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
echinopsii/net.echinopsii.ariane.community.cli.python3
ariane_clip3/natsd/driver.py
Driver.make_requester
def make_requester(self, my_args=None): """ make a new requester instance and handle it from driver :param my_args: dict like {request_q}. Default : None :return: created requester proxy """ LOGGER.debug("natsd.Driver.make_requester") if my_args is None: ...
python
def make_requester(self, my_args=None): """ make a new requester instance and handle it from driver :param my_args: dict like {request_q}. Default : None :return: created requester proxy """ LOGGER.debug("natsd.Driver.make_requester") if my_args is None: ...
[ "def", "make_requester", "(", "self", ",", "my_args", "=", "None", ")", ":", "LOGGER", ".", "debug", "(", "\"natsd.Driver.make_requester\"", ")", "if", "my_args", "is", "None", ":", "raise", "exceptions", ".", "ArianeConfError", "(", "'requester factory arguments'...
make a new requester instance and handle it from driver :param my_args: dict like {request_q}. Default : None :return: created requester proxy
[ "make", "a", "new", "requester", "instance", "and", "handle", "it", "from", "driver", ":", "param", "my_args", ":", "dict", "like", "{", "request_q", "}", ".", "Default", ":", "None", ":", "return", ":", "created", "requester", "proxy" ]
train
https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/natsd/driver.py#L876-L889
b3j0f/annotation
b3j0f/annotation/core.py
Annotation.ttl
def ttl(self): """Get actual ttl in seconds. :return: actual ttl. :rtype: float """ # result is self ts result = getattr(self, Annotation.__TS, None) # if result is not None if result is not None: # result is now - result now = ti...
python
def ttl(self): """Get actual ttl in seconds. :return: actual ttl. :rtype: float """ # result is self ts result = getattr(self, Annotation.__TS, None) # if result is not None if result is not None: # result is now - result now = ti...
[ "def", "ttl", "(", "self", ")", ":", "# result is self ts", "result", "=", "getattr", "(", "self", ",", "Annotation", ".", "__TS", ",", "None", ")", "# if result is not None", "if", "result", "is", "not", "None", ":", "# result is now - result", "now", "=", ...
Get actual ttl in seconds. :return: actual ttl. :rtype: float
[ "Get", "actual", "ttl", "in", "seconds", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L191-L206
b3j0f/annotation
b3j0f/annotation/core.py
Annotation.ttl
def ttl(self, value): """Change self ttl with input value. :param float value: new ttl in seconds. """ # get timer timer = getattr(self, Annotation.__TIMER, None) # if timer is running, stop the timer if timer is not None: timer.cancel() # ...
python
def ttl(self, value): """Change self ttl with input value. :param float value: new ttl in seconds. """ # get timer timer = getattr(self, Annotation.__TIMER, None) # if timer is running, stop the timer if timer is not None: timer.cancel() # ...
[ "def", "ttl", "(", "self", ",", "value", ")", ":", "# get timer", "timer", "=", "getattr", "(", "self", ",", "Annotation", ".", "__TIMER", ",", "None", ")", "# if timer is running, stop the timer", "if", "timer", "is", "not", "None", ":", "timer", ".", "ca...
Change self ttl with input value. :param float value: new ttl in seconds.
[ "Change", "self", "ttl", "with", "input", "value", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L209-L239
b3j0f/annotation
b3j0f/annotation/core.py
Annotation.in_memory
def in_memory(self): """ :return: True if self is in a global memory of annotations. """ self_class = self.__class__ # check if self class is in global memory memory = Annotation.__ANNOTATIONS_IN_MEMORY__.get(self_class, ()) # check if self is in memory r...
python
def in_memory(self): """ :return: True if self is in a global memory of annotations. """ self_class = self.__class__ # check if self class is in global memory memory = Annotation.__ANNOTATIONS_IN_MEMORY__.get(self_class, ()) # check if self is in memory r...
[ "def", "in_memory", "(", "self", ")", ":", "self_class", "=", "self", ".", "__class__", "# check if self class is in global memory", "memory", "=", "Annotation", ".", "__ANNOTATIONS_IN_MEMORY__", ".", "get", "(", "self_class", ",", "(", ")", ")", "# check if self is...
:return: True if self is in a global memory of annotations.
[ ":", "return", ":", "True", "if", "self", "is", "in", "a", "global", "memory", "of", "annotations", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L242-L253
b3j0f/annotation
b3j0f/annotation/core.py
Annotation.in_memory
def in_memory(self, value): """Add or remove self from global memory. :param bool value: if True(False) ensure self is(is not) in memory. """ self_class = self.__class__ memory = Annotation.__ANNOTATIONS_IN_MEMORY__ if value: annotations_memory = memory.set...
python
def in_memory(self, value): """Add or remove self from global memory. :param bool value: if True(False) ensure self is(is not) in memory. """ self_class = self.__class__ memory = Annotation.__ANNOTATIONS_IN_MEMORY__ if value: annotations_memory = memory.set...
[ "def", "in_memory", "(", "self", ",", "value", ")", ":", "self_class", "=", "self", ".", "__class__", "memory", "=", "Annotation", ".", "__ANNOTATIONS_IN_MEMORY__", "if", "value", ":", "annotations_memory", "=", "memory", ".", "setdefault", "(", "self_class", ...
Add or remove self from global memory. :param bool value: if True(False) ensure self is(is not) in memory.
[ "Add", "or", "remove", "self", "from", "global", "memory", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L256-L275
b3j0f/annotation
b3j0f/annotation/core.py
Annotation.bind_target
def bind_target(self, target, ctx=None): """Bind self annotation to target. :param target: target to annotate. :param ctx: target ctx. :return: bound target. """ # process self _bind_target result = self._bind_target(target=target, ctx=ctx) # fire on bi...
python
def bind_target(self, target, ctx=None): """Bind self annotation to target. :param target: target to annotate. :param ctx: target ctx. :return: bound target. """ # process self _bind_target result = self._bind_target(target=target, ctx=ctx) # fire on bi...
[ "def", "bind_target", "(", "self", ",", "target", ",", "ctx", "=", "None", ")", ":", "# process self _bind_target", "result", "=", "self", ".", "_bind_target", "(", "target", "=", "target", ",", "ctx", "=", "ctx", ")", "# fire on bind target event", "self", ...
Bind self annotation to target. :param target: target to annotate. :param ctx: target ctx. :return: bound target.
[ "Bind", "self", "annotation", "to", "target", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L277-L291
b3j0f/annotation
b3j0f/annotation/core.py
Annotation._bind_target
def _bind_target(self, target, ctx=None): """Method to override in order to specialize binding of target. :param target: target to bind. :param ctx: target ctx. :return: bound target. """ result = target try: # get annotations from target if exists....
python
def _bind_target(self, target, ctx=None): """Method to override in order to specialize binding of target. :param target: target to bind. :param ctx: target ctx. :return: bound target. """ result = target try: # get annotations from target if exists....
[ "def", "_bind_target", "(", "self", ",", "target", ",", "ctx", "=", "None", ")", ":", "result", "=", "target", "try", ":", "# get annotations from target if exists.", "local_annotations", "=", "get_local_property", "(", "target", ",", "Annotation", ".", "__ANNOTAT...
Method to override in order to specialize binding of target. :param target: target to bind. :param ctx: target ctx. :return: bound target.
[ "Method", "to", "override", "in", "order", "to", "specialize", "binding", "of", "target", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L293-L326
b3j0f/annotation
b3j0f/annotation/core.py
Annotation.on_bind_target
def on_bind_target(self, target, ctx=None): """Fired after target is bound to self. :param target: newly bound target. :param ctx: target ctx. """ _on_bind_target = getattr(self, Annotation._ON_BIND_TARGET, None) if _on_bind_target is not None: _on_bind_tar...
python
def on_bind_target(self, target, ctx=None): """Fired after target is bound to self. :param target: newly bound target. :param ctx: target ctx. """ _on_bind_target = getattr(self, Annotation._ON_BIND_TARGET, None) if _on_bind_target is not None: _on_bind_tar...
[ "def", "on_bind_target", "(", "self", ",", "target", ",", "ctx", "=", "None", ")", ":", "_on_bind_target", "=", "getattr", "(", "self", ",", "Annotation", ".", "_ON_BIND_TARGET", ",", "None", ")", "if", "_on_bind_target", "is", "not", "None", ":", "_on_bin...
Fired after target is bound to self. :param target: newly bound target. :param ctx: target ctx.
[ "Fired", "after", "target", "is", "bound", "to", "self", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L328-L338
b3j0f/annotation
b3j0f/annotation/core.py
Annotation.remove_from
def remove_from(self, target, ctx=None): """Remove self annotation from target annotations. :param target: target from where remove self annotation. :param ctx: target ctx. """ annotations_key = Annotation.__ANNOTATIONS_KEY__ try: # get local annotations ...
python
def remove_from(self, target, ctx=None): """Remove self annotation from target annotations. :param target: target from where remove self annotation. :param ctx: target ctx. """ annotations_key = Annotation.__ANNOTATIONS_KEY__ try: # get local annotations ...
[ "def", "remove_from", "(", "self", ",", "target", ",", "ctx", "=", "None", ")", ":", "annotations_key", "=", "Annotation", ".", "__ANNOTATIONS_KEY__", "try", ":", "# get local annotations", "local_annotations", "=", "get_local_property", "(", "target", ",", "annot...
Remove self annotation from target annotations. :param target: target from where remove self annotation. :param ctx: target ctx.
[ "Remove", "self", "annotation", "from", "target", "annotations", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L340-L368
b3j0f/annotation
b3j0f/annotation/core.py
Annotation.free_memory
def free_memory(cls, exclude=None): """Free global annotation memory.""" annotations_in_memory = Annotation.__ANNOTATIONS_IN_MEMORY__ exclude = () if exclude is None else exclude for annotation_cls in list(annotations_in_memory.keys()): if issubclass(annotation_cls, exclu...
python
def free_memory(cls, exclude=None): """Free global annotation memory.""" annotations_in_memory = Annotation.__ANNOTATIONS_IN_MEMORY__ exclude = () if exclude is None else exclude for annotation_cls in list(annotations_in_memory.keys()): if issubclass(annotation_cls, exclu...
[ "def", "free_memory", "(", "cls", ",", "exclude", "=", "None", ")", ":", "annotations_in_memory", "=", "Annotation", ".", "__ANNOTATIONS_IN_MEMORY__", "exclude", "=", "(", ")", "if", "exclude", "is", "None", "else", "exclude", "for", "annotation_cls", "in", "l...
Free global annotation memory.
[ "Free", "global", "annotation", "memory", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L371-L384
b3j0f/annotation
b3j0f/annotation/core.py
Annotation.get_memory_annotations
def get_memory_annotations(cls, exclude=None): """Get annotations in memory which inherits from cls. :param tuple/type exclude: annotation type(s) to exclude from search. :return: found annotations which inherits from cls. :rtype: set """ result = set() # get g...
python
def get_memory_annotations(cls, exclude=None): """Get annotations in memory which inherits from cls. :param tuple/type exclude: annotation type(s) to exclude from search. :return: found annotations which inherits from cls. :rtype: set """ result = set() # get g...
[ "def", "get_memory_annotations", "(", "cls", ",", "exclude", "=", "None", ")", ":", "result", "=", "set", "(", ")", "# get global dictionary", "annotations_in_memory", "=", "Annotation", ".", "__ANNOTATIONS_IN_MEMORY__", "exclude", "=", "(", ")", "if", "exclude", ...
Get annotations in memory which inherits from cls. :param tuple/type exclude: annotation type(s) to exclude from search. :return: found annotations which inherits from cls. :rtype: set
[ "Get", "annotations", "in", "memory", "which", "inherits", "from", "cls", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L387-L413
b3j0f/annotation
b3j0f/annotation/core.py
Annotation.get_local_annotations
def get_local_annotations( cls, target, exclude=None, ctx=None, select=lambda *p: True ): """Get a list of local target annotations in the order of their definition. :param type cls: type of annotation to get from target. :param target: target from where get annotati...
python
def get_local_annotations( cls, target, exclude=None, ctx=None, select=lambda *p: True ): """Get a list of local target annotations in the order of their definition. :param type cls: type of annotation to get from target. :param target: target from where get annotati...
[ "def", "get_local_annotations", "(", "cls", ",", "target", ",", "exclude", "=", "None", ",", "ctx", "=", "None", ",", "select", "=", "lambda", "*", "p", ":", "True", ")", ":", "result", "=", "[", "]", "# initialize exclude", "exclude", "=", "(", ")", ...
Get a list of local target annotations in the order of their definition. :param type cls: type of annotation to get from target. :param target: target from where get annotations. :param tuple/type exclude: annotation types to exclude from selection. :param ctx: target ctx. ...
[ "Get", "a", "list", "of", "local", "target", "annotations", "in", "the", "order", "of", "their", "definition", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L416-L476
b3j0f/annotation
b3j0f/annotation/core.py
Annotation.remove
def remove(cls, target, exclude=None, ctx=None, select=lambda *p: True): """Remove from target annotations which inherit from cls. :param target: target from where remove annotations which inherits from cls. :param tuple/type exclude: annotation types to exclude from selection. ...
python
def remove(cls, target, exclude=None, ctx=None, select=lambda *p: True): """Remove from target annotations which inherit from cls. :param target: target from where remove annotations which inherits from cls. :param tuple/type exclude: annotation types to exclude from selection. ...
[ "def", "remove", "(", "cls", ",", "target", ",", "exclude", "=", "None", ",", "ctx", "=", "None", ",", "select", "=", "lambda", "*", "p", ":", "True", ")", ":", "# initialize exclude", "exclude", "=", "(", ")", "if", "exclude", "is", "None", "else", ...
Remove from target annotations which inherit from cls. :param target: target from where remove annotations which inherits from cls. :param tuple/type exclude: annotation types to exclude from selection. :param ctx: target ctx. :param select: annotation selection function whi...
[ "Remove", "from", "target", "annotations", "which", "inherit", "from", "cls", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L479-L518
b3j0f/annotation
b3j0f/annotation/core.py
Annotation.get_annotations
def get_annotations( cls, target, exclude=None, ctx=None, select=lambda *p: True, mindepth=0, maxdepth=0, followannotated=True, public=True, _history=None ): """Returns all input target annotations of cls type sorted by definition order. :para...
python
def get_annotations( cls, target, exclude=None, ctx=None, select=lambda *p: True, mindepth=0, maxdepth=0, followannotated=True, public=True, _history=None ): """Returns all input target annotations of cls type sorted by definition order. :para...
[ "def", "get_annotations", "(", "cls", ",", "target", ",", "exclude", "=", "None", ",", "ctx", "=", "None", ",", "select", "=", "lambda", "*", "p", ":", "True", ",", "mindepth", "=", "0", ",", "maxdepth", "=", "0", ",", "followannotated", "=", "True",...
Returns all input target annotations of cls type sorted by definition order. :param type cls: type of annotation to get from target. :param target: target from where get annotations. :param tuple/type exclude: annotation types to remove from selection. :param ctx: target ctx. ...
[ "Returns", "all", "input", "target", "annotations", "of", "cls", "type", "sorted", "by", "definition", "order", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L521-L621
b3j0f/annotation
b3j0f/annotation/core.py
Annotation.get_annotated_fields
def get_annotated_fields(cls, instance, select=lambda *p: True): """Get dict of {annotated fields: annotations} by cls of input instance. :return: a set of (annotated fields, annotations). :rtype: dict """ result = {} for _, member in getmembers(instance): ...
python
def get_annotated_fields(cls, instance, select=lambda *p: True): """Get dict of {annotated fields: annotations} by cls of input instance. :return: a set of (annotated fields, annotations). :rtype: dict """ result = {} for _, member in getmembers(instance): ...
[ "def", "get_annotated_fields", "(", "cls", ",", "instance", ",", "select", "=", "lambda", "*", "p", ":", "True", ")", ":", "result", "=", "{", "}", "for", "_", ",", "member", "in", "getmembers", "(", "instance", ")", ":", "try", ":", "annotations", "...
Get dict of {annotated fields: annotations} by cls of input instance. :return: a set of (annotated fields, annotations). :rtype: dict
[ "Get", "dict", "of", "{", "annotated", "fields", ":", "annotations", "}", "by", "cls", "of", "input", "instance", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L624-L651
ulf1/oxyba
oxyba/rand_chol.py
rand_chol
def rand_chol(X, rho): """Transform C uncorrelated random variables into correlated data X : ndarray C univariate correlated random variables with N observations as <N x C> matrix rho : ndarray Correlation Matrix (Pearson method) with coefficients between [-1, +1] """ ...
python
def rand_chol(X, rho): """Transform C uncorrelated random variables into correlated data X : ndarray C univariate correlated random variables with N observations as <N x C> matrix rho : ndarray Correlation Matrix (Pearson method) with coefficients between [-1, +1] """ ...
[ "def", "rand_chol", "(", "X", ",", "rho", ")", ":", "import", "numpy", "as", "np", "return", "np", ".", "dot", "(", "X", ",", "np", ".", "linalg", ".", "cholesky", "(", "rho", ")", ".", "T", ")" ]
Transform C uncorrelated random variables into correlated data X : ndarray C univariate correlated random variables with N observations as <N x C> matrix rho : ndarray Correlation Matrix (Pearson method) with coefficients between [-1, +1]
[ "Transform", "C", "uncorrelated", "random", "variables", "into", "correlated", "data" ]
train
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/rand_chol.py#L2-L14
opinkerfi/nago
nago/protocols/httpserver/__init__.py
login_required
def login_required(func, permission=None): """ decorate with this function in order to require a valid token for any view If no token is present you will be sent to a login page """ @wraps(func) def decorated_function(*args, **kwargs): if not check_token(): return login() ...
python
def login_required(func, permission=None): """ decorate with this function in order to require a valid token for any view If no token is present you will be sent to a login page """ @wraps(func) def decorated_function(*args, **kwargs): if not check_token(): return login() ...
[ "def", "login_required", "(", "func", ",", "permission", "=", "None", ")", ":", "@", "wraps", "(", "func", ")", "def", "decorated_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "check_token", "(", ")", ":", "return", "lo...
decorate with this function in order to require a valid token for any view If no token is present you will be sent to a login page
[ "decorate", "with", "this", "function", "in", "order", "to", "require", "a", "valid", "token", "for", "any", "view" ]
train
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/protocols/httpserver/__init__.py#L25-L37
opinkerfi/nago
nago/protocols/httpserver/__init__.py
list_nodes
def list_nodes(): """ Return a list of all nodes """ token = session.get('token') node = nago.core.get_node(token) if not node.get('access') == 'master': return jsonify(status='error', error="You need master access to view this page") nodes = nago.core.get_nodes().values() return render...
python
def list_nodes(): """ Return a list of all nodes """ token = session.get('token') node = nago.core.get_node(token) if not node.get('access') == 'master': return jsonify(status='error', error="You need master access to view this page") nodes = nago.core.get_nodes().values() return render...
[ "def", "list_nodes", "(", ")", ":", "token", "=", "session", ".", "get", "(", "'token'", ")", "node", "=", "nago", ".", "core", ".", "get_node", "(", "token", ")", "if", "not", "node", ".", "get", "(", "'access'", ")", "==", "'master'", ":", "retur...
Return a list of all nodes
[ "Return", "a", "list", "of", "all", "nodes" ]
train
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/protocols/httpserver/__init__.py#L96-L104
opinkerfi/nago
nago/protocols/httpserver/__init__.py
node_detail
def node_detail(node_name): """ View one specific node """ token = session.get('token') node = nago.core.get_node(token) if not node.get('access') == 'master': return jsonify(status='error', error="You need master access to view this page") node = nago.core.get_node(node_name) return re...
python
def node_detail(node_name): """ View one specific node """ token = session.get('token') node = nago.core.get_node(token) if not node.get('access') == 'master': return jsonify(status='error', error="You need master access to view this page") node = nago.core.get_node(node_name) return re...
[ "def", "node_detail", "(", "node_name", ")", ":", "token", "=", "session", ".", "get", "(", "'token'", ")", "node", "=", "nago", ".", "core", ".", "get_node", "(", "token", ")", "if", "not", "node", ".", "get", "(", "'access'", ")", "==", "'master'",...
View one specific node
[ "View", "one", "specific", "node" ]
train
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/protocols/httpserver/__init__.py#L108-L116
eddiejessup/agaro
agaro/output_utils.py
get_filenames
def get_filenames(dirname): """Return all model output filenames inside a model output directory, sorted by iteration number. Parameters ---------- dirname: str A path to a directory. Returns ------- filenames: list[str] Paths to all output files inside `dirname`, sorte...
python
def get_filenames(dirname): """Return all model output filenames inside a model output directory, sorted by iteration number. Parameters ---------- dirname: str A path to a directory. Returns ------- filenames: list[str] Paths to all output files inside `dirname`, sorte...
[ "def", "get_filenames", "(", "dirname", ")", ":", "filenames", "=", "glob", ".", "glob", "(", "'{}/*.pkl'", ".", "format", "(", "dirname", ")", ")", "return", "sorted", "(", "filenames", ",", "key", "=", "_f_to_i", ")" ]
Return all model output filenames inside a model output directory, sorted by iteration number. Parameters ---------- dirname: str A path to a directory. Returns ------- filenames: list[str] Paths to all output files inside `dirname`, sorted in order of increasing it...
[ "Return", "all", "model", "output", "filenames", "inside", "a", "model", "output", "directory", "sorted", "by", "iteration", "number", "." ]
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/output_utils.py#L24-L40
eddiejessup/agaro
agaro/output_utils.py
get_output_every
def get_output_every(dirname): """Get how many iterations between outputs have been done in a directory run. If there are multiple values used in a run, raise an exception. Parameters ---------- dirname: str A path to a directory. Returns ------- output_every: int ...
python
def get_output_every(dirname): """Get how many iterations between outputs have been done in a directory run. If there are multiple values used in a run, raise an exception. Parameters ---------- dirname: str A path to a directory. Returns ------- output_every: int ...
[ "def", "get_output_every", "(", "dirname", ")", ":", "fnames", "=", "get_filenames", "(", "dirname", ")", "i_s", "=", "np", ".", "array", "(", "[", "_f_to_i", "(", "fname", ")", "for", "fname", "in", "fnames", "]", ")", "everys", "=", "list", "(", "s...
Get how many iterations between outputs have been done in a directory run. If there are multiple values used in a run, raise an exception. Parameters ---------- dirname: str A path to a directory. Returns ------- output_every: int The inferred number of iterations betw...
[ "Get", "how", "many", "iterations", "between", "outputs", "have", "been", "done", "in", "a", "directory", "run", "." ]
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/output_utils.py#L59-L87
eddiejessup/agaro
agaro/output_utils.py
model_to_file
def model_to_file(model, filename): """Dump a model to a file as a pickle file. Parameters ---------- model: Model Model instance. filename: str A path to the file in which to store the pickle output. """ with open(filename, 'wb') as f: pickle.dump(model, f)
python
def model_to_file(model, filename): """Dump a model to a file as a pickle file. Parameters ---------- model: Model Model instance. filename: str A path to the file in which to store the pickle output. """ with open(filename, 'wb') as f: pickle.dump(model, f)
[ "def", "model_to_file", "(", "model", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "f", ":", "pickle", ".", "dump", "(", "model", ",", "f", ")" ]
Dump a model to a file as a pickle file. Parameters ---------- model: Model Model instance. filename: str A path to the file in which to store the pickle output.
[ "Dump", "a", "model", "to", "a", "file", "as", "a", "pickle", "file", "." ]
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/output_utils.py#L107-L118
eddiejessup/agaro
agaro/output_utils.py
sparsify
def sparsify(dirname, output_every): """Remove files from an output directory at regular interval, so as to make it as if there had been more iterations between outputs. Can be used to reduce the storage size of a directory. If the new number of iterations between outputs is not an integer multiple ...
python
def sparsify(dirname, output_every): """Remove files from an output directory at regular interval, so as to make it as if there had been more iterations between outputs. Can be used to reduce the storage size of a directory. If the new number of iterations between outputs is not an integer multiple ...
[ "def", "sparsify", "(", "dirname", ",", "output_every", ")", ":", "fnames", "=", "get_filenames", "(", "dirname", ")", "output_every_old", "=", "get_output_every", "(", "dirname", ")", "if", "output_every", "%", "output_every_old", "!=", "0", ":", "raise", "Va...
Remove files from an output directory at regular interval, so as to make it as if there had been more iterations between outputs. Can be used to reduce the storage size of a directory. If the new number of iterations between outputs is not an integer multiple of the old number, then raise an exception....
[ "Remove", "files", "from", "an", "output", "directory", "at", "regular", "interval", "so", "as", "to", "make", "it", "as", "if", "there", "had", "been", "more", "iterations", "between", "outputs", ".", "Can", "be", "used", "to", "reduce", "the", "storage",...
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/output_utils.py#L121-L150
tempodb/tempodb-python
tempodb/endpoint.py
make_url_args
def make_url_args(params): """Utility function for constructing a URL query string from a dictionary of parameters. The dictionary's values can be of various types: lists, tuples, dictionaries, strings, or None. :param dict params: the key-value pairs to construct a query string from :rtype: strin...
python
def make_url_args(params): """Utility function for constructing a URL query string from a dictionary of parameters. The dictionary's values can be of various types: lists, tuples, dictionaries, strings, or None. :param dict params: the key-value pairs to construct a query string from :rtype: strin...
[ "def", "make_url_args", "(", "params", ")", ":", "p", "=", "[", "]", "for", "key", ",", "value", "in", "params", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "for", "v", "in", ...
Utility function for constructing a URL query string from a dictionary of parameters. The dictionary's values can be of various types: lists, tuples, dictionaries, strings, or None. :param dict params: the key-value pairs to construct a query string from :rtype: string
[ "Utility", "function", "for", "constructing", "a", "URL", "query", "string", "from", "a", "dictionary", "of", "parameters", ".", "The", "dictionary", "s", "values", "can", "be", "of", "various", "types", ":", "lists", "tuples", "dictionaries", "strings", "or",...
train
https://github.com/tempodb/tempodb-python/blob/8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3/tempodb/endpoint.py#L11-L33
tempodb/tempodb-python
tempodb/endpoint.py
HTTPEndpoint.post
def post(self, url, body): """Perform a POST request to the given resource with the given body. The "url" argument will be joined to the base URL this object was initialized with. :param string url: the URL resource to hit :param string body: the POST body for the request ...
python
def post(self, url, body): """Perform a POST request to the given resource with the given body. The "url" argument will be joined to the base URL this object was initialized with. :param string url: the URL resource to hit :param string body: the POST body for the request ...
[ "def", "post", "(", "self", ",", "url", ",", "body", ")", ":", "to_hit", "=", "urlparse", ".", "urljoin", "(", "self", ".", "base_url", ",", "url", ")", "resp", "=", "self", ".", "pool", ".", "post", "(", "to_hit", ",", "data", "=", "body", ",", ...
Perform a POST request to the given resource with the given body. The "url" argument will be joined to the base URL this object was initialized with. :param string url: the URL resource to hit :param string body: the POST body for the request :rtype: requests.Response object
[ "Perform", "a", "POST", "request", "to", "the", "given", "resource", "with", "the", "given", "body", ".", "The", "url", "argument", "will", "be", "joined", "to", "the", "base", "URL", "this", "object", "was", "initialized", "with", "." ]
train
https://github.com/tempodb/tempodb-python/blob/8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3/tempodb/endpoint.py#L63-L74
tempodb/tempodb-python
tempodb/endpoint.py
HTTPEndpoint.get
def get(self, url): """Perform a GET request to the given resource with the given URL. The "url" argument will be joined to the base URL this object was initialized with. :param string url: the URL resource to hit :rtype: requests.Response object""" to_hit = urlparse.u...
python
def get(self, url): """Perform a GET request to the given resource with the given URL. The "url" argument will be joined to the base URL this object was initialized with. :param string url: the URL resource to hit :rtype: requests.Response object""" to_hit = urlparse.u...
[ "def", "get", "(", "self", ",", "url", ")", ":", "to_hit", "=", "urlparse", ".", "urljoin", "(", "self", ".", "base_url", ",", "url", ")", "resp", "=", "self", ".", "pool", ".", "get", "(", "to_hit", ",", "auth", "=", "self", ".", "auth", ")", ...
Perform a GET request to the given resource with the given URL. The "url" argument will be joined to the base URL this object was initialized with. :param string url: the URL resource to hit :rtype: requests.Response object
[ "Perform", "a", "GET", "request", "to", "the", "given", "resource", "with", "the", "given", "URL", ".", "The", "url", "argument", "will", "be", "joined", "to", "the", "base", "URL", "this", "object", "was", "initialized", "with", "." ]
train
https://github.com/tempodb/tempodb-python/blob/8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3/tempodb/endpoint.py#L76-L86
kalekundert/nonstdlib
nonstdlib/sci.py
sci
def sci(x, precision=2, base=10, exp_only=False): """ Convert the given floating point number into scientific notation, using unicode superscript characters to nicely render the exponent. """ # Handle the corner cases of zero and non-finite numbers, which can't be # represented using scientif...
python
def sci(x, precision=2, base=10, exp_only=False): """ Convert the given floating point number into scientific notation, using unicode superscript characters to nicely render the exponent. """ # Handle the corner cases of zero and non-finite numbers, which can't be # represented using scientif...
[ "def", "sci", "(", "x", ",", "precision", "=", "2", ",", "base", "=", "10", ",", "exp_only", "=", "False", ")", ":", "# Handle the corner cases of zero and non-finite numbers, which can't be ", "# represented using scientific notation.", "if", "x", "==", "0", "or", ...
Convert the given floating point number into scientific notation, using unicode superscript characters to nicely render the exponent.
[ "Convert", "the", "given", "floating", "point", "number", "into", "scientific", "notation", "using", "unicode", "superscript", "characters", "to", "nicely", "render", "the", "exponent", "." ]
train
https://github.com/kalekundert/nonstdlib/blob/3abf4a4680056d6d97f2a5988972eb9392756fb6/nonstdlib/sci.py#L6-L32
ryanjdillon/pyotelem
pyotelem/seawater.py
SWdensityFromCTD
def SWdensityFromCTD(SA, t, p, potential=False): '''Calculate seawater density at CTD depth Args ---- SA: ndarray Absolute salinity, g/kg t: ndarray In-situ temperature (ITS-90), degrees C p: ndarray Sea pressure (absolute pressure minus 10.1325 dbar), dbar Returns ...
python
def SWdensityFromCTD(SA, t, p, potential=False): '''Calculate seawater density at CTD depth Args ---- SA: ndarray Absolute salinity, g/kg t: ndarray In-situ temperature (ITS-90), degrees C p: ndarray Sea pressure (absolute pressure minus 10.1325 dbar), dbar Returns ...
[ "def", "SWdensityFromCTD", "(", "SA", ",", "t", ",", "p", ",", "potential", "=", "False", ")", ":", "import", "numpy", "import", "gsw", "CT", "=", "gsw", ".", "CT_from_t", "(", "SA", ",", "t", ",", "p", ")", "# Calculate potential density (0 bar) instead o...
Calculate seawater density at CTD depth Args ---- SA: ndarray Absolute salinity, g/kg t: ndarray In-situ temperature (ITS-90), degrees C p: ndarray Sea pressure (absolute pressure minus 10.1325 dbar), dbar Returns ------- rho: ndarray Seawater density, i...
[ "Calculate", "seawater", "density", "at", "CTD", "depth" ]
train
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/seawater.py#L2-L28
ryanjdillon/pyotelem
pyotelem/seawater.py
interp_S_t
def interp_S_t(S, t, z, z_new, p=None): ''' Linearly interpolate CTD S, t, and p (optional) from `z` to `z_new`. Args ---- S: ndarray CTD salinities t: ndarray CTD temperatures z: ndarray CTD Depths, must be a strictly increasing or decreasing 1-D array, and its ...
python
def interp_S_t(S, t, z, z_new, p=None): ''' Linearly interpolate CTD S, t, and p (optional) from `z` to `z_new`. Args ---- S: ndarray CTD salinities t: ndarray CTD temperatures z: ndarray CTD Depths, must be a strictly increasing or decreasing 1-D array, and its ...
[ "def", "interp_S_t", "(", "S", ",", "t", ",", "z", ",", "z_new", ",", "p", "=", "None", ")", ":", "import", "numpy", "# Create array-like query depth if single value passed", "isscalar", "=", "False", "if", "not", "numpy", ".", "iterable", "(", "z_new", ")",...
Linearly interpolate CTD S, t, and p (optional) from `z` to `z_new`. Args ---- S: ndarray CTD salinities t: ndarray CTD temperatures z: ndarray CTD Depths, must be a strictly increasing or decreasing 1-D array, and its length must match the last dimension of `S` and ...
[ "Linearly", "interpolate", "CTD", "S", "t", "and", "p", "(", "optional", ")", "from", "z", "to", "z_new", "." ]
train
https://github.com/ryanjdillon/pyotelem/blob/816563a9c3feb3fa416f1c2921c6b75db34111ad/pyotelem/seawater.py#L31-L141
ulf1/oxyba
oxyba/drop_empty_records.py
drop_empty_records
def drop_empty_records(x, axis=1): """delete data items that contains only nan (or inf) """ # load module import numpy as np # input args check if not isinstance(x, np.ndarray or np.matrix): raise ValueError("x is not a numpy.ndarray or numpy.matrix.") # index idx = np.logical_not(n...
python
def drop_empty_records(x, axis=1): """delete data items that contains only nan (or inf) """ # load module import numpy as np # input args check if not isinstance(x, np.ndarray or np.matrix): raise ValueError("x is not a numpy.ndarray or numpy.matrix.") # index idx = np.logical_not(n...
[ "def", "drop_empty_records", "(", "x", ",", "axis", "=", "1", ")", ":", "# load module", "import", "numpy", "as", "np", "# input args check", "if", "not", "isinstance", "(", "x", ",", "np", ".", "ndarray", "or", "np", ".", "matrix", ")", ":", "raise", ...
delete data items that contains only nan (or inf)
[ "delete", "data", "items", "that", "contains", "only", "nan", "(", "or", "inf", ")" ]
train
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/drop_empty_records.py#L2-L19
minhhoit/yacms
yacms/utils/views.py
is_editable
def is_editable(obj, request): """ Returns ``True`` if the object is editable for the request. First check for a custom ``editable`` handler on the object, otherwise use the logged in user and check change permissions for the object's model. """ if hasattr(obj, "is_editable"): return...
python
def is_editable(obj, request): """ Returns ``True`` if the object is editable for the request. First check for a custom ``editable`` handler on the object, otherwise use the logged in user and check change permissions for the object's model. """ if hasattr(obj, "is_editable"): return...
[ "def", "is_editable", "(", "obj", ",", "request", ")", ":", "if", "hasattr", "(", "obj", ",", "\"is_editable\"", ")", ":", "return", "obj", ".", "is_editable", "(", "request", ")", "else", ":", "codename", "=", "get_permission_codename", "(", "\"change\"", ...
Returns ``True`` if the object is editable for the request. First check for a custom ``editable`` handler on the object, otherwise use the logged in user and check change permissions for the object's model.
[ "Returns", "True", "if", "the", "object", "is", "editable", "for", "the", "request", ".", "First", "check", "for", "a", "custom", "editable", "handler", "on", "the", "object", "otherwise", "use", "the", "logged", "in", "user", "and", "check", "change", "pe...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/views.py#L32-L46
minhhoit/yacms
yacms/utils/views.py
is_spam_akismet
def is_spam_akismet(request, form, url): """ Identifies form data as being spam, using the http://akismet.com service. The Akismet API key should be specified in the ``AKISMET_API_KEY`` setting. This function is the default spam handler defined in the ``SPAM_FILTERS`` setting. The name, email, ...
python
def is_spam_akismet(request, form, url): """ Identifies form data as being spam, using the http://akismet.com service. The Akismet API key should be specified in the ``AKISMET_API_KEY`` setting. This function is the default spam handler defined in the ``SPAM_FILTERS`` setting. The name, email, ...
[ "def", "is_spam_akismet", "(", "request", ",", "form", ",", "url", ")", ":", "if", "not", "settings", ".", "AKISMET_API_KEY", ":", "return", "False", "protocol", "=", "\"http\"", "if", "not", "request", ".", "is_secure", "(", ")", "else", "\"https\"", "hos...
Identifies form data as being spam, using the http://akismet.com service. The Akismet API key should be specified in the ``AKISMET_API_KEY`` setting. This function is the default spam handler defined in the ``SPAM_FILTERS`` setting. The name, email, url and comment fields are all guessed from the f...
[ "Identifies", "form", "data", "as", "being", "spam", "using", "the", "http", ":", "//", "akismet", ".", "com", "service", ".", "The", "Akismet", "API", "key", "should", "be", "specified", "in", "the", "AKISMET_API_KEY", "setting", ".", "This", "function", ...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/views.py#L58-L121
minhhoit/yacms
yacms/utils/views.py
is_spam
def is_spam(request, form, url): """ Main entry point for spam handling - called from the comment view and page processor for ``yacms.forms``, to check if posted content is spam. Spam filters are configured via the ``SPAM_FILTERS`` setting. """ for spam_filter_path in settings.SPAM_FILTERS: ...
python
def is_spam(request, form, url): """ Main entry point for spam handling - called from the comment view and page processor for ``yacms.forms``, to check if posted content is spam. Spam filters are configured via the ``SPAM_FILTERS`` setting. """ for spam_filter_path in settings.SPAM_FILTERS: ...
[ "def", "is_spam", "(", "request", ",", "form", ",", "url", ")", ":", "for", "spam_filter_path", "in", "settings", ".", "SPAM_FILTERS", ":", "spam_filter", "=", "import_dotted_path", "(", "spam_filter_path", ")", "if", "spam_filter", "(", "request", ",", "form"...
Main entry point for spam handling - called from the comment view and page processor for ``yacms.forms``, to check if posted content is spam. Spam filters are configured via the ``SPAM_FILTERS`` setting.
[ "Main", "entry", "point", "for", "spam", "handling", "-", "called", "from", "the", "comment", "view", "and", "page", "processor", "for", "yacms", ".", "forms", "to", "check", "if", "posted", "content", "is", "spam", ".", "Spam", "filters", "are", "configur...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/views.py#L124-L133
minhhoit/yacms
yacms/utils/views.py
paginate
def paginate(objects, page_num, per_page, max_paging_links): """ Return a paginated page for the given objects, giving it a custom ``visible_page_range`` attribute calculated from ``max_paging_links``. """ if not per_page: return Paginator(objects, 0) paginator = Paginator(objects, per_p...
python
def paginate(objects, page_num, per_page, max_paging_links): """ Return a paginated page for the given objects, giving it a custom ``visible_page_range`` attribute calculated from ``max_paging_links``. """ if not per_page: return Paginator(objects, 0) paginator = Paginator(objects, per_p...
[ "def", "paginate", "(", "objects", ",", "page_num", ",", "per_page", ",", "max_paging_links", ")", ":", "if", "not", "per_page", ":", "return", "Paginator", "(", "objects", ",", "0", ")", "paginator", "=", "Paginator", "(", "objects", ",", "per_page", ")",...
Return a paginated page for the given objects, giving it a custom ``visible_page_range`` attribute calculated from ``max_paging_links``.
[ "Return", "a", "paginated", "page", "for", "the", "given", "objects", "giving", "it", "a", "custom", "visible_page_range", "attribute", "calculated", "from", "max_paging_links", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/views.py#L136-L158
minhhoit/yacms
yacms/utils/views.py
render
def render(request, templates, dictionary=None, context_instance=None, **kwargs): """ Mimics ``django.shortcuts.render`` but uses a TemplateResponse for ``yacms.core.middleware.TemplateForDeviceMiddleware`` """ warnings.warn( "yacms.utils.views.render is deprecated and will be re...
python
def render(request, templates, dictionary=None, context_instance=None, **kwargs): """ Mimics ``django.shortcuts.render`` but uses a TemplateResponse for ``yacms.core.middleware.TemplateForDeviceMiddleware`` """ warnings.warn( "yacms.utils.views.render is deprecated and will be re...
[ "def", "render", "(", "request", ",", "templates", ",", "dictionary", "=", "None", ",", "context_instance", "=", "None", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"yacms.utils.views.render is deprecated and will be removed \"", "\"in a futur...
Mimics ``django.shortcuts.render`` but uses a TemplateResponse for ``yacms.core.middleware.TemplateForDeviceMiddleware``
[ "Mimics", "django", ".", "shortcuts", ".", "render", "but", "uses", "a", "TemplateResponse", "for", "yacms", ".", "core", ".", "middleware", ".", "TemplateForDeviceMiddleware" ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/views.py#L161-L180
minhhoit/yacms
yacms/utils/views.py
set_cookie
def set_cookie(response, name, value, expiry_seconds=None, secure=False): """ Set cookie wrapper that allows number of seconds to be given as the expiry time, and ensures values are correctly encoded. """ if expiry_seconds is None: expiry_seconds = 90 * 24 * 60 * 60 # Default to 90 days. ...
python
def set_cookie(response, name, value, expiry_seconds=None, secure=False): """ Set cookie wrapper that allows number of seconds to be given as the expiry time, and ensures values are correctly encoded. """ if expiry_seconds is None: expiry_seconds = 90 * 24 * 60 * 60 # Default to 90 days. ...
[ "def", "set_cookie", "(", "response", ",", "name", ",", "value", ",", "expiry_seconds", "=", "None", ",", "secure", "=", "False", ")", ":", "if", "expiry_seconds", "is", "None", ":", "expiry_seconds", "=", "90", "*", "24", "*", "60", "*", "60", "# Defa...
Set cookie wrapper that allows number of seconds to be given as the expiry time, and ensures values are correctly encoded.
[ "Set", "cookie", "wrapper", "that", "allows", "number", "of", "seconds", "to", "be", "given", "as", "the", "expiry", "time", "and", "ensures", "values", "are", "correctly", "encoded", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/views.py#L183-L200
coghost/izen
izen/chaos.py
Chaos.encrypt
def encrypt(self, plain, algorithm='md5'): """ 简单封装系统加密 :param plain: 待加密内容 :type plain: ``str/bytes`` :param algorithm: 加密算法 :type algorithm: str :return: :rtype: """ plain = helper.to_bytes(plain) return getattr(hashlib, algorithm)(plai...
python
def encrypt(self, plain, algorithm='md5'): """ 简单封装系统加密 :param plain: 待加密内容 :type plain: ``str/bytes`` :param algorithm: 加密算法 :type algorithm: str :return: :rtype: """ plain = helper.to_bytes(plain) return getattr(hashlib, algorithm)(plai...
[ "def", "encrypt", "(", "self", ",", "plain", ",", "algorithm", "=", "'md5'", ")", ":", "plain", "=", "helper", ".", "to_bytes", "(", "plain", ")", "return", "getattr", "(", "hashlib", ",", "algorithm", ")", "(", "plain", ")", ".", "hexdigest", "(", "...
简单封装系统加密 :param plain: 待加密内容 :type plain: ``str/bytes`` :param algorithm: 加密算法 :type algorithm: str :return: :rtype:
[ "简单封装系统加密" ]
train
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/chaos.py#L48-L59
coghost/izen
izen/chaos.py
Chaos.aes_obj
def aes_obj(self, sec_key, encrypt_sec_key=True): """ 生成aes加密所需要的 ``key, iv`` .. warning:: 每个AES.new对象, 只能使用一次 :param sec_key: :type sec_key: str :param encrypt_sec_key: ``如果为true, 则md5加密 sec_key, 生成 key,iv, 否则直接使用 sec_key, 来作为key,iv`` :type encrypt_sec_key:...
python
def aes_obj(self, sec_key, encrypt_sec_key=True): """ 生成aes加密所需要的 ``key, iv`` .. warning:: 每个AES.new对象, 只能使用一次 :param sec_key: :type sec_key: str :param encrypt_sec_key: ``如果为true, 则md5加密 sec_key, 生成 key,iv, 否则直接使用 sec_key, 来作为key,iv`` :type encrypt_sec_key:...
[ "def", "aes_obj", "(", "self", ",", "sec_key", ",", "encrypt_sec_key", "=", "True", ")", ":", "# 使用 md5加密 key, 获取32个长度, 拆分为两个16长度作为 AES的 key, iv", "p", "=", "self", ".", "encrypt", "(", "sec_key", ")", "if", "encrypt_sec_key", "else", "sec_key", "key", ",", "iv"...
生成aes加密所需要的 ``key, iv`` .. warning:: 每个AES.new对象, 只能使用一次 :param sec_key: :type sec_key: str :param encrypt_sec_key: ``如果为true, 则md5加密 sec_key, 生成 key,iv, 否则直接使用 sec_key, 来作为key,iv`` :type encrypt_sec_key: bool :return: :rtype:
[ "生成aes加密所需要的", "key", "iv" ]
train
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/chaos.py#L61-L78
coghost/izen
izen/chaos.py
Chaos.aes_encrypt
def aes_encrypt(self, plain, sec_key, enable_b64=True): """ 使用 ``aes`` 加密数据, 并由 ``base64编码`` 加密后的数据 - ``sec_key`` 加密 ``msg``, 最后选择 ``是否由base64编码数据`` - msg长度为16位数, 不足则补 'ascii \\0' .. warning:: msg长度为16位数, 不足则补 'ascii \\0' :param plain: :type pl...
python
def aes_encrypt(self, plain, sec_key, enable_b64=True): """ 使用 ``aes`` 加密数据, 并由 ``base64编码`` 加密后的数据 - ``sec_key`` 加密 ``msg``, 最后选择 ``是否由base64编码数据`` - msg长度为16位数, 不足则补 'ascii \\0' .. warning:: msg长度为16位数, 不足则补 'ascii \\0' :param plain: :type pl...
[ "def", "aes_encrypt", "(", "self", ",", "plain", ",", "sec_key", ",", "enable_b64", "=", "True", ")", ":", "plain", "=", "helper", ".", "to_str", "(", "plain", ")", "sec_key", "=", "helper", ".", "to_str", "(", "sec_key", ")", "# 如果msg长度不为16倍数, 需要补位 '\\0'"...
使用 ``aes`` 加密数据, 并由 ``base64编码`` 加密后的数据 - ``sec_key`` 加密 ``msg``, 最后选择 ``是否由base64编码数据`` - msg长度为16位数, 不足则补 'ascii \\0' .. warning:: msg长度为16位数, 不足则补 'ascii \\0' :param plain: :type plain: str :param sec_key: :type sec_key: str :param enab...
[ "使用", "aes", "加密数据", "并由", "base64编码", "加密后的数据" ]
train
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/chaos.py#L80-L108
coghost/izen
izen/chaos.py
Chaos.aes_decrypt
def aes_decrypt(self, cipher, sec_key, enable_b64=True): """ 由 ``base64解码数据``, 然后再使用 ``aes`` 解密数据 - 使用 ``sec_key`` 解密由 ``base64解码后的cipher`` 数据 - 先base64 decode, 再解密, 最后移除补位值 'ascii \\0' :param cipher: :type cipher: str :param sec_key: :type sec_key: ...
python
def aes_decrypt(self, cipher, sec_key, enable_b64=True): """ 由 ``base64解码数据``, 然后再使用 ``aes`` 解密数据 - 使用 ``sec_key`` 解密由 ``base64解码后的cipher`` 数据 - 先base64 decode, 再解密, 最后移除补位值 'ascii \\0' :param cipher: :type cipher: str :param sec_key: :type sec_key: ...
[ "def", "aes_decrypt", "(", "self", ",", "cipher", ",", "sec_key", ",", "enable_b64", "=", "True", ")", ":", "cipher", "=", "base64", ".", "b64decode", "(", "cipher", ")", "if", "enable_b64", "else", "cipher", "plain_", "=", "self", ".", "aes_obj", "(", ...
由 ``base64解码数据``, 然后再使用 ``aes`` 解密数据 - 使用 ``sec_key`` 解密由 ``base64解码后的cipher`` 数据 - 先base64 decode, 再解密, 最后移除补位值 'ascii \\0' :param cipher: :type cipher: str :param sec_key: :type sec_key: str :param enable_b64: :type enable_b64: bool :return: ...
[ "由", "base64解码数据", "然后再使用", "aes", "解密数据" ]
train
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/chaos.py#L110-L129
coghost/izen
izen/chaos.py
RsaPub.rsa_base64_encrypt
def rsa_base64_encrypt(self, plain, b64=True): """ 使用公钥加密 ``可见数据`` - 由于rsa公钥加密相对耗时, 多用来 ``加密数据量小`` 的数据 .. note:: 1. 使用aes加密数据 2. 然后rsa用来加密aes加密数据时使用的key :param plain: :type plain: :param b64: :type b64: :return: ...
python
def rsa_base64_encrypt(self, plain, b64=True): """ 使用公钥加密 ``可见数据`` - 由于rsa公钥加密相对耗时, 多用来 ``加密数据量小`` 的数据 .. note:: 1. 使用aes加密数据 2. 然后rsa用来加密aes加密数据时使用的key :param plain: :type plain: :param b64: :type b64: :return: ...
[ "def", "rsa_base64_encrypt", "(", "self", ",", "plain", ",", "b64", "=", "True", ")", ":", "with", "open", "(", "self", ".", "key_file", ")", "as", "fp", ":", "key_", "=", "RSA", ".", "importKey", "(", "fp", ".", "read", "(", ")", ")", "plain", "...
使用公钥加密 ``可见数据`` - 由于rsa公钥加密相对耗时, 多用来 ``加密数据量小`` 的数据 .. note:: 1. 使用aes加密数据 2. 然后rsa用来加密aes加密数据时使用的key :param plain: :type plain: :param b64: :type b64: :return: :rtype:
[ "使用公钥加密", "可见数据" ]
train
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/chaos.py#L143-L165
coghost/izen
izen/chaos.py
RsaPub.rsa_check_base64_sign_str
def rsa_check_base64_sign_str(self, cipher, sign, b64=True): """ 验证服务端数据 ``rsa`` 签名 """ with open(self.key_file) as fp: key_ = RSA.importKey(fp.read()) v = pkcs.new(key_) sign = base64.b64decode(sign) if b64 else sign cipher = helper.t...
python
def rsa_check_base64_sign_str(self, cipher, sign, b64=True): """ 验证服务端数据 ``rsa`` 签名 """ with open(self.key_file) as fp: key_ = RSA.importKey(fp.read()) v = pkcs.new(key_) sign = base64.b64decode(sign) if b64 else sign cipher = helper.t...
[ "def", "rsa_check_base64_sign_str", "(", "self", ",", "cipher", ",", "sign", ",", "b64", "=", "True", ")", ":", "with", "open", "(", "self", ".", "key_file", ")", "as", "fp", ":", "key_", "=", "RSA", ".", "importKey", "(", "fp", ".", "read", "(", "...
验证服务端数据 ``rsa`` 签名
[ "验证服务端数据", "rsa", "签名" ]
train
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/chaos.py#L167-L179
coghost/izen
izen/chaos.py
RsaPriv.rsa_base64_decrypt
def rsa_base64_decrypt(self, cipher, b64=True): """ 先base64 解码 再rsa 解密数据 """ with open(self.key_file) as fp: key_ = RSA.importKey(fp.read()) _cip = PKCS1_v1_5.new(key_) cipher = base64.b64decode(cipher) if b64 else cipher plain = _cip.d...
python
def rsa_base64_decrypt(self, cipher, b64=True): """ 先base64 解码 再rsa 解密数据 """ with open(self.key_file) as fp: key_ = RSA.importKey(fp.read()) _cip = PKCS1_v1_5.new(key_) cipher = base64.b64decode(cipher) if b64 else cipher plain = _cip.d...
[ "def", "rsa_base64_decrypt", "(", "self", ",", "cipher", ",", "b64", "=", "True", ")", ":", "with", "open", "(", "self", ".", "key_file", ")", "as", "fp", ":", "key_", "=", "RSA", ".", "importKey", "(", "fp", ".", "read", "(", ")", ")", "_cip", "...
先base64 解码 再rsa 解密数据
[ "先base64", "解码", "再rsa", "解密数据" ]
train
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/chaos.py#L193-L202
coghost/izen
izen/chaos.py
RsaPriv.rsa_base64_sign_str
def rsa_base64_sign_str(self, plain, b64=True): """ 对 msg rsa 签名, 然后使用 base64 encode 编码数据 """ with open(self.key_file) as fp: key_ = RSA.importKey(fp.read()) # h = SHA.new(plain if sys.version_info < (3, 0) else plain.encode('utf-8')) plain = help...
python
def rsa_base64_sign_str(self, plain, b64=True): """ 对 msg rsa 签名, 然后使用 base64 encode 编码数据 """ with open(self.key_file) as fp: key_ = RSA.importKey(fp.read()) # h = SHA.new(plain if sys.version_info < (3, 0) else plain.encode('utf-8')) plain = help...
[ "def", "rsa_base64_sign_str", "(", "self", ",", "plain", ",", "b64", "=", "True", ")", ":", "with", "open", "(", "self", ".", "key_file", ")", "as", "fp", ":", "key_", "=", "RSA", ".", "importKey", "(", "fp", ".", "read", "(", ")", ")", "# h = SHA....
对 msg rsa 签名, 然后使用 base64 encode 编码数据
[ "对", "msg", "rsa", "签名", "然后使用", "base64", "encode", "编码数据" ]
train
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/chaos.py#L204-L218
MitalAshok/objecttools
objecttools/cached_property.py
CachedProperty.getter
def getter(self, fget): """ Change the getter for this descriptor to use to get the value :param fget: Function to call with an object as its only argument :type fget: Callable[[Any], Any] :return: self, so this can be used as a decorator like a `property` :rtype: Cached...
python
def getter(self, fget): """ Change the getter for this descriptor to use to get the value :param fget: Function to call with an object as its only argument :type fget: Callable[[Any], Any] :return: self, so this can be used as a decorator like a `property` :rtype: Cached...
[ "def", "getter", "(", "self", ",", "fget", ")", ":", "if", "getattr", "(", "self", ",", "'__doc__'", ",", "None", ")", "is", "None", ":", "self", ".", "__doc__", "=", "getattr", "(", "fget", ",", "_FUNC_DOC", ",", "None", ")", "if", "self", ".", ...
Change the getter for this descriptor to use to get the value :param fget: Function to call with an object as its only argument :type fget: Callable[[Any], Any] :return: self, so this can be used as a decorator like a `property` :rtype: CachedProperty
[ "Change", "the", "getter", "for", "this", "descriptor", "to", "use", "to", "get", "the", "value" ]
train
https://github.com/MitalAshok/objecttools/blob/bddd14d1f702c8b559d3fcc2099bc22370e16de7/objecttools/cached_property.py#L94-L108
MitalAshok/objecttools
objecttools/cached_property.py
CachedProperty.setter
def setter(self, can_set=None): """ Like `CachedProp.deleter` is for `CachedProp.can_delete`, but for `can_set` :param can_set: boolean to change to it, and None to toggle :type can_set: Optional[bool] :return: self, so this can be used as a decorator like a `property` :...
python
def setter(self, can_set=None): """ Like `CachedProp.deleter` is for `CachedProp.can_delete`, but for `can_set` :param can_set: boolean to change to it, and None to toggle :type can_set: Optional[bool] :return: self, so this can be used as a decorator like a `property` :...
[ "def", "setter", "(", "self", ",", "can_set", "=", "None", ")", ":", "if", "can_set", "is", "None", ":", "self", ".", "_setter", "=", "not", "self", ".", "_setter", "else", ":", "self", ".", "_setter", "=", "bool", "(", "can_set", ")", "# For use as ...
Like `CachedProp.deleter` is for `CachedProp.can_delete`, but for `can_set` :param can_set: boolean to change to it, and None to toggle :type can_set: Optional[bool] :return: self, so this can be used as a decorator like a `property` :rtype: CachedProperty
[ "Like", "CachedProp", ".", "deleter", "is", "for", "CachedProp", ".", "can_delete", "but", "for", "can_set" ]
train
https://github.com/MitalAshok/objecttools/blob/bddd14d1f702c8b559d3fcc2099bc22370e16de7/objecttools/cached_property.py#L110-L124
MitalAshok/objecttools
objecttools/cached_property.py
CachedProperty.deleter
def deleter(self, can_delete=None): """ Change if this descriptor's can be invalidated through `del obj.attr`. `cached_prop.deleter(True)` and:: @cached_prop.deleter def cached_prop(self): pass are equivalent to `cached_prop.can_delete = True`. ...
python
def deleter(self, can_delete=None): """ Change if this descriptor's can be invalidated through `del obj.attr`. `cached_prop.deleter(True)` and:: @cached_prop.deleter def cached_prop(self): pass are equivalent to `cached_prop.can_delete = True`. ...
[ "def", "deleter", "(", "self", ",", "can_delete", "=", "None", ")", ":", "if", "can_delete", "is", "None", ":", "self", ".", "_deleter", "=", "not", "self", ".", "_deleter", "else", ":", "self", ".", "_deleter", "=", "bool", "(", "can_delete", ")", "...
Change if this descriptor's can be invalidated through `del obj.attr`. `cached_prop.deleter(True)` and:: @cached_prop.deleter def cached_prop(self): pass are equivalent to `cached_prop.can_delete = True`. :param can_delete: boolean to change to it, and...
[ "Change", "if", "this", "descriptor", "s", "can", "be", "invalidated", "through", "del", "obj", ".", "attr", "." ]
train
https://github.com/MitalAshok/objecttools/blob/bddd14d1f702c8b559d3fcc2099bc22370e16de7/objecttools/cached_property.py#L139-L161
blubberdiblub/eztemplate
eztemplate/engines/string_template_engine.py
StringTemplate.apply
def apply(self, mapping): """Apply a mapping of name-value-pairs to a template.""" mapping = {name: self.str(value, tolerant=self.tolerant) for name, value in mapping.items() if value is not None or self.tolerant} if self.tolerant: return self.t...
python
def apply(self, mapping): """Apply a mapping of name-value-pairs to a template.""" mapping = {name: self.str(value, tolerant=self.tolerant) for name, value in mapping.items() if value is not None or self.tolerant} if self.tolerant: return self.t...
[ "def", "apply", "(", "self", ",", "mapping", ")", ":", "mapping", "=", "{", "name", ":", "self", ".", "str", "(", "value", ",", "tolerant", "=", "self", ".", "tolerant", ")", "for", "name", ",", "value", "in", "mapping", ".", "items", "(", ")", "...
Apply a mapping of name-value-pairs to a template.
[ "Apply", "a", "mapping", "of", "name", "-", "value", "-", "pairs", "to", "a", "template", "." ]
train
https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/engines/string_template_engine.py#L25-L34
exekias/droplet
droplet/files.py
ConfFile.write
def write(self): """ Write the file, forcing the proper permissions """ with root(): self._write_log() with open(self.path, 'w') as f: # file owner os.chown(self.path, self.uid(), self.gid()) # mode ...
python
def write(self): """ Write the file, forcing the proper permissions """ with root(): self._write_log() with open(self.path, 'w') as f: # file owner os.chown(self.path, self.uid(), self.gid()) # mode ...
[ "def", "write", "(", "self", ")", ":", "with", "root", "(", ")", ":", "self", ".", "_write_log", "(", ")", "with", "open", "(", "self", ".", "path", ",", "'w'", ")", "as", "f", ":", "# file owner", "os", ".", "chown", "(", "self", ".", "path", ...
Write the file, forcing the proper permissions
[ "Write", "the", "file", "forcing", "the", "proper", "permissions" ]
train
https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/files.py#L53-L69
exekias/droplet
droplet/files.py
ConfFile._write_log
def _write_log(self): """ Write log info """ logger.info("Writing config file %s" % self.path) if settings.DEBUG: try: old_content = open(self.path, 'r').readlines() except IOError: old_content = '' new_content...
python
def _write_log(self): """ Write log info """ logger.info("Writing config file %s" % self.path) if settings.DEBUG: try: old_content = open(self.path, 'r').readlines() except IOError: old_content = '' new_content...
[ "def", "_write_log", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Writing config file %s\"", "%", "self", ".", "path", ")", "if", "settings", ".", "DEBUG", ":", "try", ":", "old_content", "=", "open", "(", "self", ".", "path", ",", "'r'", ")",...
Write log info
[ "Write", "log", "info" ]
train
https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/files.py#L77-L95
tschaume/ccsgp_get_started
ccsgp_get_started/examples/gp_rapp.py
gp_rapp
def gp_rapp(): """rho in-medium ratios by Rapp (based on protected data)""" inDir, outDir = getWorkDirs() # prepare data yields = {} for infile in os.listdir(inDir): energy = re.compile('\d+').search(infile).group() medium = np.loadtxt(open(os.path.join(inDir, infile), 'rb')) getMassRangesSums(ene...
python
def gp_rapp(): """rho in-medium ratios by Rapp (based on protected data)""" inDir, outDir = getWorkDirs() # prepare data yields = {} for infile in os.listdir(inDir): energy = re.compile('\d+').search(infile).group() medium = np.loadtxt(open(os.path.join(inDir, infile), 'rb')) getMassRangesSums(ene...
[ "def", "gp_rapp", "(", ")", ":", "inDir", ",", "outDir", "=", "getWorkDirs", "(", ")", "# prepare data", "yields", "=", "{", "}", "for", "infile", "in", "os", ".", "listdir", "(", "inDir", ")", ":", "energy", "=", "re", ".", "compile", "(", "'\\d+'",...
rho in-medium ratios by Rapp (based on protected data)
[ "rho", "in", "-", "medium", "ratios", "by", "Rapp", "(", "based", "on", "protected", "data", ")" ]
train
https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_rapp.py#L9-L36
SkyTruth/vectortile
utils/tileinfo.py
info
def info(data, cols): """ Compute min/max for all registered columns. Parameters ---------- data : list List of points from tile. cols : list List of columns from tile header. Returns ------- dict { column: { min: value, ...
python
def info(data, cols): """ Compute min/max for all registered columns. Parameters ---------- data : list List of points from tile. cols : list List of columns from tile header. Returns ------- dict { column: { min: value, ...
[ "def", "info", "(", "data", ",", "cols", ")", ":", "stats", "=", "{", "c", "[", "'name'", "]", ":", "[", "]", "for", "c", "in", "cols", "}", "for", "point", "in", "data", ":", "for", "c", ",", "v", "in", "point", ".", "items", "(", ")", ":"...
Compute min/max for all registered columns. Parameters ---------- data : list List of points from tile. cols : list List of columns from tile header. Returns ------- dict { column: { min: value, max: value } ...
[ "Compute", "min", "/", "max", "for", "all", "registered", "columns", "." ]
train
https://github.com/SkyTruth/vectortile/blob/f4838545d9f10f3c6b21d714470826b40ce75848/utils/tileinfo.py#L25-L52
SkyTruth/vectortile
utils/tileinfo.py
main
def main(): """ Get an info report for a tile. Format is same as input tile but with min/max values for values under 'data'. """ arguments = docopt(__doc__, version='tileinfo 0.1') src_name = arguments['SOURCE'] src_format = arguments['--srcformat'] indent = arguments['--indent'] ...
python
def main(): """ Get an info report for a tile. Format is same as input tile but with min/max values for values under 'data'. """ arguments = docopt(__doc__, version='tileinfo 0.1') src_name = arguments['SOURCE'] src_format = arguments['--srcformat'] indent = arguments['--indent'] ...
[ "def", "main", "(", ")", ":", "arguments", "=", "docopt", "(", "__doc__", ",", "version", "=", "'tileinfo 0.1'", ")", "src_name", "=", "arguments", "[", "'SOURCE'", "]", "src_format", "=", "arguments", "[", "'--srcformat'", "]", "indent", "=", "arguments", ...
Get an info report for a tile. Format is same as input tile but with min/max values for values under 'data'.
[ "Get", "an", "info", "report", "for", "a", "tile", ".", "Format", "is", "same", "as", "input", "tile", "but", "with", "min", "/", "max", "values", "for", "values", "under", "data", "." ]
train
https://github.com/SkyTruth/vectortile/blob/f4838545d9f10f3c6b21d714470826b40ce75848/utils/tileinfo.py#L55-L99
cirruscluster/cirruscluster
cirruscluster/ami/builder.py
GetAmi
def GetAmi(ec2, ami_spec): """ Get the boto ami object given a AmiSpecification object. """ images = ec2.get_all_images(owners=[ami_spec.owner_id] ) requested_image = None for image in images: if image.name == ami_spec.ami_name: requested_image = image break return requested_i...
python
def GetAmi(ec2, ami_spec): """ Get the boto ami object given a AmiSpecification object. """ images = ec2.get_all_images(owners=[ami_spec.owner_id] ) requested_image = None for image in images: if image.name == ami_spec.ami_name: requested_image = image break return requested_i...
[ "def", "GetAmi", "(", "ec2", ",", "ami_spec", ")", ":", "images", "=", "ec2", ".", "get_all_images", "(", "owners", "=", "[", "ami_spec", ".", "owner_id", "]", ")", "requested_image", "=", "None", "for", "image", "in", "images", ":", "if", "image", "."...
Get the boto ami object given a AmiSpecification object.
[ "Get", "the", "boto", "ami", "object", "given", "a", "AmiSpecification", "object", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ami/builder.py#L53-L61
cirruscluster/cirruscluster
cirruscluster/ami/builder.py
AmiBuilder.Run
def Run(self): """ Build the Amazon Machine Image. """ template_instance = None res = self.ec2.get_all_instances( \ filters={'tag-key': 'spec', 'tag-value' : self.ami_spec.ami_name, 'instance-state-name' : 'running'}) if res: running_templ...
python
def Run(self): """ Build the Amazon Machine Image. """ template_instance = None res = self.ec2.get_all_instances( \ filters={'tag-key': 'spec', 'tag-value' : self.ami_spec.ami_name, 'instance-state-name' : 'running'}) if res: running_templ...
[ "def", "Run", "(", "self", ")", ":", "template_instance", "=", "None", "res", "=", "self", ".", "ec2", ".", "get_all_instances", "(", "filters", "=", "{", "'tag-key'", ":", "'spec'", ",", "'tag-value'", ":", "self", ".", "ami_spec", ".", "ami_name", ",",...
Build the Amazon Machine Image.
[ "Build", "the", "Amazon", "Machine", "Image", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ami/builder.py#L79-L133
ramrod-project/database-brain
schema/brain/environment.py
log_env_gte
def log_env_gte(desired): """ Boolean check if the current environment LOGLEVEL is at least as verbose as a desired LOGLEVEL :param desired: <str> one of 9 keys in <brain.environment.stage> :return: <bool> """ return LOGLEVELS.get(check_log_env()) >= LOGLEVELS.get(desired, LOGLEVELS[TEST])
python
def log_env_gte(desired): """ Boolean check if the current environment LOGLEVEL is at least as verbose as a desired LOGLEVEL :param desired: <str> one of 9 keys in <brain.environment.stage> :return: <bool> """ return LOGLEVELS.get(check_log_env()) >= LOGLEVELS.get(desired, LOGLEVELS[TEST])
[ "def", "log_env_gte", "(", "desired", ")", ":", "return", "LOGLEVELS", ".", "get", "(", "check_log_env", "(", ")", ")", ">=", "LOGLEVELS", ".", "get", "(", "desired", ",", "LOGLEVELS", "[", "TEST", "]", ")" ]
Boolean check if the current environment LOGLEVEL is at least as verbose as a desired LOGLEVEL :param desired: <str> one of 9 keys in <brain.environment.stage> :return: <bool>
[ "Boolean", "check", "if", "the", "current", "environment", "LOGLEVEL", "is", "at", "least", "as", "verbose", "as", "a", "desired", "LOGLEVEL" ]
train
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/environment.py#L50-L58
wlwang41/cb
cb/tools.py
copytree
def copytree(src, dst, symlinks=False, ignore=None): """Copy from source directory to destination""" # TODO(crow): OSError: [Errno 17] File exists if not osp.exists(dst): os.makedirs(dst) for item in os.listdir(src): s = osp.join(src, item) d = osp.join(dst, item) if osp...
python
def copytree(src, dst, symlinks=False, ignore=None): """Copy from source directory to destination""" # TODO(crow): OSError: [Errno 17] File exists if not osp.exists(dst): os.makedirs(dst) for item in os.listdir(src): s = osp.join(src, item) d = osp.join(dst, item) if osp...
[ "def", "copytree", "(", "src", ",", "dst", ",", "symlinks", "=", "False", ",", "ignore", "=", "None", ")", ":", "# TODO(crow): OSError: [Errno 17] File exists", "if", "not", "osp", ".", "exists", "(", "dst", ")", ":", "os", ".", "makedirs", "(", "dst", "...
Copy from source directory to destination
[ "Copy", "from", "source", "directory", "to", "destination" ]
train
https://github.com/wlwang41/cb/blob/0a7faa427e3e6593980687dfe1a882ac99d743f6/cb/tools.py#L58-L70
wlwang41/cb
cb/tools.py
emptytree
def emptytree(directory): """Delete all the files and dirs under specified directory""" for p in os.listdir(directory): fp = osp.join(directory, p) if osp.isdir(fp): try: shutil.rmtree(fp) logger.info("Delete directory %s" % fp) except Exc...
python
def emptytree(directory): """Delete all the files and dirs under specified directory""" for p in os.listdir(directory): fp = osp.join(directory, p) if osp.isdir(fp): try: shutil.rmtree(fp) logger.info("Delete directory %s" % fp) except Exc...
[ "def", "emptytree", "(", "directory", ")", ":", "for", "p", "in", "os", ".", "listdir", "(", "directory", ")", ":", "fp", "=", "osp", ".", "join", "(", "directory", ",", "p", ")", "if", "osp", ".", "isdir", "(", "fp", ")", ":", "try", ":", "shu...
Delete all the files and dirs under specified directory
[ "Delete", "all", "the", "files", "and", "dirs", "under", "specified", "directory" ]
train
https://github.com/wlwang41/cb/blob/0a7faa427e3e6593980687dfe1a882ac99d743f6/cb/tools.py#L73-L91
wlwang41/cb
cb/tools.py
listdir_nohidden
def listdir_nohidden(path): """List not hidden files or directories under path""" for f in os.listdir(path): if isinstance(f, str): f = unicode(f, "utf-8") if not f.startswith('.'): yield f
python
def listdir_nohidden(path): """List not hidden files or directories under path""" for f in os.listdir(path): if isinstance(f, str): f = unicode(f, "utf-8") if not f.startswith('.'): yield f
[ "def", "listdir_nohidden", "(", "path", ")", ":", "for", "f", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "isinstance", "(", "f", ",", "str", ")", ":", "f", "=", "unicode", "(", "f", ",", "\"utf-8\"", ")", "if", "not", "f", ".", "s...
List not hidden files or directories under path
[ "List", "not", "hidden", "files", "or", "directories", "under", "path" ]
train
https://github.com/wlwang41/cb/blob/0a7faa427e3e6593980687dfe1a882ac99d743f6/cb/tools.py#L105-L111
wlwang41/cb
cb/tools.py
check_config
def check_config(data): """Check if metadata is right TODO(crow): check more """ is_right = True if "title" not in data: logging.error("No 'title' in _config.yml") is_right = False return is_right
python
def check_config(data): """Check if metadata is right TODO(crow): check more """ is_right = True if "title" not in data: logging.error("No 'title' in _config.yml") is_right = False return is_right
[ "def", "check_config", "(", "data", ")", ":", "is_right", "=", "True", "if", "\"title\"", "not", "in", "data", ":", "logging", ".", "error", "(", "\"No 'title' in _config.yml\"", ")", "is_right", "=", "False", "return", "is_right" ]
Check if metadata is right TODO(crow): check more
[ "Check", "if", "metadata", "is", "right" ]
train
https://github.com/wlwang41/cb/blob/0a7faa427e3e6593980687dfe1a882ac99d743f6/cb/tools.py#L131-L143
wlwang41/cb
cb/tools.py
get_ymal_data
def get_ymal_data(data): """Get metadata and validate them :param data: metadata in yaml format """ try: format_data = yaml.load(data) except yaml.YAMLError, e: msg = "Yaml format error: {}".format( unicode(str(e), "utf-8") ) logging.error(msg) sy...
python
def get_ymal_data(data): """Get metadata and validate them :param data: metadata in yaml format """ try: format_data = yaml.load(data) except yaml.YAMLError, e: msg = "Yaml format error: {}".format( unicode(str(e), "utf-8") ) logging.error(msg) sy...
[ "def", "get_ymal_data", "(", "data", ")", ":", "try", ":", "format_data", "=", "yaml", ".", "load", "(", "data", ")", "except", "yaml", ".", "YAMLError", ",", "e", ":", "msg", "=", "\"Yaml format error: {}\"", ".", "format", "(", "unicode", "(", "str", ...
Get metadata and validate them :param data: metadata in yaml format
[ "Get", "metadata", "and", "validate", "them" ]
train
https://github.com/wlwang41/cb/blob/0a7faa427e3e6593980687dfe1a882ac99d743f6/cb/tools.py#L146-L163
wlwang41/cb
cb/tools.py
parse_markdown
def parse_markdown(markdown_content, site_settings): """Parse markdown text to html. :param markdown_content: Markdown text lists #TODO# """ markdown_extensions = set_markdown_extensions(site_settings) html_content = markdown.markdown( markdown_content, extensions=markdown_extensio...
python
def parse_markdown(markdown_content, site_settings): """Parse markdown text to html. :param markdown_content: Markdown text lists #TODO# """ markdown_extensions = set_markdown_extensions(site_settings) html_content = markdown.markdown( markdown_content, extensions=markdown_extensio...
[ "def", "parse_markdown", "(", "markdown_content", ",", "site_settings", ")", ":", "markdown_extensions", "=", "set_markdown_extensions", "(", "site_settings", ")", "html_content", "=", "markdown", ".", "markdown", "(", "markdown_content", ",", "extensions", "=", "mark...
Parse markdown text to html. :param markdown_content: Markdown text lists #TODO#
[ "Parse", "markdown", "text", "to", "html", "." ]
train
https://github.com/wlwang41/cb/blob/0a7faa427e3e6593980687dfe1a882ac99d743f6/cb/tools.py#L180-L192
fopina/tgbotplug
tgbot/botapi.py
send_message
def send_message(chat_id, text, parse_mode=None, disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None, **kwargs): """ Use this method to send text messages. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param ...
python
def send_message(chat_id, text, parse_mode=None, disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None, **kwargs): """ Use this method to send text messages. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param ...
[ "def", "send_message", "(", "chat_id", ",", "text", ",", "parse_mode", "=", "None", ",", "disable_web_page_preview", "=", "None", ",", "reply_to_message_id", "=", "None", ",", "reply_markup", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# required args", ...
Use this method to send text messages. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param text: Text of the message to be sent :param parse_mode: Send ``"Markdown"``, if you want Telegram apps to show bold, italic and inline URLs in your bot's m...
[ "Use", "this", "method", "to", "send", "text", "messages", "." ]
train
https://github.com/fopina/tgbotplug/blob/c115733b03f2e23ddcdecfce588d1a6a1e5bde91/tgbot/botapi.py#L1261-L1301
fopina/tgbotplug
tgbot/botapi.py
forward_message
def forward_message(chat_id, from_chat_id, message_id, **kwargs): """ Use this method to forward messages of any kind. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param from_chat_id: Unique identifier for the chat where the original message wa...
python
def forward_message(chat_id, from_chat_id, message_id, **kwargs): """ Use this method to forward messages of any kind. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param from_chat_id: Unique identifier for the chat where the original message wa...
[ "def", "forward_message", "(", "chat_id", ",", "from_chat_id", ",", "message_id", ",", "*", "*", "kwargs", ")", ":", "# required args", "params", "=", "dict", "(", "chat_id", "=", "chat_id", ",", "from_chat_id", "=", "from_chat_id", ",", "message_id", "=", "...
Use this method to forward messages of any kind. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param from_chat_id: Unique identifier for the chat where the original message was sent — User or GroupChat id :param message_id: Unique message ident...
[ "Use", "this", "method", "to", "forward", "messages", "of", "any", "kind", "." ]
train
https://github.com/fopina/tgbotplug/blob/c115733b03f2e23ddcdecfce588d1a6a1e5bde91/tgbot/botapi.py#L1304-L1330
fopina/tgbotplug
tgbot/botapi.py
send_document
def send_document(chat_id, document, reply_to_message_id=None, reply_markup=None, **kwargs): """ Use this method to send general files. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param document: File to send. You can either pa...
python
def send_document(chat_id, document, reply_to_message_id=None, reply_markup=None, **kwargs): """ Use this method to send general files. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param document: File to send. You can either pa...
[ "def", "send_document", "(", "chat_id", ",", "document", ",", "reply_to_message_id", "=", "None", ",", "reply_markup", "=", "None", ",", "*", "*", "kwargs", ")", ":", "files", "=", "None", "if", "isinstance", "(", "document", ",", "InputFile", ")", ":", ...
Use this method to send general files. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param document: File to send. You can either pass a file_id as String to resend a file that is already on the Telegram servers, or upload a new file using multipart/fo...
[ "Use", "this", "method", "to", "send", "general", "files", "." ]
train
https://github.com/fopina/tgbotplug/blob/c115733b03f2e23ddcdecfce588d1a6a1e5bde91/tgbot/botapi.py#L1447-L1490
fopina/tgbotplug
tgbot/botapi.py
send_sticker
def send_sticker(chat_id, sticker, reply_to_message_id=None, reply_markup=None, **kwargs): """ :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param sticker: Sticker to send. You can either pass a file_id as String to resend a sticker ...
python
def send_sticker(chat_id, sticker, reply_to_message_id=None, reply_markup=None, **kwargs): """ :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param sticker: Sticker to send. You can either pass a file_id as String to resend a sticker ...
[ "def", "send_sticker", "(", "chat_id", ",", "sticker", ",", "reply_to_message_id", "=", "None", ",", "reply_markup", "=", "None", ",", "*", "*", "kwargs", ")", ":", "files", "=", "None", "if", "isinstance", "(", "sticker", ",", "InputFile", ")", ":", "fi...
:param chat_id: Unique identifier for the message recipient — User or GroupChat id :param sticker: Sticker to send. You can either pass a file_id as String to resend a sticker that is already on the Telegram servers, or upload a new sticker using multipart/form-data. :param reply_to_message_...
[ ":", "param", "chat_id", ":", "Unique", "identifier", "for", "the", "message", "recipient", "—", "User", "or", "GroupChat", "id", ":", "param", "sticker", ":", "Sticker", "to", "send", ".", "You", "can", "either", "pass", "a", "file_id", "as", "String", ...
train
https://github.com/fopina/tgbotplug/blob/c115733b03f2e23ddcdecfce588d1a6a1e5bde91/tgbot/botapi.py#L1493-L1534
fopina/tgbotplug
tgbot/botapi.py
send_video
def send_video(chat_id, video, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, **kwargs): """ Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). :param chat_id: Unique identifier for the m...
python
def send_video(chat_id, video, duration=None, caption=None, reply_to_message_id=None, reply_markup=None, **kwargs): """ Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). :param chat_id: Unique identifier for the m...
[ "def", "send_video", "(", "chat_id", ",", "video", ",", "duration", "=", "None", ",", "caption", "=", "None", ",", "reply_to_message_id", "=", "None", ",", "reply_markup", "=", "None", ",", "*", "*", "kwargs", ")", ":", "files", "=", "None", "if", "isi...
Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param video: Video to send. You can either pass a file_id as String to resend a video that is a...
[ "Use", "this", "method", "to", "send", "video", "files", "Telegram", "clients", "support", "mp4", "videos", "(", "other", "formats", "may", "be", "sent", "as", "Document", ")", "." ]
train
https://github.com/fopina/tgbotplug/blob/c115733b03f2e23ddcdecfce588d1a6a1e5bde91/tgbot/botapi.py#L1537-L1588
fopina/tgbotplug
tgbot/botapi.py
send_location
def send_location(chat_id, latitude, longitude, reply_to_message_id=None, reply_markup=None, **kwargs): """ Use this method to send point on the map. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param latitude: Latitude of locat...
python
def send_location(chat_id, latitude, longitude, reply_to_message_id=None, reply_markup=None, **kwargs): """ Use this method to send point on the map. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param latitude: Latitude of locat...
[ "def", "send_location", "(", "chat_id", ",", "latitude", ",", "longitude", ",", "reply_to_message_id", "=", "None", ",", "reply_markup", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# required args", "params", "=", "dict", "(", "chat_id", "=", "chat_id",...
Use this method to send point on the map. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param latitude: Latitude of location. :param longitude: Longitude of location. :param reply_to_message_id: If the message is a reply, ID of the original message :param reply...
[ "Use", "this", "method", "to", "send", "point", "on", "the", "map", "." ]
train
https://github.com/fopina/tgbotplug/blob/c115733b03f2e23ddcdecfce588d1a6a1e5bde91/tgbot/botapi.py#L1643-L1683
fopina/tgbotplug
tgbot/botapi.py
answer_inline_query
def answer_inline_query(inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, **kwargs): """ Use this method to send answers to an inline query. On success, True is returned. :param inline_query_id: Unique identifier for the message recipient — String :param results: An array of re...
python
def answer_inline_query(inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, **kwargs): """ Use this method to send answers to an inline query. On success, True is returned. :param inline_query_id: Unique identifier for the message recipient — String :param results: An array of re...
[ "def", "answer_inline_query", "(", "inline_query_id", ",", "results", ",", "cache_time", "=", "None", ",", "is_personal", "=", "None", ",", "next_offset", "=", "None", ",", "*", "*", "kwargs", ")", ":", "json_results", "=", "[", "]", "for", "result", "in",...
Use this method to send answers to an inline query. On success, True is returned. :param inline_query_id: Unique identifier for the message recipient — String :param results: An array of results for the inline query — Array of InlineQueryResult :param cache_time: The maximum amount of time the result of th...
[ "Use", "this", "method", "to", "send", "answers", "to", "an", "inline", "query", ".", "On", "success", "True", "is", "returned", "." ]
train
https://github.com/fopina/tgbotplug/blob/c115733b03f2e23ddcdecfce588d1a6a1e5bde91/tgbot/botapi.py#L1731-L1774
fopina/tgbotplug
tgbot/botapi.py
TelegramBotRPCRequest.wait
def wait(self): """ Wait for the request to finish and return the result or error when finished :returns: result or error :type: result tyoe or Error """ self.thread.join() if self.error is not None: return self.error return self.result
python
def wait(self): """ Wait for the request to finish and return the result or error when finished :returns: result or error :type: result tyoe or Error """ self.thread.join() if self.error is not None: return self.error return self.result
[ "def", "wait", "(", "self", ")", ":", "self", ".", "thread", ".", "join", "(", ")", "if", "self", ".", "error", "is", "not", "None", ":", "return", "self", ".", "error", "return", "self", ".", "result" ]
Wait for the request to finish and return the result or error when finished :returns: result or error :type: result tyoe or Error
[ "Wait", "for", "the", "request", "to", "finish", "and", "return", "the", "result", "or", "error", "when", "finished" ]
train
https://github.com/fopina/tgbotplug/blob/c115733b03f2e23ddcdecfce588d1a6a1e5bde91/tgbot/botapi.py#L1149-L1159
armstrong/armstrong.core.arm_sections
armstrong/core/arm_sections/backends.py
ItemFilter.filter_objects_by_section
def filter_objects_by_section(self, rels, section): """Build a queryset containing all objects in the section subtree.""" subtree = section.get_descendants(include_self=True) kwargs_list = [{'%s__in' % rel.field.name: subtree} for rel in rels] q = Q(**kwargs_list[0]) for kwargs ...
python
def filter_objects_by_section(self, rels, section): """Build a queryset containing all objects in the section subtree.""" subtree = section.get_descendants(include_self=True) kwargs_list = [{'%s__in' % rel.field.name: subtree} for rel in rels] q = Q(**kwargs_list[0]) for kwargs ...
[ "def", "filter_objects_by_section", "(", "self", ",", "rels", ",", "section", ")", ":", "subtree", "=", "section", ".", "get_descendants", "(", "include_self", "=", "True", ")", "kwargs_list", "=", "[", "{", "'%s__in'", "%", "rel", ".", "field", ".", "name...
Build a queryset containing all objects in the section subtree.
[ "Build", "a", "queryset", "containing", "all", "objects", "in", "the", "section", "subtree", "." ]
train
https://github.com/armstrong/armstrong.core.arm_sections/blob/39c999c93771da909359e53b35afefe4846f77cb/armstrong/core/arm_sections/backends.py#L16-L24
daknuett/py_register_machine2
core/commands.py
ArithmeticCommand.exec
def exec(self, operand1, operand2): """ Uses two operands and performs a function on their content.:: operand1 = function(operand1, operand2) """ in1 = self.register_interface.read(operand1) in2 = self.register_interface.read(operand2) out = self.function(in1, in2) self.register_interface.write(operan...
python
def exec(self, operand1, operand2): """ Uses two operands and performs a function on their content.:: operand1 = function(operand1, operand2) """ in1 = self.register_interface.read(operand1) in2 = self.register_interface.read(operand2) out = self.function(in1, in2) self.register_interface.write(operan...
[ "def", "exec", "(", "self", ",", "operand1", ",", "operand2", ")", ":", "in1", "=", "self", ".", "register_interface", ".", "read", "(", "operand1", ")", "in2", "=", "self", ".", "register_interface", ".", "read", "(", "operand2", ")", "out", "=", "sel...
Uses two operands and performs a function on their content.:: operand1 = function(operand1, operand2)
[ "Uses", "two", "operands", "and", "performs", "a", "function", "on", "their", "content", ".", "::" ]
train
https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/core/commands.py#L122-L131
etgalloway/fullqualname
fullqualname.py
fullqualname_py3
def fullqualname_py3(obj): """Fully qualified name for objects in Python 3.""" if type(obj).__name__ == 'builtin_function_or_method': return _fullqualname_builtin_py3(obj) elif type(obj).__name__ == 'function': return _fullqualname_function_py3(obj) elif type(obj).__name__ in ['memb...
python
def fullqualname_py3(obj): """Fully qualified name for objects in Python 3.""" if type(obj).__name__ == 'builtin_function_or_method': return _fullqualname_builtin_py3(obj) elif type(obj).__name__ == 'function': return _fullqualname_function_py3(obj) elif type(obj).__name__ in ['memb...
[ "def", "fullqualname_py3", "(", "obj", ")", ":", "if", "type", "(", "obj", ")", ".", "__name__", "==", "'builtin_function_or_method'", ":", "return", "_fullqualname_builtin_py3", "(", "obj", ")", "elif", "type", "(", "obj", ")", ".", "__name__", "==", "'func...
Fully qualified name for objects in Python 3.
[ "Fully", "qualified", "name", "for", "objects", "in", "Python", "3", "." ]
train
https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L9-L45
etgalloway/fullqualname
fullqualname.py
_fullqualname_builtin_py3
def _fullqualname_builtin_py3(obj): """Fully qualified name for 'builtin_function_or_method' objects in Python 3. """ if obj.__module__ is not None: # built-in functions module = obj.__module__ else: # built-in methods if inspect.isclass(obj.__self__): mo...
python
def _fullqualname_builtin_py3(obj): """Fully qualified name for 'builtin_function_or_method' objects in Python 3. """ if obj.__module__ is not None: # built-in functions module = obj.__module__ else: # built-in methods if inspect.isclass(obj.__self__): mo...
[ "def", "_fullqualname_builtin_py3", "(", "obj", ")", ":", "if", "obj", ".", "__module__", "is", "not", "None", ":", "# built-in functions", "module", "=", "obj", ".", "__module__", "else", ":", "# built-in methods", "if", "inspect", ".", "isclass", "(", "obj",...
Fully qualified name for 'builtin_function_or_method' objects in Python 3.
[ "Fully", "qualified", "name", "for", "builtin_function_or_method", "objects", "in", "Python", "3", "." ]
train
https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L48-L63
etgalloway/fullqualname
fullqualname.py
_fullqualname_function_py3
def _fullqualname_function_py3(obj): """Fully qualified name for 'function' objects in Python 3. """ if hasattr(obj, "__wrapped__"): # Required for decorator.__version__ <= 4.0.0. qualname = obj.__wrapped__.__qualname__ else: qualname = obj.__qualname__ return obj.__module_...
python
def _fullqualname_function_py3(obj): """Fully qualified name for 'function' objects in Python 3. """ if hasattr(obj, "__wrapped__"): # Required for decorator.__version__ <= 4.0.0. qualname = obj.__wrapped__.__qualname__ else: qualname = obj.__qualname__ return obj.__module_...
[ "def", "_fullqualname_function_py3", "(", "obj", ")", ":", "if", "hasattr", "(", "obj", ",", "\"__wrapped__\"", ")", ":", "# Required for decorator.__version__ <= 4.0.0.", "qualname", "=", "obj", ".", "__wrapped__", ".", "__qualname__", "else", ":", "qualname", "=",...
Fully qualified name for 'function' objects in Python 3.
[ "Fully", "qualified", "name", "for", "function", "objects", "in", "Python", "3", "." ]
train
https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L66-L76
etgalloway/fullqualname
fullqualname.py
_fullqualname_method_py3
def _fullqualname_method_py3(obj): """Fully qualified name for 'method' objects in Python 3. """ if inspect.isclass(obj.__self__): cls = obj.__self__.__qualname__ else: cls = obj.__self__.__class__.__qualname__ return obj.__self__.__module__ + '.' + cls + '.' + obj.__name__
python
def _fullqualname_method_py3(obj): """Fully qualified name for 'method' objects in Python 3. """ if inspect.isclass(obj.__self__): cls = obj.__self__.__qualname__ else: cls = obj.__self__.__class__.__qualname__ return obj.__self__.__module__ + '.' + cls + '.' + obj.__name__
[ "def", "_fullqualname_method_py3", "(", "obj", ")", ":", "if", "inspect", ".", "isclass", "(", "obj", ".", "__self__", ")", ":", "cls", "=", "obj", ".", "__self__", ".", "__qualname__", "else", ":", "cls", "=", "obj", ".", "__self__", ".", "__class__", ...
Fully qualified name for 'method' objects in Python 3.
[ "Fully", "qualified", "name", "for", "method", "objects", "in", "Python", "3", "." ]
train
https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L79-L88
etgalloway/fullqualname
fullqualname.py
fullqualname_py2
def fullqualname_py2(obj): """Fully qualified name for objects in Python 2.""" if type(obj).__name__ == 'builtin_function_or_method': return _fullqualname_builtin_py2(obj) elif type(obj).__name__ == 'function': return obj.__module__ + '.' + obj.__name__ elif type(obj).__name__ in ['...
python
def fullqualname_py2(obj): """Fully qualified name for objects in Python 2.""" if type(obj).__name__ == 'builtin_function_or_method': return _fullqualname_builtin_py2(obj) elif type(obj).__name__ == 'function': return obj.__module__ + '.' + obj.__name__ elif type(obj).__name__ in ['...
[ "def", "fullqualname_py2", "(", "obj", ")", ":", "if", "type", "(", "obj", ")", ".", "__name__", "==", "'builtin_function_or_method'", ":", "return", "_fullqualname_builtin_py2", "(", "obj", ")", "elif", "type", "(", "obj", ")", ".", "__name__", "==", "'func...
Fully qualified name for objects in Python 2.
[ "Fully", "qualified", "name", "for", "objects", "in", "Python", "2", "." ]
train
https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L91-L125
etgalloway/fullqualname
fullqualname.py
_fullqualname_builtin_py2
def _fullqualname_builtin_py2(obj): """Fully qualified name for 'builtin_function_or_method' objects in Python 2. """ if obj.__self__ is None: # built-in functions module = obj.__module__ qualname = obj.__name__ else: # built-in methods if inspect.isclass(obj...
python
def _fullqualname_builtin_py2(obj): """Fully qualified name for 'builtin_function_or_method' objects in Python 2. """ if obj.__self__ is None: # built-in functions module = obj.__module__ qualname = obj.__name__ else: # built-in methods if inspect.isclass(obj...
[ "def", "_fullqualname_builtin_py2", "(", "obj", ")", ":", "if", "obj", ".", "__self__", "is", "None", ":", "# built-in functions", "module", "=", "obj", ".", "__module__", "qualname", "=", "obj", ".", "__name__", "else", ":", "# built-in methods", "if", "inspe...
Fully qualified name for 'builtin_function_or_method' objects in Python 2.
[ "Fully", "qualified", "name", "for", "builtin_function_or_method", "objects", "in", "Python", "2", "." ]
train
https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L128-L146
etgalloway/fullqualname
fullqualname.py
_fullqualname_method_py2
def _fullqualname_method_py2(obj): """Fully qualified name for 'instancemethod' objects in Python 2. """ if obj.__self__ is None: # unbound methods module = obj.im_class.__module__ cls = obj.im_class.__name__ else: # bound methods if inspect.isclass(obj.__self__)...
python
def _fullqualname_method_py2(obj): """Fully qualified name for 'instancemethod' objects in Python 2. """ if obj.__self__ is None: # unbound methods module = obj.im_class.__module__ cls = obj.im_class.__name__ else: # bound methods if inspect.isclass(obj.__self__)...
[ "def", "_fullqualname_method_py2", "(", "obj", ")", ":", "if", "obj", ".", "__self__", "is", "None", ":", "# unbound methods", "module", "=", "obj", ".", "im_class", ".", "__module__", "cls", "=", "obj", ".", "im_class", ".", "__name__", "else", ":", "# bo...
Fully qualified name for 'instancemethod' objects in Python 2.
[ "Fully", "qualified", "name", "for", "instancemethod", "objects", "in", "Python", "2", "." ]
train
https://github.com/etgalloway/fullqualname/blob/c16fa82880219cf91cdcd5466db9bf2099592c59/fullqualname.py#L149-L167
monkeython/scriba
scriba/content_types/scriba_x_tar.py
parse
def parse(binary, **params): """Turns a TAR file into a frozen sample.""" binary = io.BytesIO(binary) collection = list() with tarfile.TarFile(fileobj=binary, mode='r') as tar: for tar_info in tar.getmembers(): content_type, encoding = mimetypes.guess_type(tar_info.name) ...
python
def parse(binary, **params): """Turns a TAR file into a frozen sample.""" binary = io.BytesIO(binary) collection = list() with tarfile.TarFile(fileobj=binary, mode='r') as tar: for tar_info in tar.getmembers(): content_type, encoding = mimetypes.guess_type(tar_info.name) ...
[ "def", "parse", "(", "binary", ",", "*", "*", "params", ")", ":", "binary", "=", "io", ".", "BytesIO", "(", "binary", ")", "collection", "=", "list", "(", ")", "with", "tarfile", ".", "TarFile", "(", "fileobj", "=", "binary", ",", "mode", "=", "'r'...
Turns a TAR file into a frozen sample.
[ "Turns", "a", "TAR", "file", "into", "a", "frozen", "sample", "." ]
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_x_tar.py#L16-L27
monkeython/scriba
scriba/content_types/scriba_x_tar.py
format
def format(collection, **params): """Truns a frozen sample into a TAR file.""" binary = io.BytesIO() with tarfile.TarFile(fileobj=binary, mode='w') as tar: mode = params.get('mode', 0o640) now = calendar.timegm(datetime.datetime.utcnow().timetuple()) for filename, content in collecti...
python
def format(collection, **params): """Truns a frozen sample into a TAR file.""" binary = io.BytesIO() with tarfile.TarFile(fileobj=binary, mode='w') as tar: mode = params.get('mode', 0o640) now = calendar.timegm(datetime.datetime.utcnow().timetuple()) for filename, content in collecti...
[ "def", "format", "(", "collection", ",", "*", "*", "params", ")", ":", "binary", "=", "io", ".", "BytesIO", "(", ")", "with", "tarfile", ".", "TarFile", "(", "fileobj", "=", "binary", ",", "mode", "=", "'w'", ")", "as", "tar", ":", "mode", "=", "...
Truns a frozen sample into a TAR file.
[ "Truns", "a", "frozen", "sample", "into", "a", "TAR", "file", "." ]
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_x_tar.py#L30-L47
antonybholmes/libbam
libbam/libbam.py
parse_sam_read
def parse_sam_read(sam): """ Parses a SAM alignment and returns a SamFile object. Parameters ---------- sam : str or list Either a tab delimited SAM string, or an already tokenized list of SAM fields. Returns ------- SamRead a SamRead object representat...
python
def parse_sam_read(sam): """ Parses a SAM alignment and returns a SamFile object. Parameters ---------- sam : str or list Either a tab delimited SAM string, or an already tokenized list of SAM fields. Returns ------- SamRead a SamRead object representat...
[ "def", "parse_sam_read", "(", "sam", ")", ":", "if", "isinstance", "(", "sam", ",", "str", ")", ":", "sam", "=", "sam", ".", "strip", "(", ")", ".", "split", "(", "'\\t'", ")", "if", "not", "isinstance", "(", "sam", ",", "list", ")", ":", "return...
Parses a SAM alignment and returns a SamFile object. Parameters ---------- sam : str or list Either a tab delimited SAM string, or an already tokenized list of SAM fields. Returns ------- SamRead a SamRead object representation of the SAM alignment.
[ "Parses", "a", "SAM", "alignment", "and", "returns", "a", "SamFile", "object", ".", "Parameters", "----------", "sam", ":", "str", "or", "list", "Either", "a", "tab", "delimited", "SAM", "string", "or", "an", "already", "tokenized", "list", "of", "SAM", "f...
train
https://github.com/antonybholmes/libbam/blob/88d6c4734bf32f41e63d2082457c2bad2207a866/libbam/libbam.py#L176-L214
antonybholmes/libbam
libbam/libbam.py
BamReader.header
def header(self): """ Return the BAM/SAM header Returns ------- generator Each line of the header """ cmd = [self.__samtools, 'view', '-H', self.__bam] stdout = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout fo...
python
def header(self): """ Return the BAM/SAM header Returns ------- generator Each line of the header """ cmd = [self.__samtools, 'view', '-H', self.__bam] stdout = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout fo...
[ "def", "header", "(", "self", ")", ":", "cmd", "=", "[", "self", ".", "__samtools", ",", "'view'", ",", "'-H'", ",", "self", ".", "__bam", "]", "stdout", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ")...
Return the BAM/SAM header Returns ------- generator Each line of the header
[ "Return", "the", "BAM", "/", "SAM", "header", "Returns", "-------", "generator", "Each", "line", "of", "the", "header" ]
train
https://github.com/antonybholmes/libbam/blob/88d6c4734bf32f41e63d2082457c2bad2207a866/libbam/libbam.py#L239-L256
antonybholmes/libbam
libbam/libbam.py
BamReader.count_reads
def count_reads(self, l): """ Iterate over the reads on a particular genome in the bam file. Parameters ---------- l : str A location. """ if self.__paired: cmd = [self.__samtools, 'view', '-c', '-f', '3', self.__bam, l] ...
python
def count_reads(self, l): """ Iterate over the reads on a particular genome in the bam file. Parameters ---------- l : str A location. """ if self.__paired: cmd = [self.__samtools, 'view', '-c', '-f', '3', self.__bam, l] ...
[ "def", "count_reads", "(", "self", ",", "l", ")", ":", "if", "self", ".", "__paired", ":", "cmd", "=", "[", "self", ".", "__samtools", ",", "'view'", ",", "'-c'", ",", "'-f'", ",", "'3'", ",", "self", ".", "__bam", ",", "l", "]", "else", ":", "...
Iterate over the reads on a particular genome in the bam file. Parameters ---------- l : str A location.
[ "Iterate", "over", "the", "reads", "on", "a", "particular", "genome", "in", "the", "bam", "file", ".", "Parameters", "----------", "l", ":", "str", "A", "location", "." ]
train
https://github.com/antonybholmes/libbam/blob/88d6c4734bf32f41e63d2082457c2bad2207a866/libbam/libbam.py#L313-L335
abalkin/tz
tzdata-pkg/tzdata/__init__.py
get
def get(tzid): """Return timezone data""" ns = {} path = os.path.join(DATA_DIR, tzid) with open(path) as f: raw_data = f.read() exec(raw_data, ns, ns) z = ZoneData() z.types = [(delta(offset), delta(save), abbr) for offset, save, abbr in ns['types']] z.times = [(da...
python
def get(tzid): """Return timezone data""" ns = {} path = os.path.join(DATA_DIR, tzid) with open(path) as f: raw_data = f.read() exec(raw_data, ns, ns) z = ZoneData() z.types = [(delta(offset), delta(save), abbr) for offset, save, abbr in ns['types']] z.times = [(da...
[ "def", "get", "(", "tzid", ")", ":", "ns", "=", "{", "}", "path", "=", "os", ".", "path", ".", "join", "(", "DATA_DIR", ",", "tzid", ")", "with", "open", "(", "path", ")", "as", "f", ":", "raw_data", "=", "f", ".", "read", "(", ")", "exec", ...
Return timezone data
[ "Return", "timezone", "data" ]
train
https://github.com/abalkin/tz/blob/f25fca6afbf1abd46fd7aeb978282823c7dab5ab/tzdata-pkg/tzdata/__init__.py#L40-L53
veltzer/pylogconf
config/helpers.py
find_packages
def find_packages(path: str) -> List[str]: """ A better version of find_packages than what setuptools offers This function needs to be deterministic. :param path: :return: """ ret = [] for root, _dir, files in os.walk(path): if '__init__.py' in files: ret.append(root....
python
def find_packages(path: str) -> List[str]: """ A better version of find_packages than what setuptools offers This function needs to be deterministic. :param path: :return: """ ret = [] for root, _dir, files in os.walk(path): if '__init__.py' in files: ret.append(root....
[ "def", "find_packages", "(", "path", ":", "str", ")", "->", "List", "[", "str", "]", ":", "ret", "=", "[", "]", "for", "root", ",", "_dir", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "if", "'__init__.py'", "in", "files", ":", ...
A better version of find_packages than what setuptools offers This function needs to be deterministic. :param path: :return:
[ "A", "better", "version", "of", "find_packages", "than", "what", "setuptools", "offers", "This", "function", "needs", "to", "be", "deterministic", ".", ":", "param", "path", ":", ":", "return", ":" ]
train
https://github.com/veltzer/pylogconf/blob/a3e230a073380b43b5d5096f40bb37ae28f3e430/config/helpers.py#L24-L35
carlitux/turboengine
src/turboengine/decorators.py
login_required
def login_required(method): """A decorator that control if a user is logged.""" def wrapper(self, *arg, **karg): if not self.user: if self.request.method == "GET": self.redirect(settings.LOGIN_PATH) else: self.error(403) else: m...
python
def login_required(method): """A decorator that control if a user is logged.""" def wrapper(self, *arg, **karg): if not self.user: if self.request.method == "GET": self.redirect(settings.LOGIN_PATH) else: self.error(403) else: m...
[ "def", "login_required", "(", "method", ")", ":", "def", "wrapper", "(", "self", ",", "*", "arg", ",", "*", "*", "karg", ")", ":", "if", "not", "self", ".", "user", ":", "if", "self", ".", "request", ".", "method", "==", "\"GET\"", ":", "self", "...
A decorator that control if a user is logged.
[ "A", "decorator", "that", "control", "if", "a", "user", "is", "logged", "." ]
train
https://github.com/carlitux/turboengine/blob/627b6dbc400d8c16e2ff7e17afd01915371ea287/src/turboengine/decorators.py#L29-L39
ramrod-project/database-brain
schema/brain/binary/data.py
put
def put(obj_dict, conn=None, **kwargs): """ This function might thorw an error like: Query size (290114573) greater than maximum (134217727) caller may need to manually split files at this time :param obj_dict: <dict> matching brain_pb2.Binary object :param conn: :param kwargs: :retu...
python
def put(obj_dict, conn=None, **kwargs): """ This function might thorw an error like: Query size (290114573) greater than maximum (134217727) caller may need to manually split files at this time :param obj_dict: <dict> matching brain_pb2.Binary object :param conn: :param kwargs: :retu...
[ "def", "put", "(", "obj_dict", ",", "conn", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "\"verify\"", ",", "False", ")", ":", "verify", "(", "obj_dict", ",", "Binary", "(", ")", ")", "inserted", "=", "RBF", "....
This function might thorw an error like: Query size (290114573) greater than maximum (134217727) caller may need to manually split files at this time :param obj_dict: <dict> matching brain_pb2.Binary object :param conn: :param kwargs: :return:
[ "This", "function", "might", "thorw", "an", "error", "like", ":", "Query", "size", "(", "290114573", ")", "greater", "than", "maximum", "(", "134217727", ")", "caller", "may", "need", "to", "manually", "split", "files", "at", "this", "time", ":", "param", ...
train
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/binary/data.py#L28-L41
ramrod-project/database-brain
schema/brain/binary/data.py
put_buffer
def put_buffer(filename, content, conn=None): """ helper function for put :param filename: <str> :param content: <bytes> :param conn: <rethinkdb.DefaultConnection> :return: <dict> """ obj_dict = {PRIMARY_FIELD: filename, CONTENT_FIELD: content, TIMESTAMP_F...
python
def put_buffer(filename, content, conn=None): """ helper function for put :param filename: <str> :param content: <bytes> :param conn: <rethinkdb.DefaultConnection> :return: <dict> """ obj_dict = {PRIMARY_FIELD: filename, CONTENT_FIELD: content, TIMESTAMP_F...
[ "def", "put_buffer", "(", "filename", ",", "content", ",", "conn", "=", "None", ")", ":", "obj_dict", "=", "{", "PRIMARY_FIELD", ":", "filename", ",", "CONTENT_FIELD", ":", "content", ",", "TIMESTAMP_FIELD", ":", "time", "(", ")", "}", "return", "put", "...
helper function for put :param filename: <str> :param content: <bytes> :param conn: <rethinkdb.DefaultConnection> :return: <dict>
[ "helper", "function", "for", "put", ":", "param", "filename", ":", "<str", ">", ":", "param", "content", ":", "<bytes", ">", ":", "param", "conn", ":", "<rethinkdb", ".", "DefaultConnection", ">", ":", "return", ":", "<dict", ">" ]
train
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/binary/data.py#L44-L55
ramrod-project/database-brain
schema/brain/binary/data.py
delete
def delete(filename, conn=None): """ deletes a file filename being a value in the "id" key :param filename: <str> :param conn: <rethinkdb.DefaultConnection> :return: <dict> """ return RBF.filter((r.row[PRIMARY_FIELD] == filename) | (r.row[PARENT_FIELD] == filename)).delete().run(conn)
python
def delete(filename, conn=None): """ deletes a file filename being a value in the "id" key :param filename: <str> :param conn: <rethinkdb.DefaultConnection> :return: <dict> """ return RBF.filter((r.row[PRIMARY_FIELD] == filename) | (r.row[PARENT_FIELD] == filename)).delete().run(conn)
[ "def", "delete", "(", "filename", ",", "conn", "=", "None", ")", ":", "return", "RBF", ".", "filter", "(", "(", "r", ".", "row", "[", "PRIMARY_FIELD", "]", "==", "filename", ")", "|", "(", "r", ".", "row", "[", "PARENT_FIELD", "]", "==", "filename"...
deletes a file filename being a value in the "id" key :param filename: <str> :param conn: <rethinkdb.DefaultConnection> :return: <dict>
[ "deletes", "a", "file", "filename", "being", "a", "value", "in", "the", "id", "key", ":", "param", "filename", ":", "<str", ">", ":", "param", "conn", ":", "<rethinkdb", ".", "DefaultConnection", ">", ":", "return", ":", "<dict", ">" ]
train
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/binary/data.py#L94-L102
b3j0f/annotation
b3j0f/annotation/interception.py
Interceptor.pointcut
def pointcut(self, value): """Change of pointcut. """ pointcut = getattr(self, Interceptor.POINTCUT) # for all targets for target in self.targets: # unweave old advices unweave(target, pointcut=pointcut, advices=self.intercepts) # weave new a...
python
def pointcut(self, value): """Change of pointcut. """ pointcut = getattr(self, Interceptor.POINTCUT) # for all targets for target in self.targets: # unweave old advices unweave(target, pointcut=pointcut, advices=self.intercepts) # weave new a...
[ "def", "pointcut", "(", "self", ",", "value", ")", ":", "pointcut", "=", "getattr", "(", "self", ",", "Interceptor", ".", "POINTCUT", ")", "# for all targets", "for", "target", "in", "self", ".", "targets", ":", "# unweave old advices", "unweave", "(", "targ...
Change of pointcut.
[ "Change", "of", "pointcut", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/interception.py#L95-L109
b3j0f/annotation
b3j0f/annotation/interception.py
Interceptor._bind_target
def _bind_target(self, target, ctx=None, *args, **kwargs): """Weave self.intercepts among target advices with pointcut.""" result = super(Interceptor, self)._bind_target( target=target, ctx=ctx, *args, **kwargs ) pointcut = getattr(self, Interceptor.POINTCUT) weave...
python
def _bind_target(self, target, ctx=None, *args, **kwargs): """Weave self.intercepts among target advices with pointcut.""" result = super(Interceptor, self)._bind_target( target=target, ctx=ctx, *args, **kwargs ) pointcut = getattr(self, Interceptor.POINTCUT) weave...
[ "def", "_bind_target", "(", "self", ",", "target", ",", "ctx", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "super", "(", "Interceptor", ",", "self", ")", ".", "_bind_target", "(", "target", "=", "target", ",", "...
Weave self.intercepts among target advices with pointcut.
[ "Weave", "self", ".", "intercepts", "among", "target", "advices", "with", "pointcut", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/interception.py#L111-L122
b3j0f/annotation
b3j0f/annotation/interception.py
Interceptor.intercepts
def intercepts(self, joinpoint): """Self target interception if self is enabled :param joinpoint: advices executor """ result = None if self.enable: interception = getattr(self, Interceptor.INTERCEPTION) joinpoint.exec_ctx[Interceptor.INTERCEPTION] = ...
python
def intercepts(self, joinpoint): """Self target interception if self is enabled :param joinpoint: advices executor """ result = None if self.enable: interception = getattr(self, Interceptor.INTERCEPTION) joinpoint.exec_ctx[Interceptor.INTERCEPTION] = ...
[ "def", "intercepts", "(", "self", ",", "joinpoint", ")", ":", "result", "=", "None", "if", "self", ".", "enable", ":", "interception", "=", "getattr", "(", "self", ",", "Interceptor", ".", "INTERCEPTION", ")", "joinpoint", ".", "exec_ctx", "[", "Intercepto...
Self target interception if self is enabled :param joinpoint: advices executor
[ "Self", "target", "interception", "if", "self", "is", "enabled" ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/interception.py#L132-L151
b3j0f/annotation
b3j0f/annotation/interception.py
Interceptor.set_enable
def set_enable(cls, target, enable=True): """(Dis|En)able annotated interceptors.""" interceptors = cls.get_annotations(target) for interceptor in interceptors: setattr(interceptor, Interceptor.ENABLE, enable)
python
def set_enable(cls, target, enable=True): """(Dis|En)able annotated interceptors.""" interceptors = cls.get_annotations(target) for interceptor in interceptors: setattr(interceptor, Interceptor.ENABLE, enable)
[ "def", "set_enable", "(", "cls", ",", "target", ",", "enable", "=", "True", ")", ":", "interceptors", "=", "cls", ".", "get_annotations", "(", "target", ")", "for", "interceptor", "in", "interceptors", ":", "setattr", "(", "interceptor", ",", "Interceptor", ...
(Dis|En)able annotated interceptors.
[ "(", "Dis|En", ")", "able", "annotated", "interceptors", "." ]
train
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/interception.py#L154-L160
devricks/soft_drf
soft_drf/auth/utilities.py
jwt_get_secret_key
def jwt_get_secret_key(payload=None): """ For enchanced security you may use secret key on user itself. This way you have an option to logout only this user if: - token is compromised - password is changed - etc. """ User = get_user_model() # noqa if api_settings.JWT_GET...
python
def jwt_get_secret_key(payload=None): """ For enchanced security you may use secret key on user itself. This way you have an option to logout only this user if: - token is compromised - password is changed - etc. """ User = get_user_model() # noqa if api_settings.JWT_GET...
[ "def", "jwt_get_secret_key", "(", "payload", "=", "None", ")", ":", "User", "=", "get_user_model", "(", ")", "# noqa", "if", "api_settings", ".", "JWT_GET_USER_SECRET_KEY", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "pk", "=", "payload", "....
For enchanced security you may use secret key on user itself. This way you have an option to logout only this user if: - token is compromised - password is changed - etc.
[ "For", "enchanced", "security", "you", "may", "use", "secret", "key", "on", "user", "itself", ".", "This", "way", "you", "have", "an", "option", "to", "logout", "only", "this", "user", "if", ":", "-", "token", "is", "compromised", "-", "password", "is", ...
train
https://github.com/devricks/soft_drf/blob/1869b13f9341bfcebd931059e93de2bc38570da3/soft_drf/auth/utilities.py#L13-L27
devricks/soft_drf
soft_drf/auth/utilities.py
create_token
def create_token(user): """ Create token. """ payload = jwt_payload_handler(user) if api_settings.JWT_ALLOW_REFRESH: payload['orig_iat'] = timegm( datetime.utcnow().utctimetuple() ) # Return values token = jwt_encode_handler(payload) return token
python
def create_token(user): """ Create token. """ payload = jwt_payload_handler(user) if api_settings.JWT_ALLOW_REFRESH: payload['orig_iat'] = timegm( datetime.utcnow().utctimetuple() ) # Return values token = jwt_encode_handler(payload) return token
[ "def", "create_token", "(", "user", ")", ":", "payload", "=", "jwt_payload_handler", "(", "user", ")", "if", "api_settings", ".", "JWT_ALLOW_REFRESH", ":", "payload", "[", "'orig_iat'", "]", "=", "timegm", "(", "datetime", ".", "utcnow", "(", ")", ".", "ut...
Create token.
[ "Create", "token", "." ]
train
https://github.com/devricks/soft_drf/blob/1869b13f9341bfcebd931059e93de2bc38570da3/soft_drf/auth/utilities.py#L107-L119
kmedian/onepara
onepara/onepara_func.py
onepara
def onepara(R): """Converts an ill-conditioned correlation matrix into well-conditioned matrix with one common correlation coefficient Parameters: ----------- R : ndarray an illconditioned correlation matrix, e.g. oxyba.illcond_corrmat Return: ------- cmat : n...
python
def onepara(R): """Converts an ill-conditioned correlation matrix into well-conditioned matrix with one common correlation coefficient Parameters: ----------- R : ndarray an illconditioned correlation matrix, e.g. oxyba.illcond_corrmat Return: ------- cmat : n...
[ "def", "onepara", "(", "R", ")", ":", "import", "numpy", "as", "np", "import", "warnings", "d", "=", "R", ".", "shape", "[", "0", "]", "if", "d", "<", "2", ":", "raise", "Exception", "(", "(", "\"More than one variable is required.\"", "\"Supply at least a...
Converts an ill-conditioned correlation matrix into well-conditioned matrix with one common correlation coefficient Parameters: ----------- R : ndarray an illconditioned correlation matrix, e.g. oxyba.illcond_corrmat Return: ------- cmat : ndarray DxD matr...
[ "Converts", "an", "ill", "-", "conditioned", "correlation", "matrix", "into", "well", "-", "conditioned", "matrix", "with", "one", "common", "correlation", "coefficient" ]
train
https://github.com/kmedian/onepara/blob/ed4142b92e3f67bad209dbea1eafc9ea6e3c32b9/onepara/onepara_func.py#L2-L39
Jayin/ETipsService
service/_.py
get_charset
def get_charset(html): """ get charset in html page return : default if not exist `charset` """ regex = r'charset=([a-zA-Z0-9-]+)?' pattern = re.compile(regex, re.IGNORECASE) if len(pattern.findall(html)) == 0: return 'UTF-8' return pattern.findall(html)[0]
python
def get_charset(html): """ get charset in html page return : default if not exist `charset` """ regex = r'charset=([a-zA-Z0-9-]+)?' pattern = re.compile(regex, re.IGNORECASE) if len(pattern.findall(html)) == 0: return 'UTF-8' return pattern.findall(html)[0]
[ "def", "get_charset", "(", "html", ")", ":", "regex", "=", "r'charset=([a-zA-Z0-9-]+)?'", "pattern", "=", "re", ".", "compile", "(", "regex", ",", "re", ".", "IGNORECASE", ")", "if", "len", "(", "pattern", ".", "findall", "(", "html", ")", ")", "==", "...
get charset in html page return : default if not exist `charset`
[ "get", "charset", "in", "html", "page", "return", ":", "default", "if", "not", "exist", "charset" ]
train
https://github.com/Jayin/ETipsService/blob/1a42612a5e5d11bec0ec1a26c99dec6fe216fca4/service/_.py#L7-L16
cbrand/vpnchooser
src/vpnchooser/query/rules_query.py
RulesQuery._load_rules
def _load_rules(self): """ Loads the rules from the SSH-Connection """ with self._sftp_connection.open(self.RULE_PATH) as file: data = file.read() lines = ( line.strip() for line in data.split('\n') ) rule_strings = ( ...
python
def _load_rules(self): """ Loads the rules from the SSH-Connection """ with self._sftp_connection.open(self.RULE_PATH) as file: data = file.read() lines = ( line.strip() for line in data.split('\n') ) rule_strings = ( ...
[ "def", "_load_rules", "(", "self", ")", ":", "with", "self", ".", "_sftp_connection", ".", "open", "(", "self", ".", "RULE_PATH", ")", "as", "file", ":", "data", "=", "file", ".", "read", "(", ")", "lines", "=", "(", "line", ".", "strip", "(", ")",...
Loads the rules from the SSH-Connection
[ "Loads", "the", "rules", "from", "the", "SSH", "-", "Connection" ]
train
https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/query/rules_query.py#L17-L39
cbrand/vpnchooser
src/vpnchooser/query/rules_query.py
RulesQuery._exec_command
def _exec_command(self, command: str): """ Executes the command and closes the handles afterwards. """ stdin, stdout, stderr = self._ssh.exec_command(command) # Clearing the buffers stdout.read() stderr.read() stdin.close()
python
def _exec_command(self, command: str): """ Executes the command and closes the handles afterwards. """ stdin, stdout, stderr = self._ssh.exec_command(command) # Clearing the buffers stdout.read() stderr.read() stdin.close()
[ "def", "_exec_command", "(", "self", ",", "command", ":", "str", ")", ":", "stdin", ",", "stdout", ",", "stderr", "=", "self", ".", "_ssh", ".", "exec_command", "(", "command", ")", "# Clearing the buffers", "stdout", ".", "read", "(", ")", "stderr", "."...
Executes the command and closes the handles afterwards.
[ "Executes", "the", "command", "and", "closes", "the", "handles", "afterwards", "." ]
train
https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/query/rules_query.py#L71-L80