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 |
|---|---|---|---|---|---|---|---|---|---|
apache/airflow | airflow/contrib/hooks/gcp_sql_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_sql_hook.py#L524-L565 | def start_proxy(self):
"""
Starts Cloud SQL Proxy.
You have to remember to stop the proxy if you started it!
"""
self._download_sql_proxy_if_needed()
if self.sql_proxy_process:
raise AirflowException("The sql proxy is already running: {}".format(
... | [
"def",
"start_proxy",
"(",
"self",
")",
":",
"self",
".",
"_download_sql_proxy_if_needed",
"(",
")",
"if",
"self",
".",
"sql_proxy_process",
":",
"raise",
"AirflowException",
"(",
"\"The sql proxy is already running: {}\"",
".",
"format",
"(",
"self",
".",
"sql_prox... | Starts Cloud SQL Proxy.
You have to remember to stop the proxy if you started it! | [
"Starts",
"Cloud",
"SQL",
"Proxy",
"."
] | python | test | 48.190476 |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/python_message.py#L962-L966 | def _AddStrMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def __str__(self):
return text_format.MessageToString(self)
cls.__str__ = __str__ | [
"def",
"_AddStrMethod",
"(",
"message_descriptor",
",",
"cls",
")",
":",
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"text_format",
".",
"MessageToString",
"(",
"self",
")",
"cls",
".",
"__str__",
"=",
"__str__"
] | Helper for _AddMessageMethods(). | [
"Helper",
"for",
"_AddMessageMethods",
"()",
"."
] | python | train | 34 |
marshmallow-code/marshmallow | src/marshmallow/fields.py | https://github.com/marshmallow-code/marshmallow/blob/a6b6c4151f1fbf16f3774d4052ca2bddf6903750/src/marshmallow/fields.py#L774-L783 | def _validated(self, value):
"""Format the value or raise a :exc:`ValidationError` if an error occurs."""
if value is None:
return None
try:
return self._format_num(value)
except (TypeError, ValueError):
self.fail('invalid', input=value)
except... | [
"def",
"_validated",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"try",
":",
"return",
"self",
".",
"_format_num",
"(",
"value",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"self",
".",
"... | Format the value or raise a :exc:`ValidationError` if an error occurs. | [
"Format",
"the",
"value",
"or",
"raise",
"a",
":",
"exc",
":",
"ValidationError",
"if",
"an",
"error",
"occurs",
"."
] | python | train | 37.4 |
ioos/pyoos | pyoos/utils/dataorg.py | https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/utils/dataorg.py#L4-L16 | def flatten_element(p):
"""
Convenience function to return record-style time series representation
from elements ('p') members in station element.
member['standard'] is a standard_name parameter name, typically CF based.
Ideally, member['value'] should already be floating point value,
so it's re... | [
"def",
"flatten_element",
"(",
"p",
")",
":",
"rd",
"=",
"{",
"\"time\"",
":",
"p",
".",
"time",
"}",
"for",
"member",
"in",
"p",
".",
"members",
":",
"rd",
"[",
"member",
"[",
"\"standard\"",
"]",
"]",
"=",
"member",
"[",
"\"value\"",
"]",
"return... | Convenience function to return record-style time series representation
from elements ('p') members in station element.
member['standard'] is a standard_name parameter name, typically CF based.
Ideally, member['value'] should already be floating point value,
so it's ready to use.
Useful with most pyo... | [
"Convenience",
"function",
"to",
"return",
"record",
"-",
"style",
"time",
"series",
"representation",
"from",
"elements",
"(",
"p",
")",
"members",
"in",
"station",
"element",
".",
"member",
"[",
"standard",
"]",
"is",
"a",
"standard_name",
"parameter",
"name... | python | train | 37.230769 |
MartinThoma/hwrt | hwrt/utils.py | https://github.com/MartinThoma/hwrt/blob/725c21a3d0f5a30b8492cbc184b3688ceb364e1c/hwrt/utils.py#L635-L653 | def evaluate_model_single_recording(model_file, recording):
"""
Evaluate a model for a single recording.
Parameters
----------
model_file : string
Model file (.tar)
recording :
The handwritten recording.
"""
(preprocessing_queue, feature_list, model,
output_semantic... | [
"def",
"evaluate_model_single_recording",
"(",
"model_file",
",",
"recording",
")",
":",
"(",
"preprocessing_queue",
",",
"feature_list",
",",
"model",
",",
"output_semantics",
")",
"=",
"load_model",
"(",
"model_file",
")",
"results",
"=",
"evaluate_model_single_reco... | Evaluate a model for a single recording.
Parameters
----------
model_file : string
Model file (.tar)
recording :
The handwritten recording. | [
"Evaluate",
"a",
"model",
"for",
"a",
"single",
"recording",
"."
] | python | train | 36.789474 |
balabit/typesafety | typesafety/validator.py | https://github.com/balabit/typesafety/blob/452242dd93da9ebd53c173c243156d1351cd96fd/typesafety/validator.py#L107-L118 | def undecorate(cls, function):
'''
Remove validator decoration from a function.
The `function` argument is the function to be cleaned from
the validator decorator.
'''
if cls.is_function_validated(function):
return cls.get_function_validator(function).functi... | [
"def",
"undecorate",
"(",
"cls",
",",
"function",
")",
":",
"if",
"cls",
".",
"is_function_validated",
"(",
"function",
")",
":",
"return",
"cls",
".",
"get_function_validator",
"(",
"function",
")",
".",
"function",
"return",
"function"
] | Remove validator decoration from a function.
The `function` argument is the function to be cleaned from
the validator decorator. | [
"Remove",
"validator",
"decoration",
"from",
"a",
"function",
"."
] | python | train | 28 |
RealTimeWeb/datasets | preprocess/earthquakes/earthquakes.py | https://github.com/RealTimeWeb/datasets/blob/2fe5befd251c783744d000bd4763e277616a152f/preprocess/earthquakes/earthquakes.py#L513-L533 | def _from_json(json_data):
"""
Creates a Report from json data.
:param json_data: The raw json data to parse
:type json_data: dict
:returns: Report
"""
if 'bbox' in json_data:
box = BoundingBox._from_json(json_data['bbox'])
else:
... | [
"def",
"_from_json",
"(",
"json_data",
")",
":",
"if",
"'bbox'",
"in",
"json_data",
":",
"box",
"=",
"BoundingBox",
".",
"_from_json",
"(",
"json_data",
"[",
"'bbox'",
"]",
")",
"else",
":",
"box",
"=",
"BoundingBox",
"(",
"Coordinate",
"(",
"0.",
",",
... | Creates a Report from json data.
:param json_data: The raw json data to parse
:type json_data: dict
:returns: Report | [
"Creates",
"a",
"Report",
"from",
"json",
"data",
".",
":",
"param",
"json_data",
":",
"The",
"raw",
"json",
"data",
"to",
"parse",
":",
"type",
"json_data",
":",
"dict",
":",
"returns",
":",
"Report"
] | python | train | 36.095238 |
mitsei/dlkit | dlkit/json_/repository/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/objects.py#L979-L994 | def set_source(self, source_id):
"""Sets the source.
arg: source_id (osid.id.Id): the new publisher
raise: InvalidArgument - ``source_id`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``source_id`` is ``null``
*compliance... | [
"def",
"set_source",
"(",
"self",
",",
"source_id",
")",
":",
"# Implemented from template for osid.resource.ResourceForm.set_avatar_template",
"if",
"self",
".",
"get_source_metadata",
"(",
")",
".",
"is_read_only",
"(",
")",
":",
"raise",
"errors",
".",
"NoAccess",
... | Sets the source.
arg: source_id (osid.id.Id): the new publisher
raise: InvalidArgument - ``source_id`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``source_id`` is ``null``
*compliance: mandatory -- This method must be implement... | [
"Sets",
"the",
"source",
"."
] | python | train | 42.5625 |
bpython/curtsies | examples/tictactoeexample.py | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tictactoeexample.py#L68-L94 | def value(board, who='x'):
"""Returns the value of a board
>>> b = Board(); b._rows = [['x', 'x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'x']]
>>> value(b)
1
>>> b = Board(); b._rows = [['o', 'o', 'o'], ['o', 'o', 'o'], ['o', 'o', 'o']]
>>> value(b)
-1
>>> b = Board(); b._rows = [['x', 'o', '... | [
"def",
"value",
"(",
"board",
",",
"who",
"=",
"'x'",
")",
":",
"w",
"=",
"board",
".",
"winner",
"(",
")",
"if",
"w",
"==",
"who",
":",
"return",
"1",
"if",
"w",
"==",
"opp",
"(",
"who",
")",
":",
"return",
"-",
"1",
"if",
"board",
".",
"t... | Returns the value of a board
>>> b = Board(); b._rows = [['x', 'x', 'x'], ['x', 'x', 'x'], ['x', 'x', 'x']]
>>> value(b)
1
>>> b = Board(); b._rows = [['o', 'o', 'o'], ['o', 'o', 'o'], ['o', 'o', 'o']]
>>> value(b)
-1
>>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', '... | [
"Returns",
"the",
"value",
"of",
"a",
"board",
">>>",
"b",
"=",
"Board",
"()",
";",
"b",
".",
"_rows",
"=",
"[[",
"x",
"x",
"x",
"]",
"[",
"x",
"x",
"x",
"]",
"[",
"x",
"x",
"x",
"]]",
">>>",
"value",
"(",
"b",
")",
"1",
">>>",
"b",
"=",
... | python | train | 26.666667 |
kadrlica/pymodeler | pymodeler/model.py | https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/model.py#L292-L306 | def _init_properties(self):
""" Loop through the list of Properties,
extract the derived and required properties and do the
appropriate book-keeping
"""
self._missing = {}
for k, p in self.params.items():
if p.required:
self._missing[k] = p
... | [
"def",
"_init_properties",
"(",
"self",
")",
":",
"self",
".",
"_missing",
"=",
"{",
"}",
"for",
"k",
",",
"p",
"in",
"self",
".",
"params",
".",
"items",
"(",
")",
":",
"if",
"p",
".",
"required",
":",
"self",
".",
"_missing",
"[",
"k",
"]",
"... | Loop through the list of Properties,
extract the derived and required properties and do the
appropriate book-keeping | [
"Loop",
"through",
"the",
"list",
"of",
"Properties",
"extract",
"the",
"derived",
"and",
"required",
"properties",
"and",
"do",
"the",
"appropriate",
"book",
"-",
"keeping"
] | python | test | 40.4 |
pypa/setuptools | setuptools/package_index.py | https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/package_index.py#L510-L524 | def check_hash(self, checker, filename, tfp):
"""
checker is a ContentChecker
"""
checker.report(
self.debug,
"Validating %%s checksum for %s" % filename)
if not checker.is_valid():
tfp.close()
os.unlink(filename)
raise ... | [
"def",
"check_hash",
"(",
"self",
",",
"checker",
",",
"filename",
",",
"tfp",
")",
":",
"checker",
".",
"report",
"(",
"self",
".",
"debug",
",",
"\"Validating %%s checksum for %s\"",
"%",
"filename",
")",
"if",
"not",
"checker",
".",
"is_valid",
"(",
")"... | checker is a ContentChecker | [
"checker",
"is",
"a",
"ContentChecker"
] | python | train | 32.933333 |
pyviz/holoviews | holoviews/core/layout.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/layout.py#L201-L220 | def dimension_values(self, dimension, expanded=True, flat=True):
"""Return the values along the requested dimension.
Applies to the main object in the AdjointLayout.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
... | [
"def",
"dimension_values",
"(",
"self",
",",
"dimension",
",",
"expanded",
"=",
"True",
",",
"flat",
"=",
"True",
")",
":",
"dimension",
"=",
"self",
".",
"get_dimension",
"(",
"dimension",
",",
"strict",
"=",
"True",
")",
".",
"name",
"return",
"self",
... | Return the values along the requested dimension.
Applies to the main object in the AdjointLayout.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
Whether to return the expanded values, behavior depends
... | [
"Return",
"the",
"values",
"along",
"the",
"requested",
"dimension",
"."
] | python | train | 44.8 |
milesrichardson/ParsePy | parse_rest/installation.py | https://github.com/milesrichardson/ParsePy/blob/7c52d8a5dc63bb7c3b0b8c0c09d032b4bc7299ea/parse_rest/installation.py#L30-L49 | def update_channels(cls, installation_id, channels_to_add=set(),
channels_to_remove=set(), **kw):
"""
Allow an application to manually subscribe or unsubscribe an
installation to a certain push channel in a unified operation.
this is based on:
https://www... | [
"def",
"update_channels",
"(",
"cls",
",",
"installation_id",
",",
"channels_to_add",
"=",
"set",
"(",
")",
",",
"channels_to_remove",
"=",
"set",
"(",
")",
",",
"*",
"*",
"kw",
")",
":",
"installation_url",
"=",
"cls",
".",
"_get_installation_url",
"(",
"... | Allow an application to manually subscribe or unsubscribe an
installation to a certain push channel in a unified operation.
this is based on:
https://www.parse.com/docs/rest#installations-updating
installation_id: the installation id you'd like to add a channel to
channels_to_a... | [
"Allow",
"an",
"application",
"to",
"manually",
"subscribe",
"or",
"unsubscribe",
"an",
"installation",
"to",
"a",
"certain",
"push",
"channel",
"in",
"a",
"unified",
"operation",
"."
] | python | train | 45.3 |
twilio/twilio-python | twilio/rest/api/v2010/account/usage/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/__init__.py#L91-L100 | def get_instance(self, payload):
"""
Build an instance of UsageInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.UsageInstance
:rtype: twilio.rest.api.v2010.account.usage.UsageInstance
"""
return UsageInsta... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"UsageInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")"
] | Build an instance of UsageInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.UsageInstance
:rtype: twilio.rest.api.v2010.account.usage.UsageInstance | [
"Build",
"an",
"instance",
"of",
"UsageInstance"
] | python | train | 38.3 |
dossier/dossier.fc | python/dossier/fc/feature_collection.py | https://github.com/dossier/dossier.fc/blob/3e969d0cb2592fc06afc1c849d2b22283450b5e2/python/dossier/fc/feature_collection.py#L451-L456 | def total(self):
'''
Returns sum of all counts in all features that are multisets.
'''
feats = imap(lambda name: self[name], self._counters())
return sum(chain(*map(lambda mset: map(abs, mset.values()), feats))) | [
"def",
"total",
"(",
"self",
")",
":",
"feats",
"=",
"imap",
"(",
"lambda",
"name",
":",
"self",
"[",
"name",
"]",
",",
"self",
".",
"_counters",
"(",
")",
")",
"return",
"sum",
"(",
"chain",
"(",
"*",
"map",
"(",
"lambda",
"mset",
":",
"map",
... | Returns sum of all counts in all features that are multisets. | [
"Returns",
"sum",
"of",
"all",
"counts",
"in",
"all",
"features",
"that",
"are",
"multisets",
"."
] | python | train | 41 |
SiLab-Bonn/pyBAR | pybar/fei4/register_utils.py | https://github.com/SiLab-Bonn/pyBAR/blob/5ad95bbcd41cd358825823fb78f396cfce23593e/pybar/fei4/register_utils.py#L598-L633 | def read_pixel_register(self, pix_regs=None, dcs=range(40), overwrite_config=False):
'''The function reads the pixel register, interprets the data and returns a masked numpy arrays with the data for the chosen pixel register.
Pixels without any data are masked.
Parameters
----------
pix_regs ... | [
"def",
"read_pixel_register",
"(",
"self",
",",
"pix_regs",
"=",
"None",
",",
"dcs",
"=",
"range",
"(",
"40",
")",
",",
"overwrite_config",
"=",
"False",
")",
":",
"if",
"pix_regs",
"is",
"None",
":",
"pix_regs",
"=",
"[",
"\"EnableDigInj\"",
",",
"\"Imo... | The function reads the pixel register, interprets the data and returns a masked numpy arrays with the data for the chosen pixel register.
Pixels without any data are masked.
Parameters
----------
pix_regs : iterable, string
List of pixel register to read (e.g. Enable, C_High, ...).
... | [
"The",
"function",
"reads",
"the",
"pixel",
"register",
"interprets",
"the",
"data",
"and",
"returns",
"a",
"masked",
"numpy",
"arrays",
"with",
"the",
"data",
"for",
"the",
"chosen",
"pixel",
"register",
".",
"Pixels",
"without",
"any",
"data",
"are",
"mask... | python | train | 45.277778 |
zblz/naima | naima/radiative.py | https://github.com/zblz/naima/blob/d6a6781d73bf58fd8269e8b0e3b70be22723cd5b/naima/radiative.py#L768-L819 | def flux(self, photon_energy, distance=1 * u.kpc, seed=None):
"""Differential flux at a given distance from the source from a single
seed photon field
Parameters
----------
photon_energy : :class:`~astropy.units.Quantity` float or array
Photon energy array.
... | [
"def",
"flux",
"(",
"self",
",",
"photon_energy",
",",
"distance",
"=",
"1",
"*",
"u",
".",
"kpc",
",",
"seed",
"=",
"None",
")",
":",
"model",
"=",
"super",
"(",
"InverseCompton",
",",
"self",
")",
".",
"flux",
"(",
"photon_energy",
",",
"distance",... | Differential flux at a given distance from the source from a single
seed photon field
Parameters
----------
photon_energy : :class:`~astropy.units.Quantity` float or array
Photon energy array.
distance : :class:`~astropy.units.Quantity` float, optional
D... | [
"Differential",
"flux",
"at",
"a",
"given",
"distance",
"from",
"the",
"source",
"from",
"a",
"single",
"seed",
"photon",
"field"
] | python | train | 37.730769 |
dbcli/athenacli | athenacli/main.py | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/main.py#L643-L693 | def cli(execute, region, aws_access_key_id, aws_secret_access_key,
s3_staging_dir, athenaclirc, profile, database):
'''A Athena terminal client with auto-completion and syntax highlighting.
\b
Examples:
- athenacli
- athenacli my_database
'''
if (athenaclirc == ATHENACLIRC) and ... | [
"def",
"cli",
"(",
"execute",
",",
"region",
",",
"aws_access_key_id",
",",
"aws_secret_access_key",
",",
"s3_staging_dir",
",",
"athenaclirc",
",",
"profile",
",",
"database",
")",
":",
"if",
"(",
"athenaclirc",
"==",
"ATHENACLIRC",
")",
"and",
"(",
"not",
... | A Athena terminal client with auto-completion and syntax highlighting.
\b
Examples:
- athenacli
- athenacli my_database | [
"A",
"Athena",
"terminal",
"client",
"with",
"auto",
"-",
"completion",
"and",
"syntax",
"highlighting",
"."
] | python | train | 29.27451 |
lsst-sqre/ltd-conveyor | ltdconveyor/s3/upload.py | https://github.com/lsst-sqre/ltd-conveyor/blob/c492937c4c1e050ccc4a0b9dcc38f9980d57e305/ltdconveyor/s3/upload.py#L213-L254 | def upload_object(bucket_path, bucket, content='',
metadata=None, acl=None, cache_control=None,
content_type=None):
"""Upload an arbitrary object to an S3 bucket.
Parameters
----------
bucket_path : `str`
Destination path (also known as the key name) of the f... | [
"def",
"upload_object",
"(",
"bucket_path",
",",
"bucket",
",",
"content",
"=",
"''",
",",
"metadata",
"=",
"None",
",",
"acl",
"=",
"None",
",",
"cache_control",
"=",
"None",
",",
"content_type",
"=",
"None",
")",
":",
"obj",
"=",
"bucket",
".",
"Obje... | Upload an arbitrary object to an S3 bucket.
Parameters
----------
bucket_path : `str`
Destination path (also known as the key name) of the file in the
S3 bucket.
content : `str` or `bytes`, optional
Object content.
bucket : boto3 Bucket instance
S3 bucket.
metada... | [
"Upload",
"an",
"arbitrary",
"object",
"to",
"an",
"S3",
"bucket",
"."
] | python | test | 37.833333 |
ekzhu/datasketch | datasketch/lsh.py | https://github.com/ekzhu/datasketch/blob/b3e4129987890a2beb04f2c0b6dc618ae35f2e14/datasketch/lsh.py#L136-L149 | def insert(self, key, minhash, check_duplication=True):
'''
Insert a key to the index, together
with a MinHash (or weighted MinHash) of the set referenced by
the key.
:param str key: The identifier of the set.
:param datasketch.MinHash minhash: The MinHash of the set.
... | [
"def",
"insert",
"(",
"self",
",",
"key",
",",
"minhash",
",",
"check_duplication",
"=",
"True",
")",
":",
"self",
".",
"_insert",
"(",
"key",
",",
"minhash",
",",
"check_duplication",
"=",
"check_duplication",
",",
"buffer",
"=",
"False",
")"
] | Insert a key to the index, together
with a MinHash (or weighted MinHash) of the set referenced by
the key.
:param str key: The identifier of the set.
:param datasketch.MinHash minhash: The MinHash of the set.
:param bool check_duplication: To avoid duplicate keys in the storage... | [
"Insert",
"a",
"key",
"to",
"the",
"index",
"together",
"with",
"a",
"MinHash",
"(",
"or",
"weighted",
"MinHash",
")",
"of",
"the",
"set",
"referenced",
"by",
"the",
"key",
"."
] | python | test | 53.785714 |
prechelt/typecheck-decorator | typecheck/framework.py | https://github.com/prechelt/typecheck-decorator/blob/4aa5a7f17235c70b5b787c9e80bb1f24d3f15933/typecheck/framework.py#L198-L210 | def check(self, values, namespace):
"""specifying a plain tuple allows arguments that are tuples or lists;
specifying a specialized (subclassed) tuple allows only that type;
specifying a list allows only that list type."""
is_tuplish_type = (issubclass(self._cls, tg.Tuple) or
... | [
"def",
"check",
"(",
"self",
",",
"values",
",",
"namespace",
")",
":",
"is_tuplish_type",
"=",
"(",
"issubclass",
"(",
"self",
".",
"_cls",
",",
"tg",
".",
"Tuple",
")",
"or",
"issubclass",
"(",
"type",
"(",
"values",
")",
",",
"self",
".",
"_cls",
... | specifying a plain tuple allows arguments that are tuples or lists;
specifying a specialized (subclassed) tuple allows only that type;
specifying a list allows only that list type. | [
"specifying",
"a",
"plain",
"tuple",
"allows",
"arguments",
"that",
"are",
"tuples",
"or",
"lists",
";",
"specifying",
"a",
"specialized",
"(",
"subclassed",
")",
"tuple",
"allows",
"only",
"that",
"type",
";",
"specifying",
"a",
"list",
"allows",
"only",
"t... | python | train | 51 |
pydata/xarray | xarray/core/groupby.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/groupby.py#L72-L88 | def _consolidate_slices(slices):
"""Consolidate adjacent slices in a list of slices.
"""
result = []
last_slice = slice(None)
for slice_ in slices:
if not isinstance(slice_, slice):
raise ValueError('list element is not a slice: %r' % slice_)
if (result and last_slice.sto... | [
"def",
"_consolidate_slices",
"(",
"slices",
")",
":",
"result",
"=",
"[",
"]",
"last_slice",
"=",
"slice",
"(",
"None",
")",
"for",
"slice_",
"in",
"slices",
":",
"if",
"not",
"isinstance",
"(",
"slice_",
",",
"slice",
")",
":",
"raise",
"ValueError",
... | Consolidate adjacent slices in a list of slices. | [
"Consolidate",
"adjacent",
"slices",
"in",
"a",
"list",
"of",
"slices",
"."
] | python | train | 37.294118 |
BerkeleyAutomation/perception | perception/colorized_phoxi_sensor.py | https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/colorized_phoxi_sensor.py#L145-L196 | def _colorize(self, depth_im, color_im):
"""Colorize a depth image from the PhoXi using a color image from the webcam.
Parameters
----------
depth_im : DepthImage
The PhoXi depth image.
color_im : ColorImage
Corresponding color image.
Returns
... | [
"def",
"_colorize",
"(",
"self",
",",
"depth_im",
",",
"color_im",
")",
":",
"# Project the point cloud into the webcam's frame",
"target_shape",
"=",
"(",
"depth_im",
".",
"data",
".",
"shape",
"[",
"0",
"]",
",",
"depth_im",
".",
"data",
".",
"shape",
"[",
... | Colorize a depth image from the PhoXi using a color image from the webcam.
Parameters
----------
depth_im : DepthImage
The PhoXi depth image.
color_im : ColorImage
Corresponding color image.
Returns
-------
ColorImage
A colori... | [
"Colorize",
"a",
"depth",
"image",
"from",
"the",
"PhoXi",
"using",
"a",
"color",
"image",
"from",
"the",
"webcam",
"."
] | python | train | 47.653846 |
nion-software/nionswift-io | nionswift_plugin/TIFF_IO/tifffile.py | https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L10782-L11057 | def imshow(data, photometric=None, planarconfig=None, bitspersample=None,
interpolation=None, cmap=None, vmin=None, vmax=None,
figure=None, title=None, dpi=96, subplot=None, maxdim=None,
**kwargs):
"""Plot n-dimensional images using matplotlib.pyplot.
Return figure, subplot and... | [
"def",
"imshow",
"(",
"data",
",",
"photometric",
"=",
"None",
",",
"planarconfig",
"=",
"None",
",",
"bitspersample",
"=",
"None",
",",
"interpolation",
"=",
"None",
",",
"cmap",
"=",
"None",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
",",
... | Plot n-dimensional images using matplotlib.pyplot.
Return figure, subplot and plot axis.
Requires pyplot already imported C{from matplotlib import pyplot}.
Parameters
----------
data : nd array
The image data.
photometric : {'MINISWHITE', 'MINISBLACK', 'RGB', or 'PALETTE'}
The ... | [
"Plot",
"n",
"-",
"dimensional",
"images",
"using",
"matplotlib",
".",
"pyplot",
"."
] | python | train | 34.362319 |
hydraplatform/hydra-base | hydra_base/lib/notes.py | https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/notes.py#L82-L97 | def update_note(note, **kwargs):
"""
Update a note
"""
note_i = _get_note(note.id)
if note.ref_key != note_i.ref_key:
raise HydraError("Cannot convert a %s note to a %s note. Please create a new note instead."%(note_i.ref_key, note.ref_key))
note_i.set_ref(note.ref_key, note.ref_id)
... | [
"def",
"update_note",
"(",
"note",
",",
"*",
"*",
"kwargs",
")",
":",
"note_i",
"=",
"_get_note",
"(",
"note",
".",
"id",
")",
"if",
"note",
".",
"ref_key",
"!=",
"note_i",
".",
"ref_key",
":",
"raise",
"HydraError",
"(",
"\"Cannot convert a %s note to a %... | Update a note | [
"Update",
"a",
"note"
] | python | train | 23.625 |
wakatime/wakatime | wakatime/packages/pygments/lexers/rebol.py | https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/lexers/rebol.py#L235-L244 | def analyse_text(text):
"""
Check if code contains REBOL header and so it probably not R code
"""
if re.match(r'^\s*REBOL\s*\[', text, re.IGNORECASE):
# The code starts with REBOL header
return 1.0
elif re.search(r'\s*REBOL\s*[', text, re.IGNORECASE):
... | [
"def",
"analyse_text",
"(",
"text",
")",
":",
"if",
"re",
".",
"match",
"(",
"r'^\\s*REBOL\\s*\\['",
",",
"text",
",",
"re",
".",
"IGNORECASE",
")",
":",
"# The code starts with REBOL header",
"return",
"1.0",
"elif",
"re",
".",
"search",
"(",
"r'\\s*REBOL\\s*... | Check if code contains REBOL header and so it probably not R code | [
"Check",
"if",
"code",
"contains",
"REBOL",
"header",
"and",
"so",
"it",
"probably",
"not",
"R",
"code"
] | python | train | 40.3 |
John-Lin/pydcard | pydcard/pydcard.py | https://github.com/John-Lin/pydcard/blob/57b57cca2c69dc0c260f5b05ae440341860d8ce4/pydcard/pydcard.py#L9-L18 | def pageassert(func):
'''
Decorator that assert page number
'''
@wraps(func)
def wrapper(*args, **kwargs):
if args[0] < 1 or args[0] > 40:
raise ValueError('Page Number not found')
return func(*args, **kwargs)
return wrapper | [
"def",
"pageassert",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
"[",
"0",
"]",
"<",
"1",
"or",
"args",
"[",
"0",
"]",
">",
"40",
":",
"raise",
... | Decorator that assert page number | [
"Decorator",
"that",
"assert",
"page",
"number"
] | python | train | 26.7 |
aksas/pypo4sel | core/pypo4sel/core/common.py | https://github.com/aksas/pypo4sel/blob/935b5f9bfa6682aefdef8a43ebcbcf274dec752c/core/pypo4sel/core/common.py#L226-L252 | def build_locator(selector):
"""
- ID = "#valid_id"
- CLASS_NAME = ".valid_class_name"
- TAG_NAME = "valid_tag_name"
- XPATH = start with "./" or "//" or "$x:"
- LINK_TEXT = start with "$link_text:"
- PARTIAL_LINK_TEXT = start with "$partial_link_text:"
- NAME = "@valid_name_attribute_va... | [
"def",
"build_locator",
"(",
"selector",
")",
":",
"if",
"type",
"(",
"selector",
")",
"is",
"tuple",
":",
"return",
"selector",
"if",
"not",
"isinstance",
"(",
"selector",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"InvalidSelectorException",
"(",
... | - ID = "#valid_id"
- CLASS_NAME = ".valid_class_name"
- TAG_NAME = "valid_tag_name"
- XPATH = start with "./" or "//" or "$x:"
- LINK_TEXT = start with "$link_text:"
- PARTIAL_LINK_TEXT = start with "$partial_link_text:"
- NAME = "@valid_name_attribute_value"
CSS_SELECTOR = all other that s... | [
"-",
"ID",
"=",
"#valid_id",
"-",
"CLASS_NAME",
"=",
".",
"valid_class_name",
"-",
"TAG_NAME",
"=",
"valid_tag_name",
"-",
"XPATH",
"=",
"start",
"with",
".",
"/",
"or",
"//",
"or",
"$x",
":",
"-",
"LINK_TEXT",
"=",
"start",
"with",
"$link_text",
":",
... | python | train | 32.666667 |
acutesoftware/AIKIF | aikif/toolbox/text_tools.py | https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/text_tools.py#L5-L25 | def parse_text_to_table(txt):
"""
takes a blob of text and finds delimiter OR guesses
the column positions to parse into a table.
input: txt = blob of text, lines separated by \n
output: res = table of text
"""
res = [] # resulting table
delim = identify_delim(txt)
print('txt to pars... | [
"def",
"parse_text_to_table",
"(",
"txt",
")",
":",
"res",
"=",
"[",
"]",
"# resulting table\r",
"delim",
"=",
"identify_delim",
"(",
"txt",
")",
"print",
"(",
"'txt to parse = '",
",",
"txt",
",",
"'\\ndelim='",
",",
"delim",
")",
"if",
"delim",
"==",
"''... | takes a blob of text and finds delimiter OR guesses
the column positions to parse into a table.
input: txt = blob of text, lines separated by \n
output: res = table of text | [
"takes",
"a",
"blob",
"of",
"text",
"and",
"finds",
"delimiter",
"OR",
"guesses",
"the",
"column",
"positions",
"to",
"parse",
"into",
"a",
"table",
".",
"input",
":",
"txt",
"=",
"blob",
"of",
"text",
"lines",
"separated",
"by",
"\\",
"n",
"output",
"... | python | train | 26.904762 |
danilobellini/audiolazy | audiolazy/lazy_io.py | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_io.py#L220-L250 | def close(self):
"""
Destructor for this audio interface. Waits the threads to finish their
streams, if desired.
"""
with self.halting: # Avoid simultaneous "close" threads
if not self.finished: # Ignore all "close" calls, but the first,
self.finished = True # and any call to play wo... | [
"def",
"close",
"(",
"self",
")",
":",
"with",
"self",
".",
"halting",
":",
"# Avoid simultaneous \"close\" threads",
"if",
"not",
"self",
".",
"finished",
":",
"# Ignore all \"close\" calls, but the first,",
"self",
".",
"finished",
"=",
"True",
"# and any call to pl... | Destructor for this audio interface. Waits the threads to finish their
streams, if desired. | [
"Destructor",
"for",
"this",
"audio",
"interface",
".",
"Waits",
"the",
"threads",
"to",
"finish",
"their",
"streams",
"if",
"desired",
"."
] | python | train | 32.870968 |
hugapi/hug | hug/routing.py | https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/routing.py#L256-L277 | def allow_origins(self, *origins, methods=None, max_age=None, credentials=None, headers=None, **overrides):
"""Convenience method for quickly allowing other resources to access this one"""
response_headers = {}
if origins:
@hug.response_middleware()
def process_data(reque... | [
"def",
"allow_origins",
"(",
"self",
",",
"*",
"origins",
",",
"methods",
"=",
"None",
",",
"max_age",
"=",
"None",
",",
"credentials",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"overrides",
")",
":",
"response_headers",
"=",
"{",
"}",
... | Convenience method for quickly allowing other resources to access this one | [
"Convenience",
"method",
"for",
"quickly",
"allowing",
"other",
"resources",
"to",
"access",
"this",
"one"
] | python | train | 49.909091 |
RedFantom/ttkwidgets | ttkwidgets/checkboxtreeview.py | https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/checkboxtreeview.py#L133-L145 | def tag_del(self, item, tag):
"""
Remove tag from the tags of item.
:param item: item identifier
:type item: str
:param tag: tag name
:type tag: str
"""
tags = list(self.item(item, "tags"))
if tag in tags:
tags.remove(tag)
... | [
"def",
"tag_del",
"(",
"self",
",",
"item",
",",
"tag",
")",
":",
"tags",
"=",
"list",
"(",
"self",
".",
"item",
"(",
"item",
",",
"\"tags\"",
")",
")",
"if",
"tag",
"in",
"tags",
":",
"tags",
".",
"remove",
"(",
"tag",
")",
"self",
".",
"item"... | Remove tag from the tags of item.
:param item: item identifier
:type item: str
:param tag: tag name
:type tag: str | [
"Remove",
"tag",
"from",
"the",
"tags",
"of",
"item",
".",
":",
"param",
"item",
":",
"item",
"identifier",
":",
"type",
"item",
":",
"str",
":",
"param",
"tag",
":",
"tag",
"name",
":",
"type",
"tag",
":",
"str"
] | python | train | 26.846154 |
inspirehep/harvesting-kit | harvestingkit/inspire_cds_package/from_inspire.py | https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/inspire_cds_package/from_inspire.py#L178-L230 | def get_record(self):
"""Override the base."""
self.recid = self.get_recid()
self.remove_controlfields()
self.update_system_numbers()
self.add_systemnumber("Inspire", recid=self.recid)
self.add_control_number("003", "SzGeCERN")
self.update_collections()
se... | [
"def",
"get_record",
"(",
"self",
")",
":",
"self",
".",
"recid",
"=",
"self",
".",
"get_recid",
"(",
")",
"self",
".",
"remove_controlfields",
"(",
")",
"self",
".",
"update_system_numbers",
"(",
")",
"self",
".",
"add_systemnumber",
"(",
"\"Inspire\"",
"... | Override the base. | [
"Override",
"the",
"base",
"."
] | python | valid | 33.698113 |
senaite/senaite.core | bika/lims/workflow/analysisservice/guards.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/workflow/analysisservice/guards.py#L24-L43 | def guard_activate(analysis_service):
"""Returns whether the transition activate can be performed for the
analysis service passed in
"""
calculation = analysis_service.getCalculation()
if not calculation:
return True
# If the calculation is inactive, we cannot activate the service
i... | [
"def",
"guard_activate",
"(",
"analysis_service",
")",
":",
"calculation",
"=",
"analysis_service",
".",
"getCalculation",
"(",
")",
"if",
"not",
"calculation",
":",
"return",
"True",
"# If the calculation is inactive, we cannot activate the service",
"if",
"not",
"api",
... | Returns whether the transition activate can be performed for the
analysis service passed in | [
"Returns",
"whether",
"the",
"transition",
"activate",
"can",
"be",
"performed",
"for",
"the",
"analysis",
"service",
"passed",
"in"
] | python | train | 32.3 |
Chilipp/docrep | docrep/__init__.py | https://github.com/Chilipp/docrep/blob/637971f76e1a6e1c70e36dcd1b02bbc37ba02487/docrep/__init__.py#L289-L330 | def get_sections(self, s, base,
sections=['Parameters', 'Other Parameters']):
"""
Method that extracts the specified sections out of the given string if
(and only if) the docstring follows the numpy documentation guidelines
[1]_. Note that the section either must app... | [
"def",
"get_sections",
"(",
"self",
",",
"s",
",",
"base",
",",
"sections",
"=",
"[",
"'Parameters'",
",",
"'Other Parameters'",
"]",
")",
":",
"params",
"=",
"self",
".",
"params",
"# Remove the summary and dedent the rest",
"s",
"=",
"self",
".",
"_remove_su... | Method that extracts the specified sections out of the given string if
(and only if) the docstring follows the numpy documentation guidelines
[1]_. Note that the section either must appear in the
:attr:`param_like_sections` or the :attr:`text_sections` attribute.
Parameters
----... | [
"Method",
"that",
"extracts",
"the",
"specified",
"sections",
"out",
"of",
"the",
"given",
"string",
"if",
"(",
"and",
"only",
"if",
")",
"the",
"docstring",
"follows",
"the",
"numpy",
"documentation",
"guidelines",
"[",
"1",
"]",
"_",
".",
"Note",
"that",... | python | train | 35.285714 |
raiden-network/raiden | raiden/network/transport/matrix/client.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/client.py#L389-L408 | def _sync(self, timeout_ms=30000):
""" Reimplements MatrixClient._sync, add 'account_data' support to /sync """
response = self.api.sync(self.sync_token, timeout_ms)
prev_sync_token = self.sync_token
self.sync_token = response["next_batch"]
if self._handle_thread is not None:
... | [
"def",
"_sync",
"(",
"self",
",",
"timeout_ms",
"=",
"30000",
")",
":",
"response",
"=",
"self",
".",
"api",
".",
"sync",
"(",
"self",
".",
"sync_token",
",",
"timeout_ms",
")",
"prev_sync_token",
"=",
"self",
".",
"sync_token",
"self",
".",
"sync_token"... | Reimplements MatrixClient._sync, add 'account_data' support to /sync | [
"Reimplements",
"MatrixClient",
".",
"_sync",
"add",
"account_data",
"support",
"to",
"/",
"sync"
] | python | train | 46.5 |
CybOXProject/mixbox | mixbox/signals.py | https://github.com/CybOXProject/mixbox/blob/9097dae7a433f5b98c18171c4a5598f69a7d30af/mixbox/signals.py#L59-L72 | def __purge():
"""Remove all dead signal receivers from the global receivers collection.
Note:
It is assumed that the caller holds the __lock.
"""
global __receivers
newreceivers = collections.defaultdict(list)
for signal, receivers in six.iteritems(__receivers):
alive = [x for... | [
"def",
"__purge",
"(",
")",
":",
"global",
"__receivers",
"newreceivers",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"signal",
",",
"receivers",
"in",
"six",
".",
"iteritems",
"(",
"__receivers",
")",
":",
"alive",
"=",
"[",
"x",
"f... | Remove all dead signal receivers from the global receivers collection.
Note:
It is assumed that the caller holds the __lock. | [
"Remove",
"all",
"dead",
"signal",
"receivers",
"from",
"the",
"global",
"receivers",
"collection",
"."
] | python | train | 29.428571 |
Murali-group/halp | halp/directed_hypergraph.py | https://github.com/Murali-group/halp/blob/6eb27466ba84e2281e18f93b62aae5efb21ef8b3/halp/directed_hypergraph.py#L912-L924 | def is_F_hypergraph(self):
"""Indicates whether the hypergraph is an F-hypergraph.
In an F-hypergraph, all hyperedges are F-hyperedges -- that is, every
hyperedge has exactly one node in the tail.
:returns: bool -- True iff the hypergraph is an F-hypergraph.
"""
for hyp... | [
"def",
"is_F_hypergraph",
"(",
"self",
")",
":",
"for",
"hyperedge_id",
"in",
"self",
".",
"_hyperedge_attributes",
":",
"tail",
"=",
"self",
".",
"get_hyperedge_tail",
"(",
"hyperedge_id",
")",
"if",
"len",
"(",
"tail",
")",
">",
"1",
":",
"return",
"Fals... | Indicates whether the hypergraph is an F-hypergraph.
In an F-hypergraph, all hyperedges are F-hyperedges -- that is, every
hyperedge has exactly one node in the tail.
:returns: bool -- True iff the hypergraph is an F-hypergraph. | [
"Indicates",
"whether",
"the",
"hypergraph",
"is",
"an",
"F",
"-",
"hypergraph",
".",
"In",
"an",
"F",
"-",
"hypergraph",
"all",
"hyperedges",
"are",
"F",
"-",
"hyperedges",
"--",
"that",
"is",
"every",
"hyperedge",
"has",
"exactly",
"one",
"node",
"in",
... | python | train | 37.230769 |
hbldh/pybankid | bankid/jsonclient.py | https://github.com/hbldh/pybankid/blob/1405f66e41f912cdda15e20aea08cdfa6b60480a/bankid/jsonclient.py#L79-L126 | def authenticate(
self, end_user_ip, personal_number=None, requirement=None, **kwargs
):
"""Request an authentication order. The :py:meth:`collect` method
is used to query the status of the order.
Note that personal number is not needed when authentication is to
be done on t... | [
"def",
"authenticate",
"(",
"self",
",",
"end_user_ip",
",",
"personal_number",
"=",
"None",
",",
"requirement",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"{",
"\"endUserIp\"",
":",
"end_user_ip",
"}",
"if",
"personal_number",
":",
"data... | Request an authentication order. The :py:meth:`collect` method
is used to query the status of the order.
Note that personal number is not needed when authentication is to
be done on the same device, provided that the returned
``autoStartToken`` is used to open the BankID Client.
... | [
"Request",
"an",
"authentication",
"order",
".",
"The",
":",
"py",
":",
"meth",
":",
"collect",
"method",
"is",
"used",
"to",
"query",
"the",
"status",
"of",
"the",
"order",
"."
] | python | train | 37.979167 |
zerotk/easyfs | zerotk/easyfs/_easyfs.py | https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L302-L349 | def _DoCopyFile(source_filename, target_filename, copy_symlink=True):
'''
:param unicode source_filename:
The source filename.
Schemas: local, ftp, http
:param unicode target_filename:
Target filename.
Schemas: local, ftp
:param copy_symlink:
@see _CopyFileLoca... | [
"def",
"_DoCopyFile",
"(",
"source_filename",
",",
"target_filename",
",",
"copy_symlink",
"=",
"True",
")",
":",
"from",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
"import",
"urlparse",
"source_url",
"=",
"urlparse",
"(",
"source_filename",
")",
"targe... | :param unicode source_filename:
The source filename.
Schemas: local, ftp, http
:param unicode target_filename:
Target filename.
Schemas: local, ftp
:param copy_symlink:
@see _CopyFileLocal
:raises FileNotFoundError:
If source_filename does not exist | [
":",
"param",
"unicode",
"source_filename",
":",
"The",
"source",
"filename",
".",
"Schemas",
":",
"local",
"ftp",
"http"
] | python | valid | 35.166667 |
paramiko/paramiko | paramiko/sftp_file.py | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L343-L356 | def truncate(self, size):
"""
Change the size of this file. This usually extends
or shrinks the size of the file, just like the ``truncate()`` method on
Python file objects.
:param size: the new size of the file
"""
self.sftp._log(
DEBUG, "truncate({... | [
"def",
"truncate",
"(",
"self",
",",
"size",
")",
":",
"self",
".",
"sftp",
".",
"_log",
"(",
"DEBUG",
",",
"\"truncate({}, {!r})\"",
".",
"format",
"(",
"hexlify",
"(",
"self",
".",
"handle",
")",
",",
"size",
")",
")",
"attr",
"=",
"SFTPAttributes",
... | Change the size of this file. This usually extends
or shrinks the size of the file, just like the ``truncate()`` method on
Python file objects.
:param size: the new size of the file | [
"Change",
"the",
"size",
"of",
"this",
"file",
".",
"This",
"usually",
"extends",
"or",
"shrinks",
"the",
"size",
"of",
"the",
"file",
"just",
"like",
"the",
"truncate",
"()",
"method",
"on",
"Python",
"file",
"objects",
"."
] | python | train | 34.357143 |
fastai/fastai | old/fastai/structured.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/old/fastai/structured.py#L139-L176 | def apply_cats(df, trn):
"""Changes any columns of strings in df into categorical variables using trn as
a template for the category codes.
Parameters:
-----------
df: A pandas dataframe. Any columns of strings will be changed to
categorical values. The category codes are determined by trn.
... | [
"def",
"apply_cats",
"(",
"df",
",",
"trn",
")",
":",
"for",
"n",
",",
"c",
"in",
"df",
".",
"items",
"(",
")",
":",
"if",
"(",
"n",
"in",
"trn",
".",
"columns",
")",
"and",
"(",
"trn",
"[",
"n",
"]",
".",
"dtype",
".",
"name",
"==",
"'cate... | Changes any columns of strings in df into categorical variables using trn as
a template for the category codes.
Parameters:
-----------
df: A pandas dataframe. Any columns of strings will be changed to
categorical values. The category codes are determined by trn.
trn: A pandas dataframe. Whe... | [
"Changes",
"any",
"columns",
"of",
"strings",
"in",
"df",
"into",
"categorical",
"variables",
"using",
"trn",
"as",
"a",
"template",
"for",
"the",
"category",
"codes",
".",
"Parameters",
":",
"-----------",
"df",
":",
"A",
"pandas",
"dataframe",
".",
"Any",
... | python | train | 34.552632 |
ace0/pyrelic | pyrelic/pbc.py | https://github.com/ace0/pyrelic/blob/f23d4e6586674675f72304d5938548267d6413bf/pyrelic/pbc.py#L139-L158 | def mul_table(self, other):
"""
Fast multiplication using a the LWNAF precomputation table.
"""
# Get a BigInt
other = coerceBigInt(other)
if not other:
return NotImplemented
other %= orderG2()
# Building the precomputation table, if there is ... | [
"def",
"mul_table",
"(",
"self",
",",
"other",
")",
":",
"# Get a BigInt",
"other",
"=",
"coerceBigInt",
"(",
"other",
")",
"if",
"not",
"other",
":",
"return",
"NotImplemented",
"other",
"%=",
"orderG2",
"(",
")",
"# Building the precomputation table, if there is... | Fast multiplication using a the LWNAF precomputation table. | [
"Fast",
"multiplication",
"using",
"a",
"the",
"LWNAF",
"precomputation",
"table",
"."
] | python | train | 30.3 |
googleapis/google-cloud-python | bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery_storage/google/cloud/bigquery_storage_v1beta1/reader.py#L337-L372 | def to_dataframe(self, dtypes=None):
"""Create a :class:`pandas.DataFrame` of rows in the page.
This method requires the pandas libary to create a data frame and the
fastavro library to parse row blocks.
.. warning::
DATETIME columns are not supported. They are currently pa... | [
"def",
"to_dataframe",
"(",
"self",
",",
"dtypes",
"=",
"None",
")",
":",
"if",
"pandas",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"_PANDAS_REQUIRED",
")",
"if",
"dtypes",
"is",
"None",
":",
"dtypes",
"=",
"{",
"}",
"columns",
"=",
"collections",
... | Create a :class:`pandas.DataFrame` of rows in the page.
This method requires the pandas libary to create a data frame and the
fastavro library to parse row blocks.
.. warning::
DATETIME columns are not supported. They are currently parsed as
strings in the fastavro libr... | [
"Create",
"a",
":",
"class",
":",
"pandas",
".",
"DataFrame",
"of",
"rows",
"in",
"the",
"page",
"."
] | python | train | 35.777778 |
Autodesk/aomi | aomi/vault.py | https://github.com/Autodesk/aomi/blob/84da2dfb0424837adf9c4ddc1aa352e942bb7a4a/aomi/vault.py#L130-L151 | def wrap_hvac(msg):
"""Error catching Vault API wrapper
This decorator wraps API interactions with Vault. It will
catch and return appropriate error output on common
problems. Do we even need this now that we extend the
hvac class?"""
# pylint: disable=missing-docstring
def wrap_call(func):
... | [
"def",
"wrap_hvac",
"(",
"msg",
")",
":",
"# pylint: disable=missing-docstring",
"def",
"wrap_call",
"(",
"func",
")",
":",
"# pylint: disable=missing-docstring",
"def",
"func_wrapper",
"(",
"self",
",",
"vault_client",
")",
":",
"try",
":",
"return",
"func",
"(",... | Error catching Vault API wrapper
This decorator wraps API interactions with Vault. It will
catch and return appropriate error output on common
problems. Do we even need this now that we extend the
hvac class? | [
"Error",
"catching",
"Vault",
"API",
"wrapper",
"This",
"decorator",
"wraps",
"API",
"interactions",
"with",
"Vault",
".",
"It",
"will",
"catch",
"and",
"return",
"appropriate",
"error",
"output",
"on",
"common",
"problems",
".",
"Do",
"we",
"even",
"need",
... | python | train | 40 |
openfisca/openfisca-survey-manager | openfisca_survey_manager/scenarios.py | https://github.com/openfisca/openfisca-survey-manager/blob/bed6c65dc5e4ec2bdc9cda5b865fefd9e3d0c358/openfisca_survey_manager/scenarios.py#L1071-L1182 | def summarize_variable(self, variable = None, use_baseline = False, weighted = False, force_compute = False):
"""
Prints a summary of a variable including its memory usage.
:param string variable: the variable being summarized
:param bool use_baseline: the tax-benefit-system... | [
"def",
"summarize_variable",
"(",
"self",
",",
"variable",
"=",
"None",
",",
"use_baseline",
"=",
"False",
",",
"weighted",
"=",
"False",
",",
"force_compute",
"=",
"False",
")",
":",
"if",
"use_baseline",
":",
"simulation",
"=",
"self",
".",
"baseline_simul... | Prints a summary of a variable including its memory usage.
:param string variable: the variable being summarized
:param bool use_baseline: the tax-benefit-system considered
:param bool weighted: whether the produced statistics should be weigthted or not
:param bool force... | [
"Prints",
"a",
"summary",
"of",
"a",
"variable",
"including",
"its",
"memory",
"usage",
"."
] | python | train | 53.678571 |
lowandrew/OLCTools | spadespipeline/typingclasses.py | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/typingclasses.py#L31-L42 | def main(self):
"""
Run the necessary methods in the correct order
"""
if not os.path.isfile(self.gdcs_report):
logging.info('Starting {} analysis pipeline'.format(self.analysistype))
# Run the analyses
ShortKSippingMethods(self, self.cutoff)
... | [
"def",
"main",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"gdcs_report",
")",
":",
"logging",
".",
"info",
"(",
"'Starting {} analysis pipeline'",
".",
"format",
"(",
"self",
".",
"analysistype",
")",
")",
"... | Run the necessary methods in the correct order | [
"Run",
"the",
"necessary",
"methods",
"in",
"the",
"correct",
"order"
] | python | train | 33.833333 |
Azure/azure-cosmos-python | azure/cosmos/auth.py | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/auth.py#L69-L114 | def __GetAuthorizationTokenUsingMasterKey(verb,
resource_id_or_fullname,
resource_type,
headers,
master_key):
"""Gets the authorization token using `mas... | [
"def",
"__GetAuthorizationTokenUsingMasterKey",
"(",
"verb",
",",
"resource_id_or_fullname",
",",
"resource_type",
",",
"headers",
",",
"master_key",
")",
":",
"# decodes the master key which is encoded in base64 ",
"key",
"=",
"base64",
".",
"b64decode",
"(",
"master_ke... | Gets the authorization token using `master_key.
:param str verb:
:param str resource_id_or_fullname:
:param str resource_type:
:param dict headers:
:param str master_key:
:return:
The authorization token.
:rtype: dict | [
"Gets",
"the",
"authorization",
"token",
"using",
"master_key",
"."
] | python | train | 38.021739 |
lowandrew/OLCTools | spadespipeline/mMLST.py | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/mMLST.py#L132-L153 | def makedbthreads(self, folder):
"""
Setup and create threads for class
:param folder: folder with sequence files with which to create blast databases
"""
# Create and start threads for each fasta file in the list
for i in range(len(folder)):
# Send the thread... | [
"def",
"makedbthreads",
"(",
"self",
",",
"folder",
")",
":",
"# Create and start threads for each fasta file in the list",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"folder",
")",
")",
":",
"# Send the threads to makeblastdb",
"threads",
"=",
"Thread",
"(",
"targ... | Setup and create threads for class
:param folder: folder with sequence files with which to create blast databases | [
"Setup",
"and",
"create",
"threads",
"for",
"class",
":",
"param",
"folder",
":",
"folder",
"with",
"sequence",
"files",
"with",
"which",
"to",
"create",
"blast",
"databases"
] | python | train | 45.5 |
numenta/htmresearch | htmresearch/frameworks/layers/physical_objects.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/layers/physical_objects.py#L429-L444 | def sampleLocationFromFeature(self, feature):
"""
Samples a location from one specific feature.
This is only supported with three dimensions.
"""
if feature == "face":
return self._sampleFromFaces()
elif feature == "edge":
return self._sampleFromEdges()
elif feature == "vertex":... | [
"def",
"sampleLocationFromFeature",
"(",
"self",
",",
"feature",
")",
":",
"if",
"feature",
"==",
"\"face\"",
":",
"return",
"self",
".",
"_sampleFromFaces",
"(",
")",
"elif",
"feature",
"==",
"\"edge\"",
":",
"return",
"self",
".",
"_sampleFromEdges",
"(",
... | Samples a location from one specific feature.
This is only supported with three dimensions. | [
"Samples",
"a",
"location",
"from",
"one",
"specific",
"feature",
"."
] | python | train | 30.8125 |
lsbardel/python-stdnet | stdnet/backends/redisb/__init__.py | https://github.com/lsbardel/python-stdnet/blob/78db5320bdedc3f28c5e4f38cda13a4469e35db7/stdnet/backends/redisb/__init__.py#L346-L363 | def related_lua_args(self):
'''Generator of load_related arguments'''
related = self.queryelem.select_related
if related:
meta = self.meta
for rel in related:
field = meta.dfields[rel]
relmodel = field.relmodel
bk = ... | [
"def",
"related_lua_args",
"(",
"self",
")",
":",
"related",
"=",
"self",
".",
"queryelem",
".",
"select_related",
"if",
"related",
":",
"meta",
"=",
"self",
".",
"meta",
"for",
"rel",
"in",
"related",
":",
"field",
"=",
"meta",
".",
"dfields",
"[",
"r... | Generator of load_related arguments | [
"Generator",
"of",
"load_related",
"arguments"
] | python | train | 44.888889 |
secynic/ipwhois | ipwhois/scripts/ipwhois_cli.py | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/scripts/ipwhois_cli.py#L762-L840 | def generate_output_network(self, json_data=None, hr=True, show_name=False,
colorize=True):
"""
The function for generating CLI output RDAP network results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bo... | [
"def",
"generate_output_network",
"(",
"self",
",",
"json_data",
"=",
"None",
",",
"hr",
"=",
"True",
",",
"show_name",
"=",
"False",
",",
"colorize",
"=",
"True",
")",
":",
"if",
"json_data",
"is",
"None",
":",
"json_data",
"=",
"{",
"}",
"output",
"=... | The function for generating CLI output RDAP network results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (d... | [
"The",
"function",
"for",
"generating",
"CLI",
"output",
"RDAP",
"network",
"results",
"."
] | python | train | 31.392405 |
juga0/dhcpcanon | dhcpcanon/dhcpcapfsm.py | https://github.com/juga0/dhcpcanon/blob/9f51a29e57fe93dc93fb22bb0ed12fcfe9557e59/dhcpcanon/dhcpcapfsm.py#L48-L70 | def reset(self, iface=None, client_mac=None, xid=None, scriptfile=None):
"""Reset object attributes when state is INIT."""
logger.debug('Reseting attributes.')
if iface is None:
iface = conf.iface
if client_mac is None:
# scapy for python 3 returns byte, not tuple... | [
"def",
"reset",
"(",
"self",
",",
"iface",
"=",
"None",
",",
"client_mac",
"=",
"None",
",",
"xid",
"=",
"None",
",",
"scriptfile",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'Reseting attributes.'",
")",
"if",
"iface",
"is",
"None",
":",
"... | Reset object attributes when state is INIT. | [
"Reset",
"object",
"attributes",
"when",
"state",
"is",
"INIT",
"."
] | python | test | 39.73913 |
neo4j-drivers/neobolt | neobolt/impl/python/routing.py | https://github.com/neo4j-drivers/neobolt/blob/724569d76e85777c4f5e30e8d0a18116bda4d8cd/neobolt/impl/python/routing.py#L403-L408 | def remove_writer(self, address):
""" Remove a writer address from the routing table, if present.
"""
log_debug("[#0000] C: <ROUTING> Removing writer %r", address)
self.routing_table.writers.discard(address)
log_debug("[#0000] C: <ROUTING> table=%r", self.routing_table) | [
"def",
"remove_writer",
"(",
"self",
",",
"address",
")",
":",
"log_debug",
"(",
"\"[#0000] C: <ROUTING> Removing writer %r\"",
",",
"address",
")",
"self",
".",
"routing_table",
".",
"writers",
".",
"discard",
"(",
"address",
")",
"log_debug",
"(",
"\"[#0000] C... | Remove a writer address from the routing table, if present. | [
"Remove",
"a",
"writer",
"address",
"from",
"the",
"routing",
"table",
"if",
"present",
"."
] | python | train | 51.166667 |
calvinku96/labreporthelper | labreporthelper/bestfit/bestfit.py | https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/bestfit.py#L108-L128 | def get_rmse(self, data_x=None, data_y=None):
"""
Get Root Mean Square Error using
self.bestfit_func
args:
x_min: scalar, default=min(x)
minimum x value of the line
x_max: scalar, default=max(x)
maximum x value of the line
... | [
"def",
"get_rmse",
"(",
"self",
",",
"data_x",
"=",
"None",
",",
"data_y",
"=",
"None",
")",
":",
"if",
"data_x",
"is",
"None",
":",
"data_x",
"=",
"np",
".",
"array",
"(",
"self",
".",
"args",
"[",
"\"x\"",
"]",
")",
"if",
"data_y",
"is",
"None"... | Get Root Mean Square Error using
self.bestfit_func
args:
x_min: scalar, default=min(x)
minimum x value of the line
x_max: scalar, default=max(x)
maximum x value of the line
resolution: int, default=1000
how many steps b... | [
"Get",
"Root",
"Mean",
"Square",
"Error",
"using",
"self",
".",
"bestfit_func"
] | python | train | 36.142857 |
trevisanj/f311 | f311/hapi.py | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/hapi.py#L10086-L10099 | def PROFILE_SDRAUTIAN(sg0,GamD,Gam0,Gam2,Shift0,Shift2,anuVC,sg):
"""
# Speed dependent Rautian profile based on HTP.
# Input parameters:
# sg0 : Unperturbed line position in cm-1 (Input).
# GamD : Doppler HWHM in cm-1 (Input)
# Gam0 : Speed-averaged line-width in cm-1 (... | [
"def",
"PROFILE_SDRAUTIAN",
"(",
"sg0",
",",
"GamD",
",",
"Gam0",
",",
"Gam2",
",",
"Shift0",
",",
"Shift2",
",",
"anuVC",
",",
"sg",
")",
":",
"return",
"pcqsdhc",
"(",
"sg0",
",",
"GamD",
",",
"Gam0",
",",
"Gam2",
",",
"Shift0",
",",
"Shift2",
",... | # Speed dependent Rautian profile based on HTP.
# Input parameters:
# sg0 : Unperturbed line position in cm-1 (Input).
# GamD : Doppler HWHM in cm-1 (Input)
# Gam0 : Speed-averaged line-width in cm-1 (Input).
# Gam2 : Speed dependence of the line-width in cm-1... | [
"#",
"Speed",
"dependent",
"Rautian",
"profile",
"based",
"on",
"HTP",
".",
"#",
"Input",
"parameters",
":",
"#",
"sg0",
":",
"Unperturbed",
"line",
"position",
"in",
"cm",
"-",
"1",
"(",
"Input",
")",
".",
"#",
"GamD",
":",
"Doppler",
"HWHM",
"in",
... | python | train | 53.928571 |
Asana/python-asana | asana/resources/gen/teams.py | https://github.com/Asana/python-asana/blob/6deb7a34495db23f44858e53b6bb2c9eccff7872/asana/resources/gen/teams.py#L33-L45 | def find_by_user(self, user, params={}, **options):
"""Returns the compact records for all teams to which user is assigned.
Parameters
----------
user : {String} An identifier for the user. Can be one of an email address,
the globally unique identifier for the user, or the keyw... | [
"def",
"find_by_user",
"(",
"self",
",",
"user",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/users/%s/teams\"",
"%",
"(",
"user",
")",
"return",
"self",
".",
"client",
".",
"get_collection",
"(",
"path",
",",
"p... | Returns the compact records for all teams to which user is assigned.
Parameters
----------
user : {String} An identifier for the user. Can be one of an email address,
the globally unique identifier for the user, or the keyword `me`
to indicate the current user making the request... | [
"Returns",
"the",
"compact",
"records",
"for",
"all",
"teams",
"to",
"which",
"user",
"is",
"assigned",
"."
] | python | train | 48.692308 |
saltstack/salt | salt/cli/daemons.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/daemons.py#L570-L588 | def start(self):
'''
Start the actual syndic.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
'''
super(Syndic, self).start()
if check_user(self.config['user']):
... | [
"def",
"start",
"(",
"self",
")",
":",
"super",
"(",
"Syndic",
",",
"self",
")",
".",
"start",
"(",
")",
"if",
"check_user",
"(",
"self",
".",
"config",
"[",
"'user'",
"]",
")",
":",
"self",
".",
"action_log_info",
"(",
"'Starting up'",
")",
"self",
... | Start the actual syndic.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`. | [
"Start",
"the",
"actual",
"syndic",
"."
] | python | train | 29.368421 |
numba/llvmlite | llvmlite/ir/builder.py | https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/ir/builder.py#L968-L973 | def assume(self, cond):
"""
Optimizer hint: assume *cond* is always true.
"""
fn = self.module.declare_intrinsic("llvm.assume")
return self.call(fn, [cond]) | [
"def",
"assume",
"(",
"self",
",",
"cond",
")",
":",
"fn",
"=",
"self",
".",
"module",
".",
"declare_intrinsic",
"(",
"\"llvm.assume\"",
")",
"return",
"self",
".",
"call",
"(",
"fn",
",",
"[",
"cond",
"]",
")"
] | Optimizer hint: assume *cond* is always true. | [
"Optimizer",
"hint",
":",
"assume",
"*",
"cond",
"*",
"is",
"always",
"true",
"."
] | python | train | 31.833333 |
Tanganelli/CoAPthon3 | coapthon/layers/forwardLayer.py | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/forwardLayer.py#L83-L119 | def _forward_request(transaction, destination, path):
"""
Forward requests.
:type transaction: Transaction
:param transaction: the transaction that owns the request
:param destination: the destination of the request (IP, port)
:param path: the path of the request.
... | [
"def",
"_forward_request",
"(",
"transaction",
",",
"destination",
",",
"path",
")",
":",
"client",
"=",
"HelperClient",
"(",
"destination",
")",
"request",
"=",
"Request",
"(",
")",
"request",
".",
"options",
"=",
"copy",
".",
"deepcopy",
"(",
"transaction"... | Forward requests.
:type transaction: Transaction
:param transaction: the transaction that owns the request
:param destination: the destination of the request (IP, port)
:param path: the path of the request.
:rtype : Transaction
:return: the edited transaction | [
"Forward",
"requests",
"."
] | python | train | 36.135135 |
apache/spark | python/pyspark/mllib/linalg/__init__.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/mllib/linalg/__init__.py#L1328-L1344 | def fromML(mat):
"""
Convert a matrix from the new mllib-local representation.
This does NOT copy the data; it copies references.
:param mat: a :py:class:`pyspark.ml.linalg.Matrix`
:return: a :py:class:`pyspark.mllib.linalg.Matrix`
.. versionadded:: 2.0.0
"""
... | [
"def",
"fromML",
"(",
"mat",
")",
":",
"if",
"isinstance",
"(",
"mat",
",",
"newlinalg",
".",
"DenseMatrix",
")",
":",
"return",
"DenseMatrix",
"(",
"mat",
".",
"numRows",
",",
"mat",
".",
"numCols",
",",
"mat",
".",
"values",
",",
"mat",
".",
"isTra... | Convert a matrix from the new mllib-local representation.
This does NOT copy the data; it copies references.
:param mat: a :py:class:`pyspark.ml.linalg.Matrix`
:return: a :py:class:`pyspark.mllib.linalg.Matrix`
.. versionadded:: 2.0.0 | [
"Convert",
"a",
"matrix",
"from",
"the",
"new",
"mllib",
"-",
"local",
"representation",
".",
"This",
"does",
"NOT",
"copy",
"the",
"data",
";",
"it",
"copies",
"references",
"."
] | python | train | 42.705882 |
google/apitools | apitools/base/py/base_api.py | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L689-L731 | def _RunMethod(self, method_config, request, global_params=None,
upload=None, upload_config=None, download=None):
"""Call this method with request."""
if upload is not None and download is not None:
# TODO(craigcitro): This just involves refactoring the logic
#... | [
"def",
"_RunMethod",
"(",
"self",
",",
"method_config",
",",
"request",
",",
"global_params",
"=",
"None",
",",
"upload",
"=",
"None",
",",
"upload_config",
"=",
"None",
",",
"download",
"=",
"None",
")",
":",
"if",
"upload",
"is",
"not",
"None",
"and",
... | Call this method with request. | [
"Call",
"this",
"method",
"with",
"request",
"."
] | python | train | 46.72093 |
googleapis/google-cloud-python | datastore/google/cloud/datastore/_gapic.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/datastore/google/cloud/datastore/_gapic.py#L28-L49 | def make_datastore_api(client):
"""Create an instance of the GAPIC Datastore API.
:type client: :class:`~google.cloud.datastore.client.Client`
:param client: The client that holds configuration details.
:rtype: :class:`.datastore.v1.datastore_client.DatastoreClient`
:returns: A datastore API insta... | [
"def",
"make_datastore_api",
"(",
"client",
")",
":",
"parse_result",
"=",
"six",
".",
"moves",
".",
"urllib_parse",
".",
"urlparse",
"(",
"client",
".",
"_base_url",
")",
"host",
"=",
"parse_result",
".",
"netloc",
"if",
"parse_result",
".",
"scheme",
"==",... | Create an instance of the GAPIC Datastore API.
:type client: :class:`~google.cloud.datastore.client.Client`
:param client: The client that holds configuration details.
:rtype: :class:`.datastore.v1.datastore_client.DatastoreClient`
:returns: A datastore API instance with the proper credentials. | [
"Create",
"an",
"instance",
"of",
"the",
"GAPIC",
"Datastore",
"API",
"."
] | python | train | 37.272727 |
apache/incubator-mxnet | python/mxnet/gluon/trainer.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/trainer.py#L258-L270 | def set_learning_rate(self, lr):
"""Sets a new learning rate of the optimizer.
Parameters
----------
lr : float
The new learning rate of the optimizer.
"""
if not isinstance(self._optimizer, opt.Optimizer):
raise UserWarning("Optimizer has to be d... | [
"def",
"set_learning_rate",
"(",
"self",
",",
"lr",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_optimizer",
",",
"opt",
".",
"Optimizer",
")",
":",
"raise",
"UserWarning",
"(",
"\"Optimizer has to be defined before its learning \"",
"\"rate is mutated.\... | Sets a new learning rate of the optimizer.
Parameters
----------
lr : float
The new learning rate of the optimizer. | [
"Sets",
"a",
"new",
"learning",
"rate",
"of",
"the",
"optimizer",
"."
] | python | train | 34.615385 |
tornadoweb/tornado | tornado/iostream.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L526-L563 | def write(self, data: Union[bytes, memoryview]) -> "Future[None]":
"""Asynchronously write the given data to this stream.
This method returns a `.Future` that resolves (with a result
of ``None``) when the write has been completed.
The ``data`` argument may be of type `bytes` or `memory... | [
"def",
"write",
"(",
"self",
",",
"data",
":",
"Union",
"[",
"bytes",
",",
"memoryview",
"]",
")",
"->",
"\"Future[None]\"",
":",
"self",
".",
"_check_closed",
"(",
")",
"if",
"data",
":",
"if",
"(",
"self",
".",
"max_write_buffer_size",
"is",
"not",
"... | Asynchronously write the given data to this stream.
This method returns a `.Future` that resolves (with a result
of ``None``) when the write has been completed.
The ``data`` argument may be of type `bytes` or `memoryview`.
.. versionchanged:: 4.0
Now returns a `.Future` if... | [
"Asynchronously",
"write",
"the",
"given",
"data",
"to",
"this",
"stream",
"."
] | python | train | 36.973684 |
tensorflow/tensor2tensor | tensor2tensor/models/research/autoencoders.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1085-L1103 | def autoencoder_residual():
"""Residual autoencoder model."""
hparams = autoencoder_autoregressive()
hparams.optimizer = "Adafactor"
hparams.clip_grad_norm = 1.0
hparams.learning_rate_constant = 0.5
hparams.learning_rate_warmup_steps = 500
hparams.learning_rate_schedule = "constant * linear_warmup * rsqrt... | [
"def",
"autoencoder_residual",
"(",
")",
":",
"hparams",
"=",
"autoencoder_autoregressive",
"(",
")",
"hparams",
".",
"optimizer",
"=",
"\"Adafactor\"",
"hparams",
".",
"clip_grad_norm",
"=",
"1.0",
"hparams",
".",
"learning_rate_constant",
"=",
"0.5",
"hparams",
... | Residual autoencoder model. | [
"Residual",
"autoencoder",
"model",
"."
] | python | train | 40.315789 |
Xion/taipan | taipan/collections/dicts.py | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/dicts.py#L320-L336 | def mapkeys(function, dict_):
"""Return a new dictionary where the keys come from applying ``function``
to the keys of given dictionary.
.. warning::
If ``function`` returns the same value for more than one key,
it is undefined which key will be chosen for the resulting dictionary.
:p... | [
"def",
"mapkeys",
"(",
"function",
",",
"dict_",
")",
":",
"ensure_mapping",
"(",
"dict_",
")",
"function",
"=",
"identity",
"(",
")",
"if",
"function",
"is",
"None",
"else",
"ensure_callable",
"(",
"function",
")",
"return",
"dict_",
".",
"__class__",
"("... | Return a new dictionary where the keys come from applying ``function``
to the keys of given dictionary.
.. warning::
If ``function`` returns the same value for more than one key,
it is undefined which key will be chosen for the resulting dictionary.
:param function: Function taking a dict... | [
"Return",
"a",
"new",
"dictionary",
"where",
"the",
"keys",
"come",
"from",
"applying",
"function",
"to",
"the",
"keys",
"of",
"given",
"dictionary",
"."
] | python | train | 37.176471 |
BD2KGenomics/protect | src/protect/pipeline/ProTECT.py | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/pipeline/ProTECT.py#L94-L148 | def _ensure_patient_group_is_ok(patient_object, patient_name=None):
"""
Ensure that the provided entries for the patient groups is formatted properly.
:param set|dict patient_object: The values passed to the samples patient group
:param str patient_name: Optional name for the set
:raises ParameterE... | [
"def",
"_ensure_patient_group_is_ok",
"(",
"patient_object",
",",
"patient_name",
"=",
"None",
")",
":",
"from",
"protect",
".",
"addons",
".",
"common",
"import",
"TCGAToGTEx",
"assert",
"isinstance",
"(",
"patient_object",
",",
"(",
"set",
",",
"dict",
")",
... | Ensure that the provided entries for the patient groups is formatted properly.
:param set|dict patient_object: The values passed to the samples patient group
:param str patient_name: Optional name for the set
:raises ParameterError: If required entry doesnt exist | [
"Ensure",
"that",
"the",
"provided",
"entries",
"for",
"the",
"patient",
"groups",
"is",
"formatted",
"properly",
"."
] | python | train | 69.745455 |
onnx/onnxmltools | onnxmltools/convert/coreml/shape_calculators/neural_network/LSTM.py | https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/coreml/shape_calculators/neural_network/LSTM.py#L12-L43 | def calculate_lstm_output_shapes(operator):
'''
See LSTM's conversion function for its output shapes.
'''
check_input_and_output_numbers(operator, input_count_range=[1, 3], output_count_range=[1, 3])
check_input_and_output_types(operator, good_input_types=[FloatTensorType])
input_shape = operat... | [
"def",
"calculate_lstm_output_shapes",
"(",
"operator",
")",
":",
"check_input_and_output_numbers",
"(",
"operator",
",",
"input_count_range",
"=",
"[",
"1",
",",
"3",
"]",
",",
"output_count_range",
"=",
"[",
"1",
",",
"3",
"]",
")",
"check_input_and_output_types... | See LSTM's conversion function for its output shapes. | [
"See",
"LSTM",
"s",
"conversion",
"function",
"for",
"its",
"output",
"shapes",
"."
] | python | train | 44.1875 |
Parsl/parsl | parsl/dataflow/usage_tracking/usage.py | https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/dataflow/usage_tracking/usage.py#L156-L176 | def construct_start_message(self):
"""Collect preliminary run info at the start of the DFK.
Returns :
- Message dict dumped as json string, ready for UDP
"""
uname = getpass.getuser().encode('latin1')
hashed_username = hashlib.sha256(uname).hexdigest()[0:10]
... | [
"def",
"construct_start_message",
"(",
"self",
")",
":",
"uname",
"=",
"getpass",
".",
"getuser",
"(",
")",
".",
"encode",
"(",
"'latin1'",
")",
"hashed_username",
"=",
"hashlib",
".",
"sha256",
"(",
"uname",
")",
".",
"hexdigest",
"(",
")",
"[",
"0",
... | Collect preliminary run info at the start of the DFK.
Returns :
- Message dict dumped as json string, ready for UDP | [
"Collect",
"preliminary",
"run",
"info",
"at",
"the",
"start",
"of",
"the",
"DFK",
"."
] | python | valid | 40.666667 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L1199-L1206 | def get_output_files(self):
"""
Return list of output files for this DAG node and its job.
"""
output_files = list(self.__output_files)
if isinstance(self.job(), CondorDAGJob):
output_files = output_files + self.job().get_output_files()
return output_files | [
"def",
"get_output_files",
"(",
"self",
")",
":",
"output_files",
"=",
"list",
"(",
"self",
".",
"__output_files",
")",
"if",
"isinstance",
"(",
"self",
".",
"job",
"(",
")",
",",
"CondorDAGJob",
")",
":",
"output_files",
"=",
"output_files",
"+",
"self",
... | Return list of output files for this DAG node and its job. | [
"Return",
"list",
"of",
"output",
"files",
"for",
"this",
"DAG",
"node",
"and",
"its",
"job",
"."
] | python | train | 34.875 |
openid/python-openid | openid/yadis/accept.py | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/accept.py#L74-L119 | def matchTypes(accept_types, have_types):
"""Given the result of parsing an Accept: header, and the
available MIME types, return the acceptable types with their
quality markdowns.
For example:
>>> acceptable = parseAcceptHeader('text/html, text/plain; q=0.5')
>>> matchTypes(acceptable, ['text/... | [
"def",
"matchTypes",
"(",
"accept_types",
",",
"have_types",
")",
":",
"if",
"not",
"accept_types",
":",
"# Accept all of them",
"default",
"=",
"1",
"else",
":",
"default",
"=",
"0",
"match_main",
"=",
"{",
"}",
"match_sub",
"=",
"{",
"}",
"for",
"(",
"... | Given the result of parsing an Accept: header, and the
available MIME types, return the acceptable types with their
quality markdowns.
For example:
>>> acceptable = parseAcceptHeader('text/html, text/plain; q=0.5')
>>> matchTypes(acceptable, ['text/plain', 'text/html', 'image/jpeg'])
[('text/h... | [
"Given",
"the",
"result",
"of",
"parsing",
"an",
"Accept",
":",
"header",
"and",
"the",
"available",
"MIME",
"types",
"return",
"the",
"acceptable",
"types",
"with",
"their",
"quality",
"markdowns",
"."
] | python | train | 29.021739 |
textbook/aslack | aslack/slack_bot/bot.py | https://github.com/textbook/aslack/blob/9ac6a44e4464180109fa4be130ad7a980a9d1acc/aslack/slack_bot/bot.py#L231-L245 | def _respond(self, channel, text):
"""Respond to a message on the current socket.
Args:
channel (:py:class:`str`): The channel to send to.
text (:py:class:`str`): The message text to send.
"""
result = self._format_message(channel, text)
if result is not Non... | [
"def",
"_respond",
"(",
"self",
",",
"channel",
",",
"text",
")",
":",
"result",
"=",
"self",
".",
"_format_message",
"(",
"channel",
",",
"text",
")",
"if",
"result",
"is",
"not",
"None",
":",
"logger",
".",
"info",
"(",
"'Sending message: %r'",
",",
... | Respond to a message on the current socket.
Args:
channel (:py:class:`str`): The channel to send to.
text (:py:class:`str`): The message text to send. | [
"Respond",
"to",
"a",
"message",
"on",
"the",
"current",
"socket",
"."
] | python | valid | 31.266667 |
spyder-ide/spyder | spyder/plugins/editor/plugin.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/plugin.py#L2189-L2194 | def set_or_clear_breakpoint(self):
"""Set/Clear breakpoint"""
editorstack = self.get_current_editorstack()
if editorstack is not None:
self.switch_to_plugin()
editorstack.set_or_clear_breakpoint() | [
"def",
"set_or_clear_breakpoint",
"(",
"self",
")",
":",
"editorstack",
"=",
"self",
".",
"get_current_editorstack",
"(",
")",
"if",
"editorstack",
"is",
"not",
"None",
":",
"self",
".",
"switch_to_plugin",
"(",
")",
"editorstack",
".",
"set_or_clear_breakpoint",
... | Set/Clear breakpoint | [
"Set",
"/",
"Clear",
"breakpoint"
] | python | train | 40.666667 |
d11wtq/dockerpty | dockerpty/__init__.py | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/__init__.py#L20-L30 | def start(client, container, interactive=True, stdout=None, stderr=None, stdin=None, logs=None):
"""
Present the PTY of the container inside the current process.
This is just a wrapper for PseudoTerminal(client, container).start()
"""
operation = RunOperation(client, container, interactive=interac... | [
"def",
"start",
"(",
"client",
",",
"container",
",",
"interactive",
"=",
"True",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
",",
"stdin",
"=",
"None",
",",
"logs",
"=",
"None",
")",
":",
"operation",
"=",
"RunOperation",
"(",
"client",
... | Present the PTY of the container inside the current process.
This is just a wrapper for PseudoTerminal(client, container).start() | [
"Present",
"the",
"PTY",
"of",
"the",
"container",
"inside",
"the",
"current",
"process",
"."
] | python | train | 40.454545 |
pypa/pipenv | pipenv/patched/notpip/_vendor/pkg_resources/__init__.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/pkg_resources/__init__.py#L3045-L3048 | def ensure_directory(path):
"""Ensure that the parent directory of `path` exists"""
dirname = os.path.dirname(path)
py31compat.makedirs(dirname, exist_ok=True) | [
"def",
"ensure_directory",
"(",
"path",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"py31compat",
".",
"makedirs",
"(",
"dirname",
",",
"exist_ok",
"=",
"True",
")"
] | Ensure that the parent directory of `path` exists | [
"Ensure",
"that",
"the",
"parent",
"directory",
"of",
"path",
"exists"
] | python | train | 42 |
apache/incubator-heron | third_party/python/cpplint/cpplint.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L3995-L4139 | def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
"""Looks for redundant trailing semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any error... | [
"def",
"CheckTrailingSemicolon",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"# Block bodies should not be followed by a semicolon. Due to C++11",
"# brace initialization, ther... | Looks for redundant trailing semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | [
"Looks",
"for",
"redundant",
"trailing",
"semicolon",
"."
] | python | valid | 37.951724 |
thespacedoctor/tastic | tastic/tastic.py | https://github.com/thespacedoctor/tastic/blob/a0a16cf329a50057906ac3f696bb60b6fcee25e0/tastic/tastic.py#L970-L1003 | def del_tag(
self,
tag):
"""*delete a tag this taskpaper object*
**Key Arguments:**
- ``tag`` -- the tag to delete to the object
**Usage:**
.. code-block:: python
aTask.del_tag("@due")
"""
if tag.replace("@", "... | [
"def",
"del_tag",
"(",
"self",
",",
"tag",
")",
":",
"if",
"tag",
".",
"replace",
"(",
"\"@\"",
",",
"\"\"",
")",
"not",
"in",
"self",
".",
"tags",
":",
"return",
"self",
".",
"refresh",
"oldContent",
"=",
"self",
".",
"to_string",
"(",
"indentLevel"... | *delete a tag this taskpaper object*
**Key Arguments:**
- ``tag`` -- the tag to delete to the object
**Usage:**
.. code-block:: python
aTask.del_tag("@due") | [
"*",
"delete",
"a",
"tag",
"this",
"taskpaper",
"object",
"*"
] | python | train | 24.235294 |
KelSolaar/Umbra | umbra/components/factory/script_editor/models.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/script_editor/models.py#L1087-L1108 | def insert_pattern(self, pattern, index):
"""
Inserts given pattern into the Model.
:param pattern: Pattern.
:type pattern: unicode
:param index: Insertion index.
:type index: int
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> ... | [
"def",
"insert_pattern",
"(",
"self",
",",
"pattern",
",",
"index",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Inserting '{0}' at '{1}' index.\"",
".",
"format",
"(",
"pattern",
",",
"index",
")",
")",
"self",
".",
"remove_pattern",
"(",
"pattern",
")",
"se... | Inserts given pattern into the Model.
:param pattern: Pattern.
:type pattern: unicode
:param index: Insertion index.
:type index: int
:return: Method success.
:rtype: bool | [
"Inserts",
"given",
"pattern",
"into",
"the",
"Model",
"."
] | python | train | 30.818182 |
mozilla/socorrolib | socorrolib/lib/context_tools.py | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/context_tools.py#L13-L30 | def temp_file_context(raw_dump_path, logger=None):
"""this contextmanager implements conditionally deleting a pathname
at the end of a context if the pathname indicates that it is a temp
file by having the word 'TEMPORARY' embedded in it."""
try:
yield raw_dump_path
finally:
if 'TEMP... | [
"def",
"temp_file_context",
"(",
"raw_dump_path",
",",
"logger",
"=",
"None",
")",
":",
"try",
":",
"yield",
"raw_dump_path",
"finally",
":",
"if",
"'TEMPORARY'",
"in",
"raw_dump_path",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"raw_dump_path",
")",
"except... | this contextmanager implements conditionally deleting a pathname
at the end of a context if the pathname indicates that it is a temp
file by having the word 'TEMPORARY' embedded in it. | [
"this",
"contextmanager",
"implements",
"conditionally",
"deleting",
"a",
"pathname",
"at",
"the",
"end",
"of",
"a",
"context",
"if",
"the",
"pathname",
"indicates",
"that",
"it",
"is",
"a",
"temp",
"file",
"by",
"having",
"the",
"word",
"TEMPORARY",
"embedded... | python | train | 37.888889 |
boakley/robotframework-lint | rflint/parser/parser.py | https://github.com/boakley/robotframework-lint/blob/3e3578f4e39af9af9961aa0a715f146b74474091/rflint/parser/parser.py#L34-L55 | def RobotFactory(path, parent=None):
'''Return an instance of SuiteFile, ResourceFile, SuiteFolder
Exactly which is returned depends on whether it's a file or
folder, and if a file, the contents of the file. If there is a
testcase table, this will return an instance of SuiteFile,
otherwise it will ... | [
"def",
"RobotFactory",
"(",
"path",
",",
"parent",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"SuiteFolder",
"(",
"path",
",",
"parent",
")",
"else",
":",
"rf",
"=",
"RobotFile",
"(",
"path",
",",... | Return an instance of SuiteFile, ResourceFile, SuiteFolder
Exactly which is returned depends on whether it's a file or
folder, and if a file, the contents of the file. If there is a
testcase table, this will return an instance of SuiteFile,
otherwise it will return an instance of ResourceFile. | [
"Return",
"an",
"instance",
"of",
"SuiteFile",
"ResourceFile",
"SuiteFolder"
] | python | valid | 30.181818 |
amcat/nlpipe | nlpipe/modules/corenlp.py | https://github.com/amcat/nlpipe/blob/e9dcf0214d5dc6ba3900b8d7359909e1e33f1ce7/nlpipe/modules/corenlp.py#L55-L65 | def get_singleton(cls, annotators=None, **options):
"""
Get or create a corenlp parser with the given annotator and options
Note: multiple parsers with the same annotator and different options
are not supported.
"""
if annotators is not None:
annotators ... | [
"def",
"get_singleton",
"(",
"cls",
",",
"annotators",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"if",
"annotators",
"is",
"not",
"None",
":",
"annotators",
"=",
"tuple",
"(",
"annotators",
")",
"if",
"annotators",
"not",
"in",
"cls",
".",
"_sin... | Get or create a corenlp parser with the given annotator and options
Note: multiple parsers with the same annotator and different options
are not supported. | [
"Get",
"or",
"create",
"a",
"corenlp",
"parser",
"with",
"the",
"given",
"annotator",
"and",
"options",
"Note",
":",
"multiple",
"parsers",
"with",
"the",
"same",
"annotator",
"and",
"different",
"options",
"are",
"not",
"supported",
"."
] | python | train | 44.272727 |
elmotec/massedit | massedit.py | https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L310-L315 | def set_code_exprs(self, codes):
"""Convenience: sets all the code expressions at once."""
self.code_objs = dict()
self._codes = []
for code in codes:
self.append_code_expr(code) | [
"def",
"set_code_exprs",
"(",
"self",
",",
"codes",
")",
":",
"self",
".",
"code_objs",
"=",
"dict",
"(",
")",
"self",
".",
"_codes",
"=",
"[",
"]",
"for",
"code",
"in",
"codes",
":",
"self",
".",
"append_code_expr",
"(",
"code",
")"
] | Convenience: sets all the code expressions at once. | [
"Convenience",
":",
"sets",
"all",
"the",
"code",
"expressions",
"at",
"once",
"."
] | python | train | 36.166667 |
Azure/azure-cosmos-table-python | azure-cosmosdb-table/azure/cosmosdb/table/tableservice.py | https://github.com/Azure/azure-cosmos-table-python/blob/a7b618f6bddc465c9fdf899ea2971dfe4d04fcf0/azure-cosmosdb-table/azure/cosmosdb/table/tableservice.py#L742-L804 | def _query_entities(self, table_name, filter=None, select=None, max_results=None,
marker=None, accept=TablePayloadFormat.JSON_MINIMAL_METADATA,
property_resolver=None, timeout=None, _context=None):
'''
Returns a list of entities under the specified table. ... | [
"def",
"_query_entities",
"(",
"self",
",",
"table_name",
",",
"filter",
"=",
"None",
",",
"select",
"=",
"None",
",",
"max_results",
"=",
"None",
",",
"marker",
"=",
"None",
",",
"accept",
"=",
"TablePayloadFormat",
".",
"JSON_MINIMAL_METADATA",
",",
"prope... | Returns a list of entities under the specified table. Makes a single list
request to the service. Used internally by the query_entities method.
:param str table_name:
The name of the table to query.
:param str filter:
Returns only entities that satisfy the specified fil... | [
"Returns",
"a",
"list",
"of",
"entities",
"under",
"the",
"specified",
"table",
".",
"Makes",
"a",
"single",
"list",
"request",
"to",
"the",
"service",
".",
"Used",
"internally",
"by",
"the",
"query_entities",
"method",
"."
] | python | train | 54.269841 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/interactive.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/interactive.py#L1561-L1571 | def do_trace(self, arg):
"""
t - trace at the current assembly instruction
trace - trace at the current assembly instruction
"""
if arg: # XXX this check is to be removed
raise CmdError("too many arguments")
if self.lastEvent is None:
raise Cmd... | [
"def",
"do_trace",
"(",
"self",
",",
"arg",
")",
":",
"if",
"arg",
":",
"# XXX this check is to be removed",
"raise",
"CmdError",
"(",
"\"too many arguments\"",
")",
"if",
"self",
".",
"lastEvent",
"is",
"None",
":",
"raise",
"CmdError",
"(",
"\"no current threa... | t - trace at the current assembly instruction
trace - trace at the current assembly instruction | [
"t",
"-",
"trace",
"at",
"the",
"current",
"assembly",
"instruction",
"trace",
"-",
"trace",
"at",
"the",
"current",
"assembly",
"instruction"
] | python | train | 36.818182 |
apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L5313-L5317 | def parseExternalSubset(self, ExternalID, SystemID):
"""parse Markup declarations from an external subset [30]
extSubset ::= textDecl? extSubsetDecl [31] extSubsetDecl
::= (markupdecl | conditionalSect | PEReference | S) * """
libxml2mod.xmlParseExternalSubset(self._o, ExternalID,... | [
"def",
"parseExternalSubset",
"(",
"self",
",",
"ExternalID",
",",
"SystemID",
")",
":",
"libxml2mod",
".",
"xmlParseExternalSubset",
"(",
"self",
".",
"_o",
",",
"ExternalID",
",",
"SystemID",
")"
] | parse Markup declarations from an external subset [30]
extSubset ::= textDecl? extSubsetDecl [31] extSubsetDecl
::= (markupdecl | conditionalSect | PEReference | S) * | [
"parse",
"Markup",
"declarations",
"from",
"an",
"external",
"subset",
"[",
"30",
"]",
"extSubset",
"::",
"=",
"textDecl?",
"extSubsetDecl",
"[",
"31",
"]",
"extSubsetDecl",
"::",
"=",
"(",
"markupdecl",
"|",
"conditionalSect",
"|",
"PEReference",
"|",
"S",
... | python | train | 65.2 |
aboSamoor/polyglot | polyglot/base.py | https://github.com/aboSamoor/polyglot/blob/d0d2aa8d06cec4e03bd96618ae960030f7069a17/polyglot/base.py#L159-L166 | def read(self, size=None):
""" Read `size` of bytes."""
if size is None:
return self.buf.read() + self.open_file.read()
contents = self.buf.read(size)
if len(contents) < size:
contents += self.open_file.read(size - len(contents))
return contents | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"if",
"size",
"is",
"None",
":",
"return",
"self",
".",
"buf",
".",
"read",
"(",
")",
"+",
"self",
".",
"open_file",
".",
"read",
"(",
")",
"contents",
"=",
"self",
".",
"buf",
"."... | Read `size` of bytes. | [
"Read",
"size",
"of",
"bytes",
"."
] | python | train | 33.75 |
numenta/htmresearch | htmresearch/frameworks/thalamus/thalamus.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/thalamus/thalamus.py#L326-L343 | def _preSynapticTRNCells(self, i, j):
"""
Given a relay cell at the given coordinate, return a list of the (x,y)
coordinates of all TRN cells that project to it. This assumes a 3X3 fan-in.
:param i, j: relay cell Coordinates
:return:
"""
xmin = max(i - 1, 0)
xmax = min(i + 2, self.trnW... | [
"def",
"_preSynapticTRNCells",
"(",
"self",
",",
"i",
",",
"j",
")",
":",
"xmin",
"=",
"max",
"(",
"i",
"-",
"1",
",",
"0",
")",
"xmax",
"=",
"min",
"(",
"i",
"+",
"2",
",",
"self",
".",
"trnWidth",
")",
"ymin",
"=",
"max",
"(",
"j",
"-",
"... | Given a relay cell at the given coordinate, return a list of the (x,y)
coordinates of all TRN cells that project to it. This assumes a 3X3 fan-in.
:param i, j: relay cell Coordinates
:return: | [
"Given",
"a",
"relay",
"cell",
"at",
"the",
"given",
"coordinate",
"return",
"a",
"list",
"of",
"the",
"(",
"x",
"y",
")",
"coordinates",
"of",
"all",
"TRN",
"cells",
"that",
"project",
"to",
"it",
".",
"This",
"assumes",
"a",
"3X3",
"fan",
"-",
"in"... | python | train | 26.777778 |
suds-community/suds | suds/store.py | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/store.py#L548-L570 | def open(self, url):
"""
Open a document at the specified URL.
The document URL's needs not contain a protocol identifier, and if it
does, that protocol identifier is ignored when looking up the store
content.
Missing documents referenced using the internal 'suds' proto... | [
"def",
"open",
"(",
"self",
",",
"url",
")",
":",
"protocol",
",",
"location",
"=",
"self",
".",
"__split",
"(",
"url",
")",
"content",
"=",
"self",
".",
"__find",
"(",
"location",
")",
"if",
"protocol",
"==",
"'suds'",
"and",
"content",
"is",
"None"... | Open a document at the specified URL.
The document URL's needs not contain a protocol identifier, and if it
does, that protocol identifier is ignored when looking up the store
content.
Missing documents referenced using the internal 'suds' protocol are
reported by raising an ex... | [
"Open",
"a",
"document",
"at",
"the",
"specified",
"URL",
"."
] | python | train | 34.434783 |
lpantano/seqcluster | seqcluster/libs/report.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/report.py#L64-L71 | def _expand(dat, counts, start, end):
"""
expand the same counts from start to end
"""
for pos in range(start, end):
for s in counts:
dat[s][pos] += counts[s]
return dat | [
"def",
"_expand",
"(",
"dat",
",",
"counts",
",",
"start",
",",
"end",
")",
":",
"for",
"pos",
"in",
"range",
"(",
"start",
",",
"end",
")",
":",
"for",
"s",
"in",
"counts",
":",
"dat",
"[",
"s",
"]",
"[",
"pos",
"]",
"+=",
"counts",
"[",
"s"... | expand the same counts from start to end | [
"expand",
"the",
"same",
"counts",
"from",
"start",
"to",
"end"
] | python | train | 25.25 |
mbedmicro/pyOCD | pyocd/probe/pydapaccess/dap_access_cmsis_dap.py | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/probe/pydapaccess/dap_access_cmsis_dap.py#L1010-L1025 | def _abort_all_transfers(self, exception):
"""
Abort any ongoing transfers and clear all buffers
"""
pending_reads = len(self._commands_to_read)
# invalidate _transfer_list
for transfer in self._transfer_list:
transfer.add_error(exception)
# clear all ... | [
"def",
"_abort_all_transfers",
"(",
"self",
",",
"exception",
")",
":",
"pending_reads",
"=",
"len",
"(",
"self",
".",
"_commands_to_read",
")",
"# invalidate _transfer_list",
"for",
"transfer",
"in",
"self",
".",
"_transfer_list",
":",
"transfer",
".",
"add_error... | Abort any ongoing transfers and clear all buffers | [
"Abort",
"any",
"ongoing",
"transfers",
"and",
"clear",
"all",
"buffers"
] | python | train | 41.875 |
anthill/koala | koala/ast/__init__.py | https://github.com/anthill/koala/blob/393089fe081380506e73235db18a32b4e078d222/koala/ast/__init__.py#L271-L320 | def build_ast(expression, debug = False):
"""build an AST from an Excel formula expression in reverse polish notation"""
#use a directed graph to store the tree
G = DiGraph()
stack = []
for n in expression:
# Since the graph does not maintain the order of adding nodes/edges
# add a... | [
"def",
"build_ast",
"(",
"expression",
",",
"debug",
"=",
"False",
")",
":",
"#use a directed graph to store the tree",
"G",
"=",
"DiGraph",
"(",
")",
"stack",
"=",
"[",
"]",
"for",
"n",
"in",
"expression",
":",
"# Since the graph does not maintain the order of addi... | build an AST from an Excel formula expression in reverse polish notation | [
"build",
"an",
"AST",
"from",
"an",
"Excel",
"formula",
"expression",
"in",
"reverse",
"polish",
"notation"
] | python | train | 34.64 |
minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L703-L729 | def translate_url(context, language):
"""
Translates the current URL for the given language code, eg:
{% translate_url de %}
"""
try:
request = context["request"]
except KeyError:
return ""
view = resolve(request.path)
current_language = translation.get_language()
... | [
"def",
"translate_url",
"(",
"context",
",",
"language",
")",
":",
"try",
":",
"request",
"=",
"context",
"[",
"\"request\"",
"]",
"except",
"KeyError",
":",
"return",
"\"\"",
"view",
"=",
"resolve",
"(",
"request",
".",
"path",
")",
"current_language",
"=... | Translates the current URL for the given language code, eg:
{% translate_url de %} | [
"Translates",
"the",
"current",
"URL",
"for",
"the",
"given",
"language",
"code",
"eg",
":"
] | python | train | 35.777778 |
googleapis/google-cloud-python | bigtable/google/cloud/bigtable/row.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/row.py#L870-L918 | def commit(self):
"""Makes a ``ReadModifyWriteRow`` API request.
This commits modifications made by :meth:`append_cell_value` and
:meth:`increment_cell_value`. If no modifications were made, makes
no API request and just returns ``{}``.
Modifies a row atomically, reading the la... | [
"def",
"commit",
"(",
"self",
")",
":",
"num_mutations",
"=",
"len",
"(",
"self",
".",
"_rule_pb_list",
")",
"if",
"num_mutations",
"==",
"0",
":",
"return",
"{",
"}",
"if",
"num_mutations",
">",
"MAX_MUTATIONS",
":",
"raise",
"ValueError",
"(",
"\"%d tota... | Makes a ``ReadModifyWriteRow`` API request.
This commits modifications made by :meth:`append_cell_value` and
:meth:`increment_cell_value`. If no modifications were made, makes
no API request and just returns ``{}``.
Modifies a row atomically, reading the latest existing
timesta... | [
"Makes",
"a",
"ReadModifyWriteRow",
"API",
"request",
"."
] | python | train | 42.938776 |
ucsb-cs/submit | submit/models.py | https://github.com/ucsb-cs/submit/blob/92810c81255a4fc6bbebac1ac8aae856fd576ffe/submit/models.py#L613-L616 | def most_recent_submission(project, group):
"""Return the most recent submission for the user and project id."""
return (Submission.query_by(project=project, group=group)
.order_by(Submission.created_at.desc()).first()) | [
"def",
"most_recent_submission",
"(",
"project",
",",
"group",
")",
":",
"return",
"(",
"Submission",
".",
"query_by",
"(",
"project",
"=",
"project",
",",
"group",
"=",
"group",
")",
".",
"order_by",
"(",
"Submission",
".",
"created_at",
".",
"desc",
"(",... | Return the most recent submission for the user and project id. | [
"Return",
"the",
"most",
"recent",
"submission",
"for",
"the",
"user",
"and",
"project",
"id",
"."
] | python | train | 62 |
oscarbranson/latools | latools/D_obj.py | https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/D_obj.py#L409-L427 | def bkg_subtract(self, analyte, bkg, ind=None, focus_stage='despiked'):
"""
Subtract provided background from signal (focus stage).
Results is saved in new 'bkgsub' focus stage
Returns
-------
None
"""
if 'bkgsub' not in self.data.keys():
sel... | [
"def",
"bkg_subtract",
"(",
"self",
",",
"analyte",
",",
"bkg",
",",
"ind",
"=",
"None",
",",
"focus_stage",
"=",
"'despiked'",
")",
":",
"if",
"'bkgsub'",
"not",
"in",
"self",
".",
"data",
".",
"keys",
"(",
")",
":",
"self",
".",
"data",
"[",
"'bk... | Subtract provided background from signal (focus stage).
Results is saved in new 'bkgsub' focus stage
Returns
-------
None | [
"Subtract",
"provided",
"background",
"from",
"signal",
"(",
"focus",
"stage",
")",
"."
] | python | test | 26.631579 |
googleapis/google-cloud-python | logging/google/cloud/logging/_http.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_http.py#L287-L322 | def sink_update(
self, project, sink_name, filter_, destination, unique_writer_identity=False
):
"""API call: update a sink resource.
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/update
:type project: str
:param project: ID of the p... | [
"def",
"sink_update",
"(",
"self",
",",
"project",
",",
"sink_name",
",",
"filter_",
",",
"destination",
",",
"unique_writer_identity",
"=",
"False",
")",
":",
"target",
"=",
"\"/projects/%s/sinks/%s\"",
"%",
"(",
"project",
",",
"sink_name",
")",
"data",
"=",... | API call: update a sink resource.
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/update
:type project: str
:param project: ID of the project containing the sink.
:type sink_name: str
:param sink_name: the name of the sink
:type ... | [
"API",
"call",
":",
"update",
"a",
"sink",
"resource",
"."
] | python | train | 37.805556 |
IdentityPython/pyop | src/pyop/provider.py | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/provider.py#L116-L131 | def parse_authentication_request(self, request_body, http_headers=None):
# type: (str, Optional[Mapping[str, str]]) -> oic.oic.message.AuthorizationRequest
"""
Parses and verifies an authentication request.
:param request_body: urlencoded authentication request
:param http_heade... | [
"def",
"parse_authentication_request",
"(",
"self",
",",
"request_body",
",",
"http_headers",
"=",
"None",
")",
":",
"# type: (str, Optional[Mapping[str, str]]) -> oic.oic.message.AuthorizationRequest",
"auth_req",
"=",
"AuthorizationRequest",
"(",
")",
".",
"deserialize",
"(... | Parses and verifies an authentication request.
:param request_body: urlencoded authentication request
:param http_headers: http headers | [
"Parses",
"and",
"verifies",
"an",
"authentication",
"request",
"."
] | python | train | 37.0625 |
Yubico/python-pyhsm | pyhsm/tools/decrypt_aead.py | https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/decrypt_aead.py#L264-L277 | def walk_dir(path, args, state):
"""
Check all files in `path' to see if there is any requests that
we should send out on the bus.
"""
if args.debug:
sys.stderr.write("Walking %s\n" % path)
for root, _dirs, files in os.walk(path):
if not safe_process_files(root, files, args, sta... | [
"def",
"walk_dir",
"(",
"path",
",",
"args",
",",
"state",
")",
":",
"if",
"args",
".",
"debug",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"Walking %s\\n\"",
"%",
"path",
")",
"for",
"root",
",",
"_dirs",
",",
"files",
"in",
"os",
".",
"walk"... | Check all files in `path' to see if there is any requests that
we should send out on the bus. | [
"Check",
"all",
"files",
"in",
"path",
"to",
"see",
"if",
"there",
"is",
"any",
"requests",
"that",
"we",
"should",
"send",
"out",
"on",
"the",
"bus",
"."
] | python | train | 29.214286 |
mila-iqia/fuel | fuel/converters/ilsvrc2010.py | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/ilsvrc2010.py#L243-L280 | def train_set_producer(socket, train_archive, patch_archive, wnid_map):
"""Load/send images from the training set TAR file or patch images.
Parameters
----------
socket : :class:`zmq.Socket`
PUSH socket on which to send loaded images.
train_archive : str or file-like object
Filenam... | [
"def",
"train_set_producer",
"(",
"socket",
",",
"train_archive",
",",
"patch_archive",
",",
"wnid_map",
")",
":",
"patch_images",
"=",
"extract_patch_images",
"(",
"patch_archive",
",",
"'train'",
")",
"num_patched",
"=",
"0",
"with",
"tar_open",
"(",
"train_arch... | Load/send images from the training set TAR file or patch images.
Parameters
----------
socket : :class:`zmq.Socket`
PUSH socket on which to send loaded images.
train_archive : str or file-like object
Filename or file handle for the TAR archive of training images.
patch_archive : s... | [
"Load",
"/",
"send",
"images",
"from",
"the",
"training",
"set",
"TAR",
"file",
"or",
"patch",
"images",
"."
] | python | train | 47.315789 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.