repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
QualiSystems/vCenterShell
package/cloudshell/cp/vcenter/commands/DeleteInstance.py
https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/commands/DeleteInstance.py#L47-L64
def DeleteInstance(self, si, logger, session, vcenter_data_model, vm_uuid, vm_name): """ :param logger: :param CloudShellAPISession session: :param str vm_name: This is the resource name :return: """ # find vm vm = self.pv_service.find_by_uuid(si, vm_uuid)...
[ "def", "DeleteInstance", "(", "self", ",", "si", ",", "logger", ",", "session", ",", "vcenter_data_model", ",", "vm_uuid", ",", "vm_name", ")", ":", "# find vm", "vm", "=", "self", ".", "pv_service", ".", "find_by_uuid", "(", "si", ",", "vm_uuid", ")", "...
:param logger: :param CloudShellAPISession session: :param str vm_name: This is the resource name :return:
[ ":", "param", "logger", ":", ":", "param", "CloudShellAPISession", "session", ":", ":", "param", "str", "vm_name", ":", "This", "is", "the", "resource", "name", ":", "return", ":" ]
python
train
estnltk/estnltk
estnltk/text.py
https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/text.py#L362-L367
def tag(self, layer): """Tag the annotations of given layer. It can automatically tag any built-in layer type.""" mapping = self.layer_tagger_mapping if layer in mapping: mapping[layer]() return self
[ "def", "tag", "(", "self", ",", "layer", ")", ":", "mapping", "=", "self", ".", "layer_tagger_mapping", "if", "layer", "in", "mapping", ":", "mapping", "[", "layer", "]", "(", ")", "return", "self" ]
Tag the annotations of given layer. It can automatically tag any built-in layer type.
[ "Tag", "the", "annotations", "of", "given", "layer", ".", "It", "can", "automatically", "tag", "any", "built", "-", "in", "layer", "type", "." ]
python
train
senaite/senaite.core
bika/lims/vocabularies/__init__.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/vocabularies/__init__.py#L466-L504
def getStickerTemplates(filter_by_type=False): """ Returns an array with the sticker templates available. Retrieves the TAL templates saved in templates/stickers folder. Each array item is a dictionary with the following structure: {'id': <template_id>, 'title': <template_t...
[ "def", "getStickerTemplates", "(", "filter_by_type", "=", "False", ")", ":", "# Retrieve the templates from bika.lims add-on", "# resdirname", "resdirname", "=", "'stickers'", "if", "filter_by_type", ":", "bikalims_path", "=", "os", ".", "path", ".", "join", "(", "\"b...
Returns an array with the sticker templates available. Retrieves the TAL templates saved in templates/stickers folder. Each array item is a dictionary with the following structure: {'id': <template_id>, 'title': <template_title>} If the template lives outside the bika....
[ "Returns", "an", "array", "with", "the", "sticker", "templates", "available", ".", "Retrieves", "the", "TAL", "templates", "saved", "in", "templates", "/", "stickers", "folder", "." ]
python
train
jamieleshaw/lurklib
lurklib/channel.py
https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/channel.py#L359-L378
def invite(self, channel, nick): """ Invite someone to a channel. Required arguments: * channel - Channel to invite them to. * nick - Nick to invite. """ with self.lock: self.is_in_channel(channel) self.send('INVITE %s %s' % (nick, channel...
[ "def", "invite", "(", "self", ",", "channel", ",", "nick", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "is_in_channel", "(", "channel", ")", "self", ".", "send", "(", "'INVITE %s %s'", "%", "(", "nick", ",", "channel", ")", ")", "while",...
Invite someone to a channel. Required arguments: * channel - Channel to invite them to. * nick - Nick to invite.
[ "Invite", "someone", "to", "a", "channel", ".", "Required", "arguments", ":", "*", "channel", "-", "Channel", "to", "invite", "them", "to", ".", "*", "nick", "-", "Nick", "to", "invite", "." ]
python
train
ThreatConnect-Inc/tcex
tcex/tcex_playbook.py
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L877-L907
def read_string(self, key, embedded=True): """Read method of CRUD operation for string data. Args: key (string): The variable to read from the DB. embedded (boolean): Resolve embedded variables. Returns: (string): Results retrieved from DB. """ ...
[ "def", "read_string", "(", "self", ",", "key", ",", "embedded", "=", "True", ")", ":", "data", "=", "None", "if", "key", "is", "not", "None", ":", "key_type", "=", "self", ".", "variable_type", "(", "key", ")", "data", "=", "self", ".", "db", ".", ...
Read method of CRUD operation for string data. Args: key (string): The variable to read from the DB. embedded (boolean): Resolve embedded variables. Returns: (string): Results retrieved from DB.
[ "Read", "method", "of", "CRUD", "operation", "for", "string", "data", "." ]
python
train
chimera0/accel-brain-code
Algorithmic-Composition/pycomposer/noisesampler/bar_noise_sampler.py
https://github.com/chimera0/accel-brain-code/blob/03661f6f544bed656269fcd4b3c23c9061629daa/Algorithmic-Composition/pycomposer/noisesampler/bar_noise_sampler.py#L54-L82
def generate(self): ''' Generate noise samples. Returns: `np.ndarray` of samples. ''' sampled_arr = np.zeros((self.__batch_size, self.__channel, self.__seq_len, self.__dim)) for batch in range(self.__batch_size): for i in range(...
[ "def", "generate", "(", "self", ")", ":", "sampled_arr", "=", "np", ".", "zeros", "(", "(", "self", ".", "__batch_size", ",", "self", ".", "__channel", ",", "self", ".", "__seq_len", ",", "self", ".", "__dim", ")", ")", "for", "batch", "in", "range",...
Generate noise samples. Returns: `np.ndarray` of samples.
[ "Generate", "noise", "samples", ".", "Returns", ":", "np", ".", "ndarray", "of", "samples", "." ]
python
train
pytroll/posttroll
posttroll/subscriber.py
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/subscriber.py#L233-L242
def close(self): """Close the subscriber: stop it and close the local subscribers. """ self.stop() for sub in list(self.subscribers) + self._hooks: try: sub.setsockopt(LINGER, 1) sub.close() except ZMQError: pass
[ "def", "close", "(", "self", ")", ":", "self", ".", "stop", "(", ")", "for", "sub", "in", "list", "(", "self", ".", "subscribers", ")", "+", "self", ".", "_hooks", ":", "try", ":", "sub", ".", "setsockopt", "(", "LINGER", ",", "1", ")", "sub", ...
Close the subscriber: stop it and close the local subscribers.
[ "Close", "the", "subscriber", ":", "stop", "it", "and", "close", "the", "local", "subscribers", "." ]
python
train
mitsei/dlkit
dlkit/json_/grading/objects.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/objects.py#L203-L221
def set_input_score_start_range(self, score): """Sets the input score start range. arg: score (decimal): the new start range raise: InvalidArgument - ``score`` is invalid raise: NoAccess - ``range`` cannot be modified *compliance: mandatory -- This method must be implemente...
[ "def", "set_input_score_start_range", "(", "self", ",", "score", ")", ":", "# Implemented from template for osid.grading.GradeSystemForm.set_lowest_numeric_score", "if", "self", ".", "get_input_score_start_range_metadata", "(", ")", ".", "is_read_only", "(", ")", ":", "raise"...
Sets the input score start range. arg: score (decimal): the new start range raise: InvalidArgument - ``score`` is invalid raise: NoAccess - ``range`` cannot be modified *compliance: mandatory -- This method must be implemented.*
[ "Sets", "the", "input", "score", "start", "range", "." ]
python
train
serge-sans-paille/pythran
pythran/passmanager.py
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/passmanager.py#L80-L91
def prepare(self, node): '''Gather analysis result required by this analysis''' if isinstance(node, ast.Module): self.ctx.module = node elif isinstance(node, ast.FunctionDef): self.ctx.function = node for D in self.deps: d = D() d.attach(s...
[ "def", "prepare", "(", "self", ",", "node", ")", ":", "if", "isinstance", "(", "node", ",", "ast", ".", "Module", ")", ":", "self", ".", "ctx", ".", "module", "=", "node", "elif", "isinstance", "(", "node", ",", "ast", ".", "FunctionDef", ")", ":",...
Gather analysis result required by this analysis
[ "Gather", "analysis", "result", "required", "by", "this", "analysis" ]
python
train
fhs/pyhdf
pyhdf/SD.py
https://github.com/fhs/pyhdf/blob/dbdc1810a74a38df50dcad81fe903e239d2b388d/pyhdf/SD.py#L2344-L2426
def getrange(self): """Retrieve the dataset min and max values. Args:: no argument Returns:: (min, max) tuple (attribute 'valid_range') Note that those are the values as stored by the 'setrange' method. 'getrange' does *NOT* compute the min ...
[ "def", "getrange", "(", "self", ")", ":", "# Obtain SDS data type.", "try", ":", "sds_name", ",", "rank", ",", "dim_sizes", ",", "data_type", ",", "n_attrs", "=", "self", ".", "info", "(", ")", "except", "HDF4Error", ":", "raise", "HDF4Error", "(", "'getra...
Retrieve the dataset min and max values. Args:: no argument Returns:: (min, max) tuple (attribute 'valid_range') Note that those are the values as stored by the 'setrange' method. 'getrange' does *NOT* compute the min and max from the current datase...
[ "Retrieve", "the", "dataset", "min", "and", "max", "values", "." ]
python
train
Unidata/siphon
siphon/cdmr/ncstream.py
https://github.com/Unidata/siphon/blob/53fb0d84fbce1c18c8e81c9e68bc81620ee0a6ac/siphon/cdmr/ncstream.py#L373-L397
def unpack_attribute(att): """Unpack an embedded attribute into a python or numpy object.""" if att.unsigned: log.warning('Unsupported unsigned attribute!') # TDS 5.0 now has a dataType attribute that takes precedence if att.len == 0: # Empty val = None elif att.dataType == stream....
[ "def", "unpack_attribute", "(", "att", ")", ":", "if", "att", ".", "unsigned", ":", "log", ".", "warning", "(", "'Unsupported unsigned attribute!'", ")", "# TDS 5.0 now has a dataType attribute that takes precedence", "if", "att", ".", "len", "==", "0", ":", "# Empt...
Unpack an embedded attribute into a python or numpy object.
[ "Unpack", "an", "embedded", "attribute", "into", "a", "python", "or", "numpy", "object", "." ]
python
train
Kortemme-Lab/klab
klab/bio/fragments/hpc/SGE.py
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/fragments/hpc/SGE.py#L150-L210
def query(logfile, jobID = None): """If jobID is an integer then return False if the job has finished and True if it is still running. Otherwise, returns a table of jobs run by the user.""" joblist = logfile.readFromLogfile() if jobID and type(jobID) == type(1): command = ['qstat', '-j',...
[ "def", "query", "(", "logfile", ",", "jobID", "=", "None", ")", ":", "joblist", "=", "logfile", ".", "readFromLogfile", "(", ")", "if", "jobID", "and", "type", "(", "jobID", ")", "==", "type", "(", "1", ")", ":", "command", "=", "[", "'qstat'", ","...
If jobID is an integer then return False if the job has finished and True if it is still running. Otherwise, returns a table of jobs run by the user.
[ "If", "jobID", "is", "an", "integer", "then", "return", "False", "if", "the", "job", "has", "finished", "and", "True", "if", "it", "is", "still", "running", ".", "Otherwise", "returns", "a", "table", "of", "jobs", "run", "by", "the", "user", "." ]
python
train
saltstack/salt
salt/modules/bsd_shadow.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bsd_shadow.py#L178-L216
def set_password(name, password): ''' Set the password for a named user. The password must be a properly defined hash. The password hash can be generated with this command: ``python -c "import crypt; print crypt.crypt('password', ciphersalt)"`` .. note:: When constructing the ``ciphersalt`...
[ "def", "set_password", "(", "name", ",", "password", ")", ":", "if", "__grains__", ".", "get", "(", "'os'", ",", "''", ")", "==", "'FreeBSD'", ":", "cmd", "=", "[", "'pw'", ",", "'user'", ",", "'mod'", ",", "name", ",", "'-H'", ",", "'0'", "]", "...
Set the password for a named user. The password must be a properly defined hash. The password hash can be generated with this command: ``python -c "import crypt; print crypt.crypt('password', ciphersalt)"`` .. note:: When constructing the ``ciphersalt`` string, you must escape any dollar s...
[ "Set", "the", "password", "for", "a", "named", "user", ".", "The", "password", "must", "be", "a", "properly", "defined", "hash", ".", "The", "password", "hash", "can", "be", "generated", "with", "this", "command", ":" ]
python
train
wylee/runcommands
runcommands/util/string.py
https://github.com/wylee/runcommands/blob/b1d7c262885b9ced7ab89b63562f5464ca9970fe/runcommands/util/string.py#L4-L42
def camel_to_underscore(name): """Convert camel case name to underscore name. Examples:: >>> camel_to_underscore('HttpRequest') 'http_request' >>> camel_to_underscore('httpRequest') 'http_request' >>> camel_to_underscore('HTTPRequest') 'http_request' >>>...
[ "def", "camel_to_underscore", "(", "name", ")", ":", "name", "=", "re", ".", "sub", "(", "r'(?<!\\b)(?<!_)([A-Z][a-z])'", ",", "r'_\\1'", ",", "name", ")", "name", "=", "re", ".", "sub", "(", "r'(?<!\\b)(?<!_)([a-z])([A-Z])'", ",", "r'\\1_\\2'", ",", "name", ...
Convert camel case name to underscore name. Examples:: >>> camel_to_underscore('HttpRequest') 'http_request' >>> camel_to_underscore('httpRequest') 'http_request' >>> camel_to_underscore('HTTPRequest') 'http_request' >>> camel_to_underscore('myHTTPRequest') ...
[ "Convert", "camel", "case", "name", "to", "underscore", "name", "." ]
python
train
sods/ods
pods/assesser.py
https://github.com/sods/ods/blob/3995c659f25a0a640f6009ed7fcc2559ce659b1d/pods/assesser.py#L211-L228
def marksheet(self): """Returns an pandas empty dataframe object containing rows and columns for marking. This can then be passed to a google doc that is distributed to markers for editing with the mark for each section.""" columns=['Number', 'Question', 'Correct (a fraction)', 'Max Mark', 'Comments'] ...
[ "def", "marksheet", "(", "self", ")", ":", "columns", "=", "[", "'Number'", ",", "'Question'", ",", "'Correct (a fraction)'", ",", "'Max Mark'", ",", "'Comments'", "]", "mark_sheet", "=", "pd", ".", "DataFrame", "(", ")", "for", "qu_number", ",", "question",...
Returns an pandas empty dataframe object containing rows and columns for marking. This can then be passed to a google doc that is distributed to markers for editing with the mark for each section.
[ "Returns", "an", "pandas", "empty", "dataframe", "object", "containing", "rows", "and", "columns", "for", "marking", ".", "This", "can", "then", "be", "passed", "to", "a", "google", "doc", "that", "is", "distributed", "to", "markers", "for", "editing", "with...
python
train
ASMfreaK/yandex_weather_api
yandex_weather_api/types.py
https://github.com/ASMfreaK/yandex_weather_api/blob/d58ad80f7389dc3b58c721bb42c2441e9ff3e351/yandex_weather_api/types.py#L60-L66
def validate(cls, cnd): "Проверяет, что переданный объект - один из возможных `VALUES`" if cnd not in cls.VALUES: raise ValueError("Value {} cannot be used in {}".format( cnd, cls )) return cls(cnd)
[ "def", "validate", "(", "cls", ",", "cnd", ")", ":", "if", "cnd", "not", "in", "cls", ".", "VALUES", ":", "raise", "ValueError", "(", "\"Value {} cannot be used in {}\"", ".", "format", "(", "cnd", ",", "cls", ")", ")", "return", "cls", "(", "cnd", ")"...
Проверяет, что переданный объект - один из возможных `VALUES`
[ "Проверяет", "что", "переданный", "объект", "-", "один", "из", "возможных", "VALUES" ]
python
train
timkpaine/pyEX
pyEX/alternative.py
https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/alternative.py#L38-L58
def sentiment(symbol, type='daily', date=None, token='', version=''): '''This endpoint provides social sentiment data from StockTwits. Data can be viewed as a daily value, or by minute for a given date. https://iexcloud.io/docs/api/#social-sentiment Continuous Args: symbol (string); Ticker to ...
[ "def", "sentiment", "(", "symbol", ",", "type", "=", "'daily'", ",", "date", "=", "None", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "_raiseIfNotStr", "(", "symbol", ")", "if", "date", ":", "date", "=", "_strOrDate", "(", "date", ...
This endpoint provides social sentiment data from StockTwits. Data can be viewed as a daily value, or by minute for a given date. https://iexcloud.io/docs/api/#social-sentiment Continuous Args: symbol (string); Ticker to request type (string); 'daily' or 'minute' date (string); dat...
[ "This", "endpoint", "provides", "social", "sentiment", "data", "from", "StockTwits", ".", "Data", "can", "be", "viewed", "as", "a", "daily", "value", "or", "by", "minute", "for", "a", "given", "date", "." ]
python
valid
IvanMalison/okcupyd
okcupyd/util/__init__.py
https://github.com/IvanMalison/okcupyd/blob/46f4eaa9419098f6c299738ce148af55c64deb64/okcupyd/util/__init__.py#L105-L111
def from_string_pairs(cls, string_value_pairs, **kwargs): """Build an :class:`~.REMap` from str, value pairs by applying `re.compile` to each string and calling the __init__ of :class:`~.REMap` """ return cls(re_value_pairs=[(re.compile(s), v) for s, v ...
[ "def", "from_string_pairs", "(", "cls", ",", "string_value_pairs", ",", "*", "*", "kwargs", ")", ":", "return", "cls", "(", "re_value_pairs", "=", "[", "(", "re", ".", "compile", "(", "s", ")", ",", "v", ")", "for", "s", ",", "v", "in", "string_value...
Build an :class:`~.REMap` from str, value pairs by applying `re.compile` to each string and calling the __init__ of :class:`~.REMap`
[ "Build", "an", ":", "class", ":", "~", ".", "REMap", "from", "str", "value", "pairs", "by", "applying", "re", ".", "compile", "to", "each", "string", "and", "calling", "the", "__init__", "of", ":", "class", ":", "~", ".", "REMap" ]
python
train
InspectorMustache/base16-builder-python
pybase16_builder/shared.py
https://github.com/InspectorMustache/base16-builder-python/blob/586f1f87ee9f70696ab19c542af6ef55c6548a2e/pybase16_builder/shared.py#L12-L20
def get_yaml_dict(yaml_file): """Return a yaml_dict from reading yaml_file. If yaml_file is empty or doesn't exist, return an empty dict instead.""" try: with open(yaml_file, 'r') as file_: yaml_dict = yaml.safe_load(file_.read()) or {} return yaml_dict except FileNotFoundErr...
[ "def", "get_yaml_dict", "(", "yaml_file", ")", ":", "try", ":", "with", "open", "(", "yaml_file", ",", "'r'", ")", "as", "file_", ":", "yaml_dict", "=", "yaml", ".", "safe_load", "(", "file_", ".", "read", "(", ")", ")", "or", "{", "}", "return", "...
Return a yaml_dict from reading yaml_file. If yaml_file is empty or doesn't exist, return an empty dict instead.
[ "Return", "a", "yaml_dict", "from", "reading", "yaml_file", ".", "If", "yaml_file", "is", "empty", "or", "doesn", "t", "exist", "return", "an", "empty", "dict", "instead", "." ]
python
train
nickoala/telepot
telepot/helper.py
https://github.com/nickoala/telepot/blob/3792fde251d0f1d5a6ca16c8ad1a71f89360c41d/telepot/helper.py#L1002-L1008
def map(self, msg): """ Apply key function to ``msg`` to obtain a key. Return the routing table entry. """ k = self.key_function(msg) key = k[0] if isinstance(k, (tuple, list)) else k return self.routing_table[key]
[ "def", "map", "(", "self", ",", "msg", ")", ":", "k", "=", "self", ".", "key_function", "(", "msg", ")", "key", "=", "k", "[", "0", "]", "if", "isinstance", "(", "k", ",", "(", "tuple", ",", "list", ")", ")", "else", "k", "return", "self", "....
Apply key function to ``msg`` to obtain a key. Return the routing table entry.
[ "Apply", "key", "function", "to", "msg", "to", "obtain", "a", "key", ".", "Return", "the", "routing", "table", "entry", "." ]
python
train
fbcotter/py3nvml
py3nvml/py3nvml.py
https://github.com/fbcotter/py3nvml/blob/47f0f2c0eee56dec4e4beebec26b734e01d357b7/py3nvml/py3nvml.py#L4019-L4058
def nvmlDeviceClearEccErrorCounts(handle, counterType): r""" /** * Clear the ECC error and other memory error counts for the device. * * For Kepler &tm; or newer fully supported devices. * Only applicable to devices with ECC. * Requires \a NVML_INFOROM_ECC version 2.0 or higher to clear...
[ "def", "nvmlDeviceClearEccErrorCounts", "(", "handle", ",", "counterType", ")", ":", "fn", "=", "_nvmlGetFunctionPointer", "(", "\"nvmlDeviceClearEccErrorCounts\"", ")", "ret", "=", "fn", "(", "handle", ",", "_nvmlEccCounterType_t", "(", "counterType", ")", ")", "_n...
r""" /** * Clear the ECC error and other memory error counts for the device. * * For Kepler &tm; or newer fully supported devices. * Only applicable to devices with ECC. * Requires \a NVML_INFOROM_ECC version 2.0 or higher to clear aggregate location-based ECC counts. * Requires \a NVM...
[ "r", "/", "**", "*", "Clear", "the", "ECC", "error", "and", "other", "memory", "error", "counts", "for", "the", "device", ".", "*", "*", "For", "Kepler", "&tm", ";", "or", "newer", "fully", "supported", "devices", ".", "*", "Only", "applicable", "to", ...
python
train
ActivisionGameScience/assertpy
assertpy/assertpy.py
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L856-L864
def is_before(self, other): """Asserts that val is a date and is before other date.""" if type(self.val) is not datetime.datetime: raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__) if type(other) is not datetime.datetime: raise TypeError...
[ "def", "is_before", "(", "self", ",", "other", ")", ":", "if", "type", "(", "self", ".", "val", ")", "is", "not", "datetime", ".", "datetime", ":", "raise", "TypeError", "(", "'val must be datetime, but was type <%s>'", "%", "type", "(", "self", ".", "val"...
Asserts that val is a date and is before other date.
[ "Asserts", "that", "val", "is", "a", "date", "and", "is", "before", "other", "date", "." ]
python
valid
Pegase745/sqlalchemy-datatables
examples/pyramid_tut/pyramid_tut/views.py
https://github.com/Pegase745/sqlalchemy-datatables/blob/049ab5f98f20ad37926fe86d5528da0c91cd462d/examples/pyramid_tut/pyramid_tut/views.py#L83-L98
def data_advanced(request): """Return server side data.""" columns = [ ColumnDT(User.id, search_method="numeric"), ColumnDT(User.name), ColumnDT(Address.description), ColumnDT(User.birthday, search_method="date"), ColumnDT(User.age, search_method="numeric") ] que...
[ "def", "data_advanced", "(", "request", ")", ":", "columns", "=", "[", "ColumnDT", "(", "User", ".", "id", ",", "search_method", "=", "\"numeric\"", ")", ",", "ColumnDT", "(", "User", ".", "name", ")", ",", "ColumnDT", "(", "Address", ".", "description",...
Return server side data.
[ "Return", "server", "side", "data", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L208-L258
def unit(x1, x2, block_num, depth, num_layers, dim='2d', bottleneck=True, first_batch_norm=True, stride=1, training=True): """Implements bottleneck RevNet unit from authors' RevNet architecture. Args: x1: [N, H, W, C] tensor of network activations. x2: [N, H, W, C] tensor of network activations. ...
[ "def", "unit", "(", "x1", ",", "x2", ",", "block_num", ",", "depth", ",", "num_layers", ",", "dim", "=", "'2d'", ",", "bottleneck", "=", "True", ",", "first_batch_norm", "=", "True", ",", "stride", "=", "1", ",", "training", "=", "True", ")", ":", ...
Implements bottleneck RevNet unit from authors' RevNet architecture. Args: x1: [N, H, W, C] tensor of network activations. x2: [N, H, W, C] tensor of network activations. block_num: integer ID of block depth: First depth in bottleneck residual unit. num_layers: Number of layers in the RevNet bloc...
[ "Implements", "bottleneck", "RevNet", "unit", "from", "authors", "RevNet", "architecture", "." ]
python
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/util/quaternion.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/quaternion.py#L87-L103
def exp(self): """ Returns the exponent of the quaternion. (not tested) """ # Init vecNorm = self.x**2 + self.y**2 + self.z**2 wPart = np.exp(self.w) q = Quaternion() # Calculate q.w = wPart * np.cos(vecNorm) q.x ...
[ "def", "exp", "(", "self", ")", ":", "# Init", "vecNorm", "=", "self", ".", "x", "**", "2", "+", "self", ".", "y", "**", "2", "+", "self", ".", "z", "**", "2", "wPart", "=", "np", ".", "exp", "(", "self", ".", "w", ")", "q", "=", "Quaternio...
Returns the exponent of the quaternion. (not tested)
[ "Returns", "the", "exponent", "of", "the", "quaternion", ".", "(", "not", "tested", ")" ]
python
train
davgeo/clear
clear/database.py
https://github.com/davgeo/clear/blob/5ec85d27efd28afddfcd4c3f44df17f0115a77aa/clear/database.py#L230-L252
def SetConfigValue(self, fieldName, value): """ Set value in Config table. If a entry already exists this is updated with the new value, otherwise a new entry is added. Parameters ---------- fieldName : string String to be inserted or matched against Name column in Config table. ...
[ "def", "SetConfigValue", "(", "self", ",", "fieldName", ",", "value", ")", ":", "currentConfigValue", "=", "self", ".", "GetConfigValue", "(", "fieldName", ")", "if", "currentConfigValue", "is", "None", ":", "goodlogging", ".", "Log", ".", "Info", "(", "\"DB...
Set value in Config table. If a entry already exists this is updated with the new value, otherwise a new entry is added. Parameters ---------- fieldName : string String to be inserted or matched against Name column in Config table. value : string Entry to be inserted or up...
[ "Set", "value", "in", "Config", "table", "." ]
python
train
econ-ark/HARK
HARK/ConsumptionSaving/ConsIndShockModel.py
https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsIndShockModel.py#L1383-L1446
def solveConsKinkedR(solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,Rboro,Rsave, PermGroFac,BoroCnstArt,aXtraGrid,vFuncBool,CubicBool): ''' Solves a single period consumption-saving problem with CRRA utility and risky income (subject to permanent and transitory shocks), and ...
[ "def", "solveConsKinkedR", "(", "solution_next", ",", "IncomeDstn", ",", "LivPrb", ",", "DiscFac", ",", "CRRA", ",", "Rboro", ",", "Rsave", ",", "PermGroFac", ",", "BoroCnstArt", ",", "aXtraGrid", ",", "vFuncBool", ",", "CubicBool", ")", ":", "solver", "=", ...
Solves a single period consumption-saving problem with CRRA utility and risky income (subject to permanent and transitory shocks), and different interest factors on borrowing and saving. Restriction: Rboro >= Rsave. Currently cannot construct a cubic spline consumption function, only linear. Can gen- ...
[ "Solves", "a", "single", "period", "consumption", "-", "saving", "problem", "with", "CRRA", "utility", "and", "risky", "income", "(", "subject", "to", "permanent", "and", "transitory", "shocks", ")", "and", "different", "interest", "factors", "on", "borrowing", ...
python
train
fastai/fastai
fastai/widgets/image_downloader.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/widgets/image_downloader.py#L78-L91
def download_google_images(path:PathOrStr, search_term:str, size:str='>400*300', n_images:int=10, format:str='jpg', max_workers:int=defaults.cpus, timeout:int=4) -> FilePathList: """ Search for `n_images` images on Google, matching `search_term` and `size` requirements, download ...
[ "def", "download_google_images", "(", "path", ":", "PathOrStr", ",", "search_term", ":", "str", ",", "size", ":", "str", "=", "'>400*300'", ",", "n_images", ":", "int", "=", "10", ",", "format", ":", "str", "=", "'jpg'", ",", "max_workers", ":", "int", ...
Search for `n_images` images on Google, matching `search_term` and `size` requirements, download them into `path`/`search_term` and verify them, using `max_workers` threads.
[ "Search", "for", "n_images", "images", "on", "Google", "matching", "search_term", "and", "size", "requirements", "download", "them", "into", "path", "/", "search_term", "and", "verify", "them", "using", "max_workers", "threads", "." ]
python
train
mozilla/elasticutils
elasticutils/__init__.py
https://github.com/mozilla/elasticutils/blob/b880cc5d51fb1079b0581255ec664c1ec934656e/elasticutils/__init__.py#L694-L759
def query(self, *queries, **kw): """ Return a new S instance with query args combined with existing set in a must boolean query. :arg queries: instances of Q :arg kw: queries in the form of ``field__action=value`` There are three special flags you can use: * ``...
[ "def", "query", "(", "self", ",", "*", "queries", ",", "*", "*", "kw", ")", ":", "q", "=", "Q", "(", ")", "for", "query", "in", "queries", ":", "q", "+=", "query", "if", "'or_'", "in", "kw", ":", "# Backwards compatibile with pre-0.7 version.", "or_que...
Return a new S instance with query args combined with existing set in a must boolean query. :arg queries: instances of Q :arg kw: queries in the form of ``field__action=value`` There are three special flags you can use: * ``must=True``: Specifies that the queries and kw querie...
[ "Return", "a", "new", "S", "instance", "with", "query", "args", "combined", "with", "existing", "set", "in", "a", "must", "boolean", "query", "." ]
python
train
spyder-ide/spyder
spyder/config/gui.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/config/gui.py#L169-L173
def is_dark_font_color(color_scheme): """Check if the font color used in the color scheme is dark.""" color_scheme = get_color_scheme(color_scheme) font_color, fon_fw, fon_fs = color_scheme['normal'] return dark_color(font_color)
[ "def", "is_dark_font_color", "(", "color_scheme", ")", ":", "color_scheme", "=", "get_color_scheme", "(", "color_scheme", ")", "font_color", ",", "fon_fw", ",", "fon_fs", "=", "color_scheme", "[", "'normal'", "]", "return", "dark_color", "(", "font_color", ")" ]
Check if the font color used in the color scheme is dark.
[ "Check", "if", "the", "font", "color", "used", "in", "the", "color", "scheme", "is", "dark", "." ]
python
train
ratt-ru/PyMORESANE
pymoresane/iuwt_convolution.py
https://github.com/ratt-ru/PyMORESANE/blob/b024591ad0bbb69320d08841f28a2c27f62ae1af/pymoresane/iuwt_convolution.py#L242-L265
def scale_fft(in1): """ This function performs in-place scaling after the IFFT without recompilation. INPUTS: in1 (no default): Array containing data which is to be scaled. """ ker = SourceModule(""" __global__ void scale_fft_ker(float *in1) ...
[ "def", "scale_fft", "(", "in1", ")", ":", "ker", "=", "SourceModule", "(", "\"\"\"\n __global__ void scale_fft_ker(float *in1)\n {\n const int len = gridDim.x*blockDim.x;\n const int col = (blockD...
This function performs in-place scaling after the IFFT without recompilation. INPUTS: in1 (no default): Array containing data which is to be scaled.
[ "This", "function", "performs", "in", "-", "place", "scaling", "after", "the", "IFFT", "without", "recompilation", "." ]
python
train
Gandi/gandi.cli
gandi/cli/modules/domain.py
https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/domain.py#L122-L126
def from_fqdn(cls, fqdn): """Retrieve domain id associated to a FQDN.""" result = cls.list({'fqdn': fqdn}) if len(result) > 0: return result[0]['id']
[ "def", "from_fqdn", "(", "cls", ",", "fqdn", ")", ":", "result", "=", "cls", ".", "list", "(", "{", "'fqdn'", ":", "fqdn", "}", ")", "if", "len", "(", "result", ")", ">", "0", ":", "return", "result", "[", "0", "]", "[", "'id'", "]" ]
Retrieve domain id associated to a FQDN.
[ "Retrieve", "domain", "id", "associated", "to", "a", "FQDN", "." ]
python
train
emory-libraries/eulfedora
eulfedora/models.py
https://github.com/emory-libraries/eulfedora/blob/161826f3fdcdab4007f6fa7dfd9f1ecabc4bcbe4/eulfedora/models.py#L2155-L2191
def for_class(digobj, repo): '''Generate a ContentModel object for the specified :class:`DigitalObject` class. Content model object is saved in the specified repository if it doesn't already exist.''' full_name = '%s.%s' % (digobj.__module__, digobj.__name__) cmodels = getattr(d...
[ "def", "for_class", "(", "digobj", ",", "repo", ")", ":", "full_name", "=", "'%s.%s'", "%", "(", "digobj", ".", "__module__", ",", "digobj", ".", "__name__", ")", "cmodels", "=", "getattr", "(", "digobj", ",", "'CONTENT_MODELS'", ",", "None", ")", "if", ...
Generate a ContentModel object for the specified :class:`DigitalObject` class. Content model object is saved in the specified repository if it doesn't already exist.
[ "Generate", "a", "ContentModel", "object", "for", "the", "specified", ":", "class", ":", "DigitalObject", "class", ".", "Content", "model", "object", "is", "saved", "in", "the", "specified", "repository", "if", "it", "doesn", "t", "already", "exist", "." ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/mp_tile.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_map/mp_tile.py#L216-L225
def coord_to_tile(self, lat, lon, zoom): '''convert lat/lon/zoom to a TileInfo''' world_tiles = 1<<zoom x = world_tiles / 360.0 * (lon + 180.0) tiles_pre_radian = world_tiles / (2 * math.pi) e = math.sin(lat * (1/180.*math.pi)) y = world_tiles/2 + 0.5*math.log((1+e)/(1-e)) * (-tiles_pre_radian) offsetx = ...
[ "def", "coord_to_tile", "(", "self", ",", "lat", ",", "lon", ",", "zoom", ")", ":", "world_tiles", "=", "1", "<<", "zoom", "x", "=", "world_tiles", "/", "360.0", "*", "(", "lon", "+", "180.0", ")", "tiles_pre_radian", "=", "world_tiles", "/", "(", "2...
convert lat/lon/zoom to a TileInfo
[ "convert", "lat", "/", "lon", "/", "zoom", "to", "a", "TileInfo" ]
python
train
aws/aws-xray-sdk-python
aws_xray_sdk/core/sampling/reservoir.py
https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/core/sampling/reservoir.py#L23-L30
def borrow_or_take(self, now, can_borrow): """ Decide whether to borrow or take one quota from the reservoir. Return ``False`` if it can neither borrow nor take. This method is thread-safe. """ with self._lock: return self._borrow_or_take(now, can_borrow)
[ "def", "borrow_or_take", "(", "self", ",", "now", ",", "can_borrow", ")", ":", "with", "self", ".", "_lock", ":", "return", "self", ".", "_borrow_or_take", "(", "now", ",", "can_borrow", ")" ]
Decide whether to borrow or take one quota from the reservoir. Return ``False`` if it can neither borrow nor take. This method is thread-safe.
[ "Decide", "whether", "to", "borrow", "or", "take", "one", "quota", "from", "the", "reservoir", ".", "Return", "False", "if", "it", "can", "neither", "borrow", "nor", "take", ".", "This", "method", "is", "thread", "-", "safe", "." ]
python
train
hydraplatform/hydra-base
hydra_base/util/hydra_dateutil.py
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/hydra_dateutil.py#L296-L352
def reindex_timeseries(ts_string, new_timestamps): """ get data for timesamp :param a JSON string, in pandas-friendly format :param a timestamp or list of timestamps (datetimes) :returns a pandas data frame, reindexed with the supplied timestamos or None if no data is found """ ...
[ "def", "reindex_timeseries", "(", "ts_string", ",", "new_timestamps", ")", ":", "#If a single timestamp is passed in, turn it into a list", "#Reindexing can't work if it's not a list", "if", "not", "isinstance", "(", "new_timestamps", ",", "list", ")", ":", "new_timestamps", ...
get data for timesamp :param a JSON string, in pandas-friendly format :param a timestamp or list of timestamps (datetimes) :returns a pandas data frame, reindexed with the supplied timestamos or None if no data is found
[ "get", "data", "for", "timesamp" ]
python
train
pymc-devs/pymc
pymc/diagnostics.py
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/diagnostics.py#L94-L228
def validate(sampler, replicates=20, iterations=10000, burn=5000, thin=1, deterministic=False, db='ram', plot=True, verbose=0): """ Model validation method, following Cook et al. (Journal of Computational and Graphical Statistics, 2006, DOI: 10.1198/106186006X136976). Generates posterior s...
[ "def", "validate", "(", "sampler", ",", "replicates", "=", "20", ",", "iterations", "=", "10000", ",", "burn", "=", "5000", ",", "thin", "=", "1", ",", "deterministic", "=", "False", ",", "db", "=", "'ram'", ",", "plot", "=", "True", ",", "verbose", ...
Model validation method, following Cook et al. (Journal of Computational and Graphical Statistics, 2006, DOI: 10.1198/106186006X136976). Generates posterior samples based on 'true' parameter values and data simulated from the priors. The quantiles of the parameter values are calculated, based on the sa...
[ "Model", "validation", "method", "following", "Cook", "et", "al", ".", "(", "Journal", "of", "Computational", "and", "Graphical", "Statistics", "2006", "DOI", ":", "10", ".", "1198", "/", "106186006X136976", ")", "." ]
python
train
Hackerfleet/hfos
modules/chat/hfos/chat/bot.py
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/modules/chat/hfos/chat/bot.py#L67-L81
def say(self, event): """Chat event handler for incoming events :param event: say-event with incoming chat message """ try: userid = event.user.uuid recipient = self._get_recipient(event) content = self._get_content(event) if self.config....
[ "def", "say", "(", "self", ",", "event", ")", ":", "try", ":", "userid", "=", "event", ".", "user", ".", "uuid", "recipient", "=", "self", ".", "_get_recipient", "(", "event", ")", "content", "=", "self", ".", "_get_content", "(", "event", ")", "if",...
Chat event handler for incoming events :param event: say-event with incoming chat message
[ "Chat", "event", "handler", "for", "incoming", "events", ":", "param", "event", ":", "say", "-", "event", "with", "incoming", "chat", "message" ]
python
train
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L846-L884
def no_more_a_problem(self, hosts, services, timeperiods, bi_modulations): """Remove this objects as an impact for other schedulingitem. :param hosts: hosts objects, used to get impacts :type hosts: alignak.objects.host.Hosts :param services: services objects, used to get impacts ...
[ "def", "no_more_a_problem", "(", "self", ",", "hosts", ",", "services", ",", "timeperiods", ",", "bi_modulations", ")", ":", "was_pb", "=", "self", ".", "is_problem", "if", "self", ".", "is_problem", ":", "self", ".", "is_problem", "=", "False", "# we warn i...
Remove this objects as an impact for other schedulingitem. :param hosts: hosts objects, used to get impacts :type hosts: alignak.objects.host.Hosts :param services: services objects, used to get impacts :type services: alignak.objects.service.Services :param timeperiods: Timeper...
[ "Remove", "this", "objects", "as", "an", "impact", "for", "other", "schedulingitem", "." ]
python
train
swisscom/cleanerversion
versions/deletion.py
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/deletion.py#L185-L194
def versionable_delete(self, instance, timestamp): """ Soft-deletes the instance, setting it's version_end_date to timestamp. Override this method to implement custom behaviour. :param Versionable instance: :param datetime timestamp: """ instance._delete_at(time...
[ "def", "versionable_delete", "(", "self", ",", "instance", ",", "timestamp", ")", ":", "instance", ".", "_delete_at", "(", "timestamp", ",", "using", "=", "self", ".", "using", ")" ]
Soft-deletes the instance, setting it's version_end_date to timestamp. Override this method to implement custom behaviour. :param Versionable instance: :param datetime timestamp:
[ "Soft", "-", "deletes", "the", "instance", "setting", "it", "s", "version_end_date", "to", "timestamp", "." ]
python
train
wolfhong/formic
formic/formic.py
https://github.com/wolfhong/formic/blob/0d81eb88dcbb6fa705194fc6ccf2993f4abbaa76/formic/formic.py#L801-L811
def _find_parent(self, path_elements): """Recurse up the tree of FileSetStates until we find a parent, i.e. one whose path_elements member is the start of the path_element argument""" if not self.path_elements: # Automatically terminate on root return self ...
[ "def", "_find_parent", "(", "self", ",", "path_elements", ")", ":", "if", "not", "self", ".", "path_elements", ":", "# Automatically terminate on root", "return", "self", "elif", "self", ".", "path_elements", "==", "path_elements", "[", "0", ":", "len", "(", "...
Recurse up the tree of FileSetStates until we find a parent, i.e. one whose path_elements member is the start of the path_element argument
[ "Recurse", "up", "the", "tree", "of", "FileSetStates", "until", "we", "find", "a", "parent", "i", ".", "e", ".", "one", "whose", "path_elements", "member", "is", "the", "start", "of", "the", "path_element", "argument" ]
python
train
PythonCharmers/python-future
src/future/backports/email/utils.py
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/utils.py#L267-L279
def encode_rfc2231(s, charset=None, language=None): """Encode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the string is encoded using the empty string for language. """ s = url_quote(s, safe='', encodin...
[ "def", "encode_rfc2231", "(", "s", ",", "charset", "=", "None", ",", "language", "=", "None", ")", ":", "s", "=", "url_quote", "(", "s", ",", "safe", "=", "''", ",", "encoding", "=", "charset", "or", "'ascii'", ")", "if", "charset", "is", "None", "...
Encode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the string is encoded using the empty string for language.
[ "Encode", "string", "according", "to", "RFC", "2231", "." ]
python
train
gnosis/gnosis-py
gnosis/safe/safe_tx.py
https://github.com/gnosis/gnosis-py/blob/2a9a5d75a375fc9813ac04df133e6910c82f9d49/gnosis/safe/safe_tx.py#L189-L223
def execute(self, tx_sender_private_key: str, tx_gas: Optional[int] = None, tx_gas_price: Optional[int] = None, tx_nonce: Optional[int] = None, block_identifier='pending') -> Tuple[bytes, Dict[str, any]]: """ Send multisig t...
[ "def", "execute", "(", "self", ",", "tx_sender_private_key", ":", "str", ",", "tx_gas", ":", "Optional", "[", "int", "]", "=", "None", ",", "tx_gas_price", ":", "Optional", "[", "int", "]", "=", "None", ",", "tx_nonce", ":", "Optional", "[", "int", "]"...
Send multisig tx to the Safe :param tx_sender_private_key: Sender private key :param tx_gas: Gas for the external tx. If not, `(safe_tx_gas + data_gas) * 2` will be used :param tx_gas_price: Gas price of the external tx. If not, `gas_price` will be used :param tx_nonce: Force nonce for `...
[ "Send", "multisig", "tx", "to", "the", "Safe", ":", "param", "tx_sender_private_key", ":", "Sender", "private", "key", ":", "param", "tx_gas", ":", "Gas", "for", "the", "external", "tx", ".", "If", "not", "(", "safe_tx_gas", "+", "data_gas", ")", "*", "2...
python
test
pyviz/holoviews
holoviews/plotting/util.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/util.py#L985-L998
def _get_min_distance_numpy(element): """ NumPy based implementation of get_min_distance """ xys = element.array([0, 1]) with warnings.catch_warnings(): warnings.filterwarnings('ignore', r'invalid value encountered in') xys = xys.astype('float32').view(np.complex64) distances...
[ "def", "_get_min_distance_numpy", "(", "element", ")", ":", "xys", "=", "element", ".", "array", "(", "[", "0", ",", "1", "]", ")", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "filterwarnings", "(", "'ignore'", ",", "r'inva...
NumPy based implementation of get_min_distance
[ "NumPy", "based", "implementation", "of", "get_min_distance" ]
python
train
oemof/demandlib
demandlib/bdew.py
https://github.com/oemof/demandlib/blob/4b62d60e05cb06eb2590f9c5655c2cdebf494080/demandlib/bdew.py#L178-L219
def weighted_temperature(self, how='geometric_series'): r""" A new temperature vector is generated containing a multi-day average temperature as needed in the load profile function. Parameters ---------- how : string string which type to return ("geometric_se...
[ "def", "weighted_temperature", "(", "self", ",", "how", "=", "'geometric_series'", ")", ":", "# calculate daily mean temperature", "temperature", "=", "self", ".", "df", "[", "'temperature'", "]", ".", "resample", "(", "'D'", ")", ".", "mean", "(", ")", ".", ...
r""" A new temperature vector is generated containing a multi-day average temperature as needed in the load profile function. Parameters ---------- how : string string which type to return ("geometric_series" or "mean") Notes ----- Equation f...
[ "r", "A", "new", "temperature", "vector", "is", "generated", "containing", "a", "multi", "-", "day", "average", "temperature", "as", "needed", "in", "the", "load", "profile", "function", "." ]
python
train
KelSolaar/Foundations
foundations/parsers.py
https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/parsers.py#L672-L798
def parse(self, raw_sections=None, namespaces=True, strip_comments=True, strip_whitespaces=True, strip_quotation_markers=True, raise_parsing_errors=True): """ Process the file content and extracts the sections / attribut...
[ "def", "parse", "(", "self", ",", "raw_sections", "=", "None", ",", "namespaces", "=", "True", ",", "strip_comments", "=", "True", ",", "strip_whitespaces", "=", "True", ",", "strip_quotation_markers", "=", "True", ",", "raise_parsing_errors", "=", "True", ")"...
Process the file content and extracts the sections / attributes as nested :class:`collections.OrderedDict` dictionaries or dictionaries. Usage:: >>> content = ["; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "Attribute 2 = \\"Value B\\"\\n"] >>> sections_file_parser = Se...
[ "Process", "the", "file", "content", "and", "extracts", "the", "sections", "/", "attributes", "as", "nested", ":", "class", ":", "collections", ".", "OrderedDict", "dictionaries", "or", "dictionaries", "." ]
python
train
ekzhu/datasketch
datasketch/lean_minhash.py
https://github.com/ekzhu/datasketch/blob/b3e4129987890a2beb04f2c0b6dc618ae35f2e14/datasketch/lean_minhash.py#L51-L60
def _initialize_slots(self, seed, hashvalues): '''Initialize the slots of the LeanMinHash. Args: seed (int): The random seed controls the set of random permutation functions generated for this LeanMinHash. hashvalues: The hash values is the internal state of the ...
[ "def", "_initialize_slots", "(", "self", ",", "seed", ",", "hashvalues", ")", ":", "self", ".", "seed", "=", "seed", "self", ".", "hashvalues", "=", "self", ".", "_parse_hashvalues", "(", "hashvalues", ")" ]
Initialize the slots of the LeanMinHash. Args: seed (int): The random seed controls the set of random permutation functions generated for this LeanMinHash. hashvalues: The hash values is the internal state of the LeanMinHash.
[ "Initialize", "the", "slots", "of", "the", "LeanMinHash", "." ]
python
test
tensorflow/tensor2tensor
tensor2tensor/models/vanilla_gan.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/vanilla_gan.py#L37-L48
def deconv2d( input_, output_shape, k_h, k_w, d_h, d_w, stddev=0.02, name="deconv2d"): """Deconvolution layer.""" with tf.variable_scope(name): w = tf.get_variable( "w", [k_h, k_w, output_shape[-1], input_.get_shape()[-1]], initializer=tf.random_normal_initializer(stddev=stddev)) deconv ...
[ "def", "deconv2d", "(", "input_", ",", "output_shape", ",", "k_h", ",", "k_w", ",", "d_h", ",", "d_w", ",", "stddev", "=", "0.02", ",", "name", "=", "\"deconv2d\"", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "w", "=", "tf...
Deconvolution layer.
[ "Deconvolution", "layer", "." ]
python
train
icgood/pymap
pymap/parsing/specials/sequenceset.py
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/specials/sequenceset.py#L61-L72
def is_all(self) -> bool: """True if the sequence set starts at ``1`` and ends at the maximum value. This may be used to optimize cases of checking for a value in the set, avoiding the need to provide ``max_value`` in :meth:`.flatten` or :meth:`.iter`. """ first...
[ "def", "is_all", "(", "self", ")", "->", "bool", ":", "first", "=", "self", ".", "sequences", "[", "0", "]", "return", "isinstance", "(", "first", ",", "tuple", ")", "and", "first", "[", "0", "]", "==", "1", "and", "isinstance", "(", "first", "[", ...
True if the sequence set starts at ``1`` and ends at the maximum value. This may be used to optimize cases of checking for a value in the set, avoiding the need to provide ``max_value`` in :meth:`.flatten` or :meth:`.iter`.
[ "True", "if", "the", "sequence", "set", "starts", "at", "1", "and", "ends", "at", "the", "maximum", "value", "." ]
python
train
tkem/cachetools
cachetools/__init__.py
https://github.com/tkem/cachetools/blob/1b67cddadccb89993e9d2567bac22e57e2b2b373/cachetools/__init__.py#L71-L112
def cachedmethod(cache, key=keys.hashkey, lock=None): """Decorator to wrap a class or instance method with a memoizing callable that saves results in a cache. """ def decorator(method): if lock is None: def wrapper(self, *args, **kwargs): c = cache(self) ...
[ "def", "cachedmethod", "(", "cache", ",", "key", "=", "keys", ".", "hashkey", ",", "lock", "=", "None", ")", ":", "def", "decorator", "(", "method", ")", ":", "if", "lock", "is", "None", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", ...
Decorator to wrap a class or instance method with a memoizing callable that saves results in a cache.
[ "Decorator", "to", "wrap", "a", "class", "or", "instance", "method", "with", "a", "memoizing", "callable", "that", "saves", "results", "in", "a", "cache", "." ]
python
train
manns/pyspread
pyspread/src/lib/vlc.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/vlc.py#L5676-L5684
def libvlc_video_get_aspect_ratio(p_mi): '''Get current video aspect ratio. @param p_mi: the media player. @return: the video aspect ratio or NULL if unspecified (the result must be released with free() or L{libvlc_free}()). ''' f = _Cfunctions.get('libvlc_video_get_aspect_ratio', None) or \ ...
[ "def", "libvlc_video_get_aspect_ratio", "(", "p_mi", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_video_get_aspect_ratio'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_get_aspect_ratio'", ",", "(", "(", "1", ",", ")", ",", ")", ",...
Get current video aspect ratio. @param p_mi: the media player. @return: the video aspect ratio or NULL if unspecified (the result must be released with free() or L{libvlc_free}()).
[ "Get", "current", "video", "aspect", "ratio", "." ]
python
train
dariosky/wfcli
wfcli/tossl.py
https://github.com/dariosky/wfcli/blob/87a9ed30dbd456f801135a55099f0541b0614ccb/wfcli/tossl.py#L184-L198
def website_exists_as_secure(self, website): """" Return true if the website has an equivalent that is secure we will have 2 websites with the same name, one insecure (that will contain just the redirect and the identity-verification) and one secured """ if website['https...
[ "def", "website_exists_as_secure", "(", "self", ",", "website", ")", ":", "if", "website", "[", "'https'", "]", ":", "logger", ".", "info", "(", "\"website %s is already secured, skip\"", "%", "website", "[", "'name'", "]", ")", "return", "website", "# changes i...
Return true if the website has an equivalent that is secure we will have 2 websites with the same name, one insecure (that will contain just the redirect and the identity-verification) and one secured
[ "Return", "true", "if", "the", "website", "has", "an", "equivalent", "that", "is", "secure", "we", "will", "have", "2", "websites", "with", "the", "same", "name", "one", "insecure", "(", "that", "will", "contain", "just", "the", "redirect", "and", "the", ...
python
train
pandas-dev/pandas
pandas/io/parsers.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/parsers.py#L1951-L2003
def _set_noconvert_columns(self): """ Set the columns that should not undergo dtype conversions. Currently, any column that is involved with date parsing will not undergo such conversions. """ names = self.orig_names if self.usecols_dtype == 'integer': ...
[ "def", "_set_noconvert_columns", "(", "self", ")", ":", "names", "=", "self", ".", "orig_names", "if", "self", ".", "usecols_dtype", "==", "'integer'", ":", "# A set of integers will be converted to a list in", "# the correct order every single time.", "usecols", "=", "li...
Set the columns that should not undergo dtype conversions. Currently, any column that is involved with date parsing will not undergo such conversions.
[ "Set", "the", "columns", "that", "should", "not", "undergo", "dtype", "conversions", "." ]
python
train
andycasey/sick
sick/models/cannon.py
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/cannon.py#L82-L114
def train_local(self, closest_point, label_vector_description=None, N=None, pivot=True, **kwargs): """ Train the model in a Cannon-like fashion using the grid points as labels and the intensities as normalsied rest-frame fluxes within some local regime. """ lv = ...
[ "def", "train_local", "(", "self", ",", "closest_point", ",", "label_vector_description", "=", "None", ",", "N", "=", "None", ",", "pivot", "=", "True", ",", "*", "*", "kwargs", ")", ":", "lv", "=", "self", ".", "_cannon_label_vector", "if", "label_vector_...
Train the model in a Cannon-like fashion using the grid points as labels and the intensities as normalsied rest-frame fluxes within some local regime.
[ "Train", "the", "model", "in", "a", "Cannon", "-", "like", "fashion", "using", "the", "grid", "points", "as", "labels", "and", "the", "intensities", "as", "normalsied", "rest", "-", "frame", "fluxes", "within", "some", "local", "regime", "." ]
python
train
mushkevych/scheduler
synergy/scheduler/timetable.py
https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/scheduler/timetable.py#L262-L267
def is_job_record_finalizable(self, job_record): """ :return: True, if the node and all its children are in [STATE_PROCESSED, STATE_SKIPPED, STATE_NOOP] """ assert isinstance(job_record, Job) tree = self.get_tree(job_record.process_name) node = tree.get_node(job_record.process_name, job_...
[ "def", "is_job_record_finalizable", "(", "self", ",", "job_record", ")", ":", "assert", "isinstance", "(", "job_record", ",", "Job", ")", "tree", "=", "self", ".", "get_tree", "(", "job_record", ".", "process_name", ")", "node", "=", "tree", ".", "get_node",...
:return: True, if the node and all its children are in [STATE_PROCESSED, STATE_SKIPPED, STATE_NOOP]
[ ":", "return", ":", "True", "if", "the", "node", "and", "all", "its", "children", "are", "in", "[", "STATE_PROCESSED", "STATE_SKIPPED", "STATE_NOOP", "]" ]
python
train
jalanb/pysyte
pysyte/getch.py
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/getch.py#L155-L167
def get_key(): """Get a key from the keyboard as a string A 'key' will be a single char, or the name of an extended key """ character_name = chr codes = _get_keycodes() if len(codes) == 1: code = codes[0] if code >= 32: return character_name(code) return cont...
[ "def", "get_key", "(", ")", ":", "character_name", "=", "chr", "codes", "=", "_get_keycodes", "(", ")", "if", "len", "(", "codes", ")", "==", "1", ":", "code", "=", "codes", "[", "0", "]", "if", "code", ">=", "32", ":", "return", "character_name", ...
Get a key from the keyboard as a string A 'key' will be a single char, or the name of an extended key
[ "Get", "a", "key", "from", "the", "keyboard", "as", "a", "string" ]
python
train
potash/drain
drain/util.py
https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/util.py#L273-L291
def dict_diff(dicts): """ Subset dictionaries to keys which map to multiple values """ diff_keys = set() for k in union(set(d.keys()) for d in dicts): values = [] for d in dicts: if k not in d: diff_keys.add(k) break else: ...
[ "def", "dict_diff", "(", "dicts", ")", ":", "diff_keys", "=", "set", "(", ")", "for", "k", "in", "union", "(", "set", "(", "d", ".", "keys", "(", ")", ")", "for", "d", "in", "dicts", ")", ":", "values", "=", "[", "]", "for", "d", "in", "dicts...
Subset dictionaries to keys which map to multiple values
[ "Subset", "dictionaries", "to", "keys", "which", "map", "to", "multiple", "values" ]
python
train
gem/oq-engine
openquake/calculators/export/hazard.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L59-L77
def export_ruptures_xml(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ fmt = ekey[-1] oq = dstore['oqparam'] num_ses = oq.ses_per_logic_tree_path mesh = get_mesh(dstore['sitecol']) ruptures_by_grp = {} for rgetter ...
[ "def", "export_ruptures_xml", "(", "ekey", ",", "dstore", ")", ":", "fmt", "=", "ekey", "[", "-", "1", "]", "oq", "=", "dstore", "[", "'oqparam'", "]", "num_ses", "=", "oq", ".", "ses_per_logic_tree_path", "mesh", "=", "get_mesh", "(", "dstore", "[", "...
:param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object
[ ":", "param", "ekey", ":", "export", "key", "i", ".", "e", ".", "a", "pair", "(", "datastore", "key", "fmt", ")", ":", "param", "dstore", ":", "datastore", "object" ]
python
train
akfullfo/taskforce
taskforce/task.py
https://github.com/akfullfo/taskforce/blob/bc6dd744bd33546447d085dbd18a350532220193/taskforce/task.py#L1355-L1372
def file_del(self, key, paths=None): """ Deregister a task for file event changes. If paths is None, all paths assoicated with the task will be deregistered. """ if paths is None: paths = [] for path in self._file_event_map: if key in self._fi...
[ "def", "file_del", "(", "self", ",", "key", ",", "paths", "=", "None", ")", ":", "if", "paths", "is", "None", ":", "paths", "=", "[", "]", "for", "path", "in", "self", ".", "_file_event_map", ":", "if", "key", "in", "self", ".", "_file_event_map", ...
Deregister a task for file event changes. If paths is None, all paths assoicated with the task will be deregistered.
[ "Deregister", "a", "task", "for", "file", "event", "changes", ".", "If", "paths", "is", "None", "all", "paths", "assoicated", "with", "the", "task", "will", "be", "deregistered", "." ]
python
train
inspirehep/inspire-utils
inspire_utils/name.py
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/name.py#L146-L200
def dumps(self): """Dump the name to string, after normalizing it.""" def _is_initial(author_name): return len(author_name) == 1 or u'.' in author_name def _ensure_dotted_initials(author_name): if _is_initial(author_name) \ and u'.' not in author_name...
[ "def", "dumps", "(", "self", ")", ":", "def", "_is_initial", "(", "author_name", ")", ":", "return", "len", "(", "author_name", ")", "==", "1", "or", "u'.'", "in", "author_name", "def", "_ensure_dotted_initials", "(", "author_name", ")", ":", "if", "_is_in...
Dump the name to string, after normalizing it.
[ "Dump", "the", "name", "to", "string", "after", "normalizing", "it", "." ]
python
train
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L1074-L1186
def _table_viewer(table, rows_per_page=25, fields=None): """ Return a table viewer. This includes a static rendering of the first page of the table, that gets replaced by the charting code in environments where Javascript is executable and BQ is available. Args: table: the table to view. rows_per...
[ "def", "_table_viewer", "(", "table", ",", "rows_per_page", "=", "25", ",", "fields", "=", "None", ")", ":", "# TODO(gram): rework this to use google.datalab.utils.commands.chart_html", "if", "not", "table", ".", "exists", "(", ")", ":", "raise", "Exception", "(", ...
Return a table viewer. This includes a static rendering of the first page of the table, that gets replaced by the charting code in environments where Javascript is executable and BQ is available. Args: table: the table to view. rows_per_page: how many rows to display at one time. fields: an arra...
[ "Return", "a", "table", "viewer", "." ]
python
train
chaoss/grimoirelab-elk
grimoire_elk/elk.py
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/grimoire_elk/elk.py#L524-L668
def enrich_backend(url, clean, backend_name, backend_params, cfg_section_name, ocean_index=None, ocean_index_enrich=None, db_projects_map=None, json_projects_map=None, db_sortinghat=None, no_incremental=False, only_identities...
[ "def", "enrich_backend", "(", "url", ",", "clean", ",", "backend_name", ",", "backend_params", ",", "cfg_section_name", ",", "ocean_index", "=", "None", ",", "ocean_index_enrich", "=", "None", ",", "db_projects_map", "=", "None", ",", "json_projects_map", "=", "...
Enrich Ocean index
[ "Enrich", "Ocean", "index" ]
python
train
vtkiorg/vtki
vtki/common.py
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L295-L328
def _point_scalar(self, name=None): """ Returns point scalars of a vtk object Parameters ---------- name : str Name of point scalars to retrive. Returns ------- scalars : np.ndarray Numpy array of scalars """ if n...
[ "def", "_point_scalar", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "# use active scalar array", "field", ",", "name", "=", "self", ".", "active_scalar_info", "if", "field", "!=", "POINT_DATA_FIELD", ":", "raise", "Runti...
Returns point scalars of a vtk object Parameters ---------- name : str Name of point scalars to retrive. Returns ------- scalars : np.ndarray Numpy array of scalars
[ "Returns", "point", "scalars", "of", "a", "vtk", "object" ]
python
train
mozilla/treeherder
treeherder/etl/jobs.py
https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/etl/jobs.py#L75-L328
def _load_job(repository, job_datum, push_id): """ Load a job into the treeherder database If the job is a ``retry`` the ``job_guid`` will have a special suffix on it. But the matching ``pending``/``running`` job will not. So we append the suffixed ``job_guid`` to ``retry_job_guids`` so that w...
[ "def", "_load_job", "(", "repository", ",", "job_datum", ",", "push_id", ")", ":", "build_platform", ",", "_", "=", "BuildPlatform", ".", "objects", ".", "get_or_create", "(", "os_name", "=", "job_datum", ".", "get", "(", "'build_platform'", ",", "{", "}", ...
Load a job into the treeherder database If the job is a ``retry`` the ``job_guid`` will have a special suffix on it. But the matching ``pending``/``running`` job will not. So we append the suffixed ``job_guid`` to ``retry_job_guids`` so that we can update the job_id_lookup later with the non-suffixed ...
[ "Load", "a", "job", "into", "the", "treeherder", "database" ]
python
train
tdryer/hangups
examples/lookup_entities.py
https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/examples/lookup_entities.py#L8-L20
async def lookup_entities(client, args): """Search for entities by phone number, email, or gaia_id.""" lookup_spec = _get_lookup_spec(args.entity_identifier) request = hangups.hangouts_pb2.GetEntityByIdRequest( request_header=client.get_request_header(), batch_lookup_spec=[lookup_spec], ...
[ "async", "def", "lookup_entities", "(", "client", ",", "args", ")", ":", "lookup_spec", "=", "_get_lookup_spec", "(", "args", ".", "entity_identifier", ")", "request", "=", "hangups", ".", "hangouts_pb2", ".", "GetEntityByIdRequest", "(", "request_header", "=", ...
Search for entities by phone number, email, or gaia_id.
[ "Search", "for", "entities", "by", "phone", "number", "email", "or", "gaia_id", "." ]
python
valid
odlgroup/odl
odl/solvers/functional/default_functionals.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/solvers/functional/default_functionals.py#L2635-L2651
def _call(self, x): """Return ``self(x)``.""" if isinstance(self.domain, ProductSpace): norm = PointwiseNorm(self.domain, 2)(x) else: norm = x.ufuncs.absolute() if self.gamma > 0: tmp = norm.ufuncs.square() tmp *= 1 / (2 * self.gamma) ...
[ "def", "_call", "(", "self", ",", "x", ")", ":", "if", "isinstance", "(", "self", ".", "domain", ",", "ProductSpace", ")", ":", "norm", "=", "PointwiseNorm", "(", "self", ".", "domain", ",", "2", ")", "(", "x", ")", "else", ":", "norm", "=", "x",...
Return ``self(x)``.
[ "Return", "self", "(", "x", ")", "." ]
python
train
readbeyond/aeneas
aeneas/adjustboundaryalgorithm.py
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/adjustboundaryalgorithm.py#L541-L546
def _adjust_rate_aggressive(self, real_wave_mfcc, algo_parameters): """ RATEAGGRESSIVE """ self.log(u"Called _adjust_rate_aggressive") self._apply_rate(max_rate=algo_parameters[0], aggressive=True)
[ "def", "_adjust_rate_aggressive", "(", "self", ",", "real_wave_mfcc", ",", "algo_parameters", ")", ":", "self", ".", "log", "(", "u\"Called _adjust_rate_aggressive\"", ")", "self", ".", "_apply_rate", "(", "max_rate", "=", "algo_parameters", "[", "0", "]", ",", ...
RATEAGGRESSIVE
[ "RATEAGGRESSIVE" ]
python
train
projectshift/shift-schema
shiftschema/translator.py
https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/translator.py#L22-L34
def normalize_locale(locale): """ Normalize locale Extracts language code from passed in locale string to be used later for dictionaries loading. :param locale: string, locale (en, en_US) :return: string, language code """ import r...
[ "def", "normalize_locale", "(", "locale", ")", ":", "import", "re", "match", "=", "re", ".", "match", "(", "r'^[a-z]+'", ",", "locale", ".", "lower", "(", ")", ")", "if", "match", ":", "return", "match", ".", "group", "(", ")" ]
Normalize locale Extracts language code from passed in locale string to be used later for dictionaries loading. :param locale: string, locale (en, en_US) :return: string, language code
[ "Normalize", "locale", "Extracts", "language", "code", "from", "passed", "in", "locale", "string", "to", "be", "used", "later", "for", "dictionaries", "loading", "." ]
python
train
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L2104-L2125
def dafus(insum, nd, ni): """ Unpack an array summary into its double precision and integer components. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafus_c.html :param insum: Array summary. :type insum: Array of floats :param nd: Number of double precision components. :type nd:...
[ "def", "dafus", "(", "insum", ",", "nd", ",", "ni", ")", ":", "insum", "=", "stypes", ".", "toDoubleVector", "(", "insum", ")", "dc", "=", "stypes", ".", "emptyDoubleVector", "(", "nd", ")", "ic", "=", "stypes", ".", "emptyIntVector", "(", "ni", ")",...
Unpack an array summary into its double precision and integer components. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafus_c.html :param insum: Array summary. :type insum: Array of floats :param nd: Number of double precision components. :type nd: int :param ni: Number of integer ...
[ "Unpack", "an", "array", "summary", "into", "its", "double", "precision", "and", "integer", "components", "." ]
python
train
tensorflow/tensor2tensor
tensor2tensor/models/research/attention_lm.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/attention_lm.py#L167-L182
def attention_lm_small(): """Cheap model. on lm1b_32k: 45M params 2 steps/sec on [GeForce GTX TITAN X] Returns: an hparams object. """ hparams = attention_lm_base() hparams.num_hidden_layers = 4 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.layer_prepostprocess_dropout ...
[ "def", "attention_lm_small", "(", ")", ":", "hparams", "=", "attention_lm_base", "(", ")", "hparams", ".", "num_hidden_layers", "=", "4", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "filter_size", "=", "2048", "hparams", ".", "layer_prepostprocess...
Cheap model. on lm1b_32k: 45M params 2 steps/sec on [GeForce GTX TITAN X] Returns: an hparams object.
[ "Cheap", "model", "." ]
python
train
blockstack/blockstack-core
blockstack/lib/subdomains.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/subdomains.py#L1250-L1269
def get_domain_resolver(self, domain_name, cur=None): """ Get the last-knwon resolver entry for a domain name Returns None if not found. """ get_cmd = "SELECT resolver FROM {} WHERE domain=? AND resolver != '' AND accepted=1 ORDER BY sequence DESC, parent_zonefile_index DESC LIMI...
[ "def", "get_domain_resolver", "(", "self", ",", "domain_name", ",", "cur", "=", "None", ")", ":", "get_cmd", "=", "\"SELECT resolver FROM {} WHERE domain=? AND resolver != '' AND accepted=1 ORDER BY sequence DESC, parent_zonefile_index DESC LIMIT 1;\"", ".", "format", "(", "self"...
Get the last-knwon resolver entry for a domain name Returns None if not found.
[ "Get", "the", "last", "-", "knwon", "resolver", "entry", "for", "a", "domain", "name", "Returns", "None", "if", "not", "found", "." ]
python
train
rameshg87/pyremotevbox
pyremotevbox/ZSI/address.py
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/address.py#L88-L93
def _checkReplyTo(self, value): '''WS-Address From value -- From server returned in wsa:To ''' if value != self._replyTo: raise WSActionException, 'wrong WS-Address ReplyTo(%s), expecting %s'%(value,self._replyTo)
[ "def", "_checkReplyTo", "(", "self", ",", "value", ")", ":", "if", "value", "!=", "self", ".", "_replyTo", ":", "raise", "WSActionException", ",", "'wrong WS-Address ReplyTo(%s), expecting %s'", "%", "(", "value", ",", "self", ".", "_replyTo", ")" ]
WS-Address From value -- From server returned in wsa:To
[ "WS", "-", "Address", "From", "value", "--", "From", "server", "returned", "in", "wsa", ":", "To" ]
python
train
orbeckst/RecSQL
recsql/export.py
https://github.com/orbeckst/RecSQL/blob/6acbf821022361719391697c9c2f0822f9f8022a/recsql/export.py#L50-L54
def rec2latex(r, filename, empty=""): """Export a recarray *r* to a LaTeX table in *filename*""" with open(filename, "w") as latex: latex.write(s_rec2latex(r, empty=empty)) return filename
[ "def", "rec2latex", "(", "r", ",", "filename", ",", "empty", "=", "\"\"", ")", ":", "with", "open", "(", "filename", ",", "\"w\"", ")", "as", "latex", ":", "latex", ".", "write", "(", "s_rec2latex", "(", "r", ",", "empty", "=", "empty", ")", ")", ...
Export a recarray *r* to a LaTeX table in *filename*
[ "Export", "a", "recarray", "*", "r", "*", "to", "a", "LaTeX", "table", "in", "*", "filename", "*" ]
python
train
google/grumpy
third_party/stdlib/warnings.py
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/warnings.py#L95-L113
def simplefilter(action, category=Warning, lineno=0, append=0): """Insert a simple entry into the list of warnings filters (at the front). A simple filter matches all modules and messages. 'action' -- one of "error", "ignore", "always", "default", "module", or "once" 'category' -- a cla...
[ "def", "simplefilter", "(", "action", ",", "category", "=", "Warning", ",", "lineno", "=", "0", ",", "append", "=", "0", ")", ":", "assert", "action", "in", "(", "\"error\"", ",", "\"ignore\"", ",", "\"always\"", ",", "\"default\"", ",", "\"module\"", ",...
Insert a simple entry into the list of warnings filters (at the front). A simple filter matches all modules and messages. 'action' -- one of "error", "ignore", "always", "default", "module", or "once" 'category' -- a class that the warning must be a subclass of 'lineno' -- an integer li...
[ "Insert", "a", "simple", "entry", "into", "the", "list", "of", "warnings", "filters", "(", "at", "the", "front", ")", "." ]
python
valid
croscon/fleaker
fleaker/exceptions.py
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/exceptions.py#L349-L373
def post_create_app(cls, app, **settings): """Register the errorhandler for the AppException to the passed in App. Args: app (fleaker.base.BaseApplication): A Flask application that extends the Fleaker Base Application, such that the hooks are impleme...
[ "def", "post_create_app", "(", "cls", ",", "app", ",", "*", "*", "settings", ")", ":", "register_errorhandler", "=", "settings", ".", "pop", "(", "'register_errorhandler'", ",", "True", ")", "if", "register_errorhandler", ":", "AppException", ".", "register_erro...
Register the errorhandler for the AppException to the passed in App. Args: app (fleaker.base.BaseApplication): A Flask application that extends the Fleaker Base Application, such that the hooks are implemented. Kwargs: register_errorhandl...
[ "Register", "the", "errorhandler", "for", "the", "AppException", "to", "the", "passed", "in", "App", "." ]
python
train
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/fda3bb39181437b6b8a0aa0185f21ae5f14385dd/autopep8.py#L2134-L2173
def _add_item(self, item, indent_amt): """Add an item to the line. Reflow the line to get the best formatting after the item is inserted. The bracket depth indicates if the item is being inserted inside of a container or not. """ if self._prev_item and self._prev_item.i...
[ "def", "_add_item", "(", "self", ",", "item", ",", "indent_amt", ")", ":", "if", "self", ".", "_prev_item", "and", "self", ".", "_prev_item", ".", "is_string", "and", "item", ".", "is_string", ":", "# Place consecutive string literals on separate lines.", "self", ...
Add an item to the line. Reflow the line to get the best formatting after the item is inserted. The bracket depth indicates if the item is being inserted inside of a container or not.
[ "Add", "an", "item", "to", "the", "line", "." ]
python
train
benley/butcher
butcher/targets/pkgfilegroup.py
https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/targets/pkgfilegroup.py#L51-L59
def translate_path(self, dep_file, dep_rule): """Translate dep_file from dep_rule into this rule's output path.""" dst_base = dep_file.split(os.path.join(dep_rule.address.repo, dep_rule.address.path), 1)[-1] if self.params['strip_prefix']: ...
[ "def", "translate_path", "(", "self", ",", "dep_file", ",", "dep_rule", ")", ":", "dst_base", "=", "dep_file", ".", "split", "(", "os", ".", "path", ".", "join", "(", "dep_rule", ".", "address", ".", "repo", ",", "dep_rule", ".", "address", ".", "path"...
Translate dep_file from dep_rule into this rule's output path.
[ "Translate", "dep_file", "from", "dep_rule", "into", "this", "rule", "s", "output", "path", "." ]
python
train
pydata/pandas-gbq
pandas_gbq/gbq.py
https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L1185-L1195
def _generate_bq_schema(df, default_type="STRING"): """DEPRECATED: Given a dataframe, generate a Google BigQuery schema. This is a private method, but was used in external code to work around issues in the default schema generation. Now that individual columns can be overridden: https://github.com/pyda...
[ "def", "_generate_bq_schema", "(", "df", ",", "default_type", "=", "\"STRING\"", ")", ":", "from", "pandas_gbq", "import", "schema", "return", "schema", ".", "generate_bq_schema", "(", "df", ",", "default_type", "=", "default_type", ")" ]
DEPRECATED: Given a dataframe, generate a Google BigQuery schema. This is a private method, but was used in external code to work around issues in the default schema generation. Now that individual columns can be overridden: https://github.com/pydata/pandas-gbq/issues/218, this method can be removed af...
[ "DEPRECATED", ":", "Given", "a", "dataframe", "generate", "a", "Google", "BigQuery", "schema", "." ]
python
train
python-hyper/wsproto
example/synchronous_server.py
https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/example/synchronous_server.py#L18-L41
def main(): ''' Run the server. ''' try: ip = sys.argv[1] port = int(sys.argv[2]) except (IndexError, ValueError): print('Usage: {} <BIND_IP> <PORT>'.format(sys.argv[0])) sys.exit(1) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket....
[ "def", "main", "(", ")", ":", "try", ":", "ip", "=", "sys", ".", "argv", "[", "1", "]", "port", "=", "int", "(", "sys", ".", "argv", "[", "2", "]", ")", "except", "(", "IndexError", ",", "ValueError", ")", ":", "print", "(", "'Usage: {} <BIND_IP>...
Run the server.
[ "Run", "the", "server", "." ]
python
train
nickstenning/tagalog
tagalog/io.py
https://github.com/nickstenning/tagalog/blob/c6847a957dc4f96836a5cf13c4eb664fccafaac2/tagalog/io.py#L24-L68
def lines(fp): """ Read lines of UTF-8 from the file-like object given in ``fp``, making sure that when reading from STDIN, reads are at most line-buffered. UTF-8 decoding errors are handled silently. Invalid characters are replaced by U+FFFD REPLACEMENT CHARACTER. Line endings are normalised ...
[ "def", "lines", "(", "fp", ")", ":", "if", "fp", ".", "fileno", "(", ")", "==", "sys", ".", "stdin", ".", "fileno", "(", ")", ":", "close", "=", "True", "try", ":", "# Python 3", "fp", "=", "open", "(", "fp", ".", "fileno", "(", ")", ",", "mo...
Read lines of UTF-8 from the file-like object given in ``fp``, making sure that when reading from STDIN, reads are at most line-buffered. UTF-8 decoding errors are handled silently. Invalid characters are replaced by U+FFFD REPLACEMENT CHARACTER. Line endings are normalised to newlines by Python's uni...
[ "Read", "lines", "of", "UTF", "-", "8", "from", "the", "file", "-", "like", "object", "given", "in", "fp", "making", "sure", "that", "when", "reading", "from", "STDIN", "reads", "are", "at", "most", "line", "-", "buffered", "." ]
python
train
marcomusy/vtkplotter
vtkplotter/utils.py
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/utils.py#L100-L105
def versor(v): """Return the unit vector. Input can be a list of vectors.""" if isinstance(v[0], np.ndarray): return np.divide(v, mag(v)[:, None]) else: return v / mag(v)
[ "def", "versor", "(", "v", ")", ":", "if", "isinstance", "(", "v", "[", "0", "]", ",", "np", ".", "ndarray", ")", ":", "return", "np", ".", "divide", "(", "v", ",", "mag", "(", "v", ")", "[", ":", ",", "None", "]", ")", "else", ":", "return...
Return the unit vector. Input can be a list of vectors.
[ "Return", "the", "unit", "vector", ".", "Input", "can", "be", "a", "list", "of", "vectors", "." ]
python
train
arteria/django-openinghours
openinghours/utils.py
https://github.com/arteria/django-openinghours/blob/6bad47509a14d65a3a5a08777455f4cc8b4961fa/openinghours/utils.py#L69-L111
def is_open(location, now=None): """ Is the company currently open? Pass "now" to test with a specific timestamp. Can be used stand-alone or as a helper. """ if now is None: now = get_now() if has_closing_rule_for_now(location): return False now_time = datetime.time(now.hou...
[ "def", "is_open", "(", "location", ",", "now", "=", "None", ")", ":", "if", "now", "is", "None", ":", "now", "=", "get_now", "(", ")", "if", "has_closing_rule_for_now", "(", "location", ")", ":", "return", "False", "now_time", "=", "datetime", ".", "ti...
Is the company currently open? Pass "now" to test with a specific timestamp. Can be used stand-alone or as a helper.
[ "Is", "the", "company", "currently", "open?", "Pass", "now", "to", "test", "with", "a", "specific", "timestamp", ".", "Can", "be", "used", "stand", "-", "alone", "or", "as", "a", "helper", "." ]
python
train
klmitch/aversion
aversion.py
https://github.com/klmitch/aversion/blob/90ca68e7d6426a77db8a926171f8d3bbeb00ee4c/aversion.py#L137-L156
def _match_mask(mask, ctype): """ Determine if a content type mask matches a given content type. :param mask: The content type mask, taken from the Accept header. :param ctype: The content type to match to the mask. """ # Handle the simple cases first if '*' not in mask: ...
[ "def", "_match_mask", "(", "mask", ",", "ctype", ")", ":", "# Handle the simple cases first", "if", "'*'", "not", "in", "mask", ":", "return", "ctype", "==", "mask", "elif", "mask", "==", "'*/*'", ":", "return", "True", "elif", "not", "mask", ".", "endswit...
Determine if a content type mask matches a given content type. :param mask: The content type mask, taken from the Accept header. :param ctype: The content type to match to the mask.
[ "Determine", "if", "a", "content", "type", "mask", "matches", "a", "given", "content", "type", "." ]
python
train
kennethreitz/omnijson
omnijson/core.py
https://github.com/kennethreitz/omnijson/blob/a5890a51a59ad76f78a61f5bf91fa86b784cf694/omnijson/core.py#L41-L51
def loads(s, **kwargs): """Loads JSON object.""" try: return _engine[0](s) except _engine[2]: # except_clause: 'except' [test ['as' NAME]] # grammar for py3x # except_clause: 'except' [test [('as' | ',') test]] # grammar for py2x why = sys.exc_info()[1] raise JSONE...
[ "def", "loads", "(", "s", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "_engine", "[", "0", "]", "(", "s", ")", "except", "_engine", "[", "2", "]", ":", "# except_clause: 'except' [test ['as' NAME]] # grammar for py3x", "# except_clause: 'except' [t...
Loads JSON object.
[ "Loads", "JSON", "object", "." ]
python
train
aliyun/aliyun-odps-python-sdk
odps/models/instance.py
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/models/instance.py#L385-L414
def get_task_cost(self, task_name): """ Get task cost :param task_name: name of the task :return: task cost :rtype: Instance.TaskCost :Example: >>> cost = instance.get_task_cost(instance.get_task_names()[0]) >>> cost.cpu_cost 200 >>> cos...
[ "def", "get_task_cost", "(", "self", ",", "task_name", ")", ":", "summary", "=", "self", ".", "get_task_summary", "(", "task_name", ")", "if", "summary", "is", "None", ":", "return", "None", "if", "'Cost'", "in", "summary", ":", "task_cost", "=", "summary"...
Get task cost :param task_name: name of the task :return: task cost :rtype: Instance.TaskCost :Example: >>> cost = instance.get_task_cost(instance.get_task_names()[0]) >>> cost.cpu_cost 200 >>> cost.memory_cost 4096 >>> cost.input_size ...
[ "Get", "task", "cost" ]
python
train
annoviko/pyclustering
pyclustering/nnet/hysteresis.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/nnet/hysteresis.py#L192-L199
def outputs(self, values): """! @brief Sets outputs of neurons. """ self._outputs = [val for val in values]; self._outputs_buffer = [val for val in values];
[ "def", "outputs", "(", "self", ",", "values", ")", ":", "self", ".", "_outputs", "=", "[", "val", "for", "val", "in", "values", "]", "self", ".", "_outputs_buffer", "=", "[", "val", "for", "val", "in", "values", "]" ]
! @brief Sets outputs of neurons.
[ "!" ]
python
valid
NatLibFi/Skosify
skosify/check.py
https://github.com/NatLibFi/Skosify/blob/1d269987f10df08e706272dcf6a86aef4abebcde/skosify/check.py#L37-L58
def hierarchy_cycles(rdf, fix=False): """Check if the graph contains skos:broader cycles and optionally break these. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix: Fix the problem by removing any skos:broader that overlaps with skos:broaderTransitive. """ top_concepts = so...
[ "def", "hierarchy_cycles", "(", "rdf", ",", "fix", "=", "False", ")", ":", "top_concepts", "=", "sorted", "(", "rdf", ".", "subject_objects", "(", "SKOS", ".", "hasTopConcept", ")", ")", "status", "=", "{", "}", "for", "cs", ",", "root", "in", "top_con...
Check if the graph contains skos:broader cycles and optionally break these. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix: Fix the problem by removing any skos:broader that overlaps with skos:broaderTransitive.
[ "Check", "if", "the", "graph", "contains", "skos", ":", "broader", "cycles", "and", "optionally", "break", "these", "." ]
python
train
pypa/pipenv
pipenv/vendor/attr/_make.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/attr/_make.py#L2067-L2086
def and_(*validators): """ A validator that composes multiple validators into one. When called on a value, it runs all wrapped validators. :param validators: Arbitrary number of validators. :type validators: callables .. versionadded:: 17.1.0 """ vals = [] for validator in validat...
[ "def", "and_", "(", "*", "validators", ")", ":", "vals", "=", "[", "]", "for", "validator", "in", "validators", ":", "vals", ".", "extend", "(", "validator", ".", "_validators", "if", "isinstance", "(", "validator", ",", "_AndValidator", ")", "else", "["...
A validator that composes multiple validators into one. When called on a value, it runs all wrapped validators. :param validators: Arbitrary number of validators. :type validators: callables .. versionadded:: 17.1.0
[ "A", "validator", "that", "composes", "multiple", "validators", "into", "one", "." ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_policer.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_policer.py#L12-L21
def police_priority_map_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer") name = ET.SubElement(police_priority_map, "name") name.t...
[ "def", "police_priority_map_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "police_priority_map", "=", "ET", ".", "SubElement", "(", "config", ",", "\"police-priority-map\"", ",", "xmlns", ...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
urbn/Caesium
caesium/document.py
https://github.com/urbn/Caesium/blob/2a14fe79724c38fe9a1b20f7b8f518f8c6d50df1/caesium/document.py#L298-L309
def __make_storeable_patch_patchable(self, patch): """Replace all pipes with dots, transform back into the a namespace path. This is done before the $set query is applied to the document :param dict patch: The patch that is to be prepared to be applied """ new_patch = {} ...
[ "def", "__make_storeable_patch_patchable", "(", "self", ",", "patch", ")", ":", "new_patch", "=", "{", "}", "for", "key", "in", "patch", ":", "new_patch", "[", "key", ".", "replace", "(", "\"|\"", ",", "\".\"", ")", "]", "=", "patch", "[", "key", "]", ...
Replace all pipes with dots, transform back into the a namespace path. This is done before the $set query is applied to the document :param dict patch: The patch that is to be prepared to be applied
[ "Replace", "all", "pipes", "with", "dots", "transform", "back", "into", "the", "a", "namespace", "path", ".", "This", "is", "done", "before", "the", "$set", "query", "is", "applied", "to", "the", "document" ]
python
train
dw/mitogen
mitogen/minify.py
https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/mitogen/minify.py#L46-L61
def minimize_source(source): """Remove comments and docstrings from Python `source`, preserving line numbers and syntax of empty blocks. :param str source: The source to minimize. :returns str: The minimized source. """ source = mitogen.core.to_text(source) tokens = tokeniz...
[ "def", "minimize_source", "(", "source", ")", ":", "source", "=", "mitogen", ".", "core", ".", "to_text", "(", "source", ")", "tokens", "=", "tokenize", ".", "generate_tokens", "(", "StringIO", "(", "source", ")", ".", "readline", ")", "tokens", "=", "st...
Remove comments and docstrings from Python `source`, preserving line numbers and syntax of empty blocks. :param str source: The source to minimize. :returns str: The minimized source.
[ "Remove", "comments", "and", "docstrings", "from", "Python", "source", "preserving", "line", "numbers", "and", "syntax", "of", "empty", "blocks", "." ]
python
train
GeoffAtHome/lightwave
lightwave/lightwave.py
https://github.com/GeoffAtHome/lightwave/blob/2fab4ee8c9f14dd97dffd4b8cd70b217e884e581/lightwave/lightwave.py#L65-L68
def turn_off(self, device_id, name): """Create the message to turn light or switch off.""" msg = "!%sF0|Turn Off|%s" % (device_id, name) self._send_message(msg)
[ "def", "turn_off", "(", "self", ",", "device_id", ",", "name", ")", ":", "msg", "=", "\"!%sF0|Turn Off|%s\"", "%", "(", "device_id", ",", "name", ")", "self", ".", "_send_message", "(", "msg", ")" ]
Create the message to turn light or switch off.
[ "Create", "the", "message", "to", "turn", "light", "or", "switch", "off", "." ]
python
test
kibitzr/kibitzr
kibitzr/conf.py
https://github.com/kibitzr/kibitzr/blob/749da312488f1dda1ed1093cf4c95aaac0a604f7/kibitzr/conf.py#L135-L154
def reread(self): """ Read and parse credentials file. If something goes wrong, log exception and continue. """ logger.debug("Loading credentials from %s", os.path.abspath(self.creds_filename)) creds = {} try: with self.open_creds(...
[ "def", "reread", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Loading credentials from %s\"", ",", "os", ".", "path", ".", "abspath", "(", "self", ".", "creds_filename", ")", ")", "creds", "=", "{", "}", "try", ":", "with", "self", ".", "open...
Read and parse credentials file. If something goes wrong, log exception and continue.
[ "Read", "and", "parse", "credentials", "file", ".", "If", "something", "goes", "wrong", "log", "exception", "and", "continue", "." ]
python
train
PythonOptimizers/cygenja
cygenja/treemap/treemap.py
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/treemap/treemap.py#L111-L155
def _create_entry(self, location, element, unique=True, delete_element=False): """ Create an entry located at ``location``. Args: location: String or :class:`LocationDescriptor` to describe a "separator location" (i.e. dir1/dir2/dir3 for instance). ...
[ "def", "_create_entry", "(", "self", ",", "location", ",", "element", ",", "unique", "=", "True", ",", "delete_element", "=", "False", ")", ":", "loc_descriptor", "=", "self", ".", "_get_location_descriptor", "(", "location", ")", "# find parent node", "parent_n...
Create an entry located at ``location``. Args: location: String or :class:`LocationDescriptor` to describe a "separator location" (i.e. dir1/dir2/dir3 for instance). element: Element to store at the location. unique: ``True`` means that the element to...
[ "Create", "an", "entry", "located", "at", "location", ".", "Args", ":", "location", ":", "String", "or", ":", "class", ":", "LocationDescriptor", "to", "describe", "a", "separator", "location", "(", "i", ".", "e", ".", "dir1", "/", "dir2", "/", "dir3", ...
python
train
rinocloud/rinocloud-python
rinocloud/config.py
https://github.com/rinocloud/rinocloud-python/blob/7c4bf994a518f961cffedb7260fc1e4fa1838b38/rinocloud/config.py#L6-L20
def set_local_path(directory, create_dir=False): """ sets path for local saving of information if create is true we will create the folder even if it doesnt exist """ if not os.path.exists(directory) and create_dir is True: os.makedirs(directory) if not os.path.exists(directory)...
[ "def", "set_local_path", "(", "directory", ",", "create_dir", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", "and", "create_dir", "is", "True", ":", "os", ".", "makedirs", "(", "directory", ")", "if", "not...
sets path for local saving of information if create is true we will create the folder even if it doesnt exist
[ "sets", "path", "for", "local", "saving", "of", "information", "if", "create", "is", "true", "we", "will", "create", "the", "folder", "even", "if", "it", "doesnt", "exist" ]
python
train
klahnakoski/pyLibrary
mo_math/vendor/strangman/stats.py
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_math/vendor/strangman/stats.py#L427-L440
def itemfreq(inlist): """ Returns a list of pairs. Each pair consists of one of the scores in inlist and it's frequency count. Assumes a 1D list is passed. Usage: litemfreq(inlist) Returns: a 2D frequency table (col [0:n-1]=scores, col n=frequencies) """ scores = pstat.unique(inlist) scores.sort() ...
[ "def", "itemfreq", "(", "inlist", ")", ":", "scores", "=", "pstat", ".", "unique", "(", "inlist", ")", "scores", ".", "sort", "(", ")", "freq", "=", "[", "]", "for", "item", "in", "scores", ":", "freq", ".", "append", "(", "inlist", ".", "count", ...
Returns a list of pairs. Each pair consists of one of the scores in inlist and it's frequency count. Assumes a 1D list is passed. Usage: litemfreq(inlist) Returns: a 2D frequency table (col [0:n-1]=scores, col n=frequencies)
[ "Returns", "a", "list", "of", "pairs", ".", "Each", "pair", "consists", "of", "one", "of", "the", "scores", "in", "inlist", "and", "it", "s", "frequency", "count", ".", "Assumes", "a", "1D", "list", "is", "passed", "." ]
python
train
deepmipt/DeepPavlov
deeppavlov/core/models/keras_model.py
https://github.com/deepmipt/DeepPavlov/blob/f3e4a69a3764d25d2f5bad4f1f1aebc872b00f9c/deeppavlov/core/models/keras_model.py#L156-L165
def train_on_batch(self, *args) -> None: """Trains the model on a single batch. Args: *args: the list of network inputs. Last element of `args` is the batch of targets, all previous elements are training data batches """ *data, labels = args s...
[ "def", "train_on_batch", "(", "self", ",", "*", "args", ")", "->", "None", ":", "*", "data", ",", "labels", "=", "args", "self", ".", "_net", ".", "train_on_batch", "(", "data", ",", "labels", ")" ]
Trains the model on a single batch. Args: *args: the list of network inputs. Last element of `args` is the batch of targets, all previous elements are training data batches
[ "Trains", "the", "model", "on", "a", "single", "batch", "." ]
python
test
PyCQA/pydocstyle
src/pydocstyle/config.py
https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L218-L284
def _get_config(self, node): """Get and cache the run configuration for `node`. If no configuration exists (not local and not for the parent node), returns and caches a default configuration. The algorithm: ------------- * If the current directory's configuration exists...
[ "def", "_get_config", "(", "self", ",", "node", ")", ":", "if", "self", ".", "_run_conf", ".", "config", "is", "None", ":", "log", ".", "debug", "(", "'No config file specified, discovering.'", ")", "config", "=", "self", ".", "_get_config_by_discovery", "(", ...
Get and cache the run configuration for `node`. If no configuration exists (not local and not for the parent node), returns and caches a default configuration. The algorithm: ------------- * If the current directory's configuration exists in `self._cache` - return it...
[ "Get", "and", "cache", "the", "run", "configuration", "for", "node", "." ]
python
train
stevearc/dql
dql/models.py
https://github.com/stevearc/dql/blob/e9d3aa22873076dae5ebd02e35318aa996b1e56a/dql/models.py#L574-L590
def schema(self): """ The DQL query that will construct this table's schema """ attrs = self.attrs.copy() parts = ["CREATE", "TABLE", self.name, "(%s," % self.hash_key.schema] del attrs[self.hash_key.name] if self.range_key: parts.append(self.range_key.schema + ",") ...
[ "def", "schema", "(", "self", ")", ":", "attrs", "=", "self", ".", "attrs", ".", "copy", "(", ")", "parts", "=", "[", "\"CREATE\"", ",", "\"TABLE\"", ",", "self", ".", "name", ",", "\"(%s,\"", "%", "self", ".", "hash_key", ".", "schema", "]", "del"...
The DQL query that will construct this table's schema
[ "The", "DQL", "query", "that", "will", "construct", "this", "table", "s", "schema" ]
python
train
twilio/twilio-python
twilio/rest/api/v2010/account/sip/domain/__init__.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/sip/domain/__init__.py#L369-L382
def auth(self): """ Access the auth :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList """ if self._auth is None: self._auth = AuthTypesList( se...
[ "def", "auth", "(", "self", ")", ":", "if", "self", ".", "_auth", "is", "None", ":", "self", ".", "_auth", "=", "AuthTypesList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", "domain_si...
Access the auth :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList
[ "Access", "the", "auth" ]
python
train