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 |
|---|---|---|---|---|---|---|---|---|---|
exa-analytics/exa | exa/core/container.py | https://github.com/exa-analytics/exa/blob/40fb3c22b531d460dbc51e603de75b856cc28f0d/exa/core/container.py#L446-L457 | def _data(self, copy=False):
"""
Get data kwargs of the container (i.e. dataframe and series objects).
"""
data = {}
for key, obj in vars(self).items():
if isinstance(obj, (pd.Series, pd.DataFrame, pd.SparseSeries, pd.SparseDataFrame)):
if copy:
... | [
"def",
"_data",
"(",
"self",
",",
"copy",
"=",
"False",
")",
":",
"data",
"=",
"{",
"}",
"for",
"key",
",",
"obj",
"in",
"vars",
"(",
"self",
")",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"pd",
".",
"Series",
","... | Get data kwargs of the container (i.e. dataframe and series objects). | [
"Get",
"data",
"kwargs",
"of",
"the",
"container",
"(",
"i",
".",
"e",
".",
"dataframe",
"and",
"series",
"objects",
")",
"."
] | python | train | 36 |
bretth/woven | woven/linux.py | https://github.com/bretth/woven/blob/ec1da7b401a335f43129e7115fe7a4d145649f1e/woven/linux.py#L68-L88 | def change_ssh_port():
"""
For security woven changes the default ssh port.
"""
host = normalize(env.host_string)[1]
after = env.port
before = str(env.DEFAULT_SSH_PORT)
host_string=join_host_strings(env.user,host,before)
with settings(host_string=host_string, user=env.user):
... | [
"def",
"change_ssh_port",
"(",
")",
":",
"host",
"=",
"normalize",
"(",
"env",
".",
"host_string",
")",
"[",
"1",
"]",
"after",
"=",
"env",
".",
"port",
"before",
"=",
"str",
"(",
"env",
".",
"DEFAULT_SSH_PORT",
")",
"host_string",
"=",
"join_host_string... | For security woven changes the default ssh port. | [
"For",
"security",
"woven",
"changes",
"the",
"default",
"ssh",
"port",
"."
] | python | train | 29.52381 |
buildbot/buildbot | master/buildbot/steps/package/rpm/mock.py | https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/steps/package/rpm/mock.py#L87-L110 | def start(self):
"""
Try to remove the old mock logs first.
"""
if self.resultdir:
for lname in self.mock_logfiles:
self.logfiles[lname] = self.build.path_module.join(self.resultdir,
lname)
... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"resultdir",
":",
"for",
"lname",
"in",
"self",
".",
"mock_logfiles",
":",
"self",
".",
"logfiles",
"[",
"lname",
"]",
"=",
"self",
".",
"build",
".",
"path_module",
".",
"join",
"(",
"self",
... | Try to remove the old mock logs first. | [
"Try",
"to",
"remove",
"the",
"old",
"mock",
"logs",
"first",
"."
] | python | train | 39.458333 |
MSchnei/pyprf_feature | pyprf_feature/analysis/utils_general.py | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/utils_general.py#L556-L577 | def map_pol_to_crt(aryTht, aryRad):
"""Remap coordinates from polar to cartesian
Parameters
----------
aryTht : 1D numpy array
Angle of coordinates
aryRad : 1D numpy array
Radius of coordinates.
Returns
-------
aryXCrds : 1D numpy array
Array with x coordinate v... | [
"def",
"map_pol_to_crt",
"(",
"aryTht",
",",
"aryRad",
")",
":",
"aryXCrds",
"=",
"aryRad",
"*",
"np",
".",
"cos",
"(",
"aryTht",
")",
"aryYrds",
"=",
"aryRad",
"*",
"np",
".",
"sin",
"(",
"aryTht",
")",
"return",
"aryXCrds",
",",
"aryYrds"
] | Remap coordinates from polar to cartesian
Parameters
----------
aryTht : 1D numpy array
Angle of coordinates
aryRad : 1D numpy array
Radius of coordinates.
Returns
-------
aryXCrds : 1D numpy array
Array with x coordinate values.
aryYrds : 1D numpy array
... | [
"Remap",
"coordinates",
"from",
"polar",
"to",
"cartesian"
] | python | train | 22.272727 |
maas/python-libmaas | maas/client/viscera/nodes.py | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/nodes.py#L103-L111 | def as_device(self):
"""Convert to a `Device` object.
`node_type` must be `NodeType.DEVICE`.
"""
if self.node_type != NodeType.DEVICE:
raise ValueError(
'Cannot convert to `Device`, node_type is not a device.')
return self._origin.Device(self._data) | [
"def",
"as_device",
"(",
"self",
")",
":",
"if",
"self",
".",
"node_type",
"!=",
"NodeType",
".",
"DEVICE",
":",
"raise",
"ValueError",
"(",
"'Cannot convert to `Device`, node_type is not a device.'",
")",
"return",
"self",
".",
"_origin",
".",
"Device",
"(",
"s... | Convert to a `Device` object.
`node_type` must be `NodeType.DEVICE`. | [
"Convert",
"to",
"a",
"Device",
"object",
"."
] | python | train | 34.444444 |
nicolargo/glances | glances/password_list.py | https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/password_list.py#L58-L72 | def get_password(self, host=None):
"""
If host=None, return the current server list (dict).
Else, return the host's password (or the default one if defined or None)
"""
if host is None:
return self._password_dict
else:
try:
return s... | [
"def",
"get_password",
"(",
"self",
",",
"host",
"=",
"None",
")",
":",
"if",
"host",
"is",
"None",
":",
"return",
"self",
".",
"_password_dict",
"else",
":",
"try",
":",
"return",
"self",
".",
"_password_dict",
"[",
"host",
"]",
"except",
"(",
"KeyErr... | If host=None, return the current server list (dict).
Else, return the host's password (or the default one if defined or None) | [
"If",
"host",
"=",
"None",
"return",
"the",
"current",
"server",
"list",
"(",
"dict",
")",
".",
"Else",
"return",
"the",
"host",
"s",
"password",
"(",
"or",
"the",
"default",
"one",
"if",
"defined",
"or",
"None",
")"
] | python | train | 35.266667 |
pudo/dataset | dataset/table.py | https://github.com/pudo/dataset/blob/a008d120c7f3c48ccba98a282c0c67d6e719c0e5/dataset/table.py#L220-L256 | def _sync_table(self, columns):
"""Lazy load, create or adapt the table structure in the database."""
if self._table is None:
# Load an existing table from the database.
self._reflect_table()
if self._table is None:
# Create the table with an initial set of co... | [
"def",
"_sync_table",
"(",
"self",
",",
"columns",
")",
":",
"if",
"self",
".",
"_table",
"is",
"None",
":",
"# Load an existing table from the database.",
"self",
".",
"_reflect_table",
"(",
")",
"if",
"self",
".",
"_table",
"is",
"None",
":",
"# Create the t... | Lazy load, create or adapt the table structure in the database. | [
"Lazy",
"load",
"create",
"or",
"adapt",
"the",
"table",
"structure",
"in",
"the",
"database",
"."
] | python | train | 52.243243 |
cdumay/cdumay-rest-client | src/cdumay_rest_client/tracing.py | https://github.com/cdumay/cdumay-rest-client/blob/bca34d45748cb8227a7492af5ccfead3d8ab435d/src/cdumay_rest_client/tracing.py#L56-L66 | def extract_tags(cls, obj):
""" Extract tags from the given object
:param Any obj: Object to use as context
:return: Tags to add on span
:rtype: dict
"""
return dict(
[("request.{}".format(attr), obj.get(attr, None)) for attr in
cls.TAGS]
... | [
"def",
"extract_tags",
"(",
"cls",
",",
"obj",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"\"request.{}\"",
".",
"format",
"(",
"attr",
")",
",",
"obj",
".",
"get",
"(",
"attr",
",",
"None",
")",
")",
"for",
"attr",
"in",
"cls",
".",
"TAGS",
"]",... | Extract tags from the given object
:param Any obj: Object to use as context
:return: Tags to add on span
:rtype: dict | [
"Extract",
"tags",
"from",
"the",
"given",
"object"
] | python | train | 28.363636 |
wonambi-python/wonambi | wonambi/ioeeg/moberg.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/moberg.py#L28-L97 | def return_hdr(self):
"""Return the header for further use.
Returns
-------
subj_id : str
subject identification code
start_time : datetime
start time of the dataset
s_freq : float
sampling frequency
chan_name : list of str
... | [
"def",
"return_hdr",
"(",
"self",
")",
":",
"subj_id",
"=",
"str",
"(",
")",
"patient",
"=",
"parse",
"(",
"join",
"(",
"self",
".",
"filename",
",",
"'patient.info'",
")",
")",
"for",
"patientname",
"in",
"[",
"'PatientFirstName'",
",",
"'PatientLastName'... | Return the header for further use.
Returns
-------
subj_id : str
subject identification code
start_time : datetime
start time of the dataset
s_freq : float
sampling frequency
chan_name : list of str
list of all the channels... | [
"Return",
"the",
"header",
"for",
"further",
"use",
"."
] | python | train | 41.314286 |
google/budou | budou/nlapisegmenter.py | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/nlapisegmenter.py#L224-L253 | def _get_annotations(self, text, language=''):
"""Returns the list of annotations retrieved from the given text.
Args:
text (str): Input text.
language (:obj:`str`, optional): Language code.
Returns:
Results in a dictionary. :code:`tokens` contains the list of annotations
and :code... | [
"def",
"_get_annotations",
"(",
"self",
",",
"text",
",",
"language",
"=",
"''",
")",
":",
"body",
"=",
"{",
"'document'",
":",
"{",
"'type'",
":",
"'PLAIN_TEXT'",
",",
"'content'",
":",
"text",
",",
"}",
",",
"'features'",
":",
"{",
"'extract_syntax'",
... | Returns the list of annotations retrieved from the given text.
Args:
text (str): Input text.
language (:obj:`str`, optional): Language code.
Returns:
Results in a dictionary. :code:`tokens` contains the list of annotations
and :code:`language` contains the inferred language from the in... | [
"Returns",
"the",
"list",
"of",
"annotations",
"retrieved",
"from",
"the",
"given",
"text",
"."
] | python | train | 28.9 |
kodexlab/reliure | reliure/types.py | https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/types.py#L132-L137 | def serialize(self, value, **kwargs):
""" pre-serialize value """
if self._serialize is not None:
return self._serialize(value, **kwargs)
else:
return value | [
"def",
"serialize",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_serialize",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_serialize",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"va... | pre-serialize value | [
"pre",
"-",
"serialize",
"value"
] | python | train | 33.166667 |
HazyResearch/pdftotree | pdftotree/utils/pdf/vector_utils.py | https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/pdf/vector_utils.py#L128-L136 | def intersect(a, b):
"""
Check if two rectangles intersect
"""
if a[x0] == a[x1] or a[y0] == a[y1]:
return False
if b[x0] == b[x1] or b[y0] == b[y1]:
return False
return a[x0] <= b[x1] and b[x0] <= a[x1] and a[y0] <= b[y1] and b[y0] <= a[y1] | [
"def",
"intersect",
"(",
"a",
",",
"b",
")",
":",
"if",
"a",
"[",
"x0",
"]",
"==",
"a",
"[",
"x1",
"]",
"or",
"a",
"[",
"y0",
"]",
"==",
"a",
"[",
"y1",
"]",
":",
"return",
"False",
"if",
"b",
"[",
"x0",
"]",
"==",
"b",
"[",
"x1",
"]",
... | Check if two rectangles intersect | [
"Check",
"if",
"two",
"rectangles",
"intersect"
] | python | train | 30.333333 |
google-research/batch-ppo | agents/algorithms/ppo/utility.py | https://github.com/google-research/batch-ppo/blob/3d09705977bae4e7c3eb20339a3b384d2a5531e4/agents/algorithms/ppo/utility.py#L160-L189 | def variable_summaries(vars_, groups=None, scope='weights'):
"""Create histogram summaries for the provided variables.
Summaries can be grouped via regexes matching variables names.
Args:
vars_: List of variables to summarize.
groups: Mapping of name to regex for grouping summaries.
scope: Name scop... | [
"def",
"variable_summaries",
"(",
"vars_",
",",
"groups",
"=",
"None",
",",
"scope",
"=",
"'weights'",
")",
":",
"groups",
"=",
"groups",
"or",
"{",
"r'all'",
":",
"r'.*'",
"}",
"grouped",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
... | Create histogram summaries for the provided variables.
Summaries can be grouped via regexes matching variables names.
Args:
vars_: List of variables to summarize.
groups: Mapping of name to regex for grouping summaries.
scope: Name scope for this operation.
Returns:
Summary tensor. | [
"Create",
"histogram",
"summaries",
"for",
"the",
"provided",
"variables",
"."
] | python | train | 34.266667 |
saltstack/salt | salt/modules/freebsdports.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdports.py#L480-L512 | def search(name):
'''
Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Tak... | [
"def",
"search",
"(",
"name",
")",
":",
"name",
"=",
"six",
".",
"text_type",
"(",
"name",
")",
"all_ports",
"=",
"list_all",
"(",
")",
"if",
"'/'",
"in",
"name",
":",
"if",
"name",
".",
"count",
"(",
"'/'",
")",
">",
"1",
":",
"raise",
"SaltInvo... | Search for matches in the ports tree. Globs are supported, and the category
is optional
CLI Examples:
.. code-block:: bash
salt '*' ports.search 'security/*'
salt '*' ports.search 'security/n*'
salt '*' ports.search nmap
.. warning::
Takes a while to run | [
"Search",
"for",
"matches",
"in",
"the",
"ports",
"tree",
".",
"Globs",
"are",
"supported",
"and",
"the",
"category",
"is",
"optional"
] | python | train | 24.909091 |
rosenbrockc/fortpy | fortpy/scripts/analyze.py | https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/scripts/analyze.py#L1602-L1609 | def do_cd(self, arg):
"""Imitates the bash shell 'cd' command."""
from os import chdir, path
fullpath = path.abspath(path.expanduser(arg))
if path.isdir(fullpath):
chdir(fullpath)
else:
msg.err("'{}' is not a valid directory.".format(arg)) | [
"def",
"do_cd",
"(",
"self",
",",
"arg",
")",
":",
"from",
"os",
"import",
"chdir",
",",
"path",
"fullpath",
"=",
"path",
".",
"abspath",
"(",
"path",
".",
"expanduser",
"(",
"arg",
")",
")",
"if",
"path",
".",
"isdir",
"(",
"fullpath",
")",
":",
... | Imitates the bash shell 'cd' command. | [
"Imitates",
"the",
"bash",
"shell",
"cd",
"command",
"."
] | python | train | 37 |
dopefishh/pympi | pympi/Praat.py | https://github.com/dopefishh/pympi/blob/79c747cde45b5ba203ed93154d8c123ac9c3ef56/pympi/Praat.py#L414-L430 | def get_all_intervals(self):
"""Returns the true list of intervals including the empty intervals."""
ints = sorted(self.get_intervals(True))
if self.tier_type == 'IntervalTier':
if not ints:
ints.append((self.xmin, self.xmax, ''))
else:
if ... | [
"def",
"get_all_intervals",
"(",
"self",
")",
":",
"ints",
"=",
"sorted",
"(",
"self",
".",
"get_intervals",
"(",
"True",
")",
")",
"if",
"self",
".",
"tier_type",
"==",
"'IntervalTier'",
":",
"if",
"not",
"ints",
":",
"ints",
".",
"append",
"(",
"(",
... | Returns the true list of intervals including the empty intervals. | [
"Returns",
"the",
"true",
"list",
"of",
"intervals",
"including",
"the",
"empty",
"intervals",
"."
] | python | test | 43.941176 |
DarkEnergySurvey/ugali | ugali/observation/mask.py | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/mask.py#L651-L684 | def restrictCatalogToObservableSpaceMMD(self, catalog):
"""
Retain only the catalog objects which fall within the observable (i.e., unmasked) space.
Parameters:
catalog: a Catalog object
Returns:
sel : boolean selection array where True means the object would be obser... | [
"def",
"restrictCatalogToObservableSpaceMMD",
"(",
"self",
",",
"catalog",
")",
":",
"# ADW: This creates a slope in color-magnitude space near the magnitude limit",
"# i.e., if color=g-r then you can't have an object with g-r=1 and mag_r > mask_r-1",
"# Depending on which is the detection band,... | Retain only the catalog objects which fall within the observable (i.e., unmasked) space.
Parameters:
catalog: a Catalog object
Returns:
sel : boolean selection array where True means the object would be observable (i.e., unmasked).
ADW: Careful, this function is fragile! The... | [
"Retain",
"only",
"the",
"catalog",
"objects",
"which",
"fall",
"within",
"the",
"observable",
"(",
"i",
".",
"e",
".",
"unmasked",
")",
"space",
"."
] | python | train | 53.176471 |
artefactual-labs/mets-reader-writer | metsrw/utils.py | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/utils.py#L45-L52 | def _urlendecode(url, func):
"""Encode or decode ``url`` by applying ``func`` to all of its
URL-encodable parts.
"""
parsed = urlparse(url)
for attr in URL_ENCODABLE_PARTS:
parsed = parsed._replace(**{attr: func(getattr(parsed, attr))})
return urlunparse(parsed) | [
"def",
"_urlendecode",
"(",
"url",
",",
"func",
")",
":",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"for",
"attr",
"in",
"URL_ENCODABLE_PARTS",
":",
"parsed",
"=",
"parsed",
".",
"_replace",
"(",
"*",
"*",
"{",
"attr",
":",
"func",
"(",
"getattr",
... | Encode or decode ``url`` by applying ``func`` to all of its
URL-encodable parts. | [
"Encode",
"or",
"decode",
"url",
"by",
"applying",
"func",
"to",
"all",
"of",
"its",
"URL",
"-",
"encodable",
"parts",
"."
] | python | train | 35.875 |
Erotemic/utool | utool/util_time.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_time.py#L840-L885 | def get_timedelta_str(timedelta, exclude_zeros=False):
"""
get_timedelta_str
Returns:
str: timedelta_str, formated time string
References:
http://stackoverflow.com/questions/8906926/formatting-python-timedelta-objects
Example:
>>> # ENABLE_DOCTEST
>>> from utool.ut... | [
"def",
"get_timedelta_str",
"(",
"timedelta",
",",
"exclude_zeros",
"=",
"False",
")",
":",
"if",
"timedelta",
"==",
"datetime",
".",
"timedelta",
"(",
"0",
")",
":",
"return",
"'0 seconds'",
"days",
"=",
"timedelta",
".",
"days",
"hours",
",",
"rem",
"=",... | get_timedelta_str
Returns:
str: timedelta_str, formated time string
References:
http://stackoverflow.com/questions/8906926/formatting-python-timedelta-objects
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_time import * # NOQA
>>> timedelta = get_unix_timedelta... | [
"get_timedelta_str"
] | python | train | 31.043478 |
not-na/peng3d | peng3d/gui/menus.py | https://github.com/not-na/peng3d/blob/1151be665b26cc8a479f6307086ba919e4d32d85/peng3d/gui/menus.py#L132-L149 | def add_widgets(self,**kwargs):
"""
Called by the initializer to add all widgets.
Widgets are discovered by searching through the :py:attr:`WIDGETS` class attribute.
If a key in :py:attr:`WIDGETS` is also found in the keyword arguments and
not none, the function with the... | [
"def",
"add_widgets",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"name",
",",
"fname",
"in",
"self",
".",
"WIDGETS",
".",
"items",
"(",
")",
":",
"if",
"name",
"in",
"kwargs",
"and",
"kwargs",
"[",
"name",
"]",
"is",
"not",
"None",
":... | Called by the initializer to add all widgets.
Widgets are discovered by searching through the :py:attr:`WIDGETS` class attribute.
If a key in :py:attr:`WIDGETS` is also found in the keyword arguments and
not none, the function with the name given in the value of the key will
be ... | [
"Called",
"by",
"the",
"initializer",
"to",
"add",
"all",
"widgets",
".",
"Widgets",
"are",
"discovered",
"by",
"searching",
"through",
"the",
":",
"py",
":",
"attr",
":",
"WIDGETS",
"class",
"attribute",
".",
"If",
"a",
"key",
"in",
":",
"py",
":",
"a... | python | test | 51.5 |
quantmind/pulsar | pulsar/async/actor.py | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/actor.py#L395-L425 | def info(self):
'''Return a nested dictionary of information related to the actor
status and performance. The dictionary contains the following entries:
* ``actor`` a dictionary containing information regarding the type of
actor and its status.
* ``events`` a dictionary of inf... | [
"def",
"info",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"started",
"(",
")",
":",
"return",
"isp",
"=",
"self",
".",
"is_process",
"(",
")",
"actor",
"=",
"{",
"'name'",
":",
"self",
".",
"name",
",",
"'state'",
":",
"self",
".",
"info_st... | Return a nested dictionary of information related to the actor
status and performance. The dictionary contains the following entries:
* ``actor`` a dictionary containing information regarding the type of
actor and its status.
* ``events`` a dictionary of information about the
... | [
"Return",
"a",
"nested",
"dictionary",
"of",
"information",
"related",
"to",
"the",
"actor",
"status",
"and",
"performance",
".",
"The",
"dictionary",
"contains",
"the",
"following",
"entries",
":"
] | python | train | 40.483871 |
TrafficSenseMSD/SumoTools | sumolib/net/lane.py | https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/sumolib/net/lane.py#L70-L78 | def addJunctionPos(shape, fromPos, toPos):
"""Extends shape with the given positions in case they differ from the
existing endpoints. assumes that shape and positions have the same dimensionality"""
result = list(shape)
if fromPos != shape[0]:
result = [fromPos] + result
if toPos != shape[-1... | [
"def",
"addJunctionPos",
"(",
"shape",
",",
"fromPos",
",",
"toPos",
")",
":",
"result",
"=",
"list",
"(",
"shape",
")",
"if",
"fromPos",
"!=",
"shape",
"[",
"0",
"]",
":",
"result",
"=",
"[",
"fromPos",
"]",
"+",
"result",
"if",
"toPos",
"!=",
"sh... | Extends shape with the given positions in case they differ from the
existing endpoints. assumes that shape and positions have the same dimensionality | [
"Extends",
"shape",
"with",
"the",
"given",
"positions",
"in",
"case",
"they",
"differ",
"from",
"the",
"existing",
"endpoints",
".",
"assumes",
"that",
"shape",
"and",
"positions",
"have",
"the",
"same",
"dimensionality"
] | python | train | 40.111111 |
secdev/scapy | scapy/layers/inet.py | https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/layers/inet.py#L1643-L1666 | def traceroute(target, dport=80, minttl=1, maxttl=30, sport=RandShort(), l4=None, filter=None, timeout=2, verbose=None, **kargs): # noqa: E501
"""Instant TCP traceroute
traceroute(target, [maxttl=30,] [dport=80,] [sport=80,] [verbose=conf.verb]) -> None # noqa: E501
"""
if verbose is None:
verbose = c... | [
"def",
"traceroute",
"(",
"target",
",",
"dport",
"=",
"80",
",",
"minttl",
"=",
"1",
",",
"maxttl",
"=",
"30",
",",
"sport",
"=",
"RandShort",
"(",
")",
",",
"l4",
"=",
"None",
",",
"filter",
"=",
"None",
",",
"timeout",
"=",
"2",
",",
"verbose"... | Instant TCP traceroute
traceroute(target, [maxttl=30,] [dport=80,] [sport=80,] [verbose=conf.verb]) -> None # noqa: E501 | [
"Instant",
"TCP",
"traceroute",
"traceroute",
"(",
"target",
"[",
"maxttl",
"=",
"30",
"]",
"[",
"dport",
"=",
"80",
"]",
"[",
"sport",
"=",
"80",
"]",
"[",
"verbose",
"=",
"conf",
".",
"verb",
"]",
")",
"-",
">",
"None",
"#",
"noqa",
":",
"E501"... | python | train | 48.25 |
saltstack/salt | salt/modules/win_dacl.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dacl.py#L208-L217 | def getSecurityHkey(self, s):
'''
returns the necessary string value for an HKEY for the win32security module
'''
try:
return self.hkeys_security[s]
except KeyError:
raise CommandExecutionError((
'No HKEY named "{0}". It should be one of t... | [
"def",
"getSecurityHkey",
"(",
"self",
",",
"s",
")",
":",
"try",
":",
"return",
"self",
".",
"hkeys_security",
"[",
"s",
"]",
"except",
"KeyError",
":",
"raise",
"CommandExecutionError",
"(",
"(",
"'No HKEY named \"{0}\". It should be one of the following: {1}'",
... | returns the necessary string value for an HKEY for the win32security module | [
"returns",
"the",
"necessary",
"string",
"value",
"for",
"an",
"HKEY",
"for",
"the",
"win32security",
"module"
] | python | train | 39.1 |
jssimporter/python-jss | jss/tools.py | https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/tools.py#L81-L89 | def error_handler(exception_cls, response):
"""Handle HTTP errors by formatting into strings."""
# Responses are sent as html. Split on the newlines and give us
# the <p> text back.
error = convert_response_to_text(response)
exception = exception_cls("Response Code: %s\tResponse: %s" %
... | [
"def",
"error_handler",
"(",
"exception_cls",
",",
"response",
")",
":",
"# Responses are sent as html. Split on the newlines and give us",
"# the <p> text back.",
"error",
"=",
"convert_response_to_text",
"(",
"response",
")",
"exception",
"=",
"exception_cls",
"(",
"\"Respo... | Handle HTTP errors by formatting into strings. | [
"Handle",
"HTTP",
"errors",
"by",
"formatting",
"into",
"strings",
"."
] | python | train | 47.555556 |
etal/biofrills | biofrills/alnutils.py | https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/alnutils.py#L218-L231 | def to_graph(alnfname, weight_func):
"""Create a NetworkX graph from a sequence alignment.
Nodes are string sequence IDs; edge weights are the output of weight_func
between each pair, by default the absolute identity (# identical chars).
"""
import networkx
G = networkx.Graph()
aln = AlignI... | [
"def",
"to_graph",
"(",
"alnfname",
",",
"weight_func",
")",
":",
"import",
"networkx",
"G",
"=",
"networkx",
".",
"Graph",
"(",
")",
"aln",
"=",
"AlignIO",
".",
"read",
"(",
"alnfname",
",",
"'fasta'",
")",
"for",
"i",
",",
"arec",
"in",
"enumerate",
... | Create a NetworkX graph from a sequence alignment.
Nodes are string sequence IDs; edge weights are the output of weight_func
between each pair, by default the absolute identity (# identical chars). | [
"Create",
"a",
"NetworkX",
"graph",
"from",
"a",
"sequence",
"alignment",
"."
] | python | train | 37.714286 |
DistilledLtd/heimdall | heimdall/heimdall.py | https://github.com/DistilledLtd/heimdall/blob/7568c915a2e5bce759750d5456b39ea3498a6683/heimdall/heimdall.py#L46-L88 | def screenshot(url, *args, **kwargs):
""" Call PhantomJS with the specified flags and options. """
phantomscript = os.path.join(os.path.dirname(__file__),
'take_screenshot.js')
directory = kwargs.get('save_dir', '/tmp')
image_name = kwargs.get('image_name', None) or _i... | [
"def",
"screenshot",
"(",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"phantomscript",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'take_screenshot.js'",
")",
"directory",
"... | Call PhantomJS with the specified flags and options. | [
"Call",
"PhantomJS",
"with",
"the",
"specified",
"flags",
"and",
"options",
"."
] | python | valid | 27.883721 |
tobami/littlechef | littlechef/runner.py | https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L92-L99 | def nodes_with_role(rolename):
"""Configures a list of nodes that have the given role in their run list"""
nodes = [n['name'] for n in
lib.get_nodes_with_role(rolename, env.chef_environment)]
if not len(nodes):
print("No nodes found with role '{0}'".format(rolename))
sys.exit(0)... | [
"def",
"nodes_with_role",
"(",
"rolename",
")",
":",
"nodes",
"=",
"[",
"n",
"[",
"'name'",
"]",
"for",
"n",
"in",
"lib",
".",
"get_nodes_with_role",
"(",
"rolename",
",",
"env",
".",
"chef_environment",
")",
"]",
"if",
"not",
"len",
"(",
"nodes",
")",... | Configures a list of nodes that have the given role in their run list | [
"Configures",
"a",
"list",
"of",
"nodes",
"that",
"have",
"the",
"given",
"role",
"in",
"their",
"run",
"list"
] | python | train | 42.125 |
saltstack/salt | salt/modules/snapper.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/snapper.py#L99-L138 | def _snapshot_to_data(snapshot):
'''
Returns snapshot data from a D-Bus response.
A snapshot D-Bus response is a dbus.Struct containing the
information related to a snapshot:
[id, type, pre_snapshot, timestamp, user, description,
cleanup_algorithm, userdata]
id: dbus.UInt32
type: dbu... | [
"def",
"_snapshot_to_data",
"(",
"snapshot",
")",
":",
"data",
"=",
"{",
"}",
"data",
"[",
"'id'",
"]",
"=",
"snapshot",
"[",
"0",
"]",
"data",
"[",
"'type'",
"]",
"=",
"[",
"'single'",
",",
"'pre'",
",",
"'post'",
"]",
"[",
"snapshot",
"[",
"1",
... | Returns snapshot data from a D-Bus response.
A snapshot D-Bus response is a dbus.Struct containing the
information related to a snapshot:
[id, type, pre_snapshot, timestamp, user, description,
cleanup_algorithm, userdata]
id: dbus.UInt32
type: dbus.UInt16
pre_snapshot: dbus.UInt32
ti... | [
"Returns",
"snapshot",
"data",
"from",
"a",
"D",
"-",
"Bus",
"response",
"."
] | python | train | 24.975 |
vanheeringen-lab/gimmemotifs | gimmemotifs/genome_index.py | https://github.com/vanheeringen-lab/gimmemotifs/blob/1dc0572179e5d0c8f96958060133c1f8d92c6675/gimmemotifs/genome_index.py#L299-L398 | def create_index(self,fasta_dir=None, index_dir=None):
"""Index all fasta-files in fasta_dir (one sequence per file!) and
store the results in index_dir"""
# Use default directories if they are not supplied
if not fasta_dir:
fasta_dir = self.fasta_dir
if not... | [
"def",
"create_index",
"(",
"self",
",",
"fasta_dir",
"=",
"None",
",",
"index_dir",
"=",
"None",
")",
":",
"# Use default directories if they are not supplied",
"if",
"not",
"fasta_dir",
":",
"fasta_dir",
"=",
"self",
".",
"fasta_dir",
"if",
"not",
"index_dir",
... | Index all fasta-files in fasta_dir (one sequence per file!) and
store the results in index_dir | [
"Index",
"all",
"fasta",
"-",
"files",
"in",
"fasta_dir",
"(",
"one",
"sequence",
"per",
"file!",
")",
"and",
"store",
"the",
"results",
"in",
"index_dir"
] | python | train | 35.17 |
jason-weirather/py-seq-tools | seqtools/range/__init__.py | https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/range/__init__.py#L311-L331 | def cmp(self,range2,overlap_size=0):
"""the comparitor for ranges
* return 1 if greater than range2
* return -1 if less than range2
* return 0 if overlapped
:param range2:
:param overlap_size: allow some padding for an 'equal' comparison (default 0)
:type range2: GenomicRange
:type ... | [
"def",
"cmp",
"(",
"self",
",",
"range2",
",",
"overlap_size",
"=",
"0",
")",
":",
"if",
"self",
".",
"overlaps",
"(",
"range2",
",",
"padding",
"=",
"overlap_size",
")",
":",
"return",
"0",
"if",
"self",
".",
"chr",
"<",
"range2",
".",
"chr",
":",... | the comparitor for ranges
* return 1 if greater than range2
* return -1 if less than range2
* return 0 if overlapped
:param range2:
:param overlap_size: allow some padding for an 'equal' comparison (default 0)
:type range2: GenomicRange
:type overlap_size: int | [
"the",
"comparitor",
"for",
"ranges"
] | python | train | 30.666667 |
idmillington/layout | layout/datatypes/position.py | https://github.com/idmillington/layout/blob/c452d1d7a74c9a74f7639c1b49e2a41c4e354bb5/layout/datatypes/position.py#L66-L71 | def get_rotated(self, angle):
"""Rotates this vector through the given anti-clockwise angle
in radians."""
ca = math.cos(angle)
sa = math.sin(angle)
return Point(self.x*ca-self.y*sa, self.x*sa+self.y*ca) | [
"def",
"get_rotated",
"(",
"self",
",",
"angle",
")",
":",
"ca",
"=",
"math",
".",
"cos",
"(",
"angle",
")",
"sa",
"=",
"math",
".",
"sin",
"(",
"angle",
")",
"return",
"Point",
"(",
"self",
".",
"x",
"*",
"ca",
"-",
"self",
".",
"y",
"*",
"s... | Rotates this vector through the given anti-clockwise angle
in radians. | [
"Rotates",
"this",
"vector",
"through",
"the",
"given",
"anti",
"-",
"clockwise",
"angle",
"in",
"radians",
"."
] | python | train | 39.666667 |
sgaynetdinov/py-vkontakte | vk/users.py | https://github.com/sgaynetdinov/py-vkontakte/blob/c09654f89008b5847418bb66f1f9c408cd7aa128/vk/users.py#L182-L187 | def get_followers(self):
"""
https://vk.com/dev/users.getFollowers
"""
response = self._session.fetch_items("users.getFollowers", self.from_json, self._session, count=1000, user_id=self.id, fields=self.USER_FIELDS)
return response | [
"def",
"get_followers",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_session",
".",
"fetch_items",
"(",
"\"users.getFollowers\"",
",",
"self",
".",
"from_json",
",",
"self",
".",
"_session",
",",
"count",
"=",
"1000",
",",
"user_id",
"=",
"self",... | https://vk.com/dev/users.getFollowers | [
"https",
":",
"//",
"vk",
".",
"com",
"/",
"dev",
"/",
"users",
".",
"getFollowers"
] | python | train | 44.333333 |
Esri/ArcREST | src/arcrest/manageags/administration.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageags/administration.py#L428-L440 | def logs(self):
"""returns an object to work with the site logs"""
if self._resources is None:
self.__init()
if "logs" in self._resources:
url = self._url + "/logs"
return _logs.Log(url=url,
securityHandler=self._securityHandler,
... | [
"def",
"logs",
"(",
"self",
")",
":",
"if",
"self",
".",
"_resources",
"is",
"None",
":",
"self",
".",
"__init",
"(",
")",
"if",
"\"logs\"",
"in",
"self",
".",
"_resources",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/logs\"",
"return",
"_logs",
... | returns an object to work with the site logs | [
"returns",
"an",
"object",
"to",
"work",
"with",
"the",
"site",
"logs"
] | python | train | 38.769231 |
pypa/pipenv | pipenv/vendor/requests/utils.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/requests/utils.py#L889-L903 | def prepend_scheme_if_needed(url, new_scheme):
"""Given a URL that may or may not have a scheme, prepend the given scheme.
Does not replace a present scheme with the one provided as an argument.
:rtype: str
"""
scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)
# urlpars... | [
"def",
"prepend_scheme_if_needed",
"(",
"url",
",",
"new_scheme",
")",
":",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
"=",
"urlparse",
"(",
"url",
",",
"new_scheme",
")",
"# urlparse is a finicky beast, and sometimes decid... | Given a URL that may or may not have a scheme, prepend the given scheme.
Does not replace a present scheme with the one provided as an argument.
:rtype: str | [
"Given",
"a",
"URL",
"that",
"may",
"or",
"may",
"not",
"have",
"a",
"scheme",
"prepend",
"the",
"given",
"scheme",
".",
"Does",
"not",
"replace",
"a",
"present",
"scheme",
"with",
"the",
"one",
"provided",
"as",
"an",
"argument",
"."
] | python | train | 41.933333 |
theiviaxx/Frog | frog/views/comment.py | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/views/comment.py#L49-L55 | def index(request, obj_id):
"""Handles a request based on method and calls the appropriate function"""
if request.method == 'GET':
return get(request, obj_id)
elif request.method == 'PUT':
getPutData(request)
return put(request, obj_id) | [
"def",
"index",
"(",
"request",
",",
"obj_id",
")",
":",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"return",
"get",
"(",
"request",
",",
"obj_id",
")",
"elif",
"request",
".",
"method",
"==",
"'PUT'",
":",
"getPutData",
"(",
"request",
")",
... | Handles a request based on method and calls the appropriate function | [
"Handles",
"a",
"request",
"based",
"on",
"method",
"and",
"calls",
"the",
"appropriate",
"function"
] | python | train | 38 |
ibelie/typy | typy/google/protobuf/text_format.py | https://github.com/ibelie/typy/blob/3616845fb91459aacd8df6bf82c5d91f4542bee7/typy/google/protobuf/text_format.py#L348-L369 | def Merge(text, message, allow_unknown_extension=False,
allow_field_number=False):
"""Parses an text representation of a protocol message into a message.
Like Parse(), but allows repeated values for a non-repeated field, and uses
the last one.
Args:
text: Message text representation.
message... | [
"def",
"Merge",
"(",
"text",
",",
"message",
",",
"allow_unknown_extension",
"=",
"False",
",",
"allow_field_number",
"=",
"False",
")",
":",
"return",
"MergeLines",
"(",
"text",
".",
"split",
"(",
"'\\n'",
")",
",",
"message",
",",
"allow_unknown_extension",
... | Parses an text representation of a protocol message into a message.
Like Parse(), but allows repeated values for a non-repeated field, and uses
the last one.
Args:
text: Message text representation.
message: A protocol buffer message to merge into.
allow_unknown_extension: if True, skip over missing... | [
"Parses",
"an",
"text",
"representation",
"of",
"a",
"protocol",
"message",
"into",
"a",
"message",
"."
] | python | valid | 33.363636 |
ANTsX/ANTsPy | ants/registration/reorient_image.py | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/reorient_image.py#L171-L200 | def get_center_of_mass(image):
"""
Compute an image center of mass in physical space which is defined
as the mean of the intensity weighted voxel coordinate system.
ANTsR function: `getCenterOfMass`
Arguments
---------
image : ANTsImage
image from which center of mass will be ... | [
"def",
"get_center_of_mass",
"(",
"image",
")",
":",
"if",
"image",
".",
"pixeltype",
"!=",
"'float'",
":",
"image",
"=",
"image",
".",
"clone",
"(",
"'float'",
")",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'centerOfMass%s'",
"%",
"image",
".",
"_... | Compute an image center of mass in physical space which is defined
as the mean of the intensity weighted voxel coordinate system.
ANTsR function: `getCenterOfMass`
Arguments
---------
image : ANTsImage
image from which center of mass will be computed
Returns
-------
scala... | [
"Compute",
"an",
"image",
"center",
"of",
"mass",
"in",
"physical",
"space",
"which",
"is",
"defined",
"as",
"the",
"mean",
"of",
"the",
"intensity",
"weighted",
"voxel",
"coordinate",
"system",
"."
] | python | train | 25.5 |
philgyford/django-spectator | spectator/events/migrations/0039_populate_exhibitions.py | https://github.com/philgyford/django-spectator/blob/f3c72004f9caa1fde0f5a3b2f0d2bf285fc01ada/spectator/events/migrations/0039_populate_exhibitions.py#L27-L70 | def forwards(apps, schema_editor):
"""
Having added the new 'exhibition' Work type, we're going to assume that
every Event of type 'museum' should actually have one Exhibition attached.
So, we'll add one, with the same title as the Event.
And we'll move all Creators from the Event to the Exhibition... | [
"def",
"forwards",
"(",
"apps",
",",
"schema_editor",
")",
":",
"Event",
"=",
"apps",
".",
"get_model",
"(",
"'spectator_events'",
",",
"'Event'",
")",
"Work",
"=",
"apps",
".",
"get_model",
"(",
"'spectator_events'",
",",
"'Work'",
")",
"WorkRole",
"=",
"... | Having added the new 'exhibition' Work type, we're going to assume that
every Event of type 'museum' should actually have one Exhibition attached.
So, we'll add one, with the same title as the Event.
And we'll move all Creators from the Event to the Exhibition. | [
"Having",
"added",
"the",
"new",
"exhibition",
"Work",
"type",
"we",
"re",
"going",
"to",
"assume",
"that",
"every",
"Event",
"of",
"type",
"museum",
"should",
"actually",
"have",
"one",
"Exhibition",
"attached",
"."
] | python | train | 34.340909 |
adafruit/Adafruit_Python_VCNL40xx | Adafruit_VCNL40xx/VCNL40xx.py | https://github.com/adafruit/Adafruit_Python_VCNL40xx/blob/f88ec755fd23017028b6dec1be0607ff4a018e10/Adafruit_VCNL40xx/VCNL40xx.py#L139-L145 | def read_ambient(self, timeout_sec=1):
"""Read the ambient light sensor and return it as an unsigned 16-bit value.
"""
# Clear any interrupts.
self._clear_interrupt(VCNL4010_INT_ALS_READY)
# Call base class read_ambient and return result.
return super(VCNL4010, self).read... | [
"def",
"read_ambient",
"(",
"self",
",",
"timeout_sec",
"=",
"1",
")",
":",
"# Clear any interrupts.",
"self",
".",
"_clear_interrupt",
"(",
"VCNL4010_INT_ALS_READY",
")",
"# Call base class read_ambient and return result.",
"return",
"super",
"(",
"VCNL4010",
",",
"sel... | Read the ambient light sensor and return it as an unsigned 16-bit value. | [
"Read",
"the",
"ambient",
"light",
"sensor",
"and",
"return",
"it",
"as",
"an",
"unsigned",
"16",
"-",
"bit",
"value",
"."
] | python | train | 47.857143 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L326-L368 | def visit_Compare(self, node):
""" Boolean are possible index.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2 or 3
... b = 4 or 5
... c = a < b
... d = b < 3
... | [
"def",
"visit_Compare",
"(",
"self",
",",
"node",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"op",
",",
"(",
"ast",
".",
"In",
",",
"ast",
".",
"NotIn",
",",
"ast",
".",
"Is",
",",
"ast",
".",
"IsNot",
")",
")",
"for",
"op",
"in",
"node",
... | Boolean are possible index.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2 or 3
... b = 4 or 5
... c = a < b
... d = b < 3
... e = b == 4''')
>>> pm... | [
"Boolean",
"are",
"possible",
"index",
"."
] | python | train | 36.325581 |
thiezn/iperf3-python | iperf3/iperf3.py | https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L486-L489 | def omit(self):
"""The test startup duration to omit in seconds."""
self._omit = self.lib.iperf_get_test_omit(self._test)
return self._omit | [
"def",
"omit",
"(",
"self",
")",
":",
"self",
".",
"_omit",
"=",
"self",
".",
"lib",
".",
"iperf_get_test_omit",
"(",
"self",
".",
"_test",
")",
"return",
"self",
".",
"_omit"
] | The test startup duration to omit in seconds. | [
"The",
"test",
"startup",
"duration",
"to",
"omit",
"in",
"seconds",
"."
] | python | train | 40 |
swevm/scaleio-py | scaleiopy/api/scaleio/cluster/sdc.py | https://github.com/swevm/scaleio-py/blob/d043a0137cb925987fd5c895a3210968ce1d9028/scaleiopy/api/scaleio/cluster/sdc.py#L62-L73 | def get_sdc_by_id(self, id):
"""
Get ScaleIO SDC object by its id
:param name: id of SDC
:return: ScaleIO SDC object
:raise KeyError: No SDC with specified id found
:rtype: SDC object
"""
for sdc in self.sdc:
if sdc.id == id:
re... | [
"def",
"get_sdc_by_id",
"(",
"self",
",",
"id",
")",
":",
"for",
"sdc",
"in",
"self",
".",
"sdc",
":",
"if",
"sdc",
".",
"id",
"==",
"id",
":",
"return",
"sdc",
"raise",
"KeyError",
"(",
"\"SDC with that ID not found\"",
")"
] | Get ScaleIO SDC object by its id
:param name: id of SDC
:return: ScaleIO SDC object
:raise KeyError: No SDC with specified id found
:rtype: SDC object | [
"Get",
"ScaleIO",
"SDC",
"object",
"by",
"its",
"id",
":",
"param",
"name",
":",
"id",
"of",
"SDC",
":",
"return",
":",
"ScaleIO",
"SDC",
"object",
":",
"raise",
"KeyError",
":",
"No",
"SDC",
"with",
"specified",
"id",
"found",
":",
"rtype",
":",
"SD... | python | train | 30.833333 |
stevearc/dynamo3 | dynamo3/rate.py | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/rate.py#L27-L31 | def add(self, now, num):
""" Add a timestamp and date to the data """
if num == 0:
return
self.points.append((now, num)) | [
"def",
"add",
"(",
"self",
",",
"now",
",",
"num",
")",
":",
"if",
"num",
"==",
"0",
":",
"return",
"self",
".",
"points",
".",
"append",
"(",
"(",
"now",
",",
"num",
")",
")"
] | Add a timestamp and date to the data | [
"Add",
"a",
"timestamp",
"and",
"date",
"to",
"the",
"data"
] | python | train | 30.4 |
danielfrg/datasciencebox | datasciencebox/core/project.py | https://github.com/danielfrg/datasciencebox/blob/6b7aa642c6616a46547035fcb815acc1de605a6f/datasciencebox/core/project.py#L66-L72 | def read_settings(self):
"""
Read the "dsbfile" file
Populates `self.settings`
"""
logger.debug('Reading settings from: %s', self.settings_path)
self.settings = Settings.from_dsbfile(self.settings_path) | [
"def",
"read_settings",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Reading settings from: %s'",
",",
"self",
".",
"settings_path",
")",
"self",
".",
"settings",
"=",
"Settings",
".",
"from_dsbfile",
"(",
"self",
".",
"settings_path",
")"
] | Read the "dsbfile" file
Populates `self.settings` | [
"Read",
"the",
"dsbfile",
"file",
"Populates",
"self",
".",
"settings"
] | python | train | 34.857143 |
Kortemme-Lab/klab | klab/chainsequence.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/chainsequence.py#L57-L81 | def parse_atoms(self, pdb):
"""Parse the ATOM entries into the object"""
atomre = re.compile("ATOM")
atomlines = [line for line in pdb.lines if atomre.match(line)]
chainresnums = {}
for line in atomlines:
chain = line[21]
resname = line[17:20]
resnum = line[22:2... | [
"def",
"parse_atoms",
"(",
"self",
",",
"pdb",
")",
":",
"atomre",
"=",
"re",
".",
"compile",
"(",
"\"ATOM\"",
")",
"atomlines",
"=",
"[",
"line",
"for",
"line",
"in",
"pdb",
".",
"lines",
"if",
"atomre",
".",
"match",
"(",
"line",
")",
"]",
"chain... | Parse the ATOM entries into the object | [
"Parse",
"the",
"ATOM",
"entries",
"into",
"the",
"object"
] | python | train | 26.56 |
mbakker7/timml | timml/linesink1d.py | https://github.com/mbakker7/timml/blob/91e99ad573cb8a9ad8ac1fa041c3ca44520c2390/timml/linesink1d.py#L92-L96 | def discharge(self):
"""Discharge per unit length"""
Q = np.zeros(self.aq.naq)
Q[self.layers] = self.parameters[:, 0]
return Q | [
"def",
"discharge",
"(",
"self",
")",
":",
"Q",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"aq",
".",
"naq",
")",
"Q",
"[",
"self",
".",
"layers",
"]",
"=",
"self",
".",
"parameters",
"[",
":",
",",
"0",
"]",
"return",
"Q"
] | Discharge per unit length | [
"Discharge",
"per",
"unit",
"length"
] | python | train | 30.8 |
sanger-pathogens/Fastaq | pyfastaq/sequences.py | https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/sequences.py#L580-L582 | def subseq(self, start, end):
'''Returns Fastq object with the same name, of the bases from start to end, but not including end'''
return Fastq(self.id, self.seq[start:end], self.qual[start:end]) | [
"def",
"subseq",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"return",
"Fastq",
"(",
"self",
".",
"id",
",",
"self",
".",
"seq",
"[",
"start",
":",
"end",
"]",
",",
"self",
".",
"qual",
"[",
"start",
":",
"end",
"]",
")"
] | Returns Fastq object with the same name, of the bases from start to end, but not including end | [
"Returns",
"Fastq",
"object",
"with",
"the",
"same",
"name",
"of",
"the",
"bases",
"from",
"start",
"to",
"end",
"but",
"not",
"including",
"end"
] | python | valid | 69.666667 |
rstoneback/pysat | pysat/_meta.py | https://github.com/rstoneback/pysat/blob/4ae1afd80e15e4449397d39dce8c3e969c32c422/pysat/_meta.py#L776-L807 | def attr_case_name(self, name):
"""Returns preserved case name for case insensitive value of name.
Checks first within standard attributes. If not found there, checks
attributes for higher order data structures. If not found, returns
supplied name as it is available for use. Int... | [
"def",
"attr_case_name",
"(",
"self",
",",
"name",
")",
":",
"lower_name",
"=",
"name",
".",
"lower",
"(",
")",
"for",
"i",
"in",
"self",
".",
"attrs",
"(",
")",
":",
"if",
"lower_name",
"==",
"i",
".",
"lower",
"(",
")",
":",
"return",
"i",
"# c... | Returns preserved case name for case insensitive value of name.
Checks first within standard attributes. If not found there, checks
attributes for higher order data structures. If not found, returns
supplied name as it is available for use. Intended to be used to help
ensure tha... | [
"Returns",
"preserved",
"case",
"name",
"for",
"case",
"insensitive",
"value",
"of",
"name",
".",
"Checks",
"first",
"within",
"standard",
"attributes",
".",
"If",
"not",
"found",
"there",
"checks",
"attributes",
"for",
"higher",
"order",
"data",
"structures",
... | python | train | 33.71875 |
Diaoul/subliminal | subliminal/providers/legendastv.py | https://github.com/Diaoul/subliminal/blob/a952dfb2032eb0fd6eb1eb89f04080923c11c4cf/subliminal/providers/legendastv.py#L258-L314 | def get_archives(self, title_id, language_code):
"""Get the archive list from a given `title_id` and `language_code`.
:param int title_id: title id.
:param int language_code: language code.
:return: the archives.
:rtype: list of :class:`LegendasTVArchive`
"""
lo... | [
"def",
"get_archives",
"(",
"self",
",",
"title_id",
",",
"language_code",
")",
":",
"logger",
".",
"info",
"(",
"'Getting archives for title %d and language %d'",
",",
"title_id",
",",
"language_code",
")",
"archives",
"=",
"[",
"]",
"page",
"=",
"1",
"while",
... | Get the archive list from a given `title_id` and `language_code`.
:param int title_id: title id.
:param int language_code: language code.
:return: the archives.
:rtype: list of :class:`LegendasTVArchive` | [
"Get",
"the",
"archive",
"list",
"from",
"a",
"given",
"title_id",
"and",
"language_code",
"."
] | python | train | 42.824561 |
XuShaohua/bcloud | bcloud/auth.py | https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/auth.py#L285-L295 | def get_bdstoken(cookie):
'''从/disk/home页面获取bdstoken等token信息
这些token对于之后的请求非常重要.
'''
url = const.PAN_REFERER
req = net.urlopen(url, headers={'Cookie': cookie.header_output()})
if req:
return parse_bdstoken(req.data.decode())
else:
return None | [
"def",
"get_bdstoken",
"(",
"cookie",
")",
":",
"url",
"=",
"const",
".",
"PAN_REFERER",
"req",
"=",
"net",
".",
"urlopen",
"(",
"url",
",",
"headers",
"=",
"{",
"'Cookie'",
":",
"cookie",
".",
"header_output",
"(",
")",
"}",
")",
"if",
"req",
":",
... | 从/disk/home页面获取bdstoken等token信息
这些token对于之后的请求非常重要. | [
"从",
"/",
"disk",
"/",
"home页面获取bdstoken等token信息"
] | python | train | 25.181818 |
brentp/cruzdb | cruzdb/models.py | https://github.com/brentp/cruzdb/blob/9068d46e25952f4a929dde0242beb31fa4c7e89a/cruzdb/models.py#L348-L357 | def is_downstream_of(self, other):
"""
return a boolean indicating whether this feature is downstream of
`other` taking the strand of other into account
"""
if self.chrom != other.chrom: return None
if getattr(other, "strand", None) == "-":
# other feature is ... | [
"def",
"is_downstream_of",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"chrom",
"!=",
"other",
".",
"chrom",
":",
"return",
"None",
"if",
"getattr",
"(",
"other",
",",
"\"strand\"",
",",
"None",
")",
"==",
"\"-\"",
":",
"# other feature is on... | return a boolean indicating whether this feature is downstream of
`other` taking the strand of other into account | [
"return",
"a",
"boolean",
"indicating",
"whether",
"this",
"feature",
"is",
"downstream",
"of",
"other",
"taking",
"the",
"strand",
"of",
"other",
"into",
"account"
] | python | train | 43.6 |
datastore/datastore | datastore/core/serialize.py | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/serialize.py#L112-L121 | def monkey_patch_bson(bson=None):
'''Patch bson in pymongo to use loads and dumps interface.'''
if not bson:
import bson
if not hasattr(bson, 'loads'):
bson.loads = lambda bsondoc: bson.BSON(bsondoc).decode()
if not hasattr(bson, 'dumps'):
bson.dumps = lambda document: bson.BSON.encode(document) | [
"def",
"monkey_patch_bson",
"(",
"bson",
"=",
"None",
")",
":",
"if",
"not",
"bson",
":",
"import",
"bson",
"if",
"not",
"hasattr",
"(",
"bson",
",",
"'loads'",
")",
":",
"bson",
".",
"loads",
"=",
"lambda",
"bsondoc",
":",
"bson",
".",
"BSON",
"(",
... | Patch bson in pymongo to use loads and dumps interface. | [
"Patch",
"bson",
"in",
"pymongo",
"to",
"use",
"loads",
"and",
"dumps",
"interface",
"."
] | python | train | 30.9 |
tristantao/py-bing-search | py_bing_search/py_bing_search.py | https://github.com/tristantao/py-bing-search/blob/d18b8fcfe5a5502682c65dd458f50c0a29a510e9/py_bing_search/py_bing_search.py#L216-L232 | def _search(self, limit, format):
'''
Returns a list of result objects, with the url for the next page bing search url.
'''
url = self.QUERY_URL.format(requests.utils.quote("'{}'".format(self.query)), min(50, limit), self.current_offset, format)
r = requests.get(url, auth=("", se... | [
"def",
"_search",
"(",
"self",
",",
"limit",
",",
"format",
")",
":",
"url",
"=",
"self",
".",
"QUERY_URL",
".",
"format",
"(",
"requests",
".",
"utils",
".",
"quote",
"(",
"\"'{}'\"",
".",
"format",
"(",
"self",
".",
"query",
")",
")",
",",
"min",... | Returns a list of result objects, with the url for the next page bing search url. | [
"Returns",
"a",
"list",
"of",
"result",
"objects",
"with",
"the",
"url",
"for",
"the",
"next",
"page",
"bing",
"search",
"url",
"."
] | python | train | 55.470588 |
Jajcus/pyxmpp2 | pyxmpp2/xmppparser.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppparser.py#L112-L127 | def start(self, tag, attrs):
"""Handle the start tag.
Call the handler's 'stream_start' methods with
an empty root element if it is top level.
For lower level tags use :etree:`ElementTree.TreeBuilder` to collect
them.
"""
if self._level == 0:
self._r... | [
"def",
"start",
"(",
"self",
",",
"tag",
",",
"attrs",
")",
":",
"if",
"self",
".",
"_level",
"==",
"0",
":",
"self",
".",
"_root",
"=",
"ElementTree",
".",
"Element",
"(",
"tag",
",",
"attrs",
")",
"self",
".",
"_handler",
".",
"stream_start",
"("... | Handle the start tag.
Call the handler's 'stream_start' methods with
an empty root element if it is top level.
For lower level tags use :etree:`ElementTree.TreeBuilder` to collect
them. | [
"Handle",
"the",
"start",
"tag",
"."
] | python | valid | 34.1875 |
alpha-xone/xbbg | xbbg/blp.py | https://github.com/alpha-xone/xbbg/blob/70226eb19a72a08144b5d8cea9db4913200f7bc5/xbbg/blp.py#L350-L398 | def intraday(ticker, dt, session='', **kwargs) -> pd.DataFrame:
"""
Bloomberg intraday bar data within market session
Args:
ticker: ticker
dt: date
session: examples include
day_open_30, am_normal_30_30, day_close_30, allday_exact_0930_1000
**kwargs:
... | [
"def",
"intraday",
"(",
"ticker",
",",
"dt",
",",
"session",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
"->",
"pd",
".",
"DataFrame",
":",
"from",
"xbbg",
".",
"core",
"import",
"intervals",
"cur_data",
"=",
"bdib",
"(",
"ticker",
"=",
"ticker",
",",
... | Bloomberg intraday bar data within market session
Args:
ticker: ticker
dt: date
session: examples include
day_open_30, am_normal_30_30, day_close_30, allday_exact_0930_1000
**kwargs:
ref: reference ticker or exchange for timezone
keep_tz: if ... | [
"Bloomberg",
"intraday",
"bar",
"data",
"within",
"market",
"session"
] | python | valid | 34.142857 |
atztogo/phonopy | phonopy/structure/spglib.py | https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/structure/spglib.py#L123-L235 | def get_symmetry_dataset(cell,
symprec=1e-5,
angle_tolerance=-1.0,
hall_number=0):
"""Search symmetry dataset from an input cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
hall_... | [
"def",
"get_symmetry_dataset",
"(",
"cell",
",",
"symprec",
"=",
"1e-5",
",",
"angle_tolerance",
"=",
"-",
"1.0",
",",
"hall_number",
"=",
"0",
")",
":",
"_set_no_error",
"(",
")",
"lattice",
",",
"positions",
",",
"numbers",
",",
"_",
"=",
"_expand_cell",... | Search symmetry dataset from an input cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
hall_number: If a serial number of Hall symbol (>0) is given,
the database corresponding to the Hall symbol is made.
Return:
A dictionar... | [
"Search",
"symmetry",
"dataset",
"from",
"an",
"input",
"cell",
"."
] | python | train | 42.522124 |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/build/build_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/build/build_client.py#L1292-L1313 | def get_build_report(self, project, build_id, type=None):
"""GetBuildReport.
[Preview API] Gets a build report.
:param str project: Project ID or project name
:param int build_id: The ID of the build.
:param str type:
:rtype: :class:`<BuildReportMetadata> <azure.devops.v5... | [
"def",
"get_build_report",
"(",
"self",
",",
"project",
",",
"build_id",
",",
"type",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
... | GetBuildReport.
[Preview API] Gets a build report.
:param str project: Project ID or project name
:param int build_id: The ID of the build.
:param str type:
:rtype: :class:`<BuildReportMetadata> <azure.devops.v5_0.build.models.BuildReportMetadata>` | [
"GetBuildReport",
".",
"[",
"Preview",
"API",
"]",
"Gets",
"a",
"build",
"report",
".",
":",
"param",
"str",
"project",
":",
"Project",
"ID",
"or",
"project",
"name",
":",
"param",
"int",
"build_id",
":",
"The",
"ID",
"of",
"the",
"build",
".",
":",
... | python | train | 51.181818 |
rsennrich/Bleualign | bleualign/gale_church.py | https://github.com/rsennrich/Bleualign/blob/1de181dcc3257d885a2b981f751c0220c0e8958f/bleualign/gale_church.py#L97-L146 | def align_blocks(source_sentences, target_sentences, params = LanguageIndependent):
"""Creates the sentence alignment of two blocks of texts (usually paragraphs).
@param source_sentences: The list of source sentence lengths.
@param target_sentences: The list of target sentence lengths.
@param params: t... | [
"def",
"align_blocks",
"(",
"source_sentences",
",",
"target_sentences",
",",
"params",
"=",
"LanguageIndependent",
")",
":",
"alignment_types",
"=",
"list",
"(",
"params",
".",
"PRIORS",
".",
"keys",
"(",
")",
")",
"# there are always three rows in the history (with ... | Creates the sentence alignment of two blocks of texts (usually paragraphs).
@param source_sentences: The list of source sentence lengths.
@param target_sentences: The list of target sentence lengths.
@param params: the sentence alignment parameters.
@return: The sentence alignments, a list of index pa... | [
"Creates",
"the",
"sentence",
"alignment",
"of",
"two",
"blocks",
"of",
"texts",
"(",
"usually",
"paragraphs",
")",
"."
] | python | test | 32.58 |
obriencj/python-javatools | javatools/distdiff.py | https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/distdiff.py#L591-L617 | def add_distdiff_optgroup(parser):
"""
Option group relating to the use of a DistChange or DistReport
"""
# for the --processes default
cpus = cpu_count()
og = parser.add_argument_group("Distribution Checking Options")
og.add_argument("--processes", type=int, default=cpus,
... | [
"def",
"add_distdiff_optgroup",
"(",
"parser",
")",
":",
"# for the --processes default",
"cpus",
"=",
"cpu_count",
"(",
")",
"og",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"Distribution Checking Options\"",
")",
"og",
".",
"add_argument",
"(",
"\"--processes\... | Option group relating to the use of a DistChange or DistReport | [
"Option",
"group",
"relating",
"to",
"the",
"use",
"of",
"a",
"DistChange",
"or",
"DistReport"
] | python | train | 39.925926 |
sdispater/pendulum | pendulum/__init__.py | https://github.com/sdispater/pendulum/blob/94d28b0d3cb524ae02361bd1ed7ea03e2e655e4e/pendulum/__init__.py#L137-L145 | def local(
year, month, day, hour=0, minute=0, second=0, microsecond=0
): # type: (int, int, int, int, int, int, int) -> DateTime
"""
Return a DateTime in the local timezone.
"""
return datetime(
year, month, day, hour, minute, second, microsecond, tz=local_timezone()
) | [
"def",
"local",
"(",
"year",
",",
"month",
",",
"day",
",",
"hour",
"=",
"0",
",",
"minute",
"=",
"0",
",",
"second",
"=",
"0",
",",
"microsecond",
"=",
"0",
")",
":",
"# type: (int, int, int, int, int, int, int) -> DateTime",
"return",
"datetime",
"(",
"y... | Return a DateTime in the local timezone. | [
"Return",
"a",
"DateTime",
"in",
"the",
"local",
"timezone",
"."
] | python | train | 32.777778 |
KE-works/pykechain | pykechain/models/activity.py | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/activity.py#L120-L139 | def parts(self, *args, **kwargs):
"""Retrieve parts belonging to this activity.
Without any arguments it retrieves the Instances related to this task only.
This call only returns the configured properties in an activity. So properties that are not configured
are not in the returned par... | [
"def",
"parts",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_client",
".",
"parts",
"(",
"*",
"args",
",",
"activity",
"=",
"self",
".",
"id",
",",
"*",
"*",
"kwargs",
")"
] | Retrieve parts belonging to this activity.
Without any arguments it retrieves the Instances related to this task only.
This call only returns the configured properties in an activity. So properties that are not configured
are not in the returned parts.
See :class:`pykechain.Client.par... | [
"Retrieve",
"parts",
"belonging",
"to",
"this",
"activity",
"."
] | python | train | 34.5 |
tensorflow/probability | tensorflow_probability/python/mcmc/eight_schools_hmc.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/eight_schools_hmc.py#L63-L129 | def benchmark_eight_schools_hmc(
num_results=int(5e3),
num_burnin_steps=int(3e3),
num_leapfrog_steps=3,
step_size=0.4):
"""Runs HMC on the eight-schools unnormalized posterior."""
num_schools = 8
treatment_effects = tf.constant(
[28, 8, -3, 7, -1, 1, 18, 12],
dtype=np.float32,
n... | [
"def",
"benchmark_eight_schools_hmc",
"(",
"num_results",
"=",
"int",
"(",
"5e3",
")",
",",
"num_burnin_steps",
"=",
"int",
"(",
"3e3",
")",
",",
"num_leapfrog_steps",
"=",
"3",
",",
"step_size",
"=",
"0.4",
")",
":",
"num_schools",
"=",
"8",
"treatment_effe... | Runs HMC on the eight-schools unnormalized posterior. | [
"Runs",
"HMC",
"on",
"the",
"eight",
"-",
"schools",
"unnormalized",
"posterior",
"."
] | python | test | 31.955224 |
ikegami-yukino/jaconv | jaconv/jaconv.py | https://github.com/ikegami-yukino/jaconv/blob/5319e4c6b4676ab27b5e9ebec9a299d09a5a62d7/jaconv/jaconv.py#L178-L229 | def z2h(text, ignore='', kana=True, ascii=False, digit=False):
"""Convert Full-width (Zenkaku) Katakana to Half-width (Hankaku) Katakana
Parameters
----------
text : str
Full-width Katakana string.
ignore : str
Characters to be ignored in converting.
kana : bool
Either c... | [
"def",
"z2h",
"(",
"text",
",",
"ignore",
"=",
"''",
",",
"kana",
"=",
"True",
",",
"ascii",
"=",
"False",
",",
"digit",
"=",
"False",
")",
":",
"if",
"ascii",
":",
"if",
"digit",
":",
"if",
"kana",
":",
"z2h_map",
"=",
"Z2H_ALL",
"else",
":",
... | Convert Full-width (Zenkaku) Katakana to Half-width (Hankaku) Katakana
Parameters
----------
text : str
Full-width Katakana string.
ignore : str
Characters to be ignored in converting.
kana : bool
Either converting Kana or not.
ascii : bool
Either converting asci... | [
"Convert",
"Full",
"-",
"width",
"(",
"Zenkaku",
")",
"Katakana",
"to",
"Half",
"-",
"width",
"(",
"Hankaku",
")",
"Katakana"
] | python | train | 23.25 |
DAI-Lab/Copulas | copulas/bivariate/gumbel.py | https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/bivariate/gumbel.py#L20-L35 | def probability_density(self, X):
"""Compute density function for given copula family."""
self.check_fit()
U, V = self.split_matrix(X)
if self.theta == 1:
return np.multiply(U, V)
else:
a = np.power(np.multiply(U, V), -1)
tmp = np.power(-np.... | [
"def",
"probability_density",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"check_fit",
"(",
")",
"U",
",",
"V",
"=",
"self",
".",
"split_matrix",
"(",
"X",
")",
"if",
"self",
".",
"theta",
"==",
"1",
":",
"return",
"np",
".",
"multiply",
"(",
"... | Compute density function for given copula family. | [
"Compute",
"density",
"function",
"for",
"given",
"copula",
"family",
"."
] | python | train | 39.1875 |
wummel/linkchecker | setup.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/setup.py#L330-L339 | def run (self):
"""Remove share directory on clean."""
if self.all:
# remove share directory
directory = os.path.join("build", "share")
if os.path.exists(directory):
remove_tree(directory, dry_run=self.dry_run)
else:
log.war... | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"all",
":",
"# remove share directory",
"directory",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"build\"",
",",
"\"share\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
... | Remove share directory on clean. | [
"Remove",
"share",
"directory",
"on",
"clean",
"."
] | python | train | 38.8 |
bcbio/bcbio-nextgen | bcbio/structural/gatkcnv.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L150-L165 | def pon_to_bed(pon_file, out_dir, data):
"""Extract BED intervals from a GATK4 hdf5 panel of normal file.
"""
out_file = os.path.join(out_dir, "%s-intervals.bed" % (utils.splitext_plus(os.path.basename(pon_file))[0]))
if not utils.file_uptodate(out_file, pon_file):
import h5py
with file_... | [
"def",
"pon_to_bed",
"(",
"pon_file",
",",
"out_dir",
",",
"data",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"\"%s-intervals.bed\"",
"%",
"(",
"utils",
".",
"splitext_plus",
"(",
"os",
".",
"path",
".",
"basename",
... | Extract BED intervals from a GATK4 hdf5 panel of normal file. | [
"Extract",
"BED",
"intervals",
"from",
"a",
"GATK4",
"hdf5",
"panel",
"of",
"normal",
"file",
"."
] | python | train | 61.5 |
rhgrant10/Groupy | groupy/api/bots.py | https://github.com/rhgrant10/Groupy/blob/ffd8cac57586fa1c218e3b4bfaa531142c3be766/groupy/api/bots.py#L20-L44 | def create(self, name, group_id, avatar_url=None, callback_url=None,
dm_notification=None, **kwargs):
"""Create a new bot in a particular group.
:param str name: bot name
:param str group_id: the group_id of a group
:param str avatar_url: the URL of an image to use as an ... | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"group_id",
",",
"avatar_url",
"=",
"None",
",",
"callback_url",
"=",
"None",
",",
"dm_notification",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"{",
"'bot'",
":",
"{",
"'name'",
":... | Create a new bot in a particular group.
:param str name: bot name
:param str group_id: the group_id of a group
:param str avatar_url: the URL of an image to use as an avatar
:param str callback_url: a POST-back URL for each new message
:param bool dm_notification: whether to POS... | [
"Create",
"a",
"new",
"bot",
"in",
"a",
"particular",
"group",
"."
] | python | train | 39.12 |
simodalla/pygmount | thirdparty/PyZenity-0.1.7/PyZenity.py | https://github.com/simodalla/pygmount/blob/8027cfa2ed5fa8e9207d72b6013ecec7fcf2e5f5/thirdparty/PyZenity-0.1.7/PyZenity.py#L274-L287 | def ErrorMessage(text, **kwargs):
"""Show an error message dialog to the user.
This will raise a Zenity Error Dialog with a description of the error.
text - A description of the error.
kwargs - Optional command line parameters for Zenity such as height,
width, etc."""
args = ... | [
"def",
"ErrorMessage",
"(",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"'--text=%s'",
"%",
"text",
"]",
"for",
"generic_args",
"in",
"kwargs_helper",
"(",
"kwargs",
")",
":",
"args",
".",
"append",
"(",
"'--%s=%s'",
"%",
"generic_args",... | Show an error message dialog to the user.
This will raise a Zenity Error Dialog with a description of the error.
text - A description of the error.
kwargs - Optional command line parameters for Zenity such as height,
width, etc. | [
"Show",
"an",
"error",
"message",
"dialog",
"to",
"the",
"user",
".",
"This",
"will",
"raise",
"a",
"Zenity",
"Error",
"Dialog",
"with",
"a",
"description",
"of",
"the",
"error",
".",
"text",
"-",
"A",
"description",
"of",
"the",
"error",
".",
"kwargs",
... | python | train | 32.928571 |
BD2KOnFHIR/fhirtordf | fhirtordf/fhir/fhirmetavoc.py | https://github.com/BD2KOnFHIR/fhirtordf/blob/f97b3df683fa4caacf5cf4f29699ab060bcc0fbf/fhirtordf/fhir/fhirmetavoc.py#L60-L68 | def _to_str(uri: URIRef) -> str:
"""
Convert a FHIR style URI into a tag name to be used to retrieve data from a JSON representation
Example: http://hl7.org/fhir/Provenance.agent.whoReference --> whoReference
:param uri: URI to convert
:return: tag name
"""
local_... | [
"def",
"_to_str",
"(",
"uri",
":",
"URIRef",
")",
"->",
"str",
":",
"local_name",
"=",
"str",
"(",
"uri",
")",
".",
"replace",
"(",
"str",
"(",
"FHIR",
")",
",",
"''",
")",
"return",
"local_name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
... | Convert a FHIR style URI into a tag name to be used to retrieve data from a JSON representation
Example: http://hl7.org/fhir/Provenance.agent.whoReference --> whoReference
:param uri: URI to convert
:return: tag name | [
"Convert",
"a",
"FHIR",
"style",
"URI",
"into",
"a",
"tag",
"name",
"to",
"be",
"used",
"to",
"retrieve",
"data",
"from",
"a",
"JSON",
"representation",
"Example",
":",
"http",
":",
"//",
"hl7",
".",
"org",
"/",
"fhir",
"/",
"Provenance",
".",
"agent",... | python | train | 47.888889 |
ryanvarley/ExoData | exodata/equations.py | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/equations.py#L876-L918 | def _createAbsMagEstimationDict():
""" loads magnitude_estimation.dat which is from
http://xoomer.virgilio.it/hrtrace/Sk.htm on 24/01/2014 and based on
Schmid-Kaler (1982)
creates a dict in the form [Classletter][ClassNumber][List of values for
each L Class]
"""
magnitude_estimation_filepat... | [
"def",
"_createAbsMagEstimationDict",
"(",
")",
":",
"magnitude_estimation_filepath",
"=",
"resource_filename",
"(",
"__name__",
",",
"'data/magnitude_estimation.dat'",
")",
"raw_table",
"=",
"np",
".",
"loadtxt",
"(",
"magnitude_estimation_filepath",
",",
"'|S5'",
")",
... | loads magnitude_estimation.dat which is from
http://xoomer.virgilio.it/hrtrace/Sk.htm on 24/01/2014 and based on
Schmid-Kaler (1982)
creates a dict in the form [Classletter][ClassNumber][List of values for
each L Class] | [
"loads",
"magnitude_estimation",
".",
"dat",
"which",
"is",
"from",
"http",
":",
"//",
"xoomer",
".",
"virgilio",
".",
"it",
"/",
"hrtrace",
"/",
"Sk",
".",
"htm",
"on",
"24",
"/",
"01",
"/",
"2014",
"and",
"based",
"on",
"Schmid",
"-",
"Kaler",
"(",... | python | train | 29.976744 |
pydata/xarray | xarray/coding/cftime_offsets.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/coding/cftime_offsets.py#L412-L417 | def rollforward(self, date):
"""Roll date forward to nearest start of quarter"""
if self.onOffset(date):
return date
else:
return date + QuarterBegin(month=self.month) | [
"def",
"rollforward",
"(",
"self",
",",
"date",
")",
":",
"if",
"self",
".",
"onOffset",
"(",
"date",
")",
":",
"return",
"date",
"else",
":",
"return",
"date",
"+",
"QuarterBegin",
"(",
"month",
"=",
"self",
".",
"month",
")"
] | Roll date forward to nearest start of quarter | [
"Roll",
"date",
"forward",
"to",
"nearest",
"start",
"of",
"quarter"
] | python | train | 35 |
topic2k/pygcgen | pygcgen/generator.py | https://github.com/topic2k/pygcgen/blob/c41701815df2c8c3a57fd5f7b8babe702127c8a1/pygcgen/generator.py#L26-L38 | def timestring_to_datetime(timestring):
"""
Convert an ISO formated date and time string to a datetime object.
:param str timestring: String with date and time in ISO format.
:rtype: datetime
:return: datetime object
"""
with warnings.catch_warnings():
warnings.filterwarnings("ignor... | [
"def",
"timestring_to_datetime",
"(",
"timestring",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"\"ignore\"",
",",
"category",
"=",
"UnicodeWarning",
")",
"result",
"=",
"dateutil_parser",
"(",
"tim... | Convert an ISO formated date and time string to a datetime object.
:param str timestring: String with date and time in ISO format.
:rtype: datetime
:return: datetime object | [
"Convert",
"an",
"ISO",
"formated",
"date",
"and",
"time",
"string",
"to",
"a",
"datetime",
"object",
"."
] | python | valid | 30.769231 |
rene-aguirre/pywinusb | pywinusb/hid/core.py | https://github.com/rene-aguirre/pywinusb/blob/954c4b2105d9f01cb0c50e24500bb747d4ecdc43/pywinusb/hid/core.py#L717-L763 | def _process_raw_report(self, raw_report):
"Default raw input report data handler"
if not self.is_opened():
return
if not self.__evt_handlers and not self.__raw_handler:
return
if not raw_report[0] and \
(raw_report[0] not in self.__input... | [
"def",
"_process_raw_report",
"(",
"self",
",",
"raw_report",
")",
":",
"if",
"not",
"self",
".",
"is_opened",
"(",
")",
":",
"return",
"if",
"not",
"self",
".",
"__evt_handlers",
"and",
"not",
"self",
".",
"__raw_handler",
":",
"return",
"if",
"not",
"r... | Default raw input report data handler | [
"Default",
"raw",
"input",
"report",
"data",
"handler"
] | python | train | 45.638298 |
horazont/aioxmpp | aioxmpp/muc/service.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L48-L60 | def _extract_one_pair(body):
"""
Extract one language-text pair from a :class:`~.LanguageMap`.
This is used for tracking.
"""
if not body:
return None, None
try:
return None, body[None]
except KeyError:
return min(body.items(), key=lambda x: x[0]) | [
"def",
"_extract_one_pair",
"(",
"body",
")",
":",
"if",
"not",
"body",
":",
"return",
"None",
",",
"None",
"try",
":",
"return",
"None",
",",
"body",
"[",
"None",
"]",
"except",
"KeyError",
":",
"return",
"min",
"(",
"body",
".",
"items",
"(",
")",
... | Extract one language-text pair from a :class:`~.LanguageMap`.
This is used for tracking. | [
"Extract",
"one",
"language",
"-",
"text",
"pair",
"from",
"a",
":",
"class",
":",
"~",
".",
"LanguageMap",
"."
] | python | train | 22.230769 |
facelessuser/pyspelling | pyspelling/filters/cpp.py | https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/cpp.py#L392-L405 | def extend_src_text(self, content, context, text_list, category):
"""Extend the source text list with the gathered text data."""
prefix = self.prefix + '-' if self.prefix else ''
for comment, line, encoding in text_list:
content.append(
filters.SourceText(
... | [
"def",
"extend_src_text",
"(",
"self",
",",
"content",
",",
"context",
",",
"text_list",
",",
"category",
")",
":",
"prefix",
"=",
"self",
".",
"prefix",
"+",
"'-'",
"if",
"self",
".",
"prefix",
"else",
"''",
"for",
"comment",
",",
"line",
",",
"encodi... | Extend the source text list with the gathered text data. | [
"Extend",
"the",
"source",
"text",
"list",
"with",
"the",
"gathered",
"text",
"data",
"."
] | python | train | 35.142857 |
InfoAgeTech/django-core | django_core/db/models/managers.py | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/managers.py#L241-L252 | def create_generic(self, content_object=None, **kwargs):
"""Create a generic object.
:param content_object: the content object to create a new object for.
"""
if content_object:
kwargs['content_type'] = ContentType.objects.get_for_model(
content_object
... | [
"def",
"create_generic",
"(",
"self",
",",
"content_object",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"content_object",
":",
"kwargs",
"[",
"'content_type'",
"]",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"content_object",
"... | Create a generic object.
:param content_object: the content object to create a new object for. | [
"Create",
"a",
"generic",
"object",
"."
] | python | train | 33.833333 |
theislab/scanpy | scanpy/plotting/_tools/scatterplots.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/plotting/_tools/scatterplots.py#L739-L751 | def _basis2name(basis):
"""
converts the 'basis' into the proper name.
"""
component_name = (
'DC' if basis == 'diffmap'
else 'tSNE' if basis == 'tsne'
else 'UMAP' if basis == 'umap'
else 'PC' if basis == 'pca'
else basis.replace('draw_graph_', '').upper() if 'dr... | [
"def",
"_basis2name",
"(",
"basis",
")",
":",
"component_name",
"=",
"(",
"'DC'",
"if",
"basis",
"==",
"'diffmap'",
"else",
"'tSNE'",
"if",
"basis",
"==",
"'tsne'",
"else",
"'UMAP'",
"if",
"basis",
"==",
"'umap'",
"else",
"'PC'",
"if",
"basis",
"==",
"'p... | converts the 'basis' into the proper name. | [
"converts",
"the",
"basis",
"into",
"the",
"proper",
"name",
"."
] | python | train | 28.615385 |
CalebBell/ht | ht/hx.py | https://github.com/CalebBell/ht/blob/3097ef9524c4cf0068ad453c17b10ec9ce551eee/ht/hx.py#L6187-L6236 | def DBundle_for_Ntubes_HEDH(N, Do, pitch, angle=30):
r'''A rough equation presented in the HEDH for estimating the tube bundle
diameter necessary to fit a given number of tubes.
No accuracy estimation given. Only 1 pass is supported.
.. math::
D_{bundle} = (D_o + (\text{pitch})\sqrt{\frac{1}{0... | [
"def",
"DBundle_for_Ntubes_HEDH",
"(",
"N",
",",
"Do",
",",
"pitch",
",",
"angle",
"=",
"30",
")",
":",
"if",
"angle",
"==",
"30",
"or",
"angle",
"==",
"60",
":",
"C1",
"=",
"13",
"/",
"15.",
"elif",
"angle",
"==",
"45",
"or",
"angle",
"==",
"90"... | r'''A rough equation presented in the HEDH for estimating the tube bundle
diameter necessary to fit a given number of tubes.
No accuracy estimation given. Only 1 pass is supported.
.. math::
D_{bundle} = (D_o + (\text{pitch})\sqrt{\frac{1}{0.78}}\cdot
\sqrt{C_1\cdot N})
C1 = 0.866 fo... | [
"r",
"A",
"rough",
"equation",
"presented",
"in",
"the",
"HEDH",
"for",
"estimating",
"the",
"tube",
"bundle",
"diameter",
"necessary",
"to",
"fit",
"a",
"given",
"number",
"of",
"tubes",
".",
"No",
"accuracy",
"estimation",
"given",
".",
"Only",
"1",
"pas... | python | train | 28.16 |
sffjunkie/astral | src/astral.py | https://github.com/sffjunkie/astral/blob/b0aa63fce692357cd33c2bf36c69ed5b6582440c/src/astral.py#L1334-L1354 | def solar_azimuth(self, dateandtime=None):
"""Calculates the solar azimuth angle for a specific date/time.
:param dateandtime: The date and time for which to calculate the angle.
:type dateandtime: :class:`~datetime.datetime`
:returns: The azimuth angle in degrees clockwise from North.... | [
"def",
"solar_azimuth",
"(",
"self",
",",
"dateandtime",
"=",
"None",
")",
":",
"if",
"self",
".",
"astral",
"is",
"None",
":",
"self",
".",
"astral",
"=",
"Astral",
"(",
")",
"if",
"dateandtime",
"is",
"None",
":",
"dateandtime",
"=",
"datetime",
".",... | Calculates the solar azimuth angle for a specific date/time.
:param dateandtime: The date and time for which to calculate the angle.
:type dateandtime: :class:`~datetime.datetime`
:returns: The azimuth angle in degrees clockwise from North.
:rtype: float | [
"Calculates",
"the",
"solar",
"azimuth",
"angle",
"for",
"a",
"specific",
"date",
"/",
"time",
"."
] | python | train | 34.619048 |
eaton-lab/toytree | versioner.py | https://github.com/eaton-lab/toytree/blob/0347ed2098acc5f707fadf52a0ecd411a6d1859c/versioner.py#L39-L67 | def get_git_status(self):
"""
Gets git and init versions and commits since the init version
"""
## get git branch
self._get_git_branch()
## get tag in the init file
self._get_init_release_tag()
## get log commits since <tag>
try:
self... | [
"def",
"get_git_status",
"(",
"self",
")",
":",
"## get git branch",
"self",
".",
"_get_git_branch",
"(",
")",
"## get tag in the init file",
"self",
".",
"_get_init_release_tag",
"(",
")",
"## get log commits since <tag>",
"try",
":",
"self",
".",
"_get_log_commits",
... | Gets git and init versions and commits since the init version | [
"Gets",
"git",
"and",
"init",
"versions",
"and",
"commits",
"since",
"the",
"init",
"version"
] | python | train | 34.724138 |
rigetti/quantumflow | quantumflow/ops.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/ops.py#L243-L252 | def aschannel(self) -> 'Channel':
"""Converts a Gate into a Channel"""
N = self.qubit_nb
R = 4
tensor = bk.outer(self.tensor, self.H.tensor)
tensor = bk.reshape(tensor, [2**N]*R)
tensor = bk.transpose(tensor, [0, 3, 1, 2])
return Channel(tensor, self.qubits) | [
"def",
"aschannel",
"(",
"self",
")",
"->",
"'Channel'",
":",
"N",
"=",
"self",
".",
"qubit_nb",
"R",
"=",
"4",
"tensor",
"=",
"bk",
".",
"outer",
"(",
"self",
".",
"tensor",
",",
"self",
".",
"H",
".",
"tensor",
")",
"tensor",
"=",
"bk",
".",
... | Converts a Gate into a Channel | [
"Converts",
"a",
"Gate",
"into",
"a",
"Channel"
] | python | train | 30.7 |
matthewgilbert/mapping | mapping/mappings.py | https://github.com/matthewgilbert/mapping/blob/24ea21acfe37a0ee273f63a273b5d24ea405e70d/mapping/mappings.py#L315-L407 | def to_generics(instruments, weights):
"""
Map tradeable instruments to generics given weights and tradeable
instrument holdings. This is solving the equation Ax = b where A is the
weights, and b is the instrument holdings. When Ax = b has no solution we
solve for x' such that Ax' is closest to b in... | [
"def",
"to_generics",
"(",
"instruments",
",",
"weights",
")",
":",
"if",
"not",
"isinstance",
"(",
"weights",
",",
"dict",
")",
":",
"weights",
"=",
"{",
"\"\"",
":",
"weights",
"}",
"allocations",
"=",
"[",
"]",
"unmapped_instr",
"=",
"instruments",
".... | Map tradeable instruments to generics given weights and tradeable
instrument holdings. This is solving the equation Ax = b where A is the
weights, and b is the instrument holdings. When Ax = b has no solution we
solve for x' such that Ax' is closest to b in the least squares sense with
the additional co... | [
"Map",
"tradeable",
"instruments",
"to",
"generics",
"given",
"weights",
"and",
"tradeable",
"instrument",
"holdings",
".",
"This",
"is",
"solving",
"the",
"equation",
"Ax",
"=",
"b",
"where",
"A",
"is",
"the",
"weights",
"and",
"b",
"is",
"the",
"instrument... | python | train | 40.935484 |
Microsoft/nni | tools/nni_cmd/config_utils.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/config_utils.py#L49-L57 | def write_file(self):
'''save config to local file'''
if self.config:
try:
with open(self.config_file, 'w') as file:
json.dump(self.config, file)
except IOError as error:
print('Error:', error)
return | [
"def",
"write_file",
"(",
"self",
")",
":",
"if",
"self",
".",
"config",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"config_file",
",",
"'w'",
")",
"as",
"file",
":",
"json",
".",
"dump",
"(",
"self",
".",
"config",
",",
"file",
")",
"exc... | save config to local file | [
"save",
"config",
"to",
"local",
"file"
] | python | train | 33.333333 |
Yelp/kafka-utils | kafka_utils/kafka_check/main.py | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_check/main.py#L49-L120 | def parse_args():
"""Parse the command line arguments."""
parser = argparse.ArgumentParser(
description='Check kafka current status',
)
parser.add_argument(
"--cluster-type",
"-t",
dest='cluster_type',
required=True,
help='Type of cluster',
default... | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Check kafka current status'",
",",
")",
"parser",
".",
"add_argument",
"(",
"\"--cluster-type\"",
",",
"\"-t\"",
",",
"dest",
"=",
"'cluster_type'",
... | Parse the command line arguments. | [
"Parse",
"the",
"command",
"line",
"arguments",
"."
] | python | train | 31.388889 |
richardchien/python-cqhttp | cqhttp_helper.py | https://github.com/richardchien/python-cqhttp/blob/1869819a8f89001e3f70668e31afc6c78f7f5bc2/cqhttp_helper.py#L287-L300 | def send_discuss_msg_async(self, *, discuss_id, message, auto_escape=False):
"""
发送讨论组消息 (异步版本)
------------
:param int discuss_id: 讨论组 ID(正常情况下看不到,需要从讨论组消息上报的数据中获得)
:param str | list[ dict[ str, unknown ] ] message: 要发送的内容
:param bool auto_escape: 消息内容是否作为纯文本发送(即不解析 CQ... | [
"def",
"send_discuss_msg_async",
"(",
"self",
",",
"*",
",",
"discuss_id",
",",
"message",
",",
"auto_escape",
"=",
"False",
")",
":",
"return",
"super",
"(",
")",
".",
"__getattr__",
"(",
"'send_discuss_msg_async'",
")",
"(",
"discuss_id",
"=",
"discuss_id",
... | 发送讨论组消息 (异步版本)
------------
:param int discuss_id: 讨论组 ID(正常情况下看不到,需要从讨论组消息上报的数据中获得)
:param str | list[ dict[ str, unknown ] ] message: 要发送的内容
:param bool auto_escape: 消息内容是否作为纯文本发送(即不解析 CQ 码),`message` 数据类型为 `list` 时无效
:return: None
:rtype: None | [
"发送讨论组消息",
"(",
"异步版本",
")"
] | python | valid | 38.071429 |
gunyarakun/python-shogi | shogi/__init__.py | https://github.com/gunyarakun/python-shogi/blob/137fe5f5e72251e8a97a1dba4a9b44b7c3c79914/shogi/__init__.py#L599-L606 | def piece_at(self, square):
'''Gets the piece at the given square.'''
mask = BB_SQUARES[square]
color = int(bool(self.occupied[WHITE] & mask))
piece_type = self.piece_type_at(square)
if piece_type:
return Piece(piece_type, color) | [
"def",
"piece_at",
"(",
"self",
",",
"square",
")",
":",
"mask",
"=",
"BB_SQUARES",
"[",
"square",
"]",
"color",
"=",
"int",
"(",
"bool",
"(",
"self",
".",
"occupied",
"[",
"WHITE",
"]",
"&",
"mask",
")",
")",
"piece_type",
"=",
"self",
".",
"piece... | Gets the piece at the given square. | [
"Gets",
"the",
"piece",
"at",
"the",
"given",
"square",
"."
] | python | test | 34.375 |
cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/connection_plugins/paramiko_ssh.py | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/connection_plugins/paramiko_ssh.py#L178-L188 | def fetch_file(self, in_path, out_path):
''' save a remote file to the specified path '''
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
try:
self.sftp = self._connect_sftp()
except:
raise errors.AnsibleError("failed to open a SFTP connection")
... | [
"def",
"fetch_file",
"(",
"self",
",",
"in_path",
",",
"out_path",
")",
":",
"vvv",
"(",
"\"FETCH %s TO %s\"",
"%",
"(",
"in_path",
",",
"out_path",
")",
",",
"host",
"=",
"self",
".",
"host",
")",
"try",
":",
"self",
".",
"sftp",
"=",
"self",
".",
... | save a remote file to the specified path | [
"save",
"a",
"remote",
"file",
"to",
"the",
"specified",
"path"
] | python | train | 42.545455 |
galactics/beyond | beyond/orbits/tle.py | https://github.com/galactics/beyond/blob/7a7590ff0fd4c0bac3e8e383ecca03caa98e5742/beyond/orbits/tle.py#L82-L102 | def _unfloat(flt, precision=5):
"""Function to convert float to 'decimal point assumed' format
>>> _unfloat(0)
'00000-0'
>>> _unfloat(3.4473e-4)
'34473-3'
>>> _unfloat(-6.0129e-05)
'-60129-4'
>>> _unfloat(4.5871e-05)
'45871-4'
"""
if flt == 0.:
return "{}-0".format(... | [
"def",
"_unfloat",
"(",
"flt",
",",
"precision",
"=",
"5",
")",
":",
"if",
"flt",
"==",
"0.",
":",
"return",
"\"{}-0\"",
".",
"format",
"(",
"\"0\"",
"*",
"precision",
")",
"num",
",",
"_",
",",
"exp",
"=",
"\"{:.{}e}\"",
".",
"format",
"(",
"flt",... | Function to convert float to 'decimal point assumed' format
>>> _unfloat(0)
'00000-0'
>>> _unfloat(3.4473e-4)
'34473-3'
>>> _unfloat(-6.0129e-05)
'-60129-4'
>>> _unfloat(4.5871e-05)
'45871-4' | [
"Function",
"to",
"convert",
"float",
"to",
"decimal",
"point",
"assumed",
"format"
] | python | train | 22.52381 |
ArchiveTeam/wpull | wpull/cookiewrapper.py | https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/cookiewrapper.py#L43-L53 | def info(self):
'''Return the header fields as a Message:
Returns:
Message: An instance of :class:`email.message.Message`. If
Python 2, returns an instance of :class:`mimetools.Message`.
'''
if sys.version_info[0] == 2:
return mimetools.Message(io.Str... | [
"def",
"info",
"(",
"self",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"return",
"mimetools",
".",
"Message",
"(",
"io",
".",
"StringIO",
"(",
"str",
"(",
"self",
".",
"_response",
".",
"fields",
")",
")",
")",
"el... | Return the header fields as a Message:
Returns:
Message: An instance of :class:`email.message.Message`. If
Python 2, returns an instance of :class:`mimetools.Message`. | [
"Return",
"the",
"header",
"fields",
"as",
"a",
"Message",
":"
] | python | train | 39.181818 |
lrq3000/pyFileFixity | pyFileFixity/lib/tee.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/tee.py#L27-L34 | def write(self, data, end="\n", flush=True):
""" Output data to stdout and/or file """
if not self.nostdout:
self.stdout.write(data+end)
if self.file is not None:
self.file.write(data+end)
if flush:
self.flush() | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"end",
"=",
"\"\\n\"",
",",
"flush",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"nostdout",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"data",
"+",
"end",
")",
"if",
"self",
".",
"file",
... | Output data to stdout and/or file | [
"Output",
"data",
"to",
"stdout",
"and",
"/",
"or",
"file"
] | python | train | 34 |
aetros/aetros-cli | aetros/backend.py | https://github.com/aetros/aetros-cli/blob/a2a1f38d6af1660e1e2680c7d413ec2aef45faab/aetros/backend.py#L505-L517 | def external_aborted(self, params):
"""
Immediately abort the job by server.
This runs in the Client:read() thread.
"""
self.ended = True
self.running = False
# When the server sends an abort signal, we really have to close immediately,
# since for examp... | [
"def",
"external_aborted",
"(",
"self",
",",
"params",
")",
":",
"self",
".",
"ended",
"=",
"True",
"self",
".",
"running",
"=",
"False",
"# When the server sends an abort signal, we really have to close immediately,",
"# since for example the job has been already deleted.",
... | Immediately abort the job by server.
This runs in the Client:read() thread. | [
"Immediately",
"abort",
"the",
"job",
"by",
"server",
"."
] | python | train | 32.461538 |
lrq3000/pyFileFixity | pyFileFixity/lib/reedsolomon/reedsolo.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/reedsolomon/reedsolo.py#L588-L600 | def rs_find_errors(err_loc, nmess, generator=2):
'''Find the roots (ie, where evaluation = zero) of error polynomial by bruteforce trial, this is a sort of Chien's search (but less efficient, Chien's search is a way to evaluate the polynomial such that each evaluation only takes constant time).'''
# nmess = len... | [
"def",
"rs_find_errors",
"(",
"err_loc",
",",
"nmess",
",",
"generator",
"=",
"2",
")",
":",
"# nmess = length of whole codeword (message + ecc symbols)",
"errs",
"=",
"len",
"(",
"err_loc",
")",
"-",
"1",
"err_pos",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
... | Find the roots (ie, where evaluation = zero) of error polynomial by bruteforce trial, this is a sort of Chien's search (but less efficient, Chien's search is a way to evaluate the polynomial such that each evaluation only takes constant time). | [
"Find",
"the",
"roots",
"(",
"ie",
"where",
"evaluation",
"=",
"zero",
")",
"of",
"error",
"polynomial",
"by",
"bruteforce",
"trial",
"this",
"is",
"a",
"sort",
"of",
"Chien",
"s",
"search",
"(",
"but",
"less",
"efficient",
"Chien",
"s",
"search",
"is",
... | python | train | 132.692308 |
brantai/python-rightscale | rightscale/util.py | https://github.com/brantai/python-rightscale/blob/5fbf4089922917247be712d58645a7b1504f0944/rightscale/util.py#L57-L83 | def find_by_name(collection, name, exact=True):
"""
Searches collection by resource name.
:param rightscale.ResourceCollection collection: The collection in which to
look for :attr:`name`.
:param str name: The name to look for in collection.
:param bool exact: A RightScale ``index`` searc... | [
"def",
"find_by_name",
"(",
"collection",
",",
"name",
",",
"exact",
"=",
"True",
")",
":",
"params",
"=",
"{",
"'filter[]'",
":",
"[",
"'name==%s'",
"%",
"name",
"]",
"}",
"found",
"=",
"collection",
".",
"index",
"(",
"params",
"=",
"params",
")",
... | Searches collection by resource name.
:param rightscale.ResourceCollection collection: The collection in which to
look for :attr:`name`.
:param str name: The name to look for in collection.
:param bool exact: A RightScale ``index`` search with a :attr:`name` filter
can return multiple res... | [
"Searches",
"collection",
"by",
"resource",
"name",
"."
] | python | train | 39.777778 |
mabuchilab/QNET | src/qnet/algebra/core/hilbert_space_algebra.py | https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/core/hilbert_space_algebra.py#L463-L507 | def next_basis_label_or_index(self, label_or_index, n=1):
"""Given the label or index of a basis state, return the label/index of
the next basis state.
More generally, if `n` is given, return the `n`'th next basis state
label/index; `n` may also be negative to obtain previous basis stat... | [
"def",
"next_basis_label_or_index",
"(",
"self",
",",
"label_or_index",
",",
"n",
"=",
"1",
")",
":",
"if",
"isinstance",
"(",
"label_or_index",
",",
"int",
")",
":",
"new_index",
"=",
"label_or_index",
"+",
"n",
"if",
"new_index",
"<",
"0",
":",
"raise",
... | Given the label or index of a basis state, return the label/index of
the next basis state.
More generally, if `n` is given, return the `n`'th next basis state
label/index; `n` may also be negative to obtain previous basis state
labels/indices.
The return type is the same as the... | [
"Given",
"the",
"label",
"or",
"index",
"of",
"a",
"basis",
"state",
"return",
"the",
"label",
"/",
"index",
"of",
"the",
"next",
"basis",
"state",
"."
] | python | train | 46.511111 |
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#L122-L170 | def _set_cell(self, column_family_id, column, value, timestamp=None, state=None):
"""Helper for :meth:`set_cell`
Adds a mutation to set the value in a specific cell.
``state`` is unused by :class:`DirectRow` but is used by
subclasses.
:type column_family_id: str
:param... | [
"def",
"_set_cell",
"(",
"self",
",",
"column_family_id",
",",
"column",
",",
"value",
",",
"timestamp",
"=",
"None",
",",
"state",
"=",
"None",
")",
":",
"column",
"=",
"_to_bytes",
"(",
"column",
")",
"if",
"isinstance",
"(",
"value",
",",
"six",
"."... | Helper for :meth:`set_cell`
Adds a mutation to set the value in a specific cell.
``state`` is unused by :class:`DirectRow` but is used by
subclasses.
:type column_family_id: str
:param column_family_id: The column family that contains the column.
... | [
"Helper",
"for",
":",
"meth",
":",
"set_cell"
] | python | train | 38.714286 |
profitbricks/profitbricks-sdk-python | profitbricks/client.py | https://github.com/profitbricks/profitbricks-sdk-python/blob/2c804b141688eccb07d6ae56601d5c60a62abebd/profitbricks/client.py#L2147-L2166 | def create_volume(self, datacenter_id, volume):
"""
Creates a volume within the specified data center.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param volume: A volume dict.
:type volume: ``dict``
... | [
"def",
"create_volume",
"(",
"self",
",",
"datacenter_id",
",",
"volume",
")",
":",
"data",
"=",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"_create_volume_dict",
"(",
"volume",
")",
")",
")",
"response",
"=",
"self",
".",
"_perform_request",
"(",
"url... | Creates a volume within the specified data center.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param volume: A volume dict.
:type volume: ``dict`` | [
"Creates",
"a",
"volume",
"within",
"the",
"specified",
"data",
"center",
"."
] | python | valid | 27.3 |
HEPData/hepdata-converter | hepdata_converter/parsers/oldhepdata_parser.py | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/oldhepdata_parser.py#L34-L44 | def reset(self):
"""Clean any processing data, and prepare object for reuse
"""
self.current_table = None
self.tables = []
self.data = [{}]
self.additional_data = {}
self.lines = []
self.set_state('document')
self.current_file = None
self.s... | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"current_table",
"=",
"None",
"self",
".",
"tables",
"=",
"[",
"]",
"self",
".",
"data",
"=",
"[",
"{",
"}",
"]",
"self",
".",
"additional_data",
"=",
"{",
"}",
"self",
".",
"lines",
"=",
"[",
... | Clean any processing data, and prepare object for reuse | [
"Clean",
"any",
"processing",
"data",
"and",
"prepare",
"object",
"for",
"reuse"
] | python | train | 30.181818 |
wummel/linkchecker | third_party/dnspython/dns/rdataset.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/rdataset.py#L308-L324 | def from_rdata_list(ttl, rdatas):
"""Create an rdataset with the specified TTL, and with
the specified list of rdata objects.
@rtype: dns.rdataset.Rdataset object
"""
if len(rdatas) == 0:
raise ValueError("rdata list must not be empty")
r = None
for rd in rdatas:
if r is No... | [
"def",
"from_rdata_list",
"(",
"ttl",
",",
"rdatas",
")",
":",
"if",
"len",
"(",
"rdatas",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"rdata list must not be empty\"",
")",
"r",
"=",
"None",
"for",
"rd",
"in",
"rdatas",
":",
"if",
"r",
"is",
"N... | Create an rdataset with the specified TTL, and with
the specified list of rdata objects.
@rtype: dns.rdataset.Rdataset object | [
"Create",
"an",
"rdataset",
"with",
"the",
"specified",
"TTL",
"and",
"with",
"the",
"specified",
"list",
"of",
"rdata",
"objects",
"."
] | python | train | 26.294118 |
apache/spark | python/pyspark/sql/avro/functions.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/avro/functions.py#L31-L67 | def from_avro(data, jsonFormatSchema, options={}):
"""
Converts a binary column of avro format into its corresponding catalyst value. The specified
schema must match the read data, otherwise the behavior is undefined: it may fail or return
arbitrary result.
Note: Avro is built-in but external data ... | [
"def",
"from_avro",
"(",
"data",
",",
"jsonFormatSchema",
",",
"options",
"=",
"{",
"}",
")",
":",
"sc",
"=",
"SparkContext",
".",
"_active_spark_context",
"try",
":",
"jc",
"=",
"sc",
".",
"_jvm",
".",
"org",
".",
"apache",
".",
"spark",
".",
"sql",
... | Converts a binary column of avro format into its corresponding catalyst value. The specified
schema must match the read data, otherwise the behavior is undefined: it may fail or return
arbitrary result.
Note: Avro is built-in but external data source module since Spark 2.4. Please deploy the
applicatio... | [
"Converts",
"a",
"binary",
"column",
"of",
"avro",
"format",
"into",
"its",
"corresponding",
"catalyst",
"value",
".",
"The",
"specified",
"schema",
"must",
"match",
"the",
"read",
"data",
"otherwise",
"the",
"behavior",
"is",
"undefined",
":",
"it",
"may",
... | python | train | 48 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.