id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
248,500
Mollom/mollom_python
mollom/mollom.py
Mollom.verify_keys
def verify_keys(self): """Verify that the public and private key combination is valid; raises MollomAuthenticationError otherwise""" verify_keys_endpoint = Template("${rest_root}/site/${public_key}") url = verify_keys_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key) data = { "clientName": "mollom_python", "clientVersion": "1.0" } self._client.headers["Content-Type"] = "application/x-www-form-urlencoded" response = self._client.post(url, data, timeout=self._timeout) if response.status_code != 200: raise MollomAuthenticationError return True
python
def verify_keys(self): """Verify that the public and private key combination is valid; raises MollomAuthenticationError otherwise""" verify_keys_endpoint = Template("${rest_root}/site/${public_key}") url = verify_keys_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key) data = { "clientName": "mollom_python", "clientVersion": "1.0" } self._client.headers["Content-Type"] = "application/x-www-form-urlencoded" response = self._client.post(url, data, timeout=self._timeout) if response.status_code != 200: raise MollomAuthenticationError return True
[ "def", "verify_keys", "(", "self", ")", ":", "verify_keys_endpoint", "=", "Template", "(", "\"${rest_root}/site/${public_key}\"", ")", "url", "=", "verify_keys_endpoint", ".", "substitute", "(", "rest_root", "=", "self", ".", "_rest_root", ",", "public_key", "=", "self", ".", "_public_key", ")", "data", "=", "{", "\"clientName\"", ":", "\"mollom_python\"", ",", "\"clientVersion\"", ":", "\"1.0\"", "}", "self", ".", "_client", ".", "headers", "[", "\"Content-Type\"", "]", "=", "\"application/x-www-form-urlencoded\"", "response", "=", "self", ".", "_client", ".", "post", "(", "url", ",", "data", ",", "timeout", "=", "self", ".", "_timeout", ")", "if", "response", ".", "status_code", "!=", "200", ":", "raise", "MollomAuthenticationError", "return", "True" ]
Verify that the public and private key combination is valid; raises MollomAuthenticationError otherwise
[ "Verify", "that", "the", "public", "and", "private", "key", "combination", "is", "valid", ";", "raises", "MollomAuthenticationError", "otherwise" ]
dfacb63fd79f82c0eabde76b511116df5b51d6f1
https://github.com/Mollom/mollom_python/blob/dfacb63fd79f82c0eabde76b511116df5b51d6f1/mollom/mollom.py#L49-L62
248,501
Mollom/mollom_python
mollom/mollom.py
Mollom.check_captcha
def check_captcha(self, captcha_id, solution, author_name=None, author_url=None, author_mail=None, author_ip=None, author_id=None, author_open_id=None, honeypot=None ): """Checks a CAPTCHA that was solved by the end-user. Keyword arguments: captcha_id -- Unique identifier of the CAPTCHA solved. solution -- Solution provided by the end-user for the CAPTCHA. author_name -- The name of the content author. author_url -- The homepage/website URL of the content author. author_mail -- The e-mail address of the content author. author_ip -- The IP address of the content author. author_id -- The local user ID on the client site of the content author. author_open_id -- List of Open IDs of the content author. honeypot -- The value of a client-side honeypot form element, if non-empty. Returns: solved -- Boolean whether or not the CAPTCHA was solved correctly. If the CAPTCHA is associated with an unsure contents, it is recommended to recheck the content. """ check_catpcha_endpoint = Template("${rest_root}/captcha/${captcha_id}") url = check_catpcha_endpoint.substitute(rest_root=self._rest_root, captcha_id=captcha_id) data = {"solution": solution} response = self.__post_request(url, data) # Mollom returns "1" for success and "0" for failure return response["captcha"]["solved"] == "1"
python
def check_captcha(self, captcha_id, solution, author_name=None, author_url=None, author_mail=None, author_ip=None, author_id=None, author_open_id=None, honeypot=None ): """Checks a CAPTCHA that was solved by the end-user. Keyword arguments: captcha_id -- Unique identifier of the CAPTCHA solved. solution -- Solution provided by the end-user for the CAPTCHA. author_name -- The name of the content author. author_url -- The homepage/website URL of the content author. author_mail -- The e-mail address of the content author. author_ip -- The IP address of the content author. author_id -- The local user ID on the client site of the content author. author_open_id -- List of Open IDs of the content author. honeypot -- The value of a client-side honeypot form element, if non-empty. Returns: solved -- Boolean whether or not the CAPTCHA was solved correctly. If the CAPTCHA is associated with an unsure contents, it is recommended to recheck the content. """ check_catpcha_endpoint = Template("${rest_root}/captcha/${captcha_id}") url = check_catpcha_endpoint.substitute(rest_root=self._rest_root, captcha_id=captcha_id) data = {"solution": solution} response = self.__post_request(url, data) # Mollom returns "1" for success and "0" for failure return response["captcha"]["solved"] == "1"
[ "def", "check_captcha", "(", "self", ",", "captcha_id", ",", "solution", ",", "author_name", "=", "None", ",", "author_url", "=", "None", ",", "author_mail", "=", "None", ",", "author_ip", "=", "None", ",", "author_id", "=", "None", ",", "author_open_id", "=", "None", ",", "honeypot", "=", "None", ")", ":", "check_catpcha_endpoint", "=", "Template", "(", "\"${rest_root}/captcha/${captcha_id}\"", ")", "url", "=", "check_catpcha_endpoint", ".", "substitute", "(", "rest_root", "=", "self", ".", "_rest_root", ",", "captcha_id", "=", "captcha_id", ")", "data", "=", "{", "\"solution\"", ":", "solution", "}", "response", "=", "self", ".", "__post_request", "(", "url", ",", "data", ")", "# Mollom returns \"1\" for success and \"0\" for failure", "return", "response", "[", "\"captcha\"", "]", "[", "\"solved\"", "]", "==", "\"1\"" ]
Checks a CAPTCHA that was solved by the end-user. Keyword arguments: captcha_id -- Unique identifier of the CAPTCHA solved. solution -- Solution provided by the end-user for the CAPTCHA. author_name -- The name of the content author. author_url -- The homepage/website URL of the content author. author_mail -- The e-mail address of the content author. author_ip -- The IP address of the content author. author_id -- The local user ID on the client site of the content author. author_open_id -- List of Open IDs of the content author. honeypot -- The value of a client-side honeypot form element, if non-empty. Returns: solved -- Boolean whether or not the CAPTCHA was solved correctly. If the CAPTCHA is associated with an unsure contents, it is recommended to recheck the content.
[ "Checks", "a", "CAPTCHA", "that", "was", "solved", "by", "the", "end", "-", "user", "." ]
dfacb63fd79f82c0eabde76b511116df5b51d6f1
https://github.com/Mollom/mollom_python/blob/dfacb63fd79f82c0eabde76b511116df5b51d6f1/mollom/mollom.py#L211-L246
248,502
Mollom/mollom_python
mollom/mollom.py
Mollom.get_blacklist_entries
def get_blacklist_entries(self): """Get a list of all blacklist entries. """ get_blacklist_entries_endpoint = Template("${rest_root}/blacklist/${public_key}/") url = get_blacklist_entries_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key) response = self.__get_request(url) return response["list"]["entry"]
python
def get_blacklist_entries(self): """Get a list of all blacklist entries. """ get_blacklist_entries_endpoint = Template("${rest_root}/blacklist/${public_key}/") url = get_blacklist_entries_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key) response = self.__get_request(url) return response["list"]["entry"]
[ "def", "get_blacklist_entries", "(", "self", ")", ":", "get_blacklist_entries_endpoint", "=", "Template", "(", "\"${rest_root}/blacklist/${public_key}/\"", ")", "url", "=", "get_blacklist_entries_endpoint", ".", "substitute", "(", "rest_root", "=", "self", ".", "_rest_root", ",", "public_key", "=", "self", ".", "_public_key", ")", "response", "=", "self", ".", "__get_request", "(", "url", ")", "return", "response", "[", "\"list\"", "]", "[", "\"entry\"", "]" ]
Get a list of all blacklist entries.
[ "Get", "a", "list", "of", "all", "blacklist", "entries", "." ]
dfacb63fd79f82c0eabde76b511116df5b51d6f1
https://github.com/Mollom/mollom_python/blob/dfacb63fd79f82c0eabde76b511116df5b51d6f1/mollom/mollom.py#L349-L357
248,503
Mollom/mollom_python
mollom/mollom.py
Mollom.get_blacklist_entry
def get_blacklist_entry(self, blacklist_entry_id): """Get a single blacklist entry Keyword arguments: blacklist_entry_id -- The unique identifier of the blacklist entry to get. """ get_blacklist_entries_endpoint = Template("${rest_root}/blacklist/${public_key}/${blacklist_entry_id}") url = get_blacklist_entries_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key, blacklist_entry_id=blacklist_entry_id) response = self.__get_request(url) return response["entry"]
python
def get_blacklist_entry(self, blacklist_entry_id): """Get a single blacklist entry Keyword arguments: blacklist_entry_id -- The unique identifier of the blacklist entry to get. """ get_blacklist_entries_endpoint = Template("${rest_root}/blacklist/${public_key}/${blacklist_entry_id}") url = get_blacklist_entries_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key, blacklist_entry_id=blacklist_entry_id) response = self.__get_request(url) return response["entry"]
[ "def", "get_blacklist_entry", "(", "self", ",", "blacklist_entry_id", ")", ":", "get_blacklist_entries_endpoint", "=", "Template", "(", "\"${rest_root}/blacklist/${public_key}/${blacklist_entry_id}\"", ")", "url", "=", "get_blacklist_entries_endpoint", ".", "substitute", "(", "rest_root", "=", "self", ".", "_rest_root", ",", "public_key", "=", "self", ".", "_public_key", ",", "blacklist_entry_id", "=", "blacklist_entry_id", ")", "response", "=", "self", ".", "__get_request", "(", "url", ")", "return", "response", "[", "\"entry\"", "]" ]
Get a single blacklist entry Keyword arguments: blacklist_entry_id -- The unique identifier of the blacklist entry to get.
[ "Get", "a", "single", "blacklist", "entry" ]
dfacb63fd79f82c0eabde76b511116df5b51d6f1
https://github.com/Mollom/mollom_python/blob/dfacb63fd79f82c0eabde76b511116df5b51d6f1/mollom/mollom.py#L359-L369
248,504
jut-io/jut-python-tools
jut/api/deployments.py
create_deployment
def create_deployment(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ create a deployment with the specified name """ headers = token_manager.get_access_token_headers() payload = { 'name': deployment_name, 'isAdmin': True } deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.post('%s/api/v1/deployments' % deployment_url, data=json.dumps(payload), headers=headers) if response.status_code == 201: return response.json() else: raise JutException('Error %s: %s' % (response.status_code, response.text))
python
def create_deployment(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ create a deployment with the specified name """ headers = token_manager.get_access_token_headers() payload = { 'name': deployment_name, 'isAdmin': True } deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.post('%s/api/v1/deployments' % deployment_url, data=json.dumps(payload), headers=headers) if response.status_code == 201: return response.json() else: raise JutException('Error %s: %s' % (response.status_code, response.text))
[ "def", "create_deployment", "(", "deployment_name", ",", "token_manager", "=", "None", ",", "app_url", "=", "defaults", ".", "APP_URL", ")", ":", "headers", "=", "token_manager", ".", "get_access_token_headers", "(", ")", "payload", "=", "{", "'name'", ":", "deployment_name", ",", "'isAdmin'", ":", "True", "}", "deployment_url", "=", "environment", ".", "get_deployment_url", "(", "app_url", "=", "app_url", ")", "response", "=", "requests", ".", "post", "(", "'%s/api/v1/deployments'", "%", "deployment_url", ",", "data", "=", "json", ".", "dumps", "(", "payload", ")", ",", "headers", "=", "headers", ")", "if", "response", ".", "status_code", "==", "201", ":", "return", "response", ".", "json", "(", ")", "else", ":", "raise", "JutException", "(", "'Error %s: %s'", "%", "(", "response", ".", "status_code", ",", "response", ".", "text", ")", ")" ]
create a deployment with the specified name
[ "create", "a", "deployment", "with", "the", "specified", "name" ]
65574d23f51a7bbced9bb25010d02da5ca5d906f
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/api/deployments.py#L16-L39
248,505
jut-io/jut-python-tools
jut/api/deployments.py
get_deployments
def get_deployments(token_manager=None, app_url=defaults.APP_URL): """ return the list of deployments that the current access_token gives you access to """ headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.get('%s/api/v1/deployments' % deployment_url, headers=headers) if response.status_code == 200: return response.json() else: raise JutException('Error %s: %s' % (response.status_code, response.text))
python
def get_deployments(token_manager=None, app_url=defaults.APP_URL): """ return the list of deployments that the current access_token gives you access to """ headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.get('%s/api/v1/deployments' % deployment_url, headers=headers) if response.status_code == 200: return response.json() else: raise JutException('Error %s: %s' % (response.status_code, response.text))
[ "def", "get_deployments", "(", "token_manager", "=", "None", ",", "app_url", "=", "defaults", ".", "APP_URL", ")", ":", "headers", "=", "token_manager", ".", "get_access_token_headers", "(", ")", "deployment_url", "=", "environment", ".", "get_deployment_url", "(", "app_url", "=", "app_url", ")", "response", "=", "requests", ".", "get", "(", "'%s/api/v1/deployments'", "%", "deployment_url", ",", "headers", "=", "headers", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "response", ".", "json", "(", ")", "else", ":", "raise", "JutException", "(", "'Error %s: %s'", "%", "(", "response", ".", "status_code", ",", "response", ".", "text", ")", ")" ]
return the list of deployments that the current access_token gives you access to
[ "return", "the", "list", "of", "deployments", "that", "the", "current", "access_token", "gives", "you", "access", "to" ]
65574d23f51a7bbced9bb25010d02da5ca5d906f
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/api/deployments.py#L42-L57
248,506
jut-io/jut-python-tools
jut/api/deployments.py
get_deployment_id
def get_deployment_id(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ return the deployment id for the deployment with the specified name """ headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.get('%s/api/v1/deployments' % deployment_url, headers=headers) if response.status_code == 200: deployments = response.json() for deployment in deployments: if deployment['name'] == deployment_name: return deployment['deployment_id'] raise JutException('Unable to find deployment with name %s' % deployment_name) else: raise JutException('Error %s: %s' % (response.status_code, response.text))
python
def get_deployment_id(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ return the deployment id for the deployment with the specified name """ headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.get('%s/api/v1/deployments' % deployment_url, headers=headers) if response.status_code == 200: deployments = response.json() for deployment in deployments: if deployment['name'] == deployment_name: return deployment['deployment_id'] raise JutException('Unable to find deployment with name %s' % deployment_name) else: raise JutException('Error %s: %s' % (response.status_code, response.text))
[ "def", "get_deployment_id", "(", "deployment_name", ",", "token_manager", "=", "None", ",", "app_url", "=", "defaults", ".", "APP_URL", ")", ":", "headers", "=", "token_manager", ".", "get_access_token_headers", "(", ")", "deployment_url", "=", "environment", ".", "get_deployment_url", "(", "app_url", "=", "app_url", ")", "response", "=", "requests", ".", "get", "(", "'%s/api/v1/deployments'", "%", "deployment_url", ",", "headers", "=", "headers", ")", "if", "response", ".", "status_code", "==", "200", ":", "deployments", "=", "response", ".", "json", "(", ")", "for", "deployment", "in", "deployments", ":", "if", "deployment", "[", "'name'", "]", "==", "deployment_name", ":", "return", "deployment", "[", "'deployment_id'", "]", "raise", "JutException", "(", "'Unable to find deployment with name %s'", "%", "deployment_name", ")", "else", ":", "raise", "JutException", "(", "'Error %s: %s'", "%", "(", "response", ".", "status_code", ",", "response", ".", "text", ")", ")" ]
return the deployment id for the deployment with the specified name
[ "return", "the", "deployment", "id", "for", "the", "deployment", "with", "the", "specified", "name" ]
65574d23f51a7bbced9bb25010d02da5ca5d906f
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/api/deployments.py#L60-L82
248,507
jut-io/jut-python-tools
jut/api/deployments.py
get_space_id
def get_space_id(deployment_name, space_name, token_manager=None, app_url=defaults.APP_URL): """ get the space id that relates to the space name provided """ spaces = get_spaces(deployment_name, token_manager=token_manager, app_url=app_url) for space in spaces: if space['name'] == space_name: return space['id'] raise JutException('Unable to find space "%s" within deployment "%s"' % (space_name, deployment_name))
python
def get_space_id(deployment_name, space_name, token_manager=None, app_url=defaults.APP_URL): """ get the space id that relates to the space name provided """ spaces = get_spaces(deployment_name, token_manager=token_manager, app_url=app_url) for space in spaces: if space['name'] == space_name: return space['id'] raise JutException('Unable to find space "%s" within deployment "%s"' % (space_name, deployment_name))
[ "def", "get_space_id", "(", "deployment_name", ",", "space_name", ",", "token_manager", "=", "None", ",", "app_url", "=", "defaults", ".", "APP_URL", ")", ":", "spaces", "=", "get_spaces", "(", "deployment_name", ",", "token_manager", "=", "token_manager", ",", "app_url", "=", "app_url", ")", "for", "space", "in", "spaces", ":", "if", "space", "[", "'name'", "]", "==", "space_name", ":", "return", "space", "[", "'id'", "]", "raise", "JutException", "(", "'Unable to find space \"%s\" within deployment \"%s\"'", "%", "(", "space_name", ",", "deployment_name", ")", ")" ]
get the space id that relates to the space name provided
[ "get", "the", "space", "id", "that", "relates", "to", "the", "space", "name", "provided" ]
65574d23f51a7bbced9bb25010d02da5ca5d906f
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/api/deployments.py#L153-L170
248,508
jut-io/jut-python-tools
jut/api/deployments.py
create_space
def create_space(deployment_name, space_name, security_policy='public', events_retention_days=0, metrics_retention_days=0, token_manager=None, app_url=defaults.APP_URL): """ create a space within the deployment specified and with the various rentention values set """ deployment_id = get_deployment_id(deployment_name, token_manager=token_manager, app_url=app_url) payload = { 'name': space_name, 'security_policy': security_policy, 'events_retention_days': events_retention_days, 'metrics_retention_days': metrics_retention_days, } headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.post('%s/api/v1/deployments/%s/spaces' % (deployment_url, deployment_id), data=json.dumps(payload), headers=headers) if response.status_code == 201: return response.json() else: raise JutException('Error %s: %s' % (response.status_code, response.text))
python
def create_space(deployment_name, space_name, security_policy='public', events_retention_days=0, metrics_retention_days=0, token_manager=None, app_url=defaults.APP_URL): """ create a space within the deployment specified and with the various rentention values set """ deployment_id = get_deployment_id(deployment_name, token_manager=token_manager, app_url=app_url) payload = { 'name': space_name, 'security_policy': security_policy, 'events_retention_days': events_retention_days, 'metrics_retention_days': metrics_retention_days, } headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.post('%s/api/v1/deployments/%s/spaces' % (deployment_url, deployment_id), data=json.dumps(payload), headers=headers) if response.status_code == 201: return response.json() else: raise JutException('Error %s: %s' % (response.status_code, response.text))
[ "def", "create_space", "(", "deployment_name", ",", "space_name", ",", "security_policy", "=", "'public'", ",", "events_retention_days", "=", "0", ",", "metrics_retention_days", "=", "0", ",", "token_manager", "=", "None", ",", "app_url", "=", "defaults", ".", "APP_URL", ")", ":", "deployment_id", "=", "get_deployment_id", "(", "deployment_name", ",", "token_manager", "=", "token_manager", ",", "app_url", "=", "app_url", ")", "payload", "=", "{", "'name'", ":", "space_name", ",", "'security_policy'", ":", "security_policy", ",", "'events_retention_days'", ":", "events_retention_days", ",", "'metrics_retention_days'", ":", "metrics_retention_days", ",", "}", "headers", "=", "token_manager", ".", "get_access_token_headers", "(", ")", "deployment_url", "=", "environment", ".", "get_deployment_url", "(", "app_url", "=", "app_url", ")", "response", "=", "requests", ".", "post", "(", "'%s/api/v1/deployments/%s/spaces'", "%", "(", "deployment_url", ",", "deployment_id", ")", ",", "data", "=", "json", ".", "dumps", "(", "payload", ")", ",", "headers", "=", "headers", ")", "if", "response", ".", "status_code", "==", "201", ":", "return", "response", ".", "json", "(", ")", "else", ":", "raise", "JutException", "(", "'Error %s: %s'", "%", "(", "response", ".", "status_code", ",", "response", ".", "text", ")", ")" ]
create a space within the deployment specified and with the various rentention values set
[ "create", "a", "space", "within", "the", "deployment", "specified", "and", "with", "the", "various", "rentention", "values", "set" ]
65574d23f51a7bbced9bb25010d02da5ca5d906f
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/api/deployments.py#L173-L206
248,509
jut-io/jut-python-tools
jut/api/deployments.py
get_users
def get_users(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ get all users in the deployment specified """ deployment_id = get_deployment_id(deployment_name, token_manager=token_manager, app_url=app_url) headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.get('%s/api/v1/deployments/%s/accounts' % (deployment_url, deployment_id), headers=headers) if response.status_code == 200: return response.json() else: raise JutException('Error %s: %s' % (response.status_code, response.text))
python
def get_users(deployment_name, token_manager=None, app_url=defaults.APP_URL): """ get all users in the deployment specified """ deployment_id = get_deployment_id(deployment_name, token_manager=token_manager, app_url=app_url) headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.get('%s/api/v1/deployments/%s/accounts' % (deployment_url, deployment_id), headers=headers) if response.status_code == 200: return response.json() else: raise JutException('Error %s: %s' % (response.status_code, response.text))
[ "def", "get_users", "(", "deployment_name", ",", "token_manager", "=", "None", ",", "app_url", "=", "defaults", ".", "APP_URL", ")", ":", "deployment_id", "=", "get_deployment_id", "(", "deployment_name", ",", "token_manager", "=", "token_manager", ",", "app_url", "=", "app_url", ")", "headers", "=", "token_manager", ".", "get_access_token_headers", "(", ")", "deployment_url", "=", "environment", ".", "get_deployment_url", "(", "app_url", "=", "app_url", ")", "response", "=", "requests", ".", "get", "(", "'%s/api/v1/deployments/%s/accounts'", "%", "(", "deployment_url", ",", "deployment_id", ")", ",", "headers", "=", "headers", ")", "if", "response", ".", "status_code", "==", "200", ":", "return", "response", ".", "json", "(", ")", "else", ":", "raise", "JutException", "(", "'Error %s: %s'", "%", "(", "response", ".", "status_code", ",", "response", ".", "text", ")", ")" ]
get all users in the deployment specified
[ "get", "all", "users", "in", "the", "deployment", "specified" ]
65574d23f51a7bbced9bb25010d02da5ca5d906f
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/api/deployments.py#L253-L273
248,510
jut-io/jut-python-tools
jut/api/deployments.py
add_user
def add_user(username, deployment_name, token_manager=None, app_url=defaults.APP_URL): """ add user to deployment """ deployment_id = get_deployment_id(deployment_name, token_manager=token_manager, app_url=app_url) account_id = accounts.get_account_id(username, token_manager=token_manager, app_url=app_url) headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.put('%s/api/v1/deployments/%s/accounts/%s' % (deployment_url, deployment_id, account_id), headers=headers) if response.status_code == 204: return response.text else: raise JutException('Error %s: %s' % (response.status_code, response.text))
python
def add_user(username, deployment_name, token_manager=None, app_url=defaults.APP_URL): """ add user to deployment """ deployment_id = get_deployment_id(deployment_name, token_manager=token_manager, app_url=app_url) account_id = accounts.get_account_id(username, token_manager=token_manager, app_url=app_url) headers = token_manager.get_access_token_headers() deployment_url = environment.get_deployment_url(app_url=app_url) response = requests.put('%s/api/v1/deployments/%s/accounts/%s' % (deployment_url, deployment_id, account_id), headers=headers) if response.status_code == 204: return response.text else: raise JutException('Error %s: %s' % (response.status_code, response.text))
[ "def", "add_user", "(", "username", ",", "deployment_name", ",", "token_manager", "=", "None", ",", "app_url", "=", "defaults", ".", "APP_URL", ")", ":", "deployment_id", "=", "get_deployment_id", "(", "deployment_name", ",", "token_manager", "=", "token_manager", ",", "app_url", "=", "app_url", ")", "account_id", "=", "accounts", ".", "get_account_id", "(", "username", ",", "token_manager", "=", "token_manager", ",", "app_url", "=", "app_url", ")", "headers", "=", "token_manager", ".", "get_access_token_headers", "(", ")", "deployment_url", "=", "environment", ".", "get_deployment_url", "(", "app_url", "=", "app_url", ")", "response", "=", "requests", ".", "put", "(", "'%s/api/v1/deployments/%s/accounts/%s'", "%", "(", "deployment_url", ",", "deployment_id", ",", "account_id", ")", ",", "headers", "=", "headers", ")", "if", "response", ".", "status_code", "==", "204", ":", "return", "response", ".", "text", "else", ":", "raise", "JutException", "(", "'Error %s: %s'", "%", "(", "response", ".", "status_code", ",", "response", ".", "text", ")", ")" ]
add user to deployment
[ "add", "user", "to", "deployment" ]
65574d23f51a7bbced9bb25010d02da5ca5d906f
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/api/deployments.py#L276-L301
248,511
20tab/twentytab-tree
tree/menu.py
Menu.as_ul
def as_ul(self, current_linkable=False, class_current="active_link", before_1="", after_1="", before_all="", after_all=""): """ It returns menu as ul """ return self.__do_menu("as_ul", current_linkable, class_current, before_1=before_1, after_1=after_1, before_all=before_all, after_all=after_all)
python
def as_ul(self, current_linkable=False, class_current="active_link", before_1="", after_1="", before_all="", after_all=""): """ It returns menu as ul """ return self.__do_menu("as_ul", current_linkable, class_current, before_1=before_1, after_1=after_1, before_all=before_all, after_all=after_all)
[ "def", "as_ul", "(", "self", ",", "current_linkable", "=", "False", ",", "class_current", "=", "\"active_link\"", ",", "before_1", "=", "\"\"", ",", "after_1", "=", "\"\"", ",", "before_all", "=", "\"\"", ",", "after_all", "=", "\"\"", ")", ":", "return", "self", ".", "__do_menu", "(", "\"as_ul\"", ",", "current_linkable", ",", "class_current", ",", "before_1", "=", "before_1", ",", "after_1", "=", "after_1", ",", "before_all", "=", "before_all", ",", "after_all", "=", "after_all", ")" ]
It returns menu as ul
[ "It", "returns", "menu", "as", "ul" ]
f2c1ced33e6c211bb52a25a7d48155e39fbdc088
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/menu.py#L68-L74
248,512
20tab/twentytab-tree
tree/menu.py
Menu.as_string
def as_string(self, chars, current_linkable=False, class_current="active_link"): """ It returns menu as string """ return self.__do_menu("as_string", current_linkable, class_current, chars)
python
def as_string(self, chars, current_linkable=False, class_current="active_link"): """ It returns menu as string """ return self.__do_menu("as_string", current_linkable, class_current, chars)
[ "def", "as_string", "(", "self", ",", "chars", ",", "current_linkable", "=", "False", ",", "class_current", "=", "\"active_link\"", ")", ":", "return", "self", ".", "__do_menu", "(", "\"as_string\"", ",", "current_linkable", ",", "class_current", ",", "chars", ")" ]
It returns menu as string
[ "It", "returns", "menu", "as", "string" ]
f2c1ced33e6c211bb52a25a7d48155e39fbdc088
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/menu.py#L82-L86
248,513
20tab/twentytab-tree
tree/menu.py
Breadcrumb.as_ul
def as_ul(self, show_leaf=True, current_linkable=False, class_current="active_link"): """ It returns breadcrumb as ul """ return self.__do_menu("as_ul", show_leaf, current_linkable, class_current)
python
def as_ul(self, show_leaf=True, current_linkable=False, class_current="active_link"): """ It returns breadcrumb as ul """ return self.__do_menu("as_ul", show_leaf, current_linkable, class_current)
[ "def", "as_ul", "(", "self", ",", "show_leaf", "=", "True", ",", "current_linkable", "=", "False", ",", "class_current", "=", "\"active_link\"", ")", ":", "return", "self", ".", "__do_menu", "(", "\"as_ul\"", ",", "show_leaf", ",", "current_linkable", ",", "class_current", ")" ]
It returns breadcrumb as ul
[ "It", "returns", "breadcrumb", "as", "ul" ]
f2c1ced33e6c211bb52a25a7d48155e39fbdc088
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/menu.py#L132-L136
248,514
20tab/twentytab-tree
tree/menu.py
Breadcrumb.as_p
def as_p(self, show_leaf=True, current_linkable=False, class_current="active_link"): """ It returns breadcrumb as p """ return self.__do_menu("as_p", show_leaf, current_linkable, class_current)
python
def as_p(self, show_leaf=True, current_linkable=False, class_current="active_link"): """ It returns breadcrumb as p """ return self.__do_menu("as_p", show_leaf, current_linkable, class_current)
[ "def", "as_p", "(", "self", ",", "show_leaf", "=", "True", ",", "current_linkable", "=", "False", ",", "class_current", "=", "\"active_link\"", ")", ":", "return", "self", ".", "__do_menu", "(", "\"as_p\"", ",", "show_leaf", ",", "current_linkable", ",", "class_current", ")" ]
It returns breadcrumb as p
[ "It", "returns", "breadcrumb", "as", "p" ]
f2c1ced33e6c211bb52a25a7d48155e39fbdc088
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/menu.py#L138-L142
248,515
20tab/twentytab-tree
tree/menu.py
Breadcrumb.as_string
def as_string(self, chars, show_leaf=True, current_linkable=False, class_current="active_link"): """ It returns breadcrumb as string """ return self.__do_menu("as_string", show_leaf, current_linkable, class_current, chars)
python
def as_string(self, chars, show_leaf=True, current_linkable=False, class_current="active_link"): """ It returns breadcrumb as string """ return self.__do_menu("as_string", show_leaf, current_linkable, class_current, chars)
[ "def", "as_string", "(", "self", ",", "chars", ",", "show_leaf", "=", "True", ",", "current_linkable", "=", "False", ",", "class_current", "=", "\"active_link\"", ")", ":", "return", "self", ".", "__do_menu", "(", "\"as_string\"", ",", "show_leaf", ",", "current_linkable", ",", "class_current", ",", "chars", ")" ]
It returns breadcrumb as string
[ "It", "returns", "breadcrumb", "as", "string" ]
f2c1ced33e6c211bb52a25a7d48155e39fbdc088
https://github.com/20tab/twentytab-tree/blob/f2c1ced33e6c211bb52a25a7d48155e39fbdc088/tree/menu.py#L144-L148
248,516
xtrementl/focus
focus/parser/__init__.py
parse_config
def parse_config(filename, header): """ Parses the provided filename and returns ``SettingParser`` if the parsing was successful and header matches the header defined in the file. Returns ``SettingParser`` instance. * Raises a ``ParseError`` exception if header doesn't match or parsing fails. """ parser = SettingParser(filename) if parser.header != header: header_value = parser.header or '' raise ParseError(u"Unexpected header '{0}', expecting '{1}'" .format(common.from_utf8(header_value), header)) return parser
python
def parse_config(filename, header): """ Parses the provided filename and returns ``SettingParser`` if the parsing was successful and header matches the header defined in the file. Returns ``SettingParser`` instance. * Raises a ``ParseError`` exception if header doesn't match or parsing fails. """ parser = SettingParser(filename) if parser.header != header: header_value = parser.header or '' raise ParseError(u"Unexpected header '{0}', expecting '{1}'" .format(common.from_utf8(header_value), header)) return parser
[ "def", "parse_config", "(", "filename", ",", "header", ")", ":", "parser", "=", "SettingParser", "(", "filename", ")", "if", "parser", ".", "header", "!=", "header", ":", "header_value", "=", "parser", ".", "header", "or", "''", "raise", "ParseError", "(", "u\"Unexpected header '{0}', expecting '{1}'\"", ".", "format", "(", "common", ".", "from_utf8", "(", "header_value", ")", ",", "header", ")", ")", "return", "parser" ]
Parses the provided filename and returns ``SettingParser`` if the parsing was successful and header matches the header defined in the file. Returns ``SettingParser`` instance. * Raises a ``ParseError`` exception if header doesn't match or parsing fails.
[ "Parses", "the", "provided", "filename", "and", "returns", "SettingParser", "if", "the", "parsing", "was", "successful", "and", "header", "matches", "the", "header", "defined", "in", "the", "file", "." ]
cbbbc0b49a7409f9e0dc899de5b7e057f50838e4
https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/parser/__init__.py#L15-L32
248,517
Ffisegydd/whatis
whatis/_variable.py
print_variable
def print_variable(obj, **kwargs): """Print the variable out. Limit the string length to, by default, 300 characters.""" variable_print_length = kwargs.get("variable_print_length", 1000) s = str(obj) if len(s) < 300: return "Printing the object:\n" + str(obj) else: return "Printing the object:\n" + str(obj)[:variable_print_length] + ' ...'
python
def print_variable(obj, **kwargs): """Print the variable out. Limit the string length to, by default, 300 characters.""" variable_print_length = kwargs.get("variable_print_length", 1000) s = str(obj) if len(s) < 300: return "Printing the object:\n" + str(obj) else: return "Printing the object:\n" + str(obj)[:variable_print_length] + ' ...'
[ "def", "print_variable", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "variable_print_length", "=", "kwargs", ".", "get", "(", "\"variable_print_length\"", ",", "1000", ")", "s", "=", "str", "(", "obj", ")", "if", "len", "(", "s", ")", "<", "300", ":", "return", "\"Printing the object:\\n\"", "+", "str", "(", "obj", ")", "else", ":", "return", "\"Printing the object:\\n\"", "+", "str", "(", "obj", ")", "[", ":", "variable_print_length", "]", "+", "' ...'" ]
Print the variable out. Limit the string length to, by default, 300 characters.
[ "Print", "the", "variable", "out", ".", "Limit", "the", "string", "length", "to", "by", "default", "300", "characters", "." ]
eef780ced61aae6d001aeeef7574e5e27e613583
https://github.com/Ffisegydd/whatis/blob/eef780ced61aae6d001aeeef7574e5e27e613583/whatis/_variable.py#L4-L11
248,518
appointlet/span
span/__init__.py
Span.encompasses
def encompasses(self, span): """ Returns true if the given span fits inside this one """ if isinstance(span, list): return [sp for sp in span if self._encompasses(sp)] return self._encompasses(span)
python
def encompasses(self, span): """ Returns true if the given span fits inside this one """ if isinstance(span, list): return [sp for sp in span if self._encompasses(sp)] return self._encompasses(span)
[ "def", "encompasses", "(", "self", ",", "span", ")", ":", "if", "isinstance", "(", "span", ",", "list", ")", ":", "return", "[", "sp", "for", "sp", "in", "span", "if", "self", ".", "_encompasses", "(", "sp", ")", "]", "return", "self", ".", "_encompasses", "(", "span", ")" ]
Returns true if the given span fits inside this one
[ "Returns", "true", "if", "the", "given", "span", "fits", "inside", "this", "one" ]
6d4f2920e45df827890ebe55b1c41b1f3414c0c9
https://github.com/appointlet/span/blob/6d4f2920e45df827890ebe55b1c41b1f3414c0c9/span/__init__.py#L66-L73
248,519
appointlet/span
span/__init__.py
Span.encompassed_by
def encompassed_by(self, span): """ Returns true if the given span encompasses this span. """ if isinstance(span, list): return [sp for sp in span if sp.encompasses(self)] return span.encompasses(self)
python
def encompassed_by(self, span): """ Returns true if the given span encompasses this span. """ if isinstance(span, list): return [sp for sp in span if sp.encompasses(self)] return span.encompasses(self)
[ "def", "encompassed_by", "(", "self", ",", "span", ")", ":", "if", "isinstance", "(", "span", ",", "list", ")", ":", "return", "[", "sp", "for", "sp", "in", "span", "if", "sp", ".", "encompasses", "(", "self", ")", "]", "return", "span", ".", "encompasses", "(", "self", ")" ]
Returns true if the given span encompasses this span.
[ "Returns", "true", "if", "the", "given", "span", "encompasses", "this", "span", "." ]
6d4f2920e45df827890ebe55b1c41b1f3414c0c9
https://github.com/appointlet/span/blob/6d4f2920e45df827890ebe55b1c41b1f3414c0c9/span/__init__.py#L77-L84
248,520
udoprog/mimeprovider
mimeprovider/packages/mxml.py
mXml.adds
def adds(self, string): """ Add a string child. """ if isinstance(string, unicode): string = string.encode("utf-8") self.children.append((STRING, str(string)))
python
def adds(self, string): """ Add a string child. """ if isinstance(string, unicode): string = string.encode("utf-8") self.children.append((STRING, str(string)))
[ "def", "adds", "(", "self", ",", "string", ")", ":", "if", "isinstance", "(", "string", ",", "unicode", ")", ":", "string", "=", "string", ".", "encode", "(", "\"utf-8\"", ")", "self", ".", "children", ".", "append", "(", "(", "STRING", ",", "str", "(", "string", ")", ")", ")" ]
Add a string child.
[ "Add", "a", "string", "child", "." ]
5acd61eb0ef813b4a2eb6bbe75d07af1e11847a4
https://github.com/udoprog/mimeprovider/blob/5acd61eb0ef813b4a2eb6bbe75d07af1e11847a4/mimeprovider/packages/mxml.py#L34-L41
248,521
ECESeniorDesign/lazy_record
lazy_record/base/__init__.py
Base.delete
def delete(self): """ Delete this record without deleting any dependent or child records. This can orphan records, so use with care. """ if self.id: with Repo.db: Repo(self.__table).where(id=self.id).delete()
python
def delete(self): """ Delete this record without deleting any dependent or child records. This can orphan records, so use with care. """ if self.id: with Repo.db: Repo(self.__table).where(id=self.id).delete()
[ "def", "delete", "(", "self", ")", ":", "if", "self", ".", "id", ":", "with", "Repo", ".", "db", ":", "Repo", "(", "self", ".", "__table", ")", ".", "where", "(", "id", "=", "self", ".", "id", ")", ".", "delete", "(", ")" ]
Delete this record without deleting any dependent or child records. This can orphan records, so use with care.
[ "Delete", "this", "record", "without", "deleting", "any", "dependent", "or", "child", "records", ".", "This", "can", "orphan", "records", "so", "use", "with", "care", "." ]
929d3cc7c2538b0f792365c0d2b0e0d41084c2dd
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/base/__init__.py#L125-L132
248,522
CodyKochmann/stricttuple
stricttuple/__init__.py
shorten
def shorten(string, max_length=80, trailing_chars=3): ''' trims the 'string' argument down to 'max_length' to make previews to long string values ''' assert type(string).__name__ in {'str', 'unicode'}, 'shorten needs string to be a string, not {}'.format(type(string)) assert type(max_length) == int, 'shorten needs max_length to be an int, not {}'.format(type(max_length)) assert type(trailing_chars) == int, 'shorten needs trailing_chars to be an int, not {}'.format(type(trailing_chars)) assert max_length > 0, 'shorten needs max_length to be positive, not {}'.format(max_length) assert trailing_chars >= 0, 'shorten needs trailing_chars to be greater than or equal to 0, not {}'.format(trailing_chars) return ( string ) if len(string) <= max_length else ( '{before:}...{after:}'.format( before=string[:max_length-(trailing_chars+3)], after=string[-trailing_chars:] if trailing_chars>0 else '' ) )
python
def shorten(string, max_length=80, trailing_chars=3): ''' trims the 'string' argument down to 'max_length' to make previews to long string values ''' assert type(string).__name__ in {'str', 'unicode'}, 'shorten needs string to be a string, not {}'.format(type(string)) assert type(max_length) == int, 'shorten needs max_length to be an int, not {}'.format(type(max_length)) assert type(trailing_chars) == int, 'shorten needs trailing_chars to be an int, not {}'.format(type(trailing_chars)) assert max_length > 0, 'shorten needs max_length to be positive, not {}'.format(max_length) assert trailing_chars >= 0, 'shorten needs trailing_chars to be greater than or equal to 0, not {}'.format(trailing_chars) return ( string ) if len(string) <= max_length else ( '{before:}...{after:}'.format( before=string[:max_length-(trailing_chars+3)], after=string[-trailing_chars:] if trailing_chars>0 else '' ) )
[ "def", "shorten", "(", "string", ",", "max_length", "=", "80", ",", "trailing_chars", "=", "3", ")", ":", "assert", "type", "(", "string", ")", ".", "__name__", "in", "{", "'str'", ",", "'unicode'", "}", ",", "'shorten needs string to be a string, not {}'", ".", "format", "(", "type", "(", "string", ")", ")", "assert", "type", "(", "max_length", ")", "==", "int", ",", "'shorten needs max_length to be an int, not {}'", ".", "format", "(", "type", "(", "max_length", ")", ")", "assert", "type", "(", "trailing_chars", ")", "==", "int", ",", "'shorten needs trailing_chars to be an int, not {}'", ".", "format", "(", "type", "(", "trailing_chars", ")", ")", "assert", "max_length", ">", "0", ",", "'shorten needs max_length to be positive, not {}'", ".", "format", "(", "max_length", ")", "assert", "trailing_chars", ">=", "0", ",", "'shorten needs trailing_chars to be greater than or equal to 0, not {}'", ".", "format", "(", "trailing_chars", ")", "return", "(", "string", ")", "if", "len", "(", "string", ")", "<=", "max_length", "else", "(", "'{before:}...{after:}'", ".", "format", "(", "before", "=", "string", "[", ":", "max_length", "-", "(", "trailing_chars", "+", "3", ")", "]", ",", "after", "=", "string", "[", "-", "trailing_chars", ":", "]", "if", "trailing_chars", ">", "0", "else", "''", ")", ")" ]
trims the 'string' argument down to 'max_length' to make previews to long string values
[ "trims", "the", "string", "argument", "down", "to", "max_length", "to", "make", "previews", "to", "long", "string", "values" ]
072cbd6f7b90f3f666dc0f2c10ab6056d86dfc72
https://github.com/CodyKochmann/stricttuple/blob/072cbd6f7b90f3f666dc0f2c10ab6056d86dfc72/stricttuple/__init__.py#L40-L55
248,523
CodyKochmann/stricttuple
stricttuple/__init__.py
is_prettytable
def is_prettytable(string): """ returns true if the input looks like a prettytable """ return type(string).__name__ in {'str','unicode'} and ( len(string.splitlines()) > 1 ) and ( all(string[i] == string[-i-1] for i in range(3)) )
python
def is_prettytable(string): """ returns true if the input looks like a prettytable """ return type(string).__name__ in {'str','unicode'} and ( len(string.splitlines()) > 1 ) and ( all(string[i] == string[-i-1] for i in range(3)) )
[ "def", "is_prettytable", "(", "string", ")", ":", "return", "type", "(", "string", ")", ".", "__name__", "in", "{", "'str'", ",", "'unicode'", "}", "and", "(", "len", "(", "string", ".", "splitlines", "(", ")", ")", ">", "1", ")", "and", "(", "all", "(", "string", "[", "i", "]", "==", "string", "[", "-", "i", "-", "1", "]", "for", "i", "in", "range", "(", "3", ")", ")", ")" ]
returns true if the input looks like a prettytable
[ "returns", "true", "if", "the", "input", "looks", "like", "a", "prettytable" ]
072cbd6f7b90f3f666dc0f2c10ab6056d86dfc72
https://github.com/CodyKochmann/stricttuple/blob/072cbd6f7b90f3f666dc0f2c10ab6056d86dfc72/stricttuple/__init__.py#L57-L63
248,524
evetrivia/thanatos
thanatos/database/inventory.py
get_all_published_ships_basic
def get_all_published_ships_basic(db_connection): """ Gets a list of all published ships and their basic information. :return: Each result has a tuple of (typeID, typeName, groupID, groupName, categoryID, and categoryName). :rtype: list """ if not hasattr(get_all_published_ships_basic, '_results'): sql = 'CALL get_all_published_ships_basic();' results = execute_sql(sql, db_connection) get_all_published_ships_basic._results = results return get_all_published_ships_basic._results
python
def get_all_published_ships_basic(db_connection): """ Gets a list of all published ships and their basic information. :return: Each result has a tuple of (typeID, typeName, groupID, groupName, categoryID, and categoryName). :rtype: list """ if not hasattr(get_all_published_ships_basic, '_results'): sql = 'CALL get_all_published_ships_basic();' results = execute_sql(sql, db_connection) get_all_published_ships_basic._results = results return get_all_published_ships_basic._results
[ "def", "get_all_published_ships_basic", "(", "db_connection", ")", ":", "if", "not", "hasattr", "(", "get_all_published_ships_basic", ",", "'_results'", ")", ":", "sql", "=", "'CALL get_all_published_ships_basic();'", "results", "=", "execute_sql", "(", "sql", ",", "db_connection", ")", "get_all_published_ships_basic", ".", "_results", "=", "results", "return", "get_all_published_ships_basic", ".", "_results" ]
Gets a list of all published ships and their basic information. :return: Each result has a tuple of (typeID, typeName, groupID, groupName, categoryID, and categoryName). :rtype: list
[ "Gets", "a", "list", "of", "all", "published", "ships", "and", "their", "basic", "information", "." ]
664c12a8ccf4d27ab0e06e0969bbb6381f74789c
https://github.com/evetrivia/thanatos/blob/664c12a8ccf4d27ab0e06e0969bbb6381f74789c/thanatos/database/inventory.py#L10-L22
248,525
evetrivia/thanatos
thanatos/database/inventory.py
get_ships_that_have_variations
def get_ships_that_have_variations(db_connection): """ Gets a list of all published ship type IDs that have at least 3 variations. :return: :rtype: list """ if not hasattr(get_ships_that_have_variations, '_results'): sql = 'CALL get_ships_that_have_variations();' results = execute_sql(sql, db_connection) get_ships_that_have_variations._results = results return get_ships_that_have_variations._results
python
def get_ships_that_have_variations(db_connection): """ Gets a list of all published ship type IDs that have at least 3 variations. :return: :rtype: list """ if not hasattr(get_ships_that_have_variations, '_results'): sql = 'CALL get_ships_that_have_variations();' results = execute_sql(sql, db_connection) get_ships_that_have_variations._results = results return get_ships_that_have_variations._results
[ "def", "get_ships_that_have_variations", "(", "db_connection", ")", ":", "if", "not", "hasattr", "(", "get_ships_that_have_variations", ",", "'_results'", ")", ":", "sql", "=", "'CALL get_ships_that_have_variations();'", "results", "=", "execute_sql", "(", "sql", ",", "db_connection", ")", "get_ships_that_have_variations", ".", "_results", "=", "results", "return", "get_ships_that_have_variations", ".", "_results" ]
Gets a list of all published ship type IDs that have at least 3 variations. :return: :rtype: list
[ "Gets", "a", "list", "of", "all", "published", "ship", "type", "IDs", "that", "have", "at", "least", "3", "variations", "." ]
664c12a8ccf4d27ab0e06e0969bbb6381f74789c
https://github.com/evetrivia/thanatos/blob/664c12a8ccf4d27ab0e06e0969bbb6381f74789c/thanatos/database/inventory.py#L44-L56
248,526
mohamedattahri/PyXMLi
pyxmli/xmldsig.py
c14n
def c14n(xml): ''' Applies c14n to the xml input @param xml: str @return: str ''' tree = etree.parse(StringIO(xml)) output = StringIO() tree.write_c14n(output, exclusive=False, with_comments=True, compression=0) output.flush() c14nized = output.getvalue() output.close() return c14nized
python
def c14n(xml): ''' Applies c14n to the xml input @param xml: str @return: str ''' tree = etree.parse(StringIO(xml)) output = StringIO() tree.write_c14n(output, exclusive=False, with_comments=True, compression=0) output.flush() c14nized = output.getvalue() output.close() return c14nized
[ "def", "c14n", "(", "xml", ")", ":", "tree", "=", "etree", ".", "parse", "(", "StringIO", "(", "xml", ")", ")", "output", "=", "StringIO", "(", ")", "tree", ".", "write_c14n", "(", "output", ",", "exclusive", "=", "False", ",", "with_comments", "=", "True", ",", "compression", "=", "0", ")", "output", ".", "flush", "(", ")", "c14nized", "=", "output", ".", "getvalue", "(", ")", "output", ".", "close", "(", ")", "return", "c14nized" ]
Applies c14n to the xml input @param xml: str @return: str
[ "Applies", "c14n", "to", "the", "xml", "input" ]
a81a245be822d62f1a20c734ca14b42c786ae81e
https://github.com/mohamedattahri/PyXMLi/blob/a81a245be822d62f1a20c734ca14b42c786ae81e/pyxmli/xmldsig.py#L50-L62
248,527
mohamedattahri/PyXMLi
pyxmli/xmldsig.py
sign
def sign(xml, private, public): ''' Return xmldsig XML string from xml_string of XML. @param xml: str of bytestring xml to sign @param private: publicKey Private key @param public: publicKey Public key @return str: signed XML byte string ''' xml = xml.encode('utf-8', 'xmlcharrefreplace') signed_info_xml = _generate_signed_info(xml) signer = PKCS1_v1_5.PKCS115_SigScheme(private) signature_value = signer.sign(SHA.new(c14n(signed_info_xml))) signature_xml = PTN_SIGNATURE_XML % { 'signed_info_xml': signed_info_xml, 'signature_value': binascii.b2a_base64(signature_value)[:-1], 'key_info_xml': _generate_key_info_xml_rsa(public.key.n, public.key.e) } position = xml.rfind('</') return xml[0:position] + signature_xml + xml[position:]
python
def sign(xml, private, public): ''' Return xmldsig XML string from xml_string of XML. @param xml: str of bytestring xml to sign @param private: publicKey Private key @param public: publicKey Public key @return str: signed XML byte string ''' xml = xml.encode('utf-8', 'xmlcharrefreplace') signed_info_xml = _generate_signed_info(xml) signer = PKCS1_v1_5.PKCS115_SigScheme(private) signature_value = signer.sign(SHA.new(c14n(signed_info_xml))) signature_xml = PTN_SIGNATURE_XML % { 'signed_info_xml': signed_info_xml, 'signature_value': binascii.b2a_base64(signature_value)[:-1], 'key_info_xml': _generate_key_info_xml_rsa(public.key.n, public.key.e) } position = xml.rfind('</') return xml[0:position] + signature_xml + xml[position:]
[ "def", "sign", "(", "xml", ",", "private", ",", "public", ")", ":", "xml", "=", "xml", ".", "encode", "(", "'utf-8'", ",", "'xmlcharrefreplace'", ")", "signed_info_xml", "=", "_generate_signed_info", "(", "xml", ")", "signer", "=", "PKCS1_v1_5", ".", "PKCS115_SigScheme", "(", "private", ")", "signature_value", "=", "signer", ".", "sign", "(", "SHA", ".", "new", "(", "c14n", "(", "signed_info_xml", ")", ")", ")", "signature_xml", "=", "PTN_SIGNATURE_XML", "%", "{", "'signed_info_xml'", ":", "signed_info_xml", ",", "'signature_value'", ":", "binascii", ".", "b2a_base64", "(", "signature_value", ")", "[", ":", "-", "1", "]", ",", "'key_info_xml'", ":", "_generate_key_info_xml_rsa", "(", "public", ".", "key", ".", "n", ",", "public", ".", "key", ".", "e", ")", "}", "position", "=", "xml", ".", "rfind", "(", "'</'", ")", "return", "xml", "[", "0", ":", "position", "]", "+", "signature_xml", "+", "xml", "[", "position", ":", "]" ]
Return xmldsig XML string from xml_string of XML. @param xml: str of bytestring xml to sign @param private: publicKey Private key @param public: publicKey Public key @return str: signed XML byte string
[ "Return", "xmldsig", "XML", "string", "from", "xml_string", "of", "XML", "." ]
a81a245be822d62f1a20c734ca14b42c786ae81e
https://github.com/mohamedattahri/PyXMLi/blob/a81a245be822d62f1a20c734ca14b42c786ae81e/pyxmli/xmldsig.py#L65-L86
248,528
mohamedattahri/PyXMLi
pyxmli/xmldsig.py
verify
def verify(xml): '''Verifies whether the validity of the signature contained in an XML document following the XMLDSig standard''' try: from cStringIO import cStringIO as StringIO except ImportError: from StringIO import StringIO xml = xml.encode('utf-8', 'xmlcharrefreplace') tree = etree.parse(StringIO(xml)) try: '''Isolating the Signature element''' signature_tree = tree.xpath('xmldsig:Signature', namespaces=NAMESPACES)[0] '''Removing the Signature element from the main tree to compute a new digest value with the actual content of the XML.''' signature_tree.getparent().remove(signature_tree) signed_info = _generate_signed_info(etree.tostring(tree)) '''Constructing the key from the Modulus and Exponent stored in the Signature/KeyInfo/KeyValue/RSAKeyValue element''' from Crypto.PublicKey import RSA modulus = signature_tree.xpath(KEY_INFO_PATH + '/xmldsig:Modulus', namespaces=NAMESPACES)[0].text exponent = signature_tree.xpath(KEY_INFO_PATH + '/xmldsig:Exponent', namespaces=NAMESPACES)[0].text public_key = RSA.construct((b64d(modulus), b64d(exponent))) '''Isolating the signature value to verify''' signature = signature_tree.xpath('xmldsig:SignatureValue', namespaces=NAMESPACES)[0].text except IndexError: raise RuntimeError('XML does not contain a properly formatted ' \ ' Signature element') verifier = PKCS1_v1_5.PKCS115_SigScheme(public_key) return verifier.verify(SHA.new(c14n(signed_info)), binascii.a2b_base64(signature))
python
def verify(xml): '''Verifies whether the validity of the signature contained in an XML document following the XMLDSig standard''' try: from cStringIO import cStringIO as StringIO except ImportError: from StringIO import StringIO xml = xml.encode('utf-8', 'xmlcharrefreplace') tree = etree.parse(StringIO(xml)) try: '''Isolating the Signature element''' signature_tree = tree.xpath('xmldsig:Signature', namespaces=NAMESPACES)[0] '''Removing the Signature element from the main tree to compute a new digest value with the actual content of the XML.''' signature_tree.getparent().remove(signature_tree) signed_info = _generate_signed_info(etree.tostring(tree)) '''Constructing the key from the Modulus and Exponent stored in the Signature/KeyInfo/KeyValue/RSAKeyValue element''' from Crypto.PublicKey import RSA modulus = signature_tree.xpath(KEY_INFO_PATH + '/xmldsig:Modulus', namespaces=NAMESPACES)[0].text exponent = signature_tree.xpath(KEY_INFO_PATH + '/xmldsig:Exponent', namespaces=NAMESPACES)[0].text public_key = RSA.construct((b64d(modulus), b64d(exponent))) '''Isolating the signature value to verify''' signature = signature_tree.xpath('xmldsig:SignatureValue', namespaces=NAMESPACES)[0].text except IndexError: raise RuntimeError('XML does not contain a properly formatted ' \ ' Signature element') verifier = PKCS1_v1_5.PKCS115_SigScheme(public_key) return verifier.verify(SHA.new(c14n(signed_info)), binascii.a2b_base64(signature))
[ "def", "verify", "(", "xml", ")", ":", "try", ":", "from", "cStringIO", "import", "cStringIO", "as", "StringIO", "except", "ImportError", ":", "from", "StringIO", "import", "StringIO", "xml", "=", "xml", ".", "encode", "(", "'utf-8'", ",", "'xmlcharrefreplace'", ")", "tree", "=", "etree", ".", "parse", "(", "StringIO", "(", "xml", ")", ")", "try", ":", "'''Isolating the Signature element'''", "signature_tree", "=", "tree", ".", "xpath", "(", "'xmldsig:Signature'", ",", "namespaces", "=", "NAMESPACES", ")", "[", "0", "]", "'''Removing the Signature element from the main tree to compute a new \n digest value with the actual content of the XML.'''", "signature_tree", ".", "getparent", "(", ")", ".", "remove", "(", "signature_tree", ")", "signed_info", "=", "_generate_signed_info", "(", "etree", ".", "tostring", "(", "tree", ")", ")", "'''Constructing the key from the Modulus and Exponent stored in the\n Signature/KeyInfo/KeyValue/RSAKeyValue element'''", "from", "Crypto", ".", "PublicKey", "import", "RSA", "modulus", "=", "signature_tree", ".", "xpath", "(", "KEY_INFO_PATH", "+", "'/xmldsig:Modulus'", ",", "namespaces", "=", "NAMESPACES", ")", "[", "0", "]", ".", "text", "exponent", "=", "signature_tree", ".", "xpath", "(", "KEY_INFO_PATH", "+", "'/xmldsig:Exponent'", ",", "namespaces", "=", "NAMESPACES", ")", "[", "0", "]", ".", "text", "public_key", "=", "RSA", ".", "construct", "(", "(", "b64d", "(", "modulus", ")", ",", "b64d", "(", "exponent", ")", ")", ")", "'''Isolating the signature value to verify'''", "signature", "=", "signature_tree", ".", "xpath", "(", "'xmldsig:SignatureValue'", ",", "namespaces", "=", "NAMESPACES", ")", "[", "0", "]", ".", "text", "except", "IndexError", ":", "raise", "RuntimeError", "(", "'XML does not contain a properly formatted '", "' Signature element'", ")", "verifier", "=", "PKCS1_v1_5", ".", "PKCS115_SigScheme", "(", "public_key", ")", "return", "verifier", ".", "verify", "(", "SHA", ".", "new", "(", "c14n", "(", "signed_info", ")", ")", ",", "binascii", ".", "a2b_base64", "(", "signature", ")", ")" ]
Verifies whether the validity of the signature contained in an XML document following the XMLDSig standard
[ "Verifies", "whether", "the", "validity", "of", "the", "signature", "contained", "in", "an", "XML", "document", "following", "the", "XMLDSig", "standard" ]
a81a245be822d62f1a20c734ca14b42c786ae81e
https://github.com/mohamedattahri/PyXMLi/blob/a81a245be822d62f1a20c734ca14b42c786ae81e/pyxmli/xmldsig.py#L89-L128
248,529
devricks/soft_drf
soft_drf/routing/autodiscover.py
autodiscover
def autodiscover(): """ Perform an autodiscover of an api.py file in the installed apps to generate the routes of the registered viewsets. """ for app in settings.INSTALLED_APPS: try: import_module('.'.join((app, 'api'))) except ImportError as e: if e.msg != "No module named '{0}.api'".format(app): print(e.msg)
python
def autodiscover(): """ Perform an autodiscover of an api.py file in the installed apps to generate the routes of the registered viewsets. """ for app in settings.INSTALLED_APPS: try: import_module('.'.join((app, 'api'))) except ImportError as e: if e.msg != "No module named '{0}.api'".format(app): print(e.msg)
[ "def", "autodiscover", "(", ")", ":", "for", "app", "in", "settings", ".", "INSTALLED_APPS", ":", "try", ":", "import_module", "(", "'.'", ".", "join", "(", "(", "app", ",", "'api'", ")", ")", ")", "except", "ImportError", "as", "e", ":", "if", "e", ".", "msg", "!=", "\"No module named '{0}.api'\"", ".", "format", "(", "app", ")", ":", "print", "(", "e", ".", "msg", ")" ]
Perform an autodiscover of an api.py file in the installed apps to generate the routes of the registered viewsets.
[ "Perform", "an", "autodiscover", "of", "an", "api", ".", "py", "file", "in", "the", "installed", "apps", "to", "generate", "the", "routes", "of", "the", "registered", "viewsets", "." ]
1869b13f9341bfcebd931059e93de2bc38570da3
https://github.com/devricks/soft_drf/blob/1869b13f9341bfcebd931059e93de2bc38570da3/soft_drf/routing/autodiscover.py#L7-L17
248,530
markpasc/pywhich
pywhich.py
identify_module
def identify_module(arg): """Import and return the Python module named in `arg`. If the module cannot be imported, a `pywhich.ModuleNotFound` exception is raised. """ try: __import__(arg) except Exception: exc = sys.exc_info()[1] raise ModuleNotFound("%s: %s" % (type(exc).__name__, str(exc))) mod = sys.modules[arg] return mod
python
def identify_module(arg): """Import and return the Python module named in `arg`. If the module cannot be imported, a `pywhich.ModuleNotFound` exception is raised. """ try: __import__(arg) except Exception: exc = sys.exc_info()[1] raise ModuleNotFound("%s: %s" % (type(exc).__name__, str(exc))) mod = sys.modules[arg] return mod
[ "def", "identify_module", "(", "arg", ")", ":", "try", ":", "__import__", "(", "arg", ")", "except", "Exception", ":", "exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "raise", "ModuleNotFound", "(", "\"%s: %s\"", "%", "(", "type", "(", "exc", ")", ".", "__name__", ",", "str", "(", "exc", ")", ")", ")", "mod", "=", "sys", ".", "modules", "[", "arg", "]", "return", "mod" ]
Import and return the Python module named in `arg`. If the module cannot be imported, a `pywhich.ModuleNotFound` exception is raised.
[ "Import", "and", "return", "the", "Python", "module", "named", "in", "arg", "." ]
2c7cbe0d8a6789ede48c53f263872ceac5b67ca3
https://github.com/markpasc/pywhich/blob/2c7cbe0d8a6789ede48c53f263872ceac5b67ca3/pywhich.py#L16-L30
248,531
markpasc/pywhich
pywhich.py
identify_modules
def identify_modules(*args, **kwargs): """Find the disk locations of the given named modules, printing the discovered paths to stdout and errors discovering paths to stderr. Any provided keyword arguments are passed to `identify_filepath()`. """ if len(args) == 1: path_template = "%(file)s" error_template = "Module '%(mod)s' not found (%(error)s)" else: path_template = "%(mod)s: %(file)s" error_template = "%(mod)s: not found (%(error)s)" for modulename in args: try: filepath = identify_filepath(modulename, **kwargs) except ModuleNotFound: exc = sys.exc_info()[1] sys.stderr.write(error_template % { 'mod': modulename, 'error': str(exc), }) sys.stderr.write('\n') else: print(path_template % { 'mod': modulename, 'file': filepath })
python
def identify_modules(*args, **kwargs): """Find the disk locations of the given named modules, printing the discovered paths to stdout and errors discovering paths to stderr. Any provided keyword arguments are passed to `identify_filepath()`. """ if len(args) == 1: path_template = "%(file)s" error_template = "Module '%(mod)s' not found (%(error)s)" else: path_template = "%(mod)s: %(file)s" error_template = "%(mod)s: not found (%(error)s)" for modulename in args: try: filepath = identify_filepath(modulename, **kwargs) except ModuleNotFound: exc = sys.exc_info()[1] sys.stderr.write(error_template % { 'mod': modulename, 'error': str(exc), }) sys.stderr.write('\n') else: print(path_template % { 'mod': modulename, 'file': filepath })
[ "def", "identify_modules", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "path_template", "=", "\"%(file)s\"", "error_template", "=", "\"Module '%(mod)s' not found (%(error)s)\"", "else", ":", "path_template", "=", "\"%(mod)s: %(file)s\"", "error_template", "=", "\"%(mod)s: not found (%(error)s)\"", "for", "modulename", "in", "args", ":", "try", ":", "filepath", "=", "identify_filepath", "(", "modulename", ",", "*", "*", "kwargs", ")", "except", "ModuleNotFound", ":", "exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "sys", ".", "stderr", ".", "write", "(", "error_template", "%", "{", "'mod'", ":", "modulename", ",", "'error'", ":", "str", "(", "exc", ")", ",", "}", ")", "sys", ".", "stderr", ".", "write", "(", "'\\n'", ")", "else", ":", "print", "(", "path_template", "%", "{", "'mod'", ":", "modulename", ",", "'file'", ":", "filepath", "}", ")" ]
Find the disk locations of the given named modules, printing the discovered paths to stdout and errors discovering paths to stderr. Any provided keyword arguments are passed to `identify_filepath()`.
[ "Find", "the", "disk", "locations", "of", "the", "given", "named", "modules", "printing", "the", "discovered", "paths", "to", "stdout", "and", "errors", "discovering", "paths", "to", "stderr", "." ]
2c7cbe0d8a6789ede48c53f263872ceac5b67ca3
https://github.com/markpasc/pywhich/blob/2c7cbe0d8a6789ede48c53f263872ceac5b67ca3/pywhich.py#L83-L111
248,532
markpasc/pywhich
pywhich.py
find_version
def find_version(*args): """Find the versions of the given named modules, printing the discovered versions to stdout and errors discovering versions to stderr.""" if len(args) == 1: ver_template = "%(version)s" error_template = "Distribution/module '%(mod)s' not found (%(error)s)" else: ver_template = "%(mod)s: %(version)s" error_template = "%(mod)s: not found (%(error)s)" import pkg_resources for modulename in args: try: try: dist = pkg_resources.get_distribution(modulename) except pkg_resources.DistributionNotFound: mod = identify_module(modulename) # raises ModuleNotFound if not hasattr(mod, '__version__'): raise ModuleNotFound('module has no __version__') version = mod.__version__ else: version = dist.version except ModuleNotFound: exc = sys.exc_info()[1] sys.stderr.write(error_template % { 'mod': modulename, 'error': str(exc), }) sys.stderr.write('\n') else: print(ver_template % { 'mod': modulename, 'version': version, })
python
def find_version(*args): """Find the versions of the given named modules, printing the discovered versions to stdout and errors discovering versions to stderr.""" if len(args) == 1: ver_template = "%(version)s" error_template = "Distribution/module '%(mod)s' not found (%(error)s)" else: ver_template = "%(mod)s: %(version)s" error_template = "%(mod)s: not found (%(error)s)" import pkg_resources for modulename in args: try: try: dist = pkg_resources.get_distribution(modulename) except pkg_resources.DistributionNotFound: mod = identify_module(modulename) # raises ModuleNotFound if not hasattr(mod, '__version__'): raise ModuleNotFound('module has no __version__') version = mod.__version__ else: version = dist.version except ModuleNotFound: exc = sys.exc_info()[1] sys.stderr.write(error_template % { 'mod': modulename, 'error': str(exc), }) sys.stderr.write('\n') else: print(ver_template % { 'mod': modulename, 'version': version, })
[ "def", "find_version", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "ver_template", "=", "\"%(version)s\"", "error_template", "=", "\"Distribution/module '%(mod)s' not found (%(error)s)\"", "else", ":", "ver_template", "=", "\"%(mod)s: %(version)s\"", "error_template", "=", "\"%(mod)s: not found (%(error)s)\"", "import", "pkg_resources", "for", "modulename", "in", "args", ":", "try", ":", "try", ":", "dist", "=", "pkg_resources", ".", "get_distribution", "(", "modulename", ")", "except", "pkg_resources", ".", "DistributionNotFound", ":", "mod", "=", "identify_module", "(", "modulename", ")", "# raises ModuleNotFound", "if", "not", "hasattr", "(", "mod", ",", "'__version__'", ")", ":", "raise", "ModuleNotFound", "(", "'module has no __version__'", ")", "version", "=", "mod", ".", "__version__", "else", ":", "version", "=", "dist", ".", "version", "except", "ModuleNotFound", ":", "exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "sys", ".", "stderr", ".", "write", "(", "error_template", "%", "{", "'mod'", ":", "modulename", ",", "'error'", ":", "str", "(", "exc", ")", ",", "}", ")", "sys", ".", "stderr", ".", "write", "(", "'\\n'", ")", "else", ":", "print", "(", "ver_template", "%", "{", "'mod'", ":", "modulename", ",", "'version'", ":", "version", ",", "}", ")" ]
Find the versions of the given named modules, printing the discovered versions to stdout and errors discovering versions to stderr.
[ "Find", "the", "versions", "of", "the", "given", "named", "modules", "printing", "the", "discovered", "versions", "to", "stdout", "and", "errors", "discovering", "versions", "to", "stderr", "." ]
2c7cbe0d8a6789ede48c53f263872ceac5b67ca3
https://github.com/markpasc/pywhich/blob/2c7cbe0d8a6789ede48c53f263872ceac5b67ca3/pywhich.py#L114-L151
248,533
markpasc/pywhich
pywhich.py
main
def main(argv=None): """Run the pywhich command as if invoked with arguments `argv`. If `argv` is `None`, arguments from `sys.argv` are used. """ if argv is None: argv = sys.argv parser = OptionParser() parser.add_option('-v', '--verbose', dest="verbose", action="count", default=2, help="be chattier (stackable)") def quiet(option, opt_str, value, parser): parser.values.verbose -= 1 parser.add_option('-q', '--quiet', action="callback", callback=quiet, help="be less chatty (stackable)") parser.add_option('-r', action="store_true", dest="real_path", default=False, help="dereference symlinks") parser.add_option('-b', action="store_true", dest="show_directory", default=False, help="show directory instead of filename") parser.add_option('-i', '--hide-init', action="store_true", dest="hide_init", default=False, help="show directory if the module ends in __init__.py") parser.add_option('-s', '--source', action="store_true", dest="find_source", default=False, help="find .py files for .pyc/.pyo files") parser.add_option('--ver', action="store_true", dest="find_version", default=False, help="find the version of the named package, not the location on disk") opts, args = parser.parse_args() verbose = max(0, min(4, opts.verbose)) log_levels = (logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG) logging.basicConfig() log.setLevel(log_levels[verbose]) if opts.find_version: find_version(*args) else: kwargs = dict((fld, getattr(opts, fld)) for fld in ('real_path', 'show_directory', 'find_source', 'hide_init')) identify_modules(*args, **kwargs) return 0
python
def main(argv=None): """Run the pywhich command as if invoked with arguments `argv`. If `argv` is `None`, arguments from `sys.argv` are used. """ if argv is None: argv = sys.argv parser = OptionParser() parser.add_option('-v', '--verbose', dest="verbose", action="count", default=2, help="be chattier (stackable)") def quiet(option, opt_str, value, parser): parser.values.verbose -= 1 parser.add_option('-q', '--quiet', action="callback", callback=quiet, help="be less chatty (stackable)") parser.add_option('-r', action="store_true", dest="real_path", default=False, help="dereference symlinks") parser.add_option('-b', action="store_true", dest="show_directory", default=False, help="show directory instead of filename") parser.add_option('-i', '--hide-init', action="store_true", dest="hide_init", default=False, help="show directory if the module ends in __init__.py") parser.add_option('-s', '--source', action="store_true", dest="find_source", default=False, help="find .py files for .pyc/.pyo files") parser.add_option('--ver', action="store_true", dest="find_version", default=False, help="find the version of the named package, not the location on disk") opts, args = parser.parse_args() verbose = max(0, min(4, opts.verbose)) log_levels = (logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG) logging.basicConfig() log.setLevel(log_levels[verbose]) if opts.find_version: find_version(*args) else: kwargs = dict((fld, getattr(opts, fld)) for fld in ('real_path', 'show_directory', 'find_source', 'hide_init')) identify_modules(*args, **kwargs) return 0
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "parser", "=", "OptionParser", "(", ")", "parser", ".", "add_option", "(", "'-v'", ",", "'--verbose'", ",", "dest", "=", "\"verbose\"", ",", "action", "=", "\"count\"", ",", "default", "=", "2", ",", "help", "=", "\"be chattier (stackable)\"", ")", "def", "quiet", "(", "option", ",", "opt_str", ",", "value", ",", "parser", ")", ":", "parser", ".", "values", ".", "verbose", "-=", "1", "parser", ".", "add_option", "(", "'-q'", ",", "'--quiet'", ",", "action", "=", "\"callback\"", ",", "callback", "=", "quiet", ",", "help", "=", "\"be less chatty (stackable)\"", ")", "parser", ".", "add_option", "(", "'-r'", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"real_path\"", ",", "default", "=", "False", ",", "help", "=", "\"dereference symlinks\"", ")", "parser", ".", "add_option", "(", "'-b'", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"show_directory\"", ",", "default", "=", "False", ",", "help", "=", "\"show directory instead of filename\"", ")", "parser", ".", "add_option", "(", "'-i'", ",", "'--hide-init'", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"hide_init\"", ",", "default", "=", "False", ",", "help", "=", "\"show directory if the module ends in __init__.py\"", ")", "parser", ".", "add_option", "(", "'-s'", ",", "'--source'", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"find_source\"", ",", "default", "=", "False", ",", "help", "=", "\"find .py files for .pyc/.pyo files\"", ")", "parser", ".", "add_option", "(", "'--ver'", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"find_version\"", ",", "default", "=", "False", ",", "help", "=", "\"find the version of the named package, not the location on disk\"", ")", "opts", ",", "args", "=", "parser", ".", "parse_args", "(", ")", "verbose", "=", "max", "(", "0", ",", "min", "(", "4", ",", "opts", ".", "verbose", ")", ")", "log_levels", "=", "(", "logging", ".", "CRITICAL", ",", "logging", ".", "ERROR", ",", "logging", ".", "WARNING", ",", "logging", ".", "INFO", ",", "logging", ".", "DEBUG", ")", "logging", ".", "basicConfig", "(", ")", "log", ".", "setLevel", "(", "log_levels", "[", "verbose", "]", ")", "if", "opts", ".", "find_version", ":", "find_version", "(", "*", "args", ")", "else", ":", "kwargs", "=", "dict", "(", "(", "fld", ",", "getattr", "(", "opts", ",", "fld", ")", ")", "for", "fld", "in", "(", "'real_path'", ",", "'show_directory'", ",", "'find_source'", ",", "'hide_init'", ")", ")", "identify_modules", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "0" ]
Run the pywhich command as if invoked with arguments `argv`. If `argv` is `None`, arguments from `sys.argv` are used.
[ "Run", "the", "pywhich", "command", "as", "if", "invoked", "with", "arguments", "argv", "." ]
2c7cbe0d8a6789ede48c53f263872ceac5b67ca3
https://github.com/markpasc/pywhich/blob/2c7cbe0d8a6789ede48c53f263872ceac5b67ca3/pywhich.py#L154-L197
248,534
vecnet/vecnet.simulation
vecnet/simulation/__init__.py
DictConvertible.read_json_file
def read_json_file(cls, path): """ Read an instance from a JSON-formatted file. :return: A new instance """ with open(path, 'r') as f: return cls.from_dict(json.load(f))
python
def read_json_file(cls, path): """ Read an instance from a JSON-formatted file. :return: A new instance """ with open(path, 'r') as f: return cls.from_dict(json.load(f))
[ "def", "read_json_file", "(", "cls", ",", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "return", "cls", ".", "from_dict", "(", "json", ".", "load", "(", "f", ")", ")" ]
Read an instance from a JSON-formatted file. :return: A new instance
[ "Read", "an", "instance", "from", "a", "JSON", "-", "formatted", "file", "." ]
3a4b3df7b12418c6fa8a7d9cd49656a1c031fc0e
https://github.com/vecnet/vecnet.simulation/blob/3a4b3df7b12418c6fa8a7d9cd49656a1c031fc0e/vecnet/simulation/__init__.py#L32-L39
248,535
vecnet/vecnet.simulation
vecnet/simulation/__init__.py
DictConvertible.write_json_file
def write_json_file(self, path): """ Write the instance in JSON format to a file. """ with open(path, 'w') as f: json.dump(self.to_dict(), f, indent=2)
python
def write_json_file(self, path): """ Write the instance in JSON format to a file. """ with open(path, 'w') as f: json.dump(self.to_dict(), f, indent=2)
[ "def", "write_json_file", "(", "self", ",", "path", ")", ":", "with", "open", "(", "path", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "self", ".", "to_dict", "(", ")", ",", "f", ",", "indent", "=", "2", ")" ]
Write the instance in JSON format to a file.
[ "Write", "the", "instance", "in", "JSON", "format", "to", "a", "file", "." ]
3a4b3df7b12418c6fa8a7d9cd49656a1c031fc0e
https://github.com/vecnet/vecnet.simulation/blob/3a4b3df7b12418c6fa8a7d9cd49656a1c031fc0e/vecnet/simulation/__init__.py#L50-L55
248,536
ardydedase/pycouchbase
pycouchbase/fields.py
EmailField.is_valid
def is_valid(email): """Email address validation method. :param email: Email address to be saved. :type email: basestring :returns: True if email address is correct, False otherwise. :rtype: bool """ if isinstance(email, basestring) and EMAIL_RE.match(email): return True return False
python
def is_valid(email): """Email address validation method. :param email: Email address to be saved. :type email: basestring :returns: True if email address is correct, False otherwise. :rtype: bool """ if isinstance(email, basestring) and EMAIL_RE.match(email): return True return False
[ "def", "is_valid", "(", "email", ")", ":", "if", "isinstance", "(", "email", ",", "basestring", ")", "and", "EMAIL_RE", ".", "match", "(", "email", ")", ":", "return", "True", "return", "False" ]
Email address validation method. :param email: Email address to be saved. :type email: basestring :returns: True if email address is correct, False otherwise. :rtype: bool
[ "Email", "address", "validation", "method", "." ]
6f010b4d2ef41aead2366878d0cf0b1284c0db0e
https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/pycouchbase/fields.py#L143-L153
248,537
ardydedase/pycouchbase
pycouchbase/fields.py
PasswordField.check_password
def check_password(self, raw_password): """Validates the given raw password against the intance's encrypted one. :param raw_password: Raw password to be checked against. :type raw_password: unicode :returns: True if comparison was successful, False otherwise. :rtype: bool :raises: :exc:`ImportError` if `py-bcrypt` was not found. """ bcrypt = self.get_bcrypt() return bcrypt.hashpw(raw_password, self.value)==self.value
python
def check_password(self, raw_password): """Validates the given raw password against the intance's encrypted one. :param raw_password: Raw password to be checked against. :type raw_password: unicode :returns: True if comparison was successful, False otherwise. :rtype: bool :raises: :exc:`ImportError` if `py-bcrypt` was not found. """ bcrypt = self.get_bcrypt() return bcrypt.hashpw(raw_password, self.value)==self.value
[ "def", "check_password", "(", "self", ",", "raw_password", ")", ":", "bcrypt", "=", "self", ".", "get_bcrypt", "(", ")", "return", "bcrypt", ".", "hashpw", "(", "raw_password", ",", "self", ".", "value", ")", "==", "self", ".", "value" ]
Validates the given raw password against the intance's encrypted one. :param raw_password: Raw password to be checked against. :type raw_password: unicode :returns: True if comparison was successful, False otherwise. :rtype: bool :raises: :exc:`ImportError` if `py-bcrypt` was not found.
[ "Validates", "the", "given", "raw", "password", "against", "the", "intance", "s", "encrypted", "one", "." ]
6f010b4d2ef41aead2366878d0cf0b1284c0db0e
https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/pycouchbase/fields.py#L189-L199
248,538
fred49/argtoolbox
setup.py
is_archlinux
def is_archlinux(): """return True if the current distribution is running on debian like OS.""" if platform.system().lower() == 'linux': if platform.linux_distribution() == ('', '', ''): # undefined distribution. Fixed in python 3. if os.path.exists('/etc/arch-release'): return True return False
python
def is_archlinux(): """return True if the current distribution is running on debian like OS.""" if platform.system().lower() == 'linux': if platform.linux_distribution() == ('', '', ''): # undefined distribution. Fixed in python 3. if os.path.exists('/etc/arch-release'): return True return False
[ "def", "is_archlinux", "(", ")", ":", "if", "platform", ".", "system", "(", ")", ".", "lower", "(", ")", "==", "'linux'", ":", "if", "platform", ".", "linux_distribution", "(", ")", "==", "(", "''", ",", "''", ",", "''", ")", ":", "# undefined distribution. Fixed in python 3.", "if", "os", ".", "path", ".", "exists", "(", "'/etc/arch-release'", ")", ":", "return", "True", "return", "False" ]
return True if the current distribution is running on debian like OS.
[ "return", "True", "if", "the", "current", "distribution", "is", "running", "on", "debian", "like", "OS", "." ]
e32ad6265567d5a1891df3c3425423774dafab41
https://github.com/fred49/argtoolbox/blob/e32ad6265567d5a1891df3c3425423774dafab41/setup.py#L46-L53
248,539
malthe/pop
src/pop/client.py
ZookeeperClient.create_or_clear
def create_or_clear(self, path, **kwargs): """Create path and recursively clear contents.""" try: yield self.create(path, **kwargs) except NodeExistsException: children = yield self.get_children(path) for name in children: yield self.recursive_delete(path + "/" + name)
python
def create_or_clear(self, path, **kwargs): """Create path and recursively clear contents.""" try: yield self.create(path, **kwargs) except NodeExistsException: children = yield self.get_children(path) for name in children: yield self.recursive_delete(path + "/" + name)
[ "def", "create_or_clear", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "try", ":", "yield", "self", ".", "create", "(", "path", ",", "*", "*", "kwargs", ")", "except", "NodeExistsException", ":", "children", "=", "yield", "self", ".", "get_children", "(", "path", ")", "for", "name", "in", "children", ":", "yield", "self", ".", "recursive_delete", "(", "path", "+", "\"/\"", "+", "name", ")" ]
Create path and recursively clear contents.
[ "Create", "path", "and", "recursively", "clear", "contents", "." ]
3b58b91b41d8b9bee546eb40dc280a57500b8bed
https://github.com/malthe/pop/blob/3b58b91b41d8b9bee546eb40dc280a57500b8bed/src/pop/client.py#L12-L20
248,540
malthe/pop
src/pop/client.py
ZookeeperClient.recursive_delete
def recursive_delete(self, path, **kwargs): """Recursively delete path.""" while True: try: yield self.delete(path, **kwargs) except NoNodeException: break except NotEmptyException: children = yield self.get_children(path) for name in children: yield self.recursive_delete(path + "/" + name) else: break
python
def recursive_delete(self, path, **kwargs): """Recursively delete path.""" while True: try: yield self.delete(path, **kwargs) except NoNodeException: break except NotEmptyException: children = yield self.get_children(path) for name in children: yield self.recursive_delete(path + "/" + name) else: break
[ "def", "recursive_delete", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "while", "True", ":", "try", ":", "yield", "self", ".", "delete", "(", "path", ",", "*", "*", "kwargs", ")", "except", "NoNodeException", ":", "break", "except", "NotEmptyException", ":", "children", "=", "yield", "self", ".", "get_children", "(", "path", ")", "for", "name", "in", "children", ":", "yield", "self", ".", "recursive_delete", "(", "path", "+", "\"/\"", "+", "name", ")", "else", ":", "break" ]
Recursively delete path.
[ "Recursively", "delete", "path", "." ]
3b58b91b41d8b9bee546eb40dc280a57500b8bed
https://github.com/malthe/pop/blob/3b58b91b41d8b9bee546eb40dc280a57500b8bed/src/pop/client.py#L23-L36
248,541
malthe/pop
src/pop/client.py
ZookeeperClient.create_path
def create_path(self, path, **kwargs): """Create nodes required to complete path.""" i = 0 while i < len(path): i = path.find("/", i) if i < 0: return subpath = path[:i] if i > 0: try: yield self.create(subpath, **kwargs) except NodeExistsException: pass i += 1
python
def create_path(self, path, **kwargs): """Create nodes required to complete path.""" i = 0 while i < len(path): i = path.find("/", i) if i < 0: return subpath = path[:i] if i > 0: try: yield self.create(subpath, **kwargs) except NodeExistsException: pass i += 1
[ "def", "create_path", "(", "self", ",", "path", ",", "*", "*", "kwargs", ")", ":", "i", "=", "0", "while", "i", "<", "len", "(", "path", ")", ":", "i", "=", "path", ".", "find", "(", "\"/\"", ",", "i", ")", "if", "i", "<", "0", ":", "return", "subpath", "=", "path", "[", ":", "i", "]", "if", "i", ">", "0", ":", "try", ":", "yield", "self", ".", "create", "(", "subpath", ",", "*", "*", "kwargs", ")", "except", "NodeExistsException", ":", "pass", "i", "+=", "1" ]
Create nodes required to complete path.
[ "Create", "nodes", "required", "to", "complete", "path", "." ]
3b58b91b41d8b9bee546eb40dc280a57500b8bed
https://github.com/malthe/pop/blob/3b58b91b41d8b9bee546eb40dc280a57500b8bed/src/pop/client.py#L39-L57
248,542
malthe/pop
src/pop/client.py
ZookeeperClient.set_or_create
def set_or_create(self, path, *args, **kwargs): """Sets the data of a node at the given path, or creates it.""" d = self.set(path, *args, **kwargs) @d.addErrback def _error(result): return self.create(path, *args, **kwargs) return d
python
def set_or_create(self, path, *args, **kwargs): """Sets the data of a node at the given path, or creates it.""" d = self.set(path, *args, **kwargs) @d.addErrback def _error(result): return self.create(path, *args, **kwargs) return d
[ "def", "set_or_create", "(", "self", ",", "path", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "d", "=", "self", ".", "set", "(", "path", ",", "*", "args", ",", "*", "*", "kwargs", ")", "@", "d", ".", "addErrback", "def", "_error", "(", "result", ")", ":", "return", "self", ".", "create", "(", "path", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "d" ]
Sets the data of a node at the given path, or creates it.
[ "Sets", "the", "data", "of", "a", "node", "at", "the", "given", "path", "or", "creates", "it", "." ]
3b58b91b41d8b9bee546eb40dc280a57500b8bed
https://github.com/malthe/pop/blob/3b58b91b41d8b9bee546eb40dc280a57500b8bed/src/pop/client.py#L59-L68
248,543
malthe/pop
src/pop/client.py
ZookeeperClient.get_or_wait
def get_or_wait(self, path, name): """Get data of node under path, or wait for it.""" # First, get children and watch folder. d, watch = self.get_children_and_watch(path) deferred = Deferred() path += "/" + name @watch.addCallback def _notify(event): if event.type_name == "child": d = self.get(path) d.addCallback(deferred.callback) # Retrieve children. children = yield d if name in children: watch.cancel() deferred = self.get(path) result = yield deferred returnValue(result)
python
def get_or_wait(self, path, name): """Get data of node under path, or wait for it.""" # First, get children and watch folder. d, watch = self.get_children_and_watch(path) deferred = Deferred() path += "/" + name @watch.addCallback def _notify(event): if event.type_name == "child": d = self.get(path) d.addCallback(deferred.callback) # Retrieve children. children = yield d if name in children: watch.cancel() deferred = self.get(path) result = yield deferred returnValue(result)
[ "def", "get_or_wait", "(", "self", ",", "path", ",", "name", ")", ":", "# First, get children and watch folder.", "d", ",", "watch", "=", "self", ".", "get_children_and_watch", "(", "path", ")", "deferred", "=", "Deferred", "(", ")", "path", "+=", "\"/\"", "+", "name", "@", "watch", ".", "addCallback", "def", "_notify", "(", "event", ")", ":", "if", "event", ".", "type_name", "==", "\"child\"", ":", "d", "=", "self", ".", "get", "(", "path", ")", "d", ".", "addCallback", "(", "deferred", ".", "callback", ")", "# Retrieve children.", "children", "=", "yield", "d", "if", "name", "in", "children", ":", "watch", ".", "cancel", "(", ")", "deferred", "=", "self", ".", "get", "(", "path", ")", "result", "=", "yield", "deferred", "returnValue", "(", "result", ")" ]
Get data of node under path, or wait for it.
[ "Get", "data", "of", "node", "under", "path", "or", "wait", "for", "it", "." ]
3b58b91b41d8b9bee546eb40dc280a57500b8bed
https://github.com/malthe/pop/blob/3b58b91b41d8b9bee546eb40dc280a57500b8bed/src/pop/client.py#L71-L94
248,544
ryanjdillon/pyotelem
pyotelem/utils.py
contiguous_regions
def contiguous_regions(condition): '''Finds contiguous True regions of the boolean array 'condition'. Args ---- condition: numpy.ndarray, dtype bool boolean mask array, but can pass the condition itself (e.g. x > 5) Returns ------- start_ind: numpy.ndarray, dtype int array with the start indices for each contiguous region stop_ind: numpy.ndarray, dtype int array with the stop indices for each contiguous region Notes ----- This function is adpated from Joe Kington's answer on StackOverflow: http://stackoverflow.com/a/4495197/943773 ''' import numpy if condition.ndim > 1: raise IndexError('contiguous_regions(): condition must be 1-D') # Find the indicies of changes in 'condition' idx = numpy.diff(condition).nonzero()[0] if condition[0]: # If the start of condition is True prepend a 0 idx = numpy.r_[0, idx] if condition[-1]: # If the end of condition is True, append the length of the array idx = numpy.r_[idx, condition.size] # Edit # Reshape the result into two columns idx.shape = (-1,2) # We need to start things after the change in 'condition'. Therefore, # we'll shift the index by 1 to the right. start_ind = idx[:,0] + 1 # keep the stop ending just before the change in condition stop_ind = idx[:,1] # remove reversed or same start/stop index good_vals = (stop_ind-start_ind) > 0 start_ind = start_ind[good_vals] stop_ind = stop_ind[good_vals] return start_ind, stop_ind
python
def contiguous_regions(condition): '''Finds contiguous True regions of the boolean array 'condition'. Args ---- condition: numpy.ndarray, dtype bool boolean mask array, but can pass the condition itself (e.g. x > 5) Returns ------- start_ind: numpy.ndarray, dtype int array with the start indices for each contiguous region stop_ind: numpy.ndarray, dtype int array with the stop indices for each contiguous region Notes ----- This function is adpated from Joe Kington's answer on StackOverflow: http://stackoverflow.com/a/4495197/943773 ''' import numpy if condition.ndim > 1: raise IndexError('contiguous_regions(): condition must be 1-D') # Find the indicies of changes in 'condition' idx = numpy.diff(condition).nonzero()[0] if condition[0]: # If the start of condition is True prepend a 0 idx = numpy.r_[0, idx] if condition[-1]: # If the end of condition is True, append the length of the array idx = numpy.r_[idx, condition.size] # Edit # Reshape the result into two columns idx.shape = (-1,2) # We need to start things after the change in 'condition'. Therefore, # we'll shift the index by 1 to the right. start_ind = idx[:,0] + 1 # keep the stop ending just before the change in condition stop_ind = idx[:,1] # remove reversed or same start/stop index good_vals = (stop_ind-start_ind) > 0 start_ind = start_ind[good_vals] stop_ind = stop_ind[good_vals] return start_ind, stop_ind
[ "def", "contiguous_regions", "(", "condition", ")", ":", "import", "numpy", "if", "condition", ".", "ndim", ">", "1", ":", "raise", "IndexError", "(", "'contiguous_regions(): condition must be 1-D'", ")", "# Find the indicies of changes in 'condition'", "idx", "=", "numpy", ".", "diff", "(", "condition", ")", ".", "nonzero", "(", ")", "[", "0", "]", "if", "condition", "[", "0", "]", ":", "# If the start of condition is True prepend a 0", "idx", "=", "numpy", ".", "r_", "[", "0", ",", "idx", "]", "if", "condition", "[", "-", "1", "]", ":", "# If the end of condition is True, append the length of the array", "idx", "=", "numpy", ".", "r_", "[", "idx", ",", "condition", ".", "size", "]", "# Edit", "# Reshape the result into two columns", "idx", ".", "shape", "=", "(", "-", "1", ",", "2", ")", "# We need to start things after the change in 'condition'. Therefore,", "# we'll shift the index by 1 to the right.", "start_ind", "=", "idx", "[", ":", ",", "0", "]", "+", "1", "# keep the stop ending just before the change in condition", "stop_ind", "=", "idx", "[", ":", ",", "1", "]", "# remove reversed or same start/stop index", "good_vals", "=", "(", "stop_ind", "-", "start_ind", ")", ">", "0", "start_ind", "=", "start_ind", "[", "good_vals", "]", "stop_ind", "=", "stop_ind", "[", "good_vals", "]", "return", "start_ind", ",", "stop_ind" ]
Finds contiguous True regions of the boolean array 'condition'. Args ---- condition: numpy.ndarray, dtype bool boolean mask array, but can pass the condition itself (e.g. x > 5) Returns ------- start_ind: numpy.ndarray, dtype int array with the start indices for each contiguous region stop_ind: numpy.ndarray, dtype int array with the stop indices for each contiguous region Notes ----- This function is adpated from Joe Kington's answer on StackOverflow: http://stackoverflow.com/a/4495197/943773
[ "Finds", "contiguous", "True", "regions", "of", "the", "boolean", "array", "condition", "." ]
816563a9c3feb3fa416f1c2921c6b75db34111ad
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/utils.py#L20-L70
248,545
ryanjdillon/pyotelem
pyotelem/utils.py
rm_regions
def rm_regions(a, b, a_start_ind, a_stop_ind): '''Remove contiguous regions in `a` before region `b` Boolean arrays `a` and `b` should have alternating occuances of regions of `True` values. This routine removes additional contiguous regions in `a` that occur before a complimentary region in `b` has occured Args ---- a: ndarray Boolean array with regions of contiguous `True` values b: ndarray Boolean array with regions of contiguous `True` values a_start_ind: ndarray indices of start of `a` regions a_stop_ind: ndarray indices of stop of `a` regions Returns ------- a: ndarray Boolean array with regions for which began before a complimentary region in `b` have occured ''' import numpy for i in range(len(a_stop_ind)): next_a_start = numpy.argmax(a[a_stop_ind[i]:]) next_b_start = numpy.argmax(b[a_stop_ind[i]:]) if next_b_start > next_a_start: a[a_start_ind[i]:a_stop_ind[i]] = False return a
python
def rm_regions(a, b, a_start_ind, a_stop_ind): '''Remove contiguous regions in `a` before region `b` Boolean arrays `a` and `b` should have alternating occuances of regions of `True` values. This routine removes additional contiguous regions in `a` that occur before a complimentary region in `b` has occured Args ---- a: ndarray Boolean array with regions of contiguous `True` values b: ndarray Boolean array with regions of contiguous `True` values a_start_ind: ndarray indices of start of `a` regions a_stop_ind: ndarray indices of stop of `a` regions Returns ------- a: ndarray Boolean array with regions for which began before a complimentary region in `b` have occured ''' import numpy for i in range(len(a_stop_ind)): next_a_start = numpy.argmax(a[a_stop_ind[i]:]) next_b_start = numpy.argmax(b[a_stop_ind[i]:]) if next_b_start > next_a_start: a[a_start_ind[i]:a_stop_ind[i]] = False return a
[ "def", "rm_regions", "(", "a", ",", "b", ",", "a_start_ind", ",", "a_stop_ind", ")", ":", "import", "numpy", "for", "i", "in", "range", "(", "len", "(", "a_stop_ind", ")", ")", ":", "next_a_start", "=", "numpy", ".", "argmax", "(", "a", "[", "a_stop_ind", "[", "i", "]", ":", "]", ")", "next_b_start", "=", "numpy", ".", "argmax", "(", "b", "[", "a_stop_ind", "[", "i", "]", ":", "]", ")", "if", "next_b_start", ">", "next_a_start", ":", "a", "[", "a_start_ind", "[", "i", "]", ":", "a_stop_ind", "[", "i", "]", "]", "=", "False", "return", "a" ]
Remove contiguous regions in `a` before region `b` Boolean arrays `a` and `b` should have alternating occuances of regions of `True` values. This routine removes additional contiguous regions in `a` that occur before a complimentary region in `b` has occured Args ---- a: ndarray Boolean array with regions of contiguous `True` values b: ndarray Boolean array with regions of contiguous `True` values a_start_ind: ndarray indices of start of `a` regions a_stop_ind: ndarray indices of stop of `a` regions Returns ------- a: ndarray Boolean array with regions for which began before a complimentary region in `b` have occured
[ "Remove", "contiguous", "regions", "in", "a", "before", "region", "b" ]
816563a9c3feb3fa416f1c2921c6b75db34111ad
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/utils.py#L73-L106
248,546
ryanjdillon/pyotelem
pyotelem/utils.py
recursive_input
def recursive_input(input_label, type_class): '''Recursive user input prompter with type checker Args ---- type_class: type name of python type (e.g. float, no parentheses) Returns ------- output: str value entered by user converted to type `type_class` Note ---- Use `ctrl-c` to exit input cycling ''' import sys type_str = str(type_class).split("'")[1] msg = 'Enter {} (type `{}`): '.format(input_label, type_str) # Catch `Ctrl-c` keyboard interupts try: output = input(msg) print('') # Type class input, else cycle input function again try: output = type_class(output) return output except: print('Input must be of type `{}`\n'.format(type_str)) return recursive_input(input_label, type_class) # Keyboard interrupt passed, exit recursive input except KeyboardInterrupt: return sys.exit()
python
def recursive_input(input_label, type_class): '''Recursive user input prompter with type checker Args ---- type_class: type name of python type (e.g. float, no parentheses) Returns ------- output: str value entered by user converted to type `type_class` Note ---- Use `ctrl-c` to exit input cycling ''' import sys type_str = str(type_class).split("'")[1] msg = 'Enter {} (type `{}`): '.format(input_label, type_str) # Catch `Ctrl-c` keyboard interupts try: output = input(msg) print('') # Type class input, else cycle input function again try: output = type_class(output) return output except: print('Input must be of type `{}`\n'.format(type_str)) return recursive_input(input_label, type_class) # Keyboard interrupt passed, exit recursive input except KeyboardInterrupt: return sys.exit()
[ "def", "recursive_input", "(", "input_label", ",", "type_class", ")", ":", "import", "sys", "type_str", "=", "str", "(", "type_class", ")", ".", "split", "(", "\"'\"", ")", "[", "1", "]", "msg", "=", "'Enter {} (type `{}`): '", ".", "format", "(", "input_label", ",", "type_str", ")", "# Catch `Ctrl-c` keyboard interupts", "try", ":", "output", "=", "input", "(", "msg", ")", "print", "(", "''", ")", "# Type class input, else cycle input function again", "try", ":", "output", "=", "type_class", "(", "output", ")", "return", "output", "except", ":", "print", "(", "'Input must be of type `{}`\\n'", ".", "format", "(", "type_str", ")", ")", "return", "recursive_input", "(", "input_label", ",", "type_class", ")", "# Keyboard interrupt passed, exit recursive input", "except", "KeyboardInterrupt", ":", "return", "sys", ".", "exit", "(", ")" ]
Recursive user input prompter with type checker Args ---- type_class: type name of python type (e.g. float, no parentheses) Returns ------- output: str value entered by user converted to type `type_class` Note ---- Use `ctrl-c` to exit input cycling
[ "Recursive", "user", "input", "prompter", "with", "type", "checker" ]
816563a9c3feb3fa416f1c2921c6b75db34111ad
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/utils.py#L109-L146
248,547
minhhoit/yacms
yacms/pages/templatetags/pages_tags.py
models_for_pages
def models_for_pages(*args): """ Create a select list containing each of the models that subclass the ``Page`` model. """ from warnings import warn warn("template tag models_for_pages is deprectaed, use " "PageAdmin.get_content_models instead") from yacms.pages.admin import PageAdmin return PageAdmin.get_content_models()
python
def models_for_pages(*args): """ Create a select list containing each of the models that subclass the ``Page`` model. """ from warnings import warn warn("template tag models_for_pages is deprectaed, use " "PageAdmin.get_content_models instead") from yacms.pages.admin import PageAdmin return PageAdmin.get_content_models()
[ "def", "models_for_pages", "(", "*", "args", ")", ":", "from", "warnings", "import", "warn", "warn", "(", "\"template tag models_for_pages is deprectaed, use \"", "\"PageAdmin.get_content_models instead\"", ")", "from", "yacms", ".", "pages", ".", "admin", "import", "PageAdmin", "return", "PageAdmin", ".", "get_content_models", "(", ")" ]
Create a select list containing each of the models that subclass the ``Page`` model.
[ "Create", "a", "select", "list", "containing", "each", "of", "the", "models", "that", "subclass", "the", "Page", "model", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/templatetags/pages_tags.py#L138-L147
248,548
minhhoit/yacms
yacms/pages/templatetags/pages_tags.py
set_model_permissions
def set_model_permissions(context, token): """ Assigns a permissions dict to the given model, much like Django does with its dashboard app list. Used within the change list for pages, to implement permission checks for the navigation tree. """ model = context[token.split_contents()[1]] opts = model._meta perm_name = opts.app_label + ".%s_" + opts.object_name.lower() request = context["request"] setattr(model, "perms", {}) for perm_type in ("add", "change", "delete"): model.perms[perm_type] = request.user.has_perm(perm_name % perm_type) return ""
python
def set_model_permissions(context, token): """ Assigns a permissions dict to the given model, much like Django does with its dashboard app list. Used within the change list for pages, to implement permission checks for the navigation tree. """ model = context[token.split_contents()[1]] opts = model._meta perm_name = opts.app_label + ".%s_" + opts.object_name.lower() request = context["request"] setattr(model, "perms", {}) for perm_type in ("add", "change", "delete"): model.perms[perm_type] = request.user.has_perm(perm_name % perm_type) return ""
[ "def", "set_model_permissions", "(", "context", ",", "token", ")", ":", "model", "=", "context", "[", "token", ".", "split_contents", "(", ")", "[", "1", "]", "]", "opts", "=", "model", ".", "_meta", "perm_name", "=", "opts", ".", "app_label", "+", "\".%s_\"", "+", "opts", ".", "object_name", ".", "lower", "(", ")", "request", "=", "context", "[", "\"request\"", "]", "setattr", "(", "model", ",", "\"perms\"", ",", "{", "}", ")", "for", "perm_type", "in", "(", "\"add\"", ",", "\"change\"", ",", "\"delete\"", ")", ":", "model", ".", "perms", "[", "perm_type", "]", "=", "request", ".", "user", ".", "has_perm", "(", "perm_name", "%", "perm_type", ")", "return", "\"\"" ]
Assigns a permissions dict to the given model, much like Django does with its dashboard app list. Used within the change list for pages, to implement permission checks for the navigation tree.
[ "Assigns", "a", "permissions", "dict", "to", "the", "given", "model", "much", "like", "Django", "does", "with", "its", "dashboard", "app", "list", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/templatetags/pages_tags.py#L151-L166
248,549
minhhoit/yacms
yacms/pages/templatetags/pages_tags.py
set_page_permissions
def set_page_permissions(context, token): """ Assigns a permissions dict to the given page instance, combining Django's permission for the page's model and a permission check against the instance itself calling the page's ``can_add``, ``can_change`` and ``can_delete`` custom methods. Used within the change list for pages, to implement permission checks for the navigation tree. """ page = context[token.split_contents()[1]] model = page.get_content_model() try: opts = model._meta except AttributeError: if model is None: error = _("Could not load the model for the following page, " "was it removed?") obj = page else: # A missing inner Meta class usually means the Page model # hasn't been directly subclassed. error = _("An error occured with the following class. Does " "it subclass Page directly?") obj = model.__class__.__name__ raise ImproperlyConfigured(error + " '%s'" % obj) perm_name = opts.app_label + ".%s_" + opts.object_name.lower() request = context["request"] setattr(page, "perms", {}) for perm_type in ("add", "change", "delete"): perm = request.user.has_perm(perm_name % perm_type) perm = perm and getattr(model, "can_%s" % perm_type)(request) page.perms[perm_type] = perm return ""
python
def set_page_permissions(context, token): """ Assigns a permissions dict to the given page instance, combining Django's permission for the page's model and a permission check against the instance itself calling the page's ``can_add``, ``can_change`` and ``can_delete`` custom methods. Used within the change list for pages, to implement permission checks for the navigation tree. """ page = context[token.split_contents()[1]] model = page.get_content_model() try: opts = model._meta except AttributeError: if model is None: error = _("Could not load the model for the following page, " "was it removed?") obj = page else: # A missing inner Meta class usually means the Page model # hasn't been directly subclassed. error = _("An error occured with the following class. Does " "it subclass Page directly?") obj = model.__class__.__name__ raise ImproperlyConfigured(error + " '%s'" % obj) perm_name = opts.app_label + ".%s_" + opts.object_name.lower() request = context["request"] setattr(page, "perms", {}) for perm_type in ("add", "change", "delete"): perm = request.user.has_perm(perm_name % perm_type) perm = perm and getattr(model, "can_%s" % perm_type)(request) page.perms[perm_type] = perm return ""
[ "def", "set_page_permissions", "(", "context", ",", "token", ")", ":", "page", "=", "context", "[", "token", ".", "split_contents", "(", ")", "[", "1", "]", "]", "model", "=", "page", ".", "get_content_model", "(", ")", "try", ":", "opts", "=", "model", ".", "_meta", "except", "AttributeError", ":", "if", "model", "is", "None", ":", "error", "=", "_", "(", "\"Could not load the model for the following page, \"", "\"was it removed?\"", ")", "obj", "=", "page", "else", ":", "# A missing inner Meta class usually means the Page model", "# hasn't been directly subclassed.", "error", "=", "_", "(", "\"An error occured with the following class. Does \"", "\"it subclass Page directly?\"", ")", "obj", "=", "model", ".", "__class__", ".", "__name__", "raise", "ImproperlyConfigured", "(", "error", "+", "\" '%s'\"", "%", "obj", ")", "perm_name", "=", "opts", ".", "app_label", "+", "\".%s_\"", "+", "opts", ".", "object_name", ".", "lower", "(", ")", "request", "=", "context", "[", "\"request\"", "]", "setattr", "(", "page", ",", "\"perms\"", ",", "{", "}", ")", "for", "perm_type", "in", "(", "\"add\"", ",", "\"change\"", ",", "\"delete\"", ")", ":", "perm", "=", "request", ".", "user", ".", "has_perm", "(", "perm_name", "%", "perm_type", ")", "perm", "=", "perm", "and", "getattr", "(", "model", ",", "\"can_%s\"", "%", "perm_type", ")", "(", "request", ")", "page", ".", "perms", "[", "perm_type", "]", "=", "perm", "return", "\"\"" ]
Assigns a permissions dict to the given page instance, combining Django's permission for the page's model and a permission check against the instance itself calling the page's ``can_add``, ``can_change`` and ``can_delete`` custom methods. Used within the change list for pages, to implement permission checks for the navigation tree.
[ "Assigns", "a", "permissions", "dict", "to", "the", "given", "page", "instance", "combining", "Django", "s", "permission", "for", "the", "page", "s", "model", "and", "a", "permission", "check", "against", "the", "instance", "itself", "calling", "the", "page", "s", "can_add", "can_change", "and", "can_delete", "custom", "methods", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/pages/templatetags/pages_tags.py#L170-L203
248,550
af/turrentine
turrentine/models.py
CMSPageManager.create
def create(self, *args, **kwargs): """ Allow an 'author' kwarg to automatically fill in the created_by and last_modified_by fields. """ if kwargs.has_key('author'): kwargs['created_by'] = kwargs['author'] kwargs['last_modified_by'] = kwargs['author'] del kwargs['author'] return super(CMSPageManager, self).create(*args, **kwargs)
python
def create(self, *args, **kwargs): """ Allow an 'author' kwarg to automatically fill in the created_by and last_modified_by fields. """ if kwargs.has_key('author'): kwargs['created_by'] = kwargs['author'] kwargs['last_modified_by'] = kwargs['author'] del kwargs['author'] return super(CMSPageManager, self).create(*args, **kwargs)
[ "def", "create", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "has_key", "(", "'author'", ")", ":", "kwargs", "[", "'created_by'", "]", "=", "kwargs", "[", "'author'", "]", "kwargs", "[", "'last_modified_by'", "]", "=", "kwargs", "[", "'author'", "]", "del", "kwargs", "[", "'author'", "]", "return", "super", "(", "CMSPageManager", ",", "self", ")", ".", "create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Allow an 'author' kwarg to automatically fill in the created_by and last_modified_by fields.
[ "Allow", "an", "author", "kwarg", "to", "automatically", "fill", "in", "the", "created_by", "and", "last_modified_by", "fields", "." ]
bbbd5139744ccc6264595cc8960784e5c308c009
https://github.com/af/turrentine/blob/bbbd5139744ccc6264595cc8960784e5c308c009/turrentine/models.py#L41-L49
248,551
af/turrentine
turrentine/models.py
CMSPage.get_template_options
def get_template_options(): """ Returns a list of all templates that can be used for CMS pages. The paths that are returned are relative to TURRENTINE_TEMPLATE_ROOT. """ template_root = turrentine_settings.TURRENTINE_TEMPLATE_ROOT turrentine_dir = turrentine_settings.TURRENTINE_TEMPLATE_SUBDIR output = [] for root, dirs, files in os.walk(turrentine_dir): for file_name in files: full_path = os.path.join(root, file_name) relative_path = os.path.relpath(full_path, template_root) output.append(relative_path) return output
python
def get_template_options(): """ Returns a list of all templates that can be used for CMS pages. The paths that are returned are relative to TURRENTINE_TEMPLATE_ROOT. """ template_root = turrentine_settings.TURRENTINE_TEMPLATE_ROOT turrentine_dir = turrentine_settings.TURRENTINE_TEMPLATE_SUBDIR output = [] for root, dirs, files in os.walk(turrentine_dir): for file_name in files: full_path = os.path.join(root, file_name) relative_path = os.path.relpath(full_path, template_root) output.append(relative_path) return output
[ "def", "get_template_options", "(", ")", ":", "template_root", "=", "turrentine_settings", ".", "TURRENTINE_TEMPLATE_ROOT", "turrentine_dir", "=", "turrentine_settings", ".", "TURRENTINE_TEMPLATE_SUBDIR", "output", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "turrentine_dir", ")", ":", "for", "file_name", "in", "files", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "file_name", ")", "relative_path", "=", "os", ".", "path", ".", "relpath", "(", "full_path", ",", "template_root", ")", "output", ".", "append", "(", "relative_path", ")", "return", "output" ]
Returns a list of all templates that can be used for CMS pages. The paths that are returned are relative to TURRENTINE_TEMPLATE_ROOT.
[ "Returns", "a", "list", "of", "all", "templates", "that", "can", "be", "used", "for", "CMS", "pages", ".", "The", "paths", "that", "are", "returned", "are", "relative", "to", "TURRENTINE_TEMPLATE_ROOT", "." ]
bbbd5139744ccc6264595cc8960784e5c308c009
https://github.com/af/turrentine/blob/bbbd5139744ccc6264595cc8960784e5c308c009/turrentine/models.py#L88-L101
248,552
kshlm/gant
gant/utils/ssh.py
launch_shell
def launch_shell(username, hostname, password, port=22): """ Launches an ssh shell """ if not username or not hostname or not password: return False with tempfile.NamedTemporaryFile() as tmpFile: os.system(sshCmdLine.format(password, tmpFile.name, username, hostname, port)) return True
python
def launch_shell(username, hostname, password, port=22): """ Launches an ssh shell """ if not username or not hostname or not password: return False with tempfile.NamedTemporaryFile() as tmpFile: os.system(sshCmdLine.format(password, tmpFile.name, username, hostname, port)) return True
[ "def", "launch_shell", "(", "username", ",", "hostname", ",", "password", ",", "port", "=", "22", ")", ":", "if", "not", "username", "or", "not", "hostname", "or", "not", "password", ":", "return", "False", "with", "tempfile", ".", "NamedTemporaryFile", "(", ")", "as", "tmpFile", ":", "os", ".", "system", "(", "sshCmdLine", ".", "format", "(", "password", ",", "tmpFile", ".", "name", ",", "username", ",", "hostname", ",", "port", ")", ")", "return", "True" ]
Launches an ssh shell
[ "Launches", "an", "ssh", "shell" ]
eabaa17ebfd31b1654ee1f27e7026f6d7b370609
https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/ssh.py#L10-L20
248,553
cariad/py-wpconfigr
wpconfigr/wp_config_string.py
WpConfigString._get_match
def _get_match(self, key): """ Gets a MatchObject for the given key. Args: key (str): Key of the property to look-up. Return: MatchObject: The discovered match. """ return self._get_string_match(key=key) or \ self._get_non_string_match(key=key)
python
def _get_match(self, key): """ Gets a MatchObject for the given key. Args: key (str): Key of the property to look-up. Return: MatchObject: The discovered match. """ return self._get_string_match(key=key) or \ self._get_non_string_match(key=key)
[ "def", "_get_match", "(", "self", ",", "key", ")", ":", "return", "self", ".", "_get_string_match", "(", "key", "=", "key", ")", "or", "self", ".", "_get_non_string_match", "(", "key", "=", "key", ")" ]
Gets a MatchObject for the given key. Args: key (str): Key of the property to look-up. Return: MatchObject: The discovered match.
[ "Gets", "a", "MatchObject", "for", "the", "given", "key", "." ]
8f25bb849b72ce95957566544a2be8445316c818
https://github.com/cariad/py-wpconfigr/blob/8f25bb849b72ce95957566544a2be8445316c818/wpconfigr/wp_config_string.py#L29-L41
248,554
cariad/py-wpconfigr
wpconfigr/wp_config_string.py
WpConfigString._get_non_string_match
def _get_non_string_match(self, key): """ Gets a MatchObject for the given key, assuming a non-string value. Args: key (str): Key of the property to look-up. Return: MatchObject: The discovered match. """ expression = r'(?:\s*)'.join([ '^', 'define', r'\(', '\'{}\''.format(key), ',', r'(.*)', r'\)', ';' ]) pattern = re.compile(expression, re.MULTILINE) return pattern.search(self._content)
python
def _get_non_string_match(self, key): """ Gets a MatchObject for the given key, assuming a non-string value. Args: key (str): Key of the property to look-up. Return: MatchObject: The discovered match. """ expression = r'(?:\s*)'.join([ '^', 'define', r'\(', '\'{}\''.format(key), ',', r'(.*)', r'\)', ';' ]) pattern = re.compile(expression, re.MULTILINE) return pattern.search(self._content)
[ "def", "_get_non_string_match", "(", "self", ",", "key", ")", ":", "expression", "=", "r'(?:\\s*)'", ".", "join", "(", "[", "'^'", ",", "'define'", ",", "r'\\('", ",", "'\\'{}\\''", ".", "format", "(", "key", ")", ",", "','", ",", "r'(.*)'", ",", "r'\\)'", ",", "';'", "]", ")", "pattern", "=", "re", ".", "compile", "(", "expression", ",", "re", ".", "MULTILINE", ")", "return", "pattern", ".", "search", "(", "self", ".", "_content", ")" ]
Gets a MatchObject for the given key, assuming a non-string value. Args: key (str): Key of the property to look-up. Return: MatchObject: The discovered match.
[ "Gets", "a", "MatchObject", "for", "the", "given", "key", "assuming", "a", "non", "-", "string", "value", "." ]
8f25bb849b72ce95957566544a2be8445316c818
https://github.com/cariad/py-wpconfigr/blob/8f25bb849b72ce95957566544a2be8445316c818/wpconfigr/wp_config_string.py#L43-L66
248,555
cariad/py-wpconfigr
wpconfigr/wp_config_string.py
WpConfigString._get_string_match
def _get_string_match(self, key): """ Gets a MatchObject for the given key, assuming a string value. Args: key (str): Key of the property to look-up. Return: MatchObject: The discovered match. """ expression = r'(?:\s*)'.join([ '^', 'define', r'\(', '\'{}\''.format(key), ',', r'\'(.*)\'', r'\)', ';' ]) pattern = re.compile(expression, re.MULTILINE) return pattern.search(self._content)
python
def _get_string_match(self, key): """ Gets a MatchObject for the given key, assuming a string value. Args: key (str): Key of the property to look-up. Return: MatchObject: The discovered match. """ expression = r'(?:\s*)'.join([ '^', 'define', r'\(', '\'{}\''.format(key), ',', r'\'(.*)\'', r'\)', ';' ]) pattern = re.compile(expression, re.MULTILINE) return pattern.search(self._content)
[ "def", "_get_string_match", "(", "self", ",", "key", ")", ":", "expression", "=", "r'(?:\\s*)'", ".", "join", "(", "[", "'^'", ",", "'define'", ",", "r'\\('", ",", "'\\'{}\\''", ".", "format", "(", "key", ")", ",", "','", ",", "r'\\'(.*)\\''", ",", "r'\\)'", ",", "';'", "]", ")", "pattern", "=", "re", ".", "compile", "(", "expression", ",", "re", ".", "MULTILINE", ")", "return", "pattern", ".", "search", "(", "self", ".", "_content", ")" ]
Gets a MatchObject for the given key, assuming a string value. Args: key (str): Key of the property to look-up. Return: MatchObject: The discovered match.
[ "Gets", "a", "MatchObject", "for", "the", "given", "key", "assuming", "a", "string", "value", "." ]
8f25bb849b72ce95957566544a2be8445316c818
https://github.com/cariad/py-wpconfigr/blob/8f25bb849b72ce95957566544a2be8445316c818/wpconfigr/wp_config_string.py#L68-L91
248,556
cariad/py-wpconfigr
wpconfigr/wp_config_string.py
WpConfigString._get_value_from_match
def _get_value_from_match(self, key, match): """ Gets the value of the property in the given MatchObject. Args: key (str): Key of the property looked-up. match (MatchObject): The matched property. Return: The discovered value, as a string or boolean. """ value = match.groups(1)[0] clean_value = str(value).lstrip().rstrip() if clean_value == 'true': self._log.info('Got value of "%s" as boolean true.', key) return True if clean_value == 'false': self._log.info('Got value of "%s" as boolean false.', key) return False try: float_value = float(clean_value) self._log.info('Got value of "%s" as float "%f".', key, float_value) return float_value except ValueError: self._log.info('Got value of "%s" as string "%s".', key, clean_value) return clean_value
python
def _get_value_from_match(self, key, match): """ Gets the value of the property in the given MatchObject. Args: key (str): Key of the property looked-up. match (MatchObject): The matched property. Return: The discovered value, as a string or boolean. """ value = match.groups(1)[0] clean_value = str(value).lstrip().rstrip() if clean_value == 'true': self._log.info('Got value of "%s" as boolean true.', key) return True if clean_value == 'false': self._log.info('Got value of "%s" as boolean false.', key) return False try: float_value = float(clean_value) self._log.info('Got value of "%s" as float "%f".', key, float_value) return float_value except ValueError: self._log.info('Got value of "%s" as string "%s".', key, clean_value) return clean_value
[ "def", "_get_value_from_match", "(", "self", ",", "key", ",", "match", ")", ":", "value", "=", "match", ".", "groups", "(", "1", ")", "[", "0", "]", "clean_value", "=", "str", "(", "value", ")", ".", "lstrip", "(", ")", ".", "rstrip", "(", ")", "if", "clean_value", "==", "'true'", ":", "self", ".", "_log", ".", "info", "(", "'Got value of \"%s\" as boolean true.'", ",", "key", ")", "return", "True", "if", "clean_value", "==", "'false'", ":", "self", ".", "_log", ".", "info", "(", "'Got value of \"%s\" as boolean false.'", ",", "key", ")", "return", "False", "try", ":", "float_value", "=", "float", "(", "clean_value", ")", "self", ".", "_log", ".", "info", "(", "'Got value of \"%s\" as float \"%f\".'", ",", "key", ",", "float_value", ")", "return", "float_value", "except", "ValueError", ":", "self", ".", "_log", ".", "info", "(", "'Got value of \"%s\" as string \"%s\".'", ",", "key", ",", "clean_value", ")", "return", "clean_value" ]
Gets the value of the property in the given MatchObject. Args: key (str): Key of the property looked-up. match (MatchObject): The matched property. Return: The discovered value, as a string or boolean.
[ "Gets", "the", "value", "of", "the", "property", "in", "the", "given", "MatchObject", "." ]
8f25bb849b72ce95957566544a2be8445316c818
https://github.com/cariad/py-wpconfigr/blob/8f25bb849b72ce95957566544a2be8445316c818/wpconfigr/wp_config_string.py#L93-L126
248,557
cariad/py-wpconfigr
wpconfigr/wp_config_string.py
WpConfigString.get
def get(self, key): """ Gets the value of the property of the given key. Args: key (str): Key of the property to look-up. """ match = self._get_match(key=key) if not match: return None return self._get_value_from_match(key=key, match=match)
python
def get(self, key): """ Gets the value of the property of the given key. Args: key (str): Key of the property to look-up. """ match = self._get_match(key=key) if not match: return None return self._get_value_from_match(key=key, match=match)
[ "def", "get", "(", "self", ",", "key", ")", ":", "match", "=", "self", ".", "_get_match", "(", "key", "=", "key", ")", "if", "not", "match", ":", "return", "None", "return", "self", ".", "_get_value_from_match", "(", "key", "=", "key", ",", "match", "=", "match", ")" ]
Gets the value of the property of the given key. Args: key (str): Key of the property to look-up.
[ "Gets", "the", "value", "of", "the", "property", "of", "the", "given", "key", "." ]
8f25bb849b72ce95957566544a2be8445316c818
https://github.com/cariad/py-wpconfigr/blob/8f25bb849b72ce95957566544a2be8445316c818/wpconfigr/wp_config_string.py#L128-L141
248,558
cariad/py-wpconfigr
wpconfigr/wp_config_string.py
WpConfigString.set
def set(self, key, value): """ Updates the value of the given key in the loaded content. Args: key (str): Key of the property to update. value (str): New value of the property. Return: bool: Indicates whether or not a change was made. """ match = self._get_match(key=key) if not match: self._log.info('"%s" does not exist, so it will be added.', key) if isinstance(value, str): self._log.info('"%s" will be added as a PHP string value.', key) value_str = '\'{}\''.format(value) else: self._log.info('"%s" will be added as a PHP object value.', key) value_str = str(value).lower() new = 'define(\'{key}\', {value});'.format( key=key, value=value_str) self._log.info('"%s" will be added as: %s', key, new) replace_this = '<?php\n' replace_with = '<?php\n' + new + '\n' self._content = self._content.replace(replace_this, replace_with) self._log.info('Content string has been updated.') return True if self._get_value_from_match(key=key, match=match) == value: self._log.info('"%s" is already up-to-date.', key) return False self._log.info('"%s" exists and will be updated.', key) start_index = match.start(1) end_index = match.end(1) if isinstance(value, bool): value = str(value).lower() self._log.info('"%s" will be updated with boolean value: %s', key, value) else: self._log.info('"%s" will be updated with string value: %s', key, value) start = self._content[:start_index] end = self._content[end_index:] self._content = start + value + end return True
python
def set(self, key, value): """ Updates the value of the given key in the loaded content. Args: key (str): Key of the property to update. value (str): New value of the property. Return: bool: Indicates whether or not a change was made. """ match = self._get_match(key=key) if not match: self._log.info('"%s" does not exist, so it will be added.', key) if isinstance(value, str): self._log.info('"%s" will be added as a PHP string value.', key) value_str = '\'{}\''.format(value) else: self._log.info('"%s" will be added as a PHP object value.', key) value_str = str(value).lower() new = 'define(\'{key}\', {value});'.format( key=key, value=value_str) self._log.info('"%s" will be added as: %s', key, new) replace_this = '<?php\n' replace_with = '<?php\n' + new + '\n' self._content = self._content.replace(replace_this, replace_with) self._log.info('Content string has been updated.') return True if self._get_value_from_match(key=key, match=match) == value: self._log.info('"%s" is already up-to-date.', key) return False self._log.info('"%s" exists and will be updated.', key) start_index = match.start(1) end_index = match.end(1) if isinstance(value, bool): value = str(value).lower() self._log.info('"%s" will be updated with boolean value: %s', key, value) else: self._log.info('"%s" will be updated with string value: %s', key, value) start = self._content[:start_index] end = self._content[end_index:] self._content = start + value + end return True
[ "def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "match", "=", "self", ".", "_get_match", "(", "key", "=", "key", ")", "if", "not", "match", ":", "self", ".", "_log", ".", "info", "(", "'\"%s\" does not exist, so it will be added.'", ",", "key", ")", "if", "isinstance", "(", "value", ",", "str", ")", ":", "self", ".", "_log", ".", "info", "(", "'\"%s\" will be added as a PHP string value.'", ",", "key", ")", "value_str", "=", "'\\'{}\\''", ".", "format", "(", "value", ")", "else", ":", "self", ".", "_log", ".", "info", "(", "'\"%s\" will be added as a PHP object value.'", ",", "key", ")", "value_str", "=", "str", "(", "value", ")", ".", "lower", "(", ")", "new", "=", "'define(\\'{key}\\', {value});'", ".", "format", "(", "key", "=", "key", ",", "value", "=", "value_str", ")", "self", ".", "_log", ".", "info", "(", "'\"%s\" will be added as: %s'", ",", "key", ",", "new", ")", "replace_this", "=", "'<?php\\n'", "replace_with", "=", "'<?php\\n'", "+", "new", "+", "'\\n'", "self", ".", "_content", "=", "self", ".", "_content", ".", "replace", "(", "replace_this", ",", "replace_with", ")", "self", ".", "_log", ".", "info", "(", "'Content string has been updated.'", ")", "return", "True", "if", "self", ".", "_get_value_from_match", "(", "key", "=", "key", ",", "match", "=", "match", ")", "==", "value", ":", "self", ".", "_log", ".", "info", "(", "'\"%s\" is already up-to-date.'", ",", "key", ")", "return", "False", "self", ".", "_log", ".", "info", "(", "'\"%s\" exists and will be updated.'", ",", "key", ")", "start_index", "=", "match", ".", "start", "(", "1", ")", "end_index", "=", "match", ".", "end", "(", "1", ")", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "value", "=", "str", "(", "value", ")", ".", "lower", "(", ")", "self", ".", "_log", ".", "info", "(", "'\"%s\" will be updated with boolean value: %s'", ",", "key", ",", "value", ")", "else", ":", "self", ".", "_log", ".", "info", "(", "'\"%s\" will be updated with string value: %s'", ",", "key", ",", "value", ")", "start", "=", "self", ".", "_content", "[", ":", "start_index", "]", "end", "=", "self", ".", "_content", "[", "end_index", ":", "]", "self", ".", "_content", "=", "start", "+", "value", "+", "end", "return", "True" ]
Updates the value of the given key in the loaded content. Args: key (str): Key of the property to update. value (str): New value of the property. Return: bool: Indicates whether or not a change was made.
[ "Updates", "the", "value", "of", "the", "given", "key", "in", "the", "loaded", "content", "." ]
8f25bb849b72ce95957566544a2be8445316c818
https://github.com/cariad/py-wpconfigr/blob/8f25bb849b72ce95957566544a2be8445316c818/wpconfigr/wp_config_string.py#L143-L204
248,559
pingviini/aja
src/aja/utils.py
get_buildout_config
def get_buildout_config(buildout_filename): """Parse buildout config with zc.buildout ConfigParser """ print("[localhost] get_buildout_config: {0:s}".format(buildout_filename)) buildout = Buildout(buildout_filename, [('buildout', 'verbosity', '-100')]) while True: try: len(buildout.items()) break except OSError: pass return buildout
python
def get_buildout_config(buildout_filename): """Parse buildout config with zc.buildout ConfigParser """ print("[localhost] get_buildout_config: {0:s}".format(buildout_filename)) buildout = Buildout(buildout_filename, [('buildout', 'verbosity', '-100')]) while True: try: len(buildout.items()) break except OSError: pass return buildout
[ "def", "get_buildout_config", "(", "buildout_filename", ")", ":", "print", "(", "\"[localhost] get_buildout_config: {0:s}\"", ".", "format", "(", "buildout_filename", ")", ")", "buildout", "=", "Buildout", "(", "buildout_filename", ",", "[", "(", "'buildout'", ",", "'verbosity'", ",", "'-100'", ")", "]", ")", "while", "True", ":", "try", ":", "len", "(", "buildout", ".", "items", "(", ")", ")", "break", "except", "OSError", ":", "pass", "return", "buildout" ]
Parse buildout config with zc.buildout ConfigParser
[ "Parse", "buildout", "config", "with", "zc", ".", "buildout", "ConfigParser" ]
60ce80aee082b7a1ea9c55471c6e717c9b46710f
https://github.com/pingviini/aja/blob/60ce80aee082b7a1ea9c55471c6e717c9b46710f/src/aja/utils.py#L30-L41
248,560
pingviini/aja
src/aja/utils.py
get_buildout_parts
def get_buildout_parts(buildout, query=None): """Return buildout parts matching the given query """ parts = names = (buildout['buildout'].get('parts') or '').split('\n') for name in names: part = buildout.get(name) or {} for key, value in (query or {}).items(): if value not in (part.get(key) or ''): parts.remove(name) break return parts
python
def get_buildout_parts(buildout, query=None): """Return buildout parts matching the given query """ parts = names = (buildout['buildout'].get('parts') or '').split('\n') for name in names: part = buildout.get(name) or {} for key, value in (query or {}).items(): if value not in (part.get(key) or ''): parts.remove(name) break return parts
[ "def", "get_buildout_parts", "(", "buildout", ",", "query", "=", "None", ")", ":", "parts", "=", "names", "=", "(", "buildout", "[", "'buildout'", "]", ".", "get", "(", "'parts'", ")", "or", "''", ")", ".", "split", "(", "'\\n'", ")", "for", "name", "in", "names", ":", "part", "=", "buildout", ".", "get", "(", "name", ")", "or", "{", "}", "for", "key", ",", "value", "in", "(", "query", "or", "{", "}", ")", ".", "items", "(", ")", ":", "if", "value", "not", "in", "(", "part", ".", "get", "(", "key", ")", "or", "''", ")", ":", "parts", ".", "remove", "(", "name", ")", "break", "return", "parts" ]
Return buildout parts matching the given query
[ "Return", "buildout", "parts", "matching", "the", "given", "query" ]
60ce80aee082b7a1ea9c55471c6e717c9b46710f
https://github.com/pingviini/aja/blob/60ce80aee082b7a1ea9c55471c6e717c9b46710f/src/aja/utils.py#L44-L54
248,561
pingviini/aja
src/aja/utils.py
get_buildout_eggs
def get_buildout_eggs(buildout, query=None): """Return buildout eggs matching the parts for the given query """ eggs = set() for name in get_buildout_parts(buildout, query=query): if name == 'buildout': continue # skip eggs from the buildout script itself path = os.path.join(buildout['buildout'].get('bin-directory'), name) if os.path.isfile(path): eggs.update(parse_eggs_list(path)) return list(eggs)
python
def get_buildout_eggs(buildout, query=None): """Return buildout eggs matching the parts for the given query """ eggs = set() for name in get_buildout_parts(buildout, query=query): if name == 'buildout': continue # skip eggs from the buildout script itself path = os.path.join(buildout['buildout'].get('bin-directory'), name) if os.path.isfile(path): eggs.update(parse_eggs_list(path)) return list(eggs)
[ "def", "get_buildout_eggs", "(", "buildout", ",", "query", "=", "None", ")", ":", "eggs", "=", "set", "(", ")", "for", "name", "in", "get_buildout_parts", "(", "buildout", ",", "query", "=", "query", ")", ":", "if", "name", "==", "'buildout'", ":", "continue", "# skip eggs from the buildout script itself", "path", "=", "os", ".", "path", ".", "join", "(", "buildout", "[", "'buildout'", "]", ".", "get", "(", "'bin-directory'", ")", ",", "name", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "eggs", ".", "update", "(", "parse_eggs_list", "(", "path", ")", ")", "return", "list", "(", "eggs", ")" ]
Return buildout eggs matching the parts for the given query
[ "Return", "buildout", "eggs", "matching", "the", "parts", "for", "the", "given", "query" ]
60ce80aee082b7a1ea9c55471c6e717c9b46710f
https://github.com/pingviini/aja/blob/60ce80aee082b7a1ea9c55471c6e717c9b46710f/src/aja/utils.py#L57-L67
248,562
pingviini/aja
src/aja/utils.py
parse_eggs_list
def parse_eggs_list(path): """Parse eggs list from the script at the given path """ with open(path, 'r') as script: data = script.readlines() start = 0 end = 0 for counter, line in enumerate(data): if not start: if 'sys.path[0:0]' in line: start = counter + 1 if counter >= start and not end: if ']' in line: end = counter script_eggs = tidy_eggs_list(data[start:end]) return script_eggs
python
def parse_eggs_list(path): """Parse eggs list from the script at the given path """ with open(path, 'r') as script: data = script.readlines() start = 0 end = 0 for counter, line in enumerate(data): if not start: if 'sys.path[0:0]' in line: start = counter + 1 if counter >= start and not end: if ']' in line: end = counter script_eggs = tidy_eggs_list(data[start:end]) return script_eggs
[ "def", "parse_eggs_list", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "script", ":", "data", "=", "script", ".", "readlines", "(", ")", "start", "=", "0", "end", "=", "0", "for", "counter", ",", "line", "in", "enumerate", "(", "data", ")", ":", "if", "not", "start", ":", "if", "'sys.path[0:0]'", "in", "line", ":", "start", "=", "counter", "+", "1", "if", "counter", ">=", "start", "and", "not", "end", ":", "if", "']'", "in", "line", ":", "end", "=", "counter", "script_eggs", "=", "tidy_eggs_list", "(", "data", "[", "start", ":", "end", "]", ")", "return", "script_eggs" ]
Parse eggs list from the script at the given path
[ "Parse", "eggs", "list", "from", "the", "script", "at", "the", "given", "path" ]
60ce80aee082b7a1ea9c55471c6e717c9b46710f
https://github.com/pingviini/aja/blob/60ce80aee082b7a1ea9c55471c6e717c9b46710f/src/aja/utils.py#L70-L85
248,563
pingviini/aja
src/aja/utils.py
tidy_eggs_list
def tidy_eggs_list(eggs_list): """Tidy the given eggs list """ tmp = [] for line in eggs_list: line = line.lstrip().rstrip() line = line.replace('\'', '') line = line.replace(',', '') if line.endswith('site-packages'): continue tmp.append(line) return tmp
python
def tidy_eggs_list(eggs_list): """Tidy the given eggs list """ tmp = [] for line in eggs_list: line = line.lstrip().rstrip() line = line.replace('\'', '') line = line.replace(',', '') if line.endswith('site-packages'): continue tmp.append(line) return tmp
[ "def", "tidy_eggs_list", "(", "eggs_list", ")", ":", "tmp", "=", "[", "]", "for", "line", "in", "eggs_list", ":", "line", "=", "line", ".", "lstrip", "(", ")", ".", "rstrip", "(", ")", "line", "=", "line", ".", "replace", "(", "'\\''", ",", "''", ")", "line", "=", "line", ".", "replace", "(", "','", ",", "''", ")", "if", "line", ".", "endswith", "(", "'site-packages'", ")", ":", "continue", "tmp", ".", "append", "(", "line", ")", "return", "tmp" ]
Tidy the given eggs list
[ "Tidy", "the", "given", "eggs", "list" ]
60ce80aee082b7a1ea9c55471c6e717c9b46710f
https://github.com/pingviini/aja/blob/60ce80aee082b7a1ea9c55471c6e717c9b46710f/src/aja/utils.py#L88-L99
248,564
heikomuller/sco-client
scocli/modelrun.py
Attachment.download
def download(self, filename=None): """Download an attachment. The files are currently not cached since they can be overwritten on the server. Parameters ---------- filename : string, optional Optional name for the file on local disk. Returns ------- string Path to downloaded temporary file on disk """ tmp_file, f_suffix = download_file(self.url) if not filename is None: shutil.move(tmp_file, filename) return filename else: return tmp_file
python
def download(self, filename=None): """Download an attachment. The files are currently not cached since they can be overwritten on the server. Parameters ---------- filename : string, optional Optional name for the file on local disk. Returns ------- string Path to downloaded temporary file on disk """ tmp_file, f_suffix = download_file(self.url) if not filename is None: shutil.move(tmp_file, filename) return filename else: return tmp_file
[ "def", "download", "(", "self", ",", "filename", "=", "None", ")", ":", "tmp_file", ",", "f_suffix", "=", "download_file", "(", "self", ".", "url", ")", "if", "not", "filename", "is", "None", ":", "shutil", ".", "move", "(", "tmp_file", ",", "filename", ")", "return", "filename", "else", ":", "return", "tmp_file" ]
Download an attachment. The files are currently not cached since they can be overwritten on the server. Parameters ---------- filename : string, optional Optional name for the file on local disk. Returns ------- string Path to downloaded temporary file on disk
[ "Download", "an", "attachment", ".", "The", "files", "are", "currently", "not", "cached", "since", "they", "can", "be", "overwritten", "on", "the", "server", "." ]
c4afab71297f73003379bba4c1679be9dcf7cef8
https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/modelrun.py#L68-L87
248,565
heikomuller/sco-client
scocli/modelrun.py
ModelRunHandle.attach_file
def attach_file(self, filename, resource_id=None): """Upload an attachment for the model run. Paramerers ---------- filename : string Path to uploaded file resource_id : string Identifier of the attachment. If None, the filename will be used as resource identifier. Returns ------- ModelRunHandle Refreshed run handle. """ # Use file base name as resource identifier if none given if resource_id is None: resource_id = os.path.basename(filename) # Need to append resource identifier to base attachment Url upload_url = self.links[REF_MODEL_RUN_ATTACHMENTS] + '/' + resource_id # Upload model output response = requests.post( upload_url, files={'file': open(filename, 'rb')} ) if response.status_code != 200: try: raise ValueError(json.loads(response.text)['message']) except KeyError as ex: raise ValueError('invalid state change: ' + str(response.text)) # Returned refreshed verion of the handle return self.refresh()
python
def attach_file(self, filename, resource_id=None): """Upload an attachment for the model run. Paramerers ---------- filename : string Path to uploaded file resource_id : string Identifier of the attachment. If None, the filename will be used as resource identifier. Returns ------- ModelRunHandle Refreshed run handle. """ # Use file base name as resource identifier if none given if resource_id is None: resource_id = os.path.basename(filename) # Need to append resource identifier to base attachment Url upload_url = self.links[REF_MODEL_RUN_ATTACHMENTS] + '/' + resource_id # Upload model output response = requests.post( upload_url, files={'file': open(filename, 'rb')} ) if response.status_code != 200: try: raise ValueError(json.loads(response.text)['message']) except KeyError as ex: raise ValueError('invalid state change: ' + str(response.text)) # Returned refreshed verion of the handle return self.refresh()
[ "def", "attach_file", "(", "self", ",", "filename", ",", "resource_id", "=", "None", ")", ":", "# Use file base name as resource identifier if none given", "if", "resource_id", "is", "None", ":", "resource_id", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "# Need to append resource identifier to base attachment Url", "upload_url", "=", "self", ".", "links", "[", "REF_MODEL_RUN_ATTACHMENTS", "]", "+", "'/'", "+", "resource_id", "# Upload model output", "response", "=", "requests", ".", "post", "(", "upload_url", ",", "files", "=", "{", "'file'", ":", "open", "(", "filename", ",", "'rb'", ")", "}", ")", "if", "response", ".", "status_code", "!=", "200", ":", "try", ":", "raise", "ValueError", "(", "json", ".", "loads", "(", "response", ".", "text", ")", "[", "'message'", "]", ")", "except", "KeyError", "as", "ex", ":", "raise", "ValueError", "(", "'invalid state change: '", "+", "str", "(", "response", ".", "text", ")", ")", "# Returned refreshed verion of the handle", "return", "self", ".", "refresh", "(", ")" ]
Upload an attachment for the model run. Paramerers ---------- filename : string Path to uploaded file resource_id : string Identifier of the attachment. If None, the filename will be used as resource identifier. Returns ------- ModelRunHandle Refreshed run handle.
[ "Upload", "an", "attachment", "for", "the", "model", "run", "." ]
c4afab71297f73003379bba4c1679be9dcf7cef8
https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/modelrun.py#L275-L308
248,566
heikomuller/sco-client
scocli/modelrun.py
ModelRunHandle.create
def create(url, model_id, name, arguments, properties=None): """Create a new model run using the given SCO-API create model run Url. Parameters ---------- url : string Url to POST model run create model run request model_id : string Unique model identifier name : string User-defined name for model run arguments : Dictionary Dictionary of arguments for model run properties : Dictionary, optional Set of additional properties for created mode run. Returns ------- string Url of created model run resource """ # Create list of model run arguments. Catch TypeErrors if arguments is # not a list. obj_args = [] try: for arg in arguments: obj_args.append({'name' : arg, 'value' : arguments[arg]}) except TypeError as ex: raise ValueError('invalid argument set') # Create request body and send POST request to given Url body = { 'model' : model_id, 'name' : name, 'arguments' : obj_args, } # Create list of properties if given. Catch TypeErrors if properties is # not a list. if not properties is None: obj_props = [] try: for key in properties: if key != 'name': obj_props.append({'key':key, 'value':properties[key]}) except TypeError as ex: raise ValueError('invalid property set') body['properties'] = obj_props # POST create model run request try: req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, json.dumps(body)) except urllib2.URLError as ex: raise ValueError(str(ex)) # Get model run self reference from successful response return references_to_dict(json.load(response)['links'])[REF_SELF]
python
def create(url, model_id, name, arguments, properties=None): """Create a new model run using the given SCO-API create model run Url. Parameters ---------- url : string Url to POST model run create model run request model_id : string Unique model identifier name : string User-defined name for model run arguments : Dictionary Dictionary of arguments for model run properties : Dictionary, optional Set of additional properties for created mode run. Returns ------- string Url of created model run resource """ # Create list of model run arguments. Catch TypeErrors if arguments is # not a list. obj_args = [] try: for arg in arguments: obj_args.append({'name' : arg, 'value' : arguments[arg]}) except TypeError as ex: raise ValueError('invalid argument set') # Create request body and send POST request to given Url body = { 'model' : model_id, 'name' : name, 'arguments' : obj_args, } # Create list of properties if given. Catch TypeErrors if properties is # not a list. if not properties is None: obj_props = [] try: for key in properties: if key != 'name': obj_props.append({'key':key, 'value':properties[key]}) except TypeError as ex: raise ValueError('invalid property set') body['properties'] = obj_props # POST create model run request try: req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, json.dumps(body)) except urllib2.URLError as ex: raise ValueError(str(ex)) # Get model run self reference from successful response return references_to_dict(json.load(response)['links'])[REF_SELF]
[ "def", "create", "(", "url", ",", "model_id", ",", "name", ",", "arguments", ",", "properties", "=", "None", ")", ":", "# Create list of model run arguments. Catch TypeErrors if arguments is", "# not a list.", "obj_args", "=", "[", "]", "try", ":", "for", "arg", "in", "arguments", ":", "obj_args", ".", "append", "(", "{", "'name'", ":", "arg", ",", "'value'", ":", "arguments", "[", "arg", "]", "}", ")", "except", "TypeError", "as", "ex", ":", "raise", "ValueError", "(", "'invalid argument set'", ")", "# Create request body and send POST request to given Url", "body", "=", "{", "'model'", ":", "model_id", ",", "'name'", ":", "name", ",", "'arguments'", ":", "obj_args", ",", "}", "# Create list of properties if given. Catch TypeErrors if properties is", "# not a list.", "if", "not", "properties", "is", "None", ":", "obj_props", "=", "[", "]", "try", ":", "for", "key", "in", "properties", ":", "if", "key", "!=", "'name'", ":", "obj_props", ".", "append", "(", "{", "'key'", ":", "key", ",", "'value'", ":", "properties", "[", "key", "]", "}", ")", "except", "TypeError", "as", "ex", ":", "raise", "ValueError", "(", "'invalid property set'", ")", "body", "[", "'properties'", "]", "=", "obj_props", "# POST create model run request", "try", ":", "req", "=", "urllib2", ".", "Request", "(", "url", ")", "req", ".", "add_header", "(", "'Content-Type'", ",", "'application/json'", ")", "response", "=", "urllib2", ".", "urlopen", "(", "req", ",", "json", ".", "dumps", "(", "body", ")", ")", "except", "urllib2", ".", "URLError", "as", "ex", ":", "raise", "ValueError", "(", "str", "(", "ex", ")", ")", "# Get model run self reference from successful response", "return", "references_to_dict", "(", "json", ".", "load", "(", "response", ")", "[", "'links'", "]", ")", "[", "REF_SELF", "]" ]
Create a new model run using the given SCO-API create model run Url. Parameters ---------- url : string Url to POST model run create model run request model_id : string Unique model identifier name : string User-defined name for model run arguments : Dictionary Dictionary of arguments for model run properties : Dictionary, optional Set of additional properties for created mode run. Returns ------- string Url of created model run resource
[ "Create", "a", "new", "model", "run", "using", "the", "given", "SCO", "-", "API", "create", "model", "run", "Url", "." ]
c4afab71297f73003379bba4c1679be9dcf7cef8
https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/modelrun.py#L311-L365
248,567
heikomuller/sco-client
scocli/modelrun.py
ModelRunHandle.update_state
def update_state(url, state_obj): """Update the state of a given model run. The state object is a Json representation of the state as created by the SCO-Server. Throws a ValueError if the resource is unknown or the update state request failed. Parameters ---------- url : string Url to POST model run create model run request state_obj : Json object State object serialization as expected by the API. """ # POST update run state request try: req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, json.dumps(state_obj)) except urllib2.URLError as ex: raise ValueError(str(ex)) # Throw exception if resource was unknown or update request failed if response.code == 400: raise ValueError(response.message) elif response.code == 404: raise ValueError('unknown model run')
python
def update_state(url, state_obj): """Update the state of a given model run. The state object is a Json representation of the state as created by the SCO-Server. Throws a ValueError if the resource is unknown or the update state request failed. Parameters ---------- url : string Url to POST model run create model run request state_obj : Json object State object serialization as expected by the API. """ # POST update run state request try: req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, json.dumps(state_obj)) except urllib2.URLError as ex: raise ValueError(str(ex)) # Throw exception if resource was unknown or update request failed if response.code == 400: raise ValueError(response.message) elif response.code == 404: raise ValueError('unknown model run')
[ "def", "update_state", "(", "url", ",", "state_obj", ")", ":", "# POST update run state request", "try", ":", "req", "=", "urllib2", ".", "Request", "(", "url", ")", "req", ".", "add_header", "(", "'Content-Type'", ",", "'application/json'", ")", "response", "=", "urllib2", ".", "urlopen", "(", "req", ",", "json", ".", "dumps", "(", "state_obj", ")", ")", "except", "urllib2", ".", "URLError", "as", "ex", ":", "raise", "ValueError", "(", "str", "(", "ex", ")", ")", "# Throw exception if resource was unknown or update request failed", "if", "response", ".", "code", "==", "400", ":", "raise", "ValueError", "(", "response", ".", "message", ")", "elif", "response", ".", "code", "==", "404", ":", "raise", "ValueError", "(", "'unknown model run'", ")" ]
Update the state of a given model run. The state object is a Json representation of the state as created by the SCO-Server. Throws a ValueError if the resource is unknown or the update state request failed. Parameters ---------- url : string Url to POST model run create model run request state_obj : Json object State object serialization as expected by the API.
[ "Update", "the", "state", "of", "a", "given", "model", "run", ".", "The", "state", "object", "is", "a", "Json", "representation", "of", "the", "state", "as", "created", "by", "the", "SCO", "-", "Server", "." ]
c4afab71297f73003379bba4c1679be9dcf7cef8
https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/modelrun.py#L403-L428
248,568
heikomuller/sco-client
scocli/modelrun.py
ModelRunHandle.update_state_active
def update_state_active(self): """Update the state of the model run to active. Raises an exception if update fails or resource is unknown. Returns ------- ModelRunHandle Refreshed run handle. """ # Update state to active self.update_state(self.links[REF_UPDATE_STATE_ACTIVE], {'type' : RUN_ACTIVE}) # Returned refreshed verion of the handle return self.refresh()
python
def update_state_active(self): """Update the state of the model run to active. Raises an exception if update fails or resource is unknown. Returns ------- ModelRunHandle Refreshed run handle. """ # Update state to active self.update_state(self.links[REF_UPDATE_STATE_ACTIVE], {'type' : RUN_ACTIVE}) # Returned refreshed verion of the handle return self.refresh()
[ "def", "update_state_active", "(", "self", ")", ":", "# Update state to active", "self", ".", "update_state", "(", "self", ".", "links", "[", "REF_UPDATE_STATE_ACTIVE", "]", ",", "{", "'type'", ":", "RUN_ACTIVE", "}", ")", "# Returned refreshed verion of the handle", "return", "self", ".", "refresh", "(", ")" ]
Update the state of the model run to active. Raises an exception if update fails or resource is unknown. Returns ------- ModelRunHandle Refreshed run handle.
[ "Update", "the", "state", "of", "the", "model", "run", "to", "active", "." ]
c4afab71297f73003379bba4c1679be9dcf7cef8
https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/modelrun.py#L430-L443
248,569
heikomuller/sco-client
scocli/modelrun.py
ModelRunHandle.update_state_error
def update_state_error(self, errors): """Update the state of the model run to 'FAILED'. Expects a list of error messages. Raises an exception if update fails or resource is unknown. Parameters ---------- errors : List(string) List of error messages Returns ------- ModelRunHandle Refreshed run handle. """ # Update state to active self.update_state( self.links[REF_UPDATE_STATE_ERROR], {'type' : RUN_FAILED, 'errors' : errors} ) # Returned refreshed verion of the handle return self.refresh()
python
def update_state_error(self, errors): """Update the state of the model run to 'FAILED'. Expects a list of error messages. Raises an exception if update fails or resource is unknown. Parameters ---------- errors : List(string) List of error messages Returns ------- ModelRunHandle Refreshed run handle. """ # Update state to active self.update_state( self.links[REF_UPDATE_STATE_ERROR], {'type' : RUN_FAILED, 'errors' : errors} ) # Returned refreshed verion of the handle return self.refresh()
[ "def", "update_state_error", "(", "self", ",", "errors", ")", ":", "# Update state to active", "self", ".", "update_state", "(", "self", ".", "links", "[", "REF_UPDATE_STATE_ERROR", "]", ",", "{", "'type'", ":", "RUN_FAILED", ",", "'errors'", ":", "errors", "}", ")", "# Returned refreshed verion of the handle", "return", "self", ".", "refresh", "(", ")" ]
Update the state of the model run to 'FAILED'. Expects a list of error messages. Raises an exception if update fails or resource is unknown. Parameters ---------- errors : List(string) List of error messages Returns ------- ModelRunHandle Refreshed run handle.
[ "Update", "the", "state", "of", "the", "model", "run", "to", "FAILED", ".", "Expects", "a", "list", "of", "error", "messages", "." ]
c4afab71297f73003379bba4c1679be9dcf7cef8
https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/modelrun.py#L445-L467
248,570
heikomuller/sco-client
scocli/modelrun.py
ModelRunHandle.update_state_success
def update_state_success(self, model_output): """Update the state of the model run to 'SUCCESS'. Expects a model output result file. Will upload the file before changing the model run state. Raises an exception if update fails or resource is unknown. Parameters ---------- model_output : string Path to model run output file Returns ------- ModelRunHandle Refreshed run handle. """ # Upload model output response = requests.post( self.links[REF_UPDATE_STATE_SUCCESS], files={'file': open(model_output, 'rb')} ) if response.status_code != 200: try: raise ValueError(json.loads(response.text)['message']) except ValueError as ex: raise ValueError('invalid state change: ' + str(response.text)) # Returned refreshed verion of the handle return self.refresh()
python
def update_state_success(self, model_output): """Update the state of the model run to 'SUCCESS'. Expects a model output result file. Will upload the file before changing the model run state. Raises an exception if update fails or resource is unknown. Parameters ---------- model_output : string Path to model run output file Returns ------- ModelRunHandle Refreshed run handle. """ # Upload model output response = requests.post( self.links[REF_UPDATE_STATE_SUCCESS], files={'file': open(model_output, 'rb')} ) if response.status_code != 200: try: raise ValueError(json.loads(response.text)['message']) except ValueError as ex: raise ValueError('invalid state change: ' + str(response.text)) # Returned refreshed verion of the handle return self.refresh()
[ "def", "update_state_success", "(", "self", ",", "model_output", ")", ":", "# Upload model output", "response", "=", "requests", ".", "post", "(", "self", ".", "links", "[", "REF_UPDATE_STATE_SUCCESS", "]", ",", "files", "=", "{", "'file'", ":", "open", "(", "model_output", ",", "'rb'", ")", "}", ")", "if", "response", ".", "status_code", "!=", "200", ":", "try", ":", "raise", "ValueError", "(", "json", ".", "loads", "(", "response", ".", "text", ")", "[", "'message'", "]", ")", "except", "ValueError", "as", "ex", ":", "raise", "ValueError", "(", "'invalid state change: '", "+", "str", "(", "response", ".", "text", ")", ")", "# Returned refreshed verion of the handle", "return", "self", ".", "refresh", "(", ")" ]
Update the state of the model run to 'SUCCESS'. Expects a model output result file. Will upload the file before changing the model run state. Raises an exception if update fails or resource is unknown. Parameters ---------- model_output : string Path to model run output file Returns ------- ModelRunHandle Refreshed run handle.
[ "Update", "the", "state", "of", "the", "model", "run", "to", "SUCCESS", ".", "Expects", "a", "model", "output", "result", "file", ".", "Will", "upload", "the", "file", "before", "changing", "the", "model", "run", "state", "." ]
c4afab71297f73003379bba4c1679be9dcf7cef8
https://github.com/heikomuller/sco-client/blob/c4afab71297f73003379bba4c1679be9dcf7cef8/scocli/modelrun.py#L469-L497
248,571
cirruscluster/cirruscluster
cirruscluster/workstation.py
CirrusIamUserReady
def CirrusIamUserReady(iam_aws_id, iam_aws_secret): """ Returns true if provided IAM credentials are ready to use. """ is_ready = False try: s3 = core.CreateTestedS3Connection(iam_aws_id, iam_aws_secret) if s3: if core.CirrusAccessIdMetadata(s3, iam_aws_id).IsInitialized(): is_ready = True except boto.exception.BotoServerError as e: print e return is_ready
python
def CirrusIamUserReady(iam_aws_id, iam_aws_secret): """ Returns true if provided IAM credentials are ready to use. """ is_ready = False try: s3 = core.CreateTestedS3Connection(iam_aws_id, iam_aws_secret) if s3: if core.CirrusAccessIdMetadata(s3, iam_aws_id).IsInitialized(): is_ready = True except boto.exception.BotoServerError as e: print e return is_ready
[ "def", "CirrusIamUserReady", "(", "iam_aws_id", ",", "iam_aws_secret", ")", ":", "is_ready", "=", "False", "try", ":", "s3", "=", "core", ".", "CreateTestedS3Connection", "(", "iam_aws_id", ",", "iam_aws_secret", ")", "if", "s3", ":", "if", "core", ".", "CirrusAccessIdMetadata", "(", "s3", ",", "iam_aws_id", ")", ".", "IsInitialized", "(", ")", ":", "is_ready", "=", "True", "except", "boto", ".", "exception", ".", "BotoServerError", "as", "e", ":", "print", "e", "return", "is_ready" ]
Returns true if provided IAM credentials are ready to use.
[ "Returns", "true", "if", "provided", "IAM", "credentials", "are", "ready", "to", "use", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/workstation.py#L60-L71
248,572
cirruscluster/cirruscluster
cirruscluster/workstation.py
NoSuchEntityOk
def NoSuchEntityOk(f): """ Decorator to remove NoSuchEntity exceptions, and raises all others. """ def ExceptionFilter(*args): try: return f(*args) except boto.exception.BotoServerError as e: if e.error_code == 'NoSuchEntity': pass else: raise except: raise return False return ExceptionFilter
python
def NoSuchEntityOk(f): """ Decorator to remove NoSuchEntity exceptions, and raises all others. """ def ExceptionFilter(*args): try: return f(*args) except boto.exception.BotoServerError as e: if e.error_code == 'NoSuchEntity': pass else: raise except: raise return False return ExceptionFilter
[ "def", "NoSuchEntityOk", "(", "f", ")", ":", "def", "ExceptionFilter", "(", "*", "args", ")", ":", "try", ":", "return", "f", "(", "*", "args", ")", "except", "boto", ".", "exception", ".", "BotoServerError", "as", "e", ":", "if", "e", ".", "error_code", "==", "'NoSuchEntity'", ":", "pass", "else", ":", "raise", "except", ":", "raise", "return", "False", "return", "ExceptionFilter" ]
Decorator to remove NoSuchEntity exceptions, and raises all others.
[ "Decorator", "to", "remove", "NoSuchEntity", "exceptions", "and", "raises", "all", "others", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/workstation.py#L78-L91
248,573
cirruscluster/cirruscluster
cirruscluster/workstation.py
CirrusIamUserManager.__IsInitialized
def __IsInitialized(self): """ Returns true if IAM user initialization has completed. """ is_initialized = False iam_id = self.GetAccessKeyId() if iam_id: if core.CirrusAccessIdMetadata(self.s3, iam_id).IsInitialized(): is_initialized = True return is_initialized
python
def __IsInitialized(self): """ Returns true if IAM user initialization has completed. """ is_initialized = False iam_id = self.GetAccessKeyId() if iam_id: if core.CirrusAccessIdMetadata(self.s3, iam_id).IsInitialized(): is_initialized = True return is_initialized
[ "def", "__IsInitialized", "(", "self", ")", ":", "is_initialized", "=", "False", "iam_id", "=", "self", ".", "GetAccessKeyId", "(", ")", "if", "iam_id", ":", "if", "core", ".", "CirrusAccessIdMetadata", "(", "self", ".", "s3", ",", "iam_id", ")", ".", "IsInitialized", "(", ")", ":", "is_initialized", "=", "True", "return", "is_initialized" ]
Returns true if IAM user initialization has completed.
[ "Returns", "true", "if", "IAM", "user", "initialization", "has", "completed", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/workstation.py#L116-L123
248,574
cirruscluster/cirruscluster
cirruscluster/workstation.py
Manager.__GetInstances
def __GetInstances(self, group_name = None, state_filter=None): """ Get all the instances in a group, filtered by state. @param group_name: the name of the group @param state_filter: the state that the instance should be in (e.g. "running"), or None for all states """ all_instances = self.ec2.get_all_instances() instances = [] for res in all_instances: for group in res.groups: if group_name and group.name != group_name: continue for instance in res.instances: if state_filter == None or instance.state == state_filter: instances.append(instance) return instances
python
def __GetInstances(self, group_name = None, state_filter=None): """ Get all the instances in a group, filtered by state. @param group_name: the name of the group @param state_filter: the state that the instance should be in (e.g. "running"), or None for all states """ all_instances = self.ec2.get_all_instances() instances = [] for res in all_instances: for group in res.groups: if group_name and group.name != group_name: continue for instance in res.instances: if state_filter == None or instance.state == state_filter: instances.append(instance) return instances
[ "def", "__GetInstances", "(", "self", ",", "group_name", "=", "None", ",", "state_filter", "=", "None", ")", ":", "all_instances", "=", "self", ".", "ec2", ".", "get_all_instances", "(", ")", "instances", "=", "[", "]", "for", "res", "in", "all_instances", ":", "for", "group", "in", "res", ".", "groups", ":", "if", "group_name", "and", "group", ".", "name", "!=", "group_name", ":", "continue", "for", "instance", "in", "res", ".", "instances", ":", "if", "state_filter", "==", "None", "or", "instance", ".", "state", "==", "state_filter", ":", "instances", ".", "append", "(", "instance", ")", "return", "instances" ]
Get all the instances in a group, filtered by state. @param group_name: the name of the group @param state_filter: the state that the instance should be in (e.g. "running"), or None for all states
[ "Get", "all", "the", "instances", "in", "a", "group", "filtered", "by", "state", "." ]
977409929dd81322d886425cdced10608117d5d7
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/workstation.py#L487-L504
248,575
spookey/photon
photon/meta.py
Meta.load
def load(self, mkey, mdesc, mdict=None, merge=False): ''' Loads a dictionary into current meta :param mkey: Type of data to load. Is be used to reference the data from the 'header' within meta :param mdesc: Either filename of json-file to load or further description of imported data when `mdict` is used :param dict mdict: Directly pass data as dictionary instead of loading it from a json-file. Make sure to set `mkey` and `mdesc` accordingly :param merge: Merge received data into current meta or place it under 'import' within meta :returns: The loaded (or directly passed) content ''' j = mdict if mdict else read_json(mdesc) if j and isinstance(j, dict): self.__meta['header'].update({mkey: mdesc}) if merge: self.__meta = dict_merge(self.__meta, j) else: self.__meta['import'][mkey] = j self.log = shell_notify( 'load %s data and %s it into meta' % ( 'got' if mdict else 'read', 'merged' if merge else 'imported' ), more=dict(mkey=mkey, mdesc=mdesc, merge=merge), verbose=self.__verbose ) return j
python
def load(self, mkey, mdesc, mdict=None, merge=False): ''' Loads a dictionary into current meta :param mkey: Type of data to load. Is be used to reference the data from the 'header' within meta :param mdesc: Either filename of json-file to load or further description of imported data when `mdict` is used :param dict mdict: Directly pass data as dictionary instead of loading it from a json-file. Make sure to set `mkey` and `mdesc` accordingly :param merge: Merge received data into current meta or place it under 'import' within meta :returns: The loaded (or directly passed) content ''' j = mdict if mdict else read_json(mdesc) if j and isinstance(j, dict): self.__meta['header'].update({mkey: mdesc}) if merge: self.__meta = dict_merge(self.__meta, j) else: self.__meta['import'][mkey] = j self.log = shell_notify( 'load %s data and %s it into meta' % ( 'got' if mdict else 'read', 'merged' if merge else 'imported' ), more=dict(mkey=mkey, mdesc=mdesc, merge=merge), verbose=self.__verbose ) return j
[ "def", "load", "(", "self", ",", "mkey", ",", "mdesc", ",", "mdict", "=", "None", ",", "merge", "=", "False", ")", ":", "j", "=", "mdict", "if", "mdict", "else", "read_json", "(", "mdesc", ")", "if", "j", "and", "isinstance", "(", "j", ",", "dict", ")", ":", "self", ".", "__meta", "[", "'header'", "]", ".", "update", "(", "{", "mkey", ":", "mdesc", "}", ")", "if", "merge", ":", "self", ".", "__meta", "=", "dict_merge", "(", "self", ".", "__meta", ",", "j", ")", "else", ":", "self", ".", "__meta", "[", "'import'", "]", "[", "mkey", "]", "=", "j", "self", ".", "log", "=", "shell_notify", "(", "'load %s data and %s it into meta'", "%", "(", "'got'", "if", "mdict", "else", "'read'", ",", "'merged'", "if", "merge", "else", "'imported'", ")", ",", "more", "=", "dict", "(", "mkey", "=", "mkey", ",", "mdesc", "=", "mdesc", ",", "merge", "=", "merge", ")", ",", "verbose", "=", "self", ".", "__verbose", ")", "return", "j" ]
Loads a dictionary into current meta :param mkey: Type of data to load. Is be used to reference the data from the 'header' within meta :param mdesc: Either filename of json-file to load or further description of imported data when `mdict` is used :param dict mdict: Directly pass data as dictionary instead of loading it from a json-file. Make sure to set `mkey` and `mdesc` accordingly :param merge: Merge received data into current meta or place it under 'import' within meta :returns: The loaded (or directly passed) content
[ "Loads", "a", "dictionary", "into", "current", "meta" ]
57212a26ce713ab7723910ee49e3d0ba1697799f
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/meta.py#L72-L108
248,576
jeremylow/pyshk
pyshk/api.py
Api.get_user
def get_user(self, user_id=None, user_name=None): """ Get a user object from the API. If no ``user_id`` or ``user_name`` is specified, it will return the User object for the currently authenticated user. Args: user_id (int): User ID of the user for whom you want to get information. [Optional] user_name(str): Username for the user for whom you want to get information. [Optional] Returns: A User object. """ if user_id: endpoint = '/api/user_id/{0}'.format(user_id) elif user_name: endpoint = '/api/user_name/{0}'.format(user_name) else: # Return currently authorized user endpoint = '/api/user' data = self._make_request(verb="GET", endpoint=endpoint) try: return User.NewFromJSON(data) except: return data
python
def get_user(self, user_id=None, user_name=None): """ Get a user object from the API. If no ``user_id`` or ``user_name`` is specified, it will return the User object for the currently authenticated user. Args: user_id (int): User ID of the user for whom you want to get information. [Optional] user_name(str): Username for the user for whom you want to get information. [Optional] Returns: A User object. """ if user_id: endpoint = '/api/user_id/{0}'.format(user_id) elif user_name: endpoint = '/api/user_name/{0}'.format(user_name) else: # Return currently authorized user endpoint = '/api/user' data = self._make_request(verb="GET", endpoint=endpoint) try: return User.NewFromJSON(data) except: return data
[ "def", "get_user", "(", "self", ",", "user_id", "=", "None", ",", "user_name", "=", "None", ")", ":", "if", "user_id", ":", "endpoint", "=", "'/api/user_id/{0}'", ".", "format", "(", "user_id", ")", "elif", "user_name", ":", "endpoint", "=", "'/api/user_name/{0}'", ".", "format", "(", "user_name", ")", "else", ":", "# Return currently authorized user", "endpoint", "=", "'/api/user'", "data", "=", "self", ".", "_make_request", "(", "verb", "=", "\"GET\"", ",", "endpoint", "=", "endpoint", ")", "try", ":", "return", "User", ".", "NewFromJSON", "(", "data", ")", "except", ":", "return", "data" ]
Get a user object from the API. If no ``user_id`` or ``user_name`` is specified, it will return the User object for the currently authenticated user. Args: user_id (int): User ID of the user for whom you want to get information. [Optional] user_name(str): Username for the user for whom you want to get information. [Optional] Returns: A User object.
[ "Get", "a", "user", "object", "from", "the", "API", ".", "If", "no", "user_id", "or", "user_name", "is", "specified", "it", "will", "return", "the", "User", "object", "for", "the", "currently", "authenticated", "user", "." ]
3ab92f6706397cde7a18367266eba9e0f1ada868
https://github.com/jeremylow/pyshk/blob/3ab92f6706397cde7a18367266eba9e0f1ada868/pyshk/api.py#L267-L295
248,577
jeremylow/pyshk
pyshk/api.py
Api.get_user_shakes
def get_user_shakes(self): """ Get a list of Shake objects for the currently authenticated user. Returns: A list of Shake objects. """ endpoint = '/api/shakes' data = self._make_request(verb="GET", endpoint=endpoint) shakes = [Shake.NewFromJSON(shk) for shk in data['shakes']] return shakes
python
def get_user_shakes(self): """ Get a list of Shake objects for the currently authenticated user. Returns: A list of Shake objects. """ endpoint = '/api/shakes' data = self._make_request(verb="GET", endpoint=endpoint) shakes = [Shake.NewFromJSON(shk) for shk in data['shakes']] return shakes
[ "def", "get_user_shakes", "(", "self", ")", ":", "endpoint", "=", "'/api/shakes'", "data", "=", "self", ".", "_make_request", "(", "verb", "=", "\"GET\"", ",", "endpoint", "=", "endpoint", ")", "shakes", "=", "[", "Shake", ".", "NewFromJSON", "(", "shk", ")", "for", "shk", "in", "data", "[", "'shakes'", "]", "]", "return", "shakes" ]
Get a list of Shake objects for the currently authenticated user. Returns: A list of Shake objects.
[ "Get", "a", "list", "of", "Shake", "objects", "for", "the", "currently", "authenticated", "user", "." ]
3ab92f6706397cde7a18367266eba9e0f1ada868
https://github.com/jeremylow/pyshk/blob/3ab92f6706397cde7a18367266eba9e0f1ada868/pyshk/api.py#L297-L307
248,578
jeremylow/pyshk
pyshk/api.py
Api.get_shared_files_from_shake
def get_shared_files_from_shake(self, shake_id=None, before=None, after=None): """ Returns a list of SharedFile objects from a particular shake. Args: shake_id (int): Shake from which to get a list of SharedFiles before (str): get 10 SharedFile objects before (but not including) the SharedFile given by `before` for the given Shake. after (str): get 10 SharedFile objects after (but not including) the SharedFile give by `after' for the given Shake. Returns: List (list) of SharedFiles. """ if before and after: raise Exception("You cannot specify both before and after keys") endpoint = '/api/shakes' if shake_id: endpoint += '/{0}'.format(shake_id) if before: endpoint += '/before/{0}'.format(before) elif after: endpoint += '/after/{0}'.format(after) data = self._make_request(verb="GET", endpoint=endpoint) return [SharedFile.NewFromJSON(f) for f in data['sharedfiles']]
python
def get_shared_files_from_shake(self, shake_id=None, before=None, after=None): """ Returns a list of SharedFile objects from a particular shake. Args: shake_id (int): Shake from which to get a list of SharedFiles before (str): get 10 SharedFile objects before (but not including) the SharedFile given by `before` for the given Shake. after (str): get 10 SharedFile objects after (but not including) the SharedFile give by `after' for the given Shake. Returns: List (list) of SharedFiles. """ if before and after: raise Exception("You cannot specify both before and after keys") endpoint = '/api/shakes' if shake_id: endpoint += '/{0}'.format(shake_id) if before: endpoint += '/before/{0}'.format(before) elif after: endpoint += '/after/{0}'.format(after) data = self._make_request(verb="GET", endpoint=endpoint) return [SharedFile.NewFromJSON(f) for f in data['sharedfiles']]
[ "def", "get_shared_files_from_shake", "(", "self", ",", "shake_id", "=", "None", ",", "before", "=", "None", ",", "after", "=", "None", ")", ":", "if", "before", "and", "after", ":", "raise", "Exception", "(", "\"You cannot specify both before and after keys\"", ")", "endpoint", "=", "'/api/shakes'", "if", "shake_id", ":", "endpoint", "+=", "'/{0}'", ".", "format", "(", "shake_id", ")", "if", "before", ":", "endpoint", "+=", "'/before/{0}'", ".", "format", "(", "before", ")", "elif", "after", ":", "endpoint", "+=", "'/after/{0}'", ".", "format", "(", "after", ")", "data", "=", "self", ".", "_make_request", "(", "verb", "=", "\"GET\"", ",", "endpoint", "=", "endpoint", ")", "return", "[", "SharedFile", ".", "NewFromJSON", "(", "f", ")", "for", "f", "in", "data", "[", "'sharedfiles'", "]", "]" ]
Returns a list of SharedFile objects from a particular shake. Args: shake_id (int): Shake from which to get a list of SharedFiles before (str): get 10 SharedFile objects before (but not including) the SharedFile given by `before` for the given Shake. after (str): get 10 SharedFile objects after (but not including) the SharedFile give by `after' for the given Shake. Returns: List (list) of SharedFiles.
[ "Returns", "a", "list", "of", "SharedFile", "objects", "from", "a", "particular", "shake", "." ]
3ab92f6706397cde7a18367266eba9e0f1ada868
https://github.com/jeremylow/pyshk/blob/3ab92f6706397cde7a18367266eba9e0f1ada868/pyshk/api.py#L309-L340
248,579
jeremylow/pyshk
pyshk/api.py
Api.get_shared_file
def get_shared_file(self, sharekey=None): """ Returns a SharedFile object given by the sharekey. Args: sharekey (str): Sharekey of the SharedFile you want to retrieve. Returns: SharedFile """ if not sharekey: raise Exception("You must specify a sharekey.") endpoint = '/api/sharedfile/{0}'.format(sharekey) data = self._make_request('GET', endpoint) return SharedFile.NewFromJSON(data)
python
def get_shared_file(self, sharekey=None): """ Returns a SharedFile object given by the sharekey. Args: sharekey (str): Sharekey of the SharedFile you want to retrieve. Returns: SharedFile """ if not sharekey: raise Exception("You must specify a sharekey.") endpoint = '/api/sharedfile/{0}'.format(sharekey) data = self._make_request('GET', endpoint) return SharedFile.NewFromJSON(data)
[ "def", "get_shared_file", "(", "self", ",", "sharekey", "=", "None", ")", ":", "if", "not", "sharekey", ":", "raise", "Exception", "(", "\"You must specify a sharekey.\"", ")", "endpoint", "=", "'/api/sharedfile/{0}'", ".", "format", "(", "sharekey", ")", "data", "=", "self", ".", "_make_request", "(", "'GET'", ",", "endpoint", ")", "return", "SharedFile", ".", "NewFromJSON", "(", "data", ")" ]
Returns a SharedFile object given by the sharekey. Args: sharekey (str): Sharekey of the SharedFile you want to retrieve. Returns: SharedFile
[ "Returns", "a", "SharedFile", "object", "given", "by", "the", "sharekey", "." ]
3ab92f6706397cde7a18367266eba9e0f1ada868
https://github.com/jeremylow/pyshk/blob/3ab92f6706397cde7a18367266eba9e0f1ada868/pyshk/api.py#L342-L356
248,580
jeremylow/pyshk
pyshk/api.py
Api.like_shared_file
def like_shared_file(self, sharekey=None): """ 'Like' a SharedFile. mlkshk doesn't allow you to unlike a sharedfile, so this is ~~permanent~~. Args: sharekey (str): Sharekey for the file you want to 'like'. Returns: Either a SharedFile on success, or an exception on error. """ if not sharekey: raise Exception( "You must specify a sharekey of the file you" "want to 'like'.") endpoint = '/api/sharedfile/{sharekey}/like'.format(sharekey=sharekey) data = self._make_request("POST", endpoint=endpoint, data=None) try: sf = SharedFile.NewFromJSON(data) sf.liked = True return sf except: raise Exception("{0}".format(data['error']))
python
def like_shared_file(self, sharekey=None): """ 'Like' a SharedFile. mlkshk doesn't allow you to unlike a sharedfile, so this is ~~permanent~~. Args: sharekey (str): Sharekey for the file you want to 'like'. Returns: Either a SharedFile on success, or an exception on error. """ if not sharekey: raise Exception( "You must specify a sharekey of the file you" "want to 'like'.") endpoint = '/api/sharedfile/{sharekey}/like'.format(sharekey=sharekey) data = self._make_request("POST", endpoint=endpoint, data=None) try: sf = SharedFile.NewFromJSON(data) sf.liked = True return sf except: raise Exception("{0}".format(data['error']))
[ "def", "like_shared_file", "(", "self", ",", "sharekey", "=", "None", ")", ":", "if", "not", "sharekey", ":", "raise", "Exception", "(", "\"You must specify a sharekey of the file you\"", "\"want to 'like'.\"", ")", "endpoint", "=", "'/api/sharedfile/{sharekey}/like'", ".", "format", "(", "sharekey", "=", "sharekey", ")", "data", "=", "self", ".", "_make_request", "(", "\"POST\"", ",", "endpoint", "=", "endpoint", ",", "data", "=", "None", ")", "try", ":", "sf", "=", "SharedFile", ".", "NewFromJSON", "(", "data", ")", "sf", ".", "liked", "=", "True", "return", "sf", "except", ":", "raise", "Exception", "(", "\"{0}\"", ".", "format", "(", "data", "[", "'error'", "]", ")", ")" ]
'Like' a SharedFile. mlkshk doesn't allow you to unlike a sharedfile, so this is ~~permanent~~. Args: sharekey (str): Sharekey for the file you want to 'like'. Returns: Either a SharedFile on success, or an exception on error.
[ "Like", "a", "SharedFile", ".", "mlkshk", "doesn", "t", "allow", "you", "to", "unlike", "a", "sharedfile", "so", "this", "is", "~~permanent~~", "." ]
3ab92f6706397cde7a18367266eba9e0f1ada868
https://github.com/jeremylow/pyshk/blob/3ab92f6706397cde7a18367266eba9e0f1ada868/pyshk/api.py#L358-L382
248,581
jeremylow/pyshk
pyshk/api.py
Api.save_shared_file
def save_shared_file(self, sharekey=None): """ Save a SharedFile to your Shake. Args: sharekey (str): Sharekey for the file to save. Returns: SharedFile saved to your shake. """ endpoint = '/api/sharedfile/{sharekey}/save'.format(sharekey=sharekey) data = self._make_request("POST", endpoint=endpoint, data=None) try: sf = SharedFile.NewFromJSON(data) sf.saved = True return sf except: raise Exception("{0}".format(data['error']))
python
def save_shared_file(self, sharekey=None): """ Save a SharedFile to your Shake. Args: sharekey (str): Sharekey for the file to save. Returns: SharedFile saved to your shake. """ endpoint = '/api/sharedfile/{sharekey}/save'.format(sharekey=sharekey) data = self._make_request("POST", endpoint=endpoint, data=None) try: sf = SharedFile.NewFromJSON(data) sf.saved = True return sf except: raise Exception("{0}".format(data['error']))
[ "def", "save_shared_file", "(", "self", ",", "sharekey", "=", "None", ")", ":", "endpoint", "=", "'/api/sharedfile/{sharekey}/save'", ".", "format", "(", "sharekey", "=", "sharekey", ")", "data", "=", "self", ".", "_make_request", "(", "\"POST\"", ",", "endpoint", "=", "endpoint", ",", "data", "=", "None", ")", "try", ":", "sf", "=", "SharedFile", ".", "NewFromJSON", "(", "data", ")", "sf", ".", "saved", "=", "True", "return", "sf", "except", ":", "raise", "Exception", "(", "\"{0}\"", ".", "format", "(", "data", "[", "'error'", "]", ")", ")" ]
Save a SharedFile to your Shake. Args: sharekey (str): Sharekey for the file to save. Returns: SharedFile saved to your shake.
[ "Save", "a", "SharedFile", "to", "your", "Shake", "." ]
3ab92f6706397cde7a18367266eba9e0f1ada868
https://github.com/jeremylow/pyshk/blob/3ab92f6706397cde7a18367266eba9e0f1ada868/pyshk/api.py#L384-L402
248,582
jeremylow/pyshk
pyshk/api.py
Api.get_friends_shake
def get_friends_shake(self, before=None, after=None): """ Contrary to the endpoint naming, this resource is for a list of SharedFiles from your friends on mlkshk. Returns: List of SharedFiles. """ if before and after: raise Exception("You cannot specify both before and after keys") endpoint = '/api/friends' if before: endpoint += '/before/{0}'.format(before) elif after: endpoint += '/after/{0}'.format(after) data = self._make_request("GET", endpoint=endpoint) return [SharedFile.NewFromJSON(sf) for sf in data['friend_shake']]
python
def get_friends_shake(self, before=None, after=None): """ Contrary to the endpoint naming, this resource is for a list of SharedFiles from your friends on mlkshk. Returns: List of SharedFiles. """ if before and after: raise Exception("You cannot specify both before and after keys") endpoint = '/api/friends' if before: endpoint += '/before/{0}'.format(before) elif after: endpoint += '/after/{0}'.format(after) data = self._make_request("GET", endpoint=endpoint) return [SharedFile.NewFromJSON(sf) for sf in data['friend_shake']]
[ "def", "get_friends_shake", "(", "self", ",", "before", "=", "None", ",", "after", "=", "None", ")", ":", "if", "before", "and", "after", ":", "raise", "Exception", "(", "\"You cannot specify both before and after keys\"", ")", "endpoint", "=", "'/api/friends'", "if", "before", ":", "endpoint", "+=", "'/before/{0}'", ".", "format", "(", "before", ")", "elif", "after", ":", "endpoint", "+=", "'/after/{0}'", ".", "format", "(", "after", ")", "data", "=", "self", ".", "_make_request", "(", "\"GET\"", ",", "endpoint", "=", "endpoint", ")", "return", "[", "SharedFile", ".", "NewFromJSON", "(", "sf", ")", "for", "sf", "in", "data", "[", "'friend_shake'", "]", "]" ]
Contrary to the endpoint naming, this resource is for a list of SharedFiles from your friends on mlkshk. Returns: List of SharedFiles.
[ "Contrary", "to", "the", "endpoint", "naming", "this", "resource", "is", "for", "a", "list", "of", "SharedFiles", "from", "your", "friends", "on", "mlkshk", "." ]
3ab92f6706397cde7a18367266eba9e0f1ada868
https://github.com/jeremylow/pyshk/blob/3ab92f6706397cde7a18367266eba9e0f1ada868/pyshk/api.py#L404-L423
248,583
jeremylow/pyshk
pyshk/api.py
Api.get_comments
def get_comments(self, sharekey=None): """ Retrieve comments on a SharedFile Args: sharekey (str): Sharekey for the file from which you want to return the set of comments. Returns: List of Comment objects. """ if not sharekey: raise Exception( "You must specify a sharekey of the file you" "want to 'like'.") endpoint = '/api/sharedfile/{0}/comments'.format(sharekey) data = self._make_request("GET", endpoint=endpoint) return [Comment.NewFromJSON(c) for c in data['comments']]
python
def get_comments(self, sharekey=None): """ Retrieve comments on a SharedFile Args: sharekey (str): Sharekey for the file from which you want to return the set of comments. Returns: List of Comment objects. """ if not sharekey: raise Exception( "You must specify a sharekey of the file you" "want to 'like'.") endpoint = '/api/sharedfile/{0}/comments'.format(sharekey) data = self._make_request("GET", endpoint=endpoint) return [Comment.NewFromJSON(c) for c in data['comments']]
[ "def", "get_comments", "(", "self", ",", "sharekey", "=", "None", ")", ":", "if", "not", "sharekey", ":", "raise", "Exception", "(", "\"You must specify a sharekey of the file you\"", "\"want to 'like'.\"", ")", "endpoint", "=", "'/api/sharedfile/{0}/comments'", ".", "format", "(", "sharekey", ")", "data", "=", "self", ".", "_make_request", "(", "\"GET\"", ",", "endpoint", "=", "endpoint", ")", "return", "[", "Comment", ".", "NewFromJSON", "(", "c", ")", "for", "c", "in", "data", "[", "'comments'", "]", "]" ]
Retrieve comments on a SharedFile Args: sharekey (str): Sharekey for the file from which you want to return the set of comments. Returns: List of Comment objects.
[ "Retrieve", "comments", "on", "a", "SharedFile" ]
3ab92f6706397cde7a18367266eba9e0f1ada868
https://github.com/jeremylow/pyshk/blob/3ab92f6706397cde7a18367266eba9e0f1ada868/pyshk/api.py#L474-L494
248,584
jeremylow/pyshk
pyshk/api.py
Api.post_comment
def post_comment(self, sharekey=None, comment=None): """ Post a comment on behalf of the current user to the SharedFile with the given sharekey. Args: sharekey (str): Sharekey of the SharedFile to which you'd like to post a comment. comment (str): Text of the comment to post. Returns: Comment object. """ endpoint = '/api/sharedfile/{0}/comments'.format(sharekey) post_data = {'body': comment} data = self._make_request("POST", endpoint=endpoint, data=post_data) return Comment.NewFromJSON(data)
python
def post_comment(self, sharekey=None, comment=None): """ Post a comment on behalf of the current user to the SharedFile with the given sharekey. Args: sharekey (str): Sharekey of the SharedFile to which you'd like to post a comment. comment (str): Text of the comment to post. Returns: Comment object. """ endpoint = '/api/sharedfile/{0}/comments'.format(sharekey) post_data = {'body': comment} data = self._make_request("POST", endpoint=endpoint, data=post_data) return Comment.NewFromJSON(data)
[ "def", "post_comment", "(", "self", ",", "sharekey", "=", "None", ",", "comment", "=", "None", ")", ":", "endpoint", "=", "'/api/sharedfile/{0}/comments'", ".", "format", "(", "sharekey", ")", "post_data", "=", "{", "'body'", ":", "comment", "}", "data", "=", "self", ".", "_make_request", "(", "\"POST\"", ",", "endpoint", "=", "endpoint", ",", "data", "=", "post_data", ")", "return", "Comment", ".", "NewFromJSON", "(", "data", ")" ]
Post a comment on behalf of the current user to the SharedFile with the given sharekey. Args: sharekey (str): Sharekey of the SharedFile to which you'd like to post a comment. comment (str): Text of the comment to post. Returns: Comment object.
[ "Post", "a", "comment", "on", "behalf", "of", "the", "current", "user", "to", "the", "SharedFile", "with", "the", "given", "sharekey", "." ]
3ab92f6706397cde7a18367266eba9e0f1ada868
https://github.com/jeremylow/pyshk/blob/3ab92f6706397cde7a18367266eba9e0f1ada868/pyshk/api.py#L496-L514
248,585
jeremylow/pyshk
pyshk/api.py
Api.post_shared_file
def post_shared_file(self, image_file=None, source_link=None, shake_id=None, title=None, description=None): """ Upload an image. TODO: Don't have a pro account to test (or even write) code to upload a shared filed to a particular shake. Args: image_file (str): path to an image (jpg/gif) on your computer. source_link (str): URL of a source (youtube/vine/etc.) shake_id (int): shake to which to upload the file or source_link [optional] title (str): title of the SharedFile [optional] description (str): description of the SharedFile Returns: SharedFile key. """ if image_file and source_link: raise Exception('You can only specify an image file or ' 'a source link, not both.') if not image_file and not source_link: raise Exception('You must specify an image file or a source link') content_type = self._get_image_type(image_file) if not title: title = os.path.basename(image_file) f = open(image_file, 'rb') endpoint = '/api/upload' files = {'file': (title, f, content_type)} data = self._make_request('POST', endpoint=endpoint, files=files) f.close() return data
python
def post_shared_file(self, image_file=None, source_link=None, shake_id=None, title=None, description=None): """ Upload an image. TODO: Don't have a pro account to test (or even write) code to upload a shared filed to a particular shake. Args: image_file (str): path to an image (jpg/gif) on your computer. source_link (str): URL of a source (youtube/vine/etc.) shake_id (int): shake to which to upload the file or source_link [optional] title (str): title of the SharedFile [optional] description (str): description of the SharedFile Returns: SharedFile key. """ if image_file and source_link: raise Exception('You can only specify an image file or ' 'a source link, not both.') if not image_file and not source_link: raise Exception('You must specify an image file or a source link') content_type = self._get_image_type(image_file) if not title: title = os.path.basename(image_file) f = open(image_file, 'rb') endpoint = '/api/upload' files = {'file': (title, f, content_type)} data = self._make_request('POST', endpoint=endpoint, files=files) f.close() return data
[ "def", "post_shared_file", "(", "self", ",", "image_file", "=", "None", ",", "source_link", "=", "None", ",", "shake_id", "=", "None", ",", "title", "=", "None", ",", "description", "=", "None", ")", ":", "if", "image_file", "and", "source_link", ":", "raise", "Exception", "(", "'You can only specify an image file or '", "'a source link, not both.'", ")", "if", "not", "image_file", "and", "not", "source_link", ":", "raise", "Exception", "(", "'You must specify an image file or a source link'", ")", "content_type", "=", "self", ".", "_get_image_type", "(", "image_file", ")", "if", "not", "title", ":", "title", "=", "os", ".", "path", ".", "basename", "(", "image_file", ")", "f", "=", "open", "(", "image_file", ",", "'rb'", ")", "endpoint", "=", "'/api/upload'", "files", "=", "{", "'file'", ":", "(", "title", ",", "f", ",", "content_type", ")", "}", "data", "=", "self", ".", "_make_request", "(", "'POST'", ",", "endpoint", "=", "endpoint", ",", "files", "=", "files", ")", "f", ".", "close", "(", ")", "return", "data" ]
Upload an image. TODO: Don't have a pro account to test (or even write) code to upload a shared filed to a particular shake. Args: image_file (str): path to an image (jpg/gif) on your computer. source_link (str): URL of a source (youtube/vine/etc.) shake_id (int): shake to which to upload the file or source_link [optional] title (str): title of the SharedFile [optional] description (str): description of the SharedFile Returns: SharedFile key.
[ "Upload", "an", "image", "." ]
3ab92f6706397cde7a18367266eba9e0f1ada868
https://github.com/jeremylow/pyshk/blob/3ab92f6706397cde7a18367266eba9e0f1ada868/pyshk/api.py#L516-L557
248,586
svasilev94/GraphLibrary
graphlibrary/graph.py
Graph.add_edge
def add_edge(self, u, v, **attr): """ Add an edge between vertices u and v and update edge attributes """ if u not in self.vertices: self.vertices[u] = [] if v not in self.vertices: self.vertices[v] = [] vertex = (u, v) self.edges[vertex] = {} if attr: self.edges[vertex].update(attr) self.vertices[u].append(v) self.vertices[v].append(u)
python
def add_edge(self, u, v, **attr): """ Add an edge between vertices u and v and update edge attributes """ if u not in self.vertices: self.vertices[u] = [] if v not in self.vertices: self.vertices[v] = [] vertex = (u, v) self.edges[vertex] = {} if attr: self.edges[vertex].update(attr) self.vertices[u].append(v) self.vertices[v].append(u)
[ "def", "add_edge", "(", "self", ",", "u", ",", "v", ",", "*", "*", "attr", ")", ":", "if", "u", "not", "in", "self", ".", "vertices", ":", "self", ".", "vertices", "[", "u", "]", "=", "[", "]", "if", "v", "not", "in", "self", ".", "vertices", ":", "self", ".", "vertices", "[", "v", "]", "=", "[", "]", "vertex", "=", "(", "u", ",", "v", ")", "self", ".", "edges", "[", "vertex", "]", "=", "{", "}", "if", "attr", ":", "self", ".", "edges", "[", "vertex", "]", ".", "update", "(", "attr", ")", "self", ".", "vertices", "[", "u", "]", ".", "append", "(", "v", ")", "self", ".", "vertices", "[", "v", "]", ".", "append", "(", "u", ")" ]
Add an edge between vertices u and v and update edge attributes
[ "Add", "an", "edge", "between", "vertices", "u", "and", "v", "and", "update", "edge", "attributes" ]
bf979a80bdea17eeb25955f0c119ca8f711ef62b
https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/graph.py#L57-L70
248,587
svasilev94/GraphLibrary
graphlibrary/graph.py
Graph.remove_edge
def remove_edge(self, u, v): """ Remove the edge between vertices u and v """ try: self.edges.pop((u, v)) except KeyError: raise GraphInsertError("Edge %s-%s doesn't exist." % (u, v)) self.vertices[u].remove(v) self.vertices[v].remove(u)
python
def remove_edge(self, u, v): """ Remove the edge between vertices u and v """ try: self.edges.pop((u, v)) except KeyError: raise GraphInsertError("Edge %s-%s doesn't exist." % (u, v)) self.vertices[u].remove(v) self.vertices[v].remove(u)
[ "def", "remove_edge", "(", "self", ",", "u", ",", "v", ")", ":", "try", ":", "self", ".", "edges", ".", "pop", "(", "(", "u", ",", "v", ")", ")", "except", "KeyError", ":", "raise", "GraphInsertError", "(", "\"Edge %s-%s doesn't exist.\"", "%", "(", "u", ",", "v", ")", ")", "self", ".", "vertices", "[", "u", "]", ".", "remove", "(", "v", ")", "self", ".", "vertices", "[", "v", "]", ".", "remove", "(", "u", ")" ]
Remove the edge between vertices u and v
[ "Remove", "the", "edge", "between", "vertices", "u", "and", "v" ]
bf979a80bdea17eeb25955f0c119ca8f711ef62b
https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/graph.py#L92-L101
248,588
svasilev94/GraphLibrary
graphlibrary/graph.py
Graph.degree
def degree(self, vertex): """ Return the degree of a vertex """ try: return len(self.vertices[vertex]) except KeyError: raise GraphInsertError("Vertex %s doesn't exist." % (vertex,))
python
def degree(self, vertex): """ Return the degree of a vertex """ try: return len(self.vertices[vertex]) except KeyError: raise GraphInsertError("Vertex %s doesn't exist." % (vertex,))
[ "def", "degree", "(", "self", ",", "vertex", ")", ":", "try", ":", "return", "len", "(", "self", ".", "vertices", "[", "vertex", "]", ")", "except", "KeyError", ":", "raise", "GraphInsertError", "(", "\"Vertex %s doesn't exist.\"", "%", "(", "vertex", ",", ")", ")" ]
Return the degree of a vertex
[ "Return", "the", "degree", "of", "a", "vertex" ]
bf979a80bdea17eeb25955f0c119ca8f711ef62b
https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/graph.py#L112-L119
248,589
sys-git/certifiable
certifiable/cli_impl/core/certify_int.py
cli_certify_core_integer
def cli_certify_core_integer( config, min_value, max_value, value, ): """Console script for certify_int""" def parser(v): # Attempt a json/pickle decode: try: v = load_json_pickle(v, config) except Exception: pass # Attempt a straight conversion to integer: try: return int(v) except Exception as err: six.raise_from( CertifierTypeError( message='Not integer: {x}'.format( x=v, ), value=v, ), err, ) execute_cli_command( 'integer', config, parser, certify_int, value[0] if value else None, min_value=min_value, max_value=max_value, required=config['required'], )
python
def cli_certify_core_integer( config, min_value, max_value, value, ): """Console script for certify_int""" def parser(v): # Attempt a json/pickle decode: try: v = load_json_pickle(v, config) except Exception: pass # Attempt a straight conversion to integer: try: return int(v) except Exception as err: six.raise_from( CertifierTypeError( message='Not integer: {x}'.format( x=v, ), value=v, ), err, ) execute_cli_command( 'integer', config, parser, certify_int, value[0] if value else None, min_value=min_value, max_value=max_value, required=config['required'], )
[ "def", "cli_certify_core_integer", "(", "config", ",", "min_value", ",", "max_value", ",", "value", ",", ")", ":", "def", "parser", "(", "v", ")", ":", "# Attempt a json/pickle decode:", "try", ":", "v", "=", "load_json_pickle", "(", "v", ",", "config", ")", "except", "Exception", ":", "pass", "# Attempt a straight conversion to integer:", "try", ":", "return", "int", "(", "v", ")", "except", "Exception", "as", "err", ":", "six", ".", "raise_from", "(", "CertifierTypeError", "(", "message", "=", "'Not integer: {x}'", ".", "format", "(", "x", "=", "v", ",", ")", ",", "value", "=", "v", ",", ")", ",", "err", ",", ")", "execute_cli_command", "(", "'integer'", ",", "config", ",", "parser", ",", "certify_int", ",", "value", "[", "0", "]", "if", "value", "else", "None", ",", "min_value", "=", "min_value", ",", "max_value", "=", "max_value", ",", "required", "=", "config", "[", "'required'", "]", ",", ")" ]
Console script for certify_int
[ "Console", "script", "for", "certify_int" ]
a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8
https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/cli_impl/core/certify_int.py#L22-L57
248,590
ardydedase/pycouchbase
couchbase-python-cffi/couchbase_ffi/bucket.py
Bucket._warn_dupkey
def _warn_dupkey(self, k): """ Really odd function - used to help ensure we actually warn for duplicate keys. """ if self._privflags & PYCBC_CONN_F_WARNEXPLICIT: warnings.warn_explicit( 'Found duplicate keys! {0}'.format(k), RuntimeWarning, __file__, -1, module='couchbase_ffi.bucket', registry={}) else: warnings.warn('Found duplicate keys!', RuntimeWarning)
python
def _warn_dupkey(self, k): """ Really odd function - used to help ensure we actually warn for duplicate keys. """ if self._privflags & PYCBC_CONN_F_WARNEXPLICIT: warnings.warn_explicit( 'Found duplicate keys! {0}'.format(k), RuntimeWarning, __file__, -1, module='couchbase_ffi.bucket', registry={}) else: warnings.warn('Found duplicate keys!', RuntimeWarning)
[ "def", "_warn_dupkey", "(", "self", ",", "k", ")", ":", "if", "self", ".", "_privflags", "&", "PYCBC_CONN_F_WARNEXPLICIT", ":", "warnings", ".", "warn_explicit", "(", "'Found duplicate keys! {0}'", ".", "format", "(", "k", ")", ",", "RuntimeWarning", ",", "__file__", ",", "-", "1", ",", "module", "=", "'couchbase_ffi.bucket'", ",", "registry", "=", "{", "}", ")", "else", ":", "warnings", ".", "warn", "(", "'Found duplicate keys!'", ",", "RuntimeWarning", ")" ]
Really odd function - used to help ensure we actually warn for duplicate keys.
[ "Really", "odd", "function", "-", "used", "to", "help", "ensure", "we", "actually", "warn", "for", "duplicate", "keys", "." ]
6f010b4d2ef41aead2366878d0cf0b1284c0db0e
https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/couchbase-python-cffi/couchbase_ffi/bucket.py#L750-L760
248,591
minhhoit/yacms
yacms/blog/management/commands/import_wordpress.py
Command.get_text
def get_text(self, xml, name): """ Gets the element's text value from the XML object provided. """ nodes = xml.getElementsByTagName("wp:comment_" + name)[0].childNodes accepted_types = [Node.CDATA_SECTION_NODE, Node.TEXT_NODE] return "".join([n.data for n in nodes if n.nodeType in accepted_types])
python
def get_text(self, xml, name): """ Gets the element's text value from the XML object provided. """ nodes = xml.getElementsByTagName("wp:comment_" + name)[0].childNodes accepted_types = [Node.CDATA_SECTION_NODE, Node.TEXT_NODE] return "".join([n.data for n in nodes if n.nodeType in accepted_types])
[ "def", "get_text", "(", "self", ",", "xml", ",", "name", ")", ":", "nodes", "=", "xml", ".", "getElementsByTagName", "(", "\"wp:comment_\"", "+", "name", ")", "[", "0", "]", ".", "childNodes", "accepted_types", "=", "[", "Node", ".", "CDATA_SECTION_NODE", ",", "Node", ".", "TEXT_NODE", "]", "return", "\"\"", ".", "join", "(", "[", "n", ".", "data", "for", "n", "in", "nodes", "if", "n", ".", "nodeType", "in", "accepted_types", "]", ")" ]
Gets the element's text value from the XML object provided.
[ "Gets", "the", "element", "s", "text", "value", "from", "the", "XML", "object", "provided", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/management/commands/import_wordpress.py#L28-L34
248,592
minhhoit/yacms
yacms/blog/management/commands/import_wordpress.py
Command.handle_import
def handle_import(self, options): """ Gets the posts from either the provided URL or the path if it is local. """ url = options.get("url") if url is None: raise CommandError("Usage is import_wordpress %s" % self.args) try: import feedparser except ImportError: raise CommandError("Could not import the feedparser library.") feed = feedparser.parse(url) # We use the minidom parser as well because feedparser won't # interpret WXR comments correctly and ends up munging them. # xml.dom.minidom is used simply to pull the comments when we # get to them. xml = parse(url) xmlitems = xml.getElementsByTagName("item") for (i, entry) in enumerate(feed["entries"]): # Get a pointer to the right position in the minidom as well. xmlitem = xmlitems[i] content = linebreaks(self.wp_caption(entry.content[0]["value"])) # Get the time struct of the published date if possible and # the updated date if we can't. pub_date = getattr(entry, "published_parsed", entry.updated_parsed) if pub_date: pub_date = datetime.fromtimestamp(mktime(pub_date)) pub_date -= timedelta(seconds=timezone) # Tags and categories are all under "tags" marked with a scheme. terms = defaultdict(set) for item in getattr(entry, "tags", []): terms[item.scheme].add(item.term) if entry.wp_post_type == "post": post = self.add_post(title=entry.title, content=content, pub_date=pub_date, tags=terms["tag"], categories=terms["category"], old_url=entry.id) # Get the comments from the xml doc. for c in xmlitem.getElementsByTagName("wp:comment"): name = self.get_text(c, "author") email = self.get_text(c, "author_email") url = self.get_text(c, "author_url") body = self.get_text(c, "content") pub_date = self.get_text(c, "date_gmt") fmt = "%Y-%m-%d %H:%M:%S" pub_date = datetime.strptime(pub_date, fmt) pub_date -= timedelta(seconds=timezone) self.add_comment(post=post, name=name, email=email, body=body, website=url, pub_date=pub_date) elif entry.wp_post_type == "page": old_id = getattr(entry, "wp_post_id") parent_id = getattr(entry, "wp_post_parent") self.add_page(title=entry.title, content=content, tags=terms["tag"], old_id=old_id, old_parent_id=parent_id)
python
def handle_import(self, options): """ Gets the posts from either the provided URL or the path if it is local. """ url = options.get("url") if url is None: raise CommandError("Usage is import_wordpress %s" % self.args) try: import feedparser except ImportError: raise CommandError("Could not import the feedparser library.") feed = feedparser.parse(url) # We use the minidom parser as well because feedparser won't # interpret WXR comments correctly and ends up munging them. # xml.dom.minidom is used simply to pull the comments when we # get to them. xml = parse(url) xmlitems = xml.getElementsByTagName("item") for (i, entry) in enumerate(feed["entries"]): # Get a pointer to the right position in the minidom as well. xmlitem = xmlitems[i] content = linebreaks(self.wp_caption(entry.content[0]["value"])) # Get the time struct of the published date if possible and # the updated date if we can't. pub_date = getattr(entry, "published_parsed", entry.updated_parsed) if pub_date: pub_date = datetime.fromtimestamp(mktime(pub_date)) pub_date -= timedelta(seconds=timezone) # Tags and categories are all under "tags" marked with a scheme. terms = defaultdict(set) for item in getattr(entry, "tags", []): terms[item.scheme].add(item.term) if entry.wp_post_type == "post": post = self.add_post(title=entry.title, content=content, pub_date=pub_date, tags=terms["tag"], categories=terms["category"], old_url=entry.id) # Get the comments from the xml doc. for c in xmlitem.getElementsByTagName("wp:comment"): name = self.get_text(c, "author") email = self.get_text(c, "author_email") url = self.get_text(c, "author_url") body = self.get_text(c, "content") pub_date = self.get_text(c, "date_gmt") fmt = "%Y-%m-%d %H:%M:%S" pub_date = datetime.strptime(pub_date, fmt) pub_date -= timedelta(seconds=timezone) self.add_comment(post=post, name=name, email=email, body=body, website=url, pub_date=pub_date) elif entry.wp_post_type == "page": old_id = getattr(entry, "wp_post_id") parent_id = getattr(entry, "wp_post_parent") self.add_page(title=entry.title, content=content, tags=terms["tag"], old_id=old_id, old_parent_id=parent_id)
[ "def", "handle_import", "(", "self", ",", "options", ")", ":", "url", "=", "options", ".", "get", "(", "\"url\"", ")", "if", "url", "is", "None", ":", "raise", "CommandError", "(", "\"Usage is import_wordpress %s\"", "%", "self", ".", "args", ")", "try", ":", "import", "feedparser", "except", "ImportError", ":", "raise", "CommandError", "(", "\"Could not import the feedparser library.\"", ")", "feed", "=", "feedparser", ".", "parse", "(", "url", ")", "# We use the minidom parser as well because feedparser won't", "# interpret WXR comments correctly and ends up munging them.", "# xml.dom.minidom is used simply to pull the comments when we", "# get to them.", "xml", "=", "parse", "(", "url", ")", "xmlitems", "=", "xml", ".", "getElementsByTagName", "(", "\"item\"", ")", "for", "(", "i", ",", "entry", ")", "in", "enumerate", "(", "feed", "[", "\"entries\"", "]", ")", ":", "# Get a pointer to the right position in the minidom as well.", "xmlitem", "=", "xmlitems", "[", "i", "]", "content", "=", "linebreaks", "(", "self", ".", "wp_caption", "(", "entry", ".", "content", "[", "0", "]", "[", "\"value\"", "]", ")", ")", "# Get the time struct of the published date if possible and", "# the updated date if we can't.", "pub_date", "=", "getattr", "(", "entry", ",", "\"published_parsed\"", ",", "entry", ".", "updated_parsed", ")", "if", "pub_date", ":", "pub_date", "=", "datetime", ".", "fromtimestamp", "(", "mktime", "(", "pub_date", ")", ")", "pub_date", "-=", "timedelta", "(", "seconds", "=", "timezone", ")", "# Tags and categories are all under \"tags\" marked with a scheme.", "terms", "=", "defaultdict", "(", "set", ")", "for", "item", "in", "getattr", "(", "entry", ",", "\"tags\"", ",", "[", "]", ")", ":", "terms", "[", "item", ".", "scheme", "]", ".", "add", "(", "item", ".", "term", ")", "if", "entry", ".", "wp_post_type", "==", "\"post\"", ":", "post", "=", "self", ".", "add_post", "(", "title", "=", "entry", ".", "title", ",", "content", "=", "content", ",", "pub_date", "=", "pub_date", ",", "tags", "=", "terms", "[", "\"tag\"", "]", ",", "categories", "=", "terms", "[", "\"category\"", "]", ",", "old_url", "=", "entry", ".", "id", ")", "# Get the comments from the xml doc.", "for", "c", "in", "xmlitem", ".", "getElementsByTagName", "(", "\"wp:comment\"", ")", ":", "name", "=", "self", ".", "get_text", "(", "c", ",", "\"author\"", ")", "email", "=", "self", ".", "get_text", "(", "c", ",", "\"author_email\"", ")", "url", "=", "self", ".", "get_text", "(", "c", ",", "\"author_url\"", ")", "body", "=", "self", ".", "get_text", "(", "c", ",", "\"content\"", ")", "pub_date", "=", "self", ".", "get_text", "(", "c", ",", "\"date_gmt\"", ")", "fmt", "=", "\"%Y-%m-%d %H:%M:%S\"", "pub_date", "=", "datetime", ".", "strptime", "(", "pub_date", ",", "fmt", ")", "pub_date", "-=", "timedelta", "(", "seconds", "=", "timezone", ")", "self", ".", "add_comment", "(", "post", "=", "post", ",", "name", "=", "name", ",", "email", "=", "email", ",", "body", "=", "body", ",", "website", "=", "url", ",", "pub_date", "=", "pub_date", ")", "elif", "entry", ".", "wp_post_type", "==", "\"page\"", ":", "old_id", "=", "getattr", "(", "entry", ",", "\"wp_post_id\"", ")", "parent_id", "=", "getattr", "(", "entry", ",", "\"wp_post_parent\"", ")", "self", ".", "add_page", "(", "title", "=", "entry", ".", "title", ",", "content", "=", "content", ",", "tags", "=", "terms", "[", "\"tag\"", "]", ",", "old_id", "=", "old_id", ",", "old_parent_id", "=", "parent_id", ")" ]
Gets the posts from either the provided URL or the path if it is local.
[ "Gets", "the", "posts", "from", "either", "the", "provided", "URL", "or", "the", "path", "if", "it", "is", "local", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/management/commands/import_wordpress.py#L36-L100
248,593
minhhoit/yacms
yacms/blog/management/commands/import_wordpress.py
Command.wp_caption
def wp_caption(self, post): """ Filters a Wordpress Post for Image Captions and renders to match HTML. """ for match in re.finditer(r"\[caption (.*?)\](.*?)\[/caption\]", post): meta = '<div ' caption = '' for imatch in re.finditer(r'(\w+)="(.*?)"', match.group(1)): if imatch.group(1) == 'id': meta += 'id="%s" ' % imatch.group(2) if imatch.group(1) == 'align': meta += 'class="wp-caption %s" ' % imatch.group(2) if imatch.group(1) == 'width': width = int(imatch.group(2)) + 10 meta += 'style="width: %spx;" ' % width if imatch.group(1) == 'caption': caption = imatch.group(2) parts = (match.group(2), caption) meta += '>%s<p class="wp-caption-text">%s</p></div>' % parts post = post.replace(match.group(0), meta) return post
python
def wp_caption(self, post): """ Filters a Wordpress Post for Image Captions and renders to match HTML. """ for match in re.finditer(r"\[caption (.*?)\](.*?)\[/caption\]", post): meta = '<div ' caption = '' for imatch in re.finditer(r'(\w+)="(.*?)"', match.group(1)): if imatch.group(1) == 'id': meta += 'id="%s" ' % imatch.group(2) if imatch.group(1) == 'align': meta += 'class="wp-caption %s" ' % imatch.group(2) if imatch.group(1) == 'width': width = int(imatch.group(2)) + 10 meta += 'style="width: %spx;" ' % width if imatch.group(1) == 'caption': caption = imatch.group(2) parts = (match.group(2), caption) meta += '>%s<p class="wp-caption-text">%s</p></div>' % parts post = post.replace(match.group(0), meta) return post
[ "def", "wp_caption", "(", "self", ",", "post", ")", ":", "for", "match", "in", "re", ".", "finditer", "(", "r\"\\[caption (.*?)\\](.*?)\\[/caption\\]\"", ",", "post", ")", ":", "meta", "=", "'<div '", "caption", "=", "''", "for", "imatch", "in", "re", ".", "finditer", "(", "r'(\\w+)=\"(.*?)\"'", ",", "match", ".", "group", "(", "1", ")", ")", ":", "if", "imatch", ".", "group", "(", "1", ")", "==", "'id'", ":", "meta", "+=", "'id=\"%s\" '", "%", "imatch", ".", "group", "(", "2", ")", "if", "imatch", ".", "group", "(", "1", ")", "==", "'align'", ":", "meta", "+=", "'class=\"wp-caption %s\" '", "%", "imatch", ".", "group", "(", "2", ")", "if", "imatch", ".", "group", "(", "1", ")", "==", "'width'", ":", "width", "=", "int", "(", "imatch", ".", "group", "(", "2", ")", ")", "+", "10", "meta", "+=", "'style=\"width: %spx;\" '", "%", "width", "if", "imatch", ".", "group", "(", "1", ")", "==", "'caption'", ":", "caption", "=", "imatch", ".", "group", "(", "2", ")", "parts", "=", "(", "match", ".", "group", "(", "2", ")", ",", "caption", ")", "meta", "+=", "'>%s<p class=\"wp-caption-text\">%s</p></div>'", "%", "parts", "post", "=", "post", ".", "replace", "(", "match", ".", "group", "(", "0", ")", ",", "meta", ")", "return", "post" ]
Filters a Wordpress Post for Image Captions and renders to match HTML.
[ "Filters", "a", "Wordpress", "Post", "for", "Image", "Captions", "and", "renders", "to", "match", "HTML", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/management/commands/import_wordpress.py#L102-L123
248,594
d6e/emotion
emote/emote.py
read_emote_mappings
def read_emote_mappings(json_obj_files=[]): """ Reads the contents of a list of files of json objects and combines them into one large json object. """ super_json = {} for fname in json_obj_files: with open(fname) as f: super_json.update(json.loads(f.read().decode('utf-8'))) return super_json
python
def read_emote_mappings(json_obj_files=[]): """ Reads the contents of a list of files of json objects and combines them into one large json object. """ super_json = {} for fname in json_obj_files: with open(fname) as f: super_json.update(json.loads(f.read().decode('utf-8'))) return super_json
[ "def", "read_emote_mappings", "(", "json_obj_files", "=", "[", "]", ")", ":", "super_json", "=", "{", "}", "for", "fname", "in", "json_obj_files", ":", "with", "open", "(", "fname", ")", "as", "f", ":", "super_json", ".", "update", "(", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", ")", ")", "return", "super_json" ]
Reads the contents of a list of files of json objects and combines them into one large json object.
[ "Reads", "the", "contents", "of", "a", "list", "of", "files", "of", "json", "objects", "and", "combines", "them", "into", "one", "large", "json", "object", "." ]
8ea84935a9103c3079579b3d9b9db85e12710af2
https://github.com/d6e/emotion/blob/8ea84935a9103c3079579b3d9b9db85e12710af2/emote/emote.py#L9-L16
248,595
sternoru/goscalecms
goscale/themes/site_middleware.py
make_tls_property
def make_tls_property(default=None): """Creates a class-wide instance property with a thread-specific value.""" class TLSProperty(object): def __init__(self): from threading import local self.local = local() def __get__(self, instance, cls): if not instance: return self return self.value def __set__(self, instance, value): self.value = value def _get_value(self): return getattr(self.local, 'value', default) def _set_value(self, value): self.local.value = value value = property(_get_value, _set_value) return TLSProperty()
python
def make_tls_property(default=None): """Creates a class-wide instance property with a thread-specific value.""" class TLSProperty(object): def __init__(self): from threading import local self.local = local() def __get__(self, instance, cls): if not instance: return self return self.value def __set__(self, instance, value): self.value = value def _get_value(self): return getattr(self.local, 'value', default) def _set_value(self, value): self.local.value = value value = property(_get_value, _set_value) return TLSProperty()
[ "def", "make_tls_property", "(", "default", "=", "None", ")", ":", "class", "TLSProperty", "(", "object", ")", ":", "def", "__init__", "(", "self", ")", ":", "from", "threading", "import", "local", "self", ".", "local", "=", "local", "(", ")", "def", "__get__", "(", "self", ",", "instance", ",", "cls", ")", ":", "if", "not", "instance", ":", "return", "self", "return", "self", ".", "value", "def", "__set__", "(", "self", ",", "instance", ",", "value", ")", ":", "self", ".", "value", "=", "value", "def", "_get_value", "(", "self", ")", ":", "return", "getattr", "(", "self", ".", "local", ",", "'value'", ",", "default", ")", "def", "_set_value", "(", "self", ",", "value", ")", ":", "self", ".", "local", ".", "value", "=", "value", "value", "=", "property", "(", "_get_value", ",", "_set_value", ")", "return", "TLSProperty", "(", ")" ]
Creates a class-wide instance property with a thread-specific value.
[ "Creates", "a", "class", "-", "wide", "instance", "property", "with", "a", "thread", "-", "specific", "value", "." ]
7eee50357c47ebdfe3e573a8b4be3b67892d229e
https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/themes/site_middleware.py#L7-L28
248,596
sternoru/goscalecms
goscale/themes/site_middleware.py
SiteOnFlyDetectionMiddleware.lookup
def lookup(self): """ The meat of this middleware. Returns None and sets settings.SITE_ID if able to find a Site object by domain and its subdomain is valid. Returns an HttpResponsePermanentRedirect to the Site's default subdomain if a site is found but the requested subdomain is not supported, or if domain_unsplit is defined in settings.HOSTNAME_REDIRECTS Otherwise, returns False. """ # check to see if this hostname is actually a env hostname if self.domain: if self.subdomain: self.domain_unsplit = '%s.%s' % (self.subdomain, self.domain) else: self.domain_unsplit = self.domain self.domain_requested = self.domain_unsplit # check cache cache_key = 'site_id:%s' % self.domain_unsplit site_id = cache.get(cache_key) if site_id: SITE_ID.value = site_id try: self.site = Site.objects.get(id=site_id) except Site.DoesNotExist: # This might happen if the Site object was deleted from the # database after it was cached. Remove from cache and act # as if the cache lookup failed. cache.delete(cache_key) else: return None # check database try: self.site = Site.objects.get(domain=self.domain) except Site.DoesNotExist: return False if not self.site: return False SITE_ID.value = self.site.pk cache.set(cache_key, SITE_ID.value, 5*60) return None
python
def lookup(self): """ The meat of this middleware. Returns None and sets settings.SITE_ID if able to find a Site object by domain and its subdomain is valid. Returns an HttpResponsePermanentRedirect to the Site's default subdomain if a site is found but the requested subdomain is not supported, or if domain_unsplit is defined in settings.HOSTNAME_REDIRECTS Otherwise, returns False. """ # check to see if this hostname is actually a env hostname if self.domain: if self.subdomain: self.domain_unsplit = '%s.%s' % (self.subdomain, self.domain) else: self.domain_unsplit = self.domain self.domain_requested = self.domain_unsplit # check cache cache_key = 'site_id:%s' % self.domain_unsplit site_id = cache.get(cache_key) if site_id: SITE_ID.value = site_id try: self.site = Site.objects.get(id=site_id) except Site.DoesNotExist: # This might happen if the Site object was deleted from the # database after it was cached. Remove from cache and act # as if the cache lookup failed. cache.delete(cache_key) else: return None # check database try: self.site = Site.objects.get(domain=self.domain) except Site.DoesNotExist: return False if not self.site: return False SITE_ID.value = self.site.pk cache.set(cache_key, SITE_ID.value, 5*60) return None
[ "def", "lookup", "(", "self", ")", ":", "# check to see if this hostname is actually a env hostname", "if", "self", ".", "domain", ":", "if", "self", ".", "subdomain", ":", "self", ".", "domain_unsplit", "=", "'%s.%s'", "%", "(", "self", ".", "subdomain", ",", "self", ".", "domain", ")", "else", ":", "self", ".", "domain_unsplit", "=", "self", ".", "domain", "self", ".", "domain_requested", "=", "self", ".", "domain_unsplit", "# check cache", "cache_key", "=", "'site_id:%s'", "%", "self", ".", "domain_unsplit", "site_id", "=", "cache", ".", "get", "(", "cache_key", ")", "if", "site_id", ":", "SITE_ID", ".", "value", "=", "site_id", "try", ":", "self", ".", "site", "=", "Site", ".", "objects", ".", "get", "(", "id", "=", "site_id", ")", "except", "Site", ".", "DoesNotExist", ":", "# This might happen if the Site object was deleted from the", "# database after it was cached. Remove from cache and act", "# as if the cache lookup failed.", "cache", ".", "delete", "(", "cache_key", ")", "else", ":", "return", "None", "# check database", "try", ":", "self", ".", "site", "=", "Site", ".", "objects", ".", "get", "(", "domain", "=", "self", ".", "domain", ")", "except", "Site", ".", "DoesNotExist", ":", "return", "False", "if", "not", "self", ".", "site", ":", "return", "False", "SITE_ID", ".", "value", "=", "self", ".", "site", ".", "pk", "cache", ".", "set", "(", "cache_key", ",", "SITE_ID", ".", "value", ",", "5", "*", "60", ")", "return", "None" ]
The meat of this middleware. Returns None and sets settings.SITE_ID if able to find a Site object by domain and its subdomain is valid. Returns an HttpResponsePermanentRedirect to the Site's default subdomain if a site is found but the requested subdomain is not supported, or if domain_unsplit is defined in settings.HOSTNAME_REDIRECTS Otherwise, returns False.
[ "The", "meat", "of", "this", "middleware", "." ]
7eee50357c47ebdfe3e573a8b4be3b67892d229e
https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/themes/site_middleware.py#L70-L118
248,597
sternoru/goscalecms
goscale/themes/site_middleware.py
SiteOnFlyDetectionMiddleware.theme_lookup
def theme_lookup(self): """ Returns theme based on site Returns None and sets settings.THEME if able to find a theme object by site. Otherwise, returns False. """ # check cache cache_key = 'theme:%s' % self.domain_unsplit theme = cache.get(cache_key) if theme: THEME.value = theme return None # check database if hasattr(self.site, 'themes'): try: themes = [theme.name for theme in self.site.themes.all()] THEME.value = themes[0] cache.set(cache_key, THEME.value, 5*60) except: return False return None
python
def theme_lookup(self): """ Returns theme based on site Returns None and sets settings.THEME if able to find a theme object by site. Otherwise, returns False. """ # check cache cache_key = 'theme:%s' % self.domain_unsplit theme = cache.get(cache_key) if theme: THEME.value = theme return None # check database if hasattr(self.site, 'themes'): try: themes = [theme.name for theme in self.site.themes.all()] THEME.value = themes[0] cache.set(cache_key, THEME.value, 5*60) except: return False return None
[ "def", "theme_lookup", "(", "self", ")", ":", "# check cache", "cache_key", "=", "'theme:%s'", "%", "self", ".", "domain_unsplit", "theme", "=", "cache", ".", "get", "(", "cache_key", ")", "if", "theme", ":", "THEME", ".", "value", "=", "theme", "return", "None", "# check database", "if", "hasattr", "(", "self", ".", "site", ",", "'themes'", ")", ":", "try", ":", "themes", "=", "[", "theme", ".", "name", "for", "theme", "in", "self", ".", "site", ".", "themes", ".", "all", "(", ")", "]", "THEME", ".", "value", "=", "themes", "[", "0", "]", "cache", ".", "set", "(", "cache_key", ",", "THEME", ".", "value", ",", "5", "*", "60", ")", "except", ":", "return", "False", "return", "None" ]
Returns theme based on site Returns None and sets settings.THEME if able to find a theme object by site. Otherwise, returns False.
[ "Returns", "theme", "based", "on", "site" ]
7eee50357c47ebdfe3e573a8b4be3b67892d229e
https://github.com/sternoru/goscalecms/blob/7eee50357c47ebdfe3e573a8b4be3b67892d229e/goscale/themes/site_middleware.py#L120-L144
248,598
Valuehorizon/valuehorizon-people
people/models.py
Person.age
def age(self, as_at_date=None): """ Compute the person's age """ if self.date_of_death != None or self.is_deceased == True: return None as_at_date = date.today() if as_at_date == None else as_at_date if self.date_of_birth != None: if (as_at_date.month >= self.date_of_birth.month) and (as_at_date.day >= self.date_of_birth.day): return (as_at_date.year - self.date_of_birth.year) else: return ((as_at_date.year - self.date_of_birth.year) -1) else: return None
python
def age(self, as_at_date=None): """ Compute the person's age """ if self.date_of_death != None or self.is_deceased == True: return None as_at_date = date.today() if as_at_date == None else as_at_date if self.date_of_birth != None: if (as_at_date.month >= self.date_of_birth.month) and (as_at_date.day >= self.date_of_birth.day): return (as_at_date.year - self.date_of_birth.year) else: return ((as_at_date.year - self.date_of_birth.year) -1) else: return None
[ "def", "age", "(", "self", ",", "as_at_date", "=", "None", ")", ":", "if", "self", ".", "date_of_death", "!=", "None", "or", "self", ".", "is_deceased", "==", "True", ":", "return", "None", "as_at_date", "=", "date", ".", "today", "(", ")", "if", "as_at_date", "==", "None", "else", "as_at_date", "if", "self", ".", "date_of_birth", "!=", "None", ":", "if", "(", "as_at_date", ".", "month", ">=", "self", ".", "date_of_birth", ".", "month", ")", "and", "(", "as_at_date", ".", "day", ">=", "self", ".", "date_of_birth", ".", "day", ")", ":", "return", "(", "as_at_date", ".", "year", "-", "self", ".", "date_of_birth", ".", "year", ")", "else", ":", "return", "(", "(", "as_at_date", ".", "year", "-", "self", ".", "date_of_birth", ".", "year", ")", "-", "1", ")", "else", ":", "return", "None" ]
Compute the person's age
[ "Compute", "the", "person", "s", "age" ]
f32d9f1349c1a9384bae5ea61d10c1b1e0318401
https://github.com/Valuehorizon/valuehorizon-people/blob/f32d9f1349c1a9384bae5ea61d10c1b1e0318401/people/models.py#L53-L68
248,599
Valuehorizon/valuehorizon-people
people/models.py
Person.name
def name(self): """ Return the person's name. If we have special titles, use them, otherwise, don't include the title. """ if self.title in ["DR", "SIR", "LORD"]: return "%s %s %s" % (self.get_title_display(), self.first_name, self.last_name) else: return "%s %s" % (self.first_name, self.last_name)
python
def name(self): """ Return the person's name. If we have special titles, use them, otherwise, don't include the title. """ if self.title in ["DR", "SIR", "LORD"]: return "%s %s %s" % (self.get_title_display(), self.first_name, self.last_name) else: return "%s %s" % (self.first_name, self.last_name)
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "title", "in", "[", "\"DR\"", ",", "\"SIR\"", ",", "\"LORD\"", "]", ":", "return", "\"%s %s %s\"", "%", "(", "self", ".", "get_title_display", "(", ")", ",", "self", ".", "first_name", ",", "self", ".", "last_name", ")", "else", ":", "return", "\"%s %s\"", "%", "(", "self", ".", "first_name", ",", "self", ".", "last_name", ")" ]
Return the person's name. If we have special titles, use them, otherwise, don't include the title.
[ "Return", "the", "person", "s", "name", ".", "If", "we", "have", "special", "titles", "use", "them", "otherwise", "don", "t", "include", "the", "title", "." ]
f32d9f1349c1a9384bae5ea61d10c1b1e0318401
https://github.com/Valuehorizon/valuehorizon-people/blob/f32d9f1349c1a9384bae5ea61d10c1b1e0318401/people/models.py#L78-L86