repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
oceanprotocol/squid-py | squid_py/ddo/service.py | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/service.py#L134-L151 | def as_dictionary(self):
"""Return the service as a python dictionary."""
values = {
'type': self._type,
self.SERVICE_ENDPOINT: self._service_endpoint,
}
if self._consume_endpoint is not None:
values[self.CONSUME_ENDPOINT] = self._consume_endpoint
... | [
"def",
"as_dictionary",
"(",
"self",
")",
":",
"values",
"=",
"{",
"'type'",
":",
"self",
".",
"_type",
",",
"self",
".",
"SERVICE_ENDPOINT",
":",
"self",
".",
"_service_endpoint",
",",
"}",
"if",
"self",
".",
"_consume_endpoint",
"is",
"not",
"None",
":... | Return the service as a python dictionary. | [
"Return",
"the",
"service",
"as",
"a",
"python",
"dictionary",
"."
] | python | train |
INM-6/hybridLFPy | examples/Hagen_et_al_2016_cercor/plotting_helpers.py | https://github.com/INM-6/hybridLFPy/blob/c38bdf38982c4624c2f70caeb50c40f1d5980abd/examples/Hagen_et_al_2016_cercor/plotting_helpers.py#L42-L46 | def empty_bar_plot(ax):
''' Delete all axis ticks and labels '''
plt.sca(ax)
plt.setp(plt.gca(),xticks=[],xticklabels=[])
return ax | [
"def",
"empty_bar_plot",
"(",
"ax",
")",
":",
"plt",
".",
"sca",
"(",
"ax",
")",
"plt",
".",
"setp",
"(",
"plt",
".",
"gca",
"(",
")",
",",
"xticks",
"=",
"[",
"]",
",",
"xticklabels",
"=",
"[",
"]",
")",
"return",
"ax"
] | Delete all axis ticks and labels | [
"Delete",
"all",
"axis",
"ticks",
"and",
"labels"
] | python | train |
globocom/GloboNetworkAPI-client-python | networkapiclient/Ambiente.py | https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/Ambiente.py#L888-L911 | def get_all_rules(self, id_env):
"""Save an environment rule
:param id_env: Environment id
:return: Estrutura:
::
{ 'rules': [{'id': < id >,
'environment': < Environment Object >,
'content': < content >,
'name': < name >,
'c... | [
"def",
"get_all_rules",
"(",
"self",
",",
"id_env",
")",
":",
"url",
"=",
"'rule/all/'",
"+",
"str",
"(",
"id_env",
")",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"None",
",",
"'GET'",
",",
"url",
")",
"return",
"self",
".",
"response",
... | Save an environment rule
:param id_env: Environment id
:return: Estrutura:
::
{ 'rules': [{'id': < id >,
'environment': < Environment Object >,
'content': < content >,
'name': < name >,
'custom': < custom > },... ]}
:raise ... | [
"Save",
"an",
"environment",
"rule"
] | python | train |
wakatime/wakatime | wakatime/stats.py | https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/stats.py#L349-L372 | def customize_lexer_priority(file_name, accuracy, lexer):
"""Customize lexer priority"""
priority = lexer.priority
lexer_name = lexer.name.lower().replace('sharp', '#')
if lexer_name in LANGUAGES:
priority = LANGUAGES[lexer_name]
elif lexer_name == 'matlab':
available_extensions = ... | [
"def",
"customize_lexer_priority",
"(",
"file_name",
",",
"accuracy",
",",
"lexer",
")",
":",
"priority",
"=",
"lexer",
".",
"priority",
"lexer_name",
"=",
"lexer",
".",
"name",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'sharp'",
",",
"'#'",
")",
"if... | Customize lexer priority | [
"Customize",
"lexer",
"priority"
] | python | train |
grycap/RADL | radl/radl.py | https://github.com/grycap/RADL/blob/03ccabb0313a48a5aa0e20c1f7983fddcb95e9cb/radl/radl.py#L312-L316 | def hasFeature(self, prop, check_softs=False):
"""Return if there is a property with that name."""
return prop in self.props or (check_softs and
any([fs.hasFeature(prop) for fs in self.props.get(SoftFeatures.SOFT, [])])) | [
"def",
"hasFeature",
"(",
"self",
",",
"prop",
",",
"check_softs",
"=",
"False",
")",
":",
"return",
"prop",
"in",
"self",
".",
"props",
"or",
"(",
"check_softs",
"and",
"any",
"(",
"[",
"fs",
".",
"hasFeature",
"(",
"prop",
")",
"for",
"fs",
"in",
... | Return if there is a property with that name. | [
"Return",
"if",
"there",
"is",
"a",
"property",
"with",
"that",
"name",
"."
] | python | train |
PMEAL/porespy | porespy/visualization/__plots__.py | https://github.com/PMEAL/porespy/blob/1e13875b56787d8f5b7ffdabce8c4342c33ba9f8/porespy/visualization/__plots__.py#L6-L40 | def show_mesh(mesh):
r"""
Visualizes the mesh of a region as obtained by ``get_mesh`` function in
the ``metrics`` submodule.
Parameters
----------
mesh : tuple
A mesh returned by ``skimage.measure.marching_cubes``
Returns
-------
fig : Matplotlib figure
A handle to ... | [
"def",
"show_mesh",
"(",
"mesh",
")",
":",
"lim_max",
"=",
"sp",
".",
"amax",
"(",
"mesh",
".",
"verts",
",",
"axis",
"=",
"0",
")",
"lim_min",
"=",
"sp",
".",
"amin",
"(",
"mesh",
".",
"verts",
",",
"axis",
"=",
"0",
")",
"# Display resulting tria... | r"""
Visualizes the mesh of a region as obtained by ``get_mesh`` function in
the ``metrics`` submodule.
Parameters
----------
mesh : tuple
A mesh returned by ``skimage.measure.marching_cubes``
Returns
-------
fig : Matplotlib figure
A handle to a matplotlib 3D axis | [
"r",
"Visualizes",
"the",
"mesh",
"of",
"a",
"region",
"as",
"obtained",
"by",
"get_mesh",
"function",
"in",
"the",
"metrics",
"submodule",
"."
] | python | train |
ssato/python-anyconfig | src/anyconfig/backend/ini.py | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/ini.py#L152-L165 | def _dumps_itr(cnf, dkey=DEFAULTSECT):
"""
:param cnf: Configuration data to dump
"""
for sect, params in iteritems(cnf):
yield "[%s]" % sect
for key, val in iteritems(params):
if sect != dkey and dkey in cnf and cnf[dkey].get(key) == val:
continue # It shou... | [
"def",
"_dumps_itr",
"(",
"cnf",
",",
"dkey",
"=",
"DEFAULTSECT",
")",
":",
"for",
"sect",
",",
"params",
"in",
"iteritems",
"(",
"cnf",
")",
":",
"yield",
"\"[%s]\"",
"%",
"sect",
"for",
"key",
",",
"val",
"in",
"iteritems",
"(",
"params",
")",
":",... | :param cnf: Configuration data to dump | [
":",
"param",
"cnf",
":",
"Configuration",
"data",
"to",
"dump"
] | python | train |
saltstack/salt | salt/modules/virt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L685-L706 | def _gen_net_xml(name,
bridge,
forward,
vport,
tag=None):
'''
Generate the XML string to define a libvirt network
'''
context = {
'name': name,
'bridge': bridge,
'forward': forward,
'vport': vport,
... | [
"def",
"_gen_net_xml",
"(",
"name",
",",
"bridge",
",",
"forward",
",",
"vport",
",",
"tag",
"=",
"None",
")",
":",
"context",
"=",
"{",
"'name'",
":",
"name",
",",
"'bridge'",
":",
"bridge",
",",
"'forward'",
":",
"forward",
",",
"'vport'",
":",
"vp... | Generate the XML string to define a libvirt network | [
"Generate",
"the",
"XML",
"string",
"to",
"define",
"a",
"libvirt",
"network"
] | python | train |
shymonk/django-datatable | table/views.py | https://github.com/shymonk/django-datatable/blob/f20a6ed2ce31aa7488ff85b4b0e80fe1ad94ec44/table/views.py#L119-L149 | def get_context_data(self, **kwargs):
"""
Get context data for datatable server-side response.
See http://www.datatables.net/usage/server-side
"""
sEcho = self.query_data["sEcho"]
context = super(BaseListView, self).get_context_data(**kwargs)
queryset = context["... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"sEcho",
"=",
"self",
".",
"query_data",
"[",
"\"sEcho\"",
"]",
"context",
"=",
"super",
"(",
"BaseListView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
... | Get context data for datatable server-side response.
See http://www.datatables.net/usage/server-side | [
"Get",
"context",
"data",
"for",
"datatable",
"server",
"-",
"side",
"response",
".",
"See",
"http",
":",
"//",
"www",
".",
"datatables",
".",
"net",
"/",
"usage",
"/",
"server",
"-",
"side"
] | python | valid |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/segments.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/segments.py#L504-L517 | def has_segment_tables(xmldoc, name = None):
"""
Return True if the document contains a complete set of segment
tables. Returns False otherwise. If name is given and not None
then the return value is True only if the document's segment
tables, if present, contain a segment list by that name.
"""
try:
names =... | [
"def",
"has_segment_tables",
"(",
"xmldoc",
",",
"name",
"=",
"None",
")",
":",
"try",
":",
"names",
"=",
"lsctables",
".",
"SegmentDefTable",
".",
"get_table",
"(",
"xmldoc",
")",
".",
"getColumnByName",
"(",
"\"name\"",
")",
"lsctables",
".",
"SegmentTable... | Return True if the document contains a complete set of segment
tables. Returns False otherwise. If name is given and not None
then the return value is True only if the document's segment
tables, if present, contain a segment list by that name. | [
"Return",
"True",
"if",
"the",
"document",
"contains",
"a",
"complete",
"set",
"of",
"segment",
"tables",
".",
"Returns",
"False",
"otherwise",
".",
"If",
"name",
"is",
"given",
"and",
"not",
"None",
"then",
"the",
"return",
"value",
"is",
"True",
"only",
... | python | train |
EpistasisLab/tpot | tpot/builtins/feature_set_selector.py | https://github.com/EpistasisLab/tpot/blob/b626271e6b5896a73fb9d7d29bebc7aa9100772e/tpot/builtins/feature_set_selector.py#L66-L114 | def fit(self, X, y=None):
"""Fit FeatureSetSelector for feature selection
Parameters
----------
X: array-like of shape (n_samples, n_features)
The training input samples.
y: array-like, shape (n_samples,)
The target values (integers that correspond to cla... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"subset_df",
"=",
"pd",
".",
"read_csv",
"(",
"self",
".",
"subset_list",
",",
"header",
"=",
"0",
",",
"index_col",
"=",
"0",
")",
"if",
"isinstance",
"(",
"self",
".",
"sel_s... | Fit FeatureSetSelector for feature selection
Parameters
----------
X: array-like of shape (n_samples, n_features)
The training input samples.
y: array-like, shape (n_samples,)
The target values (integers that correspond to classes in classification, real numbers ... | [
"Fit",
"FeatureSetSelector",
"for",
"feature",
"selection"
] | python | train |
log2timeline/plaso | plaso/storage/interface.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/storage/interface.py#L1683-L1701 | def ReadPreprocessingInformation(self, knowledge_base):
"""Reads preprocessing information.
The preprocessing information contains the system configuration which
contains information about various system specific configuration data,
for example the user accounts.
Args:
knowledge_base (Knowle... | [
"def",
"ReadPreprocessingInformation",
"(",
"self",
",",
"knowledge_base",
")",
":",
"if",
"not",
"self",
".",
"_storage_file",
":",
"raise",
"IOError",
"(",
"'Unable to read from closed storage writer.'",
")",
"self",
".",
"_storage_file",
".",
"ReadPreprocessingInform... | Reads preprocessing information.
The preprocessing information contains the system configuration which
contains information about various system specific configuration data,
for example the user accounts.
Args:
knowledge_base (KnowledgeBase): is used to store the preprocessing
informat... | [
"Reads",
"preprocessing",
"information",
"."
] | python | train |
apache/spark | python/pyspark/sql/context.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/context.py#L194-L203 | def registerJavaFunction(self, name, javaClassName, returnType=None):
"""An alias for :func:`spark.udf.registerJavaFunction`.
See :meth:`pyspark.sql.UDFRegistration.registerJavaFunction`.
.. note:: Deprecated in 2.3.0. Use :func:`spark.udf.registerJavaFunction` instead.
"""
warn... | [
"def",
"registerJavaFunction",
"(",
"self",
",",
"name",
",",
"javaClassName",
",",
"returnType",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Deprecated in 2.3.0. Use spark.udf.registerJavaFunction instead.\"",
",",
"DeprecationWarning",
")",
"return",
"self... | An alias for :func:`spark.udf.registerJavaFunction`.
See :meth:`pyspark.sql.UDFRegistration.registerJavaFunction`.
.. note:: Deprecated in 2.3.0. Use :func:`spark.udf.registerJavaFunction` instead. | [
"An",
"alias",
"for",
":",
"func",
":",
"spark",
".",
"udf",
".",
"registerJavaFunction",
".",
"See",
":",
"meth",
":",
"pyspark",
".",
"sql",
".",
"UDFRegistration",
".",
"registerJavaFunction",
"."
] | python | train |
b3j0f/utils | b3j0f/utils/runtime.py | https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/runtime.py#L279-L309 | def getcodeobj(consts, intcode, newcodeobj, oldcodeobj):
"""Get code object from decompiled code.
:param list consts: constants to add in the result.
:param list intcode: list of byte code to use.
:param newcodeobj: new code object with empty body.
:param oldcodeobj: old code object.
:return: n... | [
"def",
"getcodeobj",
"(",
"consts",
",",
"intcode",
",",
"newcodeobj",
",",
"oldcodeobj",
")",
":",
"# get code string",
"if",
"PY3",
":",
"codestr",
"=",
"bytes",
"(",
"intcode",
")",
"else",
":",
"codestr",
"=",
"reduce",
"(",
"lambda",
"x",
",",
"y",
... | Get code object from decompiled code.
:param list consts: constants to add in the result.
:param list intcode: list of byte code to use.
:param newcodeobj: new code object with empty body.
:param oldcodeobj: old code object.
:return: new code object to produce. | [
"Get",
"code",
"object",
"from",
"decompiled",
"code",
"."
] | python | train |
allenai/allennlp | allennlp/semparse/domain_languages/nlvr_language.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/nlvr_language.py#L357-L367 | def bottom(self, objects: Set[Object]) -> Set[Object]:
"""
Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for
each box.
"""
objects_per_box = self._separate_objects_by_boxes(objects)
return_set: Set[Object] = set()
for _, box... | [
"def",
"bottom",
"(",
"self",
",",
"objects",
":",
"Set",
"[",
"Object",
"]",
")",
"->",
"Set",
"[",
"Object",
"]",
":",
"objects_per_box",
"=",
"self",
".",
"_separate_objects_by_boxes",
"(",
"objects",
")",
"return_set",
":",
"Set",
"[",
"Object",
"]",... | Return the bottom most objects(i.e. maximum y_loc). The comparison is done separately for
each box. | [
"Return",
"the",
"bottom",
"most",
"objects",
"(",
"i",
".",
"e",
".",
"maximum",
"y_loc",
")",
".",
"The",
"comparison",
"is",
"done",
"separately",
"for",
"each",
"box",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1452-L1522 | def _delete_port_channel_resources(self, host_id, switch_ip,
intf_type, nexus_port, port_id):
'''This determines if port channel id needs to be freed.'''
# if this connection is not a port-channel, nothing to do.
if intf_type != 'port-channel':
... | [
"def",
"_delete_port_channel_resources",
"(",
"self",
",",
"host_id",
",",
"switch_ip",
",",
"intf_type",
",",
"nexus_port",
",",
"port_id",
")",
":",
"# if this connection is not a port-channel, nothing to do.",
"if",
"intf_type",
"!=",
"'port-channel'",
":",
"return",
... | This determines if port channel id needs to be freed. | [
"This",
"determines",
"if",
"port",
"channel",
"id",
"needs",
"to",
"be",
"freed",
"."
] | python | train |
bibanon/BASC-py4chan | basc_py4chan/board.py | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L145-L158 | def thread_exists(self, thread_id):
"""Check if a thread exists or has 404'd.
Args:
thread_id (int): Thread ID
Returns:
bool: Whether the given thread exists on this board.
"""
return self._requests_session.head(
self._url.thread_api_url(
... | [
"def",
"thread_exists",
"(",
"self",
",",
"thread_id",
")",
":",
"return",
"self",
".",
"_requests_session",
".",
"head",
"(",
"self",
".",
"_url",
".",
"thread_api_url",
"(",
"thread_id",
"=",
"thread_id",
")",
")",
".",
"ok"
] | Check if a thread exists or has 404'd.
Args:
thread_id (int): Thread ID
Returns:
bool: Whether the given thread exists on this board. | [
"Check",
"if",
"a",
"thread",
"exists",
"or",
"has",
"404",
"d",
"."
] | python | train |
FelixSchwarz/pymta | pymta/command_parser.py | https://github.com/FelixSchwarz/pymta/blob/1884accc3311e6c2e89259784f9592314f6d34fc/pymta/command_parser.py#L92-L98 | def multiline_push(self, code, lines):
"""Send a multi-message to the peer (using the correct SMTP line
terminators (usually only called from the SMTPSession)."""
for line in lines[:-1]:
answer = '%s-%s' % (code, line)
self.push(answer)
self.push(code, lines[-1]) | [
"def",
"multiline_push",
"(",
"self",
",",
"code",
",",
"lines",
")",
":",
"for",
"line",
"in",
"lines",
"[",
":",
"-",
"1",
"]",
":",
"answer",
"=",
"'%s-%s'",
"%",
"(",
"code",
",",
"line",
")",
"self",
".",
"push",
"(",
"answer",
")",
"self",
... | Send a multi-message to the peer (using the correct SMTP line
terminators (usually only called from the SMTPSession). | [
"Send",
"a",
"multi",
"-",
"message",
"to",
"the",
"peer",
"(",
"using",
"the",
"correct",
"SMTP",
"line",
"terminators",
"(",
"usually",
"only",
"called",
"from",
"the",
"SMTPSession",
")",
"."
] | python | train |
metachris/logzero | logzero/__init__.py | https://github.com/metachris/logzero/blob/b5d49fc2b118c370994c4ae5360d7c246d43ddc8/logzero/__init__.py#L320-L331 | def reset_default_logger():
"""
Resets the internal default logger to the initial configuration
"""
global logger
global _loglevel
global _logfile
global _formatter
_loglevel = logging.DEBUG
_logfile = None
_formatter = None
logger = setup_logger(name=LOGZERO_DEFAULT_LOGGER, ... | [
"def",
"reset_default_logger",
"(",
")",
":",
"global",
"logger",
"global",
"_loglevel",
"global",
"_logfile",
"global",
"_formatter",
"_loglevel",
"=",
"logging",
".",
"DEBUG",
"_logfile",
"=",
"None",
"_formatter",
"=",
"None",
"logger",
"=",
"setup_logger",
"... | Resets the internal default logger to the initial configuration | [
"Resets",
"the",
"internal",
"default",
"logger",
"to",
"the",
"initial",
"configuration"
] | python | train |
evhub/coconut | coconut/compiler/matching.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/matching.py#L549-L555 | def match_set(self, tokens, item):
"""Matches a set."""
match, = tokens
self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Set)")
self.add_check("_coconut.len(" + item + ") == " + str(len(match)))
for const in match:
self.add_check(const + " in " + item) | [
"def",
"match_set",
"(",
"self",
",",
"tokens",
",",
"item",
")",
":",
"match",
",",
"=",
"tokens",
"self",
".",
"add_check",
"(",
"\"_coconut.isinstance(\"",
"+",
"item",
"+",
"\", _coconut.abc.Set)\"",
")",
"self",
".",
"add_check",
"(",
"\"_coconut.len(\"",... | Matches a set. | [
"Matches",
"a",
"set",
"."
] | python | train |
hiposfer/o2g | o2g/gtfs/gtfs_dummy.py | https://github.com/hiposfer/o2g/blob/1165ba75a5eb64b3091e9b71ebd589507ae1ebf3/o2g/gtfs/gtfs_dummy.py#L14-L39 | def create_dummy_data(routes, stops):
"""Create `calendar`, `stop_times`, `trips` and `shapes`.
:return: DummyData namedtuple
"""
# Build stops per route auxiliary map
stops_per_route = defaultdict(lambda: [])
stops_map = {}
for s in stops:
if not s.route_id:
continue
... | [
"def",
"create_dummy_data",
"(",
"routes",
",",
"stops",
")",
":",
"# Build stops per route auxiliary map",
"stops_per_route",
"=",
"defaultdict",
"(",
"lambda",
":",
"[",
"]",
")",
"stops_map",
"=",
"{",
"}",
"for",
"s",
"in",
"stops",
":",
"if",
"not",
"s"... | Create `calendar`, `stop_times`, `trips` and `shapes`.
:return: DummyData namedtuple | [
"Create",
"calendar",
"stop_times",
"trips",
"and",
"shapes",
"."
] | python | test |
JensRantil/rewind | rewind/server/eventstores.py | https://github.com/JensRantil/rewind/blob/7f645d20186c1db55cfe53a0310c9fd6292f91ea/rewind/server/eventstores.py#L575-L589 | def add_event(self, key, event):
"""Add an event and its corresponding key to the store."""
assert isinstance(key, str)
assert isinstance(event, bytes)
if all([char.isalnum() or char == '-' for char in key]):
safe_key = key
else:
raise ValueError("Key must... | [
"def",
"add_event",
"(",
"self",
",",
"key",
",",
"event",
")",
":",
"assert",
"isinstance",
"(",
"key",
",",
"str",
")",
"assert",
"isinstance",
"(",
"event",
",",
"bytes",
")",
"if",
"all",
"(",
"[",
"char",
".",
"isalnum",
"(",
")",
"or",
"char"... | Add an event and its corresponding key to the store. | [
"Add",
"an",
"event",
"and",
"its",
"corresponding",
"key",
"to",
"the",
"store",
"."
] | python | train |
pywbem/pywbem | pywbem/cim_operations.py | https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/cim_operations.py#L2158-L2183 | def _iparam_namespace_from_objectname(self, objectname, arg_name):
# pylint: disable=invalid-name,
"""
Determine the namespace from an object name, that can be a class
name string, a CIMClassName or CIMInstanceName object, or `None`.
The default namespace of the connection object... | [
"def",
"_iparam_namespace_from_objectname",
"(",
"self",
",",
"objectname",
",",
"arg_name",
")",
":",
"# pylint: disable=invalid-name,",
"if",
"isinstance",
"(",
"objectname",
",",
"(",
"CIMClassName",
",",
"CIMInstanceName",
")",
")",
":",
"namespace",
"=",
"objec... | Determine the namespace from an object name, that can be a class
name string, a CIMClassName or CIMInstanceName object, or `None`.
The default namespace of the connection object is used, if needed.
Return the so determined namespace for use as an argument to
imethodcall(). | [
"Determine",
"the",
"namespace",
"from",
"an",
"object",
"name",
"that",
"can",
"be",
"a",
"class",
"name",
"string",
"a",
"CIMClassName",
"or",
"CIMInstanceName",
"object",
"or",
"None",
".",
"The",
"default",
"namespace",
"of",
"the",
"connection",
"object",... | python | train |
gwpy/gwpy | gwpy/io/mp.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/io/mp.py#L34-L106 | def read_multi(flatten, cls, source, *args, **kwargs):
"""Read sources into a `cls` with multiprocessing
This method should be called by `cls.read` and uses the `nproc`
keyword to enable and handle pool-based multiprocessing of
multiple source files, using `flatten` to combine the
chunked data into... | [
"def",
"read_multi",
"(",
"flatten",
",",
"cls",
",",
"source",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"verbose",
"=",
"kwargs",
".",
"pop",
"(",
"'verbose'",
",",
"False",
")",
"# parse input as a list of files",
"try",
":",
"# try and map t... | Read sources into a `cls` with multiprocessing
This method should be called by `cls.read` and uses the `nproc`
keyword to enable and handle pool-based multiprocessing of
multiple source files, using `flatten` to combine the
chunked data into a single object of the correct type.
Parameters
----... | [
"Read",
"sources",
"into",
"a",
"cls",
"with",
"multiprocessing"
] | python | train |
nanoporetech/ont_fast5_api | ont_fast5_api/fast5_file.py | https://github.com/nanoporetech/ont_fast5_api/blob/352b3903155fcf4f19234c4f429dcefaa6d6bc4a/ont_fast5_api/fast5_file.py#L706-L714 | def _add_group(self, group, attrs):
"""
:param group: group_name
:param attrs:
:return:
"""
self.handle.create_group(group)
if attrs is not None:
self._add_attributes(group, attrs) | [
"def",
"_add_group",
"(",
"self",
",",
"group",
",",
"attrs",
")",
":",
"self",
".",
"handle",
".",
"create_group",
"(",
"group",
")",
"if",
"attrs",
"is",
"not",
"None",
":",
"self",
".",
"_add_attributes",
"(",
"group",
",",
"attrs",
")"
] | :param group: group_name
:param attrs:
:return: | [
":",
"param",
"group",
":",
"group_name",
":",
"param",
"attrs",
":",
":",
"return",
":"
] | python | train |
mosdef-hub/mbuild | mbuild/formats/hoomdxml.py | https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/formats/hoomdxml.py#L311-L329 | def _write_rigid_information(xml_file, rigid_bodies):
"""Write rigid body information.
Parameters
----------
xml_file : file object
The file object of the hoomdxml file being written
rigid_bodies : list, len=n_particles
The rigid body that each particle belongs to (-1 for none)
... | [
"def",
"_write_rigid_information",
"(",
"xml_file",
",",
"rigid_bodies",
")",
":",
"if",
"not",
"all",
"(",
"body",
"is",
"None",
"for",
"body",
"in",
"rigid_bodies",
")",
":",
"xml_file",
".",
"write",
"(",
"'<body>\\n'",
")",
"for",
"body",
"in",
"rigid_... | Write rigid body information.
Parameters
----------
xml_file : file object
The file object of the hoomdxml file being written
rigid_bodies : list, len=n_particles
The rigid body that each particle belongs to (-1 for none) | [
"Write",
"rigid",
"body",
"information",
"."
] | python | train |
tcalmant/ipopo | pelix/ldapfilter.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L660-L704 | def _compute_comparator(string, idx):
# type: (str, int) -> Optional[Callable[[Any, Any], bool]]
"""
Tries to compute the LDAP comparator at the given index
Valid operators are :
* = : equality
* <= : less than
* >= : greater than
* ~= : approximate
:param string: A LDAP filter st... | [
"def",
"_compute_comparator",
"(",
"string",
",",
"idx",
")",
":",
"# type: (str, int) -> Optional[Callable[[Any, Any], bool]]",
"part1",
"=",
"string",
"[",
"idx",
"]",
"try",
":",
"part2",
"=",
"string",
"[",
"idx",
"+",
"1",
"]",
"except",
"IndexError",
":",
... | Tries to compute the LDAP comparator at the given index
Valid operators are :
* = : equality
* <= : less than
* >= : greater than
* ~= : approximate
:param string: A LDAP filter string
:param idx: An index in the given string
:return: The corresponding operator, None if unknown | [
"Tries",
"to",
"compute",
"the",
"LDAP",
"comparator",
"at",
"the",
"given",
"index"
] | python | train |
has2k1/plydata | plydata/types.py | https://github.com/has2k1/plydata/blob/d8ca85ff70eee621e96f7c74034e90fec16e8b61/plydata/types.py#L49-L61 | def group_indices(self):
"""
Return group indices
"""
# No groups
if not self.plydata_groups:
return np.ones(len(self), dtype=int)
grouper = self.groupby()
indices = np.empty(len(self), dtype=int)
for i, (_, idx) in enumerate(sorted(grouper.in... | [
"def",
"group_indices",
"(",
"self",
")",
":",
"# No groups",
"if",
"not",
"self",
".",
"plydata_groups",
":",
"return",
"np",
".",
"ones",
"(",
"len",
"(",
"self",
")",
",",
"dtype",
"=",
"int",
")",
"grouper",
"=",
"self",
".",
"groupby",
"(",
")",... | Return group indices | [
"Return",
"group",
"indices"
] | python | train |
pandas-dev/pandas | pandas/core/sparse/frame.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L951-L960 | def to_manager(sdf, columns, index):
""" create and return the block manager from a dataframe of series,
columns, index
"""
# from BlockManager perspective
axes = [ensure_index(columns), ensure_index(index)]
return create_block_manager_from_arrays(
[sdf[c] for c in columns], columns, a... | [
"def",
"to_manager",
"(",
"sdf",
",",
"columns",
",",
"index",
")",
":",
"# from BlockManager perspective",
"axes",
"=",
"[",
"ensure_index",
"(",
"columns",
")",
",",
"ensure_index",
"(",
"index",
")",
"]",
"return",
"create_block_manager_from_arrays",
"(",
"["... | create and return the block manager from a dataframe of series,
columns, index | [
"create",
"and",
"return",
"the",
"block",
"manager",
"from",
"a",
"dataframe",
"of",
"series",
"columns",
"index"
] | python | train |
saltstack/salt | salt/modules/win_lgpo.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_lgpo.py#L4553-L4568 | def _driver_signing_reg_reverse_conversion(cls, val, **kwargs):
'''
converts the string value seen in the GUI to the correct registry value
for secedit
'''
if val is not None:
if val.upper() == 'SILENTLY SUCCEED':
return ','.join(['3', '0'])
... | [
"def",
"_driver_signing_reg_reverse_conversion",
"(",
"cls",
",",
"val",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"val",
"is",
"not",
"None",
":",
"if",
"val",
".",
"upper",
"(",
")",
"==",
"'SILENTLY SUCCEED'",
":",
"return",
"','",
".",
"join",
"(",
... | converts the string value seen in the GUI to the correct registry value
for secedit | [
"converts",
"the",
"string",
"value",
"seen",
"in",
"the",
"GUI",
"to",
"the",
"correct",
"registry",
"value",
"for",
"secedit"
] | python | train |
scanny/python-pptx | pptx/parts/image.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/parts/image.py#L161-L179 | def from_file(cls, image_file):
"""
Return a new |Image| object loaded from *image_file*, which can be
either a path (string) or a file-like object.
"""
if is_string(image_file):
# treat image_file as a path
with open(image_file, 'rb') as f:
... | [
"def",
"from_file",
"(",
"cls",
",",
"image_file",
")",
":",
"if",
"is_string",
"(",
"image_file",
")",
":",
"# treat image_file as a path",
"with",
"open",
"(",
"image_file",
",",
"'rb'",
")",
"as",
"f",
":",
"blob",
"=",
"f",
".",
"read",
"(",
")",
"... | Return a new |Image| object loaded from *image_file*, which can be
either a path (string) or a file-like object. | [
"Return",
"a",
"new",
"|Image|",
"object",
"loaded",
"from",
"*",
"image_file",
"*",
"which",
"can",
"be",
"either",
"a",
"path",
"(",
"string",
")",
"or",
"a",
"file",
"-",
"like",
"object",
"."
] | python | train |
TrafficSenseMSD/SumoTools | sumolib/net/lane.py | https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/sumolib/net/lane.py#L70-L78 | def addJunctionPos(shape, fromPos, toPos):
"""Extends shape with the given positions in case they differ from the
existing endpoints. assumes that shape and positions have the same dimensionality"""
result = list(shape)
if fromPos != shape[0]:
result = [fromPos] + result
if toPos != shape[-1... | [
"def",
"addJunctionPos",
"(",
"shape",
",",
"fromPos",
",",
"toPos",
")",
":",
"result",
"=",
"list",
"(",
"shape",
")",
"if",
"fromPos",
"!=",
"shape",
"[",
"0",
"]",
":",
"result",
"=",
"[",
"fromPos",
"]",
"+",
"result",
"if",
"toPos",
"!=",
"sh... | Extends shape with the given positions in case they differ from the
existing endpoints. assumes that shape and positions have the same dimensionality | [
"Extends",
"shape",
"with",
"the",
"given",
"positions",
"in",
"case",
"they",
"differ",
"from",
"the",
"existing",
"endpoints",
".",
"assumes",
"that",
"shape",
"and",
"positions",
"have",
"the",
"same",
"dimensionality"
] | python | train |
phoebe-project/phoebe2 | phoebe/parameters/constraint.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/constraint.py#L798-L857 | def comp_sma(b, component, solve_for=None, **kwargs):
"""
Create a constraint for the star's semi-major axes WITHIN its
parent orbit. This is NOT the same as the semi-major axes OF
the parent orbit
If 'sma' does not exist in the component, it will be created
:parameter b: the :class:`phoebe.f... | [
"def",
"comp_sma",
"(",
"b",
",",
"component",
",",
"solve_for",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"hier",
"=",
"b",
".",
"get_hierarchy",
"(",
")",
"if",
"not",
"len",
"(",
"hier",
".",
"get_value",
"(",
")",
")",
":",
"# TODO: chang... | Create a constraint for the star's semi-major axes WITHIN its
parent orbit. This is NOT the same as the semi-major axes OF
the parent orbit
If 'sma' does not exist in the component, it will be created
:parameter b: the :class:`phoebe.frontend.bundle.Bundle`
:parameter str component: the label of ... | [
"Create",
"a",
"constraint",
"for",
"the",
"star",
"s",
"semi",
"-",
"major",
"axes",
"WITHIN",
"its",
"parent",
"orbit",
".",
"This",
"is",
"NOT",
"the",
"same",
"as",
"the",
"semi",
"-",
"major",
"axes",
"OF",
"the",
"parent",
"orbit"
] | python | train |
wummel/dosage | dosagelib/director.py | https://github.com/wummel/dosage/blob/a0109c3a46219f280e6e5e77183674e40da0f304/dosagelib/director.py#L183-L189 | def finish():
"""Print warning about interrupt and empty the job queue."""
out.warn("Interrupted!")
for t in threads:
t.stop()
jobs.clear()
out.warn("Waiting for download threads to finish.") | [
"def",
"finish",
"(",
")",
":",
"out",
".",
"warn",
"(",
"\"Interrupted!\"",
")",
"for",
"t",
"in",
"threads",
":",
"t",
".",
"stop",
"(",
")",
"jobs",
".",
"clear",
"(",
")",
"out",
".",
"warn",
"(",
"\"Waiting for download threads to finish.\"",
")"
] | Print warning about interrupt and empty the job queue. | [
"Print",
"warning",
"about",
"interrupt",
"and",
"empty",
"the",
"job",
"queue",
"."
] | python | train |
ga4gh/ga4gh-server | ga4gh/server/datamodel/genotype_phenotype.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datamodel/genotype_phenotype.py#L208-L224 | def _formatOntologyTermObject(self, terms, element_type):
"""
Formats the ontology term object for query
"""
elementClause = None
if not isinstance(terms, collections.Iterable):
terms = [terms]
elements = []
for term in terms:
if term.term_... | [
"def",
"_formatOntologyTermObject",
"(",
"self",
",",
"terms",
",",
"element_type",
")",
":",
"elementClause",
"=",
"None",
"if",
"not",
"isinstance",
"(",
"terms",
",",
"collections",
".",
"Iterable",
")",
":",
"terms",
"=",
"[",
"terms",
"]",
"elements",
... | Formats the ontology term object for query | [
"Formats",
"the",
"ontology",
"term",
"object",
"for",
"query"
] | python | train |
bykof/billomapy | billomapy/billomapy.py | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L1120-L1133 | def get_all_items_of_invoice(self, invoice_id):
"""
Get all items of invoice
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param invoice_id: the invoice id
:return: list
... | [
"def",
"get_all_items_of_invoice",
"(",
"self",
",",
"invoice_id",
")",
":",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"get_function",
"=",
"self",
".",
"get_items_of_invoice_per_page",
",",
"resource",
"=",
"INVOICE_ITEMS",
",",
"*",
"*",
"{",
"'invoi... | Get all items of invoice
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param invoice_id: the invoice id
:return: list | [
"Get",
"all",
"items",
"of",
"invoice",
"This",
"will",
"iterate",
"over",
"all",
"pages",
"until",
"it",
"gets",
"all",
"elements",
".",
"So",
"if",
"the",
"rate",
"limit",
"exceeded",
"it",
"will",
"throw",
"an",
"Exception",
"and",
"you",
"will",
"get... | python | train |
deepmind/pysc2 | pysc2/env/lan_sc2_env.py | https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/env/lan_sc2_env.py#L142-L154 | def read_tcp_size(conn, size):
"""Read `size` number of bytes from `conn`, retrying as needed."""
chunks = []
bytes_read = 0
while bytes_read < size:
chunk = conn.recv(size - bytes_read)
if not chunk:
if bytes_read > 0:
logging.warning("Incomplete read: %s of %s.", bytes_read, size)
... | [
"def",
"read_tcp_size",
"(",
"conn",
",",
"size",
")",
":",
"chunks",
"=",
"[",
"]",
"bytes_read",
"=",
"0",
"while",
"bytes_read",
"<",
"size",
":",
"chunk",
"=",
"conn",
".",
"recv",
"(",
"size",
"-",
"bytes_read",
")",
"if",
"not",
"chunk",
":",
... | Read `size` number of bytes from `conn`, retrying as needed. | [
"Read",
"size",
"number",
"of",
"bytes",
"from",
"conn",
"retrying",
"as",
"needed",
"."
] | python | train |
basecrm/basecrm-python | basecrm/services.py | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L313-L328 | def retrieve(self, id) :
"""
Retrieve a single deal
Returns a single deal available to the user, according to the unique deal ID provided
If the specified deal does not exist, the request will return an error
:calls: ``get /deals/{id}``
:param int id: Unique identifier ... | [
"def",
"retrieve",
"(",
"self",
",",
"id",
")",
":",
"_",
",",
"_",
",",
"deal",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/deals/{id}\"",
".",
"format",
"(",
"id",
"=",
"id",
")",
")",
"deal",
"[",
"\"value\"",
"]",
"=",
"Coercion",
"... | Retrieve a single deal
Returns a single deal available to the user, according to the unique deal ID provided
If the specified deal does not exist, the request will return an error
:calls: ``get /deals/{id}``
:param int id: Unique identifier of a Deal.
:return: Dictionary that s... | [
"Retrieve",
"a",
"single",
"deal"
] | python | train |
saltstack/salt | salt/modules/keystoneng.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/keystoneng.py#L680-L692 | def endpoint_list(auth=None, **kwargs):
'''
List endpoints
CLI Example:
.. code-block:: bash
salt '*' keystoneng.endpoint_list
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.list_endpoints(**kwargs) | [
"def",
"endpoint_list",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"list_endpoints",
"(",
"*",
... | List endpoints
CLI Example:
.. code-block:: bash
salt '*' keystoneng.endpoint_list | [
"List",
"endpoints"
] | python | train |
e7dal/bubble3 | bubble3/util/cli_misc.py | https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/bubble3/util/cli_misc.py#L217-L264 | def make_uniq_for_step(ctx, ukeys, step, stage, full_data, clean_missing_after_seconds, to_uniq):
"""initially just a copy from UNIQ_PULL"""
# TODO:
# this still seems to work ok for Storage types json/bubble,
# for DS we need to reload de dumped step to uniqify
if not ukeys:
return to_uni... | [
"def",
"make_uniq_for_step",
"(",
"ctx",
",",
"ukeys",
",",
"step",
",",
"stage",
",",
"full_data",
",",
"clean_missing_after_seconds",
",",
"to_uniq",
")",
":",
"# TODO:",
"# this still seems to work ok for Storage types json/bubble,",
"# for DS we need to reload de dumped s... | initially just a copy from UNIQ_PULL | [
"initially",
"just",
"a",
"copy",
"from",
"UNIQ_PULL"
] | python | train |
jazzband/django-ddp | dddp/api.py | https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/api.py#L54-L103 | def api_endpoint(path_or_func=None, decorate=True):
"""
Decorator to mark a method as an API endpoint for later registration.
Args:
path_or_func: either the function to be decorated or its API path.
decorate (bool): Apply API_ENDPOINT_DECORATORS if True (default).
Returns:
Call... | [
"def",
"api_endpoint",
"(",
"path_or_func",
"=",
"None",
",",
"decorate",
"=",
"True",
")",
":",
"def",
"maybe_decorated",
"(",
"func",
")",
":",
"\"\"\"Apply API_ENDPOINT_DECORATORS to func.\"\"\"",
"if",
"decorate",
":",
"for",
"decorator",
"in",
"API_ENDPOINT_DEC... | Decorator to mark a method as an API endpoint for later registration.
Args:
path_or_func: either the function to be decorated or its API path.
decorate (bool): Apply API_ENDPOINT_DECORATORS if True (default).
Returns:
Callable: Decorated function (with optionally applied decorators).
... | [
"Decorator",
"to",
"mark",
"a",
"method",
"as",
"an",
"API",
"endpoint",
"for",
"later",
"registration",
"."
] | python | test |
LEMS/pylems | lems/sim/runnable.py | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/runnable.py#L597-L793 | def copy(self):
"""
Make a copy of this runnable.
@return: Copy of this runnable.
@rtype: lems.sim.runnable.Runnable
"""
if self.debug: print("Coping....."+self.id)
r = Runnable(self.id, self.component, self.parent)
copies = dict()
# Copy simulat... | [
"def",
"copy",
"(",
"self",
")",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Coping.....\"",
"+",
"self",
".",
"id",
")",
"r",
"=",
"Runnable",
"(",
"self",
".",
"id",
",",
"self",
".",
"component",
",",
"self",
".",
"parent",
")",
"co... | Make a copy of this runnable.
@return: Copy of this runnable.
@rtype: lems.sim.runnable.Runnable | [
"Make",
"a",
"copy",
"of",
"this",
"runnable",
"."
] | python | train |
odlgroup/odl | odl/operator/pspace_ops.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/operator/pspace_ops.py#L230-L283 | def _convert_to_spmatrix(operators):
"""Convert an array-like object of operators to a sparse matrix."""
# Lazy import to improve `import odl` time
import scipy.sparse
# Convert ops to sparse representation. This is not trivial because
# operators can be indexable themselves and... | [
"def",
"_convert_to_spmatrix",
"(",
"operators",
")",
":",
"# Lazy import to improve `import odl` time",
"import",
"scipy",
".",
"sparse",
"# Convert ops to sparse representation. This is not trivial because",
"# operators can be indexable themselves and give the wrong impression",
"# of a... | Convert an array-like object of operators to a sparse matrix. | [
"Convert",
"an",
"array",
"-",
"like",
"object",
"of",
"operators",
"to",
"a",
"sparse",
"matrix",
"."
] | python | train |
CivicSpleen/ambry | ambry/orm/partition.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/partition.py#L598-L609 | def local_datafile(self):
"""Return the datafile for this partition, from the build directory, the remote, or the warehouse"""
from ambry_sources import MPRowsFile
from fs.errors import ResourceNotFoundError
from ambry.orm.exc import NotFoundError
try:
return MPRowsF... | [
"def",
"local_datafile",
"(",
"self",
")",
":",
"from",
"ambry_sources",
"import",
"MPRowsFile",
"from",
"fs",
".",
"errors",
"import",
"ResourceNotFoundError",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError",
"try",
":",
"return",
"MPRowsFile... | Return the datafile for this partition, from the build directory, the remote, or the warehouse | [
"Return",
"the",
"datafile",
"for",
"this",
"partition",
"from",
"the",
"build",
"directory",
"the",
"remote",
"or",
"the",
"warehouse"
] | python | train |
andycasey/sick | sick/models/base.py | https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/base.py#L277-L284 | def _format_data(self, data):
"""
Sort the data in blue wavelengths to red, and ignore any spectra that
have entirely non-finite or negative fluxes.
"""
return [spectrum for spectrum in \
sorted(data if isinstance(data, (list, tuple)) else [data],
key=... | [
"def",
"_format_data",
"(",
"self",
",",
"data",
")",
":",
"return",
"[",
"spectrum",
"for",
"spectrum",
"in",
"sorted",
"(",
"data",
"if",
"isinstance",
"(",
"data",
",",
"(",
"list",
",",
"tuple",
")",
")",
"else",
"[",
"data",
"]",
",",
"key",
"... | Sort the data in blue wavelengths to red, and ignore any spectra that
have entirely non-finite or negative fluxes. | [
"Sort",
"the",
"data",
"in",
"blue",
"wavelengths",
"to",
"red",
"and",
"ignore",
"any",
"spectra",
"that",
"have",
"entirely",
"non",
"-",
"finite",
"or",
"negative",
"fluxes",
"."
] | python | train |
bgyori/pykqml | kqml/kqml_list.py | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L44-L72 | def get(self, keyword):
"""Return the element of the list after the given keyword.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automat... | [
"def",
"get",
"(",
"self",
",",
"keyword",
")",
":",
"if",
"not",
"keyword",
".",
"startswith",
"(",
"':'",
")",
":",
"keyword",
"=",
"':'",
"+",
"keyword",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"self",
".",
"data",
")",
":",
"if",
"s",
... | Return the element of the list after the given keyword.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automatically (e.g. "keyword" will be foun... | [
"Return",
"the",
"element",
"of",
"the",
"list",
"after",
"the",
"given",
"keyword",
"."
] | python | train |
LionelAuroux/pyrser | pyrser/passes/topython.py | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L49-L62 | def visit_Call(self, node: parsing.Call) -> ast.expr:
"""Generates python code calling the function.
fn(*args)
"""
return ast.Call(
ast.Attribute(
ast.Name('self', ast.Load),
node.callObject.__name__,
ast.Load()),
[... | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
":",
"parsing",
".",
"Call",
")",
"->",
"ast",
".",
"expr",
":",
"return",
"ast",
".",
"Call",
"(",
"ast",
".",
"Attribute",
"(",
"ast",
".",
"Name",
"(",
"'self'",
",",
"ast",
".",
"Load",
")",
",",... | Generates python code calling the function.
fn(*args) | [
"Generates",
"python",
"code",
"calling",
"the",
"function",
"."
] | python | test |
seung-lab/cloud-volume | cloudvolume/compression.py | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/compression.py#L9-L34 | def decompress(content, encoding, filename='N/A'):
"""
Decompress file content.
Required:
content (bytes): a file to be compressed
encoding: None (no compression) or 'gzip'
Optional:
filename (str:default:'N/A'): Used for debugging messages
Raises:
NotImplementedError if an unsupported ... | [
"def",
"decompress",
"(",
"content",
",",
"encoding",
",",
"filename",
"=",
"'N/A'",
")",
":",
"try",
":",
"encoding",
"=",
"(",
"encoding",
"or",
"''",
")",
".",
"lower",
"(",
")",
"if",
"encoding",
"==",
"''",
":",
"return",
"content",
"elif",
"enc... | Decompress file content.
Required:
content (bytes): a file to be compressed
encoding: None (no compression) or 'gzip'
Optional:
filename (str:default:'N/A'): Used for debugging messages
Raises:
NotImplementedError if an unsupported codec is specified.
compression.EncodeError if the enc... | [
"Decompress",
"file",
"content",
"."
] | python | train |
sethmlarson/virtualbox-python | virtualbox/library.py | https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L16915-L16952 | def insert_usb_device_filter(self, position, filter_p):
"""Inserts the given USB device to the specified position
in the list of filters.
Positions are numbered starting from @c 0. If the specified
position is equal to or greater than the number of elements in
the list, ... | [
"def",
"insert_usb_device_filter",
"(",
"self",
",",
"position",
",",
"filter_p",
")",
":",
"if",
"not",
"isinstance",
"(",
"position",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"position can only be an instance of type baseinteger\"",
")",
"if",
"n... | Inserts the given USB device to the specified position
in the list of filters.
Positions are numbered starting from @c 0. If the specified
position is equal to or greater than the number of elements in
the list, the filter is added at the end of the collection.
... | [
"Inserts",
"the",
"given",
"USB",
"device",
"to",
"the",
"specified",
"position",
"in",
"the",
"list",
"of",
"filters",
".",
"Positions",
"are",
"numbered",
"starting",
"from",
"@c",
"0",
".",
"If",
"the",
"specified",
"position",
"is",
"equal",
"to",
"or"... | python | train |
The-Politico/politico-civic-ap-loader | aploader/management/commands/initialize_election_date.py | https://github.com/The-Politico/politico-civic-ap-loader/blob/4afeebb62da4b8f22da63711e7176bf4527bccfb/aploader/management/commands/initialize_election_date.py#L195-L213 | def get_or_create_party(self, row):
"""
Gets or creates the Party object based on AP code of the row of
election data.
All parties that aren't Democratic or Republican are aggregable.
"""
if row["party"] in ["Dem", "GOP"]:
aggregable = False
else:
... | [
"def",
"get_or_create_party",
"(",
"self",
",",
"row",
")",
":",
"if",
"row",
"[",
"\"party\"",
"]",
"in",
"[",
"\"Dem\"",
",",
"\"GOP\"",
"]",
":",
"aggregable",
"=",
"False",
"else",
":",
"aggregable",
"=",
"True",
"defaults",
"=",
"{",
"\"label\"",
... | Gets or creates the Party object based on AP code of the row of
election data.
All parties that aren't Democratic or Republican are aggregable. | [
"Gets",
"or",
"creates",
"the",
"Party",
"object",
"based",
"on",
"AP",
"code",
"of",
"the",
"row",
"of",
"election",
"data",
"."
] | python | train |
saltstack/salt | salt/client/mixins.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/mixins.py#L525-L540 | def asynchronous(self, fun, low, user='UNKNOWN', pub=None):
'''
Execute the function in a multiprocess and return the event tag to use
to watch for the return
'''
async_pub = pub if pub is not None else self._gen_async_pub()
proc = salt.utils.process.SignalHandlingMultip... | [
"def",
"asynchronous",
"(",
"self",
",",
"fun",
",",
"low",
",",
"user",
"=",
"'UNKNOWN'",
",",
"pub",
"=",
"None",
")",
":",
"async_pub",
"=",
"pub",
"if",
"pub",
"is",
"not",
"None",
"else",
"self",
".",
"_gen_async_pub",
"(",
")",
"proc",
"=",
"... | Execute the function in a multiprocess and return the event tag to use
to watch for the return | [
"Execute",
"the",
"function",
"in",
"a",
"multiprocess",
"and",
"return",
"the",
"event",
"tag",
"to",
"use",
"to",
"watch",
"for",
"the",
"return"
] | python | train |
avelkoski/FRB | fred/utils/__init__.py | https://github.com/avelkoski/FRB/blob/692bcf576e17bd1a81db2b7644f4f61aeb39e5c7/fred/utils/__init__.py#L4-L19 | def query_params(*frb_fred_params):
"""
Decorator that pops all accepted parameters from method's kwargs and puts
them in the params argument. Modeled after elasticsearch-py client utils strategy.
See https://github.com/elastic/elasticsearch-py/blob/3400179153cc13b6ae2c26734337202569bdfd80/elasticsearch... | [
"def",
"query_params",
"(",
"*",
"frb_fred_params",
")",
":",
"def",
"_wrapper",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"_wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"kwargs",
".",
"pop",
"("... | Decorator that pops all accepted parameters from method's kwargs and puts
them in the params argument. Modeled after elasticsearch-py client utils strategy.
See https://github.com/elastic/elasticsearch-py/blob/3400179153cc13b6ae2c26734337202569bdfd80/elasticsearch/client/utils.py | [
"Decorator",
"that",
"pops",
"all",
"accepted",
"parameters",
"from",
"method",
"s",
"kwargs",
"and",
"puts",
"them",
"in",
"the",
"params",
"argument",
".",
"Modeled",
"after",
"elasticsearch",
"-",
"py",
"client",
"utils",
"strategy",
".",
"See",
"https",
... | python | train |
thumbor/thumbor | thumbor/handlers/__init__.py | https://github.com/thumbor/thumbor/blob/558ccdd6e3bc29e1c9ee3687372c4b3eb05ac607/thumbor/handlers/__init__.py#L146-L224 | def get_image(self):
"""
This function is called after the PRE_LOAD filters have been applied.
It applies the AFTER_LOAD filters on the result, then crops the image.
"""
try:
result = yield self._fetch(
self.context.request.image_url
)
... | [
"def",
"get_image",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"yield",
"self",
".",
"_fetch",
"(",
"self",
".",
"context",
".",
"request",
".",
"image_url",
")",
"if",
"not",
"result",
".",
"successful",
":",
"if",
"result",
".",
"loader_error"... | This function is called after the PRE_LOAD filters have been applied.
It applies the AFTER_LOAD filters on the result, then crops the image. | [
"This",
"function",
"is",
"called",
"after",
"the",
"PRE_LOAD",
"filters",
"have",
"been",
"applied",
".",
"It",
"applies",
"the",
"AFTER_LOAD",
"filters",
"on",
"the",
"result",
"then",
"crops",
"the",
"image",
"."
] | python | train |
rameshg87/pyremotevbox | pyremotevbox/ZSI/wstools/XMLSchema.py | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/wstools/XMLSchema.py#L2059-L2066 | def getElementDeclaration(self, attribute=None):
"""If attribute is None, "ref" is assumed, return the corresponding
representation of the global element declaration (ElementDeclaration),
To maintain backwards compat, if attribute is provided call base class method.
"""
if attrib... | [
"def",
"getElementDeclaration",
"(",
"self",
",",
"attribute",
"=",
"None",
")",
":",
"if",
"attribute",
":",
"return",
"XMLSchemaComponent",
".",
"getElementDeclaration",
"(",
"self",
",",
"attribute",
")",
"return",
"XMLSchemaComponent",
".",
"getElementDeclaratio... | If attribute is None, "ref" is assumed, return the corresponding
representation of the global element declaration (ElementDeclaration),
To maintain backwards compat, if attribute is provided call base class method. | [
"If",
"attribute",
"is",
"None",
"ref",
"is",
"assumed",
"return",
"the",
"corresponding",
"representation",
"of",
"the",
"global",
"element",
"declaration",
"(",
"ElementDeclaration",
")",
"To",
"maintain",
"backwards",
"compat",
"if",
"attribute",
"is",
"provide... | python | train |
RJT1990/pyflux | pyflux/gas/gasrank.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gas/gasrank.py#L258-L292 | def _model_abilities_one_components(self,beta):
""" Creates the structure of the model - store abilities
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
theta : np.array
... | [
"def",
"_model_abilities_one_components",
"(",
"self",
",",
"beta",
")",
":",
"parm",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"latent_variables",
".",
"z_list",
"[",
"k",
"]",
".",
"prior",
".",
"transform",
"(",
"beta",
"[",
"k",
"]",
")",
"... | Creates the structure of the model - store abilities
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
theta : np.array
Contains the predicted values for the time series
... | [
"Creates",
"the",
"structure",
"of",
"the",
"model",
"-",
"store",
"abilities"
] | python | train |
Azure/blobxfer | blobxfer/operations/azure/__init__.py | https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/operations/azure/__init__.py#L620-L683 | def _populate_from_list_blobs(self, creds, options, dry_run):
# type: (SourcePath, StorageCredentials, Any, bool) -> StorageEntity
"""Internal generator for Azure remote blobs
:param SourcePath self: this
:param StorageCredentials creds: storage creds
:param object options: downl... | [
"def",
"_populate_from_list_blobs",
"(",
"self",
",",
"creds",
",",
"options",
",",
"dry_run",
")",
":",
"# type: (SourcePath, StorageCredentials, Any, bool) -> StorageEntity",
"is_synccopy",
"=",
"isinstance",
"(",
"options",
",",
"blobxfer",
".",
"models",
".",
"optio... | Internal generator for Azure remote blobs
:param SourcePath self: this
:param StorageCredentials creds: storage creds
:param object options: download or synccopy options
:param bool dry_run: dry run
:rtype: StorageEntity
:return: Azure storage entity object | [
"Internal",
"generator",
"for",
"Azure",
"remote",
"blobs",
":",
"param",
"SourcePath",
"self",
":",
"this",
":",
"param",
"StorageCredentials",
"creds",
":",
"storage",
"creds",
":",
"param",
"object",
"options",
":",
"download",
"or",
"synccopy",
"options",
... | python | train |
FujiMakoto/AgentML | agentml/parser/element.py | https://github.com/FujiMakoto/AgentML/blob/c8cb64b460d876666bf29ea2c682189874c7c403/agentml/parser/element.py#L107-L125 | def _parse_chance(self, element):
"""
Parse a chance element
:param element: The XML Element object
:type element: etree._Element
"""
try:
chance = float(element.text)
except (ValueError, TypeError, AttributeError):
self._log.warn('Invalid... | [
"def",
"_parse_chance",
"(",
"self",
",",
"element",
")",
":",
"try",
":",
"chance",
"=",
"float",
"(",
"element",
".",
"text",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
",",
"AttributeError",
")",
":",
"self",
".",
"_log",
".",
"warn",
"(",
... | Parse a chance element
:param element: The XML Element object
:type element: etree._Element | [
"Parse",
"a",
"chance",
"element",
":",
"param",
"element",
":",
"The",
"XML",
"Element",
"object",
":",
"type",
"element",
":",
"etree",
".",
"_Element"
] | python | train |
shapiromatron/bmds | bmds/datasets.py | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/datasets.py#L494-L504 | def as_dfile(self):
"""
Return the dataset representation in BMDS .(d) file.
"""
rows = ["Dose Response"]
for dose, response in zip(self.individual_doses, self.responses):
dose_idx = self.doses.index(dose)
if dose_idx >= self.num_dose_groups:
... | [
"def",
"as_dfile",
"(",
"self",
")",
":",
"rows",
"=",
"[",
"\"Dose Response\"",
"]",
"for",
"dose",
",",
"response",
"in",
"zip",
"(",
"self",
".",
"individual_doses",
",",
"self",
".",
"responses",
")",
":",
"dose_idx",
"=",
"self",
".",
"doses",
"."... | Return the dataset representation in BMDS .(d) file. | [
"Return",
"the",
"dataset",
"representation",
"in",
"BMDS",
".",
"(",
"d",
")",
"file",
"."
] | python | train |
goldsborough/li | scripts/bump.py | https://github.com/goldsborough/li/blob/8ea4f8b55183aadaa96bc70cfcfcb7b198874319/scripts/bump.py#L11-L26 | def bump(match):
"""Bumps the version"""
before, old_version, after = match.groups()
major, minor, patch = map(int, old_version.split('.'))
patch += 1
if patch == 10:
patch = 0
minor += 1
if minor == 10:
minor = 0
major += 1
new_version = '{0}.{1}.{2}'.format(major, minor, patch)
print('{0} => {1}'.... | [
"def",
"bump",
"(",
"match",
")",
":",
"before",
",",
"old_version",
",",
"after",
"=",
"match",
".",
"groups",
"(",
")",
"major",
",",
"minor",
",",
"patch",
"=",
"map",
"(",
"int",
",",
"old_version",
".",
"split",
"(",
"'.'",
")",
")",
"patch",
... | Bumps the version | [
"Bumps",
"the",
"version"
] | python | train |
markuskiller/textblob-de | textblob_de/ext/_pattern/text/tree.py | https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/tree.py#L900-L916 | def _do_anchor(self, anchor):
""" Collects preposition anchors and attachments in a dictionary.
Once the dictionary has an entry for both the anchor and the attachment, they are linked.
"""
if anchor:
for x in anchor.split("-"):
A, P = None, None
... | [
"def",
"_do_anchor",
"(",
"self",
",",
"anchor",
")",
":",
"if",
"anchor",
":",
"for",
"x",
"in",
"anchor",
".",
"split",
"(",
"\"-\"",
")",
":",
"A",
",",
"P",
"=",
"None",
",",
"None",
"if",
"x",
".",
"startswith",
"(",
"\"A\"",
")",
"and",
"... | Collects preposition anchors and attachments in a dictionary.
Once the dictionary has an entry for both the anchor and the attachment, they are linked. | [
"Collects",
"preposition",
"anchors",
"and",
"attachments",
"in",
"a",
"dictionary",
".",
"Once",
"the",
"dictionary",
"has",
"an",
"entry",
"for",
"both",
"the",
"anchor",
"and",
"the",
"attachment",
"they",
"are",
"linked",
"."
] | python | train |
d0ugal/home | home/collect/handlers.py | https://github.com/d0ugal/home/blob/e984716ae6c74dc8e40346584668ac5cfeaaf520/home/collect/handlers.py#L26-L69 | def load_handlers(handler_mapping):
"""
Given a dictionary mapping which looks like the following, import the
objects based on the dotted path and yield the packet type and handler as
pairs.
If the special string '*' is passed, don't process that, pass it on as it
is a wildcard.
If an non-... | [
"def",
"load_handlers",
"(",
"handler_mapping",
")",
":",
"handlers",
"=",
"{",
"}",
"for",
"packet_type",
",",
"handler",
"in",
"handler_mapping",
".",
"items",
"(",
")",
":",
"if",
"packet_type",
"==",
"'*'",
":",
"Packet",
"=",
"packet_type",
"elif",
"i... | Given a dictionary mapping which looks like the following, import the
objects based on the dotted path and yield the packet type and handler as
pairs.
If the special string '*' is passed, don't process that, pass it on as it
is a wildcard.
If an non-string object is given for either packet or hand... | [
"Given",
"a",
"dictionary",
"mapping",
"which",
"looks",
"like",
"the",
"following",
"import",
"the",
"objects",
"based",
"on",
"the",
"dotted",
"path",
"and",
"yield",
"the",
"packet",
"type",
"and",
"handler",
"as",
"pairs",
"."
] | python | test |
aguinane/nem-reader | nemreader/nem_reader.py | https://github.com/aguinane/nem-reader/blob/5405a5cba4bb8ebdad05c28455d12bb34a6d3ce5/nemreader/nem_reader.py#L186-L201 | def parse_300_row(row: list, interval: int, uom: str) -> IntervalRecord:
""" Interval data record (300) """
num_intervals = int(24 * 60 / interval)
interval_date = parse_datetime(row[1])
last_interval = 2 + num_intervals
quality_method = row[last_interval]
interval_values = parse_interval_reco... | [
"def",
"parse_300_row",
"(",
"row",
":",
"list",
",",
"interval",
":",
"int",
",",
"uom",
":",
"str",
")",
"->",
"IntervalRecord",
":",
"num_intervals",
"=",
"int",
"(",
"24",
"*",
"60",
"/",
"interval",
")",
"interval_date",
"=",
"parse_datetime",
"(",
... | Interval data record (300) | [
"Interval",
"data",
"record",
"(",
"300",
")"
] | python | train |
aboSamoor/polyglot | polyglot/__main__.py | https://github.com/aboSamoor/polyglot/blob/d0d2aa8d06cec4e03bd96618ae960030f7069a17/polyglot/__main__.py#L39-L49 | def vocab_counter(args):
"""Calculate the vocabulary."""
if isinstance(args.input, TextFiles):
v = CountedVocabulary.from_textfiles(args.input, workers=args.workers)
else:
v = CountedVocabulary.from_textfile(args.input, workers=args.workers)
if args.min_count > 1:
v = v.min_count(args.min_count)
... | [
"def",
"vocab_counter",
"(",
"args",
")",
":",
"if",
"isinstance",
"(",
"args",
".",
"input",
",",
"TextFiles",
")",
":",
"v",
"=",
"CountedVocabulary",
".",
"from_textfiles",
"(",
"args",
".",
"input",
",",
"workers",
"=",
"args",
".",
"workers",
")",
... | Calculate the vocabulary. | [
"Calculate",
"the",
"vocabulary",
"."
] | python | train |
tanghaibao/goatools | goatools/grouper/grprobj_init.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/grprobj_init.py#L49-L62 | def _init_usrgos(self, goids):
"""Return user GO IDs which have GO Terms."""
usrgos = set()
goids_missing = set()
_go2obj = self.gosubdag.go2obj
for goid in goids:
if goid in _go2obj:
usrgos.add(goid)
else:
goids_missing.add... | [
"def",
"_init_usrgos",
"(",
"self",
",",
"goids",
")",
":",
"usrgos",
"=",
"set",
"(",
")",
"goids_missing",
"=",
"set",
"(",
")",
"_go2obj",
"=",
"self",
".",
"gosubdag",
".",
"go2obj",
"for",
"goid",
"in",
"goids",
":",
"if",
"goid",
"in",
"_go2obj... | Return user GO IDs which have GO Terms. | [
"Return",
"user",
"GO",
"IDs",
"which",
"have",
"GO",
"Terms",
"."
] | python | train |
Kozea/wdb | client/wdb/__init__.py | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L692-L707 | def get_stack(self, f, t):
"""Build the stack from frame and traceback"""
stack = []
if t and t.tb_frame == f:
t = t.tb_next
while f is not None:
stack.append((f, f.f_lineno))
f = f.f_back
stack.reverse()
i = max(0, len(stack) - 1)
... | [
"def",
"get_stack",
"(",
"self",
",",
"f",
",",
"t",
")",
":",
"stack",
"=",
"[",
"]",
"if",
"t",
"and",
"t",
".",
"tb_frame",
"==",
"f",
":",
"t",
"=",
"t",
".",
"tb_next",
"while",
"f",
"is",
"not",
"None",
":",
"stack",
".",
"append",
"(",... | Build the stack from frame and traceback | [
"Build",
"the",
"stack",
"from",
"frame",
"and",
"traceback"
] | python | train |
usc-isi-i2/etk | etk/extractors/mailman_extractor.py | https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/etk/extractors/mailman_extractor.py#L31-L73 | def old_format(self, content: BeautifulSoup) -> List[str]:
"""
Extracts email message information if it uses the old Mailman format
Args:
content: BeautifulSoup
Returns: List[str]
"""
b = content.find('body')
sender, date, nxt, rep_to = None... | [
"def",
"old_format",
"(",
"self",
",",
"content",
":",
"BeautifulSoup",
")",
"->",
"List",
"[",
"str",
"]",
":",
"b",
"=",
"content",
".",
"find",
"(",
"'body'",
")",
"sender",
",",
"date",
",",
"nxt",
",",
"rep_to",
"=",
"None",
",",
"None",
",",
... | Extracts email message information if it uses the old Mailman format
Args:
content: BeautifulSoup
Returns: List[str] | [
"Extracts",
"email",
"message",
"information",
"if",
"it",
"uses",
"the",
"old",
"Mailman",
"format",
"Args",
":",
"content",
":",
"BeautifulSoup"
] | python | train |
Alignak-monitoring/alignak | alignak/modulesmanager.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L90-L99 | def set_daemon_name(self, daemon_name):
"""Set the daemon name of the daemon which this manager is attached to
and propagate this daemon name to our managed modules
:param daemon_name:
:return:
"""
self.daemon_name = daemon_name
for instance in self.instances:
... | [
"def",
"set_daemon_name",
"(",
"self",
",",
"daemon_name",
")",
":",
"self",
".",
"daemon_name",
"=",
"daemon_name",
"for",
"instance",
"in",
"self",
".",
"instances",
":",
"instance",
".",
"set_loaded_into",
"(",
"daemon_name",
")"
] | Set the daemon name of the daemon which this manager is attached to
and propagate this daemon name to our managed modules
:param daemon_name:
:return: | [
"Set",
"the",
"daemon",
"name",
"of",
"the",
"daemon",
"which",
"this",
"manager",
"is",
"attached",
"to",
"and",
"propagate",
"this",
"daemon",
"name",
"to",
"our",
"managed",
"modules"
] | python | train |
broadinstitute/fiss | firecloud/api.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/api.py#L292-L308 | def get_entity(namespace, workspace, etype, ename):
"""Request entity information.
Gets entity metadata and attributes.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
etype (str): Entity type
ename (str): The entity's unique id
... | [
"def",
"get_entity",
"(",
"namespace",
",",
"workspace",
",",
"etype",
",",
"ename",
")",
":",
"uri",
"=",
"\"workspaces/{0}/{1}/entities/{2}/{3}\"",
".",
"format",
"(",
"namespace",
",",
"workspace",
",",
"etype",
",",
"ename",
")",
"return",
"__get",
"(",
... | Request entity information.
Gets entity metadata and attributes.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
etype (str): Entity type
ename (str): The entity's unique id
Swagger:
https://api.firecloud.org/#!/Entities/ge... | [
"Request",
"entity",
"information",
"."
] | python | train |
Azure/azure-cli-extensions | src/azure-firewall/azext_firewall/_validators.py | https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/azure-firewall/azext_firewall/_validators.py#L24-L49 | def get_public_ip_validator():
""" Retrieves a validator for public IP address. Accepting all defaults will perform a check
for an existing name or ID with no ARM-required -type parameter. """
from msrestazure.tools import is_valid_resource_id, resource_id
def simple_validator(cmd, namespace):
... | [
"def",
"get_public_ip_validator",
"(",
")",
":",
"from",
"msrestazure",
".",
"tools",
"import",
"is_valid_resource_id",
",",
"resource_id",
"def",
"simple_validator",
"(",
"cmd",
",",
"namespace",
")",
":",
"if",
"namespace",
".",
"public_ip_address",
":",
"is_lis... | Retrieves a validator for public IP address. Accepting all defaults will perform a check
for an existing name or ID with no ARM-required -type parameter. | [
"Retrieves",
"a",
"validator",
"for",
"public",
"IP",
"address",
".",
"Accepting",
"all",
"defaults",
"will",
"perform",
"a",
"check",
"for",
"an",
"existing",
"name",
"or",
"ID",
"with",
"no",
"ARM",
"-",
"required",
"-",
"type",
"parameter",
"."
] | python | train |
trailofbits/protofuzz | protofuzz/protofuzz.py | https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L71-L105 | def _prototype_to_generator(descriptor, cls):
'Helper to map a descriptor to a protofuzz generator'
_fd = D.FieldDescriptor
generator = None
ints32 = [_fd.TYPE_INT32, _fd.TYPE_UINT32, _fd.TYPE_FIXED32,
_fd.TYPE_SFIXED32, _fd.TYPE_SINT32]
ints64 = [_fd.TYPE_INT64, _fd.TYPE_UINT64, _fd.... | [
"def",
"_prototype_to_generator",
"(",
"descriptor",
",",
"cls",
")",
":",
"_fd",
"=",
"D",
".",
"FieldDescriptor",
"generator",
"=",
"None",
"ints32",
"=",
"[",
"_fd",
".",
"TYPE_INT32",
",",
"_fd",
".",
"TYPE_UINT32",
",",
"_fd",
".",
"TYPE_FIXED32",
","... | Helper to map a descriptor to a protofuzz generator | [
"Helper",
"to",
"map",
"a",
"descriptor",
"to",
"a",
"protofuzz",
"generator"
] | python | train |
AmesCornish/buttersink | buttersink/BestDiffs.py | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/BestDiffs.py#L110-L153 | def analyze(self, chunkSize, *sinks):
""" Figure out the best diffs to use to reach all our required volumes. """
measureSize = False
if self.measureSize:
for sink in sinks:
if sink.isRemote:
measureSize = True
# Use destination (already ... | [
"def",
"analyze",
"(",
"self",
",",
"chunkSize",
",",
"*",
"sinks",
")",
":",
"measureSize",
"=",
"False",
"if",
"self",
".",
"measureSize",
":",
"for",
"sink",
"in",
"sinks",
":",
"if",
"sink",
".",
"isRemote",
":",
"measureSize",
"=",
"True",
"# Use ... | Figure out the best diffs to use to reach all our required volumes. | [
"Figure",
"out",
"the",
"best",
"diffs",
"to",
"use",
"to",
"reach",
"all",
"our",
"required",
"volumes",
"."
] | python | train |
pybel/pybel | src/pybel/manager/query_manager.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/query_manager.py#L22-L29 | def graph_from_edges(edges: Iterable[Edge], **kwargs) -> BELGraph:
"""Build a BEL graph from edges."""
graph = BELGraph(**kwargs)
for edge in edges:
edge.insert_into_graph(graph)
return graph | [
"def",
"graph_from_edges",
"(",
"edges",
":",
"Iterable",
"[",
"Edge",
"]",
",",
"*",
"*",
"kwargs",
")",
"->",
"BELGraph",
":",
"graph",
"=",
"BELGraph",
"(",
"*",
"*",
"kwargs",
")",
"for",
"edge",
"in",
"edges",
":",
"edge",
".",
"insert_into_graph"... | Build a BEL graph from edges. | [
"Build",
"a",
"BEL",
"graph",
"from",
"edges",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xorbtreewidget/xorbtreewidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbtreewidget.py#L2049-L2062 | def setRecords(self, records):
"""
Manually sets the list of records that will be displayed in this tree.
This is a shortcut method to creating a RecordSet with a list of records
and assigning it to the tree.
:param records | [<orb.Table>, ..]
... | [
"def",
"setRecords",
"(",
"self",
",",
"records",
")",
":",
"self",
".",
"_searchTerms",
"=",
"''",
"if",
"not",
"isinstance",
"(",
"records",
",",
"RecordSet",
")",
":",
"records",
"=",
"RecordSet",
"(",
"records",
")",
"self",
".",
"setRecordSet",
"(",... | Manually sets the list of records that will be displayed in this tree.
This is a shortcut method to creating a RecordSet with a list of records
and assigning it to the tree.
:param records | [<orb.Table>, ..] | [
"Manually",
"sets",
"the",
"list",
"of",
"records",
"that",
"will",
"be",
"displayed",
"in",
"this",
"tree",
".",
"This",
"is",
"a",
"shortcut",
"method",
"to",
"creating",
"a",
"RecordSet",
"with",
"a",
"list",
"of",
"records",
"and",
"assigning",
"it",
... | python | train |
axialmarket/fsq | libexec/fsq/push.py | https://github.com/axialmarket/fsq/blob/43b84c292cb8a187599d86753b947cf73248f989/libexec/fsq/push.py#L26-L41 | def usage(asked_for=0):
'''Exit with a usage string, used for bad argument or with -h'''
exit = fsq.const('FSQ_SUCCESS') if asked_for else\
fsq.const('FSQ_FAIL_PERM')
f = sys.stdout if asked_for else sys.stderr
shout('{0} [opts] src_queue trg_queue host item_id [item_id [...]]'.format(
... | [
"def",
"usage",
"(",
"asked_for",
"=",
"0",
")",
":",
"exit",
"=",
"fsq",
".",
"const",
"(",
"'FSQ_SUCCESS'",
")",
"if",
"asked_for",
"else",
"fsq",
".",
"const",
"(",
"'FSQ_FAIL_PERM'",
")",
"f",
"=",
"sys",
".",
"stdout",
"if",
"asked_for",
"else",
... | Exit with a usage string, used for bad argument or with -h | [
"Exit",
"with",
"a",
"usage",
"string",
"used",
"for",
"bad",
"argument",
"or",
"with",
"-",
"h"
] | python | train |
MrYsLab/pymata-aio | pymata_aio/pymata_core.py | https://github.com/MrYsLab/pymata-aio/blob/015081a4628b9d47dfe3f8d6c698ff903f107810/pymata_aio/pymata_core.py#L1369-L1385 | async def pixy_set_led(self, r, g, b):
"""
Sends the setLed Pixy command.
This method sets the RGB LED on front of Pixy.
:param r: red range between 0 and 255
:param g: green range between 0 and 255
:param b: blue range between 0 and 255
:returns: No return va... | [
"async",
"def",
"pixy_set_led",
"(",
"self",
",",
"r",
",",
"g",
",",
"b",
")",
":",
"data",
"=",
"[",
"PrivateConstants",
".",
"PIXY_SET_LED",
",",
"r",
"&",
"0x7f",
",",
"(",
"r",
">>",
"7",
")",
"&",
"0x7f",
",",
"g",
"&",
"0x7f",
",",
"(",
... | Sends the setLed Pixy command.
This method sets the RGB LED on front of Pixy.
:param r: red range between 0 and 255
:param g: green range between 0 and 255
:param b: blue range between 0 and 255
:returns: No return value. | [
"Sends",
"the",
"setLed",
"Pixy",
"command",
".",
"This",
"method",
"sets",
"the",
"RGB",
"LED",
"on",
"front",
"of",
"Pixy",
"."
] | python | train |
KelSolaar/Foundations | foundations/nodes.py | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/nodes.py#L707-L729 | def index_of(self, child):
"""
Returns the given child index.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_a.index_of(no... | [
"def",
"index_of",
"(",
"self",
",",
"child",
")",
":",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"self",
".",
"__children",
")",
":",
"if",
"child",
"is",
"item",
":",
"return",
"i"
] | Returns the given child index.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_a.index_of(node_b)
0
>>> node_a.inde... | [
"Returns",
"the",
"given",
"child",
"index",
"."
] | python | train |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/__init__.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/__init__.py#L95-L115 | def local_path_from_url(url):
"""
For URLs that point to locations in the local filesystem, extract
and return the filesystem path of the object to which they point.
As a special case pass-through, if the URL is None, the return
value is None. Raises ValueError if the URL is not None and does
not point to a loca... | [
"def",
"local_path_from_url",
"(",
"url",
")",
":",
"if",
"url",
"is",
"None",
":",
"return",
"None",
"scheme",
",",
"host",
",",
"path",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"[",
":",
"3",
"]",
"if",
"scheme",
".",
"lower",
"(",
")",... | For URLs that point to locations in the local filesystem, extract
and return the filesystem path of the object to which they point.
As a special case pass-through, if the URL is None, the return
value is None. Raises ValueError if the URL is not None and does
not point to a local file.
Example:
>>> print local... | [
"For",
"URLs",
"that",
"point",
"to",
"locations",
"in",
"the",
"local",
"filesystem",
"extract",
"and",
"return",
"the",
"filesystem",
"path",
"of",
"the",
"object",
"to",
"which",
"they",
"point",
".",
"As",
"a",
"special",
"case",
"pass",
"-",
"through"... | python | train |
bintoro/overloading.py | overloading.py | https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L658-L691 | def sig_cmp(sig1, sig2):
"""
Compares two normalized type signatures for validation purposes.
"""
types1 = sig1.required
types2 = sig2.required
if len(types1) != len(types2):
return False
dup_pos = []
dup_kw = {}
for t1, t2 in zip(types1, types2):
match = type_cmp(t1,... | [
"def",
"sig_cmp",
"(",
"sig1",
",",
"sig2",
")",
":",
"types1",
"=",
"sig1",
".",
"required",
"types2",
"=",
"sig2",
".",
"required",
"if",
"len",
"(",
"types1",
")",
"!=",
"len",
"(",
"types2",
")",
":",
"return",
"False",
"dup_pos",
"=",
"[",
"]"... | Compares two normalized type signatures for validation purposes. | [
"Compares",
"two",
"normalized",
"type",
"signatures",
"for",
"validation",
"purposes",
"."
] | python | train |
wavycloud/pyboto3 | pyboto3/opsworks.py | https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/opsworks.py#L152-L350 | def clone_stack(SourceStackId=None, Name=None, Region=None, VpcId=None, Attributes=None, ServiceRoleArn=None, DefaultInstanceProfileArn=None, DefaultOs=None, HostnameTheme=None, DefaultAvailabilityZone=None, DefaultSubnetId=None, CustomJson=None, ConfigurationManager=None, ChefConfiguration=None, UseCustomCookbooks=Non... | [
"def",
"clone_stack",
"(",
"SourceStackId",
"=",
"None",
",",
"Name",
"=",
"None",
",",
"Region",
"=",
"None",
",",
"VpcId",
"=",
"None",
",",
"Attributes",
"=",
"None",
",",
"ServiceRoleArn",
"=",
"None",
",",
"DefaultInstanceProfileArn",
"=",
"None",
","... | Creates a clone of a specified stack. For more information, see Clone a Stack . By default, all parameters are set to the values used by the parent stack.
See also: AWS API Documentation
:example: response = client.clone_stack(
SourceStackId='string',
Name='string',
Region='str... | [
"Creates",
"a",
"clone",
"of",
"a",
"specified",
"stack",
".",
"For",
"more",
"information",
"see",
"Clone",
"a",
"Stack",
".",
"By",
"default",
"all",
"parameters",
"are",
"set",
"to",
"the",
"values",
"used",
"by",
"the",
"parent",
"stack",
".",
"See",... | python | train |
seleniumbase/SeleniumBase | seleniumbase/fixtures/base_case.py | https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/fixtures/base_case.py#L2364-L2375 | def wait_for_element_absent(self, selector, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
""" Waits for an element to no longer appear in the HTML of a page.
A hidden element still counts as appearing in the page HTML.
If an element with "hidden" st... | [
"def",
"wait_for_element_absent",
"(",
"self",
",",
"selector",
",",
"by",
"=",
"By",
".",
"CSS_SELECTOR",
",",
"timeout",
"=",
"settings",
".",
"LARGE_TIMEOUT",
")",
":",
"if",
"self",
".",
"timeout_multiplier",
"and",
"timeout",
"==",
"settings",
".",
"LAR... | Waits for an element to no longer appear in the HTML of a page.
A hidden element still counts as appearing in the page HTML.
If an element with "hidden" status is acceptable,
use wait_for_element_not_visible() instead. | [
"Waits",
"for",
"an",
"element",
"to",
"no",
"longer",
"appear",
"in",
"the",
"HTML",
"of",
"a",
"page",
".",
"A",
"hidden",
"element",
"still",
"counts",
"as",
"appearing",
"in",
"the",
"page",
"HTML",
".",
"If",
"an",
"element",
"with",
"hidden",
"st... | python | train |
johnnoone/json-spec | src/jsonspec/validators/__init__.py | https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/validators/__init__.py#L21-L37 | def load(schema, uri=None, spec=None, provider=None):
"""Scaffold a validator against a schema.
:param schema: the schema to compile into a Validator
:type schema: Mapping
:param uri: the uri of the schema.
it may be ignored in case of not cross
referencing.
:type ur... | [
"def",
"load",
"(",
"schema",
",",
"uri",
"=",
"None",
",",
"spec",
"=",
"None",
",",
"provider",
"=",
"None",
")",
":",
"factory",
"=",
"Factory",
"(",
"provider",
",",
"spec",
")",
"return",
"factory",
"(",
"schema",
",",
"uri",
"or",
"'#'",
")"
... | Scaffold a validator against a schema.
:param schema: the schema to compile into a Validator
:type schema: Mapping
:param uri: the uri of the schema.
it may be ignored in case of not cross
referencing.
:type uri: Pointer, str
:param spec: fallback to this spec if the... | [
"Scaffold",
"a",
"validator",
"against",
"a",
"schema",
"."
] | python | train |
spyder-ide/spyder | spyder/plugins/editor/panels/scrollflag.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/scrollflag.py#L49-L61 | def offset(self):
"""This property holds the vertical offset of the scroll flag area
relative to the top of the text editor."""
vsb = self.editor.verticalScrollBar()
style = vsb.style()
opt = QStyleOptionSlider()
vsb.initStyleOption(opt)
# Get the area in which t... | [
"def",
"offset",
"(",
"self",
")",
":",
"vsb",
"=",
"self",
".",
"editor",
".",
"verticalScrollBar",
"(",
")",
"style",
"=",
"vsb",
".",
"style",
"(",
")",
"opt",
"=",
"QStyleOptionSlider",
"(",
")",
"vsb",
".",
"initStyleOption",
"(",
"opt",
")",
"#... | This property holds the vertical offset of the scroll flag area
relative to the top of the text editor. | [
"This",
"property",
"holds",
"the",
"vertical",
"offset",
"of",
"the",
"scroll",
"flag",
"area",
"relative",
"to",
"the",
"top",
"of",
"the",
"text",
"editor",
"."
] | python | train |
chaimleib/intervaltree | intervaltree/interval.py | https://github.com/chaimleib/intervaltree/blob/ffb2b1667f8b832e89324a75a175be8440504c9d/intervaltree/interval.py#L255-L268 | def gt(self, other):
"""
Strictly greater than. Returns True if no part of this Interval
extends lower than or into other.
:raises ValueError: if either self or other is a null Interval
:param other: Interval or point
:return: True or False
:rtype: bool
""... | [
"def",
"gt",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"_raise_if_null",
"(",
"other",
")",
"if",
"hasattr",
"(",
"other",
",",
"'end'",
")",
":",
"return",
"self",
".",
"begin",
">=",
"other",
".",
"end",
"else",
":",
"return",
"self",
"."... | Strictly greater than. Returns True if no part of this Interval
extends lower than or into other.
:raises ValueError: if either self or other is a null Interval
:param other: Interval or point
:return: True or False
:rtype: bool | [
"Strictly",
"greater",
"than",
".",
"Returns",
"True",
"if",
"no",
"part",
"of",
"this",
"Interval",
"extends",
"lower",
"than",
"or",
"into",
"other",
".",
":",
"raises",
"ValueError",
":",
"if",
"either",
"self",
"or",
"other",
"is",
"a",
"null",
"Inte... | python | train |
Kortemme-Lab/klab | klab/biblio/pubmed.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/biblio/pubmed.py#L43-L86 | def convert(ids, from_type):
'''Uses the NCBI IP Converter API to converts a list of publication IDs in the same format e.g. DOI identifiers to
another format e.g. PubMed identifiers.
ids is a list of IDs of the type from_type e.g. a from_type of 'doi' specifies DOI identifiers.
The function ret... | [
"def",
"convert",
"(",
"ids",
",",
"from_type",
")",
":",
"if",
"from_type",
"not",
"in",
"converter_types",
":",
"raise",
"PubMedConverterTypeException",
"(",
"from_type",
")",
"# Avoid multiple requests of the same ID",
"mapping",
"=",
"{",
"}",
"ids",
"=",
"lis... | Uses the NCBI IP Converter API to converts a list of publication IDs in the same format e.g. DOI identifiers to
another format e.g. PubMed identifiers.
ids is a list of IDs of the type from_type e.g. a from_type of 'doi' specifies DOI identifiers.
The function returns a Python dict with the mappings... | [
"Uses",
"the",
"NCBI",
"IP",
"Converter",
"API",
"to",
"converts",
"a",
"list",
"of",
"publication",
"IDs",
"in",
"the",
"same",
"format",
"e",
".",
"g",
".",
"DOI",
"identifiers",
"to",
"another",
"format",
"e",
".",
"g",
".",
"PubMed",
"identifiers",
... | python | train |
sbarham/dsrt | build/lib/dsrt/application/Application.py | https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/build/lib/dsrt/application/Application.py#L69-L90 | def corpus(self):
'''Command to add a corpus to the dsrt library'''
# Initialize the addcorpus subcommand's argparser
description = '''The corpus subcommand has a number of subcommands of its own, including:
list\t-\tlists all available corpora in dsrt's library
add\t-\t... | [
"def",
"corpus",
"(",
"self",
")",
":",
"# Initialize the addcorpus subcommand's argparser",
"description",
"=",
"'''The corpus subcommand has a number of subcommands of its own, including:\n list\\t-\\tlists all available corpora in dsrt's library\n add\\t-\\tadds a corpus t... | Command to add a corpus to the dsrt library | [
"Command",
"to",
"add",
"a",
"corpus",
"to",
"the",
"dsrt",
"library"
] | python | train |
Azure/azure-kusto-python | azure-kusto-ingest/azure/kusto/ingest/_ingestion_blob_info.py | https://github.com/Azure/azure-kusto-python/blob/92466a2ae175d6353d1dee3496a02517b2a71a86/azure-kusto-ingest/azure/kusto/ingest/_ingestion_blob_info.py#L70-L80 | def _convert_dict_to_json(array):
""" Converts array to a json string """
return json.dumps(
array,
skipkeys=False,
allow_nan=False,
indent=None,
separators=(",", ":"),
sort_keys=True,
default=lambda o: o.__dict__,
) | [
"def",
"_convert_dict_to_json",
"(",
"array",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"array",
",",
"skipkeys",
"=",
"False",
",",
"allow_nan",
"=",
"False",
",",
"indent",
"=",
"None",
",",
"separators",
"=",
"(",
"\",\"",
",",
"\":\"",
")",
",... | Converts array to a json string | [
"Converts",
"array",
"to",
"a",
"json",
"string"
] | python | train |
GuyAllard/markov_clustering | markov_clustering/mcl.py | https://github.com/GuyAllard/markov_clustering/blob/28787cf64ef06bf024ff915246008c767ea830cf/markov_clustering/mcl.py#L123-L137 | def iterate(matrix, expansion, inflation):
"""
Run a single iteration (expansion + inflation) of the mcl algorithm
:param matrix: The matrix to perform the iteration on
:param expansion: Cluster expansion factor
:param inflation: Cluster inflation factor
"""
# Expansion
matrix = exp... | [
"def",
"iterate",
"(",
"matrix",
",",
"expansion",
",",
"inflation",
")",
":",
"# Expansion",
"matrix",
"=",
"expand",
"(",
"matrix",
",",
"expansion",
")",
"# Inflation",
"matrix",
"=",
"inflate",
"(",
"matrix",
",",
"inflation",
")",
"return",
"matrix"
] | Run a single iteration (expansion + inflation) of the mcl algorithm
:param matrix: The matrix to perform the iteration on
:param expansion: Cluster expansion factor
:param inflation: Cluster inflation factor | [
"Run",
"a",
"single",
"iteration",
"(",
"expansion",
"+",
"inflation",
")",
"of",
"the",
"mcl",
"algorithm",
":",
"param",
"matrix",
":",
"The",
"matrix",
"to",
"perform",
"the",
"iteration",
"on",
":",
"param",
"expansion",
":",
"Cluster",
"expansion",
"f... | python | train |
radujica/baloo | baloo/core/frame.py | https://github.com/radujica/baloo/blob/f6e05e35b73a75e8a300754c6bdc575e5f2d53b9/baloo/core/frame.py#L982-L1024 | def drop_duplicates(self, subset=None, keep='min'):
"""Return DataFrame with duplicate rows (excluding index) removed,
optionally only considering subset columns.
Note that the row order is NOT maintained due to hashing.
Parameters
----------
subset : list of str, optio... | [
"def",
"drop_duplicates",
"(",
"self",
",",
"subset",
"=",
"None",
",",
"keep",
"=",
"'min'",
")",
":",
"subset",
"=",
"check_and_obtain_subset_columns",
"(",
"subset",
",",
"self",
")",
"df",
"=",
"self",
".",
"reset_index",
"(",
")",
"df_names",
"=",
"... | Return DataFrame with duplicate rows (excluding index) removed,
optionally only considering subset columns.
Note that the row order is NOT maintained due to hashing.
Parameters
----------
subset : list of str, optional
Which columns to consider
keep : {'+', ... | [
"Return",
"DataFrame",
"with",
"duplicate",
"rows",
"(",
"excluding",
"index",
")",
"removed",
"optionally",
"only",
"considering",
"subset",
"columns",
"."
] | python | train |
The-Politico/politico-civic-election-night | electionnight/serializers/election.py | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/election.py#L128-L136 | def get_override_winner(self, obj):
"""Winner marked in backend."""
if obj.election.division.level.name == DivisionLevel.DISTRICT:
division = obj.election.division.parent
else:
division = obj.election.division
vote = obj.votes.filter(division=division).first()
... | [
"def",
"get_override_winner",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
".",
"election",
".",
"division",
".",
"level",
".",
"name",
"==",
"DivisionLevel",
".",
"DISTRICT",
":",
"division",
"=",
"obj",
".",
"election",
".",
"division",
".",
"parent... | Winner marked in backend. | [
"Winner",
"marked",
"in",
"backend",
"."
] | python | train |
tensorflow/lucid | lucid/optvis/objectives.py | https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/objectives.py#L442-L461 | def class_logit(layer, label):
"""Like channel, but for softmax layers.
Args:
layer: A layer name string.
label: Either a string (refering to a label in model.labels) or an int
label position.
Returns:
Objective maximizing a logit.
"""
def inner(T):
if isinstance(label, int):
cla... | [
"def",
"class_logit",
"(",
"layer",
",",
"label",
")",
":",
"def",
"inner",
"(",
"T",
")",
":",
"if",
"isinstance",
"(",
"label",
",",
"int",
")",
":",
"class_n",
"=",
"label",
"else",
":",
"class_n",
"=",
"T",
"(",
"\"labels\"",
")",
".",
"index",... | Like channel, but for softmax layers.
Args:
layer: A layer name string.
label: Either a string (refering to a label in model.labels) or an int
label position.
Returns:
Objective maximizing a logit. | [
"Like",
"channel",
"but",
"for",
"softmax",
"layers",
"."
] | python | train |
letuananh/chirptext | chirptext/texttaglib.py | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L265-L276 | def add_concept(self, concept_obj):
''' Add a concept to current concept list '''
if concept_obj is None:
raise Exception("Concept object cannot be None")
elif concept_obj in self.__concepts:
raise Exception("Concept object is already inside")
elif concept_obj.cid... | [
"def",
"add_concept",
"(",
"self",
",",
"concept_obj",
")",
":",
"if",
"concept_obj",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Concept object cannot be None\"",
")",
"elif",
"concept_obj",
"in",
"self",
".",
"__concepts",
":",
"raise",
"Exception",
"(",
... | Add a concept to current concept list | [
"Add",
"a",
"concept",
"to",
"current",
"concept",
"list"
] | python | train |
ssato/python-anytemplate | anytemplate/utils.py | https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/utils.py#L44-L57 | def uniq(items):
"""Remove duplicates in given list with its order kept.
>>> uniq([])
[]
>>> uniq([1, 4, 5, 1, 2, 3, 5, 10])
[1, 4, 5, 2, 3, 10]
"""
acc = items[:1]
for item in items[1:]:
if item not in acc:
acc += [item]
return acc | [
"def",
"uniq",
"(",
"items",
")",
":",
"acc",
"=",
"items",
"[",
":",
"1",
"]",
"for",
"item",
"in",
"items",
"[",
"1",
":",
"]",
":",
"if",
"item",
"not",
"in",
"acc",
":",
"acc",
"+=",
"[",
"item",
"]",
"return",
"acc"
] | Remove duplicates in given list with its order kept.
>>> uniq([])
[]
>>> uniq([1, 4, 5, 1, 2, 3, 5, 10])
[1, 4, 5, 2, 3, 10] | [
"Remove",
"duplicates",
"in",
"given",
"list",
"with",
"its",
"order",
"kept",
"."
] | python | train |
nicolargo/glances | glances/plugins/glances_cpu.py | https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/plugins/glances_cpu.py#L141-L188 | def update_snmp(self):
"""Update CPU stats using SNMP."""
# Init new stats
stats = self.get_init_value()
# Update stats using SNMP
if self.short_system_name in ('windows', 'esxi'):
# Windows or VMWare ESXi
# You can find the CPU utilization of windows sy... | [
"def",
"update_snmp",
"(",
"self",
")",
":",
"# Init new stats",
"stats",
"=",
"self",
".",
"get_init_value",
"(",
")",
"# Update stats using SNMP",
"if",
"self",
".",
"short_system_name",
"in",
"(",
"'windows'",
",",
"'esxi'",
")",
":",
"# Windows or VMWare ESXi"... | Update CPU stats using SNMP. | [
"Update",
"CPU",
"stats",
"using",
"SNMP",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/core/xcfunc.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/xcfunc.py#L149-L175 | def from_type_name(cls, typ, name):
"""Build the object from (type, name)."""
# Try aliases first.
for k, nt in cls.defined_aliases.items():
if typ is not None and typ != nt.type: continue
#print(name, nt.name)
if name == nt.name:
if len(k) == ... | [
"def",
"from_type_name",
"(",
"cls",
",",
"typ",
",",
"name",
")",
":",
"# Try aliases first.",
"for",
"k",
",",
"nt",
"in",
"cls",
".",
"defined_aliases",
".",
"items",
"(",
")",
":",
"if",
"typ",
"is",
"not",
"None",
"and",
"typ",
"!=",
"nt",
".",
... | Build the object from (type, name). | [
"Build",
"the",
"object",
"from",
"(",
"type",
"name",
")",
"."
] | python | train |
blockstack/blockstack-core | blockstack/lib/fast_sync.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/fast_sync.py#L492-L509 | def fast_sync_inspect_snapshot( snapshot_path ):
"""
Inspect a snapshot
Return useful information
Return {'status': True, 'signatures': ..., 'payload_size': ..., 'sig_append_offset': ..., 'hash': ...} on success
Return {'error': ...} on error
"""
with open(snapshot_path, 'r') as f:
i... | [
"def",
"fast_sync_inspect_snapshot",
"(",
"snapshot_path",
")",
":",
"with",
"open",
"(",
"snapshot_path",
",",
"'r'",
")",
"as",
"f",
":",
"info",
"=",
"fast_sync_inspect",
"(",
"f",
")",
"if",
"'error'",
"in",
"info",
":",
"log",
".",
"error",
"(",
"\"... | Inspect a snapshot
Return useful information
Return {'status': True, 'signatures': ..., 'payload_size': ..., 'sig_append_offset': ..., 'hash': ...} on success
Return {'error': ...} on error | [
"Inspect",
"a",
"snapshot",
"Return",
"useful",
"information",
"Return",
"{",
"status",
":",
"True",
"signatures",
":",
"...",
"payload_size",
":",
"...",
"sig_append_offset",
":",
"...",
"hash",
":",
"...",
"}",
"on",
"success",
"Return",
"{",
"error",
":",... | python | train |
googleads/googleads-python-lib | googleads/ad_manager.py | https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/googleads/ad_manager.py#L996-L1025 | def _ConvertDateTimeToOffset(self, date_time_value):
"""Converts the PQL formatted response for a dateTime object.
Output conforms to ISO 8061 format, e.g. 'YYYY-MM-DDTHH:MM:SSz.'
Args:
date_time_value: dict The date time value from the PQL response.
Returns:
str: A string representation ... | [
"def",
"_ConvertDateTimeToOffset",
"(",
"self",
",",
"date_time_value",
")",
":",
"date_time_obj",
"=",
"datetime",
".",
"datetime",
"(",
"int",
"(",
"date_time_value",
"[",
"'date'",
"]",
"[",
"'year'",
"]",
")",
",",
"int",
"(",
"date_time_value",
"[",
"'d... | Converts the PQL formatted response for a dateTime object.
Output conforms to ISO 8061 format, e.g. 'YYYY-MM-DDTHH:MM:SSz.'
Args:
date_time_value: dict The date time value from the PQL response.
Returns:
str: A string representation of the date time value uniform to
ReportService. | [
"Converts",
"the",
"PQL",
"formatted",
"response",
"for",
"a",
"dateTime",
"object",
"."
] | python | train |
SBRG/ssbio | ssbio/pipeline/atlas2.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/atlas2.py#L242-L310 | def filter_genes_and_strains(self, remove_genes_not_in_reference_model=True,
remove_strains_with_no_orthology=True, remove_strains_with_no_differences=False,
custom_keep_strains=None, custom_keep_genes=None):
"""Filters the analysis by keeping a ... | [
"def",
"filter_genes_and_strains",
"(",
"self",
",",
"remove_genes_not_in_reference_model",
"=",
"True",
",",
"remove_strains_with_no_orthology",
"=",
"True",
",",
"remove_strains_with_no_differences",
"=",
"False",
",",
"custom_keep_strains",
"=",
"None",
",",
"custom_keep... | Filters the analysis by keeping a subset of strains or genes based on certain criteria.
Args:
remove_genes_not_in_reference_model (bool): Remove genes from reference model not in orthology matrix
remove_strains_with_no_orthology (bool): Remove strains which have no orthologous genes fou... | [
"Filters",
"the",
"analysis",
"by",
"keeping",
"a",
"subset",
"of",
"strains",
"or",
"genes",
"based",
"on",
"certain",
"criteria",
"."
] | python | train |
nerdvegas/rez | src/rez/package_order.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_order.py#L141-L178 | def to_pod(self):
"""
Example (in yaml):
type: per_family
orderers:
- packages: ['foo', 'bah']
type: version_split
first_version: '4.0.5'
- packages: ['python']
type: sorted
descending: false
... | [
"def",
"to_pod",
"(",
"self",
")",
":",
"orderers",
"=",
"{",
"}",
"packages",
"=",
"{",
"}",
"# group package fams by orderer they use",
"for",
"fam",
",",
"orderer",
"in",
"self",
".",
"order_dict",
".",
"iteritems",
"(",
")",
":",
"k",
"=",
"id",
"(",... | Example (in yaml):
type: per_family
orderers:
- packages: ['foo', 'bah']
type: version_split
first_version: '4.0.5'
- packages: ['python']
type: sorted
descending: false
default_order:
type... | [
"Example",
"(",
"in",
"yaml",
")",
":"
] | python | train |
tschaume/ccsgp_get_started | ccsgp_get_started/examples/utils.py | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/utils.py#L49-L52 | def getEdges(npArr):
"""get np array of bin edges"""
edges = np.concatenate(([0], npArr[:,0] + npArr[:,2]))
return np.array([Decimal(str(i)) for i in edges]) | [
"def",
"getEdges",
"(",
"npArr",
")",
":",
"edges",
"=",
"np",
".",
"concatenate",
"(",
"(",
"[",
"0",
"]",
",",
"npArr",
"[",
":",
",",
"0",
"]",
"+",
"npArr",
"[",
":",
",",
"2",
"]",
")",
")",
"return",
"np",
".",
"array",
"(",
"[",
"Dec... | get np array of bin edges | [
"get",
"np",
"array",
"of",
"bin",
"edges"
] | python | train |
NuGrid/NuGridPy | nugridpy/ppn.py | https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/ppn.py#L478-L540 | def getCycleData(self, attri, fname, numtype='cycNum'):
"""
In this method a column of data for the associated cycle
attribute is returned.
Parameters
----------
attri : string
The name of the attribute we are looking for.
fname : string
T... | [
"def",
"getCycleData",
"(",
"self",
",",
"attri",
",",
"fname",
",",
"numtype",
"=",
"'cycNum'",
")",
":",
"fname",
"=",
"self",
".",
"findFile",
"(",
"fname",
",",
"numtype",
")",
"if",
"self",
".",
"inputdir",
"==",
"''",
":",
"self",
".",
"inputdi... | In this method a column of data for the associated cycle
attribute is returned.
Parameters
----------
attri : string
The name of the attribute we are looking for.
fname : string
The name of the file we are getting the data from or the
cycle nu... | [
"In",
"this",
"method",
"a",
"column",
"of",
"data",
"for",
"the",
"associated",
"cycle",
"attribute",
"is",
"returned",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.