repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
openergy/oplus | oplus/epm/record.py | https://github.com/openergy/oplus/blob/f095868d1990c1d126e906ada6acbab26348b3d3/oplus/epm/record.py#L461-L473 | def set_defaults(self):
"""
sets all empty fields for which a default value is defined to default value
"""
defaults = {}
for i in range(len(self)):
if i in self._data:
continue
default = self.get_field_descriptor(i).tags.get("default", [No... | [
"def",
"set_defaults",
"(",
"self",
")",
":",
"defaults",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
")",
")",
":",
"if",
"i",
"in",
"self",
".",
"_data",
":",
"continue",
"default",
"=",
"self",
".",
"get_field_descriptor",
... | sets all empty fields for which a default value is defined to default value | [
"sets",
"all",
"empty",
"fields",
"for",
"which",
"a",
"default",
"value",
"is",
"defined",
"to",
"default",
"value"
] | python | test | 32.307692 |
ioos/compliance-checker | compliance_checker/cf/cf.py | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cf/cf.py#L3359-L3380 | def _check_hint_bounds(self, ds):
'''
Checks for variables ending with _bounds, if they are not cell methods,
make the recommendation
:param netCDF4.Dataset ds: An open netCDF dataset
:rtype: list
:return: List of results
'''
ret_val = []
boundary... | [
"def",
"_check_hint_bounds",
"(",
"self",
",",
"ds",
")",
":",
"ret_val",
"=",
"[",
"]",
"boundary_variables",
"=",
"cfutil",
".",
"get_cell_boundary_variables",
"(",
"ds",
")",
"for",
"name",
"in",
"ds",
".",
"variables",
":",
"if",
"name",
".",
"endswith... | Checks for variables ending with _bounds, if they are not cell methods,
make the recommendation
:param netCDF4.Dataset ds: An open netCDF dataset
:rtype: list
:return: List of results | [
"Checks",
"for",
"variables",
"ending",
"with",
"_bounds",
"if",
"they",
"are",
"not",
"cell",
"methods",
"make",
"the",
"recommendation"
] | python | train | 40.681818 |
saltstack/salt | salt/utils/schedule.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/schedule.py#L165-L171 | def option(self, opt):
'''
Return options merged from config and pillar
'''
if 'config.merge' in self.functions:
return self.functions['config.merge'](opt, {}, omit_master=True)
return self.opts.get(opt, {}) | [
"def",
"option",
"(",
"self",
",",
"opt",
")",
":",
"if",
"'config.merge'",
"in",
"self",
".",
"functions",
":",
"return",
"self",
".",
"functions",
"[",
"'config.merge'",
"]",
"(",
"opt",
",",
"{",
"}",
",",
"omit_master",
"=",
"True",
")",
"return",
... | Return options merged from config and pillar | [
"Return",
"options",
"merged",
"from",
"config",
"and",
"pillar"
] | python | train | 36.142857 |
tensorflow/mesh | mesh_tensorflow/ops.py | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1046-L1059 | def laid_out_pcoord(self, mesh_axis):
"""Returns a LaidOutTensor containing the processor coordinate.
Args:
mesh_axis: int.
Returns:
LaidOutTensor where each slice is an integer scalar.
"""
divisor = list_product(self.shape.to_integer_list[mesh_axis + 1:])
modulus = self.shape[mesh... | [
"def",
"laid_out_pcoord",
"(",
"self",
",",
"mesh_axis",
")",
":",
"divisor",
"=",
"list_product",
"(",
"self",
".",
"shape",
".",
"to_integer_list",
"[",
"mesh_axis",
"+",
"1",
":",
"]",
")",
"modulus",
"=",
"self",
".",
"shape",
"[",
"mesh_axis",
"]",
... | Returns a LaidOutTensor containing the processor coordinate.
Args:
mesh_axis: int.
Returns:
LaidOutTensor where each slice is an integer scalar. | [
"Returns",
"a",
"LaidOutTensor",
"containing",
"the",
"processor",
"coordinate",
"."
] | python | train | 31.071429 |
ghackebeil/PyORAM | src/pyoram/util/virtual_heap.py | https://github.com/ghackebeil/PyORAM/blob/b8832c1b753c0b2148ef7a143c5f5dd3bbbb61e7/src/pyoram/util/virtual_heap.py#L379-L417 | def write_as_dot(self, f, data=None, max_levels=None):
"Write the tree in the dot language format to f."
assert (max_levels is None) or (max_levels >= 0)
def visit_node(n, levels):
lbl = "{"
if data is None:
if self.k <= max_k_labeled:
... | [
"def",
"write_as_dot",
"(",
"self",
",",
"f",
",",
"data",
"=",
"None",
",",
"max_levels",
"=",
"None",
")",
":",
"assert",
"(",
"max_levels",
"is",
"None",
")",
"or",
"(",
"max_levels",
">=",
"0",
")",
"def",
"visit_node",
"(",
"n",
",",
"levels",
... | Write the tree in the dot language format to f. | [
"Write",
"the",
"tree",
"in",
"the",
"dot",
"language",
"format",
"to",
"f",
"."
] | python | train | 40.692308 |
numenta/htmresearch | htmresearch/regions/GridCellLocationRegion.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/regions/GridCellLocationRegion.py#L502-L509 | def getOutputElementCount(self, name):
"""
Returns the size of the output array
"""
if name in ["activeCells", "learnableCells", "sensoryAssociatedCells"]:
return self.cellCount * self.moduleCount
else:
raise Exception("Invalid output name specified: " + name) | [
"def",
"getOutputElementCount",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"[",
"\"activeCells\"",
",",
"\"learnableCells\"",
",",
"\"sensoryAssociatedCells\"",
"]",
":",
"return",
"self",
".",
"cellCount",
"*",
"self",
".",
"moduleCount",
"else",
... | Returns the size of the output array | [
"Returns",
"the",
"size",
"of",
"the",
"output",
"array"
] | python | train | 35.625 |
openstack/networking-cisco | networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py#L292-L306 | def get_hosting_device_plugging_driver(self, context, id):
"""Returns plugging driver for hosting device template with <id>."""
if id is None:
return
try:
return self._plugging_drivers[id]
except KeyError:
try:
template = self._get_hos... | [
"def",
"get_hosting_device_plugging_driver",
"(",
"self",
",",
"context",
",",
"id",
")",
":",
"if",
"id",
"is",
"None",
":",
"return",
"try",
":",
"return",
"self",
".",
"_plugging_drivers",
"[",
"id",
"]",
"except",
"KeyError",
":",
"try",
":",
"template... | Returns plugging driver for hosting device template with <id>. | [
"Returns",
"plugging",
"driver",
"for",
"hosting",
"device",
"template",
"with",
"<id",
">",
"."
] | python | train | 47.333333 |
saltstack/salt | salt/utils/network.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/network.py#L2057-L2066 | def is_fqdn(hostname):
"""
Verify if hostname conforms to be a FQDN.
:param hostname: text string with the name of the host
:return: bool, True if hostname is correct FQDN, False otherwise
"""
compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE)
return "." in hostname an... | [
"def",
"is_fqdn",
"(",
"hostname",
")",
":",
"compliant",
"=",
"re",
".",
"compile",
"(",
"r\"(?!-)[A-Z\\d\\-\\_]{1,63}(?<!-)$\"",
",",
"re",
".",
"IGNORECASE",
")",
"return",
"\".\"",
"in",
"hostname",
"and",
"len",
"(",
"hostname",
")",
"<",
"0xff",
"and",... | Verify if hostname conforms to be a FQDN.
:param hostname: text string with the name of the host
:return: bool, True if hostname is correct FQDN, False otherwise | [
"Verify",
"if",
"hostname",
"conforms",
"to",
"be",
"a",
"FQDN",
"."
] | python | train | 40.2 |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/commands/CommandSet.py | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/commands/CommandSet.py#L122-L132 | def _rebuild_all_command_chains(self):
"""
Rebuilds execution chain for all registered commands.
This method is typically called when intercepters are changed.
Because of that it is more efficient to register intercepters
before registering commands (typically it will be done in ... | [
"def",
"_rebuild_all_command_chains",
"(",
"self",
")",
":",
"self",
".",
"_commands_by_name",
"=",
"{",
"}",
"for",
"command",
"in",
"self",
".",
"_commands",
":",
"self",
".",
"_build_command_chain",
"(",
"command",
")"
] | Rebuilds execution chain for all registered commands.
This method is typically called when intercepters are changed.
Because of that it is more efficient to register intercepters
before registering commands (typically it will be done in abstract classes).
However, that performance penalt... | [
"Rebuilds",
"execution",
"chain",
"for",
"all",
"registered",
"commands",
".",
"This",
"method",
"is",
"typically",
"called",
"when",
"intercepters",
"are",
"changed",
".",
"Because",
"of",
"that",
"it",
"is",
"more",
"efficient",
"to",
"register",
"intercepters... | python | train | 49.454545 |
eventbrite/pysoa | pysoa/client/client.py | https://github.com/eventbrite/pysoa/blob/9c052cae2397d13de3df8ae2c790846a70b53f18/pysoa/client/client.py#L453-L494 | def call_actions_parallel(self, service_name, actions, **kwargs):
"""
Build and send multiple job requests to one service, each job with one action, to be executed in parallel, and
return once all responses have been received.
Returns a list of action responses, one for each action in t... | [
"def",
"call_actions_parallel",
"(",
"self",
",",
"service_name",
",",
"actions",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"call_actions_parallel_future",
"(",
"service_name",
",",
"actions",
",",
"*",
"*",
"kwargs",
")",
".",
"result",
"(",... | Build and send multiple job requests to one service, each job with one action, to be executed in parallel, and
return once all responses have been received.
Returns a list of action responses, one for each action in the same order as provided, or raises an exception
if any action response is an... | [
"Build",
"and",
"send",
"multiple",
"job",
"requests",
"to",
"one",
"service",
"each",
"job",
"with",
"one",
"action",
"to",
"be",
"executed",
"in",
"parallel",
"and",
"return",
"once",
"all",
"responses",
"have",
"been",
"received",
"."
] | python | train | 61.047619 |
ultrabug/py3status | py3status/core.py | https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L696-L715 | def stop(self):
"""
Set the Event lock, this will break all threads' loops.
"""
self.running = False
# stop the command server
try:
self.commands_thread.kill()
except: # noqa e722
pass
try:
self.lock.set()
... | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"running",
"=",
"False",
"# stop the command server",
"try",
":",
"self",
".",
"commands_thread",
".",
"kill",
"(",
")",
"except",
":",
"# noqa e722",
"pass",
"try",
":",
"self",
".",
"lock",
".",
"set",... | Set the Event lock, this will break all threads' loops. | [
"Set",
"the",
"Event",
"lock",
"this",
"will",
"break",
"all",
"threads",
"loops",
"."
] | python | train | 27.65 |
blue-yonder/tsfresh | tsfresh/feature_selection/relevance.py | https://github.com/blue-yonder/tsfresh/blob/c72c9c574371cf7dd7d54e00a466792792e5d202/tsfresh/feature_selection/relevance.py#L247-L263 | def get_feature_type(feature_column):
"""
For a given feature, determine if it is real, binary or constant.
Here binary means that only two unique values occur in the feature.
:param feature_column: The feature column
:type feature_column: pandas.Series
:return: 'constant', 'binary' or 'real'
... | [
"def",
"get_feature_type",
"(",
"feature_column",
")",
":",
"n_unique_values",
"=",
"len",
"(",
"set",
"(",
"feature_column",
".",
"values",
")",
")",
"if",
"n_unique_values",
"==",
"1",
":",
"_logger",
".",
"warning",
"(",
"\"[test_feature_significance] Feature {... | For a given feature, determine if it is real, binary or constant.
Here binary means that only two unique values occur in the feature.
:param feature_column: The feature column
:type feature_column: pandas.Series
:return: 'constant', 'binary' or 'real' | [
"For",
"a",
"given",
"feature",
"determine",
"if",
"it",
"is",
"real",
"binary",
"or",
"constant",
".",
"Here",
"binary",
"means",
"that",
"only",
"two",
"unique",
"values",
"occur",
"in",
"the",
"feature",
"."
] | python | train | 36 |
signetlabdei/sem | sem/parallelrunner.py | https://github.com/signetlabdei/sem/blob/5077dd7a6d15644a18790bb6fde320e905f0fef0/sem/parallelrunner.py#L12-L24 | def run_simulations(self, parameter_list, data_folder):
"""
This function runs multiple simulations in parallel.
Args:
parameter_list (list): list of parameter combinations to simulate.
data_folder (str): folder in which to create output folders.
"""
self... | [
"def",
"run_simulations",
"(",
"self",
",",
"parameter_list",
",",
"data_folder",
")",
":",
"self",
".",
"data_folder",
"=",
"data_folder",
"with",
"Pool",
"(",
"processes",
"=",
"MAX_PARALLEL_PROCESSES",
")",
"as",
"pool",
":",
"for",
"result",
"in",
"pool",
... | This function runs multiple simulations in parallel.
Args:
parameter_list (list): list of parameter combinations to simulate.
data_folder (str): folder in which to create output folders. | [
"This",
"function",
"runs",
"multiple",
"simulations",
"in",
"parallel",
"."
] | python | train | 42.846154 |
tanghaibao/goatools | goatools/grouper/aart_geneproducts_all.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/aart_geneproducts_all.py#L40-L46 | def run(self, name, goea_nts, log):
"""Run gene product ASCII art."""
objaart = AArtGeneProductSetsOne(name, goea_nts, self)
if self.hdrobj.sections:
return objaart.prt_report_grp1(log)
else:
return objaart.prt_report_grp0(log) | [
"def",
"run",
"(",
"self",
",",
"name",
",",
"goea_nts",
",",
"log",
")",
":",
"objaart",
"=",
"AArtGeneProductSetsOne",
"(",
"name",
",",
"goea_nts",
",",
"self",
")",
"if",
"self",
".",
"hdrobj",
".",
"sections",
":",
"return",
"objaart",
".",
"prt_r... | Run gene product ASCII art. | [
"Run",
"gene",
"product",
"ASCII",
"art",
"."
] | python | train | 39.571429 |
log2timeline/plaso | plaso/lib/timelib.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/lib/timelib.py#L206-L246 | def CopyToDatetime(cls, timestamp, timezone, raise_error=False):
"""Copies the timestamp to a datetime object.
Args:
timestamp: The timestamp which is an integer containing the number
of micro seconds since January 1, 1970, 00:00:00 UTC.
timezone: The timezone (pytz.timezone) objec... | [
"def",
"CopyToDatetime",
"(",
"cls",
",",
"timestamp",
",",
"timezone",
",",
"raise_error",
"=",
"False",
")",
":",
"datetime_object",
"=",
"datetime",
".",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"... | Copies the timestamp to a datetime object.
Args:
timestamp: The timestamp which is an integer containing the number
of micro seconds since January 1, 1970, 00:00:00 UTC.
timezone: The timezone (pytz.timezone) object.
raise_error: Boolean that if set to True will not absorb an Ove... | [
"Copies",
"the",
"timestamp",
"to",
"a",
"datetime",
"object",
"."
] | python | train | 35.219512 |
saltstack/salt | salt/modules/csf.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L407-L418 | def tempdeny(ip=None, ttl=None, port=None, direction=None, comment=''):
'''
Add a rule to the temporary ip deny list.
See :func:`_access_rule`.
1- Add an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.tempdeny 127.0.0.1 300 port=22 direction='in' comment='# Brute force attempt'
... | [
"def",
"tempdeny",
"(",
"ip",
"=",
"None",
",",
"ttl",
"=",
"None",
",",
"port",
"=",
"None",
",",
"direction",
"=",
"None",
",",
"comment",
"=",
"''",
")",
":",
"return",
"_tmp_access_rule",
"(",
"'tempdeny'",
",",
"ip",
",",
"ttl",
",",
"port",
"... | Add a rule to the temporary ip deny list.
See :func:`_access_rule`.
1- Add an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.tempdeny 127.0.0.1 300 port=22 direction='in' comment='# Brute force attempt' | [
"Add",
"a",
"rule",
"to",
"the",
"temporary",
"ip",
"deny",
"list",
".",
"See",
":",
"func",
":",
"_access_rule",
".",
"1",
"-",
"Add",
"an",
"IP",
":",
"CLI",
"Example",
":"
] | python | train | 32.333333 |
akissa/clamavmirror | clamavmirror/__init__.py | https://github.com/akissa/clamavmirror/blob/6ef1cfa9fb4fa4a7b8439004f1cd8775f51d77f6/clamavmirror/__init__.py#L372-L423 | def main():
"""Main entry point"""
parser = OptionParser()
parser.add_option('-a', '--hostname',
help='ClamAV source server hostname',
dest='hostname',
type='str',
default='db.de.clamav.net')
parser.add_option('-r', ... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"OptionParser",
"(",
")",
"parser",
".",
"add_option",
"(",
"'-a'",
",",
"'--hostname'",
",",
"help",
"=",
"'ClamAV source server hostname'",
",",
"dest",
"=",
"'hostname'",
",",
"type",
"=",
"'str'",
",",
"defa... | Main entry point | [
"Main",
"entry",
"point"
] | python | train | 40.576923 |
Dallinger/Dallinger | dallinger/heroku/tools.py | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L430-L438 | def monitor(self, listener):
"""Relay the stream to listener until told to stop.
"""
for line in self._stream():
self._record.append(line)
if self.verbose:
self.out.blather(line)
if listener(line) is self.MONITOR_STOP:
return | [
"def",
"monitor",
"(",
"self",
",",
"listener",
")",
":",
"for",
"line",
"in",
"self",
".",
"_stream",
"(",
")",
":",
"self",
".",
"_record",
".",
"append",
"(",
"line",
")",
"if",
"self",
".",
"verbose",
":",
"self",
".",
"out",
".",
"blather",
... | Relay the stream to listener until told to stop. | [
"Relay",
"the",
"stream",
"to",
"listener",
"until",
"told",
"to",
"stop",
"."
] | python | train | 34.333333 |
tensorflow/tensor2tensor | tensor2tensor/data_generators/imagenet.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/imagenet.py#L559-L567 | def _do_scale(image, size):
"""Rescale the image by scaling the smaller spatial dimension to `size`."""
shape = tf.cast(tf.shape(image), tf.float32)
w_greater = tf.greater(shape[0], shape[1])
shape = tf.cond(w_greater,
lambda: tf.cast([shape[0] / shape[1] * size, size], tf.int32),
... | [
"def",
"_do_scale",
"(",
"image",
",",
"size",
")",
":",
"shape",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"shape",
"(",
"image",
")",
",",
"tf",
".",
"float32",
")",
"w_greater",
"=",
"tf",
".",
"greater",
"(",
"shape",
"[",
"0",
"]",
",",
"sha... | Rescale the image by scaling the smaller spatial dimension to `size`. | [
"Rescale",
"the",
"image",
"by",
"scaling",
"the",
"smaller",
"spatial",
"dimension",
"to",
"size",
"."
] | python | train | 48.111111 |
e7dal/bubble3 | bubble3/commands/cmd_pipe.py | https://github.com/e7dal/bubble3/blob/59c735281a95b44f6263a25f4d6ce24fca520082/bubble3/commands/cmd_pipe.py#L18-L33 | def cli(ctx, amount, index, stage):
"""Pull, Transform, Push,streaming inside a pipe(experimental)."""
ctx.obj.say_green('Starting Streaming Pipe')
res_pull = ctx.invoke(pull, amount=amount, index=index, stage=stage)
res_tra = False
if res_pull:
# amount to transform can be less (or more)
... | [
"def",
"cli",
"(",
"ctx",
",",
"amount",
",",
"index",
",",
"stage",
")",
":",
"ctx",
".",
"obj",
".",
"say_green",
"(",
"'Starting Streaming Pipe'",
")",
"res_pull",
"=",
"ctx",
".",
"invoke",
"(",
"pull",
",",
"amount",
"=",
"amount",
",",
"index",
... | Pull, Transform, Push,streaming inside a pipe(experimental). | [
"Pull",
"Transform",
"Push",
"streaming",
"inside",
"a",
"pipe",
"(",
"experimental",
")",
"."
] | python | train | 41.8125 |
konstantinstadler/pymrio | pymrio/core/fileio.py | https://github.com/konstantinstadler/pymrio/blob/d764aa0dd2150200e867a9713a98ddae203e12d4/pymrio/core/fileio.py#L434-L676 | def _load_ini_based_io(path, recursive=False, ini=None,
subini={}, include_core=True,
only_coefficients=False):
""" DEPRECATED: For convert a previous version to the new json format
Loads a IOSystem or Extension from a ini files
This function can be used to lo... | [
"def",
"_load_ini_based_io",
"(",
"path",
",",
"recursive",
"=",
"False",
",",
"ini",
"=",
"None",
",",
"subini",
"=",
"{",
"}",
",",
"include_core",
"=",
"True",
",",
"only_coefficients",
"=",
"False",
")",
":",
"# check path and given parameter",
"ini_file_n... | DEPRECATED: For convert a previous version to the new json format
Loads a IOSystem or Extension from a ini files
This function can be used to load a IOSystem or Extension specified in a
ini file. DataFrames (tables) are loaded from text or binary pickle files.
For the latter, the extension .pkl or .pi... | [
"DEPRECATED",
":",
"For",
"convert",
"a",
"previous",
"version",
"to",
"the",
"new",
"json",
"format"
] | python | train | 36.650206 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/app/canvas.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/app/canvas.py#L460-L468 | def _update_fps(self, event):
"""Update the fps after every window"""
self._frame_count += 1
diff = time() - self._basetime
if (diff > self._fps_window):
self._fps = self._frame_count / diff
self._basetime = time()
self._frame_count = 0
sel... | [
"def",
"_update_fps",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"_frame_count",
"+=",
"1",
"diff",
"=",
"time",
"(",
")",
"-",
"self",
".",
"_basetime",
"if",
"(",
"diff",
">",
"self",
".",
"_fps_window",
")",
":",
"self",
".",
"_fps",
"=",... | Update the fps after every window | [
"Update",
"the",
"fps",
"after",
"every",
"window"
] | python | train | 37.444444 |
vaexio/vaex | packages/vaex-core/vaex/dataframe.py | https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/dataframe.py#L4619-L4640 | def data(self):
"""Gives direct access to the data as numpy arrays.
Convenient when working with IPython in combination with small DataFrames, since this gives tab-completion.
Only real columns (i.e. no virtual) columns can be accessed, for getting the data from virtual columns, use
Dat... | [
"def",
"data",
"(",
"self",
")",
":",
"class",
"Datas",
"(",
"object",
")",
":",
"pass",
"datas",
"=",
"Datas",
"(",
")",
"for",
"name",
",",
"array",
"in",
"self",
".",
"columns",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"datas",
",",
"name"... | Gives direct access to the data as numpy arrays.
Convenient when working with IPython in combination with small DataFrames, since this gives tab-completion.
Only real columns (i.e. no virtual) columns can be accessed, for getting the data from virtual columns, use
DataFrame.evalulate(...).
... | [
"Gives",
"direct",
"access",
"to",
"the",
"data",
"as",
"numpy",
"arrays",
"."
] | python | test | 33.181818 |
juju/charm-helpers | charmhelpers/core/services/base.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L222-L236 | def fire_event(self, event_name, service_name, default=None):
"""
Fire a data_ready, data_lost, start, or stop event on a given service.
"""
service = self.get_service(service_name)
callbacks = service.get(event_name, default)
if not callbacks:
return
... | [
"def",
"fire_event",
"(",
"self",
",",
"event_name",
",",
"service_name",
",",
"default",
"=",
"None",
")",
":",
"service",
"=",
"self",
".",
"get_service",
"(",
"service_name",
")",
"callbacks",
"=",
"service",
".",
"get",
"(",
"event_name",
",",
"default... | Fire a data_ready, data_lost, start, or stop event on a given service. | [
"Fire",
"a",
"data_ready",
"data_lost",
"start",
"or",
"stop",
"event",
"on",
"a",
"given",
"service",
"."
] | python | train | 38.933333 |
quantumlib/Cirq | cirq/linalg/decompositions.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/linalg/decompositions.py#L472-L537 | def kak_decomposition(
mat: np.ndarray,
rtol: float = 1e-5,
atol: float = 1e-8) -> KakDecomposition:
"""Decomposes a 2-qubit unitary into 1-qubit ops and XX/YY/ZZ interactions.
Args:
mat: The 4x4 unitary matrix to decompose.
rtol: Per-matrix-entry relative tolerance on e... | [
"def",
"kak_decomposition",
"(",
"mat",
":",
"np",
".",
"ndarray",
",",
"rtol",
":",
"float",
"=",
"1e-5",
",",
"atol",
":",
"float",
"=",
"1e-8",
")",
"->",
"KakDecomposition",
":",
"magic",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
... | Decomposes a 2-qubit unitary into 1-qubit ops and XX/YY/ZZ interactions.
Args:
mat: The 4x4 unitary matrix to decompose.
rtol: Per-matrix-entry relative tolerance on equality.
atol: Per-matrix-entry absolute tolerance on equality.
Returns:
A `cirq.KakDecomposition` canonicalize... | [
"Decomposes",
"a",
"2",
"-",
"qubit",
"unitary",
"into",
"1",
"-",
"qubit",
"ops",
"and",
"XX",
"/",
"YY",
"/",
"ZZ",
"interactions",
"."
] | python | train | 36.318182 |
Yubico/python-pyhsm | pyhsm/tools/keystore_unlock.py | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/keystore_unlock.py#L84-L100 | def get_otp(hsm, args):
""" Get OTP from YubiKey. """
if args.no_otp:
return None
if hsm.version.have_unlock():
if args.stdin:
otp = sys.stdin.readline()
while otp and otp[-1] == '\n':
otp = otp[:-1]
else:
otp = raw_input('Enter adm... | [
"def",
"get_otp",
"(",
"hsm",
",",
"args",
")",
":",
"if",
"args",
".",
"no_otp",
":",
"return",
"None",
"if",
"hsm",
".",
"version",
".",
"have_unlock",
"(",
")",
":",
"if",
"args",
".",
"stdin",
":",
"otp",
"=",
"sys",
".",
"stdin",
".",
"readl... | Get OTP from YubiKey. | [
"Get",
"OTP",
"from",
"YubiKey",
"."
] | python | train | 33.176471 |
broadinstitute/fiss | firecloud/supervisor.py | https://github.com/broadinstitute/fiss/blob/dddf91547479506dbbafb69ec84d44dcc4a94ab4/firecloud/supervisor.py#L148-L289 | def supervise_until_complete(monitor_data, dependencies, args, recovery_file):
""" Supervisor loop. Loop forever until all tasks are evaluated or completed """
project = args['project']
workspace = args['workspace']
namespace = args['namespace']
sample_sets = args['sample_sets']
recovery_data = ... | [
"def",
"supervise_until_complete",
"(",
"monitor_data",
",",
"dependencies",
",",
"args",
",",
"recovery_file",
")",
":",
"project",
"=",
"args",
"[",
"'project'",
"]",
"workspace",
"=",
"args",
"[",
"'workspace'",
"]",
"namespace",
"=",
"args",
"[",
"'namespa... | Supervisor loop. Loop forever until all tasks are evaluated or completed | [
"Supervisor",
"loop",
".",
"Loop",
"forever",
"until",
"all",
"tasks",
"are",
"evaluated",
"or",
"completed"
] | python | train | 47.422535 |
ajenhl/tacl | tacl/cli/utils.py | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/cli/utils.py#L73-L87 | def configure_logging(verbose, logger):
"""Configures the logging used."""
if not verbose:
log_level = logging.WARNING
elif verbose == 1:
log_level = logging.INFO
else:
log_level = logging.DEBUG
logger.setLevel(log_level)
ch = colorlog.StreamHandler()
ch.setLevel(log_... | [
"def",
"configure_logging",
"(",
"verbose",
",",
"logger",
")",
":",
"if",
"not",
"verbose",
":",
"log_level",
"=",
"logging",
".",
"WARNING",
"elif",
"verbose",
"==",
"1",
":",
"log_level",
"=",
"logging",
".",
"INFO",
"else",
":",
"log_level",
"=",
"lo... | Configures the logging used. | [
"Configures",
"the",
"logging",
"used",
"."
] | python | train | 32.266667 |
jmurty/xml4h | xml4h/writer.py | https://github.com/jmurty/xml4h/blob/adbb45e27a01a869a505aee7bc16bad2f517b511/xml4h/writer.py#L12-L182 | def write_node(node, writer=None, encoding='utf-8', indent=0, newline='',
omit_declaration=False, node_depth=0, quote_char='"'):
"""
Serialize an *xml4h* DOM node and its descendants to text, writing
the output to a given *writer* or to stdout.
:param node: the DOM node whose content and descen... | [
"def",
"write_node",
"(",
"node",
",",
"writer",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
",",
"indent",
"=",
"0",
",",
"newline",
"=",
"''",
",",
"omit_declaration",
"=",
"False",
",",
"node_depth",
"=",
"0",
",",
"quote_char",
"=",
"'\"'",
")",
... | Serialize an *xml4h* DOM node and its descendants to text, writing
the output to a given *writer* or to stdout.
:param node: the DOM node whose content and descendants will
be serialized.
:type node: an :class:`xml4h.nodes.Node` or subclass
:param writer: an object such as a file or stream to w... | [
"Serialize",
"an",
"*",
"xml4h",
"*",
"DOM",
"node",
"and",
"its",
"descendants",
"to",
"text",
"writing",
"the",
"output",
"to",
"a",
"given",
"*",
"writer",
"*",
"or",
"to",
"stdout",
"."
] | python | train | 41.847953 |
googleads/googleads-python-lib | googleads/adwords.py | https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/googleads/adwords.py#L350-L370 | def GetReportDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1],
server=None):
"""Creates a downloader for AdWords reports.
This is a convenience method. It is functionally identical to calling
ReportDownloader(adwords_client, version, server).
Args:
[optional]
... | [
"def",
"GetReportDownloader",
"(",
"self",
",",
"version",
"=",
"sorted",
"(",
"_SERVICE_MAP",
".",
"keys",
"(",
")",
")",
"[",
"-",
"1",
"]",
",",
"server",
"=",
"None",
")",
":",
"if",
"not",
"server",
":",
"server",
"=",
"_DEFAULT_ENDPOINT",
"return... | Creates a downloader for AdWords reports.
This is a convenience method. It is functionally identical to calling
ReportDownloader(adwords_client, version, server).
Args:
[optional]
version: A string identifying the AdWords version to connect to. This
defaults to what is currently the ... | [
"Creates",
"a",
"downloader",
"for",
"AdWords",
"reports",
"."
] | python | train | 38.47619 |
pandas-dev/pandas | pandas/core/sparse/frame.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/sparse/frame.py#L963-L994 | def stack_sparse_frame(frame):
"""
Only makes sense when fill_value is NaN
"""
lengths = [s.sp_index.npoints for _, s in frame.items()]
nobs = sum(lengths)
# this is pretty fast
minor_codes = np.repeat(np.arange(len(frame.columns)), lengths)
inds_to_concat = []
vals_to_concat = []
... | [
"def",
"stack_sparse_frame",
"(",
"frame",
")",
":",
"lengths",
"=",
"[",
"s",
".",
"sp_index",
".",
"npoints",
"for",
"_",
",",
"s",
"in",
"frame",
".",
"items",
"(",
")",
"]",
"nobs",
"=",
"sum",
"(",
"lengths",
")",
"# this is pretty fast",
"minor_c... | Only makes sense when fill_value is NaN | [
"Only",
"makes",
"sense",
"when",
"fill_value",
"is",
"NaN"
] | python | train | 36.875 |
fastai/fastai | old/fastai/metrics.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/metrics.py#L48-L60 | def fbeta(log_preds, targs, beta, thresh=0.5, epsilon=1e-8):
"""Calculates the F-beta score (the weighted harmonic mean of precision and recall).
This is the micro averaged version where the true positives, false negatives and
false positives are calculated globally (as opposed to on a per label basis).
... | [
"def",
"fbeta",
"(",
"log_preds",
",",
"targs",
",",
"beta",
",",
"thresh",
"=",
"0.5",
",",
"epsilon",
"=",
"1e-8",
")",
":",
"assert",
"beta",
">",
"0",
",",
"'beta needs to be greater than 0'",
"beta2",
"=",
"beta",
"**",
"2",
"rec",
"=",
"recall",
... | Calculates the F-beta score (the weighted harmonic mean of precision and recall).
This is the micro averaged version where the true positives, false negatives and
false positives are calculated globally (as opposed to on a per label basis).
beta == 1 places equal weight on precision and recall, b < 1 empha... | [
"Calculates",
"the",
"F",
"-",
"beta",
"score",
"(",
"the",
"weighted",
"harmonic",
"mean",
"of",
"precision",
"and",
"recall",
")",
".",
"This",
"is",
"the",
"micro",
"averaged",
"version",
"where",
"the",
"true",
"positives",
"false",
"negatives",
"and",
... | python | train | 51.307692 |
Dentosal/python-sc2 | sc2/client.py | https://github.com/Dentosal/python-sc2/blob/608bd25f04e89d39cef68b40101d8e9a8a7f1634/sc2/client.py#L382-L384 | def debug_text_simple(self, text: str):
""" Draws a text in the top left corner of the screen (up to a max of 6 messages it seems). Don't forget to add 'await self._client.send_debug'. """
self._debug_texts.append(self.to_debug_message(text)) | [
"def",
"debug_text_simple",
"(",
"self",
",",
"text",
":",
"str",
")",
":",
"self",
".",
"_debug_texts",
".",
"append",
"(",
"self",
".",
"to_debug_message",
"(",
"text",
")",
")"
] | Draws a text in the top left corner of the screen (up to a max of 6 messages it seems). Don't forget to add 'await self._client.send_debug'. | [
"Draws",
"a",
"text",
"in",
"the",
"top",
"left",
"corner",
"of",
"the",
"screen",
"(",
"up",
"to",
"a",
"max",
"of",
"6",
"messages",
"it",
"seems",
")",
".",
"Don",
"t",
"forget",
"to",
"add",
"await",
"self",
".",
"_client",
".",
"send_debug",
"... | python | train | 85.333333 |
saltstack/salt | salt/modules/win_pki.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_pki.py#L186-L250 | def get_cert_file(name, cert_format=_DEFAULT_FORMAT, password=''):
'''
Get the details of the certificate file.
:param str name: The filesystem path of the certificate file.
:param str cert_format: The certificate format. Specify 'cer' for X.509, or
'pfx' for PKCS #12.
:param str password: ... | [
"def",
"get_cert_file",
"(",
"name",
",",
"cert_format",
"=",
"_DEFAULT_FORMAT",
",",
"password",
"=",
"''",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"cmd",
"=",
"list",
"(",
")",
"blacklist_keys",
"=",
"[",
"'DnsNameList'",
"]",
"cert_format",
"=",
"cert... | Get the details of the certificate file.
:param str name: The filesystem path of the certificate file.
:param str cert_format: The certificate format. Specify 'cer' for X.509, or
'pfx' for PKCS #12.
:param str password: The password of the certificate. Only applicable to pfx
format. Note th... | [
"Get",
"the",
"details",
"of",
"the",
"certificate",
"file",
"."
] | python | train | 37.984615 |
celiao/tmdbsimple | tmdbsimple/tv.py | https://github.com/celiao/tmdbsimple/blob/ff17893110c99771d6398a62c35d36dd9735f4b9/tmdbsimple/tv.py#L260-L277 | def on_the_air(self, **kwargs):
"""
Get the list of TV shows that are currently on the air. This query
looks for any TV show that has an episode with an air date in the
next 7 days.
Args:
page: (optional) Minimum 1, maximum 1000.
language: (optional) ISO ... | [
"def",
"on_the_air",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_get_path",
"(",
"'on_the_air'",
")",
"response",
"=",
"self",
".",
"_GET",
"(",
"path",
",",
"kwargs",
")",
"self",
".",
"_set_attrs_to_values",
"(",
"resp... | Get the list of TV shows that are currently on the air. This query
looks for any TV show that has an episode with an air date in the
next 7 days.
Args:
page: (optional) Minimum 1, maximum 1000.
language: (optional) ISO 639 code.
Returns:
A dict respr... | [
"Get",
"the",
"list",
"of",
"TV",
"shows",
"that",
"are",
"currently",
"on",
"the",
"air",
".",
"This",
"query",
"looks",
"for",
"any",
"TV",
"show",
"that",
"has",
"an",
"episode",
"with",
"an",
"air",
"date",
"in",
"the",
"next",
"7",
"days",
"."
] | python | test | 31.555556 |
limodou/ido | ido/__init__.py | https://github.com/limodou/ido/blob/7fcf5c20b47993b6c16eb6007f77ad1c868a6d68/ido/__init__.py#L544-L567 | def execute(self):
"""
Given the command-line arguments, this figures out which subcommand is
being run, creates a parser appropriate to that command, and runs it.
"""
# Preprocess options to extract --settings and --pythonpath.
# These options could affect the commands t... | [
"def",
"execute",
"(",
"self",
")",
":",
"# Preprocess options to extract --settings and --pythonpath.",
"# These options could affect the commands that are available, so they",
"# must be processed early.",
"parser",
"=",
"NewOptionParser",
"(",
"prog",
"=",
"self",
".",
"prog_nam... | Given the command-line arguments, this figures out which subcommand is
being run, creates a parser appropriate to that command, and runs it. | [
"Given",
"the",
"command",
"-",
"line",
"arguments",
"this",
"figures",
"out",
"which",
"subcommand",
"is",
"being",
"run",
"creates",
"a",
"parser",
"appropriate",
"to",
"that",
"command",
"and",
"runs",
"it",
"."
] | python | train | 42.125 |
softlayer/softlayer-python | SoftLayer/managers/hardware.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L822-L828 | def _get_location(package, location):
"""Get the longer key with a short location name."""
for region in package['regions']:
if region['location']['location']['name'] == location:
return region
raise SoftLayer.SoftLayerError("Could not find valid location for: '%s'" % location) | [
"def",
"_get_location",
"(",
"package",
",",
"location",
")",
":",
"for",
"region",
"in",
"package",
"[",
"'regions'",
"]",
":",
"if",
"region",
"[",
"'location'",
"]",
"[",
"'location'",
"]",
"[",
"'name'",
"]",
"==",
"location",
":",
"return",
"region"... | Get the longer key with a short location name. | [
"Get",
"the",
"longer",
"key",
"with",
"a",
"short",
"location",
"name",
"."
] | python | train | 43.571429 |
tensorflow/probability | tensorflow_probability/python/distributions/mixture_same_family.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/mixture_same_family.py#L542-L562 | def _value_and_batch_jacobian(f, x):
"""Enables uniform interface to value and batch jacobian calculation.
Works in both eager and graph modes.
Arguments:
f: The scalar function to evaluate.
x: The value at which to compute the value and the batch jacobian.
Returns:
A tuple (f(x), J(x)), where J(... | [
"def",
"_value_and_batch_jacobian",
"(",
"f",
",",
"x",
")",
":",
"if",
"tf",
".",
"executing_eagerly",
"(",
")",
":",
"with",
"tf",
".",
"GradientTape",
"(",
")",
"as",
"tape",
":",
"tape",
".",
"watch",
"(",
"x",
")",
"value",
"=",
"f",
"(",
"x",... | Enables uniform interface to value and batch jacobian calculation.
Works in both eager and graph modes.
Arguments:
f: The scalar function to evaluate.
x: The value at which to compute the value and the batch jacobian.
Returns:
A tuple (f(x), J(x)), where J(x) is the batch jacobian. | [
"Enables",
"uniform",
"interface",
"to",
"value",
"and",
"batch",
"jacobian",
"calculation",
"."
] | python | test | 28.47619 |
UDST/urbansim | urbansim/models/util.py | https://github.com/UDST/urbansim/blob/79f815a6503e109f50be270cee92d0f4a34f49ef/urbansim/models/util.py#L92-L126 | def filter_table(table, filter_series, ignore=None):
"""
Filter a table based on a set of restrictions given in
Series of column name / filter parameter pairs. The column
names can have suffixes `_min` and `_max` to indicate
"less than" and "greater than" constraints.
Parameters
----------
... | [
"def",
"filter_table",
"(",
"table",
",",
"filter_series",
",",
"ignore",
"=",
"None",
")",
":",
"with",
"log_start_finish",
"(",
"'filter table'",
",",
"logger",
")",
":",
"ignore",
"=",
"ignore",
"if",
"ignore",
"else",
"set",
"(",
")",
"filters",
"=",
... | Filter a table based on a set of restrictions given in
Series of column name / filter parameter pairs. The column
names can have suffixes `_min` and `_max` to indicate
"less than" and "greater than" constraints.
Parameters
----------
table : pandas.DataFrame
Table to filter.
filter_... | [
"Filter",
"a",
"table",
"based",
"on",
"a",
"set",
"of",
"restrictions",
"given",
"in",
"Series",
"of",
"column",
"name",
"/",
"filter",
"parameter",
"pairs",
".",
"The",
"column",
"names",
"can",
"have",
"suffixes",
"_min",
"and",
"_max",
"to",
"indicate"... | python | train | 36.6 |
spotify/luigi | luigi/contrib/mongodb.py | https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/mongodb.py#L38-L43 | def get_collection(self):
"""
Return targeted mongo collection to query on
"""
db_mongo = self._mongo_client[self._index]
return db_mongo[self._collection] | [
"def",
"get_collection",
"(",
"self",
")",
":",
"db_mongo",
"=",
"self",
".",
"_mongo_client",
"[",
"self",
".",
"_index",
"]",
"return",
"db_mongo",
"[",
"self",
".",
"_collection",
"]"
] | Return targeted mongo collection to query on | [
"Return",
"targeted",
"mongo",
"collection",
"to",
"query",
"on"
] | python | train | 31.666667 |
open511/open511 | open511/utils/schedule.py | https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/schedule.py#L36-L44 | def from_element(root, timezone):
"""Return a Schedule object based on an lxml Element for the <schedule>
tag. timezone is a tzinfo object, ideally from pytz."""
assert root.tag == 'schedule'
if root.xpath('intervals'):
return _ScheduleIntervals(root, timezone)
elif r... | [
"def",
"from_element",
"(",
"root",
",",
"timezone",
")",
":",
"assert",
"root",
".",
"tag",
"==",
"'schedule'",
"if",
"root",
".",
"xpath",
"(",
"'intervals'",
")",
":",
"return",
"_ScheduleIntervals",
"(",
"root",
",",
"timezone",
")",
"elif",
"root",
... | Return a Schedule object based on an lxml Element for the <schedule>
tag. timezone is a tzinfo object, ideally from pytz. | [
"Return",
"a",
"Schedule",
"object",
"based",
"on",
"an",
"lxml",
"Element",
"for",
"the",
"<schedule",
">",
"tag",
".",
"timezone",
"is",
"a",
"tzinfo",
"object",
"ideally",
"from",
"pytz",
"."
] | python | valid | 48.111111 |
pyQode/pyqode.core | pyqode/core/modes/pygments_sh.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/modes/pygments_sh.py#L207-L230 | def set_lexer_from_filename(self, filename):
"""
Change the lexer based on the filename (actually only the extension is
needed)
:param filename: Filename or extension
"""
self._lexer = None
if filename.endswith("~"):
filename = filename[0:len(filename... | [
"def",
"set_lexer_from_filename",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"_lexer",
"=",
"None",
"if",
"filename",
".",
"endswith",
"(",
"\"~\"",
")",
":",
"filename",
"=",
"filename",
"[",
"0",
":",
"len",
"(",
"filename",
")",
"-",
"1",
... | Change the lexer based on the filename (actually only the extension is
needed)
:param filename: Filename or extension | [
"Change",
"the",
"lexer",
"based",
"on",
"the",
"filename",
"(",
"actually",
"only",
"the",
"extension",
"is",
"needed",
")"
] | python | train | 40.333333 |
pysathq/pysat | examples/lbx.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/examples/lbx.py#L386-L431 | def do_cld_check(self, cld):
"""
Do the "clause :math:`D`" check. This method receives a list of
literals, which serves a "clause :math:`D`" [2]_, and checks
whether the formula conjoined with :math:`D` is satisfiable.
.. [2] Joao Marques-Silva, Federico Heras, M... | [
"def",
"do_cld_check",
"(",
"self",
",",
"cld",
")",
":",
"# adding a selector literal to clause D",
"# selector literals for clauses D currently",
"# cannot be reused, but this may change later",
"self",
".",
"topv",
"+=",
"1",
"sel",
"=",
"self",
".",
"topv",
"cld",
"."... | Do the "clause :math:`D`" check. This method receives a list of
literals, which serves a "clause :math:`D`" [2]_, and checks
whether the formula conjoined with :math:`D` is satisfiable.
.. [2] Joao Marques-Silva, Federico Heras, Mikolas Janota,
Alessandro Previti, An... | [
"Do",
"the",
"clause",
":",
"math",
":",
"D",
"check",
".",
"This",
"method",
"receives",
"a",
"list",
"of",
"literals",
"which",
"serves",
"a",
"clause",
":",
"math",
":",
"D",
"[",
"2",
"]",
"_",
"and",
"checks",
"whether",
"the",
"formula",
"conjo... | python | train | 41.673913 |
materialsproject/pymatgen | pymatgen/command_line/critic2_caller.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/command_line/critic2_caller.py#L196-L239 | def from_path(cls, path, suffix=''):
"""
Convenience method to run critic2 analysis on a folder containing
typical VASP output files.
This method will:
1. Look for files CHGCAR, AECAR0, AECAR2, POTCAR or their gzipped
counterparts.
2. If AECCAR* files are present,... | [
"def",
"from_path",
"(",
"cls",
",",
"path",
",",
"suffix",
"=",
"''",
")",
":",
"def",
"_get_filepath",
"(",
"filename",
",",
"warning",
",",
"path",
"=",
"path",
",",
"suffix",
"=",
"suffix",
")",
":",
"paths",
"=",
"glob",
".",
"glob",
"(",
"os"... | Convenience method to run critic2 analysis on a folder containing
typical VASP output files.
This method will:
1. Look for files CHGCAR, AECAR0, AECAR2, POTCAR or their gzipped
counterparts.
2. If AECCAR* files are present, constructs a temporary reference
file as AECCAR0... | [
"Convenience",
"method",
"to",
"run",
"critic2",
"analysis",
"on",
"a",
"folder",
"containing",
"typical",
"VASP",
"output",
"files",
".",
"This",
"method",
"will",
":",
"1",
".",
"Look",
"for",
"files",
"CHGCAR",
"AECAR0",
"AECAR2",
"POTCAR",
"or",
"their",... | python | train | 46.795455 |
senaite/senaite.core | bika/lims/browser/analysisrequest/add2.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/analysisrequest/add2.py#L133-L141 | def get_ar_count(self):
"""Return the ar_count request paramteter
"""
ar_count = 1
try:
ar_count = int(self.request.form.get("ar_count", 1))
except (TypeError, ValueError):
ar_count = 1
return ar_count | [
"def",
"get_ar_count",
"(",
"self",
")",
":",
"ar_count",
"=",
"1",
"try",
":",
"ar_count",
"=",
"int",
"(",
"self",
".",
"request",
".",
"form",
".",
"get",
"(",
"\"ar_count\"",
",",
"1",
")",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",... | Return the ar_count request paramteter | [
"Return",
"the",
"ar_count",
"request",
"paramteter"
] | python | train | 29.444444 |
chemlab/chemlab | chemlab/core/base.py | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/base.py#L446-L452 | def sub_dimension(self, index, dimension, propagate=True, inplace=False):
"""Return a ChemicalEntity sliced through a dimension.
If other dimensions depend on this one those are updated accordingly.
"""
filter_ = self._propagate_dim(index, dimension, propagate)
return se... | [
"def",
"sub_dimension",
"(",
"self",
",",
"index",
",",
"dimension",
",",
"propagate",
"=",
"True",
",",
"inplace",
"=",
"False",
")",
":",
"filter_",
"=",
"self",
".",
"_propagate_dim",
"(",
"index",
",",
"dimension",
",",
"propagate",
")",
"return",
"s... | Return a ChemicalEntity sliced through a dimension.
If other dimensions depend on this one those are updated accordingly. | [
"Return",
"a",
"ChemicalEntity",
"sliced",
"through",
"a",
"dimension",
".",
"If",
"other",
"dimensions",
"depend",
"on",
"this",
"one",
"those",
"are",
"updated",
"accordingly",
"."
] | python | train | 49 |
nirum/descent | descent/objectives.py | https://github.com/nirum/descent/blob/074c8452f15a0da638668a4fe139fde06ccfae7f/descent/objectives.py#L11-L40 | def objective(param_scales=(1, 1), xstar=None, seed=None):
"""Gives objective functions a number of dimensions and parameter range
Parameters
----------
param_scales : (int, int)
Scale (std. dev.) for choosing each parameter
xstar : array_like
Optimal parameters
"""
ndim = ... | [
"def",
"objective",
"(",
"param_scales",
"=",
"(",
"1",
",",
"1",
")",
",",
"xstar",
"=",
"None",
",",
"seed",
"=",
"None",
")",
":",
"ndim",
"=",
"len",
"(",
"param_scales",
")",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"fun... | Gives objective functions a number of dimensions and parameter range
Parameters
----------
param_scales : (int, int)
Scale (std. dev.) for choosing each parameter
xstar : array_like
Optimal parameters | [
"Gives",
"objective",
"functions",
"a",
"number",
"of",
"dimensions",
"and",
"parameter",
"range"
] | python | valid | 22.9 |
OpenTreeOfLife/peyotl | scripts/nexson/prune_to_clean_mapped.py | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/scripts/nexson/prune_to_clean_mapped.py#L305-L393 | def prune_tree_for_supertree(self,
ott,
to_prune_fsi_set,
root_ott_id,
taxonomy_treefile=None,
id_to_other_prune_reason=None):
"""
`to_prun... | [
"def",
"prune_tree_for_supertree",
"(",
"self",
",",
"ott",
",",
"to_prune_fsi_set",
",",
"root_ott_id",
",",
"taxonomy_treefile",
"=",
"None",
",",
"id_to_other_prune_reason",
"=",
"None",
")",
":",
"if",
"id_to_other_prune_reason",
"is",
"None",
":",
"id_to_other_... | `to_prune_fsi_set` is a set of flag indices to be pruned. | [
"to_prune_fsi_set",
"is",
"a",
"set",
"of",
"flag",
"indices",
"to",
"be",
"pruned",
"."
] | python | train | 48.067416 |
sorgerlab/indra | indra/sources/trips/client.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/sources/trips/client.py#L91-L114 | def save_xml(xml_str, file_name, pretty=True):
"""Save the TRIPS EKB XML in a file.
Parameters
----------
xml_str : str
The TRIPS EKB XML string to be saved.
file_name : str
The name of the file to save the result in.
pretty : Optional[bool]
If True, the XML is pretty pr... | [
"def",
"save_xml",
"(",
"xml_str",
",",
"file_name",
",",
"pretty",
"=",
"True",
")",
":",
"try",
":",
"fh",
"=",
"open",
"(",
"file_name",
",",
"'wt'",
")",
"except",
"IOError",
":",
"logger",
".",
"error",
"(",
"'Could not open %s for writing.'",
"%",
... | Save the TRIPS EKB XML in a file.
Parameters
----------
xml_str : str
The TRIPS EKB XML string to be saved.
file_name : str
The name of the file to save the result in.
pretty : Optional[bool]
If True, the XML is pretty printed. | [
"Save",
"the",
"TRIPS",
"EKB",
"XML",
"in",
"a",
"file",
"."
] | python | train | 27.166667 |
tensorflow/cleverhans | scripts/print_report.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/print_report.py#L43-L65 | def deprecated(report):
"""
The deprecated implementation of report printing.
:param report: dict
"""
warnings.warn("Printing dict-based reports is deprecated. This function "
"is included only to support a private development branch "
"and may be removed without warning.")
... | [
"def",
"deprecated",
"(",
"report",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Printing dict-based reports is deprecated. This function \"",
"\"is included only to support a private development branch \"",
"\"and may be removed without warning.\"",
")",
"for",
"key",
"in",
"report"... | The deprecated implementation of report printing.
:param report: dict | [
"The",
"deprecated",
"implementation",
"of",
"report",
"printing",
".",
":",
"param",
"report",
":",
"dict"
] | python | train | 42.565217 |
PMBio/limix-backup | limix/deprecated/archive/varianceDecompositionOld.py | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/deprecated/archive/varianceDecompositionOld.py#L675-L684 | def getLaplaceCovar(self):
"""
USES LAPLACE APPROXIMATION TO CALCULATE THE COVARIANCE MATRIX OF THE OPTIMIZED PARAMETERS
"""
assert self.init, 'GP not initialised'
assert self.fast==False, 'Not supported for fast implementation'
if self.cache['Sigma']==Non... | [
"def",
"getLaplaceCovar",
"(",
"self",
")",
":",
"assert",
"self",
".",
"init",
",",
"'GP not initialised'",
"assert",
"self",
".",
"fast",
"==",
"False",
",",
"'Not supported for fast implementation'",
"if",
"self",
".",
"cache",
"[",
"'Sigma'",
"]",
"==",
"N... | USES LAPLACE APPROXIMATION TO CALCULATE THE COVARIANCE MATRIX OF THE OPTIMIZED PARAMETERS | [
"USES",
"LAPLACE",
"APPROXIMATION",
"TO",
"CALCULATE",
"THE",
"COVARIANCE",
"MATRIX",
"OF",
"THE",
"OPTIMIZED",
"PARAMETERS"
] | python | train | 41.5 |
SBRG/ssbio | ssbio/pipeline/gempro.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/gempro.py#L341-L396 | def kegg_mapping_and_metadata(self, kegg_organism_code, custom_gene_mapping=None, outdir=None,
set_as_representative=False, force_rerun=False):
"""Map all genes in the model to KEGG IDs using the KEGG service.
Steps:
1. Download all metadata and sequence fi... | [
"def",
"kegg_mapping_and_metadata",
"(",
"self",
",",
"kegg_organism_code",
",",
"custom_gene_mapping",
"=",
"None",
",",
"outdir",
"=",
"None",
",",
"set_as_representative",
"=",
"False",
",",
"force_rerun",
"=",
"False",
")",
":",
"# First map all of the organism's ... | Map all genes in the model to KEGG IDs using the KEGG service.
Steps:
1. Download all metadata and sequence files in the sequences directory
2. Creates a KEGGProp object in the protein.sequences attribute
3. Returns a Pandas DataFrame of mapping results
Args:
... | [
"Map",
"all",
"genes",
"in",
"the",
"model",
"to",
"KEGG",
"IDs",
"using",
"the",
"KEGG",
"service",
"."
] | python | train | 51.857143 |
robehickman/simple-http-file-sync | shttpfs/storage.py | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/storage.py#L38-L47 | def new_backup(self, src):
""" Create a new backup file allocation """
backup_id_file = p.join(self.backup_dir, '.bk_idx')
backup_num = file_or_default(backup_id_file, 1, int)
backup_name = str(backup_num) + "_" + os.path.basename(src)
backup_num += 1
file_put_contents(... | [
"def",
"new_backup",
"(",
"self",
",",
"src",
")",
":",
"backup_id_file",
"=",
"p",
".",
"join",
"(",
"self",
".",
"backup_dir",
",",
"'.bk_idx'",
")",
"backup_num",
"=",
"file_or_default",
"(",
"backup_id_file",
",",
"1",
",",
"int",
")",
"backup_name",
... | Create a new backup file allocation | [
"Create",
"a",
"new",
"backup",
"file",
"allocation"
] | python | train | 39.5 |
PythonCharmers/python-future | src/future/backports/email/charset.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/charset.py#L303-L363 | def header_encode_lines(self, string, maxlengths):
"""Header-encode a string by converting it first to bytes.
This is similar to `header_encode()` except that the string is fit
into maximum line lengths as given by the argument.
:param string: A unicode string for the header. It must ... | [
"def",
"header_encode_lines",
"(",
"self",
",",
"string",
",",
"maxlengths",
")",
":",
"# See which encoding we should use.",
"codec",
"=",
"self",
".",
"output_codec",
"or",
"'us-ascii'",
"header_bytes",
"=",
"_encode",
"(",
"string",
",",
"codec",
")",
"encoder_... | Header-encode a string by converting it first to bytes.
This is similar to `header_encode()` except that the string is fit
into maximum line lengths as given by the argument.
:param string: A unicode string for the header. It must be possible
to encode this string to bytes using t... | [
"Header",
"-",
"encode",
"a",
"string",
"by",
"converting",
"it",
"first",
"to",
"bytes",
"."
] | python | train | 53.131148 |
helixyte/everest | everest/representers/mapping.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/representers/mapping.py#L217-L229 | def create_linked_data_element(self, url, kind, id=None, # pylint: disable=W0622
relation=None, title=None):
"""
Returns a new linked data element for the given url and kind.
:param str url: URL to assign to the linked data element.
:param str kind: ki... | [
"def",
"create_linked_data_element",
"(",
"self",
",",
"url",
",",
"kind",
",",
"id",
"=",
"None",
",",
"# pylint: disable=W0622",
"relation",
"=",
"None",
",",
"title",
"=",
"None",
")",
":",
"mp",
"=",
"self",
".",
"__mp_reg",
".",
"find_or_create_mapping"... | Returns a new linked data element for the given url and kind.
:param str url: URL to assign to the linked data element.
:param str kind: kind of the resource that is linked. One of the
constantes defined by :class:`everest.constants.RESOURCE_KINDS`.
:returns: object implementing :clas... | [
"Returns",
"a",
"new",
"linked",
"data",
"element",
"for",
"the",
"given",
"url",
"and",
"kind",
"."
] | python | train | 53.923077 |
mlperf/training | translation/data_download.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/data_download.py#L146-L185 | def download_and_extract(path, url, input_filename, target_filename):
"""Extract files from downloaded compressed archive file.
Args:
path: string directory where the files will be downloaded
url: url containing the compressed input and target files
input_filename: name of file containing data in sourc... | [
"def",
"download_and_extract",
"(",
"path",
",",
"url",
",",
"input_filename",
",",
"target_filename",
")",
":",
"logging",
".",
"info",
"(",
"'Downloading and extracting data to: %s'",
"%",
"path",
")",
"# Check if extracted files already exist in path",
"input_file",
"=... | Extract files from downloaded compressed archive file.
Args:
path: string directory where the files will be downloaded
url: url containing the compressed input and target files
input_filename: name of file containing data in source language
target_filename: name of file containing data in target lang... | [
"Extract",
"files",
"from",
"downloaded",
"compressed",
"archive",
"file",
"."
] | python | train | 35.55 |
aws/sagemaker-python-sdk | src/sagemaker/tensorflow/estimator.py | https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/tensorflow/estimator.py#L66-L92 | def _sync_directories(from_directory, to_directory):
"""Sync to_directory with from_directory by copying each file in
to_directory with new contents. Files in to_directory will be
overwritten by files of the same name in from_directory. We need to
keep two copies of the log directory bec... | [
"def",
"_sync_directories",
"(",
"from_directory",
",",
"to_directory",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"to_directory",
")",
":",
"os",
".",
"mkdir",
"(",
"to_directory",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
... | Sync to_directory with from_directory by copying each file in
to_directory with new contents. Files in to_directory will be
overwritten by files of the same name in from_directory. We need to
keep two copies of the log directory because otherwise TensorBoard
picks up temp files from `aws... | [
"Sync",
"to_directory",
"with",
"from_directory",
"by",
"copying",
"each",
"file",
"in",
"to_directory",
"with",
"new",
"contents",
".",
"Files",
"in",
"to_directory",
"will",
"be",
"overwritten",
"by",
"files",
"of",
"the",
"same",
"name",
"in",
"from_directory... | python | train | 50.814815 |
JNRowe/jnrbase | jnrbase/template.py | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/template.py#L119-L128 | def regexp(__string: str, __pattern: str, __repl: Union[Callable, str], *,
count: int = 0, flags: int = 0) -> str:
"""Jinja filter for regexp replacements.
See :func:`re.sub` for documentation.
Returns:
Text with substitutions applied
"""
return re.sub(__pattern, __repl, __strin... | [
"def",
"regexp",
"(",
"__string",
":",
"str",
",",
"__pattern",
":",
"str",
",",
"__repl",
":",
"Union",
"[",
"Callable",
",",
"str",
"]",
",",
"*",
",",
"count",
":",
"int",
"=",
"0",
",",
"flags",
":",
"int",
"=",
"0",
")",
"->",
"str",
":",
... | Jinja filter for regexp replacements.
See :func:`re.sub` for documentation.
Returns:
Text with substitutions applied | [
"Jinja",
"filter",
"for",
"regexp",
"replacements",
"."
] | python | train | 32.7 |
Opentrons/opentrons | api/src/opentrons/legacy_api/modules/magdeck.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/modules/magdeck.py#L38-L65 | def engage(self, **kwargs):
'''
Move the magnet to either:
the default height for the labware loaded on magdeck
[engage()]
or a +/- 'offset' from the default height for the labware
[engage(offset=2)]
or a 'height' value specified as mm from magdeck h... | [
"def",
"engage",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'height'",
"in",
"kwargs",
":",
"height",
"=",
"kwargs",
".",
"get",
"(",
"'height'",
")",
"else",
":",
"height",
"=",
"LABWARE_ENGAGE_HEIGHT",
".",
"get",
"(",
"self",
".",
"lab... | Move the magnet to either:
the default height for the labware loaded on magdeck
[engage()]
or a +/- 'offset' from the default height for the labware
[engage(offset=2)]
or a 'height' value specified as mm from magdeck home position
[engage(height=20)] | [
"Move",
"the",
"magnet",
"to",
"either",
":",
"the",
"default",
"height",
"for",
"the",
"labware",
"loaded",
"on",
"magdeck",
"[",
"engage",
"()",
"]",
"or",
"a",
"+",
"/",
"-",
"offset",
"from",
"the",
"default",
"height",
"for",
"the",
"labware",
"["... | python | train | 42.392857 |
hydraplatform/hydra-base | hydra_base/lib/units.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/units.py#L233-L242 | def get_unit(unit_id, **kwargs):
"""
Returns a single unit
"""
try:
unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one()
return JSONObject(unit)
except NoResultFound:
# The dimension does not exist
raise ResourceNotFoundError("Unit %s not found"%(unit_id... | [
"def",
"get_unit",
"(",
"unit_id",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"unit",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Unit",
")",
".",
"filter",
"(",
"Unit",
".",
"id",
"==",
"unit_id",
")",
".",
"one",
"(",
")",
"return",
... | Returns a single unit | [
"Returns",
"a",
"single",
"unit"
] | python | train | 31.3 |
LuqueDaniel/pybooru | pybooru/api_danbooru.py | https://github.com/LuqueDaniel/pybooru/blob/60cd5254684d293b308f0b11b8f4ac2dce101479/pybooru/api_danbooru.py#L1292-L1300 | def forum_post_create(self, topic_id, body):
"""Create a forum post (Requires login).
Parameters:
topic_id (int):
body (str): Post content.
"""
params = {'forum_post[topic_id]': topic_id, 'forum_post[body]': body}
return self._get('forum_posts.json', para... | [
"def",
"forum_post_create",
"(",
"self",
",",
"topic_id",
",",
"body",
")",
":",
"params",
"=",
"{",
"'forum_post[topic_id]'",
":",
"topic_id",
",",
"'forum_post[body]'",
":",
"body",
"}",
"return",
"self",
".",
"_get",
"(",
"'forum_posts.json'",
",",
"params"... | Create a forum post (Requires login).
Parameters:
topic_id (int):
body (str): Post content. | [
"Create",
"a",
"forum",
"post",
"(",
"Requires",
"login",
")",
"."
] | python | train | 37.888889 |
saltstack/salt | salt/cloud/clouds/proxmox.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L149-L196 | def query(conn_type, option, post_data=None):
'''
Execute the HTTP request to the API
'''
if ticket is None or csrf is None or url is None:
log.debug('Not authenticated yet, doing that now..')
_authenticate()
full_url = 'https://{0}:{1}/api2/json/{2}'.format(url, port, option)
... | [
"def",
"query",
"(",
"conn_type",
",",
"option",
",",
"post_data",
"=",
"None",
")",
":",
"if",
"ticket",
"is",
"None",
"or",
"csrf",
"is",
"None",
"or",
"url",
"is",
"None",
":",
"log",
".",
"debug",
"(",
"'Not authenticated yet, doing that now..'",
")",
... | Execute the HTTP request to the API | [
"Execute",
"the",
"HTTP",
"request",
"to",
"the",
"API"
] | python | train | 38.270833 |
jadolg/rocketchat_API | rocketchat_API/rocketchat.py | https://github.com/jadolg/rocketchat_API/blob/f220d094434991cb9892418245f054ea06f28aad/rocketchat_API/rocketchat.py#L687-L689 | def subscriptions_unread(self, room_id, **kwargs):
"""Mark messages as unread by roomId or from a message"""
return self.__call_api_post('subscriptions.unread', roomId=room_id, kwargs=kwargs) | [
"def",
"subscriptions_unread",
"(",
"self",
",",
"room_id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'subscriptions.unread'",
",",
"roomId",
"=",
"room_id",
",",
"kwargs",
"=",
"kwargs",
")"
] | Mark messages as unread by roomId or from a message | [
"Mark",
"messages",
"as",
"unread",
"by",
"roomId",
"or",
"from",
"a",
"message"
] | python | train | 68.333333 |
agile-geoscience/striplog | striplog/legend.py | https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/legend.py#L696-L726 | def get_decor(self, c, match_only=None):
"""
Get the decor for a component.
Args:
c (component): The component to look up.
match_only (list of str): The component attributes to include in the
comparison. Default: All of them.
Returns:
Dec... | [
"def",
"get_decor",
"(",
"self",
",",
"c",
",",
"match_only",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"c",
",",
"Component",
")",
":",
"if",
"c",
":",
"if",
"match_only",
":",
"# Filter the component only those attributes",
"c",
"=",
"Component",
"... | Get the decor for a component.
Args:
c (component): The component to look up.
match_only (list of str): The component attributes to include in the
comparison. Default: All of them.
Returns:
Decor. The matching Decor from the Legend, or None if not found. | [
"Get",
"the",
"decor",
"for",
"a",
"component",
"."
] | python | test | 37.225806 |
SeanOC/sharpy | sharpy/product.py | https://github.com/SeanOC/sharpy/blob/935943ca86034255f0a93c1a84734814be176ed4/sharpy/product.py#L482-L505 | def charge(self, code, each_amount, quantity=1, description=None):
'''
Add an arbitrary charge or credit to a customer's account. A positive
number will create a charge. A negative number will create a credit.
each_amount is normalized to a Decimal with a precision of 2 as tha... | [
"def",
"charge",
"(",
"self",
",",
"code",
",",
"each_amount",
",",
"quantity",
"=",
"1",
",",
"description",
"=",
"None",
")",
":",
"each_amount",
"=",
"Decimal",
"(",
"each_amount",
")",
"each_amount",
"=",
"each_amount",
".",
"quantize",
"(",
"Decimal",... | Add an arbitrary charge or credit to a customer's account. A positive
number will create a charge. A negative number will create a credit.
each_amount is normalized to a Decimal with a precision of 2 as that
is the level of precision which the cheddar API supports. | [
"Add",
"an",
"arbitrary",
"charge",
"or",
"credit",
"to",
"a",
"customer",
"s",
"account",
".",
"A",
"positive",
"number",
"will",
"create",
"a",
"charge",
".",
"A",
"negative",
"number",
"will",
"create",
"a",
"credit",
".",
"each_amount",
"is",
"normaliz... | python | train | 38.416667 |
eng-tools/geofound | geofound/stiffness.py | https://github.com/eng-tools/geofound/blob/6b1b097d5db998907bdcb5b4798fb4629674c770/geofound/stiffness.py#L4-L29 | def rotational_stiffness(sl, fd, axis="length", a0=0.0, **kwargs):
"""
Rotation stiffness of foundation.
:param fd: Foundation object
:param sl: Soil Object.
:param axis: The axis which it should be computed around
:return:
"""
if not kwargs.get("disable_requires", False):
gf.mod... | [
"def",
"rotational_stiffness",
"(",
"sl",
",",
"fd",
",",
"axis",
"=",
"\"length\"",
",",
"a0",
"=",
"0.0",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
".",
"get",
"(",
"\"disable_requires\"",
",",
"False",
")",
":",
"gf",
".",
"models"... | Rotation stiffness of foundation.
:param fd: Foundation object
:param sl: Soil Object.
:param axis: The axis which it should be computed around
:return: | [
"Rotation",
"stiffness",
"of",
"foundation",
".",
":",
"param",
"fd",
":",
"Foundation",
"object",
":",
"param",
"sl",
":",
"Soil",
"Object",
".",
":",
"param",
"axis",
":",
"The",
"axis",
"which",
"it",
"should",
"be",
"computed",
"around",
":",
"return... | python | test | 33.115385 |
HacKanCuBa/passphrase-py | passphrase/passphrase.py | https://github.com/HacKanCuBa/passphrase-py/blob/219d6374338ed9a1475b4f09b0d85212376f11e0/passphrase/passphrase.py#L473-L488 | def generate_password(self) -> list:
"""Generate a list of random characters."""
characterset = self._get_password_characters()
if (
self.passwordlen is None
or not characterset
):
raise ValueError("Can't generate password: character set is "
... | [
"def",
"generate_password",
"(",
"self",
")",
"->",
"list",
":",
"characterset",
"=",
"self",
".",
"_get_password_characters",
"(",
")",
"if",
"(",
"self",
".",
"passwordlen",
"is",
"None",
"or",
"not",
"characterset",
")",
":",
"raise",
"ValueError",
"(",
... | Generate a list of random characters. | [
"Generate",
"a",
"list",
"of",
"random",
"characters",
"."
] | python | train | 34.3125 |
ArchiveTeam/wpull | wpull/util.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/util.py#L64-L73 | def seek_file_end(file):
'''Seek to the end of the file.'''
try:
file.seek(0, 2)
except ValueError:
# gzip files don't support seek from end
while True:
data = file.read(4096)
if not data:
break | [
"def",
"seek_file_end",
"(",
"file",
")",
":",
"try",
":",
"file",
".",
"seek",
"(",
"0",
",",
"2",
")",
"except",
"ValueError",
":",
"# gzip files don't support seek from end",
"while",
"True",
":",
"data",
"=",
"file",
".",
"read",
"(",
"4096",
")",
"i... | Seek to the end of the file. | [
"Seek",
"to",
"the",
"end",
"of",
"the",
"file",
"."
] | python | train | 26.1 |
yhat/db.py | db/db.py | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/db.py#L809-L854 | def refresh_schema(self, exclude_system_tables=True, use_cache=False):
"""
Pulls your database's schema again and looks for any new tables and
columns.
"""
col_meta, table_meta = self._get_db_metadata(exclude_system_tables, use_cache)
tables = self._gen_tables_from_col_t... | [
"def",
"refresh_schema",
"(",
"self",
",",
"exclude_system_tables",
"=",
"True",
",",
"use_cache",
"=",
"False",
")",
":",
"col_meta",
",",
"table_meta",
"=",
"self",
".",
"_get_db_metadata",
"(",
"exclude_system_tables",
",",
"use_cache",
")",
"tables",
"=",
... | Pulls your database's schema again and looks for any new tables and
columns. | [
"Pulls",
"your",
"database",
"s",
"schema",
"again",
"and",
"looks",
"for",
"any",
"new",
"tables",
"and",
"columns",
"."
] | python | train | 55.782609 |
pydsigner/pygu | pygu/pygw.py | https://github.com/pydsigner/pygu/blob/09fe71534900933908ab83db12f5659b7827e31c/pygu/pygw.py#L490-L496 | def insert(self, s):
'''
Insert string @s at the current cursor location.
'''
for c in s:
self.text.insert(self.cursor_loc, c)
self.cursor_loc += 1 | [
"def",
"insert",
"(",
"self",
",",
"s",
")",
":",
"for",
"c",
"in",
"s",
":",
"self",
".",
"text",
".",
"insert",
"(",
"self",
".",
"cursor_loc",
",",
"c",
")",
"self",
".",
"cursor_loc",
"+=",
"1"
] | Insert string @s at the current cursor location. | [
"Insert",
"string"
] | python | train | 28.142857 |
dade-ai/snipy | snipy/enum.py | https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/enum.py#L26-L37 | def enum(name, *members, **withvalue):
"""class buider"""
if len(members) == 1:
if isinstance(members[0], str):
members = members[0].split()
elif isinstance(members[0], (list, tuple)):
members = members[0]
dic = {v: v for v in members}
dic.update(withvalue)
... | [
"def",
"enum",
"(",
"name",
",",
"*",
"members",
",",
"*",
"*",
"withvalue",
")",
":",
"if",
"len",
"(",
"members",
")",
"==",
"1",
":",
"if",
"isinstance",
"(",
"members",
"[",
"0",
"]",
",",
"str",
")",
":",
"members",
"=",
"members",
"[",
"0... | class buider | [
"class",
"buider"
] | python | valid | 28.333333 |
limodou/uliweb | uliweb/lib/werkzeug/wsgi.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wsgi.py#L85-L119 | def host_is_trusted(hostname, trusted_list):
"""Checks if a host is trusted against a list. This also takes care
of port normalization.
.. versionadded:: 0.9
:param hostname: the hostname to check
:param trusted_list: a list of hostnames to check against. If a
hostname s... | [
"def",
"host_is_trusted",
"(",
"hostname",
",",
"trusted_list",
")",
":",
"if",
"not",
"hostname",
":",
"return",
"False",
"if",
"isinstance",
"(",
"trusted_list",
",",
"string_types",
")",
":",
"trusted_list",
"=",
"[",
"trusted_list",
"]",
"def",
"_normalize... | Checks if a host is trusted against a list. This also takes care
of port normalization.
.. versionadded:: 0.9
:param hostname: the hostname to check
:param trusted_list: a list of hostnames to check against. If a
hostname starts with a dot it will match against
... | [
"Checks",
"if",
"a",
"host",
"is",
"trusted",
"against",
"a",
"list",
".",
"This",
"also",
"takes",
"care",
"of",
"port",
"normalization",
"."
] | python | train | 29.714286 |
tanghaibao/goatools | goatools/gosubdag/go_tasks.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/go_tasks.py#L118-L126 | def fill_main_goids(go2obj, goids):
"""Ensure main GO IDs are included in go2obj."""
# User GO IDs (goids) may be either main GO IDs or alternate GO IDs.
for goid in goids:
goobj = go2obj[goid]
# If a user specified an ALT GO ID and main GO ID not in go2obj:
if goid != goobj.id and g... | [
"def",
"fill_main_goids",
"(",
"go2obj",
",",
"goids",
")",
":",
"# User GO IDs (goids) may be either main GO IDs or alternate GO IDs.",
"for",
"goid",
"in",
"goids",
":",
"goobj",
"=",
"go2obj",
"[",
"goid",
"]",
"# If a user specified an ALT GO ID and main GO ID not in go2o... | Ensure main GO IDs are included in go2obj. | [
"Ensure",
"main",
"GO",
"IDs",
"are",
"included",
"in",
"go2obj",
"."
] | python | train | 45.555556 |
feliphebueno/Rinzler | rinzler/__init__.py | https://github.com/feliphebueno/Rinzler/blob/7f6d5445b5662cba2e8938bb82c7f3ef94e5ded8/rinzler/__init__.py#L377-L388 | def get_json_ident(request_headers: dict) -> int:
"""
Defines whether the JSON response will be indented or not
:param request_headers: dict
:return: self
"""
if 'HTTP_USER_AGENT' in request_headers:
indent = 2 if re.match("[Mozilla]{7}", request_headers['HTTP... | [
"def",
"get_json_ident",
"(",
"request_headers",
":",
"dict",
")",
"->",
"int",
":",
"if",
"'HTTP_USER_AGENT'",
"in",
"request_headers",
":",
"indent",
"=",
"2",
"if",
"re",
".",
"match",
"(",
"\"[Mozilla]{7}\"",
",",
"request_headers",
"[",
"'HTTP_USER_AGENT'",... | Defines whether the JSON response will be indented or not
:param request_headers: dict
:return: self | [
"Defines",
"whether",
"the",
"JSON",
"response",
"will",
"be",
"indented",
"or",
"not",
":",
"param",
"request_headers",
":",
"dict",
":",
"return",
":",
"self"
] | python | train | 32.5 |
Tanganelli/CoAPthon3 | coapthon/messages/request.py | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L113-L123 | def accept(self, value):
"""
Add an Accept option to a request.
:param value: the Accept value
"""
if value in list(defines.Content_types.values()):
option = Option()
option.number = defines.OptionRegistry.ACCEPT.number
option.value = value
... | [
"def",
"accept",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"list",
"(",
"defines",
".",
"Content_types",
".",
"values",
"(",
")",
")",
":",
"option",
"=",
"Option",
"(",
")",
"option",
".",
"number",
"=",
"defines",
".",
"OptionRegist... | Add an Accept option to a request.
:param value: the Accept value | [
"Add",
"an",
"Accept",
"option",
"to",
"a",
"request",
"."
] | python | train | 31.181818 |
xeroc/python-graphenelib | graphenecommon/message.py | https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/message.py#L112-L190 | def verify(self, **kwargs):
""" Verify a message with an account's memo key
:param str account: (optional) the account that owns the bet
(defaults to ``default_account``)
:returns: True if the message is verified successfully
:raises InvalidMessageSignature ... | [
"def",
"verify",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Split message into its parts",
"parts",
"=",
"re",
".",
"split",
"(",
"\"|\"",
".",
"join",
"(",
"self",
".",
"MESSAGE_SPLIT",
")",
",",
"self",
".",
"message",
")",
"parts",
"=",
"[",... | Verify a message with an account's memo key
:param str account: (optional) the account that owns the bet
(defaults to ``default_account``)
:returns: True if the message is verified successfully
:raises InvalidMessageSignature if the signature is not ok | [
"Verify",
"a",
"message",
"with",
"an",
"account",
"s",
"memo",
"key"
] | python | valid | 38.240506 |
CityOfZion/neo-python | neo/Core/State/ValidatorState.py | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/ValidatorState.py#L40-L50 | def Deserialize(self, reader: BinaryReader):
"""
Deserialize full object.
Args:
reader (neocore.IO.BinaryReader):
"""
super(ValidatorState, self).Deserialize(reader)
self.PublicKey = ECDSA.Deserialize_Secp256r1(reader)
self.Registered = reader.ReadBoo... | [
"def",
"Deserialize",
"(",
"self",
",",
"reader",
":",
"BinaryReader",
")",
":",
"super",
"(",
"ValidatorState",
",",
"self",
")",
".",
"Deserialize",
"(",
"reader",
")",
"self",
".",
"PublicKey",
"=",
"ECDSA",
".",
"Deserialize_Secp256r1",
"(",
"reader",
... | Deserialize full object.
Args:
reader (neocore.IO.BinaryReader): | [
"Deserialize",
"full",
"object",
"."
] | python | train | 32.181818 |
alexras/bread | bread/utils.py | https://github.com/alexras/bread/blob/2e131380878c07500167fc12685e7bff1df258a4/bread/utils.py#L1-L10 | def indent_text(string, indent_level=2):
"""Indent every line of text in a newline-delimited string"""
indented_lines = []
indent_spaces = ' ' * indent_level
for line in string.split('\n'):
indented_lines.append(indent_spaces + line)
return '\n'.join(indented_lines) | [
"def",
"indent_text",
"(",
"string",
",",
"indent_level",
"=",
"2",
")",
":",
"indented_lines",
"=",
"[",
"]",
"indent_spaces",
"=",
"' '",
"*",
"indent_level",
"for",
"line",
"in",
"string",
".",
"split",
"(",
"'\\n'",
")",
":",
"indented_lines",
".",
"... | Indent every line of text in a newline-delimited string | [
"Indent",
"every",
"line",
"of",
"text",
"in",
"a",
"newline",
"-",
"delimited",
"string"
] | python | train | 28.8 |
ellmetha/django-machina | machina/apps/forum_moderation/views.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum_moderation/views.py#L158-L160 | def perform_permissions_check(self, user, obj, perms):
""" Performs the permissions check. """
return self.request.forum_permission_handler.can_delete_topics(obj, user) | [
"def",
"perform_permissions_check",
"(",
"self",
",",
"user",
",",
"obj",
",",
"perms",
")",
":",
"return",
"self",
".",
"request",
".",
"forum_permission_handler",
".",
"can_delete_topics",
"(",
"obj",
",",
"user",
")"
] | Performs the permissions check. | [
"Performs",
"the",
"permissions",
"check",
"."
] | python | train | 60.666667 |
Cog-Creators/Red-Lavalink | lavalink/player_manager.py | https://github.com/Cog-Creators/Red-Lavalink/blob/5b3fc6eb31ee5db8bd2b633a523cf69749957111/lavalink/player_manager.py#L214-L224 | async def handle_player_update(self, state: "node.PlayerState"):
"""
Handles player updates from lavalink.
Parameters
----------
state : websocket.PlayerState
"""
if state.position > self.position:
self._is_playing = True
self.position = state... | [
"async",
"def",
"handle_player_update",
"(",
"self",
",",
"state",
":",
"\"node.PlayerState\"",
")",
":",
"if",
"state",
".",
"position",
">",
"self",
".",
"position",
":",
"self",
".",
"_is_playing",
"=",
"True",
"self",
".",
"position",
"=",
"state",
"."... | Handles player updates from lavalink.
Parameters
----------
state : websocket.PlayerState | [
"Handles",
"player",
"updates",
"from",
"lavalink",
"."
] | python | train | 29 |
theislab/scanpy | scanpy/plotting/_anndata.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/plotting/_anndata.py#L244-L499 | def _scatter_obs(
adata,
x=None,
y=None,
color=None,
use_raw=None,
layers='X',
sort_order=True,
alpha=None,
basis=None,
groups=None,
components=None,
projection='2d',
legend_loc='right margin',
legend_fontsiz... | [
"def",
"_scatter_obs",
"(",
"adata",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"color",
"=",
"None",
",",
"use_raw",
"=",
"None",
",",
"layers",
"=",
"'X'",
",",
"sort_order",
"=",
"True",
",",
"alpha",
"=",
"None",
",",
"basis",
"=",
"N... | See docstring of scatter. | [
"See",
"docstring",
"of",
"scatter",
"."
] | python | train | 42.035156 |
ellmetha/neojsonrpc | neojsonrpc/utils.py | https://github.com/ellmetha/neojsonrpc/blob/e369b633a727482d5f9e310f0c3337ae5f7265db/neojsonrpc/utils.py#L16-L20 | def is_hash256(s):
""" Returns True if the considered string is a valid SHA256 hash. """
if not s or not isinstance(s, str):
return False
return re.match('^[0-9A-F]{64}$', s.strip(), re.IGNORECASE) | [
"def",
"is_hash256",
"(",
"s",
")",
":",
"if",
"not",
"s",
"or",
"not",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"return",
"False",
"return",
"re",
".",
"match",
"(",
"'^[0-9A-F]{64}$'",
",",
"s",
".",
"strip",
"(",
")",
",",
"re",
".",
"IGN... | Returns True if the considered string is a valid SHA256 hash. | [
"Returns",
"True",
"if",
"the",
"considered",
"string",
"is",
"a",
"valid",
"SHA256",
"hash",
"."
] | python | test | 42.6 |
CGATOxford/UMI-tools | umi_tools/sam_methods.py | https://github.com/CGATOxford/UMI-tools/blob/c4b5d84aac391d59916d294f8f4f8f5378abcfbe/umi_tools/sam_methods.py#L597-L613 | def write_mates(self):
'''Scan the current chromosome for matches to any of the reads stored
in the read1s buffer'''
if self.chrom is not None:
U.debug("Dumping %i mates for contig %s" % (
len(self.read1s), self.chrom))
for read in self.infile.fetch(reference... | [
"def",
"write_mates",
"(",
"self",
")",
":",
"if",
"self",
".",
"chrom",
"is",
"not",
"None",
":",
"U",
".",
"debug",
"(",
"\"Dumping %i mates for contig %s\"",
"%",
"(",
"len",
"(",
"self",
".",
"read1s",
")",
",",
"self",
".",
"chrom",
")",
")",
"f... | Scan the current chromosome for matches to any of the reads stored
in the read1s buffer | [
"Scan",
"the",
"current",
"chromosome",
"for",
"matches",
"to",
"any",
"of",
"the",
"reads",
"stored",
"in",
"the",
"read1s",
"buffer"
] | python | train | 41 |
tdryer/hangups | hangups/channel.py | https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/channel.py#L241-L260 | async def _fetch_channel_sid(self):
"""Creates a new channel for receiving push data.
Sending an empty forward channel request will create a new channel on
the server.
There's a separate API to get the gsessionid alone that Hangouts for
Chrome uses, but if we don't send a gsess... | [
"async",
"def",
"_fetch_channel_sid",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Requesting new gsessionid and SID...'",
")",
"# Set SID and gsessionid to None so they aren't sent in by send_maps.",
"self",
".",
"_sid_param",
"=",
"None",
"self",
".",
"_gsessionid... | Creates a new channel for receiving push data.
Sending an empty forward channel request will create a new channel on
the server.
There's a separate API to get the gsessionid alone that Hangouts for
Chrome uses, but if we don't send a gsessionid with this request, it
will return... | [
"Creates",
"a",
"new",
"channel",
"for",
"receiving",
"push",
"data",
"."
] | python | valid | 46.15 |
matthewdeanmartin/jiggle_version | jiggle_version/module_finder.py | https://github.com/matthewdeanmartin/jiggle_version/blob/963656a0a47b7162780a5f6c8f4b8bbbebc148f5/jiggle_version/module_finder.py#L84-L93 | def setup_py_source(self): # type: () -> Optional[str]
"""
Read setup.py to string
:return:
"""
if not self.setup_source:
self.setup_source = self._read_file("setup.py")
if not self.setup_source:
self.setup_source = self._read_file("setup") # rar... | [
"def",
"setup_py_source",
"(",
"self",
")",
":",
"# type: () -> Optional[str]",
"if",
"not",
"self",
".",
"setup_source",
":",
"self",
".",
"setup_source",
"=",
"self",
".",
"_read_file",
"(",
"\"setup.py\"",
")",
"if",
"not",
"self",
".",
"setup_source",
":",... | Read setup.py to string
:return: | [
"Read",
"setup",
".",
"py",
"to",
"string",
":",
"return",
":"
] | python | train | 35 |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1264-L1280 | def run(self):
"""Begin serving. Returns the bound port, or 0 for domain socket."""
self._listening_sock, self._address = (
bind_domain_socket(self._address)
if self._uds_path
else bind_tcp_socket(self._address))
if self._ssl:
certfile = os.path.j... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_listening_sock",
",",
"self",
".",
"_address",
"=",
"(",
"bind_domain_socket",
"(",
"self",
".",
"_address",
")",
"if",
"self",
".",
"_uds_path",
"else",
"bind_tcp_socket",
"(",
"self",
".",
"_address",
... | Begin serving. Returns the bound port, or 0 for domain socket. | [
"Begin",
"serving",
".",
"Returns",
"the",
"bound",
"port",
"or",
"0",
"for",
"domain",
"socket",
"."
] | python | train | 40.235294 |
quantopian/serializable-traitlets | straitlets/serializable.py | https://github.com/quantopian/serializable-traitlets/blob/dd334366d1130825aea55d3dfecd6756973594e0/straitlets/serializable.py#L219-L228 | def to_base64(self, skip=()):
"""
Construct from base64-encoded JSON.
"""
return base64.b64encode(
ensure_bytes(
self.to_json(skip=skip),
encoding='utf-8',
)
) | [
"def",
"to_base64",
"(",
"self",
",",
"skip",
"=",
"(",
")",
")",
":",
"return",
"base64",
".",
"b64encode",
"(",
"ensure_bytes",
"(",
"self",
".",
"to_json",
"(",
"skip",
"=",
"skip",
")",
",",
"encoding",
"=",
"'utf-8'",
",",
")",
")"
] | Construct from base64-encoded JSON. | [
"Construct",
"from",
"base64",
"-",
"encoded",
"JSON",
"."
] | python | train | 24.6 |
awacha/credolib | credolib/atsas.py | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/atsas.py#L371-L428 | def datcmp(*curves, alpha=None, adjust=None, test='CORMAP'):
"""Run datcmp on the scattering curves.
Inputs:
*curves: scattering curves as positional arguments
alpha: confidence parameter
adjust: adjustment type (string), see the help of datcmp for details
test: test (string), s... | [
"def",
"datcmp",
"(",
"*",
"curves",
",",
"alpha",
"=",
"None",
",",
"adjust",
"=",
"None",
",",
"test",
"=",
"'CORMAP'",
")",
":",
"if",
"len",
"(",
"{",
"len",
"(",
"c",
")",
"for",
"c",
"in",
"curves",
"}",
")",
"!=",
"1",
":",
"raise",
"V... | Run datcmp on the scattering curves.
Inputs:
*curves: scattering curves as positional arguments
alpha: confidence parameter
adjust: adjustment type (string), see the help of datcmp for details
test: test (string), see the help of datcmp for details
Outputs:
matC: the C ... | [
"Run",
"datcmp",
"on",
"the",
"scattering",
"curves",
"."
] | python | train | 44.724138 |
LLNL/certipy | certipy/certipy.py | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L281-L285 | def get_files(self, common_name):
"""Return a bundle of TLS files associated with a common name"""
record = self.get_record(common_name)
return TLSFileBundle(common_name).from_record(record) | [
"def",
"get_files",
"(",
"self",
",",
"common_name",
")",
":",
"record",
"=",
"self",
".",
"get_record",
"(",
"common_name",
")",
"return",
"TLSFileBundle",
"(",
"common_name",
")",
".",
"from_record",
"(",
"record",
")"
] | Return a bundle of TLS files associated with a common name | [
"Return",
"a",
"bundle",
"of",
"TLS",
"files",
"associated",
"with",
"a",
"common",
"name"
] | python | train | 42.2 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/core/application.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/application.py#L313-L320 | def stage_default_config_file(self):
"""auto generate default config file, and stage it into the profile."""
s = self.generate_config_file()
fname = os.path.join(self.profile_dir.location, self.config_file_name)
if self.overwrite or not os.path.exists(fname):
self.log.warn("G... | [
"def",
"stage_default_config_file",
"(",
"self",
")",
":",
"s",
"=",
"self",
".",
"generate_config_file",
"(",
")",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"profile_dir",
".",
"location",
",",
"self",
".",
"config_file_name",
")",
... | auto generate default config file, and stage it into the profile. | [
"auto",
"generate",
"default",
"config",
"file",
"and",
"stage",
"it",
"into",
"the",
"profile",
"."
] | python | test | 52.875 |
kylebebak/questionnaire | questionnaire/prompters.py | https://github.com/kylebebak/questionnaire/blob/ed92642e8a2a0198da198acbcde2707f1d528585/questionnaire/prompters.py#L128-L152 | def raw(prompt, *args, **kwargs):
"""Calls input to allow user to input an arbitrary string. User can go
back by entering the `go_back` string. Works in both Python 2 and 3.
"""
go_back = kwargs.get('go_back', '<')
type_ = kwargs.get('type', str)
default = kwargs.get('default', '')
with stdo... | [
"def",
"raw",
"(",
"prompt",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"go_back",
"=",
"kwargs",
".",
"get",
"(",
"'go_back'",
",",
"'<'",
")",
"type_",
"=",
"kwargs",
".",
"get",
"(",
"'type'",
",",
"str",
")",
"default",
"=",
"kwargs... | Calls input to allow user to input an arbitrary string. User can go
back by entering the `go_back` string. Works in both Python 2 and 3. | [
"Calls",
"input",
"to",
"allow",
"user",
"to",
"input",
"an",
"arbitrary",
"string",
".",
"User",
"can",
"go",
"back",
"by",
"entering",
"the",
"go_back",
"string",
".",
"Works",
"in",
"both",
"Python",
"2",
"and",
"3",
"."
] | python | valid | 36.76 |
inasafe/inasafe | safe/gui/tools/wizard/step_fc90_analysis.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc90_analysis.py#L293-L300 | def setup_gui_analysis_done(self):
"""Helper method to setup gui if analysis is done."""
self.progress_bar.hide()
self.lblAnalysisStatus.setText(tr('Analysis done.'))
self.pbnReportWeb.show()
self.pbnReportPDF.show()
# self.pbnReportComposer.show() # Hide until it works ... | [
"def",
"setup_gui_analysis_done",
"(",
"self",
")",
":",
"self",
".",
"progress_bar",
".",
"hide",
"(",
")",
"self",
".",
"lblAnalysisStatus",
".",
"setText",
"(",
"tr",
"(",
"'Analysis done.'",
")",
")",
"self",
".",
"pbnReportWeb",
".",
"show",
"(",
")",... | Helper method to setup gui if analysis is done. | [
"Helper",
"method",
"to",
"setup",
"gui",
"if",
"analysis",
"is",
"done",
"."
] | python | train | 47.125 |
bram85/topydo | topydo/ui/prompt/Prompt.py | https://github.com/bram85/topydo/blob/b59fcfca5361869a6b78d4c9808c7c6cd0a18b58/topydo/ui/prompt/Prompt.py#L65-L96 | def run(self):
""" Main entry function. """
history = InMemoryHistory()
self._load_file()
while True:
# (re)load the todo.txt file (only if it has been modified)
try:
user_input = prompt(u'topydo> ', history=history,
... | [
"def",
"run",
"(",
"self",
")",
":",
"history",
"=",
"InMemoryHistory",
"(",
")",
"self",
".",
"_load_file",
"(",
")",
"while",
"True",
":",
"# (re)load the todo.txt file (only if it has been modified)",
"try",
":",
"user_input",
"=",
"prompt",
"(",
"u'topydo> '",... | Main entry function. | [
"Main",
"entry",
"function",
"."
] | python | train | 33.78125 |
saltstack/salt | salt/modules/boto_asg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_asg.py#L498-L526 | def get_cloud_init_mime(cloud_init):
'''
Get a mime multipart encoded string from a cloud-init dict. Currently
supports boothooks, scripts and cloud-config.
CLI Example:
.. code-block:: bash
salt myminion boto.get_cloud_init_mime <cloud init>
'''
if isinstance(cloud_init, six.stri... | [
"def",
"get_cloud_init_mime",
"(",
"cloud_init",
")",
":",
"if",
"isinstance",
"(",
"cloud_init",
",",
"six",
".",
"string_types",
")",
":",
"cloud_init",
"=",
"salt",
".",
"utils",
".",
"json",
".",
"loads",
"(",
"cloud_init",
")",
"_cloud_init",
"=",
"em... | Get a mime multipart encoded string from a cloud-init dict. Currently
supports boothooks, scripts and cloud-config.
CLI Example:
.. code-block:: bash
salt myminion boto.get_cloud_init_mime <cloud init> | [
"Get",
"a",
"mime",
"multipart",
"encoded",
"string",
"from",
"a",
"cloud",
"-",
"init",
"dict",
".",
"Currently",
"supports",
"boothooks",
"scripts",
"and",
"cloud",
"-",
"config",
"."
] | python | train | 40.413793 |
taskcluster/taskcluster-client.py | taskcluster/aio/queue.py | https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/aio/queue.py#L265-L285 | async def claimWork(self, *args, **kwargs):
"""
Claim Work
Claim pending task(s) for the given `provisionerId`/`workerType` queue.
If any work is available (even if fewer than the requested number of
tasks, this will return immediately. Otherwise, it will block for tens of
... | [
"async",
"def",
"claimWork",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"claimWork\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Claim Work
Claim pending task(s) for the given `provisionerId`/`workerType` queue.
If any work is available (even if fewer than the requested number of
tasks, this will return immediately. Otherwise, it will block for tens of
seconds waiting for work. If no work appears, it will retur... | [
"Claim",
"Work"
] | python | train | 40.333333 |
gmr/tinman | tinman/controller.py | https://github.com/gmr/tinman/blob/98f0acd15a228d752caa1864cdf02aaa3d492a9f/tinman/controller.py#L121-L132 | def shutdown(self):
"""Send SIGABRT to child processes to instruct them to stop"""
self.signal_children(signal.SIGABRT)
# Wait a few iterations when trying to stop children before terminating
waiting = 0
while self.living_children:
time.sleep(0.5)
waiting... | [
"def",
"shutdown",
"(",
"self",
")",
":",
"self",
".",
"signal_children",
"(",
"signal",
".",
"SIGABRT",
")",
"# Wait a few iterations when trying to stop children before terminating",
"waiting",
"=",
"0",
"while",
"self",
".",
"living_children",
":",
"time",
".",
"... | Send SIGABRT to child processes to instruct them to stop | [
"Send",
"SIGABRT",
"to",
"child",
"processes",
"to",
"instruct",
"them",
"to",
"stop"
] | python | train | 36.583333 |
bcb/jsonrpcserver | jsonrpcserver/dispatcher.py | https://github.com/bcb/jsonrpcserver/blob/26bb70e868f81691816cabfc4b60a83428842b2f/jsonrpcserver/dispatcher.py#L172-L192 | def create_requests(
requests: Union[Dict, List], *, context: Any = NOCONTEXT, convert_camel_case: bool
) -> Union[Request, Set[Request]]:
"""
Create a Request object from a dictionary (or list of them).
Args:
requests: Request object, or a collection of them.
methods: The list of metho... | [
"def",
"create_requests",
"(",
"requests",
":",
"Union",
"[",
"Dict",
",",
"List",
"]",
",",
"*",
",",
"context",
":",
"Any",
"=",
"NOCONTEXT",
",",
"convert_camel_case",
":",
"bool",
")",
"->",
"Union",
"[",
"Request",
",",
"Set",
"[",
"Request",
"]",... | Create a Request object from a dictionary (or list of them).
Args:
requests: Request object, or a collection of them.
methods: The list of methods that can be called.
context: If specified, will be the first positional argument in all requests.
convert_camel_case: Will convert the m... | [
"Create",
"a",
"Request",
"object",
"from",
"a",
"dictionary",
"(",
"or",
"list",
"of",
"them",
")",
"."
] | python | train | 40.095238 |
nerdvegas/rez | src/build_utils/virtualenv/virtualenv.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/virtualenv/virtualenv.py#L999-L1050 | def path_locations(home_dir):
"""Return the path locations for the environment (where libraries are,
where scripts go, etc)"""
# XXX: We'd use distutils.sysconfig.get_python_inc/lib but its
# prefix arg is broken: http://bugs.python.org/issue3386
if is_win:
# Windows has lots of problems wit... | [
"def",
"path_locations",
"(",
"home_dir",
")",
":",
"# XXX: We'd use distutils.sysconfig.get_python_inc/lib but its",
"# prefix arg is broken: http://bugs.python.org/issue3386",
"if",
"is_win",
":",
"# Windows has lots of problems with executables with spaces in",
"# the name; this function ... | Return the path locations for the environment (where libraries are,
where scripts go, etc) | [
"Return",
"the",
"path",
"locations",
"for",
"the",
"environment",
"(",
"where",
"libraries",
"are",
"where",
"scripts",
"go",
"etc",
")"
] | python | train | 44.346154 |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_oven.py | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_oven.py#L269-L276 | def canonical_ops(ops):
''' Returns the given operations array sorted with duplicates removed.
@param ops checker.Ops
@return: checker.Ops
'''
new_ops = sorted(set(ops), key=lambda x: (x.entity, x.action))
return new_ops | [
"def",
"canonical_ops",
"(",
"ops",
")",
":",
"new_ops",
"=",
"sorted",
"(",
"set",
"(",
"ops",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"(",
"x",
".",
"entity",
",",
"x",
".",
"action",
")",
")",
"return",
"new_ops"
] | Returns the given operations array sorted with duplicates removed.
@param ops checker.Ops
@return: checker.Ops | [
"Returns",
"the",
"given",
"operations",
"array",
"sorted",
"with",
"duplicates",
"removed",
"."
] | python | train | 29.75 |
annoviko/pyclustering | pyclustering/cluster/bsas.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/bsas.py#L221-L239 | def _find_nearest_cluster(self, point):
"""!
@brief Find nearest cluster to the specified point.
@param[in] point (list): Point from dataset.
@return (uint, double) Index of nearest cluster and distance to it.
"""
index_cluster = -1;
nearest_distance = float('i... | [
"def",
"_find_nearest_cluster",
"(",
"self",
",",
"point",
")",
":",
"index_cluster",
"=",
"-",
"1",
"nearest_distance",
"=",
"float",
"(",
"'inf'",
")",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_representatives",
")",
")",
":",
"dis... | !
@brief Find nearest cluster to the specified point.
@param[in] point (list): Point from dataset.
@return (uint, double) Index of nearest cluster and distance to it. | [
"!",
"@brief",
"Find",
"nearest",
"cluster",
"to",
"the",
"specified",
"point",
"."
] | python | valid | 32.368421 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.