nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
triaquae/triaquae | bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9 | TriAquae/models/django_auth_ldap/backend.py | python | _LDAPUser._populate_and_save_user_profile | (self) | Populates a User profile object with fields from the LDAP directory. | Populates a User profile object with fields from the LDAP directory. | [
"Populates",
"a",
"User",
"profile",
"object",
"with",
"fields",
"from",
"the",
"LDAP",
"directory",
"."
] | def _populate_and_save_user_profile(self):
"""
Populates a User profile object with fields from the LDAP directory.
"""
try:
profile = self._user.get_profile()
save_profile = False
logger.debug("Populating Django user profile for %s", get_user_username(self._user))
save_profile = self._populate_profile_from_attributes(profile) or save_profile
save_profile = self._populate_profile_from_group_memberships(profile) or save_profile
signal_responses = populate_user_profile.send(self.backend.__class__, profile=profile, ldap_user=self)
if len(signal_responses) > 0:
save_profile = True
if save_profile:
profile.save()
except (SiteProfileNotAvailable, ObjectDoesNotExist):
logger.debug("Django user %s does not have a profile to populate", get_user_username(self._user)) | [
"def",
"_populate_and_save_user_profile",
"(",
"self",
")",
":",
"try",
":",
"profile",
"=",
"self",
".",
"_user",
".",
"get_profile",
"(",
")",
"save_profile",
"=",
"False",
"logger",
".",
"debug",
"(",
"\"Populating Django user profile for %s\"",
",",
"get_user_... | https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django_auth_ldap/backend.py#L578-L598 | ||
blazeinfosec/bt2 | c80d599b441a4307ddd8467877ac3beeb2291ec9 | backdoorutils.py | python | get_internal_ip | () | return | NOT IMPLEMENTED YET | NOT IMPLEMENTED YET | [
"NOT",
"IMPLEMENTED",
"YET"
] | def get_internal_ip():
''' NOT IMPLEMENTED YET '''
return | [
"def",
"get_internal_ip",
"(",
")",
":",
"return"
] | https://github.com/blazeinfosec/bt2/blob/c80d599b441a4307ddd8467877ac3beeb2291ec9/backdoorutils.py#L109-L111 | |
Esri/ArcREST | ab240fde2b0200f61d4a5f6df033516e53f2f416 | src/arcrest/webmap/symbols.py | python | PictureFillSymbol.__init__ | (self,
url=None,
imageData="",
contentType=None,
width=18,
height=18,
angle=0,
xoffset=0,
yoffset=0,
xscale=0,
yscale=0,
outline=None) | Constructor | Constructor | [
"Constructor"
] | def __init__(self,
url=None,
imageData="",
contentType=None,
width=18,
height=18,
angle=0,
xoffset=0,
yoffset=0,
xscale=0,
yscale=0,
outline=None):
"""Constructor"""
self._url = url
self._imageDate = imageData
self._contentType = contentType
self._width = width
self._height = height
self._angle = angle
self._xoffset = xoffset
self._yoffset = yoffset
self._xscale = xscale
self._yscale = yscale
if self._outline is not None and \
self._outline is SimpleLineSymbol:
self._outline = outline.asDictionary | [
"def",
"__init__",
"(",
"self",
",",
"url",
"=",
"None",
",",
"imageData",
"=",
"\"\"",
",",
"contentType",
"=",
"None",
",",
"width",
"=",
"18",
",",
"height",
"=",
"18",
",",
"angle",
"=",
"0",
",",
"xoffset",
"=",
"0",
",",
"yoffset",
"=",
"0"... | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/webmap/symbols.py#L494-L519 | ||
nvdv/vprof | 8898b528b4a6bea6384a2b5dbe8f38b03a47bfda | vprof/profiler.py | python | Profiler._profile_package | (self) | return {
'objectName': self._object_name,
'callStats': self._transform_stats(prof_stats),
'totalTime': prof_stats.total_tt,
'primitiveCalls': prof_stats.prim_calls,
'totalCalls': prof_stats.total_calls,
'timestamp': int(time.time())
} | Runs cProfile on a package. | Runs cProfile on a package. | [
"Runs",
"cProfile",
"on",
"a",
"package",
"."
] | def _profile_package(self):
"""Runs cProfile on a package."""
prof = cProfile.Profile()
prof.enable()
try:
runpy.run_path(self._run_object, run_name='__main__')
except SystemExit:
pass
prof.disable()
prof_stats = pstats.Stats(prof)
prof_stats.calc_callees()
return {
'objectName': self._object_name,
'callStats': self._transform_stats(prof_stats),
'totalTime': prof_stats.total_tt,
'primitiveCalls': prof_stats.prim_calls,
'totalCalls': prof_stats.total_calls,
'timestamp': int(time.time())
} | [
"def",
"_profile_package",
"(",
"self",
")",
":",
"prof",
"=",
"cProfile",
".",
"Profile",
"(",
")",
"prof",
".",
"enable",
"(",
")",
"try",
":",
"runpy",
".",
"run_path",
"(",
"self",
".",
"_run_object",
",",
"run_name",
"=",
"'__main__'",
")",
"excep... | https://github.com/nvdv/vprof/blob/8898b528b4a6bea6384a2b5dbe8f38b03a47bfda/vprof/profiler.py#L36-L54 | |
docker-archive/docker-registry | f93b432d3fc7befa508ab27a590e6d0f78c86401 | depends/docker-registry-core/docker_registry/drivers/file.py | python | Storage.get_size | (self, path) | [] | def get_size(self, path):
path = self._init_path(path)
try:
return os.path.getsize(path)
except OSError:
raise exceptions.FileNotFoundError('%s is not there' % path) | [
"def",
"get_size",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"self",
".",
"_init_path",
"(",
"path",
")",
"try",
":",
"return",
"os",
".",
"path",
".",
"getsize",
"(",
"path",
")",
"except",
"OSError",
":",
"raise",
"exceptions",
".",
"FileNot... | https://github.com/docker-archive/docker-registry/blob/f93b432d3fc7befa508ab27a590e6d0f78c86401/depends/docker-registry-core/docker_registry/drivers/file.py#L140-L145 | ||||
mitre-attack/attack-scripts | b94e05c0a29a6fdfc9701c721fcf03cdf9f7945b | scripts/techniques_data_sources_vis.py | python | parse_relationships | (relationships) | parse stix relationships into appropriate data structures.
arguments:
relationships: list of stix-formatted relationship dicts | parse stix relationships into appropriate data structures. | [
"parse",
"stix",
"relationships",
"into",
"appropriate",
"data",
"structures",
"."
] | def parse_relationships(relationships):
"""parse stix relationships into appropriate data structures.
arguments:
relationships: list of stix-formatted relationship dicts
"""
# Iterate over each relationship
for obj in relationships:
# Load the source and target STIX IDs
src=obj['source_ref']
tgt=obj['target_ref']
# Handle each case
if src in id_to_tech and tgt in id_to_group:
add_link(id_to_tech[src], id_to_group[tgt], tech_to_group, group_to_tech)
if src in id_to_tech and tgt in id_to_software:
add_link(id_to_tech[src], id_to_software[tgt], tech_to_software, software_to_tech)
if src in id_to_software and tgt in id_to_group:
add_link(id_to_software[src], id_to_group[tgt], software_to_group, group_to_software)
if src in id_to_software and tgt in id_to_tech:
add_link(id_to_software[src], id_to_tech[tgt], software_to_tech, tech_to_software)
if src in id_to_group and tgt in id_to_tech:
add_link(id_to_group[src], id_to_tech[tgt], group_to_tech, tech_to_group)
if src in id_to_group and tgt in id_to_software:
add_link(id_to_group[src], id_to_software[tgt], group_to_software, software_to_group) | [
"def",
"parse_relationships",
"(",
"relationships",
")",
":",
"# Iterate over each relationship",
"for",
"obj",
"in",
"relationships",
":",
"# Load the source and target STIX IDs",
"src",
"=",
"obj",
"[",
"'source_ref'",
"]",
"tgt",
"=",
"obj",
"[",
"'target_ref'",
"]... | https://github.com/mitre-attack/attack-scripts/blob/b94e05c0a29a6fdfc9701c721fcf03cdf9f7945b/scripts/techniques_data_sources_vis.py#L152-L176 | ||
maas/maas | db2f89970c640758a51247c59bf1ec6f60cf4ab5 | src/metadataserver/builtin_scripts/commissioning_scripts/bmc_config.py | python | BMCConfig.power_type | (self) | The power_type of the BMC. | The power_type of the BMC. | [
"The",
"power_type",
"of",
"the",
"BMC",
"."
] | def power_type(self):
"""The power_type of the BMC.""" | [
"def",
"power_type",
"(",
"self",
")",
":"
] | https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/metadataserver/builtin_scripts/commissioning_scripts/bmc_config.py#L107-L108 | ||
PaddlePaddle/PaddleSlim | f895aebe441b2bef79ecc434626d3cac4b3cbd09 | paddleslim/nas/darts/search_space/conv_bert/reader/cls.py | python | _truncate_seq_pair | (tokens_a, tokens_b, max_length) | Truncates a sequence pair in place to the maximum length. | Truncates a sequence pair in place to the maximum length. | [
"Truncates",
"a",
"sequence",
"pair",
"in",
"place",
"to",
"the",
"maximum",
"length",
"."
] | def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop() | [
"def",
"_truncate_seq_pair",
"(",
"tokens_a",
",",
"tokens_b",
",",
"max_length",
")",
":",
"# This is a simple heuristic which will always truncate the longer sequence",
"# one token at a time. This makes more sense than truncating an equal percent",
"# of tokens from each, since if one seq... | https://github.com/PaddlePaddle/PaddleSlim/blob/f895aebe441b2bef79ecc434626d3cac4b3cbd09/paddleslim/nas/darts/search_space/conv_bert/reader/cls.py#L233-L247 | ||
spatialaudio/python-sounddevice | a56cdb96c9c8e3d23b877bbcc7d26bd0cda231e0 | examples/play_long_file_raw.py | python | int_or_str | (text) | Helper function for argument parsing. | Helper function for argument parsing. | [
"Helper",
"function",
"for",
"argument",
"parsing",
"."
] | def int_or_str(text):
"""Helper function for argument parsing."""
try:
return int(text)
except ValueError:
return text | [
"def",
"int_or_str",
"(",
"text",
")",
":",
"try",
":",
"return",
"int",
"(",
"text",
")",
"except",
"ValueError",
":",
"return",
"text"
] | https://github.com/spatialaudio/python-sounddevice/blob/a56cdb96c9c8e3d23b877bbcc7d26bd0cda231e0/examples/play_long_file_raw.py#L16-L21 | ||
rembo10/headphones | b3199605be1ebc83a7a8feab6b1e99b64014187c | lib/yaml/scanner.py | python | Scanner.check_value | (self) | [] | def check_value(self):
# VALUE(flow context): ':'
if self.flow_level:
return True
# VALUE(block context): ':' (' '|'\n')
else:
return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029' | [
"def",
"check_value",
"(",
"self",
")",
":",
"# VALUE(flow context): ':'",
"if",
"self",
".",
"flow_level",
":",
"return",
"True",
"# VALUE(block context): ':' (' '|'\\n')",
"else",
":",
"return",
"self",
".",
"peek",
"(",
"1",
")",
"in",
"u'\\0 \\t\\r\\n\\x85\\u20... | https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/yaml/scanner.py#L722-L730 | ||||
gmate/gmate | 83312e64e0c115a9842500e4eb8617d3f5f4025b | plugins/gedit3/zencoding/zencoding/zencoding/html_matcher.py | python | save_match | (opening_tag=None, closing_tag=None, ix=0) | return last_match['start_ix'] != -1 and (last_match['start_ix'], last_match['end_ix']) or (None, None) | Save matched tag for later use and return found indexes
@type opening_tag: Tag
@type closing_tag: Tag
@type ix: int
@return list | Save matched tag for later use and return found indexes | [
"Save",
"matched",
"tag",
"for",
"later",
"use",
"and",
"return",
"found",
"indexes"
] | def save_match(opening_tag=None, closing_tag=None, ix=0):
"""
Save matched tag for later use and return found indexes
@type opening_tag: Tag
@type closing_tag: Tag
@type ix: int
@return list
"""
last_match['opening_tag'] = opening_tag;
last_match['closing_tag'] = closing_tag;
last_match['start_ix'], last_match['end_ix'] = make_range(opening_tag, closing_tag, ix)
return last_match['start_ix'] != -1 and (last_match['start_ix'], last_match['end_ix']) or (None, None) | [
"def",
"save_match",
"(",
"opening_tag",
"=",
"None",
",",
"closing_tag",
"=",
"None",
",",
"ix",
"=",
"0",
")",
":",
"last_match",
"[",
"'opening_tag'",
"]",
"=",
"opening_tag",
"last_match",
"[",
"'closing_tag'",
"]",
"=",
"closing_tag",
"last_match",
"[",... | https://github.com/gmate/gmate/blob/83312e64e0c115a9842500e4eb8617d3f5f4025b/plugins/gedit3/zencoding/zencoding/zencoding/html_matcher.py#L119-L132 | |
vyapp/vy | 4ba0d379e21744fd79a740e8aeaba3a0a779973c | vyapp/areavi.py | python | AreaVi.replace_ranges | (self, name, regex, data, exact=False, regexp=True,
nocase=False, elide=False, nolinestop=False) | It replaces all occurrences of regex in the ranges that are mapped to tag name. | [] | def replace_ranges(self, name, regex, data, exact=False, regexp=True,
nocase=False, elide=False, nolinestop=False):
"""
It replaces all occurrences of regex in the ranges that are mapped to tag name.
"""
while True:
map = self.tag_nextrange(name, '1.0', 'end')
if not map: break
self.tag_remove(name, *map)
self.replace_all(regex, data, map[0], map[1],
exact, regexp, nocase, elide, nolinestop) | [
"def",
"replace_ranges",
"(",
"self",
",",
"name",
",",
"regex",
",",
"data",
",",
"exact",
"=",
"False",
",",
"regexp",
"=",
"True",
",",
"nocase",
"=",
"False",
",",
"elide",
"=",
"False",
",",
"nolinestop",
"=",
"False",
")",
":",
"while",
"True",... | https://github.com/vyapp/vy/blob/4ba0d379e21744fd79a740e8aeaba3a0a779973c/vyapp/areavi.py#L500-L513 | |||
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/site-packages/pip-7.1.2-py3.3.egg/pip/_vendor/distlib/database.py | python | InstalledDistribution.shared_locations | (self) | return result | A dictionary of shared locations whose keys are in the set 'prefix',
'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'.
The corresponding value is the absolute path of that category for
this distribution, and takes into account any paths selected by the
user at installation time (e.g. via command-line arguments). In the
case of the 'namespace' key, this would be a list of absolute paths
for the roots of namespace packages in this distribution.
The first time this property is accessed, the relevant information is
read from the SHARED file in the .dist-info directory. | A dictionary of shared locations whose keys are in the set 'prefix',
'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'.
The corresponding value is the absolute path of that category for
this distribution, and takes into account any paths selected by the
user at installation time (e.g. via command-line arguments). In the
case of the 'namespace' key, this would be a list of absolute paths
for the roots of namespace packages in this distribution. | [
"A",
"dictionary",
"of",
"shared",
"locations",
"whose",
"keys",
"are",
"in",
"the",
"set",
"prefix",
"purelib",
"platlib",
"scripts",
"headers",
"data",
"and",
"namespace",
".",
"The",
"corresponding",
"value",
"is",
"the",
"absolute",
"path",
"of",
"that",
... | def shared_locations(self):
"""
A dictionary of shared locations whose keys are in the set 'prefix',
'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'.
The corresponding value is the absolute path of that category for
this distribution, and takes into account any paths selected by the
user at installation time (e.g. via command-line arguments). In the
case of the 'namespace' key, this would be a list of absolute paths
for the roots of namespace packages in this distribution.
The first time this property is accessed, the relevant information is
read from the SHARED file in the .dist-info directory.
"""
result = {}
shared_path = os.path.join(self.path, 'SHARED')
if os.path.isfile(shared_path):
with codecs.open(shared_path, 'r', encoding='utf-8') as f:
lines = f.read().splitlines()
for line in lines:
key, value = line.split('=', 1)
if key == 'namespace':
result.setdefault(key, []).append(value)
else:
result[key] = value
return result | [
"def",
"shared_locations",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"shared_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"'SHARED'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"shared_path",
")",
":",
"wi... | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/pip-7.1.2-py3.3.egg/pip/_vendor/distlib/database.py#L726-L750 | |
pycalphad/pycalphad | 631c41c3d041d4e8a47c57d0f25d078344b9da52 | pycalphad/core/light_dataset.py | python | LightDataset.__init__ | (self, data_vars=None, coords=None, attrs=None) | Parameters
----------
data_vars :
Dictionary of {Variable: (Dimensions, Values)}
coords :
Mapping of {Dimension: Values}
attrs :
Returns
-------
LightDataset
Notes
-----
Takes on same format as xarray.Dataset initializer | [] | def __init__(self, data_vars=None, coords=None, attrs=None):
"""
Parameters
----------
data_vars :
Dictionary of {Variable: (Dimensions, Values)}
coords :
Mapping of {Dimension: Values}
attrs :
Returns
-------
LightDataset
Notes
-----
Takes on same format as xarray.Dataset initializer
"""
self.data_vars = data_vars or dict()
self.coords = coords or dict()
self.attrs = attrs or dict()
for var, (coord, values) in data_vars.items():
setattr(self, var, values)
for coord, values in coords.items():
setattr(self, coord, values) | [
"def",
"__init__",
"(",
"self",
",",
"data_vars",
"=",
"None",
",",
"coords",
"=",
"None",
",",
"attrs",
"=",
"None",
")",
":",
"self",
".",
"data_vars",
"=",
"data_vars",
"or",
"dict",
"(",
")",
"self",
".",
"coords",
"=",
"coords",
"or",
"dict",
... | https://github.com/pycalphad/pycalphad/blob/631c41c3d041d4e8a47c57d0f25d078344b9da52/pycalphad/core/light_dataset.py#L30-L56 | |||
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/site-packages/ipython-4.0.0-py3.3.egg/IPython/core/formatters.py | python | BaseFormatter.pop | (self, typ, default=_raise_key_error) | return old | Pop a formatter for the given type.
Parameters
----------
typ : type or '__module__.__name__' string for a type
default : object
value to be returned if no formatter is registered for typ.
Returns
-------
obj : object
The last registered object for the type.
Raises
------
KeyError if the type is not registered and default is not specified. | Pop a formatter for the given type. | [
"Pop",
"a",
"formatter",
"for",
"the",
"given",
"type",
"."
] | def pop(self, typ, default=_raise_key_error):
"""Pop a formatter for the given type.
Parameters
----------
typ : type or '__module__.__name__' string for a type
default : object
value to be returned if no formatter is registered for typ.
Returns
-------
obj : object
The last registered object for the type.
Raises
------
KeyError if the type is not registered and default is not specified.
"""
if isinstance(typ, string_types):
typ_key = tuple(typ.rsplit('.',1))
if typ_key not in self.deferred_printers:
# We may have it cached in the type map. We will have to
# iterate over all of the types to check.
for cls in self.type_printers:
if _mod_name_key(cls) == typ_key:
old = self.type_printers.pop(cls)
break
else:
old = default
else:
old = self.deferred_printers.pop(typ_key)
else:
if typ in self.type_printers:
old = self.type_printers.pop(typ)
else:
old = self.deferred_printers.pop(_mod_name_key(typ), default)
if old is _raise_key_error:
raise KeyError("No registered value for {0!r}".format(typ))
return old | [
"def",
"pop",
"(",
"self",
",",
"typ",
",",
"default",
"=",
"_raise_key_error",
")",
":",
"if",
"isinstance",
"(",
"typ",
",",
"string_types",
")",
":",
"typ_key",
"=",
"tuple",
"(",
"typ",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
")",
"if",
"typ_... | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/ipython-4.0.0-py3.3.egg/IPython/core/formatters.py#L505-L544 | |
BillBillBillBill/Tickeys-linux | 2df31b8665004c58a5d4ab05277f245267d96364 | tickeys/kivy/core/text/__init__.py | python | LabelBase.register | (name, fn_regular, fn_italic=None, fn_bold=None,
fn_bolditalic=None) | Register an alias for a Font.
.. versionadded:: 1.1.0
If you're using a ttf directly, you might not be able to use the
bold/italic properties of
the ttf version. If the font is delivered in multiple files
(one regular, one italic and one bold), then you need to register these
files and use the alias instead.
All the fn_regular/fn_italic/fn_bold parameters are resolved with
:func:`kivy.resources.resource_find`. If fn_italic/fn_bold are None,
fn_regular will be used instead. | Register an alias for a Font. | [
"Register",
"an",
"alias",
"for",
"a",
"Font",
"."
] | def register(name, fn_regular, fn_italic=None, fn_bold=None,
fn_bolditalic=None):
'''Register an alias for a Font.
.. versionadded:: 1.1.0
If you're using a ttf directly, you might not be able to use the
bold/italic properties of
the ttf version. If the font is delivered in multiple files
(one regular, one italic and one bold), then you need to register these
files and use the alias instead.
All the fn_regular/fn_italic/fn_bold parameters are resolved with
:func:`kivy.resources.resource_find`. If fn_italic/fn_bold are None,
fn_regular will be used instead.
'''
fonts = []
for font_type in fn_regular, fn_italic, fn_bold, fn_bolditalic:
if font_type is not None:
font = resource_find(font_type)
if font is None:
raise IOError('File {0}s not found'.format(font_type))
else:
fonts.append(font)
else:
fonts.append(fonts[-1]) # add regular font to list again
LabelBase._fonts[name] = tuple(fonts) | [
"def",
"register",
"(",
"name",
",",
"fn_regular",
",",
"fn_italic",
"=",
"None",
",",
"fn_bold",
"=",
"None",
",",
"fn_bolditalic",
"=",
"None",
")",
":",
"fonts",
"=",
"[",
"]",
"for",
"font_type",
"in",
"fn_regular",
",",
"fn_italic",
",",
"fn_bold",
... | https://github.com/BillBillBillBill/Tickeys-linux/blob/2df31b8665004c58a5d4ab05277f245267d96364/tickeys/kivy/core/text/__init__.py#L195-L225 | ||
iocast/featureserver | 2828532294fe232f1ddf358cfbd2cc81af102e56 | vectorformats/lib/shapefile.py | python | Writer.__shpFileLength | (self) | return size | Calculates the file length of the shp file. | Calculates the file length of the shp file. | [
"Calculates",
"the",
"file",
"length",
"of",
"the",
"shp",
"file",
"."
] | def __shpFileLength(self):
"""Calculates the file length of the shp file."""
# Start with header length
size = 100
# Calculate size of all shapes
for s in self._shapes:
# Add in record header and shape type fields
size += 12
# nParts and nPoints do not apply to all shapes
#if self.shapeType not in (0,1):
# nParts = len(s.parts)
# nPoints = len(s.points)
if hasattr(s,'parts'):
nParts = len(s.parts)
if hasattr(s,'points'):
nPoints = len(s.points)
# All shape types capable of having a bounding box
if self.shapeType in (3,5,8,13,15,18,23,25,28,31):
size += 32
# Shape types with parts
if self.shapeType in (3,5,13,15,23,25,31):
# Parts count
size += 4
# Parts index array
size += nParts * 4
# Shape types with points
if self.shapeType in (3,5,8,13,15,23,25,31):
# Points count
size += 4
# Points array
size += 16 * nPoints
# Calc size of part types for Multipatch (31)
if self.shapeType == 31:
size += nParts * 4
# Calc z extremes and values
if self.shapeType in (13,15,18,31):
# z extremes
size += 16
# z array
size += 8 * nPoints
# Calc m extremes and values
if self.shapeType in (23,25,31):
# m extremes
size += 16
# m array
size += 8 * nPoints
# Calc a single point
if self.shapeType in (1,11,21):
size += 16
# Calc a single Z value
if self.shapeType == 11:
size += 8
# Calc a single M value
if self.shapeType in (11,21):
size += 8
# Calculate size as 16-bit words
size //= 2
return size | [
"def",
"__shpFileLength",
"(",
"self",
")",
":",
"# Start with header length",
"size",
"=",
"100",
"# Calculate size of all shapes",
"for",
"s",
"in",
"self",
".",
"_shapes",
":",
"# Add in record header and shape type fields",
"size",
"+=",
"12",
"# nParts and nPoints do... | https://github.com/iocast/featureserver/blob/2828532294fe232f1ddf358cfbd2cc81af102e56/vectorformats/lib/shapefile.py#L460-L517 | |
researchmm/tasn | 5dba8ccc096cedc63913730eeea14a9647911129 | tasn-mxnet/example/ssd/dataset/pascal_voc.py | python | PascalVoc.image_path_from_index | (self, index) | return image_file | given image index, find out full path
Parameters:
----------
index: int
index of a specific image
Returns:
----------
full path of this image | given image index, find out full path | [
"given",
"image",
"index",
"find",
"out",
"full",
"path"
] | def image_path_from_index(self, index):
"""
given image index, find out full path
Parameters:
----------
index: int
index of a specific image
Returns:
----------
full path of this image
"""
assert self.image_set_index is not None, "Dataset not initialized"
name = self.image_set_index[index]
image_file = os.path.join(self.data_path, 'JPEGImages', name + self.extension)
assert os.path.exists(image_file), 'Path does not exist: {}'.format(image_file)
return image_file | [
"def",
"image_path_from_index",
"(",
"self",
",",
"index",
")",
":",
"assert",
"self",
".",
"image_set_index",
"is",
"not",
"None",
",",
"\"Dataset not initialized\"",
"name",
"=",
"self",
".",
"image_set_index",
"[",
"index",
"]",
"image_file",
"=",
"os",
"."... | https://github.com/researchmm/tasn/blob/5dba8ccc096cedc63913730eeea14a9647911129/tasn-mxnet/example/ssd/dataset/pascal_voc.py#L100-L116 | |
ganeti/ganeti | d340a9ddd12f501bef57da421b5f9b969a4ba905 | lib/utils/io.py | python | TimestampForFilename | () | return time.strftime("%Y-%m-%d_%H_%M_%S") | Returns the current time formatted for filenames.
The format doesn't contain colons as some shells and applications treat them
as separators. Uses the local timezone. | Returns the current time formatted for filenames. | [
"Returns",
"the",
"current",
"time",
"formatted",
"for",
"filenames",
"."
] | def TimestampForFilename():
"""Returns the current time formatted for filenames.
The format doesn't contain colons as some shells and applications treat them
as separators. Uses the local timezone.
"""
return time.strftime("%Y-%m-%d_%H_%M_%S") | [
"def",
"TimestampForFilename",
"(",
")",
":",
"return",
"time",
".",
"strftime",
"(",
"\"%Y-%m-%d_%H_%M_%S\"",
")"
] | https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/utils/io.py#L539-L546 | |
biolab/orange3 | 41685e1c7b1d1babe680113685a2d44bcc9fec0b | Orange/widgets/visualize/owdistributions.py | python | DistributionBarItem.x0 | (self) | return self.x | [] | def x0(self):
return self.x | [
"def",
"x0",
"(",
"self",
")",
":",
"return",
"self",
".",
"x"
] | https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/visualize/owdistributions.py#L154-L155 | |||
googleads/google-ads-python | 2a1d6062221f6aad1992a6bcca0e7e4a93d2db86 | google/ads/googleads/v7/services/services/google_ads_service/client.py | python | GoogleAdsServiceClient.parse_feed_placeholder_view_path | (path: str) | return m.groupdict() if m else {} | Parse a feed_placeholder_view path into its component segments. | Parse a feed_placeholder_view path into its component segments. | [
"Parse",
"a",
"feed_placeholder_view",
"path",
"into",
"its",
"component",
"segments",
"."
] | def parse_feed_placeholder_view_path(path: str) -> Dict[str, str]:
"""Parse a feed_placeholder_view path into its component segments."""
m = re.match(
r"^customers/(?P<customer_id>.+?)/feedPlaceholderViews/(?P<placeholder_type>.+?)$",
path,
)
return m.groupdict() if m else {} | [
"def",
"parse_feed_placeholder_view_path",
"(",
"path",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r\"^customers/(?P<customer_id>.+?)/feedPlaceholderViews/(?P<placeholder_type>.+?)$\"",
",",
"path",
",",
")",... | https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/google_ads_service/client.py#L1618-L1624 | |
zhanghang1989/PyTorch-Encoding | 331ecdd5306104614cb414b16fbcd9d1a8d40e1e | encoding/models/sseg/deeplab.py | python | get_deeplab_resnest50_ade | (pretrained=False, root='~/.encoding/models', **kwargs) | return get_deeplab('ade20k', 'resnest50', pretrained, aux=True, root=root, **kwargs) | r"""DeepLabV3 model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping the model parameters.
Examples
--------
>>> model = get_deeplab_resnet50_ade(pretrained=True)
>>> print(model) | r"""DeepLabV3 model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_ | [
"r",
"DeepLabV3",
"model",
"from",
"the",
"paper",
"Context",
"Encoding",
"for",
"Semantic",
"Segmentation",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1803",
".",
"08904",
".",
"pdf",
">",
"_"
] | def get_deeplab_resnest50_ade(pretrained=False, root='~/.encoding/models', **kwargs):
r"""DeepLabV3 model from the paper `"Context Encoding for Semantic Segmentation"
<https://arxiv.org/pdf/1803.08904.pdf>`_
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.encoding/models'
Location for keeping the model parameters.
Examples
--------
>>> model = get_deeplab_resnet50_ade(pretrained=True)
>>> print(model)
"""
return get_deeplab('ade20k', 'resnest50', pretrained, aux=True, root=root, **kwargs) | [
"def",
"get_deeplab_resnest50_ade",
"(",
"pretrained",
"=",
"False",
",",
"root",
"=",
"'~/.encoding/models'",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"get_deeplab",
"(",
"'ade20k'",
",",
"'resnest50'",
",",
"pretrained",
",",
"aux",
"=",
"True",
",",
"... | https://github.com/zhanghang1989/PyTorch-Encoding/blob/331ecdd5306104614cb414b16fbcd9d1a8d40e1e/encoding/models/sseg/deeplab.py#L159-L176 | |
Qiskit/qiskit-terra | b66030e3b9192efdd3eb95cf25c6545fe0a13da4 | qiskit/pulse/schedule.py | python | ScheduleBlock.replace | (
self,
old: BlockComponent,
new: BlockComponent,
inplace: bool = True,
) | Return a ``ScheduleBlock`` with the ``old`` component replaced with a ``new``
component.
Args:
old: Schedule block component to replace.
new: Schedule block component to replace with.
inplace: Replace instruction by mutably modifying this ``ScheduleBlock``.
Returns:
The modified schedule block with ``old`` replaced by ``new``. | Return a ``ScheduleBlock`` with the ``old`` component replaced with a ``new``
component. | [
"Return",
"a",
"ScheduleBlock",
"with",
"the",
"old",
"component",
"replaced",
"with",
"a",
"new",
"component",
"."
] | def replace(
self,
old: BlockComponent,
new: BlockComponent,
inplace: bool = True,
) -> "ScheduleBlock":
"""Return a ``ScheduleBlock`` with the ``old`` component replaced with a ``new``
component.
Args:
old: Schedule block component to replace.
new: Schedule block component to replace with.
inplace: Replace instruction by mutably modifying this ``ScheduleBlock``.
Returns:
The modified schedule block with ``old`` replaced by ``new``.
"""
from qiskit.pulse.parameter_manager import ParameterManager
new_blocks = []
new_parameters = ParameterManager()
for block in self.blocks:
if block == old:
new_blocks.append(new)
new_parameters.update_parameter_table(new)
else:
if isinstance(block, ScheduleBlock):
new_blocks.append(block.replace(old, new, inplace))
else:
new_blocks.append(block)
new_parameters.update_parameter_table(block)
if inplace:
self._blocks = new_blocks
self._parameter_manager = new_parameters
return self
else:
ret_block = copy.deepcopy(self)
ret_block._blocks = new_blocks
ret_block._parameter_manager = new_parameters
return ret_block | [
"def",
"replace",
"(",
"self",
",",
"old",
":",
"BlockComponent",
",",
"new",
":",
"BlockComponent",
",",
"inplace",
":",
"bool",
"=",
"True",
",",
")",
"->",
"\"ScheduleBlock\"",
":",
"from",
"qiskit",
".",
"pulse",
".",
"parameter_manager",
"import",
"Pa... | https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/pulse/schedule.py#L1173-L1214 | ||
plone/Products.CMFPlone | 83137764e3e7e4fe60d03c36dfc6ba9c7c543324 | Products/CMFPlone/relationhelper.py | python | rebuild_intids | () | Create new intids | Create new intids | [
"Create",
"new",
"intids"
] | def rebuild_intids():
""" Create new intids
"""
def add_to_intids(obj, path):
if IContentish.providedBy(obj):
logger.info(f'Added {obj} at {path} to intid')
addIntIdSubscriber(obj, None)
portal = getSite()
portal.ZopeFindAndApply(portal,
search_sub=True,
apply_func=add_to_intids) | [
"def",
"rebuild_intids",
"(",
")",
":",
"def",
"add_to_intids",
"(",
"obj",
",",
"path",
")",
":",
"if",
"IContentish",
".",
"providedBy",
"(",
"obj",
")",
":",
"logger",
".",
"info",
"(",
"f'Added {obj} at {path} to intid'",
")",
"addIntIdSubscriber",
"(",
... | https://github.com/plone/Products.CMFPlone/blob/83137764e3e7e4fe60d03c36dfc6ba9c7c543324/Products/CMFPlone/relationhelper.py#L311-L321 | ||
CvvT/dumpDex | 92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1 | python/idaapi.py | python | get_struc_first_offset | (*args) | return _idaapi.get_struc_first_offset(*args) | get_struc_first_offset(sptr) -> ea_t | get_struc_first_offset(sptr) -> ea_t | [
"get_struc_first_offset",
"(",
"sptr",
")",
"-",
">",
"ea_t"
] | def get_struc_first_offset(*args):
"""
get_struc_first_offset(sptr) -> ea_t
"""
return _idaapi.get_struc_first_offset(*args) | [
"def",
"get_struc_first_offset",
"(",
"*",
"args",
")",
":",
"return",
"_idaapi",
".",
"get_struc_first_offset",
"(",
"*",
"args",
")"
] | https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L48763-L48767 | |
jython/jython3 | def4f8ec47cb7a9c799ea4c745f12badf92c5769 | lib-python/3.5.1/multiprocessing/util.py | python | _run_finalizers | (minpriority=None) | Run all finalizers whose exit priority is not None and at least minpriority
Finalizers with highest priority are called first; finalizers with
the same priority will be called in reverse order of creation. | Run all finalizers whose exit priority is not None and at least minpriority | [
"Run",
"all",
"finalizers",
"whose",
"exit",
"priority",
"is",
"not",
"None",
"and",
"at",
"least",
"minpriority"
] | def _run_finalizers(minpriority=None):
'''
Run all finalizers whose exit priority is not None and at least minpriority
Finalizers with highest priority are called first; finalizers with
the same priority will be called in reverse order of creation.
'''
if _finalizer_registry is None:
# This function may be called after this module's globals are
# destroyed. See the _exit_function function in this module for more
# notes.
return
if minpriority is None:
f = lambda p : p[0][0] is not None
else:
f = lambda p : p[0][0] is not None and p[0][0] >= minpriority
items = [x for x in list(_finalizer_registry.items()) if f(x)]
items.sort(reverse=True)
for key, finalizer in items:
sub_debug('calling %s', finalizer)
try:
finalizer()
except Exception:
import traceback
traceback.print_exc()
if minpriority is None:
_finalizer_registry.clear() | [
"def",
"_run_finalizers",
"(",
"minpriority",
"=",
"None",
")",
":",
"if",
"_finalizer_registry",
"is",
"None",
":",
"# This function may be called after this module's globals are",
"# destroyed. See the _exit_function function in this module for more",
"# notes.",
"return",
"if",... | https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/multiprocessing/util.py#L229-L259 | ||
hakril/PythonForWindows | 61e027a678d5b87aa64fcf8a37a6661a86236589 | samples/find_value.py | python | search_name | (target) | [] | def search_name(target):
print("== Functions ==")
search_name_in_function(target)
print("== Enums ==")
search_name_in_enum(target)
print("== Structs ==")
search_name_in_struct(target)
print("== Windef ==")
search_name_in_windef(target)
print("== Winerror ==")
search_name_in_winerror(target)
print("== Interfaces ==")
search_name_in_interface(target) | [
"def",
"search_name",
"(",
"target",
")",
":",
"print",
"(",
"\"== Functions ==\"",
")",
"search_name_in_function",
"(",
"target",
")",
"print",
"(",
"\"== Enums ==\"",
")",
"search_name_in_enum",
"(",
"target",
")",
"print",
"(",
"\"== Structs ==\"",
")",
"search... | https://github.com/hakril/PythonForWindows/blob/61e027a678d5b87aa64fcf8a37a6661a86236589/samples/find_value.py#L54-L66 | ||||
archlinux/archweb | 19e5da892ef2af7bf045576f8114c256589e16c4 | releng/views.py | python | releases_json | (request) | return response | [] | def releases_json(request):
releases = Release.objects.all()
try:
latest_version = Release.objects.filter(available=True).values_list(
'version', flat=True).latest()
except Release.DoesNotExist:
latest_version = None
data = {
'version': 1,
'releases': list(releases),
'latest_version': latest_version,
}
to_json = json.dumps(data, ensure_ascii=False, cls=ReleaseJSONEncoder)
response = HttpResponse(to_json, content_type='application/json')
return response | [
"def",
"releases_json",
"(",
"request",
")",
":",
"releases",
"=",
"Release",
".",
"objects",
".",
"all",
"(",
")",
"try",
":",
"latest_version",
"=",
"Release",
".",
"objects",
".",
"filter",
"(",
"available",
"=",
"True",
")",
".",
"values_list",
"(",
... | https://github.com/archlinux/archweb/blob/19e5da892ef2af7bf045576f8114c256589e16c4/releng/views.py#L58-L73 | |||
grow/grow | 97fc21730b6a674d5d33948d94968e79447ce433 | grow/cache/podcache.py | python | Error.__init__ | (self, message) | [] | def __init__(self, message):
super(Error, self).__init__(message)
self.message = message | [
"def",
"__init__",
"(",
"self",
",",
"message",
")",
":",
"super",
"(",
"Error",
",",
"self",
")",
".",
"__init__",
"(",
"message",
")",
"self",
".",
"message",
"=",
"message"
] | https://github.com/grow/grow/blob/97fc21730b6a674d5d33948d94968e79447ce433/grow/cache/podcache.py#L22-L24 | ||||
thu-coai/CrossWOZ | 265e97379b34221f5949beb46f3eec0e2dc943c4 | convlab2/dst/trade/crosswoz/utils/utils_temp.py | python | Dataset.preprocess | (self, sequence, word2idx) | return story | Converts words to idx. | Converts words to idx. | [
"Converts",
"words",
"to",
"idx",
"."
] | def preprocess(self, sequence, word2idx):
"""Converts words to idx."""
story = []
for i, word_triple in enumerate(sequence):
story.append([])
for ii, word in enumerate(word_triple):
temp = word2idx[word] if word in word2idx else UNK_token
story[i].append(temp)
try:
story = torch.LongTensor(story)
except:
print("Cannot change to tensor...")
exit(1)
return story | [
"def",
"preprocess",
"(",
"self",
",",
"sequence",
",",
"word2idx",
")",
":",
"story",
"=",
"[",
"]",
"for",
"i",
",",
"word_triple",
"in",
"enumerate",
"(",
"sequence",
")",
":",
"story",
".",
"append",
"(",
"[",
"]",
")",
"for",
"ii",
",",
"word"... | https://github.com/thu-coai/CrossWOZ/blob/265e97379b34221f5949beb46f3eec0e2dc943c4/convlab2/dst/trade/crosswoz/utils/utils_temp.py#L90-L103 | |
SheffieldML/GPy | bb1bc5088671f9316bc92a46d356734e34c2d5c0 | GPy/util/diag.py | python | divide | (A, b, offset=0) | return _diag_ufunc(A, b, offset, np.divide) | Divide the view of A by b in place (!).
Returns modified A
Broadcasting is allowed, thus b can be scalar.
if offset is not zero, make sure b is of right shape!
:param ndarray A: 2 dimensional array
:param ndarray-like b: either one dimensional or scalar
:param int offset: same as in view.
:rtype: view of A, which is adjusted inplace | Divide the view of A by b in place (!).
Returns modified A
Broadcasting is allowed, thus b can be scalar. | [
"Divide",
"the",
"view",
"of",
"A",
"by",
"b",
"in",
"place",
"(",
"!",
")",
".",
"Returns",
"modified",
"A",
"Broadcasting",
"is",
"allowed",
"thus",
"b",
"can",
"be",
"scalar",
"."
] | def divide(A, b, offset=0):
"""
Divide the view of A by b in place (!).
Returns modified A
Broadcasting is allowed, thus b can be scalar.
if offset is not zero, make sure b is of right shape!
:param ndarray A: 2 dimensional array
:param ndarray-like b: either one dimensional or scalar
:param int offset: same as in view.
:rtype: view of A, which is adjusted inplace
"""
return _diag_ufunc(A, b, offset, np.divide) | [
"def",
"divide",
"(",
"A",
",",
"b",
",",
"offset",
"=",
"0",
")",
":",
"return",
"_diag_ufunc",
"(",
"A",
",",
"b",
",",
"offset",
",",
"np",
".",
"divide",
")"
] | https://github.com/SheffieldML/GPy/blob/bb1bc5088671f9316bc92a46d356734e34c2d5c0/GPy/util/diag.py#L70-L83 | |
CGCookie/retopoflow | 3d8b3a47d1d661f99ab0aeb21d31370bf15de35e | retopoflow/rf/rf_spaces.py | python | RetopoFlow_Spaces.Point2D_to_Origin | (self, xy:Point2D) | return Point(region_2d_to_origin_3d(self.actions.region, self.actions.r3d, xy)) | [] | def Point2D_to_Origin(self, xy:Point2D):
if xy is None: return None
return Point(region_2d_to_origin_3d(self.actions.region, self.actions.r3d, xy)) | [
"def",
"Point2D_to_Origin",
"(",
"self",
",",
"xy",
":",
"Point2D",
")",
":",
"if",
"xy",
"is",
"None",
":",
"return",
"None",
"return",
"Point",
"(",
"region_2d_to_origin_3d",
"(",
"self",
".",
"actions",
".",
"region",
",",
"self",
".",
"actions",
".",... | https://github.com/CGCookie/retopoflow/blob/3d8b3a47d1d661f99ab0aeb21d31370bf15de35e/retopoflow/rf/rf_spaces.py#L65-L67 | |||
makerbot/ReplicatorG | d6f2b07785a5a5f1e172fb87cb4303b17c575d5d | skein_engines/skeinforge-47/skeinforge_application/skeinforge_plugins/craft_plugins/tower.py | python | TowerRepository.__init__ | (self) | Set the default settings, execute title & settings fileName. | Set the default settings, execute title & settings fileName. | [
"Set",
"the",
"default",
"settings",
"execute",
"title",
"&",
"settings",
"fileName",
"."
] | def __init__(self):
"Set the default settings, execute title & settings fileName."
skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.tower.html', self )
self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Tower', self, '')
self.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Tower')
self.activateTower = settings.BooleanSetting().getFromValue('Activate Tower', self, False )
self.extruderPossibleCollisionConeAngle = settings.FloatSpin().getFromValue( 40.0, 'Extruder Possible Collision Cone Angle (degrees):', self, 80.0, 60.0 )
self.maximumTowerHeight = settings.IntSpin().getFromValue( 2, 'Maximum Tower Height (layers):', self, 10, 5 )
self.towerStartLayer = settings.IntSpin().getFromValue( 1, 'Tower Start Layer (integer):', self, 5, 1 )
self.executeTitle = 'Tower' | [
"def",
"__init__",
"(",
"self",
")",
":",
"skeinforge_profile",
".",
"addListsToCraftTypeRepository",
"(",
"'skeinforge_application.skeinforge_plugins.craft_plugins.tower.html'",
",",
"self",
")",
"self",
".",
"fileNameInput",
"=",
"settings",
".",
"FileNameInput",
"(",
"... | https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/skeinforge_application/skeinforge_plugins/craft_plugins/tower.py#L122-L131 | ||
UniShared/videonotes | 803cdd97b90823fb17f50dd55999aa7d1fec6c3a | lib/oauth2client/xsrfutil.py | python | validate_token | (key, token, user_id, action_id="", current_time=None) | return True | Validates that the given token authorizes the user for the action.
Tokens are invalid if the time of issue is too old or if the token
does not match what generateToken outputs (i.e. the token was forged).
Args:
key: secret key to use.
token: a string of the token generated by generateToken.
user_id: the user ID of the authenticated user.
action_id: a string identifier of the action they requested
authorization for.
Returns:
A boolean - True if the user is authorized for the action, False
otherwise. | Validates that the given token authorizes the user for the action. | [
"Validates",
"that",
"the",
"given",
"token",
"authorizes",
"the",
"user",
"for",
"the",
"action",
"."
] | def validate_token(key, token, user_id, action_id="", current_time=None):
"""Validates that the given token authorizes the user for the action.
Tokens are invalid if the time of issue is too old or if the token
does not match what generateToken outputs (i.e. the token was forged).
Args:
key: secret key to use.
token: a string of the token generated by generateToken.
user_id: the user ID of the authenticated user.
action_id: a string identifier of the action they requested
authorization for.
Returns:
A boolean - True if the user is authorized for the action, False
otherwise.
"""
if not token:
return False
try:
decoded = base64.urlsafe_b64decode(str(token))
token_time = long(decoded.split(DELIMITER)[-1])
except (TypeError, ValueError):
return False
if current_time is None:
current_time = time.time()
# If the token is too old it's not valid.
if current_time - token_time > DEFAULT_TIMEOUT_SECS:
return False
# The given token should match the generated one with the same time.
expected_token = generate_token(key, user_id, action_id=action_id,
when=token_time)
if len(token) != len(expected_token):
return False
# Perform constant time comparison to avoid timing attacks
different = 0
for x, y in zip(token, expected_token):
different |= ord(x) ^ ord(y)
if different:
return False
return True | [
"def",
"validate_token",
"(",
"key",
",",
"token",
",",
"user_id",
",",
"action_id",
"=",
"\"\"",
",",
"current_time",
"=",
"None",
")",
":",
"if",
"not",
"token",
":",
"return",
"False",
"try",
":",
"decoded",
"=",
"base64",
".",
"urlsafe_b64decode",
"(... | https://github.com/UniShared/videonotes/blob/803cdd97b90823fb17f50dd55999aa7d1fec6c3a/lib/oauth2client/xsrfutil.py#L70-L113 | |
boston-dynamics/spot-sdk | 5ffa12e6943a47323c7279d86e30346868755f52 | python/bosdyn-mission/src/bosdyn/mission/client.py | python | MissionClient.answer_question | (self, question_id, code, **kwargs) | return self.call(self._stub.AnswerQuestion, req, None, _answer_question_error_from_response,
**kwargs) | Specify an answer to the question asked by the mission.
Args:
question_id (int): Id of the question to answer.
code (int): Answer code.
Raises:
RpcError: Problem communicating with the robot.
InvalidQuestionId: question_id was not a valid id.
InvalidAnswerCode: code was not valid for the question.
QuestionAlreadyAnswered: The question for question_id was already answered. | Specify an answer to the question asked by the mission.
Args:
question_id (int): Id of the question to answer.
code (int): Answer code. | [
"Specify",
"an",
"answer",
"to",
"the",
"question",
"asked",
"by",
"the",
"mission",
".",
"Args",
":",
"question_id",
"(",
"int",
")",
":",
"Id",
"of",
"the",
"question",
"to",
"answer",
".",
"code",
"(",
"int",
")",
":",
"Answer",
"code",
"."
] | def answer_question(self, question_id, code, **kwargs):
"""Specify an answer to the question asked by the mission.
Args:
question_id (int): Id of the question to answer.
code (int): Answer code.
Raises:
RpcError: Problem communicating with the robot.
InvalidQuestionId: question_id was not a valid id.
InvalidAnswerCode: code was not valid for the question.
QuestionAlreadyAnswered: The question for question_id was already answered.
"""
req = self._answer_question_request(question_id, code)
return self.call(self._stub.AnswerQuestion, req, None, _answer_question_error_from_response,
**kwargs) | [
"def",
"answer_question",
"(",
"self",
",",
"question_id",
",",
"code",
",",
"*",
"*",
"kwargs",
")",
":",
"req",
"=",
"self",
".",
"_answer_question_request",
"(",
"question_id",
",",
"code",
")",
"return",
"self",
".",
"call",
"(",
"self",
".",
"_stub"... | https://github.com/boston-dynamics/spot-sdk/blob/5ffa12e6943a47323c7279d86e30346868755f52/python/bosdyn-mission/src/bosdyn/mission/client.py#L105-L119 | |
spack/spack | 675210bd8bd1c5d32ad1cc83d898fb43b569ed74 | lib/spack/external/attr/_make.py | python | _get_annotations | (cls) | return {} | Get annotations for *cls*. | Get annotations for *cls*. | [
"Get",
"annotations",
"for",
"*",
"cls",
"*",
"."
] | def _get_annotations(cls):
"""
Get annotations for *cls*.
"""
if _has_own_attribute(cls, "__annotations__"):
return cls.__annotations__
return {} | [
"def",
"_get_annotations",
"(",
"cls",
")",
":",
"if",
"_has_own_attribute",
"(",
"cls",
",",
"\"__annotations__\"",
")",
":",
"return",
"cls",
".",
"__annotations__",
"return",
"{",
"}"
] | https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/external/attr/_make.py#L421-L428 | |
idanr1986/cuckoo-droid | 1350274639473d3d2b0ac740cae133ca53ab7444 | analyzer/android/lib/api/androguard/dvm.py | python | FieldIdItem.get_type | (self) | return self.type_idx_value | Return the type of the field
:rtype: string | Return the type of the field | [
"Return",
"the",
"type",
"of",
"the",
"field"
] | def get_type(self) :
"""
Return the type of the field
:rtype: string
"""
return self.type_idx_value | [
"def",
"get_type",
"(",
"self",
")",
":",
"return",
"self",
".",
"type_idx_value"
] | https://github.com/idanr1986/cuckoo-droid/blob/1350274639473d3d2b0ac740cae133ca53ab7444/analyzer/android/lib/api/androguard/dvm.py#L2163-L2169 | |
jgagneastro/coffeegrindsize | 22661ebd21831dba4cf32bfc6ba59fe3d49f879c | App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/backends/backend_wxagg.py | python | FigureCanvasWxAgg.draw | (self, drawDC=None) | Render the figure using agg. | Render the figure using agg. | [
"Render",
"the",
"figure",
"using",
"agg",
"."
] | def draw(self, drawDC=None):
"""
Render the figure using agg.
"""
FigureCanvasAgg.draw(self)
self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None)
self._isDrawn = True
self.gui_repaint(drawDC=drawDC, origin='WXAgg') | [
"def",
"draw",
"(",
"self",
",",
"drawDC",
"=",
"None",
")",
":",
"FigureCanvasAgg",
".",
"draw",
"(",
"self",
")",
"self",
".",
"bitmap",
"=",
"_convert_agg_to_wx_bitmap",
"(",
"self",
".",
"get_renderer",
"(",
")",
",",
"None",
")",
"self",
".",
"_is... | https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/backends/backend_wxagg.py#L25-L33 | ||
datacenter/acitoolkit | 629b84887dd0f0183b81efc8adb16817f985541a | acitoolkit/acisession.py | python | Subscriber._send_subscription | (self, url, only_new=False) | return resp | Send the subscription for the specified URL.
:param url: URL string to issue the subscription | Send the subscription for the specified URL. | [
"Send",
"the",
"subscription",
"for",
"the",
"specified",
"URL",
"."
] | def _send_subscription(self, url, only_new=False):
"""
Send the subscription for the specified URL.
:param url: URL string to issue the subscription
"""
try:
resp = self._apic.get(url)
except ConnectionError:
self._subscriptions[url] = None
log.error('Could not send subscription to APIC for url %s', url)
resp = requests.Response()
resp.status_code = 404
resp._content = '{"error": "Could not send subscription to APIC"}'
return resp
if not resp.ok:
self._subscriptions[url] = None
log.error('Could not send subscription to APIC for url %s', url)
resp = requests.Response()
resp.status_code = 404
resp._content = '{"error": "Could not send subscription to APIC"}'
return resp
resp_data = json.loads(resp.text)
if 'subscriptionId' not in resp_data:
log.error('Did not receive proper subscription response from APIC for url %s response: %s',
url, resp_data)
resp = requests.Response()
resp.status_code = 404
resp._content = '{"error": "Could not send subscription to APIC"}'
return resp
subscription_id = resp_data['subscriptionId']
self._subscriptions[url] = subscription_id
if not only_new:
while len(resp_data['imdata']):
event = {"totalCount": "1",
"subscriptionId": [resp_data['subscriptionId']],
"imdata": [resp_data["imdata"][0]]}
self._event_q.put(json.dumps(event))
resp_data["imdata"].remove(resp_data["imdata"][0])
return resp | [
"def",
"_send_subscription",
"(",
"self",
",",
"url",
",",
"only_new",
"=",
"False",
")",
":",
"try",
":",
"resp",
"=",
"self",
".",
"_apic",
".",
"get",
"(",
"url",
")",
"except",
"ConnectionError",
":",
"self",
".",
"_subscriptions",
"[",
"url",
"]",... | https://github.com/datacenter/acitoolkit/blob/629b84887dd0f0183b81efc8adb16817f985541a/acitoolkit/acisession.py#L194-L233 | |
ganeti/ganeti | d340a9ddd12f501bef57da421b5f9b969a4ba905 | lib/confd/client.py | python | ConfdClient.ReceiveReply | (self, timeout=1) | return self._socket.process_next_packet(timeout=timeout) | Receive one reply.
@type timeout: float
@param timeout: how long to wait for the reply
@rtype: boolean
@return: True if some data has been handled, False otherwise | Receive one reply. | [
"Receive",
"one",
"reply",
"."
] | def ReceiveReply(self, timeout=1):
"""Receive one reply.
@type timeout: float
@param timeout: how long to wait for the reply
@rtype: boolean
@return: True if some data has been handled, False otherwise
"""
return self._socket.process_next_packet(timeout=timeout) | [
"def",
"ReceiveReply",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"return",
"self",
".",
"_socket",
".",
"process_next_packet",
"(",
"timeout",
"=",
"timeout",
")"
] | https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/confd/client.py#L311-L320 | |
sahana/eden | 1696fa50e90ce967df69f66b571af45356cc18da | controllers/org.py | python | service | () | return s3_rest_controller() | RESTful CRUD controller | RESTful CRUD controller | [
"RESTful",
"CRUD",
"controller"
] | def service():
""" RESTful CRUD controller """
return s3_rest_controller() | [
"def",
"service",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
")"
] | https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/controllers/org.py#L435-L438 | |
plotly/plotly.py | cfad7862594b35965c0e000813bd7805e8494a5b | packages/python/plotly/plotly/graph_objs/scattergl/marker/_colorbar.py | python | ColorBar.tickfont | (self) | return self["tickfont"] | Sets the color bar's tick label font
The 'tickfont' property is an instance of Tickfont
that may be specified as:
- An instance of :class:`plotly.graph_objs.scattergl.marker.colorbar.Tickfont`
- A dict of string/value properties that will be passed
to the Tickfont constructor
Supported dict properties:
color
family
HTML font family - the typeface that will be
applied by the web browser. The web browser
will only be able to apply a font if it is
available on the system which it operates.
Provide multiple font families, separated by
commas, to indicate the preference in which to
apply fonts if they aren't available on the
system. The Chart Studio Cloud (at
https://chart-studio.plotly.com or on-premise)
generates images on a server, where only a
select number of fonts are installed and
supported. These include "Arial", "Balto",
"Courier New", "Droid Sans",, "Droid Serif",
"Droid Sans Mono", "Gravitas One", "Old
Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
size
Returns
-------
plotly.graph_objs.scattergl.marker.colorbar.Tickfont | Sets the color bar's tick label font
The 'tickfont' property is an instance of Tickfont
that may be specified as:
- An instance of :class:`plotly.graph_objs.scattergl.marker.colorbar.Tickfont`
- A dict of string/value properties that will be passed
to the Tickfont constructor
Supported dict properties:
color
family
HTML font family - the typeface that will be
applied by the web browser. The web browser
will only be able to apply a font if it is
available on the system which it operates.
Provide multiple font families, separated by
commas, to indicate the preference in which to
apply fonts if they aren't available on the
system. The Chart Studio Cloud (at
https://chart-studio.plotly.com or on-premise)
generates images on a server, where only a
select number of fonts are installed and
supported. These include "Arial", "Balto",
"Courier New", "Droid Sans",, "Droid Serif",
"Droid Sans Mono", "Gravitas One", "Old
Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
size | [
"Sets",
"the",
"color",
"bar",
"s",
"tick",
"label",
"font",
"The",
"tickfont",
"property",
"is",
"an",
"instance",
"of",
"Tickfont",
"that",
"may",
"be",
"specified",
"as",
":",
"-",
"An",
"instance",
"of",
":",
"class",
":",
"plotly",
".",
"graph_objs"... | def tickfont(self):
"""
Sets the color bar's tick label font
The 'tickfont' property is an instance of Tickfont
that may be specified as:
- An instance of :class:`plotly.graph_objs.scattergl.marker.colorbar.Tickfont`
- A dict of string/value properties that will be passed
to the Tickfont constructor
Supported dict properties:
color
family
HTML font family - the typeface that will be
applied by the web browser. The web browser
will only be able to apply a font if it is
available on the system which it operates.
Provide multiple font families, separated by
commas, to indicate the preference in which to
apply fonts if they aren't available on the
system. The Chart Studio Cloud (at
https://chart-studio.plotly.com or on-premise)
generates images on a server, where only a
select number of fonts are installed and
supported. These include "Arial", "Balto",
"Courier New", "Droid Sans",, "Droid Serif",
"Droid Sans Mono", "Gravitas One", "Old
Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
size
Returns
-------
plotly.graph_objs.scattergl.marker.colorbar.Tickfont
"""
return self["tickfont"] | [
"def",
"tickfont",
"(",
"self",
")",
":",
"return",
"self",
"[",
"\"tickfont\"",
"]"
] | https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/scattergl/marker/_colorbar.py#L718-L755 | |
openedx/edx-platform | 68dd185a0ab45862a2a61e0f803d7e03d2be71b5 | common/lib/xmodule/xmodule/modulestore/split_mongo/split_draft.py | python | DraftVersioningModuleStore.publish | (self, location, user_id, blacklist=None, **kwargs) | return self.get_item(location.for_branch(ModuleStoreEnum.BranchName.published), **kwargs) | Publishes the subtree under location from the draft branch to the published branch
Returns the newly published item. | Publishes the subtree under location from the draft branch to the published branch
Returns the newly published item. | [
"Publishes",
"the",
"subtree",
"under",
"location",
"from",
"the",
"draft",
"branch",
"to",
"the",
"published",
"branch",
"Returns",
"the",
"newly",
"published",
"item",
"."
] | def publish(self, location, user_id, blacklist=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Publishes the subtree under location from the draft branch to the published branch
Returns the newly published item.
"""
super().copy(
user_id,
# Directly using the replace function rather than the for_branch function
# because for_branch obliterates the version_guid and will lead to missed version conflicts.
# TODO Instead, the for_branch implementation should be fixed in the Opaque Keys library.
location.course_key.replace(branch=ModuleStoreEnum.BranchName.draft),
# We clear out the version_guid here because the location here is from the draft branch, and that
# won't have the same version guid
location.course_key.replace(branch=ModuleStoreEnum.BranchName.published, version_guid=None),
[location],
blacklist=blacklist
)
self._flag_publish_event(location.course_key)
return self.get_item(location.for_branch(ModuleStoreEnum.BranchName.published), **kwargs) | [
"def",
"publish",
"(",
"self",
",",
"location",
",",
"user_id",
",",
"blacklist",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# lint-amnesty, pylint: disable=arguments-differ",
"super",
"(",
")",
".",
"copy",
"(",
"user_id",
",",
"# Directly using the repla... | https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/common/lib/xmodule/xmodule/modulestore/split_mongo/split_draft.py#L370-L390 | |
aws-samples/machine-learning-samples | 025bd6d97a9f45813aad38cc2734252103ba3a93 | targeted-marketing-python/build_model.py | python | build_model | (data_s3_url, schema_fn, recipe_fn, name, train_percent=70) | return ml_model_id | Creates all the objects needed to build an ML Model & evaluate its quality. | Creates all the objects needed to build an ML Model & evaluate its quality. | [
"Creates",
"all",
"the",
"objects",
"needed",
"to",
"build",
"an",
"ML",
"Model",
"&",
"evaluate",
"its",
"quality",
"."
] | def build_model(data_s3_url, schema_fn, recipe_fn, name, train_percent=70):
"""Creates all the objects needed to build an ML Model & evaluate its quality.
"""
ml = boto3.client('machinelearning')
(train_ds_id, test_ds_id) = create_data_sources(ml, data_s3_url, schema_fn,
train_percent, name)
ml_model_id = create_model(ml, train_ds_id, recipe_fn, name)
eval_id = create_evaluation(ml, ml_model_id, test_ds_id, name)
return ml_model_id | [
"def",
"build_model",
"(",
"data_s3_url",
",",
"schema_fn",
",",
"recipe_fn",
",",
"name",
",",
"train_percent",
"=",
"70",
")",
":",
"ml",
"=",
"boto3",
".",
"client",
"(",
"'machinelearning'",
")",
"(",
"train_ds_id",
",",
"test_ds_id",
")",
"=",
"create... | https://github.com/aws-samples/machine-learning-samples/blob/025bd6d97a9f45813aad38cc2734252103ba3a93/targeted-marketing-python/build_model.py#L32-L41 | |
tahoe-lafs/tahoe-lafs | 766a53b5208c03c45ca0a98e97eee76870276aa1 | src/allmydata/crypto/aes.py | python | _validate_cryptor | (cryptor, encrypt=True) | raise ValueError if `cryptor` is not a valid object | raise ValueError if `cryptor` is not a valid object | [
"raise",
"ValueError",
"if",
"cryptor",
"is",
"not",
"a",
"valid",
"object"
] | def _validate_cryptor(cryptor, encrypt=True):
"""
raise ValueError if `cryptor` is not a valid object
"""
klass = IEncryptor if encrypt else IDecryptor
name = "encryptor" if encrypt else "decryptor"
if not isinstance(cryptor, CipherContext):
raise ValueError(
"'{}' must be a CipherContext".format(name)
)
if not klass.providedBy(cryptor):
raise ValueError(
"'{}' must be created with create_{}()".format(name, name)
) | [
"def",
"_validate_cryptor",
"(",
"cryptor",
",",
"encrypt",
"=",
"True",
")",
":",
"klass",
"=",
"IEncryptor",
"if",
"encrypt",
"else",
"IDecryptor",
"name",
"=",
"\"encryptor\"",
"if",
"encrypt",
"else",
"\"decryptor\"",
"if",
"not",
"isinstance",
"(",
"crypt... | https://github.com/tahoe-lafs/tahoe-lafs/blob/766a53b5208c03c45ca0a98e97eee76870276aa1/src/allmydata/crypto/aes.py#L151-L164 | ||
pyparallel/pyparallel | 11e8c6072d48c8f13641925d17b147bf36ee0ba3 | Lib/site-packages/ipython-4.0.0-py3.3.egg/IPython/core/logger.py | python | Logger.logstart | (self, logfname=None, loghead=None, logmode=None,
log_output=False, timestamp=False, log_raw_input=False) | Generate a new log-file with a default header.
Raises RuntimeError if the log has already been started | Generate a new log-file with a default header. | [
"Generate",
"a",
"new",
"log",
"-",
"file",
"with",
"a",
"default",
"header",
"."
] | def logstart(self, logfname=None, loghead=None, logmode=None,
log_output=False, timestamp=False, log_raw_input=False):
"""Generate a new log-file with a default header.
Raises RuntimeError if the log has already been started"""
if self.logfile is not None:
raise RuntimeError('Log file is already active: %s' %
self.logfname)
# The parameters can override constructor defaults
if logfname is not None: self.logfname = logfname
if loghead is not None: self.loghead = loghead
if logmode is not None: self.logmode = logmode
# Parameters not part of the constructor
self.timestamp = timestamp
self.log_output = log_output
self.log_raw_input = log_raw_input
# init depending on the log mode requested
isfile = os.path.isfile
logmode = self.logmode
if logmode == 'append':
self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
elif logmode == 'backup':
if isfile(self.logfname):
backup_logname = self.logfname+'~'
# Manually remove any old backup, since os.rename may fail
# under Windows.
if isfile(backup_logname):
os.remove(backup_logname)
os.rename(self.logfname,backup_logname)
self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
elif logmode == 'global':
self.logfname = os.path.join(self.home_dir,self.logfname)
self.logfile = io.open(self.logfname, 'a', encoding='utf-8')
elif logmode == 'over':
if isfile(self.logfname):
os.remove(self.logfname)
self.logfile = io.open(self.logfname,'w', encoding='utf-8')
elif logmode == 'rotate':
if isfile(self.logfname):
if isfile(self.logfname+'.001~'):
old = glob.glob(self.logfname+'.*~')
old.sort()
old.reverse()
for f in old:
root, ext = os.path.splitext(f)
num = int(ext[1:-1])+1
os.rename(f, root+'.'+repr(num).zfill(3)+'~')
os.rename(self.logfname, self.logfname+'.001~')
self.logfile = io.open(self.logfname, 'w', encoding='utf-8')
if logmode != 'append':
self.logfile.write(self.loghead)
self.logfile.flush()
self.log_active = True | [
"def",
"logstart",
"(",
"self",
",",
"logfname",
"=",
"None",
",",
"loghead",
"=",
"None",
",",
"logmode",
"=",
"None",
",",
"log_output",
"=",
"False",
",",
"timestamp",
"=",
"False",
",",
"log_raw_input",
"=",
"False",
")",
":",
"if",
"self",
".",
... | https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/ipython-4.0.0-py3.3.egg/IPython/core/logger.py#L66-L129 | ||
Raschka-research-group/coral-cnn | 726e54579db008d9c16868fa76b2292b9dec9fbc | model-code/cacd-coral.py | python | resnet34 | (num_classes, grayscale) | return model | Constructs a ResNet-34 model. | Constructs a ResNet-34 model. | [
"Constructs",
"a",
"ResNet",
"-",
"34",
"model",
"."
] | def resnet34(num_classes, grayscale):
"""Constructs a ResNet-34 model."""
model = ResNet(block=BasicBlock,
layers=[3, 4, 6, 3],
num_classes=num_classes,
grayscale=grayscale)
return model | [
"def",
"resnet34",
"(",
"num_classes",
",",
"grayscale",
")",
":",
"model",
"=",
"ResNet",
"(",
"block",
"=",
"BasicBlock",
",",
"layers",
"=",
"[",
"3",
",",
"4",
",",
"6",
",",
"3",
"]",
",",
"num_classes",
"=",
"num_classes",
",",
"grayscale",
"="... | https://github.com/Raschka-research-group/coral-cnn/blob/726e54579db008d9c16868fa76b2292b9dec9fbc/model-code/cacd-coral.py#L325-L331 | |
BlackLight/platypush | a6b552504e2ac327c94f3a28b607061b6b60cf36 | platypush/plugins/gpio/zeroborg/lib/__init__.py | python | ZeroBorg.Help | (self) | Help()
Displays the names and descriptions of the various functions and settings provided | Help() | [
"Help",
"()"
] | def Help(self):
"""
Help()
Displays the names and descriptions of the various functions and settings provided
"""
# noinspection PyTypeChecker
funcList = [ZeroBorg.__dict__.get(a) for a in dir(ZeroBorg) if
isinstance(ZeroBorg.__dict__.get(a), types.FunctionType)]
funcListSorted = sorted(funcList, key=lambda x: x.func_code.co_firstlineno)
print(self.__doc__)
print()
for func in funcListSorted:
print('=== %s === %s' % (func.func_name, func.func_doc)) | [
"def",
"Help",
"(",
"self",
")",
":",
"# noinspection PyTypeChecker",
"funcList",
"=",
"[",
"ZeroBorg",
".",
"__dict__",
".",
"get",
"(",
"a",
")",
"for",
"a",
"in",
"dir",
"(",
"ZeroBorg",
")",
"if",
"isinstance",
"(",
"ZeroBorg",
".",
"__dict__",
".",
... | https://github.com/BlackLight/platypush/blob/a6b552504e2ac327c94f3a28b607061b6b60cf36/platypush/plugins/gpio/zeroborg/lib/__init__.py#L929-L943 | ||
sqlmapproject/sqlmap | 3b07b70864624dff4c29dcaa8a61c78e7f9189f7 | thirdparty/clientform/clientform.py | python | HTMLForm.possible_items | (self, # deprecated
name=None, type=None, kind=None, id=None,
nr=None, by_label=False, label=None) | return c.possible_items(by_label) | Return a list of all values that the specified control can take. | Return a list of all values that the specified control can take. | [
"Return",
"a",
"list",
"of",
"all",
"values",
"that",
"the",
"specified",
"control",
"can",
"take",
"."
] | def possible_items(self, # deprecated
name=None, type=None, kind=None, id=None,
nr=None, by_label=False, label=None):
"""Return a list of all values that the specified control can take."""
c = self._find_list_control(name, type, kind, id, label, nr)
return c.possible_items(by_label) | [
"def",
"possible_items",
"(",
"self",
",",
"# deprecated",
"name",
"=",
"None",
",",
"type",
"=",
"None",
",",
"kind",
"=",
"None",
",",
"id",
"=",
"None",
",",
"nr",
"=",
"None",
",",
"by_label",
"=",
"False",
",",
"label",
"=",
"None",
")",
":",
... | https://github.com/sqlmapproject/sqlmap/blob/3b07b70864624dff4c29dcaa8a61c78e7f9189f7/thirdparty/clientform/clientform.py#L3011-L3016 | |
jeetsukumaran/DendroPy | 29fd294bf05d890ebf6a8d576c501e471db27ca1 | src/dendropy/model/continuous.py | python | _calc_KTB_rates_crop | (starting_rate, duration, roeotroe, rng, min_rate=None, max_rate=None) | return r, (starting_rate + r)/2.0 | Returns a descendant rate and mean rate according to the Kishino, Thorne,
Bruno model. Assumes that the min_rate <= starting_rate <= max_rate if a max
and min are provided.
rate is kept within in the [min_rate, max_rate] range by cropping at these
values and acting is if the cropping occurred at an appropriate point
in the duration of the branch (based on a linear change in rate from the
beginning of the random_variate drawn for the end of the branch). | Returns a descendant rate and mean rate according to the Kishino, Thorne,
Bruno model. Assumes that the min_rate <= starting_rate <= max_rate if a max
and min are provided.
rate is kept within in the [min_rate, max_rate] range by cropping at these
values and acting is if the cropping occurred at an appropriate point
in the duration of the branch (based on a linear change in rate from the
beginning of the random_variate drawn for the end of the branch). | [
"Returns",
"a",
"descendant",
"rate",
"and",
"mean",
"rate",
"according",
"to",
"the",
"Kishino",
"Thorne",
"Bruno",
"model",
".",
"Assumes",
"that",
"the",
"min_rate",
"<",
"=",
"starting_rate",
"<",
"=",
"max_rate",
"if",
"a",
"max",
"and",
"min",
"are",... | def _calc_KTB_rates_crop(starting_rate, duration, roeotroe, rng, min_rate=None, max_rate=None):
"""Returns a descendant rate and mean rate according to the Kishino, Thorne,
Bruno model. Assumes that the min_rate <= starting_rate <= max_rate if a max
and min are provided.
rate is kept within in the [min_rate, max_rate] range by cropping at these
values and acting is if the cropping occurred at an appropriate point
in the duration of the branch (based on a linear change in rate from the
beginning of the random_variate drawn for the end of the branch).
"""
if roeotroe*duration <= 0.0:
if (min_rate and starting_rate < min_rate) or (max_rate and starting_rate > max_rate):
raise ValueError("Parent rate is out of bounds, but no rate change is possible")
r = _calc_KTB_rate(starting_rate, duration, roeotroe, rng)
if max_rate and r > max_rate:
assert(starting_rate <= max_rate)
p_changing = (max_rate - starting_rate)/(r - starting_rate)
mean_changing = (starting_rate + max_rate)/2.0
mr = p_changing*mean_changing + (1.0 - p_changing)*max_rate
return max_rate, mr
elif min_rate and r < min_rate:
assert(starting_rate >= min_rate)
p_changing = (starting_rate - min_rate)/(starting_rate - r)
mean_changing = (starting_rate + min_rate)/2.0
mr = p_changing*mean_changing + (1.0 - p_changing)*min_rate
return min_rate, mr
return r, (starting_rate + r)/2.0 | [
"def",
"_calc_KTB_rates_crop",
"(",
"starting_rate",
",",
"duration",
",",
"roeotroe",
",",
"rng",
",",
"min_rate",
"=",
"None",
",",
"max_rate",
"=",
"None",
")",
":",
"if",
"roeotroe",
"*",
"duration",
"<=",
"0.0",
":",
"if",
"(",
"min_rate",
"and",
"s... | https://github.com/jeetsukumaran/DendroPy/blob/29fd294bf05d890ebf6a8d576c501e471db27ca1/src/dendropy/model/continuous.py#L458-L483 | |
bikalims/bika.lims | 35e4bbdb5a3912cae0b5eb13e51097c8b0486349 | bika/lims/browser/samplinground/printform.py | python | PrintForm.__call__ | (self) | [] | def __call__(self):
if self.context.portal_type == 'SamplingRound':
self._samplingrounds = [self.context]
elif self.context.portal_type == 'SamplingRounds' \
and self.request.get('items', ''):
uids = self.request.get('items').split(',')
uc = getToolByName(self.context, 'uid_catalog')
self._samplingrounds = [obj.getObject() for obj in uc(UID=uids)]
else:
# Warn and redirect to referer
logger.warning('PrintView: type not allowed: %s' %
self.context.portal_type)
self.destination_url = self.request.get_header("referer",
self.context.absolute_url())
# Do print?
if self.request.form.get('pdf', '0') == '1':
response = self.request.response
response.setHeader("Content-type", "application/pdf")
response.setHeader("Content-Disposition", "inline")
response.setHeader("filename", "temp.pdf")
return self.pdfFromPOST()
else:
return self.template() | [
"def",
"__call__",
"(",
"self",
")",
":",
"if",
"self",
".",
"context",
".",
"portal_type",
"==",
"'SamplingRound'",
":",
"self",
".",
"_samplingrounds",
"=",
"[",
"self",
".",
"context",
"]",
"elif",
"self",
".",
"context",
".",
"portal_type",
"==",
"'S... | https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/browser/samplinground/printform.py#L30-L55 | ||||
volatilityfoundation/volatility3 | 168b0d0b053ab97a7cb096ef2048795cc54d885f | volatility3/framework/interfaces/configuration.py | python | ClassRequirement.cls | (self) | return self._cls | Contains the actual chosen class based on the configuration value's
class name. | Contains the actual chosen class based on the configuration value's
class name. | [
"Contains",
"the",
"actual",
"chosen",
"class",
"based",
"on",
"the",
"configuration",
"value",
"s",
"class",
"name",
"."
] | def cls(self) -> Optional[Type]:
"""Contains the actual chosen class based on the configuration value's
class name."""
return self._cls | [
"def",
"cls",
"(",
"self",
")",
"->",
"Optional",
"[",
"Type",
"]",
":",
"return",
"self",
".",
"_cls"
] | https://github.com/volatilityfoundation/volatility3/blob/168b0d0b053ab97a7cb096ef2048795cc54d885f/volatility3/framework/interfaces/configuration.py#L487-L490 | |
python-telegram-bot/python-telegram-bot | ade1529986f5b6d394a65372d6a27045a70725b2 | telegram/files/inputfile.py | python | InputFile.is_file | (obj: object) | return hasattr(obj, 'read') | [] | def is_file(obj: object) -> bool: # skipcq: PY-D0003
return hasattr(obj, 'read') | [
"def",
"is_file",
"(",
"obj",
":",
"object",
")",
"->",
"bool",
":",
"# skipcq: PY-D0003",
"return",
"hasattr",
"(",
"obj",
",",
"'read'",
")"
] | https://github.com/python-telegram-bot/python-telegram-bot/blob/ade1529986f5b6d394a65372d6a27045a70725b2/telegram/files/inputfile.py#L112-L113 | |||
jhultman/vision3d | 8d73f4fe2b9037bc428b7cf7040c563110f2f0a7 | vision3d/dataset/kitti_dataset.py | python | AnnotationLoader._numpify_object | (self, obj, calib) | return obj | Converts from camera to velodyne frame. | Converts from camera to velodyne frame. | [
"Converts",
"from",
"camera",
"to",
"velodyne",
"frame",
"."
] | def _numpify_object(self, obj, calib):
"""Converts from camera to velodyne frame."""
xyz = calib.C2V @ np.r_[calib.R0 @ obj.t, 1]
box = np.r_[xyz, obj.w, obj.l, obj.h, -obj.ry]
obj = dict(box=box, class_idx=obj.class_idx)
return obj | [
"def",
"_numpify_object",
"(",
"self",
",",
"obj",
",",
"calib",
")",
":",
"xyz",
"=",
"calib",
".",
"C2V",
"@",
"np",
".",
"r_",
"[",
"calib",
".",
"R0",
"@",
"obj",
".",
"t",
",",
"1",
"]",
"box",
"=",
"np",
".",
"r_",
"[",
"xyz",
",",
"o... | https://github.com/jhultman/vision3d/blob/8d73f4fe2b9037bc428b7cf7040c563110f2f0a7/vision3d/dataset/kitti_dataset.py#L75-L80 | |
IdentityPython/pysaml2 | 6badb32d212257bd83ffcc816f9b625f68281b47 | src/saml2/ecp_client.py | python | Client.add_paos_headers | (headers=None) | return headers | [] | def add_paos_headers(headers=None):
if headers:
headers = set_list2dict(headers)
headers["PAOS"] = PAOS_HEADER_INFO
if "Accept" in headers:
headers["Accept"] += ";%s" % MIME_PAOS
elif "accept" in headers:
headers["Accept"] = headers["accept"]
headers["Accept"] += ";%s" % MIME_PAOS
del headers["accept"]
headers = dict2set_list(headers)
else:
headers = [
('Accept', 'text/html; %s' % MIME_PAOS),
('PAOS', PAOS_HEADER_INFO)
]
return headers | [
"def",
"add_paos_headers",
"(",
"headers",
"=",
"None",
")",
":",
"if",
"headers",
":",
"headers",
"=",
"set_list2dict",
"(",
"headers",
")",
"headers",
"[",
"\"PAOS\"",
"]",
"=",
"PAOS_HEADER_INFO",
"if",
"\"Accept\"",
"in",
"headers",
":",
"headers",
"[",
... | https://github.com/IdentityPython/pysaml2/blob/6badb32d212257bd83ffcc816f9b625f68281b47/src/saml2/ecp_client.py#L257-L274 | |||
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/quivers/representation.py | python | QuiverRep_generic.quotient | (self, sub, check=True) | return self._semigroup.representation(self.base_ring(), spaces, maps) | Return the quotient of ``self`` by the submodule ``sub``.
INPUT:
- ``sub`` -- :class:`QuiverRep`; this must be a submodule of ``self``,
meaning the space associated to each vertex `v` of ``sub`` is a
subspace of the space associated to `v` in ``self`` and the map
associated to each edge `e` of ``sub`` is the restriction of
the map associated to `e` in ``self``
- ``check`` -- bool; if ``True`` then ``sub`` is checked to verify
that it is indeed a submodule of ``self`` and an error is raised
if it is not
OUTPUT:
- :class:`QuiverRep`, the quotient module ``self / sub``
.. NOTE::
This function returns only a QuiverRep object ``quot``. The
projection map from ``self`` to ``quot`` can be obtained by
calling ``quot.coerce_map_from(self)``.
EXAMPLES::
sage: Q = DiGraph({1:{2:['a','b']}, 2:{3:['c']}}).path_semigroup()
sage: M = Q.I(GF(3), 3)
sage: N = Q.S(GF(3), 3)
sage: M.quotient(N)
Representation with dimension vector (2, 1, 0)
sage: M.quotient(M.radical())
Representation with dimension vector (2, 0, 0)
sage: M.quotient(M)
Representation with dimension vector (0, 0, 0) | Return the quotient of ``self`` by the submodule ``sub``. | [
"Return",
"the",
"quotient",
"of",
"self",
"by",
"the",
"submodule",
"sub",
"."
] | def quotient(self, sub, check=True):
"""
Return the quotient of ``self`` by the submodule ``sub``.
INPUT:
- ``sub`` -- :class:`QuiverRep`; this must be a submodule of ``self``,
meaning the space associated to each vertex `v` of ``sub`` is a
subspace of the space associated to `v` in ``self`` and the map
associated to each edge `e` of ``sub`` is the restriction of
the map associated to `e` in ``self``
- ``check`` -- bool; if ``True`` then ``sub`` is checked to verify
that it is indeed a submodule of ``self`` and an error is raised
if it is not
OUTPUT:
- :class:`QuiverRep`, the quotient module ``self / sub``
.. NOTE::
This function returns only a QuiverRep object ``quot``. The
projection map from ``self`` to ``quot`` can be obtained by
calling ``quot.coerce_map_from(self)``.
EXAMPLES::
sage: Q = DiGraph({1:{2:['a','b']}, 2:{3:['c']}}).path_semigroup()
sage: M = Q.I(GF(3), 3)
sage: N = Q.S(GF(3), 3)
sage: M.quotient(N)
Representation with dimension vector (2, 1, 0)
sage: M.quotient(M.radical())
Representation with dimension vector (2, 0, 0)
sage: M.quotient(M)
Representation with dimension vector (0, 0, 0)
"""
# First form the quotient space at each vertex
spaces = {}
for v in self._quiver:
spaces[v] = self._spaces[v].quotient(sub._spaces[v], check)
# Check the maps of sub if desired
if check:
for e in self._semigroup._sorted_edges:
for x in sub._spaces[e[0]].gens():
if sub._maps[e](x) != self._maps[e](x):
raise ValueError("the quotient method was not passed a submodule")
# Then pass the edge maps to the quotient
maps = {}
for e in self._semigroup._sorted_edges:
# Sage can automatically coerce an element of a module to an
# element of a quotient of that module but not the other way
# around. So in order to pass a map to the quotient we need to
# construct the quotient map for the domain so that we can take
# inverse images to lift elements. As sage can coerce to a quotient
# this is easy, we just send generators to themselves and set the
# domain to be the quotient.
# TODO: This 'if' shouldn't need to be here, but sage crashes when
# coercing elements into a quotient that is zero. Once Trac ticket
# 12413 gets fixed only the else should need to execute.
# NOTE: This is no longer necessary. Keep around for speed or
# remove? -- darij, 16 Feb 2014
if spaces[e[1]].dimension() == 0:
maps[e] = spaces[e[0]].Hom(spaces[e[1]]).zero()
else:
factor = self._spaces[e[0]].hom(self._spaces[e[0]].gens(), spaces[e[0]])
# Now we create a homomorphism by specifying the images of
# generators. Each generator is lifted to the original domain and
# mapped over using the original map. The codomain is set as the
# quotient so sage will take care of pushing the result to the
# quotient in the codomain.
maps[e] = spaces[e[0]].hom([self._maps[e](factor.lift(x))
for x in spaces[e[0]].gens()], spaces[e[1]])
return self._semigroup.representation(self.base_ring(), spaces, maps) | [
"def",
"quotient",
"(",
"self",
",",
"sub",
",",
"check",
"=",
"True",
")",
":",
"# First form the quotient space at each vertex",
"spaces",
"=",
"{",
"}",
"for",
"v",
"in",
"self",
".",
"_quiver",
":",
"spaces",
"[",
"v",
"]",
"=",
"self",
".",
"_spaces... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/quivers/representation.py#L2178-L2257 | |
trezor/trezor-core | 18c3a6a5bd45923380312b064be96155f5a7377d | src/apps/monero/signing/offloading_keys.py | python | enc_key_spend | (key_enc, idx: int) | return _build_key(key_enc, b"txin-spend", idx) | Chacha20Poly1305 encryption key for alpha[i] used in Pedersen commitment in pseudo_outs[i] | Chacha20Poly1305 encryption key for alpha[i] used in Pedersen commitment in pseudo_outs[i] | [
"Chacha20Poly1305",
"encryption",
"key",
"for",
"alpha",
"[",
"i",
"]",
"used",
"in",
"Pedersen",
"commitment",
"in",
"pseudo_outs",
"[",
"i",
"]"
] | def enc_key_spend(key_enc, idx: int) -> bytes:
"""
Chacha20Poly1305 encryption key for alpha[i] used in Pedersen commitment in pseudo_outs[i]
"""
return _build_key(key_enc, b"txin-spend", idx) | [
"def",
"enc_key_spend",
"(",
"key_enc",
",",
"idx",
":",
"int",
")",
"->",
"bytes",
":",
"return",
"_build_key",
"(",
"key_enc",
",",
"b\"txin-spend\"",
",",
"idx",
")"
] | https://github.com/trezor/trezor-core/blob/18c3a6a5bd45923380312b064be96155f5a7377d/src/apps/monero/signing/offloading_keys.py#L86-L90 | |
wistbean/fxxkpython | 88e16d79d8dd37236ba6ecd0d0ff11d63143968c | vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/html5lib/_inputstream.py | python | HTMLUnicodeInputStream.__init__ | (self, source) | Initialises the HTMLInputStream.
HTMLInputStream(source, [encoding]) -> Normalized stream from source
for use by html5lib.
source can be either a file-object, local filename or a string.
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element) | Initialises the HTMLInputStream. | [
"Initialises",
"the",
"HTMLInputStream",
"."
] | def __init__(self, source):
"""Initialises the HTMLInputStream.
HTMLInputStream(source, [encoding]) -> Normalized stream from source
for use by html5lib.
source can be either a file-object, local filename or a string.
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element)
"""
if not _utils.supports_lone_surrogates:
# Such platforms will have already checked for such
# surrogate errors, so no need to do this checking.
self.reportCharacterErrors = None
elif len("\U0010FFFF") == 1:
self.reportCharacterErrors = self.characterErrorsUCS4
else:
self.reportCharacterErrors = self.characterErrorsUCS2
# List of where new lines occur
self.newLines = [0]
self.charEncoding = (lookupEncoding("utf-8"), "certain")
self.dataStream = self.openStream(source)
self.reset() | [
"def",
"__init__",
"(",
"self",
",",
"source",
")",
":",
"if",
"not",
"_utils",
".",
"supports_lone_surrogates",
":",
"# Such platforms will have already checked for such",
"# surrogate errors, so no need to do this checking.",
"self",
".",
"reportCharacterErrors",
"=",
"None... | https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/html5lib/_inputstream.py#L164-L194 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/redis/client.py | python | StrictRedis.hdel | (self, name, *keys) | return self.execute_command('HDEL', name, *keys) | Delete ``keys`` from hash ``name`` | Delete ``keys`` from hash ``name`` | [
"Delete",
"keys",
"from",
"hash",
"name"
] | def hdel(self, name, *keys):
"Delete ``keys`` from hash ``name``"
return self.execute_command('HDEL', name, *keys) | [
"def",
"hdel",
"(",
"self",
",",
"name",
",",
"*",
"keys",
")",
":",
"return",
"self",
".",
"execute_command",
"(",
"'HDEL'",
",",
"name",
",",
"*",
"keys",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/redis/client.py#L1953-L1955 | |
jesse-ai/jesse | 28759547138fbc76dff12741204833e39c93b083 | jesse/strategies/Strategy.py | python | Strategy.candles | (self) | return store.candles.get_candles(self.exchange, self.symbol, self.timeframe) | Returns candles for current trading route
:return: np.ndarray | Returns candles for current trading route | [
"Returns",
"candles",
"for",
"current",
"trading",
"route"
] | def candles(self) -> np.ndarray:
"""
Returns candles for current trading route
:return: np.ndarray
"""
return store.candles.get_candles(self.exchange, self.symbol, self.timeframe) | [
"def",
"candles",
"(",
"self",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"store",
".",
"candles",
".",
"get_candles",
"(",
"self",
".",
"exchange",
",",
"self",
".",
"symbol",
",",
"self",
".",
"timeframe",
")"
] | https://github.com/jesse-ai/jesse/blob/28759547138fbc76dff12741204833e39c93b083/jesse/strategies/Strategy.py#L937-L943 | |
MegEngine/Models | 4c55d28bad03652a4e352bf5e736a75df041d84a | official/vision/detection/configs/retinanet_res34_coco_3x_800size.py | python | CustomRetinaNetConfig.__init__ | (self) | [] | def __init__(self):
super().__init__()
self.backbone = "resnet34"
self.fpn_in_channels = [128, 256, 512]
self.fpn_top_in_channel = 512 | [
"def",
"__init__",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"backbone",
"=",
"\"resnet34\"",
"self",
".",
"fpn_in_channels",
"=",
"[",
"128",
",",
"256",
",",
"512",
"]",
"self",
".",
"fpn_top_in_channel",
"=",
... | https://github.com/MegEngine/Models/blob/4c55d28bad03652a4e352bf5e736a75df041d84a/official/vision/detection/configs/retinanet_res34_coco_3x_800size.py#L15-L20 | ||||
cnbeining/onedrivecmd | 5deabf1114c041e0eabd2ed6ca2484adecd65443 | onedrivecmd/utils/helper_item.py | python | get_remote_item | (client, path = '', id = '') | return f | str->A item
Return a file/folder item.
If item not exist at remote, return None.
Only works with path OR id. | str->A item | [
"str",
"-",
">",
"A",
"item"
] | def get_remote_item(client, path = '', id = ''):
"""str->A item
Return a file/folder item.
If item not exist at remote, return None.
Only works with path OR id.
"""
try:
if path != '': # check path
path = od_path_to_api_path(path)
if path.endswith("/") and path != "/":
path=path[:-1]
f = client.item(drive = 'me', path = path).get()
elif id != '': # check id
f = client.item(drive = 'me', id = id).get()
except onedrivesdk.error.OneDriveError:
# onedrivesdk.error.OneDriveError: itemNotFound - Item does not exist
return None
#if f.folder:
# f = get_remote_folder_children(client, id = f.id)
return f | [
"def",
"get_remote_item",
"(",
"client",
",",
"path",
"=",
"''",
",",
"id",
"=",
"''",
")",
":",
"try",
":",
"if",
"path",
"!=",
"''",
":",
"# check path",
"path",
"=",
"od_path_to_api_path",
"(",
"path",
")",
"if",
"path",
".",
"endswith",
"(",
"\"/... | https://github.com/cnbeining/onedrivecmd/blob/5deabf1114c041e0eabd2ed6ca2484adecd65443/onedrivecmd/utils/helper_item.py#L20-L42 | |
wakatime/komodo-wakatime | 8923c04ded9fa64d7374fadd8cde3a6fadfe053d | components/wakatime/packages/urllib3/packages/ordered_dict.py | python | OrderedDict.__delitem__ | (self, key, dict_delitem=dict.__delitem__) | od.__delitem__(y) <==> del od[y] | od.__delitem__(y) <==> del od[y] | [
"od",
".",
"__delitem__",
"(",
"y",
")",
"<",
"==",
">",
"del",
"od",
"[",
"y",
"]"
] | def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which is
# then removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link_prev, link_next, key = self.__map.pop(key)
link_prev[1] = link_next
link_next[0] = link_prev | [
"def",
"__delitem__",
"(",
"self",
",",
"key",
",",
"dict_delitem",
"=",
"dict",
".",
"__delitem__",
")",
":",
"# Deleting an existing item uses self.__map to find the link which is",
"# then removed by updating the links in the predecessor and successor nodes.",
"dict_delitem",
"(... | https://github.com/wakatime/komodo-wakatime/blob/8923c04ded9fa64d7374fadd8cde3a6fadfe053d/components/wakatime/packages/urllib3/packages/ordered_dict.py#L54-L61 | ||
tensorflow/models | 6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3 | orbit/controller.py | python | Controller.restore_checkpoint | (self, checkpoint_path: Optional[str] = None) | return checkpoint_path | Restores the model from a checkpoint.
Args:
checkpoint_path: An optional string specifying the checkpoint path to
restore from. If `None`, will restore from the most recent checkpoint
(or initialize the model using a custom `init_fn` if no checkpoints can
be found) using `self.checkpoint_manager.restore_or_initialize()`.
Returns:
The path to the restored checkpoint if a restore happened, or `None` if no
restore occurred. | Restores the model from a checkpoint. | [
"Restores",
"the",
"model",
"from",
"a",
"checkpoint",
"."
] | def restore_checkpoint(self, checkpoint_path: Optional[str] = None):
"""Restores the model from a checkpoint.
Args:
checkpoint_path: An optional string specifying the checkpoint path to
restore from. If `None`, will restore from the most recent checkpoint
(or initialize the model using a custom `init_fn` if no checkpoints can
be found) using `self.checkpoint_manager.restore_or_initialize()`.
Returns:
The path to the restored checkpoint if a restore happened, or `None` if no
restore occurred.
"""
self._require("checkpoint_manager", for_method="restore_checkpoint")
with self.strategy.scope():
# Checkpoint restoring should be inside scope (b/139450638).
if checkpoint_path is not None:
_log(f"restoring model from {checkpoint_path}...")
self.checkpoint_manager.checkpoint.restore(checkpoint_path)
else:
_log("restoring or initializing model...")
checkpoint_path = self.checkpoint_manager.restore_or_initialize()
if checkpoint_path is not None:
_log(f"restored model from {checkpoint_path}.")
else:
_log("initialized model.")
return checkpoint_path | [
"def",
"restore_checkpoint",
"(",
"self",
",",
"checkpoint_path",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"self",
".",
"_require",
"(",
"\"checkpoint_manager\"",
",",
"for_method",
"=",
"\"restore_checkpoint\"",
")",
"with",
"self",
".",
"stra... | https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/orbit/controller.py#L370-L399 | |
MultiChain/multichain-explorer | 9e850fa79d0759b7348647ccf73a31d387c945a5 | Mce/DataStore.py | python | DataStore.get_rawmempool | (store, chain) | return resp | Get the result of getrawmempool json-rpc command as json object
:param chain:
:return: json object (key is txid, value is dict) | Get the result of getrawmempool json-rpc command as json object
:param chain:
:return: json object (key is txid, value is dict) | [
"Get",
"the",
"result",
"of",
"getrawmempool",
"json",
"-",
"rpc",
"command",
"as",
"json",
"object",
":",
"param",
"chain",
":",
":",
"return",
":",
"json",
"object",
"(",
"key",
"is",
"txid",
"value",
"is",
"dict",
")"
] | def get_rawmempool(store, chain):
"""
Get the result of getrawmempool json-rpc command as json object
:param chain:
:return: json object (key is txid, value is dict)
"""
url = store.get_url_by_chain(chain)
multichain_name = store.get_multichain_name_by_id(chain.id)
resp = None
try:
resp = util.jsonrpc(multichain_name, url, "getrawmempool", True)
except util.JsonrpcException as e:
raise Exception("JSON-RPC error({0}): {1}".format(e.code, e.message))
except IOError as e:
raise e
return resp | [
"def",
"get_rawmempool",
"(",
"store",
",",
"chain",
")",
":",
"url",
"=",
"store",
".",
"get_url_by_chain",
"(",
"chain",
")",
"multichain_name",
"=",
"store",
".",
"get_multichain_name_by_id",
"(",
"chain",
".",
"id",
")",
"resp",
"=",
"None",
"try",
":"... | https://github.com/MultiChain/multichain-explorer/blob/9e850fa79d0759b7348647ccf73a31d387c945a5/Mce/DataStore.py#L4255-L4270 | |
shiyanhui/FileHeader | f347cc134021fb0b710694b71c57742476f5fd2b | jinja2/parser.py | python | Parser.parse_statements | (self, end_tokens, drop_needle=False) | return result | Parse multiple statements into a list until one of the end tokens
is reached. This is used to parse the body of statements as it also
parses template data if appropriate. The parser checks first if the
current token is a colon and skips it if there is one. Then it checks
for the block end and parses until if one of the `end_tokens` is
reached. Per default the active token in the stream at the end of
the call is the matched end token. If this is not wanted `drop_needle`
can be set to `True` and the end token is removed. | Parse multiple statements into a list until one of the end tokens
is reached. This is used to parse the body of statements as it also
parses template data if appropriate. The parser checks first if the
current token is a colon and skips it if there is one. Then it checks
for the block end and parses until if one of the `end_tokens` is
reached. Per default the active token in the stream at the end of
the call is the matched end token. If this is not wanted `drop_needle`
can be set to `True` and the end token is removed. | [
"Parse",
"multiple",
"statements",
"into",
"a",
"list",
"until",
"one",
"of",
"the",
"end",
"tokens",
"is",
"reached",
".",
"This",
"is",
"used",
"to",
"parse",
"the",
"body",
"of",
"statements",
"as",
"it",
"also",
"parses",
"template",
"data",
"if",
"a... | def parse_statements(self, end_tokens, drop_needle=False):
"""Parse multiple statements into a list until one of the end tokens
is reached. This is used to parse the body of statements as it also
parses template data if appropriate. The parser checks first if the
current token is a colon and skips it if there is one. Then it checks
for the block end and parses until if one of the `end_tokens` is
reached. Per default the active token in the stream at the end of
the call is the matched end token. If this is not wanted `drop_needle`
can be set to `True` and the end token is removed.
"""
# the first token may be a colon for python compatibility
self.stream.skip_if('colon')
# in the future it would be possible to add whole code sections
# by adding some sort of end of statement token and parsing those here.
self.stream.expect('block_end')
result = self.subparse(end_tokens)
# we reached the end of the template too early, the subparser
# does not check for this, so we do that now
if self.stream.current.type == 'eof':
self.fail_eof(end_tokens)
if drop_needle:
next(self.stream)
return result | [
"def",
"parse_statements",
"(",
"self",
",",
"end_tokens",
",",
"drop_needle",
"=",
"False",
")",
":",
"# the first token may be a colon for python compatibility",
"self",
".",
"stream",
".",
"skip_if",
"(",
"'colon'",
")",
"# in the future it would be possible to add whole... | https://github.com/shiyanhui/FileHeader/blob/f347cc134021fb0b710694b71c57742476f5fd2b/jinja2/parser.py#L141-L166 | |
missionpinball/mpf | 8e6b74cff4ba06d2fec9445742559c1068b88582 | mpf/platforms/p_roc_devices.py | python | PDBLight.source_bank | (self) | return self.source_boardnum * 2 + self.source_banknum | Return source bank. | Return source bank. | [
"Return",
"source",
"bank",
"."
] | def source_bank(self):
"""Return source bank."""
return self.source_boardnum * 2 + self.source_banknum | [
"def",
"source_bank",
"(",
"self",
")",
":",
"return",
"self",
".",
"source_boardnum",
"*",
"2",
"+",
"self",
".",
"source_banknum"
] | https://github.com/missionpinball/mpf/blob/8e6b74cff4ba06d2fec9445742559c1068b88582/mpf/platforms/p_roc_devices.py#L323-L325 | |
citronneur/rdpy | cef16a9f64d836a3221a344ca7d571644280d829 | rdpy/protocol/rfb/rfb.py | python | RFBClientController.sendPointerEvent | (self, mask, x, y) | @summary: Send a pointer event throw RFB protocol
@param mask: mask of button if button 1 and 3 are pressed then mask is 00000101
@param x: x coordinate of mouse pointer
@param y: y pointer of mouse pointer | [] | def sendPointerEvent(self, mask, x, y):
"""
@summary: Send a pointer event throw RFB protocol
@param mask: mask of button if button 1 and 3 are pressed then mask is 00000101
@param x: x coordinate of mouse pointer
@param y: y pointer of mouse pointer
"""
if not self._isReady:
log.info("Try to send pointer event on non ready layer")
return
try:
event = PointerEvent()
event.mask.value = mask
event.x.value = x
event.y.value = y
self._rfbLayer.sendPointerEvent(event)
except InvalidValue:
log.debug("Try to send an invalid pointer event") | [
"def",
"sendPointerEvent",
"(",
"self",
",",
"mask",
",",
"x",
",",
"y",
")",
":",
"if",
"not",
"self",
".",
"_isReady",
":",
"log",
".",
"info",
"(",
"\"Try to send pointer event on non ready layer\"",
")",
"return",
"try",
":",
"event",
"=",
"PointerEvent"... | https://github.com/citronneur/rdpy/blob/cef16a9f64d836a3221a344ca7d571644280d829/rdpy/protocol/rfb/rfb.py#L634-L652 | |||
openshift/openshift-ansible-contrib | cd17fa3c5b8cab87b2403bde3a560eadcdcd0955 | misc/gce-federation/inventory/gce.py | python | CloudInventoryCache.write_to_cache | (self, data, filename='') | return True | Writes data to file as JSON. Returns True. | Writes data to file as JSON. Returns True. | [
"Writes",
"data",
"to",
"file",
"as",
"JSON",
".",
"Returns",
"True",
"."
] | def write_to_cache(self, data, filename=''):
''' Writes data to file as JSON. Returns True. '''
if not filename:
filename = self.cache_path_cache
json_data = json.dumps(data)
with open(filename, 'w') as cache:
cache.write(json_data)
return True | [
"def",
"write_to_cache",
"(",
"self",
",",
"data",
",",
"filename",
"=",
"''",
")",
":",
"if",
"not",
"filename",
":",
"filename",
"=",
"self",
".",
"cache_path_cache",
"json_data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
"with",
"open",
"(",
"fil... | https://github.com/openshift/openshift-ansible-contrib/blob/cd17fa3c5b8cab87b2403bde3a560eadcdcd0955/misc/gce-federation/inventory/gce.py#L148-L155 | |
Azure/azure-devops-cli-extension | 11334cd55806bef0b99c3bee5a438eed71e44037 | azure-devops/azext_devops/devops_sdk/v6_0/pipelines/pipelines_client.py | python | PipelinesClient.get_run | (self, project, pipeline_id, run_id) | return self._deserialize('Run', response) | GetRun.
[Preview API] Gets a run for a particular pipeline.
:param str project: Project ID or project name
:param int pipeline_id: The pipeline id
:param int run_id: The run id
:rtype: :class:`<Run> <azure.devops.v6_0.pipelines.models.Run>` | GetRun.
[Preview API] Gets a run for a particular pipeline.
:param str project: Project ID or project name
:param int pipeline_id: The pipeline id
:param int run_id: The run id
:rtype: :class:`<Run> <azure.devops.v6_0.pipelines.models.Run>` | [
"GetRun",
".",
"[",
"Preview",
"API",
"]",
"Gets",
"a",
"run",
"for",
"a",
"particular",
"pipeline",
".",
":",
"param",
"str",
"project",
":",
"Project",
"ID",
"or",
"project",
"name",
":",
"param",
"int",
"pipeline_id",
":",
"The",
"pipeline",
"id",
"... | def get_run(self, project, pipeline_id, run_id):
"""GetRun.
[Preview API] Gets a run for a particular pipeline.
:param str project: Project ID or project name
:param int pipeline_id: The pipeline id
:param int run_id: The run id
:rtype: :class:`<Run> <azure.devops.v6_0.pipelines.models.Run>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if pipeline_id is not None:
route_values['pipelineId'] = self._serialize.url('pipeline_id', pipeline_id, 'int')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
response = self._send(http_method='GET',
location_id='7859261e-d2e9-4a68-b820-a5d84cc5bb3d',
version='6.0-preview.1',
route_values=route_values)
return self._deserialize('Run', response) | [
"def",
"get_run",
"(",
"self",
",",
"project",
",",
"pipeline_id",
",",
"run_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"("... | https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v6_0/pipelines/pipelines_client.py#L179-L198 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/asn1crypto-0.24.0/asn1crypto/core.py | python | Boolean.__nonzero__ | (self) | return self.__bool__() | :return:
True or False | :return:
True or False | [
":",
"return",
":",
"True",
"or",
"False"
] | def __nonzero__(self):
"""
:return:
True or False
"""
return self.__bool__() | [
"def",
"__nonzero__",
"(",
"self",
")",
":",
"return",
"self",
".",
"__bool__",
"(",
")"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/asn1crypto-0.24.0/asn1crypto/core.py#L1798-L1803 | |
eirannejad/pyRevit | 49c0b7eb54eb343458ce1365425e6552d0c47d44 | site-packages/sortedcontainers/sortedset.py | python | SortedSet.remove | (self, value) | Remove first occurrence of *value*. Raises ValueError if
*value* is not present. | Remove first occurrence of *value*. Raises ValueError if
*value* is not present. | [
"Remove",
"first",
"occurrence",
"of",
"*",
"value",
"*",
".",
"Raises",
"ValueError",
"if",
"*",
"value",
"*",
"is",
"not",
"present",
"."
] | def remove(self, value):
"""
Remove first occurrence of *value*. Raises ValueError if
*value* is not present.
"""
self._set.remove(value)
self._list.remove(value) | [
"def",
"remove",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_set",
".",
"remove",
"(",
"value",
")",
"self",
".",
"_list",
".",
"remove",
"(",
"value",
")"
] | https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/sortedcontainers/sortedset.py#L193-L199 | ||
akaraspt/deepsleepnet | d4906b4875547a45175eaba8bdde280b7b1496f1 | tensorlayer/layers.py | python | initialize_global_variables | (sess=None) | Excute ``sess.run(tf.compat.v1.global_variables_initializer())`` for TF12+ or
sess.run(tf.initialize_all_variables()) for TF11.
Parameters
----------
sess : a Session | Excute ``sess.run(tf.compat.v1.global_variables_initializer())`` for TF12+ or
sess.run(tf.initialize_all_variables()) for TF11. | [
"Excute",
"sess",
".",
"run",
"(",
"tf",
".",
"compat",
".",
"v1",
".",
"global_variables_initializer",
"()",
")",
"for",
"TF12",
"+",
"or",
"sess",
".",
"run",
"(",
"tf",
".",
"initialize_all_variables",
"()",
")",
"for",
"TF11",
"."
] | def initialize_global_variables(sess=None):
"""Excute ``sess.run(tf.compat.v1.global_variables_initializer())`` for TF12+ or
sess.run(tf.initialize_all_variables()) for TF11.
Parameters
----------
sess : a Session
"""
assert sess is not None
try: # TF12
sess.run(tf.compat.v1.global_variables_initializer())
except: # TF11
sess.run(tf.compat.v1.global_variables_initializer()) | [
"def",
"initialize_global_variables",
"(",
"sess",
"=",
"None",
")",
":",
"assert",
"sess",
"is",
"not",
"None",
"try",
":",
"# TF12",
"sess",
".",
"run",
"(",
"tf",
".",
"compat",
".",
"v1",
".",
"global_variables_initializer",
"(",
")",
")",
"except",
... | https://github.com/akaraspt/deepsleepnet/blob/d4906b4875547a45175eaba8bdde280b7b1496f1/tensorlayer/layers.py#L225-L237 | ||
mrkipling/maraschino | c6be9286937783ae01df2d6d8cebfc8b2734a7d7 | lib/sqlalchemy/schema.py | python | Sequence.next_value | (self) | return expression.func.next_value(self, bind=self.bind) | Return a :class:`.next_value` function element
which will render the appropriate increment function
for this :class:`.Sequence` within any SQL expression. | Return a :class:`.next_value` function element
which will render the appropriate increment function
for this :class:`.Sequence` within any SQL expression. | [
"Return",
"a",
":",
"class",
":",
".",
"next_value",
"function",
"element",
"which",
"will",
"render",
"the",
"appropriate",
"increment",
"function",
"for",
"this",
":",
"class",
":",
".",
"Sequence",
"within",
"any",
"SQL",
"expression",
"."
] | def next_value(self):
"""Return a :class:`.next_value` function element
which will render the appropriate increment function
for this :class:`.Sequence` within any SQL expression.
"""
return expression.func.next_value(self, bind=self.bind) | [
"def",
"next_value",
"(",
"self",
")",
":",
"return",
"expression",
".",
"func",
".",
"next_value",
"(",
"self",
",",
"bind",
"=",
"self",
".",
"bind",
")"
] | https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/sqlalchemy/schema.py#L1652-L1658 | |
tosher/Mediawiker | 81bf97cace59bedcb1668e7830b85c36e014428e | lib/Crypto.lin.x64/Crypto/Cipher/_mode_eax.py | python | _create_eax_cipher | (factory, **kwargs) | return EaxMode(factory, key, nonce, mac_len, kwargs) | Create a new block cipher, configured in EAX mode.
:Parameters:
factory : module
A symmetric cipher module from `Crypto.Cipher` (like
`Crypto.Cipher.AES`).
:Keywords:
key : bytes/bytearray/memoryview
The secret key to use in the symmetric cipher.
nonce : bytes/bytearray/memoryview
A value that must never be reused for any other encryption.
There are no restrictions on its length, but it is recommended to use
at least 16 bytes.
The nonce shall never repeat for two different messages encrypted with
the same key, but it does not need to be random.
If not specified, a 16 byte long random string is used.
mac_len : integer
Length of the MAC, in bytes. It must be no larger than the cipher
block bytes (which is the default). | Create a new block cipher, configured in EAX mode. | [
"Create",
"a",
"new",
"block",
"cipher",
"configured",
"in",
"EAX",
"mode",
"."
] | def _create_eax_cipher(factory, **kwargs):
"""Create a new block cipher, configured in EAX mode.
:Parameters:
factory : module
A symmetric cipher module from `Crypto.Cipher` (like
`Crypto.Cipher.AES`).
:Keywords:
key : bytes/bytearray/memoryview
The secret key to use in the symmetric cipher.
nonce : bytes/bytearray/memoryview
A value that must never be reused for any other encryption.
There are no restrictions on its length, but it is recommended to use
at least 16 bytes.
The nonce shall never repeat for two different messages encrypted with
the same key, but it does not need to be random.
If not specified, a 16 byte long random string is used.
mac_len : integer
Length of the MAC, in bytes. It must be no larger than the cipher
block bytes (which is the default).
"""
try:
key = kwargs.pop("key")
nonce = kwargs.pop("nonce", None)
if nonce is None:
nonce = get_random_bytes(16)
mac_len = kwargs.pop("mac_len", factory.block_size)
except KeyError as e:
raise TypeError("Missing parameter: " + str(e))
return EaxMode(factory, key, nonce, mac_len, kwargs) | [
"def",
"_create_eax_cipher",
"(",
"factory",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"key",
"=",
"kwargs",
".",
"pop",
"(",
"\"key\"",
")",
"nonce",
"=",
"kwargs",
".",
"pop",
"(",
"\"nonce\"",
",",
"None",
")",
"if",
"nonce",
"is",
"None",
... | https://github.com/tosher/Mediawiker/blob/81bf97cace59bedcb1668e7830b85c36e014428e/lib/Crypto.lin.x64/Crypto/Cipher/_mode_eax.py#L345-L381 | |
lixinsu/RCZoo | 37fcb7962fbd4c751c561d4a0c84173881ea8339 | reader/docqa/utils.py | python | load_text | (filename) | return texts | Load the paragraphs only of a SQuAD dataset. Store as qid -> text. | Load the paragraphs only of a SQuAD dataset. Store as qid -> text. | [
"Load",
"the",
"paragraphs",
"only",
"of",
"a",
"SQuAD",
"dataset",
".",
"Store",
"as",
"qid",
"-",
">",
"text",
"."
] | def load_text(filename):
"""Load the paragraphs only of a SQuAD dataset. Store as qid -> text."""
# Load JSON file
if 'SQuAD' in filename:
with open(filename) as f:
examples = json.load(f)['data']
texts = {}
for article in examples:
for paragraph in article['paragraphs']:
for qa in paragraph['qas']:
texts[qa['id']] = paragraph['context']
else:
texts = {}
with open(filename) as f:
for line in f:
row = json.loads(line)
texts[row['query_id']] = row['passage']
return texts | [
"def",
"load_text",
"(",
"filename",
")",
":",
"# Load JSON file",
"if",
"'SQuAD'",
"in",
"filename",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"examples",
"=",
"json",
".",
"load",
"(",
"f",
")",
"[",
"'data'",
"]",
"texts",
"=",
"{... | https://github.com/lixinsu/RCZoo/blob/37fcb7962fbd4c751c561d4a0c84173881ea8339/reader/docqa/utils.py#L57-L75 | |
scikit-learn-contrib/DESlib | 64260ae7c6dd745ef0003cc6322c9f829c807708 | deslib/util/aggregation.py | python | _get_ensemble_probabilities | (classifier_ensemble, X,
estimator_features=None) | return np.array(list_proba).transpose((1, 0, 2)) | Get the probabilities estimate for each base classifier in the ensemble
Parameters
----------
classifier_ensemble : list of shape = [n_classifiers]
Containing the ensemble of classifiers used in the aggregation scheme.
X : array of shape (n_samples, n_features)
The input data.
estimator_features : array of shape (n_classifiers, n_selected_features)
Indices containing the features used by each classifier.
Returns
-------
list_proba : array of shape (n_samples, n_classifiers, n_classes)
Probabilities predicted by each base classifier in the ensemble for all
samples in X. | Get the probabilities estimate for each base classifier in the ensemble | [
"Get",
"the",
"probabilities",
"estimate",
"for",
"each",
"base",
"classifier",
"in",
"the",
"ensemble"
] | def _get_ensemble_probabilities(classifier_ensemble, X,
estimator_features=None):
"""Get the probabilities estimate for each base classifier in the ensemble
Parameters
----------
classifier_ensemble : list of shape = [n_classifiers]
Containing the ensemble of classifiers used in the aggregation scheme.
X : array of shape (n_samples, n_features)
The input data.
estimator_features : array of shape (n_classifiers, n_selected_features)
Indices containing the features used by each classifier.
Returns
-------
list_proba : array of shape (n_samples, n_classifiers, n_classes)
Probabilities predicted by each base classifier in the ensemble for all
samples in X.
"""
list_proba = []
if estimator_features is None:
for idx, clf in enumerate(classifier_ensemble):
list_proba.append(clf.predict_proba(X))
else:
for idx, clf in enumerate(classifier_ensemble):
list_proba.append(clf.predict_proba(X[:, estimator_features[idx]]))
# transpose the array to have the
# shape = [n_samples, n_classifiers, n_classes]
return np.array(list_proba).transpose((1, 0, 2)) | [
"def",
"_get_ensemble_probabilities",
"(",
"classifier_ensemble",
",",
"X",
",",
"estimator_features",
"=",
"None",
")",
":",
"list_proba",
"=",
"[",
"]",
"if",
"estimator_features",
"is",
"None",
":",
"for",
"idx",
",",
"clf",
"in",
"enumerate",
"(",
"classif... | https://github.com/scikit-learn-contrib/DESlib/blob/64260ae7c6dd745ef0003cc6322c9f829c807708/deslib/util/aggregation.py#L194-L224 | |
IJDykeman/wangTiles | 7c1ee2095ebdf7f72bce07d94c6484915d5cae8b | experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/setuptools/_vendor/packaging/version.py | python | _parse_local_version | (local) | Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). | Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). | [
"Takes",
"a",
"string",
"like",
"abc",
".",
"1",
".",
"twelve",
"and",
"turns",
"it",
"into",
"(",
"abc",
"1",
"twelve",
")",
"."
] | def _parse_local_version(local):
"""
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
"""
if local is not None:
return tuple(
part.lower() if not part.isdigit() else int(part)
for part in _local_version_seperators.split(local)
) | [
"def",
"_parse_local_version",
"(",
"local",
")",
":",
"if",
"local",
"is",
"not",
"None",
":",
"return",
"tuple",
"(",
"part",
".",
"lower",
"(",
")",
"if",
"not",
"part",
".",
"isdigit",
"(",
")",
"else",
"int",
"(",
"part",
")",
"for",
"part",
"... | https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/setuptools/_vendor/packaging/version.py#L332-L340 | ||
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/multiprocessing/sharedctypes.py | python | SynchronizedArray.__setitem__ | (self, i, value) | [] | def __setitem__(self, i, value):
with self:
self._obj[i] = value | [
"def",
"__setitem__",
"(",
"self",
",",
"i",
",",
"value",
")",
":",
"with",
"self",
":",
"self",
".",
"_obj",
"[",
"i",
"]",
"=",
"value"
] | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/multiprocessing/sharedctypes.py#L225-L227 | ||||
irmen/Tale | a2a26443465ab6978b32d9253e833471500e7b68 | tale/util.py | python | Context.from_global | (cls, player_connection=None) | return cls(driver=mud_context.driver, clock=mud_context.driver.game_clock,
config=mud_context.config, player_connection=player_connection) | Create a Context based on the current global mud_context
Should only be used to (re)create a ctx where one is required,
and you don't have a ctx argument provided already. | Create a Context based on the current global mud_context
Should only be used to (re)create a ctx where one is required,
and you don't have a ctx argument provided already. | [
"Create",
"a",
"Context",
"based",
"on",
"the",
"current",
"global",
"mud_context",
"Should",
"only",
"be",
"used",
"to",
"(",
"re",
")",
"create",
"a",
"ctx",
"where",
"one",
"is",
"required",
"and",
"you",
"don",
"t",
"have",
"a",
"ctx",
"argument",
... | def from_global(cls, player_connection=None) -> 'Context':
"""
Create a Context based on the current global mud_context
Should only be used to (re)create a ctx where one is required,
and you don't have a ctx argument provided already.
"""
return cls(driver=mud_context.driver, clock=mud_context.driver.game_clock,
config=mud_context.config, player_connection=player_connection) | [
"def",
"from_global",
"(",
"cls",
",",
"player_connection",
"=",
"None",
")",
"->",
"'Context'",
":",
"return",
"cls",
"(",
"driver",
"=",
"mud_context",
".",
"driver",
",",
"clock",
"=",
"mud_context",
".",
"driver",
".",
"game_clock",
",",
"config",
"=",... | https://github.com/irmen/Tale/blob/a2a26443465ab6978b32d9253e833471500e7b68/tale/util.py#L371-L378 | |
gem/oq-engine | 1bdb88f3914e390abcbd285600bfd39477aae47c | openquake/hazardlib/gsim/rietbrock_edwards_2019.py | python | _get_distance_term | (C, rjb, mag) | return ((C["c4"] + C["c5"] * mag) * f_0 +
(C["c6"] + C["c7"] * mag) * f_1 +
(C["c8"] + C["c9"] * mag) * f_2 +
(C["c10"] * rval)) | Returns the distance scaling component of the model
Equation 10, Page 63 | Returns the distance scaling component of the model
Equation 10, Page 63 | [
"Returns",
"the",
"distance",
"scaling",
"component",
"of",
"the",
"model",
"Equation",
"10",
"Page",
"63"
] | def _get_distance_term(C, rjb, mag):
"""
Returns the distance scaling component of the model
Equation 10, Page 63
"""
# Depth adjusted distance, equation 11 (Page 63)
rval = np.sqrt(rjb ** 2.0 + C["c11"] ** 2.0)
f_0, f_1, f_2 = _get_distance_segment_coefficients(rval)
return ((C["c4"] + C["c5"] * mag) * f_0 +
(C["c6"] + C["c7"] * mag) * f_1 +
(C["c8"] + C["c9"] * mag) * f_2 +
(C["c10"] * rval)) | [
"def",
"_get_distance_term",
"(",
"C",
",",
"rjb",
",",
"mag",
")",
":",
"# Depth adjusted distance, equation 11 (Page 63)",
"rval",
"=",
"np",
".",
"sqrt",
"(",
"rjb",
"**",
"2.0",
"+",
"C",
"[",
"\"c11\"",
"]",
"**",
"2.0",
")",
"f_0",
",",
"f_1",
",",... | https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/hazardlib/gsim/rietbrock_edwards_2019.py#L53-L64 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/libs/metadata/src/metadata/catalog/atlas_client.py | python | AtlasApi.get_entity | (self, entity_id) | # TODO: get entity by Atlas __guid or qualifiedName
GET /v2/search/dsl?query=? | # TODO: get entity by Atlas __guid or qualifiedName
GET /v2/search/dsl?query=? | [
"#",
"TODO",
":",
"get",
"entity",
"by",
"Atlas",
"__guid",
"or",
"qualifiedName",
"GET",
"/",
"v2",
"/",
"search",
"/",
"dsl?query",
"=",
"?"
] | def get_entity(self, entity_id):
"""
# TODO: get entity by Atlas __guid or qualifiedName
GET /v2/search/dsl?query=?
"""
try:
return self._root.get('entities/%s' % entity_id, headers=self.__headers, params=self.__params)
except RestException as e:
msg = 'Failed to get entity %s: %s' % (entity_id, str(e))
LOG.error(msg)
raise CatalogApiException(e.message) | [
"def",
"get_entity",
"(",
"self",
",",
"entity_id",
")",
":",
"try",
":",
"return",
"self",
".",
"_root",
".",
"get",
"(",
"'entities/%s'",
"%",
"entity_id",
",",
"headers",
"=",
"self",
".",
"__headers",
",",
"params",
"=",
"self",
".",
"__params",
")... | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/libs/metadata/src/metadata/catalog/atlas_client.py#L396-L406 | ||
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/xmlrpc/server.py | python | DocXMLRPCRequestHandler.do_GET | (self) | Handles the HTTP GET request.
Interpret all HTTP GET requests as requests for server
documentation. | Handles the HTTP GET request. | [
"Handles",
"the",
"HTTP",
"GET",
"request",
"."
] | def do_GET(self):
"""Handles the HTTP GET request.
Interpret all HTTP GET requests as requests for server
documentation.
"""
# Check that the path is legal
if not self.is_rpc_path_valid():
self.report_404()
return
response = self.server.generate_html_documentation().encode('utf-8')
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Content-length", str(len(response)))
self.end_headers()
self.wfile.write(response) | [
"def",
"do_GET",
"(",
"self",
")",
":",
"# Check that the path is legal",
"if",
"not",
"self",
".",
"is_rpc_path_valid",
"(",
")",
":",
"self",
".",
"report_404",
"(",
")",
"return",
"response",
"=",
"self",
".",
"server",
".",
"generate_html_documentation",
"... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/xmlrpc/server.py#L909-L925 | ||
amazon-archives/automating-governance-sample | 289dcd29106e16b54dd2c8a87a88b2189cde56bb | LambdaIsolateInstance.py | python | remove_from_asg | (instance) | return "done" | Identifies if instance is part of an ASG and removes it from group if that is the case.
Takes an instance ID as input.
Returns dict with outcome of requests. | Identifies if instance is part of an ASG and removes it from group if that is the case.
Takes an instance ID as input.
Returns dict with outcome of requests. | [
"Identifies",
"if",
"instance",
"is",
"part",
"of",
"an",
"ASG",
"and",
"removes",
"it",
"from",
"group",
"if",
"that",
"is",
"the",
"case",
".",
"Takes",
"an",
"instance",
"ID",
"as",
"input",
".",
"Returns",
"dict",
"with",
"outcome",
"of",
"requests",... | def remove_from_asg(instance):
'''
Identifies if instance is part of an ASG and removes it from group if that is the case.
Takes an instance ID as input.
Returns dict with outcome of requests.
'''
client = boto3.client('autoscaling', region_name=global_args.REGION)
try:
response = client.describe_auto_scaling_instances(
InstanceIds=[
instance
]
)
except Exception as e:
logging.info('API fail to describe ASG instances. Raw: ' + e.message)
return {'result': 'failure', 'message': 'API fail to describe ASG instances. Raw: ' + e.message}
logging.info(response)
if 'AutoScalingInstances' in response and len(response['AutoScalingInstances']) > 0:
if 'AutoScalingGroupName' in response['AutoScalingInstances'][0]:
asg_name = response['AutoScalingInstances'][0]['AutoScalingGroupName']
else:
logging.info('Unable to obtain ASG name... will not be able to deregister instance. Exiting.')
return {'result': 'failure', 'message': 'unable to get ASG name'}
# found ASG, will now remove
try:
response = client.detach_instances(
InstanceIds=[
instance,
],
AutoScalingGroupName=asg_name,
ShouldDecrementDesiredCapacity=False
)
logging.info('ASG removal outcome: ' + str(response))
subject = 'L3(' + instance + '): Successfuly removed instance from asg'
message = 'Success in detaching instance from ASG,' + asg_name + '.'
return {'result': 'ok', 'message': message, 'subject': subject}
except Exception as e:
logging.info('Unable to remove ' + instance + ' from ' + asg_name + '. Raw error: ' + e.message)
return {'result': 'failure',
'message': 'Unable to remove ' + instance + ' from ' + asg_name + '. Raw error: ' + e.message}
else:
return {'result': 'notfound', 'message': 'Instance doesn\'t seem part of an ASG'}
return "done" | [
"def",
"remove_from_asg",
"(",
"instance",
")",
":",
"client",
"=",
"boto3",
".",
"client",
"(",
"'autoscaling'",
",",
"region_name",
"=",
"global_args",
".",
"REGION",
")",
"try",
":",
"response",
"=",
"client",
".",
"describe_auto_scaling_instances",
"(",
"I... | https://github.com/amazon-archives/automating-governance-sample/blob/289dcd29106e16b54dd2c8a87a88b2189cde56bb/LambdaIsolateInstance.py#L112-L157 | |
hatRiot/zarp | 2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad | src/lib/libmproxy/console/grideditor.py | python | SetHeadersEditor.set_user_agent | (self, k) | [] | def set_user_agent(self, k):
ua = http_uastrings.get_by_shortcut(k)
if ua:
self.walker.add_value(
[
".*",
"User-Agent",
ua[2]
]
) | [
"def",
"set_user_agent",
"(",
"self",
",",
"k",
")",
":",
"ua",
"=",
"http_uastrings",
".",
"get_by_shortcut",
"(",
"k",
")",
"if",
"ua",
":",
"self",
".",
"walker",
".",
"add_value",
"(",
"[",
"\".*\"",
",",
"\"User-Agent\"",
",",
"ua",
"[",
"2",
"]... | https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/libmproxy/console/grideditor.py#L474-L483 | ||||
geopython/pycsw | 43a5c92fa819a3a3fdc8a8e3ef075d784dff73fc | pycsw/core/repository.py | python | Repository.update | (self, record=None, recprops=None, constraint=None) | Update a record in the repository based on identifier | Update a record in the repository based on identifier | [
"Update",
"a",
"record",
"in",
"the",
"repository",
"based",
"on",
"identifier"
] | def update(self, record=None, recprops=None, constraint=None):
''' Update a record in the repository based on identifier '''
if record is not None:
identifier = getattr(record,
self.context.md_core_model['mappings']['pycsw:Identifier'])
xml = getattr(self.dataset,
self.context.md_core_model['mappings']['pycsw:XML'])
anytext = getattr(self.dataset,
self.context.md_core_model['mappings']['pycsw:AnyText'])
if isinstance(record.xml, bytes):
LOGGER.debug('Decoding bytes to unicode')
record.xml = record.xml.decode()
if recprops is None and constraint is None: # full update
LOGGER.debug('full update')
update_dict = dict([(getattr(self.dataset, key),
getattr(record, key)) \
for key in record.__dict__.keys() if key != '_sa_instance_state'])
try:
self.session.begin()
self._get_repo_filter(self.session.query(self.dataset)).filter_by(
identifier=identifier).update(update_dict, synchronize_session='fetch')
self.session.commit()
except Exception as err:
self.session.rollback()
msg = 'Cannot commit to repository'
LOGGER.exception(msg)
raise RuntimeError(msg) from err
else: # update based on record properties
LOGGER.debug('property based update')
try:
rows = rows2 = 0
self.session.begin()
for rpu in recprops:
# update queryable column and XML document via XPath
if 'xpath' not in rpu['rp']:
self.session.rollback()
raise RuntimeError('XPath not found for property %s' % rpu['rp']['name'])
if 'dbcol' not in rpu['rp']:
self.session.rollback()
raise RuntimeError('property not found for XPath %s' % rpu['rp']['name'])
rows += self._get_repo_filter(self.session.query(self.dataset)).filter(
text(constraint['where'])).params(self._create_values(constraint['values'])).update({
getattr(self.dataset,
rpu['rp']['dbcol']): rpu['value'],
'xml': func.update_xpath(str(self.context.namespaces),
getattr(self.dataset,
self.context.md_core_model['mappings']['pycsw:XML']),
str(rpu)),
}, synchronize_session='fetch')
# then update anytext tokens
rows2 += self._get_repo_filter(self.session.query(self.dataset)).filter(
text(constraint['where'])).params(self._create_values(constraint['values'])).update({
'anytext': func.get_anytext(getattr(
self.dataset, self.context.md_core_model['mappings']['pycsw:XML']))
}, synchronize_session='fetch')
self.session.commit()
return rows
except Exception as err:
self.session.rollback()
msg = 'Cannot commit to repository'
LOGGER.exception(msg)
raise RuntimeError(msg) from err | [
"def",
"update",
"(",
"self",
",",
"record",
"=",
"None",
",",
"recprops",
"=",
"None",
",",
"constraint",
"=",
"None",
")",
":",
"if",
"record",
"is",
"not",
"None",
":",
"identifier",
"=",
"getattr",
"(",
"record",
",",
"self",
".",
"context",
".",... | https://github.com/geopython/pycsw/blob/43a5c92fa819a3a3fdc8a8e3ef075d784dff73fc/pycsw/core/repository.py#L341-L406 | ||
FSecureLABS/drozer | df11e6e63fbaefa9b58ed1e42533ddf76241d7e1 | src/mwr/common/argparse_completer.py | python | ArgumentParserCompleter.get_suggestions | (self, text, line, begidx, endidx, offs=0) | return suggestions | readline should immediately defer to get_suggestions() when its completer is
invoked. get_suggestions() accepts the arguments available to readline at
this point, and converts them into a list() of suggestions. | readline should immediately defer to get_suggestions() when its completer is
invoked. get_suggestions() accepts the arguments available to readline at
this point, and converts them into a list() of suggestions. | [
"readline",
"should",
"immediately",
"defer",
"to",
"get_suggestions",
"()",
"when",
"its",
"completer",
"is",
"invoked",
".",
"get_suggestions",
"()",
"accepts",
"the",
"arguments",
"available",
"to",
"readline",
"at",
"this",
"point",
"and",
"converts",
"them",
... | def get_suggestions(self, text, line, begidx, endidx, offs=0):
"""
readline should immediately defer to get_suggestions() when its completer is
invoked. get_suggestions() accepts the arguments available to readline at
this point, and converts them into a list() of suggestions.
"""
real_offset, text, words, word = self.__get_additional_metadata(text, line, begidx, endidx)
suggestions = []
pos_actions = self.__get_positional_actions()
offset = word - offs
if pos_actions is not None and (offset < len(pos_actions)):
suggestions.extend(filter(lambda s: s.startswith(text), self.__get_suggestions_for(self.__get_positional_action(offset), text, line)))
else:
offer_flags = True
# find the last option flag in the line, if there was one
flag, value_index = self.__get_flag_metadata(words, word)
# if we found a previous flag, we try to offer suggestions for it
if flag != None:
action = self.__get_action(flag)
if action != None:
_suggestions, offer_flags = self.__offer_action_suggestions(action, value_index, text, line)
suggestions.extend(filter(lambda s: s.startswith(text), _suggestions))
# if we could be trying to type an option flag, add them to the
# suggestions
if offer_flags:
suggestions.extend(map(lambda os: os[begidx-real_offset:], filter(lambda s: s.startswith(text), self.__offer_flag_suggestions())))
return suggestions | [
"def",
"get_suggestions",
"(",
"self",
",",
"text",
",",
"line",
",",
"begidx",
",",
"endidx",
",",
"offs",
"=",
"0",
")",
":",
"real_offset",
",",
"text",
",",
"words",
",",
"word",
"=",
"self",
".",
"__get_additional_metadata",
"(",
"text",
",",
"lin... | https://github.com/FSecureLABS/drozer/blob/df11e6e63fbaefa9b58ed1e42533ddf76241d7e1/src/mwr/common/argparse_completer.py#L20-L54 | |
fake-name/ReadableWebProxy | ed5c7abe38706acc2684a1e6cd80242a03c5f010 | WebMirror/management/rss_parser_funcs/feed_parse_extractSangriatranslationsWordpressCom.py | python | extractSangriatranslationsWordpressCom | (item) | return False | Parser for 'sangriatranslations.wordpress.com' | Parser for 'sangriatranslations.wordpress.com' | [
"Parser",
"for",
"sangriatranslations",
".",
"wordpress",
".",
"com"
] | def extractSangriatranslationsWordpressCom(item):
'''
Parser for 'sangriatranslations.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('novel: may I ask', 'May I Ask For One Final Thing?', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
if item['tags'] == ['Uncategorized']:
titlemap = [
('May I Ask For One Final Thing', 'May I Ask For One Final Thing?', 'translated'),
('May I Ask For One Final Thing?', 'May I Ask For One Final Thing?', 'translated'),
('Tensei Shoujo no Rirekisho', 'Tensei Shoujo no Rirekisho', 'translated'),
('Master of Dungeon', 'Master of Dungeon', 'oel'),
]
for titlecomponent, name, tl_type in titlemap:
if titlecomponent.lower() in item['title'].lower():
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False | [
"def",
"extractSangriatranslationsWordpressCom",
"(",
"item",
")",
":",
"vol",
",",
"chp",
",",
"frag",
",",
"postfix",
"=",
"extractVolChapterFragmentPostfix",
"(",
"item",
"[",
"'title'",
"]",
")",
"if",
"not",
"(",
"chp",
"or",
"vol",
")",
"or",
"\"previe... | https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractSangriatranslationsWordpressCom.py#L1-L33 | |
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/src/class/oc_clusterrole.py | python | OCClusterRole.clusterrole | (self, data) | setter function for clusterrole property | setter function for clusterrole property | [
"setter",
"function",
"for",
"clusterrole",
"property"
] | def clusterrole(self, data):
''' setter function for clusterrole property'''
self._clusterrole = data | [
"def",
"clusterrole",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_clusterrole",
"=",
"data"
] | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/src/class/oc_clusterrole.py#L30-L32 | ||
h2non/pook | d2970eff5ef7b611e786422145cff4f6d6df412e | pook/mock.py | python | Mock.file | (self, path) | return self | Reads the body to match from a disk file.
Arguments:
path (str): relative or absolute path to file to read from.
Returns:
self: current Mock instance. | Reads the body to match from a disk file. | [
"Reads",
"the",
"body",
"to",
"match",
"from",
"a",
"disk",
"file",
"."
] | def file(self, path):
"""
Reads the body to match from a disk file.
Arguments:
path (str): relative or absolute path to file to read from.
Returns:
self: current Mock instance.
"""
with open(path, 'r') as f:
self.body(str(f.read()))
return self | [
"def",
"file",
"(",
"self",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"self",
".",
"body",
"(",
"str",
"(",
"f",
".",
"read",
"(",
")",
")",
")",
"return",
"self"
] | https://github.com/h2non/pook/blob/d2970eff5ef7b611e786422145cff4f6d6df412e/pook/mock.py#L422-L434 | |
zedshaw/learn-more-python-the-hard-way-solutions | 7886c860f69d69739a41d6490b8dc3fa777f227b | ex24_urlrouter/dllist.py | python | DoubleLinkedList.push | (self, obj) | Appends a new value on the end of the list. | Appends a new value on the end of the list. | [
"Appends",
"a",
"new",
"value",
"on",
"the",
"end",
"of",
"the",
"list",
"."
] | def push(self, obj):
"""Appends a new value on the end of the list."""
# if there are contents
if self.end:
# new node with prev=end
node = DoubleLinkedListNode(obj, None, self.end)
# end.next = new node
self.end.next = node
# new end is node
self.end = node
# else begin and end are new node with none
else:
self.begin = DoubleLinkedListNode(obj, None, None)
self.end = self.begin | [
"def",
"push",
"(",
"self",
",",
"obj",
")",
":",
"# if there are contents",
"if",
"self",
".",
"end",
":",
"# new node with prev=end",
"node",
"=",
"DoubleLinkedListNode",
"(",
"obj",
",",
"None",
",",
"self",
".",
"end",
")",
"# end.next = new node",
"self",... | https://github.com/zedshaw/learn-more-python-the-hard-way-solutions/blob/7886c860f69d69739a41d6490b8dc3fa777f227b/ex24_urlrouter/dllist.py#L19-L32 | ||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/numato/switch.py | python | NumatoGpioSwitch.name | (self) | return self._name | Return the name of the switch. | Return the name of the switch. | [
"Return",
"the",
"name",
"of",
"the",
"switch",
"."
] | def name(self):
"""Return the name of the switch."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/numato/switch.py#L80-L82 | |
rgalanakis/goless | 3611103a52982d475ae24afe66177ba702080c45 | write_benchresults.py | python | collect_results | () | return results | Runs all platforms/backends/benchmarks and returns as list of
BenchmarkResults, sorted by benchmark and time taken. | Runs all platforms/backends/benchmarks and returns as list of
BenchmarkResults, sorted by benchmark and time taken. | [
"Runs",
"all",
"platforms",
"/",
"backends",
"/",
"benchmarks",
"and",
"returns",
"as",
"list",
"of",
"BenchmarkResults",
"sorted",
"by",
"benchmark",
"and",
"time",
"taken",
"."
] | def collect_results():
"""Runs all platforms/backends/benchmarks and returns as list of
BenchmarkResults, sorted by benchmark and time taken.
"""
results = []
for exe, backendname in EXE_BACKEND_MATRIX:
results.extend(benchmark_process_and_backend(exe, backendname))
results.extend(benchmark_go())
results.sort(
key=lambda br: (br.benchmark, float(br.time), br.platform, br.backend))
return results | [
"def",
"collect_results",
"(",
")",
":",
"results",
"=",
"[",
"]",
"for",
"exe",
",",
"backendname",
"in",
"EXE_BACKEND_MATRIX",
":",
"results",
".",
"extend",
"(",
"benchmark_process_and_backend",
"(",
"exe",
",",
"backendname",
")",
")",
"results",
".",
"e... | https://github.com/rgalanakis/goless/blob/3611103a52982d475ae24afe66177ba702080c45/write_benchresults.py#L72-L83 | |
AirBernard/Scene-Text-Detection-with-SPCNET | 9c197525bf05fb46e7523d0dc98ea0339ddbff9c | nets/model.py | python | generate_all_anchors | (fpn_shapes, image_shape, config) | return batch_anchors | generate anchor for pyramid feature maps | generate anchor for pyramid feature maps | [
"generate",
"anchor",
"for",
"pyramid",
"feature",
"maps"
] | def generate_all_anchors(fpn_shapes, image_shape, config):
'''
generate anchor for pyramid feature maps
'''
anchors = utils.generate_pyramid_anchors(config.RPN_ANCHOR_SCALES, \
config.RPN_ANCHOR_RATIOS, \
fpn_shapes, \
config.BACKBONE_STRIDES, \
config.RPN_ANCHOR_STRIDE)
# normalize coordinates
# numpy array [N, 4]
norm_anchors = utils.norm_boxes(anchors, image_shape)
anchors_tensor = tf.convert_to_tensor(norm_anchors)
# Duplicate across the batch dimension
batch_anchors = tf.broadcast_to(anchors_tensor,\
[config.IMAGES_PER_GPU, tf.shape(anchors_tensor)[0],tf.shape(anchors_tensor)[1]])
return batch_anchors | [
"def",
"generate_all_anchors",
"(",
"fpn_shapes",
",",
"image_shape",
",",
"config",
")",
":",
"anchors",
"=",
"utils",
".",
"generate_pyramid_anchors",
"(",
"config",
".",
"RPN_ANCHOR_SCALES",
",",
"config",
".",
"RPN_ANCHOR_RATIOS",
",",
"fpn_shapes",
",",
"conf... | https://github.com/AirBernard/Scene-Text-Detection-with-SPCNET/blob/9c197525bf05fb46e7523d0dc98ea0339ddbff9c/nets/model.py#L312-L328 | |
CedricGuillemet/Imogen | ee417b42747ed5b46cb11b02ef0c3630000085b3 | bin/Lib/logging/config.py | python | _create_formatters | (cp) | return formatters | Create and return formatters | Create and return formatters | [
"Create",
"and",
"return",
"formatters"
] | def _create_formatters(cp):
"""Create and return formatters"""
flist = cp["formatters"]["keys"]
if not len(flist):
return {}
flist = flist.split(",")
flist = _strip_spaces(flist)
formatters = {}
for form in flist:
sectname = "formatter_%s" % form
fs = cp.get(sectname, "format", raw=True, fallback=None)
dfs = cp.get(sectname, "datefmt", raw=True, fallback=None)
stl = cp.get(sectname, "style", raw=True, fallback='%')
c = logging.Formatter
class_name = cp[sectname].get("class")
if class_name:
c = _resolve(class_name)
f = c(fs, dfs, stl)
formatters[form] = f
return formatters | [
"def",
"_create_formatters",
"(",
"cp",
")",
":",
"flist",
"=",
"cp",
"[",
"\"formatters\"",
"]",
"[",
"\"keys\"",
"]",
"if",
"not",
"len",
"(",
"flist",
")",
":",
"return",
"{",
"}",
"flist",
"=",
"flist",
".",
"split",
"(",
"\",\"",
")",
"flist",
... | https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/logging/config.py#L102-L121 | |
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/CPython/27/Lib/imaplib.py | python | IMAP4.getacl | (self, mailbox) | return self._untagged_response(typ, dat, 'ACL') | Get the ACLs for a mailbox.
(typ, [data]) = <instance>.getacl(mailbox) | Get the ACLs for a mailbox. | [
"Get",
"the",
"ACLs",
"for",
"a",
"mailbox",
"."
] | def getacl(self, mailbox):
"""Get the ACLs for a mailbox.
(typ, [data]) = <instance>.getacl(mailbox)
"""
typ, dat = self._simple_command('GETACL', mailbox)
return self._untagged_response(typ, dat, 'ACL') | [
"def",
"getacl",
"(",
"self",
",",
"mailbox",
")",
":",
"typ",
",",
"dat",
"=",
"self",
".",
"_simple_command",
"(",
"'GETACL'",
",",
"mailbox",
")",
"return",
"self",
".",
"_untagged_response",
"(",
"typ",
",",
"dat",
",",
"'ACL'",
")"
] | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/imaplib.py#L447-L453 | |
PySimpleGUI/PySimpleGUI | 6c0d1fb54f493d45e90180b322fbbe70f7a5af3c | PySimpleGUIQt/PySimpleGUIQt.py | python | Window.BringToFront | (self) | [] | def BringToFront(self):
if not self._is_window_created():
return
self.QTMainWindow.activateWindow(self.QT_QMainWindow)
self.QTMainWindow.raise_(self.QT_QMainWindow) | [
"def",
"BringToFront",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_is_window_created",
"(",
")",
":",
"return",
"self",
".",
"QTMainWindow",
".",
"activateWindow",
"(",
"self",
".",
"QT_QMainWindow",
")",
"self",
".",
"QTMainWindow",
".",
"raise_",
... | https://github.com/PySimpleGUI/PySimpleGUI/blob/6c0d1fb54f493d45e90180b322fbbe70f7a5af3c/PySimpleGUIQt/PySimpleGUIQt.py#L4659-L4663 | ||||
rwth-i6/returnn | f2d718a197a280b0d5f0fd91a7fcb8658560dddb | returnn/tf/updater.py | python | WrapOptimizer.create_all_needed_optimizers | (self, train_vars) | :param list[tf.Variable] train_vars: | :param list[tf.Variable] train_vars: | [
":",
"param",
"list",
"[",
"tf",
".",
"Variable",
"]",
"train_vars",
":"
] | def create_all_needed_optimizers(self, train_vars):
"""
:param list[tf.Variable] train_vars:
"""
for var in train_vars:
self._get_optimizer_item_for_variable(var, auto_create_new=True) | [
"def",
"create_all_needed_optimizers",
"(",
"self",
",",
"train_vars",
")",
":",
"for",
"var",
"in",
"train_vars",
":",
"self",
".",
"_get_optimizer_item_for_variable",
"(",
"var",
",",
"auto_create_new",
"=",
"True",
")"
] | https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/tf/updater.py#L466-L471 | ||
chribsen/simple-machine-learning-examples | dc94e52a4cebdc8bb959ff88b81ff8cfeca25022 | venv/lib/python2.7/site-packages/pandas/sparse/series.py | python | SparseSeries.__iter__ | (self) | return iter(self.values) | forward to the array | forward to the array | [
"forward",
"to",
"the",
"array"
] | def __iter__(self):
""" forward to the array """
return iter(self.values) | [
"def",
"__iter__",
"(",
"self",
")",
":",
"return",
"iter",
"(",
"self",
".",
"values",
")"
] | https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pandas/sparse/series.py#L362-L364 | |
eirannejad/pyRevit | 49c0b7eb54eb343458ce1365425e6552d0c47d44 | extensions/pyRevitCore.extension/pyRevit.tab/pyRevit.panel/Settings.smartbutton/script.py | python | SettingsWindow.save_settings | (self, sender, args) | Callback method for saving pyRevit settings | Callback method for saving pyRevit settings | [
"Callback",
"method",
"for",
"saving",
"pyRevit",
"settings"
] | def save_settings(self, sender, args):
"""Callback method for saving pyRevit settings"""
self.reload_requested = \
self._save_core_options() or self.reload_requested
self.reload_requested = \
self._save_engines() or self.reload_requested
self.reload_requested = \
self._save_user_extensions_list() or self.reload_requested
self.reload_requested = \
self._save_uiux() or self.reload_requested
self.reload_requested = \
self._save_routes() or self.reload_requested
self.reload_requested = \
self._save_telemetry() or self.reload_requested
# save all new values into config file
user_config.save_changes()
# update addin files
self.update_addinfiles()
self.Close()
# if reload requested by any of the save methods, then reload
if self.reload_requested:
self._reload() | [
"def",
"save_settings",
"(",
"self",
",",
"sender",
",",
"args",
")",
":",
"self",
".",
"reload_requested",
"=",
"self",
".",
"_save_core_options",
"(",
")",
"or",
"self",
".",
"reload_requested",
"self",
".",
"reload_requested",
"=",
"self",
".",
"_save_eng... | https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/extensions/pyRevitCore.extension/pyRevit.tab/pyRevit.panel/Settings.smartbutton/script.py#L960-L983 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.