repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
GNS3/gns3-server | gns3server/compute/iou/iou_vm.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/iou/iou_vm.py#L832-L867 | def adapter_add_nio_binding(self, adapter_number, port_number, nio):
"""
Adds a adapter NIO binding.
:param adapter_number: adapter number
:param port_number: port number
:param nio: NIO instance to add to the adapter/port
"""
try:
adapter = self._ad... | [
"def",
"adapter_add_nio_binding",
"(",
"self",
",",
"adapter_number",
",",
"port_number",
",",
"nio",
")",
":",
"try",
":",
"adapter",
"=",
"self",
".",
"_adapters",
"[",
"adapter_number",
"]",
"except",
"IndexError",
":",
"raise",
"IOUError",
"(",
"'Adapter {... | Adds a adapter NIO binding.
:param adapter_number: adapter number
:param port_number: port number
:param nio: NIO instance to add to the adapter/port | [
"Adds",
"a",
"adapter",
"NIO",
"binding",
"."
] | python | train |
googlefonts/fontbakery | Lib/fontbakery/profiles/googlefonts.py | https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/googlefonts.py#L3579-L3611 | def com_google_fonts_check_family_tnum_horizontal_metrics(fonts):
"""All tabular figures must have the same width across the RIBBI-family."""
from fontbakery.constants import RIBBI_STYLE_NAMES
from fontTools.ttLib import TTFont
RIBBI_ttFonts = [TTFont(f)
for f in fonts
if s... | [
"def",
"com_google_fonts_check_family_tnum_horizontal_metrics",
"(",
"fonts",
")",
":",
"from",
"fontbakery",
".",
"constants",
"import",
"RIBBI_STYLE_NAMES",
"from",
"fontTools",
".",
"ttLib",
"import",
"TTFont",
"RIBBI_ttFonts",
"=",
"[",
"TTFont",
"(",
"f",
")",
... | All tabular figures must have the same width across the RIBBI-family. | [
"All",
"tabular",
"figures",
"must",
"have",
"the",
"same",
"width",
"across",
"the",
"RIBBI",
"-",
"family",
"."
] | python | train |
openstates/billy | billy/reports/utils.py | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/reports/utils.py#L11-L19 | def update_common(obj, report):
""" do updated_at checks """
# updated checks
if obj['updated_at'] >= yesterday:
report['_updated_today_count'] += 1
if obj['updated_at'] >= last_month:
report['_updated_this_month_count'] += 1
if obj['updated_at'] >= last_year:
... | [
"def",
"update_common",
"(",
"obj",
",",
"report",
")",
":",
"# updated checks",
"if",
"obj",
"[",
"'updated_at'",
"]",
">=",
"yesterday",
":",
"report",
"[",
"'_updated_today_count'",
"]",
"+=",
"1",
"if",
"obj",
"[",
"'updated_at'",
"]",
">=",
"last_month"... | do updated_at checks | [
"do",
"updated_at",
"checks"
] | python | train |
gem/oq-engine | openquake/hazardlib/gsim/afshari_stewart_2016.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/afshari_stewart_2016.py#L174-L184 | def _get_tau(self, C, mag):
"""
Returns magnitude dependent inter-event standard deviation (tau)
(equation 14)
"""
if mag < 6.5:
return C["tau1"]
elif mag < 7.:
return C["tau1"] + (C["tau2"] - C["tau1"]) * ((mag - 6.5) / 0.5)
else:
... | [
"def",
"_get_tau",
"(",
"self",
",",
"C",
",",
"mag",
")",
":",
"if",
"mag",
"<",
"6.5",
":",
"return",
"C",
"[",
"\"tau1\"",
"]",
"elif",
"mag",
"<",
"7.",
":",
"return",
"C",
"[",
"\"tau1\"",
"]",
"+",
"(",
"C",
"[",
"\"tau2\"",
"]",
"-",
"... | Returns magnitude dependent inter-event standard deviation (tau)
(equation 14) | [
"Returns",
"magnitude",
"dependent",
"inter",
"-",
"event",
"standard",
"deviation",
"(",
"tau",
")",
"(",
"equation",
"14",
")"
] | python | train |
LudovicRousseau/pyscard | smartcard/ExclusiveConnectCardConnection.py | https://github.com/LudovicRousseau/pyscard/blob/62e675028086c75656444cc21d563d9f08ebf8e7/smartcard/ExclusiveConnectCardConnection.py#L41-L72 | def connect(self, protocol=None, mode=None, disposition=None):
'''Disconnect and reconnect in exclusive mode PCSCCardconnections.'''
CardConnectionDecorator.connect(self, protocol, mode, disposition)
component = self.component
while True:
if isinstance(component,
... | [
"def",
"connect",
"(",
"self",
",",
"protocol",
"=",
"None",
",",
"mode",
"=",
"None",
",",
"disposition",
"=",
"None",
")",
":",
"CardConnectionDecorator",
".",
"connect",
"(",
"self",
",",
"protocol",
",",
"mode",
",",
"disposition",
")",
"component",
... | Disconnect and reconnect in exclusive mode PCSCCardconnections. | [
"Disconnect",
"and",
"reconnect",
"in",
"exclusive",
"mode",
"PCSCCardconnections",
"."
] | python | train |
PythonCharmers/python-future | src/future/builtins/newnext.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/builtins/newnext.py#L43-L67 | def newnext(iterator, default=_SENTINEL):
"""
next(iterator[, default])
Return the next item from the iterator. If default is given and the iterator
is exhausted, it is returned instead of raising StopIteration.
"""
# args = []
# if default is not _SENTINEL:
# args.append(default)
... | [
"def",
"newnext",
"(",
"iterator",
",",
"default",
"=",
"_SENTINEL",
")",
":",
"# args = []",
"# if default is not _SENTINEL:",
"# args.append(default)",
"try",
":",
"try",
":",
"return",
"iterator",
".",
"__next__",
"(",
")",
"except",
"AttributeError",
":",
... | next(iterator[, default])
Return the next item from the iterator. If default is given and the iterator
is exhausted, it is returned instead of raising StopIteration. | [
"next",
"(",
"iterator",
"[",
"default",
"]",
")"
] | python | train |
ibis-project/ibis | ibis/expr/api.py | https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/expr/api.py#L1350-L1363 | def _integer_to_interval(arg, unit='s'):
"""
Convert integer interval with the same inner type
Parameters
----------
unit : {'Y', 'M', 'W', 'D', 'h', 'm', s', 'ms', 'us', 'ns'}
Returns
-------
interval : interval value expression
"""
op = ops.IntervalFromInteger(arg, unit)
... | [
"def",
"_integer_to_interval",
"(",
"arg",
",",
"unit",
"=",
"'s'",
")",
":",
"op",
"=",
"ops",
".",
"IntervalFromInteger",
"(",
"arg",
",",
"unit",
")",
"return",
"op",
".",
"to_expr",
"(",
")"
] | Convert integer interval with the same inner type
Parameters
----------
unit : {'Y', 'M', 'W', 'D', 'h', 'm', s', 'ms', 'us', 'ns'}
Returns
-------
interval : interval value expression | [
"Convert",
"integer",
"interval",
"with",
"the",
"same",
"inner",
"type"
] | python | train |
materialsproject/pymatgen | pymatgen/io/vasp/outputs.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/vasp/outputs.py#L2090-L2207 | def read_igpar(self):
"""
Renders accessible:
er_ev = e<r>_ev (dictionary with Spin.up/Spin.down as keys)
er_bp = e<r>_bp (dictionary with Spin.up/Spin.down as keys)
er_ev_tot = spin up + spin down summed
er_bp_tot = spin up + spin down summed
... | [
"def",
"read_igpar",
"(",
"self",
")",
":",
"# variables to be filled",
"self",
".",
"er_ev",
"=",
"{",
"}",
"# will be dict (Spin.up/down) of array(3*float)",
"self",
".",
"er_bp",
"=",
"{",
"}",
"# will be dics (Spin.up/down) of array(3*float)",
"self",
".",
"er_e... | Renders accessible:
er_ev = e<r>_ev (dictionary with Spin.up/Spin.down as keys)
er_bp = e<r>_bp (dictionary with Spin.up/Spin.down as keys)
er_ev_tot = spin up + spin down summed
er_bp_tot = spin up + spin down summed
p_elc = spin up + spin down summed
... | [
"Renders",
"accessible",
":",
"er_ev",
"=",
"e<r",
">",
"_ev",
"(",
"dictionary",
"with",
"Spin",
".",
"up",
"/",
"Spin",
".",
"down",
"as",
"keys",
")",
"er_bp",
"=",
"e<r",
">",
"_bp",
"(",
"dictionary",
"with",
"Spin",
".",
"up",
"/",
"Spin",
".... | python | train |
pandas-dev/pandas | pandas/core/generic.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/generic.py#L274-L278 | def _construct_axes_dict(self, axes=None, **kwargs):
"""Return an axes dictionary for myself."""
d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)}
d.update(kwargs)
return d | [
"def",
"_construct_axes_dict",
"(",
"self",
",",
"axes",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"{",
"a",
":",
"self",
".",
"_get_axis",
"(",
"a",
")",
"for",
"a",
"in",
"(",
"axes",
"or",
"self",
".",
"_AXIS_ORDERS",
")",
"}",... | Return an axes dictionary for myself. | [
"Return",
"an",
"axes",
"dictionary",
"for",
"myself",
"."
] | python | train |
deviantony/valigator | valigator/scheduler.py | https://github.com/deviantony/valigator/blob/0557029bc58ea1270e358c14ca382d3807ed5b6f/valigator/scheduler.py#L11-L38 | def validate_backup(configuration, backup_data):
"""Celery task.
It will extract the backup archive into a unique folder
in the temporary directory specified in the configuration.
Once extracted, a Docker container will be started and will
start a restoration procedure. The worker will wait for the... | [
"def",
"validate_backup",
"(",
"configuration",
",",
"backup_data",
")",
":",
"extract_archive",
"(",
"backup_data",
"[",
"'archive_path'",
"]",
",",
"backup_data",
"[",
"'workdir'",
"]",
")",
"docker_client",
"=",
"Client",
"(",
"configuration",
"[",
"'docker'",
... | Celery task.
It will extract the backup archive into a unique folder
in the temporary directory specified in the configuration.
Once extracted, a Docker container will be started and will
start a restoration procedure. The worker will wait for the
container to exit and retrieve its return code.
... | [
"Celery",
"task",
".",
"It",
"will",
"extract",
"the",
"backup",
"archive",
"into",
"a",
"unique",
"folder",
"in",
"the",
"temporary",
"directory",
"specified",
"in",
"the",
"configuration",
"."
] | python | train |
pkgw/pwkit | pwkit/io.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/io.py#L736-L754 | def read_fits_bintable (self, hdu=1, drop_nonscalar_ok=True, **kwargs):
"""Open as a FITS file, read in a binary table, and return it as a
:class:`pandas.DataFrame`, converted with
:func:`pkwit.numutil.fits_recarray_to_data_frame`. The *hdu* argument
specifies which HDU to read, with its... | [
"def",
"read_fits_bintable",
"(",
"self",
",",
"hdu",
"=",
"1",
",",
"drop_nonscalar_ok",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"astropy",
".",
"io",
"import",
"fits",
"from",
".",
"numutil",
"import",
"fits_recarray_to_data_frame",
"as",
... | Open as a FITS file, read in a binary table, and return it as a
:class:`pandas.DataFrame`, converted with
:func:`pkwit.numutil.fits_recarray_to_data_frame`. The *hdu* argument
specifies which HDU to read, with its default 1 indicating the first
FITS extension. The *drop_nonscalar_ok* arg... | [
"Open",
"as",
"a",
"FITS",
"file",
"read",
"in",
"a",
"binary",
"table",
"and",
"return",
"it",
"as",
"a",
":",
"class",
":",
"pandas",
".",
"DataFrame",
"converted",
"with",
":",
"func",
":",
"pkwit",
".",
"numutil",
".",
"fits_recarray_to_data_frame",
... | python | train |
spacetelescope/acstools | acstools/acs_destripe_plus.py | https://github.com/spacetelescope/acstools/blob/bbf8dd080cefcbf88529ec87c420f9e1b8002554/acstools/acs_destripe_plus.py#L111-L498 | def destripe_plus(inputfile, suffix='strp', stat='pmode1', maxiter=15,
sigrej=2.0, lower=None, upper=None, binwidth=0.3,
scimask1=None, scimask2=None,
dqbits=None, rpt_clean=0, atol=0.01,
cte_correct=True, clobber=False, verbose=True):
r"""Cali... | [
"def",
"destripe_plus",
"(",
"inputfile",
",",
"suffix",
"=",
"'strp'",
",",
"stat",
"=",
"'pmode1'",
",",
"maxiter",
"=",
"15",
",",
"sigrej",
"=",
"2.0",
",",
"lower",
"=",
"None",
",",
"upper",
"=",
"None",
",",
"binwidth",
"=",
"0.3",
",",
"scima... | r"""Calibrate post-SM4 ACS/WFC exposure(s) and use
standalone :ref:`acsdestripe`.
This takes a RAW image and generates a FLT file containing
its calibrated and destriped counterpart.
If CTE correction is performed, FLC will also be present.
Parameters
----------
inputfile : str or list of ... | [
"r",
"Calibrate",
"post",
"-",
"SM4",
"ACS",
"/",
"WFC",
"exposure",
"(",
"s",
")",
"and",
"use",
"standalone",
":",
"ref",
":",
"acsdestripe",
"."
] | python | train |
estnltk/estnltk | estnltk/text.py | https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/text.py#L937-L941 | def timex_spans(self):
"""The list of spans of ``timexes`` layer elements."""
if not self.is_tagged(TIMEXES):
self.tag_timexes()
return self.spans(TIMEXES) | [
"def",
"timex_spans",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"TIMEXES",
")",
":",
"self",
".",
"tag_timexes",
"(",
")",
"return",
"self",
".",
"spans",
"(",
"TIMEXES",
")"
] | The list of spans of ``timexes`` layer elements. | [
"The",
"list",
"of",
"spans",
"of",
"timexes",
"layer",
"elements",
"."
] | python | train |
divio/python-mautic | mautic/contacts.py | https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/contacts.py#L17-L26 | def get_owners(self):
"""
Get a list of users available as contact owners
:return: dict|str
"""
response = self._client.session.get(
'{url}/list/owners'.format(url=self.endpoint_url)
)
return self.process_response(response) | [
"def",
"get_owners",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_client",
".",
"session",
".",
"get",
"(",
"'{url}/list/owners'",
".",
"format",
"(",
"url",
"=",
"self",
".",
"endpoint_url",
")",
")",
"return",
"self",
".",
"process_response",
... | Get a list of users available as contact owners
:return: dict|str | [
"Get",
"a",
"list",
"of",
"users",
"available",
"as",
"contact",
"owners"
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_firmware.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_firmware.py#L853-L865 | def logical_chassis_fwdl_status_output_cluster_fwdl_entries_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status")
config = logical_chassis_fwdl_status
output = ET.SubEle... | [
"def",
"logical_chassis_fwdl_status_output_cluster_fwdl_entries_rbridge_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"logical_chassis_fwdl_status",
"=",
"ET",
".",
"Element",
"(",
"\"logical_chassis_... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
byt3bl33d3r/CrackMapExec | cme/protocols/smb/db_navigator.py | https://github.com/byt3bl33d3r/CrackMapExec/blob/333f1c4e06884e85b2776459963ef85d182aba8e/cme/protocols/smb/db_navigator.py#L255-L262 | def complete_hosts(self, text, line, begidx, endidx):
"Tab-complete 'creds' commands."
commands = ["add", "remove", "dc"]
mline = line.partition(' ')[2]
offs = len(mline) - len(text)
return [s[offs:] for s in commands if s.startswith(mline)] | [
"def",
"complete_hosts",
"(",
"self",
",",
"text",
",",
"line",
",",
"begidx",
",",
"endidx",
")",
":",
"commands",
"=",
"[",
"\"add\"",
",",
"\"remove\"",
",",
"\"dc\"",
"]",
"mline",
"=",
"line",
".",
"partition",
"(",
"' '",
")",
"[",
"2",
"]",
... | Tab-complete 'creds' commands. | [
"Tab",
"-",
"complete",
"creds",
"commands",
"."
] | python | train |
pandas-dev/pandas | pandas/core/internals/blocks.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/internals/blocks.py#L224-L234 | def make_block_same_class(self, values, placement=None, ndim=None,
dtype=None):
""" Wrap given values in a block of same type as self. """
if dtype is not None:
# issue 19431 fastparquet is passing this
warnings.warn("dtype argument is deprecated, wi... | [
"def",
"make_block_same_class",
"(",
"self",
",",
"values",
",",
"placement",
"=",
"None",
",",
"ndim",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"dtype",
"is",
"not",
"None",
":",
"# issue 19431 fastparquet is passing this",
"warnings",
".",
"... | Wrap given values in a block of same type as self. | [
"Wrap",
"given",
"values",
"in",
"a",
"block",
"of",
"same",
"type",
"as",
"self",
"."
] | python | train |
PMBio/limix-backup | limix/core/old/gp/gp_base.py | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/core/old/gp/gp_base.py#L120-L142 | def checkGradient(self,h=1e-6,verbose=True):
""" utility function to check the gradient of the gp """
grad_an = self.LMLgrad()
grad_num = {}
params0 = self.params.copy()
for key in list(self.params.keys()):
paramsL = params0.copy()
paramsR = params0.copy()... | [
"def",
"checkGradient",
"(",
"self",
",",
"h",
"=",
"1e-6",
",",
"verbose",
"=",
"True",
")",
":",
"grad_an",
"=",
"self",
".",
"LMLgrad",
"(",
")",
"grad_num",
"=",
"{",
"}",
"params0",
"=",
"self",
".",
"params",
".",
"copy",
"(",
")",
"for",
"... | utility function to check the gradient of the gp | [
"utility",
"function",
"to",
"check",
"the",
"gradient",
"of",
"the",
"gp"
] | python | train |
jaraco/jaraco.itertools | jaraco/itertools.py | https://github.com/jaraco/jaraco.itertools/blob/0dc47c8924fa3d9ab676c3a6e195f03f728b72c6/jaraco/itertools.py#L856-L877 | def partition_items(count, bin_size):
"""
Given the total number of items, determine the number of items that
can be added to each bin with a limit on the bin size.
So if you want to partition 11 items into groups of 3, you'll want
three of three and one of two.
>>> partition_items(11, 3)
[3, 3, 3, 2]
But if... | [
"def",
"partition_items",
"(",
"count",
",",
"bin_size",
")",
":",
"num_bins",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"count",
"/",
"float",
"(",
"bin_size",
")",
")",
")",
"bins",
"=",
"[",
"0",
"]",
"*",
"num_bins",
"for",
"i",
"in",
"range",... | Given the total number of items, determine the number of items that
can be added to each bin with a limit on the bin size.
So if you want to partition 11 items into groups of 3, you'll want
three of three and one of two.
>>> partition_items(11, 3)
[3, 3, 3, 2]
But if you only have ten items, you'll have two gr... | [
"Given",
"the",
"total",
"number",
"of",
"items",
"determine",
"the",
"number",
"of",
"items",
"that",
"can",
"be",
"added",
"to",
"each",
"bin",
"with",
"a",
"limit",
"on",
"the",
"bin",
"size",
"."
] | python | test |
PmagPy/PmagPy | programs/conversion_scripts2/pmd_magic2.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/conversion_scripts2/pmd_magic2.py#L7-L276 | def main(command_line=True, **kwargs):
"""
NAME
pmd_magic.py
DESCRIPTION
converts PMD (Enkin) format files to magic_measurements format files
SYNTAX
pmd_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-f FILE: specify input... | [
"def",
"main",
"(",
"command_line",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# initialize some stuff",
"noave",
"=",
"0",
"inst",
"=",
"\"\"",
"samp_con",
",",
"Z",
"=",
"'1'",
",",
"\"\"",
"missing",
"=",
"1",
"demag",
"=",
"\"N\"",
"er_locati... | NAME
pmd_magic.py
DESCRIPTION
converts PMD (Enkin) format files to magic_measurements format files
SYNTAX
pmd_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-f FILE: specify input file, or
-F FILE: specify output file, def... | [
"NAME",
"pmd_magic",
".",
"py",
"DESCRIPTION",
"converts",
"PMD",
"(",
"Enkin",
")",
"format",
"files",
"to",
"magic_measurements",
"format",
"files"
] | python | train |
WebarchivCZ/WA-KAT | src/wa_kat/templates/static/js/Lib/site-packages/components/keyword_handler.py | https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/templates/static/js/Lib/site-packages/components/keyword_handler.py#L144-L157 | def set_kw_typeahead_input(cls):
"""
Map the typeahead input to remote dataset.
"""
# get reference to parent element
parent_id = cls.intput_el.parent.id
if "typeahead" not in parent_id.lower():
parent_id = cls.intput_el.parent.parent.id
window.make_k... | [
"def",
"set_kw_typeahead_input",
"(",
"cls",
")",
":",
"# get reference to parent element",
"parent_id",
"=",
"cls",
".",
"intput_el",
".",
"parent",
".",
"id",
"if",
"\"typeahead\"",
"not",
"in",
"parent_id",
".",
"lower",
"(",
")",
":",
"parent_id",
"=",
"cl... | Map the typeahead input to remote dataset. | [
"Map",
"the",
"typeahead",
"input",
"to",
"remote",
"dataset",
"."
] | python | train |
pantsbuild/pants | contrib/python/src/python/pants/contrib/python/checks/checker/common.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/python/src/python/pants/contrib/python/checks/checker/common.py#L218-L227 | def line_range(self, line_number):
"""Return a slice for the given line number"""
if line_number <= 0 or line_number > len(self.lines):
raise IndexError('NOTE: Python file line numbers are offset by 1.')
if line_number not in self.logical_lines:
return slice(line_number, line_number + 1)
el... | [
"def",
"line_range",
"(",
"self",
",",
"line_number",
")",
":",
"if",
"line_number",
"<=",
"0",
"or",
"line_number",
">",
"len",
"(",
"self",
".",
"lines",
")",
":",
"raise",
"IndexError",
"(",
"'NOTE: Python file line numbers are offset by 1.'",
")",
"if",
"l... | Return a slice for the given line number | [
"Return",
"a",
"slice",
"for",
"the",
"given",
"line",
"number"
] | python | train |
opendatateam/udata | udata/forms/fields.py | https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/forms/fields.py#L55-L59 | def pre_validate(self, form):
'''Calls preprocessors before pre_validation'''
for preprocessor in self._preprocessors:
preprocessor(form, self)
super(FieldHelper, self).pre_validate(form) | [
"def",
"pre_validate",
"(",
"self",
",",
"form",
")",
":",
"for",
"preprocessor",
"in",
"self",
".",
"_preprocessors",
":",
"preprocessor",
"(",
"form",
",",
"self",
")",
"super",
"(",
"FieldHelper",
",",
"self",
")",
".",
"pre_validate",
"(",
"form",
")... | Calls preprocessors before pre_validation | [
"Calls",
"preprocessors",
"before",
"pre_validation"
] | python | train |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/widgets/reftrackwidget.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/reftrackwidget.py#L402-L411 | def replace(self, ):
"""Replace the current reftrack
:returns: None
:rtype: None
:raises: None
"""
tfi = self.get_taskfileinfo_selection()
if tfi:
self.reftrack.replace(tfi) | [
"def",
"replace",
"(",
"self",
",",
")",
":",
"tfi",
"=",
"self",
".",
"get_taskfileinfo_selection",
"(",
")",
"if",
"tfi",
":",
"self",
".",
"reftrack",
".",
"replace",
"(",
"tfi",
")"
] | Replace the current reftrack
:returns: None
:rtype: None
:raises: None | [
"Replace",
"the",
"current",
"reftrack"
] | python | train |
neurosynth/neurosynth | neurosynth/analysis/reduce.py | https://github.com/neurosynth/neurosynth/blob/948ce7edce15d7df693446e76834e0c23bfe8f11/neurosynth/analysis/reduce.py#L176-L323 | def run_lda(abstracts, n_topics=50, n_words=31, n_iters=1000, alpha=None,
beta=0.001):
""" Perform topic modeling using Latent Dirichlet Allocation with the
Java toolbox MALLET.
Args:
abstracts: A pandas DataFrame with two columns ('pmid' and 'abstract')
containing ... | [
"def",
"run_lda",
"(",
"abstracts",
",",
"n_topics",
"=",
"50",
",",
"n_words",
"=",
"31",
",",
"n_iters",
"=",
"1000",
",",
"alpha",
"=",
"None",
",",
"beta",
"=",
"0.001",
")",
":",
"if",
"abstracts",
".",
"index",
".",
"name",
"!=",
"'pmid'",
":... | Perform topic modeling using Latent Dirichlet Allocation with the
Java toolbox MALLET.
Args:
abstracts: A pandas DataFrame with two columns ('pmid' and 'abstract')
containing article abstracts.
n_topics: Number of topics to generate. Default=50.
n_words: Number... | [
"Perform",
"topic",
"modeling",
"using",
"Latent",
"Dirichlet",
"Allocation",
"with",
"the",
"Java",
"toolbox",
"MALLET",
"."
] | python | test |
senaite/senaite.core | bika/lims/adapters/identifiers.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/adapters/identifiers.py#L39-L45 | def IdentifiersIndexer(instance):
"""Return a list of unique Identifier strings
This populates the Identifiers Keyword index, but with some
replacements to prevent the word-splitter etc from taking effect.
"""
identifiers = instance.Schema()['Identifiers'].get(instance)
return [safe_unicode(i['I... | [
"def",
"IdentifiersIndexer",
"(",
"instance",
")",
":",
"identifiers",
"=",
"instance",
".",
"Schema",
"(",
")",
"[",
"'Identifiers'",
"]",
".",
"get",
"(",
"instance",
")",
"return",
"[",
"safe_unicode",
"(",
"i",
"[",
"'Identifier'",
"]",
")",
"for",
"... | Return a list of unique Identifier strings
This populates the Identifiers Keyword index, but with some
replacements to prevent the word-splitter etc from taking effect. | [
"Return",
"a",
"list",
"of",
"unique",
"Identifier",
"strings",
"This",
"populates",
"the",
"Identifiers",
"Keyword",
"index",
"but",
"with",
"some",
"replacements",
"to",
"prevent",
"the",
"word",
"-",
"splitter",
"etc",
"from",
"taking",
"effect",
"."
] | python | train |
Fantomas42/django-blog-zinnia | zinnia/sitemaps.py | https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/sitemaps.py#L61-L69 | def get_queryset(self):
"""
Build a queryset of items with published entries and annotated
with the number of entries and the latest modification date.
"""
return self.model.published.annotate(
count_entries_published=Count('entries')).annotate(
last_updat... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"return",
"self",
".",
"model",
".",
"published",
".",
"annotate",
"(",
"count_entries_published",
"=",
"Count",
"(",
"'entries'",
")",
")",
".",
"annotate",
"(",
"last_update",
"=",
"Max",
"(",
"'entries__last_u... | Build a queryset of items with published entries and annotated
with the number of entries and the latest modification date. | [
"Build",
"a",
"queryset",
"of",
"items",
"with",
"published",
"entries",
"and",
"annotated",
"with",
"the",
"number",
"of",
"entries",
"and",
"the",
"latest",
"modification",
"date",
"."
] | python | train |
miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L197-L254 | def create_relationship(self, json_data, relationship_field, related_id_field, view_kwargs):
"""Create a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of t... | [
"def",
"create_relationship",
"(",
"self",
",",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_create_relationship",
"(",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_k... | Create a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return boolean:... | [
"Create",
"a",
"relationship"
] | python | train |
josiah-wolf-oberholtzer/uqbar | uqbar/io/__init__.py | https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/io/__init__.py#L146-L186 | def write(
contents: str,
path: Union[str, pathlib.Path],
verbose: bool = False,
logger_func=None,
) -> bool:
"""
Writes ``contents`` to ``path``.
Checks if ``path`` already exists and only write out new contents if the
old contents do not match.
Creates any intermediate missing di... | [
"def",
"write",
"(",
"contents",
":",
"str",
",",
"path",
":",
"Union",
"[",
"str",
",",
"pathlib",
".",
"Path",
"]",
",",
"verbose",
":",
"bool",
"=",
"False",
",",
"logger_func",
"=",
"None",
",",
")",
"->",
"bool",
":",
"print_func",
"=",
"logge... | Writes ``contents`` to ``path``.
Checks if ``path`` already exists and only write out new contents if the
old contents do not match.
Creates any intermediate missing directories.
:param contents: the file contents to write
:param path: the path to write to
:param verbose: whether to print out... | [
"Writes",
"contents",
"to",
"path",
"."
] | python | train |
ampl/amplpy | amplpy/entity.py | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/entity.py#L177-L205 | def setValues(self, data):
"""
Set the values of this entiy to the correponding values of a
DataFrame indexed over the same sets (or a subset).
This function assigns the values in the first data column of
the passed dataframe to the entity the function is called from.
In ... | [
"def",
"setValues",
"(",
"self",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"DataFrame",
")",
":",
"self",
".",
"_impl",
".",
"setValuesDf",
"(",
"data",
".",
"_impl",
")",
"else",
":",
"if",
"pd",
"is",
"not",
"None",
"and",
"isi... | Set the values of this entiy to the correponding values of a
DataFrame indexed over the same sets (or a subset).
This function assigns the values in the first data column of
the passed dataframe to the entity the function is called from.
In particular, the statement:
.. code-blo... | [
"Set",
"the",
"values",
"of",
"this",
"entiy",
"to",
"the",
"correponding",
"values",
"of",
"a",
"DataFrame",
"indexed",
"over",
"the",
"same",
"sets",
"(",
"or",
"a",
"subset",
")",
".",
"This",
"function",
"assigns",
"the",
"values",
"in",
"the",
"firs... | python | train |
ontio/ontology-python-sdk | ontology/smart_contract/neo_contract/oep4.py | https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/neo_contract/oep4.py#L89-L102 | def get_total_supply(self) -> int:
"""
This interface is used to call the TotalSupply method in ope4
that return the total supply of the oep4 token.
:return: the total supply of the oep4 token.
"""
func = InvokeFunction('totalSupply')
response = self.__sdk.get_ne... | [
"def",
"get_total_supply",
"(",
"self",
")",
"->",
"int",
":",
"func",
"=",
"InvokeFunction",
"(",
"'totalSupply'",
")",
"response",
"=",
"self",
".",
"__sdk",
".",
"get_network",
"(",
")",
".",
"send_neo_vm_transaction_pre_exec",
"(",
"self",
".",
"__hex_cont... | This interface is used to call the TotalSupply method in ope4
that return the total supply of the oep4 token.
:return: the total supply of the oep4 token. | [
"This",
"interface",
"is",
"used",
"to",
"call",
"the",
"TotalSupply",
"method",
"in",
"ope4",
"that",
"return",
"the",
"total",
"supply",
"of",
"the",
"oep4",
"token",
"."
] | python | train |
kejbaly2/metrique | metrique/sqlalchemy.py | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/sqlalchemy.py#L849-L863 | def index_list(self):
'''
List all cube indexes
:param collection: cube name
:param owner: username of cube owner
'''
logger.info('Listing indexes')
_ix = {}
_i = self.inspector
for tbl in _i.get_table_names():
_ix.setdefault(tbl, [])
... | [
"def",
"index_list",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Listing indexes'",
")",
"_ix",
"=",
"{",
"}",
"_i",
"=",
"self",
".",
"inspector",
"for",
"tbl",
"in",
"_i",
".",
"get_table_names",
"(",
")",
":",
"_ix",
".",
"setdefault",
"(... | List all cube indexes
:param collection: cube name
:param owner: username of cube owner | [
"List",
"all",
"cube",
"indexes"
] | python | train |
quantumlib/Cirq | cirq/devices/noise_model.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/devices/noise_model.py#L94-L111 | def noisy_operation(self, operation: 'cirq.Operation') -> 'cirq.OP_TREE':
"""Adds noise to an individual operation.
Args:
operation: The operation to make noisy.
Returns:
An OP_TREE corresponding to the noisy operations implementing the
noisy version of the ... | [
"def",
"noisy_operation",
"(",
"self",
",",
"operation",
":",
"'cirq.Operation'",
")",
"->",
"'cirq.OP_TREE'",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"noisy_moments",
",",
"'_not_overridden'",
")",
":",
"return",
"self",
".",
"noisy_moments",
"(",
"[",... | Adds noise to an individual operation.
Args:
operation: The operation to make noisy.
Returns:
An OP_TREE corresponding to the noisy operations implementing the
noisy version of the given operation. | [
"Adds",
"noise",
"to",
"an",
"individual",
"operation",
"."
] | python | train |
255BITS/hyperchamber | hyperchamber/selector.py | https://github.com/255BITS/hyperchamber/blob/4d5774bde9ea6ce1113f77a069ffc605148482b8/hyperchamber/selector.py#L29-L32 | def set(self, key, value):
"""Sets a hyperparameter. Can be used to set an array of hyperparameters."""
self.store[key]=value
return self.store | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"store",
"[",
"key",
"]",
"=",
"value",
"return",
"self",
".",
"store"
] | Sets a hyperparameter. Can be used to set an array of hyperparameters. | [
"Sets",
"a",
"hyperparameter",
".",
"Can",
"be",
"used",
"to",
"set",
"an",
"array",
"of",
"hyperparameters",
"."
] | python | train |
Valuehorizon/valuehorizon-companies | companies/models.py | https://github.com/Valuehorizon/valuehorizon-companies/blob/5366e230da69ee30fcdc1bf4beddc99310f6b767/companies/models.py#L242-L249 | def get_immediate_children_ownership(self):
"""
Return all direct subsidiaries of this company AS OWNERSHIP OBJECTS.
Excludes subsidiaries of subsidiaries.
"""
ownership = Ownership.objects.filter(parent=self).select_related('child', 'child__country')
return ownership | [
"def",
"get_immediate_children_ownership",
"(",
"self",
")",
":",
"ownership",
"=",
"Ownership",
".",
"objects",
".",
"filter",
"(",
"parent",
"=",
"self",
")",
".",
"select_related",
"(",
"'child'",
",",
"'child__country'",
")",
"return",
"ownership"
] | Return all direct subsidiaries of this company AS OWNERSHIP OBJECTS.
Excludes subsidiaries of subsidiaries. | [
"Return",
"all",
"direct",
"subsidiaries",
"of",
"this",
"company",
"AS",
"OWNERSHIP",
"OBJECTS",
".",
"Excludes",
"subsidiaries",
"of",
"subsidiaries",
"."
] | python | train |
wonambi-python/wonambi | wonambi/widgets/notes.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/notes.py#L878-L908 | def find_row(self, ev_start, ev_end):
"""Highlight event row in table from start and end time.
Parameters
----------
ev_start : float
start time, in seconds from record start
ev_end : float
end time, in seconds from record start
... | [
"def",
"find_row",
"(",
"self",
",",
"ev_start",
",",
"ev_end",
")",
":",
"all_starts",
"=",
"self",
".",
"idx_annot_list",
".",
"property",
"(",
"'start'",
")",
"all_ends",
"=",
"self",
".",
"idx_annot_list",
".",
"property",
"(",
"'end'",
")",
"for",
"... | Highlight event row in table from start and end time.
Parameters
----------
ev_start : float
start time, in seconds from record start
ev_end : float
end time, in seconds from record start
Returns
-------
int
... | [
"Highlight",
"event",
"row",
"in",
"table",
"from",
"start",
"and",
"end",
"time",
".",
"Parameters",
"----------",
"ev_start",
":",
"float",
"start",
"time",
"in",
"seconds",
"from",
"record",
"start",
"ev_end",
":",
"float",
"end",
"time",
"in",
"seconds",... | python | train |
creare-com/pydem | pydem/reader/my_types.py | https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/reader/my_types.py#L150-L159 | def grid_coords_from_corners(upper_left_corner, lower_right_corner, size):
''' Points are the outer edges of the UL and LR pixels. Size is rows, columns.
GC projection type is taken from Points. '''
assert upper_left_corner.wkt == lower_right_corner.wkt
geotransform = np.array([upper_left_corner.lon, -(... | [
"def",
"grid_coords_from_corners",
"(",
"upper_left_corner",
",",
"lower_right_corner",
",",
"size",
")",
":",
"assert",
"upper_left_corner",
".",
"wkt",
"==",
"lower_right_corner",
".",
"wkt",
"geotransform",
"=",
"np",
".",
"array",
"(",
"[",
"upper_left_corner",
... | Points are the outer edges of the UL and LR pixels. Size is rows, columns.
GC projection type is taken from Points. | [
"Points",
"are",
"the",
"outer",
"edges",
"of",
"the",
"UL",
"and",
"LR",
"pixels",
".",
"Size",
"is",
"rows",
"columns",
".",
"GC",
"projection",
"type",
"is",
"taken",
"from",
"Points",
"."
] | python | train |
astropy/photutils | photutils/segmentation/properties.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/segmentation/properties.py#L931-L945 | def area(self):
"""
The total unmasked area of the source segment in units of
pixels**2.
Note that the source area may be smaller than its segment area
if a mask is input to `SourceProperties` or `source_properties`,
or if the ``data`` within the segment contains invalid... | [
"def",
"area",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_completely_masked",
":",
"return",
"np",
".",
"nan",
"*",
"u",
".",
"pix",
"**",
"2",
"else",
":",
"return",
"len",
"(",
"self",
".",
"values",
")",
"*",
"u",
".",
"pix",
"**",
"2"
] | The total unmasked area of the source segment in units of
pixels**2.
Note that the source area may be smaller than its segment area
if a mask is input to `SourceProperties` or `source_properties`,
or if the ``data`` within the segment contains invalid values
(e.g. NaN or infs). | [
"The",
"total",
"unmasked",
"area",
"of",
"the",
"source",
"segment",
"in",
"units",
"of",
"pixels",
"**",
"2",
"."
] | python | train |
ValvePython/steam | steam/steamid.py | https://github.com/ValvePython/steam/blob/2de1364c47598410b572114e6129eab8fff71d5b/steam/steamid.py#L145-L171 | def as_steam3(self):
"""
:return: steam3 format (e.g ``[U:1:1234]``)
:rtype: :class:`str`
"""
typechar = str(ETypeChar(self.type))
instance = None
if self.type in (EType.AnonGameServer, EType.Multiseat):
instance = self.instance
elif self.type... | [
"def",
"as_steam3",
"(",
"self",
")",
":",
"typechar",
"=",
"str",
"(",
"ETypeChar",
"(",
"self",
".",
"type",
")",
")",
"instance",
"=",
"None",
"if",
"self",
".",
"type",
"in",
"(",
"EType",
".",
"AnonGameServer",
",",
"EType",
".",
"Multiseat",
")... | :return: steam3 format (e.g ``[U:1:1234]``)
:rtype: :class:`str` | [
":",
"return",
":",
"steam3",
"format",
"(",
"e",
".",
"g",
"[",
"U",
":",
"1",
":",
"1234",
"]",
")",
":",
"rtype",
":",
":",
"class",
":",
"str"
] | python | train |
collectiveacuity/labPack | labpack/storage/aws/s3.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/storage/aws/s3.py#L1873-L1991 | def list(self, prefix='', delimiter='', filter_function=None, max_results=1, previous_key=''):
'''
a method to list keys in the collection
:param prefix: string with prefix value to filter results
:param delimiter: string with value results must not contain (after prefix)
... | [
"def",
"list",
"(",
"self",
",",
"prefix",
"=",
"''",
",",
"delimiter",
"=",
"''",
",",
"filter_function",
"=",
"None",
",",
"max_results",
"=",
"1",
",",
"previous_key",
"=",
"''",
")",
":",
"title",
"=",
"'%s.list'",
"%",
"self",
".",
"__class__",
... | a method to list keys in the collection
:param prefix: string with prefix value to filter results
:param delimiter: string with value results must not contain (after prefix)
:param filter_function: (positional arguments) function used to filter results
:param max_results: integer with m... | [
"a",
"method",
"to",
"list",
"keys",
"in",
"the",
"collection"
] | python | train |
volfpeter/graphscraper | src/graphscraper/base.py | https://github.com/volfpeter/graphscraper/blob/11d407509956a282ee25190ed6491a162fc0fe7f/src/graphscraper/base.py#L330-L387 | def get_node_by_name(self, node_name: str,
can_validate_and_load: bool = False,
external_id: Optional[str] = None) -> Optional[Node]:
"""
Returns the node with the given name if it exists either in the graph
or in its database cache or `None... | [
"def",
"get_node_by_name",
"(",
"self",
",",
"node_name",
":",
"str",
",",
"can_validate_and_load",
":",
"bool",
"=",
"False",
",",
"external_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Optional",
"[",
"Node",
"]",
":",
"node",
":",
... | Returns the node with the given name if it exists either in the graph
or in its database cache or `None` otherwise.
Arguments:
node_name (str): The name of the node to return.
can_validate_and_load (bool): Whether `self._graph.get_authentic_node_name(node_name)`
... | [
"Returns",
"the",
"node",
"with",
"the",
"given",
"name",
"if",
"it",
"exists",
"either",
"in",
"the",
"graph",
"or",
"in",
"its",
"database",
"cache",
"or",
"None",
"otherwise",
".",
"Arguments",
":",
"node_name",
"(",
"str",
")",
":",
"The",
"name",
... | python | train |
BD2KGenomics/protect | src/protect/mutation_calling/somaticsniper.py | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/mutation_calling/somaticsniper.py#L67-L123 | def run_somaticsniper(job, tumor_bam, normal_bam, univ_options, somaticsniper_options, split=True):
"""
Run the SomaticSniper subgraph on the DNA bams. Optionally split the results into
per-chromosome vcfs.
:param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq
:param dict normal_bam: Dict o... | [
"def",
"run_somaticsniper",
"(",
"job",
",",
"tumor_bam",
",",
"normal_bam",
",",
"univ_options",
",",
"somaticsniper_options",
",",
"split",
"=",
"True",
")",
":",
"# Get a list of chromosomes to handle",
"if",
"somaticsniper_options",
"[",
"'chromosomes'",
"]",
":",... | Run the SomaticSniper subgraph on the DNA bams. Optionally split the results into
per-chromosome vcfs.
:param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq
:param dict normal_bam: Dict of bam and bai for normal DNA-Seq
:param dict univ_options: Dict of universal options used by almost all tool... | [
"Run",
"the",
"SomaticSniper",
"subgraph",
"on",
"the",
"DNA",
"bams",
".",
"Optionally",
"split",
"the",
"results",
"into",
"per",
"-",
"chromosome",
"vcfs",
"."
] | python | train |
mlperf/training | reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/ml_perf/reference_implementation.py#L417-L447 | def main(unused_argv):
"""Run the reinforcement learning loop."""
print('Wiping dir %s' % FLAGS.base_dir, flush=True)
shutil.rmtree(FLAGS.base_dir, ignore_errors=True)
dirs = [fsdb.models_dir(), fsdb.selfplay_dir(), fsdb.holdout_dir(),
fsdb.eval_dir(), fsdb.golden_chunk_dir(), fsdb.working_dir()]
f... | [
"def",
"main",
"(",
"unused_argv",
")",
":",
"print",
"(",
"'Wiping dir %s'",
"%",
"FLAGS",
".",
"base_dir",
",",
"flush",
"=",
"True",
")",
"shutil",
".",
"rmtree",
"(",
"FLAGS",
".",
"base_dir",
",",
"ignore_errors",
"=",
"True",
")",
"dirs",
"=",
"[... | Run the reinforcement learning loop. | [
"Run",
"the",
"reinforcement",
"learning",
"loop",
"."
] | python | train |
calmjs/calmjs.parse | src/calmjs/parse/parsers/es5.py | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/parsers/es5.py#L542-L550 | def p_arguments(self, p):
"""arguments : LPAREN RPAREN
| LPAREN argument_list RPAREN
"""
if len(p) == 4:
p[0] = self.asttypes.Arguments(p[2])
else:
p[0] = self.asttypes.Arguments([])
p[0].setpos(p) | [
"def",
"p_arguments",
"(",
"self",
",",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"==",
"4",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Arguments",
"(",
"p",
"[",
"2",
"]",
")",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"se... | arguments : LPAREN RPAREN
| LPAREN argument_list RPAREN | [
"arguments",
":",
"LPAREN",
"RPAREN",
"|",
"LPAREN",
"argument_list",
"RPAREN"
] | python | train |
SeleniumHQ/selenium | py/selenium/webdriver/common/action_chains.py | https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L327-L343 | def send_keys(self, *keys_to_send):
"""
Sends keys to current focused element.
:Args:
- keys_to_send: The keys to send. Modifier keys constants can be found in the
'Keys' class.
"""
typing = keys_to_typing(keys_to_send)
if self._driver.w3c:
... | [
"def",
"send_keys",
"(",
"self",
",",
"*",
"keys_to_send",
")",
":",
"typing",
"=",
"keys_to_typing",
"(",
"keys_to_send",
")",
"if",
"self",
".",
"_driver",
".",
"w3c",
":",
"for",
"key",
"in",
"typing",
":",
"self",
".",
"key_down",
"(",
"key",
")",
... | Sends keys to current focused element.
:Args:
- keys_to_send: The keys to send. Modifier keys constants can be found in the
'Keys' class. | [
"Sends",
"keys",
"to",
"current",
"focused",
"element",
"."
] | python | train |
hyperledger/sawtooth-core | validator/sawtooth_validator/execution/scheduler_parallel.py | https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/validator/sawtooth_validator/execution/scheduler_parallel.py#L107-L121 | def prune(self, address):
'''
Remove all children (and descendants) below ADDRESS.
Arguments:
address (str): the address to be pruned
'''
try:
for step in self._walk_to_address(address):
node = step
except AddressNotInTree:
... | [
"def",
"prune",
"(",
"self",
",",
"address",
")",
":",
"try",
":",
"for",
"step",
"in",
"self",
".",
"_walk_to_address",
"(",
"address",
")",
":",
"node",
"=",
"step",
"except",
"AddressNotInTree",
":",
"return",
"node",
".",
"children",
".",
"clear",
... | Remove all children (and descendants) below ADDRESS.
Arguments:
address (str): the address to be pruned | [
"Remove",
"all",
"children",
"(",
"and",
"descendants",
")",
"below",
"ADDRESS",
"."
] | python | train |
IBMStreams/pypi.streamsx | streamsx/spl/spl.py | https://github.com/IBMStreams/pypi.streamsx/blob/abd67b4757120f6f805787fba390f53e9df9cdd8/streamsx/spl/spl.py#L1082-L1097 | def ignore(wrapped):
"""
Decorator to ignore a Python function.
If a Python callable is decorated with ``@spl.ignore``
then function is ignored by ``spl-python-extract.py``.
Args:
wrapped: Function that will be ignored.
"""
@functools.wraps(wrapped)
def _ignore(*args, **kw... | [
"def",
"ignore",
"(",
"wrapped",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"wrapped",
")",
"def",
"_ignore",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"_ignore",
... | Decorator to ignore a Python function.
If a Python callable is decorated with ``@spl.ignore``
then function is ignored by ``spl-python-extract.py``.
Args:
wrapped: Function that will be ignored. | [
"Decorator",
"to",
"ignore",
"a",
"Python",
"function",
"."
] | python | train |
apache/spark | python/pyspark/sql/functions.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L908-L924 | def date_format(date, format):
"""
Converts a date/timestamp/string to a value of string in the format specified by the date
format given by the second argument.
A pattern could be for instance `dd.MM.yyyy` and could return a string like '18.03.1993'. All
pattern letters of the Java class `java.tim... | [
"def",
"date_format",
"(",
"date",
",",
"format",
")",
":",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"return",
"Column",
"(",
"sc",
".",
"_jvm",
".",
"functions",
".",
"date_format",
"(",
"_to_java_column",
"(",
"date",
")",
",",
"format",
... | Converts a date/timestamp/string to a value of string in the format specified by the date
format given by the second argument.
A pattern could be for instance `dd.MM.yyyy` and could return a string like '18.03.1993'. All
pattern letters of the Java class `java.time.format.DateTimeFormatter` can be used.
... | [
"Converts",
"a",
"date",
"/",
"timestamp",
"/",
"string",
"to",
"a",
"value",
"of",
"string",
"in",
"the",
"format",
"specified",
"by",
"the",
"date",
"format",
"given",
"by",
"the",
"second",
"argument",
"."
] | python | train |
idlesign/django-siteprefs | siteprefs/toolbox.py | https://github.com/idlesign/django-siteprefs/blob/3d6bf5e64220fe921468a36fce68e15d7947cf92/siteprefs/toolbox.py#L171-L180 | def patch_locals(depth=2):
"""Temporarily (see unpatch_locals()) replaces all module variables
considered preferences with PatchedLocal objects, so that every
variable has different hash returned by id().
"""
for name, locals_dict in traverse_local_prefs(depth):
locals_dict[name] = PatchedL... | [
"def",
"patch_locals",
"(",
"depth",
"=",
"2",
")",
":",
"for",
"name",
",",
"locals_dict",
"in",
"traverse_local_prefs",
"(",
"depth",
")",
":",
"locals_dict",
"[",
"name",
"]",
"=",
"PatchedLocal",
"(",
"name",
",",
"locals_dict",
"[",
"name",
"]",
")"... | Temporarily (see unpatch_locals()) replaces all module variables
considered preferences with PatchedLocal objects, so that every
variable has different hash returned by id(). | [
"Temporarily",
"(",
"see",
"unpatch_locals",
"()",
")",
"replaces",
"all",
"module",
"variables",
"considered",
"preferences",
"with",
"PatchedLocal",
"objects",
"so",
"that",
"every",
"variable",
"has",
"different",
"hash",
"returned",
"by",
"id",
"()",
"."
] | python | valid |
idlesign/srptools | srptools/context.py | https://github.com/idlesign/srptools/blob/eb08a27137d3216e41d63bbeafbac79f43881a6a/srptools/context.py#L213-L232 | def get_common_session_key_proof(self, session_key, salt, server_public, client_public):
"""M = H(H(N) XOR H(g) | H(U) | s | A | B | K)
:param bytes session_key:
:param int salt:
:param int server_public:
:param int client_public:
:rtype: bytes
"""
h = se... | [
"def",
"get_common_session_key_proof",
"(",
"self",
",",
"session_key",
",",
"salt",
",",
"server_public",
",",
"client_public",
")",
":",
"h",
"=",
"self",
".",
"hash",
"prove",
"=",
"h",
"(",
"h",
"(",
"self",
".",
"_prime",
")",
"^",
"h",
"(",
"self... | M = H(H(N) XOR H(g) | H(U) | s | A | B | K)
:param bytes session_key:
:param int salt:
:param int server_public:
:param int client_public:
:rtype: bytes | [
"M",
"=",
"H",
"(",
"H",
"(",
"N",
")",
"XOR",
"H",
"(",
"g",
")",
"|",
"H",
"(",
"U",
")",
"|",
"s",
"|",
"A",
"|",
"B",
"|",
"K",
")"
] | python | train |
ejeschke/ginga | ginga/ImageView.py | https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/ImageView.py#L2488-L2503 | def panset_xy(self, data_x, data_y, no_reset=False):
"""Similar to :meth:`set_pan`, except that input pan positions
are always in data space.
"""
pan_coord = self.t_['pan_coord']
# To center on the pixel
if pan_coord == 'wcs':
image = self.get_image()
... | [
"def",
"panset_xy",
"(",
"self",
",",
"data_x",
",",
"data_y",
",",
"no_reset",
"=",
"False",
")",
":",
"pan_coord",
"=",
"self",
".",
"t_",
"[",
"'pan_coord'",
"]",
"# To center on the pixel",
"if",
"pan_coord",
"==",
"'wcs'",
":",
"image",
"=",
"self",
... | Similar to :meth:`set_pan`, except that input pan positions
are always in data space. | [
"Similar",
"to",
":",
"meth",
":",
"set_pan",
"except",
"that",
"input",
"pan",
"positions",
"are",
"always",
"in",
"data",
"space",
"."
] | python | train |
PyCQA/astroid | astroid/node_classes.py | https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/node_classes.py#L333-L364 | def infer(self, context=None, **kwargs):
"""Get a generator of the inferred values.
This is the main entry point to the inference system.
.. seealso:: :ref:`inference`
If the instance has some explicit inference function set, it will be
called instead of the default interface.... | [
"def",
"infer",
"(",
"self",
",",
"context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"context",
"is",
"not",
"None",
":",
"context",
"=",
"context",
".",
"extra_context",
".",
"get",
"(",
"self",
",",
"context",
")",
"if",
"self",
"."... | Get a generator of the inferred values.
This is the main entry point to the inference system.
.. seealso:: :ref:`inference`
If the instance has some explicit inference function set, it will be
called instead of the default interface.
:returns: The inferred values.
:rt... | [
"Get",
"a",
"generator",
"of",
"the",
"inferred",
"values",
"."
] | python | train |
allenai/allennlp | allennlp/state_machines/trainers/expected_risk_minimization.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/trainers/expected_risk_minimization.py#L151-L166 | def _get_best_final_states(self, finished_states: List[StateType]) -> Dict[int, List[StateType]]:
"""
Returns the best finished states for each batch instance based on model scores. We return
at most ``self._max_num_decoded_sequences`` number of sequences per instance.
"""
batch_... | [
"def",
"_get_best_final_states",
"(",
"self",
",",
"finished_states",
":",
"List",
"[",
"StateType",
"]",
")",
"->",
"Dict",
"[",
"int",
",",
"List",
"[",
"StateType",
"]",
"]",
":",
"batch_states",
":",
"Dict",
"[",
"int",
",",
"List",
"[",
"StateType",... | Returns the best finished states for each batch instance based on model scores. We return
at most ``self._max_num_decoded_sequences`` number of sequences per instance. | [
"Returns",
"the",
"best",
"finished",
"states",
"for",
"each",
"batch",
"instance",
"based",
"on",
"model",
"scores",
".",
"We",
"return",
"at",
"most",
"self",
".",
"_max_num_decoded_sequences",
"number",
"of",
"sequences",
"per",
"instance",
"."
] | python | train |
liminspace/dju-common | dju_common/validators.py | https://github.com/liminspace/dju-common/blob/c68860bb84d454a35e66275841c20f38375c2135/dju_common/validators.py#L6-L14 | def validate_email_domain(email):
""" Validates email domain by blacklist. """
try:
domain = email.split('@', 1)[1].lower().strip()
except IndexError:
return
if domain in dju_settings.DJU_EMAIL_DOMAIN_BLACK_LIST:
raise ValidationError(_(u'Email with domain "%(domain)s" is disallo... | [
"def",
"validate_email_domain",
"(",
"email",
")",
":",
"try",
":",
"domain",
"=",
"email",
".",
"split",
"(",
"'@'",
",",
"1",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"except",
"IndexError",
":",
"return",
"if",
"domain... | Validates email domain by blacklist. | [
"Validates",
"email",
"domain",
"by",
"blacklist",
"."
] | python | train |
mcs07/ChemDataExtractor | chemdataextractor/scrape/scraper.py | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/scraper.py#L77-L90 | def run(self, url):
"""Request URL, scrape response and return an EntityList."""
url = self.process_url(url)
if not url:
return
response = self.make_request(self.http, url)
selector = self.process_response(response)
entities = []
for root in self.get_r... | [
"def",
"run",
"(",
"self",
",",
"url",
")",
":",
"url",
"=",
"self",
".",
"process_url",
"(",
"url",
")",
"if",
"not",
"url",
":",
"return",
"response",
"=",
"self",
".",
"make_request",
"(",
"self",
".",
"http",
",",
"url",
")",
"selector",
"=",
... | Request URL, scrape response and return an EntityList. | [
"Request",
"URL",
"scrape",
"response",
"and",
"return",
"an",
"EntityList",
"."
] | python | train |
kevin1024/vcrpy | vcr/stubs/__init__.py | https://github.com/kevin1024/vcrpy/blob/114fcd29b43c55896aaa6a6613bc7766f2707c8b/vcr/stubs/__init__.py#L137-L148 | def _uri(self, url):
"""Returns request absolute URI"""
if url and not url.startswith('/'):
# Then this must be a proxy request.
return url
uri = "{0}://{1}{2}{3}".format(
self._protocol,
self.real_connection.host,
self._port_postfix(),... | [
"def",
"_uri",
"(",
"self",
",",
"url",
")",
":",
"if",
"url",
"and",
"not",
"url",
".",
"startswith",
"(",
"'/'",
")",
":",
"# Then this must be a proxy request.",
"return",
"url",
"uri",
"=",
"\"{0}://{1}{2}{3}\"",
".",
"format",
"(",
"self",
".",
"_prot... | Returns request absolute URI | [
"Returns",
"request",
"absolute",
"URI"
] | python | train |
CamDavidsonPilon/lifelines | lifelines/fitters/__init__.py | https://github.com/CamDavidsonPilon/lifelines/blob/bdf6be6f1d10eea4c46365ee0ee6a47d8c30edf8/lifelines/fitters/__init__.py#L986-L1003 | def hazard_at_times(self, times, label=None):
"""
Return a Pandas series of the predicted hazard at specific times.
Parameters
-----------
times: iterable or float
values to return the hazard at.
label: string, optional
Rename the series returned. Use... | [
"def",
"hazard_at_times",
"(",
"self",
",",
"times",
",",
"label",
"=",
"None",
")",
":",
"label",
"=",
"coalesce",
"(",
"label",
",",
"self",
".",
"_label",
")",
"return",
"pd",
".",
"Series",
"(",
"self",
".",
"_hazard",
"(",
"self",
".",
"_fitted_... | Return a Pandas series of the predicted hazard at specific times.
Parameters
-----------
times: iterable or float
values to return the hazard at.
label: string, optional
Rename the series returned. Useful for plotting.
Returns
--------
pd.Ser... | [
"Return",
"a",
"Pandas",
"series",
"of",
"the",
"predicted",
"hazard",
"at",
"specific",
"times",
"."
] | python | train |
atztogo/phonopy | phonopy/interface/qe.py | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/interface/qe.py#L457-L473 | def _parse_q2r(self, f):
"""Parse q2r output file
The format of q2r output is described at the mailing list below:
http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html
http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html
http://www.democritos.it/p... | [
"def",
"_parse_q2r",
"(",
"self",
",",
"f",
")",
":",
"natom",
",",
"dim",
",",
"epsilon",
",",
"borns",
"=",
"self",
".",
"_parse_parameters",
"(",
"f",
")",
"fc_dct",
"=",
"{",
"'fc'",
":",
"self",
".",
"_parse_fc",
"(",
"f",
",",
"natom",
",",
... | Parse q2r output file
The format of q2r output is described at the mailing list below:
http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html
http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html
http://www.democritos.it/pipermail/pw_forum/2009-August/013613... | [
"Parse",
"q2r",
"output",
"file"
] | python | train |
ask/carrot | carrot/messaging.py | https://github.com/ask/carrot/blob/5889a25cd2e274642071c9bba39772f4b3e3d9da/carrot/messaging.py#L914-L926 | def _receive_callback(self, raw_message):
"""Internal method used when a message is received in consume mode."""
message = self.backend.message_to_python(raw_message)
if self.auto_ack and not message.acknowledged:
message.ack()
try:
decoded = message.decode()
... | [
"def",
"_receive_callback",
"(",
"self",
",",
"raw_message",
")",
":",
"message",
"=",
"self",
".",
"backend",
".",
"message_to_python",
"(",
"raw_message",
")",
"if",
"self",
".",
"auto_ack",
"and",
"not",
"message",
".",
"acknowledged",
":",
"message",
"."... | Internal method used when a message is received in consume mode. | [
"Internal",
"method",
"used",
"when",
"a",
"message",
"is",
"received",
"in",
"consume",
"mode",
"."
] | python | train |
GreenBuildingRegistry/yaml-config | yamlconf/config.py | https://github.com/GreenBuildingRegistry/yaml-config/blob/3d4bf4cadd07d4c3b71674077bd7cf16efb6ea10/yamlconf/config.py#L142-L147 | def keys(self, section=None):
"""Provide dict like keys method"""
if not section and self.section:
section = self.section
config = self.config.get(section, {}) if section else self.config
return config.keys() | [
"def",
"keys",
"(",
"self",
",",
"section",
"=",
"None",
")",
":",
"if",
"not",
"section",
"and",
"self",
".",
"section",
":",
"section",
"=",
"self",
".",
"section",
"config",
"=",
"self",
".",
"config",
".",
"get",
"(",
"section",
",",
"{",
"}",
... | Provide dict like keys method | [
"Provide",
"dict",
"like",
"keys",
"method"
] | python | train |
webrecorder/warcio | warcio/archiveiterator.py | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/archiveiterator.py#L231-L247 | def _next_record(self, next_line):
""" Use loader to parse the record from the reader stream
Supporting warc and arc records
"""
record = self.loader.parse_record_stream(self.reader,
next_line,
... | [
"def",
"_next_record",
"(",
"self",
",",
"next_line",
")",
":",
"record",
"=",
"self",
".",
"loader",
".",
"parse_record_stream",
"(",
"self",
".",
"reader",
",",
"next_line",
",",
"self",
".",
"known_format",
",",
"self",
".",
"no_record_parse",
",",
"sel... | Use loader to parse the record from the reader stream
Supporting warc and arc records | [
"Use",
"loader",
"to",
"parse",
"the",
"record",
"from",
"the",
"reader",
"stream",
"Supporting",
"warc",
"and",
"arc",
"records"
] | python | train |
wandb/client | wandb/vendor/prompt_toolkit/clipboard/base.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/clipboard/base.py#L46-L51 | def set_text(self, text): # Not abstract.
"""
Shortcut for setting plain text on clipboard.
"""
assert isinstance(text, six.string_types)
self.set_data(ClipboardData(text)) | [
"def",
"set_text",
"(",
"self",
",",
"text",
")",
":",
"# Not abstract.",
"assert",
"isinstance",
"(",
"text",
",",
"six",
".",
"string_types",
")",
"self",
".",
"set_data",
"(",
"ClipboardData",
"(",
"text",
")",
")"
] | Shortcut for setting plain text on clipboard. | [
"Shortcut",
"for",
"setting",
"plain",
"text",
"on",
"clipboard",
"."
] | python | train |
costastf/locationsharinglib | _CI/library/patch.py | https://github.com/costastf/locationsharinglib/blob/dcd74b0cdb59b951345df84987238763e50ef282/_CI/library/patch.py#L143-L156 | def xstrip(filename):
""" Make relative path out of absolute by stripping
prefixes used on Linux, OS X and Windows.
This function is critical for security.
"""
while xisabs(filename):
# strip windows drive with all slashes
if re.match(b'\\w:[\\\\/]', filename):
filename = re.sub(b'^\\w+... | [
"def",
"xstrip",
"(",
"filename",
")",
":",
"while",
"xisabs",
"(",
"filename",
")",
":",
"# strip windows drive with all slashes",
"if",
"re",
".",
"match",
"(",
"b'\\\\w:[\\\\\\\\/]'",
",",
"filename",
")",
":",
"filename",
"=",
"re",
".",
"sub",
"(",
"b'^... | Make relative path out of absolute by stripping
prefixes used on Linux, OS X and Windows.
This function is critical for security. | [
"Make",
"relative",
"path",
"out",
"of",
"absolute",
"by",
"stripping",
"prefixes",
"used",
"on",
"Linux",
"OS",
"X",
"and",
"Windows",
"."
] | python | train |
sdispater/orator | orator/orm/relations/has_many.py | https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/has_many.py#L14-L26 | def init_relation(self, models, relation):
"""
Initialize the relation on a set of models.
:type models: list
:type relation: str
"""
for model in models:
model.set_relation(
relation, Result(self._related.new_collection(), self, model)
... | [
"def",
"init_relation",
"(",
"self",
",",
"models",
",",
"relation",
")",
":",
"for",
"model",
"in",
"models",
":",
"model",
".",
"set_relation",
"(",
"relation",
",",
"Result",
"(",
"self",
".",
"_related",
".",
"new_collection",
"(",
")",
",",
"self",
... | Initialize the relation on a set of models.
:type models: list
:type relation: str | [
"Initialize",
"the",
"relation",
"on",
"a",
"set",
"of",
"models",
"."
] | python | train |
user-cont/conu | conu/backend/podman/backend.py | https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/backend/podman/backend.py#L139-L155 | def list_images(self):
"""
List all available podman images.
:return: collection of instances of :class:`conu.PodmanImage`
"""
images = []
for image in self._list_all_podman_images():
try:
i_name, tag = parse_reference(image["names"][0])
... | [
"def",
"list_images",
"(",
"self",
")",
":",
"images",
"=",
"[",
"]",
"for",
"image",
"in",
"self",
".",
"_list_all_podman_images",
"(",
")",
":",
"try",
":",
"i_name",
",",
"tag",
"=",
"parse_reference",
"(",
"image",
"[",
"\"names\"",
"]",
"[",
"0",
... | List all available podman images.
:return: collection of instances of :class:`conu.PodmanImage` | [
"List",
"all",
"available",
"podman",
"images",
"."
] | python | train |
Unidata/MetPy | metpy/calc/basic.py | https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/calc/basic.py#L431-L468 | def geopotential_to_height(geopot):
r"""Compute height from a given geopotential.
Parameters
----------
geopotential : `pint.Quantity`
Geopotential (array_like)
Returns
-------
`pint.Quantity`
The corresponding height value(s)
Examples
--------
>>> from metpy.c... | [
"def",
"geopotential_to_height",
"(",
"geopot",
")",
":",
"# Calculate geopotential",
"height",
"=",
"(",
"(",
"(",
"1",
"/",
"mpconsts",
".",
"Re",
")",
"-",
"(",
"geopot",
"/",
"(",
"mpconsts",
".",
"G",
"*",
"mpconsts",
".",
"me",
")",
")",
")",
"... | r"""Compute height from a given geopotential.
Parameters
----------
geopotential : `pint.Quantity`
Geopotential (array_like)
Returns
-------
`pint.Quantity`
The corresponding height value(s)
Examples
--------
>>> from metpy.constants import g, G, me, Re
>>> imp... | [
"r",
"Compute",
"height",
"from",
"a",
"given",
"geopotential",
"."
] | python | train |
SwoopSearch/pyaddress | address/address.py | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L250-L279 | def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
... | [
"def",
"preprocess_address",
"(",
"self",
",",
"address",
")",
":",
"# Run some basic cleaning",
"address",
"=",
"address",
".",
"replace",
"(",
"\"# \"",
",",
"\"#\"",
")",
"address",
"=",
"address",
".",
"replace",
"(",
"\" & \"",
",",
"\"&\"",
")",
"# Cle... | Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address. | [
"Takes",
"a",
"basic",
"address",
"and",
"attempts",
"to",
"clean",
"it",
"up",
"extract",
"reasonably",
"assured",
"bits",
"that",
"may",
"throw",
"off",
"the",
"rest",
"of",
"the",
"parsing",
"and",
"return",
"the",
"cleaned",
"address",
"."
] | python | train |
timothyb0912/pylogit | pylogit/base_multinomial_cm_v2.py | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/base_multinomial_cm_v2.py#L386-L407 | def check_num_rows_of_parameter_array(param_array, correct_num_rows, title):
"""
Ensures that `param_array.shape[0]` has the correct magnitude. Raises a
helpful ValueError if otherwise.
Parameters
----------
param_array : ndarray.
correct_num_rows : int.
The int that `param_array.sh... | [
"def",
"check_num_rows_of_parameter_array",
"(",
"param_array",
",",
"correct_num_rows",
",",
"title",
")",
":",
"if",
"param_array",
".",
"shape",
"[",
"0",
"]",
"!=",
"correct_num_rows",
":",
"msg",
"=",
"\"{}.shape[0] should equal {}, but it does not\"",
"raise",
"... | Ensures that `param_array.shape[0]` has the correct magnitude. Raises a
helpful ValueError if otherwise.
Parameters
----------
param_array : ndarray.
correct_num_rows : int.
The int that `param_array.shape[0]` should equal.
title : str.
The 'name' of the param_array whose shape ... | [
"Ensures",
"that",
"param_array",
".",
"shape",
"[",
"0",
"]",
"has",
"the",
"correct",
"magnitude",
".",
"Raises",
"a",
"helpful",
"ValueError",
"if",
"otherwise",
"."
] | python | train |
facebook/watchman | python/pywatchman/__init__.py | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L397-L434 | def _get_overlapped_result_ex_impl(pipe, olap, nbytes, millis, alertable):
""" Windows 7 and earlier does not support GetOverlappedResultEx. The
alternative is to use GetOverlappedResult and wait for read or write
operation to complete. This is done be using CreateEvent and
WaitForSingleObjectEx. Create... | [
"def",
"_get_overlapped_result_ex_impl",
"(",
"pipe",
",",
"olap",
",",
"nbytes",
",",
"millis",
",",
"alertable",
")",
":",
"log",
"(",
"\"Preparing to wait for maximum %dms\"",
",",
"millis",
")",
"if",
"millis",
"!=",
"0",
":",
"waitReturnCode",
"=",
"WaitFor... | Windows 7 and earlier does not support GetOverlappedResultEx. The
alternative is to use GetOverlappedResult and wait for read or write
operation to complete. This is done be using CreateEvent and
WaitForSingleObjectEx. CreateEvent, WaitForSingleObjectEx
and GetOverlappedResult are all part of Windows AP... | [
"Windows",
"7",
"and",
"earlier",
"does",
"not",
"support",
"GetOverlappedResultEx",
".",
"The",
"alternative",
"is",
"to",
"use",
"GetOverlappedResult",
"and",
"wait",
"for",
"read",
"or",
"write",
"operation",
"to",
"complete",
".",
"This",
"is",
"done",
"be... | python | train |
couchbase/couchbase-python-client | couchbase/bucket.py | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1159-L1167 | def replace_multi(self, keys, ttl=0, format=None,
persist_to=0, replicate_to=0):
"""Replace multiple keys. Multi variant of :meth:`replace`
.. seealso:: :meth:`replace`, :meth:`upsert_multi`, :meth:`upsert`
"""
return _Base.replace_multi(self, keys, ttl=ttl, format... | [
"def",
"replace_multi",
"(",
"self",
",",
"keys",
",",
"ttl",
"=",
"0",
",",
"format",
"=",
"None",
",",
"persist_to",
"=",
"0",
",",
"replicate_to",
"=",
"0",
")",
":",
"return",
"_Base",
".",
"replace_multi",
"(",
"self",
",",
"keys",
",",
"ttl",
... | Replace multiple keys. Multi variant of :meth:`replace`
.. seealso:: :meth:`replace`, :meth:`upsert_multi`, :meth:`upsert` | [
"Replace",
"multiple",
"keys",
".",
"Multi",
"variant",
"of",
":",
"meth",
":",
"replace"
] | python | train |
pgxcentre/geneparse | geneparse/index/impute2.py | https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/index/impute2.py#L59-L92 | def generate_index(fn, cols=None, names=None, sep=" "):
"""Build a index for the given file.
Args:
fn (str): the name of the file.
cols (list): a list containing column to keep (as int).
names (list): the name corresponding to the column to keep (as str).
sep (str): the field se... | [
"def",
"generate_index",
"(",
"fn",
",",
"cols",
"=",
"None",
",",
"names",
"=",
"None",
",",
"sep",
"=",
"\" \"",
")",
":",
"# Some assertions",
"assert",
"cols",
"is",
"not",
"None",
",",
"\"'cols' was not set\"",
"assert",
"names",
"is",
"not",
"None",
... | Build a index for the given file.
Args:
fn (str): the name of the file.
cols (list): a list containing column to keep (as int).
names (list): the name corresponding to the column to keep (as str).
sep (str): the field separator.
Returns:
pandas.DataFrame: the index. | [
"Build",
"a",
"index",
"for",
"the",
"given",
"file",
"."
] | python | train |
tcalmant/ipopo | pelix/ipopo/constants.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/constants.py#L245-L270 | def use_waiting_list(bundle_context):
# type: (BundleContext) -> Any
"""
Utility context to use the iPOPO waiting list safely in a "with" block.
It looks after the the iPOPO waiting list service and releases its
reference when exiting the context.
:param bundle_context: The calling bundle conte... | [
"def",
"use_waiting_list",
"(",
"bundle_context",
")",
":",
"# type: (BundleContext) -> Any",
"# Get the service and its reference",
"ref",
"=",
"bundle_context",
".",
"get_service_reference",
"(",
"SERVICE_IPOPO_WAITING_LIST",
")",
"if",
"ref",
"is",
"None",
":",
"raise",
... | Utility context to use the iPOPO waiting list safely in a "with" block.
It looks after the the iPOPO waiting list service and releases its
reference when exiting the context.
:param bundle_context: The calling bundle context
:return: The iPOPO waiting list service
:raise BundleException: Service no... | [
"Utility",
"context",
"to",
"use",
"the",
"iPOPO",
"waiting",
"list",
"safely",
"in",
"a",
"with",
"block",
".",
"It",
"looks",
"after",
"the",
"the",
"iPOPO",
"waiting",
"list",
"service",
"and",
"releases",
"its",
"reference",
"when",
"exiting",
"the",
"... | python | train |
duniter/duniter-python-api | duniterpy/helpers.py | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/helpers.py#L31-L42 | def xor_bytes(b1: bytes, b2: bytes) -> bytearray:
"""
Apply XOR operation on two bytes arguments
:param b1: First bytes argument
:param b2: Second bytes argument
:rtype bytearray:
"""
result = bytearray()
for i1, i2 in zip(b1, b2):
result.append(i1 ^ i2)
return result | [
"def",
"xor_bytes",
"(",
"b1",
":",
"bytes",
",",
"b2",
":",
"bytes",
")",
"->",
"bytearray",
":",
"result",
"=",
"bytearray",
"(",
")",
"for",
"i1",
",",
"i2",
"in",
"zip",
"(",
"b1",
",",
"b2",
")",
":",
"result",
".",
"append",
"(",
"i1",
"^... | Apply XOR operation on two bytes arguments
:param b1: First bytes argument
:param b2: Second bytes argument
:rtype bytearray: | [
"Apply",
"XOR",
"operation",
"on",
"two",
"bytes",
"arguments"
] | python | train |
spyder-ide/spyder-kernels | spyder_kernels/utils/dochelpers.py | https://github.com/spyder-ide/spyder-kernels/blob/2c5b36cdb797b8aba77bc406ca96f5e079c4aaca/spyder_kernels/utils/dochelpers.py#L231-L267 | def getargs(obj):
"""Get the names and default values of a function's arguments"""
if inspect.isfunction(obj) or inspect.isbuiltin(obj):
func_obj = obj
elif inspect.ismethod(obj):
func_obj = get_meth_func(obj)
elif inspect.isclass(obj) and hasattr(obj, '__init__'):
func_obj = get... | [
"def",
"getargs",
"(",
"obj",
")",
":",
"if",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
"or",
"inspect",
".",
"isbuiltin",
"(",
"obj",
")",
":",
"func_obj",
"=",
"obj",
"elif",
"inspect",
".",
"ismethod",
"(",
"obj",
")",
":",
"func_obj",
"=",
... | Get the names and default values of a function's arguments | [
"Get",
"the",
"names",
"and",
"default",
"values",
"of",
"a",
"function",
"s",
"arguments"
] | python | train |
awslabs/sockeye | sockeye/utils.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/utils.py#L909-L916 | def metric_value_is_better(new: float, old: float, metric: str) -> bool:
"""
Returns true if new value is strictly better than old for given metric.
"""
if C.METRIC_MAXIMIZE[metric]:
return new > old
else:
return new < old | [
"def",
"metric_value_is_better",
"(",
"new",
":",
"float",
",",
"old",
":",
"float",
",",
"metric",
":",
"str",
")",
"->",
"bool",
":",
"if",
"C",
".",
"METRIC_MAXIMIZE",
"[",
"metric",
"]",
":",
"return",
"new",
">",
"old",
"else",
":",
"return",
"n... | Returns true if new value is strictly better than old for given metric. | [
"Returns",
"true",
"if",
"new",
"value",
"is",
"strictly",
"better",
"than",
"old",
"for",
"given",
"metric",
"."
] | python | train |
ruipgil/TrackToTrip | tracktotrip/track.py | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/track.py#L99-L115 | def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False):
""" In-place simplification of segments
Args:
max_dist_error (float): Min distance error, in meters
max_speed_error (float): Min speed error, in km/h
topology_only: Boolean, optional. True... | [
"def",
"simplify",
"(",
"self",
",",
"eps",
",",
"max_dist_error",
",",
"max_speed_error",
",",
"topology_only",
"=",
"False",
")",
":",
"for",
"segment",
"in",
"self",
".",
"segments",
":",
"segment",
".",
"simplify",
"(",
"eps",
",",
"max_dist_error",
",... | In-place simplification of segments
Args:
max_dist_error (float): Min distance error, in meters
max_speed_error (float): Min speed error, in km/h
topology_only: Boolean, optional. True to keep
the topology, neglecting velocity and time
accurac... | [
"In",
"-",
"place",
"simplification",
"of",
"segments"
] | python | train |
johnwmillr/LyricsGenius | lyricsgenius/api.py | https://github.com/johnwmillr/LyricsGenius/blob/e36482f7c42235037f3b9b7013edcd54141124e3/lyricsgenius/api.py#L336-L381 | def save_artists(self, artists, filename="artist_lyrics", overwrite=False):
"""Save lyrics from multiple Artist objects as JSON object
:param artists: List of Artist objects to save lyrics from
:param filename: Name of output file (json)
:param overwrite: Overwrites preexisting file if T... | [
"def",
"save_artists",
"(",
"self",
",",
"artists",
",",
"filename",
"=",
"\"artist_lyrics\"",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"artists",
",",
"Artist",
")",
":",
"artists",
"=",
"[",
"artists",
"]",
"# Create a temporary d... | Save lyrics from multiple Artist objects as JSON object
:param artists: List of Artist objects to save lyrics from
:param filename: Name of output file (json)
:param overwrite: Overwrites preexisting file if True | [
"Save",
"lyrics",
"from",
"multiple",
"Artist",
"objects",
"as",
"JSON",
"object",
":",
"param",
"artists",
":",
"List",
"of",
"Artist",
"objects",
"to",
"save",
"lyrics",
"from",
":",
"param",
"filename",
":",
"Name",
"of",
"output",
"file",
"(",
"json",
... | python | train |
pricingassistant/mongokat | mongokat/collection.py | https://github.com/pricingassistant/mongokat/blob/61eaf4bc1c4cc359c6f9592ec97b9a04d9561411/mongokat/collection.py#L225-L240 | def find_by_ids(self, _ids, projection=None, **kwargs):
"""
Does a big _id:$in query on any iterator
"""
id_list = [ObjectId(_id) for _id in _ids]
if len(_ids) == 0:
return [] # FIXME : this should be an empty cursor !
# Optimized path when only fetchi... | [
"def",
"find_by_ids",
"(",
"self",
",",
"_ids",
",",
"projection",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"id_list",
"=",
"[",
"ObjectId",
"(",
"_id",
")",
"for",
"_id",
"in",
"_ids",
"]",
"if",
"len",
"(",
"_ids",
")",
"==",
"0",
":",
... | Does a big _id:$in query on any iterator | [
"Does",
"a",
"big",
"_id",
":",
"$in",
"query",
"on",
"any",
"iterator"
] | python | train |
rapidpro/expressions | python/temba_expressions/functions/custom.py | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/custom.py#L10-L26 | def field(ctx, text, index, delimiter=' '):
"""
Reference a field in string separated by a delimiter
"""
splits = text.split(delimiter)
# remove our delimiters and whitespace
splits = [f for f in splits if f != delimiter and len(f.strip()) > 0]
index = conversions.to_integer(index, ctx)
... | [
"def",
"field",
"(",
"ctx",
",",
"text",
",",
"index",
",",
"delimiter",
"=",
"' '",
")",
":",
"splits",
"=",
"text",
".",
"split",
"(",
"delimiter",
")",
"# remove our delimiters and whitespace",
"splits",
"=",
"[",
"f",
"for",
"f",
"in",
"splits",
"if"... | Reference a field in string separated by a delimiter | [
"Reference",
"a",
"field",
"in",
"string",
"separated",
"by",
"a",
"delimiter"
] | python | train |
iotile/coretools | iotileemulate/iotile/emulate/utilities/format_rpc.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/utilities/format_rpc.py#L6-L32 | def format_rpc(data):
"""Format an RPC call and response.
Args:
data (tuple): A tuple containing the address, rpc_id, argument and
response payloads and any error code.
Returns:
str: The formated RPC string.
"""
address, rpc_id, args, resp, _status = data
name = r... | [
"def",
"format_rpc",
"(",
"data",
")",
":",
"address",
",",
"rpc_id",
",",
"args",
",",
"resp",
",",
"_status",
"=",
"data",
"name",
"=",
"rpc_name",
"(",
"rpc_id",
")",
"if",
"isinstance",
"(",
"args",
",",
"(",
"bytes",
",",
"bytearray",
")",
")",
... | Format an RPC call and response.
Args:
data (tuple): A tuple containing the address, rpc_id, argument and
response payloads and any error code.
Returns:
str: The formated RPC string. | [
"Format",
"an",
"RPC",
"call",
"and",
"response",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/nsx.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/nsx.py#L69-L96 | def set_nsxcontroller_ip(self, **kwargs):
"""
Set nsx-controller IP
Args:
IP (str): IPV4 address.
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
... | [
"def",
"set_nsxcontroller_ip",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
")",
"ip_addr",
"=",
"str",
"(",
"(",
"kwargs",
".",
"pop",
"(",
"'ip_addr'",
",",
"None",
")",
")",
")",
"nsxipaddress",... | Set nsx-controller IP
Args:
IP (str): IPV4 address.
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None | [
"Set",
"nsx",
"-",
"controller",
"IP"
] | python | train |
manns/pyspread | pyspread/src/gui/_main_window.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_main_window.py#L614-L631 | def OnNewGpgKey(self, event):
"""New GPG key event handler.
Launches GPG choice and creation dialog
"""
if gnupg is None:
return
if genkey is None:
# gnupg is not present
self.interfaces.display_warning(
_("Python gnupg not ... | [
"def",
"OnNewGpgKey",
"(",
"self",
",",
"event",
")",
":",
"if",
"gnupg",
"is",
"None",
":",
"return",
"if",
"genkey",
"is",
"None",
":",
"# gnupg is not present",
"self",
".",
"interfaces",
".",
"display_warning",
"(",
"_",
"(",
"\"Python gnupg not found. No ... | New GPG key event handler.
Launches GPG choice and creation dialog | [
"New",
"GPG",
"key",
"event",
"handler",
"."
] | python | train |
iotile/coretools | iotilecore/iotile/core/utilities/workqueue_thread.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/workqueue_thread.py#L300-L314 | def stop(self, timeout=None, force=False):
"""Stop the worker thread and synchronously wait for it to finish.
Args:
timeout (float): The maximum time to wait for the thread to stop
before raising a TimeoutExpiredError. If force is True, TimeoutExpiredError
i... | [
"def",
"stop",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"self",
".",
"signal_stop",
"(",
")",
"self",
".",
"wait_stopped",
"(",
"timeout",
",",
"force",
")"
] | Stop the worker thread and synchronously wait for it to finish.
Args:
timeout (float): The maximum time to wait for the thread to stop
before raising a TimeoutExpiredError. If force is True, TimeoutExpiredError
is not raised and the thread is just marked as a daemon... | [
"Stop",
"the",
"worker",
"thread",
"and",
"synchronously",
"wait",
"for",
"it",
"to",
"finish",
"."
] | python | train |
arista-eosplus/pyeapi | pyeapi/client.py | https://github.com/arista-eosplus/pyeapi/blob/96a74faef1fe3bd79c4e900aed29c9956a0587d6/pyeapi/client.py#L815-L842 | def connect_to(name):
"""Creates a node instance based on an entry from the config
This function will retrieve the settings for the specified connection
from the config and return a Node instance. The configuration must
be loaded prior to calling this function.
Args:
name (str): The name ... | [
"def",
"connect_to",
"(",
"name",
")",
":",
"kwargs",
"=",
"config_for",
"(",
"name",
")",
"if",
"not",
"kwargs",
":",
"raise",
"AttributeError",
"(",
"'connection profile not found in config'",
")",
"node",
"=",
"connect",
"(",
"return_node",
"=",
"True",
","... | Creates a node instance based on an entry from the config
This function will retrieve the settings for the specified connection
from the config and return a Node instance. The configuration must
be loaded prior to calling this function.
Args:
name (str): The name of the connection to load fro... | [
"Creates",
"a",
"node",
"instance",
"based",
"on",
"an",
"entry",
"from",
"the",
"config"
] | python | train |
googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/transaction.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/transaction.py#L229-L264 | def _pre_commit(self, transaction, *args, **kwargs):
"""Begin transaction and call the wrapped callable.
If the callable raises an exception, the transaction will be rolled
back. If not, the transaction will be "ready" for ``Commit`` (i.e.
it will have staged writes).
Args:
... | [
"def",
"_pre_commit",
"(",
"self",
",",
"transaction",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Force the ``transaction`` to be not \"in progress\".",
"transaction",
".",
"_clean_up",
"(",
")",
"transaction",
".",
"_begin",
"(",
"retry_id",
"=",
"... | Begin transaction and call the wrapped callable.
If the callable raises an exception, the transaction will be rolled
back. If not, the transaction will be "ready" for ``Commit`` (i.e.
it will have staged writes).
Args:
transaction (~.firestore_v1beta1.transaction.Transactio... | [
"Begin",
"transaction",
"and",
"call",
"the",
"wrapped",
"callable",
"."
] | python | train |
sdispater/eloquent | eloquent/orm/relations/morph_pivot.py | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/orm/relations/morph_pivot.py#L25-L35 | def delete(self):
"""
Delete the pivot model record from the database.
:rtype: int
"""
query = self._get_delete_query()
query.where(self._morph_type, self._morph_class)
return query.delete() | [
"def",
"delete",
"(",
"self",
")",
":",
"query",
"=",
"self",
".",
"_get_delete_query",
"(",
")",
"query",
".",
"where",
"(",
"self",
".",
"_morph_type",
",",
"self",
".",
"_morph_class",
")",
"return",
"query",
".",
"delete",
"(",
")"
] | Delete the pivot model record from the database.
:rtype: int | [
"Delete",
"the",
"pivot",
"model",
"record",
"from",
"the",
"database",
"."
] | python | train |
lreis2415/PyGeoC | pygeoc/TauDEM.py | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L431-L446 | def areadinf(np, angfile, sca, outlet=None, wg=None, edgecontaimination=False,
workingdir=None, mpiexedir=None, exedir=None,
log_file=None, runtime_file=None, hostfile=None):
"""Run Accumulate area according to Dinf flow direction"""
# -nc means do not consider edge con... | [
"def",
"areadinf",
"(",
"np",
",",
"angfile",
",",
"sca",
",",
"outlet",
"=",
"None",
",",
"wg",
"=",
"None",
",",
"edgecontaimination",
"=",
"False",
",",
"workingdir",
"=",
"None",
",",
"mpiexedir",
"=",
"None",
",",
"exedir",
"=",
"None",
",",
"lo... | Run Accumulate area according to Dinf flow direction | [
"Run",
"Accumulate",
"area",
"according",
"to",
"Dinf",
"flow",
"direction"
] | python | train |
quantumlib/Cirq | cirq/ops/common_gates.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/ops/common_gates.py#L1144-L1147 | def Rz(rads: Union[float, sympy.Basic]) -> ZPowGate:
"""Returns a gate with the matrix e^{-i Z rads / 2}."""
pi = sympy.pi if protocols.is_parameterized(rads) else np.pi
return ZPowGate(exponent=rads / pi, global_shift=-0.5) | [
"def",
"Rz",
"(",
"rads",
":",
"Union",
"[",
"float",
",",
"sympy",
".",
"Basic",
"]",
")",
"->",
"ZPowGate",
":",
"pi",
"=",
"sympy",
".",
"pi",
"if",
"protocols",
".",
"is_parameterized",
"(",
"rads",
")",
"else",
"np",
".",
"pi",
"return",
"ZPow... | Returns a gate with the matrix e^{-i Z rads / 2}. | [
"Returns",
"a",
"gate",
"with",
"the",
"matrix",
"e^",
"{",
"-",
"i",
"Z",
"rads",
"/",
"2",
"}",
"."
] | python | train |
manns/pyspread | pyspread/src/gui/_grid.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_grid.py#L1405-L1427 | def OnDeleteCols(self, event):
"""Deletes columns from all tables of the grid"""
bbox = self.grid.selection.get_bbox()
if bbox is None or bbox[1][1] is None:
# Insert rows at cursor
del_point = self.grid.actions.cursor[1]
no_cols = 1
else:
... | [
"def",
"OnDeleteCols",
"(",
"self",
",",
"event",
")",
":",
"bbox",
"=",
"self",
".",
"grid",
".",
"selection",
".",
"get_bbox",
"(",
")",
"if",
"bbox",
"is",
"None",
"or",
"bbox",
"[",
"1",
"]",
"[",
"1",
"]",
"is",
"None",
":",
"# Insert rows at ... | Deletes columns from all tables of the grid | [
"Deletes",
"columns",
"from",
"all",
"tables",
"of",
"the",
"grid"
] | python | train |
rigetti/pyquil | pyquil/operator_estimation.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/operator_estimation.py#L486-L512 | def construct_tpb_graph(experiments: TomographyExperiment):
"""
Construct a graph where an edge signifies two experiments are diagonal in a TPB.
"""
g = nx.Graph()
for expt in experiments:
assert len(expt) == 1, 'already grouped?'
expt = expt[0]
if expt not in g:
... | [
"def",
"construct_tpb_graph",
"(",
"experiments",
":",
"TomographyExperiment",
")",
":",
"g",
"=",
"nx",
".",
"Graph",
"(",
")",
"for",
"expt",
"in",
"experiments",
":",
"assert",
"len",
"(",
"expt",
")",
"==",
"1",
",",
"'already grouped?'",
"expt",
"=",
... | Construct a graph where an edge signifies two experiments are diagonal in a TPB. | [
"Construct",
"a",
"graph",
"where",
"an",
"edge",
"signifies",
"two",
"experiments",
"are",
"diagonal",
"in",
"a",
"TPB",
"."
] | python | train |
brutasse/graphite-api | graphite_api/render/glyph.py | https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/render/glyph.py#L511-L524 | def computeSlop(self, step, divisor):
"""Compute the slop that would result from step and divisor.
Return the slop, or None if this combination can't cover the full
range. See chooseStep() for the definition of "slop".
"""
bottom = step * math.floor(self.minValue / float(step) ... | [
"def",
"computeSlop",
"(",
"self",
",",
"step",
",",
"divisor",
")",
":",
"bottom",
"=",
"step",
"*",
"math",
".",
"floor",
"(",
"self",
".",
"minValue",
"/",
"float",
"(",
"step",
")",
"+",
"EPSILON",
")",
"top",
"=",
"bottom",
"+",
"step",
"*",
... | Compute the slop that would result from step and divisor.
Return the slop, or None if this combination can't cover the full
range. See chooseStep() for the definition of "slop". | [
"Compute",
"the",
"slop",
"that",
"would",
"result",
"from",
"step",
"and",
"divisor",
"."
] | python | train |
Becksteinlab/GromacsWrapper | gromacs/run.py | https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/run.py#L177-L190 | def mpicommand(self, *args, **kwargs):
"""Return a list of the mpi command portion of the commandline.
Only allows primitive mpi at the moment:
*mpiexec* -n *ncores* *mdrun* *mdrun-args*
(This is a primitive example for OpenMP. Override it for more
complicated cases.)
... | [
"def",
"mpicommand",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"mpiexec",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"Override mpiexec to enable the simple OpenMP launcher\"",
")",
"# example implementation",... | Return a list of the mpi command portion of the commandline.
Only allows primitive mpi at the moment:
*mpiexec* -n *ncores* *mdrun* *mdrun-args*
(This is a primitive example for OpenMP. Override it for more
complicated cases.) | [
"Return",
"a",
"list",
"of",
"the",
"mpi",
"command",
"portion",
"of",
"the",
"commandline",
"."
] | python | valid |
DistrictDataLabs/yellowbrick | yellowbrick/bestfit.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/bestfit.py#L49-L157 | def draw_best_fit(X, y, ax, estimator='linear', **kwargs):
"""
Uses Scikit-Learn to fit a model to X and y then uses the resulting model
to predict the curve based on the X values. This curve is drawn to the ax
(matplotlib axis) which must be passed as the third variable.
The estimator function can... | [
"def",
"draw_best_fit",
"(",
"X",
",",
"y",
",",
"ax",
",",
"estimator",
"=",
"'linear'",
",",
"*",
"*",
"kwargs",
")",
":",
"# Estimators are the types of best fit lines that can be drawn.",
"estimators",
"=",
"{",
"LINEAR",
":",
"fit_linear",
",",
"# Uses OLS to... | Uses Scikit-Learn to fit a model to X and y then uses the resulting model
to predict the curve based on the X values. This curve is drawn to the ax
(matplotlib axis) which must be passed as the third variable.
The estimator function can be one of the following:
- ``'linear'``: Uses OLS to fit the... | [
"Uses",
"Scikit",
"-",
"Learn",
"to",
"fit",
"a",
"model",
"to",
"X",
"and",
"y",
"then",
"uses",
"the",
"resulting",
"model",
"to",
"predict",
"the",
"curve",
"based",
"on",
"the",
"X",
"values",
".",
"This",
"curve",
"is",
"drawn",
"to",
"the",
"ax... | python | train |
ssato/python-anytemplate | anytemplate/engines/pystache.py | https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/engines/pystache.py#L61-L78 | def _make_renderer(self, at_paths, at_encoding, **kwargs):
"""
:param at_paths: Template search paths
:param at_encoding: Template encoding
:param kwargs: Keyword arguments passed to the template engine to
render templates with specific features enabled.
"""
f... | [
"def",
"_make_renderer",
"(",
"self",
",",
"at_paths",
",",
"at_encoding",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"eopt",
"in",
"(",
"\"file_encoding\"",
",",
"\"string_encoding\"",
")",
":",
"default",
"=",
"self",
".",
"_roptions",
".",
"get",
"(",
... | :param at_paths: Template search paths
:param at_encoding: Template encoding
:param kwargs: Keyword arguments passed to the template engine to
render templates with specific features enabled. | [
":",
"param",
"at_paths",
":",
"Template",
"search",
"paths",
":",
"param",
"at_encoding",
":",
"Template",
"encoding",
":",
"param",
"kwargs",
":",
"Keyword",
"arguments",
"passed",
"to",
"the",
"template",
"engine",
"to",
"render",
"templates",
"with",
"spec... | python | train |
obfusk/m | m.py | https://github.com/obfusk/m/blob/23ec2754abc9e945e5f01fcc64c13c833faf2e33/m.py#L1705-L1715 | def zlines(f = None, sep = "\0", osep = None, size = 8192): # {{{1
"""File iterator that uses alternative line terminators."""
if f is None: f = sys.stdin
if osep is None: osep = sep
buf = ""
while True:
chars = f.read(size)
if not chars: break
buf += chars; lines = buf.split(sep); buf = lines... | [
"def",
"zlines",
"(",
"f",
"=",
"None",
",",
"sep",
"=",
"\"\\0\"",
",",
"osep",
"=",
"None",
",",
"size",
"=",
"8192",
")",
":",
"# {{{1",
"if",
"f",
"is",
"None",
":",
"f",
"=",
"sys",
".",
"stdin",
"if",
"osep",
"is",
"None",
":",
"osep",
... | File iterator that uses alternative line terminators. | [
"File",
"iterator",
"that",
"uses",
"alternative",
"line",
"terminators",
"."
] | python | train |
f3at/feat | src/feat/models/getter.py | https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/models/getter.py#L53-L65 | def source_attr(attr_name):
"""
Creates a getter that will drop the current value
and retrieve the source's attribute with specified name.
@param attr_name: the name of an attribute belonging to the source.
@type attr_name: str
"""
def source_attr(_value, context, **_params):
value ... | [
"def",
"source_attr",
"(",
"attr_name",
")",
":",
"def",
"source_attr",
"(",
"_value",
",",
"context",
",",
"*",
"*",
"_params",
")",
":",
"value",
"=",
"getattr",
"(",
"context",
"[",
"\"model\"",
"]",
".",
"source",
",",
"attr_name",
")",
"return",
"... | Creates a getter that will drop the current value
and retrieve the source's attribute with specified name.
@param attr_name: the name of an attribute belonging to the source.
@type attr_name: str | [
"Creates",
"a",
"getter",
"that",
"will",
"drop",
"the",
"current",
"value",
"and",
"retrieve",
"the",
"source",
"s",
"attribute",
"with",
"specified",
"name",
"."
] | python | train |
delfick/harpoon | harpoon/option_spec/image_objs.py | https://github.com/delfick/harpoon/blob/a2d39311d6127b7da2e15f40468bf320d598e461/harpoon/option_spec/image_objs.py#L494-L501 | def pair(self):
"""Get the name and value for this environment variable"""
if self.set_val is not None:
return self.env_name, self.set_val
elif self.default_val is not None:
return self.env_name, os.environ.get(self.env_name, self.default_val)
else:
re... | [
"def",
"pair",
"(",
"self",
")",
":",
"if",
"self",
".",
"set_val",
"is",
"not",
"None",
":",
"return",
"self",
".",
"env_name",
",",
"self",
".",
"set_val",
"elif",
"self",
".",
"default_val",
"is",
"not",
"None",
":",
"return",
"self",
".",
"env_na... | Get the name and value for this environment variable | [
"Get",
"the",
"name",
"and",
"value",
"for",
"this",
"environment",
"variable"
] | python | train |
angr/angr | angr/procedures/libc/strtol.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/procedures/libc/strtol.py#L78-L149 | def _string_to_int(s, state, region, base, signed, read_length=None):
"""
reads values from s and generates the symbolic number that it would equal
the first char is either a number in the given base, or the result is 0
expression indicates whether or not it was successful
"""
... | [
"def",
"_string_to_int",
"(",
"s",
",",
"state",
",",
"region",
",",
"base",
",",
"signed",
",",
"read_length",
"=",
"None",
")",
":",
"# if length wasn't provided, read the maximum bytes",
"length",
"=",
"state",
".",
"libc",
".",
"max_strtol_len",
"if",
"read_... | reads values from s and generates the symbolic number that it would equal
the first char is either a number in the given base, or the result is 0
expression indicates whether or not it was successful | [
"reads",
"values",
"from",
"s",
"and",
"generates",
"the",
"symbolic",
"number",
"that",
"it",
"would",
"equal",
"the",
"first",
"char",
"is",
"either",
"a",
"number",
"in",
"the",
"given",
"base",
"or",
"the",
"result",
"is",
"0",
"expression",
"indicates... | python | train |
j0ack/flask-codemirror | flask_codemirror/__init__.py | https://github.com/j0ack/flask-codemirror/blob/81ad831ff849b60bb34de5db727ad626ff3c9bdc/flask_codemirror/__init__.py#L92-L127 | def include_codemirror(self):
"""Include resources in pages"""
contents = []
# base
js = self._get_tag('codemirror.js', 'script')
css = self._get_tag('codemirror.css', 'stylesheet')
if js and css:
contents.append(js)
contents.append(css)
# ... | [
"def",
"include_codemirror",
"(",
"self",
")",
":",
"contents",
"=",
"[",
"]",
"# base",
"js",
"=",
"self",
".",
"_get_tag",
"(",
"'codemirror.js'",
",",
"'script'",
")",
"css",
"=",
"self",
".",
"_get_tag",
"(",
"'codemirror.css'",
",",
"'stylesheet'",
")... | Include resources in pages | [
"Include",
"resources",
"in",
"pages"
] | python | train |
carpyncho/feets | feets/libs/ls_fap.py | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/libs/ls_fap.py#L207-L215 | def fap_davies(Z, fmax, t, y, dy, normalization='standard'):
"""Davies upper-bound to the false alarm probability
(Eqn 5 of Baluev 2008)
"""
N = len(t)
fap_s = fap_single(Z, N, normalization=normalization)
tau = tau_davies(Z, fmax, t, y, dy, normalization=normalization)
return fap_s + tau | [
"def",
"fap_davies",
"(",
"Z",
",",
"fmax",
",",
"t",
",",
"y",
",",
"dy",
",",
"normalization",
"=",
"'standard'",
")",
":",
"N",
"=",
"len",
"(",
"t",
")",
"fap_s",
"=",
"fap_single",
"(",
"Z",
",",
"N",
",",
"normalization",
"=",
"normalization"... | Davies upper-bound to the false alarm probability
(Eqn 5 of Baluev 2008) | [
"Davies",
"upper",
"-",
"bound",
"to",
"the",
"false",
"alarm",
"probability"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.