repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
blockstack/blockstack-core | blockstack/lib/nameset/db.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2458-L2474 | def namedb_get_num_names( cur, current_block, include_expired=False ):
"""
Get the number of names that exist at the current block
"""
unexpired_query = ""
unexpired_args = ()
if not include_expired:
# count all names, including expired ones
unexpired_query, unexpired_args = nam... | [
"def",
"namedb_get_num_names",
"(",
"cur",
",",
"current_block",
",",
"include_expired",
"=",
"False",
")",
":",
"unexpired_query",
"=",
"\"\"",
"unexpired_args",
"=",
"(",
")",
"if",
"not",
"include_expired",
":",
"# count all names, including expired ones",
"unexpir... | Get the number of names that exist at the current block | [
"Get",
"the",
"number",
"of",
"names",
"that",
"exist",
"at",
"the",
"current",
"block"
] | python | train | 42.529412 |
SBRG/ssbio | ssbio/protein/structure/properties/residues.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/properties/residues.py#L391-L421 | def hse_output(pdb_file, file_type):
"""
The solvent exposure of an amino acid residue is important for analyzing,
understanding and predicting aspects of protein structure and function [73].
A residue's solvent exposure can be classified as four categories: exposed, partly exposed,
buried and deepl... | [
"def",
"hse_output",
"(",
"pdb_file",
",",
"file_type",
")",
":",
"# Get the first model",
"my_structure",
"=",
"StructureIO",
"(",
"pdb_file",
")",
"model",
"=",
"my_structure",
".",
"first_model",
"# Calculate HSEalpha",
"exp_ca",
"=",
"HSExposureCA",
"(",
"model"... | The solvent exposure of an amino acid residue is important for analyzing,
understanding and predicting aspects of protein structure and function [73].
A residue's solvent exposure can be classified as four categories: exposed, partly exposed,
buried and deeply buried residues. Hamelryck et al. [73] establi... | [
"The",
"solvent",
"exposure",
"of",
"an",
"amino",
"acid",
"residue",
"is",
"important",
"for",
"analyzing",
"understanding",
"and",
"predicting",
"aspects",
"of",
"protein",
"structure",
"and",
"function",
"[",
"73",
"]",
".",
"A",
"residue",
"s",
"solvent",
... | python | train | 37.580645 |
senaite/senaite.core | bika/lims/browser/widgets/serviceswidget.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/widgets/serviceswidget.py#L205-L210 | def process_form(self, instance, field, form, empty_marker=None,
emptyReturnsMarker=False, validating=True):
"""Return UIDs of the selected services
"""
service_uids = form.get("uids", [])
return service_uids, {} | [
"def",
"process_form",
"(",
"self",
",",
"instance",
",",
"field",
",",
"form",
",",
"empty_marker",
"=",
"None",
",",
"emptyReturnsMarker",
"=",
"False",
",",
"validating",
"=",
"True",
")",
":",
"service_uids",
"=",
"form",
".",
"get",
"(",
"\"uids\"",
... | Return UIDs of the selected services | [
"Return",
"UIDs",
"of",
"the",
"selected",
"services"
] | python | train | 43.333333 |
mryellow/maze_explorer | mazeexp/engine/score.py | https://github.com/mryellow/maze_explorer/blob/ab8a25ccd05105d2fe57e0213d690cfc07e45827/mazeexp/engine/score.py#L66-L75 | def update(self, dt):
"""
Responsabilities:
Updates game engine each tick
Copies new stats into labels
"""
for key, value in self.labels.iteritems():
str_val = str(int(self.stats[key]))
self.msgs[key][0].element.text = self.labels[key] + st... | [
"def",
"update",
"(",
"self",
",",
"dt",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"labels",
".",
"iteritems",
"(",
")",
":",
"str_val",
"=",
"str",
"(",
"int",
"(",
"self",
".",
"stats",
"[",
"key",
"]",
")",
")",
"self",
".",
... | Responsabilities:
Updates game engine each tick
Copies new stats into labels | [
"Responsabilities",
":",
"Updates",
"game",
"engine",
"each",
"tick",
"Copies",
"new",
"stats",
"into",
"labels"
] | python | train | 38.8 |
epfl-lts2/pygsp | pygsp/graphs/graph.py | https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/graph.py#L798-L811 | def lmax(self):
r"""Largest eigenvalue of the graph Laplacian.
Can be exactly computed by :func:`compute_fourier_basis` or
approximated by :func:`estimate_lmax`.
"""
if self._lmax is None:
self.logger.warning('The largest eigenvalue G.lmax is not '
... | [
"def",
"lmax",
"(",
"self",
")",
":",
"if",
"self",
".",
"_lmax",
"is",
"None",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'The largest eigenvalue G.lmax is not '",
"'available, we need to estimate it. '",
"'Explicitly call G.estimate_lmax() or '",
"'G.compute_four... | r"""Largest eigenvalue of the graph Laplacian.
Can be exactly computed by :func:`compute_fourier_basis` or
approximated by :func:`estimate_lmax`. | [
"r",
"Largest",
"eigenvalue",
"of",
"the",
"graph",
"Laplacian",
"."
] | python | train | 44.714286 |
productml/blurr | blurr/core/store.py | https://github.com/productml/blurr/blob/1b688b2c4a9bbbb2139c58bf0682ddc05a6c24fa/blurr/core/store.py#L79-L89 | def _get_range_dimension_key(self,
base_key: Key,
start_time: datetime,
end_time: datetime,
count: int = 0) -> List[Tuple[Key, Any]]:
"""
Returns the list of items from the... | [
"def",
"_get_range_dimension_key",
"(",
"self",
",",
"base_key",
":",
"Key",
",",
"start_time",
":",
"datetime",
",",
"end_time",
":",
"datetime",
",",
"count",
":",
"int",
"=",
"0",
")",
"->",
"List",
"[",
"Tuple",
"[",
"Key",
",",
"Any",
"]",
"]",
... | Returns the list of items from the store based on the given time range or count.
This is used when the key being used is a DIMENSION key. | [
"Returns",
"the",
"list",
"of",
"items",
"from",
"the",
"store",
"based",
"on",
"the",
"given",
"time",
"range",
"or",
"count",
"."
] | python | train | 42.727273 |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L310-L313 | def ToMicroseconds(self):
"""Converts a Duration to microseconds."""
micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND)
return self.seconds * _MICROS_PER_SECOND + micros | [
"def",
"ToMicroseconds",
"(",
"self",
")",
":",
"micros",
"=",
"_RoundTowardZero",
"(",
"self",
".",
"nanos",
",",
"_NANOS_PER_MICROSECOND",
")",
"return",
"self",
".",
"seconds",
"*",
"_MICROS_PER_SECOND",
"+",
"micros"
] | Converts a Duration to microseconds. | [
"Converts",
"a",
"Duration",
"to",
"microseconds",
"."
] | python | train | 47.25 |
disqus/nydus | nydus/contrib/ketama.py | https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/contrib/ketama.py#L95-L107 | def remove_node(self, node):
"""
Removes node from circle and rebuild it.
"""
try:
self._nodes.remove(node)
del self._weights[node]
except (KeyError, ValueError):
pass
self._hashring = dict()
self._sorted_keys = []
... | [
"def",
"remove_node",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"self",
".",
"_nodes",
".",
"remove",
"(",
"node",
")",
"del",
"self",
".",
"_weights",
"[",
"node",
"]",
"except",
"(",
"KeyError",
",",
"ValueError",
")",
":",
"pass",
"self",
... | Removes node from circle and rebuild it. | [
"Removes",
"node",
"from",
"circle",
"and",
"rebuild",
"it",
"."
] | python | train | 25.230769 |
edeposit/marcxml2mods | src/marcxml2mods/xslt_transformer.py | https://github.com/edeposit/marcxml2mods/blob/7b44157e859b4d2a372f79598ddbf77e43d39812/src/marcxml2mods/xslt_transformer.py#L104-L127 | def _read_marcxml(xml):
"""
Read MARC XML or OAI file, convert, add namespace and return XML in
required format with all necessities.
Args:
xml (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
Returns:
obj: Required XML parsed with ``lxml.etr... | [
"def",
"_read_marcxml",
"(",
"xml",
")",
":",
"# read file, if `xml` is valid file path",
"marc_xml",
"=",
"_read_content_or_path",
"(",
"xml",
")",
"# process input file - convert it from possible OAI to MARC XML and add",
"# required XML namespaces",
"marc_xml",
"=",
"_oai_to_xml... | Read MARC XML or OAI file, convert, add namespace and return XML in
required format with all necessities.
Args:
xml (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
Returns:
obj: Required XML parsed with ``lxml.etree``. | [
"Read",
"MARC",
"XML",
"or",
"OAI",
"file",
"convert",
"add",
"namespace",
"and",
"return",
"XML",
"in",
"required",
"format",
"with",
"all",
"necessities",
"."
] | python | train | 27.375 |
ska-sa/kittens | Kittens/utils.py | https://github.com/ska-sa/kittens/blob/92058e065ddffa5d00a44749145a6f917e0f31dc/Kittens/utils.py#L398-L404 | def weakref_proxy(obj):
"""returns either a weakref.proxy for the object, or if object is already a proxy,
returns itself."""
if type(obj) in weakref.ProxyTypes:
return obj
else:
return weakref.proxy(obj) | [
"def",
"weakref_proxy",
"(",
"obj",
")",
":",
"if",
"type",
"(",
"obj",
")",
"in",
"weakref",
".",
"ProxyTypes",
":",
"return",
"obj",
"else",
":",
"return",
"weakref",
".",
"proxy",
"(",
"obj",
")"
] | returns either a weakref.proxy for the object, or if object is already a proxy,
returns itself. | [
"returns",
"either",
"a",
"weakref",
".",
"proxy",
"for",
"the",
"object",
"or",
"if",
"object",
"is",
"already",
"a",
"proxy",
"returns",
"itself",
"."
] | python | train | 32.857143 |
juju-solutions/jujuresources | jujuresources/cli.py | https://github.com/juju-solutions/jujuresources/blob/7d2c5f50981784cc4b5cde216b930f6d59c951a4/jujuresources/cli.py#L107-L118 | def fetch(opts):
"""
Create a local mirror of one or more resources.
"""
resources = _load(opts.resources, opts.output_dir)
if opts.all:
opts.resource_names = ALL
reporthook = None if opts.quiet else lambda name: print('Fetching {}...'.format(name))
if opts.verbose:
backend.V... | [
"def",
"fetch",
"(",
"opts",
")",
":",
"resources",
"=",
"_load",
"(",
"opts",
".",
"resources",
",",
"opts",
".",
"output_dir",
")",
"if",
"opts",
".",
"all",
":",
"opts",
".",
"resource_names",
"=",
"ALL",
"reporthook",
"=",
"None",
"if",
"opts",
"... | Create a local mirror of one or more resources. | [
"Create",
"a",
"local",
"mirror",
"of",
"one",
"or",
"more",
"resources",
"."
] | python | train | 35.833333 |
pauleveritt/kaybee | kaybee/plugins/events.py | https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/events.py#L106-L112 | def call_purge_doc(cls, kb_app, sphinx_app: Sphinx,
sphinx_env: BuildEnvironment,
docname: str):
""" On env-purge-doc, do callbacks """
for callback in EventAction.get_callbacks(kb_app, SphinxEvent.EPD):
callback(kb_app, sphinx_app, sphinx_env, ... | [
"def",
"call_purge_doc",
"(",
"cls",
",",
"kb_app",
",",
"sphinx_app",
":",
"Sphinx",
",",
"sphinx_env",
":",
"BuildEnvironment",
",",
"docname",
":",
"str",
")",
":",
"for",
"callback",
"in",
"EventAction",
".",
"get_callbacks",
"(",
"kb_app",
",",
"SphinxE... | On env-purge-doc, do callbacks | [
"On",
"env",
"-",
"purge",
"-",
"doc",
"do",
"callbacks"
] | python | train | 46 |
saltstack/salt | salt/modules/apcups.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apcups.py#L86-L102 | def status_charge():
'''
Return battery charge
CLI Example:
.. code-block:: bash
salt '*' apcups.status_charge
'''
data = status()
if 'BCHARGE' in data:
charge = data['BCHARGE'].split()
if charge[1].lower() == 'percent':
return float(charge[0])
ret... | [
"def",
"status_charge",
"(",
")",
":",
"data",
"=",
"status",
"(",
")",
"if",
"'BCHARGE'",
"in",
"data",
":",
"charge",
"=",
"data",
"[",
"'BCHARGE'",
"]",
".",
"split",
"(",
")",
"if",
"charge",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"==",
"'per... | Return battery charge
CLI Example:
.. code-block:: bash
salt '*' apcups.status_charge | [
"Return",
"battery",
"charge"
] | python | train | 20 |
jgillick/LendingClub | lendingclub/filters.py | https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L197-L207 | def __normalize_grades(self):
"""
Adjust the grades list.
If a grade has been set, set All to false
"""
if 'grades' in self and self['grades']['All'] is True:
for grade in self['grades']:
if grade != 'All' and self['grades'][grade] is True:
... | [
"def",
"__normalize_grades",
"(",
"self",
")",
":",
"if",
"'grades'",
"in",
"self",
"and",
"self",
"[",
"'grades'",
"]",
"[",
"'All'",
"]",
"is",
"True",
":",
"for",
"grade",
"in",
"self",
"[",
"'grades'",
"]",
":",
"if",
"grade",
"!=",
"'All'",
"and... | Adjust the grades list.
If a grade has been set, set All to false | [
"Adjust",
"the",
"grades",
"list",
".",
"If",
"a",
"grade",
"has",
"been",
"set",
"set",
"All",
"to",
"false"
] | python | train | 34.090909 |
PySimpleGUI/PySimpleGUI | PySimpleGUIWeb/PySimpleGUIWeb.py | https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/PySimpleGUIWeb.py#L6596-L6647 | def PopupGetFolder(message, default_path='', no_window=False, size=(None, None), button_color=None,
background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False,
grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None):
... | [
"def",
"PopupGetFolder",
"(",
"message",
",",
"default_path",
"=",
"''",
",",
"no_window",
"=",
"False",
",",
"size",
"=",
"(",
"None",
",",
"None",
")",
",",
"button_color",
"=",
"None",
",",
"background_color",
"=",
"None",
",",
"text_color",
"=",
"Non... | Display popup with text entry field and browse button. Browse for folder
:param message:
:param default_path:
:param no_window:
:param size:
:param button_color:
:param background_color:
:param text_color:
:param icon:
:param font:
:param no_titlebar:
:param grab_anywhere:
... | [
"Display",
"popup",
"with",
"text",
"entry",
"field",
"and",
"browse",
"button",
".",
"Browse",
"for",
"folder",
":",
"param",
"message",
":",
":",
"param",
"default_path",
":",
":",
"param",
"no_window",
":",
":",
"param",
"size",
":",
":",
"param",
"bu... | python | train | 37.730769 |
alfredodeza/remoto | remoto/backends/__init__.py | https://github.com/alfredodeza/remoto/blob/b7625e571a4b6c83f9589a1e9ad07354e42bf0d3/remoto/backends/__init__.py#L277-L292 | def needs_ssh(hostname, _socket=None):
"""
Obtains remote hostname of the socket and cuts off the domain part
of its FQDN.
"""
if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']:
return False
_socket = _socket or socket
fqdn = _socket.getfqdn()
if hostname == fqdn:
... | [
"def",
"needs_ssh",
"(",
"hostname",
",",
"_socket",
"=",
"None",
")",
":",
"if",
"hostname",
".",
"lower",
"(",
")",
"in",
"[",
"'localhost'",
",",
"'127.0.0.1'",
",",
"'127.0.1.1'",
"]",
":",
"return",
"False",
"_socket",
"=",
"_socket",
"or",
"socket"... | Obtains remote hostname of the socket and cuts off the domain part
of its FQDN. | [
"Obtains",
"remote",
"hostname",
"of",
"the",
"socket",
"and",
"cuts",
"off",
"the",
"domain",
"part",
"of",
"its",
"FQDN",
"."
] | python | train | 33.125 |
Becksteinlab/GromacsWrapper | gromacs/fileformats/convert.py | https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/convert.py#L178-L189 | def _convert_fancy(self, field):
"""Convert to a list (sep != None) and convert list elements."""
if self.sep is False:
x = self._convert_singlet(field)
else:
x = tuple([self._convert_singlet(s) for s in field.split(self.sep)])
if len(x) == 0:
... | [
"def",
"_convert_fancy",
"(",
"self",
",",
"field",
")",
":",
"if",
"self",
".",
"sep",
"is",
"False",
":",
"x",
"=",
"self",
".",
"_convert_singlet",
"(",
"field",
")",
"else",
":",
"x",
"=",
"tuple",
"(",
"[",
"self",
".",
"_convert_singlet",
"(",
... | Convert to a list (sep != None) and convert list elements. | [
"Convert",
"to",
"a",
"list",
"(",
"sep",
"!",
"=",
"None",
")",
"and",
"convert",
"list",
"elements",
"."
] | python | valid | 35.583333 |
OpenAssets/openassets | openassets/protocol.py | https://github.com/OpenAssets/openassets/blob/e8eb5b80b9703c80980cb275dd85f17d50e39c60/openassets/protocol.py#L444-L467 | def parse_script(output_script):
"""
Parses an output and returns the payload if the output matches the right pattern for a marker output,
or None otherwise.
:param CScript output_script: The output script to be parsed.
:return: The marker output payload if the output fits the p... | [
"def",
"parse_script",
"(",
"output_script",
")",
":",
"script_iterator",
"=",
"output_script",
".",
"raw_iter",
"(",
")",
"try",
":",
"first_opcode",
",",
"_",
",",
"_",
"=",
"next",
"(",
"script_iterator",
",",
"(",
"None",
",",
"None",
",",
"None",
")... | Parses an output and returns the payload if the output matches the right pattern for a marker output,
or None otherwise.
:param CScript output_script: The output script to be parsed.
:return: The marker output payload if the output fits the pattern, None otherwise.
:rtype: bytes | [
"Parses",
"an",
"output",
"and",
"returns",
"the",
"payload",
"if",
"the",
"output",
"matches",
"the",
"right",
"pattern",
"for",
"a",
"marker",
"output",
"or",
"None",
"otherwise",
"."
] | python | train | 39.458333 |
tBaxter/tango-comments | build/lib/tango_comments/forms.py | https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L110-L126 | def get_comment_object(self):
"""
Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
ValueError if not.
Does not set any of the fields that would come from a Request object
(i.e. ``user... | [
"def",
"get_comment_object",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_valid",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"get_comment_object may only be called on valid forms\"",
")",
"CommentModel",
"=",
"self",
".",
"get_comment_model",
"(",
")",
"... | Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
ValueError if not.
Does not set any of the fields that would come from a Request object
(i.e. ``user`` or ``ip_address``). | [
"Return",
"a",
"new",
"(",
"unsaved",
")",
"comment",
"object",
"based",
"on",
"the",
"information",
"in",
"this",
"form",
".",
"Assumes",
"that",
"the",
"form",
"is",
"already",
"validated",
"and",
"will",
"throw",
"a",
"ValueError",
"if",
"not",
"."
] | python | train | 37.470588 |
swharden/SWHLab | swhlab/core.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/core.py#L445-L449 | def output_touch(self):
"""ensure the ./swhlab/ folder exists."""
if not os.path.exists(self.outFolder):
self.log.debug("creating %s",self.outFolder)
os.mkdir(self.outFolder) | [
"def",
"output_touch",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"outFolder",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"creating %s\"",
",",
"self",
".",
"outFolder",
")",
"os",
".",
"mkdir",
... | ensure the ./swhlab/ folder exists. | [
"ensure",
"the",
".",
"/",
"swhlab",
"/",
"folder",
"exists",
"."
] | python | valid | 42 |
inveniosoftware/invenio-pidstore | invenio_pidstore/alembic/999c62899c20_create_pidstore_tables.py | https://github.com/inveniosoftware/invenio-pidstore/blob/8bf35f4e62d5dcaf1a2cfe5803245ba5220a9b78/invenio_pidstore/alembic/999c62899c20_create_pidstore_tables.py#L22-L72 | def upgrade():
"""Upgrade database."""
op.create_table(
'pidstore_pid',
sa.Column('created', sa.DateTime(), nullable=False),
sa.Column('updated', sa.DateTime(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pid_type', sa.String(length=6), null... | [
"def",
"upgrade",
"(",
")",
":",
"op",
".",
"create_table",
"(",
"'pidstore_pid'",
",",
"sa",
".",
"Column",
"(",
"'created'",
",",
"sa",
".",
"DateTime",
"(",
")",
",",
"nullable",
"=",
"False",
")",
",",
"sa",
".",
"Column",
"(",
"'updated'",
",",
... | Upgrade database. | [
"Upgrade",
"database",
"."
] | python | train | 34.54902 |
tammoippen/geohash-hilbert | geohash_hilbert/_hilbert.py | https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_hilbert.py#L205-L230 | def _xy2hash(x, y, dim):
"""Convert (x, y) to hashcode.
Based on the implementation here:
https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503
Pure python implementation.
Parameters:
x: int x value of point [0, dim) in dim x dim coord system
y: int ... | [
"def",
"_xy2hash",
"(",
"x",
",",
"y",
",",
"dim",
")",
":",
"d",
"=",
"0",
"lvl",
"=",
"dim",
">>",
"1",
"while",
"(",
"lvl",
">",
"0",
")",
":",
"rx",
"=",
"int",
"(",
"(",
"x",
"&",
"lvl",
")",
">",
"0",
")",
"ry",
"=",
"int",
"(",
... | Convert (x, y) to hashcode.
Based on the implementation here:
https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503
Pure python implementation.
Parameters:
x: int x value of point [0, dim) in dim x dim coord system
y: int y value of point [0, dim) ... | [
"Convert",
"(",
"x",
"y",
")",
"to",
"hashcode",
"."
] | python | train | 29.923077 |
pysal/spglm | spglm/base.py | https://github.com/pysal/spglm/blob/1339898adcb7e1638f1da83d57aa37392525f018/spglm/base.py#L258-L338 | def cov_params(self, r_matrix=None, column=None, scale=None, cov_p=None,
other=None):
"""
Returns the variance/covariance matrix.
The variance/covariance matrix can be of a linear contrast
of the estimates of params or all params multiplied by scale which
will ... | [
"def",
"cov_params",
"(",
"self",
",",
"r_matrix",
"=",
"None",
",",
"column",
"=",
"None",
",",
"scale",
"=",
"None",
",",
"cov_p",
"=",
"None",
",",
"other",
"=",
"None",
")",
":",
"if",
"(",
"hasattr",
"(",
"self",
",",
"'mle_settings'",
")",
"a... | Returns the variance/covariance matrix.
The variance/covariance matrix can be of a linear contrast
of the estimates of params or all params multiplied by scale which
will usually be an estimate of sigma^2. Scale is assumed to be
a scalar.
Parameters
----------
r_... | [
"Returns",
"the",
"variance",
"/",
"covariance",
"matrix",
".",
"The",
"variance",
"/",
"covariance",
"matrix",
"can",
"be",
"of",
"a",
"linear",
"contrast",
"of",
"the",
"estimates",
"of",
"params",
"or",
"all",
"params",
"multiplied",
"by",
"scale",
"which... | python | train | 42.17284 |
delph-in/pydelphin | delphin/mrs/__init__.py | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/__init__.py#L53-L95 | def convert(txt, src_fmt, tgt_fmt, single=True, **kwargs):
"""
Convert a textual representation of \*MRS from one the src_fmt
representation to the tgt_fmt representation. By default, only
read and convert a single \*MRS object (e.g. for `mrx` this
starts at <mrs> and not <mrs-list>), but changing t... | [
"def",
"convert",
"(",
"txt",
",",
"src_fmt",
",",
"tgt_fmt",
",",
"single",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"importlib",
"import",
"import_module",
"reader",
"=",
"import_module",
"(",
"'{}.{}'",
".",
"format",
"(",
"'delphin.mrs'"... | Convert a textual representation of \*MRS from one the src_fmt
representation to the tgt_fmt representation. By default, only
read and convert a single \*MRS object (e.g. for `mrx` this
starts at <mrs> and not <mrs-list>), but changing the `mode`
argument to `corpus` (alternatively: `list`) reads and co... | [
"Convert",
"a",
"textual",
"representation",
"of",
"\\",
"*",
"MRS",
"from",
"one",
"the",
"src_fmt",
"representation",
"to",
"the",
"tgt_fmt",
"representation",
".",
"By",
"default",
"only",
"read",
"and",
"convert",
"a",
"single",
"\\",
"*",
"MRS",
"object... | python | train | 42 |
sdispater/orator | orator/schema/builder.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/builder.py#L62-L78 | def table(self, table):
"""
Modify a table on the schema.
:param table: The table
"""
try:
blueprint = self._create_blueprint(table)
yield blueprint
except Exception as e:
raise
try:
self._build(blueprint)
... | [
"def",
"table",
"(",
"self",
",",
"table",
")",
":",
"try",
":",
"blueprint",
"=",
"self",
".",
"_create_blueprint",
"(",
"table",
")",
"yield",
"blueprint",
"except",
"Exception",
"as",
"e",
":",
"raise",
"try",
":",
"self",
".",
"_build",
"(",
"bluep... | Modify a table on the schema.
:param table: The table | [
"Modify",
"a",
"table",
"on",
"the",
"schema",
"."
] | python | train | 20 |
bspaans/python-mingus | mingus/extra/tunings.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L274-L281 | def frets_to_NoteContainer(self, fingering):
"""Convert a list such as returned by find_fret to a NoteContainer."""
res = []
for (string, fret) in enumerate(fingering):
if fret is not None:
res.append(self.get_Note(string, fret))
return NoteContainer(res) | [
"def",
"frets_to_NoteContainer",
"(",
"self",
",",
"fingering",
")",
":",
"res",
"=",
"[",
"]",
"for",
"(",
"string",
",",
"fret",
")",
"in",
"enumerate",
"(",
"fingering",
")",
":",
"if",
"fret",
"is",
"not",
"None",
":",
"res",
".",
"append",
"(",
... | Convert a list such as returned by find_fret to a NoteContainer. | [
"Convert",
"a",
"list",
"such",
"as",
"returned",
"by",
"find_fret",
"to",
"a",
"NoteContainer",
"."
] | python | train | 38.625 |
CS207-Final-Project-Group-10/cs207-FinalProject | fluxions/elementary_functions.py | https://github.com/CS207-Final-Project-Group-10/cs207-FinalProject/blob/842e9c2d3ca1490cef18c086dfde81856d8d3a82/fluxions/elementary_functions.py#L362-L368 | def _deriv_logaddexp2(x1, x2):
"""The derivative of f(x, y) = log2(2^x + 2^y)"""
y1 = np.exp2(x1)
y2 = np.exp2(x2)
df_dx1 = y1 / (y1 + y2)
df_dx2 = y2 / (y1 + y2)
return np.vstack([df_dx1, df_dx2]).T | [
"def",
"_deriv_logaddexp2",
"(",
"x1",
",",
"x2",
")",
":",
"y1",
"=",
"np",
".",
"exp2",
"(",
"x1",
")",
"y2",
"=",
"np",
".",
"exp2",
"(",
"x2",
")",
"df_dx1",
"=",
"y1",
"/",
"(",
"y1",
"+",
"y2",
")",
"df_dx2",
"=",
"y2",
"/",
"(",
"y1"... | The derivative of f(x, y) = log2(2^x + 2^y) | [
"The",
"derivative",
"of",
"f",
"(",
"x",
"y",
")",
"=",
"log2",
"(",
"2^x",
"+",
"2^y",
")"
] | python | train | 31 |
apache/incubator-superset | superset/models/core.py | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L305-L322 | def get_viz(self, force=False):
"""Creates :py:class:viz.BaseViz object from the url_params_multidict.
:return: object of the 'viz_type' type that is taken from the
url_params_multidict or self.params.
:rtype: :py:class:viz.BaseViz
"""
slice_params = json.loads(self.... | [
"def",
"get_viz",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"slice_params",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"params",
")",
"slice_params",
"[",
"'slice_id'",
"]",
"=",
"self",
".",
"id",
"slice_params",
"[",
"'json'",
"]",
"=",
... | Creates :py:class:viz.BaseViz object from the url_params_multidict.
:return: object of the 'viz_type' type that is taken from the
url_params_multidict or self.params.
:rtype: :py:class:viz.BaseViz | [
"Creates",
":",
"py",
":",
"class",
":",
"viz",
".",
"BaseViz",
"object",
"from",
"the",
"url_params_multidict",
"."
] | python | train | 37.833333 |
jart/fabulous | fabulous/text.py | https://github.com/jart/fabulous/blob/19903cf0a980b82f5928c3bec1f28b6bdd3785bd/fabulous/text.py#L180-L208 | def get_font_files():
"""Returns a list of all font files we could find
Returned as a list of dir/files tuples::
get_font_files() -> {'FontName': '/abs/FontName.ttf', ...]
For example::
>>> fonts = get_font_files()
>>> 'NotoSans-Bold' in fonts
True
>>> fonts['Noto... | [
"def",
"get_font_files",
"(",
")",
":",
"roots",
"=",
"[",
"'/usr/share/fonts/truetype'",
",",
"# where ubuntu puts fonts",
"'/usr/share/fonts'",
",",
"# where fedora puts fonts",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.fonts'",
")",
",",
"# custom user fonts",
... | Returns a list of all font files we could find
Returned as a list of dir/files tuples::
get_font_files() -> {'FontName': '/abs/FontName.ttf', ...]
For example::
>>> fonts = get_font_files()
>>> 'NotoSans-Bold' in fonts
True
>>> fonts['NotoSans-Bold'].endswith('/NotoSa... | [
"Returns",
"a",
"list",
"of",
"all",
"font",
"files",
"we",
"could",
"find"
] | python | train | 31 |
chrisrink10/basilisp | src/basilisp/lang/compiler/optimizer.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/optimizer.py#L47-L60 | def visit_FunctionDef(self, node: ast.FunctionDef) -> Optional[ast.AST]:
"""Eliminate dead code from function bodies."""
new_node = self.generic_visit(node)
assert isinstance(new_node, ast.FunctionDef)
return ast.copy_location(
ast.FunctionDef(
name=new_node.n... | [
"def",
"visit_FunctionDef",
"(",
"self",
",",
"node",
":",
"ast",
".",
"FunctionDef",
")",
"->",
"Optional",
"[",
"ast",
".",
"AST",
"]",
":",
"new_node",
"=",
"self",
".",
"generic_visit",
"(",
"node",
")",
"assert",
"isinstance",
"(",
"new_node",
",",
... | Eliminate dead code from function bodies. | [
"Eliminate",
"dead",
"code",
"from",
"function",
"bodies",
"."
] | python | test | 39.071429 |
TissueMAPS/TmDeploy | tmdeploy/log.py | https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/tmdeploy/log.py#L68-L92 | def configure_logging(level=logging.DEBUG):
'''Configures the root logger for command line applications.
A stream handler will be added to the logger that directs
messages to the standard error stream.
By default, *no* messages will be filtered out: set a higher
level on derived/child loggers to a... | [
"def",
"configure_logging",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"fmt",
"=",
"'%(asctime)s | %(levelname)-8s | %(name)-40s | %(message)s'",
"datefmt",
"=",
"'%Y-%m-%d %H:%M:%S'",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"fmt",
"=",
"fmt",
... | Configures the root logger for command line applications.
A stream handler will be added to the logger that directs
messages to the standard error stream.
By default, *no* messages will be filtered out: set a higher
level on derived/child loggers to achieve filtering.
Warning
-------
Logg... | [
"Configures",
"the",
"root",
"logger",
"for",
"command",
"line",
"applications",
"."
] | python | train | 34.92 |
Zsailer/kubeconf | kubeconf/kubeconf.py | https://github.com/Zsailer/kubeconf/blob/b4e81001b5d2fb8d461056f25eb8b03307d57a6b/kubeconf/kubeconf.py#L267-L272 | def remove_user(self, name):
"""Remove a user from kubeconfig.
"""
user = self.get_user(name)
users = self.get_users()
users.remove(user) | [
"def",
"remove_user",
"(",
"self",
",",
"name",
")",
":",
"user",
"=",
"self",
".",
"get_user",
"(",
"name",
")",
"users",
"=",
"self",
".",
"get_users",
"(",
")",
"users",
".",
"remove",
"(",
"user",
")"
] | Remove a user from kubeconfig. | [
"Remove",
"a",
"user",
"from",
"kubeconfig",
"."
] | python | train | 28.666667 |
caioariede/docker-run-build | docker_rb/utils.py | https://github.com/caioariede/docker-run-build/blob/76ca4802018a63d6778374ebdba082d6750816b2/docker_rb/utils.py#L13-L19 | def get_old_options(cli, image):
""" Returns Dockerfile values for CMD and Entrypoint
"""
return {
'cmd': dockerapi.inspect_config(cli, image, 'Cmd'),
'entrypoint': dockerapi.inspect_config(cli, image, 'Entrypoint'),
} | [
"def",
"get_old_options",
"(",
"cli",
",",
"image",
")",
":",
"return",
"{",
"'cmd'",
":",
"dockerapi",
".",
"inspect_config",
"(",
"cli",
",",
"image",
",",
"'Cmd'",
")",
",",
"'entrypoint'",
":",
"dockerapi",
".",
"inspect_config",
"(",
"cli",
",",
"im... | Returns Dockerfile values for CMD and Entrypoint | [
"Returns",
"Dockerfile",
"values",
"for",
"CMD",
"and",
"Entrypoint"
] | python | train | 34.857143 |
cbclab/MOT | mot/sample/base.py | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/sample/base.py#L205-L253 | def _get_kernel_data(self, nmr_samples, thinning, return_output):
"""Get the kernel data we will input to the MCMC sampler.
This sets the items:
* data: the pointer to the user provided data
* method_data: the data specific to the MCMC method
* nmr_iterations: the number of ite... | [
"def",
"_get_kernel_data",
"(",
"self",
",",
"nmr_samples",
",",
"thinning",
",",
"return_output",
")",
":",
"kernel_data",
"=",
"{",
"'data'",
":",
"self",
".",
"_data",
",",
"'method_data'",
":",
"self",
".",
"_get_mcmc_method_kernel_data",
"(",
")",
",",
... | Get the kernel data we will input to the MCMC sampler.
This sets the items:
* data: the pointer to the user provided data
* method_data: the data specific to the MCMC method
* nmr_iterations: the number of iterations to sample
* iteration_offset: the current sample index, that ... | [
"Get",
"the",
"kernel",
"data",
"we",
"will",
"input",
"to",
"the",
"MCMC",
"sampler",
"."
] | python | train | 51.387755 |
pricingassistant/mrq | mrq/job.py | https://github.com/pricingassistant/mrq/blob/d0a5a34de9cba38afa94fb7c9e17f9b570b79a50/mrq/job.py#L663-L668 | def queue_raw_jobs(queue, params_list, **kwargs):
""" Queue some jobs on a raw queue """
from .queue import Queue
queue_obj = Queue(queue)
queue_obj.enqueue_raw_jobs(params_list, **kwargs) | [
"def",
"queue_raw_jobs",
"(",
"queue",
",",
"params_list",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"queue",
"import",
"Queue",
"queue_obj",
"=",
"Queue",
"(",
"queue",
")",
"queue_obj",
".",
"enqueue_raw_jobs",
"(",
"params_list",
",",
"*",
"*",
... | Queue some jobs on a raw queue | [
"Queue",
"some",
"jobs",
"on",
"a",
"raw",
"queue"
] | python | train | 33.333333 |
soldag/python-pwmled | pwmled/transitions/transition_manager.py | https://github.com/soldag/python-pwmled/blob/09cde36ecc0153fa81dc2a1b9bb07d1c0e418c8c/pwmled/transitions/transition_manager.py#L29-L40 | def _transition_loop(self):
"""Execute all queued transitions step by step."""
while self._transitions:
start = time.time()
for transition in self._transitions:
transition.step()
if transition.finished:
self._transitions.remove(... | [
"def",
"_transition_loop",
"(",
"self",
")",
":",
"while",
"self",
".",
"_transitions",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"for",
"transition",
"in",
"self",
".",
"_transitions",
":",
"transition",
".",
"step",
"(",
")",
"if",
"transition"... | Execute all queued transitions step by step. | [
"Execute",
"all",
"queued",
"transitions",
"step",
"by",
"step",
"."
] | python | train | 38.833333 |
vinci1it2000/schedula | schedula/dispatcher.py | https://github.com/vinci1it2000/schedula/blob/addb9fd685be81544b796c51383ac00a31543ce9/schedula/dispatcher.py#L1437-L1485 | def blue(self, memo=None):
"""
Constructs a BlueDispatcher out of the current object.
:param memo:
A dictionary to cache Blueprints.
:type memo: dict[T,schedula.utils.blue.Blueprint]
:return:
A BlueDispatcher of the current object.
:rtype: schedu... | [
"def",
"blue",
"(",
"self",
",",
"memo",
"=",
"None",
")",
":",
"memo",
"=",
"{",
"}",
"if",
"memo",
"is",
"None",
"else",
"memo",
"if",
"self",
"in",
"memo",
":",
"return",
"memo",
"[",
"self",
"]",
"from",
".",
"utils",
".",
"dsp",
"import",
... | Constructs a BlueDispatcher out of the current object.
:param memo:
A dictionary to cache Blueprints.
:type memo: dict[T,schedula.utils.blue.Blueprint]
:return:
A BlueDispatcher of the current object.
:rtype: schedula.utils.blue.BlueDispatcher | [
"Constructs",
"a",
"BlueDispatcher",
"out",
"of",
"the",
"current",
"object",
"."
] | python | train | 36.367347 |
RudolfCardinal/pythonlib | cardinal_pythonlib/subproc.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/subproc.py#L301-L454 | def mimic_user_input(
args: List[str],
source_challenge_response: List[Tuple[SubprocSource,
str,
Union[str, SubprocCommand]]],
line_terminators: List[str] = None,
print_stdout: bool = False,
... | [
"def",
"mimic_user_input",
"(",
"args",
":",
"List",
"[",
"str",
"]",
",",
"source_challenge_response",
":",
"List",
"[",
"Tuple",
"[",
"SubprocSource",
",",
"str",
",",
"Union",
"[",
"str",
",",
"SubprocCommand",
"]",
"]",
"]",
",",
"line_terminators",
":... | r"""
Run an external command. Pretend to be a human by sending text to the
subcommand (responses) when the external command sends us triggers
(challenges).
This is a bit nasty.
Args:
args: command-line arguments
source_challenge_response: list of tuples of the format ``(cha... | [
"r",
"Run",
"an",
"external",
"command",
".",
"Pretend",
"to",
"be",
"a",
"human",
"by",
"sending",
"text",
"to",
"the",
"subcommand",
"(",
"responses",
")",
"when",
"the",
"external",
"command",
"sends",
"us",
"triggers",
"(",
"challenges",
")",
".",
"T... | python | train | 39.311688 |
proycon/python-timbl | timbl.py | https://github.com/proycon/python-timbl/blob/e3c876711fa7f60648cfb1e4066c421a65faf524/timbl.py#L293-L311 | def leaveoneout(self):
"""Train & Test using leave one out"""
traintestfile = self.fileprefix + '.train'
options = "-F " + self.format + " " + self.timbloptions + " -t leave_one_out"
if sys.version < '3':
self.api = timblapi.TimblAPI(b(options), b"")
else:
... | [
"def",
"leaveoneout",
"(",
"self",
")",
":",
"traintestfile",
"=",
"self",
".",
"fileprefix",
"+",
"'.train'",
"options",
"=",
"\"-F \"",
"+",
"self",
".",
"format",
"+",
"\" \"",
"+",
"self",
".",
"timbloptions",
"+",
"\" -t leave_one_out\"",
"if",
"sys",
... | Train & Test using leave one out | [
"Train",
"&",
"Test",
"using",
"leave",
"one",
"out"
] | python | train | 44.684211 |
salimane/rediscluster-py | rediscluster/cluster_client.py | https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L299-L302 | def object(self, infotype, key):
"Return the encoding, idletime, or refcount about the key"
redisent = self.redises[self._getnodenamefor(key) + '_slave']
return getattr(redisent, 'object')(infotype, key) | [
"def",
"object",
"(",
"self",
",",
"infotype",
",",
"key",
")",
":",
"redisent",
"=",
"self",
".",
"redises",
"[",
"self",
".",
"_getnodenamefor",
"(",
"key",
")",
"+",
"'_slave'",
"]",
"return",
"getattr",
"(",
"redisent",
",",
"'object'",
")",
"(",
... | Return the encoding, idletime, or refcount about the key | [
"Return",
"the",
"encoding",
"idletime",
"or",
"refcount",
"about",
"the",
"key"
] | python | valid | 56 |
learningequality/ricecooker | ricecooker/managers/progress.py | https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/managers/progress.py#L198-L204 | def set_uploaded(self, files_uploaded):
""" set_uploaded: records progress after uploading files
Args: files_uploaded ([str]): list of files that have been successfully uploaded
Returns: None
"""
self.files_uploaded = files_uploaded
self.__record_progress(Status.U... | [
"def",
"set_uploaded",
"(",
"self",
",",
"files_uploaded",
")",
":",
"self",
".",
"files_uploaded",
"=",
"files_uploaded",
"self",
".",
"__record_progress",
"(",
"Status",
".",
"UPLOAD_CHANNEL",
")"
] | set_uploaded: records progress after uploading files
Args: files_uploaded ([str]): list of files that have been successfully uploaded
Returns: None | [
"set_uploaded",
":",
"records",
"progress",
"after",
"uploading",
"files",
"Args",
":",
"files_uploaded",
"(",
"[",
"str",
"]",
")",
":",
"list",
"of",
"files",
"that",
"have",
"been",
"successfully",
"uploaded",
"Returns",
":",
"None"
] | python | train | 46.857143 |
echinopsii/net.echinopsii.ariane.community.cli.python3 | ariane_clip3/mapping.py | https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/mapping.py#L378-L390 | def json_2_cluster(json_obj):
"""
transform json from Ariane server to local object
:param json_obj: json from Ariane Server
:return: transformed cluster
"""
LOGGER.debug("Cluster.json_2_cluster")
return Cluster(
cid=json_obj['clusterID'],
... | [
"def",
"json_2_cluster",
"(",
"json_obj",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Cluster.json_2_cluster\"",
")",
"return",
"Cluster",
"(",
"cid",
"=",
"json_obj",
"[",
"'clusterID'",
"]",
",",
"name",
"=",
"json_obj",
"[",
"'clusterName'",
"]",
",",
"cont... | transform json from Ariane server to local object
:param json_obj: json from Ariane Server
:return: transformed cluster | [
"transform",
"json",
"from",
"Ariane",
"server",
"to",
"local",
"object",
":",
"param",
"json_obj",
":",
"json",
"from",
"Ariane",
"Server",
":",
"return",
":",
"transformed",
"cluster"
] | python | train | 33.461538 |
portfors-lab/sparkle | sparkle/gui/stim/qauto_parameter_model.py | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/qauto_parameter_model.py#L135-L142 | def checkValidCell(self, index):
"""Asks the model if the value at *index* is valid
See :meth:`isFieldValid<sparkle.stim.auto_parameter_model.AutoParameterModel.isFieldValid>`
"""
col = index.column()
row = index.row()
return self.model.isFieldValid(row, self._headers[in... | [
"def",
"checkValidCell",
"(",
"self",
",",
"index",
")",
":",
"col",
"=",
"index",
".",
"column",
"(",
")",
"row",
"=",
"index",
".",
"row",
"(",
")",
"return",
"self",
".",
"model",
".",
"isFieldValid",
"(",
"row",
",",
"self",
".",
"_headers",
"[... | Asks the model if the value at *index* is valid
See :meth:`isFieldValid<sparkle.stim.auto_parameter_model.AutoParameterModel.isFieldValid>` | [
"Asks",
"the",
"model",
"if",
"the",
"value",
"at",
"*",
"index",
"*",
"is",
"valid"
] | python | train | 40.875 |
Becksteinlab/GromacsWrapper | gromacs/tools.py | https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/tools.py#L244-L276 | def load_v4_tools():
""" Load Gromacs 4.x tools automatically using some heuristic.
Tries to load tools (1) in configured tool groups (2) and fails back to
automatic detection from ``GMXBIN`` (3) then to a prefilled list.
Also load any extra tool configured in ``~/.gromacswrapper.cfg``
:return: ... | [
"def",
"load_v4_tools",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\"Loading v4 tools...\"",
")",
"names",
"=",
"config",
".",
"get_tool_names",
"(",
")",
"if",
"len",
"(",
"names",
")",
"==",
"0",
"and",
"'GMXBIN'",
"in",
"os",
".",
"environ",
":",
... | Load Gromacs 4.x tools automatically using some heuristic.
Tries to load tools (1) in configured tool groups (2) and fails back to
automatic detection from ``GMXBIN`` (3) then to a prefilled list.
Also load any extra tool configured in ``~/.gromacswrapper.cfg``
:return: dict mapping tool names to Gr... | [
"Load",
"Gromacs",
"4",
".",
"x",
"tools",
"automatically",
"using",
"some",
"heuristic",
"."
] | python | valid | 31.242424 |
CEA-COSMIC/ModOpt | modopt/base/wrappers.py | https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/wrappers.py#L19-L55 | def add_args_kwargs(func):
"""Add Args and Kwargs
This wrapper adds support for additional arguments and keyword arguments to
any callable function
Parameters
----------
func : function
Callable function
Returns
-------
function wrapper
"""
@wraps(func)
def w... | [
"def",
"add_args_kwargs",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"props",
"=",
"argspec",
"(",
"func",
")",
"# if 'args' not in props:",
"if",
"isinstance",
"(",
"pr... | Add Args and Kwargs
This wrapper adds support for additional arguments and keyword arguments to
any callable function
Parameters
----------
func : function
Callable function
Returns
-------
function wrapper | [
"Add",
"Args",
"and",
"Kwargs"
] | python | train | 18.405405 |
yunojuno/elasticsearch-django | elasticsearch_django/management/commands/__init__.py | https://github.com/yunojuno/elasticsearch-django/blob/e8d98d32bcd77f1bedb8f1a22b6523ca44ffd489/elasticsearch_django/management/commands/__init__.py#L39-L49 | def handle(self, *args, **options):
"""Run do_index_command on each specified index and log the output."""
for index in options.pop("indexes"):
data = {}
try:
data = self.do_index_command(index, **options)
except TransportError as ex:
l... | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"for",
"index",
"in",
"options",
".",
"pop",
"(",
"\"indexes\"",
")",
":",
"data",
"=",
"{",
"}",
"try",
":",
"data",
"=",
"self",
".",
"do_index_command",
"(",
"... | Run do_index_command on each specified index and log the output. | [
"Run",
"do_index_command",
"on",
"each",
"specified",
"index",
"and",
"log",
"the",
"output",
"."
] | python | train | 45.818182 |
singularityhub/singularity-python | singularity/views/trees.py | https://github.com/singularityhub/singularity-python/blob/498c3433724b332f7493fec632d8daf479f47b82/singularity/views/trees.py#L250-L284 | def make_interactive_tree(matrix=None,labels=None):
'''make interactive tree will return complete html for an interactive tree
:param title: a title for the plot, if not defined, will be left out.
'''
from scipy.cluster.hierarchy import (
dendrogram,
linkage,
to_tree
)
... | [
"def",
"make_interactive_tree",
"(",
"matrix",
"=",
"None",
",",
"labels",
"=",
"None",
")",
":",
"from",
"scipy",
".",
"cluster",
".",
"hierarchy",
"import",
"(",
"dendrogram",
",",
"linkage",
",",
"to_tree",
")",
"d3",
"=",
"None",
"from",
"scipy",
"."... | make interactive tree will return complete html for an interactive tree
:param title: a title for the plot, if not defined, will be left out. | [
"make",
"interactive",
"tree",
"will",
"return",
"complete",
"html",
"for",
"an",
"interactive",
"tree",
":",
"param",
"title",
":",
"a",
"title",
"for",
"the",
"plot",
"if",
"not",
"defined",
"will",
"be",
"left",
"out",
"."
] | python | train | 33.314286 |
OLC-Bioinformatics/sipprverse | cgecore/utility.py | https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/cgecore/utility.py#L223-L318 | def seqs_from_file(filename, exit_on_err=False, return_qual=False):
"""Extract sequences from a file
Name:
seqs_from_file
Author(s):
Martin C F Thomsen
Date:
18 Jul 2013
Description:
Iterator which extract sequence data from the input file
Args:
filename: string which... | [
"def",
"seqs_from_file",
"(",
"filename",
",",
"exit_on_err",
"=",
"False",
",",
"return_qual",
"=",
"False",
")",
":",
"# VALIDATE INPUT",
"if",
"not",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"msg",
"=",
"'Filename has to be a string.'",
"if",
"e... | Extract sequences from a file
Name:
seqs_from_file
Author(s):
Martin C F Thomsen
Date:
18 Jul 2013
Description:
Iterator which extract sequence data from the input file
Args:
filename: string which contain a path to the input file
Supported Formats:
fasta, fastq... | [
"Extract",
"sequences",
"from",
"a",
"file",
"Name",
":",
"seqs_from_file",
"Author",
"(",
"s",
")",
":",
"Martin",
"C",
"F",
"Thomsen",
"Date",
":",
"18",
"Jul",
"2013",
"Description",
":",
"Iterator",
"which",
"extract",
"sequence",
"data",
"from",
"the"... | python | train | 30.614583 |
getsentry/rb | rb/cluster.py | https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/cluster.py#L285-L295 | def all(self, timeout=None, max_concurrency=64, auto_batch=True):
"""Fanout to all hosts. Works otherwise exactly like :meth:`fanout`.
Example::
with cluster.all() as client:
client.flushdb()
"""
return self.fanout('all', timeout=timeout,
... | [
"def",
"all",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"max_concurrency",
"=",
"64",
",",
"auto_batch",
"=",
"True",
")",
":",
"return",
"self",
".",
"fanout",
"(",
"'all'",
",",
"timeout",
"=",
"timeout",
",",
"max_concurrency",
"=",
"max_concurre... | Fanout to all hosts. Works otherwise exactly like :meth:`fanout`.
Example::
with cluster.all() as client:
client.flushdb() | [
"Fanout",
"to",
"all",
"hosts",
".",
"Works",
"otherwise",
"exactly",
"like",
":",
"meth",
":",
"fanout",
"."
] | python | train | 36.454545 |
mback2k/python-appengine-auth | social_appengine_auth/backends.py | https://github.com/mback2k/python-appengine-auth/blob/dd27a0c53c7bebe147f7a6e3606c67ec673ac4d6/social_appengine_auth/backends.py#L42-L48 | def user_data(self, access_token, *args, **kwargs):
"""Load user data from OAuth Profile Google App Engine App"""
url = GOOGLE_APPENGINE_PROFILE_V1
auth = self.oauth_auth(access_token)
return self.get_json(url,
auth=auth, params=auth
) | [
"def",
"user_data",
"(",
"self",
",",
"access_token",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"GOOGLE_APPENGINE_PROFILE_V1",
"auth",
"=",
"self",
".",
"oauth_auth",
"(",
"access_token",
")",
"return",
"self",
".",
"get_json",
"(",
... | Load user data from OAuth Profile Google App Engine App | [
"Load",
"user",
"data",
"from",
"OAuth",
"Profile",
"Google",
"App",
"Engine",
"App"
] | python | train | 40.142857 |
cloudera/cm_api | nagios/cm_nagios.py | https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/nagios/cm_nagios.py#L283-L291 | def submit_status_external_cmd(cmd_file, status_file):
''' Submits the status lines in the status_file to Nagios' external cmd file.
'''
try:
with open(cmd_file, 'a') as cmd_file:
cmd_file.write(status_file.read())
except IOError:
exit("Fatal error: Unable to write to Nagios external command file ... | [
"def",
"submit_status_external_cmd",
"(",
"cmd_file",
",",
"status_file",
")",
":",
"try",
":",
"with",
"open",
"(",
"cmd_file",
",",
"'a'",
")",
"as",
"cmd_file",
":",
"cmd_file",
".",
"write",
"(",
"status_file",
".",
"read",
"(",
")",
")",
"except",
"... | Submits the status lines in the status_file to Nagios' external cmd file. | [
"Submits",
"the",
"status",
"lines",
"in",
"the",
"status_file",
"to",
"Nagios",
"external",
"cmd",
"file",
"."
] | python | train | 43.777778 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L734-L753 | def getMetadata(L):
"""
Get metadata from a LiPD data in memory
| Example
| m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict L: One LiPD record
:return dict d: LiPD record (metadata only)
"""
_l = {}
try:
# Create a copy. Do not affect the original d... | [
"def",
"getMetadata",
"(",
"L",
")",
":",
"_l",
"=",
"{",
"}",
"try",
":",
"# Create a copy. Do not affect the original data.",
"_l",
"=",
"copy",
".",
"deepcopy",
"(",
"L",
")",
"# Remove values fields",
"_l",
"=",
"rm_values_fields",
"(",
"_l",
")",
"except"... | Get metadata from a LiPD data in memory
| Example
| m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict L: One LiPD record
:return dict d: LiPD record (metadata only) | [
"Get",
"metadata",
"from",
"a",
"LiPD",
"data",
"in",
"memory"
] | python | train | 30.85 |
artisanofcode/python-broadway | broadway/app.py | https://github.com/artisanofcode/python-broadway/blob/a051ca5a922ecb38a541df59e8740e2a047d9a4a/broadway/app.py#L128-L146 | def add_extension(self, extension):
"""
Specify a broadway extension to initialise
.. code-block:: python
factory = Factory()
factory.add_extension('broadway_sqlalchemy')
:param extension: import path to extension
:type extension: str
"""
... | [
"def",
"add_extension",
"(",
"self",
",",
"extension",
")",
":",
"instance",
"=",
"werkzeug",
".",
"utils",
".",
"import_string",
"(",
"extension",
")",
"if",
"hasattr",
"(",
"instance",
",",
"'register'",
")",
":",
"instance",
".",
"register",
"(",
"self"... | Specify a broadway extension to initialise
.. code-block:: python
factory = Factory()
factory.add_extension('broadway_sqlalchemy')
:param extension: import path to extension
:type extension: str | [
"Specify",
"a",
"broadway",
"extension",
"to",
"initialise"
] | python | train | 25.105263 |
open-homeautomation/miflora | miflora/miflora_poller.py | https://github.com/open-homeautomation/miflora/blob/916606e7edc70bdc017dfbe681bc81771e0df7f3/miflora/miflora_poller.py#L57-L87 | def fill_cache(self):
"""Fill the cache with new data from the sensor."""
_LOGGER.debug('Filling cache with new sensor data.')
try:
firmware_version = self.firmware_version()
except BluetoothBackendException:
# If a sensor doesn't work, wait 5 minutes before retry... | [
"def",
"fill_cache",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"'Filling cache with new sensor data.'",
")",
"try",
":",
"firmware_version",
"=",
"self",
".",
"firmware_version",
"(",
")",
"except",
"BluetoothBackendException",
":",
"# If a sensor doesn't w... | Fill the cache with new data from the sensor. | [
"Fill",
"the",
"cache",
"with",
"new",
"data",
"from",
"the",
"sensor",
"."
] | python | train | 53 |
rainwoodman/kdcount | kdcount/sphere.py | https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/sphere.py#L65-L153 | def bootstrap(nside, rand, nbar, *data):
""" This function will bootstrap data based on the sky coverage of rand.
It is different from bootstrap in the traditional sense, but for correlation
functions it gives the correct answer with less computation.
nbar : number density of rand, used to ... | [
"def",
"bootstrap",
"(",
"nside",
",",
"rand",
",",
"nbar",
",",
"*",
"data",
")",
":",
"def",
"split",
"(",
"data",
",",
"indices",
",",
"axis",
")",
":",
"\"\"\" This function splits array. It fixes the bug\n in numpy that zero length array are improperly h... | This function will bootstrap data based on the sky coverage of rand.
It is different from bootstrap in the traditional sense, but for correlation
functions it gives the correct answer with less computation.
nbar : number density of rand, used to estimate the effective area of a pixel
n... | [
"This",
"function",
"will",
"bootstrap",
"data",
"based",
"on",
"the",
"sky",
"coverage",
"of",
"rand",
".",
"It",
"is",
"different",
"from",
"bootstrap",
"in",
"the",
"traditional",
"sense",
"but",
"for",
"correlation",
"functions",
"it",
"gives",
"the",
"c... | python | train | 30.955056 |
google/grr | grr/server/grr_response_server/databases/mem_cronjobs.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mem_cronjobs.py#L165-L173 | def DeleteOldCronJobRuns(self, cutoff_timestamp):
"""Deletes cron job runs for a given job id."""
deleted = 0
for run in list(itervalues(self.cronjob_runs)):
if run.timestamp < cutoff_timestamp:
del self.cronjob_runs[(run.cron_job_id, run.run_id)]
deleted += 1
return deleted | [
"def",
"DeleteOldCronJobRuns",
"(",
"self",
",",
"cutoff_timestamp",
")",
":",
"deleted",
"=",
"0",
"for",
"run",
"in",
"list",
"(",
"itervalues",
"(",
"self",
".",
"cronjob_runs",
")",
")",
":",
"if",
"run",
".",
"timestamp",
"<",
"cutoff_timestamp",
":",... | Deletes cron job runs for a given job id. | [
"Deletes",
"cron",
"job",
"runs",
"for",
"a",
"given",
"job",
"id",
"."
] | python | train | 34 |
quiltdata/quilt | compiler/quilt/tools/store.py | https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/store.py#L493-L499 | def get_file(self, hash_list):
"""
Returns the path of the file - but verifies that the hash is actually present.
"""
assert len(hash_list) == 1
self._check_hashes(hash_list)
return self.object_path(hash_list[0]) | [
"def",
"get_file",
"(",
"self",
",",
"hash_list",
")",
":",
"assert",
"len",
"(",
"hash_list",
")",
"==",
"1",
"self",
".",
"_check_hashes",
"(",
"hash_list",
")",
"return",
"self",
".",
"object_path",
"(",
"hash_list",
"[",
"0",
"]",
")"
] | Returns the path of the file - but verifies that the hash is actually present. | [
"Returns",
"the",
"path",
"of",
"the",
"file",
"-",
"but",
"verifies",
"that",
"the",
"hash",
"is",
"actually",
"present",
"."
] | python | train | 36.285714 |
goerz/clusterjob | clusterjob/backends/lsf.py | https://github.com/goerz/clusterjob/blob/361760d1a6dd3cbde49c5c2158a3acd0c314a749/clusterjob/backends/lsf.py#L92-L106 | def get_status(self, response, finished=False):
"""Given the stdout from the command returned by :meth:`cmd_status`,
return one of the status code defined in :mod:`clusterjob.status`"""
status_pos = 0
for line in response.split("\n"):
if line.startswith('JOBID'):
... | [
"def",
"get_status",
"(",
"self",
",",
"response",
",",
"finished",
"=",
"False",
")",
":",
"status_pos",
"=",
"0",
"for",
"line",
"in",
"response",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'JOBID'",
")",
":",
"t... | Given the stdout from the command returned by :meth:`cmd_status`,
return one of the status code defined in :mod:`clusterjob.status` | [
"Given",
"the",
"stdout",
"from",
"the",
"command",
"returned",
"by",
":",
"meth",
":",
"cmd_status",
"return",
"one",
"of",
"the",
"status",
"code",
"defined",
"in",
":",
"mod",
":",
"clusterjob",
".",
"status"
] | python | train | 41.933333 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L7973-L8078 | def read_tags(fh, byteorder, offsetsize, tagnames, customtags=None,
maxifds=None):
"""Read tags from chain of IFDs and return as list of dicts.
The file handle position must be at a valid IFD header.
"""
if offsetsize == 4:
offsetformat = byteorder+'I'
tagnosize = 2
... | [
"def",
"read_tags",
"(",
"fh",
",",
"byteorder",
",",
"offsetsize",
",",
"tagnames",
",",
"customtags",
"=",
"None",
",",
"maxifds",
"=",
"None",
")",
":",
"if",
"offsetsize",
"==",
"4",
":",
"offsetformat",
"=",
"byteorder",
"+",
"'I'",
"tagnosize",
"="... | Read tags from chain of IFDs and return as list of dicts.
The file handle position must be at a valid IFD header. | [
"Read",
"tags",
"from",
"chain",
"of",
"IFDs",
"and",
"return",
"as",
"list",
"of",
"dicts",
"."
] | python | train | 35.641509 |
allenai/allennlp | allennlp/data/dataset_readers/coreference_resolution/conll.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/coreference_resolution/conll.py#L18-L47 | def canonicalize_clusters(clusters: DefaultDict[int, List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]:
"""
The CONLL 2012 data includes 2 annotated spans which are identical,
but have different ids. This checks all clusters for spans which are
identical, and if it finds any, merges the clusters co... | [
"def",
"canonicalize_clusters",
"(",
"clusters",
":",
"DefaultDict",
"[",
"int",
",",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"]",
")",
"->",
"List",
"[",
"List",
"[",
"Tuple",
"[",
"int",
",",
"int",
"]",
"]",
"]",
":",
"merged_clu... | The CONLL 2012 data includes 2 annotated spans which are identical,
but have different ids. This checks all clusters for spans which are
identical, and if it finds any, merges the clusters containing the
identical spans. | [
"The",
"CONLL",
"2012",
"data",
"includes",
"2",
"annotated",
"spans",
"which",
"are",
"identical",
"but",
"have",
"different",
"ids",
".",
"This",
"checks",
"all",
"clusters",
"for",
"spans",
"which",
"are",
"identical",
"and",
"if",
"it",
"finds",
"any",
... | python | train | 47.666667 |
dagster-io/dagster | python_modules/dagster/dagster/core/types/field.py | https://github.com/dagster-io/dagster/blob/4119f8c773089de64831b1dfb9e168e353d401dc/python_modules/dagster/dagster/core/types/field.py#L34-L66 | def Field(
dagster_type,
default_value=FIELD_NO_DEFAULT_PROVIDED,
is_optional=INFER_OPTIONAL_COMPOSITE_FIELD,
is_secret=False,
description=None,
):
'''
The schema for configuration data that describes the type, optionality, defaults, and description.
Args:
dagster_type (DagsterT... | [
"def",
"Field",
"(",
"dagster_type",
",",
"default_value",
"=",
"FIELD_NO_DEFAULT_PROVIDED",
",",
"is_optional",
"=",
"INFER_OPTIONAL_COMPOSITE_FIELD",
",",
"is_secret",
"=",
"False",
",",
"description",
"=",
"None",
",",
")",
":",
"config_type",
"=",
"resolve_to_co... | The schema for configuration data that describes the type, optionality, defaults, and description.
Args:
dagster_type (DagsterType):
A ``DagsterType`` describing the schema of this field, ie `Dict({'example': Field(String)})`
default_value (Any):
A default value to use that ... | [
"The",
"schema",
"for",
"configuration",
"data",
"that",
"describes",
"the",
"type",
"optionality",
"defaults",
"and",
"description",
"."
] | python | test | 36.818182 |
mikicz/arca | arca/utils.py | https://github.com/mikicz/arca/blob/e67fdc00be473ecf8ec16d024e1a3f2c47ca882c/arca/utils.py#L96-L139 | def get(self, *keys: str, default: Any = NOT_SET) -> Any:
""" Returns values from the settings in the order of keys, the first value encountered is used.
Example:
>>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2})
>>> settings.get("one")
1
>>> settings.get("one", "... | [
"def",
"get",
"(",
"self",
",",
"*",
"keys",
":",
"str",
",",
"default",
":",
"Any",
"=",
"NOT_SET",
")",
"->",
"Any",
":",
"if",
"not",
"len",
"(",
"keys",
")",
":",
"raise",
"ValueError",
"(",
"\"At least one key must be provided.\"",
")",
"for",
"op... | Returns values from the settings in the order of keys, the first value encountered is used.
Example:
>>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2})
>>> settings.get("one")
1
>>> settings.get("one", "two")
1
>>> settings.get("two", "one")
2
... | [
"Returns",
"values",
"from",
"the",
"settings",
"in",
"the",
"order",
"of",
"keys",
"the",
"first",
"value",
"encountered",
"is",
"used",
"."
] | python | train | 33.295455 |
nerdvegas/rez | src/rez/vendor/sortedcontainers/sortedlist.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L2293-L2353 | def index(self, val, start=None, stop=None):
"""
Return the smallest *k* such that L[k] == val and i <= k < j`. Raises
ValueError if *val* is not present. *stop* defaults to the end of the
list. *start* defaults to the beginning. Negative indices are supported,
as for slice ind... | [
"def",
"index",
"(",
"self",
",",
"val",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
")",
":",
"_len",
"=",
"self",
".",
"_len",
"if",
"not",
"_len",
":",
"raise",
"ValueError",
"(",
"'{0!r} is not in list'",
".",
"format",
"(",
"val",
")",
... | Return the smallest *k* such that L[k] == val and i <= k < j`. Raises
ValueError if *val* is not present. *stop* defaults to the end of the
list. *start* defaults to the beginning. Negative indices are supported,
as for slice indices. | [
"Return",
"the",
"smallest",
"*",
"k",
"*",
"such",
"that",
"L",
"[",
"k",
"]",
"==",
"val",
"and",
"i",
"<",
"=",
"k",
"<",
"j",
".",
"Raises",
"ValueError",
"if",
"*",
"val",
"*",
"is",
"not",
"present",
".",
"*",
"stop",
"*",
"defaults",
"to... | python | train | 29.688525 |
theolind/pymysensors | mysensors/__init__.py | https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/__init__.py#L433-L437 | def handle_line(self, line):
"""Handle incoming string data one line at a time."""
if not self.gateway.can_log:
_LOGGER.debug('Receiving %s', line)
self.gateway.add_job(self.gateway.logic, line) | [
"def",
"handle_line",
"(",
"self",
",",
"line",
")",
":",
"if",
"not",
"self",
".",
"gateway",
".",
"can_log",
":",
"_LOGGER",
".",
"debug",
"(",
"'Receiving %s'",
",",
"line",
")",
"self",
".",
"gateway",
".",
"add_job",
"(",
"self",
".",
"gateway",
... | Handle incoming string data one line at a time. | [
"Handle",
"incoming",
"string",
"data",
"one",
"line",
"at",
"a",
"time",
"."
] | python | train | 45.2 |
python-bonobo/bonobo | bonobo/util/api.py | https://github.com/python-bonobo/bonobo/blob/70c8e62c4a88576976e5b52e58d380d6e3227ab4/bonobo/util/api.py#L9-L26 | def register(self, x, graph=False):
"""Register a function as being part of an API, then returns the original function."""
if graph:
# This function must comply to the "graph" API interface, meaning it can bahave like bonobo.run.
from inspect import signature
parame... | [
"def",
"register",
"(",
"self",
",",
"x",
",",
"graph",
"=",
"False",
")",
":",
"if",
"graph",
":",
"# This function must comply to the \"graph\" API interface, meaning it can bahave like bonobo.run.",
"from",
"inspect",
"import",
"signature",
"parameters",
"=",
"list",
... | Register a function as being part of an API, then returns the original function. | [
"Register",
"a",
"function",
"as",
"being",
"part",
"of",
"an",
"API",
"then",
"returns",
"the",
"original",
"function",
"."
] | python | train | 47.222222 |
sjkingo/virtualenv-api | virtualenvapi/manage.py | https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L160-L164 | def _write_to_log(self, s, truncate=False):
"""Writes the given output to the log file, appending unless `truncate` is True."""
# if truncate is True, set write mode to truncate
with open(self._logfile, 'w' if truncate else 'a') as fp:
fp.writelines((to_text(s) if six.PY2 else to_tex... | [
"def",
"_write_to_log",
"(",
"self",
",",
"s",
",",
"truncate",
"=",
"False",
")",
":",
"# if truncate is True, set write mode to truncate",
"with",
"open",
"(",
"self",
".",
"_logfile",
",",
"'w'",
"if",
"truncate",
"else",
"'a'",
")",
"as",
"fp",
":",
"fp"... | Writes the given output to the log file, appending unless `truncate` is True. | [
"Writes",
"the",
"given",
"output",
"to",
"the",
"log",
"file",
"appending",
"unless",
"truncate",
"is",
"True",
"."
] | python | train | 64.8 |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_imputer.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_imputer.py#L21-L76 | def convert(model, input_features, output_features):
"""Convert a DictVectorizer model to the protobuf spec.
Parameters
----------
model: DictVectorizer
A fitted DictVectorizer model.
input_features: str
Name of the input column.
output_features: str
Name of the output... | [
"def",
"convert",
"(",
"model",
",",
"input_features",
",",
"output_features",
")",
":",
"if",
"not",
"(",
"_HAS_SKLEARN",
")",
":",
"raise",
"RuntimeError",
"(",
"'scikit-learn not found. scikit-learn conversion API is disabled.'",
")",
"# Set the interface params.",
"sp... | Convert a DictVectorizer model to the protobuf spec.
Parameters
----------
model: DictVectorizer
A fitted DictVectorizer model.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object ... | [
"Convert",
"a",
"DictVectorizer",
"model",
"to",
"the",
"protobuf",
"spec",
"."
] | python | train | 30.107143 |
kivy/buildozer | buildozer/__init__.py | https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L173-L198 | def prepare_for_build(self):
'''Prepare the build.
'''
assert(self.target is not None)
if hasattr(self.target, '_build_prepared'):
return
self.info('Preparing build')
self.info('Check requirements for {0}'.format(self.targetname))
self.target.check_r... | [
"def",
"prepare_for_build",
"(",
"self",
")",
":",
"assert",
"(",
"self",
".",
"target",
"is",
"not",
"None",
")",
"if",
"hasattr",
"(",
"self",
".",
"target",
",",
"'_build_prepared'",
")",
":",
"return",
"self",
".",
"info",
"(",
"'Preparing build'",
"... | Prepare the build. | [
"Prepare",
"the",
"build",
"."
] | python | train | 28.346154 |
modin-project/modin | modin/engines/base/frame/partition_manager.py | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/engines/base/frame/partition_manager.py#L277-L313 | def map_across_full_axis(self, axis, map_func):
"""Applies `map_func` to every partition.
Note: This method should be used in the case that `map_func` relies on
some global information about the axis.
Args:
axis: The axis to perform the map across (0 - index, 1 - column... | [
"def",
"map_across_full_axis",
"(",
"self",
",",
"axis",
",",
"map_func",
")",
":",
"# Since we are already splitting the DataFrame back up after an",
"# operation, we will just use this time to compute the number of",
"# partitions as best we can right now.",
"num_splits",
"=",
"self"... | Applies `map_func` to every partition.
Note: This method should be used in the case that `map_func` relies on
some global information about the axis.
Args:
axis: The axis to perform the map across (0 - index, 1 - columns).
map_func: The function to apply.
R... | [
"Applies",
"map_func",
"to",
"every",
"partition",
"."
] | python | train | 45.297297 |
RJT1990/pyflux | pyflux/families/exponential.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/exponential.py#L195-L219 | def markov_blanket(y, mean, scale, shape, skewness):
""" Markov blanket for the Exponential distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
... | [
"def",
"markov_blanket",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"return",
"ss",
".",
"expon",
".",
"logpdf",
"(",
"x",
"=",
"y",
",",
"scale",
"=",
"1",
"/",
"mean",
")"
] | Markov blanket for the Exponential distribution
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float
scale parameter for the Exponential dis... | [
"Markov",
"blanket",
"for",
"the",
"Exponential",
"distribution"
] | python | train | 28.08 |
blockstack/blockstack-core | blockstack/blockstackd.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2970-L2987 | def check_recovery(working_dir):
"""
Do we need to recover on start-up?
"""
recovery_start_block, recovery_end_block = get_recovery_range(working_dir)
if recovery_start_block is not None and recovery_end_block is not None:
local_current_block = virtualchain_hooks.get_last_block(working_dir)
... | [
"def",
"check_recovery",
"(",
"working_dir",
")",
":",
"recovery_start_block",
",",
"recovery_end_block",
"=",
"get_recovery_range",
"(",
"working_dir",
")",
"if",
"recovery_start_block",
"is",
"not",
"None",
"and",
"recovery_end_block",
"is",
"not",
"None",
":",
"l... | Do we need to recover on start-up? | [
"Do",
"we",
"need",
"to",
"recover",
"on",
"start",
"-",
"up?"
] | python | train | 40.833333 |
kgori/treeCl | treeCl/bootstrap.py | https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/bootstrap.py#L190-L206 | def run_out_of_sample_mds(boot_collection, ref_collection, ref_distance_matrix, index, dimensions, task=_fast_geo, rooted=False, **kwargs):
"""
index = index of the locus the bootstrap sample corresponds to - only important if
using recalc=True in kwargs
"""
fit = np.empty((len(boot_collecti... | [
"def",
"run_out_of_sample_mds",
"(",
"boot_collection",
",",
"ref_collection",
",",
"ref_distance_matrix",
",",
"index",
",",
"dimensions",
",",
"task",
"=",
"_fast_geo",
",",
"rooted",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"fit",
"=",
"np",
".",
... | index = index of the locus the bootstrap sample corresponds to - only important if
using recalc=True in kwargs | [
"index",
"=",
"index",
"of",
"the",
"locus",
"the",
"bootstrap",
"sample",
"corresponds",
"to",
"-",
"only",
"important",
"if",
"using",
"recalc",
"=",
"True",
"in",
"kwargs"
] | python | train | 55.941176 |
farshidce/touchworks-python | touchworks/api/http.py | https://github.com/farshidce/touchworks-python/blob/ea8f93a0f4273de1317a318e945a571f5038ba62/touchworks/api/http.py#L458-L480 | def set_patient_medhx_flag(self, patient_id,
medhx_status):
"""
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:param patient_id
:param medhx_status - Field in EEHR expects U, G, or D. SP defaults to Null and
erro... | [
"def",
"set_patient_medhx_flag",
"(",
"self",
",",
"patient_id",
",",
"medhx_status",
")",
":",
"magic",
"=",
"self",
".",
"_magic_json",
"(",
"action",
"=",
"TouchWorksMagicConstants",
".",
"ACTION_SET_PATIENT_MEDHX_FLAG",
",",
"patient_id",
"=",
"patient_id",
",",... | invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action
:param patient_id
:param medhx_status - Field in EEHR expects U, G, or D. SP defaults to Null and
errors out if included.
U=Unknown
G=Granted
D=Declined
:ret... | [
"invokes",
"TouchWorksMagicConstants",
".",
"ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT",
"action",
":",
"param",
"patient_id",
":",
"param",
"medhx_status",
"-",
"Field",
"in",
"EEHR",
"expects",
"U",
"G",
"or",
"D",
".",
"SP",
"defaults",
"to",
"Null",
"and",
"errors... | python | train | 39.304348 |
mitsei/dlkit | dlkit/json_/assessment/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/sessions.py#L7739-L7762 | def alias_assessment_taken(self, assessment_taken_id, alias_id):
"""Adds an ``Id`` to an ``AssessmentTaken`` for the purpose of creating compatibility.
The primary ``Id`` of the ``AssessmentTaken`` is determined by
the provider. The new ``Id`` is an alias to the primary ``Id``.
If the a... | [
"def",
"alias_assessment_taken",
"(",
"self",
",",
"assessment_taken_id",
",",
"alias_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.alias_resources_template",
"self",
".",
"_alias_id",
"(",
"primary_id",
"=",
"assessment_taken_id",
",",... | Adds an ``Id`` to an ``AssessmentTaken`` for the purpose of creating compatibility.
The primary ``Id`` of the ``AssessmentTaken`` is determined by
the provider. The new ``Id`` is an alias to the primary ``Id``.
If the alias is a pointer to another assessment taken, it is
reassigned to t... | [
"Adds",
"an",
"Id",
"to",
"an",
"AssessmentTaken",
"for",
"the",
"purpose",
"of",
"creating",
"compatibility",
"."
] | python | train | 50.583333 |
angr/angr | angr/exploration_techniques/director.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/exploration_techniques/director.py#L249-L263 | def check_state(self, state):
"""
Check if the specific function is reached with certain arguments
:param angr.SimState state: The state to check
:return: True if the function is reached with certain arguments, False otherwise.
:rtype: bool
"""
if state.addr == ... | [
"def",
"check_state",
"(",
"self",
",",
"state",
")",
":",
"if",
"state",
".",
"addr",
"==",
"self",
".",
"function",
".",
"addr",
":",
"arch",
"=",
"state",
".",
"arch",
"if",
"self",
".",
"_check_arguments",
"(",
"arch",
",",
"state",
")",
":",
"... | Check if the specific function is reached with certain arguments
:param angr.SimState state: The state to check
:return: True if the function is reached with certain arguments, False otherwise.
:rtype: bool | [
"Check",
"if",
"the",
"specific",
"function",
"is",
"reached",
"with",
"certain",
"arguments"
] | python | train | 30.4 |
scott-maddox/openbandparams | src/openbandparams/iii_v_zinc_blende_strained.py | https://github.com/scott-maddox/openbandparams/blob/bc24e59187326bcb8948117434536082c9055777/src/openbandparams/iii_v_zinc_blende_strained.py#L150-L156 | def CBO_Gamma(self, **kwargs):
'''
Returns the strain-shifted Gamma-valley conduction band offset (CBO),
assuming the strain affects all conduction band valleys equally.
'''
return (self.unstrained.CBO_Gamma(**kwargs) +
self.CBO_strain_shift(**kwargs)) | [
"def",
"CBO_Gamma",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"(",
"self",
".",
"unstrained",
".",
"CBO_Gamma",
"(",
"*",
"*",
"kwargs",
")",
"+",
"self",
".",
"CBO_strain_shift",
"(",
"*",
"*",
"kwargs",
")",
")"
] | Returns the strain-shifted Gamma-valley conduction band offset (CBO),
assuming the strain affects all conduction band valleys equally. | [
"Returns",
"the",
"strain",
"-",
"shifted",
"Gamma",
"-",
"valley",
"conduction",
"band",
"offset",
"(",
"CBO",
")",
"assuming",
"the",
"strain",
"affects",
"all",
"conduction",
"band",
"valleys",
"equally",
"."
] | python | train | 43.142857 |
praekelt/jmbo-calendar | jmbo_calendar/admin.py | https://github.com/praekelt/jmbo-calendar/blob/ac39f3ad4c155d6755ec5c5a51fb815268b8c18c/jmbo_calendar/admin.py#L36-L46 | def get_fieldsets(self, *args, **kwargs):
"""Re-order fields"""
result = super(EventAdmin, self).get_fieldsets(*args, **kwargs)
result = list(result)
fields = list(result[0][1]['fields'])
for name in ('content', 'start', 'end', 'repeat', 'repeat_until', \
'external_li... | [
"def",
"get_fieldsets",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"super",
"(",
"EventAdmin",
",",
"self",
")",
".",
"get_fieldsets",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"result",
"=",
"list",
"(",... | Re-order fields | [
"Re",
"-",
"order",
"fields"
] | python | train | 42.545455 |
google/identity-toolkit-python-client | identitytoolkit/rpchelper.py | https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/rpchelper.py#L129-L147 | def UploadAccount(self, hash_algorithm, hash_key, accounts):
"""Uploads multiple accounts to Gitkit server.
Args:
hash_algorithm: string, algorithm to hash password.
hash_key: string, base64-encoded key of the algorithm.
accounts: array of accounts to be uploaded.
Returns:
Response... | [
"def",
"UploadAccount",
"(",
"self",
",",
"hash_algorithm",
",",
"hash_key",
",",
"accounts",
")",
":",
"param",
"=",
"{",
"'hashAlgorithm'",
":",
"hash_algorithm",
",",
"'signerKey'",
":",
"hash_key",
",",
"'users'",
":",
"accounts",
"}",
"# pylint does not rec... | Uploads multiple accounts to Gitkit server.
Args:
hash_algorithm: string, algorithm to hash password.
hash_key: string, base64-encoded key of the algorithm.
accounts: array of accounts to be uploaded.
Returns:
Response of the API. | [
"Uploads",
"multiple",
"accounts",
"to",
"Gitkit",
"server",
"."
] | python | train | 31.736842 |
bspaans/python-mingus | mingus/extra/tablature.py | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tablature.py#L328-L397 | def from_Composition(composition, width=80):
"""Convert a mingus.containers.Composition to an ASCII tablature string.
Automatically add an header based on the title, subtitle, author, e-mail
and description attributes. An extra description of the piece can also
be given.
Tunings can be set by usin... | [
"def",
"from_Composition",
"(",
"composition",
",",
"width",
"=",
"80",
")",
":",
"# Collect tunings",
"instr_tunings",
"=",
"[",
"]",
"for",
"track",
"in",
"composition",
":",
"tun",
"=",
"track",
".",
"get_tuning",
"(",
")",
"if",
"tun",
":",
"instr_tuni... | Convert a mingus.containers.Composition to an ASCII tablature string.
Automatically add an header based on the title, subtitle, author, e-mail
and description attributes. An extra description of the piece can also
be given.
Tunings can be set by using the Track.instrument.tuning or Track.tuning
at... | [
"Convert",
"a",
"mingus",
".",
"containers",
".",
"Composition",
"to",
"an",
"ASCII",
"tablature",
"string",
"."
] | python | train | 31.671429 |
hydpy-dev/hydpy | hydpy/core/objecttools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L1431-L1468 | def enumeration(values, converter=str, default=''):
"""Return an enumeration string based on the given values.
The following four examples show the standard output of function
|enumeration|:
>>> from hydpy.core.objecttools import enumeration
>>> enumeration(('text', 3, []))
'text, 3, and []'
... | [
"def",
"enumeration",
"(",
"values",
",",
"converter",
"=",
"str",
",",
"default",
"=",
"''",
")",
":",
"values",
"=",
"tuple",
"(",
"converter",
"(",
"value",
")",
"for",
"value",
"in",
"values",
")",
"if",
"not",
"values",
":",
"return",
"default",
... | Return an enumeration string based on the given values.
The following four examples show the standard output of function
|enumeration|:
>>> from hydpy.core.objecttools import enumeration
>>> enumeration(('text', 3, []))
'text, 3, and []'
>>> enumeration(('text', 3))
'text and 3'
>>> en... | [
"Return",
"an",
"enumeration",
"string",
"based",
"on",
"the",
"given",
"values",
"."
] | python | train | 31.605263 |
zomux/deepy | deepy/dataset/basic.py | https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/dataset/basic.py#L30-L40 | def map(self, func):
"""
Process all data with given function.
The scheme of function should be x,y -> x,y.
"""
if self._train_set:
self._train_set = map(func, self._train_set)
if self._valid_set:
self._valid_set = map(func, self._valid_set)
... | [
"def",
"map",
"(",
"self",
",",
"func",
")",
":",
"if",
"self",
".",
"_train_set",
":",
"self",
".",
"_train_set",
"=",
"map",
"(",
"func",
",",
"self",
".",
"_train_set",
")",
"if",
"self",
".",
"_valid_set",
":",
"self",
".",
"_valid_set",
"=",
"... | Process all data with given function.
The scheme of function should be x,y -> x,y. | [
"Process",
"all",
"data",
"with",
"given",
"function",
".",
"The",
"scheme",
"of",
"function",
"should",
"be",
"x",
"y",
"-",
">",
"x",
"y",
"."
] | python | test | 35 |
xtuml/pyxtuml | xtuml/load.py | https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/load.py#L274-L282 | def populate_unique_identifiers(self, metamodel):
'''
Populate a *metamodel* with class unique identifiers previously
encountered from input.
'''
for stmt in self.statements:
if isinstance(stmt, CreateUniqueStmt):
metamodel.define_unique_identifier(stm... | [
"def",
"populate_unique_identifiers",
"(",
"self",
",",
"metamodel",
")",
":",
"for",
"stmt",
"in",
"self",
".",
"statements",
":",
"if",
"isinstance",
"(",
"stmt",
",",
"CreateUniqueStmt",
")",
":",
"metamodel",
".",
"define_unique_identifier",
"(",
"stmt",
"... | Populate a *metamodel* with class unique identifiers previously
encountered from input. | [
"Populate",
"a",
"*",
"metamodel",
"*",
"with",
"class",
"unique",
"identifiers",
"previously",
"encountered",
"from",
"input",
"."
] | python | test | 44.444444 |
ultrabug/py3status | py3status/core.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L619-L694 | def notify_user(
self,
msg,
level="error",
rate_limit=None,
module_name="",
icon=None,
title="py3status",
):
"""
Display notification to user via i3-nagbar or send-notify
We also make sure to log anything to keep trace of it.
N... | [
"def",
"notify_user",
"(",
"self",
",",
"msg",
",",
"level",
"=",
"\"error\"",
",",
"rate_limit",
"=",
"None",
",",
"module_name",
"=",
"\"\"",
",",
"icon",
"=",
"None",
",",
"title",
"=",
"\"py3status\"",
",",
")",
":",
"dbus",
"=",
"self",
".",
"co... | Display notification to user via i3-nagbar or send-notify
We also make sure to log anything to keep trace of it.
NOTE: Message should end with a '.' for consistency. | [
"Display",
"notification",
"to",
"user",
"via",
"i3",
"-",
"nagbar",
"or",
"send",
"-",
"notify",
"We",
"also",
"make",
"sure",
"to",
"log",
"anything",
"to",
"keep",
"trace",
"of",
"it",
"."
] | python | train | 37.605263 |
bitesofcode/projexui | projexui/menus/xmenu.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/menus/xmenu.py#L374-L387 | def adjustMinimumWidth( self ):
"""
Updates the minimum width for this menu based on the font metrics \
for its title (if its shown). This method is called automatically \
when the menu is shown.
"""
if not self.showTitle():
return
metrics = ... | [
"def",
"adjustMinimumWidth",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"showTitle",
"(",
")",
":",
"return",
"metrics",
"=",
"QFontMetrics",
"(",
"self",
".",
"font",
"(",
")",
")",
"width",
"=",
"metrics",
".",
"width",
"(",
"self",
".",
"tit... | Updates the minimum width for this menu based on the font metrics \
for its title (if its shown). This method is called automatically \
when the menu is shown. | [
"Updates",
"the",
"minimum",
"width",
"for",
"this",
"menu",
"based",
"on",
"the",
"font",
"metrics",
"\\",
"for",
"its",
"title",
"(",
"if",
"its",
"shown",
")",
".",
"This",
"method",
"is",
"called",
"automatically",
"\\",
"when",
"the",
"menu",
"is",
... | python | train | 33.714286 |
jwodder/doapi | doapi/doapi.py | https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/doapi.py#L651-L671 | def fetch_all_images(self, type=None, private=None):
# pylint: disable=redefined-builtin
r"""
Returns a generator that yields all of the images available to the
account
:param type: the type of images to fetch: ``"distribution"``,
``"application"``, or all (`None`); ... | [
"def",
"fetch_all_images",
"(",
"self",
",",
"type",
"=",
"None",
",",
"private",
"=",
"None",
")",
":",
"# pylint: disable=redefined-builtin",
"params",
"=",
"{",
"}",
"if",
"type",
"is",
"not",
"None",
":",
"params",
"[",
"\"type\"",
"]",
"=",
"type",
... | r"""
Returns a generator that yields all of the images available to the
account
:param type: the type of images to fetch: ``"distribution"``,
``"application"``, or all (`None`); default: `None`
:type type: string or None
:param bool private: whether to only return th... | [
"r",
"Returns",
"a",
"generator",
"that",
"yields",
"all",
"of",
"the",
"images",
"available",
"to",
"the",
"account"
] | python | train | 42.857143 |
saltstack/salt | salt/modules/s6.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/s6.py#L135-L151 | def status(name, sig=None):
'''
Return the status for a service via s6, return pid if running
CLI Example:
.. code-block:: bash
salt '*' s6.status <service name>
'''
cmd = 's6-svstat {0}'.format(_service_path(name))
out = __salt__['cmd.run_stdout'](cmd)
try:
pid = re.s... | [
"def",
"status",
"(",
"name",
",",
"sig",
"=",
"None",
")",
":",
"cmd",
"=",
"'s6-svstat {0}'",
".",
"format",
"(",
"_service_path",
"(",
"name",
")",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run_stdout'",
"]",
"(",
"cmd",
")",
"try",
":",
"pid",
"=",... | Return the status for a service via s6, return pid if running
CLI Example:
.. code-block:: bash
salt '*' s6.status <service name> | [
"Return",
"the",
"status",
"for",
"a",
"service",
"via",
"s6",
"return",
"pid",
"if",
"running"
] | python | train | 23.705882 |
alex-kostirin/pyatomac | atomac/AXClasses.py | https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L457-L529 | def _queueMouseButton(self, coord, mouseButton, modFlags, clickCount=1,
dest_coord=None):
"""Private method to handle generic mouse button clicking.
Parameters: coord (x, y) to click, mouseButton (e.g.,
kCGMouseButtonLeft), modFlags set (int)
Option... | [
"def",
"_queueMouseButton",
"(",
"self",
",",
"coord",
",",
"mouseButton",
",",
"modFlags",
",",
"clickCount",
"=",
"1",
",",
"dest_coord",
"=",
"None",
")",
":",
"# For now allow only left and right mouse buttons:",
"mouseButtons",
"=",
"{",
"Quartz",
".",
"kCGMo... | Private method to handle generic mouse button clicking.
Parameters: coord (x, y) to click, mouseButton (e.g.,
kCGMouseButtonLeft), modFlags set (int)
Optional: clickCount (default 1; set to 2 for double-click; 3 for
triple-click on host)
Returns: None | [
"Private",
"method",
"to",
"handle",
"generic",
"mouse",
"button",
"clicking",
"."
] | python | valid | 47.520548 |
taskcluster/taskcluster-client.py | taskcluster/utils.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/utils.py#L182-L194 | def stableSlugId():
"""Returns a closure which can be used to generate stable slugIds.
Stable slugIds can be used in a graph to specify task IDs in multiple
places without regenerating them, e.g. taskId, requires, etc.
"""
_cache = {}
def closure(name):
if name not in _cache:
... | [
"def",
"stableSlugId",
"(",
")",
":",
"_cache",
"=",
"{",
"}",
"def",
"closure",
"(",
"name",
")",
":",
"if",
"name",
"not",
"in",
"_cache",
":",
"_cache",
"[",
"name",
"]",
"=",
"slugId",
"(",
")",
"return",
"_cache",
"[",
"name",
"]",
"return",
... | Returns a closure which can be used to generate stable slugIds.
Stable slugIds can be used in a graph to specify task IDs in multiple
places without regenerating them, e.g. taskId, requires, etc. | [
"Returns",
"a",
"closure",
"which",
"can",
"be",
"used",
"to",
"generate",
"stable",
"slugIds",
".",
"Stable",
"slugIds",
"can",
"be",
"used",
"in",
"a",
"graph",
"to",
"specify",
"task",
"IDs",
"in",
"multiple",
"places",
"without",
"regenerating",
"them",
... | python | train | 29.307692 |
ymoch/apyori | apyori.py | https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L60-L91 | def calc_support(self, items):
"""
Returns a support for items.
Arguments:
items -- Items as an iterable object (eg. ['A', 'B']).
"""
# Empty items is supported by all transactions.
if not items:
return 1.0
# Empty transactions supports n... | [
"def",
"calc_support",
"(",
"self",
",",
"items",
")",
":",
"# Empty items is supported by all transactions.",
"if",
"not",
"items",
":",
"return",
"1.0",
"# Empty transactions supports no items.",
"if",
"not",
"self",
".",
"num_transaction",
":",
"return",
"0.0",
"# ... | Returns a support for items.
Arguments:
items -- Items as an iterable object (eg. ['A', 'B']). | [
"Returns",
"a",
"support",
"for",
"items",
"."
] | python | train | 32.84375 |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/apps_v1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/apps_v1_api.py#L1143-L1172 | def delete_collection_namespaced_stateful_set(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_stateful_set # noqa: E501
delete collection of StatefulSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request... | [
"def",
"delete_collection_namespaced_stateful_set",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",... | delete_collection_namespaced_stateful_set # noqa: E501
delete collection of StatefulSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_stateful_set(nam... | [
"delete_collection_namespaced_stateful_set",
"#",
"noqa",
":",
"E501"
] | python | train | 164.6 |
nsavch/python-dpcolors | dpcolors/__init__.py | https://github.com/nsavch/python-dpcolors/blob/9bca11416a21eca1c5a84b7dcc852d231d911981/dpcolors/__init__.py#L110-L142 | def to_8bit(self):
"""
Convert to 8-bit color
:return: Color8Bit instance
"""
h, s, v = colorsys.rgb_to_hsv(*self.scale(1))
# Check if the color is a shade of grey
if s * v < 0.3:
if v < 0.3:
return Color8Bit(Color8Bit.BLACK, False)
... | [
"def",
"to_8bit",
"(",
"self",
")",
":",
"h",
",",
"s",
",",
"v",
"=",
"colorsys",
".",
"rgb_to_hsv",
"(",
"*",
"self",
".",
"scale",
"(",
"1",
")",
")",
"# Check if the color is a shade of grey",
"if",
"s",
"*",
"v",
"<",
"0.3",
":",
"if",
"v",
"<... | Convert to 8-bit color
:return: Color8Bit instance | [
"Convert",
"to",
"8",
"-",
"bit",
"color",
":",
"return",
":",
"Color8Bit",
"instance"
] | python | train | 32.121212 |
foremast/foremast | src/foremast/utils/dns.py | https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/dns.py#L99-L123 | def find_existing_record(env, zone_id, dns_name, check_key=None, check_value=None):
"""Check if a specific DNS record exists.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
dns_name (str): FQDN of application's dns entry to add/update.
check_key(str): K... | [
"def",
"find_existing_record",
"(",
"env",
",",
"zone_id",
",",
"dns_name",
",",
"check_key",
"=",
"None",
",",
"check_value",
"=",
"None",
")",
":",
"client",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
")",
".",
"client",
"(",
"'rout... | Check if a specific DNS record exists.
Args:
env (str): Deployment environment.
zone_id (str): Route53 zone id.
dns_name (str): FQDN of application's dns entry to add/update.
check_key(str): Key to look for in record. Example: "Type"
check_value(str): Value to look for with ... | [
"Check",
"if",
"a",
"specific",
"DNS",
"record",
"exists",
"."
] | python | train | 41.6 |
clalancette/pycdlib | pycdlib/eltorito.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/eltorito.py#L745-L790 | def add_section(self, ino, sector_count, load_seg, media_name, system_type,
efi, bootable):
# type: (inode.Inode, int, int, str, int, bool, bool) -> None
'''
A method to add an section header and entry to this Boot Catalog.
Parameters:
ino - The Inode object... | [
"def",
"add_section",
"(",
"self",
",",
"ino",
",",
"sector_count",
",",
"load_seg",
",",
"media_name",
",",
"system_type",
",",
"efi",
",",
"bootable",
")",
":",
"# type: (inode.Inode, int, int, str, int, bool, bool) -> None",
"if",
"not",
"self",
".",
"_initialize... | A method to add an section header and entry to this Boot Catalog.
Parameters:
ino - The Inode object to associate with the new Entry.
sector_count - The number of sectors to assign to the new Entry.
load_seg - The load segment address of the boot image.
media_name - The name... | [
"A",
"method",
"to",
"add",
"an",
"section",
"header",
"and",
"entry",
"to",
"this",
"Boot",
"Catalog",
"."
] | python | train | 42.434783 |
ladybug-tools/ladybug | ladybug/psychrometrics.py | https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/psychrometrics.py#L163-L173 | def rel_humid_from_db_wb(db_temp, wet_bulb, b_press=101325):
"""Relative Humidity (%) at db_temp(C), wet_bulb (C), and Pressure b_press (Pa).
"""
# Calculate saturation pressure.
p_ws = saturated_vapor_pressure(db_temp + 273.15)
p_ws_wb = saturated_vapor_pressure(wet_bulb + 273.15)
# calculate p... | [
"def",
"rel_humid_from_db_wb",
"(",
"db_temp",
",",
"wet_bulb",
",",
"b_press",
"=",
"101325",
")",
":",
"# Calculate saturation pressure.",
"p_ws",
"=",
"saturated_vapor_pressure",
"(",
"db_temp",
"+",
"273.15",
")",
"p_ws_wb",
"=",
"saturated_vapor_pressure",
"(",
... | Relative Humidity (%) at db_temp(C), wet_bulb (C), and Pressure b_press (Pa). | [
"Relative",
"Humidity",
"(",
"%",
")",
"at",
"db_temp",
"(",
"C",
")",
"wet_bulb",
"(",
"C",
")",
"and",
"Pressure",
"b_press",
"(",
"Pa",
")",
"."
] | python | train | 44.545455 |
CalebBell/thermo | thermo/eos.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos.py#L3192-L3202 | def a_alpha_and_derivatives(self, T, full=True, quick=True):
r'''Method to calculate `a_alpha` and its first and second
derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and
`d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more
documentation. Uses the set values of `T... | [
"def",
"a_alpha_and_derivatives",
"(",
"self",
",",
"T",
",",
"full",
"=",
"True",
",",
"quick",
"=",
"True",
")",
":",
"return",
"TWU_a_alpha_common",
"(",
"T",
",",
"self",
".",
"Tc",
",",
"self",
".",
"omega",
",",
"self",
".",
"a",
",",
"full",
... | r'''Method to calculate `a_alpha` and its first and second
derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and
`d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more
documentation. Uses the set values of `Tc`, `omega`, and `a`.
Because of its similarity for ... | [
"r",
"Method",
"to",
"calculate",
"a_alpha",
"and",
"its",
"first",
"and",
"second",
"derivatives",
"for",
"this",
"EOS",
".",
"Returns",
"a_alpha",
"da_alpha_dT",
"and",
"d2a_alpha_dT2",
".",
"See",
"GCEOS",
".",
"a_alpha_and_derivatives",
"for",
"more",
"docum... | python | valid | 57 |
toomore/goristock | grs/BSR.py | https://github.com/toomore/goristock/blob/e61f57f11a626cfbc4afbf66337fd9d1c51e3e71/grs/BSR.py#L67-L71 | def showinfo(self):
''' 總覽顯示 '''
print 'money:',self.money
print 'store:',self.store
print 'avgprice:',self.avgprice | [
"def",
"showinfo",
"(",
"self",
")",
":",
"print",
"'money:'",
",",
"self",
".",
"money",
"print",
"'store:'",
",",
"self",
".",
"store",
"print",
"'avgprice:'",
",",
"self",
".",
"avgprice"
] | 總覽顯示 | [
"總覽顯示"
] | python | train | 25.6 |
pantsbuild/pex | pex/executor.py | https://github.com/pantsbuild/pex/blob/87b2129d860250d3b9edce75b9cb62f9789ee521/pex/executor.py#L61-L77 | def open_process(cls, cmd, **kwargs):
"""Opens a process object via subprocess.Popen().
:param string|list cmd: A list or string representing the command to run.
:param **kwargs: Additional kwargs to pass through to subprocess.Popen.
:return: A `subprocess.Popen` object.
:raises: `Executor.Executab... | [
"def",
"open_process",
"(",
"cls",
",",
"cmd",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"len",
"(",
"cmd",
")",
">",
"0",
",",
"'cannot execute an empty command!'",
"try",
":",
"return",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"*",
"*",
"kwarg... | Opens a process object via subprocess.Popen().
:param string|list cmd: A list or string representing the command to run.
:param **kwargs: Additional kwargs to pass through to subprocess.Popen.
:return: A `subprocess.Popen` object.
:raises: `Executor.ExecutableNotFound` when the executable requested to ... | [
"Opens",
"a",
"process",
"object",
"via",
"subprocess",
".",
"Popen",
"()",
"."
] | python | train | 39.294118 |
Erotemic/utool | utool/util_path.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_path.py#L562-L628 | def checkpath(path_, verbose=VERYVERBOSE, n=None, info=VERYVERBOSE):
r""" verbose wrapper around ``os.path.exists``
Returns:
true if ``path_`` exists on the filesystem show only the
top `n` directories
Args:
path_ (str): path string
verbose (bool): verbosity flag(default = ... | [
"def",
"checkpath",
"(",
"path_",
",",
"verbose",
"=",
"VERYVERBOSE",
",",
"n",
"=",
"None",
",",
"info",
"=",
"VERYVERBOSE",
")",
":",
"assert",
"isinstance",
"(",
"path_",
",",
"six",
".",
"string_types",
")",
",",
"(",
"'path_=%r is not a string. type(pat... | r""" verbose wrapper around ``os.path.exists``
Returns:
true if ``path_`` exists on the filesystem show only the
top `n` directories
Args:
path_ (str): path string
verbose (bool): verbosity flag(default = False)
n (int): (default = None)
info (bool): (default =... | [
"r",
"verbose",
"wrapper",
"around",
"os",
".",
"path",
".",
"exists"
] | python | train | 36.731343 |
totalgood/twip | twip/scripts/clean.py | https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/scripts/clean.py#L107-L146 | def dropna(df, nonnull_rows=100, nonnull_cols=50, nanstrs=('nan', 'NaN', ''), nullstr=''):
"""Drop columns/rows with too many NaNs and replace NaNs in columns of strings with ''
>>> df = pd.DataFrame([['nan',np.nan,'str'],[np.nan,0.1,'and'],[2.0,None,np.nan]])
>>> dropna(df)
Empty DataFrame
Columns... | [
"def",
"dropna",
"(",
"df",
",",
"nonnull_rows",
"=",
"100",
",",
"nonnull_cols",
"=",
"50",
",",
"nanstrs",
"=",
"(",
"'nan'",
",",
"'NaN'",
",",
"''",
")",
",",
"nullstr",
"=",
"''",
")",
":",
"if",
"0",
"<",
"nonnull_rows",
"<",
"1",
":",
"non... | Drop columns/rows with too many NaNs and replace NaNs in columns of strings with ''
>>> df = pd.DataFrame([['nan',np.nan,'str'],[np.nan,0.1,'and'],[2.0,None,np.nan]])
>>> dropna(df)
Empty DataFrame
Columns: []
Index: []
>>> dropna(df, nonnull_cols=0, nonnull_rows=0)
0 1 2
0 ... | [
"Drop",
"columns",
"/",
"rows",
"with",
"too",
"many",
"NaNs",
"and",
"replace",
"NaNs",
"in",
"columns",
"of",
"strings",
"with"
] | python | train | 43.775 |
pytroll/satpy | satpy/writers/__init__.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/writers/__init__.py#L284-L302 | def add_text(orig, dc, img, text=None):
"""Add text to an image using the pydecorate package.
All the features of pydecorate's ``add_text`` are available.
See documentation of :doc:`pydecorate:index` for more info.
"""
LOG.info("Add text to image.")
dc.add_text(**text)
arr = da.from_arra... | [
"def",
"add_text",
"(",
"orig",
",",
"dc",
",",
"img",
",",
"text",
"=",
"None",
")",
":",
"LOG",
".",
"info",
"(",
"\"Add text to image.\"",
")",
"dc",
".",
"add_text",
"(",
"*",
"*",
"text",
")",
"arr",
"=",
"da",
".",
"from_array",
"(",
"np",
... | Add text to an image using the pydecorate package.
All the features of pydecorate's ``add_text`` are available.
See documentation of :doc:`pydecorate:index` for more info. | [
"Add",
"text",
"to",
"an",
"image",
"using",
"the",
"pydecorate",
"package",
"."
] | python | train | 35.526316 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.