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 |
|---|---|---|---|---|---|---|---|---|---|
wdv4758h/python-everywhere | setup.py | https://github.com/wdv4758h/python-everywhere/blob/1d1bafd9f908b08c7bdb0470c6e54181c928f32f/setup.py#L16-L26 | def mbcs_work_around():
'''
work around for mbcs codec to make "bdist_wininst" work
https://mail.python.org/pipermail/python-list/2012-February/620326.html
'''
import codecs
try:
codecs.lookup('mbcs')
except LookupError:
ascii = codecs.lookup('ascii')
codecs.register(... | [
"def",
"mbcs_work_around",
"(",
")",
":",
"import",
"codecs",
"try",
":",
"codecs",
".",
"lookup",
"(",
"'mbcs'",
")",
"except",
"LookupError",
":",
"ascii",
"=",
"codecs",
".",
"lookup",
"(",
"'ascii'",
")",
"codecs",
".",
"register",
"(",
"lambda",
"na... | work around for mbcs codec to make "bdist_wininst" work
https://mail.python.org/pipermail/python-list/2012-February/620326.html | [
"work",
"around",
"for",
"mbcs",
"codec",
"to",
"make",
"bdist_wininst",
"work",
"https",
":",
"//",
"mail",
".",
"python",
".",
"org",
"/",
"pipermail",
"/",
"python",
"-",
"list",
"/",
"2012",
"-",
"February",
"/",
"620326",
".",
"html"
] | python | train | 32.454545 |
soasme/rio-client | rio_client/transports/requests.py | https://github.com/soasme/rio-client/blob/c6d684c6f9deea5b43f2b05bcaf40714c48b5619/rio_client/transports/requests.py#L25-L50 | def emit(self, action, payload):
"""Emit action with payload via `requests.post`."""
url = self.get_emit_api(action)
headers = {
'User-Agent': 'rio/%s' % VERSION,
'X-Rio-Protocol': '1',
}
args = dict(
url=url,
json=payload,
... | [
"def",
"emit",
"(",
"self",
",",
"action",
",",
"payload",
")",
":",
"url",
"=",
"self",
".",
"get_emit_api",
"(",
"action",
")",
"headers",
"=",
"{",
"'User-Agent'",
":",
"'rio/%s'",
"%",
"VERSION",
",",
"'X-Rio-Protocol'",
":",
"'1'",
",",
"}",
"args... | Emit action with payload via `requests.post`. | [
"Emit",
"action",
"with",
"payload",
"via",
"requests",
".",
"post",
"."
] | python | train | 29.346154 |
bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L254-L274 | def _fill_capture_regions(data):
"""Fill short-hand specification of BED capture regions.
"""
special_targets = {"sv_regions": ("exons", "transcripts")}
ref_file = dd.get_ref_file(data)
for target in ["variant_regions", "sv_regions", "coverage"]:
val = tz.get_in(["config", "algorithm", targe... | [
"def",
"_fill_capture_regions",
"(",
"data",
")",
":",
"special_targets",
"=",
"{",
"\"sv_regions\"",
":",
"(",
"\"exons\"",
",",
"\"transcripts\"",
")",
"}",
"ref_file",
"=",
"dd",
".",
"get_ref_file",
"(",
"data",
")",
"for",
"target",
"in",
"[",
"\"varian... | Fill short-hand specification of BED capture regions. | [
"Fill",
"short",
"-",
"hand",
"specification",
"of",
"BED",
"capture",
"regions",
"."
] | python | train | 57.238095 |
bitesofcode/projexui | projexui/xhistorystack.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xhistorystack.py#L125-L139 | def goBack(self):
"""
Goes up one level if possible and returns the url at the current level.
If it cannot go up, then a blank string will be returned.
:return <str>
"""
if not self.canGoBack():
return ''
self._blockStack = Tru... | [
"def",
"goBack",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"canGoBack",
"(",
")",
":",
"return",
"''",
"self",
".",
"_blockStack",
"=",
"True",
"self",
".",
"_index",
"-=",
"1",
"self",
".",
"emitCurrentChanged",
"(",
")",
"self",
".",
"_block... | Goes up one level if possible and returns the url at the current level.
If it cannot go up, then a blank string will be returned.
:return <str> | [
"Goes",
"up",
"one",
"level",
"if",
"possible",
"and",
"returns",
"the",
"url",
"at",
"the",
"current",
"level",
".",
"If",
"it",
"cannot",
"go",
"up",
"then",
"a",
"blank",
"string",
"will",
"be",
"returned",
".",
":",
"return",
"<str",
">"
] | python | train | 28.866667 |
Saledddar/pyunet | pyunet/util.py | https://github.com/Saledddar/pyunet/blob/ca5ccc32588fae8da43f968e7747d3f3da509507/pyunet/util.py#L68-L87 | def find_modules_with_decorators(path,decorator_module,decorator_name):
'''
Finds all the modules decorated with the specified decorator in the path, file or module specified.
Args :
path : All modules in the directory and its sub-directories will be scanned.
decorato... | [
"def",
"find_modules_with_decorators",
"(",
"path",
",",
"decorator_module",
",",
"decorator_name",
")",
":",
"modules_paths",
"=",
"[",
"]",
"#If a path to a module file",
"if",
"path",
"[",
"-",
"3",
":",
"]",
"==",
"'.py'",
":",
"modules_paths",
".",
"append"... | Finds all the modules decorated with the specified decorator in the path, file or module specified.
Args :
path : All modules in the directory and its sub-directories will be scanned.
decorator_module : Then full name of the module defining the decorator.
decorator... | [
"Finds",
"all",
"the",
"modules",
"decorated",
"with",
"the",
"specified",
"decorator",
"in",
"the",
"path",
"file",
"or",
"module",
"specified",
".",
"Args",
":",
"path",
":",
"All",
"modules",
"in",
"the",
"directory",
"and",
"its",
"sub",
"-",
"director... | python | train | 41.5 |
gwastro/pycbc | pycbc/workflow/configuration.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/configuration.py#L442-L495 | def from_args(cls, args):
"""
Initialize a WorkflowConfigParser instance using the command line values
parsed in args. args must contain the values provided by the
workflow_command_line_group() function. If you are not using the standard
workflow command line interface, you shoul... | [
"def",
"from_args",
"(",
"cls",
",",
"args",
")",
":",
"# Identify the config files",
"confFiles",
"=",
"[",
"]",
"# files and URLs to resolve",
"if",
"args",
".",
"config_files",
":",
"confFiles",
"+=",
"args",
".",
"config_files",
"# Identify the deletes",
"confDe... | Initialize a WorkflowConfigParser instance using the command line values
parsed in args. args must contain the values provided by the
workflow_command_line_group() function. If you are not using the standard
workflow command line interface, you should probably initialize directly
using _... | [
"Initialize",
"a",
"WorkflowConfigParser",
"instance",
"using",
"the",
"command",
"line",
"values",
"parsed",
"in",
"args",
".",
"args",
"must",
"contain",
"the",
"values",
"provided",
"by",
"the",
"workflow_command_line_group",
"()",
"function",
".",
"If",
"you",... | python | train | 39.555556 |
bcbio/bcbio-nextgen | bcbio/structural/shared.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/shared.py#L72-L82 | def find_case_control(items):
"""Find case/control items in a population of multiple samples.
"""
cases = []
controls = []
for data in items:
if population.get_affected_status(data) == 1:
controls.append(data)
else:
cases.append(data)
return cases, control... | [
"def",
"find_case_control",
"(",
"items",
")",
":",
"cases",
"=",
"[",
"]",
"controls",
"=",
"[",
"]",
"for",
"data",
"in",
"items",
":",
"if",
"population",
".",
"get_affected_status",
"(",
"data",
")",
"==",
"1",
":",
"controls",
".",
"append",
"(",
... | Find case/control items in a population of multiple samples. | [
"Find",
"case",
"/",
"control",
"items",
"in",
"a",
"population",
"of",
"multiple",
"samples",
"."
] | python | train | 28.272727 |
zetaops/pyoko | pyoko/model.py | https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/model.py#L222-L230 | def get_unpermitted_fields(self):
"""
Gives unpermitted fields for current context/user.
Returns:
List of unpermitted field names.
"""
return (self._unpermitted_fields if self._is_unpermitted_fields_set else
self._apply_cell_filters(self._context)) | [
"def",
"get_unpermitted_fields",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_unpermitted_fields",
"if",
"self",
".",
"_is_unpermitted_fields_set",
"else",
"self",
".",
"_apply_cell_filters",
"(",
"self",
".",
"_context",
")",
")"
] | Gives unpermitted fields for current context/user.
Returns:
List of unpermitted field names. | [
"Gives",
"unpermitted",
"fields",
"for",
"current",
"context",
"/",
"user",
"."
] | python | train | 34.333333 |
RudolfCardinal/pythonlib | cardinal_pythonlib/psychiatry/drugs.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L608-L621 | def sql_like_fragments(self) -> List[str]:
"""
Returns all the string literals to which a database column should be
compared using the SQL ``LIKE`` operator, to match this drug.
This isn't as accurate as the regex, but ``LIKE`` can do less.
``LIKE`` uses the wildcards ``?`` and... | [
"def",
"sql_like_fragments",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"self",
".",
"_sql_like_fragments",
"is",
"None",
":",
"self",
".",
"_sql_like_fragments",
"=",
"[",
"]",
"for",
"p",
"in",
"list",
"(",
"set",
"(",
"self",
".",
... | Returns all the string literals to which a database column should be
compared using the SQL ``LIKE`` operator, to match this drug.
This isn't as accurate as the regex, but ``LIKE`` can do less.
``LIKE`` uses the wildcards ``?`` and ``%``. | [
"Returns",
"all",
"the",
"string",
"literals",
"to",
"which",
"a",
"database",
"column",
"should",
"be",
"compared",
"using",
"the",
"SQL",
"LIKE",
"operator",
"to",
"match",
"this",
"drug",
"."
] | python | train | 42.785714 |
glitchassassin/lackey | lackey/PlatformManagerDarwin.py | https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/PlatformManagerDarwin.py#L302-L310 | def getWindowByTitle(self, wildcard, order=0):
""" Returns a handle for the first window that matches the provided "wildcard" regex """
for w in self._get_window_list():
if "kCGWindowName" in w and re.search(wildcard, w["kCGWindowName"], flags=re.I):
# Matches - make sure we ... | [
"def",
"getWindowByTitle",
"(",
"self",
",",
"wildcard",
",",
"order",
"=",
"0",
")",
":",
"for",
"w",
"in",
"self",
".",
"_get_window_list",
"(",
")",
":",
"if",
"\"kCGWindowName\"",
"in",
"w",
"and",
"re",
".",
"search",
"(",
"wildcard",
",",
"w",
... | Returns a handle for the first window that matches the provided "wildcard" regex | [
"Returns",
"a",
"handle",
"for",
"the",
"first",
"window",
"that",
"matches",
"the",
"provided",
"wildcard",
"regex"
] | python | train | 52.333333 |
goshuirc/irc | girc/client.py | https://github.com/goshuirc/irc/blob/d6a5e3e04d337566c009b087f108cd76f9e122cc/girc/client.py#L98-L119 | def register_event(self, direction, verb, child_fn, priority=10):
"""Register an event with all servers.
Args:
direction (str): `in`, `out`, `both`, or `girc`.
verb (str): Event name, `all`, or `raw`.
child_fn (function): Handler function.
priority (int):... | [
"def",
"register_event",
"(",
"self",
",",
"direction",
",",
"verb",
",",
"child_fn",
",",
"priority",
"=",
"10",
")",
":",
"event_managers",
"=",
"[",
"]",
"if",
"direction",
"in",
"(",
"'in'",
",",
"'both'",
")",
":",
"event_managers",
".",
"append",
... | Register an event with all servers.
Args:
direction (str): `in`, `out`, `both`, or `girc`.
verb (str): Event name, `all`, or `raw`.
child_fn (function): Handler function.
priority (int): Handler priority (lower priority executes first).
Note: `all` will ... | [
"Register",
"an",
"event",
"with",
"all",
"servers",
"."
] | python | train | 42.136364 |
tensorflow/tensorboard | tensorboard/backend/event_processing/plugin_event_multiplexer.py | https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/plugin_event_multiplexer.py#L425-L442 | def SummaryMetadata(self, run, tag):
"""Return the summary metadata for the given tag on the given run.
Args:
run: A string name of the run for which summary metadata is to be
retrieved.
tag: A string name of the tag whose summary metadata is to be
retrieved.
Raises:
KeyE... | [
"def",
"SummaryMetadata",
"(",
"self",
",",
"run",
",",
"tag",
")",
":",
"accumulator",
"=",
"self",
".",
"GetAccumulator",
"(",
"run",
")",
"return",
"accumulator",
".",
"SummaryMetadata",
"(",
"tag",
")"
] | Return the summary metadata for the given tag on the given run.
Args:
run: A string name of the run for which summary metadata is to be
retrieved.
tag: A string name of the tag whose summary metadata is to be
retrieved.
Raises:
KeyError: If the run is not found, or the tag is... | [
"Return",
"the",
"summary",
"metadata",
"for",
"the",
"given",
"tag",
"on",
"the",
"given",
"run",
"."
] | python | train | 29.611111 |
lemieuxl/pyGenClean | pyGenClean/run_data_clean_up.py | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/run_data_clean_up.py#L2622-L2694 | def run_compare_gold_standard(in_prefix, in_type, out_prefix, base_dir,
options):
"""Compares with a gold standard data set (compare_gold_standard.
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output p... | [
"def",
"run_compare_gold_standard",
"(",
"in_prefix",
",",
"in_type",
",",
"out_prefix",
",",
"base_dir",
",",
"options",
")",
":",
"# Creating the output directory",
"os",
".",
"mkdir",
"(",
"out_prefix",
")",
"# We know we need bfile",
"required_type",
"=",
"\"bfile... | Compares with a gold standard data set (compare_gold_standard.
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the output directory.
:param options: the options needed.
:type in_prefix: str
... | [
"Compares",
"with",
"a",
"gold",
"standard",
"data",
"set",
"(",
"compare_gold_standard",
"."
] | python | train | 34.794521 |
signaturit/python-sdk | signaturit_sdk/signaturit_client.py | https://github.com/signaturit/python-sdk/blob/2419c6d9675d901244f807ae360dc58aa46109a9/signaturit_sdk/signaturit_client.py#L656-L667 | def remove_member_from_group(self, group_id, user_id):
"""
Add a user to a group as a member
:param group_id:
:param user_id:
"""
url = self.TEAM_MEMBERS_URL % (group_id, user_id)
connection = Connection(self.token)
connection.set_url(self.production, url... | [
"def",
"remove_member_from_group",
"(",
"self",
",",
"group_id",
",",
"user_id",
")",
":",
"url",
"=",
"self",
".",
"TEAM_MEMBERS_URL",
"%",
"(",
"group_id",
",",
"user_id",
")",
"connection",
"=",
"Connection",
"(",
"self",
".",
"token",
")",
"connection",
... | Add a user to a group as a member
:param group_id:
:param user_id: | [
"Add",
"a",
"user",
"to",
"a",
"group",
"as",
"a",
"member",
":",
"param",
"group_id",
":",
":",
"param",
"user_id",
":"
] | python | train | 29.5 |
pallets/werkzeug | src/werkzeug/datastructures.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/datastructures.py#L2343-L2355 | def to_content_range_header(self, length):
"""Converts the object into `Content-Range` HTTP header,
based on given length
"""
range_for_length = self.range_for_length(length)
if range_for_length is not None:
return "%s %d-%d/%d" % (
self.units,
... | [
"def",
"to_content_range_header",
"(",
"self",
",",
"length",
")",
":",
"range_for_length",
"=",
"self",
".",
"range_for_length",
"(",
"length",
")",
"if",
"range_for_length",
"is",
"not",
"None",
":",
"return",
"\"%s %d-%d/%d\"",
"%",
"(",
"self",
".",
"units... | Converts the object into `Content-Range` HTTP header,
based on given length | [
"Converts",
"the",
"object",
"into",
"Content",
"-",
"Range",
"HTTP",
"header",
"based",
"on",
"given",
"length"
] | python | train | 33.538462 |
apetrynet/pyfilemail | pyfilemail/users.py | https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/users.py#L641-L655 | def get_company_user(self, email):
"""Get company user based on email.
:param email: address of contact
:type email: ``str``, ``unicode``
:rtype: ``dict`` with contact information
"""
users = self.get_company_users()
for user in users:
if user['email... | [
"def",
"get_company_user",
"(",
"self",
",",
"email",
")",
":",
"users",
"=",
"self",
".",
"get_company_users",
"(",
")",
"for",
"user",
"in",
"users",
":",
"if",
"user",
"[",
"'email'",
"]",
"==",
"email",
":",
"return",
"user",
"msg",
"=",
"'No user ... | Get company user based on email.
:param email: address of contact
:type email: ``str``, ``unicode``
:rtype: ``dict`` with contact information | [
"Get",
"company",
"user",
"based",
"on",
"email",
"."
] | python | train | 31.6 |
mdsol/rwslib | rwslib/extras/rwscmd/data_scrambler.py | https://github.com/mdsol/rwslib/blob/1a86bc072d408c009ed1de8bf6e98a1769f54d18/rwslib/extras/rwscmd/data_scrambler.py#L106-L124 | def scramble_value(self, value):
"""Duck-type value and scramble appropriately"""
try:
type, format = typeof_rave_data(value)
if type == 'float':
i, f = value.split('.')
return self.scramble_float(len(value) - 1, len(f))
elif type == 'i... | [
"def",
"scramble_value",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"type",
",",
"format",
"=",
"typeof_rave_data",
"(",
"value",
")",
"if",
"type",
"==",
"'float'",
":",
"i",
",",
"f",
"=",
"value",
".",
"split",
"(",
"'.'",
")",
"return",
"... | Duck-type value and scramble appropriately | [
"Duck",
"-",
"type",
"value",
"and",
"scramble",
"appropriately"
] | python | train | 37.263158 |
dpgaspar/Flask-AppBuilder | flask_appbuilder/api/__init__.py | https://github.com/dpgaspar/Flask-AppBuilder/blob/c293734c1b86e176a3ba57ee2deab6676d125576/flask_appbuilder/api/__init__.py#L1156-L1238 | def get_list(self, **kwargs):
"""Get list of items from Model
---
get:
parameters:
- $ref: '#/components/parameters/get_list_schema'
responses:
200:
description: Items from Model
content:
application/json:
... | [
"def",
"get_list",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"_response",
"=",
"dict",
"(",
")",
"_args",
"=",
"kwargs",
".",
"get",
"(",
"\"rison\"",
",",
"{",
"}",
")",
"# handle select columns",
"select_cols",
"=",
"_args",
".",
"get",
"(",
... | Get list of items from Model
---
get:
parameters:
- $ref: '#/components/parameters/get_list_schema'
responses:
200:
description: Items from Model
content:
application/json:
schema:
... | [
"Get",
"list",
"of",
"items",
"from",
"Model",
"---",
"get",
":",
"parameters",
":",
"-",
"$ref",
":",
"#",
"/",
"components",
"/",
"parameters",
"/",
"get_list_schema",
"responses",
":",
"200",
":",
"description",
":",
"Items",
"from",
"Model",
"content",... | python | train | 35.722892 |
pgmpy/pgmpy | pgmpy/sampling/base.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/sampling/base.py#L130-L138 | def _get_gradient_log_pdf(self):
"""
Method that finds gradient and its log at position
"""
sub_vec = self.variable_assignments - self.model.mean.flatten()
grad = - np.dot(self.model.precision_matrix, sub_vec)
log_pdf = 0.5 * np.dot(sub_vec, grad)
return grad, lo... | [
"def",
"_get_gradient_log_pdf",
"(",
"self",
")",
":",
"sub_vec",
"=",
"self",
".",
"variable_assignments",
"-",
"self",
".",
"model",
".",
"mean",
".",
"flatten",
"(",
")",
"grad",
"=",
"-",
"np",
".",
"dot",
"(",
"self",
".",
"model",
".",
"precision... | Method that finds gradient and its log at position | [
"Method",
"that",
"finds",
"gradient",
"and",
"its",
"log",
"at",
"position"
] | python | train | 35.222222 |
noisyboiler/wampy | wampy/mixins.py | https://github.com/noisyboiler/wampy/blob/7c7ef246fec1b2bf3ec3a0e24c85c42fdd99d4bf/wampy/mixins.py#L12-L64 | def parse_url(self):
""" Parses a URL of the form:
- ws://host[:port][path]
- wss://host[:port][path]
- ws+unix:///path/to/my.socket
"""
self.scheme = None
self.resource = None
self.host = None
self.port = None
if self.url is None:
... | [
"def",
"parse_url",
"(",
"self",
")",
":",
"self",
".",
"scheme",
"=",
"None",
"self",
".",
"resource",
"=",
"None",
"self",
".",
"host",
"=",
"None",
"self",
".",
"port",
"=",
"None",
"if",
"self",
".",
"url",
"is",
"None",
":",
"return",
"scheme"... | Parses a URL of the form:
- ws://host[:port][path]
- wss://host[:port][path]
- ws+unix:///path/to/my.socket | [
"Parses",
"a",
"URL",
"of",
"the",
"form",
":"
] | python | train | 24.716981 |
swilson/aqualogic | aqualogic/core.py | https://github.com/swilson/aqualogic/blob/b6e904363efc4f64c70aae127d040079587ecbc6/aqualogic/core.py#L417-L455 | def set_state(self, state, enable):
"""Set the state."""
is_enabled = self.get_state(state)
if is_enabled == enable:
return True
key = None
desired_states = [{'state': state, 'enabled': not is_enabled}]
if state == States.FILTER_LOW_SPEED:
if no... | [
"def",
"set_state",
"(",
"self",
",",
"state",
",",
"enable",
")",
":",
"is_enabled",
"=",
"self",
".",
"get_state",
"(",
"state",
")",
"if",
"is_enabled",
"==",
"enable",
":",
"return",
"True",
"key",
"=",
"None",
"desired_states",
"=",
"[",
"{",
"'st... | Set the state. | [
"Set",
"the",
"state",
"."
] | python | train | 38.102564 |
loli/medpy | doc/numpydoc/numpydoc/traitsdoc.py | https://github.com/loli/medpy/blob/95216b9e22e7ce301f0edf953ee2a2f1b6c6aee5/doc/numpydoc/numpydoc/traitsdoc.py#L102-L114 | def looks_like_issubclass(obj, classname):
""" Return True if the object has a class or superclass with the given class
name.
Ignores old-style classes.
"""
t = obj
if t.__name__ == classname:
return True
for klass in t.__mro__:
if klass.__name__ == classname:
re... | [
"def",
"looks_like_issubclass",
"(",
"obj",
",",
"classname",
")",
":",
"t",
"=",
"obj",
"if",
"t",
".",
"__name__",
"==",
"classname",
":",
"return",
"True",
"for",
"klass",
"in",
"t",
".",
"__mro__",
":",
"if",
"klass",
".",
"__name__",
"==",
"classn... | Return True if the object has a class or superclass with the given class
name.
Ignores old-style classes. | [
"Return",
"True",
"if",
"the",
"object",
"has",
"a",
"class",
"or",
"superclass",
"with",
"the",
"given",
"class",
"name",
"."
] | python | train | 25.692308 |
moonlitesolutions/SolrClient | SolrClient/solrclient.py | https://github.com/moonlitesolutions/SolrClient/blob/19c5280c9f8e97ee104d22ae883c4ccfd7c4f43b/SolrClient/solrclient.py#L131-L144 | def index(self, collection, docs, params=None, min_rf=None, **kwargs):
"""
:param str collection: The name of the collection for the request.
:param docs list docs: List of dicts. ex: [{"title": "testing solr indexing", "id": "test1"}]
:param min_rf int min_rf: Required number of replica... | [
"def",
"index",
"(",
"self",
",",
"collection",
",",
"docs",
",",
"params",
"=",
"None",
",",
"min_rf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"docs",
")",
"return",
"self",
".",
"index_json",
"(",
... | :param str collection: The name of the collection for the request.
:param docs list docs: List of dicts. ex: [{"title": "testing solr indexing", "id": "test1"}]
:param min_rf int min_rf: Required number of replicas to write to'
Sends supplied list of dicts to solr for indexing. ::
... | [
":",
"param",
"str",
"collection",
":",
"The",
"name",
"of",
"the",
"collection",
"for",
"the",
"request",
".",
":",
"param",
"docs",
"list",
"docs",
":",
"List",
"of",
"dicts",
".",
"ex",
":",
"[",
"{",
"title",
":",
"testing",
"solr",
"indexing",
"... | python | train | 47.714286 |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/pymongo/cursor.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/cursor.py#L1128-L1140 | def next(self):
"""Advance the cursor."""
if self.__empty:
raise StopIteration
if len(self.__data) or self._refresh():
if self.__manipulate:
_db = self.__collection.database
return _db._fix_outgoing(self.__data.popleft(),
... | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"__empty",
":",
"raise",
"StopIteration",
"if",
"len",
"(",
"self",
".",
"__data",
")",
"or",
"self",
".",
"_refresh",
"(",
")",
":",
"if",
"self",
".",
"__manipulate",
":",
"_db",
"=",
"self... | Advance the cursor. | [
"Advance",
"the",
"cursor",
"."
] | python | train | 35.230769 |
saltstack/salt | salt/output/raw.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/raw.py#L29-L35 | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Rather basic....
'''
if not isinstance(data, six.string_types):
data = six.text_type(data)
return salt.utils.stringutils.to_unicode(data) | [
"def",
"output",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"if",
"not",
"isinstance",
"(",
"data",
",",
"six",
".",
"string_types",
")",
":",
"data",
"=",
"six",
".",
"text_type",
"(",
"data",
")",
"return",
"sa... | Rather basic.... | [
"Rather",
"basic",
"...."
] | python | train | 32.285714 |
manahl/arctic | arctic/date/_util.py | https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/date/_util.py#L164-L170 | def datetime_to_ms(d):
"""Convert a Python datetime object to a millisecond epoch (UTC) time value."""
try:
millisecond = d.microsecond // 1000
return calendar.timegm(_add_tzone(d).utctimetuple()) * 1000 + millisecond
except AttributeError:
raise TypeError('expect Python datetime obj... | [
"def",
"datetime_to_ms",
"(",
"d",
")",
":",
"try",
":",
"millisecond",
"=",
"d",
".",
"microsecond",
"//",
"1000",
"return",
"calendar",
".",
"timegm",
"(",
"_add_tzone",
"(",
"d",
")",
".",
"utctimetuple",
"(",
")",
")",
"*",
"1000",
"+",
"millisecon... | Convert a Python datetime object to a millisecond epoch (UTC) time value. | [
"Convert",
"a",
"Python",
"datetime",
"object",
"to",
"a",
"millisecond",
"epoch",
"(",
"UTC",
")",
"time",
"value",
"."
] | python | train | 48.142857 |
dw/mitogen | ansible_mitogen/plugins/connection/mitogen_local.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/plugins/connection/mitogen_local.py#L78-L86 | def get_default_env(self):
"""
Vanilla Ansible local commands execute with an environment inherited
from WorkerProcess, we must emulate that.
"""
return dict_diff(
old=ansible_mitogen.process.MuxProcess.original_env,
new=os.environ,
) | [
"def",
"get_default_env",
"(",
"self",
")",
":",
"return",
"dict_diff",
"(",
"old",
"=",
"ansible_mitogen",
".",
"process",
".",
"MuxProcess",
".",
"original_env",
",",
"new",
"=",
"os",
".",
"environ",
",",
")"
] | Vanilla Ansible local commands execute with an environment inherited
from WorkerProcess, we must emulate that. | [
"Vanilla",
"Ansible",
"local",
"commands",
"execute",
"with",
"an",
"environment",
"inherited",
"from",
"WorkerProcess",
"we",
"must",
"emulate",
"that",
"."
] | python | train | 33.111111 |
micha030201/aionationstates | aionationstates/world_.py | https://github.com/micha030201/aionationstates/blob/dc86b86d994cbab830b69ab8023601c73e778b3a/aionationstates/world_.py#L177-L220 | def dispatchlist(self, *, author=None, category=None,
subcategory=None, sort='new'):
"""Find dispatches by certain criteria.
Parameters
----------
author : str
Name of the nation authoring the dispatch.
category : str
Dispatch's prima... | [
"def",
"dispatchlist",
"(",
"self",
",",
"*",
",",
"author",
"=",
"None",
",",
"category",
"=",
"None",
",",
"subcategory",
"=",
"None",
",",
"sort",
"=",
"'new'",
")",
":",
"params",
"=",
"{",
"'sort'",
":",
"sort",
"}",
"if",
"author",
":",
"para... | Find dispatches by certain criteria.
Parameters
----------
author : str
Name of the nation authoring the dispatch.
category : str
Dispatch's primary category.
subcategory : str
Dispatch's secondary category.
sort : str
Sort... | [
"Find",
"dispatches",
"by",
"certain",
"criteria",
"."
] | python | train | 36.909091 |
dslackw/slpkg | slpkg/tracking.py | https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/tracking.py#L183-L196 | def deps_tree(self):
"""Package dependencies image map file
"""
dependencies = self.dependencies + [self.name]
if self.repo == "sbo":
for dep in dependencies:
deps = Requires(flag="").sbo(dep)
if dep not in self.deps_dict.values():
... | [
"def",
"deps_tree",
"(",
"self",
")",
":",
"dependencies",
"=",
"self",
".",
"dependencies",
"+",
"[",
"self",
".",
"name",
"]",
"if",
"self",
".",
"repo",
"==",
"\"sbo\"",
":",
"for",
"dep",
"in",
"dependencies",
":",
"deps",
"=",
"Requires",
"(",
"... | Package dependencies image map file | [
"Package",
"dependencies",
"image",
"map",
"file"
] | python | train | 44.714286 |
rootpy/rootpy | rootpy/plotting/root2matplotlib.py | https://github.com/rootpy/rootpy/blob/3926935e1f2100d8ba68070c2ab44055d4800f73/rootpy/plotting/root2matplotlib.py#L141-L265 | def hist(hists,
stacked=True,
reverse=False,
xpadding=0, ypadding=.1,
yerror_in_padding=True,
logy=None,
snap=True,
axes=None,
**kwargs):
"""
Make a matplotlib hist plot from a ROOT histogram, stack or
list of histograms.
Parameter... | [
"def",
"hist",
"(",
"hists",
",",
"stacked",
"=",
"True",
",",
"reverse",
"=",
"False",
",",
"xpadding",
"=",
"0",
",",
"ypadding",
"=",
".1",
",",
"yerror_in_padding",
"=",
"True",
",",
"logy",
"=",
"None",
",",
"snap",
"=",
"True",
",",
"axes",
"... | Make a matplotlib hist plot from a ROOT histogram, stack or
list of histograms.
Parameters
----------
hists : Hist, list of Hist, HistStack
The histogram(s) to be plotted
stacked : bool, optional (default=True)
If True then stack the histograms with the first histogram on the
... | [
"Make",
"a",
"matplotlib",
"hist",
"plot",
"from",
"a",
"ROOT",
"histogram",
"stack",
"or",
"list",
"of",
"histograms",
"."
] | python | train | 36.752 |
GetRektByMe/Raitonoberu | Raitonoberu/raitonoberu.py | https://github.com/GetRektByMe/Raitonoberu/blob/c35f83cb1c5268b7e641146bc8c6139fbc10e20f/Raitonoberu/raitonoberu.py#L69-L108 | def _get_related_series(parse_info):
"""get related_series from parse info.
:param parse_info: Parsed info from html soup.
"""
seriesother_tags = [x for x in parse_info.select('h5.seriesother')]
sibling_tag = [x for x in seriesother_tags if x.text == 'Related Series'][0]
... | [
"def",
"_get_related_series",
"(",
"parse_info",
")",
":",
"seriesother_tags",
"=",
"[",
"x",
"for",
"x",
"in",
"parse_info",
".",
"select",
"(",
"'h5.seriesother'",
")",
"]",
"sibling_tag",
"=",
"[",
"x",
"for",
"x",
"in",
"seriesother_tags",
"if",
"x",
"... | get related_series from parse info.
:param parse_info: Parsed info from html soup. | [
"get",
"related_series",
"from",
"parse",
"info",
"."
] | python | train | 37.65 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_system_monitor.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_system_monitor.py#L337-L348 | def system_monitor_SFM_threshold_down_threshold(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
SFM = ET.SubElement(system_monitor, "SFM")
... | [
"def",
"system_monitor_SFM_threshold_down_threshold",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"system_monitor",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"system-monitor\"",
",",
"x... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 47.75 |
LeonardMH/namealizer | namealizer/namealizer.py | https://github.com/LeonardMH/namealizer/blob/ef09492fb4565b692fda329dc02b8c4364f1cc0a/namealizer/namealizer.py#L211-L223 | def string_for_count(dictionary, count):
"""Create a random string of N=`count` words"""
string_to_print = ""
if count is not None:
if count == 0:
return ""
ranger = count
else:
ranger = 2
for index in range(ranger):
string_to_print += "{} ".format(get_ran... | [
"def",
"string_for_count",
"(",
"dictionary",
",",
"count",
")",
":",
"string_to_print",
"=",
"\"\"",
"if",
"count",
"is",
"not",
"None",
":",
"if",
"count",
"==",
"0",
":",
"return",
"\"\"",
"ranger",
"=",
"count",
"else",
":",
"ranger",
"=",
"2",
"fo... | Create a random string of N=`count` words | [
"Create",
"a",
"random",
"string",
"of",
"N",
"=",
"count",
"words"
] | python | train | 28.076923 |
alorence/django-modern-rpc | modernrpc/auth/basic.py | https://github.com/alorence/django-modern-rpc/blob/6dc42857d35764b24e2c09334f4b578629a75f9e/modernrpc/auth/basic.py#L68-L78 | def http_basic_auth_superuser_required(func=None):
"""Decorator. Use it to specify a RPC method is available only to logged superusers"""
wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_superuser])
# If @http_basic_auth_superuser_required() is used (with parenthesis)
... | [
"def",
"http_basic_auth_superuser_required",
"(",
"func",
"=",
"None",
")",
":",
"wrapper",
"=",
"auth",
".",
"set_authentication_predicate",
"(",
"http_basic_auth_check_user",
",",
"[",
"auth",
".",
"user_is_superuser",
"]",
")",
"# If @http_basic_auth_superuser_required... | Decorator. Use it to specify a RPC method is available only to logged superusers | [
"Decorator",
".",
"Use",
"it",
"to",
"specify",
"a",
"RPC",
"method",
"is",
"available",
"only",
"to",
"logged",
"superusers"
] | python | train | 41.090909 |
maraujop/requests-oauth | oauth_hook/hook.py | https://github.com/maraujop/requests-oauth/blob/51bdf115a259ce326e7894d1a68470387ecd5f22/oauth_hook/hook.py#L67-L104 | def get_normalized_parameters(request):
"""
Returns a string that contains the parameters that must be signed.
This function is called by SignatureMethod subclass CustomSignatureMethod_HMAC_SHA1
"""
# See issues #10 and #12
if ('Content-Type' not in request.headers or \
... | [
"def",
"get_normalized_parameters",
"(",
"request",
")",
":",
"# See issues #10 and #12",
"if",
"(",
"'Content-Type'",
"not",
"in",
"request",
".",
"headers",
"or",
"request",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
")",
".",
"startswith",
"(",
"'appl... | Returns a string that contains the parameters that must be signed.
This function is called by SignatureMethod subclass CustomSignatureMethod_HMAC_SHA1 | [
"Returns",
"a",
"string",
"that",
"contains",
"the",
"parameters",
"that",
"must",
"be",
"signed",
".",
"This",
"function",
"is",
"called",
"by",
"SignatureMethod",
"subclass",
"CustomSignatureMethod_HMAC_SHA1"
] | python | train | 45.447368 |
rocky/python-uncompyle6 | uncompyle6/semantics/helper.py | https://github.com/rocky/python-uncompyle6/blob/c5d7944e657f0ad05a0e2edd34e1acb27001abc0/uncompyle6/semantics/helper.py#L30-L45 | def find_globals_and_nonlocals(node, globs, nonlocals, code, version):
"""search a node of parse tree to find variable names that need a
either 'global' or 'nonlocal' statements added."""
for n in node:
if isinstance(n, SyntaxTree):
globs, nonlocals = find_globals_and_nonlocals(n, globs,... | [
"def",
"find_globals_and_nonlocals",
"(",
"node",
",",
"globs",
",",
"nonlocals",
",",
"code",
",",
"version",
")",
":",
"for",
"n",
"in",
"node",
":",
"if",
"isinstance",
"(",
"n",
",",
"SyntaxTree",
")",
":",
"globs",
",",
"nonlocals",
"=",
"find_globa... | search a node of parse tree to find variable names that need a
either 'global' or 'nonlocal' statements added. | [
"search",
"a",
"node",
"of",
"parse",
"tree",
"to",
"find",
"variable",
"names",
"that",
"need",
"a",
"either",
"global",
"or",
"nonlocal",
"statements",
"added",
"."
] | python | train | 45.5625 |
secdev/scapy | scapy/compat.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/compat.py#L95-L99 | def bytes_base64(x):
"""Turn bytes into base64"""
if six.PY2:
return base64.encodestring(x).replace('\n', '')
return base64.encodebytes(bytes_encode(x)).replace(b'\n', b'') | [
"def",
"bytes_base64",
"(",
"x",
")",
":",
"if",
"six",
".",
"PY2",
":",
"return",
"base64",
".",
"encodestring",
"(",
"x",
")",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
"return",
"base64",
".",
"encodebytes",
"(",
"bytes_encode",
"(",
"x",
")",... | Turn bytes into base64 | [
"Turn",
"bytes",
"into",
"base64"
] | python | train | 37.6 |
aio-libs/aioftp | aioftp/client.py | https://github.com/aio-libs/aioftp/blob/b45395b1aba41301b898040acade7010e6878a08/aioftp/client.py#L618-L632 | async def change_directory(self, path=".."):
"""
:py:func:`asyncio.coroutine`
Change current directory. Goes «up» if no parameters passed.
:param path: new directory, goes «up» if omitted
:type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath`
"""
path ... | [
"async",
"def",
"change_directory",
"(",
"self",
",",
"path",
"=",
"\"..\"",
")",
":",
"path",
"=",
"pathlib",
".",
"PurePosixPath",
"(",
"path",
")",
"if",
"path",
"==",
"pathlib",
".",
"PurePosixPath",
"(",
"\"..\"",
")",
":",
"cmd",
"=",
"\"CDUP\"",
... | :py:func:`asyncio.coroutine`
Change current directory. Goes «up» if no parameters passed.
:param path: new directory, goes «up» if omitted
:type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath` | [
":",
"py",
":",
"func",
":",
"asyncio",
".",
"coroutine"
] | python | valid | 33.2 |
saltstack/salt | salt/modules/saltcheck.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltcheck.py#L678-L692 | def __assert_false(returned):
'''
Test if an boolean is False
'''
result = "Pass"
if isinstance(returned, str):
try:
returned = bool(returned)
except ValueError:
raise
try:
assert (returned is False), "{0... | [
"def",
"__assert_false",
"(",
"returned",
")",
":",
"result",
"=",
"\"Pass\"",
"if",
"isinstance",
"(",
"returned",
",",
"str",
")",
":",
"try",
":",
"returned",
"=",
"bool",
"(",
"returned",
")",
"except",
"ValueError",
":",
"raise",
"try",
":",
"assert... | Test if an boolean is False | [
"Test",
"if",
"an",
"boolean",
"is",
"False"
] | python | train | 29.733333 |
gem/oq-engine | openquake/commonlib/shapefileparser.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/shapefileparser.py#L489-L496 | def set_area_geometry(w, src):
"""
Set area polygon as shapefile geometry
"""
assert "areaSource" in src.tag
geometry_node = src.nodes[get_taglist(src).index("areaGeometry")]
area_attrs = parse_area_geometry(geometry_node)
w.poly(parts=[area_attrs["polygon"].tolist()]) | [
"def",
"set_area_geometry",
"(",
"w",
",",
"src",
")",
":",
"assert",
"\"areaSource\"",
"in",
"src",
".",
"tag",
"geometry_node",
"=",
"src",
".",
"nodes",
"[",
"get_taglist",
"(",
"src",
")",
".",
"index",
"(",
"\"areaGeometry\"",
")",
"]",
"area_attrs",
... | Set area polygon as shapefile geometry | [
"Set",
"area",
"polygon",
"as",
"shapefile",
"geometry"
] | python | train | 36.25 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_xstp_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_xstp_ext.py#L4861-L4876 | def get_stp_mst_detail_output_msti_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti... | [
"def",
"get_stp_mst_detail_output_msti_port_admin_edge",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_stp_mst_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_stp_mst_detail\"",
")",
"config",
"... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 43.4375 |
hydpy-dev/hydpy | hydpy/cythons/modelutils.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L1194-L1215 | def remove_imath_operators(lines):
"""Remove mathematical expressions that require Pythons global
interpreter locking mechanism.
This is not a exhaustive test, but shows how the method works:
>>> lines = [' x += 1*1']
>>> from hydpy.cythons.modelutils import FuncConverter
... | [
"def",
"remove_imath_operators",
"(",
"lines",
")",
":",
"for",
"idx",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"for",
"operator",
"in",
"(",
"'+='",
",",
"'-='",
",",
"'**='",
",",
"'*='",
",",
"'//='",
",",
"'/='",
",",
"'%='",
")",
... | Remove mathematical expressions that require Pythons global
interpreter locking mechanism.
This is not a exhaustive test, but shows how the method works:
>>> lines = [' x += 1*1']
>>> from hydpy.cythons.modelutils import FuncConverter
>>> FuncConverter.remove_imath_operators... | [
"Remove",
"mathematical",
"expressions",
"that",
"require",
"Pythons",
"global",
"interpreter",
"locking",
"mechanism",
"."
] | python | train | 43.863636 |
LuminosoInsight/langcodes | langcodes/names.py | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/names.py#L89-L105 | def code_to_names(category, code):
"""
Given the code for a language, script, or region, get a dictionary of its
names in various languages.
"""
trie_name = '{}_to_name'.format(category)
if trie_name not in TRIES:
TRIES[trie_name] = load_trie(data_filename('trie/{}.marisa'.format(trie_na... | [
"def",
"code_to_names",
"(",
"category",
",",
"code",
")",
":",
"trie_name",
"=",
"'{}_to_name'",
".",
"format",
"(",
"category",
")",
"if",
"trie_name",
"not",
"in",
"TRIES",
":",
"TRIES",
"[",
"trie_name",
"]",
"=",
"load_trie",
"(",
"data_filename",
"("... | Given the code for a language, script, or region, get a dictionary of its
names in various languages. | [
"Given",
"the",
"code",
"for",
"a",
"language",
"script",
"or",
"region",
"get",
"a",
"dictionary",
"of",
"its",
"names",
"in",
"various",
"languages",
"."
] | python | train | 33.705882 |
jxtech/wechatpy | wechatpy/oauth.py | https://github.com/jxtech/wechatpy/blob/4df0da795618c0895a10f1c2cde9e9d5c0a93aaa/wechatpy/oauth.py#L98-L116 | def authorize_url(self):
"""获取授权跳转地址
:return: URL 地址
"""
redirect_uri = quote(self.redirect_uri, safe=b'')
url_list = [
self.OAUTH_BASE_URL,
'oauth2/authorize?appid=',
self.app_id,
'&redirect_uri=',
redirect_uri,
... | [
"def",
"authorize_url",
"(",
"self",
")",
":",
"redirect_uri",
"=",
"quote",
"(",
"self",
".",
"redirect_uri",
",",
"safe",
"=",
"b''",
")",
"url_list",
"=",
"[",
"self",
".",
"OAUTH_BASE_URL",
",",
"'oauth2/authorize?appid='",
",",
"self",
".",
"app_id",
... | 获取授权跳转地址
:return: URL 地址 | [
"获取授权跳转地址"
] | python | train | 27.526316 |
cokelaer/spectrum | src/spectrum/window.py | https://github.com/cokelaer/spectrum/blob/bad6c32e3f10e185098748f67bb421b378b06afe/src/spectrum/window.py#L228-L264 | def plot_frequencies(self, mindB=None, maxdB=None, norm=True):
"""Plot the window in the frequency domain
:param mindB: change the default lower y bound
:param maxdB: change the default upper lower bound
:param bool norm: if True, normalise the frequency response.
.. plot::
... | [
"def",
"plot_frequencies",
"(",
"self",
",",
"mindB",
"=",
"None",
",",
"maxdB",
"=",
"None",
",",
"norm",
"=",
"True",
")",
":",
"from",
"pylab",
"import",
"plot",
",",
"title",
",",
"xlim",
",",
"grid",
",",
"ylim",
",",
"xlabel",
",",
"ylabel",
... | Plot the window in the frequency domain
:param mindB: change the default lower y bound
:param maxdB: change the default upper lower bound
:param bool norm: if True, normalise the frequency response.
.. plot::
:width: 80%
:include-source:
from spectr... | [
"Plot",
"the",
"window",
"in",
"the",
"frequency",
"domain"
] | python | valid | 28.72973 |
wmayner/pyphi | pyphi/compute/subsystem.py | https://github.com/wmayner/pyphi/blob/deeca69a084d782a6fde7bf26f59e93b593c5d77/pyphi/compute/subsystem.py#L170-L181 | def process_result(self, new_sia, min_sia):
"""Check if the new SIA has smaller |big_phi| than the standing
result.
"""
if new_sia.phi == 0:
self.done = True # Short-circuit
return new_sia
elif new_sia < min_sia:
return new_sia
retur... | [
"def",
"process_result",
"(",
"self",
",",
"new_sia",
",",
"min_sia",
")",
":",
"if",
"new_sia",
".",
"phi",
"==",
"0",
":",
"self",
".",
"done",
"=",
"True",
"# Short-circuit",
"return",
"new_sia",
"elif",
"new_sia",
"<",
"min_sia",
":",
"return",
"new_... | Check if the new SIA has smaller |big_phi| than the standing
result. | [
"Check",
"if",
"the",
"new",
"SIA",
"has",
"smaller",
"|big_phi|",
"than",
"the",
"standing",
"result",
"."
] | python | train | 26.5 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/serverlib_fallback.py | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/serverlib_fallback.py#L140-L174 | async def update_api(request: web.Request) -> web.Response:
"""
This handler accepts a POST request with Content-Type: multipart/form-data
and file fields in the body named "whl", "serverlib", and "fw". The "whl"
and "serverlib" files should be valid Python wheels to be installed ("whl"
is expected ... | [
"async",
"def",
"update_api",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"Response",
":",
"log",
".",
"debug",
"(",
"'Update request received'",
")",
"data",
"=",
"await",
"request",
".",
"post",
"(",
")",
"try",
":",
"res0",
"=... | This handler accepts a POST request with Content-Type: multipart/form-data
and file fields in the body named "whl", "serverlib", and "fw". The "whl"
and "serverlib" files should be valid Python wheels to be installed ("whl"
is expected generally to be the API server wheel, and "serverlib" is
expected to... | [
"This",
"handler",
"accepts",
"a",
"POST",
"request",
"with",
"Content",
"-",
"Type",
":",
"multipart",
"/",
"form",
"-",
"data",
"and",
"file",
"fields",
"in",
"the",
"body",
"named",
"whl",
"serverlib",
"and",
"fw",
".",
"The",
"whl",
"and",
"serverlib... | python | train | 43.314286 |
Skype4Py/Skype4Py | Skype4Py/skype.py | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L797-L816 | def SendSms(self, *TargetNumbers, **Properties):
"""Creates and sends an SMS message.
:Parameters:
TargetNumbers : str
One or more target SMS numbers.
Properties
Message properties. Properties available are same as `SmsMessage` object properties.
:re... | [
"def",
"SendSms",
"(",
"self",
",",
"*",
"TargetNumbers",
",",
"*",
"*",
"Properties",
")",
":",
"sms",
"=",
"self",
".",
"CreateSms",
"(",
"smsMessageTypeOutgoing",
",",
"*",
"TargetNumbers",
")",
"for",
"name",
",",
"value",
"in",
"Properties",
".",
"i... | Creates and sends an SMS message.
:Parameters:
TargetNumbers : str
One or more target SMS numbers.
Properties
Message properties. Properties available are same as `SmsMessage` object properties.
:return: An sms message object. The message is already sent at ... | [
"Creates",
"and",
"sends",
"an",
"SMS",
"message",
"."
] | python | train | 38.15 |
MacHu-GWU/single_file_module-project | sfm/textformatter.py | https://github.com/MacHu-GWU/single_file_module-project/blob/01f7a6b250853bebfd73de275895bf274325cfc1/sfm/textformatter.py#L150-L176 | def format_unix_var(text):
"""
Example::
this_is_very_good
"""
text = text.strip()
if len(text) == 0: # if empty string, return it
raise ValueError("can not be empty string!")
else:
if text[0] in string.digits:
raise ValueError("variable can not start with d... | [
"def",
"format_unix_var",
"(",
"text",
")",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"text",
")",
"==",
"0",
":",
"# if empty string, return it",
"raise",
"ValueError",
"(",
"\"can not be empty string!\"",
")",
"else",
":",
"if",
... | Example::
this_is_very_good | [
"Example",
"::"
] | python | train | 27.222222 |
vasilcovsky/pytinypng | pytinypng/pytinypng.py | https://github.com/vasilcovsky/pytinypng/blob/ac633e4aa41122c49a806f411e43a76d8f73058e/pytinypng/pytinypng.py#L52-L104 | def process_directory(source, target, apikey, handler, overwrite=False):
"""Optimize and save png files form source to target directory.
@param source: path to input directory
@param target: path to output directory
@param handler: callback holder, instance of handlers.BaseHandler
@param overwrite:... | [
"def",
"process_directory",
"(",
"source",
",",
"target",
",",
"apikey",
",",
"handler",
",",
"overwrite",
"=",
"False",
")",
":",
"handler",
".",
"on_start",
"(",
")",
"attempts",
"=",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"input_files",
"=",
"fi... | Optimize and save png files form source to target directory.
@param source: path to input directory
@param target: path to output directory
@param handler: callback holder, instance of handlers.BaseHandler
@param overwrite: boolean flag to allow overwrite already existing
files in... | [
"Optimize",
"and",
"save",
"png",
"files",
"form",
"source",
"to",
"target",
"directory",
"."
] | python | train | 33.867925 |
welbornprod/colr | colr/__main__.py | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L347-L387 | def list_names():
""" List all known color names. """
names = get_all_names()
# This is 375 right now. Probably won't ever change, but I'm not sure.
nameslen = len(names)
print('\nListing {} names:\n'.format(nameslen))
# Using 3 columns of names, still alphabetically sorted from the top down.
... | [
"def",
"list_names",
"(",
")",
":",
"names",
"=",
"get_all_names",
"(",
")",
"# This is 375 right now. Probably won't ever change, but I'm not sure.",
"nameslen",
"=",
"len",
"(",
"names",
")",
"print",
"(",
"'\\nListing {} names:\\n'",
".",
"format",
"(",
"nameslen",
... | List all known color names. | [
"List",
"all",
"known",
"color",
"names",
"."
] | python | train | 31.02439 |
willhardy/django-seo | rollyourown/seo/backends.py | https://github.com/willhardy/django-seo/blob/3089686a3c490091315860979ad15ef2527c3e3e/rollyourown/seo/backends.py#L331-L341 | def _resolve(value, model_instance=None, context=None):
""" Resolves any template references in the given value.
"""
if isinstance(value, basestring) and "{" in value:
if context is None:
context = Context()
if model_instance is not None:
context[model_instance._met... | [
"def",
"_resolve",
"(",
"value",
",",
"model_instance",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"and",
"\"{\"",
"in",
"value",
":",
"if",
"context",
"is",
"None",
":",
"context",
"="... | Resolves any template references in the given value. | [
"Resolves",
"any",
"template",
"references",
"in",
"the",
"given",
"value",
"."
] | python | train | 36.909091 |
gwastro/pycbc | pycbc/vetoes/chisq.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/vetoes/chisq.py#L109-L136 | def power_chisq_at_points_from_precomputed(corr, snr, snr_norm, bins, indices):
"""Calculate the chisq timeseries from precomputed values for only select points.
This function calculates the chisq at each point by explicitly time shifting
and summing each bin. No FFT is involved.
Parameters
------... | [
"def",
"power_chisq_at_points_from_precomputed",
"(",
"corr",
",",
"snr",
",",
"snr_norm",
",",
"bins",
",",
"indices",
")",
":",
"num_bins",
"=",
"len",
"(",
"bins",
")",
"-",
"1",
"chisq",
"=",
"shift_sum",
"(",
"corr",
",",
"indices",
",",
"bins",
")"... | Calculate the chisq timeseries from precomputed values for only select points.
This function calculates the chisq at each point by explicitly time shifting
and summing each bin. No FFT is involved.
Parameters
----------
corr: FrequencySeries
The product of the template and data in the freq... | [
"Calculate",
"the",
"chisq",
"timeseries",
"from",
"precomputed",
"values",
"for",
"only",
"select",
"points",
"."
] | python | train | 39.642857 |
empymod/empymod | empymod/model.py | https://github.com/empymod/empymod/blob/4a78ca4191ed4b4d42d019ce715a9a3889dba1bc/empymod/model.py#L593-L960 | def dipole(src, rec, depth, res, freqtime, signal=None, ab=11, aniso=None,
epermH=None, epermV=None, mpermH=None, mpermV=None, xdirect=False,
ht='fht', htarg=None, ft='sin', ftarg=None, opt=None, loop=None,
verb=2):
r"""Return the electromagnetic field due to a dipole source.
C... | [
"def",
"dipole",
"(",
"src",
",",
"rec",
",",
"depth",
",",
"res",
",",
"freqtime",
",",
"signal",
"=",
"None",
",",
"ab",
"=",
"11",
",",
"aniso",
"=",
"None",
",",
"epermH",
"=",
"None",
",",
"epermV",
"=",
"None",
",",
"mpermH",
"=",
"None",
... | r"""Return the electromagnetic field due to a dipole source.
Calculate the electromagnetic frequency- or time-domain field due to
infinitesimal small electric or magnetic dipole source(s), measured by
infinitesimal small electric or magnetic dipole receiver(s); sources and
receivers are directed along ... | [
"r",
"Return",
"the",
"electromagnetic",
"field",
"due",
"to",
"a",
"dipole",
"source",
"."
] | python | train | 44.744565 |
saltstack/salt | salt/states/win_system.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_system.py#L364-L449 | def shutdown(name, message=None, timeout=5, force_close=True, reboot=False,
in_seconds=False, only_on_pending_reboot=False):
'''
Shutdown the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
... | [
"def",
"shutdown",
"(",
"name",
",",
"message",
"=",
"None",
",",
"timeout",
"=",
"5",
",",
"force_close",
"=",
"True",
",",
"reboot",
"=",
"False",
",",
"in_seconds",
"=",
"False",
",",
"only_on_pending_reboot",
"=",
"False",
")",
":",
"ret",
"=",
"{"... | Shutdown the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
The default value is None.
:param int timeout:
The number of minutes or seconds before a shutdown will occur. Whether
this numbe... | [
"Shutdown",
"the",
"computer"
] | python | train | 34.965116 |
callowayproject/Transmogrify | transmogrify/filesystem/s3.py | https://github.com/callowayproject/Transmogrify/blob/f1f891b8b923b3a1ede5eac7f60531c1c472379e/transmogrify/filesystem/s3.py#L9-L16 | def _parse_s3_file(original_file):
"""
Convert `s3://bucketname/path/to/file.txt` to ('bucketname', 'path/to/file.txt')
"""
bits = original_file.replace('s3://', '').split("/")
bucket = bits[0]
object_key = "/".join(bits[1:])
return bucket, object_key | [
"def",
"_parse_s3_file",
"(",
"original_file",
")",
":",
"bits",
"=",
"original_file",
".",
"replace",
"(",
"'s3://'",
",",
"''",
")",
".",
"split",
"(",
"\"/\"",
")",
"bucket",
"=",
"bits",
"[",
"0",
"]",
"object_key",
"=",
"\"/\"",
".",
"join",
"(",
... | Convert `s3://bucketname/path/to/file.txt` to ('bucketname', 'path/to/file.txt') | [
"Convert",
"s3",
":",
"//",
"bucketname",
"/",
"path",
"/",
"to",
"/",
"file",
".",
"txt",
"to",
"(",
"bucketname",
"path",
"/",
"to",
"/",
"file",
".",
"txt",
")"
] | python | train | 34 |
angr/angr | angr/analyses/girlscout.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/girlscout.py#L693-L746 | def _full_code_scan(self):
"""
Perform a full code scan on the target binary.
"""
# We gotta time this function
start_time = datetime.now()
traced_address = set()
self.functions = set()
self.call_map = networkx.DiGraph()
self.cfg = networkx.DiGra... | [
"def",
"_full_code_scan",
"(",
"self",
")",
":",
"# We gotta time this function",
"start_time",
"=",
"datetime",
".",
"now",
"(",
")",
"traced_address",
"=",
"set",
"(",
")",
"self",
".",
"functions",
"=",
"set",
"(",
")",
"self",
".",
"call_map",
"=",
"ne... | Perform a full code scan on the target binary. | [
"Perform",
"a",
"full",
"code",
"scan",
"on",
"the",
"target",
"binary",
"."
] | python | train | 38.462963 |
cortical-io/retina-sdk.py | retinasdk/client/classify_api.py | https://github.com/cortical-io/retina-sdk.py/blob/474c13ad399fe1e974d2650335537608f4456b07/retinasdk/client/classify_api.py#L21-L42 | def createCategoryFilter(self, retina_name, filter_name, body, ):
"""get filter for classifier
Args:
filter_name, str: A unique name for the filter. (required)
body, FilterTrainingObject: The list of positive and negative (optional) example items. (required)
retina_na... | [
"def",
"createCategoryFilter",
"(",
"self",
",",
"retina_name",
",",
"filter_name",
",",
"body",
",",
")",
":",
"resourcePath",
"=",
"'/classify/create_category_filter'",
"method",
"=",
"'POST'",
"queryParams",
"=",
"{",
"}",
"headerParams",
"=",
"{",
"'Accept'",
... | get filter for classifier
Args:
filter_name, str: A unique name for the filter. (required)
body, FilterTrainingObject: The list of positive and negative (optional) example items. (required)
retina_name, str: The retina name (required)
Returns: CategoryFilter | [
"get",
"filter",
"for",
"classifier",
"Args",
":",
"filter_name",
"str",
":",
"A",
"unique",
"name",
"for",
"the",
"filter",
".",
"(",
"required",
")",
"body",
"FilterTrainingObject",
":",
"The",
"list",
"of",
"positive",
"and",
"negative",
"(",
"optional",
... | python | train | 41.272727 |
UCL-INGI/INGInious | inginious/agent/__init__.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/__init__.py#L201-L224 | async def send_job_result(self, job_id: BackendJobId, result: str, text: str = "", grade: float = None, problems: Dict[str, SPResult] = None,
tests: Dict[str, Any] = None, custom: Dict[str, Any] = None, state: str = "", archive: Optional[bytes] = None,
stdout:... | [
"async",
"def",
"send_job_result",
"(",
"self",
",",
"job_id",
":",
"BackendJobId",
",",
"result",
":",
"str",
",",
"text",
":",
"str",
"=",
"\"\"",
",",
"grade",
":",
"float",
"=",
"None",
",",
"problems",
":",
"Dict",
"[",
"str",
",",
"SPResult",
"... | Send the result of a job back to the backend. Must be called *once and only once* for each job
:exception JobNotRunningException: is raised when send_job_result is called more than once for a given job_id | [
"Send",
"the",
"result",
"of",
"a",
"job",
"back",
"to",
"the",
"backend",
".",
"Must",
"be",
"called",
"*",
"once",
"and",
"only",
"once",
"*",
"for",
"each",
"job",
":",
"exception",
"JobNotRunningException",
":",
"is",
"raised",
"when",
"send_job_result... | python | train | 49.166667 |
CellProfiler/centrosome | centrosome/neighmovetrack.py | https://github.com/CellProfiler/centrosome/blob/7bd9350a2d4ae1b215b81eabcecfe560bbb1f32a/centrosome/neighmovetrack.py#L105-L126 | def from_labels(labels):
"""
Creates list of cell features based on label image (1-oo pixel values)
@return: list of cell features in the same order as labels
"""
labels = labels.astype(int)
areas = scipy.ndimage.measurements.sum(labels != 0, labels, list(range(1, numpy... | [
"def",
"from_labels",
"(",
"labels",
")",
":",
"labels",
"=",
"labels",
".",
"astype",
"(",
"int",
")",
"areas",
"=",
"scipy",
".",
"ndimage",
".",
"measurements",
".",
"sum",
"(",
"labels",
"!=",
"0",
",",
"labels",
",",
"list",
"(",
"range",
"(",
... | Creates list of cell features based on label image (1-oo pixel values)
@return: list of cell features in the same order as labels | [
"Creates",
"list",
"of",
"cell",
"features",
"based",
"on",
"label",
"image",
"(",
"1",
"-",
"oo",
"pixel",
"values",
")"
] | python | train | 34.636364 |
rocky/python3-trepan | trepan/lib/stack.py | https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/stack.py#L188-L224 | def get_call_function_name(frame):
"""If f_back is looking at a call function, return
the name for it. Otherwise return None"""
f_back = frame.f_back
if not f_back: return None
if 'CALL_FUNCTION' != Mbytecode.op_at_frame(f_back): return None
co = f_back.f_code
code = co.co_cod... | [
"def",
"get_call_function_name",
"(",
"frame",
")",
":",
"f_back",
"=",
"frame",
".",
"f_back",
"if",
"not",
"f_back",
":",
"return",
"None",
"if",
"'CALL_FUNCTION'",
"!=",
"Mbytecode",
".",
"op_at_frame",
"(",
"f_back",
")",
":",
"return",
"None",
"co",
"... | If f_back is looking at a call function, return
the name for it. Otherwise return None | [
"If",
"f_back",
"is",
"looking",
"at",
"a",
"call",
"function",
"return",
"the",
"name",
"for",
"it",
".",
"Otherwise",
"return",
"None"
] | python | test | 34.486486 |
apple/turicreate | src/unity/python/turicreate/data_structures/sgraph.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sgraph.py#L1229-L1238 | def _vertex_list_to_dataframe(ls, id_column_name):
"""
Convert a list of vertices into dataframe.
"""
assert HAS_PANDAS, 'Cannot use dataframe because Pandas is not available or version is too low.'
cols = reduce(set.union, (set(v.attr.keys()) for v in ls))
df = pd.DataFrame({id_column_name: [v.... | [
"def",
"_vertex_list_to_dataframe",
"(",
"ls",
",",
"id_column_name",
")",
":",
"assert",
"HAS_PANDAS",
",",
"'Cannot use dataframe because Pandas is not available or version is too low.'",
"cols",
"=",
"reduce",
"(",
"set",
".",
"union",
",",
"(",
"set",
"(",
"v",
".... | Convert a list of vertices into dataframe. | [
"Convert",
"a",
"list",
"of",
"vertices",
"into",
"dataframe",
"."
] | python | train | 40.6 |
mgedmin/findimports | findimports.py | https://github.com/mgedmin/findimports/blob/c20a50b497390fed15aa3835476f4fad57313e8a/findimports.py#L445-L461 | def parseFile(self, filename):
"""Parse a single file."""
modname = self.filenameToModname(filename)
module = Module(modname, filename)
self.modules[modname] = module
if self.trackUnusedNames:
module.imported_names, module.unused_names = \
find_imports... | [
"def",
"parseFile",
"(",
"self",
",",
"filename",
")",
":",
"modname",
"=",
"self",
".",
"filenameToModname",
"(",
"filename",
")",
"module",
"=",
"Module",
"(",
"modname",
",",
"filename",
")",
"self",
".",
"modules",
"[",
"modname",
"]",
"=",
"module",... | Parse a single file. | [
"Parse",
"a",
"single",
"file",
"."
] | python | train | 44.882353 |
carpyncho/feets | feets/libs/ls_fap.py | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/libs/ls_fap.py#L207-L215 | def fap_davies(Z, fmax, t, y, dy, normalization='standard'):
"""Davies upper-bound to the false alarm probability
(Eqn 5 of Baluev 2008)
"""
N = len(t)
fap_s = fap_single(Z, N, normalization=normalization)
tau = tau_davies(Z, fmax, t, y, dy, normalization=normalization)
return fap_s + tau | [
"def",
"fap_davies",
"(",
"Z",
",",
"fmax",
",",
"t",
",",
"y",
",",
"dy",
",",
"normalization",
"=",
"'standard'",
")",
":",
"N",
"=",
"len",
"(",
"t",
")",
"fap_s",
"=",
"fap_single",
"(",
"Z",
",",
"N",
",",
"normalization",
"=",
"normalization"... | Davies upper-bound to the false alarm probability
(Eqn 5 of Baluev 2008) | [
"Davies",
"upper",
"-",
"bound",
"to",
"the",
"false",
"alarm",
"probability"
] | python | train | 34.444444 |
jeremymcrae/denovonear | denovonear/load_gene.py | https://github.com/jeremymcrae/denovonear/blob/feaab0fc77e89d70b31e8092899e4f0e68bac9fe/denovonear/load_gene.py#L136-L159 | def load_gene(ensembl, gene_id, de_novos=[]):
""" sort out all the necessary sequences and positions for a gene
Args:
ensembl: EnsemblRequest object to request data from ensembl
gene_id: HGNC symbol for gene
de_novos: list of de novo positions, so we can check they all fit in
... | [
"def",
"load_gene",
"(",
"ensembl",
",",
"gene_id",
",",
"de_novos",
"=",
"[",
"]",
")",
":",
"transcripts",
"=",
"minimise_transcripts",
"(",
"ensembl",
",",
"gene_id",
",",
"de_novos",
")",
"genes",
"=",
"[",
"]",
"for",
"transcript_id",
"in",
"transcrip... | sort out all the necessary sequences and positions for a gene
Args:
ensembl: EnsemblRequest object to request data from ensembl
gene_id: HGNC symbol for gene
de_novos: list of de novo positions, so we can check they all fit in
the gene transcript
Returns:
... | [
"sort",
"out",
"all",
"the",
"necessary",
"sequences",
"and",
"positions",
"for",
"a",
"gene",
"Args",
":",
"ensembl",
":",
"EnsemblRequest",
"object",
"to",
"request",
"data",
"from",
"ensembl",
"gene_id",
":",
"HGNC",
"symbol",
"for",
"gene",
"de_novos",
"... | python | train | 32.416667 |
serge-sans-paille/pythran | pythran/spec.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/spec.py#L186-L189 | def t_IDENTIFER(self, t):
r'\#?[a-zA-Z_][a-zA-Z_0-9]*'
t.type = SpecParser.reserved.get(t.value, 'IDENTIFIER')
return t | [
"def",
"t_IDENTIFER",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"type",
"=",
"SpecParser",
".",
"reserved",
".",
"get",
"(",
"t",
".",
"value",
",",
"'IDENTIFIER'",
")",
"return",
"t"
] | r'\#?[a-zA-Z_][a-zA-Z_0-9]* | [
"r",
"\\",
"#?",
"[",
"a",
"-",
"zA",
"-",
"Z_",
"]",
"[",
"a",
"-",
"zA",
"-",
"Z_0",
"-",
"9",
"]",
"*"
] | python | train | 35 |
assamite/creamas | creamas/mp.py | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/mp.py#L556-L578 | async def spawn_slaves(self, slave_addrs, slave_env_cls, slave_mgr_cls,
slave_kwargs=None):
"""Spawn slave environments.
:param slave_addrs:
List of (HOST, PORT) addresses for the slave-environments.
:param slave_env_cls: Class for the slave environments.... | [
"async",
"def",
"spawn_slaves",
"(",
"self",
",",
"slave_addrs",
",",
"slave_env_cls",
",",
"slave_mgr_cls",
",",
"slave_kwargs",
"=",
"None",
")",
":",
"pool",
",",
"r",
"=",
"spawn_containers",
"(",
"slave_addrs",
",",
"env_cls",
"=",
"slave_env_cls",
",",
... | Spawn slave environments.
:param slave_addrs:
List of (HOST, PORT) addresses for the slave-environments.
:param slave_env_cls: Class for the slave environments.
:param slave_kwargs:
If not None, must be a list of the same size as *addrs*. Each item
in the l... | [
"Spawn",
"slave",
"environments",
"."
] | python | train | 40.695652 |
apache/airflow | airflow/api/common/experimental/get_task_instance.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/api/common/experimental/get_task_instance.py#L25-L55 | def get_task_instance(dag_id, task_id, execution_date):
"""Return the task object identified by the given dag_id and task_id."""
dagbag = DagBag()
# Check DAG exists.
if dag_id not in dagbag.dags:
error_message = "Dag id {} not found".format(dag_id)
raise DagNotFound(error_message)
... | [
"def",
"get_task_instance",
"(",
"dag_id",
",",
"task_id",
",",
"execution_date",
")",
":",
"dagbag",
"=",
"DagBag",
"(",
")",
"# Check DAG exists.",
"if",
"dag_id",
"not",
"in",
"dagbag",
".",
"dags",
":",
"error_message",
"=",
"\"Dag id {} not found\"",
".",
... | Return the task object identified by the given dag_id and task_id. | [
"Return",
"the",
"task",
"object",
"identified",
"by",
"the",
"given",
"dag_id",
"and",
"task_id",
"."
] | python | test | 37.16129 |
saltstack/salt | salt/modules/boto_cloudwatch_event.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudwatch_event.py#L89-L112 | def exists(Name, region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI example::
salt myminion boto_cloudwatch_event.exists myevent regio... | [
"def",
"exists",
"(",
"Name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"="... | Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI example::
salt myminion boto_cloudwatch_event.exists myevent region=us-east-1 | [
"Given",
"a",
"rule",
"name",
"check",
"to",
"see",
"if",
"the",
"given",
"rule",
"exists",
"."
] | python | train | 32.541667 |
mapbox/mapbox-sdk-py | mapbox/services/uploads.py | https://github.com/mapbox/mapbox-sdk-py/blob/72d19dbcf2d254a6ea08129a726471fd21f13023/mapbox/services/uploads.py#L119-L175 | def create(self, stage_url, tileset, name=None, patch=False, bypass=False):
"""Create a tileset
Note: this step is refered to as "upload" in the API docs;
This class's upload() method is a high-level function
which acts like the Studio upload form.
Returns a response object whe... | [
"def",
"create",
"(",
"self",
",",
"stage_url",
",",
"tileset",
",",
"name",
"=",
"None",
",",
"patch",
"=",
"False",
",",
"bypass",
"=",
"False",
")",
":",
"tileset",
"=",
"self",
".",
"_validate_tileset",
"(",
"tileset",
")",
"username",
",",
"_name"... | Create a tileset
Note: this step is refered to as "upload" in the API docs;
This class's upload() method is a high-level function
which acts like the Studio upload form.
Returns a response object where the json() contents are
an upload dict. Completion of the tileset may take s... | [
"Create",
"a",
"tileset"
] | python | train | 32.77193 |
PSPC-SPAC-buyandsell/von_agent | von_agent/agent/verifier.py | https://github.com/PSPC-SPAC-buyandsell/von_agent/blob/0b1c17cca3bd178b6e6974af84dbac1dfce5cf45/von_agent/agent/verifier.py#L206-L222 | async def open(self) -> 'HolderProver':
"""
Explicit entry. Perform ancestor opening operations,
then parse cache from archive if so configured, and
synchronize revocation registry to tails tree content.
:return: current object
"""
LOGGER.debug('Verifier.open >>... | [
"async",
"def",
"open",
"(",
"self",
")",
"->",
"'HolderProver'",
":",
"LOGGER",
".",
"debug",
"(",
"'Verifier.open >>>'",
")",
"await",
"super",
"(",
")",
".",
"open",
"(",
")",
"if",
"self",
".",
"cfg",
".",
"get",
"(",
"'parse-cache-on-open'",
",",
... | Explicit entry. Perform ancestor opening operations,
then parse cache from archive if so configured, and
synchronize revocation registry to tails tree content.
:return: current object | [
"Explicit",
"entry",
".",
"Perform",
"ancestor",
"opening",
"operations",
"then",
"parse",
"cache",
"from",
"archive",
"if",
"so",
"configured",
"and",
"synchronize",
"revocation",
"registry",
"to",
"tails",
"tree",
"content",
"."
] | python | train | 29.176471 |
blockstack/blockstack-core | blockstack/blockstackd.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L1757-L1842 | def rpc_put_zonefiles( self, zonefile_datas, **con_info ):
"""
Replicate one or more zonefiles, given as serialized strings.
Only stores zone files whose zone file hashes were announced on the blockchain (i.e. not subdomain zone files)
Returns {'status': True, 'saved': [0|1]'} on success... | [
"def",
"rpc_put_zonefiles",
"(",
"self",
",",
"zonefile_datas",
",",
"*",
"*",
"con_info",
")",
":",
"conf",
"=",
"get_blockstack_opts",
"(",
")",
"if",
"not",
"is_atlas_enabled",
"(",
"conf",
")",
":",
"return",
"{",
"'error'",
":",
"'No data'",
",",
"'ht... | Replicate one or more zonefiles, given as serialized strings.
Only stores zone files whose zone file hashes were announced on the blockchain (i.e. not subdomain zone files)
Returns {'status': True, 'saved': [0|1]'} on success ('saved' is a vector of success/failure)
Returns {'error': ...} on err... | [
"Replicate",
"one",
"or",
"more",
"zonefiles",
"given",
"as",
"serialized",
"strings",
".",
"Only",
"stores",
"zone",
"files",
"whose",
"zone",
"file",
"hashes",
"were",
"announced",
"on",
"the",
"blockchain",
"(",
"i",
".",
"e",
".",
"not",
"subdomain",
"... | python | train | 45.372093 |
delph-in/pydelphin | delphin/tdl.py | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/tdl.py#L1614-L1633 | def parse(f, encoding='utf-8'):
"""
Parse the TDL file *f* and yield the interpreted contents.
If *f* is a filename, the file is opened and closed when the
generator has finished, otherwise *f* is an open file object and
will not be closed when the generator has finished.
Args:
f (str,... | [
"def",
"parse",
"(",
"f",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"hasattr",
"(",
"f",
",",
"'read'",
")",
":",
"for",
"event",
"in",
"_parse",
"(",
"f",
")",
":",
"yield",
"event",
"else",
":",
"with",
"io",
".",
"open",
"(",
"f",
","... | Parse the TDL file *f* and yield the interpreted contents.
If *f* is a filename, the file is opened and closed when the
generator has finished, otherwise *f* is an open file object and
will not be closed when the generator has finished.
Args:
f (str, file): a filename or open file object
... | [
"Parse",
"the",
"TDL",
"file",
"*",
"f",
"*",
"and",
"yield",
"the",
"interpreted",
"contents",
"."
] | python | train | 33.45 |
mitsei/dlkit | dlkit/json_/learning/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/managers.py#L2263-L2280 | def get_objective_bank_lookup_session(self, proxy):
"""Gets the OsidSession associated with the objective bank lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveBankLookupSession) - an
``ObjectiveBankLookupSession``
raise: NullArg... | [
"def",
"get_objective_bank_lookup_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_objective_bank_lookup",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
... | Gets the OsidSession associated with the objective bank lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveBankLookupSession) - an
``ObjectiveBankLookupSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed -... | [
"Gets",
"the",
"OsidSession",
"associated",
"with",
"the",
"objective",
"bank",
"lookup",
"service",
"."
] | python | train | 46.722222 |
pkgw/pwkit | pwkit/cli/__init__.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/cli/__init__.py#L157-L174 | def backtrace_on_usr1 ():
"""Install a signal handler such that this program prints a Python traceback
upon receipt of SIGUSR1. This could be useful for checking that
long-running programs are behaving properly, or for discovering where an
infinite loop is occurring.
Note, however, that the Python ... | [
"def",
"backtrace_on_usr1",
"(",
")",
":",
"import",
"signal",
"try",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGUSR1",
",",
"_print_backtrace_signal_handler",
")",
"except",
"Exception",
"as",
"e",
":",
"warn",
"(",
"'failed to set up Python backtraces... | Install a signal handler such that this program prints a Python traceback
upon receipt of SIGUSR1. This could be useful for checking that
long-running programs are behaving properly, or for discovering where an
infinite loop is occurring.
Note, however, that the Python interpreter does not invoke Pytho... | [
"Install",
"a",
"signal",
"handler",
"such",
"that",
"this",
"program",
"prints",
"a",
"Python",
"traceback",
"upon",
"receipt",
"of",
"SIGUSR1",
".",
"This",
"could",
"be",
"useful",
"for",
"checking",
"that",
"long",
"-",
"running",
"programs",
"are",
"beh... | python | train | 47.277778 |
laginha/django-mobileesp | src/django_mobileesp/mdetect.py | https://github.com/laginha/django-mobileesp/blob/91d4babb2343b992970bdb076508d380680c8b7e/src/django_mobileesp/mdetect.py#L611-L617 | def detectTizenTV(self):
"""Return detection of a Tizen smart TV
Detects if the current browser is on a Tizen smart TV.
"""
return UAgentInfo.deviceTizen in self.__userAgent \
and UAgentInfo.smartTV1 in self.__userAgent | [
"def",
"detectTizenTV",
"(",
"self",
")",
":",
"return",
"UAgentInfo",
".",
"deviceTizen",
"in",
"self",
".",
"__userAgent",
"and",
"UAgentInfo",
".",
"smartTV1",
"in",
"self",
".",
"__userAgent"
] | Return detection of a Tizen smart TV
Detects if the current browser is on a Tizen smart TV. | [
"Return",
"detection",
"of",
"a",
"Tizen",
"smart",
"TV"
] | python | train | 36.857143 |
wolverdude/GenSON | genson/schema/node.py | https://github.com/wolverdude/GenSON/blob/76552d23cf9202e8e7c262cb018eb3cb3df686b9/genson/schema/node.py#L18-L37 | def add_schema(self, schema):
"""
Merges in an existing schema.
arguments:
* `schema` (required - `dict` or `SchemaNode`):
an existing JSON Schema to merge.
"""
# serialize instances of SchemaNode before parsing
if isinstance(schema, SchemaNode):
... | [
"def",
"add_schema",
"(",
"self",
",",
"schema",
")",
":",
"# serialize instances of SchemaNode before parsing",
"if",
"isinstance",
"(",
"schema",
",",
"SchemaNode",
")",
":",
"schema",
"=",
"schema",
".",
"to_schema",
"(",
")",
"for",
"subschema",
"in",
"self"... | Merges in an existing schema.
arguments:
* `schema` (required - `dict` or `SchemaNode`):
an existing JSON Schema to merge. | [
"Merges",
"in",
"an",
"existing",
"schema",
"."
] | python | train | 31.35 |
decryptus/sonicprobe | sonicprobe/libs/threading_tcp_server.py | https://github.com/decryptus/sonicprobe/blob/72f73f3a40d2982d79ad68686e36aa31d94b76f8/sonicprobe/libs/threading_tcp_server.py#L147-L155 | def handle_request(self):
"""simply collect requests and put them on the queue for the workers."""
try:
request, client_address = self.get_request()
except socket.error:
return
if self.verify_request(request, client_address):
self.requests.put((reques... | [
"def",
"handle_request",
"(",
"self",
")",
":",
"try",
":",
"request",
",",
"client_address",
"=",
"self",
".",
"get_request",
"(",
")",
"except",
"socket",
".",
"error",
":",
"return",
"if",
"self",
".",
"verify_request",
"(",
"request",
",",
"client_addr... | simply collect requests and put them on the queue for the workers. | [
"simply",
"collect",
"requests",
"and",
"put",
"them",
"on",
"the",
"queue",
"for",
"the",
"workers",
"."
] | python | train | 36.777778 |
apple/turicreate | src/unity/python/turicreate/toolkits/object_detector/object_detector.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/object_detector/object_detector.py#L934-L1004 | def predict(self, dataset, confidence_threshold=0.25, iou_threshold=None, verbose=True):
"""
Predict object instances in an sframe of images.
Parameters
----------
dataset : SFrame | SArray | turicreate.Image
The images on which to perform object detection.
... | [
"def",
"predict",
"(",
"self",
",",
"dataset",
",",
"confidence_threshold",
"=",
"0.25",
",",
"iou_threshold",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"_numeric_param_check_range",
"(",
"'confidence_threshold'",
",",
"confidence_threshold",
",",
"0.0",... | Predict object instances in an sframe of images.
Parameters
----------
dataset : SFrame | SArray | turicreate.Image
The images on which to perform object detection.
If dataset is an SFrame, it must have a column with the same name
as the feature column during... | [
"Predict",
"object",
"instances",
"in",
"an",
"sframe",
"of",
"images",
"."
] | python | train | 44.929577 |
tonyfischetti/sake | sakelib/acts.py | https://github.com/tonyfischetti/sake/blob/b7ad20fe8e7137db99a20ac06b8da26492601b00/sakelib/acts.py#L456-L520 | def construct_graph(sakefile, settings):
"""
Takes the sakefile dictionary and builds a NetworkX graph
Args:
A dictionary that is the parsed Sakefile (from sake.py)
The settings dictionary
Returns:
A NetworkX graph
"""
verbose = settings["verbose"]
sprint = settings... | [
"def",
"construct_graph",
"(",
"sakefile",
",",
"settings",
")",
":",
"verbose",
"=",
"settings",
"[",
"\"verbose\"",
"]",
"sprint",
"=",
"settings",
"[",
"\"sprint\"",
"]",
"G",
"=",
"nx",
".",
"DiGraph",
"(",
")",
"sprint",
"(",
"\"Going to construct Graph... | Takes the sakefile dictionary and builds a NetworkX graph
Args:
A dictionary that is the parsed Sakefile (from sake.py)
The settings dictionary
Returns:
A NetworkX graph | [
"Takes",
"the",
"sakefile",
"dictionary",
"and",
"builds",
"a",
"NetworkX",
"graph"
] | python | valid | 38.092308 |
pybluez/pybluez | macos/_lightbluecommon.py | https://github.com/pybluez/pybluez/blob/e0dc4093dcbaa3ecb3fa24f8ccf22bbfe6b57fc9/macos/_lightbluecommon.py#L73-L89 | def _isbtaddr(address):
"""
Returns whether the given address is a valid bluetooth address.
For example, "00:0e:6d:7b:a2:0a" is a valid address.
Returns False if the argument is None or is not a string.
"""
# Define validity regex. Accept either ":" or "-" as separators.
global _validbtaddr... | [
"def",
"_isbtaddr",
"(",
"address",
")",
":",
"# Define validity regex. Accept either \":\" or \"-\" as separators.",
"global",
"_validbtaddr",
"if",
"_validbtaddr",
"is",
"None",
":",
"import",
"re",
"_validbtaddr",
"=",
"re",
".",
"compile",
"(",
"\"((\\d|[a-f]){2}(:|-)... | Returns whether the given address is a valid bluetooth address.
For example, "00:0e:6d:7b:a2:0a" is a valid address.
Returns False if the argument is None or is not a string. | [
"Returns",
"whether",
"the",
"given",
"address",
"is",
"a",
"valid",
"bluetooth",
"address",
".",
"For",
"example",
"00",
":",
"0e",
":",
"6d",
":",
"7b",
":",
"a2",
":",
"0a",
"is",
"a",
"valid",
"address",
"."
] | python | train | 34.235294 |
mattjj/pylds | pylds/util.py | https://github.com/mattjj/pylds/blob/e946bfa5aa76e8f8284614561a0f40ffd5d868fb/pylds/util.py#L199-L218 | def compute_symm_block_tridiag_covariances(H_diag, H_upper_diag):
"""
use the info smoother to solve a symmetric block tridiagonal system
"""
T, D, _ = H_diag.shape
assert H_diag.ndim == 3 and H_diag.shape[2] == D
assert H_upper_diag.shape == (T - 1, D, D)
J_init = J_11 = J_22 = np.zeros((D... | [
"def",
"compute_symm_block_tridiag_covariances",
"(",
"H_diag",
",",
"H_upper_diag",
")",
":",
"T",
",",
"D",
",",
"_",
"=",
"H_diag",
".",
"shape",
"assert",
"H_diag",
".",
"ndim",
"==",
"3",
"and",
"H_diag",
".",
"shape",
"[",
"2",
"]",
"==",
"D",
"a... | use the info smoother to solve a symmetric block tridiagonal system | [
"use",
"the",
"info",
"smoother",
"to",
"solve",
"a",
"symmetric",
"block",
"tridiagonal",
"system"
] | python | train | 32.85 |
brainiak/brainiak | brainiak/eventseg/event.py | https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/eventseg/event.py#L189-L233 | def _logprob_obs(self, data, mean_pat, var):
"""Log probability of observing each timepoint under each event model
Computes the log probability of each observed timepoint being
generated by the Gaussian distribution for each event pattern
Parameters
----------
data: vox... | [
"def",
"_logprob_obs",
"(",
"self",
",",
"data",
",",
"mean_pat",
",",
"var",
")",
":",
"n_vox",
"=",
"data",
".",
"shape",
"[",
"0",
"]",
"t",
"=",
"data",
".",
"shape",
"[",
"1",
"]",
"# z-score both data and mean patterns in space, so that Gaussians",
"# ... | Log probability of observing each timepoint under each event model
Computes the log probability of each observed timepoint being
generated by the Gaussian distribution for each event pattern
Parameters
----------
data: voxel by time ndarray
fMRI data on which to com... | [
"Log",
"probability",
"of",
"observing",
"each",
"timepoint",
"under",
"each",
"event",
"model"
] | python | train | 34.222222 |
satellogic/telluric | telluric/georaster.py | https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L95-L109 | def join(rasters):
"""
This method takes a list of rasters and returns a raster that is constructed of all of them
"""
raster = rasters[0] # using the first raster to understand what is the type of data we have
mask_band = None
nodata = None
with raster._raster_opener(raster.source_file) a... | [
"def",
"join",
"(",
"rasters",
")",
":",
"raster",
"=",
"rasters",
"[",
"0",
"]",
"# using the first raster to understand what is the type of data we have",
"mask_band",
"=",
"None",
"nodata",
"=",
"None",
"with",
"raster",
".",
"_raster_opener",
"(",
"raster",
".",... | This method takes a list of rasters and returns a raster that is constructed of all of them | [
"This",
"method",
"takes",
"a",
"list",
"of",
"rasters",
"and",
"returns",
"a",
"raster",
"that",
"is",
"constructed",
"of",
"all",
"of",
"them"
] | python | train | 42.933333 |
brentpayne/phrase | phrase/phrase_dictionary.py | https://github.com/brentpayne/phrase/blob/2c25e202eff0f284cb724a36cec1b22a1169e7a2/phrase/phrase_dictionary.py#L144-L161 | def convert_to_merged_ids(self, id_run):
"""
Converts any identified phrases in the run into phrase_ids. The dictionary provides all acceptable phrases
:param id_run: a run of token ids
:param dictionary: a dictionary of acceptable phrases described as there component token ids
... | [
"def",
"convert_to_merged_ids",
"(",
"self",
",",
"id_run",
")",
":",
"i",
"=",
"0",
"rv",
"=",
"[",
"]",
"while",
"i",
"<",
"len",
"(",
"id_run",
")",
":",
"phrase_id",
",",
"offset",
"=",
"self",
".",
"max_phrase",
"(",
"id_run",
",",
"i",
")",
... | Converts any identified phrases in the run into phrase_ids. The dictionary provides all acceptable phrases
:param id_run: a run of token ids
:param dictionary: a dictionary of acceptable phrases described as there component token ids
:return: a run of token and phrase ids. | [
"Converts",
"any",
"identified",
"phrases",
"in",
"the",
"run",
"into",
"phrase_ids",
".",
"The",
"dictionary",
"provides",
"all",
"acceptable",
"phrases",
":",
"param",
"id_run",
":",
"a",
"run",
"of",
"token",
"ids",
":",
"param",
"dictionary",
":",
"a",
... | python | train | 36.666667 |
rackerlabs/txkazoo | txkazoo/client.py | https://github.com/rackerlabs/txkazoo/blob/a0989138cc08df7acd1d410f7e48708553839f46/txkazoo/client.py#L59-L65 | def remove_listener(self, listener):
"""Remove the given listener from the wrapped client.
:param listener: A listener previously passed to :meth:`add_listener`.
"""
internal_listener = self._internal_listeners.pop(listener)
return self._client.remove_listener(internal_listener) | [
"def",
"remove_listener",
"(",
"self",
",",
"listener",
")",
":",
"internal_listener",
"=",
"self",
".",
"_internal_listeners",
".",
"pop",
"(",
"listener",
")",
"return",
"self",
".",
"_client",
".",
"remove_listener",
"(",
"internal_listener",
")"
] | Remove the given listener from the wrapped client.
:param listener: A listener previously passed to :meth:`add_listener`. | [
"Remove",
"the",
"given",
"listener",
"from",
"the",
"wrapped",
"client",
"."
] | python | train | 44.857143 |
rq/Flask-RQ2 | src/flask_rq2/app.py | https://github.com/rq/Flask-RQ2/blob/58eedf6f0cd7bcde4ccd787074762ea08f531337/src/flask_rq2/app.py#L226-L308 | def job(self, func_or_queue=None, timeout=None, result_ttl=None, ttl=None,
depends_on=None, at_front=None, meta=None, description=None):
"""
Decorator to mark functions for queuing via RQ, e.g.::
rq = RQ()
@rq.job
def add(x, y):
return x ... | [
"def",
"job",
"(",
"self",
",",
"func_or_queue",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"result_ttl",
"=",
"None",
",",
"ttl",
"=",
"None",
",",
"depends_on",
"=",
"None",
",",
"at_front",
"=",
"None",
",",
"meta",
"=",
"None",
",",
"descript... | Decorator to mark functions for queuing via RQ, e.g.::
rq = RQ()
@rq.job
def add(x, y):
return x + y
or::
@rq.job(timeout=60, result_ttl=60 * 60)
def add(x, y):
return x + y
Adds various functions to the job... | [
"Decorator",
"to",
"mark",
"functions",
"for",
"queuing",
"via",
"RQ",
"e",
".",
"g",
".",
"::"
] | python | train | 31.542169 |
pyusb/pyusb | usb/core.py | https://github.com/pyusb/pyusb/blob/ffe6faf42c6ad273880b0b464b9bbf44c1d4b2e9/usb/core.py#L52-L66 | def _try_get_string(dev, index, langid = None, default_str_i0 = "",
default_access_error = "Error Accessing String"):
""" try to get a string, but return a string no matter what
"""
if index == 0 :
string = default_str_i0
else:
try:
if langid is None:
... | [
"def",
"_try_get_string",
"(",
"dev",
",",
"index",
",",
"langid",
"=",
"None",
",",
"default_str_i0",
"=",
"\"\"",
",",
"default_access_error",
"=",
"\"Error Accessing String\"",
")",
":",
"if",
"index",
"==",
"0",
":",
"string",
"=",
"default_str_i0",
"else"... | try to get a string, but return a string no matter what | [
"try",
"to",
"get",
"a",
"string",
"but",
"return",
"a",
"string",
"no",
"matter",
"what"
] | python | train | 33.2 |
saltstack/salt | salt/cloud/clouds/vmware.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vmware.py#L1528-L1547 | def get_vcenter_version(kwargs=None, call=None):
'''
Show the vCenter Server version with build number.
CLI Example:
.. code-block:: bash
salt-cloud -f get_vcenter_version my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_vcenter_versi... | [
"def",
"get_vcenter_version",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The get_vcenter_version function must be called with '",
"'-f or --function.'",
")",
"# Get the in... | Show the vCenter Server version with build number.
CLI Example:
.. code-block:: bash
salt-cloud -f get_vcenter_version my-vmware-config | [
"Show",
"the",
"vCenter",
"Server",
"version",
"with",
"build",
"number",
"."
] | python | train | 24.25 |
Garee/pytodoist | pytodoist/api.py | https://github.com/Garee/pytodoist/blob/3359cbff485ebdbbb4ffbd58d71e21a817874dd7/pytodoist/api.py#L152-L189 | def sync(self, api_token, sync_token, resource_types='["all"]', **kwargs):
"""Update and retrieve Todoist data.
:param api_token: The user's login api_token.
:type api_token: str
:param seq_no: The request sequence number. On initial request pass
``0``. On all others pass th... | [
"def",
"sync",
"(",
"self",
",",
"api_token",
",",
"sync_token",
",",
"resource_types",
"=",
"'[\"all\"]'",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'token'",
":",
"api_token",
",",
"'sync_token'",
":",
"sync_token",
",",
"}",
"req_func",
... | Update and retrieve Todoist data.
:param api_token: The user's login api_token.
:type api_token: str
:param seq_no: The request sequence number. On initial request pass
``0``. On all others pass the last seq_no you received.
:type seq_no: int
:param seq_no_global: Th... | [
"Update",
"and",
"retrieve",
"Todoist",
"data",
"."
] | python | train | 44.552632 |
saltstack/salt | salt/states/csf.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/csf.py#L220-L258 | def ports_open(name, ports, proto='tcp', direction='in'):
'''
Ensure ports are open for a protocol, in a direction.
e.g. - proto='tcp', direction='in' would set the values
for TCP_IN in the csf.conf file.
ports
A list of ports that should be open.
proto
The protocol. May be one... | [
"def",
"ports_open",
"(",
"name",
",",
"ports",
",",
"proto",
"=",
"'tcp'",
",",
"direction",
"=",
"'in'",
")",
":",
"ports",
"=",
"list",
"(",
"six",
".",
"moves",
".",
"map",
"(",
"six",
".",
"text_type",
",",
"ports",
")",
")",
"diff",
"=",
"F... | Ensure ports are open for a protocol, in a direction.
e.g. - proto='tcp', direction='in' would set the values
for TCP_IN in the csf.conf file.
ports
A list of ports that should be open.
proto
The protocol. May be one of 'tcp', 'udp',
'tcp6', or 'udp6'.
direction
Ch... | [
"Ensure",
"ports",
"are",
"open",
"for",
"a",
"protocol",
"in",
"a",
"direction",
".",
"e",
".",
"g",
".",
"-",
"proto",
"=",
"tcp",
"direction",
"=",
"in",
"would",
"set",
"the",
"values",
"for",
"TCP_IN",
"in",
"the",
"csf",
".",
"conf",
"file",
... | python | train | 32.512821 |
dslackw/slpkg | slpkg/dialog_box.py | https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/dialog_box.py#L64-L80 | def buildlist(self, enabled):
"""Run dialog buildlist
"""
choice = []
for item in self.data:
choice.append((item, False))
for item in enabled:
choice.append((item, True))
items = [(tag, tag, sta) for (tag, sta) in choice]
code, self.tags = ... | [
"def",
"buildlist",
"(",
"self",
",",
"enabled",
")",
":",
"choice",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"data",
":",
"choice",
".",
"append",
"(",
"(",
"item",
",",
"False",
")",
")",
"for",
"item",
"in",
"enabled",
":",
"choice",
"... | Run dialog buildlist | [
"Run",
"dialog",
"buildlist"
] | python | train | 34.411765 |
hvac/hvac | hvac/api/secrets_engines/kv_v1.py | https://github.com/hvac/hvac/blob/cce5b86889193f622c2a72a4a1b7e1c9c8aff1ce/hvac/api/secrets_engines/kv_v1.py#L115-L133 | def delete_secret(self, path, mount_point=DEFAULT_MOUNT_POINT):
"""Delete the secret at the specified location.
Supported methods:
DELETE: /{mount_point}/{path}. Produces: 204 (empty body)
:param path: Specifies the path of the secret to delete.
This is specified as pa... | [
"def",
"delete_secret",
"(",
"self",
",",
"path",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"api_path",
"=",
"'/v1/{mount_point}/{path}'",
".",
"format",
"(",
"mount_point",
"=",
"mount_point",
",",
"path",
"=",
"path",
")",
"return",
"self",
"... | Delete the secret at the specified location.
Supported methods:
DELETE: /{mount_point}/{path}. Produces: 204 (empty body)
:param path: Specifies the path of the secret to delete.
This is specified as part of the URL.
:type path: str | unicode
:param mount_point... | [
"Delete",
"the",
"secret",
"at",
"the",
"specified",
"location",
"."
] | python | train | 38.526316 |
senaite/senaite.api | src/senaite/api/__init__.py | https://github.com/senaite/senaite.api/blob/c79c53abcbe6e3a5ab3ced86d2f455275efa20cf/src/senaite/api/__init__.py#L394-L417 | def get_icon(brain_or_object, html_tag=True):
"""Get the icon of the content object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param html_tag: A value of 'True' returns the HTML tag, else the image url
:ty... | [
"def",
"get_icon",
"(",
"brain_or_object",
",",
"html_tag",
"=",
"True",
")",
":",
"# Manual approach, because `plone.app.layout.getIcon` does not reliable",
"# work for Bika Contents coming from other catalogs than the",
"# `portal_catalog`",
"portal_types",
"=",
"get_tool",
"(",
... | Get the icon of the content object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param html_tag: A value of 'True' returns the HTML tag, else the image url
:type html_tag: bool
:returns: HTML '<img>' tag if '... | [
"Get",
"the",
"icon",
"of",
"the",
"content",
"object"
] | python | train | 40.833333 |
CityOfZion/neo-python | neo/Network/NeoNode.py | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L399-L433 | def MessageReceived(self, m):
"""
Process a message.
Args:
m (neo.Network.Message):
"""
if m.Command == 'verack':
# only respond with a verack when we connect to another client, not when a client connected to us or
# we might end up in a verac... | [
"def",
"MessageReceived",
"(",
"self",
",",
"m",
")",
":",
"if",
"m",
".",
"Command",
"==",
"'verack'",
":",
"# only respond with a verack when we connect to another client, not when a client connected to us or",
"# we might end up in a verack loop",
"if",
"self",
".",
"incom... | Process a message.
Args:
m (neo.Network.Message): | [
"Process",
"a",
"message",
"."
] | python | train | 38.6 |
digidotcom/python-devicecloud | devicecloud/__init__.py | https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/__init__.py#L131-L134 | def hostname(self):
"""Get the hostname that this connection is associated with"""
from six.moves.urllib.parse import urlparse
return urlparse(self._base_url).netloc.split(':', 1)[0] | [
"def",
"hostname",
"(",
"self",
")",
":",
"from",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
"import",
"urlparse",
"return",
"urlparse",
"(",
"self",
".",
"_base_url",
")",
".",
"netloc",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"0",
"]... | Get the hostname that this connection is associated with | [
"Get",
"the",
"hostname",
"that",
"this",
"connection",
"is",
"associated",
"with"
] | python | train | 50.75 |
vertexproject/synapse | synapse/datamodel.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/datamodel.py#L336-L361 | def getLiftOps(self, valu, cmpr='='):
'''
Get a set of lift operations for use with an Xact.
'''
if valu is None:
iops = (('pref', b''),)
return (
('indx', ('byprop', self.pref, iops)),
)
# TODO: In an ideal world, this would g... | [
"def",
"getLiftOps",
"(",
"self",
",",
"valu",
",",
"cmpr",
"=",
"'='",
")",
":",
"if",
"valu",
"is",
"None",
":",
"iops",
"=",
"(",
"(",
"'pref'",
",",
"b''",
")",
",",
")",
"return",
"(",
"(",
"'indx'",
",",
"(",
"'byprop'",
",",
"self",
".",... | Get a set of lift operations for use with an Xact. | [
"Get",
"a",
"set",
"of",
"lift",
"operations",
"for",
"use",
"with",
"an",
"Xact",
"."
] | python | train | 33.384615 |
rigetti/pyquil | pyquil/quilbase.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/quilbase.py#L127-L136 | def controlled(self, control_qubit):
"""
Add the CONTROLLED modifier to the gate with the given control qubit.
"""
control_qubit = unpack_qubit(control_qubit)
self.modifiers.insert(0, "CONTROLLED")
self.qubits.insert(0, control_qubit)
return self | [
"def",
"controlled",
"(",
"self",
",",
"control_qubit",
")",
":",
"control_qubit",
"=",
"unpack_qubit",
"(",
"control_qubit",
")",
"self",
".",
"modifiers",
".",
"insert",
"(",
"0",
",",
"\"CONTROLLED\"",
")",
"self",
".",
"qubits",
".",
"insert",
"(",
"0"... | Add the CONTROLLED modifier to the gate with the given control qubit. | [
"Add",
"the",
"CONTROLLED",
"modifier",
"to",
"the",
"gate",
"with",
"the",
"given",
"control",
"qubit",
"."
] | python | train | 29.5 |
Hackerfleet/hfos | hfos/tool/rbac.py | https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/tool/rbac.py#L99-L115 | def del_action_role(ctx):
"""Deletes a role from an action on objects"""
objects = ctx.obj['objects']
action = ctx.obj['action']
role = ctx.obj['role']
if action is None or role is None:
log('You need to specify an action or role to the RBAC command group for this to work.', lvl=warn)
... | [
"def",
"del_action_role",
"(",
"ctx",
")",
":",
"objects",
"=",
"ctx",
".",
"obj",
"[",
"'objects'",
"]",
"action",
"=",
"ctx",
".",
"obj",
"[",
"'action'",
"]",
"role",
"=",
"ctx",
".",
"obj",
"[",
"'role'",
"]",
"if",
"action",
"is",
"None",
"or"... | Deletes a role from an action on objects | [
"Deletes",
"a",
"role",
"from",
"an",
"action",
"on",
"objects"
] | python | train | 27.294118 |
wdbm/datavision | datavision.py | https://github.com/wdbm/datavision/blob/b6f26287264632d6f8c9f8911aaf3a8e4fc4dcf5/datavision.py#L2538-L2560 | def limit_x(
self,
limit_lower = None, # float
limit_upper = None # float
):
"""
get or set x limits of the current axes
x_min, x_max = limit_x() # return the current limit_x
limit_x(x_min, x_max) # set the limit_x to x_min, x_max
"""
... | [
"def",
"limit_x",
"(",
"self",
",",
"limit_lower",
"=",
"None",
",",
"# float",
"limit_upper",
"=",
"None",
"# float",
")",
":",
"if",
"limit_lower",
"is",
"None",
"and",
"limit_upper",
"is",
"None",
":",
"return",
"self",
".",
"_limit_x",
"elif",
"hasattr... | get or set x limits of the current axes
x_min, x_max = limit_x() # return the current limit_x
limit_x(x_min, x_max) # set the limit_x to x_min, x_max | [
"get",
"or",
"set",
"x",
"limits",
"of",
"the",
"current",
"axes"
] | python | train | 30.478261 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.