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
BlackEarth/bf
bf/css.py
CSS.merge_stylesheets
def merge_stylesheets(Class, fn, *cssfns): """merge the given CSS files, in order, into a single stylesheet. First listed takes priority. """ stylesheet = Class(fn=fn) for cssfn in cssfns: css = Class(fn=cssfn) for sel in sorted(css.styles.keys()): ...
python
def merge_stylesheets(Class, fn, *cssfns): """merge the given CSS files, in order, into a single stylesheet. First listed takes priority. """ stylesheet = Class(fn=fn) for cssfn in cssfns: css = Class(fn=cssfn) for sel in sorted(css.styles.keys()): ...
[ "def", "merge_stylesheets", "(", "Class", ",", "fn", ",", "*", "cssfns", ")", ":", "stylesheet", "=", "Class", "(", "fn", "=", "fn", ")", "for", "cssfn", "in", "cssfns", ":", "css", "=", "Class", "(", "fn", "=", "cssfn", ")", "for", "sel", "in", ...
merge the given CSS files, in order, into a single stylesheet. First listed takes priority.
[ "merge", "the", "given", "CSS", "files", "in", "order", "into", "a", "single", "stylesheet", ".", "First", "listed", "takes", "priority", "." ]
train
https://github.com/BlackEarth/bf/blob/376041168874bbd6dee5ccfeece4a9e553223316/bf/css.py#L76-L88
BlackEarth/bf
bf/css.py
CSS.all_selectors
def all_selectors(Class, fn): """return a sorted list of selectors that occur in the stylesheet""" selectors = [] cssparser = cssutils.CSSParser(validate=False) css = cssparser.parseFile(fn) for rule in [r for r in css.cssRules if type(r)==cssutils.css.CSSStyleRule]: ...
python
def all_selectors(Class, fn): """return a sorted list of selectors that occur in the stylesheet""" selectors = [] cssparser = cssutils.CSSParser(validate=False) css = cssparser.parseFile(fn) for rule in [r for r in css.cssRules if type(r)==cssutils.css.CSSStyleRule]: ...
[ "def", "all_selectors", "(", "Class", ",", "fn", ")", ":", "selectors", "=", "[", "]", "cssparser", "=", "cssutils", ".", "CSSParser", "(", "validate", "=", "False", ")", "css", "=", "cssparser", ".", "parseFile", "(", "fn", ")", "for", "rule", "in", ...
return a sorted list of selectors that occur in the stylesheet
[ "return", "a", "sorted", "list", "of", "selectors", "that", "occur", "in", "the", "stylesheet" ]
train
https://github.com/BlackEarth/bf/blob/376041168874bbd6dee5ccfeece4a9e553223316/bf/css.py#L91-L99
BlackEarth/bf
bf/css.py
CSS.selector_to_xpath
def selector_to_xpath(cls, selector, xmlns=None): """convert a css selector into an xpath expression. xmlns is option single-item dict with namespace prefix and href """ selector = selector.replace(' .', ' *.') if selector[0] == '.': selector = '*' + select...
python
def selector_to_xpath(cls, selector, xmlns=None): """convert a css selector into an xpath expression. xmlns is option single-item dict with namespace prefix and href """ selector = selector.replace(' .', ' *.') if selector[0] == '.': selector = '*' + select...
[ "def", "selector_to_xpath", "(", "cls", ",", "selector", ",", "xmlns", "=", "None", ")", ":", "selector", "=", "selector", ".", "replace", "(", "' .'", ",", "' *.'", ")", "if", "selector", "[", "0", "]", "==", "'.'", ":", "selector", "=", "'*'", "+",...
convert a css selector into an xpath expression. xmlns is option single-item dict with namespace prefix and href
[ "convert", "a", "css", "selector", "into", "an", "xpath", "expression", ".", "xmlns", "is", "option", "single", "-", "item", "dict", "with", "namespace", "prefix", "and", "href" ]
train
https://github.com/BlackEarth/bf/blob/376041168874bbd6dee5ccfeece4a9e553223316/bf/css.py#L102-L131
BlackEarth/bf
bf/css.py
CSS.cmyk_to_rgb
def cmyk_to_rgb(Class, c, m, y, k): """CMYK in % to RGB in 0-255 based on https://www.openprocessing.org/sketch/46231# """ c = float(c)/100.0 m = float(m)/100.0 y = float(y)/100.0 k = float(k)/100.0 nc = (c * (1-k)) + k nm = (m * (1-k)) ...
python
def cmyk_to_rgb(Class, c, m, y, k): """CMYK in % to RGB in 0-255 based on https://www.openprocessing.org/sketch/46231# """ c = float(c)/100.0 m = float(m)/100.0 y = float(y)/100.0 k = float(k)/100.0 nc = (c * (1-k)) + k nm = (m * (1-k)) ...
[ "def", "cmyk_to_rgb", "(", "Class", ",", "c", ",", "m", ",", "y", ",", "k", ")", ":", "c", "=", "float", "(", "c", ")", "/", "100.0", "m", "=", "float", "(", "m", ")", "/", "100.0", "y", "=", "float", "(", "y", ")", "/", "100.0", "k", "="...
CMYK in % to RGB in 0-255 based on https://www.openprocessing.org/sketch/46231#
[ "CMYK", "in", "%", "to", "RGB", "in", "0", "-", "255", "based", "on", "https", ":", "//", "www", ".", "openprocessing", ".", "org", "/", "sketch", "/", "46231#" ]
train
https://github.com/BlackEarth/bf/blob/376041168874bbd6dee5ccfeece4a9e553223316/bf/css.py#L134-L151
BlackEarth/bf
bf/css.py
CSS.rgb_to_hex
def rgb_to_hex(Class, r, g, b): """RGB in 0-255 to hex (RRGGBB)""" return ("%2s%2s%2s" % (hex(int(r)).lstrip('0x'), hex(int(g)).lstrip('0x'), hex(int(b)).lstrip('0x')) ).replace(' ', '0').upper()
python
def rgb_to_hex(Class, r, g, b): """RGB in 0-255 to hex (RRGGBB)""" return ("%2s%2s%2s" % (hex(int(r)).lstrip('0x'), hex(int(g)).lstrip('0x'), hex(int(b)).lstrip('0x')) ).replace(' ', '0').upper()
[ "def", "rgb_to_hex", "(", "Class", ",", "r", ",", "g", ",", "b", ")", ":", "return", "(", "\"%2s%2s%2s\"", "%", "(", "hex", "(", "int", "(", "r", ")", ")", ".", "lstrip", "(", "'0x'", ")", ",", "hex", "(", "int", "(", "g", ")", ")", ".", "l...
RGB in 0-255 to hex (RRGGBB)
[ "RGB", "in", "0", "-", "255", "to", "hex", "(", "RRGGBB", ")" ]
train
https://github.com/BlackEarth/bf/blob/376041168874bbd6dee5ccfeece4a9e553223316/bf/css.py#L154-L158
tslight/yorn
yorn/__main__.py
getargs
def getargs(): from argparse import ArgumentParser ''' Return arguments ''' parser = ArgumentParser(description='Answer yes or no to a question.') parser.add_argument("question", type=str, help="A question to ask.") return parser.parse_args()
python
def getargs(): from argparse import ArgumentParser ''' Return arguments ''' parser = ArgumentParser(description='Answer yes or no to a question.') parser.add_argument("question", type=str, help="A question to ask.") return parser.parse_args()
[ "def", "getargs", "(", ")", ":", "from", "argparse", "import", "ArgumentParser", "parser", "=", "ArgumentParser", "(", "description", "=", "'Answer yes or no to a question.'", ")", "parser", ".", "add_argument", "(", "\"question\"", ",", "type", "=", "str", ",", ...
Return arguments
[ "Return", "arguments" ]
train
https://github.com/tslight/yorn/blob/be577261065a53d3f4a585038c597c72950aa5ce/yorn/__main__.py#L5-L12
mikerhodes/actionqueues
actionqueues/aqstatemachine.py
AQStateMachine.transition_to_add
def transition_to_add(self): """Transition to add""" assert self.state in [AQStateMachineStates.init, AQStateMachineStates.add] self.state = AQStateMachineStates.add
python
def transition_to_add(self): """Transition to add""" assert self.state in [AQStateMachineStates.init, AQStateMachineStates.add] self.state = AQStateMachineStates.add
[ "def", "transition_to_add", "(", "self", ")", ":", "assert", "self", ".", "state", "in", "[", "AQStateMachineStates", ".", "init", ",", "AQStateMachineStates", ".", "add", "]", "self", ".", "state", "=", "AQStateMachineStates", ".", "add" ]
Transition to add
[ "Transition", "to", "add" ]
train
https://github.com/mikerhodes/actionqueues/blob/a7a78ab116abe88af95b5315dc9f34d40ce81eb2/actionqueues/aqstatemachine.py#L44-L47
mikerhodes/actionqueues
actionqueues/aqstatemachine.py
AQStateMachine.transition_to_execute
def transition_to_execute(self): """Transition to execute""" assert self.state in [AQStateMachineStates.add] self.state = AQStateMachineStates.execute
python
def transition_to_execute(self): """Transition to execute""" assert self.state in [AQStateMachineStates.add] self.state = AQStateMachineStates.execute
[ "def", "transition_to_execute", "(", "self", ")", ":", "assert", "self", ".", "state", "in", "[", "AQStateMachineStates", ".", "add", "]", "self", ".", "state", "=", "AQStateMachineStates", ".", "execute" ]
Transition to execute
[ "Transition", "to", "execute" ]
train
https://github.com/mikerhodes/actionqueues/blob/a7a78ab116abe88af95b5315dc9f34d40ce81eb2/actionqueues/aqstatemachine.py#L49-L52
mikerhodes/actionqueues
actionqueues/aqstatemachine.py
AQStateMachine.transition_to_rollback
def transition_to_rollback(self): """Transition to rollback""" assert self.state in [AQStateMachineStates.execute, AQStateMachineStates.execute_complete] self.state = AQStateMachineStates.rollback
python
def transition_to_rollback(self): """Transition to rollback""" assert self.state in [AQStateMachineStates.execute, AQStateMachineStates.execute_complete] self.state = AQStateMachineStates.rollback
[ "def", "transition_to_rollback", "(", "self", ")", ":", "assert", "self", ".", "state", "in", "[", "AQStateMachineStates", ".", "execute", ",", "AQStateMachineStates", ".", "execute_complete", "]", "self", ".", "state", "=", "AQStateMachineStates", ".", "rollback"...
Transition to rollback
[ "Transition", "to", "rollback" ]
train
https://github.com/mikerhodes/actionqueues/blob/a7a78ab116abe88af95b5315dc9f34d40ce81eb2/actionqueues/aqstatemachine.py#L54-L57
mikerhodes/actionqueues
actionqueues/aqstatemachine.py
AQStateMachine.transition_to_execute_complete
def transition_to_execute_complete(self): """Transition to execute complate""" assert self.state in [AQStateMachineStates.execute] self.state = AQStateMachineStates.execute_complete
python
def transition_to_execute_complete(self): """Transition to execute complate""" assert self.state in [AQStateMachineStates.execute] self.state = AQStateMachineStates.execute_complete
[ "def", "transition_to_execute_complete", "(", "self", ")", ":", "assert", "self", ".", "state", "in", "[", "AQStateMachineStates", ".", "execute", "]", "self", ".", "state", "=", "AQStateMachineStates", ".", "execute_complete" ]
Transition to execute complate
[ "Transition", "to", "execute", "complate" ]
train
https://github.com/mikerhodes/actionqueues/blob/a7a78ab116abe88af95b5315dc9f34d40ce81eb2/actionqueues/aqstatemachine.py#L59-L62
mikerhodes/actionqueues
actionqueues/aqstatemachine.py
AQStateMachine.transition_to_rollback_complete
def transition_to_rollback_complete(self): """Transition to rollback complete""" assert self.state in [AQStateMachineStates.rollback] self.state = AQStateMachineStates.rollback_complate
python
def transition_to_rollback_complete(self): """Transition to rollback complete""" assert self.state in [AQStateMachineStates.rollback] self.state = AQStateMachineStates.rollback_complate
[ "def", "transition_to_rollback_complete", "(", "self", ")", ":", "assert", "self", ".", "state", "in", "[", "AQStateMachineStates", ".", "rollback", "]", "self", ".", "state", "=", "AQStateMachineStates", ".", "rollback_complate" ]
Transition to rollback complete
[ "Transition", "to", "rollback", "complete" ]
train
https://github.com/mikerhodes/actionqueues/blob/a7a78ab116abe88af95b5315dc9f34d40ce81eb2/actionqueues/aqstatemachine.py#L64-L67
romaryd/python-jsonrepo
jsonrepo/backends/memory.py
DictBackend.get
def get(self, key, sort_key): """ Get an element in dictionary """ key = self.prefixed('{}:{}'.format(key, sort_key)) self.logger.debug('Storage - get {}'.format(key)) if key not in self.cache.keys(): return None return self.cache[key]
python
def get(self, key, sort_key): """ Get an element in dictionary """ key = self.prefixed('{}:{}'.format(key, sort_key)) self.logger.debug('Storage - get {}'.format(key)) if key not in self.cache.keys(): return None return self.cache[key]
[ "def", "get", "(", "self", ",", "key", ",", "sort_key", ")", ":", "key", "=", "self", ".", "prefixed", "(", "'{}:{}'", ".", "format", "(", "key", ",", "sort_key", ")", ")", "self", ".", "logger", ".", "debug", "(", "'Storage - get {}'", ".", "format"...
Get an element in dictionary
[ "Get", "an", "element", "in", "dictionary" ]
train
https://github.com/romaryd/python-jsonrepo/blob/08a9c039a5bd21e93e9a6d1bce77d43e6e10b57d/jsonrepo/backends/memory.py#L24-L30
romaryd/python-jsonrepo
jsonrepo/backends/memory.py
DictBackend.delete
def delete(self, key, sort_key): primary_key = key key = self.prefixed('{}:{}'.format(key, sort_key)) """ Delete an element in dictionary """ self.logger.debug('Storage - delete {}'.format(key)) if sort_key is not None: self.cache[self.prefixed(primary_key)].remove(so...
python
def delete(self, key, sort_key): primary_key = key key = self.prefixed('{}:{}'.format(key, sort_key)) """ Delete an element in dictionary """ self.logger.debug('Storage - delete {}'.format(key)) if sort_key is not None: self.cache[self.prefixed(primary_key)].remove(so...
[ "def", "delete", "(", "self", ",", "key", ",", "sort_key", ")", ":", "primary_key", "=", "key", "key", "=", "self", ".", "prefixed", "(", "'{}:{}'", ".", "format", "(", "key", ",", "sort_key", ")", ")", "self", ".", "logger", ".", "debug", "(", "'S...
Delete an element in dictionary
[ "Delete", "an", "element", "in", "dictionary" ]
train
https://github.com/romaryd/python-jsonrepo/blob/08a9c039a5bd21e93e9a6d1bce77d43e6e10b57d/jsonrepo/backends/memory.py#L73-L86
lsst-sqre/sqre-apikit
apikit/convenience.py
set_flask_metadata
def set_flask_metadata(app, version, repository, description, api_version="1.0", name=None, auth=None, route=None): """ Sets metadata on the application to be returned via metadata routes. Parameters ---------- app : :class:`flask.Flask` instance ...
python
def set_flask_metadata(app, version, repository, description, api_version="1.0", name=None, auth=None, route=None): """ Sets metadata on the application to be returned via metadata routes. Parameters ---------- app : :class:`flask.Flask` instance ...
[ "def", "set_flask_metadata", "(", "app", ",", "version", ",", "repository", ",", "description", ",", "api_version", "=", "\"1.0\"", ",", "name", "=", "None", ",", "auth", "=", "None", ",", "route", "=", "None", ")", ":", "errstr", "=", "set_flask_metadata"...
Sets metadata on the application to be returned via metadata routes. Parameters ---------- app : :class:`flask.Flask` instance Flask application for the microservice you're adding metadata to. version: `str` Version of your microservice. repository: `str` URL of the reposi...
[ "Sets", "metadata", "on", "the", "application", "to", "be", "returned", "via", "metadata", "routes", "." ]
train
https://github.com/lsst-sqre/sqre-apikit/blob/ff505b63d2e29303ff7f05f2bd5eabd0f6d7026e/apikit/convenience.py#L15-L101
lsst-sqre/sqre-apikit
apikit/convenience.py
add_metadata_route
def add_metadata_route(app, route): """ Creates a /metadata route that returns service metadata. Also creates a /v{api_version}/metadata route, and those routes with ".json" appended. If route is specified, prepends it (or each component) to the front of the route. Parameters ---------- ...
python
def add_metadata_route(app, route): """ Creates a /metadata route that returns service metadata. Also creates a /v{api_version}/metadata route, and those routes with ".json" appended. If route is specified, prepends it (or each component) to the front of the route. Parameters ---------- ...
[ "def", "add_metadata_route", "(", "app", ",", "route", ")", ":", "errstr", "=", "add_metadata_route", ".", "__doc__", "if", "route", "is", "None", ":", "route", "=", "[", "\"\"", "]", "if", "isinstance", "(", "route", ",", "str", ")", ":", "route", "="...
Creates a /metadata route that returns service metadata. Also creates a /v{api_version}/metadata route, and those routes with ".json" appended. If route is specified, prepends it (or each component) to the front of the route. Parameters ---------- app : :class:`flask.Flask` instance F...
[ "Creates", "a", "/", "metadata", "route", "that", "returns", "service", "metadata", ".", "Also", "creates", "a", "/", "v", "{", "api_version", "}", "/", "metadata", "route", "and", "those", "routes", "with", ".", "json", "appended", ".", "If", "route", "...
train
https://github.com/lsst-sqre/sqre-apikit/blob/ff505b63d2e29303ff7f05f2bd5eabd0f6d7026e/apikit/convenience.py#L104-L146
lsst-sqre/sqre-apikit
apikit/convenience.py
_return_metadata
def _return_metadata(): """ Return JSON-formatted metadata for route attachment. Requires flask.current_app to be set, which means `with app.app_context()` """ app = current_app retdict = {"auth": app.config["AUTH"]["type"]} for fld in ["name", "repository", "version", "description", ...
python
def _return_metadata(): """ Return JSON-formatted metadata for route attachment. Requires flask.current_app to be set, which means `with app.app_context()` """ app = current_app retdict = {"auth": app.config["AUTH"]["type"]} for fld in ["name", "repository", "version", "description", ...
[ "def", "_return_metadata", "(", ")", ":", "app", "=", "current_app", "retdict", "=", "{", "\"auth\"", ":", "app", ".", "config", "[", "\"AUTH\"", "]", "[", "\"type\"", "]", "}", "for", "fld", "in", "[", "\"name\"", ",", "\"repository\"", ",", "\"version\...
Return JSON-formatted metadata for route attachment. Requires flask.current_app to be set, which means `with app.app_context()`
[ "Return", "JSON", "-", "formatted", "metadata", "for", "route", "attachment", ".", "Requires", "flask", ".", "current_app", "to", "be", "set", "which", "means", "with", "app", ".", "app_context", "()" ]
train
https://github.com/lsst-sqre/sqre-apikit/blob/ff505b63d2e29303ff7f05f2bd5eabd0f6d7026e/apikit/convenience.py#L149-L160
lsst-sqre/sqre-apikit
apikit/convenience.py
retry_request
def retry_request(method, url, headers=None, payload=None, auth=None, tries=10, initial_interval=5, callback=None): """Retry an HTTP request with linear backoff. Returns the response if the status code is < 400 or waits (try * initial_interval) seconds and retries (up to tries times) if i...
python
def retry_request(method, url, headers=None, payload=None, auth=None, tries=10, initial_interval=5, callback=None): """Retry an HTTP request with linear backoff. Returns the response if the status code is < 400 or waits (try * initial_interval) seconds and retries (up to tries times) if i...
[ "def", "retry_request", "(", "method", ",", "url", ",", "headers", "=", "None", ",", "payload", "=", "None", ",", "auth", "=", "None", ",", "tries", "=", "10", ",", "initial_interval", "=", "5", ",", "callback", "=", "None", ")", ":", "method", "=", ...
Retry an HTTP request with linear backoff. Returns the response if the status code is < 400 or waits (try * initial_interval) seconds and retries (up to tries times) if it is not. Parameters ---------- method: `str` Method: `GET`, `PUT`, or `POST` url: `str` URL of HTTP req...
[ "Retry", "an", "HTTP", "request", "with", "linear", "backoff", ".", "Returns", "the", "response", "if", "the", "status", "code", "is", "<", "400", "or", "waits", "(", "try", "*", "initial_interval", ")", "seconds", "and", "retries", "(", "up", "to", "tri...
train
https://github.com/lsst-sqre/sqre-apikit/blob/ff505b63d2e29303ff7f05f2bd5eabd0f6d7026e/apikit/convenience.py#L164-L234
lsst-sqre/sqre-apikit
apikit/convenience.py
raise_ise
def raise_ise(text): """Turn a failed request response into a BackendError that represents an Internal Server Error. Handy for reflecting HTTP errors from farther back in the call chain as failures of your service. Parameters ---------- text: `str` Error text. Raises ------ ...
python
def raise_ise(text): """Turn a failed request response into a BackendError that represents an Internal Server Error. Handy for reflecting HTTP errors from farther back in the call chain as failures of your service. Parameters ---------- text: `str` Error text. Raises ------ ...
[ "def", "raise_ise", "(", "text", ")", ":", "if", "isinstance", "(", "text", ",", "Exception", ")", ":", "# Just in case we are exuberantly passed the entire Exception and", "# not its textual representation.", "text", "=", "str", "(", "text", ")", "raise", "BackendErro...
Turn a failed request response into a BackendError that represents an Internal Server Error. Handy for reflecting HTTP errors from farther back in the call chain as failures of your service. Parameters ---------- text: `str` Error text. Raises ------ :class:`apikit.BackendErro...
[ "Turn", "a", "failed", "request", "response", "into", "a", "BackendError", "that", "represents", "an", "Internal", "Server", "Error", ".", "Handy", "for", "reflecting", "HTTP", "errors", "from", "farther", "back", "in", "the", "call", "chain", "as", "failures"...
train
https://github.com/lsst-sqre/sqre-apikit/blob/ff505b63d2e29303ff7f05f2bd5eabd0f6d7026e/apikit/convenience.py#L237-L259
lsst-sqre/sqre-apikit
apikit/convenience.py
raise_from_response
def raise_from_response(resp): """Turn a failed request response into a BackendError. Handy for reflecting HTTP errors from farther back in the call chain. Parameters ---------- resp: :class:`requests.Response` Raises ------ :class:`apikit.BackendError` If `resp.status_code` i...
python
def raise_from_response(resp): """Turn a failed request response into a BackendError. Handy for reflecting HTTP errors from farther back in the call chain. Parameters ---------- resp: :class:`requests.Response` Raises ------ :class:`apikit.BackendError` If `resp.status_code` i...
[ "def", "raise_from_response", "(", "resp", ")", ":", "if", "resp", ".", "status_code", "<", "400", ":", "# Request was successful. Or at least, not a failure.", "return", "raise", "BackendError", "(", "status_code", "=", "resp", ".", "status_code", ",", "reason", "...
Turn a failed request response into a BackendError. Handy for reflecting HTTP errors from farther back in the call chain. Parameters ---------- resp: :class:`requests.Response` Raises ------ :class:`apikit.BackendError` If `resp.status_code` is equal to or greater than 400.
[ "Turn", "a", "failed", "request", "response", "into", "a", "BackendError", ".", "Handy", "for", "reflecting", "HTTP", "errors", "from", "farther", "back", "in", "the", "call", "chain", "." ]
train
https://github.com/lsst-sqre/sqre-apikit/blob/ff505b63d2e29303ff7f05f2bd5eabd0f6d7026e/apikit/convenience.py#L262-L280
lsst-sqre/sqre-apikit
apikit/convenience.py
get_logger
def get_logger(file=None, syslog=False, loghost=None, level=None): """Creates a logging object compatible with Python standard logging, but which, as a `structlog` instance, emits JSON. Parameters ---------- file: `None` or `str` (default `None`) If given, send log output to file; otherw...
python
def get_logger(file=None, syslog=False, loghost=None, level=None): """Creates a logging object compatible with Python standard logging, but which, as a `structlog` instance, emits JSON. Parameters ---------- file: `None` or `str` (default `None`) If given, send log output to file; otherw...
[ "def", "get_logger", "(", "file", "=", "None", ",", "syslog", "=", "False", ",", "loghost", "=", "None", ",", "level", "=", "None", ")", ":", "if", "not", "syslog", ":", "if", "not", "file", ":", "handler", "=", "logging", ".", "StreamHandler", "(", ...
Creates a logging object compatible with Python standard logging, but which, as a `structlog` instance, emits JSON. Parameters ---------- file: `None` or `str` (default `None`) If given, send log output to file; otherwise, to `stdout`. syslog: `bool` (default `False`) If `True`, ...
[ "Creates", "a", "logging", "object", "compatible", "with", "Python", "standard", "logging", "but", "which", "as", "a", "structlog", "instance", "emits", "JSON", "." ]
train
https://github.com/lsst-sqre/sqre-apikit/blob/ff505b63d2e29303ff7f05f2bd5eabd0f6d7026e/apikit/convenience.py#L283-L348
Deisss/python-sockjsroom
sockjsroom/httpJsonHandler.py
JsonDefaultHandler.getBody
def getBody(self): """ Extract body json """ data = None try: data = json.loads(self.request.body) except: data = json.loads(urllib.unquote_plus(self.request.body)) return data
python
def getBody(self): """ Extract body json """ data = None try: data = json.loads(self.request.body) except: data = json.loads(urllib.unquote_plus(self.request.body)) return data
[ "def", "getBody", "(", "self", ")", ":", "data", "=", "None", "try", ":", "data", "=", "json", ".", "loads", "(", "self", ".", "request", ".", "body", ")", "except", ":", "data", "=", "json", ".", "loads", "(", "urllib", ".", "unquote_plus", "(", ...
Extract body json
[ "Extract", "body", "json" ]
train
https://github.com/Deisss/python-sockjsroom/blob/7c20187571d39e7fede848dc98f954235ca77241/sockjsroom/httpJsonHandler.py#L25-L32
Deisss/python-sockjsroom
sockjsroom/httpJsonHandler.py
JsonDefaultHandler.write
def write(self, obj): """ Print object on output """ accept = self.request.headers.get("Accept") if "json" in accept: if JsonDefaultHandler.__parser is None: JsonDefaultHandler.__parser = Parser() super(JsonDefaultHandler, self).write(JsonDefaultHandler.__...
python
def write(self, obj): """ Print object on output """ accept = self.request.headers.get("Accept") if "json" in accept: if JsonDefaultHandler.__parser is None: JsonDefaultHandler.__parser = Parser() super(JsonDefaultHandler, self).write(JsonDefaultHandler.__...
[ "def", "write", "(", "self", ",", "obj", ")", ":", "accept", "=", "self", ".", "request", ".", "headers", ".", "get", "(", "\"Accept\"", ")", "if", "\"json\"", "in", "accept", ":", "if", "JsonDefaultHandler", ".", "__parser", "is", "None", ":", "JsonDe...
Print object on output
[ "Print", "object", "on", "output" ]
train
https://github.com/Deisss/python-sockjsroom/blob/7c20187571d39e7fede848dc98f954235ca77241/sockjsroom/httpJsonHandler.py#L34-L43
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC.reconnect
async def reconnect(self): """断线重连.""" self.clean() try: self.writer.close() except: pass self.closed = True await self.connect() if self.debug: print("reconnect to {}".format((self.hostname, self.port)))
python
async def reconnect(self): """断线重连.""" self.clean() try: self.writer.close() except: pass self.closed = True await self.connect() if self.debug: print("reconnect to {}".format((self.hostname, self.port)))
[ "async", "def", "reconnect", "(", "self", ")", ":", "self", ".", "clean", "(", ")", "try", ":", "self", ".", "writer", ".", "close", "(", ")", "except", ":", "pass", "self", ".", "closed", "=", "True", "await", "self", ".", "connect", "(", ")", "...
断线重连.
[ "断线重连", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L133-L143
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC.connect
async def connect(self): """与远端建立连接. 主要执行的操作有: + 将监听响应的协程_response_handler放入事件循环 + 如果有验证信息则发送验证信息 + 获取连接建立的返回 """ self.reader, self.writer = await asyncio.open_connection( host=self.hostname, port=self.port, loop=self.loop) ...
python
async def connect(self): """与远端建立连接. 主要执行的操作有: + 将监听响应的协程_response_handler放入事件循环 + 如果有验证信息则发送验证信息 + 获取连接建立的返回 """ self.reader, self.writer = await asyncio.open_connection( host=self.hostname, port=self.port, loop=self.loop) ...
[ "async", "def", "connect", "(", "self", ")", ":", "self", ".", "reader", ",", "self", ".", "writer", "=", "await", "asyncio", ".", "open_connection", "(", "host", "=", "self", ".", "hostname", ",", "port", "=", "self", ".", "port", ",", "loop", "=", ...
与远端建立连接. 主要执行的操作有: + 将监听响应的协程_response_handler放入事件循环 + 如果有验证信息则发送验证信息 + 获取连接建立的返回
[ "与远端建立连接", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L145-L177
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC.clean
def clean(self): """清理还在执行或者等待执行的协程.""" for _, i in self.tasks.items(): i.cancel() self._heartbeat_task.cancel() self._response_task.cancel()
python
def clean(self): """清理还在执行或者等待执行的协程.""" for _, i in self.tasks.items(): i.cancel() self._heartbeat_task.cancel() self._response_task.cancel()
[ "def", "clean", "(", "self", ")", ":", "for", "_", ",", "i", "in", "self", ".", "tasks", ".", "items", "(", ")", ":", "i", ".", "cancel", "(", ")", "self", ".", "_heartbeat_task", ".", "cancel", "(", ")", "self", ".", "_response_task", ".", "canc...
清理还在执行或者等待执行的协程.
[ "清理还在执行或者等待执行的协程", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L179-L184
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC.close
def close(self): """关闭与远端的连接. 判断标志位closed是否为False,如果是则关闭,否则不进行操作 """ if self.closed is False: self.clean() try: self.writer.write_eof() except: pass self.writer.close() self.closed = True ...
python
def close(self): """关闭与远端的连接. 判断标志位closed是否为False,如果是则关闭,否则不进行操作 """ if self.closed is False: self.clean() try: self.writer.write_eof() except: pass self.writer.close() self.closed = True ...
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "closed", "is", "False", ":", "self", ".", "clean", "(", ")", "try", ":", "self", ".", "writer", ".", "write_eof", "(", ")", "except", ":", "pass", "self", ".", "writer", ".", "close", "("...
关闭与远端的连接. 判断标志位closed是否为False,如果是则关闭,否则不进行操作
[ "关闭与远端的连接", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L186-L203
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC._heartbeat_callback
async def _heartbeat_callback(self): """如果设置了心跳,则调用这个协程.""" query = { "MPRPC": self.VERSION, "HEARTBEAT": "ping" } queryb = self.encoder(query) while True: await asyncio.sleep(self.heart_beat) self.writer.write(queryb) i...
python
async def _heartbeat_callback(self): """如果设置了心跳,则调用这个协程.""" query = { "MPRPC": self.VERSION, "HEARTBEAT": "ping" } queryb = self.encoder(query) while True: await asyncio.sleep(self.heart_beat) self.writer.write(queryb) i...
[ "async", "def", "_heartbeat_callback", "(", "self", ")", ":", "query", "=", "{", "\"MPRPC\"", ":", "self", ".", "VERSION", ",", "\"HEARTBEAT\"", ":", "\"ping\"", "}", "queryb", "=", "self", ".", "encoder", "(", "query", ")", "while", "True", ":", "await"...
如果设置了心跳,则调用这个协程.
[ "如果设置了心跳", "则调用这个协程", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L207-L218
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC._response_handler
async def _response_handler(self): """监听响应数据的协程函数.`connect`被调用后会被创建为一个协程并放入事件循环.""" if self.debug is True: if self.debug is True: print("listenning response!") while True: try: res = await self.reader.readuntil(self.SEPARATOR) e...
python
async def _response_handler(self): """监听响应数据的协程函数.`connect`被调用后会被创建为一个协程并放入事件循环.""" if self.debug is True: if self.debug is True: print("listenning response!") while True: try: res = await self.reader.readuntil(self.SEPARATOR) e...
[ "async", "def", "_response_handler", "(", "self", ")", ":", "if", "self", ".", "debug", "is", "True", ":", "if", "self", ".", "debug", "is", "True", ":", "print", "(", "\"listenning response!\"", ")", "while", "True", ":", "try", ":", "res", "=", "awai...
监听响应数据的协程函数.`connect`被调用后会被创建为一个协程并放入事件循环.
[ "监听响应数据的协程函数", ".", "connect", "被调用后会被创建为一个协程并放入事件循环", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L221-L233
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC._server_error_handler
def _server_error_handler(self, code: int): """处理500~599段状态码,抛出对应警告. Parameters: (code): - 响应的状态码 Return: (bool): - 已知的警告类型则返回True,否则返回False Raise: (ServerException): - 当返回为服务异常时则抛出对应异常 """ if code == 501: self._login_fu...
python
def _server_error_handler(self, code: int): """处理500~599段状态码,抛出对应警告. Parameters: (code): - 响应的状态码 Return: (bool): - 已知的警告类型则返回True,否则返回False Raise: (ServerException): - 当返回为服务异常时则抛出对应异常 """ if code == 501: self._login_fu...
[ "def", "_server_error_handler", "(", "self", ",", "code", ":", "int", ")", ":", "if", "code", "==", "501", ":", "self", ".", "_login_fut", ".", "set_result", "(", "False", ")", "else", ":", "self", ".", "clean", "(", ")", "raise", "abort", "(", "code...
处理500~599段状态码,抛出对应警告. Parameters: (code): - 响应的状态码 Return: (bool): - 已知的警告类型则返回True,否则返回False Raise: (ServerException): - 当返回为服务异常时则抛出对应异常
[ "处理500~599段状态码", "抛出对应警告", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L281-L299
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC._method_error_handler
def _method_error_handler(self, response: Dict[str, Any]): """处理400~499段状态码,为对应的任务设置异常. Parameters:s (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ exp = response.get('MESSAGE') code = response.get("CODE") ID = exp....
python
def _method_error_handler(self, response: Dict[str, Any]): """处理400~499段状态码,为对应的任务设置异常. Parameters:s (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ exp = response.get('MESSAGE') code = response.get("CODE") ID = exp....
[ "def", "_method_error_handler", "(", "self", ",", "response", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "exp", "=", "response", ".", "get", "(", "'MESSAGE'", ")", "code", "=", "response", ".", "get", "(", "\"CODE\"", ")", "ID", "=", "exp", ...
处理400~499段状态码,为对应的任务设置异常. Parameters:s (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True
[ "处理400~499段状态码", "为对应的任务设置异常", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L301-L316
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC._method_response_handler
def _method_response_handler(self, response: Dict[str, Any]): """处理200~399段状态码,为对应的响应设置结果. Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ code = response.get("CODE") if code in (200, 300): self._resu...
python
def _method_response_handler(self, response: Dict[str, Any]): """处理200~399段状态码,为对应的响应设置结果. Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ code = response.get("CODE") if code in (200, 300): self._resu...
[ "def", "_method_response_handler", "(", "self", ",", "response", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "code", "=", "response", ".", "get", "(", "\"CODE\"", ")", "if", "code", "in", "(", "200", ",", "300", ")", ":", "self", ".", "_res...
处理200~399段状态码,为对应的响应设置结果. Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True
[ "处理200~399段状态码", "为对应的响应设置结果", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L346-L360
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC._server_response_handler
def _server_response_handler(self, response: Dict[str, Any]): """处理100~199段状态码,针对不同的服务响应进行操作. Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ code = response.get("CODE") if code == 100: if self.debug:...
python
def _server_response_handler(self, response: Dict[str, Any]): """处理100~199段状态码,针对不同的服务响应进行操作. Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ code = response.get("CODE") if code == 100: if self.debug:...
[ "def", "_server_response_handler", "(", "self", ",", "response", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "code", "=", "response", ".", "get", "(", "\"CODE\"", ")", "if", "code", "==", "100", ":", "if", "self", ".", "debug", ":", "print", ...
处理100~199段状态码,针对不同的服务响应进行操作. Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True
[ "处理100~199段状态码", "针对不同的服务响应进行操作", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L363-L381
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC._result_handler
def _result_handler(self, response: Dict[str, Any]): """应答结果响应处理. 将结果解析出来设置给任务对应的Future对象上 Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ res = response.get("MESSAGE") ID = res.get("ID") result ...
python
def _result_handler(self, response: Dict[str, Any]): """应答结果响应处理. 将结果解析出来设置给任务对应的Future对象上 Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ res = response.get("MESSAGE") ID = res.get("ID") result ...
[ "def", "_result_handler", "(", "self", ",", "response", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "res", "=", "response", ".", "get", "(", "\"MESSAGE\"", ")", "ID", "=", "res", ".", "get", "(", "\"ID\"", ")", "result", "=", "res", ".", ...
应答结果响应处理. 将结果解析出来设置给任务对应的Future对象上 Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True
[ "应答结果响应处理", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L384-L401
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC._gen_result_handler
async def _gen_result_handler(self, response: Dict[str, Any]): """流式结果响应处理. + 收到状态码标识201或301的响应后,将tasks中ID对应的Future对象的结果设置为一个用于包装的异步生成器. 并为这个ID创建一个异步队列保存在`_gens_queue[ID]`中用于存取结果 + 收到状态码标识为202的响应后向对应ID的存取队列中存入一条结果. + 收到终止状态码206后向对应ID的异步生成器结果获取队列中存入一个`StopAsyncIteration`对象用于终止异...
python
async def _gen_result_handler(self, response: Dict[str, Any]): """流式结果响应处理. + 收到状态码标识201或301的响应后,将tasks中ID对应的Future对象的结果设置为一个用于包装的异步生成器. 并为这个ID创建一个异步队列保存在`_gens_queue[ID]`中用于存取结果 + 收到状态码标识为202的响应后向对应ID的存取队列中存入一条结果. + 收到终止状态码206后向对应ID的异步生成器结果获取队列中存入一个`StopAsyncIteration`对象用于终止异...
[ "async", "def", "_gen_result_handler", "(", "self", ",", "response", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "code", "=", "response", ".", "get", "(", "\"CODE\"", ")", "res", "=", "response", ".", "get", "(", "\"MESSAGE\"", ")", "ID", "="...
流式结果响应处理. + 收到状态码标识201或301的响应后,将tasks中ID对应的Future对象的结果设置为一个用于包装的异步生成器. 并为这个ID创建一个异步队列保存在`_gens_queue[ID]`中用于存取结果 + 收到状态码标识为202的响应后向对应ID的存取队列中存入一条结果. + 收到终止状态码206后向对应ID的异步生成器结果获取队列中存入一个`StopAsyncIteration`对象用于终止异步迭代器 Parameters: (response): - 响应的python字典形式数据 ...
[ "流式结果响应处理", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L405-L435
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC._wrap_gen
async def _wrap_gen(self, ID: str): """异步迭代器包装. Parameters: ID (str): - 任务ID Yield: (Any): - 从异步迭代器结果队列中获取的结果 Raise: (StopAsyncIteration): - 异步迭代器终止时抛出该异常 """ while True: result = await self._gens_queue[ID].get() ...
python
async def _wrap_gen(self, ID: str): """异步迭代器包装. Parameters: ID (str): - 任务ID Yield: (Any): - 从异步迭代器结果队列中获取的结果 Raise: (StopAsyncIteration): - 异步迭代器终止时抛出该异常 """ while True: result = await self._gens_queue[ID].get() ...
[ "async", "def", "_wrap_gen", "(", "self", ",", "ID", ":", "str", ")", ":", "while", "True", ":", "result", "=", "await", "self", ".", "_gens_queue", "[", "ID", "]", ".", "get", "(", ")", "if", "isinstance", "(", "result", ",", "StopAsyncIteration", "...
异步迭代器包装. Parameters: ID (str): - 任务ID Yield: (Any): - 从异步迭代器结果队列中获取的结果 Raise: (StopAsyncIteration): - 异步迭代器终止时抛出该异常
[ "异步迭代器包装", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L437-L456
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC._make_query
def _make_query(self, ID: str, methodname: str, returnable: bool, *args: Any, **kwargs: Any): """将调用请求的ID,方法名,参数包装为请求数据. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 returnable (bool): - 是否要求返回结果 args (Any): - 要调用的方法的位置参数 kwargs (A...
python
def _make_query(self, ID: str, methodname: str, returnable: bool, *args: Any, **kwargs: Any): """将调用请求的ID,方法名,参数包装为请求数据. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 returnable (bool): - 是否要求返回结果 args (Any): - 要调用的方法的位置参数 kwargs (A...
[ "def", "_make_query", "(", "self", ",", "ID", ":", "str", ",", "methodname", ":", "str", ",", "returnable", ":", "bool", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", ":", "query", "=", "{", "\"MPRPC\"", ":", "self", "."...
将调用请求的ID,方法名,参数包装为请求数据. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 returnable (bool): - 是否要求返回结果 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (Dict[str, Any]) : - 请求的python字典形式
[ "将调用请求的ID", "方法名", "参数包装为请求数据", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L460-L483
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC.send_query
def send_query(self, ID, methodname, returnable, *args, **kwargs): """将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 returnable (bool): - 是否要求返回结果 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键...
python
def send_query(self, ID, methodname, returnable, *args, **kwargs): """将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 returnable (bool): - 是否要求返回结果 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键...
[ "def", "send_query", "(", "self", ",", "ID", ",", "methodname", ",", "returnable", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "_make_query", "(", "ID", ",", "methodname", ",", "returnable", ",", "*", "args", ",", ...
将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 returnable (bool): - 是否要求返回结果 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (bool): - 准确地说没有错误就会返回True
[ "将调用请求的ID", "方法名", "参数包装为请求数据后编码为字节串发送出去", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L502-L520
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC.delay
def delay(self, methodname, *args, **kwargs): """调用但不要求返回结果,而是通过系统方法getresult来获取. Parameters: methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 """ ID = str(uuid.uuid4()) self.send_query(ID, methodname, False,...
python
def delay(self, methodname, *args, **kwargs): """调用但不要求返回结果,而是通过系统方法getresult来获取. Parameters: methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 """ ID = str(uuid.uuid4()) self.send_query(ID, methodname, False,...
[ "def", "delay", "(", "self", ",", "methodname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ID", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "self", ".", "send_query", "(", "ID", ",", "methodname", ",", "False", ",", "*", "a...
调用但不要求返回结果,而是通过系统方法getresult来获取. Parameters: methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数
[ "调用但不要求返回结果", "而是通过系统方法getresult来获取", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L522-L533
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC._async_query
def _async_query(self, ID, methodname, *args, **kwargs): """将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去.并创建一个Future对象占位. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (as...
python
def _async_query(self, ID, methodname, *args, **kwargs): """将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去.并创建一个Future对象占位. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (as...
[ "def", "_async_query", "(", "self", ",", "ID", ",", "methodname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "send_query", "(", "ID", ",", "methodname", ",", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", "task", "...
将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去.并创建一个Future对象占位. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (asyncio.Future): - 返回对应ID的Future对象
[ "将调用请求的ID", "方法名", "参数包装为请求数据后编码为字节串发送出去", ".", "并创建一个Future对象占位", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L535-L550
Basic-Components/msgpack-rpc-protocol
python/pymprpc/client/aio.py
AsyncRPC.async_query
def async_query(self, methodname, *args, **kwargs): """异步调用一个远端的函数. 为调用创建一个ID,并将调用请求的方法名,参数包装为请求数据后编码为字节串发送出去.并创建一个Future对象占位. Parameters: methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (asynci...
python
def async_query(self, methodname, *args, **kwargs): """异步调用一个远端的函数. 为调用创建一个ID,并将调用请求的方法名,参数包装为请求数据后编码为字节串发送出去.并创建一个Future对象占位. Parameters: methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (asynci...
[ "def", "async_query", "(", "self", ",", "methodname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ID", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "task", "=", "self", ".", "_async_query", "(", "ID", "=", "ID", ",", "methodnam...
异步调用一个远端的函数. 为调用创建一个ID,并将调用请求的方法名,参数包装为请求数据后编码为字节串发送出去.并创建一个Future对象占位. Parameters: methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (asyncio.Future): - 返回对应ID的Future对象
[ "异步调用一个远端的函数", "." ]
train
https://github.com/Basic-Components/msgpack-rpc-protocol/blob/7983ace5d5cfd7214df6803f9b1de458df5fe3b1/python/pymprpc/client/aio.py#L552-L568
funkybob/antfarm
antfarm/request.py
Request.raw_cookies
def raw_cookies(self): '''Raw access to cookies''' cookie_data = self.environ.get('HTTP_COOKIE', '') cookies = SimpleCookie() if not cookie_data: return cookies cookies.load(cookie_data) return cookies
python
def raw_cookies(self): '''Raw access to cookies''' cookie_data = self.environ.get('HTTP_COOKIE', '') cookies = SimpleCookie() if not cookie_data: return cookies cookies.load(cookie_data) return cookies
[ "def", "raw_cookies", "(", "self", ")", ":", "cookie_data", "=", "self", ".", "environ", ".", "get", "(", "'HTTP_COOKIE'", ",", "''", ")", "cookies", "=", "SimpleCookie", "(", ")", "if", "not", "cookie_data", ":", "return", "cookies", "cookies", ".", "lo...
Raw access to cookies
[ "Raw", "access", "to", "cookies" ]
train
https://github.com/funkybob/antfarm/blob/40a7cc450eba09a280b7bc8f7c68a807b0177c62/antfarm/request.py#L22-L29
funkybob/antfarm
antfarm/request.py
Request.cookies
def cookies(self): '''Simplified Cookie access''' return { key: self.raw_cookies[key].value for key in self.raw_cookies.keys() }
python
def cookies(self): '''Simplified Cookie access''' return { key: self.raw_cookies[key].value for key in self.raw_cookies.keys() }
[ "def", "cookies", "(", "self", ")", ":", "return", "{", "key", ":", "self", ".", "raw_cookies", "[", "key", "]", ".", "value", "for", "key", "in", "self", ".", "raw_cookies", ".", "keys", "(", ")", "}" ]
Simplified Cookie access
[ "Simplified", "Cookie", "access" ]
train
https://github.com/funkybob/antfarm/blob/40a7cc450eba09a280b7bc8f7c68a807b0177c62/antfarm/request.py#L32-L37
honzamach/pynspect
pynspect/benchmark/bench_jpath.py
random_jpath
def random_jpath(depth = 3): """ Generate random JPath with given node depth. """ chunks = [] while depth > 0: length = random.randint(5, 15) ident = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in range(length)) if random.choice((True, False)...
python
def random_jpath(depth = 3): """ Generate random JPath with given node depth. """ chunks = [] while depth > 0: length = random.randint(5, 15) ident = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in range(length)) if random.choice((True, False)...
[ "def", "random_jpath", "(", "depth", "=", "3", ")", ":", "chunks", "=", "[", "]", "while", "depth", ">", "0", ":", "length", "=", "random", ".", "randint", "(", "5", ",", "15", ")", "ident", "=", "''", ".", "join", "(", "random", ".", "choice", ...
Generate random JPath with given node depth.
[ "Generate", "random", "JPath", "with", "given", "node", "depth", "." ]
train
https://github.com/honzamach/pynspect/blob/0582dcc1f7aafe50e25a21c792ea1b3367ea5881/pynspect/benchmark/bench_jpath.py#L36-L49
praekelt/jmbo-twitter
jmbo_twitter/admin_views.py
feed_fetch_force
def feed_fetch_force(request, id, redirect_to): """Forcibly fetch tweets for the feed""" feed = Feed.objects.get(id=id) feed.fetch(force=True) msg = _("Fetched tweets for %s" % feed.name) messages.success(request, msg, fail_silently=True) return HttpResponseRedirect(redirect_to)
python
def feed_fetch_force(request, id, redirect_to): """Forcibly fetch tweets for the feed""" feed = Feed.objects.get(id=id) feed.fetch(force=True) msg = _("Fetched tweets for %s" % feed.name) messages.success(request, msg, fail_silently=True) return HttpResponseRedirect(redirect_to)
[ "def", "feed_fetch_force", "(", "request", ",", "id", ",", "redirect_to", ")", ":", "feed", "=", "Feed", ".", "objects", ".", "get", "(", "id", "=", "id", ")", "feed", ".", "fetch", "(", "force", "=", "True", ")", "msg", "=", "_", "(", "\"Fetched t...
Forcibly fetch tweets for the feed
[ "Forcibly", "fetch", "tweets", "for", "the", "feed" ]
train
https://github.com/praekelt/jmbo-twitter/blob/12e8eb08efcbc9d1423fc213b2f2d9d7fed8a775/jmbo_twitter/admin_views.py#L12-L18
praekelt/jmbo-twitter
jmbo_twitter/admin_views.py
search_fetch_force
def search_fetch_force(request, id, redirect_to): """Forcibly fetch tweets for the search""" search = Search.objects.get(id=id) search.fetch(force=True) msg = _("Fetched tweets for %s" % search.criteria) messages.success(request, msg, fail_silently=True) return HttpResponseRedirect(redirect_to)
python
def search_fetch_force(request, id, redirect_to): """Forcibly fetch tweets for the search""" search = Search.objects.get(id=id) search.fetch(force=True) msg = _("Fetched tweets for %s" % search.criteria) messages.success(request, msg, fail_silently=True) return HttpResponseRedirect(redirect_to)
[ "def", "search_fetch_force", "(", "request", ",", "id", ",", "redirect_to", ")", ":", "search", "=", "Search", ".", "objects", ".", "get", "(", "id", "=", "id", ")", "search", ".", "fetch", "(", "force", "=", "True", ")", "msg", "=", "_", "(", "\"F...
Forcibly fetch tweets for the search
[ "Forcibly", "fetch", "tweets", "for", "the", "search" ]
train
https://github.com/praekelt/jmbo-twitter/blob/12e8eb08efcbc9d1423fc213b2f2d9d7fed8a775/jmbo_twitter/admin_views.py#L32-L38
flytrap/flytrap-base
flytrap/base/view.py
ViewMixin.finalize_response
def finalize_response(self, request, response, *args, **kwargs): """封装响应""" if not isinstance(response, HttpResponseBase): response = SimpleResponse(self.resp_ok(response)) super_instance = super(ViewMixin, self) if hasattr(super_instance, 'finalize_response'): re...
python
def finalize_response(self, request, response, *args, **kwargs): """封装响应""" if not isinstance(response, HttpResponseBase): response = SimpleResponse(self.resp_ok(response)) super_instance = super(ViewMixin, self) if hasattr(super_instance, 'finalize_response'): re...
[ "def", "finalize_response", "(", "self", ",", "request", ",", "response", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "response", ",", "HttpResponseBase", ")", ":", "response", "=", "SimpleResponse", "(", "self", ...
封装响应
[ "封装响应" ]
train
https://github.com/flytrap/flytrap-base/blob/fa5a3135ce669725f88ef61d5d9f548cedfaf0ff/flytrap/base/view.py#L16-L22
ereOn/pyslot
pyslot/thread_safe_signal.py
ThreadSafeSignal.connect
def connect(self, callback, weak=False): """ Connects a new callback to this signal. :param callback: The callback to connect. :param weak: If `True`, only holds a weak reference to the specified callback. `callback` will be called whenever `emit` gets called on the...
python
def connect(self, callback, weak=False): """ Connects a new callback to this signal. :param callback: The callback to connect. :param weak: If `True`, only holds a weak reference to the specified callback. `callback` will be called whenever `emit` gets called on the...
[ "def", "connect", "(", "self", ",", "callback", ",", "weak", "=", "False", ")", ":", "if", "weak", ":", "callback", "=", "ref", "(", "callback", ",", "self", ".", "_disconnect", ")", "with", "self", ".", "_write_lock", ":", "with", "self", ".", "_rea...
Connects a new callback to this signal. :param callback: The callback to connect. :param weak: If `True`, only holds a weak reference to the specified callback. `callback` will be called whenever `emit` gets called on the `Signal` instance. If a weak reference is k...
[ "Connects", "a", "new", "callback", "to", "this", "signal", "." ]
train
https://github.com/ereOn/pyslot/blob/9201ce84449ca811afb65fde6cd46a3cb7029182/pyslot/thread_safe_signal.py#L22-L53
Rafiot/PubSubLogger
pubsublogger/publisher.py
__connect
def __connect(): """ Connect to a redis instance. """ global redis_instance if use_tcp_socket: redis_instance = redis.StrictRedis(host=hostname, port=port) else: redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)
python
def __connect(): """ Connect to a redis instance. """ global redis_instance if use_tcp_socket: redis_instance = redis.StrictRedis(host=hostname, port=port) else: redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)
[ "def", "__connect", "(", ")", ":", "global", "redis_instance", "if", "use_tcp_socket", ":", "redis_instance", "=", "redis", ".", "StrictRedis", "(", "host", "=", "hostname", ",", "port", "=", "port", ")", "else", ":", "redis_instance", "=", "redis", ".", "...
Connect to a redis instance.
[ "Connect", "to", "a", "redis", "instance", "." ]
train
https://github.com/Rafiot/PubSubLogger/blob/4f28ad673f42ee2ec7792d414d325aef9a56da53/pubsublogger/publisher.py#L35-L43
Rafiot/PubSubLogger
pubsublogger/publisher.py
log
def log(level, message): """ Publish `message` with the `level` the redis `channel`. :param level: the level of the message :param message: the message you want to log """ if redis_instance is None: __connect() if level not in __error_levels: raise InvalidErrorLevel('You ha...
python
def log(level, message): """ Publish `message` with the `level` the redis `channel`. :param level: the level of the message :param message: the message you want to log """ if redis_instance is None: __connect() if level not in __error_levels: raise InvalidErrorLevel('You ha...
[ "def", "log", "(", "level", ",", "message", ")", ":", "if", "redis_instance", "is", "None", ":", "__connect", "(", ")", "if", "level", "not", "in", "__error_levels", ":", "raise", "InvalidErrorLevel", "(", "'You have used an invalid error level. \\\n ...
Publish `message` with the `level` the redis `channel`. :param level: the level of the message :param message: the message you want to log
[ "Publish", "message", "with", "the", "level", "the", "redis", "channel", "." ]
train
https://github.com/Rafiot/PubSubLogger/blob/4f28ad673f42ee2ec7792d414d325aef9a56da53/pubsublogger/publisher.py#L46-L62
JNRowe/jnrbase
jnrbase/httplib2_certs.py
find_certs
def find_certs() -> str: """Find suitable certificates for ``httplib2``. Warning: The default behaviour is to fall back to the bundled certificates when no system certificates can be found. If you're packaging ``jnrbase`` *please* set ``ALLOW_FALLBACK`` to ``False`` to disable this ver...
python
def find_certs() -> str: """Find suitable certificates for ``httplib2``. Warning: The default behaviour is to fall back to the bundled certificates when no system certificates can be found. If you're packaging ``jnrbase`` *please* set ``ALLOW_FALLBACK`` to ``False`` to disable this ver...
[ "def", "find_certs", "(", ")", "->", "str", ":", "bundle", "=", "path", ".", "realpath", "(", "path", ".", "dirname", "(", "httplib2", ".", "CA_CERTS", ")", ")", "# Some distros symlink the bundled path location to the system certs", "if", "not", "bundle", ".", ...
Find suitable certificates for ``httplib2``. Warning: The default behaviour is to fall back to the bundled certificates when no system certificates can be found. If you're packaging ``jnrbase`` *please* set ``ALLOW_FALLBACK`` to ``False`` to disable this very much unwanted behaviou...
[ "Find", "suitable", "certificates", "for", "httplib2", "." ]
train
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/httplib2_certs.py#L41-L76
tBaxter/tango-articles
build/lib/articles/models.py
Article.get_absolute_url
def get_absolute_url(self): """ If override_url was given, use that. Otherwise, if the content belongs to a blog, use a blog url. If not, use a regular article url. """ if self.override_url: return self.override_url if self.destination.is_blog:...
python
def get_absolute_url(self): """ If override_url was given, use that. Otherwise, if the content belongs to a blog, use a blog url. If not, use a regular article url. """ if self.override_url: return self.override_url if self.destination.is_blog:...
[ "def", "get_absolute_url", "(", "self", ")", ":", "if", "self", ".", "override_url", ":", "return", "self", ".", "override_url", "if", "self", ".", "destination", ".", "is_blog", ":", "return", "reverse", "(", "'blog_entry_detail'", ",", "args", "=", "[", ...
If override_url was given, use that. Otherwise, if the content belongs to a blog, use a blog url. If not, use a regular article url.
[ "If", "override_url", "was", "given", "use", "that", ".", "Otherwise", "if", "the", "content", "belongs", "to", "a", "blog", "use", "a", "blog", "url", ".", "If", "not", "use", "a", "regular", "article", "url", "." ]
train
https://github.com/tBaxter/tango-articles/blob/93818dcca1b62042a4fc19af63474691b0fe931c/build/lib/articles/models.py#L183-L193
tBaxter/tango-articles
build/lib/articles/models.py
Article.save
def save(self, *args, **kwargs): """ Store summary if none was given and created formatted version of body text. """ if not self.summary: self.summary = truncatewords(self.body, 50) self.body_formatted = sanetize_text(self.body) super(Article, ...
python
def save(self, *args, **kwargs): """ Store summary if none was given and created formatted version of body text. """ if not self.summary: self.summary = truncatewords(self.body, 50) self.body_formatted = sanetize_text(self.body) super(Article, ...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "summary", ":", "self", ".", "summary", "=", "truncatewords", "(", "self", ".", "body", ",", "50", ")", "self", ".", "body_formatted", "=", ...
Store summary if none was given and created formatted version of body text.
[ "Store", "summary", "if", "none", "was", "given", "and", "created", "formatted", "version", "of", "body", "text", "." ]
train
https://github.com/tBaxter/tango-articles/blob/93818dcca1b62042a4fc19af63474691b0fe931c/build/lib/articles/models.py#L195-L203
tBaxter/tango-articles
build/lib/articles/models.py
Article.get_top_assets
def get_top_assets(self): """ Returns chained list of top assets (photos and video) for commonized templates. """ imgs = self.articleimage_set.all() try: vids = self.videos.all() except AttributeError: # handles case where videos are not in...
python
def get_top_assets(self): """ Returns chained list of top assets (photos and video) for commonized templates. """ imgs = self.articleimage_set.all() try: vids = self.videos.all() except AttributeError: # handles case where videos are not in...
[ "def", "get_top_assets", "(", "self", ")", ":", "imgs", "=", "self", ".", "articleimage_set", ".", "all", "(", ")", "try", ":", "vids", "=", "self", ".", "videos", ".", "all", "(", ")", "except", "AttributeError", ":", "# handles case where videos are not in...
Returns chained list of top assets (photos and video) for commonized templates.
[ "Returns", "chained", "list", "of", "top", "assets", "(", "photos", "and", "video", ")", "for", "commonized", "templates", "." ]
train
https://github.com/tBaxter/tango-articles/blob/93818dcca1b62042a4fc19af63474691b0fe931c/build/lib/articles/models.py#L205-L216
bsvetchine/django-payzen
django_payzen/models.py
PaymentRequest.set_vads_payment_config
def set_vads_payment_config(self): """ vads_payment_config can be set only after object saving. A custom payment config can be set once PaymentRequest saved (adding elements to the m2m relationship). As a consequence we set vads_payment_config just before sending data elements ...
python
def set_vads_payment_config(self): """ vads_payment_config can be set only after object saving. A custom payment config can be set once PaymentRequest saved (adding elements to the m2m relationship). As a consequence we set vads_payment_config just before sending data elements ...
[ "def", "set_vads_payment_config", "(", "self", ")", ":", "self", ".", "vads_payment_config", "=", "tools", ".", "get_vads_payment_config", "(", "self", ".", "payment_config", ",", "self", ".", "custom_payment_config", ".", "all", "(", ")", ")" ]
vads_payment_config can be set only after object saving. A custom payment config can be set once PaymentRequest saved (adding elements to the m2m relationship). As a consequence we set vads_payment_config just before sending data elements to payzen.
[ "vads_payment_config", "can", "be", "set", "only", "after", "object", "saving", "." ]
train
https://github.com/bsvetchine/django-payzen/blob/944c3026120151495310cb1eb3c6370dc2db3db9/django_payzen/models.py#L407-L416
bsvetchine/django-payzen
django_payzen/models.py
PaymentRequest.save
def save(self): """ We set up vads_trans_id and theme according to payzen format. If fields values are explicitely set by user, we do not override their values. """ if not self.vads_trans_date: self.vads_trans_date = datetime.datetime.utcnow().replace( ...
python
def save(self): """ We set up vads_trans_id and theme according to payzen format. If fields values are explicitely set by user, we do not override their values. """ if not self.vads_trans_date: self.vads_trans_date = datetime.datetime.utcnow().replace( ...
[ "def", "save", "(", "self", ")", ":", "if", "not", "self", ".", "vads_trans_date", ":", "self", ".", "vads_trans_date", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "tzinfo", "=", "utc", ")", ".", "strftime", "(", "...
We set up vads_trans_id and theme according to payzen format. If fields values are explicitely set by user, we do not override their values.
[ "We", "set", "up", "vads_trans_id", "and", "theme", "according", "to", "payzen", "format", "." ]
train
https://github.com/bsvetchine/django-payzen/blob/944c3026120151495310cb1eb3c6370dc2db3db9/django_payzen/models.py#L435-L454
casebeer/factual
factual/v2/responses.py
V2ReadResponse.records
def records(self): '''Return a list of dicts corresponding to the data returned by Factual.''' if self._records == None: self._records = self._get_records() return self._records
python
def records(self): '''Return a list of dicts corresponding to the data returned by Factual.''' if self._records == None: self._records = self._get_records() return self._records
[ "def", "records", "(", "self", ")", ":", "if", "self", ".", "_records", "==", "None", ":", "self", ".", "_records", "=", "self", ".", "_get_records", "(", ")", "return", "self", ".", "_records" ]
Return a list of dicts corresponding to the data returned by Factual.
[ "Return", "a", "list", "of", "dicts", "corresponding", "to", "the", "data", "returned", "by", "Factual", "." ]
train
https://github.com/casebeer/factual/blob/f2795a8c9fd447c5d62887ae0f960481ce13be84/factual/v2/responses.py#L20-L24
Fuyukai/ConfigMaster
configmaster/ConfigGenerator.py
GenerateConfigFile
def GenerateConfigFile(load_hook, dump_hook, **kwargs) -> ConfigFile: """ Generates a ConfigFile object using the specified hooks. These hooks should be functions, and have one argument. When a hook is called, the ConfigFile object is passed to it. Use this to load your data from the fd object, or requ...
python
def GenerateConfigFile(load_hook, dump_hook, **kwargs) -> ConfigFile: """ Generates a ConfigFile object using the specified hooks. These hooks should be functions, and have one argument. When a hook is called, the ConfigFile object is passed to it. Use this to load your data from the fd object, or requ...
[ "def", "GenerateConfigFile", "(", "load_hook", ",", "dump_hook", ",", "*", "*", "kwargs", ")", "->", "ConfigFile", ":", "def", "ConfigFileGenerator", "(", "filename", ",", "safe_load", ":", "bool", "=", "True", ")", ":", "cfg", "=", "ConfigFile", "(", "fd"...
Generates a ConfigFile object using the specified hooks. These hooks should be functions, and have one argument. When a hook is called, the ConfigFile object is passed to it. Use this to load your data from the fd object, or request, or whatever. This returns a ConfigFile object.
[ "Generates", "a", "ConfigFile", "object", "using", "the", "specified", "hooks", "." ]
train
https://github.com/Fuyukai/ConfigMaster/blob/8018aa415da55c84edaa8a49664f674758a14edd/configmaster/ConfigGenerator.py#L3-L16
Fuyukai/ConfigMaster
configmaster/ConfigGenerator.py
GenerateNetworkedConfigFile
def GenerateNetworkedConfigFile(load_hook, normal_class_load_hook, normal_class_dump_hook, **kwargs) -> NetworkedConfigObject: """ Generates a NetworkedConfigObject using the specified hooks. """ def NetworkedConfigObjectGenerator(url, safe_load: bool=True): cfg = NetworkedConfigObject(url=url, ...
python
def GenerateNetworkedConfigFile(load_hook, normal_class_load_hook, normal_class_dump_hook, **kwargs) -> NetworkedConfigObject: """ Generates a NetworkedConfigObject using the specified hooks. """ def NetworkedConfigObjectGenerator(url, safe_load: bool=True): cfg = NetworkedConfigObject(url=url, ...
[ "def", "GenerateNetworkedConfigFile", "(", "load_hook", ",", "normal_class_load_hook", ",", "normal_class_dump_hook", ",", "*", "*", "kwargs", ")", "->", "NetworkedConfigObject", ":", "def", "NetworkedConfigObjectGenerator", "(", "url", ",", "safe_load", ":", "bool", ...
Generates a NetworkedConfigObject using the specified hooks.
[ "Generates", "a", "NetworkedConfigObject", "using", "the", "specified", "hooks", "." ]
train
https://github.com/Fuyukai/ConfigMaster/blob/8018aa415da55c84edaa8a49664f674758a14edd/configmaster/ConfigGenerator.py#L18-L28
Meseira/subordinate
subordinate/idrangeset.py
IdRangeSet.append
def append(self, first, count): """ Add to the set a range of count consecutive ids starting at id first. """ self.__range.append(IdRange(first, count))
python
def append(self, first, count): """ Add to the set a range of count consecutive ids starting at id first. """ self.__range.append(IdRange(first, count))
[ "def", "append", "(", "self", ",", "first", ",", "count", ")", ":", "self", ".", "__range", ".", "append", "(", "IdRange", "(", "first", ",", "count", ")", ")" ]
Add to the set a range of count consecutive ids starting at id first.
[ "Add", "to", "the", "set", "a", "range", "of", "count", "consecutive", "ids", "starting", "at", "id", "first", "." ]
train
https://github.com/Meseira/subordinate/blob/3438df304af3dccc5bd1515231402afa708f1cc3/subordinate/idrangeset.py#L90-L96
Meseira/subordinate
subordinate/idrangeset.py
IdRangeSet.remove
def remove(self, first, count): """ Remove a range of count consecutive ids starting at id first from all the ranges in the set. """ # Avoid trivialities if first < 0 or count < 1: return new_range = [] last = first + count - 1 for r ...
python
def remove(self, first, count): """ Remove a range of count consecutive ids starting at id first from all the ranges in the set. """ # Avoid trivialities if first < 0 or count < 1: return new_range = [] last = first + count - 1 for r ...
[ "def", "remove", "(", "self", ",", "first", ",", "count", ")", ":", "# Avoid trivialities", "if", "first", "<", "0", "or", "count", "<", "1", ":", "return", "new_range", "=", "[", "]", "last", "=", "first", "+", "count", "-", "1", "for", "r", "in",...
Remove a range of count consecutive ids starting at id first from all the ranges in the set.
[ "Remove", "a", "range", "of", "count", "consecutive", "ids", "starting", "at", "id", "first", "from", "all", "the", "ranges", "in", "the", "set", "." ]
train
https://github.com/Meseira/subordinate/blob/3438df304af3dccc5bd1515231402afa708f1cc3/subordinate/idrangeset.py#L103-L126
Meseira/subordinate
subordinate/idrangeset.py
IdRangeSet.simplify
def simplify(self): """ Reorganize the ranges in the set in order to ensure that each range is unique and that there is not overlap between to ranges. """ # Sort the ranges self.__range.sort() new_range = [] new_first = self.__range[0].first new_...
python
def simplify(self): """ Reorganize the ranges in the set in order to ensure that each range is unique and that there is not overlap between to ranges. """ # Sort the ranges self.__range.sort() new_range = [] new_first = self.__range[0].first new_...
[ "def", "simplify", "(", "self", ")", ":", "# Sort the ranges", "self", ".", "__range", ".", "sort", "(", ")", "new_range", "=", "[", "]", "new_first", "=", "self", ".", "__range", "[", "0", "]", ".", "first", "new_count", "=", "self", ".", "__range", ...
Reorganize the ranges in the set in order to ensure that each range is unique and that there is not overlap between to ranges.
[ "Reorganize", "the", "ranges", "in", "the", "set", "in", "order", "to", "ensure", "that", "each", "range", "is", "unique", "and", "that", "there", "is", "not", "overlap", "between", "to", "ranges", "." ]
train
https://github.com/Meseira/subordinate/blob/3438df304af3dccc5bd1515231402afa708f1cc3/subordinate/idrangeset.py#L128-L159
listen-lavender/webcrawl
webcrawl/urlkit.py
urljoin
def urljoin(refurl, objurl): """ >>> urljoin('http://www.homeinns.com/hotel', 'http://www.homeinns.com/beijing') 'http://www.homeinns.com/beijing' >>> urljoin('http://www.homeinns.com/hotel', '/beijing') 'http://www.homeinns.com/beijing' >>> urljoin('http://www.homeinns.com/hotel', 'beijing') ...
python
def urljoin(refurl, objurl): """ >>> urljoin('http://www.homeinns.com/hotel', 'http://www.homeinns.com/beijing') 'http://www.homeinns.com/beijing' >>> urljoin('http://www.homeinns.com/hotel', '/beijing') 'http://www.homeinns.com/beijing' >>> urljoin('http://www.homeinns.com/hotel', 'beijing') ...
[ "def", "urljoin", "(", "refurl", ",", "objurl", ")", ":", "if", "objurl", ".", "strip", "(", ")", "in", "(", "''", ",", "'#'", ")", ":", "return", "''", "elif", "objurl", ".", "startswith", "(", "'http'", ")", ":", "return", "objurl", "elif", "obju...
>>> urljoin('http://www.homeinns.com/hotel', 'http://www.homeinns.com/beijing') 'http://www.homeinns.com/beijing' >>> urljoin('http://www.homeinns.com/hotel', '/beijing') 'http://www.homeinns.com/beijing' >>> urljoin('http://www.homeinns.com/hotel', 'beijing') 'http://www.homeinns.com/beijing'
[ ">>>", "urljoin", "(", "http", ":", "//", "www", ".", "homeinns", ".", "com", "/", "hotel", "http", ":", "//", "www", ".", "homeinns", ".", "com", "/", "beijing", ")", "http", ":", "//", "www", ".", "homeinns", ".", "com", "/", "beijing", ">>>", ...
train
https://github.com/listen-lavender/webcrawl/blob/905dcfa6e6934aac764045660c0efcef28eae1e6/webcrawl/urlkit.py#L12-L29
wtsi-hgi/python-baton-wrapper
baton/_baton/baton_access_control_mappers.py
BatonCollectionAccessControlMapper._do_recursive
def _do_recursive(self, method_that_runs_baton_chmod: callable, *args, **kwargs): """ Adds the `--recursive` argument to all calls to `baton-chmod`. :param method_that_runs_baton_chmod: the method that, at a lower level, calls out to baton-chmod :param args: positional arguments to call ...
python
def _do_recursive(self, method_that_runs_baton_chmod: callable, *args, **kwargs): """ Adds the `--recursive` argument to all calls to `baton-chmod`. :param method_that_runs_baton_chmod: the method that, at a lower level, calls out to baton-chmod :param args: positional arguments to call ...
[ "def", "_do_recursive", "(", "self", ",", "method_that_runs_baton_chmod", ":", "callable", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "current_frame_id", "=", "id", "(", "inspect", ".", "currentframe", "(", ")", ")", "try", ":", "self", ".", "_...
Adds the `--recursive` argument to all calls to `baton-chmod`. :param method_that_runs_baton_chmod: the method that, at a lower level, calls out to baton-chmod :param args: positional arguments to call given method with :param kwargs: named arguments to call given method with
[ "Adds", "the", "--", "recursive", "argument", "to", "all", "calls", "to", "baton", "-", "chmod", ".", ":", "param", "method_that_runs_baton_chmod", ":", "the", "method", "that", "at", "a", "lower", "level", "calls", "out", "to", "baton", "-", "chmod", ":",...
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/_baton/baton_access_control_mappers.py#L194-L206
wtsi-hgi/python-baton-wrapper
baton/_baton/baton_access_control_mappers.py
BatonCollectionAccessControlMapper._hijacked_run_baton_query
def _hijacked_run_baton_query( self, baton_binary: BatonBinary, program_arguments: List[str]=None, input_data: Any=None) -> List[Dict]: """ Hijacked `run_baton_query` method with hijacking to add the `--recursive` flag to calls to `baton-chmod` that originate from code called from fr...
python
def _hijacked_run_baton_query( self, baton_binary: BatonBinary, program_arguments: List[str]=None, input_data: Any=None) -> List[Dict]: """ Hijacked `run_baton_query` method with hijacking to add the `--recursive` flag to calls to `baton-chmod` that originate from code called from fr...
[ "def", "_hijacked_run_baton_query", "(", "self", ",", "baton_binary", ":", "BatonBinary", ",", "program_arguments", ":", "List", "[", "str", "]", "=", "None", ",", "input_data", ":", "Any", "=", "None", ")", "->", "List", "[", "Dict", "]", ":", "if", "ba...
Hijacked `run_baton_query` method with hijacking to add the `--recursive` flag to calls to `baton-chmod` that originate from code called from frames with the ids in `self._hijack_frame_ids`. :param baton_binary: see `BatonRunner.run_baton_query` :param program_arguments: see `BatonRunner.run_bat...
[ "Hijacked", "run_baton_query", "method", "with", "hijacking", "to", "add", "the", "--", "recursive", "flag", "to", "calls", "to", "baton", "-", "chmod", "that", "originate", "from", "code", "called", "from", "frames", "with", "the", "ids", "in", "self", ".",...
train
https://github.com/wtsi-hgi/python-baton-wrapper/blob/ae0c9e3630e2c4729a0614cc86f493688436b0b7/baton/_baton/baton_access_control_mappers.py#L208-L232
scivision/histutils
histutils/simulFrame.py
HSTsync
def HSTsync(sim, cam, verbose): """ this function now uses UT1 time -- seconds since 1970 Jan 1 """ try: if isinstance(sim.startutc, datetime): reqStart = sim.startutc.timestamp() reqStop = sim.stoputc.timestamp() elif isinstance(sim.startutc, (float, int)): # ut1_un...
python
def HSTsync(sim, cam, verbose): """ this function now uses UT1 time -- seconds since 1970 Jan 1 """ try: if isinstance(sim.startutc, datetime): reqStart = sim.startutc.timestamp() reqStop = sim.stoputc.timestamp() elif isinstance(sim.startutc, (float, int)): # ut1_un...
[ "def", "HSTsync", "(", "sim", ",", "cam", ",", "verbose", ")", ":", "try", ":", "if", "isinstance", "(", "sim", ".", "startutc", ",", "datetime", ")", ":", "reqStart", "=", "sim", ".", "startutc", ".", "timestamp", "(", ")", "reqStop", "=", "sim", ...
this function now uses UT1 time -- seconds since 1970 Jan 1
[ "this", "function", "now", "uses", "UT1", "time", "--", "seconds", "since", "1970", "Jan", "1" ]
train
https://github.com/scivision/histutils/blob/859a91d3894cb57faed34881c6ea16130b90571e/histutils/simulFrame.py#L26-L103
fixmydjango/fixmydjango-lib
fixmydjango/__init__.py
ExceptionReporterPatch._get_fix_my_django_submission_url
def _get_fix_my_django_submission_url(self, tb_info, sanitized_tb): """ Links to the error submission url with pre filled fields """ err_post_create_path = '/create/' url = '{0}{1}'.format(base_url, err_post_create_path) return '{url}?{query}'.format( url=url,...
python
def _get_fix_my_django_submission_url(self, tb_info, sanitized_tb): """ Links to the error submission url with pre filled fields """ err_post_create_path = '/create/' url = '{0}{1}'.format(base_url, err_post_create_path) return '{url}?{query}'.format( url=url,...
[ "def", "_get_fix_my_django_submission_url", "(", "self", ",", "tb_info", ",", "sanitized_tb", ")", ":", "err_post_create_path", "=", "'/create/'", "url", "=", "'{0}{1}'", ".", "format", "(", "base_url", ",", "err_post_create_path", ")", "return", "'{url}?{query}'", ...
Links to the error submission url with pre filled fields
[ "Links", "to", "the", "error", "submission", "url", "with", "pre", "filled", "fields" ]
train
https://github.com/fixmydjango/fixmydjango-lib/blob/5402e9cb15d85daa68bb5f2418ff9c4ea966d306/fixmydjango/__init__.py#L62-L75
Apitax/Apitax
apitax/api/controllers/migrations/users_controller.py
endpoint_catalog
def endpoint_catalog(catalog=None): # noqa: E501 """Retrieve the endpoint catalog Retrieve the endpoint catalog # noqa: E501 :param catalog: The data needed to get a catalog :type catalog: dict | bytes :rtype: Response """ if connexion.request.is_json: catalog = UserAuth.from_dic...
python
def endpoint_catalog(catalog=None): # noqa: E501 """Retrieve the endpoint catalog Retrieve the endpoint catalog # noqa: E501 :param catalog: The data needed to get a catalog :type catalog: dict | bytes :rtype: Response """ if connexion.request.is_json: catalog = UserAuth.from_dic...
[ "def", "endpoint_catalog", "(", "catalog", "=", "None", ")", ":", "# noqa: E501", "if", "connexion", ".", "request", ".", "is_json", ":", "catalog", "=", "UserAuth", ".", "from_dict", "(", "connexion", ".", "request", ".", "get_json", "(", ")", ")", "# noq...
Retrieve the endpoint catalog Retrieve the endpoint catalog # noqa: E501 :param catalog: The data needed to get a catalog :type catalog: dict | bytes :rtype: Response
[ "Retrieve", "the", "endpoint", "catalog" ]
train
https://github.com/Apitax/Apitax/blob/3883e45f17e01eba4edac9d1bba42f0e7a748682/apitax/api/controllers/migrations/users_controller.py#L109-L129
Apitax/Apitax
apitax/api/controllers/migrations/users_controller.py
script_catalog
def script_catalog(): # noqa: E501 """Retrieve the script catalog Retrieve the script catalog # noqa: E501 :rtype: Response """ if (not hasAccess()): return redirectUnauthorized() driver = LoadedDrivers.getDefaultDriver() return Response(status=200, body=driver.getScriptsCatalog...
python
def script_catalog(): # noqa: E501 """Retrieve the script catalog Retrieve the script catalog # noqa: E501 :rtype: Response """ if (not hasAccess()): return redirectUnauthorized() driver = LoadedDrivers.getDefaultDriver() return Response(status=200, body=driver.getScriptsCatalog...
[ "def", "script_catalog", "(", ")", ":", "# noqa: E501", "if", "(", "not", "hasAccess", "(", ")", ")", ":", "return", "redirectUnauthorized", "(", ")", "driver", "=", "LoadedDrivers", ".", "getDefaultDriver", "(", ")", "return", "Response", "(", "status", "="...
Retrieve the script catalog Retrieve the script catalog # noqa: E501 :rtype: Response
[ "Retrieve", "the", "script", "catalog" ]
train
https://github.com/Apitax/Apitax/blob/3883e45f17e01eba4edac9d1bba42f0e7a748682/apitax/api/controllers/migrations/users_controller.py#L152-L164
sbuss/pypercube
pypercube/cube.py
Cube.get_base_url
def get_base_url(self): """ >>> c = Cube('cube.mydomain.com') >>> print(c.get_base_url()) http://cube.mydomain.com:1081/1.0 """ return "http://{hostname}:{port}/{api}".format( hostname=self.hostname, port=self.port, api=self...
python
def get_base_url(self): """ >>> c = Cube('cube.mydomain.com') >>> print(c.get_base_url()) http://cube.mydomain.com:1081/1.0 """ return "http://{hostname}:{port}/{api}".format( hostname=self.hostname, port=self.port, api=self...
[ "def", "get_base_url", "(", "self", ")", ":", "return", "\"http://{hostname}:{port}/{api}\"", ".", "format", "(", "hostname", "=", "self", ".", "hostname", ",", "port", "=", "self", ".", "port", ",", "api", "=", "self", ".", "api_version", ")" ]
>>> c = Cube('cube.mydomain.com') >>> print(c.get_base_url()) http://cube.mydomain.com:1081/1.0
[ ">>>", "c", "=", "Cube", "(", "cube", ".", "mydomain", ".", "com", ")", ">>>", "print", "(", "c", ".", "get_base_url", "()", ")", "http", ":", "//", "cube", ".", "mydomain", ".", "com", ":", "1081", "/", "1", ".", "0" ]
train
https://github.com/sbuss/pypercube/blob/e9d2cca9c004b8bad6d1e0b68b080f887a186a22/pypercube/cube.py#L15-L24
iamFIREcracker/aadbook
aadbook/config.py
read_config
def read_config(config_file): '''Reads the ~/.aadbookrc and any authentication data returns the configuration as a dictionary. ''' config = Storage({ # Default values 'cache_filename': '~/.aadbook_cache', 'auth_db_filename': '~/.aadbook_auth.json', 'cache_expiry_hours': '24'}) ...
python
def read_config(config_file): '''Reads the ~/.aadbookrc and any authentication data returns the configuration as a dictionary. ''' config = Storage({ # Default values 'cache_filename': '~/.aadbook_cache', 'auth_db_filename': '~/.aadbook_auth.json', 'cache_expiry_hours': '24'}) ...
[ "def", "read_config", "(", "config_file", ")", ":", "config", "=", "Storage", "(", "{", "# Default values", "'cache_filename'", ":", "'~/.aadbook_cache'", ",", "'auth_db_filename'", ":", "'~/.aadbook_auth.json'", ",", "'cache_expiry_hours'", ":", "'24'", "}", ")", "...
Reads the ~/.aadbookrc and any authentication data returns the configuration as a dictionary.
[ "Reads", "the", "~", "/", ".", "aadbookrc", "and", "any", "authentication", "data", "returns", "the", "configuration", "as", "a", "dictionary", "." ]
train
https://github.com/iamFIREcracker/aadbook/blob/d191e9d36a2309449ab91c1728eaf5901b7ef91c/aadbook/config.py#L37-L62
iamFIREcracker/aadbook
aadbook/config.py
_get_config
def _get_config(config_file): '''find, read and parse configuraton.''' parser = ConfigParser.SafeConfigParser() if os.path.lexists(config_file): try: log.info('Reading config: %s', config_file) inp = open(config_file) parser.readfp(inp) return parser ...
python
def _get_config(config_file): '''find, read and parse configuraton.''' parser = ConfigParser.SafeConfigParser() if os.path.lexists(config_file): try: log.info('Reading config: %s', config_file) inp = open(config_file) parser.readfp(inp) return parser ...
[ "def", "_get_config", "(", "config_file", ")", ":", "parser", "=", "ConfigParser", ".", "SafeConfigParser", "(", ")", "if", "os", ".", "path", ".", "lexists", "(", "config_file", ")", ":", "try", ":", "log", ".", "info", "(", "'Reading config: %s'", ",", ...
find, read and parse configuraton.
[ "find", "read", "and", "parse", "configuraton", "." ]
train
https://github.com/iamFIREcracker/aadbook/blob/d191e9d36a2309449ab91c1728eaf5901b7ef91c/aadbook/config.py#L65-L76
bretth/djset
djset/utils.py
getbool
def getbool(key, default=False): """ Returns True or False for any TRUE, FALSE, 0, or 1. Other values return default. """ value = os.getenv(key) if value and value.lower() in ('true', '1'): value = True elif value and value.lower() in ('false', '0'): value = False else: ...
python
def getbool(key, default=False): """ Returns True or False for any TRUE, FALSE, 0, or 1. Other values return default. """ value = os.getenv(key) if value and value.lower() in ('true', '1'): value = True elif value and value.lower() in ('false', '0'): value = False else: ...
[ "def", "getbool", "(", "key", ",", "default", "=", "False", ")", ":", "value", "=", "os", ".", "getenv", "(", "key", ")", "if", "value", "and", "value", ".", "lower", "(", ")", "in", "(", "'true'", ",", "'1'", ")", ":", "value", "=", "True", "e...
Returns True or False for any TRUE, FALSE, 0, or 1. Other values return default.
[ "Returns", "True", "or", "False", "for", "any", "TRUE", "FALSE", "0", "or", "1", ".", "Other", "values", "return", "default", "." ]
train
https://github.com/bretth/djset/blob/e04cbcadc311f6edec50a718415d0004aa304034/djset/utils.py#L4-L16
bretth/djset
djset/utils.py
_locate_settings
def _locate_settings(settings=''): "Return the path to the DJANGO_SETTINGS_MODULE" import imp import sys sys.path.append(os.getcwd()) settings = settings or os.getenv('DJANGO_SETTINGS_MODULE') if settings: parts = settings.split('.') f = imp.find_module(parts[0])[1] args...
python
def _locate_settings(settings=''): "Return the path to the DJANGO_SETTINGS_MODULE" import imp import sys sys.path.append(os.getcwd()) settings = settings or os.getenv('DJANGO_SETTINGS_MODULE') if settings: parts = settings.split('.') f = imp.find_module(parts[0])[1] args...
[ "def", "_locate_settings", "(", "settings", "=", "''", ")", ":", "import", "imp", "import", "sys", "sys", ".", "path", ".", "append", "(", "os", ".", "getcwd", "(", ")", ")", "settings", "=", "settings", "or", "os", ".", "getenv", "(", "'DJANGO_SETTING...
Return the path to the DJANGO_SETTINGS_MODULE
[ "Return", "the", "path", "to", "the", "DJANGO_SETTINGS_MODULE" ]
train
https://github.com/bretth/djset/blob/e04cbcadc311f6edec50a718415d0004aa304034/djset/utils.py#L19-L33
saltzm/yadi
yadi/datalog2sql/ast2sql/sql_generator.py
ConjunctiveQuerySQLGenerator.get_from_relations
def get_from_relations(self, query,aliases): ''' Returns list of the names of all positive relations in the query ''' return [aliases[rel.get_name()] for rel in query.get_relations() if not rel.is_negated()]
python
def get_from_relations(self, query,aliases): ''' Returns list of the names of all positive relations in the query ''' return [aliases[rel.get_name()] for rel in query.get_relations() if not rel.is_negated()]
[ "def", "get_from_relations", "(", "self", ",", "query", ",", "aliases", ")", ":", "return", "[", "aliases", "[", "rel", ".", "get_name", "(", ")", "]", "for", "rel", "in", "query", ".", "get_relations", "(", ")", "if", "not", "rel", ".", "is_negated", ...
Returns list of the names of all positive relations in the query
[ "Returns", "list", "of", "the", "names", "of", "all", "positive", "relations", "in", "the", "query" ]
train
https://github.com/saltzm/yadi/blob/755790167c350e650c1e8b15c6f9209a97be9e42/yadi/datalog2sql/ast2sql/sql_generator.py#L181-L185
saltzm/yadi
yadi/datalog2sql/ast2sql/sql_generator.py
ConjunctiveQuerySQLGenerator.get_implicit_constraints
def get_implicit_constraints(self,relations): ''' An implicit constraint is one in which you are unifying a constant to a position of the relation E.G. R(X,2) specifies that R.2 == 2''' constraints = [] for relation in [r for r in relations if not r.is_negated()] : cons...
python
def get_implicit_constraints(self,relations): ''' An implicit constraint is one in which you are unifying a constant to a position of the relation E.G. R(X,2) specifies that R.2 == 2''' constraints = [] for relation in [r for r in relations if not r.is_negated()] : cons...
[ "def", "get_implicit_constraints", "(", "self", ",", "relations", ")", ":", "constraints", "=", "[", "]", "for", "relation", "in", "[", "r", "for", "r", "in", "relations", "if", "not", "r", ".", "is_negated", "(", ")", "]", ":", "const_dict", "=", "rel...
An implicit constraint is one in which you are unifying a constant to a position of the relation E.G. R(X,2) specifies that R.2 == 2
[ "An", "implicit", "constraint", "is", "one", "in", "which", "you", "are", "unifying", "a", "constant", "to", "a", "position", "of", "the", "relation", "E", ".", "G", ".", "R", "(", "X", "2", ")", "specifies", "that", "R", ".", "2", "==", "2" ]
train
https://github.com/saltzm/yadi/blob/755790167c350e650c1e8b15c6f9209a97be9e42/yadi/datalog2sql/ast2sql/sql_generator.py#L220-L232
saltzm/yadi
yadi/datalog2sql/ast2sql/sql_generator.py
ConjunctiveQuerySQLGenerator.get_explicit_constraints
def get_explicit_constraints(self,constraints,var_dict): ''' Returns SQL representation of an explicit constraint. An explicit constraint is one of the form Element COMP Element type, explicitly listed in the conjunctive query. E.G. R(X,Y), Y>2 specifies that R.2 > 2 ''' ...
python
def get_explicit_constraints(self,constraints,var_dict): ''' Returns SQL representation of an explicit constraint. An explicit constraint is one of the form Element COMP Element type, explicitly listed in the conjunctive query. E.G. R(X,Y), Y>2 specifies that R.2 > 2 ''' ...
[ "def", "get_explicit_constraints", "(", "self", ",", "constraints", ",", "var_dict", ")", ":", "constraints_strings", "=", "[", "]", "for", "constraint", "in", "constraints", ":", "ls", "=", "constraint", ".", "get_left_side", "(", ")", "rs", "=", "constraint"...
Returns SQL representation of an explicit constraint. An explicit constraint is one of the form Element COMP Element type, explicitly listed in the conjunctive query. E.G. R(X,Y), Y>2 specifies that R.2 > 2
[ "Returns", "SQL", "representation", "of", "an", "explicit", "constraint", ".", "An", "explicit", "constraint", "is", "one", "of", "the", "form", "Element", "COMP", "Element", "type", "explicitly", "listed", "in", "the", "conjunctive", "query", ".", "E", ".", ...
train
https://github.com/saltzm/yadi/blob/755790167c350e650c1e8b15c6f9209a97be9e42/yadi/datalog2sql/ast2sql/sql_generator.py#L234-L264
gear11/pypelogs
pypein/flickr.py
Flickr.photo
def photo(self, args): """ Retrieves metadata for a specific photo. flickr:(credsfile),photo,(photo_id) """ rsp = self._load_rsp(self.flickr.photos_getInfo(photo_id=args[0])) p = rsp['photo'] yield self._prep(p)
python
def photo(self, args): """ Retrieves metadata for a specific photo. flickr:(credsfile),photo,(photo_id) """ rsp = self._load_rsp(self.flickr.photos_getInfo(photo_id=args[0])) p = rsp['photo'] yield self._prep(p)
[ "def", "photo", "(", "self", ",", "args", ")", ":", "rsp", "=", "self", ".", "_load_rsp", "(", "self", ".", "flickr", ".", "photos_getInfo", "(", "photo_id", "=", "args", "[", "0", "]", ")", ")", "p", "=", "rsp", "[", "'photo'", "]", "yield", "se...
Retrieves metadata for a specific photo. flickr:(credsfile),photo,(photo_id)
[ "Retrieves", "metadata", "for", "a", "specific", "photo", "." ]
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L58-L66
gear11/pypelogs
pypein/flickr.py
Flickr.search
def search(self, args): """ Executes a search flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)... """ kwargs = {} for a in args: k, v = a.split('=') kwargs[k] = v return self._paged_api_call(self.flickr.photos_search, kwargs)
python
def search(self, args): """ Executes a search flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)... """ kwargs = {} for a in args: k, v = a.split('=') kwargs[k] = v return self._paged_api_call(self.flickr.photos_search, kwargs)
[ "def", "search", "(", "self", ",", "args", ")", ":", "kwargs", "=", "{", "}", "for", "a", "in", "args", ":", "k", ",", "v", "=", "a", ".", "split", "(", "'='", ")", "kwargs", "[", "k", "]", "=", "v", "return", "self", ".", "_paged_api_call", ...
Executes a search flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)...
[ "Executes", "a", "search" ]
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L68-L78
gear11/pypelogs
pypein/flickr.py
Flickr.interesting
def interesting(self, args=None): """ Gets interesting photos. flickr:(credsfile),interesting """ kwargs = {'extras': ','.join(args) if args else 'last_update,geo,owner_name,url_sq'} return self._paged_api_call(self.flickr.interestingness_getList, kwargs)
python
def interesting(self, args=None): """ Gets interesting photos. flickr:(credsfile),interesting """ kwargs = {'extras': ','.join(args) if args else 'last_update,geo,owner_name,url_sq'} return self._paged_api_call(self.flickr.interestingness_getList, kwargs)
[ "def", "interesting", "(", "self", ",", "args", "=", "None", ")", ":", "kwargs", "=", "{", "'extras'", ":", "','", ".", "join", "(", "args", ")", "if", "args", "else", "'last_update,geo,owner_name,url_sq'", "}", "return", "self", ".", "_paged_api_call", "(...
Gets interesting photos. flickr:(credsfile),interesting
[ "Gets", "interesting", "photos", "." ]
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L80-L88
gear11/pypelogs
pypein/flickr.py
Flickr.search_groups
def search_groups(self, args): """ Executes a search flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)... """ kwargs = {'text': args[0]} return self._paged_api_call(self.flickr.groups_search, kwargs, 'group')
python
def search_groups(self, args): """ Executes a search flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)... """ kwargs = {'text': args[0]} return self._paged_api_call(self.flickr.groups_search, kwargs, 'group')
[ "def", "search_groups", "(", "self", ",", "args", ")", ":", "kwargs", "=", "{", "'text'", ":", "args", "[", "0", "]", "}", "return", "self", ".", "_paged_api_call", "(", "self", ".", "flickr", ".", "groups_search", ",", "kwargs", ",", "'group'", ")" ]
Executes a search flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)...
[ "Executes", "a", "search" ]
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L90-L97
gear11/pypelogs
pypein/flickr.py
Flickr.group
def group(self, args): """ Executes a search flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)... """ kwargs = {'group_id': args[0]} return self._paged_api_call(self.flickr.groups_pools_getPhotos, kwargs)
python
def group(self, args): """ Executes a search flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)... """ kwargs = {'group_id': args[0]} return self._paged_api_call(self.flickr.groups_pools_getPhotos, kwargs)
[ "def", "group", "(", "self", ",", "args", ")", ":", "kwargs", "=", "{", "'group_id'", ":", "args", "[", "0", "]", "}", "return", "self", ".", "_paged_api_call", "(", "self", ".", "flickr", ".", "groups_pools_getPhotos", ",", "kwargs", ")" ]
Executes a search flickr:(credsfile),search,(arg1)=(val1),(arg2)=(val2)...
[ "Executes", "a", "search" ]
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L99-L106
gear11/pypelogs
pypein/flickr.py
Flickr._paged_api_call
def _paged_api_call(self, func, kwargs, item_type='photo'): """ Takes a Flickr API function object and dict of keyword args and calls the API call repeatedly with an incrementing page value until all contents are exhausted. Flickr seems to limit to about 500 items. """ pa...
python
def _paged_api_call(self, func, kwargs, item_type='photo'): """ Takes a Flickr API function object and dict of keyword args and calls the API call repeatedly with an incrementing page value until all contents are exhausted. Flickr seems to limit to about 500 items. """ pa...
[ "def", "_paged_api_call", "(", "self", ",", "func", ",", "kwargs", ",", "item_type", "=", "'photo'", ")", ":", "page", "=", "1", "while", "True", ":", "LOG", ".", "info", "(", "\"Fetching page %s\"", "%", "page", ")", "kwargs", "[", "'page'", "]", "=",...
Takes a Flickr API function object and dict of keyword args and calls the API call repeatedly with an incrementing page value until all contents are exhausted. Flickr seems to limit to about 500 items.
[ "Takes", "a", "Flickr", "API", "function", "object", "and", "dict", "of", "keyword", "args", "and", "calls", "the", "API", "call", "repeatedly", "with", "an", "incrementing", "page", "value", "until", "all", "contents", "are", "exhausted", ".", "Flickr", "se...
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L108-L133
gear11/pypelogs
pypein/flickr.py
Flickr._prep
def _prep(e): """ Normalizes lastupdate to a timestamp, and constructs a URL from the embedded attributes. """ if 'lastupdate' in e: e['lastupdate'] = datetime.datetime.fromtimestamp(int(e['lastupdate'])) for k in ['farm', 'server', 'id', 'secret']: if not...
python
def _prep(e): """ Normalizes lastupdate to a timestamp, and constructs a URL from the embedded attributes. """ if 'lastupdate' in e: e['lastupdate'] = datetime.datetime.fromtimestamp(int(e['lastupdate'])) for k in ['farm', 'server', 'id', 'secret']: if not...
[ "def", "_prep", "(", "e", ")", ":", "if", "'lastupdate'", "in", "e", ":", "e", "[", "'lastupdate'", "]", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "int", "(", "e", "[", "'lastupdate'", "]", ")", ")", "for", "k", "in", "[", "'farm...
Normalizes lastupdate to a timestamp, and constructs a URL from the embedded attributes.
[ "Normalizes", "lastupdate", "to", "a", "timestamp", "and", "constructs", "a", "URL", "from", "the", "embedded", "attributes", "." ]
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L136-L146
gear11/pypelogs
pypein/flickr.py
Flickr._load_rsp
def _load_rsp(rsp): """ Converts raw Flickr string response to Python dict """ first = rsp.find('(') + 1 last = rsp.rfind(')') return json.loads(rsp[first:last])
python
def _load_rsp(rsp): """ Converts raw Flickr string response to Python dict """ first = rsp.find('(') + 1 last = rsp.rfind(')') return json.loads(rsp[first:last])
[ "def", "_load_rsp", "(", "rsp", ")", ":", "first", "=", "rsp", ".", "find", "(", "'('", ")", "+", "1", "last", "=", "rsp", ".", "rfind", "(", "')'", ")", "return", "json", ".", "loads", "(", "rsp", "[", "first", ":", "last", "]", ")" ]
Converts raw Flickr string response to Python dict
[ "Converts", "raw", "Flickr", "string", "response", "to", "Python", "dict" ]
train
https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/flickr.py#L149-L155
BlackEarth/bf
bf/styles.py
Styles.styleProperties
def styleProperties(Class, style): """return a properties dict from a given cssutils style """ properties = Dict() for property in style.getProperties(all=True): stylename = property.name + ':' properties[stylename] = property.value if property.priorit...
python
def styleProperties(Class, style): """return a properties dict from a given cssutils style """ properties = Dict() for property in style.getProperties(all=True): stylename = property.name + ':' properties[stylename] = property.value if property.priorit...
[ "def", "styleProperties", "(", "Class", ",", "style", ")", ":", "properties", "=", "Dict", "(", ")", "for", "property", "in", "style", ".", "getProperties", "(", "all", "=", "True", ")", ":", "stylename", "=", "property", ".", "name", "+", "':'", "prop...
return a properties dict from a given cssutils style
[ "return", "a", "properties", "dict", "from", "a", "given", "cssutils", "style" ]
train
https://github.com/BlackEarth/bf/blob/376041168874bbd6dee5ccfeece4a9e553223316/bf/styles.py#L14-L23
BlackEarth/bf
bf/styles.py
Styles.from_css
def from_css(Class, csstext, encoding=None, href=None, media=None, title=None, validate=None): """parse CSS text into a Styles object, using cssutils """ styles = Class() cssStyleSheet = cssutils.parseString(csstext, encoding=encoding, href=href, media=media, title=title, validate=valida...
python
def from_css(Class, csstext, encoding=None, href=None, media=None, title=None, validate=None): """parse CSS text into a Styles object, using cssutils """ styles = Class() cssStyleSheet = cssutils.parseString(csstext, encoding=encoding, href=href, media=media, title=title, validate=valida...
[ "def", "from_css", "(", "Class", ",", "csstext", ",", "encoding", "=", "None", ",", "href", "=", "None", ",", "media", "=", "None", ",", "title", "=", "None", ",", "validate", "=", "None", ")", ":", "styles", "=", "Class", "(", ")", "cssStyleSheet", ...
parse CSS text into a Styles object, using cssutils
[ "parse", "CSS", "text", "into", "a", "Styles", "object", "using", "cssutils" ]
train
https://github.com/BlackEarth/bf/blob/376041168874bbd6dee5ccfeece4a9e553223316/bf/styles.py#L26-L70
BlackEarth/bf
bf/styles.py
Styles.render
def render(C, styles, margin='', indent='\t'): """output css text from styles. margin is what to put at the beginning of every line in the output. indent is how much to indent indented lines (such as inside braces). """ from unum import Unum s = "" # render the c...
python
def render(C, styles, margin='', indent='\t'): """output css text from styles. margin is what to put at the beginning of every line in the output. indent is how much to indent indented lines (such as inside braces). """ from unum import Unum s = "" # render the c...
[ "def", "render", "(", "C", ",", "styles", ",", "margin", "=", "''", ",", "indent", "=", "'\\t'", ")", ":", "from", "unum", "import", "Unum", "s", "=", "\"\"", "# render the css text", "for", "k", "in", "styles", ".", "keys", "(", ")", ":", "s", "+=...
output css text from styles. margin is what to put at the beginning of every line in the output. indent is how much to indent indented lines (such as inside braces).
[ "output", "css", "text", "from", "styles", ".", "margin", "is", "what", "to", "put", "at", "the", "beginning", "of", "every", "line", "in", "the", "output", ".", "indent", "is", "how", "much", "to", "indent", "indented", "lines", "(", "such", "as", "in...
train
https://github.com/BlackEarth/bf/blob/376041168874bbd6dee5ccfeece4a9e553223316/bf/styles.py#L73-L103
aliafshar/oa2
oa2.py
get_token
def get_token(code, token_service, client_id, client_secret, redirect_uri, grant_type): """Fetches an OAuth 2 token.""" data = { 'code': code, 'client_id': client_id, 'client_secret': client_secret, 'redirect_uri': redirect_uri, 'grant_type': grant_type, } # Get the d...
python
def get_token(code, token_service, client_id, client_secret, redirect_uri, grant_type): """Fetches an OAuth 2 token.""" data = { 'code': code, 'client_id': client_id, 'client_secret': client_secret, 'redirect_uri': redirect_uri, 'grant_type': grant_type, } # Get the d...
[ "def", "get_token", "(", "code", ",", "token_service", ",", "client_id", ",", "client_secret", ",", "redirect_uri", ",", "grant_type", ")", ":", "data", "=", "{", "'code'", ":", "code", ",", "'client_id'", ":", "client_id", ",", "'client_secret'", ":", "clie...
Fetches an OAuth 2 token.
[ "Fetches", "an", "OAuth", "2", "token", "." ]
train
https://github.com/aliafshar/oa2/blob/0df67aea6b393e5a463e90d79bf2c3168e5fcc48/oa2.py#L160-L172
aliafshar/oa2
oa2.py
get_auth_uri
def get_auth_uri(auth_service, client_id, scope, redirect_uri, response_type, state, access_type, approval_prompt): """Generates an authorization uri.""" errors = [] if response_type not in VALID_RESPONSE_TYPES: errors.append( '{0} is not a valid response_type, must be {1}.'.format( ...
python
def get_auth_uri(auth_service, client_id, scope, redirect_uri, response_type, state, access_type, approval_prompt): """Generates an authorization uri.""" errors = [] if response_type not in VALID_RESPONSE_TYPES: errors.append( '{0} is not a valid response_type, must be {1}.'.format( ...
[ "def", "get_auth_uri", "(", "auth_service", ",", "client_id", ",", "scope", ",", "redirect_uri", ",", "response_type", ",", "state", ",", "access_type", ",", "approval_prompt", ")", ":", "errors", "=", "[", "]", "if", "response_type", "not", "in", "VALID_RESPO...
Generates an authorization uri.
[ "Generates", "an", "authorization", "uri", "." ]
train
https://github.com/aliafshar/oa2/blob/0df67aea6b393e5a463e90d79bf2c3168e5fcc48/oa2.py#L174-L203
aliafshar/oa2
oa2.py
refresh_token
def refresh_token(token_service, refresh_token, client_id, client_secret): """Refreshes a token.""" data = { 'client_id': client_id, 'client_secret': client_secret, 'refresh_token': refresh_token, 'grant_type': 'refresh_token', } resp = requests.post(token_service, data) print resp, 'refreshin...
python
def refresh_token(token_service, refresh_token, client_id, client_secret): """Refreshes a token.""" data = { 'client_id': client_id, 'client_secret': client_secret, 'refresh_token': refresh_token, 'grant_type': 'refresh_token', } resp = requests.post(token_service, data) print resp, 'refreshin...
[ "def", "refresh_token", "(", "token_service", ",", "refresh_token", ",", "client_id", ",", "client_secret", ")", ":", "data", "=", "{", "'client_id'", ":", "client_id", ",", "'client_secret'", ":", "client_secret", ",", "'refresh_token'", ":", "refresh_token", ","...
Refreshes a token.
[ "Refreshes", "a", "token", "." ]
train
https://github.com/aliafshar/oa2/blob/0df67aea6b393e5a463e90d79bf2c3168e5fcc48/oa2.py#L205-L215
aliafshar/oa2
oa2.py
run_local
def run_local(client): """Starts a local web server and wait for a redirect.""" webbrowser.open(client.get_auth_uri()) code = wait_for_redirect() return client.get_token(code)
python
def run_local(client): """Starts a local web server and wait for a redirect.""" webbrowser.open(client.get_auth_uri()) code = wait_for_redirect() return client.get_token(code)
[ "def", "run_local", "(", "client", ")", ":", "webbrowser", ".", "open", "(", "client", ".", "get_auth_uri", "(", ")", ")", "code", "=", "wait_for_redirect", "(", ")", "return", "client", ".", "get_token", "(", "code", ")" ]
Starts a local web server and wait for a redirect.
[ "Starts", "a", "local", "web", "server", "and", "wait", "for", "a", "redirect", "." ]
train
https://github.com/aliafshar/oa2/blob/0df67aea6b393e5a463e90d79bf2c3168e5fcc48/oa2.py#L323-L327
aliafshar/oa2
oa2.py
main
def main(argv): """Entry point for command line script to perform OAuth 2.0.""" p = argparse.ArgumentParser() p.add_argument('-s', '--scope', nargs='+') p.add_argument('-o', '--oauth-service', default='google') p.add_argument('-i', '--client-id') p.add_argument('-x', '--client-secret') p.add_argument('-r'...
python
def main(argv): """Entry point for command line script to perform OAuth 2.0.""" p = argparse.ArgumentParser() p.add_argument('-s', '--scope', nargs='+') p.add_argument('-o', '--oauth-service', default='google') p.add_argument('-i', '--client-id') p.add_argument('-x', '--client-secret') p.add_argument('-r'...
[ "def", "main", "(", "argv", ")", ":", "p", "=", "argparse", ".", "ArgumentParser", "(", ")", "p", ".", "add_argument", "(", "'-s'", ",", "'--scope'", ",", "nargs", "=", "'+'", ")", "p", ".", "add_argument", "(", "'-o'", ",", "'--oauth-service'", ",", ...
Entry point for command line script to perform OAuth 2.0.
[ "Entry", "point", "for", "command", "line", "script", "to", "perform", "OAuth", "2", ".", "0", "." ]
train
https://github.com/aliafshar/oa2/blob/0df67aea6b393e5a463e90d79bf2c3168e5fcc48/oa2.py#L382-L406
BlueHack-Core/blueforge
blueforge/util/file.py
check_and_create_directories
def check_and_create_directories(paths): """ Check and create directories. If the directory is exist, It will remove it and create new folder. :type paths: Array of string or string :param paths: the location of directory """ for path in paths: if os.path.exists(pat...
python
def check_and_create_directories(paths): """ Check and create directories. If the directory is exist, It will remove it and create new folder. :type paths: Array of string or string :param paths: the location of directory """ for path in paths: if os.path.exists(pat...
[ "def", "check_and_create_directories", "(", "paths", ")", ":", "for", "path", "in", "paths", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "shutil", ".", "rmtree", "(", "path", ")", "os", ".", "mkdir", "(", "path", ")" ]
Check and create directories. If the directory is exist, It will remove it and create new folder. :type paths: Array of string or string :param paths: the location of directory
[ "Check", "and", "create", "directories", "." ]
train
https://github.com/BlueHack-Core/blueforge/blob/ac40a888ee9c388638a8f312c51f7500b8891b6c/blueforge/util/file.py#L12-L24
BlueHack-Core/blueforge
blueforge/util/file.py
delete_directories
def delete_directories(paths): """ Delete directories. If the directory is exist, It will delete it including files. :type paths: Array of string or string :param paths: the location of directory """ for path in paths: if os.path.exists(path): shutil.rmt...
python
def delete_directories(paths): """ Delete directories. If the directory is exist, It will delete it including files. :type paths: Array of string or string :param paths: the location of directory """ for path in paths: if os.path.exists(path): shutil.rmt...
[ "def", "delete_directories", "(", "paths", ")", ":", "for", "path", "in", "paths", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "shutil", ".", "rmtree", "(", "path", ")" ]
Delete directories. If the directory is exist, It will delete it including files. :type paths: Array of string or string :param paths: the location of directory
[ "Delete", "directories", "." ]
train
https://github.com/BlueHack-Core/blueforge/blob/ac40a888ee9c388638a8f312c51f7500b8891b6c/blueforge/util/file.py#L27-L38
BlueHack-Core/blueforge
blueforge/util/file.py
delete_files
def delete_files(paths): """ Delete files. If the file is exist, It will delete it. :type paths: Array of string or string :param paths: the location of file """ for path in paths: if os.path.exists(path): os.remove(path)
python
def delete_files(paths): """ Delete files. If the file is exist, It will delete it. :type paths: Array of string or string :param paths: the location of file """ for path in paths: if os.path.exists(path): os.remove(path)
[ "def", "delete_files", "(", "paths", ")", ":", "for", "path", "in", "paths", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "remove", "(", "path", ")" ]
Delete files. If the file is exist, It will delete it. :type paths: Array of string or string :param paths: the location of file
[ "Delete", "files", "." ]
train
https://github.com/BlueHack-Core/blueforge/blob/ac40a888ee9c388638a8f312c51f7500b8891b6c/blueforge/util/file.py#L41-L52
BlueHack-Core/blueforge
blueforge/util/file.py
move_file
def move_file(originals, destination): """ Move file from original path to destination path. :type originals: Array of str :param originals: The original path :type destination: str :param destination: The destination path """ for original in originals: if o...
python
def move_file(originals, destination): """ Move file from original path to destination path. :type originals: Array of str :param originals: The original path :type destination: str :param destination: The destination path """ for original in originals: if o...
[ "def", "move_file", "(", "originals", ",", "destination", ")", ":", "for", "original", "in", "originals", ":", "if", "os", ".", "path", ".", "exists", "(", "original", ")", ":", "shutil", ".", "move", "(", "original", ",", "destination", ")" ]
Move file from original path to destination path. :type originals: Array of str :param originals: The original path :type destination: str :param destination: The destination path
[ "Move", "file", "from", "original", "path", "to", "destination", "path", "." ]
train
https://github.com/BlueHack-Core/blueforge/blob/ac40a888ee9c388638a8f312c51f7500b8891b6c/blueforge/util/file.py#L69-L81
BlueHack-Core/blueforge
blueforge/util/file.py
uncompress_files
def uncompress_files(original, destination): """ Move file from original path to destination path. :type original: str :param original: The location of zip file :type destination: str :param destination: The extract path """ with zipfile.ZipFile(original) as zips: ...
python
def uncompress_files(original, destination): """ Move file from original path to destination path. :type original: str :param original: The location of zip file :type destination: str :param destination: The extract path """ with zipfile.ZipFile(original) as zips: ...
[ "def", "uncompress_files", "(", "original", ",", "destination", ")", ":", "with", "zipfile", ".", "ZipFile", "(", "original", ")", "as", "zips", ":", "extract_path", "=", "os", ".", "path", ".", "join", "(", "destination", ")", "zips", ".", "extractall", ...
Move file from original path to destination path. :type original: str :param original: The location of zip file :type destination: str :param destination: The extract path
[ "Move", "file", "from", "original", "path", "to", "destination", "path", "." ]
train
https://github.com/BlueHack-Core/blueforge/blob/ac40a888ee9c388638a8f312c51f7500b8891b6c/blueforge/util/file.py#L84-L96
firstprayer/monsql
monsql/wrapper_postgresql.py
PostgreSQLDatabase.truncate_table
def truncate_table(self, tablename): """ Use 'TRUNCATE TABLE' to truncate the given table """ self.cursor.execute('TRUNCATE TABLE %s' %tablename) self.db.commit()
python
def truncate_table(self, tablename): """ Use 'TRUNCATE TABLE' to truncate the given table """ self.cursor.execute('TRUNCATE TABLE %s' %tablename) self.db.commit()
[ "def", "truncate_table", "(", "self", ",", "tablename", ")", ":", "self", ".", "cursor", ".", "execute", "(", "'TRUNCATE TABLE %s'", "%", "tablename", ")", "self", ".", "db", ".", "commit", "(", ")" ]
Use 'TRUNCATE TABLE' to truncate the given table
[ "Use", "TRUNCATE", "TABLE", "to", "truncate", "the", "given", "table" ]
train
https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/wrapper_postgresql.py#L52-L57
firstprayer/monsql
monsql/wrapper_postgresql.py
PostgreSQLDatabase.create_schema
def create_schema(self, schema_name): """ Create schema. This method only implemented for this class """ try: self.cursor.execute('CREATE SCHEMA %s' % schema_name) except Exception as e: raise e finally: self.db.commit()
python
def create_schema(self, schema_name): """ Create schema. This method only implemented for this class """ try: self.cursor.execute('CREATE SCHEMA %s' % schema_name) except Exception as e: raise e finally: self.db.commit()
[ "def", "create_schema", "(", "self", ",", "schema_name", ")", ":", "try", ":", "self", ".", "cursor", ".", "execute", "(", "'CREATE SCHEMA %s'", "%", "schema_name", ")", "except", "Exception", "as", "e", ":", "raise", "e", "finally", ":", "self", ".", "d...
Create schema. This method only implemented for this class
[ "Create", "schema", ".", "This", "method", "only", "implemented", "for", "this", "class" ]
train
https://github.com/firstprayer/monsql/blob/6285c15b574c8664046eae2edfeb548c7b173efd/monsql/wrapper_postgresql.py#L59-L68
csaez/wishlib
wishlib/si/qt.py
show_qt
def show_qt(qt_class, modal=False, onshow_event=None, force_style=True): """ Shows and raise a pyqt window inside softimage ensuring it's not duplicated (if it's duplicated then raise the old one). qt_class argument should be a class/subclass of QMainWindow, QDialog or any top-level window supported...
python
def show_qt(qt_class, modal=False, onshow_event=None, force_style=True): """ Shows and raise a pyqt window inside softimage ensuring it's not duplicated (if it's duplicated then raise the old one). qt_class argument should be a class/subclass of QMainWindow, QDialog or any top-level window supported...
[ "def", "show_qt", "(", "qt_class", ",", "modal", "=", "False", ",", "onshow_event", "=", "None", ",", "force_style", "=", "True", ")", ":", "dialog", "=", "None", "anchor", "=", "sianchor", "(", ")", "# look for a previous instance", "for", "d", "in", "anc...
Shows and raise a pyqt window inside softimage ensuring it's not duplicated (if it's duplicated then raise the old one). qt_class argument should be a class/subclass of QMainWindow, QDialog or any top-level window supported by PyQtForSoftimage plugin. onshow_event provides a way to pass a function to ex...
[ "Shows", "and", "raise", "a", "pyqt", "window", "inside", "softimage", "ensuring", "it", "s", "not", "duplicated", "(", "if", "it", "s", "duplicated", "then", "raise", "the", "old", "one", ")", ".", "qt_class", "argument", "should", "be", "a", "class", "...
train
https://github.com/csaez/wishlib/blob/c212fa7875006a332a4cefbf69885ced9647bc2f/wishlib/si/qt.py#L42-L74