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 |
|---|---|---|---|---|---|---|---|---|---|
Gandi/gandi.cli | gandi/cli/commands/paas.py | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/paas.py#L68-L93 | def info(gandi, resource, stat):
"""Display information about a PaaS instance.
Resource can be a vhost, a hostname, or an ID
Cache statistics are based on 24 hours data.
"""
output_keys = ['name', 'type', 'size', 'memory', 'console', 'vhost',
'dc', 'sftp_server', 'git_server', 's... | [
"def",
"info",
"(",
"gandi",
",",
"resource",
",",
"stat",
")",
":",
"output_keys",
"=",
"[",
"'name'",
",",
"'type'",
",",
"'size'",
",",
"'memory'",
",",
"'console'",
",",
"'vhost'",
",",
"'dc'",
",",
"'sftp_server'",
",",
"'git_server'",
",",
"'snapsh... | Display information about a PaaS instance.
Resource can be a vhost, a hostname, or an ID
Cache statistics are based on 24 hours data. | [
"Display",
"information",
"about",
"a",
"PaaS",
"instance",
"."
] | python | train | 28.076923 |
pysal/esda | esda/tabular.py | https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/tabular.py#L10-L98 | def _univariate_handler(df, cols, stat=None, w=None, inplace=True,
pvalue = 'sim', outvals = None, swapname='', **kwargs):
"""
Compute a univariate descriptive statistic `stat` over columns `cols` in
`df`.
Parameters
----------
df : pandas.DataFrame
... | [
"def",
"_univariate_handler",
"(",
"df",
",",
"cols",
",",
"stat",
"=",
"None",
",",
"w",
"=",
"None",
",",
"inplace",
"=",
"True",
",",
"pvalue",
"=",
"'sim'",
",",
"outvals",
"=",
"None",
",",
"swapname",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
... | Compute a univariate descriptive statistic `stat` over columns `cols` in
`df`.
Parameters
----------
df : pandas.DataFrame
the dataframe containing columns to compute the descriptive
statistics
cols : string or list of strings
on... | [
"Compute",
"a",
"univariate",
"descriptive",
"statistic",
"stat",
"over",
"columns",
"cols",
"in",
"df",
"."
] | python | train | 44.067416 |
nerdvegas/rez | src/rez/utils/memcached.py | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/memcached.py#L112-L117 | def delete(self, key):
"""See memcache.Client."""
if self.servers:
key = self._qualified_key(key)
hashed_key = self.key_hasher(key)
self.client.delete(hashed_key) | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"if",
"self",
".",
"servers",
":",
"key",
"=",
"self",
".",
"_qualified_key",
"(",
"key",
")",
"hashed_key",
"=",
"self",
".",
"key_hasher",
"(",
"key",
")",
"self",
".",
"client",
".",
"delete",
... | See memcache.Client. | [
"See",
"memcache",
".",
"Client",
"."
] | python | train | 34.833333 |
CalebBell/thermo | thermo/utils.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L2074-L2111 | def solve_prop(self, goal, reset_method=True):
r'''Method to solve for the temperature at which a property is at a
specified value. `T_dependent_property` is used to calculate the value
of the property as a function of temperature; if `reset_method` is True,
the best method is used at ea... | [
"def",
"solve_prop",
"(",
"self",
",",
"goal",
",",
"reset_method",
"=",
"True",
")",
":",
"if",
"self",
".",
"Tmin",
"is",
"None",
"or",
"self",
".",
"Tmax",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'Both a minimum and a maximum value are not present in... | r'''Method to solve for the temperature at which a property is at a
specified value. `T_dependent_property` is used to calculate the value
of the property as a function of temperature; if `reset_method` is True,
the best method is used at each temperature as the solver seeks a
solution. ... | [
"r",
"Method",
"to",
"solve",
"for",
"the",
"temperature",
"at",
"which",
"a",
"property",
"is",
"at",
"a",
"specified",
"value",
".",
"T_dependent_property",
"is",
"used",
"to",
"calculate",
"the",
"value",
"of",
"the",
"property",
"as",
"a",
"function",
... | python | valid | 45 |
concordusapps/alchemist | alchemist/management.py | https://github.com/concordusapps/alchemist/blob/822571366271b5dca0ac8bf41df988c6a3b61432/alchemist/management.py#L33-L55 | def run(self, commands=None, default_command=None, context=None):
"""
Context: A dict of namespaces as the key, and their objects as the
value. Used to easily inject code into the shell's runtime env.
"""
if commands:
self._commands.update(commands)
... | [
"def",
"run",
"(",
"self",
",",
"commands",
"=",
"None",
",",
"default_command",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"if",
"commands",
":",
"self",
".",
"_commands",
".",
"update",
"(",
"commands",
")",
"# HACK: Overriding the old shell isn't... | Context: A dict of namespaces as the key, and their objects as the
value. Used to easily inject code into the shell's runtime env. | [
"Context",
":",
"A",
"dict",
"of",
"namespaces",
"as",
"the",
"key",
"and",
"their",
"objects",
"as",
"the",
"value",
".",
"Used",
"to",
"easily",
"inject",
"code",
"into",
"the",
"shell",
"s",
"runtime",
"env",
"."
] | python | train | 33.086957 |
bitprophet/ssh | ssh/transport.py | https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/transport.py#L774-L817 | def request_port_forward(self, address, port, handler=None):
"""
Ask the server to forward TCP connections from a listening port on
the server, across this SSH session.
If a handler is given, that handler is called from a different thread
whenever a forwarded connection arrives.... | [
"def",
"request_port_forward",
"(",
"self",
",",
"address",
",",
"port",
",",
"handler",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"active",
":",
"raise",
"SSHException",
"(",
"'SSH session not active'",
")",
"address",
"=",
"str",
"(",
"address",
"... | Ask the server to forward TCP connections from a listening port on
the server, across this SSH session.
If a handler is given, that handler is called from a different thread
whenever a forwarded connection arrives. The handler parameters are::
handler(channel, (origin_addr, origin... | [
"Ask",
"the",
"server",
"to",
"forward",
"TCP",
"connections",
"from",
"a",
"listening",
"port",
"on",
"the",
"server",
"across",
"this",
"SSH",
"session",
"."
] | python | train | 41.590909 |
rfk/threading2 | threading2/t2_posix.py | https://github.com/rfk/threading2/blob/7ec234ddd8c0d7e683b1a5c4a79a3d001143189f/threading2/t2_posix.py#L51-L66 | def _priority_range(policy=None):
"""Determine the priority range (min,max) for the given scheduler policy.
If no policy is specified, the current default policy is used.
"""
if policy is None:
policy = libc.sched_getscheduler(0)
if policy < 0:
raise OSError(get_errno(),"sch... | [
"def",
"_priority_range",
"(",
"policy",
"=",
"None",
")",
":",
"if",
"policy",
"is",
"None",
":",
"policy",
"=",
"libc",
".",
"sched_getscheduler",
"(",
"0",
")",
"if",
"policy",
"<",
"0",
":",
"raise",
"OSError",
"(",
"get_errno",
"(",
")",
",",
"\... | Determine the priority range (min,max) for the given scheduler policy.
If no policy is specified, the current default policy is used. | [
"Determine",
"the",
"priority",
"range",
"(",
"min",
"max",
")",
"for",
"the",
"given",
"scheduler",
"policy",
"."
] | python | train | 36.6875 |
push-things/django-th | th_taiga/my_taiga.py | https://github.com/push-things/django-th/blob/86c999d16bcf30b6224206e5b40824309834ac8c/th_taiga/my_taiga.py#L47-L67 | def save_data(self, trigger_id, **data):
"""
get the data from the service
:param trigger_id: id of the trigger
:params data, dict
:rtype: dict
"""
status = False
taiga = Taiga.objects.get(trigger_id=trigger_id)
title = self.set_ti... | [
"def",
"save_data",
"(",
"self",
",",
"trigger_id",
",",
"*",
"*",
"data",
")",
":",
"status",
"=",
"False",
"taiga",
"=",
"Taiga",
".",
"objects",
".",
"get",
"(",
"trigger_id",
"=",
"trigger_id",
")",
"title",
"=",
"self",
".",
"set_title",
"(",
"d... | get the data from the service
:param trigger_id: id of the trigger
:params data, dict
:rtype: dict | [
"get",
"the",
"data",
"from",
"the",
"service"
] | python | train | 32.285714 |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L99-L125 | def ToJsonString(self):
"""Converts Timestamp to RFC 3339 date string format.
Returns:
A string converted from timestamp. The string is always Z-normalized
and uses 3, 6 or 9 fractional digits as required to represent the
exact time. Example of the return format: '1972-01-01T10:00:20.021Z'
... | [
"def",
"ToJsonString",
"(",
"self",
")",
":",
"nanos",
"=",
"self",
".",
"nanos",
"%",
"_NANOS_PER_SECOND",
"total_sec",
"=",
"self",
".",
"seconds",
"+",
"(",
"self",
".",
"nanos",
"-",
"nanos",
")",
"//",
"_NANOS_PER_SECOND",
"seconds",
"=",
"total_sec",... | Converts Timestamp to RFC 3339 date string format.
Returns:
A string converted from timestamp. The string is always Z-normalized
and uses 3, 6 or 9 fractional digits as required to represent the
exact time. Example of the return format: '1972-01-01T10:00:20.021Z' | [
"Converts",
"Timestamp",
"to",
"RFC",
"3339",
"date",
"string",
"format",
"."
] | python | train | 39.296296 |
raiden-network/raiden-contracts | raiden_contracts/contract_source_manager.py | https://github.com/raiden-network/raiden-contracts/blob/a7e72a9477f2204b03f3706360ea8d9c0a8e7063/raiden_contracts/contract_source_manager.py#L104-L133 | def verify_precompiled_checksums(self, precompiled_path: Path) -> None:
""" Compare source code checksums with those from a precompiled file. """
# We get the precompiled file data
contracts_precompiled = ContractManager(precompiled_path)
# Silence mypy
assert self.contracts_ch... | [
"def",
"verify_precompiled_checksums",
"(",
"self",
",",
"precompiled_path",
":",
"Path",
")",
"->",
"None",
":",
"# We get the precompiled file data",
"contracts_precompiled",
"=",
"ContractManager",
"(",
"precompiled_path",
")",
"# Silence mypy",
"assert",
"self",
".",
... | Compare source code checksums with those from a precompiled file. | [
"Compare",
"source",
"code",
"checksums",
"with",
"those",
"from",
"a",
"precompiled",
"file",
"."
] | python | train | 48.466667 |
pymc-devs/pymc | pymc/StepMethods.py | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L318-L324 | def current_state(self):
"""Return a dictionary with the current value of the variables defining
the state of the step method."""
state = {}
for s in self._state:
state[s] = getattr(self, s)
return state | [
"def",
"current_state",
"(",
"self",
")",
":",
"state",
"=",
"{",
"}",
"for",
"s",
"in",
"self",
".",
"_state",
":",
"state",
"[",
"s",
"]",
"=",
"getattr",
"(",
"self",
",",
"s",
")",
"return",
"state"
] | Return a dictionary with the current value of the variables defining
the state of the step method. | [
"Return",
"a",
"dictionary",
"with",
"the",
"current",
"value",
"of",
"the",
"variables",
"defining",
"the",
"state",
"of",
"the",
"step",
"method",
"."
] | python | train | 35.571429 |
barryp/py-amqplib | amqplib/client_0_8/abstract_channel.py | https://github.com/barryp/py-amqplib/blob/2b3a47de34b4712c111d0a55d7ff109dffc2a7b2/amqplib/client_0_8/abstract_channel.py#L67-L76 | def _send_method(self, method_sig, args=bytes(), content=None):
"""
Send a method for our channel.
"""
if isinstance(args, AMQPWriter):
args = args.getvalue()
self.connection.method_writer.write_method(self.channel_id,
method_sig, args, content) | [
"def",
"_send_method",
"(",
"self",
",",
"method_sig",
",",
"args",
"=",
"bytes",
"(",
")",
",",
"content",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"args",
",",
"AMQPWriter",
")",
":",
"args",
"=",
"args",
".",
"getvalue",
"(",
")",
"self",
... | Send a method for our channel. | [
"Send",
"a",
"method",
"for",
"our",
"channel",
"."
] | python | train | 30.2 |
cdumay/kser | src/kser/http/consumer.py | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/http/consumer.py#L45-L56 | def run(self, loopinfo=None, batch_size=1):
""" Run consumer
"""
logger.info("{}.Starting...".format(self.__class__.__name__))
if loopinfo:
while True:
for topic in self.topics:
self.call_kafka(topic, batch_size)
time.sleep(... | [
"def",
"run",
"(",
"self",
",",
"loopinfo",
"=",
"None",
",",
"batch_size",
"=",
"1",
")",
":",
"logger",
".",
"info",
"(",
"\"{}.Starting...\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"if",
"loopinfo",
":",
"while",
... | Run consumer | [
"Run",
"consumer"
] | python | train | 35.583333 |
binux/pyspider | pyspider/result/result_worker.py | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/result/result_worker.py#L47-L66 | def run(self):
'''Run loop'''
logger.info("result_worker starting...")
while not self._quit:
try:
task, result = self.inqueue.get(timeout=1)
self.on_result(task, result)
except Queue.Empty as e:
continue
except ... | [
"def",
"run",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"result_worker starting...\"",
")",
"while",
"not",
"self",
".",
"_quit",
":",
"try",
":",
"task",
",",
"result",
"=",
"self",
".",
"inqueue",
".",
"get",
"(",
"timeout",
"=",
"1",
")... | Run loop | [
"Run",
"loop"
] | python | train | 29.15 |
Karaage-Cluster/karaage | karaage/common/trace.py | https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/common/trace.py#L257-L264 | def _formatter_class(name, value):
"""Format the "klass" variable and value on class methods.
"""
__mname = value.__module__
if __mname != '__main__':
return "%s = <type '%s.%s'>" % (name, __mname, value.__name__)
else:
return "%s = <type '%s'>" % (name, value.__name__) | [
"def",
"_formatter_class",
"(",
"name",
",",
"value",
")",
":",
"__mname",
"=",
"value",
".",
"__module__",
"if",
"__mname",
"!=",
"'__main__'",
":",
"return",
"\"%s = <type '%s.%s'>\"",
"%",
"(",
"name",
",",
"__mname",
",",
"value",
".",
"__name__",
")",
... | Format the "klass" variable and value on class methods. | [
"Format",
"the",
"klass",
"variable",
"and",
"value",
"on",
"class",
"methods",
"."
] | python | train | 37.375 |
ff0000/scarlet | scarlet/cache/views.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cache/views.py#L179-L211 | def dispatch(self, request, *args, **kwargs):
"""
Overrides Django's default dispatch to provide caching.
If the should_cache method returns True, this will call
two functions get_cache_version and get_cache_prefix
the results of those two functions are combined and passed to
... | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"request",
"=",
"request",
"self",
".",
"args",
"=",
"args",
"self",
".",
"kwargs",
"=",
"kwargs",
"self",
".",
"cache_middleware",
"=",... | Overrides Django's default dispatch to provide caching.
If the should_cache method returns True, this will call
two functions get_cache_version and get_cache_prefix
the results of those two functions are combined and passed to
the standard django caching middleware. | [
"Overrides",
"Django",
"s",
"default",
"dispatch",
"to",
"provide",
"caching",
"."
] | python | train | 37.878788 |
Vital-Fernandez/dazer | bin/lib/Plotting_Libraries/sigfig.py | https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Plotting_Libraries/sigfig.py#L62-L78 | def round_sig_error(x, ex, n, paren=False):
'''Find ex rounded to n sig-figs and make the floating point x
match the number of decimals. If [paren], the string is
returned as quantity(error) format'''
stex = round_sig(ex,n)
if stex.find('.') < 0:
extra_zeros = len(stex) - n
sigfigs ... | [
"def",
"round_sig_error",
"(",
"x",
",",
"ex",
",",
"n",
",",
"paren",
"=",
"False",
")",
":",
"stex",
"=",
"round_sig",
"(",
"ex",
",",
"n",
")",
"if",
"stex",
".",
"find",
"(",
"'.'",
")",
"<",
"0",
":",
"extra_zeros",
"=",
"len",
"(",
"stex"... | Find ex rounded to n sig-figs and make the floating point x
match the number of decimals. If [paren], the string is
returned as quantity(error) format | [
"Find",
"ex",
"rounded",
"to",
"n",
"sig",
"-",
"figs",
"and",
"make",
"the",
"floating",
"point",
"x",
"match",
"the",
"number",
"of",
"decimals",
".",
"If",
"[",
"paren",
"]",
"the",
"string",
"is",
"returned",
"as",
"quantity",
"(",
"error",
")",
... | python | train | 37 |
hobson/pug-dj | pug/dj/explore.py | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L464-L513 | def index_model_field(model, field, value_field='pk', key_formatter=str.strip, value_formatter=str.strip, batch_len=10000, limit=10000000, verbosity=1):
'''Create dict {obj.<field>: obj.pk} for all field_values in a model or queryset.
'''
try:
qs = model.objects
except:
qs = model
N... | [
"def",
"index_model_field",
"(",
"model",
",",
"field",
",",
"value_field",
"=",
"'pk'",
",",
"key_formatter",
"=",
"str",
".",
"strip",
",",
"value_formatter",
"=",
"str",
".",
"strip",
",",
"batch_len",
"=",
"10000",
",",
"limit",
"=",
"10000000",
",",
... | Create dict {obj.<field>: obj.pk} for all field_values in a model or queryset. | [
"Create",
"dict",
"{",
"obj",
".",
"<field",
">",
":",
"obj",
".",
"pk",
"}",
"for",
"all",
"field_values",
"in",
"a",
"model",
"or",
"queryset",
"."
] | python | train | 36.64 |
barrust/mediawiki | mediawiki/utilities.py | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/utilities.py#L78-L83 | def str_or_unicode(text):
""" handle python 3 unicode and python 2.7 byte strings """
encoding = sys.stdout.encoding
if sys.version_info > (3, 0):
return text.encode(encoding).decode(encoding)
return text.encode(encoding) | [
"def",
"str_or_unicode",
"(",
"text",
")",
":",
"encoding",
"=",
"sys",
".",
"stdout",
".",
"encoding",
"if",
"sys",
".",
"version_info",
">",
"(",
"3",
",",
"0",
")",
":",
"return",
"text",
".",
"encode",
"(",
"encoding",
")",
".",
"decode",
"(",
... | handle python 3 unicode and python 2.7 byte strings | [
"handle",
"python",
"3",
"unicode",
"and",
"python",
"2",
".",
"7",
"byte",
"strings"
] | python | train | 40 |
vertica/vertica-python | vertica_python/compat.py | https://github.com/vertica/vertica-python/blob/5619c1b2b2eb5ea751c684b28648fc376b5be29c/vertica_python/compat.py#L92-L107 | def as_text(bytes_or_text, encoding='utf-8'):
"""Returns the given argument as a unicode string.
Args:
bytes_or_text: A `bytes`, `str, or `unicode` object.
encoding: A string indicating the charset for decoding unicode.
Returns:
A `unicode` (Python 2) or `str` (Python 3) object.
Raises... | [
"def",
"as_text",
"(",
"bytes_or_text",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"isinstance",
"(",
"bytes_or_text",
",",
"_six",
".",
"text_type",
")",
":",
"return",
"bytes_or_text",
"elif",
"isinstance",
"(",
"bytes_or_text",
",",
"bytes",
")",
":... | Returns the given argument as a unicode string.
Args:
bytes_or_text: A `bytes`, `str, or `unicode` object.
encoding: A string indicating the charset for decoding unicode.
Returns:
A `unicode` (Python 2) or `str` (Python 3) object.
Raises:
TypeError: If `bytes_or_text` is not a binary... | [
"Returns",
"the",
"given",
"argument",
"as",
"a",
"unicode",
"string",
".",
"Args",
":",
"bytes_or_text",
":",
"A",
"bytes",
"str",
"or",
"unicode",
"object",
".",
"encoding",
":",
"A",
"string",
"indicating",
"the",
"charset",
"for",
"decoding",
"unicode",
... | python | train | 40.5 |
scikit-learn-contrib/categorical-encoding | category_encoders/sum_coding.py | https://github.com/scikit-learn-contrib/categorical-encoding/blob/5e9e803c9131b377af305d5302723ba2415001da/category_encoders/sum_coding.py#L100-L171 | def fit(self, X, y=None, **kwargs):
"""Fit encoder according to X and y.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples
and n_features is the number of features.
y : array-... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# if the input dataset isn't already a dataframe, convert it to one (using default column names)",
"# first check the type",
"X",
"=",
"util",
".",
"convert_input",
"(",
"X... | Fit encoder according to X and y.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples
and n_features is the number of features.
y : array-like, shape = [n_samples]
Target va... | [
"Fit",
"encoder",
"according",
"to",
"X",
"and",
"y",
"."
] | python | valid | 33.708333 |
Erotemic/timerit | timerit/core.py | https://github.com/Erotemic/timerit/blob/625449f5359f757fb0ab8093b228dc8f37b8ffaf/timerit/core.py#L336-L365 | def _seconds_str(self):
"""
Returns:
str: human readable text
Example:
>>> self = Timerit(num=100, bestof=10, verbose=0)
>>> self.call(lambda : sum(range(100)))
>>> print(self._seconds_str())
... 'best=3.423 µs, ave=3.451 ± 0.027 µs'
... | [
"def",
"_seconds_str",
"(",
"self",
")",
":",
"mean",
"=",
"self",
".",
"mean",
"(",
")",
"unit",
",",
"mag",
"=",
"_choose_unit",
"(",
"mean",
",",
"self",
".",
"unit",
",",
"self",
".",
"_asciimode",
")",
"unit_min",
"=",
"self",
".",
"min",
"(",... | Returns:
str: human readable text
Example:
>>> self = Timerit(num=100, bestof=10, verbose=0)
>>> self.call(lambda : sum(range(100)))
>>> print(self._seconds_str())
... 'best=3.423 µs, ave=3.451 ± 0.027 µs' | [
"Returns",
":",
"str",
":",
"human",
"readable",
"text"
] | python | train | 37.533333 |
proycon/pynlpl | pynlpl/formats/folia.py | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L3343-L3348 | def json(self,attribs =None, recurse=True, ignorelist=False):
"""See :meth:`AbstractElement.json`"""
if not attribs: attribs = {}
if self.idref:
attribs['id'] = self.idref
return super(AbstractTextMarkup,self).json(attribs,recurse, ignorelist) | [
"def",
"json",
"(",
"self",
",",
"attribs",
"=",
"None",
",",
"recurse",
"=",
"True",
",",
"ignorelist",
"=",
"False",
")",
":",
"if",
"not",
"attribs",
":",
"attribs",
"=",
"{",
"}",
"if",
"self",
".",
"idref",
":",
"attribs",
"[",
"'id'",
"]",
... | See :meth:`AbstractElement.json` | [
"See",
":",
"meth",
":",
"AbstractElement",
".",
"json"
] | python | train | 47 |
GeoPyTool/GeoPyTool | geopytool/Rose.py | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/Rose.py#L154-L265 | def singlerose(self, Width=1, Color=['red']):
'''
draw the rose map of single sample with different items~
'''
self.chooser_label.setText(self.ChooseItems[self.chooser.value() - 1])
self.MultipleRoseName = self.ChooseItems[self.chooser.value() - 1]
self.SingleRoseName =... | [
"def",
"singlerose",
"(",
"self",
",",
"Width",
"=",
"1",
",",
"Color",
"=",
"[",
"'red'",
"]",
")",
":",
"self",
".",
"chooser_label",
".",
"setText",
"(",
"self",
".",
"ChooseItems",
"[",
"self",
".",
"chooser",
".",
"value",
"(",
")",
"-",
"1",
... | draw the rose map of single sample with different items~ | [
"draw",
"the",
"rose",
"map",
"of",
"single",
"sample",
"with",
"different",
"items~"
] | python | train | 29.410714 |
google/openhtf | openhtf/core/measurements.py | https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/core/measurements.py#L404-L411 | def from_string(cls, string):
"""Convert a string into a Dimension"""
# Note: There is some ambiguity as to whether the string passed is intended
# to become a unit looked up by name or suffix, or a Dimension descriptor.
if string in units.UNITS_BY_ALL:
return cls(description=string, unit=units.Un... | [
"def",
"from_string",
"(",
"cls",
",",
"string",
")",
":",
"# Note: There is some ambiguity as to whether the string passed is intended",
"# to become a unit looked up by name or suffix, or a Dimension descriptor.",
"if",
"string",
"in",
"units",
".",
"UNITS_BY_ALL",
":",
"return",... | Convert a string into a Dimension | [
"Convert",
"a",
"string",
"into",
"a",
"Dimension"
] | python | train | 46.375 |
capless/warrant | warrant/__init__.py | https://github.com/capless/warrant/blob/ff2e4793d8479e770f2461ef7cbc0c15ee784395/warrant/__init__.py#L278-L317 | def register(self, username, password, attr_map=None):
"""
Register the user. Other base attributes from AWS Cognito User Pools
are address, birthdate, email, family_name (last name), gender,
given_name (first name), locale, middle_name, name, nickname,
phone_number, picture, pr... | [
"def",
"register",
"(",
"self",
",",
"username",
",",
"password",
",",
"attr_map",
"=",
"None",
")",
":",
"attributes",
"=",
"self",
".",
"base_attributes",
".",
"copy",
"(",
")",
"if",
"self",
".",
"custom_attributes",
":",
"attributes",
".",
"update",
... | Register the user. Other base attributes from AWS Cognito User Pools
are address, birthdate, email, family_name (last name), gender,
given_name (first name), locale, middle_name, name, nickname,
phone_number, picture, preferred_username, profile, zoneinfo,
updated at, website
:p... | [
"Register",
"the",
"user",
".",
"Other",
"base",
"attributes",
"from",
"AWS",
"Cognito",
"User",
"Pools",
"are",
"address",
"birthdate",
"email",
"family_name",
"(",
"last",
"name",
")",
"gender",
"given_name",
"(",
"first",
"name",
")",
"locale",
"middle_name... | python | train | 38.35 |
jaredLunde/vital-tools | vital/tools/encoding.py | https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/encoding.py#L36-L75 | def uniorbytes(s, result=str, enc="utf-8", err="strict"):
"""
This function was made to avoid byte / str type errors received in
packages like base64. Accepts all input types and will recursively
encode entire lists and dicts.
@s: the #bytes or #str item you are attempting to encode or decode
@... | [
"def",
"uniorbytes",
"(",
"s",
",",
"result",
"=",
"str",
",",
"enc",
"=",
"\"utf-8\"",
",",
"err",
"=",
"\"strict\"",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"result",
")",
":",
"# the input is the desired one, return as is",
"return",
"s",
"if",
"is... | This function was made to avoid byte / str type errors received in
packages like base64. Accepts all input types and will recursively
encode entire lists and dicts.
@s: the #bytes or #str item you are attempting to encode or decode
@result: the desired output, either #str or #bytes
@enc: the desire... | [
"This",
"function",
"was",
"made",
"to",
"avoid",
"byte",
"/",
"str",
"type",
"errors",
"received",
"in",
"packages",
"like",
"base64",
".",
"Accepts",
"all",
"input",
"types",
"and",
"will",
"recursively",
"encode",
"entire",
"lists",
"and",
"dicts",
"."
] | python | train | 37.475 |
StackStorm/pybind | pybind/nos/v6_0_2f/rbridge_id/router/router_bgp/address_family/ipv6/ipv6_unicast/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/rbridge_id/router/router_bgp/address_family/ipv6/ipv6_unicast/__init__.py#L94-L115 | def _set_default_vrf(self, v, load=False):
"""
Setter method for default_vrf, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_default_vrf is considered as a p... | [
"def",
"_set_default_vrf",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"ba... | Setter method for default_vrf, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_default_vrf is considered as a private
method. Backends looking to populate this va... | [
"Setter",
"method",
"for",
"default_vrf",
"mapped",
"from",
"YANG",
"variable",
"/",
"rbridge_id",
"/",
"router",
"/",
"router_bgp",
"/",
"address_family",
"/",
"ipv6",
"/",
"ipv6_unicast",
"/",
"default_vrf",
"(",
"container",
")",
"If",
"this",
"variable",
"... | python | train | 89.954545 |
danielfrg/s3contents | s3contents/genericmanager.py | https://github.com/danielfrg/s3contents/blob/d7e398c7da8836ac7579fa475bded06838e053ea/s3contents/genericmanager.py#L132-L156 | def _file_model_from_path(self, path, content=False, format=None):
"""
Build a file model from database record.
"""
model = base_model(path)
model["type"] = "file"
if self.fs.isfile(path):
model["last_modified"] = model["created"] = self.fs.lstat(path)["ST_MTI... | [
"def",
"_file_model_from_path",
"(",
"self",
",",
"path",
",",
"content",
"=",
"False",
",",
"format",
"=",
"None",
")",
":",
"model",
"=",
"base_model",
"(",
"path",
")",
"model",
"[",
"\"type\"",
"]",
"=",
"\"file\"",
"if",
"self",
".",
"fs",
".",
... | Build a file model from database record. | [
"Build",
"a",
"file",
"model",
"from",
"database",
"record",
"."
] | python | train | 40.24 |
RedHatInsights/insights-core | insights/parsers/multipath_conf.py | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/multipath_conf.py#L105-L130 | def _create_parser(cls):
"""
Need to check the specific symbol "/" in attr_value part as well.
I checked some multipath configuraion files from the sosreport and got
although there are some more specific symbols like "-%", it is enclosed
in double quotes and will be accepted. Fur... | [
"def",
"_create_parser",
"(",
"cls",
")",
":",
"section_name",
"=",
"p",
".",
"Word",
"(",
"p",
".",
"alphas",
"+",
"\"_\"",
")",
"attr_name",
"=",
"attr_value",
"=",
"p",
".",
"Word",
"(",
"p",
".",
"alphanums",
"+",
"\"_/\"",
")",
"LBRACE",
",",
... | Need to check the specific symbol "/" in attr_value part as well.
I checked some multipath configuraion files from the sosreport and got
although there are some more specific symbols like "-%", it is enclosed
in double quotes and will be accepted. Furthermore, I also checked the
source c... | [
"Need",
"to",
"check",
"the",
"specific",
"symbol",
"/",
"in",
"attr_value",
"part",
"as",
"well",
".",
"I",
"checked",
"some",
"multipath",
"configuraion",
"files",
"from",
"the",
"sosreport",
"and",
"got",
"although",
"there",
"are",
"some",
"more",
"speci... | python | train | 57.230769 |
f3at/feat | src/feat/extern/log/log.py | https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/extern/log/log.py#L422-L452 | def stderrHandler(level, object, category, file, line, message):
"""
A log handler that writes to stderr.
@type level: string
@type object: string (or None)
@type category: string
@type message: string
"""
o = ""
if object:
o = '"' + object + '"'
where = "(%s:%d)... | [
"def",
"stderrHandler",
"(",
"level",
",",
"object",
",",
"category",
",",
"file",
",",
"line",
",",
"message",
")",
":",
"o",
"=",
"\"\"",
"if",
"object",
":",
"o",
"=",
"'\"'",
"+",
"object",
"+",
"'\"'",
"where",
"=",
"\"(%s:%d)\"",
"%",
"(",
"f... | A log handler that writes to stderr.
@type level: string
@type object: string (or None)
@type category: string
@type message: string | [
"A",
"log",
"handler",
"that",
"writes",
"to",
"stderr",
"."
] | python | train | 30.387097 |
csurfer/pyheat | pyheat/commandline.py | https://github.com/csurfer/pyheat/blob/cc0ee3721aea70a1da4918957500131aa7077afe/pyheat/commandline.py#L31-L50 | def main():
"""Starting point for the program execution."""
# Create command line parser.
parser = argparse.ArgumentParser()
# Adding command line arguments.
parser.add_argument("-o", "--out", help="Output file", default=None)
parser.add_argument(
"pyfile", help="Python file to be profil... | [
"def",
"main",
"(",
")",
":",
"# Create command line parser.",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"# Adding command line arguments.",
"parser",
".",
"add_argument",
"(",
"\"-o\"",
",",
"\"--out\"",
",",
"help",
"=",
"\"Output file\"",
",",
... | Starting point for the program execution. | [
"Starting",
"point",
"for",
"the",
"program",
"execution",
"."
] | python | train | 35.5 |
Julian/jsonschema | jsonschema/validators.py | https://github.com/Julian/jsonschema/blob/a72332004cdc3ba456de7918bc32059822b2f69a/jsonschema/validators.py#L902-L935 | def validator_for(schema, default=_LATEST_VERSION):
"""
Retrieve the validator class appropriate for validating the given schema.
Uses the :validator:`$schema` property that should be present in the given
schema to look up the appropriate validator class.
Arguments:
schema (collections.Ma... | [
"def",
"validator_for",
"(",
"schema",
",",
"default",
"=",
"_LATEST_VERSION",
")",
":",
"if",
"schema",
"is",
"True",
"or",
"schema",
"is",
"False",
"or",
"u\"$schema\"",
"not",
"in",
"schema",
":",
"return",
"default",
"if",
"schema",
"[",
"u\"$schema\"",
... | Retrieve the validator class appropriate for validating the given schema.
Uses the :validator:`$schema` property that should be present in the given
schema to look up the appropriate validator class.
Arguments:
schema (collections.Mapping or bool):
the schema to look at
defa... | [
"Retrieve",
"the",
"validator",
"class",
"appropriate",
"for",
"validating",
"the",
"given",
"schema",
"."
] | python | train | 31.264706 |
tensorflow/tensor2tensor | tensor2tensor/layers/common_attention.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_attention.py#L1985-L2074 | def dot_product_unmasked_self_attention_relative_v2(
q, k, v, bias, max_relative_position=None, dropout_rate=0.0,
image_shapes=None, name=None, make_image_summary=True,
dropout_broadcast_dims=None, heads_share_relative_embedding=False,
add_relative_to_values=False):
"""Calculate relative position-awar... | [
"def",
"dot_product_unmasked_self_attention_relative_v2",
"(",
"q",
",",
"k",
",",
"v",
",",
"bias",
",",
"max_relative_position",
"=",
"None",
",",
"dropout_rate",
"=",
"0.0",
",",
"image_shapes",
"=",
"None",
",",
"name",
"=",
"None",
",",
"make_image_summary"... | Calculate relative position-aware dot-product self-attention.
The attention calculation is augmented with learned representations for the
relative position between each element in q and each element in k and v.
Args:
q: a Tensor with shape [batch, heads, length, depth].
k: a Tensor with shape [batch, he... | [
"Calculate",
"relative",
"position",
"-",
"aware",
"dot",
"-",
"product",
"self",
"-",
"attention",
"."
] | python | train | 42.833333 |
miyakogi/wdom | wdom/element.py | https://github.com/miyakogi/wdom/blob/a21bcd23e94baceee71161829f6897bee3fd39c1/wdom/element.py#L668-L670 | def removeAttributeNode(self, attr: Attr) -> Optional[Attr]:
"""Remove ``Attr`` node from this node."""
return self.attributes.removeNamedItem(attr) | [
"def",
"removeAttributeNode",
"(",
"self",
",",
"attr",
":",
"Attr",
")",
"->",
"Optional",
"[",
"Attr",
"]",
":",
"return",
"self",
".",
"attributes",
".",
"removeNamedItem",
"(",
"attr",
")"
] | Remove ``Attr`` node from this node. | [
"Remove",
"Attr",
"node",
"from",
"this",
"node",
"."
] | python | train | 54 |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/mox.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/mox.py#L846-L860 | def equals(self, rhs):
"""Check to see if RHS is almost equal to float_value
Args:
rhs: the value to compare to float_value
Returns:
bool
"""
try:
return round(rhs-self._float_value, self._places) == 0
except TypeError:
# This is probably because either float_value or ... | [
"def",
"equals",
"(",
"self",
",",
"rhs",
")",
":",
"try",
":",
"return",
"round",
"(",
"rhs",
"-",
"self",
".",
"_float_value",
",",
"self",
".",
"_places",
")",
"==",
"0",
"except",
"TypeError",
":",
"# This is probably because either float_value or rhs is n... | Check to see if RHS is almost equal to float_value
Args:
rhs: the value to compare to float_value
Returns:
bool | [
"Check",
"to",
"see",
"if",
"RHS",
"is",
"almost",
"equal",
"to",
"float_value"
] | python | train | 23 |
23andMe/Yamale | yamale/validators/base.py | https://github.com/23andMe/Yamale/blob/0a75b4205624d9bccc52bda03efaf0d58c143c76/yamale/validators/base.py#L47-L67 | def validate(self, value):
"""
Check if ``value`` is valid.
:returns: [errors] If ``value`` is invalid, otherwise [].
"""
errors = []
# Make sure the type validates first.
valid = self._is_valid(value)
if not valid:
errors.append(self.fail(va... | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"errors",
"=",
"[",
"]",
"# Make sure the type validates first.",
"valid",
"=",
"self",
".",
"_is_valid",
"(",
"value",
")",
"if",
"not",
"valid",
":",
"errors",
".",
"append",
"(",
"self",
".",
"fa... | Check if ``value`` is valid.
:returns: [errors] If ``value`` is invalid, otherwise []. | [
"Check",
"if",
"value",
"is",
"valid",
"."
] | python | train | 26.809524 |
daviddrysdale/python-phonenumbers | python/phonenumbers/geocoder.py | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/geocoder.py#L122-L189 | def description_for_valid_number(numobj, lang, script=None, region=None):
"""Return a text description of a PhoneNumber object, in the language
provided.
The description might consist of the name of the country where the phone
number is from and/or the name of the geographical area the phone number
... | [
"def",
"description_for_valid_number",
"(",
"numobj",
",",
"lang",
",",
"script",
"=",
"None",
",",
"region",
"=",
"None",
")",
":",
"number_region",
"=",
"region_code_for_number",
"(",
"numobj",
")",
"if",
"region",
"is",
"None",
"or",
"region",
"==",
"numb... | Return a text description of a PhoneNumber object, in the language
provided.
The description might consist of the name of the country where the phone
number is from and/or the name of the geographical area the phone number
is from if more detailed information is available.
If the phone number is f... | [
"Return",
"a",
"text",
"description",
"of",
"a",
"PhoneNumber",
"object",
"in",
"the",
"language",
"provided",
"."
] | python | train | 53.970588 |
gawel/irc3 | irc3/dcc/manager.py | https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/dcc/manager.py#L114-L118 | def resume(self, mask, filename, port, pos):
"""Resume a DCC send"""
self.connections['send']['masks'][mask][port].offset = pos
message = 'DCC ACCEPT %s %d %d' % (filename, port, pos)
self.bot.ctcp(mask, message) | [
"def",
"resume",
"(",
"self",
",",
"mask",
",",
"filename",
",",
"port",
",",
"pos",
")",
":",
"self",
".",
"connections",
"[",
"'send'",
"]",
"[",
"'masks'",
"]",
"[",
"mask",
"]",
"[",
"port",
"]",
".",
"offset",
"=",
"pos",
"message",
"=",
"'D... | Resume a DCC send | [
"Resume",
"a",
"DCC",
"send"
] | python | train | 48 |
google/grr | grr/server/grr_response_server/databases/mysql_flows.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_flows.py#L150-L172 | def ReadAllClientActionRequests(self, client_id, cursor=None):
"""Reads all client messages available for a given client_id."""
query = ("SELECT request, UNIX_TIMESTAMP(leased_until), leased_by, "
"leased_count "
"FROM client_action_requests "
"WHERE client_id = %s")
... | [
"def",
"ReadAllClientActionRequests",
"(",
"self",
",",
"client_id",
",",
"cursor",
"=",
"None",
")",
":",
"query",
"=",
"(",
"\"SELECT request, UNIX_TIMESTAMP(leased_until), leased_by, \"",
"\"leased_count \"",
"\"FROM client_action_requests \"",
"\"WHERE client_id = %s\"",
")... | Reads all client messages available for a given client_id. | [
"Reads",
"all",
"client",
"messages",
"available",
"for",
"a",
"given",
"client_id",
"."
] | python | train | 39.73913 |
SiLab-Bonn/pyBAR | pybar/analysis/analyze_raw_data.py | https://github.com/SiLab-Bonn/pyBAR/blob/5ad95bbcd41cd358825823fb78f396cfce23593e/pybar/analysis/analyze_raw_data.py#L1399-L1431 | def _deduce_settings_from_file(self, opened_raw_data_file): # TODO: parse better
'''Tries to get the scan parameters needed for analysis from the raw data file
'''
try: # take infos raw data files (not avalable in old files)
flavor = opened_raw_data_file.root.configuration.miscella... | [
"def",
"_deduce_settings_from_file",
"(",
"self",
",",
"opened_raw_data_file",
")",
":",
"# TODO: parse better",
"try",
":",
"# take infos raw data files (not avalable in old files)",
"flavor",
"=",
"opened_raw_data_file",
".",
"root",
".",
"configuration",
".",
"miscellaneou... | Tries to get the scan parameters needed for analysis from the raw data file | [
"Tries",
"to",
"get",
"the",
"scan",
"parameters",
"needed",
"for",
"analysis",
"from",
"the",
"raw",
"data",
"file"
] | python | train | 94.969697 |
squaresLab/BugZoo | bugzoo/mgr/source.py | https://github.com/squaresLab/BugZoo/blob/68664f1977e85b37a78604f7c570382ffae1fa3b/bugzoo/mgr/source.py#L136-L159 | def unload(self, source: Source) -> None:
"""
Unloads a registered source, causing all of its associated bugs, tools,
and blueprints to also be unloaded. If the given source is not loaded,
this function will do nothing.
"""
logger.info('unloading source: %s', source.name)... | [
"def",
"unload",
"(",
"self",
",",
"source",
":",
"Source",
")",
"->",
"None",
":",
"logger",
".",
"info",
"(",
"'unloading source: %s'",
",",
"source",
".",
"name",
")",
"try",
":",
"contents",
"=",
"self",
".",
"contents",
"(",
"source",
")",
"del",
... | Unloads a registered source, causing all of its associated bugs, tools,
and blueprints to also be unloaded. If the given source is not loaded,
this function will do nothing. | [
"Unloads",
"a",
"registered",
"source",
"causing",
"all",
"of",
"its",
"associated",
"bugs",
"tools",
"and",
"blueprints",
"to",
"also",
"be",
"unloaded",
".",
"If",
"the",
"given",
"source",
"is",
"not",
"loaded",
"this",
"function",
"will",
"do",
"nothing"... | python | train | 41.791667 |
blue-yonder/tsfresh | tsfresh/feature_extraction/feature_calculators.py | https://github.com/blue-yonder/tsfresh/blob/c72c9c574371cf7dd7d54e00a466792792e5d202/tsfresh/feature_extraction/feature_calculators.py#L35-L78 | def _roll(a, shift):
"""
Roll 1D array elements. Improves the performance of numpy.roll() by reducing the overhead introduced from the
flexibility of the numpy.roll() method such as the support for rolling over multiple dimensions.
Elements that roll beyond the last position are re-introduced at ... | [
"def",
"_roll",
"(",
"a",
",",
"shift",
")",
":",
"if",
"not",
"isinstance",
"(",
"a",
",",
"np",
".",
"ndarray",
")",
":",
"a",
"=",
"np",
".",
"asarray",
"(",
"a",
")",
"idx",
"=",
"shift",
"%",
"len",
"(",
"a",
")",
"return",
"np",
".",
... | Roll 1D array elements. Improves the performance of numpy.roll() by reducing the overhead introduced from the
flexibility of the numpy.roll() method such as the support for rolling over multiple dimensions.
Elements that roll beyond the last position are re-introduced at the beginning. Similarly, element... | [
"Roll",
"1D",
"array",
"elements",
".",
"Improves",
"the",
"performance",
"of",
"numpy",
".",
"roll",
"()",
"by",
"reducing",
"the",
"overhead",
"introduced",
"from",
"the",
"flexibility",
"of",
"the",
"numpy",
".",
"roll",
"()",
"method",
"such",
"as",
"t... | python | train | 35.840909 |
mattharrison/rst2odp | odplib/preso.py | https://github.com/mattharrison/rst2odp/blob/4adbf29b28c8207ec882f792ded07e98b1d3e7d0/odplib/preso.py#L1322-L1339 | def _in_tag(self, tagname, attributes=None):
"""
Determine if we are already in a certain tag.
If we give attributes, make sure they match.
"""
node = self.cur_node
while not node is None:
if node.tag == tagname:
if attributes and node.attrib =... | [
"def",
"_in_tag",
"(",
"self",
",",
"tagname",
",",
"attributes",
"=",
"None",
")",
":",
"node",
"=",
"self",
".",
"cur_node",
"while",
"not",
"node",
"is",
"None",
":",
"if",
"node",
".",
"tag",
"==",
"tagname",
":",
"if",
"attributes",
"and",
"node... | Determine if we are already in a certain tag.
If we give attributes, make sure they match. | [
"Determine",
"if",
"we",
"are",
"already",
"in",
"a",
"certain",
"tag",
".",
"If",
"we",
"give",
"attributes",
"make",
"sure",
"they",
"match",
"."
] | python | train | 27.888889 |
dtmilano/AndroidViewClient | src/com/dtmilano/android/culebron.py | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/culebron.py#L548-L560 | def populateViewTree(self, view):
'''
Populates the View tree.
'''
vuid = view.getUniqueId()
text = view.__smallStr__()
if view.getParent() is None:
self.viewTree.insert('', Tkinter.END, vuid, text=text)
else:
self.viewTree.insert(view.get... | [
"def",
"populateViewTree",
"(",
"self",
",",
"view",
")",
":",
"vuid",
"=",
"view",
".",
"getUniqueId",
"(",
")",
"text",
"=",
"view",
".",
"__smallStr__",
"(",
")",
"if",
"view",
".",
"getParent",
"(",
")",
"is",
"None",
":",
"self",
".",
"viewTree"... | Populates the View tree. | [
"Populates",
"the",
"View",
"tree",
"."
] | python | train | 40.307692 |
hozn/stravalib | stravalib/client.py | https://github.com/hozn/stravalib/blob/5500ebc39e0bf4706bb1ca4c27b25e56becaaa5f/stravalib/client.py#L1430-L1444 | def get_route(self, route_id):
"""
Gets specified route.
Will be detail-level if owned by authenticated user; otherwise summary-level.
https://strava.github.io/api/v3/routes/#retreive
:param route_id: The ID of route to fetch.
:type route_id: int
:rtype: :clas... | [
"def",
"get_route",
"(",
"self",
",",
"route_id",
")",
":",
"raw",
"=",
"self",
".",
"protocol",
".",
"get",
"(",
"'/routes/{id}'",
",",
"id",
"=",
"route_id",
")",
"return",
"model",
".",
"Route",
".",
"deserialize",
"(",
"raw",
",",
"bind_client",
"=... | Gets specified route.
Will be detail-level if owned by authenticated user; otherwise summary-level.
https://strava.github.io/api/v3/routes/#retreive
:param route_id: The ID of route to fetch.
:type route_id: int
:rtype: :class:`stravalib.model.Route` | [
"Gets",
"specified",
"route",
"."
] | python | train | 31.066667 |
Robpol86/libnl | libnl/msg.py | https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/msg.py#L276-L293 | def nlmsg_convert(hdr):
"""Convert a Netlink message received from a Netlink socket to an nl_msg.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L382
Allocates a new Netlink message and copies all of the data in `hdr` into the new message object.
Positional arguments:
hdr -- Netlink ... | [
"def",
"nlmsg_convert",
"(",
"hdr",
")",
":",
"nm",
"=",
"nlmsg_alloc",
"(",
"hdr",
".",
"nlmsg_len",
")",
"if",
"not",
"nm",
":",
"return",
"None",
"nm",
".",
"nm_nlh",
".",
"bytearray",
"=",
"hdr",
".",
"bytearray",
".",
"copy",
"(",
")",
"[",
":... | Convert a Netlink message received from a Netlink socket to an nl_msg.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L382
Allocates a new Netlink message and copies all of the data in `hdr` into the new message object.
Positional arguments:
hdr -- Netlink message received from netlink s... | [
"Convert",
"a",
"Netlink",
"message",
"received",
"from",
"a",
"Netlink",
"socket",
"to",
"an",
"nl_msg",
"."
] | python | train | 33.611111 |
pgmpy/pgmpy | pgmpy/sampling/base.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/sampling/base.py#L322-L337 | def _get_proposed_values(self):
"""
Method to perform time splitting using leapfrog
"""
# Take half step in time for updating momentum
momentum_bar = self.momentum + 0.5 * self.stepsize * self.grad_log_position
# Take full step in time for updating position position
... | [
"def",
"_get_proposed_values",
"(",
"self",
")",
":",
"# Take half step in time for updating momentum",
"momentum_bar",
"=",
"self",
".",
"momentum",
"+",
"0.5",
"*",
"self",
".",
"stepsize",
"*",
"self",
".",
"grad_log_position",
"# Take full step in time for updating po... | Method to perform time splitting using leapfrog | [
"Method",
"to",
"perform",
"time",
"splitting",
"using",
"leapfrog"
] | python | train | 40.375 |
bodylabs/lace | lace/topology.py | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L456-L461 | def vertices_per_edge(self):
"""Returns an Ex2 array of adjacencies between vertices, where
each element in the array is a vertex index. Each edge is included
only once. Edges that are not shared by 2 faces are not included."""
import numpy as np
return np.asarray([vertices_in_co... | [
"def",
"vertices_per_edge",
"(",
"self",
")",
":",
"import",
"numpy",
"as",
"np",
"return",
"np",
".",
"asarray",
"(",
"[",
"vertices_in_common",
"(",
"e",
"[",
"0",
"]",
",",
"e",
"[",
"1",
"]",
")",
"for",
"e",
"in",
"self",
".",
"f",
"[",
"sel... | Returns an Ex2 array of adjacencies between vertices, where
each element in the array is a vertex index. Each edge is included
only once. Edges that are not shared by 2 faces are not included. | [
"Returns",
"an",
"Ex2",
"array",
"of",
"adjacencies",
"between",
"vertices",
"where",
"each",
"element",
"in",
"the",
"array",
"is",
"a",
"vertex",
"index",
".",
"Each",
"edge",
"is",
"included",
"only",
"once",
".",
"Edges",
"that",
"are",
"not",
"shared"... | python | train | 61.666667 |
StellarCN/py-stellar-base | stellar_base/transaction.py | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/transaction.py#L121-L148 | def from_xdr_object(cls, tx_xdr_object):
"""Create a :class:`Transaction` object from a Transaction XDR
object.
"""
source = encode_check('account', tx_xdr_object.sourceAccount.ed25519)
sequence = tx_xdr_object.seqNum - 1
time_bounds_in_xdr = tx_xdr_object.timeBounds # ... | [
"def",
"from_xdr_object",
"(",
"cls",
",",
"tx_xdr_object",
")",
":",
"source",
"=",
"encode_check",
"(",
"'account'",
",",
"tx_xdr_object",
".",
"sourceAccount",
".",
"ed25519",
")",
"sequence",
"=",
"tx_xdr_object",
".",
"seqNum",
"-",
"1",
"time_bounds_in_xdr... | Create a :class:`Transaction` object from a Transaction XDR
object. | [
"Create",
"a",
":",
"class",
":",
"Transaction",
"object",
"from",
"a",
"Transaction",
"XDR",
"object",
"."
] | python | train | 32.071429 |
jobovy/galpy | galpy/orbit/Orbit.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/Orbit.py#L794-L825 | def E(self,*args,**kwargs):
"""
NAME:
E
PURPOSE:
calculate the energy
INPUT:
t - (optional) time at which to get the energy (can be Quantity)
pot= Potential instance or list of such instances
vo= (Object-wide default) physical... | [
"def",
"E",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
".",
"get",
"(",
"'pot'",
",",
"None",
")",
"is",
"None",
":",
"kwargs",
"[",
"'pot'",
"]",
"=",
"flatten_potential",
"(",
"kwargs",
".",
"get",
... | NAME:
E
PURPOSE:
calculate the energy
INPUT:
t - (optional) time at which to get the energy (can be Quantity)
pot= Potential instance or list of such instances
vo= (Object-wide default) physical scale for velocities to use to convert (can be ... | [
"NAME",
":"
] | python | train | 23.8125 |
AtmaHou/atma | Metrics.py | https://github.com/AtmaHou/atma/blob/41cd8ea9443a9c3b2dd71432f46f44a0f83093c7/Metrics.py#L78-L99 | def get_item_metric_pair(item_lst, metric_lst, id_lst):
"""
align bleu and specific score in item_lst, reconstruct the data as (rank_score, bleu) pairs, query_dic.
Detail:
query dict is input parameter used by metrics: top-x-bleu, kendall-tau
query dict is reconstructed dict type data c... | [
"def",
"get_item_metric_pair",
"(",
"item_lst",
",",
"metric_lst",
",",
"id_lst",
")",
":",
"query_dic",
"=",
"{",
"}",
"# key is qid, value is list, whose elements are tuple eg: count of words, bleu score pairs\r",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"metric_... | align bleu and specific score in item_lst, reconstruct the data as (rank_score, bleu) pairs, query_dic.
Detail:
query dict is input parameter used by metrics: top-x-bleu, kendall-tau
query dict is reconstructed dict type data container,
query dict's key is qid and value is list type, who... | [
"align",
"bleu",
"and",
"specific",
"score",
"in",
"item_lst",
"reconstruct",
"the",
"data",
"as",
"(",
"rank_score",
"bleu",
")",
"pairs",
"query_dic",
".",
"Detail",
":",
"query",
"dict",
"is",
"input",
"parameter",
"used",
"by",
"metrics",
":",
"top",
"... | python | train | 51.909091 |
earwig/mwparserfromhell | mwparserfromhell/parser/builder.py | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/builder.py#L76-L99 | def _handle_parameter(self, default):
"""Handle a case where a parameter is at the head of the tokens.
*default* is the value to use if no parameter name is defined.
"""
key = None
showkey = False
self._push()
while self._tokens:
token = self._tokens.... | [
"def",
"_handle_parameter",
"(",
"self",
",",
"default",
")",
":",
"key",
"=",
"None",
"showkey",
"=",
"False",
"self",
".",
"_push",
"(",
")",
"while",
"self",
".",
"_tokens",
":",
"token",
"=",
"self",
".",
"_tokens",
".",
"pop",
"(",
")",
"if",
... | Handle a case where a parameter is at the head of the tokens.
*default* is the value to use if no parameter name is defined. | [
"Handle",
"a",
"case",
"where",
"a",
"parameter",
"is",
"at",
"the",
"head",
"of",
"the",
"tokens",
"."
] | python | train | 40.041667 |
jonathf/chaospy | chaospy/distributions/operators/trunkation.py | https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/distributions/operators/trunkation.py#L59-L90 | def _bnd(self, xloc, left, right, cache):
"""
Distribution bounds.
Example:
>>> print(chaospy.Uniform().range([-2, 0, 2, 4]))
[[0. 0. 0. 0.]
[1. 1. 1. 1.]]
>>> print(chaospy.Trunc(chaospy.Uniform(), 0.6).range([-2, 0, 2, 4]))
[[0. 0.... | [
"def",
"_bnd",
"(",
"self",
",",
"xloc",
",",
"left",
",",
"right",
",",
"cache",
")",
":",
"if",
"isinstance",
"(",
"left",
",",
"Dist",
")",
":",
"if",
"left",
"in",
"cache",
":",
"left",
"=",
"cache",
"[",
"left",
"]",
"else",
":",
"left",
"... | Distribution bounds.
Example:
>>> print(chaospy.Uniform().range([-2, 0, 2, 4]))
[[0. 0. 0. 0.]
[1. 1. 1. 1.]]
>>> print(chaospy.Trunc(chaospy.Uniform(), 0.6).range([-2, 0, 2, 4]))
[[0. 0. 0. 0. ]
[0.6 0.6 0.6 0.6]]
>>> pri... | [
"Distribution",
"bounds",
"."
] | python | train | 34.15625 |
Miserlou/Zappa | example/authmodule.py | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/example/authmodule.py#L186-L190 | def allowMethodWithConditions(self, verb, resource, conditions):
"""Adds an API Gateway method (Http verb + Resource path) to the list of allowed
methods and includes a condition for the policy statement. More on AWS policy
conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/referen... | [
"def",
"allowMethodWithConditions",
"(",
"self",
",",
"verb",
",",
"resource",
",",
"conditions",
")",
":",
"self",
".",
"_addMethod",
"(",
"\"Allow\"",
",",
"verb",
",",
"resource",
",",
"conditions",
")"
] | Adds an API Gateway method (Http verb + Resource path) to the list of allowed
methods and includes a condition for the policy statement. More on AWS policy
conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition | [
"Adds",
"an",
"API",
"Gateway",
"method",
"(",
"Http",
"verb",
"+",
"Resource",
"path",
")",
"to",
"the",
"list",
"of",
"allowed",
"methods",
"and",
"includes",
"a",
"condition",
"for",
"the",
"policy",
"statement",
".",
"More",
"on",
"AWS",
"policy",
"c... | python | train | 83 |
AltSchool/dynamic-rest | dynamic_rest/fields/common.py | https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/fields/common.py#L6-L17 | def _get_request_fields_from_parent(self):
"""Get request fields from the parent serializer."""
if not self.parent:
return None
if not getattr(self.parent, 'request_fields'):
return None
if not isinstance(self.parent.request_fields, dict):
return Non... | [
"def",
"_get_request_fields_from_parent",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"None",
"if",
"not",
"getattr",
"(",
"self",
".",
"parent",
",",
"'request_fields'",
")",
":",
"return",
"None",
"if",
"not",
"isinstance",
... | Get request fields from the parent serializer. | [
"Get",
"request",
"fields",
"from",
"the",
"parent",
"serializer",
"."
] | python | train | 31.166667 |
luckydonald/pytgbot | code_generation/output/teleflask_messages.py | https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/code_generation/output/teleflask_messages.py#L1301-L1313 | def send(self, sender: PytgbotApiBot):
"""
Send the message via pytgbot.
:param sender: The bot instance to send with.
:type sender: pytgbot.bot.Bot
:rtype: PytgbotApiMessage
"""
return sender.send_video(
# receiver, self.media, disable_notification... | [
"def",
"send",
"(",
"self",
",",
"sender",
":",
"PytgbotApiBot",
")",
":",
"return",
"sender",
".",
"send_video",
"(",
"# receiver, self.media, disable_notification=self.disable_notification, reply_to_message_id=reply_id",
"video",
"=",
"self",
".",
"video",
",",
"chat_id... | Send the message via pytgbot.
:param sender: The bot instance to send with.
:type sender: pytgbot.bot.Bot
:rtype: PytgbotApiMessage | [
"Send",
"the",
"message",
"via",
"pytgbot",
"."
] | python | train | 55 |
UCL-INGI/INGInious | inginious/frontend/pages/api/_api_page.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L47-L55 | def _handle_api(self, handler, handler_args, handler_kwargs):
""" Handle call to subclasses and convert the output to an appropriate value """
try:
status_code, return_value = handler(*handler_args, **handler_kwargs)
except APIError as error:
return error.send()
... | [
"def",
"_handle_api",
"(",
"self",
",",
"handler",
",",
"handler_args",
",",
"handler_kwargs",
")",
":",
"try",
":",
"status_code",
",",
"return_value",
"=",
"handler",
"(",
"*",
"handler_args",
",",
"*",
"*",
"handler_kwargs",
")",
"except",
"APIError",
"as... | Handle call to subclasses and convert the output to an appropriate value | [
"Handle",
"call",
"to",
"subclasses",
"and",
"convert",
"the",
"output",
"to",
"an",
"appropriate",
"value"
] | python | train | 45.666667 |
llllllllll/codetransformer | codetransformer/decompiler/_343.py | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1344-L1352 | def _binop_handler(nodetype):
"""
Factory function for binary operator handlers.
"""
def _handler(toplevel, stack_builders):
right = make_expr(stack_builders)
left = make_expr(stack_builders)
return ast.BinOp(left=left, op=nodetype(), right=right)
return _handler | [
"def",
"_binop_handler",
"(",
"nodetype",
")",
":",
"def",
"_handler",
"(",
"toplevel",
",",
"stack_builders",
")",
":",
"right",
"=",
"make_expr",
"(",
"stack_builders",
")",
"left",
"=",
"make_expr",
"(",
"stack_builders",
")",
"return",
"ast",
".",
"BinOp... | Factory function for binary operator handlers. | [
"Factory",
"function",
"for",
"binary",
"operator",
"handlers",
"."
] | python | train | 33.222222 |
jbloomlab/phydms | phydmslib/models.py | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/models.py#L731-L742 | def _update_prx(self):
"""Update `prx` from `phi`, `pi_codon`, and `beta`."""
qx = scipy.ones(N_CODON, dtype='float')
for j in range(3):
for w in range(N_NT):
qx[CODON_NT[j][w]] *= self.phi[w]
frx = self.pi_codon**self.beta
self.prx = frx * qx
... | [
"def",
"_update_prx",
"(",
"self",
")",
":",
"qx",
"=",
"scipy",
".",
"ones",
"(",
"N_CODON",
",",
"dtype",
"=",
"'float'",
")",
"for",
"j",
"in",
"range",
"(",
"3",
")",
":",
"for",
"w",
"in",
"range",
"(",
"N_NT",
")",
":",
"qx",
"[",
"CODON_... | Update `prx` from `phi`, `pi_codon`, and `beta`. | [
"Update",
"prx",
"from",
"phi",
"pi_codon",
"and",
"beta",
"."
] | python | train | 41.416667 |
ekmmetering/ekmmeters | ekmmeters.py | https://github.com/ekmmetering/ekmmeters/blob/b3748bdf30263bfa46ea40157bdf8df2522e1904/ekmmeters.py#L1941-L1997 | def initSchd_1_to_4(self):
""" Initialize first tariff schedule :class:`~ekmmeters.SerialBlock`. """
self.m_schd_1_to_4["reserved_40"] = [6, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_schd_1_to_4["Schedule_1_Period_1_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
... | [
"def",
"initSchd_1_to_4",
"(",
"self",
")",
":",
"self",
".",
"m_schd_1_to_4",
"[",
"\"reserved_40\"",
"]",
"=",
"[",
"6",
",",
"FieldType",
".",
"Hex",
",",
"ScaleType",
".",
"No",
",",
"\"\"",
",",
"0",
",",
"False",
",",
"False",
"]",
"self",
".",... | Initialize first tariff schedule :class:`~ekmmeters.SerialBlock`. | [
"Initialize",
"first",
"tariff",
"schedule",
":",
"class",
":",
"~ekmmeters",
".",
"SerialBlock",
"."
] | python | test | 104.263158 |
twitterdev/tweet_parser | tweet_parser/tweet.py | https://github.com/twitterdev/tweet_parser/blob/3435de8367d36b483a6cfd8d46cc28694ee8a42e/tweet_parser/tweet.py#L555-L575 | def embedded_tweet(self):
"""
Get the retweeted Tweet OR the quoted Tweet and return it as a Tweet object
Returns:
Tweet (or None, if the Tweet is neither a quote tweet or a Retweet):
a Tweet representing the quote Tweet or the Retweet
(see tweet_embeds.get_e... | [
"def",
"embedded_tweet",
"(",
"self",
")",
":",
"embedded_tweet",
"=",
"tweet_embeds",
".",
"get_embedded_tweet",
"(",
"self",
")",
"if",
"embedded_tweet",
"is",
"not",
"None",
":",
"try",
":",
"return",
"Tweet",
"(",
"embedded_tweet",
")",
"except",
"NotATwee... | Get the retweeted Tweet OR the quoted Tweet and return it as a Tweet object
Returns:
Tweet (or None, if the Tweet is neither a quote tweet or a Retweet):
a Tweet representing the quote Tweet or the Retweet
(see tweet_embeds.get_embedded_tweet, this is that value as a Tweet)
... | [
"Get",
"the",
"retweeted",
"Tweet",
"OR",
"the",
"quoted",
"Tweet",
"and",
"return",
"it",
"as",
"a",
"Tweet",
"object"
] | python | train | 40.761905 |
spyder-ide/spyder | spyder/plugins/editor/lsp/manager.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/lsp/manager.py#L118-L129 | def reinitialize_all_clients(self):
"""
Send a new initialize message to each LSP server when the project
path has changed so they can update the respective server root paths.
"""
for language in self.clients:
language_client = self.clients[language]
if la... | [
"def",
"reinitialize_all_clients",
"(",
"self",
")",
":",
"for",
"language",
"in",
"self",
".",
"clients",
":",
"language_client",
"=",
"self",
".",
"clients",
"[",
"language",
"]",
"if",
"language_client",
"[",
"'status'",
"]",
"==",
"self",
".",
"RUNNING",... | Send a new initialize message to each LSP server when the project
path has changed so they can update the respective server root paths. | [
"Send",
"a",
"new",
"initialize",
"message",
"to",
"each",
"LSP",
"server",
"when",
"the",
"project",
"path",
"has",
"changed",
"so",
"they",
"can",
"update",
"the",
"respective",
"server",
"root",
"paths",
"."
] | python | train | 44.75 |
vlasovskikh/funcparserlib | funcparserlib/parser.py | https://github.com/vlasovskikh/funcparserlib/blob/0b689920babcf6079a4b3e8721cc10bbc089d81c/funcparserlib/parser.py#L111-L129 | def parse(self, tokens):
"""Sequence(a) -> b
Applies the parser to a sequence of tokens producing a parsing result.
It provides a way to invoke a parser hiding details related to the
parser state. Also it makes error messages more readable by specifying
the position of the righ... | [
"def",
"parse",
"(",
"self",
",",
"tokens",
")",
":",
"try",
":",
"(",
"tree",
",",
"_",
")",
"=",
"self",
".",
"run",
"(",
"tokens",
",",
"State",
"(",
")",
")",
"return",
"tree",
"except",
"NoParseError",
",",
"e",
":",
"max",
"=",
"e",
".",
... | Sequence(a) -> b
Applies the parser to a sequence of tokens producing a parsing result.
It provides a way to invoke a parser hiding details related to the
parser state. Also it makes error messages more readable by specifying
the position of the rightmost token that has been reached. | [
"Sequence",
"(",
"a",
")",
"-",
">",
"b"
] | python | train | 35.789474 |
hovren/crisp | crisp/calibration.py | https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/calibration.py#L90-L134 | def initialize(self, gyro_rate, slices=None, skip_estimation=False):
"""Prepare calibrator for calibration
This method does three things:
1. Create slices from the video stream, if not already provided
2. Estimate time offset
3. Estimate rotation between camera and gyroscope
... | [
"def",
"initialize",
"(",
"self",
",",
"gyro_rate",
",",
"slices",
"=",
"None",
",",
"skip_estimation",
"=",
"False",
")",
":",
"self",
".",
"params",
"[",
"'user'",
"]",
"[",
"'gyro_rate'",
"]",
"=",
"gyro_rate",
"for",
"p",
"in",
"(",
"'gbias_x'",
",... | Prepare calibrator for calibration
This method does three things:
1. Create slices from the video stream, if not already provided
2. Estimate time offset
3. Estimate rotation between camera and gyroscope
Parameters
------------------
gyro_rate : float
... | [
"Prepare",
"calibrator",
"for",
"calibration"
] | python | train | 37.933333 |
carlthome/python-audio-effects | pysndfx/dsp.py | https://github.com/carlthome/python-audio-effects/blob/b2d85c166720c549c6ef3c382b561edd09229722/pysndfx/dsp.py#L75-L85 | def highshelf(self, gain=-20.0, frequency=3000, slope=0.5):
"""highshelf takes 3 parameters: a signed number for gain or
attenuation in dB, filter frequency in Hz and slope (default=0.5).
Beware of clipping when using positive gain.
"""
self.command.append('treble')
self... | [
"def",
"highshelf",
"(",
"self",
",",
"gain",
"=",
"-",
"20.0",
",",
"frequency",
"=",
"3000",
",",
"slope",
"=",
"0.5",
")",
":",
"self",
".",
"command",
".",
"append",
"(",
"'treble'",
")",
"self",
".",
"command",
".",
"append",
"(",
"gain",
")",... | highshelf takes 3 parameters: a signed number for gain or
attenuation in dB, filter frequency in Hz and slope (default=0.5).
Beware of clipping when using positive gain. | [
"highshelf",
"takes",
"3",
"parameters",
":",
"a",
"signed",
"number",
"for",
"gain",
"or",
"attenuation",
"in",
"dB",
"filter",
"frequency",
"in",
"Hz",
"and",
"slope",
"(",
"default",
"=",
"0",
".",
"5",
")",
"."
] | python | train | 38.636364 |
tanghaibao/goatools | goatools/grouper/wrxlsx.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/grouper/wrxlsx.py#L67-L73 | def wr_txt_gos(self, fout_txt, **kws_usr):
"""Write an Excel spreadsheet with user GO ids, grouped under broader GO terms."""
# Keyword arguments: control content: hdrgo_prt section_prt top_n use_sections
desc2nts = self.sortobj.get_desc2nts(**kws_usr)
# Keyword arguments: control txt fo... | [
"def",
"wr_txt_gos",
"(",
"self",
",",
"fout_txt",
",",
"*",
"*",
"kws_usr",
")",
":",
"# Keyword arguments: control content: hdrgo_prt section_prt top_n use_sections",
"desc2nts",
"=",
"self",
".",
"sortobj",
".",
"get_desc2nts",
"(",
"*",
"*",
"kws_usr",
")",
"# K... | Write an Excel spreadsheet with user GO ids, grouped under broader GO terms. | [
"Write",
"an",
"Excel",
"spreadsheet",
"with",
"user",
"GO",
"ids",
"grouped",
"under",
"broader",
"GO",
"terms",
"."
] | python | train | 55.142857 |
QualiSystems/vCenterShell | package/cloudshell/cp/vcenter/common/vcenter/ovf_service.py | https://github.com/QualiSystems/vCenterShell/blob/e2e24cd938a92a68f4a8e6a860810d3ef72aae6d/package/cloudshell/cp/vcenter/common/vcenter/ovf_service.py#L24-L58 | def deploy_image(self, vcenter_data_model, image_params, logger):
"""
Receives ovf image parameters and deploy it on the designated vcenter
:param VMwarevCenterResourceModel vcenter_data_model:
:type image_params: vCenterShell.vm.ovf_image_params.OvfImageParams
:param logger:
... | [
"def",
"deploy_image",
"(",
"self",
",",
"vcenter_data_model",
",",
"image_params",
",",
"logger",
")",
":",
"ovf_tool_exe_path",
"=",
"vcenter_data_model",
".",
"ovf_tool_path",
"self",
".",
"_validate_url_exists",
"(",
"ovf_tool_exe_path",
",",
"'OVF Tool'",
",",
... | Receives ovf image parameters and deploy it on the designated vcenter
:param VMwarevCenterResourceModel vcenter_data_model:
:type image_params: vCenterShell.vm.ovf_image_params.OvfImageParams
:param logger: | [
"Receives",
"ovf",
"image",
"parameters",
"and",
"deploy",
"it",
"on",
"the",
"designated",
"vcenter",
":",
"param",
"VMwarevCenterResourceModel",
"vcenter_data_model",
":",
":",
"type",
"image_params",
":",
"vCenterShell",
".",
"vm",
".",
"ovf_image_params",
".",
... | python | train | 46.771429 |
welbornprod/colr | colr/trans.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/trans.py#L540-L550 | def _init_code(self, code: int) -> None:
""" Initialize from an int terminal code. """
if -1 < code < 256:
self.code = '{:02}'.format(code)
self.hexval = term2hex(code)
self.rgb = hex2rgb(self.hexval)
else:
raise ValueError(' '.join((
... | [
"def",
"_init_code",
"(",
"self",
",",
"code",
":",
"int",
")",
"->",
"None",
":",
"if",
"-",
"1",
"<",
"code",
"<",
"256",
":",
"self",
".",
"code",
"=",
"'{:02}'",
".",
"format",
"(",
"code",
")",
"self",
".",
"hexval",
"=",
"term2hex",
"(",
... | Initialize from an int terminal code. | [
"Initialize",
"from",
"an",
"int",
"terminal",
"code",
"."
] | python | train | 42.454545 |
tuxu/python-samplerate | samplerate/lowlevel.py | https://github.com/tuxu/python-samplerate/blob/ed73d7a39e61bfb34b03dade14ffab59aa27922a/samplerate/lowlevel.py#L135-L150 | def src_process(state, input_data, output_data, ratio, end_of_input=0):
"""Standard processing function.
Returns non zero on error.
"""
input_frames, _ = _check_data(input_data)
output_frames, _ = _check_data(output_data)
data = ffi.new('SRC_DATA*')
data.input_frames = input_frames
data... | [
"def",
"src_process",
"(",
"state",
",",
"input_data",
",",
"output_data",
",",
"ratio",
",",
"end_of_input",
"=",
"0",
")",
":",
"input_frames",
",",
"_",
"=",
"_check_data",
"(",
"input_data",
")",
"output_frames",
",",
"_",
"=",
"_check_data",
"(",
"out... | Standard processing function.
Returns non zero on error. | [
"Standard",
"processing",
"function",
"."
] | python | train | 40.125 |
phoikoi/sisy | src/sisy/models.py | https://github.com/phoikoi/sisy/blob/840c5463ab65488d34e99531f230e61f755d2d69/src/sisy/models.py#L95-L165 | def func_from_string(callable_str):
"""Return a live function from a full dotted path. Must be either a plain function
directly in a module, a class function, or a static function. (No modules, classes,
or instance methods, since those can't be called as tasks.)"""
components = callable_str.split('.')... | [
"def",
"func_from_string",
"(",
"callable_str",
")",
":",
"components",
"=",
"callable_str",
".",
"split",
"(",
"'.'",
")",
"func",
"=",
"None",
"if",
"len",
"(",
"components",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"Need full dotted path to task fu... | Return a live function from a full dotted path. Must be either a plain function
directly in a module, a class function, or a static function. (No modules, classes,
or instance methods, since those can't be called as tasks.) | [
"Return",
"a",
"live",
"function",
"from",
"a",
"full",
"dotted",
"path",
".",
"Must",
"be",
"either",
"a",
"plain",
"function",
"directly",
"in",
"a",
"module",
"a",
"class",
"function",
"or",
"a",
"static",
"function",
".",
"(",
"No",
"modules",
"class... | python | test | 38.028169 |
bcbio/bcbio-nextgen | bcbio/ngsalign/alignprep.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/ngsalign/alignprep.py#L627-L657 | def _bgzip_from_fastq(data):
"""Prepare a bgzipped file from a fastq input, potentially gzipped (or bgzipped already).
"""
in_file = data["in_file"]
if isinstance(in_file, (list, tuple)):
in_file = in_file[0]
needs_convert = dd.get_quality_format(data).lower() == "illumina"
# special cas... | [
"def",
"_bgzip_from_fastq",
"(",
"data",
")",
":",
"in_file",
"=",
"data",
"[",
"\"in_file\"",
"]",
"if",
"isinstance",
"(",
"in_file",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"in_file",
"=",
"in_file",
"[",
"0",
"]",
"needs_convert",
"=",
"dd",... | Prepare a bgzipped file from a fastq input, potentially gzipped (or bgzipped already). | [
"Prepare",
"a",
"bgzipped",
"file",
"from",
"a",
"fastq",
"input",
"potentially",
"gzipped",
"(",
"or",
"bgzipped",
"already",
")",
"."
] | python | train | 53.935484 |
clalancette/pycdlib | pycdlib/udf.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/udf.py#L1834-L1871 | def new(self):
# type: () -> None
'''
A method to create a new UDF Logical Volume Descriptor.
Parameters:
None.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('UDF Logical Volume Descriptor al... | [
"def",
"new",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'UDF Logical Volume Descriptor already initialized'",
")",
"self",
".",
"desc_tag",
"=",
"UDFTag",
"(",
... | A method to create a new UDF Logical Volume Descriptor.
Parameters:
None.
Returns:
Nothing. | [
"A",
"method",
"to",
"create",
"a",
"new",
"UDF",
"Logical",
"Volume",
"Descriptor",
"."
] | python | train | 31.342105 |
Miserlou/Zappa | zappa/handler.py | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/handler.py#L343-L598 | def handler(self, event, context):
"""
An AWS Lambda function which parses specific API Gateway input into a
WSGI request, feeds it to our WSGI app, procceses the response, and returns
that back to the API Gateway.
"""
settings = self.settings
# If in DEBUG mode... | [
"def",
"handler",
"(",
"self",
",",
"event",
",",
"context",
")",
":",
"settings",
"=",
"self",
".",
"settings",
"# If in DEBUG mode, log all raw incoming events.",
"if",
"settings",
".",
"DEBUG",
":",
"logger",
".",
"debug",
"(",
"'Zappa Event: {}'",
".",
"form... | An AWS Lambda function which parses specific API Gateway input into a
WSGI request, feeds it to our WSGI app, procceses the response, and returns
that back to the API Gateway. | [
"An",
"AWS",
"Lambda",
"function",
"which",
"parses",
"specific",
"API",
"Gateway",
"input",
"into",
"a",
"WSGI",
"request",
"feeds",
"it",
"to",
"our",
"WSGI",
"app",
"procceses",
"the",
"response",
"and",
"returns",
"that",
"back",
"to",
"the",
"API",
"G... | python | train | 46.269531 |
HEPData/hepdata-converter | hepdata_converter/parsers/oldhepdata_parser.py | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/oldhepdata_parser.py#L552-L571 | def _parse_header(self, data):
"""Parse header (xheader or yheader)
:param data: data to be parsed
:type data: str
:return: list with header's data
:rtype: list
"""
return_list = []
headers = data.split(':')
for header in headers:
he... | [
"def",
"_parse_header",
"(",
"self",
",",
"data",
")",
":",
"return_list",
"=",
"[",
"]",
"headers",
"=",
"data",
".",
"split",
"(",
"':'",
")",
"for",
"header",
"in",
"headers",
":",
"header",
"=",
"re",
".",
"split",
"(",
"' IN '",
",",
"header",
... | Parse header (xheader or yheader)
:param data: data to be parsed
:type data: str
:return: list with header's data
:rtype: list | [
"Parse",
"header",
"(",
"xheader",
"or",
"yheader",
")"
] | python | train | 28.05 |
summa-tx/riemann | riemann/simple.py | https://github.com/summa-tx/riemann/blob/04ae336dfd4007ceaed748daadc91cc32fa278ec/riemann/simple.py#L47-L59 | def guess_locktime(redeem_script):
'''
str -> int
If OP_CLTV is used, guess an appropriate lock_time
Otherwise return 0 (no lock time)
Fails if there's not a constant before OP_CLTV
'''
try:
script_array = redeem_script.split()
loc = script_array.index('OP_CHECKLOCKTIMEVERIFY... | [
"def",
"guess_locktime",
"(",
"redeem_script",
")",
":",
"try",
":",
"script_array",
"=",
"redeem_script",
".",
"split",
"(",
")",
"loc",
"=",
"script_array",
".",
"index",
"(",
"'OP_CHECKLOCKTIMEVERIFY'",
")",
"return",
"int",
"(",
"script_array",
"[",
"loc",... | str -> int
If OP_CLTV is used, guess an appropriate lock_time
Otherwise return 0 (no lock time)
Fails if there's not a constant before OP_CLTV | [
"str",
"-",
">",
"int",
"If",
"OP_CLTV",
"is",
"used",
"guess",
"an",
"appropriate",
"lock_time",
"Otherwise",
"return",
"0",
"(",
"no",
"lock",
"time",
")",
"Fails",
"if",
"there",
"s",
"not",
"a",
"constant",
"before",
"OP_CLTV"
] | python | train | 30.461538 |
peterbrittain/asciimatics | asciimatics/widgets.py | https://github.com/peterbrittain/asciimatics/blob/f471427d7786ce2d5f1eeb2dae0e67d19e46e085/asciimatics/widgets.py#L1166-L1259 | def process_event(self, event, hover_focus):
"""
Process any input event.
:param event: The event that was triggered.
:param hover_focus: Whether to trigger focus change on mouse moves.
:returns: None if the Effect processed the event, else the original event.
"""
... | [
"def",
"process_event",
"(",
"self",
",",
"event",
",",
"hover_focus",
")",
":",
"# Check whether this Layout is read-only - i.e. has no active focus.",
"if",
"self",
".",
"_live_col",
"<",
"0",
"or",
"self",
".",
"_live_widget",
"<",
"0",
":",
"# Might just be that w... | Process any input event.
:param event: The event that was triggered.
:param hover_focus: Whether to trigger focus change on mouse moves.
:returns: None if the Effect processed the event, else the original event. | [
"Process",
"any",
"input",
"event",
"."
] | python | train | 52.446809 |
rstoneback/pysatMagVect | pysatMagVect/_core.py | https://github.com/rstoneback/pysatMagVect/blob/3fdc87ffbe05be58123f80f880d1237c2f34c7be/pysatMagVect/_core.py#L1241-L1431 | def scalars_for_mapping_ion_drifts(glats, glons, alts, dates, step_size=None,
max_steps=None, e_field_scaling_only=False):
"""
Calculates scalars for translating ion motions at position
glat, glon, and alt, for date, to the footpoints of the field line
as well as at t... | [
"def",
"scalars_for_mapping_ion_drifts",
"(",
"glats",
",",
"glons",
",",
"alts",
",",
"dates",
",",
"step_size",
"=",
"None",
",",
"max_steps",
"=",
"None",
",",
"e_field_scaling_only",
"=",
"False",
")",
":",
"if",
"step_size",
"is",
"None",
":",
"step_siz... | Calculates scalars for translating ion motions at position
glat, glon, and alt, for date, to the footpoints of the field line
as well as at the magnetic equator.
All inputs are assumed to be 1D arrays.
Note
----
Directions refer to the ion motion direction e.g. the zonal
sc... | [
"Calculates",
"scalars",
"for",
"translating",
"ion",
"motions",
"at",
"position",
"glat",
"glon",
"and",
"alt",
"for",
"date",
"to",
"the",
"footpoints",
"of",
"the",
"field",
"line",
"as",
"well",
"as",
"at",
"the",
"magnetic",
"equator",
".",
"All",
"in... | python | train | 52.240838 |
pypa/pipenv | pipenv/vendor/requests/help.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/help.py#L26-L56 | def _implementation():
"""Return a dict with the Python implementation and version.
Provide both the name and the version of the Python implementation
currently running. For example, on CPython 2.7.5 it will return
{'name': 'CPython', 'version': '2.7.5'}.
This function works best on CPython and Py... | [
"def",
"_implementation",
"(",
")",
":",
"implementation",
"=",
"platform",
".",
"python_implementation",
"(",
")",
"if",
"implementation",
"==",
"'CPython'",
":",
"implementation_version",
"=",
"platform",
".",
"python_version",
"(",
")",
"elif",
"implementation",
... | Return a dict with the Python implementation and version.
Provide both the name and the version of the Python implementation
currently running. For example, on CPython 2.7.5 it will return
{'name': 'CPython', 'version': '2.7.5'}.
This function works best on CPython and PyPy: in particular, it probably... | [
"Return",
"a",
"dict",
"with",
"the",
"Python",
"implementation",
"and",
"version",
"."
] | python | train | 46.419355 |
saltstack/salt | salt/modules/win_dacl.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L581-L650 | def _set_dacl_inheritance(path, objectType, inheritance=True, copy=True, clear=False):
'''
helper function to set the inheritance
Args:
path (str): The path to the object
objectType (str): The type of object
inheritance (bool): True enables inheritance, False disables
cop... | [
"def",
"_set_dacl_inheritance",
"(",
"path",
",",
"objectType",
",",
"inheritance",
"=",
"True",
",",
"copy",
"=",
"True",
",",
"clear",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
",",
"'changes'",
"... | helper function to set the inheritance
Args:
path (str): The path to the object
objectType (str): The type of object
inheritance (bool): True enables inheritance, False disables
copy (bool): Copy inherited ACEs to the DACL before disabling
inheritance
clear (bool... | [
"helper",
"function",
"to",
"set",
"the",
"inheritance",
"Args",
":"
] | python | train | 43.457143 |
eddiejessup/spatious | spatious/vector.py | https://github.com/eddiejessup/spatious/blob/b7ae91bec029e85a45a7f303ee184076433723cd/spatious/vector.py#L338-L340 | def normalise_angle(th):
"""Normalise an angle to be in the range [-pi, pi]."""
return th - (2.0 * np.pi) * np.floor((th + np.pi) / (2.0 * np.pi)) | [
"def",
"normalise_angle",
"(",
"th",
")",
":",
"return",
"th",
"-",
"(",
"2.0",
"*",
"np",
".",
"pi",
")",
"*",
"np",
".",
"floor",
"(",
"(",
"th",
"+",
"np",
".",
"pi",
")",
"/",
"(",
"2.0",
"*",
"np",
".",
"pi",
")",
")"
] | Normalise an angle to be in the range [-pi, pi]. | [
"Normalise",
"an",
"angle",
"to",
"be",
"in",
"the",
"range",
"[",
"-",
"pi",
"pi",
"]",
"."
] | python | train | 50.666667 |
sosreport/sos | sos/plugins/__init__.py | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1323-L1374 | def report(self):
""" Present all information that was gathered in an html file that
allows browsing the results.
"""
# make this prettier
html = u'<hr/><a name="%s"></a>\n' % self.name()
# Intro
html = html + "<h2> Plugin <em>" + self.name() + "</em></h2>\n"
... | [
"def",
"report",
"(",
"self",
")",
":",
"# make this prettier",
"html",
"=",
"u'<hr/><a name=\"%s\"></a>\\n'",
"%",
"self",
".",
"name",
"(",
")",
"# Intro",
"html",
"=",
"html",
"+",
"\"<h2> Plugin <em>\"",
"+",
"self",
".",
"name",
"(",
")",
"+",
"\"</em><... | Present all information that was gathered in an html file that
allows browsing the results. | [
"Present",
"all",
"information",
"that",
"was",
"gathered",
"in",
"an",
"html",
"file",
"that",
"allows",
"browsing",
"the",
"results",
"."
] | python | train | 38.884615 |
hobson/aima | aima/agents.py | https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/agents.py#L157-L170 | def TableDrivenVacuumAgent():
"[Fig. 2.3]"
table = {((loc_A, 'Clean'),): 'Right',
((loc_A, 'Dirty'),): 'Suck',
((loc_B, 'Clean'),): 'Left',
((loc_B, 'Dirty'),): 'Suck',
((loc_A, 'Clean'), (loc_A, 'Clean')): 'Right',
((loc_A, 'Clean'), (loc_A, 'Dir... | [
"def",
"TableDrivenVacuumAgent",
"(",
")",
":",
"table",
"=",
"{",
"(",
"(",
"loc_A",
",",
"'Clean'",
")",
",",
")",
":",
"'Right'",
",",
"(",
"(",
"loc_A",
",",
"'Dirty'",
")",
",",
")",
":",
"'Suck'",
",",
"(",
"(",
"loc_B",
",",
"'Clean'",
")"... | [Fig. 2.3] | [
"[",
"Fig",
".",
"2",
".",
"3",
"]"
] | python | valid | 41.285714 |
sassoftware/saspy | saspy/sasbase.py | https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasbase.py#L1138-L1157 | def symget(self, name):
"""
:param name: name of the macro varable to set:
- name is a character
"""
ll = self.submit("%put " + name + "=&" + name + ";\n")
l2 = ll['LOG'].rpartition(name + "=")
l2 = l2[2].partition("\n")
try:
var = i... | [
"def",
"symget",
"(",
"self",
",",
"name",
")",
":",
"ll",
"=",
"self",
".",
"submit",
"(",
"\"%put \"",
"+",
"name",
"+",
"\"=&\"",
"+",
"name",
"+",
"\";\\n\"",
")",
"l2",
"=",
"ll",
"[",
"'LOG'",
"]",
".",
"rpartition",
"(",
"name",
"+",
"\"=\... | :param name: name of the macro varable to set:
- name is a character | [
":",
"param",
"name",
":",
"name",
"of",
"the",
"macro",
"varable",
"to",
"set",
":"
] | python | train | 22.3 |
raiden-network/raiden | raiden/raiden_service.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/raiden_service.py#L684-L730 | def handle_state_change(self, state_change: StateChange) -> List[Greenlet]:
""" Dispatch the state change and return the processing threads.
Use this for error reporting, failures in the returned greenlets,
should be re-raised using `gevent.joinall` with `raise_error=True`.
"""
... | [
"def",
"handle_state_change",
"(",
"self",
",",
"state_change",
":",
"StateChange",
")",
"->",
"List",
"[",
"Greenlet",
"]",
":",
"assert",
"self",
".",
"wal",
",",
"f'WAL not restored. node:{self!r}'",
"log",
".",
"debug",
"(",
"'State change'",
",",
"node",
... | Dispatch the state change and return the processing threads.
Use this for error reporting, failures in the returned greenlets,
should be re-raised using `gevent.joinall` with `raise_error=True`. | [
"Dispatch",
"the",
"state",
"change",
"and",
"return",
"the",
"processing",
"threads",
"."
] | python | train | 38.957447 |
redhat-cip/python-dciclient | dciclient/v1/api/base.py | https://github.com/redhat-cip/python-dciclient/blob/a4aa5899062802bbe4c30a075d8447f8d222d214/dciclient/v1/api/base.py#L31-L42 | def list(context, resource, **kwargs):
"""List all resources"""
data = utils.sanitize_kwargs(**kwargs)
id = data.pop('id', None)
subresource = data.pop('subresource', None)
if subresource:
uri = '%s/%s/%s/%s' % (context.dci_cs_api, resource, id, subresource)
else:
uri = '%s/%s' ... | [
"def",
"list",
"(",
"context",
",",
"resource",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"utils",
".",
"sanitize_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"id",
"=",
"data",
".",
"pop",
"(",
"'id'",
",",
"None",
")",
"subresource",
"=",
"data",... | List all resources | [
"List",
"all",
"resources"
] | python | train | 34.416667 |
OCA/vertical-hotel | hotel/models/hotel.py | https://github.com/OCA/vertical-hotel/blob/a01442e92b5ea1fda7fb9e6180b3211e8749a35a/hotel/models/hotel.py#L413-L448 | def onchange_dates(self):
'''
This method gives the duration between check in and checkout
if customer will leave only for some hour it would be considers
as a whole day.If customer will check in checkout for more or equal
hours, which configured in company as additional hours th... | [
"def",
"onchange_dates",
"(",
"self",
")",
":",
"configured_addition_hours",
"=",
"0",
"wid",
"=",
"self",
".",
"warehouse_id",
"whouse_com_id",
"=",
"wid",
"or",
"wid",
".",
"company_id",
"if",
"whouse_com_id",
":",
"configured_addition_hours",
"=",
"wid",
".",... | This method gives the duration between check in and checkout
if customer will leave only for some hour it would be considers
as a whole day.If customer will check in checkout for more or equal
hours, which configured in company as additional hours than it would
be consider as full days
... | [
"This",
"method",
"gives",
"the",
"duration",
"between",
"check",
"in",
"and",
"checkout",
"if",
"customer",
"will",
"leave",
"only",
"for",
"some",
"hour",
"it",
"would",
"be",
"considers",
"as",
"a",
"whole",
"day",
".",
"If",
"customer",
"will",
"check"... | python | train | 45.694444 |
WebarchivCZ/WA-KAT | src/wa_kat/rest_api/to_output.py | https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/rest_api/to_output.py#L97-L112 | def url_to_fn(url):
"""
Convert `url` to filename used to download the datasets.
``http://kitakitsune.org/xe`` -> ``kitakitsune.org_xe``.
Args:
url (str): URL of the resource.
Returns:
str: Normalized URL.
"""
url = url.replace("http://", "").replace("https://", "")
ur... | [
"def",
"url_to_fn",
"(",
"url",
")",
":",
"url",
"=",
"url",
".",
"replace",
"(",
"\"http://\"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"https://\"",
",",
"\"\"",
")",
"url",
"=",
"url",
".",
"split",
"(",
"\"?\"",
")",
"[",
"0",
"]",
"return",
... | Convert `url` to filename used to download the datasets.
``http://kitakitsune.org/xe`` -> ``kitakitsune.org_xe``.
Args:
url (str): URL of the resource.
Returns:
str: Normalized URL. | [
"Convert",
"url",
"to",
"filename",
"used",
"to",
"download",
"the",
"datasets",
"."
] | python | train | 23.625 |
changhiskhan/poseidon | poseidon/droplet.py | https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/droplet.py#L356-L367 | def rebuild(self, image, wait=True):
"""
Rebuild this droplet with given image id
Parameters
----------
image: int or str
int for image id and str for image slug
wait: bool, default True
Whether to block until the pending action is completed
... | [
"def",
"rebuild",
"(",
"self",
",",
"image",
",",
"wait",
"=",
"True",
")",
":",
"return",
"self",
".",
"_action",
"(",
"'rebuild'",
",",
"image",
"=",
"image",
",",
"wait",
"=",
"wait",
")"
] | Rebuild this droplet with given image id
Parameters
----------
image: int or str
int for image id and str for image slug
wait: bool, default True
Whether to block until the pending action is completed | [
"Rebuild",
"this",
"droplet",
"with",
"given",
"image",
"id"
] | python | valid | 31.5 |
LonamiWebs/Telethon | telethon/client/downloads.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/client/downloads.py#L444-L483 | def _download_contact(cls, mm_contact, file):
"""
Specialized version of .download_media() for contacts.
Will make use of the vCard 4.0 format.
"""
first_name = mm_contact.first_name
last_name = mm_contact.last_name
phone_number = mm_contact.phone_number
... | [
"def",
"_download_contact",
"(",
"cls",
",",
"mm_contact",
",",
"file",
")",
":",
"first_name",
"=",
"mm_contact",
".",
"first_name",
"last_name",
"=",
"mm_contact",
".",
"last_name",
"phone_number",
"=",
"mm_contact",
".",
"phone_number",
"# Remove these pesky char... | Specialized version of .download_media() for contacts.
Will make use of the vCard 4.0 format. | [
"Specialized",
"version",
"of",
".",
"download_media",
"()",
"for",
"contacts",
".",
"Will",
"make",
"use",
"of",
"the",
"vCard",
"4",
".",
"0",
"format",
"."
] | python | train | 31 |
seleniumbase/SeleniumBase | seleniumbase/core/tour_helper.py | https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/core/tour_helper.py#L519-L634 | def play_introjs_tour(
driver, tour_steps, browser, msg_dur, name=None, interval=0):
""" Plays an IntroJS tour on the current website. """
instructions = ""
for tour_step in tour_steps[name]:
instructions += tour_step
instructions += (
"""]
});
intro.setOption("di... | [
"def",
"play_introjs_tour",
"(",
"driver",
",",
"tour_steps",
",",
"browser",
",",
"msg_dur",
",",
"name",
"=",
"None",
",",
"interval",
"=",
"0",
")",
":",
"instructions",
"=",
"\"\"",
"for",
"tour_step",
"in",
"tour_steps",
"[",
"name",
"]",
":",
"inst... | Plays an IntroJS tour on the current website. | [
"Plays",
"an",
"IntroJS",
"tour",
"on",
"the",
"current",
"website",
"."
] | python | train | 36.637931 |
tnkteja/myhelp | virtualEnvironment/lib/python2.7/site-packages/coverage/results.py | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/results.py#L169-L186 | def branch_stats(self):
"""Get stats about branches.
Returns a dict mapping line numbers to a tuple:
(total_exits, taken_exits).
"""
exit_counts = self.parser.exit_counts()
missing_arcs = self.missing_branch_arcs()
stats = {}
for lnum in self.branch_line... | [
"def",
"branch_stats",
"(",
"self",
")",
":",
"exit_counts",
"=",
"self",
".",
"parser",
".",
"exit_counts",
"(",
")",
"missing_arcs",
"=",
"self",
".",
"missing_branch_arcs",
"(",
")",
"stats",
"=",
"{",
"}",
"for",
"lnum",
"in",
"self",
".",
"branch_li... | Get stats about branches.
Returns a dict mapping line numbers to a tuple:
(total_exits, taken_exits). | [
"Get",
"stats",
"about",
"branches",
"."
] | python | test | 30.055556 |
manns/pyspread | pyspread/src/gui/_dialogs.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_dialogs.py#L140-L167 | def Draw(self, grid, attr, dc, rect, row, col, is_selected):
"""Draws the text and the combobox icon"""
render = wx.RendererNative.Get()
# clear the background
dc.SetBackgroundMode(wx.SOLID)
if is_selected:
dc.SetBrush(wx.Brush(wx.BLUE, wx.SOLID))
dc.Se... | [
"def",
"Draw",
"(",
"self",
",",
"grid",
",",
"attr",
",",
"dc",
",",
"rect",
",",
"row",
",",
"col",
",",
"is_selected",
")",
":",
"render",
"=",
"wx",
".",
"RendererNative",
".",
"Get",
"(",
")",
"# clear the background",
"dc",
".",
"SetBackgroundMod... | Draws the text and the combobox icon | [
"Draws",
"the",
"text",
"and",
"the",
"combobox",
"icon"
] | python | train | 35.107143 |
scott-griffiths/bitstring | bitstring.py | https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3963-L3983 | def peeklist(self, fmt, **kwargs):
"""Interpret next bits according to format string(s) and return list.
fmt -- One or more strings with comma separated tokens describing
how to interpret the next bits in the bitstring.
kwargs -- A dictionary or keyword-value pairs - the keywords... | [
"def",
"peeklist",
"(",
"self",
",",
"fmt",
",",
"*",
"*",
"kwargs",
")",
":",
"pos",
"=",
"self",
".",
"_pos",
"return_values",
"=",
"self",
".",
"readlist",
"(",
"fmt",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_pos",
"=",
"pos",
"return",
"r... | Interpret next bits according to format string(s) and return list.
fmt -- One or more strings with comma separated tokens describing
how to interpret the next bits in the bitstring.
kwargs -- A dictionary or keyword-value pairs - the keywords used in the
format string w... | [
"Interpret",
"next",
"bits",
"according",
"to",
"format",
"string",
"(",
"s",
")",
"and",
"return",
"list",
"."
] | python | train | 40.809524 |
OpenHumans/open-humans-api | ohapi/utils_fs.py | https://github.com/OpenHumans/open-humans-api/blob/ca2a28cf5d55cfdae13dd222ba58c25565bdb86e/ohapi/utils_fs.py#L404-L452 | def write_metadata_to_filestream(filedir, filestream,
max_bytes=MAX_FILE_DEFAULT):
"""
Make metadata file for all files in a directory(helper function)
:param filedir: This field is the filepath of the directory whose csv
has to be made.
:param filestream: This ... | [
"def",
"write_metadata_to_filestream",
"(",
"filedir",
",",
"filestream",
",",
"max_bytes",
"=",
"MAX_FILE_DEFAULT",
")",
":",
"csv_out",
"=",
"csv",
".",
"writer",
"(",
"filestream",
")",
"subdirs",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"filedir",
... | Make metadata file for all files in a directory(helper function)
:param filedir: This field is the filepath of the directory whose csv
has to be made.
:param filestream: This field is a stream for writing to the csv.
:param max_bytes: This field is the maximum file size to consider. Its
def... | [
"Make",
"metadata",
"file",
"for",
"all",
"files",
"in",
"a",
"directory",
"(",
"helper",
"function",
")"
] | python | train | 48.755102 |
tensorpack/tensorpack | tensorpack/utils/timer.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L57-L62 | def total_timer(msg):
""" A context which add the time spent inside to TotalTimer. """
start = timer()
yield
t = timer() - start
_TOTAL_TIMER_DATA[msg].feed(t) | [
"def",
"total_timer",
"(",
"msg",
")",
":",
"start",
"=",
"timer",
"(",
")",
"yield",
"t",
"=",
"timer",
"(",
")",
"-",
"start",
"_TOTAL_TIMER_DATA",
"[",
"msg",
"]",
".",
"feed",
"(",
"t",
")"
] | A context which add the time spent inside to TotalTimer. | [
"A",
"context",
"which",
"add",
"the",
"time",
"spent",
"inside",
"to",
"TotalTimer",
"."
] | python | train | 29 |
RowleyGroup/pyqueue | pyqueue/systems/slurm.py | https://github.com/RowleyGroup/pyqueue/blob/24de6e1b06b9626ed94d0d5a859bc71bd3afbb4f/pyqueue/systems/slurm.py#L172-L184 | def submit(self, job):
"""
Submits a given job
:param job: The job to submit
:type job: pyqueue.job.JobInterface
"""
script = self._printer.generate(job)
stdin, stdout, stderr = self._ssh.exec_command('sbatch')
stdin.write(script)
stdin.flush()
... | [
"def",
"submit",
"(",
"self",
",",
"job",
")",
":",
"script",
"=",
"self",
".",
"_printer",
".",
"generate",
"(",
"job",
")",
"stdin",
",",
"stdout",
",",
"stderr",
"=",
"self",
".",
"_ssh",
".",
"exec_command",
"(",
"'sbatch'",
")",
"stdin",
".",
... | Submits a given job
:param job: The job to submit
:type job: pyqueue.job.JobInterface | [
"Submits",
"a",
"given",
"job"
] | python | train | 28.692308 |
mdsol/rwslib | rwslib/builders/clinicaldata.py | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/builders/clinicaldata.py#L1167-L1181 | def build(self, builder):
"""Build XML by appending to builder"""
params = dict(Value=self.value,
Status=self.status.value,
ProtocolDeviationRepeatKey=self.repeat_key
)
if self.code:
params['Code'] = self.code
... | [
"def",
"build",
"(",
"self",
",",
"builder",
")",
":",
"params",
"=",
"dict",
"(",
"Value",
"=",
"self",
".",
"value",
",",
"Status",
"=",
"self",
".",
"status",
".",
"value",
",",
"ProtocolDeviationRepeatKey",
"=",
"self",
".",
"repeat_key",
")",
"if"... | Build XML by appending to builder | [
"Build",
"XML",
"by",
"appending",
"to",
"builder"
] | python | train | 37.733333 |
trailofbits/manticore | manticore/native/cpu/abstractcpu.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L740-L765 | def read_string(self, where, max_length=None, force=False):
"""
Read a NUL-terminated concrete buffer from memory. Stops reading at first symbolic byte.
:param int where: Address to read string from
:param int max_length:
The size in bytes to cap the string at, or None [defa... | [
"def",
"read_string",
"(",
"self",
",",
"where",
",",
"max_length",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"s",
"=",
"io",
".",
"BytesIO",
"(",
")",
"while",
"True",
":",
"c",
"=",
"self",
".",
"read_int",
"(",
"where",
",",
"8",
",",... | Read a NUL-terminated concrete buffer from memory. Stops reading at first symbolic byte.
:param int where: Address to read string from
:param int max_length:
The size in bytes to cap the string at, or None [default] for no
limit.
:param force: whether to ignore memory pe... | [
"Read",
"a",
"NUL",
"-",
"terminated",
"concrete",
"buffer",
"from",
"memory",
".",
"Stops",
"reading",
"at",
"first",
"symbolic",
"byte",
"."
] | python | valid | 32.461538 |
inasafe/inasafe | safe/gui/tools/batch/batch_dialog.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/batch/batch_dialog.py#L404-L417 | def set_layer_visible(layer, visible):
"""Sets a layer in the project visible or not
:param layer: layer to change
:type layer: QgsMapLayer
:param visible: True to show layer, False to hide layer
:type visible: bool
"""
if layer is None:
return
... | [
"def",
"set_layer_visible",
"(",
"layer",
",",
"visible",
")",
":",
"if",
"layer",
"is",
"None",
":",
"return",
"QgsProject",
".",
"instance",
"(",
")",
".",
"layerTreeRoot",
"(",
")",
".",
"findLayer",
"(",
"layer",
".",
"id",
"(",
")",
")",
".",
"s... | Sets a layer in the project visible or not
:param layer: layer to change
:type layer: QgsMapLayer
:param visible: True to show layer, False to hide layer
:type visible: bool | [
"Sets",
"a",
"layer",
"in",
"the",
"project",
"visible",
"or",
"not"
] | python | train | 29.785714 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.