repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
tnkteja/myhelp | virtualEnvironment/lib/python2.7/site-packages/coverage/data.py | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/data.py#L213-L220 | def add_arc_data(self, arc_data):
"""Add measured arc data.
`arc_data` is { filename: { (l1,l2): None, ... }, ...}
"""
for filename, arcs in iitems(arc_data):
self.arcs.setdefault(filename, {}).update(arcs) | [
"def",
"add_arc_data",
"(",
"self",
",",
"arc_data",
")",
":",
"for",
"filename",
",",
"arcs",
"in",
"iitems",
"(",
"arc_data",
")",
":",
"self",
".",
"arcs",
".",
"setdefault",
"(",
"filename",
",",
"{",
"}",
")",
".",
"update",
"(",
"arcs",
")"
] | Add measured arc data.
`arc_data` is { filename: { (l1,l2): None, ... }, ...} | [
"Add",
"measured",
"arc",
"data",
"."
] | python | test |
PMBio/limix-backup | limix/varDecomp/varianceDecomposition.py | https://github.com/PMBio/limix-backup/blob/1e201fdb5c694d0d5506f207f3de65d8ef66146c/limix/varDecomp/varianceDecomposition.py#L900-L915 | def _getScalesRand(self):
"""
Internal function for parameter initialization
Return a vector of random scales
"""
if self.P>1:
scales = []
for term_i in range(self.n_randEffs):
_scales = sp.randn(self.diag[term_i].shape[0])
... | [
"def",
"_getScalesRand",
"(",
"self",
")",
":",
"if",
"self",
".",
"P",
">",
"1",
":",
"scales",
"=",
"[",
"]",
"for",
"term_i",
"in",
"range",
"(",
"self",
".",
"n_randEffs",
")",
":",
"_scales",
"=",
"sp",
".",
"randn",
"(",
"self",
".",
"diag"... | Internal function for parameter initialization
Return a vector of random scales | [
"Internal",
"function",
"for",
"parameter",
"initialization",
"Return",
"a",
"vector",
"of",
"random",
"scales"
] | python | train |
mathiasertl/django-ca | ca/django_ca/models.py | https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/models.py#L306-L308 | def subject(self):
"""The certificates subject as :py:class:`~django_ca.subject.Subject`."""
return Subject([(s.oid, s.value) for s in self.x509.subject]) | [
"def",
"subject",
"(",
"self",
")",
":",
"return",
"Subject",
"(",
"[",
"(",
"s",
".",
"oid",
",",
"s",
".",
"value",
")",
"for",
"s",
"in",
"self",
".",
"x509",
".",
"subject",
"]",
")"
] | The certificates subject as :py:class:`~django_ca.subject.Subject`. | [
"The",
"certificates",
"subject",
"as",
":",
"py",
":",
"class",
":",
"~django_ca",
".",
"subject",
".",
"Subject",
"."
] | python | train |
ThreatConnect-Inc/tcex | tcex/tcex_resources.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_resources.py#L524-L547 | def copy(self):
"""Return a "clean" copy of this instance.
Return:
(instance): A clean copy of this instance.
"""
resource = copy.copy(self)
# workaround for bytes/str issue in Py3 with copy of instance
# TypeError: a bytes-like object is required, not 'str'... | [
"def",
"copy",
"(",
"self",
")",
":",
"resource",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"# workaround for bytes/str issue in Py3 with copy of instance",
"# TypeError: a bytes-like object is required, not 'str' (ssl.py)",
"resource",
".",
"_request",
"=",
"self",
".",
... | Return a "clean" copy of this instance.
Return:
(instance): A clean copy of this instance. | [
"Return",
"a",
"clean",
"copy",
"of",
"this",
"instance",
"."
] | python | train |
loganasherjones/yapconf | yapconf/spec.py | https://github.com/loganasherjones/yapconf/blob/d2970e6e7e3334615d4d978d8b0ca33006d79d16/yapconf/spec.py#L329-L357 | def spawn_watcher(self, label, target=None, eternal=False):
"""Spawns a config watcher in a separate daemon thread.
If a particular config value changes, and the item has a
``watch_target`` defined, then that method will be called.
If a ``target`` is passed in, then it will call the ``... | [
"def",
"spawn_watcher",
"(",
"self",
",",
"label",
",",
"target",
"=",
"None",
",",
"eternal",
"=",
"False",
")",
":",
"if",
"label",
"not",
"in",
"self",
".",
"_sources",
":",
"raise",
"YapconfSourceError",
"(",
"'Cannot watch %s no source named %s'",
"%",
... | Spawns a config watcher in a separate daemon thread.
If a particular config value changes, and the item has a
``watch_target`` defined, then that method will be called.
If a ``target`` is passed in, then it will call the ``target``
anytime the config changes.
Args:
... | [
"Spawns",
"a",
"config",
"watcher",
"in",
"a",
"separate",
"daemon",
"thread",
"."
] | python | train |
fhcrc/taxtastic | taxtastic/refpkg.py | https://github.com/fhcrc/taxtastic/blob/4e874b7f2cc146178828bfba386314f8c342722b/taxtastic/refpkg.py#L227-L231 | def open(self, name, *mode):
"""
Return an open file object for a file in the reference package.
"""
return self.file_factory(self.file_path(name), *mode) | [
"def",
"open",
"(",
"self",
",",
"name",
",",
"*",
"mode",
")",
":",
"return",
"self",
".",
"file_factory",
"(",
"self",
".",
"file_path",
"(",
"name",
")",
",",
"*",
"mode",
")"
] | Return an open file object for a file in the reference package. | [
"Return",
"an",
"open",
"file",
"object",
"for",
"a",
"file",
"in",
"the",
"reference",
"package",
"."
] | python | train |
geophysics-ubonn/crtomo_tools | src/sens_center_plot.py | https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/src/sens_center_plot.py#L293-L328 | def compute_sens(self, elem_file, elec_file, configs):
"""
Compute the sensitivities for the given input data.
A CRMod instance is called to create the sensitivity files.
"""
CRMod_config = CRMod.config()
# activate 2D mode and set sink nr
if self.options.sink is ... | [
"def",
"compute_sens",
"(",
"self",
",",
"elem_file",
",",
"elec_file",
",",
"configs",
")",
":",
"CRMod_config",
"=",
"CRMod",
".",
"config",
"(",
")",
"# activate 2D mode and set sink nr",
"if",
"self",
".",
"options",
".",
"sink",
"is",
"not",
"None",
":"... | Compute the sensitivities for the given input data.
A CRMod instance is called to create the sensitivity files. | [
"Compute",
"the",
"sensitivities",
"for",
"the",
"given",
"input",
"data",
".",
"A",
"CRMod",
"instance",
"is",
"called",
"to",
"create",
"the",
"sensitivity",
"files",
"."
] | python | train |
Nukesor/pueue | pueue/daemon/process_handler.py | https://github.com/Nukesor/pueue/blob/f1d276360454d4dd2738658a13df1e20caa4b926/pueue/daemon/process_handler.py#L226-L238 | def start_process(self, key):
"""Start a specific processes."""
if key in self.processes and key in self.paused:
os.killpg(os.getpgid(self.processes[key].pid), signal.SIGCONT)
self.queue[key]['status'] = 'running'
self.paused.remove(key)
return True
... | [
"def",
"start_process",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"processes",
"and",
"key",
"in",
"self",
".",
"paused",
":",
"os",
".",
"killpg",
"(",
"os",
".",
"getpgid",
"(",
"self",
".",
"processes",
"[",
"key",
"]",
... | Start a specific processes. | [
"Start",
"a",
"specific",
"processes",
"."
] | python | train |
aio-libs/aiodocker | aiodocker/nodes.py | https://github.com/aio-libs/aiodocker/blob/88d0285ddba8e606ff684278e0a831347209189c/aiodocker/nodes.py#L43-L69 | async def update(
self, *, node_id: str, version: int, spec: Mapping[str, Any]
) -> Mapping[str, Any]:
"""
Update the spec of a node.
Args:
node_id: The ID or name of the node
version: version number of the node being updated
spec: fields to be up... | [
"async",
"def",
"update",
"(",
"self",
",",
"*",
",",
"node_id",
":",
"str",
",",
"version",
":",
"int",
",",
"spec",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"params",
"=",
"{",
"\"ve... | Update the spec of a node.
Args:
node_id: The ID or name of the node
version: version number of the node being updated
spec: fields to be updated | [
"Update",
"the",
"spec",
"of",
"a",
"node",
"."
] | python | train |
bids-standard/pybids | bids/layout/layout.py | https://github.com/bids-standard/pybids/blob/30d924ce770622bda0e390d613a8da42a2a20c32/bids/layout/layout.py#L31-L74 | def parse_file_entities(filename, entities=None, config=None,
include_unmatched=False):
""" Parse the passed filename for entity/value pairs.
Args:
filename (str): The filename to parse for entity values
entities (list): An optional list of Entity instances to use in
... | [
"def",
"parse_file_entities",
"(",
"filename",
",",
"entities",
"=",
"None",
",",
"config",
"=",
"None",
",",
"include_unmatched",
"=",
"False",
")",
":",
"# Load Configs if needed",
"if",
"entities",
"is",
"None",
":",
"if",
"config",
"is",
"None",
":",
"co... | Parse the passed filename for entity/value pairs.
Args:
filename (str): The filename to parse for entity values
entities (list): An optional list of Entity instances to use in
extraction. If passed, the config argument is ignored.
config (str, Config, list): One or more Config o... | [
"Parse",
"the",
"passed",
"filename",
"for",
"entity",
"/",
"value",
"pairs",
"."
] | python | train |
gamechanger/mongothon | mongothon/model.py | https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/model.py#L267-L270 | def static_method(cls, f):
"""Decorator which dynamically binds static methods to the model for later use."""
setattr(cls, f.__name__, staticmethod(f))
return f | [
"def",
"static_method",
"(",
"cls",
",",
"f",
")",
":",
"setattr",
"(",
"cls",
",",
"f",
".",
"__name__",
",",
"staticmethod",
"(",
"f",
")",
")",
"return",
"f"
] | Decorator which dynamically binds static methods to the model for later use. | [
"Decorator",
"which",
"dynamically",
"binds",
"static",
"methods",
"to",
"the",
"model",
"for",
"later",
"use",
"."
] | python | train |
rikrd/inspire | inspirespeech/__init__.py | https://github.com/rikrd/inspire/blob/e281c0266a9a9633f34ab70f9c3ad58036c19b59/inspirespeech/__init__.py#L325-L371 | def what_task(self, token_id, presented_pronunciation, index, phonemes, phonemes_probability,
warn=True, default=True):
"""Provide the prediction of the what task.
This function is used to predict the probability of a given phoneme being reported at a given index
for a given t... | [
"def",
"what_task",
"(",
"self",
",",
"token_id",
",",
"presented_pronunciation",
",",
"index",
",",
"phonemes",
",",
"phonemes_probability",
",",
"warn",
"=",
"True",
",",
"default",
"=",
"True",
")",
":",
"if",
"phonemes_probability",
"is",
"not",
"None",
... | Provide the prediction of the what task.
This function is used to predict the probability of a given phoneme being reported at a given index
for a given token.
:param token_id: The token for which the prediction is provided
:param index: The index of the token for which the prediction ... | [
"Provide",
"the",
"prediction",
"of",
"the",
"what",
"task",
"."
] | python | train |
trailofbits/manticore | manticore/native/cpu/x86.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L4632-L4650 | def PXOR(cpu, dest, src):
"""
Logical exclusive OR.
Performs a bitwise logical exclusive-OR (XOR) operation on the quadword
source (second) and destination (first) operands and stores the result
in the destination operand location. The source operand can be an MMX(TM)
te... | [
"def",
"PXOR",
"(",
"cpu",
",",
"dest",
",",
"src",
")",
":",
"res",
"=",
"dest",
".",
"write",
"(",
"dest",
".",
"read",
"(",
")",
"^",
"src",
".",
"read",
"(",
")",
")"
] | Logical exclusive OR.
Performs a bitwise logical exclusive-OR (XOR) operation on the quadword
source (second) and destination (first) operands and stores the result
in the destination operand location. The source operand can be an MMX(TM)
technology register or a quadword memory locatio... | [
"Logical",
"exclusive",
"OR",
"."
] | python | valid |
wal-e/wal-e | wal_e/worker/upload_pool.py | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/upload_pool.py#L56-L69 | def _wait(self):
"""Block until an upload finishes
Raise an exception if that tar volume failed with an error.
"""
val = self.wait_change.get()
if isinstance(val, Exception):
# Don't other uncharging, because execution is going to stop
raise val
... | [
"def",
"_wait",
"(",
"self",
")",
":",
"val",
"=",
"self",
".",
"wait_change",
".",
"get",
"(",
")",
"if",
"isinstance",
"(",
"val",
",",
"Exception",
")",
":",
"# Don't other uncharging, because execution is going to stop",
"raise",
"val",
"else",
":",
"# Unc... | Block until an upload finishes
Raise an exception if that tar volume failed with an error. | [
"Block",
"until",
"an",
"upload",
"finishes"
] | python | train |
lemieuxl/pyGenClean | pyGenClean/DupSNPs/duplicated_snps.py | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/DupSNPs/duplicated_snps.py#L727-L930 | def printProblems(completion, concordance, tped, snps, frequencies, prefix,
diffFreq):
"""Print the statistics.
:param completion: the completion of each duplicated markers.
:param concordance: the pairwise concordance between duplicated markers.
:param tped: a representation of the `... | [
"def",
"printProblems",
"(",
"completion",
",",
"concordance",
",",
"tped",
",",
"snps",
",",
"frequencies",
",",
"prefix",
",",
"diffFreq",
")",
":",
"completionPercentage",
"=",
"np",
".",
"true_divide",
"(",
"completion",
"[",
"0",
"]",
",",
"completion",... | Print the statistics.
:param completion: the completion of each duplicated markers.
:param concordance: the pairwise concordance between duplicated markers.
:param tped: a representation of the ``tped`` of duplicated markers.
:param snps: the positions of the duplicated markers in the ``tped``
:par... | [
"Print",
"the",
"statistics",
"."
] | python | train |
mitsei/dlkit | dlkit/services/relationship.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/relationship.py#L905-L913 | def use_comparative_relationship_view(self):
"""Pass through to provider RelationshipLookupSession.use_comparative_relationship_view"""
self._object_views['relationship'] = COMPARATIVE
# self._get_provider_session('relationship_lookup_session') # To make sure the session is tracked
for s... | [
"def",
"use_comparative_relationship_view",
"(",
"self",
")",
":",
"self",
".",
"_object_views",
"[",
"'relationship'",
"]",
"=",
"COMPARATIVE",
"# self._get_provider_session('relationship_lookup_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
... | Pass through to provider RelationshipLookupSession.use_comparative_relationship_view | [
"Pass",
"through",
"to",
"provider",
"RelationshipLookupSession",
".",
"use_comparative_relationship_view"
] | python | train |
OpenTreeOfLife/peyotl | peyotl/utility/get_config.py | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/utility/get_config.py#L315-L324 | def get_config_object():
"""Thread-safe accessor for the immutable default ConfigWrapper object"""
global _DEFAULT_CONFIG_WRAPPER
if _DEFAULT_CONFIG_WRAPPER is not None:
return _DEFAULT_CONFIG_WRAPPER
with _DEFAULT_CONFIG_WRAPPER_LOCK:
if _DEFAULT_CONFIG_WRAPPER is not None:
... | [
"def",
"get_config_object",
"(",
")",
":",
"global",
"_DEFAULT_CONFIG_WRAPPER",
"if",
"_DEFAULT_CONFIG_WRAPPER",
"is",
"not",
"None",
":",
"return",
"_DEFAULT_CONFIG_WRAPPER",
"with",
"_DEFAULT_CONFIG_WRAPPER_LOCK",
":",
"if",
"_DEFAULT_CONFIG_WRAPPER",
"is",
"not",
"None... | Thread-safe accessor for the immutable default ConfigWrapper object | [
"Thread",
"-",
"safe",
"accessor",
"for",
"the",
"immutable",
"default",
"ConfigWrapper",
"object"
] | python | train |
lsst-sqre/ltd-conveyor | ltdconveyor/keeper/build.py | https://github.com/lsst-sqre/ltd-conveyor/blob/c492937c4c1e050ccc4a0b9dcc38f9980d57e305/ltdconveyor/keeper/build.py#L60-L87 | def confirm_build(build_url, keeper_token):
"""Confirm a build upload is complete.
Wraps ``PATCH /builds/{build}``.
Parameters
----------
build_url : `str`
URL of the build resource. Given a build resource, this URL is
available from the ``self_url`` field.
keeper_token : `str`... | [
"def",
"confirm_build",
"(",
"build_url",
",",
"keeper_token",
")",
":",
"data",
"=",
"{",
"'uploaded'",
":",
"True",
"}",
"r",
"=",
"requests",
".",
"patch",
"(",
"build_url",
",",
"auth",
"=",
"(",
"keeper_token",
",",
"''",
")",
",",
"json",
"=",
... | Confirm a build upload is complete.
Wraps ``PATCH /builds/{build}``.
Parameters
----------
build_url : `str`
URL of the build resource. Given a build resource, this URL is
available from the ``self_url`` field.
keeper_token : `str`
Auth token (`ltdconveyor.keeper.get_keeper... | [
"Confirm",
"a",
"build",
"upload",
"is",
"complete",
"."
] | python | test |
myaooo/pysbrl | pysbrl/train.py | https://github.com/myaooo/pysbrl/blob/74bba8c6913a7f82e32313108f8c3e025b89d9c7/pysbrl/train.py#L11-L46 | def train_sbrl(data_file, label_file, lambda_=20, eta=2, max_iters=300000, n_chains=20, alpha=1, seed=None, verbose=0):
"""
The basic training function of the scalable bayesian rule list.
Users are suggested to use SBRL instead of this function.
It takes the paths of the pre-processed data and label fil... | [
"def",
"train_sbrl",
"(",
"data_file",
",",
"label_file",
",",
"lambda_",
"=",
"20",
",",
"eta",
"=",
"2",
",",
"max_iters",
"=",
"300000",
",",
"n_chains",
"=",
"20",
",",
"alpha",
"=",
"1",
",",
"seed",
"=",
"None",
",",
"verbose",
"=",
"0",
")",... | The basic training function of the scalable bayesian rule list.
Users are suggested to use SBRL instead of this function.
It takes the paths of the pre-processed data and label files as input,
and return the parameters of the trained rule list.
Check pysbrl.utils:categorical2pysbrl_data to see how to c... | [
"The",
"basic",
"training",
"function",
"of",
"the",
"scalable",
"bayesian",
"rule",
"list",
".",
"Users",
"are",
"suggested",
"to",
"use",
"SBRL",
"instead",
"of",
"this",
"function",
".",
"It",
"takes",
"the",
"paths",
"of",
"the",
"pre",
"-",
"processed... | python | train |
numat/midas | midas/util.py | https://github.com/numat/midas/blob/c3a97a6cd67df1283831c3c78bf3f984212e97a8/midas/util.py#L36-L43 | async def _connect(self):
"""Start asynchronous reconnect loop."""
self.waiting = True
await self.client.start(self.ip)
self.waiting = False
if self.client.protocol is None:
raise IOError("Could not connect to '{}'.".format(self.ip))
self.open = True | [
"async",
"def",
"_connect",
"(",
"self",
")",
":",
"self",
".",
"waiting",
"=",
"True",
"await",
"self",
".",
"client",
".",
"start",
"(",
"self",
".",
"ip",
")",
"self",
".",
"waiting",
"=",
"False",
"if",
"self",
".",
"client",
".",
"protocol",
"... | Start asynchronous reconnect loop. | [
"Start",
"asynchronous",
"reconnect",
"loop",
"."
] | python | train |
monarch-initiative/dipper | dipper/utils/CurieUtil.py | https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/utils/CurieUtil.py#L46-L60 | def get_uri(self, curie):
''' Get a URI from a CURIE '''
if curie is None:
return None
parts = curie.split(':')
if len(parts) == 1:
if curie != '':
LOG.error("Not a properly formed curie: \"%s\"", curie)
return None
prefix = par... | [
"def",
"get_uri",
"(",
"self",
",",
"curie",
")",
":",
"if",
"curie",
"is",
"None",
":",
"return",
"None",
"parts",
"=",
"curie",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
":",
"if",
"curie",
"!=",
"''",
":",
"LO... | Get a URI from a CURIE | [
"Get",
"a",
"URI",
"from",
"a",
"CURIE"
] | python | train |
mfussenegger/cr8 | cr8/clients.py | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/clients.py#L146-L176 | def _to_dsn(hosts):
"""Convert a host URI into a dsn for aiopg.
>>> _to_dsn('aiopg://myhostname:4242/mydb')
'postgres://crate@myhostname:4242/mydb'
>>> _to_dsn('aiopg://myhostname:4242')
'postgres://crate@myhostname:4242/doc'
>>> _to_dsn('aiopg://hoschi:pw@myhostname:4242/doc?sslmode=require'... | [
"def",
"_to_dsn",
"(",
"hosts",
")",
":",
"p",
"=",
"urlparse",
"(",
"hosts",
")",
"try",
":",
"user_and_pw",
",",
"netloc",
"=",
"p",
".",
"netloc",
".",
"split",
"(",
"'@'",
",",
"maxsplit",
"=",
"1",
")",
"except",
"ValueError",
":",
"netloc",
"... | Convert a host URI into a dsn for aiopg.
>>> _to_dsn('aiopg://myhostname:4242/mydb')
'postgres://crate@myhostname:4242/mydb'
>>> _to_dsn('aiopg://myhostname:4242')
'postgres://crate@myhostname:4242/doc'
>>> _to_dsn('aiopg://hoschi:pw@myhostname:4242/doc?sslmode=require')
'postgres://hoschi:pw... | [
"Convert",
"a",
"host",
"URI",
"into",
"a",
"dsn",
"for",
"aiopg",
"."
] | python | train |
clalancette/pycdlib | pycdlib/pycdlib.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/pycdlib.py#L1887-L1907 | def _add_to_ptr_size(self, ptr):
# type: (path_table_record.PathTableRecord) -> int
'''
An internal method to add a PTR to a VD, adding space to the VD if
necessary.
Parameters:
ptr - The PTR to add to the vd.
Returns:
The number of additional bytes tha... | [
"def",
"_add_to_ptr_size",
"(",
"self",
",",
"ptr",
")",
":",
"# type: (path_table_record.PathTableRecord) -> int",
"num_bytes_to_add",
"=",
"0",
"for",
"pvd",
"in",
"self",
".",
"pvds",
":",
"# The add_to_ptr_size() method returns True if the PVD needs",
"# additional space ... | An internal method to add a PTR to a VD, adding space to the VD if
necessary.
Parameters:
ptr - The PTR to add to the vd.
Returns:
The number of additional bytes that are needed to fit the new PTR
(this may be zero). | [
"An",
"internal",
"method",
"to",
"add",
"a",
"PTR",
"to",
"a",
"VD",
"adding",
"space",
"to",
"the",
"VD",
"if",
"necessary",
"."
] | python | train |
pantsbuild/pants | src/python/pants/task/scm_publish_mixin.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/task/scm_publish_mixin.py#L212-L221 | def publish_pushdb_changes_to_remote_scm(self, pushdb_file, coordinate, tag_name, tag_message,
postscript=None):
"""Push pushdb changes to the remote scm repository, and then tag the commit if it succeeds."""
self._add_pushdb(pushdb_file)
self.commit_pushdb(coordi... | [
"def",
"publish_pushdb_changes_to_remote_scm",
"(",
"self",
",",
"pushdb_file",
",",
"coordinate",
",",
"tag_name",
",",
"tag_message",
",",
"postscript",
"=",
"None",
")",
":",
"self",
".",
"_add_pushdb",
"(",
"pushdb_file",
")",
"self",
".",
"commit_pushdb",
"... | Push pushdb changes to the remote scm repository, and then tag the commit if it succeeds. | [
"Push",
"pushdb",
"changes",
"to",
"the",
"remote",
"scm",
"repository",
"and",
"then",
"tag",
"the",
"commit",
"if",
"it",
"succeeds",
"."
] | python | train |
balloob/pychromecast | pychromecast/socket_client.py | https://github.com/balloob/pychromecast/blob/831b09c4fed185a7bffe0ea330b7849d5f4e36b6/pychromecast/socket_client.py#L550-L584 | def _route_message(self, message, data):
""" Route message to any handlers on the message namespace """
# route message to handlers
if message.namespace in self._handlers:
# debug messages
if message.namespace != NS_HEARTBEAT:
self.logger.debug(
... | [
"def",
"_route_message",
"(",
"self",
",",
"message",
",",
"data",
")",
":",
"# route message to handlers",
"if",
"message",
".",
"namespace",
"in",
"self",
".",
"_handlers",
":",
"# debug messages",
"if",
"message",
".",
"namespace",
"!=",
"NS_HEARTBEAT",
":",
... | Route message to any handlers on the message namespace | [
"Route",
"message",
"to",
"any",
"handlers",
"on",
"the",
"message",
"namespace"
] | python | train |
underworldcode/stripy | stripy-src/stripy/cartesian.py | https://github.com/underworldcode/stripy/blob/d4c3480c3e58c88489ded695eadbe7cd5bf94b48/stripy-src/stripy/cartesian.py#L507-L575 | def interpolate_cubic(self, xi, yi, zdata, gradz=None, derivatives=False):
"""
Cubic spline interpolation/extrapolation to arbirary point(s).
This method has C^1 continuity.
Parameters
----------
xi : float / array of floats, shape (l,)
x coordinates on the ... | [
"def",
"interpolate_cubic",
"(",
"self",
",",
"xi",
",",
"yi",
",",
"zdata",
",",
"gradz",
"=",
"None",
",",
"derivatives",
"=",
"False",
")",
":",
"if",
"zdata",
".",
"size",
"!=",
"self",
".",
"npoints",
":",
"raise",
"ValueError",
"(",
"'zdata shoul... | Cubic spline interpolation/extrapolation to arbirary point(s).
This method has C^1 continuity.
Parameters
----------
xi : float / array of floats, shape (l,)
x coordinates on the Cartesian plane
yi : float / array of floats, shape (l,)
y coordinates on ... | [
"Cubic",
"spline",
"interpolation",
"/",
"extrapolation",
"to",
"arbirary",
"point",
"(",
"s",
")",
".",
"This",
"method",
"has",
"C^1",
"continuity",
"."
] | python | train |
IDSIA/sacred | sacred/experiment.py | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/experiment.py#L408-L418 | def _gather(self, func):
"""
Removes the experiment's path (prefix) from the names of the gathered
items. This means that, for example, 'experiment.print_config' becomes
'print_config'.
"""
for ingredient, _ in self.traverse_ingredients():
for name, item in fu... | [
"def",
"_gather",
"(",
"self",
",",
"func",
")",
":",
"for",
"ingredient",
",",
"_",
"in",
"self",
".",
"traverse_ingredients",
"(",
")",
":",
"for",
"name",
",",
"item",
"in",
"func",
"(",
"ingredient",
")",
":",
"if",
"ingredient",
"==",
"self",
":... | Removes the experiment's path (prefix) from the names of the gathered
items. This means that, for example, 'experiment.print_config' becomes
'print_config'. | [
"Removes",
"the",
"experiment",
"s",
"path",
"(",
"prefix",
")",
"from",
"the",
"names",
"of",
"the",
"gathered",
"items",
".",
"This",
"means",
"that",
"for",
"example",
"experiment",
".",
"print_config",
"becomes",
"print_config",
"."
] | python | train |
Skype4Py/Skype4Py | Skype4Py/skype.py | https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/skype.py#L588-L600 | def CreateSms(self, MessageType, *TargetNumbers):
"""Creates an SMS message.
:Parameters:
MessageType : `enums`.smsMessageType*
Message type.
TargetNumbers : str
One or more target SMS numbers.
:return: An sms message object.
:rtype: `SmsMess... | [
"def",
"CreateSms",
"(",
"self",
",",
"MessageType",
",",
"*",
"TargetNumbers",
")",
":",
"return",
"SmsMessage",
"(",
"self",
",",
"chop",
"(",
"self",
".",
"_DoCommand",
"(",
"'CREATE SMS %s %s'",
"%",
"(",
"MessageType",
",",
"', '",
".",
"join",
"(",
... | Creates an SMS message.
:Parameters:
MessageType : `enums`.smsMessageType*
Message type.
TargetNumbers : str
One or more target SMS numbers.
:return: An sms message object.
:rtype: `SmsMessage` | [
"Creates",
"an",
"SMS",
"message",
"."
] | python | train |
dh1tw/pyhamtools | pyhamtools/callinfo.py | https://github.com/dh1tw/pyhamtools/blob/ee7e4b8732e23c298da10e07163748156c16d0fa/pyhamtools/callinfo.py#L341-L376 | def get_lat_long(self, callsign, timestamp=timestamp_now):
""" Returns Latitude and Longitude for a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
dict: Containing Latitude and... | [
"def",
"get_lat_long",
"(",
"self",
",",
"callsign",
",",
"timestamp",
"=",
"timestamp_now",
")",
":",
"callsign_data",
"=",
"self",
".",
"get_all",
"(",
"callsign",
",",
"timestamp",
"=",
"timestamp",
")",
"return",
"{",
"const",
".",
"LATITUDE",
":",
"ca... | Returns Latitude and Longitude for a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
dict: Containing Latitude and Longitude
Raises:
KeyError: No data found for cal... | [
"Returns",
"Latitude",
"and",
"Longitude",
"for",
"a",
"callsign"
] | python | train |
daskol/nls | nls/animation.py | https://github.com/daskol/nls/blob/00bb4555e4f56e222dc6f54faf2e286567519626/nls/animation.py#L30-L41 | def render(self, filename):
"""Perform initialization of render, set quality and size video attributes and then call template method that
is defined in child class.
"""
self.elapsed_time = -time()
dpi = 100
fig = figure(figsize=(16, 9), dpi=dpi)
with self.writer.s... | [
"def",
"render",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"elapsed_time",
"=",
"-",
"time",
"(",
")",
"dpi",
"=",
"100",
"fig",
"=",
"figure",
"(",
"figsize",
"=",
"(",
"16",
",",
"9",
")",
",",
"dpi",
"=",
"dpi",
")",
"with",
"self... | Perform initialization of render, set quality and size video attributes and then call template method that
is defined in child class. | [
"Perform",
"initialization",
"of",
"render",
"set",
"quality",
"and",
"size",
"video",
"attributes",
"and",
"then",
"call",
"template",
"method",
"that",
"is",
"defined",
"in",
"child",
"class",
"."
] | python | train |
wreckage/django-happenings | happenings/utils/calendars.py | https://github.com/wreckage/django-happenings/blob/7bca5576efa6cd4c4e87356bf9e5b8cd538ae91d/happenings/utils/calendars.py#L380-L398 | def formatday(self, day, weekday):
"""Return a day as a table cell."""
super(MiniEventCalendar, self).formatday(day, weekday)
now = get_now()
self.day = day
if day == 0:
return '<td class="noday"> </td>' # day outside month
elif now.month == self.mo and... | [
"def",
"formatday",
"(",
"self",
",",
"day",
",",
"weekday",
")",
":",
"super",
"(",
"MiniEventCalendar",
",",
"self",
")",
".",
"formatday",
"(",
"day",
",",
"weekday",
")",
"now",
"=",
"get_now",
"(",
")",
"self",
".",
"day",
"=",
"day",
"if",
"d... | Return a day as a table cell. | [
"Return",
"a",
"day",
"as",
"a",
"table",
"cell",
"."
] | python | test |
flowersteam/explauto | explauto/models/pydmps/dmp_rhythmic.py | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/pydmps/dmp_rhythmic.py#L61-L75 | def gen_goal(self, y_des):
"""Generate the goal for path imitation.
For rhythmic DMPs the goal is the average of the
desired trajectory.
y_des np.array: the desired trajectory to follow
"""
goal = np.zeros(self.dmps)
for n in range(self.dmps):
... | [
"def",
"gen_goal",
"(",
"self",
",",
"y_des",
")",
":",
"goal",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"dmps",
")",
"for",
"n",
"in",
"range",
"(",
"self",
".",
"dmps",
")",
":",
"num_idx",
"=",
"~",
"np",
".",
"isnan",
"(",
"y_des",
"[",
... | Generate the goal for path imitation.
For rhythmic DMPs the goal is the average of the
desired trajectory.
y_des np.array: the desired trajectory to follow | [
"Generate",
"the",
"goal",
"for",
"path",
"imitation",
".",
"For",
"rhythmic",
"DMPs",
"the",
"goal",
"is",
"the",
"average",
"of",
"the",
"desired",
"trajectory",
".",
"y_des",
"np",
".",
"array",
":",
"the",
"desired",
"trajectory",
"to",
"follow"
] | python | train |
ampl/amplpy | amplpy/ampl.py | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/ampl.py#L710-L729 | def setOutputHandler(self, outputhandler):
"""
Sets a new output handler.
Args:
outputhandler: The function handling the AMPL output derived from
interpreting user commands.
"""
class OutputHandlerInternal(amplpython.OutputHandler):
def output... | [
"def",
"setOutputHandler",
"(",
"self",
",",
"outputhandler",
")",
":",
"class",
"OutputHandlerInternal",
"(",
"amplpython",
".",
"OutputHandler",
")",
":",
"def",
"output",
"(",
"self",
",",
"kind",
",",
"msg",
")",
":",
"outputhandler",
".",
"output",
"(",... | Sets a new output handler.
Args:
outputhandler: The function handling the AMPL output derived from
interpreting user commands. | [
"Sets",
"a",
"new",
"output",
"handler",
"."
] | python | train |
CivicSpleen/ambry | ambry/orm/source.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/source.py#L271-L310 | def update_table(self, unknown_type='str'):
"""Update the source table from the datafile"""
from ambry_sources.intuit import TypeIntuiter
st = self.source_table
if self.reftype == 'partition':
for c in self.partition.table.columns:
st.add_column(c.sequence_i... | [
"def",
"update_table",
"(",
"self",
",",
"unknown_type",
"=",
"'str'",
")",
":",
"from",
"ambry_sources",
".",
"intuit",
"import",
"TypeIntuiter",
"st",
"=",
"self",
".",
"source_table",
"if",
"self",
".",
"reftype",
"==",
"'partition'",
":",
"for",
"c",
"... | Update the source table from the datafile | [
"Update",
"the",
"source",
"table",
"from",
"the",
"datafile"
] | python | train |
coldfix/udiskie | udiskie/tray.py | https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/tray.py#L337-L342 | def _create_statusicon(self):
"""Return a new Gtk.StatusIcon."""
statusicon = Gtk.StatusIcon()
statusicon.set_from_gicon(self._icons.get_gicon('media'))
statusicon.set_tooltip_text(_("udiskie"))
return statusicon | [
"def",
"_create_statusicon",
"(",
"self",
")",
":",
"statusicon",
"=",
"Gtk",
".",
"StatusIcon",
"(",
")",
"statusicon",
".",
"set_from_gicon",
"(",
"self",
".",
"_icons",
".",
"get_gicon",
"(",
"'media'",
")",
")",
"statusicon",
".",
"set_tooltip_text",
"("... | Return a new Gtk.StatusIcon. | [
"Return",
"a",
"new",
"Gtk",
".",
"StatusIcon",
"."
] | python | train |
saltstack/salt | salt/modules/netbsd_sysctl.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbsd_sysctl.py#L30-L66 | def show(config_file=False):
'''
Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show
'''
roots = (
'kern',
'vm',
'vfs',
'net',
'hw',
'machdep',
'user',
'ddb',
... | [
"def",
"show",
"(",
"config_file",
"=",
"False",
")",
":",
"roots",
"=",
"(",
"'kern'",
",",
"'vm'",
",",
"'vfs'",
",",
"'net'",
",",
"'hw'",
",",
"'machdep'",
",",
"'user'",
",",
"'ddb'",
",",
"'proc'",
",",
"'emul'",
",",
"'security'",
",",
"'init'... | Return a list of sysctl parameters for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.show | [
"Return",
"a",
"list",
"of",
"sysctl",
"parameters",
"for",
"this",
"minion"
] | python | train |
moonso/vcf_parser | vcf_parser/header_parser.py | https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/header_parser.py#L238-L254 | def add_info(self, info_id, number, entry_type, description):
"""
Add an info line to the header.
Arguments:
info_id (str): The id of the info line
number (str): Integer or any of [A,R,G,.]
entry_type (str): Any of [Integer,Float,Flag,Character,String... | [
"def",
"add_info",
"(",
"self",
",",
"info_id",
",",
"number",
",",
"entry_type",
",",
"description",
")",
":",
"info_line",
"=",
"'##INFO=<ID={0},Number={1},Type={2},Description=\"{3}\">'",
".",
"format",
"(",
"info_id",
",",
"number",
",",
"entry_type",
",",
"de... | Add an info line to the header.
Arguments:
info_id (str): The id of the info line
number (str): Integer or any of [A,R,G,.]
entry_type (str): Any of [Integer,Float,Flag,Character,String]
description (str): A description of the info line | [
"Add",
"an",
"info",
"line",
"to",
"the",
"header",
".",
"Arguments",
":",
"info_id",
"(",
"str",
")",
":",
"The",
"id",
"of",
"the",
"info",
"line",
"number",
"(",
"str",
")",
":",
"Integer",
"or",
"any",
"of",
"[",
"A",
"R",
"G",
".",
"]",
"e... | python | train |
IdentityPython/SATOSA | src/satosa/frontends/saml2.py | https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L439-L464 | def _register_endpoints(self, providers):
"""
Register methods to endpoints
:type providers: list[str]
:rtype: list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))]
:param providers: A list of backend providers
:return: A list of endpoint/method pa... | [
"def",
"_register_endpoints",
"(",
"self",
",",
"providers",
")",
":",
"url_map",
"=",
"[",
"]",
"for",
"endp_category",
"in",
"self",
".",
"endpoints",
":",
"for",
"binding",
",",
"endp",
"in",
"self",
".",
"endpoints",
"[",
"endp_category",
"]",
".",
"... | Register methods to endpoints
:type providers: list[str]
:rtype: list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))]
:param providers: A list of backend providers
:return: A list of endpoint/method pairs | [
"Register",
"methods",
"to",
"endpoints",
":",
"type",
"providers",
":",
"list",
"[",
"str",
"]",
":",
"rtype",
":",
"list",
"[",
"(",
"str",
"((",
"satosa",
".",
"context",
".",
"Context",
"Any",
")",
"-",
">",
"satosa",
".",
"response",
".",
"Respo... | python | train |
talkincode/txradius | txradius/radius/packet.py | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/radius/packet.py#L564-L571 | def CreateReply(self, **attributes):
"""Create a new packet as a reply to this one. This method
makes sure the authenticator and secret are copied over
to the new instance.
"""
return CoAPacket(CoAACK, self.id,
self.secret, self.authenticator, dict=self.dict,
... | [
"def",
"CreateReply",
"(",
"self",
",",
"*",
"*",
"attributes",
")",
":",
"return",
"CoAPacket",
"(",
"CoAACK",
",",
"self",
".",
"id",
",",
"self",
".",
"secret",
",",
"self",
".",
"authenticator",
",",
"dict",
"=",
"self",
".",
"dict",
",",
"*",
... | Create a new packet as a reply to this one. This method
makes sure the authenticator and secret are copied over
to the new instance. | [
"Create",
"a",
"new",
"packet",
"as",
"a",
"reply",
"to",
"this",
"one",
".",
"This",
"method",
"makes",
"sure",
"the",
"authenticator",
"and",
"secret",
"are",
"copied",
"over",
"to",
"the",
"new",
"instance",
"."
] | python | train |
mitsei/dlkit | dlkit/records/assessment/qti/ordered_choice_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/assessment/qti/ordered_choice_records.py#L40-L45 | def is_response_correct(self, response):
"""returns True if response evaluates to an Item Answer that is 100 percent correct"""
for answer in self.my_osid_object.get_answers():
if self._is_match(response, answer):
return True
return False | [
"def",
"is_response_correct",
"(",
"self",
",",
"response",
")",
":",
"for",
"answer",
"in",
"self",
".",
"my_osid_object",
".",
"get_answers",
"(",
")",
":",
"if",
"self",
".",
"_is_match",
"(",
"response",
",",
"answer",
")",
":",
"return",
"True",
"re... | returns True if response evaluates to an Item Answer that is 100 percent correct | [
"returns",
"True",
"if",
"response",
"evaluates",
"to",
"an",
"Item",
"Answer",
"that",
"is",
"100",
"percent",
"correct"
] | python | train |
PagerDuty/pagerduty-api-python-client | pypd/models/notification.py | https://github.com/PagerDuty/pagerduty-api-python-client/blob/f420b34ca9b29689cc2ecc9adca6dc5d56ae7161/pypd/models/notification.py#L14-L46 | def find(cls, *args, **kwargs):
"""
Find notifications.
Optional kwargs are:
since:
datetime instance
until:
datetime instance
If not specified, until will default to now(), and since will default
to 30 days prior to until... | [
"def",
"find",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"seconds",
"=",
"60",
"*",
"60",
"*",
"24",
"*",
"30",
"# seconds in 30 days",
"until",
"=",
"kwargs",
".",
"pop",
"(",
"'until'",
",",
"None",
")",
"since",
"=",
"kw... | Find notifications.
Optional kwargs are:
since:
datetime instance
until:
datetime instance
If not specified, until will default to now(), and since will default
to 30 days prior to until.
As per PD spec, date range must not excee... | [
"Find",
"notifications",
"."
] | python | train |
ucbvislab/radiotool | radiotool/composer/composition.py | https://github.com/ucbvislab/radiotool/blob/01c9d878a811cf400b1482896d641d9c95e83ded/radiotool/composer/composition.py#L98-L105 | def add_segments(self, segments):
"""Add a list of segments to the composition
:param segments: Segments to add to composition
:type segments: list of :py:class:`radiotool.composer.Segment`
"""
self.tracks.update([seg.track for seg in segments])
self.segments.extend(segm... | [
"def",
"add_segments",
"(",
"self",
",",
"segments",
")",
":",
"self",
".",
"tracks",
".",
"update",
"(",
"[",
"seg",
".",
"track",
"for",
"seg",
"in",
"segments",
"]",
")",
"self",
".",
"segments",
".",
"extend",
"(",
"segments",
")"
] | Add a list of segments to the composition
:param segments: Segments to add to composition
:type segments: list of :py:class:`radiotool.composer.Segment` | [
"Add",
"a",
"list",
"of",
"segments",
"to",
"the",
"composition"
] | python | train |
Esri/ArcREST | src/arcrest/hostedservice/service.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/hostedservice/service.py#L535-L552 | def refresh(self, serviceDefinition=True):
"""
The refresh operation refreshes a service, which clears the web
server cache for the service.
"""
url = self._url + "/MapServer/refresh"
params = {
"f" : "json",
"serviceDefinition" : serviceDefinition... | [
"def",
"refresh",
"(",
"self",
",",
"serviceDefinition",
"=",
"True",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/MapServer/refresh\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"serviceDefinition\"",
":",
"serviceDefinition",
"}",
"res",
... | The refresh operation refreshes a service, which clears the web
server cache for the service. | [
"The",
"refresh",
"operation",
"refreshes",
"a",
"service",
"which",
"clears",
"the",
"web",
"server",
"cache",
"for",
"the",
"service",
"."
] | python | train |
census-instrumentation/opencensus-python | contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-google-cloud-clientlibs/opencensus/ext/google_cloud_clientlibs/trace.py#L50-L76 | def trace_grpc(tracer=None):
"""Integrate with gRPC."""
# Wrap google.cloud._helpers.make_secure_channel
make_secure_channel_func = getattr(_helpers, MAKE_SECURE_CHANNEL)
make_secure_channel_wrapped = wrap_make_secure_channel(
make_secure_channel_func, tracer)
setattr(
_helpers,
... | [
"def",
"trace_grpc",
"(",
"tracer",
"=",
"None",
")",
":",
"# Wrap google.cloud._helpers.make_secure_channel",
"make_secure_channel_func",
"=",
"getattr",
"(",
"_helpers",
",",
"MAKE_SECURE_CHANNEL",
")",
"make_secure_channel_wrapped",
"=",
"wrap_make_secure_channel",
"(",
... | Integrate with gRPC. | [
"Integrate",
"with",
"gRPC",
"."
] | python | train |
StorjOld/plowshare-wrapper | plowshare/plowshare.py | https://github.com/StorjOld/plowshare-wrapper/blob/edb38d01fd1decabf92cc4f536d7404dca6a977c/plowshare/plowshare.py#L258-L273 | def parse_output(self, hostname, output):
"""Parse plowup's output.
For now, we just return the last line.
:param hostname: Name of host you are working with.
:type hostname: str
:param output: Dictionary containing information about a plowshare
action.
... | [
"def",
"parse_output",
"(",
"self",
",",
"hostname",
",",
"output",
")",
":",
"if",
"isinstance",
"(",
"output",
",",
"bytes",
")",
":",
"output",
"=",
"output",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"output",
".",
"split",
"(",
")",
"[",
"-"... | Parse plowup's output.
For now, we just return the last line.
:param hostname: Name of host you are working with.
:type hostname: str
:param output: Dictionary containing information about a plowshare
action.
:type output: dict
:returns: Parsed an... | [
"Parse",
"plowup",
"s",
"output",
"."
] | python | train |
mila-iqia/fuel | fuel/converters/ilsvrc2010.py | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/converters/ilsvrc2010.py#L390-L426 | def load_from_tar_or_patch(tar, image_filename, patch_images):
"""Do everything necessary to process an image inside a TAR.
Parameters
----------
tar : `TarFile` instance
The tar from which to read `image_filename`.
image_filename : str
Fully-qualified path inside of `tar` from whic... | [
"def",
"load_from_tar_or_patch",
"(",
"tar",
",",
"image_filename",
",",
"patch_images",
")",
":",
"patched",
"=",
"True",
"image_bytes",
"=",
"patch_images",
".",
"get",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"image_filename",
")",
",",
"None",
")",
... | Do everything necessary to process an image inside a TAR.
Parameters
----------
tar : `TarFile` instance
The tar from which to read `image_filename`.
image_filename : str
Fully-qualified path inside of `tar` from which to read an
image file.
patch_images : dict
A dic... | [
"Do",
"everything",
"necessary",
"to",
"process",
"an",
"image",
"inside",
"a",
"TAR",
"."
] | python | train |
apache/incubator-heron | third_party/python/cpplint/cpplint.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L5479-L5498 | def ExpectingFunctionArgs(clean_lines, linenum):
"""Checks whether where function type arguments are expected.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if the line at 'linenum' is inside something that expects arguments
... | [
"def",
"ExpectingFunctionArgs",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"return",
"(",
"Match",
"(",
"r'^\\s*MOCK_(CONST_)?METHOD\\d+(_T)?\\('",
",",
"line",
")",
"or",
"(",
"linenum",
">=",
... | Checks whether where function type arguments are expected.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if the line at 'linenum' is inside something that expects arguments
of function types. | [
"Checks",
"whether",
"where",
"function",
"type",
"arguments",
"are",
"expected",
"."
] | python | valid |
townsenddw/jhubctl | jhubctl/hubs/hubs.py | https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/hubs/hubs.py#L22-L41 | def get_hubs(self):
"""Get a list of hubs names.
Returns
-------
hubs : list
List of hub names
"""
# Use helm to get a list of hubs.
output = helm(
'list',
'-q'
)
# Check if an error occurred.
if... | [
"def",
"get_hubs",
"(",
"self",
")",
":",
"# Use helm to get a list of hubs.",
"output",
"=",
"helm",
"(",
"'list'",
",",
"'-q'",
")",
"# Check if an error occurred.",
"if",
"output",
".",
"returncode",
"!=",
"0",
":",
"print",
"(",
"\"Something went wrong!\"",
")... | Get a list of hubs names.
Returns
-------
hubs : list
List of hub names | [
"Get",
"a",
"list",
"of",
"hubs",
"names",
".",
"Returns",
"-------",
"hubs",
":",
"list",
"List",
"of",
"hub",
"names"
] | python | train |
BD2KGenomics/protect | src/protect/addons/assess_immunotherapy_resistance.py | https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/addons/assess_immunotherapy_resistance.py#L40-L130 | def assess_itx_resistance(job, gene_expression, univ_options, reports_options):
"""
Assess the prevalence of the various genes in various cancer pathways and return a report in the txt
format.
:param toil.fileStore.FileID gene_expression: fsID for the rsem gene expression file
:param dict univ_opti... | [
"def",
"assess_itx_resistance",
"(",
"job",
",",
"gene_expression",
",",
"univ_options",
",",
"reports_options",
")",
":",
"work_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"tumor_type",
"=",
"univ_options",
"[",
"'tumor_type'",
"]",
"# Get the input files",
"input_... | Assess the prevalence of the various genes in various cancer pathways and return a report in the txt
format.
:param toil.fileStore.FileID gene_expression: fsID for the rsem gene expression file
:param dict univ_options: Dict of universal options used by almost all tools
:param dict reports_options: Opt... | [
"Assess",
"the",
"prevalence",
"of",
"the",
"various",
"genes",
"in",
"various",
"cancer",
"pathways",
"and",
"return",
"a",
"report",
"in",
"the",
"txt",
"format",
"."
] | python | train |
woolfson-group/isambard | isambard/optimisation/evo_optimizers.py | https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/optimisation/evo_optimizers.py#L366-L374 | def _initialize_pop(self, pop_size):
"""Assigns indices to individuals in population."""
self.toolbox.register("individual", self._generate)
self.toolbox.register("population", tools.initRepeat,
list, self.toolbox.individual)
self.population = self.toolbox.p... | [
"def",
"_initialize_pop",
"(",
"self",
",",
"pop_size",
")",
":",
"self",
".",
"toolbox",
".",
"register",
"(",
"\"individual\"",
",",
"self",
".",
"_generate",
")",
"self",
".",
"toolbox",
".",
"register",
"(",
"\"population\"",
",",
"tools",
".",
"initRe... | Assigns indices to individuals in population. | [
"Assigns",
"indices",
"to",
"individuals",
"in",
"population",
"."
] | python | train |
kgiusti/pyngus | pyngus/connection.py | https://github.com/kgiusti/pyngus/blob/5392392046989f1bb84ba938c30e4d48311075f1/pyngus/connection.py#L856-L861 | def _ep_active(self):
"""Both ends of the Endpoint have become active."""
LOG.debug("Connection is up")
if self._handler:
with self._callback_lock:
self._handler.connection_active(self) | [
"def",
"_ep_active",
"(",
"self",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Connection is up\"",
")",
"if",
"self",
".",
"_handler",
":",
"with",
"self",
".",
"_callback_lock",
":",
"self",
".",
"_handler",
".",
"connection_active",
"(",
"self",
")"
] | Both ends of the Endpoint have become active. | [
"Both",
"ends",
"of",
"the",
"Endpoint",
"have",
"become",
"active",
"."
] | python | test |
seequent/properties | properties/base/base.py | https://github.com/seequent/properties/blob/096b07012fff86b0a880c8c018320c3b512751b9/properties/base/base.py#L592-L603 | def _deserialize_class(cls, input_cls_name, trusted, strict):
"""Returns the HasProperties class to use for deserialization"""
if not input_cls_name or input_cls_name == cls.__name__:
return cls
if trusted and input_cls_name in cls._REGISTRY:
return cls._REGISTRY[input_cl... | [
"def",
"_deserialize_class",
"(",
"cls",
",",
"input_cls_name",
",",
"trusted",
",",
"strict",
")",
":",
"if",
"not",
"input_cls_name",
"or",
"input_cls_name",
"==",
"cls",
".",
"__name__",
":",
"return",
"cls",
"if",
"trusted",
"and",
"input_cls_name",
"in",
... | Returns the HasProperties class to use for deserialization | [
"Returns",
"the",
"HasProperties",
"class",
"to",
"use",
"for",
"deserialization"
] | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/tools/MAVExplorer.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/tools/MAVExplorer.py#L74-L89 | def menu_callback(m):
'''called on menu selection'''
if m.returnkey.startswith('# '):
cmd = m.returnkey[2:]
if m.handler is not None:
if m.handler_result is None:
return
cmd += m.handler_result
process_stdin(cmd)
elif m.returnkey == 'menuSettin... | [
"def",
"menu_callback",
"(",
"m",
")",
":",
"if",
"m",
".",
"returnkey",
".",
"startswith",
"(",
"'# '",
")",
":",
"cmd",
"=",
"m",
".",
"returnkey",
"[",
"2",
":",
"]",
"if",
"m",
".",
"handler",
"is",
"not",
"None",
":",
"if",
"m",
".",
"hand... | called on menu selection | [
"called",
"on",
"menu",
"selection"
] | python | train |
rueckstiess/mtools | mtools/util/logevent.py | https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/util/logevent.py#L282-L333 | def _match_datetime_pattern(self, tokens):
"""
Match the datetime pattern at the beginning of the token list.
There are several formats that this method needs to understand
and distinguish between (see MongoDB's SERVER-7965):
ctime-pre2.4 Wed Dec 31 19:00:00
ctime ... | [
"def",
"_match_datetime_pattern",
"(",
"self",
",",
"tokens",
")",
":",
"# first check: less than 4 tokens can't be ctime",
"assume_iso8601_format",
"=",
"len",
"(",
"tokens",
")",
"<",
"4",
"# check for ctime-pre-2.4 or ctime format",
"if",
"not",
"assume_iso8601_format",
... | Match the datetime pattern at the beginning of the token list.
There are several formats that this method needs to understand
and distinguish between (see MongoDB's SERVER-7965):
ctime-pre2.4 Wed Dec 31 19:00:00
ctime Wed Dec 31 19:00:00.000
iso8601-utc 1970-01... | [
"Match",
"the",
"datetime",
"pattern",
"at",
"the",
"beginning",
"of",
"the",
"token",
"list",
"."
] | python | train |
mozilla/socorrolib | socorrolib/lib/transform_rules.py | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/transform_rules.py#L254-L278 | def act(self, *args, **kwargs):
"""gather a rules parameters together and run the predicate. If that
returns True, then go on and run the action function
returns:
a tuple indicating the results of applying the predicate and the
action function:
(False, Non... | [
"def",
"act",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pred_args",
"=",
"tuple",
"(",
"args",
")",
"+",
"tuple",
"(",
"self",
".",
"predicate_args",
")",
"pred_kwargs",
"=",
"kwargs",
".",
"copy",
"(",
")",
"pred_kwargs",
... | gather a rules parameters together and run the predicate. If that
returns True, then go on and run the action function
returns:
a tuple indicating the results of applying the predicate and the
action function:
(False, None) - the predicate failed, action function ... | [
"gather",
"a",
"rules",
"parameters",
"together",
"and",
"run",
"the",
"predicate",
".",
"If",
"that",
"returns",
"True",
"then",
"go",
"on",
"and",
"run",
"the",
"action",
"function"
] | python | train |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/certificates/certificates.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/certificates/certificates.py#L176-L195 | def update_certificate(self, certificate_id, **kwargs):
"""Update a certificate.
:param str certificate_id: The certificate id (Required)
:param str certificate_data: X509.v3 trusted certificate in PEM format.
:param str signature: This parameter has been DEPRECATED in the API and does ... | [
"def",
"update_certificate",
"(",
"self",
",",
"certificate_id",
",",
"*",
"*",
"kwargs",
")",
":",
"api",
"=",
"self",
".",
"_get_api",
"(",
"iam",
".",
"DeveloperApi",
")",
"cert",
"=",
"Certificate",
".",
"_create_request_map",
"(",
"kwargs",
")",
"body... | Update a certificate.
:param str certificate_id: The certificate id (Required)
:param str certificate_data: X509.v3 trusted certificate in PEM format.
:param str signature: This parameter has been DEPRECATED in the API and does not need to
be provided.
:param str type: type ... | [
"Update",
"a",
"certificate",
"."
] | python | train |
mlperf/training | translation/tensorflow/transformer/transformer_main.py | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/transformer_main.py#L187-L289 | def train_schedule(
estimator, train_eval_iterations, single_iteration_train_steps=None,
single_iteration_train_epochs=None, bleu_source=None, bleu_ref=None,
bleu_threshold=None):
"""Train and evaluate model, and optionally compute model's BLEU score.
**Step vs. Epoch vs. Iteration**
Steps and epoch... | [
"def",
"train_schedule",
"(",
"estimator",
",",
"train_eval_iterations",
",",
"single_iteration_train_steps",
"=",
"None",
",",
"single_iteration_train_epochs",
"=",
"None",
",",
"bleu_source",
"=",
"None",
",",
"bleu_ref",
"=",
"None",
",",
"bleu_threshold",
"=",
"... | Train and evaluate model, and optionally compute model's BLEU score.
**Step vs. Epoch vs. Iteration**
Steps and epochs are canonical terms used in TensorFlow and general machine
learning. They are used to describe running a single process (train/eval):
- Step refers to running the process through a single o... | [
"Train",
"and",
"evaluate",
"model",
"and",
"optionally",
"compute",
"model",
"s",
"BLEU",
"score",
"."
] | python | train |
saltstack/salt | salt/modules/openvswitch.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openvswitch.py#L607-L635 | def db_set(table, record, column, value, if_exists=False):
'''
Sets a column's value for a specific record.
Args:
table: A string - name of the database table.
record: A string - identifier of the record.
column: A string - name of the column.
value: A string - the value to ... | [
"def",
"db_set",
"(",
"table",
",",
"record",
",",
"column",
",",
"value",
",",
"if_exists",
"=",
"False",
")",
":",
"cmd",
"=",
"[",
"'ovs-vsctl'",
"]",
"if",
"if_exists",
":",
"cmd",
"+=",
"[",
"'--if-exists'",
"]",
"cmd",
"+=",
"[",
"'set'",
",",
... | Sets a column's value for a specific record.
Args:
table: A string - name of the database table.
record: A string - identifier of the record.
column: A string - name of the column.
value: A string - the value to be set
if_exists: A boolean - if True, it is not an error if th... | [
"Sets",
"a",
"column",
"s",
"value",
"for",
"a",
"specific",
"record",
"."
] | python | train |
huge-success/sanic | sanic/blueprints.py | https://github.com/huge-success/sanic/blob/6a4a3f617fdbe1d3ee8bdc9d1b12ad2d0b34acdd/sanic/blueprints.py#L260-L282 | def websocket(
self, uri, host=None, strict_slashes=None, version=None, name=None
):
"""Create a blueprint websocket route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:param host: IP Address of FQDN for the sanic server to use.
:par... | [
"def",
"websocket",
"(",
"self",
",",
"uri",
",",
"host",
"=",
"None",
",",
"strict_slashes",
"=",
"None",
",",
"version",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"strict_slashes",
"is",
"None",
":",
"strict_slashes",
"=",
"self",
".",
... | Create a blueprint websocket route from a decorated function.
:param uri: endpoint at which the route will be accessible.
:param host: IP Address of FQDN for the sanic server to use.
:param strict_slashes: Enforce the API urls are requested with a
training */*
:param version... | [
"Create",
"a",
"blueprint",
"websocket",
"route",
"from",
"a",
"decorated",
"function",
"."
] | python | train |
ssato/python-anyconfig | src/anyconfig/utils.py | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/utils.py#L192-L217 | def is_path_like_object(obj, marker='*'):
"""
Is given object 'obj' a path string, a pathlib.Path, a file / file-like
(stream) or IOInfo namedtuple object?
:param obj:
a path string, pathlib.Path object, a file / file-like or 'IOInfo'
object
:return:
True if 'obj' is a path... | [
"def",
"is_path_like_object",
"(",
"obj",
",",
"marker",
"=",
"'*'",
")",
":",
"return",
"(",
"(",
"is_path",
"(",
"obj",
")",
"and",
"marker",
"not",
"in",
"obj",
")",
"or",
"(",
"is_path_obj",
"(",
"obj",
")",
"and",
"marker",
"not",
"in",
"obj",
... | Is given object 'obj' a path string, a pathlib.Path, a file / file-like
(stream) or IOInfo namedtuple object?
:param obj:
a path string, pathlib.Path object, a file / file-like or 'IOInfo'
object
:return:
True if 'obj' is a path string or a pathlib.Path object or a file
(st... | [
"Is",
"given",
"object",
"obj",
"a",
"path",
"string",
"a",
"pathlib",
".",
"Path",
"a",
"file",
"/",
"file",
"-",
"like",
"(",
"stream",
")",
"or",
"IOInfo",
"namedtuple",
"object?"
] | python | train |
thespacedoctor/fundamentals | fundamentals/mysql/database.py | https://github.com/thespacedoctor/fundamentals/blob/1d2c007ac74442ec2eabde771cfcacdb9c1ab382/fundamentals/mysql/database.py#L85-L125 | def connect(self):
"""connect to the database
**Return:**
- ``dbConn`` -- the database connection
See the class docstring for usage
"""
self.log.debug('starting the ``get`` method')
dbSettings = self.dbSettings
port = False
if "tunnel" in d... | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``get`` method'",
")",
"dbSettings",
"=",
"self",
".",
"dbSettings",
"port",
"=",
"False",
"if",
"\"tunnel\"",
"in",
"dbSettings",
"and",
"dbSettings",
"[",
"\"tun... | connect to the database
**Return:**
- ``dbConn`` -- the database connection
See the class docstring for usage | [
"connect",
"to",
"the",
"database"
] | python | train |
chaoss/grimoirelab-kingarthur | arthur/scheduler.py | https://github.com/chaoss/grimoirelab-kingarthur/blob/9d6a638bee68d5e5c511f045eeebf06340fd3252/arthur/scheduler.py#L361-L366 | def _handle_failed_job(self, job):
"""Handle failed jobs"""
task_id = job.kwargs['task_id']
logger.error("Job #%s (task: %s) failed; cancelled",
job.id, task_id) | [
"def",
"_handle_failed_job",
"(",
"self",
",",
"job",
")",
":",
"task_id",
"=",
"job",
".",
"kwargs",
"[",
"'task_id'",
"]",
"logger",
".",
"error",
"(",
"\"Job #%s (task: %s) failed; cancelled\"",
",",
"job",
".",
"id",
",",
"task_id",
")"
] | Handle failed jobs | [
"Handle",
"failed",
"jobs"
] | python | test |
openstax/cnx-archive | cnxarchive/search.py | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/search.py#L195-L208 | def highlighted_fulltext(self):
"""Highlight the found terms in the fulltext."""
terms = self.fields.get('fulltext', [])
if not terms:
return None
arguments = {'id': self['id'],
'query': ' & '.join(terms),
}
with db_connect() ... | [
"def",
"highlighted_fulltext",
"(",
"self",
")",
":",
"terms",
"=",
"self",
".",
"fields",
".",
"get",
"(",
"'fulltext'",
",",
"[",
"]",
")",
"if",
"not",
"terms",
":",
"return",
"None",
"arguments",
"=",
"{",
"'id'",
":",
"self",
"[",
"'id'",
"]",
... | Highlight the found terms in the fulltext. | [
"Highlight",
"the",
"found",
"terms",
"in",
"the",
"fulltext",
"."
] | python | train |
daler/trackhub | trackhub/track.py | https://github.com/daler/trackhub/blob/e4655f79177822529f80b923df117e38e28df702/trackhub/track.py#L454-L472 | def add_subgroups(self, subgroups):
"""
Add a list of SubGroupDefinition objects to this composite.
Note that in contrast to :meth:`BaseTrack`, which takes a single
dictionary indicating the particular subgroups for the track, this
method takes a list of :class:`SubGroupDefiniti... | [
"def",
"add_subgroups",
"(",
"self",
",",
"subgroups",
")",
":",
"if",
"subgroups",
"is",
"None",
":",
"subgroups",
"=",
"{",
"}",
"_subgroups",
"=",
"{",
"}",
"for",
"sg",
"in",
"subgroups",
":",
"assert",
"isinstance",
"(",
"sg",
",",
"SubGroupDefiniti... | Add a list of SubGroupDefinition objects to this composite.
Note that in contrast to :meth:`BaseTrack`, which takes a single
dictionary indicating the particular subgroups for the track, this
method takes a list of :class:`SubGroupDefinition` objects representing
the allowed subgroups f... | [
"Add",
"a",
"list",
"of",
"SubGroupDefinition",
"objects",
"to",
"this",
"composite",
"."
] | python | train |
QInfer/python-qinfer | src/qinfer/utils.py | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/utils.py#L163-L202 | def sample_multinomial(N, p, size=None):
r"""
Draws fixed number of samples N from different
multinomial distributions (with the same number dice sides).
:param int N: How many samples to draw from each distribution.
:param np.ndarray p: Probabilities specifying each distribution.
Sum along... | [
"def",
"sample_multinomial",
"(",
"N",
",",
"p",
",",
"size",
"=",
"None",
")",
":",
"# ensure s is array",
"s",
"=",
"np",
".",
"array",
"(",
"[",
"1",
"]",
")",
"if",
"size",
"is",
"None",
"else",
"np",
".",
"array",
"(",
"[",
"size",
"]",
")",... | r"""
Draws fixed number of samples N from different
multinomial distributions (with the same number dice sides).
:param int N: How many samples to draw from each distribution.
:param np.ndarray p: Probabilities specifying each distribution.
Sum along axis 0 should be 1.
:param size: Output ... | [
"r",
"Draws",
"fixed",
"number",
"of",
"samples",
"N",
"from",
"different",
"multinomial",
"distributions",
"(",
"with",
"the",
"same",
"number",
"dice",
"sides",
")",
"."
] | python | train |
theislab/scanpy | scanpy/preprocessing/_bbknn.py | https://github.com/theislab/scanpy/blob/9e4e5ee02e04cf618872d9b098e24f0542e8b227/scanpy/preprocessing/_bbknn.py#L1-L84 | def bbknn(adata, batch_key='batch', save_knn=False, copy=False, **kwargs):
"""\
Batch balanced kNN [Park18]_.
Batch balanced kNN alters the kNN procedure to identify each
cell's top neighbours in each batch separately instead of the
entire cell pool with no accounting for batch. Aligns batches in a... | [
"def",
"bbknn",
"(",
"adata",
",",
"batch_key",
"=",
"'batch'",
",",
"save_knn",
"=",
"False",
",",
"copy",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"locals",
"(",
")",
"# Has to be first",
"kwargs",
"=",
"params",
".",
"pop",
... | \
Batch balanced kNN [Park18]_.
Batch balanced kNN alters the kNN procedure to identify each
cell's top neighbours in each batch separately instead of the
entire cell pool with no accounting for batch. Aligns batches in a
quick and lightweight manner.
For use in the scanpy workflow as an alter... | [
"\\",
"Batch",
"balanced",
"kNN",
"[",
"Park18",
"]",
"_",
"."
] | python | train |
apache/incubator-mxnet | python/mxnet/module/module.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/module/module.py#L722-L743 | def get_states(self, merge_multi_context=True):
"""Gets states from all devices.
If `merge_multi_context` is ``True``, it is like ``[out1, out2]``. Otherwise, it
is like ``[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]``. All the output
elements are `NDArray`.
Parameters
... | [
"def",
"get_states",
"(",
"self",
",",
"merge_multi_context",
"=",
"True",
")",
":",
"assert",
"self",
".",
"binded",
"and",
"self",
".",
"params_initialized",
"return",
"self",
".",
"_exec_group",
".",
"get_states",
"(",
"merge_multi_context",
"=",
"merge_multi... | Gets states from all devices.
If `merge_multi_context` is ``True``, it is like ``[out1, out2]``. Otherwise, it
is like ``[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]``. All the output
elements are `NDArray`.
Parameters
----------
merge_multi_context : bool
... | [
"Gets",
"states",
"from",
"all",
"devices",
"."
] | python | train |
JustinLovinger/optimal | optimal/algorithms/pbil.py | https://github.com/JustinLovinger/optimal/blob/ab48a4961697338cc32d50e3a6b06ac989e39c3f/optimal/algorithms/pbil.py#L126-L129 | def _sample(probability_vec):
"""Return random binary string, with given probabilities."""
return map(int,
numpy.random.random(probability_vec.size) <= probability_vec) | [
"def",
"_sample",
"(",
"probability_vec",
")",
":",
"return",
"map",
"(",
"int",
",",
"numpy",
".",
"random",
".",
"random",
"(",
"probability_vec",
".",
"size",
")",
"<=",
"probability_vec",
")"
] | Return random binary string, with given probabilities. | [
"Return",
"random",
"binary",
"string",
"with",
"given",
"probabilities",
"."
] | python | train |
B2W-BIT/aiologger | aiologger/handlers/files.py | https://github.com/B2W-BIT/aiologger/blob/0b366597a8305d5577a267305e81d5e4784cd398/aiologger/handlers/files.py#L276-L356 | def compute_rollover(self, current_time: int) -> int:
"""
Work out the rollover time based on the specified time.
If we are rolling over at midnight or weekly, then the interval is
already known. need to figure out is WHEN the next interval is.
In other words, if you are rolling... | [
"def",
"compute_rollover",
"(",
"self",
",",
"current_time",
":",
"int",
")",
"->",
"int",
":",
"result",
"=",
"current_time",
"+",
"self",
".",
"interval",
"if",
"(",
"self",
".",
"when",
"==",
"RolloverInterval",
".",
"MIDNIGHT",
"or",
"self",
".",
"wh... | Work out the rollover time based on the specified time.
If we are rolling over at midnight or weekly, then the interval is
already known. need to figure out is WHEN the next interval is.
In other words, if you are rolling over at midnight, then your base
interval is 1 day, but you want ... | [
"Work",
"out",
"the",
"rollover",
"time",
"based",
"on",
"the",
"specified",
"time",
"."
] | python | train |
spacetelescope/drizzlepac | drizzlepac/wcs_functions.py | https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/wcs_functions.py#L64-L70 | def backward(self,pixx,pixy):
""" Transform pixx,pixy positions from the output frame back onto their
original positions in the input frame.
"""
skyx,skyy = self.output.wcs_pix2world(pixx,pixy,self.origin)
result = self.input.all_world2pix(skyx,skyy,self.origin)
retur... | [
"def",
"backward",
"(",
"self",
",",
"pixx",
",",
"pixy",
")",
":",
"skyx",
",",
"skyy",
"=",
"self",
".",
"output",
".",
"wcs_pix2world",
"(",
"pixx",
",",
"pixy",
",",
"self",
".",
"origin",
")",
"result",
"=",
"self",
".",
"input",
".",
"all_wor... | Transform pixx,pixy positions from the output frame back onto their
original positions in the input frame. | [
"Transform",
"pixx",
"pixy",
"positions",
"from",
"the",
"output",
"frame",
"back",
"onto",
"their",
"original",
"positions",
"in",
"the",
"input",
"frame",
"."
] | python | train |
MartinThoma/hwrt | hwrt/utils.py | https://github.com/MartinThoma/hwrt/blob/725c21a3d0f5a30b8492cbc184b3688ceb364e1c/hwrt/utils.py#L448-L482 | def load_model(model_file):
"""Load a model by its file. This includes the model itself, but also
the preprocessing queue, the feature list and the output semantics.
"""
# Extract tar
with tarfile.open(model_file) as tar:
tarfolder = tempfile.mkdtemp()
tar.extractall(path=tarfolde... | [
"def",
"load_model",
"(",
"model_file",
")",
":",
"# Extract tar",
"with",
"tarfile",
".",
"open",
"(",
"model_file",
")",
"as",
"tar",
":",
"tarfolder",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"tar",
".",
"extractall",
"(",
"path",
"=",
"tarfolder",
... | Load a model by its file. This includes the model itself, but also
the preprocessing queue, the feature list and the output semantics. | [
"Load",
"a",
"model",
"by",
"its",
"file",
".",
"This",
"includes",
"the",
"model",
"itself",
"but",
"also",
"the",
"preprocessing",
"queue",
"the",
"feature",
"list",
"and",
"the",
"output",
"semantics",
"."
] | python | train |
madprime/cgivar2gvcf | cgivar2gvcf/__init__.py | https://github.com/madprime/cgivar2gvcf/blob/13b4cd8da08669f7e4b0ceed77a7a17082f91037/cgivar2gvcf/__init__.py#L65-L117 | def process_full_position(data, header, var_only=False):
"""
Return genetic data when all alleles called on same line.
Returns an array containing one item, a tuple of five items:
(string) chromosome
(string) start position (1-based)
(array of strings) matching dbSNP entries
... | [
"def",
"process_full_position",
"(",
"data",
",",
"header",
",",
"var_only",
"=",
"False",
")",
":",
"feature_type",
"=",
"data",
"[",
"header",
"[",
"'varType'",
"]",
"]",
"# Skip unmatchable, uncovered, or pseudoautosomal-in-X",
"if",
"(",
"feature_type",
"==",
... | Return genetic data when all alleles called on same line.
Returns an array containing one item, a tuple of five items:
(string) chromosome
(string) start position (1-based)
(array of strings) matching dbSNP entries
(string) reference allele sequence
(array of strings) the ge... | [
"Return",
"genetic",
"data",
"when",
"all",
"alleles",
"called",
"on",
"same",
"line",
"."
] | python | train |
bukun/TorCMS | torcms/model/wiki_hist_model.py | https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/model/wiki_hist_model.py#L11-L19 | def get_last(postid):
'''
Get the last wiki in history.
'''
recs = TabWikiHist.select().where(
TabWikiHist.wiki_id == postid
).order_by(TabWikiHist.time_update.desc())
return None if recs.count() == 0 else recs.get() | [
"def",
"get_last",
"(",
"postid",
")",
":",
"recs",
"=",
"TabWikiHist",
".",
"select",
"(",
")",
".",
"where",
"(",
"TabWikiHist",
".",
"wiki_id",
"==",
"postid",
")",
".",
"order_by",
"(",
"TabWikiHist",
".",
"time_update",
".",
"desc",
"(",
")",
")",... | Get the last wiki in history. | [
"Get",
"the",
"last",
"wiki",
"in",
"history",
"."
] | python | train |
xeroc/python-graphenelib | graphenecommon/transactionbuilder.py | https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L329-L339 | def set_fee_asset(self, fee_asset):
""" Set asset to fee
"""
if isinstance(fee_asset, self.amount_class):
self.fee_asset_id = fee_asset["id"]
elif isinstance(fee_asset, self.asset_class):
self.fee_asset_id = fee_asset["id"]
elif fee_asset:
self... | [
"def",
"set_fee_asset",
"(",
"self",
",",
"fee_asset",
")",
":",
"if",
"isinstance",
"(",
"fee_asset",
",",
"self",
".",
"amount_class",
")",
":",
"self",
".",
"fee_asset_id",
"=",
"fee_asset",
"[",
"\"id\"",
"]",
"elif",
"isinstance",
"(",
"fee_asset",
",... | Set asset to fee | [
"Set",
"asset",
"to",
"fee"
] | python | valid |
ellmetha/django-machina | machina/core/loading.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/loading.py#L82-L98 | def _pick_up_classes(modules, classnames):
""" Given a list of class names to retrieve, try to fetch them from the specified list of
modules and returns the list of the fetched classes.
"""
klasses = []
for classname in classnames:
klass = None
for module in modules:
... | [
"def",
"_pick_up_classes",
"(",
"modules",
",",
"classnames",
")",
":",
"klasses",
"=",
"[",
"]",
"for",
"classname",
"in",
"classnames",
":",
"klass",
"=",
"None",
"for",
"module",
"in",
"modules",
":",
"if",
"hasattr",
"(",
"module",
",",
"classname",
... | Given a list of class names to retrieve, try to fetch them from the specified list of
modules and returns the list of the fetched classes. | [
"Given",
"a",
"list",
"of",
"class",
"names",
"to",
"retrieve",
"try",
"to",
"fetch",
"them",
"from",
"the",
"specified",
"list",
"of",
"modules",
"and",
"returns",
"the",
"list",
"of",
"the",
"fetched",
"classes",
"."
] | python | train |
scieloorg/accessstatsapi | accessstats/queries.py | https://github.com/scieloorg/accessstatsapi/blob/8092d76bedab9e82efce4005f9bcd21fb94e8e98/accessstats/queries.py#L38-L115 | def downloads_per_year(collection, code, raw=False):
"""
This method retrieve the total of downloads per year.
arguments
collection: SciELO 3 letters Acronym
code: (Journal ISSN, Issue PID, Article PID)
return
[
("2017", "20101"),
("2016", "11201"),
("2015", "12311"... | [
"def",
"downloads_per_year",
"(",
"collection",
",",
"code",
",",
"raw",
"=",
"False",
")",
":",
"tc",
"=",
"ThriftClient",
"(",
")",
"body",
"=",
"{",
"\"query\"",
":",
"{",
"\"filtered\"",
":",
"{",
"}",
"}",
"}",
"fltr",
"=",
"{",
"}",
"query",
... | This method retrieve the total of downloads per year.
arguments
collection: SciELO 3 letters Acronym
code: (Journal ISSN, Issue PID, Article PID)
return
[
("2017", "20101"),
("2016", "11201"),
("2015", "12311"),
...
] | [
"This",
"method",
"retrieve",
"the",
"total",
"of",
"downloads",
"per",
"year",
"."
] | python | train |
pyviz/holoviews | holoviews/core/dimension.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/dimension.py#L97-L129 | def process_dimensions(kdims, vdims):
"""Converts kdims and vdims to Dimension objects.
Args:
kdims: List or single key dimension(s) specified as strings,
tuples dicts or Dimension objects.
vdims: List or single value dimension(s) specified as strings,
tuples dicts or Di... | [
"def",
"process_dimensions",
"(",
"kdims",
",",
"vdims",
")",
":",
"dimensions",
"=",
"{",
"}",
"for",
"group",
",",
"dims",
"in",
"[",
"(",
"'kdims'",
",",
"kdims",
")",
",",
"(",
"'vdims'",
",",
"vdims",
")",
"]",
":",
"if",
"dims",
"is",
"None",... | Converts kdims and vdims to Dimension objects.
Args:
kdims: List or single key dimension(s) specified as strings,
tuples dicts or Dimension objects.
vdims: List or single value dimension(s) specified as strings,
tuples dicts or Dimension objects.
Returns:
Dictio... | [
"Converts",
"kdims",
"and",
"vdims",
"to",
"Dimension",
"objects",
"."
] | python | train |
manns/pyspread | pyspread/src/actions/_main_window_actions.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/actions/_main_window_actions.py#L803-L853 | def launch_help(self, helpname, filename):
"""Generic help launcher
Launches HTMLWindow that shows content of filename
or the Internet page with the filename url
Parameters
----------
filename: String
\thtml file or url
"""
# Set up window
... | [
"def",
"launch_help",
"(",
"self",
",",
"helpname",
",",
"filename",
")",
":",
"# Set up window",
"position",
"=",
"config",
"[",
"\"help_window_position\"",
"]",
"size",
"=",
"config",
"[",
"\"help_window_size\"",
"]",
"self",
".",
"help_window",
"=",
"wx",
"... | Generic help launcher
Launches HTMLWindow that shows content of filename
or the Internet page with the filename url
Parameters
----------
filename: String
\thtml file or url | [
"Generic",
"help",
"launcher"
] | python | train |
log2timeline/plaso | plaso/storage/sqlite/sqlite_file.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/storage/sqlite/sqlite_file.py#L652-L667 | def AddEventTags(self, event_tags):
"""Adds event tags.
Args:
event_tags (list[EventTag]): event tags.
Raises:
IOError: when the storage file is closed or read-only or
if the event tags cannot be serialized.
OSError: when the storage file is closed or read-only or
if ... | [
"def",
"AddEventTags",
"(",
"self",
",",
"event_tags",
")",
":",
"self",
".",
"_RaiseIfNotWritable",
"(",
")",
"for",
"event_tag",
"in",
"event_tags",
":",
"self",
".",
"AddEventTag",
"(",
"event_tag",
")"
] | Adds event tags.
Args:
event_tags (list[EventTag]): event tags.
Raises:
IOError: when the storage file is closed or read-only or
if the event tags cannot be serialized.
OSError: when the storage file is closed or read-only or
if the event tags cannot be serialized. | [
"Adds",
"event",
"tags",
"."
] | python | train |
django-danceschool/django-danceschool | danceschool/private_lessons/models.py | https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/private_lessons/models.py#L48-L56 | def getBasePrice(self,**kwargs):
'''
This method overrides the method of the base Event class by
checking the pricingTier associated with this PrivateLessonEvent and getting
the appropriate price for it.
'''
if not self.pricingTier:
return None
return ... | [
"def",
"getBasePrice",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"pricingTier",
":",
"return",
"None",
"return",
"self",
".",
"pricingTier",
".",
"getBasePrice",
"(",
"*",
"*",
"kwargs",
")",
"*",
"max",
"(",
"self",
"... | This method overrides the method of the base Event class by
checking the pricingTier associated with this PrivateLessonEvent and getting
the appropriate price for it. | [
"This",
"method",
"overrides",
"the",
"method",
"of",
"the",
"base",
"Event",
"class",
"by",
"checking",
"the",
"pricingTier",
"associated",
"with",
"this",
"PrivateLessonEvent",
"and",
"getting",
"the",
"appropriate",
"price",
"for",
"it",
"."
] | python | train |
spookey/photon | photon/util/locations.py | https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/util/locations.py#L73-L102 | def make_locations(locations=None, verbose=True):
'''
Creates folders
:param locations:
A list of folders to create (can be a dictionary, see note below)
:param verbose:
Warn if any folders were created
.. note::
* |params_locations_dict|
* |param_locations_none|
... | [
"def",
"make_locations",
"(",
"locations",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"from",
"photon",
".",
"util",
".",
"structures",
"import",
"to_list",
"from",
"photon",
".",
"util",
".",
"system",
"import",
"shell_notify",
"if",
"not",
"loca... | Creates folders
:param locations:
A list of folders to create (can be a dictionary, see note below)
:param verbose:
Warn if any folders were created
.. note::
* |params_locations_dict|
* |param_locations_none| | [
"Creates",
"folders"
] | python | train |
MisterY/asset-allocation | asset_allocation/formatters.py | https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/formatters.py#L129-L132 | def append_text_column(self, text: str, index: int):
""" Add value to the output row, width based on index """
width = self.columns[index]["width"]
return f"{text:<{width}}" | [
"def",
"append_text_column",
"(",
"self",
",",
"text",
":",
"str",
",",
"index",
":",
"int",
")",
":",
"width",
"=",
"self",
".",
"columns",
"[",
"index",
"]",
"[",
"\"width\"",
"]",
"return",
"f\"{text:<{width}}\""
] | Add value to the output row, width based on index | [
"Add",
"value",
"to",
"the",
"output",
"row",
"width",
"based",
"on",
"index"
] | python | train |
f3at/feat | src/feat/models/call.py | https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/models/call.py#L155-L167 | def action_filter(method_name, *args, **kwargs):
"""
Creates an effect that will call the action's method with the current
value and specified arguments and keywords.
@param method_name: the name of method belonging to the action.
@type method_name: str
"""
def action_filter(value, context,... | [
"def",
"action_filter",
"(",
"method_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"action_filter",
"(",
"value",
",",
"context",
",",
"*",
"*",
"_params",
")",
":",
"method",
"=",
"getattr",
"(",
"context",
"[",
"\"action\"",
"]",... | Creates an effect that will call the action's method with the current
value and specified arguments and keywords.
@param method_name: the name of method belonging to the action.
@type method_name: str | [
"Creates",
"an",
"effect",
"that",
"will",
"call",
"the",
"action",
"s",
"method",
"with",
"the",
"current",
"value",
"and",
"specified",
"arguments",
"and",
"keywords",
"."
] | python | train |
kennethreitz/maya | maya/core.py | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L142-L146 | def add(self, **kwargs):
"""Returns a new MayaDT object with the given offsets."""
return self.from_datetime(
pendulum.instance(self.datetime()).add(**kwargs)
) | [
"def",
"add",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"from_datetime",
"(",
"pendulum",
".",
"instance",
"(",
"self",
".",
"datetime",
"(",
")",
")",
".",
"add",
"(",
"*",
"*",
"kwargs",
")",
")"
] | Returns a new MayaDT object with the given offsets. | [
"Returns",
"a",
"new",
"MayaDT",
"object",
"with",
"the",
"given",
"offsets",
"."
] | python | train |
ladybug-tools/uwg | uwg/uwg.py | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/uwg.py#L612-L727 | def init_input_obj(self):
"""Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc ... | [
"def",
"init_input_obj",
"(",
"self",
")",
":",
"climate_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"epwDir",
",",
"self",
".",
"epwFileName",
")",
"self",
".",
"simTime",
"=",
"SimParam",
"(",
"self",
".",
"dtSim",
",",
"self",... | Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc # Empty forcing obj
... | [
"Section",
"4",
"-",
"Create",
"uwg",
"objects",
"from",
"input",
"parameters",
"self",
".",
"simTime",
"#",
"simulation",
"time",
"parameter",
"obj",
"self",
".",
"weather",
"#",
"weather",
"obj",
"for",
"simulation",
"time",
"period",
"self",
".",
"forcIP"... | python | train |
wummel/linkchecker | linkcheck/url.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/url.py#L431-L441 | def match_host (host, domainlist):
"""Return True if host matches an entry in given domain list."""
if not host:
return False
for domain in domainlist:
if domain.startswith('.'):
if host.endswith(domain):
return True
elif host == domain:
return... | [
"def",
"match_host",
"(",
"host",
",",
"domainlist",
")",
":",
"if",
"not",
"host",
":",
"return",
"False",
"for",
"domain",
"in",
"domainlist",
":",
"if",
"domain",
".",
"startswith",
"(",
"'.'",
")",
":",
"if",
"host",
".",
"endswith",
"(",
"domain",... | Return True if host matches an entry in given domain list. | [
"Return",
"True",
"if",
"host",
"matches",
"an",
"entry",
"in",
"given",
"domain",
"list",
"."
] | python | train |
wummel/linkchecker | third_party/dnspython/dns/name.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/name.py#L534-L594 | def from_unicode(text, origin = root):
"""Convert unicode text into a Name object.
Lables are encoded in IDN ACE form.
@rtype: dns.name.Name object
"""
if not isinstance(text, unicode):
raise ValueError("input to from_unicode() must be a unicode string")
if not (origin is None or isin... | [
"def",
"from_unicode",
"(",
"text",
",",
"origin",
"=",
"root",
")",
":",
"if",
"not",
"isinstance",
"(",
"text",
",",
"unicode",
")",
":",
"raise",
"ValueError",
"(",
"\"input to from_unicode() must be a unicode string\"",
")",
"if",
"not",
"(",
"origin",
"is... | Convert unicode text into a Name object.
Lables are encoded in IDN ACE form.
@rtype: dns.name.Name object | [
"Convert",
"unicode",
"text",
"into",
"a",
"Name",
"object",
"."
] | python | train |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L184-L187 | def any_channel_validate_token_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/channel_framework#validate-token"
api_path = "/api/v2/any_channel/validate_token"
return self.call(api_path, method="POST", data=data, **kwargs) | [
"def",
"any_channel_validate_token_create",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/any_channel/validate_token\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"POST\"",
",",
"data",
"=",
... | https://developer.zendesk.com/rest_api/docs/core/channel_framework#validate-token | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"core",
"/",
"channel_framework#validate",
"-",
"token"
] | python | train |
carlitux/turboengine | src/turboengine/decorators.py | https://github.com/carlitux/turboengine/blob/627b6dbc400d8c16e2ff7e17afd01915371ea287/src/turboengine/decorators.py#L29-L39 | def login_required(method):
"""A decorator that control if a user is logged."""
def wrapper(self, *arg, **karg):
if not self.user:
if self.request.method == "GET":
self.redirect(settings.LOGIN_PATH)
else:
self.error(403)
else:
m... | [
"def",
"login_required",
"(",
"method",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"*",
"arg",
",",
"*",
"*",
"karg",
")",
":",
"if",
"not",
"self",
".",
"user",
":",
"if",
"self",
".",
"request",
".",
"method",
"==",
"\"GET\"",
":",
"self",
"... | A decorator that control if a user is logged. | [
"A",
"decorator",
"that",
"control",
"if",
"a",
"user",
"is",
"logged",
"."
] | python | train |
vinci1it2000/schedula | schedula/utils/dsp.py | https://github.com/vinci1it2000/schedula/blob/addb9fd685be81544b796c51383ac00a31543ce9/schedula/utils/dsp.py#L567-L603 | def combine_nested_dicts(*nested_dicts, depth=-1, base=None):
"""
Merge nested-dictionaries.
:param nested_dicts:
Nested dictionaries.
:type nested_dicts: dict
:param depth:
Maximum keys depth.
:type depth: int, optional
:param base:
Base dict where combine multipl... | [
"def",
"combine_nested_dicts",
"(",
"*",
"nested_dicts",
",",
"depth",
"=",
"-",
"1",
",",
"base",
"=",
"None",
")",
":",
"if",
"base",
"is",
"None",
":",
"base",
"=",
"{",
"}",
"for",
"nested_dict",
"in",
"nested_dicts",
":",
"for",
"k",
",",
"v",
... | Merge nested-dictionaries.
:param nested_dicts:
Nested dictionaries.
:type nested_dicts: dict
:param depth:
Maximum keys depth.
:type depth: int, optional
:param base:
Base dict where combine multiple dicts in one.
:type base: dict, optional
:return:
Combi... | [
"Merge",
"nested",
"-",
"dictionaries",
"."
] | python | train |
aouyar/PyMunin | pysysinfo/ntp.py | https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pysysinfo/ntp.py#L29-L49 | def getPeerStats(self):
"""Get NTP Peer Stats for localhost by querying local NTP Server.
@return: Dictionary of NTP stats converted to seconds.
"""
info_dict = {}
output = util.exec_command([ntpqCmd, '-n', '-c', 'peers'])
for line in output.splitlines():
... | [
"def",
"getPeerStats",
"(",
"self",
")",
":",
"info_dict",
"=",
"{",
"}",
"output",
"=",
"util",
".",
"exec_command",
"(",
"[",
"ntpqCmd",
",",
"'-n'",
",",
"'-c'",
",",
"'peers'",
"]",
")",
"for",
"line",
"in",
"output",
".",
"splitlines",
"(",
")",... | Get NTP Peer Stats for localhost by querying local NTP Server.
@return: Dictionary of NTP stats converted to seconds. | [
"Get",
"NTP",
"Peer",
"Stats",
"for",
"localhost",
"by",
"querying",
"local",
"NTP",
"Server",
".",
"@return",
":",
"Dictionary",
"of",
"NTP",
"stats",
"converted",
"to",
"seconds",
"."
] | python | train |
mushkevych/scheduler | synergy/scheduler/tree.py | https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/scheduler/tree.py#L191-L197 | def get_next_node(self, process_name):
""" :return: <AbstractTreeNode> next node to process by a process with process_name """
if process_name not in self.process_hierarchy:
raise ValueError('unable to compute the next_node due to unknown process: {0}'.format(process_name))
time_qua... | [
"def",
"get_next_node",
"(",
"self",
",",
"process_name",
")",
":",
"if",
"process_name",
"not",
"in",
"self",
".",
"process_hierarchy",
":",
"raise",
"ValueError",
"(",
"'unable to compute the next_node due to unknown process: {0}'",
".",
"format",
"(",
"process_name",... | :return: <AbstractTreeNode> next node to process by a process with process_name | [
":",
"return",
":",
"<AbstractTreeNode",
">",
"next",
"node",
"to",
"process",
"by",
"a",
"process",
"with",
"process_name"
] | python | train |
devassistant/devassistant | devassistant/yaml_checker.py | https://github.com/devassistant/devassistant/blob/2dbfeaa666a64127263664d18969c55d19ecc83e/devassistant/yaml_checker.py#L242-L273 | def _assert_struct_type(self, struct, name, types, path=None, extra_info=None):
"""Asserts that given structure is of any of given types.
Args:
struct: structure to check
name: displayable name of the checked structure (e.g. "run_foo" for section run_foo)
types: list... | [
"def",
"_assert_struct_type",
"(",
"self",
",",
"struct",
",",
"name",
",",
"types",
",",
"path",
"=",
"None",
",",
"extra_info",
"=",
"None",
")",
":",
"wanted_yaml_typenames",
"=",
"set",
"(",
")",
"for",
"t",
"in",
"types",
":",
"wanted_yaml_typenames",... | Asserts that given structure is of any of given types.
Args:
struct: structure to check
name: displayable name of the checked structure (e.g. "run_foo" for section run_foo)
types: list/tuple of types that are allowed for given struct
path: list with a source file... | [
"Asserts",
"that",
"given",
"structure",
"is",
"of",
"any",
"of",
"given",
"types",
"."
] | python | train |
spyder-ide/spyder | spyder/plugins/editor/extensions/docstring.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/extensions/docstring.py#L779-L829 | def parse_body(self, text):
"""Parse the function body text."""
re_raise = re.findall(r'[ \t]raise ([a-zA-Z0-9_]*)', text)
if len(re_raise) > 0:
self.raise_list = [x.strip() for x in re_raise]
# remove duplicates from list while keeping it in the order
#... | [
"def",
"parse_body",
"(",
"self",
",",
"text",
")",
":",
"re_raise",
"=",
"re",
".",
"findall",
"(",
"r'[ \\t]raise ([a-zA-Z0-9_]*)'",
",",
"text",
")",
"if",
"len",
"(",
"re_raise",
")",
">",
"0",
":",
"self",
".",
"raise_list",
"=",
"[",
"x",
".",
... | Parse the function body text. | [
"Parse",
"the",
"function",
"body",
"text",
"."
] | python | train |
consbio/parserutils | parserutils/numbers.py | https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/numbers.py#L4-L15 | def is_number(num, if_bool=False):
""" :return: True if num is either an actual number, or an object that converts to one """
if isinstance(num, bool):
return if_bool
elif isinstance(num, int):
return True
try:
number = float(num)
return not (isnan(number) or isinf(numbe... | [
"def",
"is_number",
"(",
"num",
",",
"if_bool",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"num",
",",
"bool",
")",
":",
"return",
"if_bool",
"elif",
"isinstance",
"(",
"num",
",",
"int",
")",
":",
"return",
"True",
"try",
":",
"number",
"=",
... | :return: True if num is either an actual number, or an object that converts to one | [
":",
"return",
":",
"True",
"if",
"num",
"is",
"either",
"an",
"actual",
"number",
"or",
"an",
"object",
"that",
"converts",
"to",
"one"
] | python | train |
bcbio/bcbio-nextgen | bcbio/distributed/runfn.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/distributed/runfn.py#L500-L510 | def _combine_cwl_records(recs, record_name, parallel):
"""Provide a list of nexted CWL records keyed by output key.
Handles batches, where we return a list of records, and single items
where we return one record.
"""
if parallel not in ["multi-batch", "single-split", "multi-combined", "batch-single... | [
"def",
"_combine_cwl_records",
"(",
"recs",
",",
"record_name",
",",
"parallel",
")",
":",
"if",
"parallel",
"not",
"in",
"[",
"\"multi-batch\"",
",",
"\"single-split\"",
",",
"\"multi-combined\"",
",",
"\"batch-single\"",
"]",
":",
"assert",
"len",
"(",
"recs",... | Provide a list of nexted CWL records keyed by output key.
Handles batches, where we return a list of records, and single items
where we return one record. | [
"Provide",
"a",
"list",
"of",
"nexted",
"CWL",
"records",
"keyed",
"by",
"output",
"key",
"."
] | python | train |
unitedstack/steth | stetho/agent/common/utils.py | https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/common/utils.py#L62-L75 | def create_deamon(cmd, shell=False, root=False):
"""Usage:
Create servcice process.
"""
try:
if root:
cmd.insert(0, 'sudo')
LOG.info(cmd)
subproc = subprocess.Popen(cmd, shell=shell, stdout=subprocess.PIPE,
stderr=subprocess.PIPE... | [
"def",
"create_deamon",
"(",
"cmd",
",",
"shell",
"=",
"False",
",",
"root",
"=",
"False",
")",
":",
"try",
":",
"if",
"root",
":",
"cmd",
".",
"insert",
"(",
"0",
",",
"'sudo'",
")",
"LOG",
".",
"info",
"(",
"cmd",
")",
"subproc",
"=",
"subproce... | Usage:
Create servcice process. | [
"Usage",
":",
"Create",
"servcice",
"process",
"."
] | python | train |
sio2project/filetracker | filetracker/servers/storage.py | https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/servers/storage.py#L289-L294 | def stored_version(self, name):
"""Returns the version of file `name` or None if it doesn't exist."""
link_path = self._link_path(name)
if not _path_exists(link_path):
return None
return _file_version(link_path) | [
"def",
"stored_version",
"(",
"self",
",",
"name",
")",
":",
"link_path",
"=",
"self",
".",
"_link_path",
"(",
"name",
")",
"if",
"not",
"_path_exists",
"(",
"link_path",
")",
":",
"return",
"None",
"return",
"_file_version",
"(",
"link_path",
")"
] | Returns the version of file `name` or None if it doesn't exist. | [
"Returns",
"the",
"version",
"of",
"file",
"name",
"or",
"None",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | python | train |
saltstack/salt | salt/cloud/clouds/vultrpy.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vultrpy.py#L175-L192 | def list_nodes_full(**kwargs):
'''
Return all data on nodes
'''
nodes = _query('server/list')
ret = {}
for node in nodes:
name = nodes[node]['label']
ret[name] = nodes[node].copy()
ret[name]['id'] = node
ret[name]['image'] = nodes[node]['os']
ret[name]['s... | [
"def",
"list_nodes_full",
"(",
"*",
"*",
"kwargs",
")",
":",
"nodes",
"=",
"_query",
"(",
"'server/list'",
")",
"ret",
"=",
"{",
"}",
"for",
"node",
"in",
"nodes",
":",
"name",
"=",
"nodes",
"[",
"node",
"]",
"[",
"'label'",
"]",
"ret",
"[",
"name"... | Return all data on nodes | [
"Return",
"all",
"data",
"on",
"nodes"
] | python | train |
ucbvislab/radiotool | radiotool/composer/segment.py | https://github.com/ucbvislab/radiotool/blob/01c9d878a811cf400b1482896d641d9c95e83ded/radiotool/composer/segment.py#L59-L75 | def get_frames(self, channels=2):
"""Get numpy array of frames corresponding to the segment.
:param integer channels: Number of channels in output array
:returns: Array of frames in the segment
:rtype: numpy array
"""
tmp_frame = self.track.current_frame
self.tr... | [
"def",
"get_frames",
"(",
"self",
",",
"channels",
"=",
"2",
")",
":",
"tmp_frame",
"=",
"self",
".",
"track",
".",
"current_frame",
"self",
".",
"track",
".",
"current_frame",
"=",
"self",
".",
"start",
"frames",
"=",
"self",
".",
"track",
".",
"read_... | Get numpy array of frames corresponding to the segment.
:param integer channels: Number of channels in output array
:returns: Array of frames in the segment
:rtype: numpy array | [
"Get",
"numpy",
"array",
"of",
"frames",
"corresponding",
"to",
"the",
"segment",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.