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
kodexlab/reliure
reliure/utils/cli.py
arguments_from_optionable
def arguments_from_optionable(parser, component, prefix=""): """ Add argparse arguments from all options of one :class:`Optionable` >>> # Let's build a dummy optionable component: >>> comp = Optionable() >>> comp.add_option("num", Numeric(default=1, max=12, help="An exemple of option")) >>> comp.ad...
python
def arguments_from_optionable(parser, component, prefix=""): """ Add argparse arguments from all options of one :class:`Optionable` >>> # Let's build a dummy optionable component: >>> comp = Optionable() >>> comp.add_option("num", Numeric(default=1, max=12, help="An exemple of option")) >>> comp.ad...
[ "def", "arguments_from_optionable", "(", "parser", ",", "component", ",", "prefix", "=", "\"\"", ")", ":", "for", "option", "in", "component", ".", "options", ":", "if", "component", ".", "options", "[", "option", "]", ".", "hidden", ":", "continue", "argu...
Add argparse arguments from all options of one :class:`Optionable` >>> # Let's build a dummy optionable component: >>> comp = Optionable() >>> comp.add_option("num", Numeric(default=1, max=12, help="An exemple of option")) >>> comp.add_option("title", Text(help="The title of the title")) >>> comp.a...
[ "Add", "argparse", "arguments", "from", "all", "options", "of", "one", ":", "class", ":", "Optionable" ]
train
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/utils/cli.py#L74-L117
kodexlab/reliure
reliure/utils/cli.py
get_config_for
def get_config_for(args, component, prefix=""): """ Returns a dictionary of option value for a given component See :func:`arguments_from_optionable` documentation """ config = {} vargs = vars(args) for option in component.options: if component.options[option].hidden: con...
python
def get_config_for(args, component, prefix=""): """ Returns a dictionary of option value for a given component See :func:`arguments_from_optionable` documentation """ config = {} vargs = vars(args) for option in component.options: if component.options[option].hidden: con...
[ "def", "get_config_for", "(", "args", ",", "component", ",", "prefix", "=", "\"\"", ")", ":", "config", "=", "{", "}", "vargs", "=", "vars", "(", "args", ")", "for", "option", "in", "component", ".", "options", ":", "if", "component", ".", "options", ...
Returns a dictionary of option value for a given component See :func:`arguments_from_optionable` documentation
[ "Returns", "a", "dictionary", "of", "option", "value", "for", "a", "given", "component", "See", ":", "func", ":", "arguments_from_optionable", "documentation" ]
train
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/utils/cli.py#L120-L131
b3j0f/conf
b3j0f/conf/parser/core.py
serialize
def serialize(expr): """Serialize input expr into a parsable value. :rtype: str""" result = None if isinstance(expr, string_types): result = expr elif expr is not None: result = '=py:{0}'.format(expr) return result
python
def serialize(expr): """Serialize input expr into a parsable value. :rtype: str""" result = None if isinstance(expr, string_types): result = expr elif expr is not None: result = '=py:{0}'.format(expr) return result
[ "def", "serialize", "(", "expr", ")", ":", "result", "=", "None", "if", "isinstance", "(", "expr", ",", "string_types", ")", ":", "result", "=", "expr", "elif", "expr", "is", "not", "None", ":", "result", "=", "'=py:{0}'", ".", "format", "(", "expr", ...
Serialize input expr into a parsable value. :rtype: str
[ "Serialize", "input", "expr", "into", "a", "parsable", "value", "." ]
train
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/parser/core.py#L198-L211
b3j0f/conf
b3j0f/conf/parser/core.py
parse
def parse( svalue, conf=None, configurable=None, ptype=None, scope=DEFAULT_SCOPE, safe=DEFAULT_SAFE, besteffort=DEFAULT_BESTEFFORT ): """Parser which delegates parsing to expression or format parser.""" result = None if ptype is None: ptype = object compilation = REGEX_EXPR.ma...
python
def parse( svalue, conf=None, configurable=None, ptype=None, scope=DEFAULT_SCOPE, safe=DEFAULT_SAFE, besteffort=DEFAULT_BESTEFFORT ): """Parser which delegates parsing to expression or format parser.""" result = None if ptype is None: ptype = object compilation = REGEX_EXPR.ma...
[ "def", "parse", "(", "svalue", ",", "conf", "=", "None", ",", "configurable", "=", "None", ",", "ptype", "=", "None", ",", "scope", "=", "DEFAULT_SCOPE", ",", "safe", "=", "DEFAULT_SAFE", ",", "besteffort", "=", "DEFAULT_BESTEFFORT", ")", ":", "result", ...
Parser which delegates parsing to expression or format parser.
[ "Parser", "which", "delegates", "parsing", "to", "expression", "or", "format", "parser", "." ]
train
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/parser/core.py#L214-L252
b3j0f/conf
b3j0f/conf/parser/core.py
_exprparser
def _exprparser( expr, scope, lang=None, conf=None, configurable=None, safe=DEFAULT_SAFE, besteffort=DEFAULT_BESTEFFORT, tostr=False ): """In charge of parsing an expression and return a python object.""" if scope is None: scope = {} scope.update({ 'configurable': configura...
python
def _exprparser( expr, scope, lang=None, conf=None, configurable=None, safe=DEFAULT_SAFE, besteffort=DEFAULT_BESTEFFORT, tostr=False ): """In charge of parsing an expression and return a python object.""" if scope is None: scope = {} scope.update({ 'configurable': configura...
[ "def", "_exprparser", "(", "expr", ",", "scope", ",", "lang", "=", "None", ",", "conf", "=", "None", ",", "configurable", "=", "None", ",", "safe", "=", "DEFAULT_SAFE", ",", "besteffort", "=", "DEFAULT_BESTEFFORT", ",", "tostr", "=", "False", ")", ":", ...
In charge of parsing an expression and return a python object.
[ "In", "charge", "of", "parsing", "an", "expression", "and", "return", "a", "python", "object", "." ]
train
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/parser/core.py#L255-L281
b3j0f/conf
b3j0f/conf/parser/core.py
_ref
def _ref( pname, conf=None, configurable=None, cname=None, path=None, history=0 ): """Resolve a parameter value. :param Configuration conf: configuration to use. :param str pname: parameter name. :param Configurable configurable: configurable. :param str cname: category name. :param str...
python
def _ref( pname, conf=None, configurable=None, cname=None, path=None, history=0 ): """Resolve a parameter value. :param Configuration conf: configuration to use. :param str pname: parameter name. :param Configurable configurable: configurable. :param str cname: category name. :param str...
[ "def", "_ref", "(", "pname", ",", "conf", "=", "None", ",", "configurable", "=", "None", ",", "cname", "=", "None", ",", "path", "=", "None", ",", "history", "=", "0", ")", ":", "result", "=", "None", "if", "configurable", "is", "not", "None", ":",...
Resolve a parameter value. :param Configuration conf: configuration to use. :param str pname: parameter name. :param Configurable configurable: configurable. :param str cname: category name. :param str path: conf path. :param int history: parameter history research. :return: parameter. ...
[ "Resolve", "a", "parameter", "value", "." ]
train
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/parser/core.py#L385-L422
dev-platypus/platyutil
python/platyutil/system.py
mount
def mount(dev, mountpoint, flags='', log=None): '''Mount the given dev to the given mountpoint by using the given flags''' ensureDirectory(mountpoint) systemCall('mount %s %s %s' % (flags, dev, mountpoint), log=log)
python
def mount(dev, mountpoint, flags='', log=None): '''Mount the given dev to the given mountpoint by using the given flags''' ensureDirectory(mountpoint) systemCall('mount %s %s %s' % (flags, dev, mountpoint), log=log)
[ "def", "mount", "(", "dev", ",", "mountpoint", ",", "flags", "=", "''", ",", "log", "=", "None", ")", ":", "ensureDirectory", "(", "mountpoint", ")", "systemCall", "(", "'mount %s %s %s'", "%", "(", "flags", ",", "dev", ",", "mountpoint", ")", ",", "lo...
Mount the given dev to the given mountpoint by using the given flags
[ "Mount", "the", "given", "dev", "to", "the", "given", "mountpoint", "by", "using", "the", "given", "flags" ]
train
https://github.com/dev-platypus/platyutil/blob/5f3dadbdc2445e71755fb09d6020641c77d13c47/python/platyutil/system.py#L37-L41
dev-platypus/platyutil
python/platyutil/system.py
systemCall
def systemCall(cmd, sh=True, log=None): '''Fancy magic version of os.system''' if log is None: log = logging log.debug('System call [sh:%s]: %s' \ % (sh, cmd)) out = [] proc = None poller = None outBuf = [''] errBuf = [''] def pollOutput(): ''' ...
python
def systemCall(cmd, sh=True, log=None): '''Fancy magic version of os.system''' if log is None: log = logging log.debug('System call [sh:%s]: %s' \ % (sh, cmd)) out = [] proc = None poller = None outBuf = [''] errBuf = [''] def pollOutput(): ''' ...
[ "def", "systemCall", "(", "cmd", ",", "sh", "=", "True", ",", "log", "=", "None", ")", ":", "if", "log", "is", "None", ":", "log", "=", "logging", "log", ".", "debug", "(", "'System call [sh:%s]: %s'", "%", "(", "sh", ",", "cmd", ")", ")", "out", ...
Fancy magic version of os.system
[ "Fancy", "magic", "version", "of", "os", ".", "system" ]
train
https://github.com/dev-platypus/platyutil/blob/5f3dadbdc2445e71755fb09d6020641c77d13c47/python/platyutil/system.py#L50-L135
dev-platypus/platyutil
python/platyutil/system.py
chrootedSystemCall
def chrootedSystemCall(chrootDir, cmd, sh=True, mountPseudoFs=True, log=None): '''Chrooted version of systemCall. Manages necessary pseudo filesystems.''' if log is None: log = conduct.app.log # determine mount points for pseudo fs proc = path.join(chrootDir, 'proc') sys = path.join(chrootD...
python
def chrootedSystemCall(chrootDir, cmd, sh=True, mountPseudoFs=True, log=None): '''Chrooted version of systemCall. Manages necessary pseudo filesystems.''' if log is None: log = conduct.app.log # determine mount points for pseudo fs proc = path.join(chrootDir, 'proc') sys = path.join(chrootD...
[ "def", "chrootedSystemCall", "(", "chrootDir", ",", "cmd", ",", "sh", "=", "True", ",", "mountPseudoFs", "=", "True", ",", "log", "=", "None", ")", ":", "if", "log", "is", "None", ":", "log", "=", "conduct", ".", "app", ".", "log", "# determine mount p...
Chrooted version of systemCall. Manages necessary pseudo filesystems.
[ "Chrooted", "version", "of", "systemCall", ".", "Manages", "necessary", "pseudo", "filesystems", "." ]
train
https://github.com/dev-platypus/platyutil/blob/5f3dadbdc2445e71755fb09d6020641c77d13c47/python/platyutil/system.py#L138-L169
cogniteev/docido-python-sdk
docido_sdk/core.py
ExtensionPoint.extensions
def extensions(self, component): """Return a list of components that declare to implement the extension point interface. """ classes = ComponentMeta._registry.get(self.interface, ()) components = [component.compmgr[cls] for cls in classes] return [c for c in components if...
python
def extensions(self, component): """Return a list of components that declare to implement the extension point interface. """ classes = ComponentMeta._registry.get(self.interface, ()) components = [component.compmgr[cls] for cls in classes] return [c for c in components if...
[ "def", "extensions", "(", "self", ",", "component", ")", ":", "classes", "=", "ComponentMeta", ".", "_registry", ".", "get", "(", "self", ".", "interface", ",", "(", ")", ")", "components", "=", "[", "component", ".", "compmgr", "[", "cls", "]", "for",...
Return a list of components that declare to implement the extension point interface.
[ "Return", "a", "list", "of", "components", "that", "declare", "to", "implement", "the", "extension", "point", "interface", "." ]
train
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/core.py#L30-L36
cogniteev/docido-python-sdk
docido_sdk/core.py
Component.implements
def implements(*interfaces): """Can be used in the class definition of `Component` subclasses to declare the extension points that are extended. """ import sys frame = sys._getframe(1) locals_ = frame.f_locals # Some sanity checks msg = 'implements() can...
python
def implements(*interfaces): """Can be used in the class definition of `Component` subclasses to declare the extension points that are extended. """ import sys frame = sys._getframe(1) locals_ = frame.f_locals # Some sanity checks msg = 'implements() can...
[ "def", "implements", "(", "*", "interfaces", ")", ":", "import", "sys", "frame", "=", "sys", ".", "_getframe", "(", "1", ")", "locals_", "=", "frame", ".", "f_locals", "# Some sanity checks", "msg", "=", "'implements() can only be used in a class definition'", "as...
Can be used in the class definition of `Component` subclasses to declare the extension points that are extended.
[ "Can", "be", "used", "in", "the", "class", "definition", "of", "Component", "subclasses", "to", "declare", "the", "extension", "points", "that", "are", "extended", "." ]
train
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/core.py#L144-L157
cogniteev/docido-python-sdk
docido_sdk/core.py
ComponentManager.is_enabled
def is_enabled(self, cls): """Return whether the given component class is enabled.""" if cls not in self.enabled: self.enabled[cls] = self.is_component_enabled(cls) return self.enabled[cls]
python
def is_enabled(self, cls): """Return whether the given component class is enabled.""" if cls not in self.enabled: self.enabled[cls] = self.is_component_enabled(cls) return self.enabled[cls]
[ "def", "is_enabled", "(", "self", ",", "cls", ")", ":", "if", "cls", "not", "in", "self", ".", "enabled", ":", "self", ".", "enabled", "[", "cls", "]", "=", "self", ".", "is_component_enabled", "(", "cls", ")", "return", "self", ".", "enabled", "[", ...
Return whether the given component class is enabled.
[ "Return", "whether", "the", "given", "component", "class", "is", "enabled", "." ]
train
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/core.py#L206-L210
cogniteev/docido-python-sdk
docido_sdk/core.py
ComponentManager.disable_component
def disable_component(self, component): """Force a component to be disabled. :param component: can be a class or an instance. """ if not isinstance(component, type): component = component.__class__ self.enabled[component] = False self.components[component] = ...
python
def disable_component(self, component): """Force a component to be disabled. :param component: can be a class or an instance. """ if not isinstance(component, type): component = component.__class__ self.enabled[component] = False self.components[component] = ...
[ "def", "disable_component", "(", "self", ",", "component", ")", ":", "if", "not", "isinstance", "(", "component", ",", "type", ")", ":", "component", "=", "component", ".", "__class__", "self", ".", "enabled", "[", "component", "]", "=", "False", "self", ...
Force a component to be disabled. :param component: can be a class or an instance.
[ "Force", "a", "component", "to", "be", "disabled", "." ]
train
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/core.py#L212-L220
dr4ke616/pinky
pinky/core/base.py
BaseServer.gotMessage
def gotMessage(self, message_id, message): """ Message comes in the data structure as: { 'method': 'some_method', 'args': ['list', 'of', 'args'], 'kwargs': {'key': 'value'} } """ d = defer.maybeDeferred(self._handle_message,...
python
def gotMessage(self, message_id, message): """ Message comes in the data structure as: { 'method': 'some_method', 'args': ['list', 'of', 'args'], 'kwargs': {'key': 'value'} } """ d = defer.maybeDeferred(self._handle_message,...
[ "def", "gotMessage", "(", "self", ",", "message_id", ",", "message", ")", ":", "d", "=", "defer", ".", "maybeDeferred", "(", "self", ".", "_handle_message", ",", "message", ")", "d", ".", "addCallback", "(", "self", ".", "generate_response", ")", "d", "....
Message comes in the data structure as: { 'method': 'some_method', 'args': ['list', 'of', 'args'], 'kwargs': {'key': 'value'} }
[ "Message", "comes", "in", "the", "data", "structure", "as", ":", "{", "method", ":", "some_method", "args", ":", "[", "list", "of", "args", "]", "kwargs", ":", "{", "key", ":", "value", "}", "}" ]
train
https://github.com/dr4ke616/pinky/blob/35c165f5a1d410be467621f3152df1dbf458622a/pinky/core/base.py#L41-L52
dr4ke616/pinky
pinky/core/base.py
BaseServer.generate_response
def generate_response(self, response): """ Serializes the response object and returns the raw form. :param response: A `pinky.core.response.Response` object """ if not response: return self.__serializer__.dump({}) return self.__seriali...
python
def generate_response(self, response): """ Serializes the response object and returns the raw form. :param response: A `pinky.core.response.Response` object """ if not response: return self.__serializer__.dump({}) return self.__seriali...
[ "def", "generate_response", "(", "self", ",", "response", ")", ":", "if", "not", "response", ":", "return", "self", ".", "__serializer__", ".", "dump", "(", "{", "}", ")", "return", "self", ".", "__serializer__", ".", "dump", "(", "response", ".", "to_di...
Serializes the response object and returns the raw form. :param response: A `pinky.core.response.Response` object
[ "Serializes", "the", "response", "object", "and", "returns", "the", "raw", "form", ".", ":", "param", "response", ":", "A", "pinky", ".", "core", ".", "response", ".", "Response", "object" ]
train
https://github.com/dr4ke616/pinky/blob/35c165f5a1d410be467621f3152df1dbf458622a/pinky/core/base.py#L81-L90
btrevizan/pystrct
pystrct/pystrct.py
StructFile.size
def size(self): """Calculate and return the file size in bytes.""" old = self.__file.tell() # old position self.__file.seek(0, 2) # end of file n_bytes = self.__file.tell() # file size in bytes self.__file.seek(old) # back to old position r...
python
def size(self): """Calculate and return the file size in bytes.""" old = self.__file.tell() # old position self.__file.seek(0, 2) # end of file n_bytes = self.__file.tell() # file size in bytes self.__file.seek(old) # back to old position r...
[ "def", "size", "(", "self", ")", ":", "old", "=", "self", ".", "__file", ".", "tell", "(", ")", "# old position", "self", ".", "__file", ".", "seek", "(", "0", ",", "2", ")", "# end of file", "n_bytes", "=", "self", ".", "__file", ".", "tell", "(",...
Calculate and return the file size in bytes.
[ "Calculate", "and", "return", "the", "file", "size", "in", "bytes", "." ]
train
https://github.com/btrevizan/pystrct/blob/80e7edaacfbcb191a26ac449f049bbce878c67a3/pystrct/pystrct.py#L33-L42
btrevizan/pystrct
pystrct/pystrct.py
StructFile.prev
def prev(self, n=1): """Get the previous n data from file. Keyword argument: n -- number of structs to be retrieved (default 1) Must be greater than 0. Return: A data in the format of obj_fmt, if n = 1. A list of structs, otherwise. ...
python
def prev(self, n=1): """Get the previous n data from file. Keyword argument: n -- number of structs to be retrieved (default 1) Must be greater than 0. Return: A data in the format of obj_fmt, if n = 1. A list of structs, otherwise. ...
[ "def", "prev", "(", "self", ",", "n", "=", "1", ")", ":", "# Current position - #data", "i", "=", "abs", "(", "self", ".", "tell", "-", "n", ")", "# Get the next n data starting from i", "return", "self", ".", "get", "(", "i", ",", "n", ")" ]
Get the previous n data from file. Keyword argument: n -- number of structs to be retrieved (default 1) Must be greater than 0. Return: A data in the format of obj_fmt, if n = 1. A list of structs, otherwise.
[ "Get", "the", "previous", "n", "data", "from", "file", "." ]
train
https://github.com/btrevizan/pystrct/blob/80e7edaacfbcb191a26ac449f049bbce878c67a3/pystrct/pystrct.py#L70-L85
btrevizan/pystrct
pystrct/pystrct.py
StructFile.get
def get(self, i, n=1): """Get the n data starting from the ith. Keyword argument: i -- position in file n -- number of structs to be retrieved (default 1) Must be greater than 0. Return: A data in the format of obj_fmt, if n = 1. A list of ...
python
def get(self, i, n=1): """Get the n data starting from the ith. Keyword argument: i -- position in file n -- number of structs to be retrieved (default 1) Must be greater than 0. Return: A data in the format of obj_fmt, if n = 1. A list of ...
[ "def", "get", "(", "self", ",", "i", ",", "n", "=", "1", ")", ":", "# If there is nothing to get...", "if", "self", ".", "size", "==", "0", ":", "return", "None", "if", "n", "<", "1", ":", "return", "[", "]", "# Current byte position - (n * data_size)", ...
Get the n data starting from the ith. Keyword argument: i -- position in file n -- number of structs to be retrieved (default 1) Must be greater than 0. Return: A data in the format of obj_fmt, if n = 1. A list of structs, otherwise. ...
[ "Get", "the", "n", "data", "starting", "from", "the", "ith", "." ]
train
https://github.com/btrevizan/pystrct/blob/80e7edaacfbcb191a26ac449f049bbce878c67a3/pystrct/pystrct.py#L87-L121
btrevizan/pystrct
pystrct/pystrct.py
StructFile.last
def last(self): """Get the last object in file.""" # End of file self.__file.seek(0, 2) # Get the last struct data = self.get(self.length - 1) return data
python
def last(self): """Get the last object in file.""" # End of file self.__file.seek(0, 2) # Get the last struct data = self.get(self.length - 1) return data
[ "def", "last", "(", "self", ")", ":", "# End of file", "self", ".", "__file", ".", "seek", "(", "0", ",", "2", ")", "# Get the last struct", "data", "=", "self", ".", "get", "(", "self", ".", "length", "-", "1", ")", "return", "data" ]
Get the last object in file.
[ "Get", "the", "last", "object", "in", "file", "." ]
train
https://github.com/btrevizan/pystrct/blob/80e7edaacfbcb191a26ac449f049bbce878c67a3/pystrct/pystrct.py#L123-L131
btrevizan/pystrct
pystrct/pystrct.py
StructFile.raw
def raw(self, n=1): """Get the data from file*. Keyword argument: n -- number of data to be retrieved (default 1). Must be greater than 0. Return: A list of raw data. *This method changes file.tell value. """ size = self.__strct...
python
def raw(self, n=1): """Get the data from file*. Keyword argument: n -- number of data to be retrieved (default 1). Must be greater than 0. Return: A list of raw data. *This method changes file.tell value. """ size = self.__strct...
[ "def", "raw", "(", "self", ",", "n", "=", "1", ")", ":", "size", "=", "self", ".", "__strct", ".", "size", "# struct size", "dataset", "=", "list", "(", ")", "# list of raw data", "try", ":", "# For n times...", "for", "_", "in", "range", "(", "n", "...
Get the data from file*. Keyword argument: n -- number of data to be retrieved (default 1). Must be greater than 0. Return: A list of raw data. *This method changes file.tell value.
[ "Get", "the", "data", "from", "file", "*", "." ]
train
https://github.com/btrevizan/pystrct/blob/80e7edaacfbcb191a26ac449f049bbce878c67a3/pystrct/pystrct.py#L133-L154
btrevizan/pystrct
pystrct/pystrct.py
StructFile.append
def append(self, value): """Write the value into the file. Keyword arguments: value -- value to be writen (tuple) """ # Pack value data = self.pack(value) # End of file self.__file.seek(0, 2) # Write packed value self.__file.write(da...
python
def append(self, value): """Write the value into the file. Keyword arguments: value -- value to be writen (tuple) """ # Pack value data = self.pack(value) # End of file self.__file.seek(0, 2) # Write packed value self.__file.write(da...
[ "def", "append", "(", "self", ",", "value", ")", ":", "# Pack value", "data", "=", "self", ".", "pack", "(", "value", ")", "# End of file", "self", ".", "__file", ".", "seek", "(", "0", ",", "2", ")", "# Write packed value", "self", ".", "__file", ".",...
Write the value into the file. Keyword arguments: value -- value to be writen (tuple)
[ "Write", "the", "value", "into", "the", "file", "." ]
train
https://github.com/btrevizan/pystrct/blob/80e7edaacfbcb191a26ac449f049bbce878c67a3/pystrct/pystrct.py#L175-L188
btrevizan/pystrct
pystrct/pystrct.py
StructFile.write
def write(self, i, value): """Write value in ith position in file. Keyword arguments: i -- position in file value -- value to be packed (tuple) """ # Current byte position - (n * data_size) offset = i * self.__strct.size # Set file pointer to -(#...
python
def write(self, i, value): """Write value in ith position in file. Keyword arguments: i -- position in file value -- value to be packed (tuple) """ # Current byte position - (n * data_size) offset = i * self.__strct.size # Set file pointer to -(#...
[ "def", "write", "(", "self", ",", "i", ",", "value", ")", ":", "# Current byte position - (n * data_size)", "offset", "=", "i", "*", "self", ".", "__strct", ".", "size", "# Set file pointer to -(#data)", "self", ".", "__file", ".", "seek", "(", "offset", ")", ...
Write value in ith position in file. Keyword arguments: i -- position in file value -- value to be packed (tuple)
[ "Write", "value", "in", "ith", "position", "in", "file", "." ]
train
https://github.com/btrevizan/pystrct/blob/80e7edaacfbcb191a26ac449f049bbce878c67a3/pystrct/pystrct.py#L190-L207
btrevizan/pystrct
pystrct/pystrct.py
StructFile.truncate
def truncate(self, n): """Erase [n] elements.""" # Current byte position - (n * data_size) size = self.size - n * self.__strct.size # Erase [size] bytes from file.tell() self.__file.truncate(size)
python
def truncate(self, n): """Erase [n] elements.""" # Current byte position - (n * data_size) size = self.size - n * self.__strct.size # Erase [size] bytes from file.tell() self.__file.truncate(size)
[ "def", "truncate", "(", "self", ",", "n", ")", ":", "# Current byte position - (n * data_size)", "size", "=", "self", ".", "size", "-", "n", "*", "self", ".", "__strct", ".", "size", "# Erase [size] bytes from file.tell()", "self", ".", "__file", ".", "truncate"...
Erase [n] elements.
[ "Erase", "[", "n", "]", "elements", "." ]
train
https://github.com/btrevizan/pystrct/blob/80e7edaacfbcb191a26ac449f049bbce878c67a3/pystrct/pystrct.py#L209-L215
radjkarl/appBase
appbase/Session.py
Session.checkMaxSessions
def checkMaxSessions(self, nMax=None): """ check whether max. number of saved sessions is reached if: remove the oldest session """ if nMax is None: nMax = self.opts['maxSessions'] l = self.stateNames() if len(l) > nMax: for f in l...
python
def checkMaxSessions(self, nMax=None): """ check whether max. number of saved sessions is reached if: remove the oldest session """ if nMax is None: nMax = self.opts['maxSessions'] l = self.stateNames() if len(l) > nMax: for f in l...
[ "def", "checkMaxSessions", "(", "self", ",", "nMax", "=", "None", ")", ":", "if", "nMax", "is", "None", ":", "nMax", "=", "self", ".", "opts", "[", "'maxSessions'", "]", "l", "=", "self", ".", "stateNames", "(", ")", "if", "len", "(", "l", ")", "...
check whether max. number of saved sessions is reached if: remove the oldest session
[ "check", "whether", "max", ".", "number", "of", "saved", "sessions", "is", "reached", "if", ":", "remove", "the", "oldest", "session" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L208-L218
radjkarl/appBase
appbase/Session.py
Session.stateNames
def stateNames(self): """Returns: list: the names of all saved sessions """ # if self.current_session: s = self.tmp_dir_session l = [x for x in s.listdir() if s.join(x).isdir()] naturalSorting(l) # else: # l=[] # bring aut...
python
def stateNames(self): """Returns: list: the names of all saved sessions """ # if self.current_session: s = self.tmp_dir_session l = [x for x in s.listdir() if s.join(x).isdir()] naturalSorting(l) # else: # l=[] # bring aut...
[ "def", "stateNames", "(", "self", ")", ":", "# if self.current_session:\r", "s", "=", "self", ".", "tmp_dir_session", "l", "=", "[", "x", "for", "x", "in", "s", ".", "listdir", "(", ")", "if", "s", ".", "join", "(", "x", ")", ".", "isdir", "(...
Returns: list: the names of all saved sessions
[ "Returns", ":", "list", ":", "the", "names", "of", "all", "saved", "sessions" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L220-L234
radjkarl/appBase
appbase/Session.py
Session._inspectArguments
def _inspectArguments(self, args): """inspect the command-line-args and give them to appBase""" if args: self.exec_path = PathStr(args[0]) else: self.exec_path = None session_name = None args = args[1:] openSession = False for ...
python
def _inspectArguments(self, args): """inspect the command-line-args and give them to appBase""" if args: self.exec_path = PathStr(args[0]) else: self.exec_path = None session_name = None args = args[1:] openSession = False for ...
[ "def", "_inspectArguments", "(", "self", ",", "args", ")", ":", "if", "args", ":", "self", ".", "exec_path", "=", "PathStr", "(", "args", "[", "0", "]", ")", "else", ":", "self", ".", "exec_path", "=", "None", "session_name", "=", "None", "args", "="...
inspect the command-line-args and give them to appBase
[ "inspect", "the", "command", "-", "line", "-", "args", "and", "give", "them", "to", "appBase" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L327-L356
radjkarl/appBase
appbase/Session.py
Session.save
def save(self): """save the current session override, if session was saved earlier""" if self.path: self._saveState(self.path) else: self.saveAs()
python
def save(self): """save the current session override, if session was saved earlier""" if self.path: self._saveState(self.path) else: self.saveAs()
[ "def", "save", "(", "self", ")", ":", "if", "self", ".", "path", ":", "self", ".", "_saveState", "(", "self", ".", "path", ")", "else", ":", "self", ".", "saveAs", "(", ")" ]
save the current session override, if session was saved earlier
[ "save", "the", "current", "session", "override", "if", "session", "was", "saved", "earlier" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L368-L374
radjkarl/appBase
appbase/Session.py
Session.open
def open(self): """open a session to define in a dialog in an extra window""" filename = self.dialogs.getOpenFileName(filter="*.%s" % self.FTYPE) if filename: self.new(filename)
python
def open(self): """open a session to define in a dialog in an extra window""" filename = self.dialogs.getOpenFileName(filter="*.%s" % self.FTYPE) if filename: self.new(filename)
[ "def", "open", "(", "self", ")", ":", "filename", "=", "self", ".", "dialogs", ".", "getOpenFileName", "(", "filter", "=", "\"*.%s\"", "%", "self", ".", "FTYPE", ")", "if", "filename", ":", "self", ".", "new", "(", "filename", ")" ]
open a session to define in a dialog in an extra window
[ "open", "a", "session", "to", "define", "in", "a", "dialog", "in", "an", "extra", "window" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L397-L401
radjkarl/appBase
appbase/Session.py
Session.new
def new(self, filename=None): """start a session an independent process""" path = (self.exec_path,) if self.exec_path.filetype() in ('py', 'pyw', 'pyz', self.FTYPE): # get the absolute path to the python-executable p = find_executable("python") path = (p...
python
def new(self, filename=None): """start a session an independent process""" path = (self.exec_path,) if self.exec_path.filetype() in ('py', 'pyw', 'pyz', self.FTYPE): # get the absolute path to the python-executable p = find_executable("python") path = (p...
[ "def", "new", "(", "self", ",", "filename", "=", "None", ")", ":", "path", "=", "(", "self", ".", "exec_path", ",", ")", "if", "self", ".", "exec_path", ".", "filetype", "(", ")", "in", "(", "'py'", ",", "'pyw'", ",", "'pyz'", ",", "self", ".", ...
start a session an independent process
[ "start", "a", "session", "an", "independent", "process" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L403-L416
radjkarl/appBase
appbase/Session.py
Session._saveState
def _saveState(self, path): """save current state and add a new state""" self.addSession() # next session self._save(str(self.n_sessions), path)
python
def _saveState(self, path): """save current state and add a new state""" self.addSession() # next session self._save(str(self.n_sessions), path)
[ "def", "_saveState", "(", "self", ",", "path", ")", ":", "self", ".", "addSession", "(", ")", "# next session\r", "self", ".", "_save", "(", "str", "(", "self", ".", "n_sessions", ")", ",", "path", ")" ]
save current state and add a new state
[ "save", "current", "state", "and", "add", "a", "new", "state" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L456-L459
radjkarl/appBase
appbase/Session.py
Session._autoSave
def _autoSave(self): """save state into 'autosave' """ a = 'autoSave' path = self.path if not path: path = self.dir.join('%s.%s' % (a, self.FTYPE)) self._createdAutosaveFile = path self.tmp_dir_save_session = self.tmp_dir_session.join(a).mkdir() ...
python
def _autoSave(self): """save state into 'autosave' """ a = 'autoSave' path = self.path if not path: path = self.dir.join('%s.%s' % (a, self.FTYPE)) self._createdAutosaveFile = path self.tmp_dir_save_session = self.tmp_dir_session.join(a).mkdir() ...
[ "def", "_autoSave", "(", "self", ")", ":", "a", "=", "'autoSave'", "path", "=", "self", ".", "path", "if", "not", "path", ":", "path", "=", "self", ".", "dir", ".", "join", "(", "'%s.%s'", "%", "(", "a", ",", "self", ".", "FTYPE", ")", ")", "se...
save state into 'autosave'
[ "save", "state", "into", "autosave" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L461-L469
radjkarl/appBase
appbase/Session.py
Session.blockingSave
def blockingSave(self, path): """ saved session to file - returns after finish only called by interactiveTutorial-save at the moment """ self.tmp_dir_save_session = self.tmp_dir_session.join('block').mkdir() state = {'session': dict(self.opts), 'di...
python
def blockingSave(self, path): """ saved session to file - returns after finish only called by interactiveTutorial-save at the moment """ self.tmp_dir_save_session = self.tmp_dir_session.join('block').mkdir() state = {'session': dict(self.opts), 'di...
[ "def", "blockingSave", "(", "self", ",", "path", ")", ":", "self", ".", "tmp_dir_save_session", "=", "self", ".", "tmp_dir_session", ".", "join", "(", "'block'", ")", ".", "mkdir", "(", ")", "state", "=", "{", "'session'", ":", "dict", "(", "self", "."...
saved session to file - returns after finish only called by interactiveTutorial-save at the moment
[ "saved", "session", "to", "file", "-", "returns", "after", "finish", "only", "called", "by", "interactiveTutorial", "-", "save", "at", "the", "moment" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L471-L481
radjkarl/appBase
appbase/Session.py
Session._save
def _save(self, stateName, path): """save into 'stateName' to pyz-path""" print('saving...') state = {'session': dict(self.opts), 'dialogs': self.dialogs.saveState()} self.sigSave.emit(state) self.saveThread.prepare(stateName, path, self.tmp_dir_session...
python
def _save(self, stateName, path): """save into 'stateName' to pyz-path""" print('saving...') state = {'session': dict(self.opts), 'dialogs': self.dialogs.saveState()} self.sigSave.emit(state) self.saveThread.prepare(stateName, path, self.tmp_dir_session...
[ "def", "_save", "(", "self", ",", "stateName", ",", "path", ")", ":", "print", "(", "'saving...'", ")", "state", "=", "{", "'session'", ":", "dict", "(", "self", ".", "opts", ")", ",", "'dialogs'", ":", "self", ".", "dialogs", ".", "saveState", "(", ...
save into 'stateName' to pyz-path
[ "save", "into", "stateName", "to", "pyz", "-", "path" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L483-L503
radjkarl/appBase
appbase/Session.py
_SaveThread._recusiveReplaceArrayWithPlaceholder
def _recusiveReplaceArrayWithPlaceholder(self, state): """ replace all numpy.array within the state dict with a placeholder this allows to save the arrays extra using numpy.save_compressed """ arrays = {} def recursive(state): for key, val in...
python
def _recusiveReplaceArrayWithPlaceholder(self, state): """ replace all numpy.array within the state dict with a placeholder this allows to save the arrays extra using numpy.save_compressed """ arrays = {} def recursive(state): for key, val in...
[ "def", "_recusiveReplaceArrayWithPlaceholder", "(", "self", ",", "state", ")", ":", "arrays", "=", "{", "}", "def", "recursive", "(", "state", ")", ":", "for", "key", ",", "val", "in", "state", ".", "items", "(", ")", ":", "if", "isinstance", "(", "val...
replace all numpy.array within the state dict with a placeholder this allows to save the arrays extra using numpy.save_compressed
[ "replace", "all", "numpy", ".", "array", "within", "the", "state", "dict", "with", "a", "placeholder", "this", "allows", "to", "save", "the", "arrays", "extra", "using", "numpy", ".", "save_compressed" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Session.py#L516-L536
eeshangarg/nukefilewalker
nukefilewalker/indexer.py
FileIndexer.start_indexing
def start_indexing(self): """ Read all the files and tokenize their text into words and accumulate all the words in a list. """ for filepath in self.filepaths: with open(filepath) as fp: blob = fp.read() self.words.extend(self.tokenize(...
python
def start_indexing(self): """ Read all the files and tokenize their text into words and accumulate all the words in a list. """ for filepath in self.filepaths: with open(filepath) as fp: blob = fp.read() self.words.extend(self.tokenize(...
[ "def", "start_indexing", "(", "self", ")", ":", "for", "filepath", "in", "self", ".", "filepaths", ":", "with", "open", "(", "filepath", ")", "as", "fp", ":", "blob", "=", "fp", ".", "read", "(", ")", "self", ".", "words", ".", "extend", "(", "self...
Read all the files and tokenize their text into words and accumulate all the words in a list.
[ "Read", "all", "the", "files", "and", "tokenize", "their", "text", "into", "words", "and", "accumulate", "all", "the", "words", "in", "a", "list", "." ]
train
https://github.com/eeshangarg/nukefilewalker/blob/8538d8b70a95691b8d2d01248cd69eae18558d11/nukefilewalker/indexer.py#L61-L69
caiyunapp/gaiabase
gaia/wsgi.py
api
def api(func): """Wraps JSONified output for JSONP requests.""" @wraps(func) def decorated_function(*args, **kwargs): try: value = func(*args, **kwargs) except BaseException as e: value = { "status": "failed", "error": "Unkonwn error!" ...
python
def api(func): """Wraps JSONified output for JSONP requests.""" @wraps(func) def decorated_function(*args, **kwargs): try: value = func(*args, **kwargs) except BaseException as e: value = { "status": "failed", "error": "Unkonwn error!" ...
[ "def", "api", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "decorated_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "value", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "...
Wraps JSONified output for JSONP requests.
[ "Wraps", "JSONified", "output", "for", "JSONP", "requests", "." ]
train
https://github.com/caiyunapp/gaiabase/blob/6e12b5beda095164f46e567fa04d7f13ad8a6965/gaia/wsgi.py#L11-L34
fred49/linshare-api
linshareapi/user/documents.py
Documents.get
def get(self, uuid): """ Get one document store into LinShare.""" #return self.core.get("documents/" + uuid) documents = (v for v in self.list() if v.get('uuid') == uuid) for i in documents: self.log.debug(i) return i return None
python
def get(self, uuid): """ Get one document store into LinShare.""" #return self.core.get("documents/" + uuid) documents = (v for v in self.list() if v.get('uuid') == uuid) for i in documents: self.log.debug(i) return i return None
[ "def", "get", "(", "self", ",", "uuid", ")", ":", "#return self.core.get(\"documents/\" + uuid)", "documents", "=", "(", "v", "for", "v", "in", "self", ".", "list", "(", ")", "if", "v", ".", "get", "(", "'uuid'", ")", "==", "uuid", ")", "for", "i", "...
Get one document store into LinShare.
[ "Get", "one", "document", "store", "into", "LinShare", "." ]
train
https://github.com/fred49/linshare-api/blob/be646c25aa8ba3718abb6869c620b157d53d6e41/linshareapi/user/documents.py#L63-L70
fred49/linshare-api
linshareapi/user/documents.py
Documents.upload
def upload(self, file_path, description=None, async=False): """ Upload a file to LinShare using its rest api. The uploaded document uuid will be returned""" url = "documents?async={a}".format(a=async) return self.core.upload(file_path, url, description)
python
def upload(self, file_path, description=None, async=False): """ Upload a file to LinShare using its rest api. The uploaded document uuid will be returned""" url = "documents?async={a}".format(a=async) return self.core.upload(file_path, url, description)
[ "def", "upload", "(", "self", ",", "file_path", ",", "description", "=", "None", ",", "async", "=", "False", ")", ":", "url", "=", "\"documents?async={a}\"", ".", "format", "(", "a", "=", "async", ")", "return", "self", ".", "core", ".", "upload", "(",...
Upload a file to LinShare using its rest api. The uploaded document uuid will be returned
[ "Upload", "a", "file", "to", "LinShare", "using", "its", "rest", "api", ".", "The", "uploaded", "document", "uuid", "will", "be", "returned" ]
train
https://github.com/fred49/linshare-api/blob/be646c25aa8ba3718abb6869c620b157d53d6e41/linshareapi/user/documents.py#L86-L90
fred49/linshare-api
linshareapi/user/documents.py
Documents.update_file
def update_file(self, uuid, file_path, async=False): """ Upload a file to LinShare using its rest api. The uploaded document uuid will be returned""" url = "documents/{u}/upload?async={a}".format(u=uuid, a=async) return self.core.upload(file_path, url, http_method='PUT')
python
def update_file(self, uuid, file_path, async=False): """ Upload a file to LinShare using its rest api. The uploaded document uuid will be returned""" url = "documents/{u}/upload?async={a}".format(u=uuid, a=async) return self.core.upload(file_path, url, http_method='PUT')
[ "def", "update_file", "(", "self", ",", "uuid", ",", "file_path", ",", "async", "=", "False", ")", ":", "url", "=", "\"documents/{u}/upload?async={a}\"", ".", "format", "(", "u", "=", "uuid", ",", "a", "=", "async", ")", "return", "self", ".", "core", ...
Upload a file to LinShare using its rest api. The uploaded document uuid will be returned
[ "Upload", "a", "file", "to", "LinShare", "using", "its", "rest", "api", ".", "The", "uploaded", "document", "uuid", "will", "be", "returned" ]
train
https://github.com/fred49/linshare-api/blob/be646c25aa8ba3718abb6869c620b157d53d6e41/linshareapi/user/documents.py#L94-L98
qzmfranklin/easyshell
easyshell/shell.py
_Shell._do_debug
def _do_debug(self, cmd, args): """\ Enter the debugging shell. debug Show current debugging status, i.e, on/off. debug {on,off} Turn on/off debugging info. debug shell Enter debugging shell. debug toggle Toggle current de...
python
def _do_debug(self, cmd, args): """\ Enter the debugging shell. debug Show current debugging status, i.e, on/off. debug {on,off} Turn on/off debugging info. debug shell Enter debugging shell. debug toggle Toggle current de...
[ "def", "_do_debug", "(", "self", ",", "cmd", ",", "args", ")", ":", "if", "not", "args", ":", "self", ".", "stdout", ".", "write", "(", "'on'", "if", "self", ".", "debug", "else", "'off'", ")", "self", ".", "stdout", ".", "write", "(", "'\\n'", "...
\ Enter the debugging shell. debug Show current debugging status, i.e, on/off. debug {on,off} Turn on/off debugging info. debug shell Enter debugging shell. debug toggle Toggle current debugging status.
[ "\\", "Enter", "the", "debugging", "shell", ".", "debug", "Show", "current", "debugging", "status", "i", ".", "e", "on", "/", "off", ".", "debug", "{", "on", "off", "}", "Turn", "on", "/", "off", "debugging", "info", ".", "debug", "shell", "Enter", "...
train
https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easyshell/shell.py#L10-L37
pudo/mqlparser
mqlparser/util.py
parse_name
def parse_name(name): """ Split a query name into field name, operator and whether it is inverted. """ inverted, op = False, OP_EQ if name is not None: for op_ in (OP_NIN, OP_IN, OP_NOT, OP_LIKE): if name.endswith(op_): op = op_ name = name[:len(name) ...
python
def parse_name(name): """ Split a query name into field name, operator and whether it is inverted. """ inverted, op = False, OP_EQ if name is not None: for op_ in (OP_NIN, OP_IN, OP_NOT, OP_LIKE): if name.endswith(op_): op = op_ name = name[:len(name) ...
[ "def", "parse_name", "(", "name", ")", ":", "inverted", ",", "op", "=", "False", ",", "OP_EQ", "if", "name", "is", "not", "None", ":", "for", "op_", "in", "(", "OP_NIN", ",", "OP_IN", ",", "OP_NOT", ",", "OP_LIKE", ")", ":", "if", "name", ".", "e...
Split a query name into field name, operator and whether it is inverted.
[ "Split", "a", "query", "name", "into", "field", "name", "operator", "and", "whether", "it", "is", "inverted", "." ]
train
https://github.com/pudo/mqlparser/blob/80f2e8c837a31ff1f5d0b8fb89dba9f3b2fef4bf/mqlparser/util.py#L9-L22
ECESeniorDesign/lazy_record
lazy_record/__init__.py
connect_db
def connect_db(database_name=":memory:"): """ Connect lazy_record to the database at the path specified in +database_name+. """ db = repo.Repo.connect_db(database_name) base.Repo.db = db query.Repo.db = db
python
def connect_db(database_name=":memory:"): """ Connect lazy_record to the database at the path specified in +database_name+. """ db = repo.Repo.connect_db(database_name) base.Repo.db = db query.Repo.db = db
[ "def", "connect_db", "(", "database_name", "=", "\":memory:\"", ")", ":", "db", "=", "repo", ".", "Repo", ".", "connect_db", "(", "database_name", ")", "base", ".", "Repo", ".", "db", "=", "db", "query", ".", "Repo", ".", "db", "=", "db" ]
Connect lazy_record to the database at the path specified in +database_name+.
[ "Connect", "lazy_record", "to", "the", "database", "at", "the", "path", "specified", "in", "+", "database_name", "+", "." ]
train
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/__init__.py#L10-L17
ECESeniorDesign/lazy_record
lazy_record/__init__.py
close_db
def close_db(): """ Close the connection to the database opened in `connect_db` """ db = repo.Repo.db if db is not None: db.close() repo.Repo.db = None base.Repo.db = None query.Repo.db = None
python
def close_db(): """ Close the connection to the database opened in `connect_db` """ db = repo.Repo.db if db is not None: db.close() repo.Repo.db = None base.Repo.db = None query.Repo.db = None
[ "def", "close_db", "(", ")", ":", "db", "=", "repo", ".", "Repo", ".", "db", "if", "db", "is", "not", "None", ":", "db", ".", "close", "(", ")", "repo", ".", "Repo", ".", "db", "=", "None", "base", ".", "Repo", ".", "db", "=", "None", "query"...
Close the connection to the database opened in `connect_db`
[ "Close", "the", "connection", "to", "the", "database", "opened", "in", "connect_db" ]
train
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/__init__.py#L20-L29
ECESeniorDesign/lazy_record
lazy_record/__init__.py
load_schema
def load_schema(schema): """ Load a schema file with path +schema+ into the database. Assumes that there exists an active database connection. """ with repo.Repo.db: repo.Repo.db.executescript(schema)
python
def load_schema(schema): """ Load a schema file with path +schema+ into the database. Assumes that there exists an active database connection. """ with repo.Repo.db: repo.Repo.db.executescript(schema)
[ "def", "load_schema", "(", "schema", ")", ":", "with", "repo", ".", "Repo", ".", "db", ":", "repo", ".", "Repo", ".", "db", ".", "executescript", "(", "schema", ")" ]
Load a schema file with path +schema+ into the database. Assumes that there exists an active database connection.
[ "Load", "a", "schema", "file", "with", "path", "+", "schema", "+", "into", "the", "database", ".", "Assumes", "that", "there", "exists", "an", "active", "database", "connection", "." ]
train
https://github.com/ECESeniorDesign/lazy_record/blob/929d3cc7c2538b0f792365c0d2b0e0d41084c2dd/lazy_record/__init__.py#L31-L37
mverleg/package_versions
package_versions/versions.py
VersionRange.update_values
def update_values(self, min=None, max=None, conflict='warning'): """ Update the boundaries, handling possible conflicts. :param conflict: What to do in case of failure: 'silent', 'warning' or 'error'. """ conflict_txt = None if min is not None: if min > self.min: if min > self.max: self.max = s...
python
def update_values(self, min=None, max=None, conflict='warning'): """ Update the boundaries, handling possible conflicts. :param conflict: What to do in case of failure: 'silent', 'warning' or 'error'. """ conflict_txt = None if min is not None: if min > self.min: if min > self.max: self.max = s...
[ "def", "update_values", "(", "self", ",", "min", "=", "None", ",", "max", "=", "None", ",", "conflict", "=", "'warning'", ")", ":", "conflict_txt", "=", "None", "if", "min", "is", "not", "None", ":", "if", "min", ">", "self", ".", "min", ":", "if",...
Update the boundaries, handling possible conflicts. :param conflict: What to do in case of failure: 'silent', 'warning' or 'error'.
[ "Update", "the", "boundaries", "handling", "possible", "conflicts", "." ]
train
https://github.com/mverleg/package_versions/blob/187c6ff709199e6abc2765d64e0851bca5906088/package_versions/versions.py#L70-L92
mverleg/package_versions
package_versions/versions.py
VersionRange.add_selection
def add_selection(self, selection, conflict = 'warning'): """ Restrict the range given a selection string :param selection: A single selection (without comma), like '>=1.3'. :param conflict: What to do in case of failure: 'silent', 'warning' or 'error'. """ selection = selection.replace(' ', '').replace('=...
python
def add_selection(self, selection, conflict = 'warning'): """ Restrict the range given a selection string :param selection: A single selection (without comma), like '>=1.3'. :param conflict: What to do in case of failure: 'silent', 'warning' or 'error'. """ selection = selection.replace(' ', '').replace('=...
[ "def", "add_selection", "(", "self", ",", "selection", ",", "conflict", "=", "'warning'", ")", ":", "selection", "=", "selection", ".", "replace", "(", "' '", ",", "''", ")", ".", "replace", "(", "'=.'", ",", "'=0.'", ")", "if", "not", "selection", ":"...
Restrict the range given a selection string :param selection: A single selection (without comma), like '>=1.3'. :param conflict: What to do in case of failure: 'silent', 'warning' or 'error'.
[ "Restrict", "the", "range", "given", "a", "selection", "string" ]
train
https://github.com/mverleg/package_versions/blob/187c6ff709199e6abc2765d64e0851bca5906088/package_versions/versions.py#L101-L149
mverleg/package_versions
package_versions/versions.py
VersionRange.choose
def choose(self, versions, conflict='silent'): """ Choose the highest version in the range. :param versions: Iterable of available versions. """ assert conflict in ('silent', 'warning', 'error') if not versions: raise VersionRangeMismatch('No versions to choose from') version_map = {} for version in...
python
def choose(self, versions, conflict='silent'): """ Choose the highest version in the range. :param versions: Iterable of available versions. """ assert conflict in ('silent', 'warning', 'error') if not versions: raise VersionRangeMismatch('No versions to choose from') version_map = {} for version in...
[ "def", "choose", "(", "self", ",", "versions", ",", "conflict", "=", "'silent'", ")", ":", "assert", "conflict", "in", "(", "'silent'", ",", "'warning'", ",", "'error'", ")", "if", "not", "versions", ":", "raise", "VersionRangeMismatch", "(", "'No versions t...
Choose the highest version in the range. :param versions: Iterable of available versions.
[ "Choose", "the", "highest", "version", "in", "the", "range", "." ]
train
https://github.com/mverleg/package_versions/blob/187c6ff709199e6abc2765d64e0851bca5906088/package_versions/versions.py#L151-L188
OpenGov/python_data_wrap
datawrap/listwrap.py
is_slice_or_dim_range_request
def is_slice_or_dim_range_request(key, depth=0): ''' Checks if a particular key is a slice, DimensionRange or list of those types ''' # Slice, DimensionRange, or list of those elements return (is_slice_or_dim_range(key) or # Don't check more than the first depth (depth ==...
python
def is_slice_or_dim_range_request(key, depth=0): ''' Checks if a particular key is a slice, DimensionRange or list of those types ''' # Slice, DimensionRange, or list of those elements return (is_slice_or_dim_range(key) or # Don't check more than the first depth (depth ==...
[ "def", "is_slice_or_dim_range_request", "(", "key", ",", "depth", "=", "0", ")", ":", "# Slice, DimensionRange, or list of those elements", "return", "(", "is_slice_or_dim_range", "(", "key", ")", "or", "# Don't check more than the first depth", "(", "depth", "==", "0", ...
Checks if a particular key is a slice, DimensionRange or list of those types
[ "Checks", "if", "a", "particular", "key", "is", "a", "slice", "DimensionRange", "or", "list", "of", "those", "types" ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/listwrap.py#L52-L61
OpenGov/python_data_wrap
datawrap/listwrap.py
get_restricted_index
def get_restricted_index(index, length, length_index_allowed=True): ''' Converts negative indices to positive ones and indices above length to length or length-1 depending on lengthAllowed. ''' if index and index >= length: index = length if length_index_allowed else length-1 return get_...
python
def get_restricted_index(index, length, length_index_allowed=True): ''' Converts negative indices to positive ones and indices above length to length or length-1 depending on lengthAllowed. ''' if index and index >= length: index = length if length_index_allowed else length-1 return get_...
[ "def", "get_restricted_index", "(", "index", ",", "length", ",", "length_index_allowed", "=", "True", ")", ":", "if", "index", "and", "index", ">=", "length", ":", "index", "=", "length", "if", "length_index_allowed", "else", "length", "-", "1", "return", "g...
Converts negative indices to positive ones and indices above length to length or length-1 depending on lengthAllowed.
[ "Converts", "negative", "indices", "to", "positive", "ones", "and", "indices", "above", "length", "to", "length", "or", "length", "-", "1", "depending", "on", "lengthAllowed", "." ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/listwrap.py#L63-L70
OpenGov/python_data_wrap
datawrap/listwrap.py
get_true_slice
def get_true_slice(dims, data_len): ''' Converts various size tuples or slices representing data ranges returns a new slice with all non-negative (or None) values. ''' rangeLen = non_str_len_no_throw(dims) # Get the range qualifier for length if isinstance(dims, slice): start = get_...
python
def get_true_slice(dims, data_len): ''' Converts various size tuples or slices representing data ranges returns a new slice with all non-negative (or None) values. ''' rangeLen = non_str_len_no_throw(dims) # Get the range qualifier for length if isinstance(dims, slice): start = get_...
[ "def", "get_true_slice", "(", "dims", ",", "data_len", ")", ":", "rangeLen", "=", "non_str_len_no_throw", "(", "dims", ")", "# Get the range qualifier for length", "if", "isinstance", "(", "dims", ",", "slice", ")", ":", "start", "=", "get_restricted_index", "(", ...
Converts various size tuples or slices representing data ranges returns a new slice with all non-negative (or None) values.
[ "Converts", "various", "size", "tuples", "or", "slices", "representing", "data", "ranges", "returns", "a", "new", "slice", "with", "all", "non", "-", "negative", "(", "or", "None", ")", "values", "." ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/listwrap.py#L72-L107
OpenGov/python_data_wrap
datawrap/listwrap.py
DimensionRange.slice_on_length
def slice_on_length(self, data_len, *addSlices): ''' Returns a slice representing the dimension range restrictions applied to a list of length data_len. If addSlices contains additional slice requirements, they are processed in the order they are given. ''' if le...
python
def slice_on_length(self, data_len, *addSlices): ''' Returns a slice representing the dimension range restrictions applied to a list of length data_len. If addSlices contains additional slice requirements, they are processed in the order they are given. ''' if le...
[ "def", "slice_on_length", "(", "self", ",", "data_len", ",", "*", "addSlices", ")", ":", "if", "len", "(", "self", ".", "ordered_ranges", ")", "+", "len", "(", "addSlices", ")", "==", "0", ":", "return", "slice", "(", "None", ",", "None", ",", "None"...
Returns a slice representing the dimension range restrictions applied to a list of length data_len. If addSlices contains additional slice requirements, they are processed in the order they are given.
[ "Returns", "a", "slice", "representing", "the", "dimension", "range", "restrictions", "applied", "to", "a", "list", "of", "length", "data_len", "." ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/listwrap.py#L142-L155
OpenGov/python_data_wrap
datawrap/listwrap.py
DimensionRange._combine_ranges_on_length
def _combine_ranges_on_length(self, data_len, first, second): ''' Combines a first range with a second range, where the second range is considered within the scope of the first. ''' first = get_true_slice(first, data_len) second = get_true_slice(second, data_len) ...
python
def _combine_ranges_on_length(self, data_len, first, second): ''' Combines a first range with a second range, where the second range is considered within the scope of the first. ''' first = get_true_slice(first, data_len) second = get_true_slice(second, data_len) ...
[ "def", "_combine_ranges_on_length", "(", "self", ",", "data_len", ",", "first", ",", "second", ")", ":", "first", "=", "get_true_slice", "(", "first", ",", "data_len", ")", "second", "=", "get_true_slice", "(", "second", ",", "data_len", ")", "final_start", ...
Combines a first range with a second range, where the second range is considered within the scope of the first.
[ "Combines", "a", "first", "range", "with", "a", "second", "range", "where", "the", "second", "range", "is", "considered", "within", "the", "scope", "of", "the", "first", "." ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/listwrap.py#L157-L190
OpenGov/python_data_wrap
datawrap/listwrap.py
DimensionRange._combine_lists_of_ranges_on_length
def _combine_lists_of_ranges_on_length(self, data_len, first, *range_list): ''' Combines an arbitrary length list of ranges into a single slice. ''' current_range = first for next_range in range_list: current_range = self._combine_ranges_on_length(data_len, current_ra...
python
def _combine_lists_of_ranges_on_length(self, data_len, first, *range_list): ''' Combines an arbitrary length list of ranges into a single slice. ''' current_range = first for next_range in range_list: current_range = self._combine_ranges_on_length(data_len, current_ra...
[ "def", "_combine_lists_of_ranges_on_length", "(", "self", ",", "data_len", ",", "first", ",", "*", "range_list", ")", ":", "current_range", "=", "first", "for", "next_range", "in", "range_list", ":", "current_range", "=", "self", ".", "_combine_ranges_on_length", ...
Combines an arbitrary length list of ranges into a single slice.
[ "Combines", "an", "arbitrary", "length", "list", "of", "ranges", "into", "a", "single", "slice", "." ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/listwrap.py#L192-L199
OpenGov/python_data_wrap
datawrap/listwrap.py
FixedListSubset._get_single_depth
def _get_single_depth(self, multi_index): ''' Helper method for determining how many single index entries there are in a particular multi-index ''' single_depth = 0 for subind in multi_index: if is_slice_or_dim_range(subind): break ...
python
def _get_single_depth(self, multi_index): ''' Helper method for determining how many single index entries there are in a particular multi-index ''' single_depth = 0 for subind in multi_index: if is_slice_or_dim_range(subind): break ...
[ "def", "_get_single_depth", "(", "self", ",", "multi_index", ")", ":", "single_depth", "=", "0", "for", "subind", "in", "multi_index", ":", "if", "is_slice_or_dim_range", "(", "subind", ")", ":", "break", "single_depth", "+=", "1", "return", "single_depth" ]
Helper method for determining how many single index entries there are in a particular multi-index
[ "Helper", "method", "for", "determining", "how", "many", "single", "index", "entries", "there", "are", "in", "a", "particular", "multi", "-", "index" ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/listwrap.py#L354-L364
OpenGov/python_data_wrap
datawrap/listwrap.py
FixedListSubset._get_slice_request_data
def _get_slice_request_data(self, index): ''' Helper function which implements multi index requests for __getitem__. ''' # Do a check on list indices for early error detection if not is_slice_or_dim_range(index): single_depth = self._get_single_depth(index) ...
python
def _get_slice_request_data(self, index): ''' Helper function which implements multi index requests for __getitem__. ''' # Do a check on list indices for early error detection if not is_slice_or_dim_range(index): single_depth = self._get_single_depth(index) ...
[ "def", "_get_slice_request_data", "(", "self", ",", "index", ")", ":", "# Do a check on list indices for early error detection", "if", "not", "is_slice_or_dim_range", "(", "index", ")", ":", "single_depth", "=", "self", ".", "_get_single_depth", "(", "index", ")", "# ...
Helper function which implements multi index requests for __getitem__.
[ "Helper", "function", "which", "implements", "multi", "index", "requests", "for", "__getitem__", "." ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/listwrap.py#L366-L391
OpenGov/python_data_wrap
datawrap/listwrap.py
FixedListSubset._get_single_index_request
def _get_single_index_request(self, index, set_to_value=False, value=None): ''' Helper function which implements single index requests for __getitem__. ''' adjusted_index = index # Multiply by step length if self.range.step: step = self.range.step ...
python
def _get_single_index_request(self, index, set_to_value=False, value=None): ''' Helper function which implements single index requests for __getitem__. ''' adjusted_index = index # Multiply by step length if self.range.step: step = self.range.step ...
[ "def", "_get_single_index_request", "(", "self", ",", "index", ",", "set_to_value", "=", "False", ",", "value", "=", "None", ")", ":", "adjusted_index", "=", "index", "# Multiply by step length", "if", "self", ".", "range", ".", "step", ":", "step", "=", "se...
Helper function which implements single index requests for __getitem__.
[ "Helper", "function", "which", "implements", "single", "index", "requests", "for", "__getitem__", "." ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/listwrap.py#L393-L431
OpenGov/python_data_wrap
datawrap/listwrap.py
FixedListSubset.compress_ranges_to_lists
def compress_ranges_to_lists(self): ''' Converts the internal dimension ranges on lists into list of the restricted size. Thus all dimension rules are applied to all dimensions of the list wrapper and returned as a list (of lists). ''' clist = [] for elem ...
python
def compress_ranges_to_lists(self): ''' Converts the internal dimension ranges on lists into list of the restricted size. Thus all dimension rules are applied to all dimensions of the list wrapper and returned as a list (of lists). ''' clist = [] for elem ...
[ "def", "compress_ranges_to_lists", "(", "self", ")", ":", "clist", "=", "[", "]", "for", "elem", "in", "self", ":", "if", "isinstance", "(", "elem", ",", "FixedListSubset", ")", ":", "clist", ".", "append", "(", "elem", ".", "compress_ranges_to_lists", "("...
Converts the internal dimension ranges on lists into list of the restricted size. Thus all dimension rules are applied to all dimensions of the list wrapper and returned as a list (of lists).
[ "Converts", "the", "internal", "dimension", "ranges", "on", "lists", "into", "list", "of", "the", "restricted", "size", ".", "Thus", "all", "dimension", "rules", "are", "applied", "to", "all", "dimensions", "of", "the", "list", "wrapper", "and", "returned", ...
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/listwrap.py#L463-L476
OpenGov/python_data_wrap
datawrap/listwrap.py
ZeroList._generate_splice
def _generate_splice(self, slice_ind): ''' Creates a splice size version of the ZeroList ''' step_size = slice_ind.step if slice_ind.step else 1 # Check for each of the four possible scenarios if slice_ind.start != None: if slice_ind.stop != None: ...
python
def _generate_splice(self, slice_ind): ''' Creates a splice size version of the ZeroList ''' step_size = slice_ind.step if slice_ind.step else 1 # Check for each of the four possible scenarios if slice_ind.start != None: if slice_ind.stop != None: ...
[ "def", "_generate_splice", "(", "self", ",", "slice_ind", ")", ":", "step_size", "=", "slice_ind", ".", "step", "if", "slice_ind", ".", "step", "else", "1", "# Check for each of the four possible scenarios", "if", "slice_ind", ".", "start", "!=", "None", ":", "i...
Creates a splice size version of the ZeroList
[ "Creates", "a", "splice", "size", "version", "of", "the", "ZeroList" ]
train
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/listwrap.py#L547-L566
minhhoit/yacms
yacms/core/models.py
SiteRelated.save
def save(self, update_site=False, *args, **kwargs): """ Set the site to the current site when the record is first created, or the ``update_site`` argument is explicitly set to ``True``. """ if update_site or (self.id is None and self.site_id is None): self.sit...
python
def save(self, update_site=False, *args, **kwargs): """ Set the site to the current site when the record is first created, or the ``update_site`` argument is explicitly set to ``True``. """ if update_site or (self.id is None and self.site_id is None): self.sit...
[ "def", "save", "(", "self", ",", "update_site", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "update_site", "or", "(", "self", ".", "id", "is", "None", "and", "self", ".", "site_id", "is", "None", ")", ":", "self", "."...
Set the site to the current site when the record is first created, or the ``update_site`` argument is explicitly set to ``True``.
[ "Set", "the", "site", "to", "the", "current", "site", "when", "the", "record", "is", "first", "created", "or", "the", "update_site", "argument", "is", "explicitly", "set", "to", "True", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L51-L59
minhhoit/yacms
yacms/core/models.py
MetaData.save
def save(self, *args, **kwargs): """ Set the description field on save. """ if self.gen_description: self.description = strip_tags(self.description_from_content()) super(MetaData, self).save(*args, **kwargs)
python
def save(self, *args, **kwargs): """ Set the description field on save. """ if self.gen_description: self.description = strip_tags(self.description_from_content()) super(MetaData, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "gen_description", ":", "self", ".", "description", "=", "strip_tags", "(", "self", ".", "description_from_content", "(", ")", ")", "super", "(", "MetaD...
Set the description field on save.
[ "Set", "the", "description", "field", "on", "save", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L137-L143
minhhoit/yacms
yacms/core/models.py
MetaData.description_from_content
def description_from_content(self): """ Returns the first block or sentence of the first content-like field. """ description = "" # Use the first RichTextField, or TextField if none found. for field_type in (RichTextField, models.TextField): if not des...
python
def description_from_content(self): """ Returns the first block or sentence of the first content-like field. """ description = "" # Use the first RichTextField, or TextField if none found. for field_type in (RichTextField, models.TextField): if not des...
[ "def", "description_from_content", "(", "self", ")", ":", "description", "=", "\"\"", "# Use the first RichTextField, or TextField if none found.", "for", "field_type", "in", "(", "RichTextField", ",", "models", ".", "TextField", ")", ":", "if", "not", "description", ...
Returns the first block or sentence of the first content-like field.
[ "Returns", "the", "first", "block", "or", "sentence", "of", "the", "first", "content", "-", "like", "field", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L152-L187
minhhoit/yacms
yacms/core/models.py
Displayable.save
def save(self, *args, **kwargs): """ Set default for ``publish_date``. We can't use ``auto_now_add`` on the field as it will be blank when a blog post is created from the quick blog form in the admin dashboard. """ if self.publish_date is None: self.publish_da...
python
def save(self, *args, **kwargs): """ Set default for ``publish_date``. We can't use ``auto_now_add`` on the field as it will be blank when a blog post is created from the quick blog form in the admin dashboard. """ if self.publish_date is None: self.publish_da...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "publish_date", "is", "None", ":", "self", ".", "publish_date", "=", "now", "(", ")", "super", "(", "Displayable", ",", "self", ")", ".", "save", ...
Set default for ``publish_date``. We can't use ``auto_now_add`` on the field as it will be blank when a blog post is created from the quick blog form in the admin dashboard.
[ "Set", "default", "for", "publish_date", ".", "We", "can", "t", "use", "auto_now_add", "on", "the", "field", "as", "it", "will", "be", "blank", "when", "a", "blog", "post", "is", "created", "from", "the", "quick", "blog", "form", "in", "the", "admin", ...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L245-L253
minhhoit/yacms
yacms/core/models.py
Displayable.set_short_url
def set_short_url(self): """ Generates the ``short_url`` attribute if the model does not already have one. Used by the ``set_short_url_for`` template tag and ``TweetableAdmin``. If no sharing service is defined (bitly is the one implemented, but others could be by overri...
python
def set_short_url(self): """ Generates the ``short_url`` attribute if the model does not already have one. Used by the ``set_short_url_for`` template tag and ``TweetableAdmin``. If no sharing service is defined (bitly is the one implemented, but others could be by overri...
[ "def", "set_short_url", "(", "self", ")", ":", "if", "self", ".", "short_url", "==", "SHORT_URL_UNSET", ":", "self", ".", "short_url", "=", "self", ".", "get_absolute_url_with_host", "(", ")", "elif", "not", "self", ".", "short_url", ":", "self", ".", "sho...
Generates the ``short_url`` attribute if the model does not already have one. Used by the ``set_short_url_for`` template tag and ``TweetableAdmin``. If no sharing service is defined (bitly is the one implemented, but others could be by overriding ``generate_short_url``), the ``S...
[ "Generates", "the", "short_url", "attribute", "if", "the", "model", "does", "not", "already", "have", "one", ".", "Used", "by", "the", "set_short_url_for", "template", "tag", "and", "TweetableAdmin", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L289-L307
minhhoit/yacms
yacms/core/models.py
Displayable.generate_short_url
def generate_short_url(self): """ Returns a new short URL generated using bit.ly if credentials for the service have been specified. """ from yacms.conf import settings if settings.BITLY_ACCESS_TOKEN: url = "https://api-ssl.bit.ly/v3/shorten?%s" % urlencode({ ...
python
def generate_short_url(self): """ Returns a new short URL generated using bit.ly if credentials for the service have been specified. """ from yacms.conf import settings if settings.BITLY_ACCESS_TOKEN: url = "https://api-ssl.bit.ly/v3/shorten?%s" % urlencode({ ...
[ "def", "generate_short_url", "(", "self", ")", ":", "from", "yacms", ".", "conf", "import", "settings", "if", "settings", ".", "BITLY_ACCESS_TOKEN", ":", "url", "=", "\"https://api-ssl.bit.ly/v3/shorten?%s\"", "%", "urlencode", "(", "{", "\"access_token\"", ":", "...
Returns a new short URL generated using bit.ly if credentials for the service have been specified.
[ "Returns", "a", "new", "short", "URL", "generated", "using", "bit", ".", "ly", "if", "credentials", "for", "the", "service", "have", "been", "specified", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L309-L323
minhhoit/yacms
yacms/core/models.py
Displayable._get_next_or_previous_by_publish_date
def _get_next_or_previous_by_publish_date(self, is_next, **kwargs): """ Retrieves next or previous object by publish date. We implement our own version instead of Django's so we can hook into the published manager and concrete subclasses. """ arg = "publish_date__gt" if i...
python
def _get_next_or_previous_by_publish_date(self, is_next, **kwargs): """ Retrieves next or previous object by publish date. We implement our own version instead of Django's so we can hook into the published manager and concrete subclasses. """ arg = "publish_date__gt" if i...
[ "def", "_get_next_or_previous_by_publish_date", "(", "self", ",", "is_next", ",", "*", "*", "kwargs", ")", ":", "arg", "=", "\"publish_date__gt\"", "if", "is_next", "else", "\"publish_date__lt\"", "order", "=", "\"publish_date\"", "if", "is_next", "else", "\"-publis...
Retrieves next or previous object by publish date. We implement our own version instead of Django's so we can hook into the published manager and concrete subclasses.
[ "Retrieves", "next", "or", "previous", "object", "by", "publish", "date", ".", "We", "implement", "our", "own", "version", "instead", "of", "Django", "s", "so", "we", "can", "hook", "into", "the", "published", "manager", "and", "concrete", "subclasses", "." ...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L325-L342
minhhoit/yacms
yacms/core/models.py
Orderable.with_respect_to
def with_respect_to(self): """ Returns a dict to use as a filter for ordering operations containing the original ``Meta.order_with_respect_to`` value if provided. If the field is a Generic Relation, the dict returned contains names and values for looking up the relation's...
python
def with_respect_to(self): """ Returns a dict to use as a filter for ordering operations containing the original ``Meta.order_with_respect_to`` value if provided. If the field is a Generic Relation, the dict returned contains names and values for looking up the relation's...
[ "def", "with_respect_to", "(", "self", ")", ":", "try", ":", "name", "=", "self", ".", "order_with_respect_to", "value", "=", "getattr", "(", "self", ",", "name", ")", "except", "AttributeError", ":", "# No ``order_with_respect_to`` specified on the model.", "return...
Returns a dict to use as a filter for ordering operations containing the original ``Meta.order_with_respect_to`` value if provided. If the field is a Generic Relation, the dict returned contains names and values for looking up the relation's ``ct_field`` and ``fk_field`` attributes.
[ "Returns", "a", "dict", "to", "use", "as", "a", "filter", "for", "ordering", "operations", "containing", "the", "original", "Meta", ".", "order_with_respect_to", "value", "if", "provided", ".", "If", "the", "field", "is", "a", "Generic", "Relation", "the", "...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L408-L427
minhhoit/yacms
yacms/core/models.py
Orderable.save
def save(self, *args, **kwargs): """ Set the initial ordering value. """ if self._order is None: lookup = self.with_respect_to() lookup["_order__isnull"] = False concrete_model = base_concrete_model(Orderable, self) self._order = concrete_m...
python
def save(self, *args, **kwargs): """ Set the initial ordering value. """ if self._order is None: lookup = self.with_respect_to() lookup["_order__isnull"] = False concrete_model = base_concrete_model(Orderable, self) self._order = concrete_m...
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_order", "is", "None", ":", "lookup", "=", "self", ".", "with_respect_to", "(", ")", "lookup", "[", "\"_order__isnull\"", "]", "=", "False", "concret...
Set the initial ordering value.
[ "Set", "the", "initial", "ordering", "value", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L429-L438
minhhoit/yacms
yacms/core/models.py
Orderable.delete
def delete(self, *args, **kwargs): """ Update the ordering values for siblings. """ lookup = self.with_respect_to() lookup["_order__gte"] = self._order concrete_model = base_concrete_model(Orderable, self) after = concrete_model.objects.filter(**lookup) af...
python
def delete(self, *args, **kwargs): """ Update the ordering values for siblings. """ lookup = self.with_respect_to() lookup["_order__gte"] = self._order concrete_model = base_concrete_model(Orderable, self) after = concrete_model.objects.filter(**lookup) af...
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lookup", "=", "self", ".", "with_respect_to", "(", ")", "lookup", "[", "\"_order__gte\"", "]", "=", "self", ".", "_order", "concrete_model", "=", "base_concrete_model", "...
Update the ordering values for siblings.
[ "Update", "the", "ordering", "values", "for", "siblings", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L440-L449
minhhoit/yacms
yacms/core/models.py
Orderable._get_next_or_previous_by_order
def _get_next_or_previous_by_order(self, is_next, **kwargs): """ Retrieves next or previous object by order. We implement our own version instead of Django's so we can hook into the published manager, concrete subclasses and our custom ``with_respect_to`` method. """ ...
python
def _get_next_or_previous_by_order(self, is_next, **kwargs): """ Retrieves next or previous object by order. We implement our own version instead of Django's so we can hook into the published manager, concrete subclasses and our custom ``with_respect_to`` method. """ ...
[ "def", "_get_next_or_previous_by_order", "(", "self", ",", "is_next", ",", "*", "*", "kwargs", ")", ":", "lookup", "=", "self", ".", "with_respect_to", "(", ")", "lookup", "[", "\"_order\"", "]", "=", "self", ".", "_order", "+", "(", "1", "if", "is_next"...
Retrieves next or previous object by order. We implement our own version instead of Django's so we can hook into the published manager, concrete subclasses and our custom ``with_respect_to`` method.
[ "Retrieves", "next", "or", "previous", "object", "by", "order", ".", "We", "implement", "our", "own", "version", "instead", "of", "Django", "s", "so", "we", "can", "hook", "into", "the", "published", "manager", "concrete", "subclasses", "and", "our", "custom...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L451-L468
minhhoit/yacms
yacms/core/models.py
Ownable.is_editable
def is_editable(self, request): """ Restrict in-line editing to the objects's owner and superusers. """ return request.user.is_superuser or request.user.id == self.user_id
python
def is_editable(self, request): """ Restrict in-line editing to the objects's owner and superusers. """ return request.user.is_superuser or request.user.id == self.user_id
[ "def", "is_editable", "(", "self", ",", "request", ")", ":", "return", "request", ".", "user", ".", "is_superuser", "or", "request", ".", "user", ".", "id", "==", "self", ".", "user_id" ]
Restrict in-line editing to the objects's owner and superusers.
[ "Restrict", "in", "-", "line", "editing", "to", "the", "objects", "s", "owner", "and", "superusers", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L494-L498
minhhoit/yacms
yacms/core/models.py
ContentTyped.get_content_models
def get_content_models(cls): """ Return all subclasses of the concrete model. """ concrete_model = base_concrete_model(ContentTyped, cls) return [m for m in apps.get_models() if m is not concrete_model and issubclass(m, concrete_model)]
python
def get_content_models(cls): """ Return all subclasses of the concrete model. """ concrete_model = base_concrete_model(ContentTyped, cls) return [m for m in apps.get_models() if m is not concrete_model and issubclass(m, concrete_model)]
[ "def", "get_content_models", "(", "cls", ")", ":", "concrete_model", "=", "base_concrete_model", "(", "ContentTyped", ",", "cls", ")", "return", "[", "m", "for", "m", "in", "apps", ".", "get_models", "(", ")", "if", "m", "is", "not", "concrete_model", "and...
Return all subclasses of the concrete model.
[ "Return", "all", "subclasses", "of", "the", "concrete", "model", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L526-L530
minhhoit/yacms
yacms/core/models.py
ContentTyped.set_content_model
def set_content_model(self): """ Set content_model to the child class's related name, or None if this is the base class. """ if not self.content_model: is_base_class = ( base_concrete_model(ContentTyped, self) == self.__class__) self.conten...
python
def set_content_model(self): """ Set content_model to the child class's related name, or None if this is the base class. """ if not self.content_model: is_base_class = ( base_concrete_model(ContentTyped, self) == self.__class__) self.conten...
[ "def", "set_content_model", "(", "self", ")", ":", "if", "not", "self", ".", "content_model", ":", "is_base_class", "=", "(", "base_concrete_model", "(", "ContentTyped", ",", "self", ")", "==", "self", ".", "__class__", ")", "self", ".", "content_model", "="...
Set content_model to the child class's related name, or None if this is the base class.
[ "Set", "content_model", "to", "the", "child", "class", "s", "related", "name", "or", "None", "if", "this", "is", "the", "base", "class", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/models.py#L532-L541
zeaphoo/budoc
budoc/budoc.py
indent
def indent(s, spaces=4): """ Inserts `spaces` after each string of new lines in `s` and before the start of the string. """ new = re.sub('(\n+)', '\\1%s' % (' ' * spaces), s) return (' ' * spaces) + new.strip()
python
def indent(s, spaces=4): """ Inserts `spaces` after each string of new lines in `s` and before the start of the string. """ new = re.sub('(\n+)', '\\1%s' % (' ' * spaces), s) return (' ' * spaces) + new.strip()
[ "def", "indent", "(", "s", ",", "spaces", "=", "4", ")", ":", "new", "=", "re", ".", "sub", "(", "'(\\n+)'", ",", "'\\\\1%s'", "%", "(", "' '", "*", "spaces", ")", ",", "s", ")", "return", "(", "' '", "*", "spaces", ")", "+", "new", ".", "str...
Inserts `spaces` after each string of new lines in `s` and before the start of the string.
[ "Inserts", "spaces", "after", "each", "string", "of", "new", "lines", "in", "s", "and", "before", "the", "start", "of", "the", "string", "." ]
train
https://github.com/zeaphoo/budoc/blob/28f3aea4ad72ac90605ced012ed20e61af90c23a/budoc/budoc.py#L15-L21
spookey/photon
photon/util/files.py
read_file
def read_file(filename): ''' Reads files :param filename: The full path of the file to read :returns: The content of the file as string (if `filename` exists) .. note:: If `filename`'s content is empty, ``None`` will also returned. To check if a file really exists ...
python
def read_file(filename): ''' Reads files :param filename: The full path of the file to read :returns: The content of the file as string (if `filename` exists) .. note:: If `filename`'s content is empty, ``None`` will also returned. To check if a file really exists ...
[ "def", "read_file", "(", "filename", ")", ":", "if", "filename", "and", "_path", ".", "exists", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
Reads files :param filename: The full path of the file to read :returns: The content of the file as string (if `filename` exists) .. note:: If `filename`'s content is empty, ``None`` will also returned. To check if a file really exists use :func:`util.locations.search_loc...
[ "Reads", "files" ]
train
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/files.py#L8-L26
spookey/photon
photon/util/files.py
read_yaml
def read_yaml(filename, add_constructor=None): ''' Reads YAML files :param filename: The full path to the YAML file :param add_constructor: A list of yaml constructors (loaders) :returns: Loaded YAML content as represented data structure .. seealso:: :func:`util...
python
def read_yaml(filename, add_constructor=None): ''' Reads YAML files :param filename: The full path to the YAML file :param add_constructor: A list of yaml constructors (loaders) :returns: Loaded YAML content as represented data structure .. seealso:: :func:`util...
[ "def", "read_yaml", "(", "filename", ",", "add_constructor", "=", "None", ")", ":", "y", "=", "read_file", "(", "filename", ")", "if", "add_constructor", ":", "if", "not", "isinstance", "(", "add_constructor", ",", "list", ")", ":", "add_constructor", "=", ...
Reads YAML files :param filename: The full path to the YAML file :param add_constructor: A list of yaml constructors (loaders) :returns: Loaded YAML content as represented data structure .. seealso:: :func:`util.structures.yaml_str_join`, :func:`util.structures....
[ "Reads", "YAML", "files" ]
train
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/files.py#L29-L52
spookey/photon
photon/util/files.py
write_file
def write_file(filename, content): ''' Writes files :param filename: The full path of the file to write (enclosing folder must already exist) :param content: The content to write :returns: The size of the data written ''' if filename and _path.exists(_path.d...
python
def write_file(filename, content): ''' Writes files :param filename: The full path of the file to write (enclosing folder must already exist) :param content: The content to write :returns: The size of the data written ''' if filename and _path.exists(_path.d...
[ "def", "write_file", "(", "filename", ",", "content", ")", ":", "if", "filename", "and", "_path", ".", "exists", "(", "_path", ".", "dirname", "(", "filename", ")", ")", "and", "content", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "...
Writes files :param filename: The full path of the file to write (enclosing folder must already exist) :param content: The content to write :returns: The size of the data written
[ "Writes", "files" ]
train
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/files.py#L70-L85
spookey/photon
photon/util/files.py
write_yaml
def write_yaml(filename, content): ''' Writes YAML files :param filename: The full path to the YAML file :param content: The content to dump :returns: The size written ''' y = _yaml.dump(content, indent=4, default_flow_style=False) if y: return write_fil...
python
def write_yaml(filename, content): ''' Writes YAML files :param filename: The full path to the YAML file :param content: The content to dump :returns: The size written ''' y = _yaml.dump(content, indent=4, default_flow_style=False) if y: return write_fil...
[ "def", "write_yaml", "(", "filename", ",", "content", ")", ":", "y", "=", "_yaml", ".", "dump", "(", "content", ",", "indent", "=", "4", ",", "default_flow_style", "=", "False", ")", "if", "y", ":", "return", "write_file", "(", "filename", ",", "y", ...
Writes YAML files :param filename: The full path to the YAML file :param content: The content to dump :returns: The size written
[ "Writes", "YAML", "files" ]
train
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/files.py#L88-L102
spookey/photon
photon/util/files.py
write_json
def write_json(filename, content): ''' Writes json files :param filename: The full path to the json file :param content: The content to dump :returns: The size written ''' j = _dumps(content, indent=4, sort_keys=True) if j: return write_file(filename, j)
python
def write_json(filename, content): ''' Writes json files :param filename: The full path to the json file :param content: The content to dump :returns: The size written ''' j = _dumps(content, indent=4, sort_keys=True) if j: return write_file(filename, j)
[ "def", "write_json", "(", "filename", ",", "content", ")", ":", "j", "=", "_dumps", "(", "content", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ")", "if", "j", ":", "return", "write_file", "(", "filename", ",", "j", ")" ]
Writes json files :param filename: The full path to the json file :param content: The content to dump :returns: The size written
[ "Writes", "json", "files" ]
train
https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/files.py#L105-L119
joshblum/beanstalk-dispatch
beanstalk_dispatch/__init__.py
get_version
def get_version(): "Returns a PEP 386-compliant version number from VERSION." assert len(VERSION) == 5 assert VERSION[3] in ('alpha', 'beta', 'rc', 'final') # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha,...
python
def get_version(): "Returns a PEP 386-compliant version number from VERSION." assert len(VERSION) == 5 assert VERSION[3] in ('alpha', 'beta', 'rc', 'final') # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha,...
[ "def", "get_version", "(", ")", ":", "assert", "len", "(", "VERSION", ")", "==", "5", "assert", "VERSION", "[", "3", "]", "in", "(", "'alpha'", ",", "'beta'", ",", "'rc'", ",", "'final'", ")", "# Now build the two parts of the version number:", "# main = X.Y[....
Returns a PEP 386-compliant version number from VERSION.
[ "Returns", "a", "PEP", "386", "-", "compliant", "version", "number", "from", "VERSION", "." ]
train
https://github.com/joshblum/beanstalk-dispatch/blob/1cc57e5496bb7114dba6de7c7988e5680d791603/beanstalk_dispatch/__init__.py#L4-L22
yougov/vr.imager
vr/imager/build.py
get_template
def get_template(name): """ Look for 'name' in the vr.runners.templates folder. Return its contents. >>> import six >>> tmpl = get_template('base_image.lxc') >>> isinstance(tmpl, six.string_types) True """ path = 'templates/' + name b_stream = pkg_resources.resource_stream('vr.imag...
python
def get_template(name): """ Look for 'name' in the vr.runners.templates folder. Return its contents. >>> import six >>> tmpl = get_template('base_image.lxc') >>> isinstance(tmpl, six.string_types) True """ path = 'templates/' + name b_stream = pkg_resources.resource_stream('vr.imag...
[ "def", "get_template", "(", "name", ")", ":", "path", "=", "'templates/'", "+", "name", "b_stream", "=", "pkg_resources", ".", "resource_stream", "(", "'vr.imager'", ",", "path", ")", "return", "b_stream", ".", "read", "(", ")", ".", "decode", "(", "'utf-8...
Look for 'name' in the vr.runners.templates folder. Return its contents. >>> import six >>> tmpl = get_template('base_image.lxc') >>> isinstance(tmpl, six.string_types) True
[ "Look", "for", "name", "in", "the", "vr", ".", "runners", ".", "templates", "folder", ".", "Return", "its", "contents", "." ]
train
https://github.com/yougov/vr.imager/blob/9bc4f448388f67a2cffaca085bf96c2c2d79120b/vr/imager/build.py#L139-L150
snorrwe/lollygag
src/lollygag/query.py
query_multiple_endpoints
def query_multiple_endpoints(urls, query: PyQuery): """ Get nodes matching the query in the response of the GET request sent to each `url` of `urls` Params: urls: iterable of strs """ urls = list(urls) return _query_multiple_endpoints(urls, query)
python
def query_multiple_endpoints(urls, query: PyQuery): """ Get nodes matching the query in the response of the GET request sent to each `url` of `urls` Params: urls: iterable of strs """ urls = list(urls) return _query_multiple_endpoints(urls, query)
[ "def", "query_multiple_endpoints", "(", "urls", ",", "query", ":", "PyQuery", ")", ":", "urls", "=", "list", "(", "urls", ")", "return", "_query_multiple_endpoints", "(", "urls", ",", "query", ")" ]
Get nodes matching the query in the response of the GET request sent to each `url` of `urls` Params: urls: iterable of strs
[ "Get", "nodes", "matching", "the", "query", "in", "the", "response", "of", "the", "GET", "request", "sent", "to", "each", "url", "of", "urls", "Params", ":", "urls", ":", "iterable", "of", "strs" ]
train
https://github.com/snorrwe/lollygag/blob/4af4b475f49070f2a3c8b32eaf78520e77acf259/src/lollygag/query.py#L9-L16
snorrwe/lollygag
src/lollygag/query.py
compile_query
def compile_query(query: dict) -> PyQuery: """ Compiles a query Syntax: TBA """ def _pair_to_dict(pair): if isinstance(pair, dict): return pair return {pair[0]: pair[1]} def _reduce(pair): try: return {'and': (_pair_to_dict(pair[0]), _pai...
python
def compile_query(query: dict) -> PyQuery: """ Compiles a query Syntax: TBA """ def _pair_to_dict(pair): if isinstance(pair, dict): return pair return {pair[0]: pair[1]} def _reduce(pair): try: return {'and': (_pair_to_dict(pair[0]), _pai...
[ "def", "compile_query", "(", "query", ":", "dict", ")", "->", "PyQuery", ":", "def", "_pair_to_dict", "(", "pair", ")", ":", "if", "isinstance", "(", "pair", ",", "dict", ")", ":", "return", "pair", "return", "{", "pair", "[", "0", "]", ":", "pair", ...
Compiles a query Syntax: TBA
[ "Compiles", "a", "query", "Syntax", ":", "TBA" ]
train
https://github.com/snorrwe/lollygag/blob/4af4b475f49070f2a3c8b32eaf78520e77acf259/src/lollygag/query.py#L33-L62
ulf1/oxyba
oxyba/block_idxmat_shuffle.py
block_idxmat_shuffle
def block_idxmat_shuffle(numdraws, numblocks, random_state=None): """Create K columns with unique random integers from 0 to N-1 Purpose: -------- - Create K blocks for k-fold cross-validation Parameters: ----------- numdraws : int number of observations N or sample size N numb...
python
def block_idxmat_shuffle(numdraws, numblocks, random_state=None): """Create K columns with unique random integers from 0 to N-1 Purpose: -------- - Create K blocks for k-fold cross-validation Parameters: ----------- numdraws : int number of observations N or sample size N numb...
[ "def", "block_idxmat_shuffle", "(", "numdraws", ",", "numblocks", ",", "random_state", "=", "None", ")", ":", "# load modules", "import", "numpy", "as", "np", "# minimum block size: bz=int(N/K)", "blocksize", "=", "int", "(", "numdraws", "/", "numblocks", ")", "# ...
Create K columns with unique random integers from 0 to N-1 Purpose: -------- - Create K blocks for k-fold cross-validation Parameters: ----------- numdraws : int number of observations N or sample size N numblocks : int number of blocks K Example: -------- ...
[ "Create", "K", "columns", "with", "unique", "random", "integers", "from", "0", "to", "N", "-", "1" ]
train
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/block_idxmat_shuffle.py#L1-L65
awacha/credolib
credolib/plotting.py
guinierplot
def guinierplot(*args, **kwargs): """Make a Guinier plot. This is simply a wrapper around plotsascurve().""" ret=plotsascurve(*args, **kwargs) plt.xscale('power',exponent=2) plt.yscale('log') return ret
python
def guinierplot(*args, **kwargs): """Make a Guinier plot. This is simply a wrapper around plotsascurve().""" ret=plotsascurve(*args, **kwargs) plt.xscale('power',exponent=2) plt.yscale('log') return ret
[ "def", "guinierplot", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "plotsascurve", "(", "*", "args", ",", "*", "*", "kwargs", ")", "plt", ".", "xscale", "(", "'power'", ",", "exponent", "=", "2", ")", "plt", ".", "yscale", "("...
Make a Guinier plot. This is simply a wrapper around plotsascurve().
[ "Make", "a", "Guinier", "plot", ".", "This", "is", "simply", "a", "wrapper", "around", "plotsascurve", "()", "." ]
train
https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/plotting.py#L40-L45
veltzer/pypitools
pypitools/scripts/install_from_remote.py
main
def main(): """ Install a package from pypi or gemfury :return: """ pypitools.common.setup_main() config = pypitools.common.ConfigData() module_name = os.path.basename(os.getcwd()) args = [] if config.use_sudo: args.extend([ 'sudo', '-H', ]) ...
python
def main(): """ Install a package from pypi or gemfury :return: """ pypitools.common.setup_main() config = pypitools.common.ConfigData() module_name = os.path.basename(os.getcwd()) args = [] if config.use_sudo: args.extend([ 'sudo', '-H', ]) ...
[ "def", "main", "(", ")", ":", "pypitools", ".", "common", ".", "setup_main", "(", ")", "config", "=", "pypitools", ".", "common", ".", "ConfigData", "(", ")", "module_name", "=", "os", ".", "path", ".", "basename", "(", "os", ".", "getcwd", "(", ")",...
Install a package from pypi or gemfury :return:
[ "Install", "a", "package", "from", "pypi", "or", "gemfury", ":", "return", ":" ]
train
https://github.com/veltzer/pypitools/blob/5f097be21e9bc65578eed5b6b7855c1945540701/pypitools/scripts/install_from_remote.py#L15-L51
neuroticnerd/armory
armory/utils/boolean.py
boolean
def boolean(value, boolmap=_BOOL_MAP): """ Convert value to <type bool>. Uses the boolean mapping dict to attempt to determine the conversion of the given value. If the value is not found in the mapping, it falls back to the built-in Python bool conversion. Optionally, a custom mapping dict can...
python
def boolean(value, boolmap=_BOOL_MAP): """ Convert value to <type bool>. Uses the boolean mapping dict to attempt to determine the conversion of the given value. If the value is not found in the mapping, it falls back to the built-in Python bool conversion. Optionally, a custom mapping dict can...
[ "def", "boolean", "(", "value", ",", "boolmap", "=", "_BOOL_MAP", ")", ":", "if", "boolmap", "==", "_BOOL_MAP", "and", "isinstance", "(", "value", ",", "str", ")", ":", "result", "=", "boolmap", ".", "get", "(", "value", ".", "lower", "(", ")", ")", ...
Convert value to <type bool>. Uses the boolean mapping dict to attempt to determine the conversion of the given value. If the value is not found in the mapping, it falls back to the built-in Python bool conversion. Optionally, a custom mapping dict can be passed to use for the value lookups. The d...
[ "Convert", "value", "to", "<type", "bool", ">", "." ]
train
https://github.com/neuroticnerd/armory/blob/d37c5ca1dbdd60dddb968e35f0bbe4bc1299dca1/armory/utils/boolean.py#L21-L50
treycucco/bidon
bidon/spreadsheet/base.py
WorksheetBase.to_cell_table
def to_cell_table(self, merged=True): """Returns a list of lists of Cells with the cooked value and note for each cell.""" new_rows = [] for row_index, row in enumerate(self.rows(CellMode.cooked)): new_row = [] for col_index, cell_value in enumerate(row): new_row.append(Cell(cell_value, ...
python
def to_cell_table(self, merged=True): """Returns a list of lists of Cells with the cooked value and note for each cell.""" new_rows = [] for row_index, row in enumerate(self.rows(CellMode.cooked)): new_row = [] for col_index, cell_value in enumerate(row): new_row.append(Cell(cell_value, ...
[ "def", "to_cell_table", "(", "self", ",", "merged", "=", "True", ")", ":", "new_rows", "=", "[", "]", "for", "row_index", ",", "row", "in", "enumerate", "(", "self", ".", "rows", "(", "CellMode", ".", "cooked", ")", ")", ":", "new_row", "=", "[", "...
Returns a list of lists of Cells with the cooked value and note for each cell.
[ "Returns", "a", "list", "of", "lists", "of", "Cells", "with", "the", "cooked", "value", "and", "note", "for", "each", "cell", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/spreadsheet/base.py#L44-L62
treycucco/bidon
bidon/spreadsheet/base.py
WorksheetBase.rows
def rows(self, cell_mode=CellMode.cooked): """Generates a sequence of parsed rows from the worksheet. The cells are parsed according to the cell_mode argument. """ for row_index in range(self.nrows): yield self.parse_row(self.get_row(row_index), row_index, cell_mode)
python
def rows(self, cell_mode=CellMode.cooked): """Generates a sequence of parsed rows from the worksheet. The cells are parsed according to the cell_mode argument. """ for row_index in range(self.nrows): yield self.parse_row(self.get_row(row_index), row_index, cell_mode)
[ "def", "rows", "(", "self", ",", "cell_mode", "=", "CellMode", ".", "cooked", ")", ":", "for", "row_index", "in", "range", "(", "self", ".", "nrows", ")", ":", "yield", "self", ".", "parse_row", "(", "self", ".", "get_row", "(", "row_index", ")", ","...
Generates a sequence of parsed rows from the worksheet. The cells are parsed according to the cell_mode argument.
[ "Generates", "a", "sequence", "of", "parsed", "rows", "from", "the", "worksheet", ".", "The", "cells", "are", "parsed", "according", "to", "the", "cell_mode", "argument", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/spreadsheet/base.py#L64-L69
treycucco/bidon
bidon/spreadsheet/base.py
WorksheetBase.parse_row
def parse_row(self, row, row_index, cell_mode=CellMode.cooked): """Parse a row according to the given cell_mode.""" return [self.parse_cell(cell, (col_index, row_index), cell_mode) \ for col_index, cell in enumerate(row)]
python
def parse_row(self, row, row_index, cell_mode=CellMode.cooked): """Parse a row according to the given cell_mode.""" return [self.parse_cell(cell, (col_index, row_index), cell_mode) \ for col_index, cell in enumerate(row)]
[ "def", "parse_row", "(", "self", ",", "row", ",", "row_index", ",", "cell_mode", "=", "CellMode", ".", "cooked", ")", ":", "return", "[", "self", ".", "parse_cell", "(", "cell", ",", "(", "col_index", ",", "row_index", ")", ",", "cell_mode", ")", "for"...
Parse a row according to the given cell_mode.
[ "Parse", "a", "row", "according", "to", "the", "given", "cell_mode", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/spreadsheet/base.py#L71-L74
treycucco/bidon
bidon/spreadsheet/base.py
WorksheetBase.get_cell
def get_cell(self, coords, cell_mode=CellMode.cooked): """Get a cell from the worksheet according to the given coords and parse it according to the given cell_mode. Coords is a tuple of (col, row). """ return self.parse_cell(self.get_row(coords[1])[coords[0]], coords, cell_mode)
python
def get_cell(self, coords, cell_mode=CellMode.cooked): """Get a cell from the worksheet according to the given coords and parse it according to the given cell_mode. Coords is a tuple of (col, row). """ return self.parse_cell(self.get_row(coords[1])[coords[0]], coords, cell_mode)
[ "def", "get_cell", "(", "self", ",", "coords", ",", "cell_mode", "=", "CellMode", ".", "cooked", ")", ":", "return", "self", ".", "parse_cell", "(", "self", ".", "get_row", "(", "coords", "[", "1", "]", ")", "[", "coords", "[", "0", "]", "]", ",", ...
Get a cell from the worksheet according to the given coords and parse it according to the given cell_mode. Coords is a tuple of (col, row).
[ "Get", "a", "cell", "from", "the", "worksheet", "according", "to", "the", "given", "coords", "and", "parse", "it", "according", "to", "the", "given", "cell_mode", ".", "Coords", "is", "a", "tuple", "of", "(", "col", "row", ")", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/spreadsheet/base.py#L76-L80
treycucco/bidon
bidon/spreadsheet/base.py
WorksheetBase.tuple_to_datetime
def tuple_to_datetime(self, date_tuple): """Converts a tuple to a either a date, time or datetime object. If the Y, M and D parts of the tuple are all 0, then a time object is returned. If the h, m and s aprts of the tuple are all 0, then a date object is returned. Otherwise a datetime object is return...
python
def tuple_to_datetime(self, date_tuple): """Converts a tuple to a either a date, time or datetime object. If the Y, M and D parts of the tuple are all 0, then a time object is returned. If the h, m and s aprts of the tuple are all 0, then a date object is returned. Otherwise a datetime object is return...
[ "def", "tuple_to_datetime", "(", "self", ",", "date_tuple", ")", ":", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ",", "second", "=", "date_tuple", "if", "year", "==", "month", "==", "day", "==", "0", ":", "return", "time", "(", "ho...
Converts a tuple to a either a date, time or datetime object. If the Y, M and D parts of the tuple are all 0, then a time object is returned. If the h, m and s aprts of the tuple are all 0, then a date object is returned. Otherwise a datetime object is returned.
[ "Converts", "a", "tuple", "to", "a", "either", "a", "date", "time", "or", "datetime", "object", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/spreadsheet/base.py#L82-L95
treycucco/bidon
bidon/spreadsheet/base.py
WorkbookBase.sheets
def sheets(self, index=None): """Return either a list of all sheets if index is None, or the sheet at the given index.""" if self._sheets is None: self._sheets = [self.get_worksheet(s, i) for i, s in enumerate(self.iterate_sheets())] if index is None: return self._sheets else: return s...
python
def sheets(self, index=None): """Return either a list of all sheets if index is None, or the sheet at the given index.""" if self._sheets is None: self._sheets = [self.get_worksheet(s, i) for i, s in enumerate(self.iterate_sheets())] if index is None: return self._sheets else: return s...
[ "def", "sheets", "(", "self", ",", "index", "=", "None", ")", ":", "if", "self", ".", "_sheets", "is", "None", ":", "self", ".", "_sheets", "=", "[", "self", ".", "get_worksheet", "(", "s", ",", "i", ")", "for", "i", ",", "s", "in", "enumerate", ...
Return either a list of all sheets if index is None, or the sheet at the given index.
[ "Return", "either", "a", "list", "of", "all", "sheets", "if", "index", "is", "None", "or", "the", "sheet", "at", "the", "given", "index", "." ]
train
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/spreadsheet/base.py#L125-L132
rerb/django-fortune
fortune/models.py
get_available_pack_names
def get_available_pack_names(): """Return a list of (lower-cased) names if available (unloaded) Packs. """ installed_pack_names = [pack.name.lower() for pack in Pack.objects.all()] fortunes_path = get_fortunes_path() for path in fortunes_path.iterdir(): if path.is_dir(): pass ...
python
def get_available_pack_names(): """Return a list of (lower-cased) names if available (unloaded) Packs. """ installed_pack_names = [pack.name.lower() for pack in Pack.objects.all()] fortunes_path = get_fortunes_path() for path in fortunes_path.iterdir(): if path.is_dir(): pass ...
[ "def", "get_available_pack_names", "(", ")", ":", "installed_pack_names", "=", "[", "pack", ".", "name", ".", "lower", "(", ")", "for", "pack", "in", "Pack", ".", "objects", ".", "all", "(", ")", "]", "fortunes_path", "=", "get_fortunes_path", "(", ")", ...
Return a list of (lower-cased) names if available (unloaded) Packs.
[ "Return", "a", "list", "of", "(", "lower", "-", "cased", ")", "names", "if", "available", "(", "unloaded", ")", "Packs", "." ]
train
https://github.com/rerb/django-fortune/blob/f84d34f616ecabd4fab8351ad7d3062cc9d6b127/fortune/models.py#L19-L32
rerb/django-fortune
fortune/models.py
get_fortunes_path
def get_fortunes_path(): """Return the path to the fortunes data packs. """ app_config = apps.get_app_config("fortune") return Path(os.sep.join([app_config.path, "fortunes"]))
python
def get_fortunes_path(): """Return the path to the fortunes data packs. """ app_config = apps.get_app_config("fortune") return Path(os.sep.join([app_config.path, "fortunes"]))
[ "def", "get_fortunes_path", "(", ")", ":", "app_config", "=", "apps", ".", "get_app_config", "(", "\"fortune\"", ")", "return", "Path", "(", "os", ".", "sep", ".", "join", "(", "[", "app_config", ".", "path", ",", "\"fortunes\"", "]", ")", ")" ]
Return the path to the fortunes data packs.
[ "Return", "the", "path", "to", "the", "fortunes", "data", "packs", "." ]
train
https://github.com/rerb/django-fortune/blob/f84d34f616ecabd4fab8351ad7d3062cc9d6b127/fortune/models.py#L35-L39
stevepeak/inquiry
inquiry/query.py
Query.select
def select(self, column, agg=None, _as=None, distinct=False): """ What columnns to select in query. :column should be a column name or equation to produce column **not** aggregated :agg should be a valid aggregate method used to producte the figure :_as should be a string used to...
python
def select(self, column, agg=None, _as=None, distinct=False): """ What columnns to select in query. :column should be a column name or equation to produce column **not** aggregated :agg should be a valid aggregate method used to producte the figure :_as should be a string used to...
[ "def", "select", "(", "self", ",", "column", ",", "agg", "=", "None", ",", "_as", "=", "None", ",", "distinct", "=", "False", ")", ":", "if", "agg", "and", "not", "_as", ":", "raise", "ValueError", "(", "\"Aggregate colunns require `_as` to be specified\"", ...
What columnns to select in query. :column should be a column name or equation to produce column **not** aggregated :agg should be a valid aggregate method used to producte the figure :_as should be a string used to represent the column. Required when agg present
[ "What", "columnns", "to", "select", "in", "query", ".", ":", "column", "should", "be", "a", "column", "name", "or", "equation", "to", "produce", "column", "**", "not", "**", "aggregated", ":", "agg", "should", "be", "a", "valid", "aggregate", "method", "...
train
https://github.com/stevepeak/inquiry/blob/f6ea435c302560ba19985b5d4ce2c97e2f321508/inquiry/query.py#L41-L53
minhhoit/yacms
yacms/accounts/templatetags/accounts_tags.py
profile_fields
def profile_fields(user): """ Returns profile fields as a dict for the given user. Used in the profile view template when the ``ACCOUNTS_PROFILE_VIEWS_ENABLED`` setting is set to ``True``, and also in the account approval emails sent to administrators when the ``ACCOUNTS_APPROVAL_REQUIRED`` sett...
python
def profile_fields(user): """ Returns profile fields as a dict for the given user. Used in the profile view template when the ``ACCOUNTS_PROFILE_VIEWS_ENABLED`` setting is set to ``True``, and also in the account approval emails sent to administrators when the ``ACCOUNTS_APPROVAL_REQUIRED`` sett...
[ "def", "profile_fields", "(", "user", ")", ":", "fields", "=", "OrderedDict", "(", ")", "try", ":", "profile", "=", "get_profile_for_user", "(", "user", ")", "user_fieldname", "=", "get_profile_user_fieldname", "(", ")", "exclude", "=", "tuple", "(", "settings...
Returns profile fields as a dict for the given user. Used in the profile view template when the ``ACCOUNTS_PROFILE_VIEWS_ENABLED`` setting is set to ``True``, and also in the account approval emails sent to administrators when the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is set to ``True``.
[ "Returns", "profile", "fields", "as", "a", "dict", "for", "the", "given", "user", ".", "Used", "in", "the", "profile", "view", "template", "when", "the", "ACCOUNTS_PROFILE_VIEWS_ENABLED", "setting", "is", "set", "to", "True", "and", "also", "in", "the", "acc...
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/templatetags/accounts_tags.py#L60-L79
minhhoit/yacms
yacms/accounts/templatetags/accounts_tags.py
username_or
def username_or(user, attr): """ Returns the user's username for display, or an alternate attribute if ``ACCOUNTS_NO_USERNAME`` is set to ``True``. """ if not settings.ACCOUNTS_NO_USERNAME: attr = "username" value = getattr(user, attr) if callable(value): value = value() ...
python
def username_or(user, attr): """ Returns the user's username for display, or an alternate attribute if ``ACCOUNTS_NO_USERNAME`` is set to ``True``. """ if not settings.ACCOUNTS_NO_USERNAME: attr = "username" value = getattr(user, attr) if callable(value): value = value() ...
[ "def", "username_or", "(", "user", ",", "attr", ")", ":", "if", "not", "settings", ".", "ACCOUNTS_NO_USERNAME", ":", "attr", "=", "\"username\"", "value", "=", "getattr", "(", "user", ",", "attr", ")", "if", "callable", "(", "value", ")", ":", "value", ...
Returns the user's username for display, or an alternate attribute if ``ACCOUNTS_NO_USERNAME`` is set to ``True``.
[ "Returns", "the", "user", "s", "username", "for", "display", "or", "an", "alternate", "attribute", "if", "ACCOUNTS_NO_USERNAME", "is", "set", "to", "True", "." ]
train
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/templatetags/accounts_tags.py#L83-L93
inspirehep/plotextractor
plotextractor/api.py
process_tarball
def process_tarball(tarball, output_directory=None, context=False): """Process one tarball end-to-end. If output directory is given, the tarball will be extracted there. Otherwise, it will extract it in a folder next to the tarball file. The function returns a list of dictionaries: .. code-block:...
python
def process_tarball(tarball, output_directory=None, context=False): """Process one tarball end-to-end. If output directory is given, the tarball will be extracted there. Otherwise, it will extract it in a folder next to the tarball file. The function returns a list of dictionaries: .. code-block:...
[ "def", "process_tarball", "(", "tarball", ",", "output_directory", "=", "None", ",", "context", "=", "False", ")", ":", "if", "not", "output_directory", ":", "# No directory given, so we use the same path as the tarball", "output_directory", "=", "os", ".", "path", "....
Process one tarball end-to-end. If output directory is given, the tarball will be extracted there. Otherwise, it will extract it in a folder next to the tarball file. The function returns a list of dictionaries: .. code-block:: python [{ 'url': '/path/to/tarball_files/d15-120f3d....
[ "Process", "one", "tarball", "end", "-", "to", "-", "end", "." ]
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/api.py#L42-L83
inspirehep/plotextractor
plotextractor/api.py
map_images_in_tex
def map_images_in_tex(tex_files, image_mapping, output_directory, context=False): """Return caption and context for image references found in TeX sources.""" extracted_image_data = [] for tex_file in tex_files: # Extract images, captions and labels based on tex file and images ...
python
def map_images_in_tex(tex_files, image_mapping, output_directory, context=False): """Return caption and context for image references found in TeX sources.""" extracted_image_data = [] for tex_file in tex_files: # Extract images, captions and labels based on tex file and images ...
[ "def", "map_images_in_tex", "(", "tex_files", ",", "image_mapping", ",", "output_directory", ",", "context", "=", "False", ")", ":", "extracted_image_data", "=", "[", "]", "for", "tex_file", "in", "tex_files", ":", "# Extract images, captions and labels based on tex fil...
Return caption and context for image references found in TeX sources.
[ "Return", "caption", "and", "context", "for", "image", "references", "found", "in", "TeX", "sources", "." ]
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/api.py#L86-L110
b3j0f/conf
b3j0f/conf/driver/file/base.py
_addconfig
def _addconfig(config, *paths): """Add path to CONF_DIRS if exists.""" for path in paths: if path is not None and exists(path): config.append(path)
python
def _addconfig(config, *paths): """Add path to CONF_DIRS if exists.""" for path in paths: if path is not None and exists(path): config.append(path)
[ "def", "_addconfig", "(", "config", ",", "*", "paths", ")", ":", "for", "path", "in", "paths", ":", "if", "path", "is", "not", "None", "and", "exists", "(", "path", ")", ":", "config", ".", "append", "(", "path", ")" ]
Add path to CONF_DIRS if exists.
[ "Add", "path", "to", "CONF_DIRS", "if", "exists", "." ]
train
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/driver/file/base.py#L46-L51