repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
RazerM/bucketcache
shovel/version.py
release
def release(): """Bump version, tag, build, gen docs.""" if check_staged(): raise EnvironmentError('There are staged changes, abort.') if check_unstaged(): raise EnvironmentError('There are unstaged changes, abort.') bump() tag() build() doc_gen() puts(colored.yellow("Rem...
python
def release(): """Bump version, tag, build, gen docs.""" if check_staged(): raise EnvironmentError('There are staged changes, abort.') if check_unstaged(): raise EnvironmentError('There are unstaged changes, abort.') bump() tag() build() doc_gen() puts(colored.yellow("Rem...
[ "def", "release", "(", ")", ":", "if", "check_staged", "(", ")", ":", "raise", "EnvironmentError", "(", "'There are staged changes, abort.'", ")", "if", "check_unstaged", "(", ")", ":", "raise", "EnvironmentError", "(", "'There are unstaged changes, abort.'", ")", "...
Bump version, tag, build, gen docs.
[ "Bump", "version", "tag", "build", "gen", "docs", "." ]
train
https://github.com/RazerM/bucketcache/blob/8d9b163b73da8c498793cce2f22f6a7cbe524d94/shovel/version.py#L105-L118
sassoo/goldman
goldman/utils/responder_helpers.py
validate_rid
def validate_rid(model, rid): """ Ensure the resource id is proper """ rid_field = getattr(model, model.rid_field) if isinstance(rid_field, IntType): try: int(rid) except (TypeError, ValueError): abort(exceptions.InvalidURL(**{ 'detail': 'The resourc...
python
def validate_rid(model, rid): """ Ensure the resource id is proper """ rid_field = getattr(model, model.rid_field) if isinstance(rid_field, IntType): try: int(rid) except (TypeError, ValueError): abort(exceptions.InvalidURL(**{ 'detail': 'The resourc...
[ "def", "validate_rid", "(", "model", ",", "rid", ")", ":", "rid_field", "=", "getattr", "(", "model", ",", "model", ".", "rid_field", ")", "if", "isinstance", "(", "rid_field", ",", "IntType", ")", ":", "try", ":", "int", "(", "rid", ")", "except", "...
Ensure the resource id is proper
[ "Ensure", "the", "resource", "id", "is", "proper" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L25-L38
sassoo/goldman
goldman/utils/responder_helpers.py
find
def find(model, rid): """ Find a model from the store by resource id """ validate_rid(model, rid) rid_field = model.rid_field model = goldman.sess.store.find(model.RTYPE, rid_field, rid) if not model: abort(exceptions.DocumentNotFound) return model
python
def find(model, rid): """ Find a model from the store by resource id """ validate_rid(model, rid) rid_field = model.rid_field model = goldman.sess.store.find(model.RTYPE, rid_field, rid) if not model: abort(exceptions.DocumentNotFound) return model
[ "def", "find", "(", "model", ",", "rid", ")", ":", "validate_rid", "(", "model", ",", "rid", ")", "rid_field", "=", "model", ".", "rid_field", "model", "=", "goldman", ".", "sess", ".", "store", ".", "find", "(", "model", ".", "RTYPE", ",", "rid_fiel...
Find a model from the store by resource id
[ "Find", "a", "model", "from", "the", "store", "by", "resource", "id" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L41-L52
sassoo/goldman
goldman/utils/responder_helpers.py
_from_rest_blank
def _from_rest_blank(model, props): """ Set empty strings to None where allowed This is done on fields with `allow_blank=True` which takes an incoming empty string & sets it to None so validations are skipped. This is useful on fields that aren't required with format validations like URLType, Email...
python
def _from_rest_blank(model, props): """ Set empty strings to None where allowed This is done on fields with `allow_blank=True` which takes an incoming empty string & sets it to None so validations are skipped. This is useful on fields that aren't required with format validations like URLType, Email...
[ "def", "_from_rest_blank", "(", "model", ",", "props", ")", ":", "blank", "=", "model", ".", "get_fields_by_prop", "(", "'allow_blank'", ",", "True", ")", "for", "field", "in", "blank", ":", "try", ":", "if", "props", "[", "field", "]", "==", "''", ":"...
Set empty strings to None where allowed This is done on fields with `allow_blank=True` which takes an incoming empty string & sets it to None so validations are skipped. This is useful on fields that aren't required with format validations like URLType, EmailType, etc.
[ "Set", "empty", "strings", "to", "None", "where", "allowed" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L55-L71
sassoo/goldman
goldman/utils/responder_helpers.py
_from_rest_hide
def _from_rest_hide(model, props): """ Purge fields not allowed during a REST deserialization This is done on fields with `from_rest=False`. """ hide = model.get_fields_by_prop('from_rest', False) for field in hide: try: del props[field] except KeyError: co...
python
def _from_rest_hide(model, props): """ Purge fields not allowed during a REST deserialization This is done on fields with `from_rest=False`. """ hide = model.get_fields_by_prop('from_rest', False) for field in hide: try: del props[field] except KeyError: co...
[ "def", "_from_rest_hide", "(", "model", ",", "props", ")", ":", "hide", "=", "model", ".", "get_fields_by_prop", "(", "'from_rest'", ",", "False", ")", "for", "field", "in", "hide", ":", "try", ":", "del", "props", "[", "field", "]", "except", "KeyError"...
Purge fields not allowed during a REST deserialization This is done on fields with `from_rest=False`.
[ "Purge", "fields", "not", "allowed", "during", "a", "REST", "deserialization" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L74-L86
sassoo/goldman
goldman/utils/responder_helpers.py
_from_rest_ignore
def _from_rest_ignore(model, props): """ Purge fields that are completely unknown """ fields = model.all_fields for prop in props.keys(): if prop not in fields: del props[prop]
python
def _from_rest_ignore(model, props): """ Purge fields that are completely unknown """ fields = model.all_fields for prop in props.keys(): if prop not in fields: del props[prop]
[ "def", "_from_rest_ignore", "(", "model", ",", "props", ")", ":", "fields", "=", "model", ".", "all_fields", "for", "prop", "in", "props", ".", "keys", "(", ")", ":", "if", "prop", "not", "in", "fields", ":", "del", "props", "[", "prop", "]" ]
Purge fields that are completely unknown
[ "Purge", "fields", "that", "are", "completely", "unknown" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L89-L96
sassoo/goldman
goldman/utils/responder_helpers.py
_from_rest_lower
def _from_rest_lower(model, props): """ Lowercase fields requesting it during a REST deserialization """ for field in model.to_lower: try: props[field] = props[field].lower() except (AttributeError, KeyError): continue
python
def _from_rest_lower(model, props): """ Lowercase fields requesting it during a REST deserialization """ for field in model.to_lower: try: props[field] = props[field].lower() except (AttributeError, KeyError): continue
[ "def", "_from_rest_lower", "(", "model", ",", "props", ")", ":", "for", "field", "in", "model", ".", "to_lower", ":", "try", ":", "props", "[", "field", "]", "=", "props", "[", "field", "]", ".", "lower", "(", ")", "except", "(", "AttributeError", ",...
Lowercase fields requesting it during a REST deserialization
[ "Lowercase", "fields", "requesting", "it", "during", "a", "REST", "deserialization" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L99-L106
sassoo/goldman
goldman/utils/responder_helpers.py
_from_rest_on_create
def _from_rest_on_create(model, props): """ Assign the default values when creating a model This is done on fields with `on_create=<value>`. """ fields = model.get_fields_with_prop('on_create') for field in fields: props[field[0]] = field[1]
python
def _from_rest_on_create(model, props): """ Assign the default values when creating a model This is done on fields with `on_create=<value>`. """ fields = model.get_fields_with_prop('on_create') for field in fields: props[field[0]] = field[1]
[ "def", "_from_rest_on_create", "(", "model", ",", "props", ")", ":", "fields", "=", "model", ".", "get_fields_with_prop", "(", "'on_create'", ")", "for", "field", "in", "fields", ":", "props", "[", "field", "[", "0", "]", "]", "=", "field", "[", "1", "...
Assign the default values when creating a model This is done on fields with `on_create=<value>`.
[ "Assign", "the", "default", "values", "when", "creating", "a", "model" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L109-L118
sassoo/goldman
goldman/utils/responder_helpers.py
_from_rest_on_update
def _from_rest_on_update(model, props): """ Assign the default values when updating a model This is done on fields with `on_update=<value>`. """ fields = model.get_fields_with_prop('on_update') for field in fields: props[field[0]] = field[1]
python
def _from_rest_on_update(model, props): """ Assign the default values when updating a model This is done on fields with `on_update=<value>`. """ fields = model.get_fields_with_prop('on_update') for field in fields: props[field[0]] = field[1]
[ "def", "_from_rest_on_update", "(", "model", ",", "props", ")", ":", "fields", "=", "model", ".", "get_fields_with_prop", "(", "'on_update'", ")", "for", "field", "in", "fields", ":", "props", "[", "field", "[", "0", "]", "]", "=", "field", "[", "1", "...
Assign the default values when updating a model This is done on fields with `on_update=<value>`.
[ "Assign", "the", "default", "values", "when", "updating", "a", "model" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L121-L130
sassoo/goldman
goldman/utils/responder_helpers.py
_from_rest_reject_update
def _from_rest_reject_update(model): """ Reject any field updates not allowed on POST This is done on fields with `reject_update=True`. """ dirty = model.dirty_fields fields = model.get_fields_by_prop('reject_update', True) reject = [] for field in fields: if field in dirty: ...
python
def _from_rest_reject_update(model): """ Reject any field updates not allowed on POST This is done on fields with `reject_update=True`. """ dirty = model.dirty_fields fields = model.get_fields_by_prop('reject_update', True) reject = [] for field in fields: if field in dirty: ...
[ "def", "_from_rest_reject_update", "(", "model", ")", ":", "dirty", "=", "model", ".", "dirty_fields", "fields", "=", "model", ".", "get_fields_by_prop", "(", "'reject_update'", ",", "True", ")", "reject", "=", "[", "]", "for", "field", "in", "fields", ":", ...
Reject any field updates not allowed on POST This is done on fields with `reject_update=True`.
[ "Reject", "any", "field", "updates", "not", "allowed", "on", "POST" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L133-L148
sassoo/goldman
goldman/utils/responder_helpers.py
from_rest
def from_rest(model, props): """ Map the REST data onto the model Additionally, perform the following tasks: * set all blank strings to None where needed * purge all fields not allowed as incoming data * purge all unknown fields from the incoming data * lowercase certain fields...
python
def from_rest(model, props): """ Map the REST data onto the model Additionally, perform the following tasks: * set all blank strings to None where needed * purge all fields not allowed as incoming data * purge all unknown fields from the incoming data * lowercase certain fields...
[ "def", "from_rest", "(", "model", ",", "props", ")", ":", "req", "=", "goldman", ".", "sess", ".", "req", "_from_rest_blank", "(", "model", ",", "props", ")", "_from_rest_hide", "(", "model", ",", "props", ")", "_from_rest_ignore", "(", "model", ",", "pr...
Map the REST data onto the model Additionally, perform the following tasks: * set all blank strings to None where needed * purge all fields not allowed as incoming data * purge all unknown fields from the incoming data * lowercase certain fields that need it * merge new dat...
[ "Map", "the", "REST", "data", "onto", "the", "model" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L151-L181
sassoo/goldman
goldman/utils/responder_helpers.py
_to_rest_hide
def _to_rest_hide(model, props): """ Purge fields not allowed during a REST serialization This is done on fields with `to_rest=False`. """ hide = model.get_fields_by_prop('to_rest', False) for field in hide: try: del props[field] except KeyError: continue
python
def _to_rest_hide(model, props): """ Purge fields not allowed during a REST serialization This is done on fields with `to_rest=False`. """ hide = model.get_fields_by_prop('to_rest', False) for field in hide: try: del props[field] except KeyError: continue
[ "def", "_to_rest_hide", "(", "model", ",", "props", ")", ":", "hide", "=", "model", ".", "get_fields_by_prop", "(", "'to_rest'", ",", "False", ")", "for", "field", "in", "hide", ":", "try", ":", "del", "props", "[", "field", "]", "except", "KeyError", ...
Purge fields not allowed during a REST serialization This is done on fields with `to_rest=False`.
[ "Purge", "fields", "not", "allowed", "during", "a", "REST", "serialization" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L184-L196
sassoo/goldman
goldman/utils/responder_helpers.py
_to_rest_includes
def _to_rest_includes(models, includes): """ Fetch the models to be included The includes should follow a few basic rules: * the include MUST not already be an array member of the included array (no dupes) * the include MUST not be the same as the primary data if the prima...
python
def _to_rest_includes(models, includes): """ Fetch the models to be included The includes should follow a few basic rules: * the include MUST not already be an array member of the included array (no dupes) * the include MUST not be the same as the primary data if the prima...
[ "def", "_to_rest_includes", "(", "models", ",", "includes", ")", ":", "included", "=", "[", "]", "includes", "=", "includes", "or", "[", "]", "if", "not", "isinstance", "(", "models", ",", "list", ")", ":", "models", "=", "[", "models", "]", "for", "...
Fetch the models to be included The includes should follow a few basic rules: * the include MUST not already be an array member of the included array (no dupes) * the include MUST not be the same as the primary data if the primary data is a single resource object (no...
[ "Fetch", "the", "models", "to", "be", "included" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L199-L244
sassoo/goldman
goldman/utils/responder_helpers.py
_to_rest_rels
def _to_rest_rels(model, props): """ Move the relationships to appropriate location in the props All to_ones should be in a to_one key while all to_manys should be in a to_many key. """ props['to_many'] = {} props['to_one'] = {} for key in model.to_one: try: props['to_...
python
def _to_rest_rels(model, props): """ Move the relationships to appropriate location in the props All to_ones should be in a to_one key while all to_manys should be in a to_many key. """ props['to_many'] = {} props['to_one'] = {} for key in model.to_one: try: props['to_...
[ "def", "_to_rest_rels", "(", "model", ",", "props", ")", ":", "props", "[", "'to_many'", "]", "=", "{", "}", "props", "[", "'to_one'", "]", "=", "{", "}", "for", "key", "in", "model", ".", "to_one", ":", "try", ":", "props", "[", "'to_one'", "]", ...
Move the relationships to appropriate location in the props All to_ones should be in a to_one key while all to_manys should be in a to_many key.
[ "Move", "the", "relationships", "to", "appropriate", "location", "in", "the", "props" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L247-L267
sassoo/goldman
goldman/utils/responder_helpers.py
_to_rest
def _to_rest(model, includes=None): """ Convert the model into a dict for serialization Notify schematics of the sparse fields requested while also forcing the resource id & resource type fields to always be present no matter the request. Additionally, any includes are implicitly added as well & au...
python
def _to_rest(model, includes=None): """ Convert the model into a dict for serialization Notify schematics of the sparse fields requested while also forcing the resource id & resource type fields to always be present no matter the request. Additionally, any includes are implicitly added as well & au...
[ "def", "_to_rest", "(", "model", ",", "includes", "=", "None", ")", ":", "includes", "=", "includes", "or", "[", "]", "sparse", "=", "goldman", ".", "sess", ".", "req", ".", "fields", ".", "get", "(", "model", ".", "rtype", ",", "[", "]", ")", "i...
Convert the model into a dict for serialization Notify schematics of the sparse fields requested while also forcing the resource id & resource type fields to always be present no matter the request. Additionally, any includes are implicitly added as well & automatically loaded. Then normalize the ...
[ "Convert", "the", "model", "into", "a", "dict", "for", "serialization" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L270-L301
sassoo/goldman
goldman/utils/responder_helpers.py
to_rest_model
def to_rest_model(model, includes=None): """ Convert the single model into a dict for serialization :return: dict """ props = {} props['data'] = _to_rest(model, includes=includes) props['included'] = _to_rest_includes(model, includes=includes) return props
python
def to_rest_model(model, includes=None): """ Convert the single model into a dict for serialization :return: dict """ props = {} props['data'] = _to_rest(model, includes=includes) props['included'] = _to_rest_includes(model, includes=includes) return props
[ "def", "to_rest_model", "(", "model", ",", "includes", "=", "None", ")", ":", "props", "=", "{", "}", "props", "[", "'data'", "]", "=", "_to_rest", "(", "model", ",", "includes", "=", "includes", ")", "props", "[", "'included'", "]", "=", "_to_rest_inc...
Convert the single model into a dict for serialization :return: dict
[ "Convert", "the", "single", "model", "into", "a", "dict", "for", "serialization" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L304-L314
sassoo/goldman
goldman/utils/responder_helpers.py
to_rest_models
def to_rest_models(models, includes=None): """ Convert the models into a dict for serialization models should be an array of single model objects that will each be serialized. :return: dict """ props = {} props['data'] = [] for model in models: props['data'].append(_to_rest(m...
python
def to_rest_models(models, includes=None): """ Convert the models into a dict for serialization models should be an array of single model objects that will each be serialized. :return: dict """ props = {} props['data'] = [] for model in models: props['data'].append(_to_rest(m...
[ "def", "to_rest_models", "(", "models", ",", "includes", "=", "None", ")", ":", "props", "=", "{", "}", "props", "[", "'data'", "]", "=", "[", "]", "for", "model", "in", "models", ":", "props", "[", "'data'", "]", ".", "append", "(", "_to_rest", "(...
Convert the models into a dict for serialization models should be an array of single model objects that will each be serialized. :return: dict
[ "Convert", "the", "models", "into", "a", "dict", "for", "serialization" ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/utils/responder_helpers.py#L317-L334
mbodenhamer/syn
syn/tree/b/node.py
Node.collect_by_type
def collect_by_type(self, typ): '''A more efficient way to collect nodes of a specified type than collect_nodes. ''' nodes = [] if isinstance(self, typ): nodes.append(self) for c in self: nodes.extend(c.collect_by_type(typ)) return nodes
python
def collect_by_type(self, typ): '''A more efficient way to collect nodes of a specified type than collect_nodes. ''' nodes = [] if isinstance(self, typ): nodes.append(self) for c in self: nodes.extend(c.collect_by_type(typ)) return nodes
[ "def", "collect_by_type", "(", "self", ",", "typ", ")", ":", "nodes", "=", "[", "]", "if", "isinstance", "(", "self", ",", "typ", ")", ":", "nodes", ".", "append", "(", "self", ")", "for", "c", "in", "self", ":", "nodes", ".", "extend", "(", "c",...
A more efficient way to collect nodes of a specified type than collect_nodes.
[ "A", "more", "efficient", "way", "to", "collect", "nodes", "of", "a", "specified", "type", "than", "collect_nodes", "." ]
train
https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/tree/b/node.py#L170-L179
xtream1101/web-wrapper
web_wrapper/driver_selenium_chrome.py
DriverSeleniumChrome.set_proxy
def set_proxy(self, proxy, update=True): """ Set proxy for chrome session """ update_web_driver = False if self.current_proxy != proxy: # Did we change proxies? update_web_driver = True self.current_proxy = proxy if proxy is None: ...
python
def set_proxy(self, proxy, update=True): """ Set proxy for chrome session """ update_web_driver = False if self.current_proxy != proxy: # Did we change proxies? update_web_driver = True self.current_proxy = proxy if proxy is None: ...
[ "def", "set_proxy", "(", "self", ",", "proxy", ",", "update", "=", "True", ")", ":", "update_web_driver", "=", "False", "if", "self", ".", "current_proxy", "!=", "proxy", ":", "# Did we change proxies?", "update_web_driver", "=", "True", "self", ".", "current_...
Set proxy for chrome session
[ "Set", "proxy", "for", "chrome", "session" ]
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_chrome.py#L46-L71
xtream1101/web-wrapper
web_wrapper/driver_selenium_chrome.py
DriverSeleniumChrome._create_session
def _create_session(self): """ Creates a fresh session with no/default headers and proxies """ self.driver = webdriver.Chrome(chrome_options=self.opts, **self.driver_args) self.driver.set_window_size(1920, 1080)
python
def _create_session(self): """ Creates a fresh session with no/default headers and proxies """ self.driver = webdriver.Chrome(chrome_options=self.opts, **self.driver_args) self.driver.set_window_size(1920, 1080)
[ "def", "_create_session", "(", "self", ")", ":", "self", ".", "driver", "=", "webdriver", ".", "Chrome", "(", "chrome_options", "=", "self", ".", "opts", ",", "*", "*", "self", ".", "driver_args", ")", "self", ".", "driver", ".", "set_window_size", "(", ...
Creates a fresh session with no/default headers and proxies
[ "Creates", "a", "fresh", "session", "with", "no", "/", "default", "headers", "and", "proxies" ]
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_chrome.py#L73-L78
xtream1101/web-wrapper
web_wrapper/driver_selenium_chrome.py
DriverSeleniumChrome.reset
def reset(self): """ Kills old session and creates a new one with no proxies or headers """ # Kill old connection self.quit() # Clear chrome configs self.opts = webdriver.ChromeOptions() # Create new web driver self._create_session()
python
def reset(self): """ Kills old session and creates a new one with no proxies or headers """ # Kill old connection self.quit() # Clear chrome configs self.opts = webdriver.ChromeOptions() # Create new web driver self._create_session()
[ "def", "reset", "(", "self", ")", ":", "# Kill old connection", "self", ".", "quit", "(", ")", "# Clear chrome configs", "self", ".", "opts", "=", "webdriver", ".", "ChromeOptions", "(", ")", "# Create new web driver", "self", ".", "_create_session", "(", ")" ]
Kills old session and creates a new one with no proxies or headers
[ "Kills", "old", "session", "and", "creates", "a", "new", "one", "with", "no", "proxies", "or", "headers" ]
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_chrome.py#L88-L97
xtream1101/web-wrapper
web_wrapper/driver_selenium_chrome.py
DriverSeleniumChrome._proxy_extension
def _proxy_extension(self, proxy_parts): """ Creates a chrome extension for the proxy Only need to be done this way when using a proxy with auth """ import zipfile manifest_json = """ { "version": "1.0.0", ...
python
def _proxy_extension(self, proxy_parts): """ Creates a chrome extension for the proxy Only need to be done this way when using a proxy with auth """ import zipfile manifest_json = """ { "version": "1.0.0", ...
[ "def", "_proxy_extension", "(", "self", ",", "proxy_parts", ")", ":", "import", "zipfile", "manifest_json", "=", "\"\"\"\n {\n \"version\": \"1.0.0\",\n \"manifest_version\": 2,\n \"name\"...
Creates a chrome extension for the proxy Only need to be done this way when using a proxy with auth
[ "Creates", "a", "chrome", "extension", "for", "the", "proxy", "Only", "need", "to", "be", "done", "this", "way", "when", "using", "a", "proxy", "with", "auth" ]
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_chrome.py#L110-L173
xtream1101/web-wrapper
web_wrapper/driver_selenium_chrome.py
DriverSeleniumChrome._header_extension
def _header_extension(self, remove_headers=[], add_or_modify_headers={}): """Create modheaders extension Source: https://vimmaniac.com/blog/bangal/modify-and-add-custom-headers-in-selenium-chrome-driver/ kwargs: remove_headers (list): headers name to remove add_or_modif...
python
def _header_extension(self, remove_headers=[], add_or_modify_headers={}): """Create modheaders extension Source: https://vimmaniac.com/blog/bangal/modify-and-add-custom-headers-in-selenium-chrome-driver/ kwargs: remove_headers (list): headers name to remove add_or_modif...
[ "def", "_header_extension", "(", "self", ",", "remove_headers", "=", "[", "]", ",", "add_or_modify_headers", "=", "{", "}", ")", ":", "import", "string", "import", "zipfile", "plugin_file", "=", "'custom_headers_plugin.zip'", "if", "remove_headers", "is", "None", ...
Create modheaders extension Source: https://vimmaniac.com/blog/bangal/modify-and-add-custom-headers-in-selenium-chrome-driver/ kwargs: remove_headers (list): headers name to remove add_or_modify_headers (dict): ie. {"Header-Name": "Header Value"} return str -> plugin p...
[ "Create", "modheaders", "extension" ]
train
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_chrome.py#L175-L279
kwarunek/file2py
file2py/conv.py
Converter.load_file
def load_file(self, input_file): """ Loads data array from file (result of this converter) Tries to import, load and replace files' data. It will overwirte previously added items with #add_file or #load_file. :param input_file :type str or unicode """ pyimg = im...
python
def load_file(self, input_file): """ Loads data array from file (result of this converter) Tries to import, load and replace files' data. It will overwirte previously added items with #add_file or #load_file. :param input_file :type str or unicode """ pyimg = im...
[ "def", "load_file", "(", "self", ",", "input_file", ")", ":", "pyimg", "=", "imp", ".", "load_source", "(", "'image2py_taf'", ",", "input_file", ")", "self", ".", "files", "=", "pyimg", ".", "data", "self", ".", "set_template", "(", "templates", ".", "te...
Loads data array from file (result of this converter) Tries to import, load and replace files' data. It will overwirte previously added items with #add_file or #load_file. :param input_file :type str or unicode
[ "Loads", "data", "array", "from", "file", "(", "result", "of", "this", "converter", ")" ]
train
https://github.com/kwarunek/file2py/blob/f94730b6d4f40ea22b5f048126f60fa14c0e2bf0/file2py/conv.py#L23-L34
kwarunek/file2py
file2py/conv.py
Converter.set_template
def set_template(self, template): """ Sets template to be used when generating output :param template TEmplate instance :type instance of BasicTemplate """ if isinstance(template, templates.BasicTemplate): self.template = template else: raise Type...
python
def set_template(self, template): """ Sets template to be used when generating output :param template TEmplate instance :type instance of BasicTemplate """ if isinstance(template, templates.BasicTemplate): self.template = template else: raise Type...
[ "def", "set_template", "(", "self", ",", "template", ")", ":", "if", "isinstance", "(", "template", ",", "templates", ".", "BasicTemplate", ")", ":", "self", ".", "template", "=", "template", "else", ":", "raise", "TypeError", "(", "'converter#set_template:'",...
Sets template to be used when generating output :param template TEmplate instance :type instance of BasicTemplate
[ "Sets", "template", "to", "be", "used", "when", "generating", "output" ]
train
https://github.com/kwarunek/file2py/blob/f94730b6d4f40ea22b5f048126f60fa14c0e2bf0/file2py/conv.py#L36-L46
kwarunek/file2py
file2py/conv.py
Converter.save
def save(self, filename=None): """ Generates output and saves to given file :param filename File name :type str or unicode """ if filename is None: raise IOError('Converter#save: Undefined filename') cnt = self.output() with (open(filename, 'wb+')) as...
python
def save(self, filename=None): """ Generates output and saves to given file :param filename File name :type str or unicode """ if filename is None: raise IOError('Converter#save: Undefined filename') cnt = self.output() with (open(filename, 'wb+')) as...
[ "def", "save", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "raise", "IOError", "(", "'Converter#save: Undefined filename'", ")", "cnt", "=", "self", ".", "output", "(", ")", "with", "(", "open", "(", "filenam...
Generates output and saves to given file :param filename File name :type str or unicode
[ "Generates", "output", "and", "saves", "to", "given", "file" ]
train
https://github.com/kwarunek/file2py/blob/f94730b6d4f40ea22b5f048126f60fa14c0e2bf0/file2py/conv.py#L48-L58
kwarunek/file2py
file2py/conv.py
Converter.add_file
def add_file(self, filename): """ Read and adds given file's content to data array that will be used to generate output :param filename File name to add :type str or unicode """ with (open(filename, 'rb')) as f: data = f.read() # below won't handle th...
python
def add_file(self, filename): """ Read and adds given file's content to data array that will be used to generate output :param filename File name to add :type str or unicode """ with (open(filename, 'rb')) as f: data = f.read() # below won't handle th...
[ "def", "add_file", "(", "self", ",", "filename", ")", ":", "with", "(", "open", "(", "filename", ",", "'rb'", ")", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", "# below won't handle the same name files", "# in different paths", "fname", "=...
Read and adds given file's content to data array that will be used to generate output :param filename File name to add :type str or unicode
[ "Read", "and", "adds", "given", "file", "s", "content", "to", "data", "array", "that", "will", "be", "used", "to", "generate", "output" ]
train
https://github.com/kwarunek/file2py/blob/f94730b6d4f40ea22b5f048126f60fa14c0e2bf0/file2py/conv.py#L60-L72
kwarunek/file2py
file2py/conv.py
Converter.output
def output(self): """ Generates output from data array :returns Pythoned file :rtype str or unicode """ if len(self.files) < 1: raise Exception('Converter#output: No files to convert') return self.template.render(self.files)
python
def output(self): """ Generates output from data array :returns Pythoned file :rtype str or unicode """ if len(self.files) < 1: raise Exception('Converter#output: No files to convert') return self.template.render(self.files)
[ "def", "output", "(", "self", ")", ":", "if", "len", "(", "self", ".", "files", ")", "<", "1", ":", "raise", "Exception", "(", "'Converter#output: No files to convert'", ")", "return", "self", ".", "template", ".", "render", "(", "self", ".", "files", ")...
Generates output from data array :returns Pythoned file :rtype str or unicode
[ "Generates", "output", "from", "data", "array" ]
train
https://github.com/kwarunek/file2py/blob/f94730b6d4f40ea22b5f048126f60fa14c0e2bf0/file2py/conv.py#L82-L90
RonenNess/Fileter
fileter/filters/pattern_filter.py
FilterPattern.match
def match(self, filepath): """ The function to check file. Should return True if match, False otherwise. """ for pattern in self.__pattern: if len(fnmatch.filter([filepath], pattern)) > 0: return True return False
python
def match(self, filepath): """ The function to check file. Should return True if match, False otherwise. """ for pattern in self.__pattern: if len(fnmatch.filter([filepath], pattern)) > 0: return True return False
[ "def", "match", "(", "self", ",", "filepath", ")", ":", "for", "pattern", "in", "self", ".", "__pattern", ":", "if", "len", "(", "fnmatch", ".", "filter", "(", "[", "filepath", "]", ",", "pattern", ")", ")", ">", "0", ":", "return", "True", "return...
The function to check file. Should return True if match, False otherwise.
[ "The", "function", "to", "check", "file", ".", "Should", "return", "True", "if", "match", "False", "otherwise", "." ]
train
https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/filters/pattern_filter.py#L24-L32
PyMLGame/pymlgame
game_example.py
Game.update
def update(self): """ Update the screens contents in every loop. """ # this is not really neccesary because the surface is black after initializing self.corners.fill(BLACK) self.corners.draw_dot((0, 0), self.colors[0]) self.corners.draw_dot((self.screen.width - 1,...
python
def update(self): """ Update the screens contents in every loop. """ # this is not really neccesary because the surface is black after initializing self.corners.fill(BLACK) self.corners.draw_dot((0, 0), self.colors[0]) self.corners.draw_dot((self.screen.width - 1,...
[ "def", "update", "(", "self", ")", ":", "# this is not really neccesary because the surface is black after initializing", "self", ".", "corners", ".", "fill", "(", "BLACK", ")", "self", ".", "corners", ".", "draw_dot", "(", "(", "0", ",", "0", ")", ",", "self", ...
Update the screens contents in every loop.
[ "Update", "the", "screens", "contents", "in", "every", "loop", "." ]
train
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/game_example.py#L63-L96
PyMLGame/pymlgame
game_example.py
Game.render
def render(self): """ Send the current screen content to Mate Light. """ self.screen.reset() self.screen.blit(self.corners) self.screen.blit(self.lines, (1, 1)) self.screen.blit(self.rects, (int(self.screen.width / 2) + 1, 1)) self.screen.blit(self.circle,...
python
def render(self): """ Send the current screen content to Mate Light. """ self.screen.reset() self.screen.blit(self.corners) self.screen.blit(self.lines, (1, 1)) self.screen.blit(self.rects, (int(self.screen.width / 2) + 1, 1)) self.screen.blit(self.circle,...
[ "def", "render", "(", "self", ")", ":", "self", ".", "screen", ".", "reset", "(", ")", "self", ".", "screen", ".", "blit", "(", "self", ".", "corners", ")", "self", ".", "screen", ".", "blit", "(", "self", ".", "lines", ",", "(", "1", ",", "1",...
Send the current screen content to Mate Light.
[ "Send", "the", "current", "screen", "content", "to", "Mate", "Light", "." ]
train
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/game_example.py#L98-L111
PyMLGame/pymlgame
game_example.py
Game.handle_events
def handle_events(self): """ Loop through all events. """ for event in pymlgame.get_events(): if event.type == E_NEWCTLR: #print(datetime.now(), '### new player connected with uid', event.uid) self.players[event.uid] = {'name': 'alien_{}'.forma...
python
def handle_events(self): """ Loop through all events. """ for event in pymlgame.get_events(): if event.type == E_NEWCTLR: #print(datetime.now(), '### new player connected with uid', event.uid) self.players[event.uid] = {'name': 'alien_{}'.forma...
[ "def", "handle_events", "(", "self", ")", ":", "for", "event", "in", "pymlgame", ".", "get_events", "(", ")", ":", "if", "event", ".", "type", "==", "E_NEWCTLR", ":", "#print(datetime.now(), '### new player connected with uid', event.uid)", "self", ".", "players", ...
Loop through all events.
[ "Loop", "through", "all", "events", "." ]
train
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/game_example.py#L113-L132
PyMLGame/pymlgame
game_example.py
Game.gameloop
def gameloop(self): """ A game loop that circles through the methods. """ try: while True: self.handle_events() self.update() self.render() except KeyboardInterrupt: pass
python
def gameloop(self): """ A game loop that circles through the methods. """ try: while True: self.handle_events() self.update() self.render() except KeyboardInterrupt: pass
[ "def", "gameloop", "(", "self", ")", ":", "try", ":", "while", "True", ":", "self", ".", "handle_events", "(", ")", "self", ".", "update", "(", ")", "self", ".", "render", "(", ")", "except", "KeyboardInterrupt", ":", "pass" ]
A game loop that circles through the methods.
[ "A", "game", "loop", "that", "circles", "through", "the", "methods", "." ]
train
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/game_example.py#L134-L144
sassoo/goldman
goldman/middleware/model_qps/__init__.py
Middleware.process_resource
def process_resource(self, req, resp, resource): """ Process the request after routing. The resource is required to determine if a model based resource is being used for validations so skip processing if no `resource.model` attribute is present. """ try: mod...
python
def process_resource(self, req, resp, resource): """ Process the request after routing. The resource is required to determine if a model based resource is being used for validations so skip processing if no `resource.model` attribute is present. """ try: mod...
[ "def", "process_resource", "(", "self", ",", "req", ",", "resp", ",", "resource", ")", ":", "try", ":", "model", "=", "resource", ".", "model", "req", ".", "fields", "=", "fields", ".", "init", "(", "req", ",", "model", ")", "req", ".", "filters", ...
Process the request after routing. The resource is required to determine if a model based resource is being used for validations so skip processing if no `resource.model` attribute is present.
[ "Process", "the", "request", "after", "routing", "." ]
train
https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/middleware/model_qps/__init__.py#L41-L60
joausaga/ideascaly
ideascaly/api.py
API.get_all_comments
def get_all_comments(self): """ :pagination_param: 'page_number', 'page_size' """ return bind_api( api=self, path='/comments', payload_type='comment', payload_list=True, pagination_param=['page_number', 'page_size'] )
python
def get_all_comments(self): """ :pagination_param: 'page_number', 'page_size' """ return bind_api( api=self, path='/comments', payload_type='comment', payload_list=True, pagination_param=['page_number', 'page_size'] )
[ "def", "get_all_comments", "(", "self", ")", ":", "return", "bind_api", "(", "api", "=", "self", ",", "path", "=", "'/comments'", ",", "payload_type", "=", "'comment'", ",", "payload_list", "=", "True", ",", "pagination_param", "=", "[", "'page_number'", ","...
:pagination_param: 'page_number', 'page_size'
[ ":", "pagination_param", ":", "page_number", "page_size" ]
train
https://github.com/joausaga/ideascaly/blob/8aabb7bb1ed058406a8d352a7844e183ab64e008/ideascaly/api.py#L68-L77
joausaga/ideascaly
ideascaly/api.py
API.get_ideas_in_review
def get_ideas_in_review(self, **kwargs): """ :pagination_param: 'page_number', 'page_size', 'order_key' """ return bind_api( api=self, path='/ideas/inreview', payload_type='idea', payload_list=True, pagination_param=['page_number', 'pag...
python
def get_ideas_in_review(self, **kwargs): """ :pagination_param: 'page_number', 'page_size', 'order_key' """ return bind_api( api=self, path='/ideas/inreview', payload_type='idea', payload_list=True, pagination_param=['page_number', 'pag...
[ "def", "get_ideas_in_review", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "bind_api", "(", "api", "=", "self", ",", "path", "=", "'/ideas/inreview'", ",", "payload_type", "=", "'idea'", ",", "payload_list", "=", "True", ",", "pagination_param",...
:pagination_param: 'page_number', 'page_size', 'order_key'
[ ":", "pagination_param", ":", "page_number", "page_size", "order_key" ]
train
https://github.com/joausaga/ideascaly/blob/8aabb7bb1ed058406a8d352a7844e183ab64e008/ideascaly/api.py#L158-L167
joausaga/ideascaly
ideascaly/api.py
API.create_idea
def create_idea(self, *args, **kwargs): """ :allowed_param: 'title', 'text', 'campaignId', 'tags' (optional), 'customFields' (optional) """ kwargs.update({'headers': {'content-type':'application/json'}}) return bind_api( api=self, path='/idea', method=...
python
def create_idea(self, *args, **kwargs): """ :allowed_param: 'title', 'text', 'campaignId', 'tags' (optional), 'customFields' (optional) """ kwargs.update({'headers': {'content-type':'application/json'}}) return bind_api( api=self, path='/idea', method=...
[ "def", "create_idea", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'headers'", ":", "{", "'content-type'", ":", "'application/json'", "}", "}", ")", "return", "bind_api", "(", "api", "=", "self",...
:allowed_param: 'title', 'text', 'campaignId', 'tags' (optional), 'customFields' (optional)
[ ":", "allowed_param", ":", "title", "text", "campaignId", "tags", "(", "optional", ")", "customFields", "(", "optional", ")" ]
train
https://github.com/joausaga/ideascaly/blob/8aabb7bb1ed058406a8d352a7844e183ab64e008/ideascaly/api.py#L256-L266
joausaga/ideascaly
ideascaly/api.py
API.attach_file_to_idea
def attach_file_to_idea(self, filename, *args, **kwargs): """ :allowed_param: ideaId """ kwargs.update({'file': {'attachment': open(filename, 'rb')}}) return bind_api( api=self, path='/ideas/{ideaId}/attach', method='POST', payload_type='id...
python
def attach_file_to_idea(self, filename, *args, **kwargs): """ :allowed_param: ideaId """ kwargs.update({'file': {'attachment': open(filename, 'rb')}}) return bind_api( api=self, path='/ideas/{ideaId}/attach', method='POST', payload_type='id...
[ "def", "attach_file_to_idea", "(", "self", ",", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'file'", ":", "{", "'attachment'", ":", "open", "(", "filename", ",", "'rb'", ")", "}", "}", ")", "...
:allowed_param: ideaId
[ ":", "allowed_param", ":", "ideaId" ]
train
https://github.com/joausaga/ideascaly/blob/8aabb7bb1ed058406a8d352a7844e183ab64e008/ideascaly/api.py#L268-L278
joausaga/ideascaly
ideascaly/api.py
API.vote_up_idea
def vote_up_idea(self, *args, **kwargs): """ :allowed_param: 'ideaId', 'myVote' (optional) """ kwargs.update({'headers': {'content-type':'application/json'}}) return bind_api( api=self, path='/ideas/{ideaId}/vote/up', method='POST', payload...
python
def vote_up_idea(self, *args, **kwargs): """ :allowed_param: 'ideaId', 'myVote' (optional) """ kwargs.update({'headers': {'content-type':'application/json'}}) return bind_api( api=self, path='/ideas/{ideaId}/vote/up', method='POST', payload...
[ "def", "vote_up_idea", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'headers'", ":", "{", "'content-type'", ":", "'application/json'", "}", "}", ")", "return", "bind_api", "(", "api", "=", "self"...
:allowed_param: 'ideaId', 'myVote' (optional)
[ ":", "allowed_param", ":", "ideaId", "myVote", "(", "optional", ")" ]
train
https://github.com/joausaga/ideascaly/blob/8aabb7bb1ed058406a8d352a7844e183ab64e008/ideascaly/api.py#L291-L302
joausaga/ideascaly
ideascaly/api.py
API.delete_comment
def delete_comment(self, *args, **kwargs): """ :allowed_param: 'commentId' """ return bind_api( api=self, path='/comments/{commentId}/delete', method='DELETE', payload_type='comment', allowed_param=['commentId'] )(*args, **kwarg...
python
def delete_comment(self, *args, **kwargs): """ :allowed_param: 'commentId' """ return bind_api( api=self, path='/comments/{commentId}/delete', method='DELETE', payload_type='comment', allowed_param=['commentId'] )(*args, **kwarg...
[ "def", "delete_comment", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "bind_api", "(", "api", "=", "self", ",", "path", "=", "'/comments/{commentId}/delete'", ",", "method", "=", "'DELETE'", ",", "payload_type", "=", "'commen...
:allowed_param: 'commentId'
[ ":", "allowed_param", ":", "commentId" ]
train
https://github.com/joausaga/ideascaly/blob/8aabb7bb1ed058406a8d352a7844e183ab64e008/ideascaly/api.py#L347-L356
joausaga/ideascaly
ideascaly/api.py
API.get_votes_comment
def get_votes_comment(self, *args, **kwargs): """ :allowed_param: 'commentId' """ return bind_api( api=self, path='/comments/{commentId}/votes', payload_type='vote', payload_list=True, allowed_param=['commentId'] )(*args, **kwar...
python
def get_votes_comment(self, *args, **kwargs): """ :allowed_param: 'commentId' """ return bind_api( api=self, path='/comments/{commentId}/votes', payload_type='vote', payload_list=True, allowed_param=['commentId'] )(*args, **kwar...
[ "def", "get_votes_comment", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "bind_api", "(", "api", "=", "self", ",", "path", "=", "'/comments/{commentId}/votes'", ",", "payload_type", "=", "'vote'", ",", "payload_list", "=", "T...
:allowed_param: 'commentId'
[ ":", "allowed_param", ":", "commentId" ]
train
https://github.com/joausaga/ideascaly/blob/8aabb7bb1ed058406a8d352a7844e183ab64e008/ideascaly/api.py#L358-L367
joausaga/ideascaly
ideascaly/api.py
API.get_member_info_by_email
def get_member_info_by_email(self, *args, **kwargs): """ :allowed_param: 'email' """ return bind_api( api=self, path='/members/email/{email}', payload_type='author', allowed_param=['email'] )(*args, **kwargs)
python
def get_member_info_by_email(self, *args, **kwargs): """ :allowed_param: 'email' """ return bind_api( api=self, path='/members/email/{email}', payload_type='author', allowed_param=['email'] )(*args, **kwargs)
[ "def", "get_member_info_by_email", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "bind_api", "(", "api", "=", "self", ",", "path", "=", "'/members/email/{email}'", ",", "payload_type", "=", "'author'", ",", "allowed_param", "=",...
:allowed_param: 'email'
[ ":", "allowed_param", ":", "email" ]
train
https://github.com/joausaga/ideascaly/blob/8aabb7bb1ed058406a8d352a7844e183ab64e008/ideascaly/api.py#L437-L445
joausaga/ideascaly
ideascaly/api.py
API.get_member_ideas
def get_member_ideas(self, *args, **kwargs): """ :allowed_param: 'memberId' :pagination_param: 'page_number', 'page_size' """ return bind_api( api=self, path='/members/{memberId}/ideas', payload_type='idea', payload_list=True, ...
python
def get_member_ideas(self, *args, **kwargs): """ :allowed_param: 'memberId' :pagination_param: 'page_number', 'page_size' """ return bind_api( api=self, path='/members/{memberId}/ideas', payload_type='idea', payload_list=True, ...
[ "def", "get_member_ideas", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "bind_api", "(", "api", "=", "self", ",", "path", "=", "'/members/{memberId}/ideas'", ",", "payload_type", "=", "'idea'", ",", "payload_list", "=", "True...
:allowed_param: 'memberId' :pagination_param: 'page_number', 'page_size'
[ ":", "allowed_param", ":", "memberId", ":", "pagination_param", ":", "page_number", "page_size" ]
train
https://github.com/joausaga/ideascaly/blob/8aabb7bb1ed058406a8d352a7844e183ab64e008/ideascaly/api.py#L447-L458
TC01/calcpkg
calcrepo/output.py
CalcpkgOutput.write
def write(self, string): """The write method for a CalcpkgOutput object- print the string""" if ("" == string or '\n' == string or '\r' == string): return # Filter out any \r newlines. string = string.replace("\r", "") # if '\r\n' in string: # string = util.replaceNewlines(string, '\r\n') if self....
python
def write(self, string): """The write method for a CalcpkgOutput object- print the string""" if ("" == string or '\n' == string or '\r' == string): return # Filter out any \r newlines. string = string.replace("\r", "") # if '\r\n' in string: # string = util.replaceNewlines(string, '\r\n') if self....
[ "def", "write", "(", "self", ",", "string", ")", ":", "if", "(", "\"\"", "==", "string", "or", "'\\n'", "==", "string", "or", "'\\r'", "==", "string", ")", ":", "return", "# Filter out any \\r newlines.", "string", "=", "string", ".", "replace", "(", "\"...
The write method for a CalcpkgOutput object- print the string
[ "The", "write", "method", "for", "a", "CalcpkgOutput", "object", "-", "print", "the", "string" ]
train
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/output.py#L34-L47
TC01/calcpkg
calcrepo/output.py
CalcpkgOutput.logWrite
def logWrite(self, string): """Only write text to the log file, do not print""" logFile = open(self.logFile, 'at') logFile.write(string + '\n') logFile.close()
python
def logWrite(self, string): """Only write text to the log file, do not print""" logFile = open(self.logFile, 'at') logFile.write(string + '\n') logFile.close()
[ "def", "logWrite", "(", "self", ",", "string", ")", ":", "logFile", "=", "open", "(", "self", ".", "logFile", ",", "'at'", ")", "logFile", ".", "write", "(", "string", "+", "'\\n'", ")", "logFile", ".", "close", "(", ")" ]
Only write text to the log file, do not print
[ "Only", "write", "text", "to", "the", "log", "file", "do", "not", "print" ]
train
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/output.py#L49-L53
TC01/calcpkg
calcrepo/output.py
CalcpkgOutput.setupLogFile
def setupLogFile(self): """Set up the logging file for a new session- include date and some whitespace""" self.logWrite("\n###############################################") self.logWrite("calcpkg.py log from " + str(datetime.datetime.now())) self.changeLogging(True)
python
def setupLogFile(self): """Set up the logging file for a new session- include date and some whitespace""" self.logWrite("\n###############################################") self.logWrite("calcpkg.py log from " + str(datetime.datetime.now())) self.changeLogging(True)
[ "def", "setupLogFile", "(", "self", ")", ":", "self", ".", "logWrite", "(", "\"\\n###############################################\"", ")", "self", ".", "logWrite", "(", "\"calcpkg.py log from \"", "+", "str", "(", "datetime", ".", "datetime", ".", "now", "(", ")",...
Set up the logging file for a new session- include date and some whitespace
[ "Set", "up", "the", "logging", "file", "for", "a", "new", "session", "-", "include", "date", "and", "some", "whitespace" ]
train
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/output.py#L55-L59
TC01/calcpkg
calcrepo/output.py
CalcpkgOutput.getLoggingLocation
def getLoggingLocation(self): """Return the path for the calcpkg.log file - at the moment, only use a Linux path since I don't know where Windows thinks logs should go.""" if sys.platform == "win32": modulePath = os.path.realpath(__file__) modulePath = modulePath[:modulePath.rfind("/")] return modulePath ...
python
def getLoggingLocation(self): """Return the path for the calcpkg.log file - at the moment, only use a Linux path since I don't know where Windows thinks logs should go.""" if sys.platform == "win32": modulePath = os.path.realpath(__file__) modulePath = modulePath[:modulePath.rfind("/")] return modulePath ...
[ "def", "getLoggingLocation", "(", "self", ")", ":", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "modulePath", "=", "os", ".", "path", ".", "realpath", "(", "__file__", ")", "modulePath", "=", "modulePath", "[", ":", "modulePath", ".", "rfind", ...
Return the path for the calcpkg.log file - at the moment, only use a Linux path since I don't know where Windows thinks logs should go.
[ "Return", "the", "path", "for", "the", "calcpkg", ".", "log", "file", "-", "at", "the", "moment", "only", "use", "a", "Linux", "path", "since", "I", "don", "t", "know", "where", "Windows", "thinks", "logs", "should", "go", "." ]
train
https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/output.py#L61-L69
narfman0/helga-markovify
helga_markovify/twitter.py
twitter_timeline
def twitter_timeline(screen_name, since_id=None): """ Return relevant twitter timeline """ consumer_key = twitter_credential('consumer_key') consumer_secret = twitter_credential('consumer_secret') access_token = twitter_credential('access_token') access_token_secret = twitter_credential('access_secr...
python
def twitter_timeline(screen_name, since_id=None): """ Return relevant twitter timeline """ consumer_key = twitter_credential('consumer_key') consumer_secret = twitter_credential('consumer_secret') access_token = twitter_credential('access_token') access_token_secret = twitter_credential('access_secr...
[ "def", "twitter_timeline", "(", "screen_name", ",", "since_id", "=", "None", ")", ":", "consumer_key", "=", "twitter_credential", "(", "'consumer_key'", ")", "consumer_secret", "=", "twitter_credential", "(", "'consumer_secret'", ")", "access_token", "=", "twitter_cre...
Return relevant twitter timeline
[ "Return", "relevant", "twitter", "timeline" ]
train
https://github.com/narfman0/helga-markovify/blob/b5a82de070102e6da1fd3f5f81cad12d0a9185d8/helga_markovify/twitter.py#L5-L14
narfman0/helga-markovify
helga_markovify/twitter.py
get_all_tweets
def get_all_tweets(screen_name, api, since_id): """ Get all tweets for the givens screen_name. Returns list of text/created_at pairs. """ # Twitter only allows access to a users most recent 3240 tweets with this method all_tweets = [] # initial request for most recent tweets (200 is the maximum allowed ...
python
def get_all_tweets(screen_name, api, since_id): """ Get all tweets for the givens screen_name. Returns list of text/created_at pairs. """ # Twitter only allows access to a users most recent 3240 tweets with this method all_tweets = [] # initial request for most recent tweets (200 is the maximum allowed ...
[ "def", "get_all_tweets", "(", "screen_name", ",", "api", ",", "since_id", ")", ":", "# Twitter only allows access to a users most recent 3240 tweets with this method", "all_tweets", "=", "[", "]", "# initial request for most recent tweets (200 is the maximum allowed count)", "new_twe...
Get all tweets for the givens screen_name. Returns list of text/created_at pairs.
[ "Get", "all", "tweets", "for", "the", "givens", "screen_name", ".", "Returns", "list", "of", "text", "/", "created_at", "pairs", "." ]
train
https://github.com/narfman0/helga-markovify/blob/b5a82de070102e6da1fd3f5f81cad12d0a9185d8/helga_markovify/twitter.py#L17-L33
narfman0/helga-markovify
helga_markovify/twitter.py
twitter_credential
def twitter_credential(name): """ Grab twitter credential from settings """ credential_name = 'TWITTER_' + name.upper() if hasattr(settings, credential_name): return getattr(settings, credential_name) else: raise AttributeError('Missing twitter credential in settings: ' + credential_name...
python
def twitter_credential(name): """ Grab twitter credential from settings """ credential_name = 'TWITTER_' + name.upper() if hasattr(settings, credential_name): return getattr(settings, credential_name) else: raise AttributeError('Missing twitter credential in settings: ' + credential_name...
[ "def", "twitter_credential", "(", "name", ")", ":", "credential_name", "=", "'TWITTER_'", "+", "name", ".", "upper", "(", ")", "if", "hasattr", "(", "settings", ",", "credential_name", ")", ":", "return", "getattr", "(", "settings", ",", "credential_name", "...
Grab twitter credential from settings
[ "Grab", "twitter", "credential", "from", "settings" ]
train
https://github.com/narfman0/helga-markovify/blob/b5a82de070102e6da1fd3f5f81cad12d0a9185d8/helga_markovify/twitter.py#L36-L42
praekelt/panya
panya/utils/__init__.py
generate_slug
def generate_slug(obj, text, tail_number=0): from panya.models import ModelBase """ Returns a new unique slug. Object must provide a SlugField called slug. URL friendly slugs are generated using django.template.defaultfilters' slugify. Numbers are added to the end of slugs for uniqueness. """ ...
python
def generate_slug(obj, text, tail_number=0): from panya.models import ModelBase """ Returns a new unique slug. Object must provide a SlugField called slug. URL friendly slugs are generated using django.template.defaultfilters' slugify. Numbers are added to the end of slugs for uniqueness. """ ...
[ "def", "generate_slug", "(", "obj", ",", "text", ",", "tail_number", "=", "0", ")", ":", "from", "panya", ".", "models", "import", "ModelBase", "# use django slugify filter to slugify", "slug", "=", "slugify", "(", "text", ")", "existing_slugs", "=", "[", "ite...
Returns a new unique slug. Object must provide a SlugField called slug. URL friendly slugs are generated using django.template.defaultfilters' slugify. Numbers are added to the end of slugs for uniqueness.
[ "Returns", "a", "new", "unique", "slug", ".", "Object", "must", "provide", "a", "SlugField", "called", "slug", ".", "URL", "friendly", "slugs", "are", "generated", "using", "django", ".", "template", ".", "defaultfilters", "slugify", ".", "Numbers", "are", "...
train
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/utils/__init__.py#L9-L27
praekelt/panya
panya/utils/__init__.py
modify_class
def modify_class(original_class, modifier_class, override=True): """ Adds class methods from modifier_class to original_class. If override is True existing methods in original_class are overriden by those provided by modifier_class. """ # get members to add modifier_methods = inspect.getmembers(...
python
def modify_class(original_class, modifier_class, override=True): """ Adds class methods from modifier_class to original_class. If override is True existing methods in original_class are overriden by those provided by modifier_class. """ # get members to add modifier_methods = inspect.getmembers(...
[ "def", "modify_class", "(", "original_class", ",", "modifier_class", ",", "override", "=", "True", ")", ":", "# get members to add", "modifier_methods", "=", "inspect", ".", "getmembers", "(", "modifier_class", ",", "inspect", ".", "ismethod", ")", "# set methods", ...
Adds class methods from modifier_class to original_class. If override is True existing methods in original_class are overriden by those provided by modifier_class.
[ "Adds", "class", "methods", "from", "modifier_class", "to", "original_class", ".", "If", "override", "is", "True", "existing", "methods", "in", "original_class", "are", "overriden", "by", "those", "provided", "by", "modifier_class", "." ]
train
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/utils/__init__.py#L29-L45
praekelt/panya
panya/utils/__init__.py
get_query
def get_query(query_string, search_fields): """ Returns a query, that is a combination of Q objects. That combination aims to search keywords within a model by testing the given search fields. search_fields should be something like: [('title', 'iexact'), ('content', 'icontains'), ] """ query = N...
python
def get_query(query_string, search_fields): """ Returns a query, that is a combination of Q objects. That combination aims to search keywords within a model by testing the given search fields. search_fields should be something like: [('title', 'iexact'), ('content', 'icontains'), ] """ query = N...
[ "def", "get_query", "(", "query_string", ",", "search_fields", ")", ":", "query", "=", "None", "# Query to search for every search term ", "terms", "=", "normalize_query", "(", "query_string", ")", "for", "term", "in", "terms", ":", "or_query", "=", "None", ...
Returns a query, that is a combination of Q objects. That combination aims to search keywords within a model by testing the given search fields. search_fields should be something like: [('title', 'iexact'), ('content', 'icontains'), ]
[ "Returns", "a", "query", "that", "is", "a", "combination", "of", "Q", "objects", ".", "That", "combination", "aims", "to", "search", "keywords", "within", "a", "model", "by", "testing", "the", "given", "search", "fields", ".", "search_fields", "should", "be"...
train
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/utils/__init__.py#L61-L81
Aperture-py/aperture-lib
aperturelib/resize.py
resize_image
def resize_image(image, tuple_wh, preserve_aspect=True): """Resizes an instance of a PIL Image. In order to prevent un-intended side effects, this function always returns a copy of the image, as the resize function from PIL returns a copy but the thumbnail function does not. Args: ima...
python
def resize_image(image, tuple_wh, preserve_aspect=True): """Resizes an instance of a PIL Image. In order to prevent un-intended side effects, this function always returns a copy of the image, as the resize function from PIL returns a copy but the thumbnail function does not. Args: ima...
[ "def", "resize_image", "(", "image", ",", "tuple_wh", ",", "preserve_aspect", "=", "True", ")", ":", "if", "preserve_aspect", ":", "img_cpy", "=", "image", ".", "copy", "(", ")", "img_cpy", ".", "thumbnail", "(", "tuple_wh", ")", "return", "img_cpy", "else...
Resizes an instance of a PIL Image. In order to prevent un-intended side effects, this function always returns a copy of the image, as the resize function from PIL returns a copy but the thumbnail function does not. Args: image: An instance of a PIL Image. tuple_wh: A tuple contai...
[ "Resizes", "an", "instance", "of", "a", "PIL", "Image", "." ]
train
https://github.com/Aperture-py/aperture-lib/blob/5c54af216319f297ddf96181a16f088cf1ba23f3/aperturelib/resize.py#L1-L23
deformio/python-deform
pydeform/utils.py
format_datetime
def format_datetime(date): """ Convert datetime to UTC ISO 8601 """ # todo: test me if date.utcoffset() is None: return date.isoformat() + 'Z' utc_offset_sec = date.utcoffset() utc_date = date - utc_offset_sec utc_date_without_offset = utc_date.replace(tzinfo=None) return ut...
python
def format_datetime(date): """ Convert datetime to UTC ISO 8601 """ # todo: test me if date.utcoffset() is None: return date.isoformat() + 'Z' utc_offset_sec = date.utcoffset() utc_date = date - utc_offset_sec utc_date_without_offset = utc_date.replace(tzinfo=None) return ut...
[ "def", "format_datetime", "(", "date", ")", ":", "# todo: test me", "if", "date", ".", "utcoffset", "(", ")", "is", "None", ":", "return", "date", ".", "isoformat", "(", ")", "+", "'Z'", "utc_offset_sec", "=", "date", ".", "utcoffset", "(", ")", "utc_dat...
Convert datetime to UTC ISO 8601
[ "Convert", "datetime", "to", "UTC", "ISO", "8601" ]
train
https://github.com/deformio/python-deform/blob/c1edc7572881b83a4981b2dd39898527e518bd1f/pydeform/utils.py#L102-L113
colab/colab-superarchives-plugin
src/colab_superarchives/management/commands/import_emails.py
Command.log
def log(self, msg, error=False): """Log message helper.""" output = self.stdout if error: output = self.stderr output.write(msg) output.write('\n')
python
def log(self, msg, error=False): """Log message helper.""" output = self.stdout if error: output = self.stderr output.write(msg) output.write('\n')
[ "def", "log", "(", "self", ",", "msg", ",", "error", "=", "False", ")", ":", "output", "=", "self", ".", "stdout", "if", "error", ":", "output", "=", "self", ".", "stderr", "output", ".", "write", "(", "msg", ")", "output", ".", "write", "(", "'\...
Log message helper.
[ "Log", "message", "helper", "." ]
train
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L66-L73
colab/colab-superarchives-plugin
src/colab_superarchives/management/commands/import_emails.py
Command.parse_emails
def parse_emails(self, email_filename, index=0): """Generator function that parse and extract emails from the file `email_filename` starting from the position `index`. Yield: An instance of `mailbox.mboxMessage` for each email in the file. """ self.log("Parsing email du...
python
def parse_emails(self, email_filename, index=0): """Generator function that parse and extract emails from the file `email_filename` starting from the position `index`. Yield: An instance of `mailbox.mboxMessage` for each email in the file. """ self.log("Parsing email du...
[ "def", "parse_emails", "(", "self", ",", "email_filename", ",", "index", "=", "0", ")", ":", "self", ".", "log", "(", "\"Parsing email dump: %s.\"", "%", "email_filename", ")", "mbox", "=", "mailbox", ".", "mbox", "(", "email_filename", ",", "factory", "=", ...
Generator function that parse and extract emails from the file `email_filename` starting from the position `index`. Yield: An instance of `mailbox.mboxMessage` for each email in the file.
[ "Generator", "function", "that", "parse", "and", "extract", "emails", "from", "the", "file", "email_filename", "starting", "from", "the", "position", "index", "." ]
train
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L75-L99
colab/colab-superarchives-plugin
src/colab_superarchives/management/commands/import_emails.py
Command.get_emails
def get_emails(self, mailinglist_dir, all, exclude_lists): """Generator function that get the emails from each mailing list dump dirctory. If `all` is set to True all the emails in the mbox will be imported if not it will just resume from the last message previously imported. The lists s...
python
def get_emails(self, mailinglist_dir, all, exclude_lists): """Generator function that get the emails from each mailing list dump dirctory. If `all` is set to True all the emails in the mbox will be imported if not it will just resume from the last message previously imported. The lists s...
[ "def", "get_emails", "(", "self", ",", "mailinglist_dir", ",", "all", ",", "exclude_lists", ")", ":", "self", ".", "log", "(", "\"Getting emails dumps from: %s\"", "%", "mailinglist_dir", ")", "# Get the list of directories ending with .mbox", "mailing_lists_mboxes", "=",...
Generator function that get the emails from each mailing list dump dirctory. If `all` is set to True all the emails in the mbox will be imported if not it will just resume from the last message previously imported. The lists set in `exclude_lists` won't be imported. Yield: A tup...
[ "Generator", "function", "that", "get", "the", "emails", "from", "each", "mailing", "list", "dump", "dirctory", ".", "If", "all", "is", "set", "to", "True", "all", "the", "emails", "in", "the", "mbox", "will", "be", "imported", "if", "not", "it", "will",...
train
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L101-L139
colab/colab-superarchives-plugin
src/colab_superarchives/management/commands/import_emails.py
Command.get_thread
def get_thread(self, email, mailinglist): """Group messages by thread looking for similar subjects""" subject_slug = slugify(email.subject_clean) thread = self.THREAD_CACHE.get(subject_slug, {}).get(mailinglist.id) if thread is None: thread = Thread.all_objects.get_or_create...
python
def get_thread(self, email, mailinglist): """Group messages by thread looking for similar subjects""" subject_slug = slugify(email.subject_clean) thread = self.THREAD_CACHE.get(subject_slug, {}).get(mailinglist.id) if thread is None: thread = Thread.all_objects.get_or_create...
[ "def", "get_thread", "(", "self", ",", "email", ",", "mailinglist", ")", ":", "subject_slug", "=", "slugify", "(", "email", ".", "subject_clean", ")", "thread", "=", "self", ".", "THREAD_CACHE", ".", "get", "(", "subject_slug", ",", "{", "}", ")", ".", ...
Group messages by thread looking for similar subjects
[ "Group", "messages", "by", "thread", "looking", "for", "similar", "subjects" ]
train
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L141-L159
colab/colab-superarchives-plugin
src/colab_superarchives/management/commands/import_emails.py
Command.save_email
def save_email(self, list_name, email_msg, index): """Save email message into the database.""" msg_id = email_msg.get('Message-ID') if not msg_id: return # Update last imported message into the DB mailinglist, created = MailingList.objects.get_or_create( ...
python
def save_email(self, list_name, email_msg, index): """Save email message into the database.""" msg_id = email_msg.get('Message-ID') if not msg_id: return # Update last imported message into the DB mailinglist, created = MailingList.objects.get_or_create( ...
[ "def", "save_email", "(", "self", ",", "list_name", ",", "email_msg", ",", "index", ")", ":", "msg_id", "=", "email_msg", ".", "get", "(", "'Message-ID'", ")", "if", "not", "msg_id", ":", "return", "# Update last imported message into the DB", "mailinglist", ","...
Save email message into the database.
[ "Save", "email", "message", "into", "the", "database", "." ]
train
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L161-L190
colab/colab-superarchives-plugin
src/colab_superarchives/management/commands/import_emails.py
Command.import_emails
def import_emails(self, archives_path, all, exclude_lists=None): """Get emails from the filesystem from the `archives_path` and store them into the database. If `all` is set to True all the filesystem storage will be imported otherwise the importation will resume from the last message pr...
python
def import_emails(self, archives_path, all, exclude_lists=None): """Get emails from the filesystem from the `archives_path` and store them into the database. If `all` is set to True all the filesystem storage will be imported otherwise the importation will resume from the last message pr...
[ "def", "import_emails", "(", "self", ",", "archives_path", ",", "all", ",", "exclude_lists", "=", "None", ")", ":", "count", "=", "0", "email_generator", "=", "self", ".", "get_emails", "(", "archives_path", ",", "all", ",", "exclude_lists", ")", "for", "m...
Get emails from the filesystem from the `archives_path` and store them into the database. If `all` is set to True all the filesystem storage will be imported otherwise the importation will resume from the last message previously imported. The lists set in `exclude_lists` won't be importe...
[ "Get", "emails", "from", "the", "filesystem", "from", "the", "archives_path", "and", "store", "them", "into", "the", "database", ".", "If", "all", "is", "set", "to", "True", "all", "the", "filesystem", "storage", "will", "be", "imported", "otherwise", "the",...
train
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L239-L263
colab/colab-superarchives-plugin
src/colab_superarchives/management/commands/import_emails.py
Command.handle
def handle(self, *args, **options): """Main command method.""" # Already running, so quit if os.path.exists(self.lock_file): self.log(("This script is already running. " "(If your are sure it's not please " "delete the lock file in {}')")....
python
def handle(self, *args, **options): """Main command method.""" # Already running, so quit if os.path.exists(self.lock_file): self.log(("This script is already running. " "(If your are sure it's not please " "delete the lock file in {}')")....
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "# Already running, so quit", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "lock_file", ")", ":", "self", ".", "log", "(", "(", "\"This script is already run...
Main command method.
[ "Main", "command", "method", "." ]
train
https://github.com/colab/colab-superarchives-plugin/blob/fe588a1d4fac874ccad2063ee19a857028a22721/src/colab_superarchives/management/commands/import_emails.py#L265-L301
praekelt/panya
panya/models.py
set_managers
def set_managers(sender, **kwargs): """ Make sure all classes have the appropriate managers """ cls = sender if issubclass(cls, ModelBase): cls.add_to_class('permitted', PermittedManager())
python
def set_managers(sender, **kwargs): """ Make sure all classes have the appropriate managers """ cls = sender if issubclass(cls, ModelBase): cls.add_to_class('permitted', PermittedManager())
[ "def", "set_managers", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "cls", "=", "sender", "if", "issubclass", "(", "cls", ",", "ModelBase", ")", ":", "cls", ".", "add_to_class", "(", "'permitted'", ",", "PermittedManager", "(", ")", ")" ]
Make sure all classes have the appropriate managers
[ "Make", "sure", "all", "classes", "have", "the", "appropriate", "managers" ]
train
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/models.py#L290-L297
praekelt/panya
panya/models.py
ModelBase.as_leaf_class
def as_leaf_class(self): """ Returns the leaf class no matter where the calling instance is in the inheritance hierarchy. Inspired by http://www.djangosnippets.org/snippets/1031/ """ try: return self.__getattribute__(self.class_name.lower()) except AttributeEr...
python
def as_leaf_class(self): """ Returns the leaf class no matter where the calling instance is in the inheritance hierarchy. Inspired by http://www.djangosnippets.org/snippets/1031/ """ try: return self.__getattribute__(self.class_name.lower()) except AttributeEr...
[ "def", "as_leaf_class", "(", "self", ")", ":", "try", ":", "return", "self", ".", "__getattribute__", "(", "self", ".", "class_name", ".", "lower", "(", ")", ")", "except", "AttributeError", ":", "content_type", "=", "self", ".", "content_type", "model", "...
Returns the leaf class no matter where the calling instance is in the inheritance hierarchy. Inspired by http://www.djangosnippets.org/snippets/1031/
[ "Returns", "the", "leaf", "class", "no", "matter", "where", "the", "calling", "instance", "is", "in", "the", "inheritance", "hierarchy", ".", "Inspired", "by", "http", ":", "//", "www", ".", "djangosnippets", ".", "org", "/", "snippets", "/", "1031", "/" ]
train
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/models.py#L144-L156
praekelt/panya
panya/models.py
ModelBase.can_vote
def can_vote(self, request): """ Determnines whether or not the current user can vote. Returns a bool as well as a string indicating the current vote status, with vote status being one of: 'closed', 'disabled', 'auth_required', 'can_vote', 'voted' """ modelbase_obj = sel...
python
def can_vote(self, request): """ Determnines whether or not the current user can vote. Returns a bool as well as a string indicating the current vote status, with vote status being one of: 'closed', 'disabled', 'auth_required', 'can_vote', 'voted' """ modelbase_obj = sel...
[ "def", "can_vote", "(", "self", ",", "request", ")", ":", "modelbase_obj", "=", "self", ".", "modelbase_obj", "# can't vote if liking is closed", "if", "modelbase_obj", ".", "likes_closed", ":", "return", "False", ",", "'closed'", "# can't vote if liking is disabled", ...
Determnines whether or not the current user can vote. Returns a bool as well as a string indicating the current vote status, with vote status being one of: 'closed', 'disabled', 'auth_required', 'can_vote', 'voted'
[ "Determnines", "whether", "or", "not", "the", "current", "user", "can", "vote", ".", "Returns", "a", "bool", "as", "well", "as", "a", "string", "indicating", "the", "current", "vote", "status", "with", "vote", "status", "being", "one", "of", ":", "closed",...
train
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/models.py#L207-L231
praekelt/panya
panya/models.py
ModelBase.vote_total
def vote_total(self): """ Calculates vote total as total_upvotes - total_downvotes. We are adding a method here instead of relying on django-secretballot's addition since that doesn't work for subclasses. """ modelbase_obj = self.modelbase_obj return modelbase_obj.votes.filter(vo...
python
def vote_total(self): """ Calculates vote total as total_upvotes - total_downvotes. We are adding a method here instead of relying on django-secretballot's addition since that doesn't work for subclasses. """ modelbase_obj = self.modelbase_obj return modelbase_obj.votes.filter(vo...
[ "def", "vote_total", "(", "self", ")", ":", "modelbase_obj", "=", "self", ".", "modelbase_obj", "return", "modelbase_obj", ".", "votes", ".", "filter", "(", "vote", "=", "+", "1", ")", ".", "count", "(", ")", "-", "modelbase_obj", ".", "votes", ".", "f...
Calculates vote total as total_upvotes - total_downvotes. We are adding a method here instead of relying on django-secretballot's addition since that doesn't work for subclasses.
[ "Calculates", "vote", "total", "as", "total_upvotes", "-", "total_downvotes", ".", "We", "are", "adding", "a", "method", "here", "instead", "of", "relying", "on", "django", "-", "secretballot", "s", "addition", "since", "that", "doesn", "t", "work", "for", "...
train
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/models.py#L252-L257
praekelt/panya
panya/models.py
ModelBase.comment_count
def comment_count(self): """ Counts total number of comments on ModelBase object. Comments should always be recorded on ModelBase objects. """ # Get the comment model. comment_model = comments.get_model() modelbase_content_type = ContentType.objects.get(app_label...
python
def comment_count(self): """ Counts total number of comments on ModelBase object. Comments should always be recorded on ModelBase objects. """ # Get the comment model. comment_model = comments.get_model() modelbase_content_type = ContentType.objects.get(app_label...
[ "def", "comment_count", "(", "self", ")", ":", "# Get the comment model.", "comment_model", "=", "comments", ".", "get_model", "(", ")", "modelbase_content_type", "=", "ContentType", ".", "objects", ".", "get", "(", "app_label", "=", "\"panya\"", ",", "model", "...
Counts total number of comments on ModelBase object. Comments should always be recorded on ModelBase objects.
[ "Counts", "total", "number", "of", "comments", "on", "ModelBase", "object", ".", "Comments", "should", "always", "be", "recorded", "on", "ModelBase", "objects", "." ]
train
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/models.py#L260-L288
LesPatamechanix/patalib
src/patalib/syzygy.py
Syzygy.generate_syzygy
def generate_syzygy(self, input_word): """ Generate a syzygy. Here we generate a list of hypernyms associated with an input word. Using the hypernym we then generate another synonym. For example: The input word 'weed' will result in a syzgy of 'band' as in rock band. ...
python
def generate_syzygy(self, input_word): """ Generate a syzygy. Here we generate a list of hypernyms associated with an input word. Using the hypernym we then generate another synonym. For example: The input word 'weed' will result in a syzgy of 'band' as in rock band. ...
[ "def", "generate_syzygy", "(", "self", ",", "input_word", ")", ":", "results", "=", "[", "]", "synset", "=", "wordnet", ".", "synsets", "(", "input_word", ")", "for", "i", "in", "synset", ":", "if", "i", ".", "hypernyms", "(", ")", ":", "hyp", "=", ...
Generate a syzygy. Here we generate a list of hypernyms associated with an input word. Using the hypernym we then generate another synonym. For example: The input word 'weed' will result in a syzgy of 'band' as in rock band.
[ "Generate", "a", "syzygy", ".", "Here", "we", "generate", "a", "list", "of", "hypernyms", "associated", "with", "an", "input", "word", ".", "Using", "the", "hypernym", "we", "then", "generate", "another", "synonym", ".", "For", "example", ":", "The", "inpu...
train
https://github.com/LesPatamechanix/patalib/blob/d88cca409b1750fdeb88cece048b308f2a710955/src/patalib/syzygy.py#L10-L30
delfick/aws_syncr
aws_syncr/actions.py
list_tasks
def list_tasks(collector): """List the available_tasks""" print("Usage: aws_syncr <environment> <task>") print("") print("Available environments to choose from are") print("-----------------------------------------") print("") for environment in os.listdir(collector.configuration_folder): ...
python
def list_tasks(collector): """List the available_tasks""" print("Usage: aws_syncr <environment> <task>") print("") print("Available environments to choose from are") print("-----------------------------------------") print("") for environment in os.listdir(collector.configuration_folder): ...
[ "def", "list_tasks", "(", "collector", ")", ":", "print", "(", "\"Usage: aws_syncr <environment> <task>\"", ")", "print", "(", "\"\"", ")", "print", "(", "\"Available environments to choose from are\"", ")", "print", "(", "\"-----------------------------------------\"", ")"...
List the available_tasks
[ "List", "the", "available_tasks" ]
train
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/actions.py#L115-L138
delfick/aws_syncr
aws_syncr/actions.py
sync
def sync(collector): """Sync an environment""" amazon = collector.configuration['amazon'] aws_syncr = collector.configuration['aws_syncr'] # Convert everything before we try and sync anything log.info("Converting configuration") converted = {} for thing in collector.configuration["__registe...
python
def sync(collector): """Sync an environment""" amazon = collector.configuration['amazon'] aws_syncr = collector.configuration['aws_syncr'] # Convert everything before we try and sync anything log.info("Converting configuration") converted = {} for thing in collector.configuration["__registe...
[ "def", "sync", "(", "collector", ")", ":", "amazon", "=", "collector", ".", "configuration", "[", "'amazon'", "]", "aws_syncr", "=", "collector", ".", "configuration", "[", "'aws_syncr'", "]", "# Convert everything before we try and sync anything", "log", ".", "info...
Sync an environment
[ "Sync", "an", "environment" ]
train
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/actions.py#L141-L163
delfick/aws_syncr
aws_syncr/actions.py
deploy_lambda
def deploy_lambda(collector): """Deploy a lambda function""" amazon = collector.configuration['amazon'] aws_syncr = collector.configuration['aws_syncr'] find_lambda_function(aws_syncr, collector.configuration).deploy(aws_syncr, amazon)
python
def deploy_lambda(collector): """Deploy a lambda function""" amazon = collector.configuration['amazon'] aws_syncr = collector.configuration['aws_syncr'] find_lambda_function(aws_syncr, collector.configuration).deploy(aws_syncr, amazon)
[ "def", "deploy_lambda", "(", "collector", ")", ":", "amazon", "=", "collector", ".", "configuration", "[", "'amazon'", "]", "aws_syncr", "=", "collector", ".", "configuration", "[", "'aws_syncr'", "]", "find_lambda_function", "(", "aws_syncr", ",", "collector", ...
Deploy a lambda function
[ "Deploy", "a", "lambda", "function" ]
train
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/actions.py#L166-L170
delfick/aws_syncr
aws_syncr/actions.py
deploy_gateway
def deploy_gateway(collector): """Deploy the apigateway to a particular stage""" configuration = collector.configuration aws_syncr = configuration['aws_syncr'] aws_syncr, amazon, stage, gateway = find_gateway(aws_syncr, configuration) gateway.deploy(aws_syncr, amazon, stage) if not configuratio...
python
def deploy_gateway(collector): """Deploy the apigateway to a particular stage""" configuration = collector.configuration aws_syncr = configuration['aws_syncr'] aws_syncr, amazon, stage, gateway = find_gateway(aws_syncr, configuration) gateway.deploy(aws_syncr, amazon, stage) if not configuratio...
[ "def", "deploy_gateway", "(", "collector", ")", ":", "configuration", "=", "collector", ".", "configuration", "aws_syncr", "=", "configuration", "[", "'aws_syncr'", "]", "aws_syncr", ",", "amazon", ",", "stage", ",", "gateway", "=", "find_gateway", "(", "aws_syn...
Deploy the apigateway to a particular stage
[ "Deploy", "the", "apigateway", "to", "a", "particular", "stage" ]
train
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/actions.py#L188-L196
delfick/aws_syncr
aws_syncr/actions.py
sync_and_deploy_gateway
def sync_and_deploy_gateway(collector): """Do a sync followed by deploying the gateway""" configuration = collector.configuration aws_syncr = configuration['aws_syncr'] find_gateway(aws_syncr, configuration) artifact = aws_syncr.artifact aws_syncr.artifact = "" sync(collector) aws_sync...
python
def sync_and_deploy_gateway(collector): """Do a sync followed by deploying the gateway""" configuration = collector.configuration aws_syncr = configuration['aws_syncr'] find_gateway(aws_syncr, configuration) artifact = aws_syncr.artifact aws_syncr.artifact = "" sync(collector) aws_sync...
[ "def", "sync_and_deploy_gateway", "(", "collector", ")", ":", "configuration", "=", "collector", ".", "configuration", "aws_syncr", "=", "configuration", "[", "'aws_syncr'", "]", "find_gateway", "(", "aws_syncr", ",", "configuration", ")", "artifact", "=", "aws_sync...
Do a sync followed by deploying the gateway
[ "Do", "a", "sync", "followed", "by", "deploying", "the", "gateway" ]
train
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/actions.py#L199-L210
delfick/aws_syncr
aws_syncr/actions.py
encrypt_certificate
def encrypt_certificate(collector): """Write encrypted values for your certificate to the configuration""" configuration = collector.configuration amazon = configuration['amazon'] aws_syncr = configuration['aws_syncr'] certificate = aws_syncr.artifact available = [] for gateway_name, gatew...
python
def encrypt_certificate(collector): """Write encrypted values for your certificate to the configuration""" configuration = collector.configuration amazon = configuration['amazon'] aws_syncr = configuration['aws_syncr'] certificate = aws_syncr.artifact available = [] for gateway_name, gatew...
[ "def", "encrypt_certificate", "(", "collector", ")", ":", "configuration", "=", "collector", ".", "configuration", "amazon", "=", "configuration", "[", "'amazon'", "]", "aws_syncr", "=", "configuration", "[", "'aws_syncr'", "]", "certificate", "=", "aws_syncr", "....
Write encrypted values for your certificate to the configuration
[ "Write", "encrypted", "values", "for", "your", "certificate", "to", "the", "configuration" ]
train
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/actions.py#L244-L312
delfick/aws_syncr
aws_syncr/actions.py
execute_as
def execute_as(collector): """Execute a command (after the --) as an assumed role (specified by --artifact)""" # Gonna assume role anyway... collector.configuration['amazon']._validated = True # Find the arn we want to assume account_id = collector.configuration['accounts'][collector.configuration[...
python
def execute_as(collector): """Execute a command (after the --) as an assumed role (specified by --artifact)""" # Gonna assume role anyway... collector.configuration['amazon']._validated = True # Find the arn we want to assume account_id = collector.configuration['accounts'][collector.configuration[...
[ "def", "execute_as", "(", "collector", ")", ":", "# Gonna assume role anyway...", "collector", ".", "configuration", "[", "'amazon'", "]", ".", "_validated", "=", "True", "# Find the arn we want to assume", "account_id", "=", "collector", ".", "configuration", "[", "'...
Execute a command (after the --) as an assumed role (specified by --artifact)
[ "Execute", "a", "command", "(", "after", "the", "--", ")", "as", "an", "assumed", "role", "(", "specified", "by", "--", "artifact", ")" ]
train
https://github.com/delfick/aws_syncr/blob/8cd214b27c1eee98dfba4632cbb8bc0ae36356bd/aws_syncr/actions.py#L315-L336
edwards-lab/MVtest
meanvar/mvresult.py
MVResult.print_header
def print_header(self, f=sys.stdout, verbose=False): """Prints header to f (will write header based on verbose) :param f: stream to print output :param verbose: print all data or only the most important parts? """ self.var_count = 2 + len(self.covar_labels) if verbose: ...
python
def print_header(self, f=sys.stdout, verbose=False): """Prints header to f (will write header based on verbose) :param f: stream to print output :param verbose: print all data or only the most important parts? """ self.var_count = 2 + len(self.covar_labels) if verbose: ...
[ "def", "print_header", "(", "self", ",", "f", "=", "sys", ".", "stdout", ",", "verbose", "=", "False", ")", ":", "self", ".", "var_count", "=", "2", "+", "len", "(", "self", ".", "covar_labels", ")", "if", "verbose", ":", "header", "=", "[", "\"Chr...
Prints header to f (will write header based on verbose) :param f: stream to print output :param verbose: print all data or only the most important parts?
[ "Prints", "header", "to", "f", "(", "will", "write", "header", "based", "on", "verbose", ")" ]
train
https://github.com/edwards-lab/MVtest/blob/fe8cf627464ef59d68b7eda628a19840d033882f/meanvar/mvresult.py#L68-L110
edwards-lab/MVtest
meanvar/mvresult.py
MVResult.print_result
def print_result(self, f=sys.stdout, verbose=False): """Print result to f :param f: stream to print output :param verbose: print all data or only the most important parts? """ var_count = len(self.betas)/2 if verbose: results = [str(x) for x in [ ...
python
def print_result(self, f=sys.stdout, verbose=False): """Print result to f :param f: stream to print output :param verbose: print all data or only the most important parts? """ var_count = len(self.betas)/2 if verbose: results = [str(x) for x in [ ...
[ "def", "print_result", "(", "self", ",", "f", "=", "sys", ".", "stdout", ",", "verbose", "=", "False", ")", ":", "var_count", "=", "len", "(", "self", ".", "betas", ")", "/", "2", "if", "verbose", ":", "results", "=", "[", "str", "(", "x", ")", ...
Print result to f :param f: stream to print output :param verbose: print all data or only the most important parts?
[ "Print", "result", "to", "f" ]
train
https://github.com/edwards-lab/MVtest/blob/fe8cf627464ef59d68b7eda628a19840d033882f/meanvar/mvresult.py#L119-L166
LesPatamechanix/patalib
src/patalib/synonym.py
Synonym.generate_synonym
def generate_synonym(self, input_word): """ Generate Synonym using a WordNet synset. """ results = [] results.append(input_word) synset = wordnet.synsets(input_word) for i in synset: index = 0 syn = i.name.split('.') i...
python
def generate_synonym(self, input_word): """ Generate Synonym using a WordNet synset. """ results = [] results.append(input_word) synset = wordnet.synsets(input_word) for i in synset: index = 0 syn = i.name.split('.') i...
[ "def", "generate_synonym", "(", "self", ",", "input_word", ")", ":", "results", "=", "[", "]", "results", ".", "append", "(", "input_word", ")", "synset", "=", "wordnet", ".", "synsets", "(", "input_word", ")", "for", "i", "in", "synset", ":", "index", ...
Generate Synonym using a WordNet synset.
[ "Generate", "Synonym", "using", "a", "WordNet", "synset", "." ]
train
https://github.com/LesPatamechanix/patalib/blob/d88cca409b1750fdeb88cece048b308f2a710955/src/patalib/synonym.py#L10-L26
matthewdeanmartin/jiggle_version
extra/vendorized/pep440.py
is_canonical
def is_canonical(version, loosedev=False): # type: (str, bool) -> bool """ Return whether or not the version string is canonical according to Pep 440 """ if loosedev: return loose440re.match(version) is not None return pep440re.match(version) is not None
python
def is_canonical(version, loosedev=False): # type: (str, bool) -> bool """ Return whether or not the version string is canonical according to Pep 440 """ if loosedev: return loose440re.match(version) is not None return pep440re.match(version) is not None
[ "def", "is_canonical", "(", "version", ",", "loosedev", "=", "False", ")", ":", "# type: (str, bool) -> bool", "if", "loosedev", ":", "return", "loose440re", ".", "match", "(", "version", ")", "is", "not", "None", "return", "pep440re", ".", "match", "(", "ve...
Return whether or not the version string is canonical according to Pep 440
[ "Return", "whether", "or", "not", "the", "version", "string", "is", "canonical", "according", "to", "Pep", "440" ]
train
https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/extra/vendorized/pep440.py#L50-L56
mrstephenneal/differentiate
differentiate/diff.py
diff
def diff(x, y, x_only=False, y_only=False): """ Retrieve a unique of list of elements that do not exist in both x and y. Capable of parsing one-dimensional (flat) and two-dimensional (lists of lists) lists. :param x: list #1 :param y: list #2 :param x_only: Return only unique values from x ...
python
def diff(x, y, x_only=False, y_only=False): """ Retrieve a unique of list of elements that do not exist in both x and y. Capable of parsing one-dimensional (flat) and two-dimensional (lists of lists) lists. :param x: list #1 :param y: list #2 :param x_only: Return only unique values from x ...
[ "def", "diff", "(", "x", ",", "y", ",", "x_only", "=", "False", ",", "y_only", "=", "False", ")", ":", "# Validate both lists, confirm neither are empty", "if", "len", "(", "x", ")", "==", "0", "and", "len", "(", "y", ")", ">", "0", ":", "return", "y...
Retrieve a unique of list of elements that do not exist in both x and y. Capable of parsing one-dimensional (flat) and two-dimensional (lists of lists) lists. :param x: list #1 :param y: list #2 :param x_only: Return only unique values from x :param y_only: Return only unique values from y :ret...
[ "Retrieve", "a", "unique", "of", "list", "of", "elements", "that", "do", "not", "exist", "in", "both", "x", "and", "y", ".", "Capable", "of", "parsing", "one", "-", "dimensional", "(", "flat", ")", "and", "two", "-", "dimensional", "(", "lists", "of", ...
train
https://github.com/mrstephenneal/differentiate/blob/482b6befff8c1b3d10a0f3db4700a3a6501a668e/differentiate/diff.py#L1-L62
edeposit/edeposit.amqp.ftp
src/edeposit/amqp/ftp/decoders/parser_json.py
decode
def decode(data): """ Handles decoding of the JSON `data`. Args: data (str): Data which will be decoded. Returns: dict: Dictionary with decoded data. """ decoded = None try: decoded = json.loads(data) except Exception, e: raise MetaParsingException("Can'...
python
def decode(data): """ Handles decoding of the JSON `data`. Args: data (str): Data which will be decoded. Returns: dict: Dictionary with decoded data. """ decoded = None try: decoded = json.loads(data) except Exception, e: raise MetaParsingException("Can'...
[ "def", "decode", "(", "data", ")", ":", "decoded", "=", "None", "try", ":", "decoded", "=", "json", ".", "loads", "(", "data", ")", "except", "Exception", ",", "e", ":", "raise", "MetaParsingException", "(", "\"Can't parse your JSON data: %s\"", "%", "e", ...
Handles decoding of the JSON `data`. Args: data (str): Data which will be decoded. Returns: dict: Dictionary with decoded data.
[ "Handles", "decoding", "of", "the", "JSON", "data", "." ]
train
https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/decoders/parser_json.py#L49-L67
PyMLGame/pymlgame
pymlgame/__init__.py
init
def init(host='0.0.0.0', port=1338): """ Initialize PyMLGame. This creates a controller thread that listens for game controllers and events. :param host: Bind to this address :param port: Bind to this port :type host: str :type port: int """ CONTROLLER.host = host CONTROLLER.port = ...
python
def init(host='0.0.0.0', port=1338): """ Initialize PyMLGame. This creates a controller thread that listens for game controllers and events. :param host: Bind to this address :param port: Bind to this port :type host: str :type port: int """ CONTROLLER.host = host CONTROLLER.port = ...
[ "def", "init", "(", "host", "=", "'0.0.0.0'", ",", "port", "=", "1338", ")", ":", "CONTROLLER", ".", "host", "=", "host", "CONTROLLER", ".", "port", "=", "port", "CONTROLLER", ".", "setDaemon", "(", "True", ")", "# because it's a deamon it will exit together w...
Initialize PyMLGame. This creates a controller thread that listens for game controllers and events. :param host: Bind to this address :param port: Bind to this port :type host: str :type port: int
[ "Initialize", "PyMLGame", ".", "This", "creates", "a", "controller", "thread", "that", "listens", "for", "game", "controllers", "and", "events", "." ]
train
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/__init__.py#L25-L37
PyMLGame/pymlgame
pymlgame/__init__.py
get_events
def get_events(maximum=10): """ Get all events since the last time you asked for them. You can define a maximum which is 10 by default. :param maximum: Maximum number of events :type maximum: int :return: List of events :rtype: list """ events = [] for ev in range(0, maximum): ...
python
def get_events(maximum=10): """ Get all events since the last time you asked for them. You can define a maximum which is 10 by default. :param maximum: Maximum number of events :type maximum: int :return: List of events :rtype: list """ events = [] for ev in range(0, maximum): ...
[ "def", "get_events", "(", "maximum", "=", "10", ")", ":", "events", "=", "[", "]", "for", "ev", "in", "range", "(", "0", ",", "maximum", ")", ":", "try", ":", "if", "CONTROLLER", ".", "queue", ".", "empty", "(", ")", ":", "break", "else", ":", ...
Get all events since the last time you asked for them. You can define a maximum which is 10 by default. :param maximum: Maximum number of events :type maximum: int :return: List of events :rtype: list
[ "Get", "all", "events", "since", "the", "last", "time", "you", "asked", "for", "them", ".", "You", "can", "define", "a", "maximum", "which", "is", "10", "by", "default", "." ]
train
https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/__init__.py#L40-L60
sampottinger/pycotracer
pycotracer/mongo_aggregator.py
clean_entry
def clean_entry(entry): """Consolidate some entry attributes and rename a few others. Consolidate address attributes into a single field and replace some field names with others as described in FIELD_TRANSFORM_INDEX. @param entry: The entry attributes to update. @type entry: dict @return: Entr...
python
def clean_entry(entry): """Consolidate some entry attributes and rename a few others. Consolidate address attributes into a single field and replace some field names with others as described in FIELD_TRANSFORM_INDEX. @param entry: The entry attributes to update. @type entry: dict @return: Entr...
[ "def", "clean_entry", "(", "entry", ")", ":", "newEntry", "=", "{", "}", "if", "'Address1'", "in", "entry", ":", "address", "=", "str", "(", "entry", "[", "'Address1'", "]", ")", "if", "entry", "[", "'Address2'", "]", "!=", "''", ":", "address", "=",...
Consolidate some entry attributes and rename a few others. Consolidate address attributes into a single field and replace some field names with others as described in FIELD_TRANSFORM_INDEX. @param entry: The entry attributes to update. @type entry: dict @return: Entry copy after running clean oper...
[ "Consolidate", "some", "entry", "attributes", "and", "rename", "a", "few", "others", "." ]
train
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L78-L111
sampottinger/pycotracer
pycotracer/mongo_aggregator.py
update_contribution_entry
def update_contribution_entry(database, entry): """Update a record of a contribution report in the provided database. @param database: The MongoDB database to operate on. The contributions collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to...
python
def update_contribution_entry(database, entry): """Update a record of a contribution report in the provided database. @param database: The MongoDB database to operate on. The contributions collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to...
[ "def", "update_contribution_entry", "(", "database", ",", "entry", ")", ":", "entry", "=", "clean_entry", "(", "entry", ")", "database", ".", "contributions", ".", "update", "(", "{", "'recordID'", ":", "entry", "[", "'recordID'", "]", "}", ",", "{", "'$se...
Update a record of a contribution report in the provided database. @param database: The MongoDB database to operate on. The contributions collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to insert into the database, updating the entry with ...
[ "Update", "a", "record", "of", "a", "contribution", "report", "in", "the", "provided", "database", "." ]
train
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L114-L129
sampottinger/pycotracer
pycotracer/mongo_aggregator.py
update_expenditure_entry
def update_expenditure_entry(database, entry): """Update a record of a expenditure report in the provided database. @param db: The MongoDB database to operate on. The expenditures collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to insert i...
python
def update_expenditure_entry(database, entry): """Update a record of a expenditure report in the provided database. @param db: The MongoDB database to operate on. The expenditures collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to insert i...
[ "def", "update_expenditure_entry", "(", "database", ",", "entry", ")", ":", "entry", "=", "clean_entry", "(", "entry", ")", "database", ".", "expenditures", ".", "update", "(", "{", "'recordID'", ":", "entry", "[", "'recordID'", "]", "}", ",", "{", "'$set'...
Update a record of a expenditure report in the provided database. @param db: The MongoDB database to operate on. The expenditures collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to insert into the database, updating the entry with the ...
[ "Update", "a", "record", "of", "a", "expenditure", "report", "in", "the", "provided", "database", "." ]
train
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L132-L147
sampottinger/pycotracer
pycotracer/mongo_aggregator.py
update_loan_entry
def update_loan_entry(database, entry): """Update a record of a loan report in the provided database. @param db: The MongoDB database to operate on. The loans collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to insert into the database, upd...
python
def update_loan_entry(database, entry): """Update a record of a loan report in the provided database. @param db: The MongoDB database to operate on. The loans collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to insert into the database, upd...
[ "def", "update_loan_entry", "(", "database", ",", "entry", ")", ":", "entry", "=", "clean_entry", "(", "entry", ")", "database", ".", "loans", ".", "update", "(", "{", "'recordID'", ":", "entry", "[", "'recordID'", "]", "}", ",", "{", "'$set'", ":", "e...
Update a record of a loan report in the provided database. @param db: The MongoDB database to operate on. The loans collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to insert into the database, updating the entry with the same recordID ...
[ "Update", "a", "record", "of", "a", "loan", "report", "in", "the", "provided", "database", "." ]
train
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L150-L165
sampottinger/pycotracer
pycotracer/mongo_aggregator.py
insert_contribution_entries
def insert_contribution_entries(database, entries): """Insert a set of records of a contribution report in the provided database. Insert a set of new records into the provided database without checking for conflicting entries. @param database: The MongoDB database to operate on. The contributions ...
python
def insert_contribution_entries(database, entries): """Insert a set of records of a contribution report in the provided database. Insert a set of new records into the provided database without checking for conflicting entries. @param database: The MongoDB database to operate on. The contributions ...
[ "def", "insert_contribution_entries", "(", "database", ",", "entries", ")", ":", "entries", "=", "map", "(", "clean_entry", ",", "entries", ")", "database", ".", "contributions", ".", "insert", "(", "entries", ",", "continue_on_error", "=", "True", ")" ]
Insert a set of records of a contribution report in the provided database. Insert a set of new records into the provided database without checking for conflicting entries. @param database: The MongoDB database to operate on. The contributions collection will be used from this database. @type d...
[ "Insert", "a", "set", "of", "records", "of", "a", "contribution", "report", "in", "the", "provided", "database", "." ]
train
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L168-L181
sampottinger/pycotracer
pycotracer/mongo_aggregator.py
insert_expenditure_entries
def insert_expenditure_entries(database, entries): """Insert a set of records of a expenditure report in the provided database. Insert a set of new records into the provided database without checking for conflicting entries. @param db: The MongoDB database to operate on. The expenditures collection ...
python
def insert_expenditure_entries(database, entries): """Insert a set of records of a expenditure report in the provided database. Insert a set of new records into the provided database without checking for conflicting entries. @param db: The MongoDB database to operate on. The expenditures collection ...
[ "def", "insert_expenditure_entries", "(", "database", ",", "entries", ")", ":", "entries", "=", "map", "(", "clean_entry", ",", "entries", ")", "database", ".", "expenditures", ".", "insert", "(", "entries", ",", "continue_on_error", "=", "True", ")" ]
Insert a set of records of a expenditure report in the provided database. Insert a set of new records into the provided database without checking for conflicting entries. @param db: The MongoDB database to operate on. The expenditures collection will be used from this database. @type db: pymon...
[ "Insert", "a", "set", "of", "records", "of", "a", "expenditure", "report", "in", "the", "provided", "database", "." ]
train
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L184-L197
sampottinger/pycotracer
pycotracer/mongo_aggregator.py
insert_loan_entries
def insert_loan_entries(database, entries): """Insert a set of records of a loan report in the provided database. Insert a set of new records into the provided database without checking for conflicting entries. @param db: The MongoDB database to operate on. The loans collection will be used fr...
python
def insert_loan_entries(database, entries): """Insert a set of records of a loan report in the provided database. Insert a set of new records into the provided database without checking for conflicting entries. @param db: The MongoDB database to operate on. The loans collection will be used fr...
[ "def", "insert_loan_entries", "(", "database", ",", "entries", ")", ":", "entries", "=", "map", "(", "clean_entry", ",", "entries", ")", "database", ".", "loans", ".", "insert", "(", "entries", ",", "continue_on_error", "=", "True", ")" ]
Insert a set of records of a loan report in the provided database. Insert a set of new records into the provided database without checking for conflicting entries. @param db: The MongoDB database to operate on. The loans collection will be used from this database. @type db: pymongo.database.Da...
[ "Insert", "a", "set", "of", "records", "of", "a", "loan", "report", "in", "the", "provided", "database", "." ]
train
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L200-L213
sampottinger/pycotracer
pycotracer/mongo_aggregator.py
update_entry
def update_entry(database, entry, report_type): """Update a record of a contribution report in the provided database. @param db: The MongoDB database to operate on. The contributions collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to inser...
python
def update_entry(database, entry, report_type): """Update a record of a contribution report in the provided database. @param db: The MongoDB database to operate on. The contributions collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to inser...
[ "def", "update_entry", "(", "database", ",", "entry", ",", "report_type", ")", ":", "factory", "=", "UpdateStrategyFactory", ".", "get_instance", "(", ")", "strategy", "=", "factory", ".", "get_strategy", "(", "report_type", ")", "if", "not", "strategy", ":", ...
Update a record of a contribution report in the provided database. @param db: The MongoDB database to operate on. The contributions collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to insert into the database, updating the entry with th...
[ "Update", "a", "record", "of", "a", "contribution", "report", "in", "the", "provided", "database", "." ]
train
https://github.com/sampottinger/pycotracer/blob/c66c3230949b7bee8c9fec5fc00ab392865a0c8b/pycotracer/mongo_aggregator.py#L216-L236
PSU-OIT-ARC/django-local-settings
local_settings/checker.py
Checker.check
def check(self, obj, prefix=None): """Recursively look for :class:`.LocalSetting`s in ``obj``. ``obj`` can be a dict, tuple, or list. Other types are skipped. This will prompt to get the value of local settings (excluding those that have had prompting disabled) that haven't already ...
python
def check(self, obj, prefix=None): """Recursively look for :class:`.LocalSetting`s in ``obj``. ``obj`` can be a dict, tuple, or list. Other types are skipped. This will prompt to get the value of local settings (excluding those that have had prompting disabled) that haven't already ...
[ "def", "check", "(", "self", ",", "obj", ",", "prefix", "=", "None", ")", ":", "self", ".", "_populate_registry", "(", "obj", ",", "prefix", ")", "settings_to_write", ",", "missing", "=", "self", ".", "_check", "(", "obj", ",", "prefix", ",", "{", "}...
Recursively look for :class:`.LocalSetting`s in ``obj``. ``obj`` can be a dict, tuple, or list. Other types are skipped. This will prompt to get the value of local settings (excluding those that have had prompting disabled) that haven't already been set locally. Returns ``True...
[ "Recursively", "look", "for", ":", "class", ":", ".", "LocalSetting", "s", "in", "obj", "." ]
train
https://github.com/PSU-OIT-ARC/django-local-settings/blob/758810fbd9411c2046a187afcac6532155cac694/local_settings/checker.py#L26-L47
emory-libraries/eulcommon
eulcommon/searchutil/templatetags/search_utils.py
pagination_links
def pagination_links(paginator_page, show_pages, url_params=None, first_page_label=None, last_page_label=None, page_url=''): '''Django template tag to display pagination links for a paginated list of items. Expects the following variables: * the current :class...
python
def pagination_links(paginator_page, show_pages, url_params=None, first_page_label=None, last_page_label=None, page_url=''): '''Django template tag to display pagination links for a paginated list of items. Expects the following variables: * the current :class...
[ "def", "pagination_links", "(", "paginator_page", ",", "show_pages", ",", "url_params", "=", "None", ",", "first_page_label", "=", "None", ",", "last_page_label", "=", "None", ",", "page_url", "=", "''", ")", ":", "return", "{", "'items'", ":", "paginator_page...
Django template tag to display pagination links for a paginated list of items. Expects the following variables: * the current :class:`~django.core.paginator.Page` of a :class:`~django.core.paginator.Paginator` object * a dictionary of the pages to be displayed, in the format generated b...
[ "Django", "template", "tag", "to", "display", "pagination", "links", "for", "a", "paginated", "list", "of", "items", "." ]
train
https://github.com/emory-libraries/eulcommon/blob/dc63a9b3b5e38205178235e0d716d1b28158d3a9/eulcommon/searchutil/templatetags/search_utils.py#L6-L40
praekelt/panya
panya/__init__.py
modify_classes
def modify_classes(): """ Auto-discover INSTALLED_APPS class_modifiers.py modules and fail silently when not present. This forces an import on them to modify any classes they may want. """ import copy from django.conf import settings from django.contrib.admin.sites import site from d...
python
def modify_classes(): """ Auto-discover INSTALLED_APPS class_modifiers.py modules and fail silently when not present. This forces an import on them to modify any classes they may want. """ import copy from django.conf import settings from django.contrib.admin.sites import site from d...
[ "def", "modify_classes", "(", ")", ":", "import", "copy", "from", "django", ".", "conf", "import", "settings", "from", "django", ".", "contrib", ".", "admin", ".", "sites", "import", "site", "from", "django", ".", "utils", ".", "importlib", "import", "impo...
Auto-discover INSTALLED_APPS class_modifiers.py modules and fail silently when not present. This forces an import on them to modify any classes they may want.
[ "Auto", "-", "discover", "INSTALLED_APPS", "class_modifiers", ".", "py", "modules", "and", "fail", "silently", "when", "not", "present", ".", "This", "forces", "an", "import", "on", "them", "to", "modify", "any", "classes", "they", "may", "want", "." ]
train
https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/__init__.py#L1-L25
carlsverre/wraptor
wraptor/decorators/exception_catcher.py
exception_catcher
def exception_catcher(fn): """ Catch exceptions raised by the decorated function. Call check() to raise any caught exceptions. """ exceptions = Queue.Queue() @wraps(fn) def wrapped(*args, **kwargs): try: ret = fn(*args, **kwargs) except Exception: exc...
python
def exception_catcher(fn): """ Catch exceptions raised by the decorated function. Call check() to raise any caught exceptions. """ exceptions = Queue.Queue() @wraps(fn) def wrapped(*args, **kwargs): try: ret = fn(*args, **kwargs) except Exception: exc...
[ "def", "exception_catcher", "(", "fn", ")", ":", "exceptions", "=", "Queue", ".", "Queue", "(", ")", "@", "wraps", "(", "fn", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "ret", "=", "fn", "(", "*", "a...
Catch exceptions raised by the decorated function. Call check() to raise any caught exceptions.
[ "Catch", "exceptions", "raised", "by", "the", "decorated", "function", ".", "Call", "check", "()", "to", "raise", "any", "caught", "exceptions", "." ]
train
https://github.com/carlsverre/wraptor/blob/f6dc23dfc8e5ac2e052a172578002964a4e15da9/wraptor/decorators/exception_catcher.py#L5-L29
ch3pjw/junction
jcn/textwrap.py
TextWrapper.wrap
def wrap(self, text): '''Wraps the text object to width, breaking at whitespaces. Runs of whitespace characters are preserved, provided they do not fall at a line boundary. The implementation is based on that of textwrap from the standard library, but we can cope with StringWithFormattin...
python
def wrap(self, text): '''Wraps the text object to width, breaking at whitespaces. Runs of whitespace characters are preserved, provided they do not fall at a line boundary. The implementation is based on that of textwrap from the standard library, but we can cope with StringWithFormattin...
[ "def", "wrap", "(", "self", ",", "text", ")", ":", "result", "=", "[", "]", "chunks", "=", "self", ".", "_chunk", "(", "text", ")", "while", "chunks", ":", "self", ".", "_lstrip", "(", "chunks", ")", "current_line", "=", "[", "]", "current_line_lengt...
Wraps the text object to width, breaking at whitespaces. Runs of whitespace characters are preserved, provided they do not fall at a line boundary. The implementation is based on that of textwrap from the standard library, but we can cope with StringWithFormatting objects. :returns: a l...
[ "Wraps", "the", "text", "object", "to", "width", "breaking", "at", "whitespaces", ".", "Runs", "of", "whitespace", "characters", "are", "preserved", "provided", "they", "do", "not", "fall", "at", "a", "line", "boundary", ".", "The", "implementation", "is", "...
train
https://github.com/ch3pjw/junction/blob/7d0c4d279589bee8ae7b3ac4dee2ab425c0b1b0e/jcn/textwrap.py#L58-L95
Othernet-Project/chainable-validators
validators/chain.py
chainable
def chainable(fn): """ Make function a chainable validator The returned function is a chainable validator factory which takes the next function in the chain and returns a chained version of the original validator: ``fn(next(value))``. The chainable validators are used with the ``make_chain()`` fun...
python
def chainable(fn): """ Make function a chainable validator The returned function is a chainable validator factory which takes the next function in the chain and returns a chained version of the original validator: ``fn(next(value))``. The chainable validators are used with the ``make_chain()`` fun...
[ "def", "chainable", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapper", "(", "nxt", "=", "lambda", "x", ":", "x", ")", ":", "if", "hasattr", "(", "nxt", ",", "'__call__'", ")", ":", "return", "lambda", "x", ":",...
Make function a chainable validator The returned function is a chainable validator factory which takes the next function in the chain and returns a chained version of the original validator: ``fn(next(value))``. The chainable validators are used with the ``make_chain()`` function.
[ "Make", "function", "a", "chainable", "validator" ]
train
https://github.com/Othernet-Project/chainable-validators/blob/8c0afebfaaa131440ffb2a960b9b38978f00d88f/validators/chain.py#L19-L34
Othernet-Project/chainable-validators
validators/chain.py
make_chain
def make_chain(fns): """ Take a list of chainable validators and return a chained validator The functions should be decorated with ``chainable`` decorator. Any exceptions raised by any of the validators are propagated except for ``ReturnEarly`` exception which is trapped. When ``ReturnEarly`` exceptio...
python
def make_chain(fns): """ Take a list of chainable validators and return a chained validator The functions should be decorated with ``chainable`` decorator. Any exceptions raised by any of the validators are propagated except for ``ReturnEarly`` exception which is trapped. When ``ReturnEarly`` exceptio...
[ "def", "make_chain", "(", "fns", ")", ":", "chain", "=", "lambda", "x", ":", "x", "for", "fn", "in", "reversed", "(", "fns", ")", ":", "chain", "=", "fn", "(", "chain", ")", "def", "validator", "(", "v", ")", ":", "try", ":", "return", "chain", ...
Take a list of chainable validators and return a chained validator The functions should be decorated with ``chainable`` decorator. Any exceptions raised by any of the validators are propagated except for ``ReturnEarly`` exception which is trapped. When ``ReturnEarly`` exception is trapped, the origina...
[ "Take", "a", "list", "of", "chainable", "validators", "and", "return", "a", "chained", "validator" ]
train
https://github.com/Othernet-Project/chainable-validators/blob/8c0afebfaaa131440ffb2a960b9b38978f00d88f/validators/chain.py#L37-L57
pip-services3-python/pip-services3-components-python
pip_services3_components/build/Factory.py
Factory.register
def register(self, locator, factory): """ Registers a component using a factory method. :param locator: a locator to identify component to be created. :param factory: a factory function that receives a locator and returns a created component. """ if locator == None: ...
python
def register(self, locator, factory): """ Registers a component using a factory method. :param locator: a locator to identify component to be created. :param factory: a factory function that receives a locator and returns a created component. """ if locator == None: ...
[ "def", "register", "(", "self", ",", "locator", ",", "factory", ")", ":", "if", "locator", "==", "None", ":", "raise", "Exception", "(", "\"Locator cannot be null\"", ")", "if", "factory", "==", "None", ":", "raise", "Exception", "(", "\"Factory cannot be null...
Registers a component using a factory method. :param locator: a locator to identify component to be created. :param factory: a factory function that receives a locator and returns a created component.
[ "Registers", "a", "component", "using", "a", "factory", "method", "." ]
train
https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/build/Factory.py#L37-L50
pip-services3-python/pip-services3-components-python
pip_services3_components/build/Factory.py
Factory.register_as_type
def register_as_type(self, locator, object_factory): """ Registers a component using its type (a constructor function). :param locator: a locator to identify component to be created. :param object_factory: a component type. """ if locator == None: raise Exce...
python
def register_as_type(self, locator, object_factory): """ Registers a component using its type (a constructor function). :param locator: a locator to identify component to be created. :param object_factory: a component type. """ if locator == None: raise Exce...
[ "def", "register_as_type", "(", "self", ",", "locator", ",", "object_factory", ")", ":", "if", "locator", "==", "None", ":", "raise", "Exception", "(", "\"Locator cannot be null\"", ")", "if", "object_factory", "==", "None", ":", "raise", "Exception", "(", "\"...
Registers a component using its type (a constructor function). :param locator: a locator to identify component to be created. :param object_factory: a component type.
[ "Registers", "a", "component", "using", "its", "type", "(", "a", "constructor", "function", ")", "." ]
train
https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/build/Factory.py#L52-L68