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 |
|---|---|---|---|---|---|---|---|---|
pantsbuild/pants | src/python/pants/source/source_root.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/source/source_root.py#L100-L122 | def all_roots(self):
"""Return all known source roots.
Returns a generator over (source root, list of langs, category) triples.
Note: Requires a directory walk to match actual directories against patterns.
However we don't descend into source roots, once found, so this should be fast in practice.
... | [
"def",
"all_roots",
"(",
"self",
")",
":",
"project_tree",
"=",
"get_project_tree",
"(",
"self",
".",
"_options",
")",
"fixed_roots",
"=",
"set",
"(",
")",
"for",
"root",
",",
"langs",
",",
"category",
"in",
"self",
".",
"_trie",
".",
"fixed",
"(",
")"... | Return all known source roots.
Returns a generator over (source root, list of langs, category) triples.
Note: Requires a directory walk to match actual directories against patterns.
However we don't descend into source roots, once found, so this should be fast in practice.
Note: Does not follow symlin... | [
"Return",
"all",
"known",
"source",
"roots",
"."
] | python | train |
spacetelescope/stsci.tools | lib/stsci/tools/basicpar.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/basicpar.py#L1458-L1463 | def _checkAttribs(self, strict):
"""Check initial attributes to make sure they are legal"""
if self.choice:
warning("Choice values not allowed for real-type parameter " +
self.name, strict)
self.choice = None | [
"def",
"_checkAttribs",
"(",
"self",
",",
"strict",
")",
":",
"if",
"self",
".",
"choice",
":",
"warning",
"(",
"\"Choice values not allowed for real-type parameter \"",
"+",
"self",
".",
"name",
",",
"strict",
")",
"self",
".",
"choice",
"=",
"None"
] | Check initial attributes to make sure they are legal | [
"Check",
"initial",
"attributes",
"to",
"make",
"sure",
"they",
"are",
"legal"
] | python | train |
diging/tethne | tethne/readers/wos.py | https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/readers/wos.py#L255-L266 | def postprocess_authorKeywords(self, entry):
"""
Parse author keywords.
Author keywords are usually semicolon-delimited.
"""
if type(entry.authorKeywords) not in [str, unicode]:
aK = u' '.join([unicode(k) for k in entry.authorKeywords])
else:
aK ... | [
"def",
"postprocess_authorKeywords",
"(",
"self",
",",
"entry",
")",
":",
"if",
"type",
"(",
"entry",
".",
"authorKeywords",
")",
"not",
"in",
"[",
"str",
",",
"unicode",
"]",
":",
"aK",
"=",
"u' '",
".",
"join",
"(",
"[",
"unicode",
"(",
"k",
")",
... | Parse author keywords.
Author keywords are usually semicolon-delimited. | [
"Parse",
"author",
"keywords",
"."
] | python | train |
boundlessgeo/lib-qgis-commons | qgiscommons2/gui/__init__.py | https://github.com/boundlessgeo/lib-qgis-commons/blob/d25d13803db08c18632b55d12036e332f006d9ac/qgiscommons2/gui/__init__.py#L47-L63 | def addAboutMenu(menuName, parentMenuFunction=None):
'''
Adds an 'about...' menu to the plugin menu.
This method should be called from the initGui() method of the plugin
:param menuName: The name of the plugin menu in which the about menu is to be added
'''
parentMenuFunction = parentMenuFunct... | [
"def",
"addAboutMenu",
"(",
"menuName",
",",
"parentMenuFunction",
"=",
"None",
")",
":",
"parentMenuFunction",
"=",
"parentMenuFunction",
"or",
"iface",
".",
"addPluginToMenu",
"namespace",
"=",
"_callerName",
"(",
")",
".",
"split",
"(",
"\".\"",
")",
"[",
"... | Adds an 'about...' menu to the plugin menu.
This method should be called from the initGui() method of the plugin
:param menuName: The name of the plugin menu in which the about menu is to be added | [
"Adds",
"an",
"about",
"...",
"menu",
"to",
"the",
"plugin",
"menu",
".",
"This",
"method",
"should",
"be",
"called",
"from",
"the",
"initGui",
"()",
"method",
"of",
"the",
"plugin"
] | python | train |
apple/turicreate | src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_classifier/image_classifier.py#L824-L1021 | def export_coreml(self, filename):
"""
Save the model in Core ML format.
See Also
--------
save
Examples
--------
>>> model.export_coreml('myModel.mlmodel')
"""
import coremltools
# First define three internal helper functions
... | [
"def",
"export_coreml",
"(",
"self",
",",
"filename",
")",
":",
"import",
"coremltools",
"# First define three internal helper functions",
"# Internal helper function",
"def",
"_create_vision_feature_print_scene",
"(",
")",
":",
"prob_name",
"=",
"self",
".",
"target",
"+... | Save the model in Core ML format.
See Also
--------
save
Examples
--------
>>> model.export_coreml('myModel.mlmodel') | [
"Save",
"the",
"model",
"in",
"Core",
"ML",
"format",
"."
] | python | train |
datastore/datastore | datastore/core/basic.py | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L999-L1004 | def appendDatastore(self, store):
'''Appends datastore `store` to this collection.'''
if not isinstance(store, Datastore):
raise TypeError("stores must be of type %s" % Datastore)
self._stores.append(store) | [
"def",
"appendDatastore",
"(",
"self",
",",
"store",
")",
":",
"if",
"not",
"isinstance",
"(",
"store",
",",
"Datastore",
")",
":",
"raise",
"TypeError",
"(",
"\"stores must be of type %s\"",
"%",
"Datastore",
")",
"self",
".",
"_stores",
".",
"append",
"(",... | Appends datastore `store` to this collection. | [
"Appends",
"datastore",
"store",
"to",
"this",
"collection",
"."
] | python | train |
apache/spark | python/pyspark/rdd.py | https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L2316-L2331 | def sumApprox(self, timeout, confidence=0.95):
"""
.. note:: Experimental
Approximate operation to return the sum within a timeout
or meet the confidence.
>>> rdd = sc.parallelize(range(1000), 10)
>>> r = sum(range(1000))
>>> abs(rdd.sumApprox(1000) - r) / r < 0... | [
"def",
"sumApprox",
"(",
"self",
",",
"timeout",
",",
"confidence",
"=",
"0.95",
")",
":",
"jrdd",
"=",
"self",
".",
"mapPartitions",
"(",
"lambda",
"it",
":",
"[",
"float",
"(",
"sum",
"(",
"it",
")",
")",
"]",
")",
".",
"_to_java_object_rdd",
"(",
... | .. note:: Experimental
Approximate operation to return the sum within a timeout
or meet the confidence.
>>> rdd = sc.parallelize(range(1000), 10)
>>> r = sum(range(1000))
>>> abs(rdd.sumApprox(1000) - r) / r < 0.05
True | [
"..",
"note",
"::",
"Experimental"
] | python | train |
codeinthehole/purl | purl/template.py | https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/template.py#L66-L73 | def _format_pair_with_equals(explode, separator, escape, key, value):
"""
Format a key, value pair including the equals sign
when there is no value
"""
if not value:
return key + '='
return _format_pair(explode, separator, escape, key, value) | [
"def",
"_format_pair_with_equals",
"(",
"explode",
",",
"separator",
",",
"escape",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"key",
"+",
"'='",
"return",
"_format_pair",
"(",
"explode",
",",
"separator",
",",
"escape",
",",
... | Format a key, value pair including the equals sign
when there is no value | [
"Format",
"a",
"key",
"value",
"pair",
"including",
"the",
"equals",
"sign",
"when",
"there",
"is",
"no",
"value"
] | python | train |
google/dotty | efilter/parsers/common/grammar.py | https://github.com/google/dotty/blob/b145131499be0c4b755fc2e2ac19be11a50bce6a/efilter/parsers/common/grammar.py#L313-L338 | def match_tokens(expected_tokens):
"""Generate a grammar function that will match 'expected_tokens' only."""
if isinstance(expected_tokens, Token):
# Match a single token.
def _grammar_func(tokens):
try:
next_token = next(iter(tokens))
except StopIteration... | [
"def",
"match_tokens",
"(",
"expected_tokens",
")",
":",
"if",
"isinstance",
"(",
"expected_tokens",
",",
"Token",
")",
":",
"# Match a single token.",
"def",
"_grammar_func",
"(",
"tokens",
")",
":",
"try",
":",
"next_token",
"=",
"next",
"(",
"iter",
"(",
... | Generate a grammar function that will match 'expected_tokens' only. | [
"Generate",
"a",
"grammar",
"function",
"that",
"will",
"match",
"expected_tokens",
"only",
"."
] | python | train |
pantsbuild/pants | pants-plugins/src/python/internal_backend/sitegen/tasks/sitegen.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/pants-plugins/src/python/internal_backend/sitegen/tasks/sitegen.py#L164-L187 | def fixup_internal_links(config, soups):
"""Find href="..." links that link to pages in our docset; fix them up.
We don't preserve relative paths between files as we copy-transform them
from source to dest. So adjust the paths to work with new locations.
"""
# Pages can come from different dirs; they can go ... | [
"def",
"fixup_internal_links",
"(",
"config",
",",
"soups",
")",
":",
"# Pages can come from different dirs; they can go to different dirs.",
"# Thus, there's some relative-path-computing here.",
"reverse_directory",
"=",
"{",
"}",
"for",
"d",
",",
"s",
"in",
"config",
"[",
... | Find href="..." links that link to pages in our docset; fix them up.
We don't preserve relative paths between files as we copy-transform them
from source to dest. So adjust the paths to work with new locations. | [
"Find",
"href",
"=",
"...",
"links",
"that",
"link",
"to",
"pages",
"in",
"our",
"docset",
";",
"fix",
"them",
"up",
"."
] | python | train |
apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L6933-L6937 | def String(self, str):
"""Get an interned string from the reader, allows for example
to speedup string name comparisons """
ret = libxml2mod.xmlTextReaderConstString(self._o, str)
return ret | [
"def",
"String",
"(",
"self",
",",
"str",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlTextReaderConstString",
"(",
"self",
".",
"_o",
",",
"str",
")",
"return",
"ret"
] | Get an interned string from the reader, allows for example
to speedup string name comparisons | [
"Get",
"an",
"interned",
"string",
"from",
"the",
"reader",
"allows",
"for",
"example",
"to",
"speedup",
"string",
"name",
"comparisons"
] | python | train |
priestc/moneywagon | moneywagon/core.py | https://github.com/priestc/moneywagon/blob/00518f1f557dcca8b3031f46d3564c2baa0227a3/moneywagon/core.py#L862-L891 | def to_rawtx(tx):
"""
Take a tx object in the moneywagon format and convert it to the format
that pybitcointools's `serialize` funcion takes, then return in raw hex
format.
"""
if tx.get('hex'):
return tx['hex']
new_tx = {}
locktime = tx.get('locktime', 0)
new_tx['locktime'... | [
"def",
"to_rawtx",
"(",
"tx",
")",
":",
"if",
"tx",
".",
"get",
"(",
"'hex'",
")",
":",
"return",
"tx",
"[",
"'hex'",
"]",
"new_tx",
"=",
"{",
"}",
"locktime",
"=",
"tx",
".",
"get",
"(",
"'locktime'",
",",
"0",
")",
"new_tx",
"[",
"'locktime'",
... | Take a tx object in the moneywagon format and convert it to the format
that pybitcointools's `serialize` funcion takes, then return in raw hex
format. | [
"Take",
"a",
"tx",
"object",
"in",
"the",
"moneywagon",
"format",
"and",
"convert",
"it",
"to",
"the",
"format",
"that",
"pybitcointools",
"s",
"serialize",
"funcion",
"takes",
"then",
"return",
"in",
"raw",
"hex",
"format",
"."
] | python | train |
openvax/varlens | varlens/read_evidence/pileup_collection.py | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L404-L443 | def match_summary(self, variant, score=lambda x: x.num_reads()):
'''
Convenience method to summarize the evidence for and against a variant
using a user-specified score function.
See also `PileupCollection.group_by_match`.
Parameters
----------
variant : Variant... | [
"def",
"match_summary",
"(",
"self",
",",
"variant",
",",
"score",
"=",
"lambda",
"x",
":",
"x",
".",
"num_reads",
"(",
")",
")",
":",
"split",
"=",
"self",
".",
"group_by_match",
"(",
"variant",
")",
"def",
"name",
"(",
"allele_to_pileup_collection",
")... | Convenience method to summarize the evidence for and against a variant
using a user-specified score function.
See also `PileupCollection.group_by_match`.
Parameters
----------
variant : Variant
The variant. Must have fields 'locus', 'ref', and 'alt'.
score ... | [
"Convenience",
"method",
"to",
"summarize",
"the",
"evidence",
"for",
"and",
"against",
"a",
"variant",
"using",
"a",
"user",
"-",
"specified",
"score",
"function",
"."
] | python | train |
celiao/tmdbsimple | tmdbsimple/configuration.py | https://github.com/celiao/tmdbsimple/blob/ff17893110c99771d6398a62c35d36dd9735f4b9/tmdbsimple/configuration.py#L30-L41 | def info(self, **kwargs):
"""
Get the system wide configuration info.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_path('info')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
... | [
"def",
"info",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_get_path",
"(",
"'info'",
")",
"response",
"=",
"self",
".",
"_GET",
"(",
"path",
",",
"kwargs",
")",
"self",
".",
"_set_attrs_to_values",
"(",
"response",
")"... | Get the system wide configuration info.
Returns:
A dict respresentation of the JSON returned from the API. | [
"Get",
"the",
"system",
"wide",
"configuration",
"info",
"."
] | python | test |
awslabs/sockeye | sockeye/training.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/training.py#L875-L881 | def _evaluate(self, val_iter: data_io.BaseParallelSampleIter, val_metric: mx.metric.EvalMetric):
"""
Evaluates the model on the validation data and updates the validation metric(s).
"""
val_iter.reset()
val_metric.reset()
self.model.evaluate(val_iter, val_metric) | [
"def",
"_evaluate",
"(",
"self",
",",
"val_iter",
":",
"data_io",
".",
"BaseParallelSampleIter",
",",
"val_metric",
":",
"mx",
".",
"metric",
".",
"EvalMetric",
")",
":",
"val_iter",
".",
"reset",
"(",
")",
"val_metric",
".",
"reset",
"(",
")",
"self",
"... | Evaluates the model on the validation data and updates the validation metric(s). | [
"Evaluates",
"the",
"model",
"on",
"the",
"validation",
"data",
"and",
"updates",
"the",
"validation",
"metric",
"(",
"s",
")",
"."
] | python | train |
databio/pypiper | pypiper/ngstk.py | https://github.com/databio/pypiper/blob/00e6c2b94033c4187d47ff14c5580bbfc2ff097f/pypiper/ngstk.py#L872-L883 | def sam_conversions(self, sam_file, depth=True):
"""
Convert sam files to bam files, then sort and index them for later use.
:param bool depth: also calculate coverage over each position
"""
cmd = self.tools.samtools + " view -bS " + sam_file + " > " + sam_file.replace(".sam", "... | [
"def",
"sam_conversions",
"(",
"self",
",",
"sam_file",
",",
"depth",
"=",
"True",
")",
":",
"cmd",
"=",
"self",
".",
"tools",
".",
"samtools",
"+",
"\" view -bS \"",
"+",
"sam_file",
"+",
"\" > \"",
"+",
"sam_file",
".",
"replace",
"(",
"\".sam\"",
",",... | Convert sam files to bam files, then sort and index them for later use.
:param bool depth: also calculate coverage over each position | [
"Convert",
"sam",
"files",
"to",
"bam",
"files",
"then",
"sort",
"and",
"index",
"them",
"for",
"later",
"use",
"."
] | python | train |
rocky/python-filecache | pyficache/main.py | https://github.com/rocky/python-filecache/blob/60709ccd837ef5df001faf3cb02d4979ba342a23/pyficache/main.py#L230-L267 | def checkcache(filename=None, opts=False):
"""Discard cache entries that are out of date. If *filename* is *None*
all entries in the file cache *file_cache* are checked. If we do not
have stat information about a file it will be kept. Return a list of
invalidated filenames. None is returned if a filen... | [
"def",
"checkcache",
"(",
"filename",
"=",
"None",
",",
"opts",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"opts",
",",
"dict",
")",
":",
"use_linecache_lines",
"=",
"opts",
"[",
"'use_linecache_lines'",
"]",
"else",
":",
"use_linecache_lines",
"=",
... | Discard cache entries that are out of date. If *filename* is *None*
all entries in the file cache *file_cache* are checked. If we do not
have stat information about a file it will be kept. Return a list of
invalidated filenames. None is returned if a filename was given but
not found cached. | [
"Discard",
"cache",
"entries",
"that",
"are",
"out",
"of",
"date",
".",
"If",
"*",
"filename",
"*",
"is",
"*",
"None",
"*",
"all",
"entries",
"in",
"the",
"file",
"cache",
"*",
"file_cache",
"*",
"are",
"checked",
".",
"If",
"we",
"do",
"not",
"have"... | python | train |
AshleySetter/frange | frange/frange/frange.py | https://github.com/AshleySetter/frange/blob/6b0412d0584fce04c870af82d3e0bf90ed60fb5b/frange/frange/frange.py#L55-L67 | def get_generator(self):
"""
Returns a generator for the frange object instance.
Returns
-------
gen : generator
A generator that yields successive samples from start (inclusive)
to stop (exclusive) in step steps.
"""
s = self.slice
... | [
"def",
"get_generator",
"(",
"self",
")",
":",
"s",
"=",
"self",
".",
"slice",
"gen",
"=",
"drange",
"(",
"s",
".",
"start",
",",
"s",
".",
"stop",
",",
"s",
".",
"step",
")",
"# intialises the generator",
"return",
"gen"
] | Returns a generator for the frange object instance.
Returns
-------
gen : generator
A generator that yields successive samples from start (inclusive)
to stop (exclusive) in step steps. | [
"Returns",
"a",
"generator",
"for",
"the",
"frange",
"object",
"instance",
"."
] | python | train |
pgmpy/pgmpy | pgmpy/readwrite/UAI.py | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/readwrite/UAI.py#L171-L203 | def get_tables(self):
"""
Returns list of tuple of child variable and CPD in case of Bayesian
and list of tuple of scope of variables and values in case of Markov.
Returns
-------
list : list of tuples of child variable and values in Bayesian
list of tuples o... | [
"def",
"get_tables",
"(",
"self",
")",
":",
"tables",
"=",
"[",
"]",
"for",
"function",
"in",
"range",
"(",
"0",
",",
"self",
".",
"no_functions",
")",
":",
"function_variables",
"=",
"self",
".",
"grammar",
".",
"parseString",
"(",
"self",
".",
"netwo... | Returns list of tuple of child variable and CPD in case of Bayesian
and list of tuple of scope of variables and values in case of Markov.
Returns
-------
list : list of tuples of child variable and values in Bayesian
list of tuples of scope of variables and values in case of... | [
"Returns",
"list",
"of",
"tuple",
"of",
"child",
"variable",
"and",
"CPD",
"in",
"case",
"of",
"Bayesian",
"and",
"list",
"of",
"tuple",
"of",
"scope",
"of",
"variables",
"and",
"values",
"in",
"case",
"of",
"Markov",
"."
] | python | train |
adamcharnock/django-hordak | hordak/models/core.py | https://github.com/adamcharnock/django-hordak/blob/0ffcad1d3b388b860c8c47fde12aa40df213066f/hordak/models/core.py#L251-L298 | def transfer_to(self, to_account, amount, **transaction_kwargs):
"""Create a transaction which transfers amount to to_account
This is a shortcut utility method which simplifies the process of
transferring between accounts.
This method attempts to perform the transaction in an intuitive... | [
"def",
"transfer_to",
"(",
"self",
",",
"to_account",
",",
"amount",
",",
"*",
"*",
"transaction_kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"amount",
",",
"Money",
")",
":",
"raise",
"TypeError",
"(",
"\"amount must be of type Money\"",
")",
"if",
"t... | Create a transaction which transfers amount to to_account
This is a shortcut utility method which simplifies the process of
transferring between accounts.
This method attempts to perform the transaction in an intuitive manner.
For example:
* Transferring income -> income wil... | [
"Create",
"a",
"transaction",
"which",
"transfers",
"amount",
"to",
"to_account"
] | python | train |
bitesofcode/projexui | projexui/widgets/xorbrecordsetedit/xorbrecordsetedit.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordsetedit/xorbrecordsetedit.py#L241-L271 | def recordSet( self ):
"""
Returns the record set that is associated with this widget.
:return <orb.RecordSet> || None
"""
if ( not self.table() ):
return None
recordSet = RecordSet(self.table())
recordSet.setQuery(self.... | [
"def",
"recordSet",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"table",
"(",
")",
")",
":",
"return",
"None",
"recordSet",
"=",
"RecordSet",
"(",
"self",
".",
"table",
"(",
")",
")",
"recordSet",
".",
"setQuery",
"(",
"self",
".",
"query... | Returns the record set that is associated with this widget.
:return <orb.RecordSet> || None | [
"Returns",
"the",
"record",
"set",
"that",
"is",
"associated",
"with",
"this",
"widget",
".",
":",
"return",
"<orb",
".",
"RecordSet",
">",
"||",
"None"
] | python | train |
PyPSA/PyPSA | pypsa/pf.py | https://github.com/PyPSA/PyPSA/blob/46954b1b3c21460550f7104681517065279a53b7/pypsa/pf.py#L414-L439 | def apply_line_types(network):
"""Calculate line electrical parameters x, r, b, g from standard
types.
"""
lines_with_types_b = network.lines.type != ""
if lines_with_types_b.zsum() == 0:
return
missing_types = (pd.Index(network.lines.loc[lines_with_types_b, 'type'].unique())
... | [
"def",
"apply_line_types",
"(",
"network",
")",
":",
"lines_with_types_b",
"=",
"network",
".",
"lines",
".",
"type",
"!=",
"\"\"",
"if",
"lines_with_types_b",
".",
"zsum",
"(",
")",
"==",
"0",
":",
"return",
"missing_types",
"=",
"(",
"pd",
".",
"Index",
... | Calculate line electrical parameters x, r, b, g from standard
types. | [
"Calculate",
"line",
"electrical",
"parameters",
"x",
"r",
"b",
"g",
"from",
"standard",
"types",
"."
] | python | train |
hyperledger/indy-sdk | wrappers/python/indy/ledger.py | https://github.com/hyperledger/indy-sdk/blob/55240dc170308d7883c48f03f308130a6d077be6/wrappers/python/indy/ledger.py#L1140-L1178 | async def build_get_revoc_reg_delta_request(submitter_did: Optional[str],
revoc_reg_def_id: str,
from_: Optional[int],
to: int) -> str:
"""
Builds a GET_REVOC_REG_DELTA request. Re... | [
"async",
"def",
"build_get_revoc_reg_delta_request",
"(",
"submitter_did",
":",
"Optional",
"[",
"str",
"]",
",",
"revoc_reg_def_id",
":",
"str",
",",
"from_",
":",
"Optional",
"[",
"int",
"]",
",",
"to",
":",
"int",
")",
"->",
"str",
":",
"logger",
"=",
... | Builds a GET_REVOC_REG_DELTA request. Request to get the delta of the accumulated state of the Revocation Registry.
The Delta is defined by from and to timestamp fields.
If from is not specified, then the whole state till to will be returned.
:param submitter_did: (Optional) DID of the read request sender ... | [
"Builds",
"a",
"GET_REVOC_REG_DELTA",
"request",
".",
"Request",
"to",
"get",
"the",
"delta",
"of",
"the",
"accumulated",
"state",
"of",
"the",
"Revocation",
"Registry",
".",
"The",
"Delta",
"is",
"defined",
"by",
"from",
"and",
"to",
"timestamp",
"fields",
... | python | train |
Kozea/cairocffi | cairocffi/context.py | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/context.py#L1777-L1794 | def set_font_size(self, size):
"""Sets the current font matrix to a scale by a factor of :obj:`size`,
replacing any font matrix previously set with :meth:`set_font_size`
or :meth:`set_font_matrix`.
This results in a font size of size user space units.
(More precisely, this matrix... | [
"def",
"set_font_size",
"(",
"self",
",",
"size",
")",
":",
"cairo",
".",
"cairo_set_font_size",
"(",
"self",
".",
"_pointer",
",",
"size",
")",
"self",
".",
"_check_status",
"(",
")"
] | Sets the current font matrix to a scale by a factor of :obj:`size`,
replacing any font matrix previously set with :meth:`set_font_size`
or :meth:`set_font_matrix`.
This results in a font size of size user space units.
(More precisely, this matrix will result in the font's
em-squa... | [
"Sets",
"the",
"current",
"font",
"matrix",
"to",
"a",
"scale",
"by",
"a",
"factor",
"of",
":",
"obj",
":",
"size",
"replacing",
"any",
"font",
"matrix",
"previously",
"set",
"with",
":",
"meth",
":",
"set_font_size",
"or",
":",
"meth",
":",
"set_font_ma... | python | train |
adaptive-learning/proso-apps | proso_common/views.py | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_common/views.py#L29-L43 | def show_one(request, post_process_fun, object_class, id, template='common_json.html'):
"""
Return object of the given type with the specified identifier.
GET parameters:
user:
identifier of the current user
stats:
turn on the enrichment of the objects by some statistics
h... | [
"def",
"show_one",
"(",
"request",
",",
"post_process_fun",
",",
"object_class",
",",
"id",
",",
"template",
"=",
"'common_json.html'",
")",
":",
"obj",
"=",
"get_object_or_404",
"(",
"object_class",
",",
"pk",
"=",
"id",
")",
"json",
"=",
"post_process_fun",
... | Return object of the given type with the specified identifier.
GET parameters:
user:
identifier of the current user
stats:
turn on the enrichment of the objects by some statistics
html
turn on the HTML version of the API | [
"Return",
"object",
"of",
"the",
"given",
"type",
"with",
"the",
"specified",
"identifier",
"."
] | python | train |
ltworf/typedload | typedload/typechecks.py | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/typechecks.py#L200-L215 | def uniontypes(type_: Type[Any]) -> Set[Type[Any]]:
'''
Returns the types of a Union.
Raises ValueError if the argument is not a Union
and AttributeError when running on an unsupported
Python version.
'''
if not is_union(type_):
raise ValueError('Not a Union: ' + str(type_))
if... | [
"def",
"uniontypes",
"(",
"type_",
":",
"Type",
"[",
"Any",
"]",
")",
"->",
"Set",
"[",
"Type",
"[",
"Any",
"]",
"]",
":",
"if",
"not",
"is_union",
"(",
"type_",
")",
":",
"raise",
"ValueError",
"(",
"'Not a Union: '",
"+",
"str",
"(",
"type_",
")"... | Returns the types of a Union.
Raises ValueError if the argument is not a Union
and AttributeError when running on an unsupported
Python version. | [
"Returns",
"the",
"types",
"of",
"a",
"Union",
"."
] | python | train |
Guake/guake | guake/theme.py | https://github.com/Guake/guake/blob/4153ef38f9044cbed6494075fce80acd5809df2b/guake/theme.py#L22-L36 | def get_resource_dirs(resource):
"""Returns a list of all known resource dirs for a given resource.
:param str resource:
Name of the resource (e.g. "themes")
:return:
A list of resource dirs
"""
dirs = [
os.path.join(dir, resource) for dir in
itertools.chain(GLib.get... | [
"def",
"get_resource_dirs",
"(",
"resource",
")",
":",
"dirs",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"resource",
")",
"for",
"dir",
"in",
"itertools",
".",
"chain",
"(",
"GLib",
".",
"get_system_data_dirs",
"(",
")",
",",
"GUAKE_TH... | Returns a list of all known resource dirs for a given resource.
:param str resource:
Name of the resource (e.g. "themes")
:return:
A list of resource dirs | [
"Returns",
"a",
"list",
"of",
"all",
"known",
"resource",
"dirs",
"for",
"a",
"given",
"resource",
"."
] | python | train |
twilio/twilio-python | twilio/rest/api/v2010/account/message/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/message/__init__.py#L218-L227 | def get(self, sid):
"""
Constructs a MessageContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.message.MessageContext
:rtype: twilio.rest.api.v2010.account.message.MessageContext
"""
return MessageContext(s... | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"MessageContext",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
"sid",
"=",
"sid",
",",
")"
] | Constructs a MessageContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.message.MessageContext
:rtype: twilio.rest.api.v2010.account.message.MessageContext | [
"Constructs",
"a",
"MessageContext"
] | python | train |
yamcs/yamcs-python | yamcs-client/yamcs/tmtc/client.py | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/yamcs/tmtc/client.py#L654-L691 | def set_default_alarm_ranges(self, parameter, watch=None, warning=None,
distress=None, critical=None, severe=None,
min_violations=1):
"""
Generate out-of-limit alarms for a parameter using the specified
alarm ranges.
This... | [
"def",
"set_default_alarm_ranges",
"(",
"self",
",",
"parameter",
",",
"watch",
"=",
"None",
",",
"warning",
"=",
"None",
",",
"distress",
"=",
"None",
",",
"critical",
"=",
"None",
",",
"severe",
"=",
"None",
",",
"min_violations",
"=",
"1",
")",
":",
... | Generate out-of-limit alarms for a parameter using the specified
alarm ranges.
This replaces any previous default alarms on this parameter.
.. note::
Contextual range sets take precedence over the default alarm
ranges. See :meth:`set_alarm_range_sets` for setting conte... | [
"Generate",
"out",
"-",
"of",
"-",
"limit",
"alarms",
"for",
"a",
"parameter",
"using",
"the",
"specified",
"alarm",
"ranges",
"."
] | python | train |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/_backends/device_directory/apis/default_api.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/device_directory/apis/default_api.py#L1430-L1450 | def group_create(self, group, **kwargs): # noqa: E501
"""Create a group # noqa: E501
Create a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.group_create(group, a... | [
"def",
"group_create",
"(",
"self",
",",
"group",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
".",
"group_cre... | Create a group # noqa: E501
Create a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.group_create(group, asynchronous=True)
>>> result = thread.get()
:para... | [
"Create",
"a",
"group",
"#",
"noqa",
":",
"E501"
] | python | train |
pytroll/satpy | satpy/readers/hrit_base.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/readers/hrit_base.py#L255-L265 | def get_xy_from_linecol(self, line, col, offsets, factors):
"""Get the intermediate coordinates from line & col.
Intermediate coordinates are actually the instruments scanning angles.
"""
loff, coff = offsets
lfac, cfac = factors
x__ = (col - coff) / cfac * 2**16
... | [
"def",
"get_xy_from_linecol",
"(",
"self",
",",
"line",
",",
"col",
",",
"offsets",
",",
"factors",
")",
":",
"loff",
",",
"coff",
"=",
"offsets",
"lfac",
",",
"cfac",
"=",
"factors",
"x__",
"=",
"(",
"col",
"-",
"coff",
")",
"/",
"cfac",
"*",
"2",... | Get the intermediate coordinates from line & col.
Intermediate coordinates are actually the instruments scanning angles. | [
"Get",
"the",
"intermediate",
"coordinates",
"from",
"line",
"&",
"col",
"."
] | python | train |
orb-framework/orb | orb/core/column_types/boolean.py | https://github.com/orb-framework/orb/blob/575be2689cb269e65a0a2678232ff940acc19e5a/orb/core/column_types/boolean.py#L26-L34 | def valueFromString(self, value, extra=None, db=None):
"""
Converts the inputted string text to a value that matches the type from
this column type.
:param value | <str>
extra | <variant>
"""
return projex.text.nativestring(value).lower() == 'tru... | [
"def",
"valueFromString",
"(",
"self",
",",
"value",
",",
"extra",
"=",
"None",
",",
"db",
"=",
"None",
")",
":",
"return",
"projex",
".",
"text",
".",
"nativestring",
"(",
"value",
")",
".",
"lower",
"(",
")",
"==",
"'true'"
] | Converts the inputted string text to a value that matches the type from
this column type.
:param value | <str>
extra | <variant> | [
"Converts",
"the",
"inputted",
"string",
"text",
"to",
"a",
"value",
"that",
"matches",
"the",
"type",
"from",
"this",
"column",
"type",
"."
] | python | train |
nornir-automation/nornir | nornir/core/task.py | https://github.com/nornir-automation/nornir/blob/3425c47fd870db896cb80f619bae23bd98d50c74/nornir/core/task.py#L97-L126 | def run(self, task, **kwargs):
"""
This is a utility method to call a task from within a task. For instance:
def grouped_tasks(task):
task.run(my_first_task)
task.run(my_second_task)
nornir.run(grouped_tasks)
This method will ensure the ... | [
"def",
"run",
"(",
"self",
",",
"task",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"host",
"or",
"not",
"self",
".",
"nornir",
":",
"msg",
"=",
"(",
"\"You have to call this after setting host and nornir attributes. \"",
",",
"\"You probably ... | This is a utility method to call a task from within a task. For instance:
def grouped_tasks(task):
task.run(my_first_task)
task.run(my_second_task)
nornir.run(grouped_tasks)
This method will ensure the subtask is run only for the host in the current thr... | [
"This",
"is",
"a",
"utility",
"method",
"to",
"call",
"a",
"task",
"from",
"within",
"a",
"task",
".",
"For",
"instance",
":"
] | python | train |
pbrisk/dcf | dcf/interpolation.py | https://github.com/pbrisk/dcf/blob/c6030f733742efb6894d9bced5f0a0efe8e84d9f/dcf/interpolation.py#L35-L54 | def update(self, x_list=list(), y_list=list()):
"""
update interpolation data
:param list(float) x_list: x values
:param list(float) y_list: y values
"""
if not y_list:
for x in x_list:
if x in self.x_list:
i = self.x_list.i... | [
"def",
"update",
"(",
"self",
",",
"x_list",
"=",
"list",
"(",
")",
",",
"y_list",
"=",
"list",
"(",
")",
")",
":",
"if",
"not",
"y_list",
":",
"for",
"x",
"in",
"x_list",
":",
"if",
"x",
"in",
"self",
".",
"x_list",
":",
"i",
"=",
"self",
".... | update interpolation data
:param list(float) x_list: x values
:param list(float) y_list: y values | [
"update",
"interpolation",
"data",
":",
"param",
"list",
"(",
"float",
")",
"x_list",
":",
"x",
"values",
":",
"param",
"list",
"(",
"float",
")",
"y_list",
":",
"y",
"values"
] | python | valid |
raiden-network/raiden | raiden/network/transport/matrix/transport.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L485-L514 | def start_health_check(self, node_address):
"""Start healthcheck (status monitoring) for a peer
It also whitelists the address to answer invites and listen for messages
"""
if self._stop_event.ready():
return
with self._health_lock:
if self._address_mgr.... | [
"def",
"start_health_check",
"(",
"self",
",",
"node_address",
")",
":",
"if",
"self",
".",
"_stop_event",
".",
"ready",
"(",
")",
":",
"return",
"with",
"self",
".",
"_health_lock",
":",
"if",
"self",
".",
"_address_mgr",
".",
"is_address_known",
"(",
"no... | Start healthcheck (status monitoring) for a peer
It also whitelists the address to answer invites and listen for messages | [
"Start",
"healthcheck",
"(",
"status",
"monitoring",
")",
"for",
"a",
"peer"
] | python | train |
geronimp/graftM | graftm/housekeeping.py | https://github.com/geronimp/graftM/blob/c82576517290167f605fd0bc4facd009cee29f48/graftm/housekeeping.py#L24-L41 | def file_basename(self, file):
'''
Strips the path and last extension from the file variable. If the
extension is found to be valid, the basename will be returned. Otherwise
an error will be raise and graftM will exit
'''
valid_extensions = set(".tree",
... | [
"def",
"file_basename",
"(",
"self",
",",
"file",
")",
":",
"valid_extensions",
"=",
"set",
"(",
"\".tree\"",
",",
"\".tre\"",
")",
"split_file",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"file",
")",
".",
"split",
"(",
"'.'",
")",
"base",
",",
"... | Strips the path and last extension from the file variable. If the
extension is found to be valid, the basename will be returned. Otherwise
an error will be raise and graftM will exit | [
"Strips",
"the",
"path",
"and",
"last",
"extension",
"from",
"the",
"file",
"variable",
".",
"If",
"the",
"extension",
"is",
"found",
"to",
"be",
"valid",
"the",
"basename",
"will",
"be",
"returned",
".",
"Otherwise",
"an",
"error",
"will",
"be",
"raise",
... | python | train |
hydpy-dev/hydpy | hydpy/models/dam/dam_derived.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/dam/dam_derived.py#L246-L303 | def update(self):
"""Calculate the smoothing parameter value.
The following example is explained in some detail in module
|smoothtools|:
>>> from hydpy.models.dam import *
>>> parameterstep()
>>> highestremotedischarge(1.0)
>>> highestremotetolerance(0.0)
... | [
"def",
"update",
"(",
"self",
")",
":",
"control",
"=",
"self",
".",
"subpars",
".",
"pars",
".",
"control",
"if",
"numpy",
".",
"isinf",
"(",
"control",
".",
"highestremotedischarge",
")",
":",
"self",
"(",
"0.0",
")",
"else",
":",
"self",
"(",
"con... | Calculate the smoothing parameter value.
The following example is explained in some detail in module
|smoothtools|:
>>> from hydpy.models.dam import *
>>> parameterstep()
>>> highestremotedischarge(1.0)
>>> highestremotetolerance(0.0)
>>> derived.highestremotesm... | [
"Calculate",
"the",
"smoothing",
"parameter",
"value",
"."
] | python | train |
scanny/python-pptx | pptx/parts/slide.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/parts/slide.py#L78-L86 | def _new(cls, package):
"""
Create and return a standalone, default notes master part based on
the built-in template (without any related parts, such as theme).
"""
partname = PackURI('/ppt/notesMasters/notesMaster1.xml')
content_type = CT.PML_NOTES_MASTER
notesMa... | [
"def",
"_new",
"(",
"cls",
",",
"package",
")",
":",
"partname",
"=",
"PackURI",
"(",
"'/ppt/notesMasters/notesMaster1.xml'",
")",
"content_type",
"=",
"CT",
".",
"PML_NOTES_MASTER",
"notesMaster",
"=",
"CT_NotesMaster",
".",
"new_default",
"(",
")",
"return",
"... | Create and return a standalone, default notes master part based on
the built-in template (without any related parts, such as theme). | [
"Create",
"and",
"return",
"a",
"standalone",
"default",
"notes",
"master",
"part",
"based",
"on",
"the",
"built",
"-",
"in",
"template",
"(",
"without",
"any",
"related",
"parts",
"such",
"as",
"theme",
")",
"."
] | python | train |
flowersteam/explauto | explauto/sensorimotor_model/inverse/cma.py | https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L4445-L4447 | def defaults():
"""return a dictionary with default option values and description"""
return dict((str(k), str(v)) for k, v in cma_default_options.items()) | [
"def",
"defaults",
"(",
")",
":",
"return",
"dict",
"(",
"(",
"str",
"(",
"k",
")",
",",
"str",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"cma_default_options",
".",
"items",
"(",
")",
")"
] | return a dictionary with default option values and description | [
"return",
"a",
"dictionary",
"with",
"default",
"option",
"values",
"and",
"description"
] | python | train |
ray-project/ray | python/ray/tune/schedulers/hyperband.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/hyperband.py#L98-L132 | def on_trial_add(self, trial_runner, trial):
"""Adds new trial.
On a new trial add, if current bracket is not filled,
add to current bracket. Else, if current band is not filled,
create new bracket, add to current bracket.
Else, create new iteration, create new bracket, add to b... | [
"def",
"on_trial_add",
"(",
"self",
",",
"trial_runner",
",",
"trial",
")",
":",
"cur_bracket",
"=",
"self",
".",
"_state",
"[",
"\"bracket\"",
"]",
"cur_band",
"=",
"self",
".",
"_hyperbands",
"[",
"self",
".",
"_state",
"[",
"\"band_idx\"",
"]",
"]",
"... | Adds new trial.
On a new trial add, if current bracket is not filled,
add to current bracket. Else, if current band is not filled,
create new bracket, add to current bracket.
Else, create new iteration, create new bracket, add to bracket. | [
"Adds",
"new",
"trial",
"."
] | python | train |
serverops/laracrypt | src/laracrypt/__init__.py | https://github.com/serverops/laracrypt/blob/bf59947a781555d53772173c21c6ad7c853a508a/src/laracrypt/__init__.py#L39-L48 | def _pad(self, data):
"""
Pad value with bytes so it's a multiple of 16
See: http://stackoverflow.com/questions/14179784/python-encrypting-with-pycrypto-aes
:param data:
:return data:
"""
length = 16 - (len(data) % 16)
data += chr(length)*length
re... | [
"def",
"_pad",
"(",
"self",
",",
"data",
")",
":",
"length",
"=",
"16",
"-",
"(",
"len",
"(",
"data",
")",
"%",
"16",
")",
"data",
"+=",
"chr",
"(",
"length",
")",
"*",
"length",
"return",
"data"
] | Pad value with bytes so it's a multiple of 16
See: http://stackoverflow.com/questions/14179784/python-encrypting-with-pycrypto-aes
:param data:
:return data: | [
"Pad",
"value",
"with",
"bytes",
"so",
"it",
"s",
"a",
"multiple",
"of",
"16",
"See",
":",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"14179784",
"/",
"python",
"-",
"encrypting",
"-",
"with",
"-",
"pycrypto",
"-",
"aes",
... | python | train |
blockstack/virtualchain | virtualchain/lib/indexer.py | https://github.com/blockstack/virtualchain/blob/fcfc970064ca7dfcab26ebd3ab955870a763ea39/virtualchain/lib/indexer.py#L776-L821 | def clear_old_backups(self, block_id):
"""
If we limit the number of backups we make, then clean out old ones
older than block_id - backup_max_age (given in the constructor)
This method does nothing otherwise.
Return None on success
Raise exception on error
"""
... | [
"def",
"clear_old_backups",
"(",
"self",
",",
"block_id",
")",
":",
"assert",
"self",
".",
"setup",
",",
"\"Not set up yet. Call .db_setup() first!\"",
"if",
"self",
".",
"backup_max_age",
"is",
"None",
":",
"# never delete backups",
"return",
"# find old backups ",
... | If we limit the number of backups we make, then clean out old ones
older than block_id - backup_max_age (given in the constructor)
This method does nothing otherwise.
Return None on success
Raise exception on error | [
"If",
"we",
"limit",
"the",
"number",
"of",
"backups",
"we",
"make",
"then",
"clean",
"out",
"old",
"ones",
"older",
"than",
"block_id",
"-",
"backup_max_age",
"(",
"given",
"in",
"the",
"constructor",
")",
"This",
"method",
"does",
"nothing",
"otherwise",
... | python | train |
datajoint/datajoint-python | datajoint/schema.py | https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/schema.py#L164-L169 | def exists(self):
"""
:return: true if the associated schema exists on the server
"""
cur = self.connection.query("SHOW DATABASES LIKE '{database}'".format(database=self.database))
return cur.rowcount > 0 | [
"def",
"exists",
"(",
"self",
")",
":",
"cur",
"=",
"self",
".",
"connection",
".",
"query",
"(",
"\"SHOW DATABASES LIKE '{database}'\"",
".",
"format",
"(",
"database",
"=",
"self",
".",
"database",
")",
")",
"return",
"cur",
".",
"rowcount",
">",
"0"
] | :return: true if the associated schema exists on the server | [
":",
"return",
":",
"true",
"if",
"the",
"associated",
"schema",
"exists",
"on",
"the",
"server"
] | python | train |
openstack/python-scciclient | scciclient/irmc/elcm.py | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L246-L281 | def elcm_profile_get_versions(irmc_info):
"""send an eLCM request to get profile versions
:param irmc_info: node info
:returns: dict object of profiles if succeed
{
"Server":{
"@Version": "1.01",
"AdapterConfigIrmc":{
"@Version": "1.00... | [
"def",
"elcm_profile_get_versions",
"(",
"irmc_info",
")",
":",
"# Send GET request to the server",
"resp",
"=",
"elcm_request",
"(",
"irmc_info",
",",
"method",
"=",
"'GET'",
",",
"path",
"=",
"URL_PATH_PROFILE_MGMT",
"+",
"'version'",
")",
"if",
"resp",
".",
"st... | send an eLCM request to get profile versions
:param irmc_info: node info
:returns: dict object of profiles if succeed
{
"Server":{
"@Version": "1.01",
"AdapterConfigIrmc":{
"@Version": "1.00"
},
"HWConfigura... | [
"send",
"an",
"eLCM",
"request",
"to",
"get",
"profile",
"versions"
] | python | train |
rhayes777/PyAutoFit | autofit/mapper/link.py | https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/mapper/link.py#L23-L41 | def path_for(path):
"""
Generate a path in the ~/.autolens directory by taking the provided path, base64 encoding it and extracting the
first and last five characters.
Parameters
----------
path: str
The path where multinest output is apparently saved
Returns
-------
actual... | [
"def",
"path_for",
"(",
"path",
")",
":",
"start",
"=",
"int",
"(",
"SUB_PATH_LENGTH",
"/",
"2",
")",
"end",
"=",
"SUB_PATH_LENGTH",
"-",
"start",
"encoded_string",
"=",
"str",
"(",
"hashlib",
".",
"sha224",
"(",
"path",
".",
"encode",
"(",
"\"utf-8\"",
... | Generate a path in the ~/.autolens directory by taking the provided path, base64 encoding it and extracting the
first and last five characters.
Parameters
----------
path: str
The path where multinest output is apparently saved
Returns
-------
actual_path: str
The path wher... | [
"Generate",
"a",
"path",
"in",
"the",
"~",
"/",
".",
"autolens",
"directory",
"by",
"taking",
"the",
"provided",
"path",
"base64",
"encoding",
"it",
"and",
"extracting",
"the",
"first",
"and",
"last",
"five",
"characters",
"."
] | python | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/pisa.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/pisa.py#L420-L434 | def showLogging(debug=False):
"""
Shortcut for enabling log dump
"""
try:
log_level = logging.WARN
log_format = LOG_FORMAT_DEBUG
if debug:
log_level = logging.DEBUG
logging.basicConfig(
level=log_level,
format=log_format)
except:
... | [
"def",
"showLogging",
"(",
"debug",
"=",
"False",
")",
":",
"try",
":",
"log_level",
"=",
"logging",
".",
"WARN",
"log_format",
"=",
"LOG_FORMAT_DEBUG",
"if",
"debug",
":",
"log_level",
"=",
"logging",
".",
"DEBUG",
"logging",
".",
"basicConfig",
"(",
"lev... | Shortcut for enabling log dump | [
"Shortcut",
"for",
"enabling",
"log",
"dump"
] | python | train |
riga/law | law/parser.py | https://github.com/riga/law/blob/479f84ce06ecf3bafe9d33cb7b8fc52e39fb80a1/law/parser.py#L107-L136 | def global_cmdline_values():
"""
Returns a dictionary of global command line arguments (computed with
:py:func:`global_cmdline_args`) to their current values. The returnd dictionary is cached.
Example:
.. code-block:: python
global_cmdline_values()
# -> {"core_local_scheduler": Tru... | [
"def",
"global_cmdline_values",
"(",
")",
":",
"global",
"_global_cmdline_values",
"if",
"_global_cmdline_values",
":",
"return",
"_global_cmdline_values",
"luigi_parser",
"=",
"luigi",
".",
"cmdline_parser",
".",
"CmdlineParser",
".",
"get_instance",
"(",
")",
"if",
... | Returns a dictionary of global command line arguments (computed with
:py:func:`global_cmdline_args`) to their current values. The returnd dictionary is cached.
Example:
.. code-block:: python
global_cmdline_values()
# -> {"core_local_scheduler": True} | [
"Returns",
"a",
"dictionary",
"of",
"global",
"command",
"line",
"arguments",
"(",
"computed",
"with",
":",
"py",
":",
"func",
":",
"global_cmdline_args",
")",
"to",
"their",
"current",
"values",
".",
"The",
"returnd",
"dictionary",
"is",
"cached",
".",
"Exa... | python | train |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/reflect/PropertyReflector.py | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/reflect/PropertyReflector.py#L127-L144 | def get_properties(obj):
"""
Get values of all properties in specified object and returns them as a map.
:param obj: an object to get properties from.
:return: a map, containing the names of the object's properties and their values.
"""
properties = {}
... | [
"def",
"get_properties",
"(",
"obj",
")",
":",
"properties",
"=",
"{",
"}",
"for",
"property_name",
"in",
"dir",
"(",
"obj",
")",
":",
"property",
"=",
"getattr",
"(",
"obj",
",",
"property_name",
")",
"if",
"PropertyReflector",
".",
"_is_property",
"(",
... | Get values of all properties in specified object and returns them as a map.
:param obj: an object to get properties from.
:return: a map, containing the names of the object's properties and their values. | [
"Get",
"values",
"of",
"all",
"properties",
"in",
"specified",
"object",
"and",
"returns",
"them",
"as",
"a",
"map",
"."
] | python | train |
CI-WATER/gsshapy | gsshapy/base/geom.py | https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/base/geom.py#L74-L97 | def getAsGeoJson(self, session):
"""
Retrieve the geometry in GeoJSON format.
This method is a veneer for an SQL query that calls the ``ST_AsGeoJSON()`` function on the geometry column.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound t... | [
"def",
"getAsGeoJson",
"(",
"self",
",",
"session",
")",
":",
"statement",
"=",
"\"\"\"\n SELECT ST_AsGeoJSON({0}) AS json\n FROM {1}\n WHERE id={2};\n \"\"\"",
".",
"format",
"(",
"self",
".",
"geometryColum... | Retrieve the geometry in GeoJSON format.
This method is a veneer for an SQL query that calls the ``ST_AsGeoJSON()`` function on the geometry column.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database.
Returns:
... | [
"Retrieve",
"the",
"geometry",
"in",
"GeoJSON",
"format",
"."
] | python | train |
andreikop/qutepart | qutepart/syntax/__init__.py | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/syntax/__init__.py#L205-L212 | def _getSyntaxByFirstLine(self, firstLine):
"""Get syntax by first line of the file
"""
for pattern, xmlFileName in self._firstLineToXmlFileName.items():
if fnmatch.fnmatch(firstLine, pattern):
return self._getSyntaxByXmlFileName(xmlFileName)
else:
... | [
"def",
"_getSyntaxByFirstLine",
"(",
"self",
",",
"firstLine",
")",
":",
"for",
"pattern",
",",
"xmlFileName",
"in",
"self",
".",
"_firstLineToXmlFileName",
".",
"items",
"(",
")",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"firstLine",
",",
"pattern",
")",
... | Get syntax by first line of the file | [
"Get",
"syntax",
"by",
"first",
"line",
"of",
"the",
"file"
] | python | train |
jfilter/text-classification-keras | texcla/corpus.py | https://github.com/jfilter/text-classification-keras/blob/a59c652805da41d18937c7fdad0d9fd943cf8578/texcla/corpus.py#L43-L66 | def imdb(limit=None, shuffle=True):
"""Downloads (and caches) IMDB Moview Reviews. 25k training data, 25k test data
Args:
limit: get only first N items for each class
Returns:
[X_train, y_train, X_test, y_test]
"""
movie_review_url = 'http://ai.stanford.edu/~amaas/data/sentiment/a... | [
"def",
"imdb",
"(",
"limit",
"=",
"None",
",",
"shuffle",
"=",
"True",
")",
":",
"movie_review_url",
"=",
"'http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz'",
"# download and extract, thus remove the suffix '.tar.gz'",
"path",
"=",
"keras",
".",
"utils",
".",... | Downloads (and caches) IMDB Moview Reviews. 25k training data, 25k test data
Args:
limit: get only first N items for each class
Returns:
[X_train, y_train, X_test, y_test] | [
"Downloads",
"(",
"and",
"caches",
")",
"IMDB",
"Moview",
"Reviews",
".",
"25k",
"training",
"data",
"25k",
"test",
"data"
] | python | train |
adafruit/Adafruit_Python_TCS34725 | Adafruit_TCS34725/TCS34725.py | https://github.com/adafruit/Adafruit_Python_TCS34725/blob/996396cd095522d788b7b15d20fd44e566c8464e/Adafruit_TCS34725/TCS34725.py#L214-L226 | def get_raw_data(self):
"""Reads the raw red, green, blue and clear channel values. Will return
a 4-tuple with the red, green, blue, clear color values (unsigned 16-bit
numbers).
"""
# Read each color register.
r = self._readU16LE(TCS34725_RDATAL)
g = self._readU1... | [
"def",
"get_raw_data",
"(",
"self",
")",
":",
"# Read each color register.",
"r",
"=",
"self",
".",
"_readU16LE",
"(",
"TCS34725_RDATAL",
")",
"g",
"=",
"self",
".",
"_readU16LE",
"(",
"TCS34725_GDATAL",
")",
"b",
"=",
"self",
".",
"_readU16LE",
"(",
"TCS347... | Reads the raw red, green, blue and clear channel values. Will return
a 4-tuple with the red, green, blue, clear color values (unsigned 16-bit
numbers). | [
"Reads",
"the",
"raw",
"red",
"green",
"blue",
"and",
"clear",
"channel",
"values",
".",
"Will",
"return",
"a",
"4",
"-",
"tuple",
"with",
"the",
"red",
"green",
"blue",
"clear",
"color",
"values",
"(",
"unsigned",
"16",
"-",
"bit",
"numbers",
")",
"."... | python | train |
broox/python-nuheat | nuheat/thermostat.py | https://github.com/broox/python-nuheat/blob/3a18852dc9465c34cb96eb3a0c84f1a6caa70707/nuheat/thermostat.py#L162-L175 | def schedule_mode(self, mode):
"""
Set the thermostat mode
:param mode: The desired mode integer value.
Auto = 1
Temporary hold = 2
Permanent hold = 3
"""
modes = [config.SCHEDULE_RUN, config.SCHEDULE_TEMPORARY_HOLD,... | [
"def",
"schedule_mode",
"(",
"self",
",",
"mode",
")",
":",
"modes",
"=",
"[",
"config",
".",
"SCHEDULE_RUN",
",",
"config",
".",
"SCHEDULE_TEMPORARY_HOLD",
",",
"config",
".",
"SCHEDULE_HOLD",
"]",
"if",
"mode",
"not",
"in",
"modes",
":",
"raise",
"Except... | Set the thermostat mode
:param mode: The desired mode integer value.
Auto = 1
Temporary hold = 2
Permanent hold = 3 | [
"Set",
"the",
"thermostat",
"mode"
] | python | valid |
linkedin/luminol | src/luminol/algorithms/anomaly_detector_algorithms/bitmap_detector.py | https://github.com/linkedin/luminol/blob/42e4ab969b774ff98f902d064cb041556017f635/src/luminol/algorithms/anomaly_detector_algorithms/bitmap_detector.py#L92-L104 | def _generate_SAX(self):
"""
Generate SAX representation for all values of the time series.
"""
sections = {}
self.value_min = self.time_series.min()
self.value_max = self.time_series.max()
# Break the whole value range into different sections.
section_hei... | [
"def",
"_generate_SAX",
"(",
"self",
")",
":",
"sections",
"=",
"{",
"}",
"self",
".",
"value_min",
"=",
"self",
".",
"time_series",
".",
"min",
"(",
")",
"self",
".",
"value_max",
"=",
"self",
".",
"time_series",
".",
"max",
"(",
")",
"# Break the who... | Generate SAX representation for all values of the time series. | [
"Generate",
"SAX",
"representation",
"for",
"all",
"values",
"of",
"the",
"time",
"series",
"."
] | python | train |
mathiasertl/django-xmpp-http-upload | xmpp_http_upload/utils.py | https://github.com/mathiasertl/django-xmpp-http-upload/blob/819cb8794647c4609bb4cb7855e2ad4bd51b9ea1/xmpp_http_upload/utils.py#L25-L41 | def get_config(jid):
"""Get the configuration for the given JID based on XMPP_HTTP_UPLOAD_ACCESS.
If the JID does not match any rule, ``False`` is returned.
"""
acls = getattr(settings, 'XMPP_HTTP_UPLOAD_ACCESS', (('.*', False), ))
for regex, config in acls:
if isinstance(regex, six.strin... | [
"def",
"get_config",
"(",
"jid",
")",
":",
"acls",
"=",
"getattr",
"(",
"settings",
",",
"'XMPP_HTTP_UPLOAD_ACCESS'",
",",
"(",
"(",
"'.*'",
",",
"False",
")",
",",
")",
")",
"for",
"regex",
",",
"config",
"in",
"acls",
":",
"if",
"isinstance",
"(",
... | Get the configuration for the given JID based on XMPP_HTTP_UPLOAD_ACCESS.
If the JID does not match any rule, ``False`` is returned. | [
"Get",
"the",
"configuration",
"for",
"the",
"given",
"JID",
"based",
"on",
"XMPP_HTTP_UPLOAD_ACCESS",
"."
] | python | valid |
Microsoft/LightGBM | python-package/lightgbm/compat.py | https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/compat.py#L52-L59 | def json_default_with_numpy(obj):
"""Convert numpy classes to JSON serializable objects."""
if isinstance(obj, (np.integer, np.floating, np.bool_)):
return obj.item()
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return obj | [
"def",
"json_default_with_numpy",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"np",
".",
"integer",
",",
"np",
".",
"floating",
",",
"np",
".",
"bool_",
")",
")",
":",
"return",
"obj",
".",
"item",
"(",
")",
"elif",
"isinstance",
... | Convert numpy classes to JSON serializable objects. | [
"Convert",
"numpy",
"classes",
"to",
"JSON",
"serializable",
"objects",
"."
] | python | train |
Qiskit/qiskit-terra | qiskit/providers/basicaer/basicaertools.py | https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/providers/basicaer/basicaertools.py#L41-L58 | def single_gate_matrix(gate, params=None):
"""Get the matrix for a single qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
array: A numpy array representing the matrix
"""
# Converting sym to floats improves the... | [
"def",
"single_gate_matrix",
"(",
"gate",
",",
"params",
"=",
"None",
")",
":",
"# Converting sym to floats improves the performance of the simulator 10x.",
"# This a is a probable a FIXME since it might show bugs in the simulator.",
"(",
"theta",
",",
"phi",
",",
"lam",
")",
"... | Get the matrix for a single qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
array: A numpy array representing the matrix | [
"Get",
"the",
"matrix",
"for",
"a",
"single",
"qubit",
"."
] | python | test |
Metatab/metapack | metapack/jupyter/core.py | https://github.com/Metatab/metapack/blob/8365f221fbeaa3c0be9091f2eaf3447fd8e2e8d6/metapack/jupyter/core.py#L95-L148 | def process_schema(doc, resource, df):
"""Add schema entiries to a metatab doc from a dataframe"""
from rowgenerators import SourceError
from requests.exceptions import ConnectionError
from metapack.cli.core import extract_path_name, alt_col_name, type_map
from tableintuit import TypeIntuiter
f... | [
"def",
"process_schema",
"(",
"doc",
",",
"resource",
",",
"df",
")",
":",
"from",
"rowgenerators",
"import",
"SourceError",
"from",
"requests",
".",
"exceptions",
"import",
"ConnectionError",
"from",
"metapack",
".",
"cli",
".",
"core",
"import",
"extract_path_... | Add schema entiries to a metatab doc from a dataframe | [
"Add",
"schema",
"entiries",
"to",
"a",
"metatab",
"doc",
"from",
"a",
"dataframe"
] | python | train |
dswah/pyGAM | pygam/distributions.py | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/distributions.py#L645-L658 | def sample(self, mu):
"""
Return random samples from this Inverse Gaussian (Wald) distribution.
Parameters
----------
mu : array-like of shape n_samples or shape (n_simulations, n_samples)
expected values
Returns
-------
random_samples : np.a... | [
"def",
"sample",
"(",
"self",
",",
"mu",
")",
":",
"return",
"np",
".",
"random",
".",
"wald",
"(",
"mean",
"=",
"mu",
",",
"scale",
"=",
"self",
".",
"scale",
",",
"size",
"=",
"None",
")"
] | Return random samples from this Inverse Gaussian (Wald) distribution.
Parameters
----------
mu : array-like of shape n_samples or shape (n_simulations, n_samples)
expected values
Returns
-------
random_samples : np.array of same shape as mu | [
"Return",
"random",
"samples",
"from",
"this",
"Inverse",
"Gaussian",
"(",
"Wald",
")",
"distribution",
"."
] | python | train |
yyuu/botornado | boto/sdb/domain.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/sdb/domain.py#L232-L265 | def to_xml(self, f=None):
"""Get this domain as an XML DOM Document
:param f: Optional File to dump directly to
:type f: File or Stream
:return: File object where the XML has been dumped to
:rtype: file
"""
if not f:
from tempfile import TemporaryFile... | [
"def",
"to_xml",
"(",
"self",
",",
"f",
"=",
"None",
")",
":",
"if",
"not",
"f",
":",
"from",
"tempfile",
"import",
"TemporaryFile",
"f",
"=",
"TemporaryFile",
"(",
")",
"print",
">>",
"f",
",",
"'<?xml version=\"1.0\" encoding=\"UTF-8\"?>'",
"print",
">>",
... | Get this domain as an XML DOM Document
:param f: Optional File to dump directly to
:type f: File or Stream
:return: File object where the XML has been dumped to
:rtype: file | [
"Get",
"this",
"domain",
"as",
"an",
"XML",
"DOM",
"Document",
":",
"param",
"f",
":",
"Optional",
"File",
"to",
"dump",
"directly",
"to",
":",
"type",
"f",
":",
"File",
"or",
"Stream"
] | python | train |
jeffknupp/sandman | sandman/sandman.py | https://github.com/jeffknupp/sandman/blob/253ea4d15cbccd9f0016d66fedd7478614cc0b2f/sandman/sandman.py#L106-L118 | def _single_attribute_html_response(resource, name, value):
"""Return the json representation of a single attribute of a resource.
:param :class:`sandman.model.Model` resource: resource for attribute
:param string name: name of the attribute
:param string value: string value of the attribute
:rtyp... | [
"def",
"_single_attribute_html_response",
"(",
"resource",
",",
"name",
",",
"value",
")",
":",
"return",
"make_response",
"(",
"render_template",
"(",
"'attribute.html'",
",",
"resource",
"=",
"resource",
",",
"name",
"=",
"name",
",",
"value",
"=",
"value",
... | Return the json representation of a single attribute of a resource.
:param :class:`sandman.model.Model` resource: resource for attribute
:param string name: name of the attribute
:param string value: string value of the attribute
:rtype: :class:`flask.Response` | [
"Return",
"the",
"json",
"representation",
"of",
"a",
"single",
"attribute",
"of",
"a",
"resource",
"."
] | python | train |
NuGrid/NuGridPy | nugridpy/h5T.py | https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/h5T.py#L993-L1009 | def red_dim(self, array):
"""
This function reduces the dimensions of an array until it is
no longer of length 1.
"""
while isinstance(array, list) == True or \
isinstance(array, np.ndarray) == True:
try:
if len(array) == 1:
... | [
"def",
"red_dim",
"(",
"self",
",",
"array",
")",
":",
"while",
"isinstance",
"(",
"array",
",",
"list",
")",
"==",
"True",
"or",
"isinstance",
"(",
"array",
",",
"np",
".",
"ndarray",
")",
"==",
"True",
":",
"try",
":",
"if",
"len",
"(",
"array",
... | This function reduces the dimensions of an array until it is
no longer of length 1. | [
"This",
"function",
"reduces",
"the",
"dimensions",
"of",
"an",
"array",
"until",
"it",
"is",
"no",
"longer",
"of",
"length",
"1",
"."
] | python | train |
icgood/pymap | pymap/parsing/response/__init__.py | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/response/__init__.py#L102-L126 | def add_untagged(self, *responses: 'Response') -> None:
"""Add an untagged response. These responses are shown before the
parent response.
Args:
responses: The untagged responses to add.
"""
for resp in responses:
try:
merge_key = resp.me... | [
"def",
"add_untagged",
"(",
"self",
",",
"*",
"responses",
":",
"'Response'",
")",
"->",
"None",
":",
"for",
"resp",
"in",
"responses",
":",
"try",
":",
"merge_key",
"=",
"resp",
".",
"merge_key",
"except",
"TypeError",
":",
"self",
".",
"_untagged",
"."... | Add an untagged response. These responses are shown before the
parent response.
Args:
responses: The untagged responses to add. | [
"Add",
"an",
"untagged",
"response",
".",
"These",
"responses",
"are",
"shown",
"before",
"the",
"parent",
"response",
"."
] | python | train |
inasafe/inasafe | safe/common/utilities.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L53-L72 | def python2_round(number, ndigits=0):
"""Python 2 round function,
see: http://python3porting.com/differences.html#rounding-behavior
The behavior of round has changed in Python 3. In Python 2, rounding of
halfway cases was away from zero, and round() would always return a float.
Round a number to a ... | [
"def",
"python2_round",
"(",
"number",
",",
"ndigits",
"=",
"0",
")",
":",
"p",
"=",
"10",
"**",
"ndigits",
"return",
"float",
"(",
"math",
".",
"floor",
"(",
"(",
"number",
"*",
"p",
")",
"+",
"math",
".",
"copysign",
"(",
"0.5",
",",
"number",
... | Python 2 round function,
see: http://python3porting.com/differences.html#rounding-behavior
The behavior of round has changed in Python 3. In Python 2, rounding of
halfway cases was away from zero, and round() would always return a float.
Round a number to a given precision in decimal digits (default 0 ... | [
"Python",
"2",
"round",
"function",
"see",
":",
"http",
":",
"//",
"python3porting",
".",
"com",
"/",
"differences",
".",
"html#rounding",
"-",
"behavior",
"The",
"behavior",
"of",
"round",
"has",
"changed",
"in",
"Python",
"3",
".",
"In",
"Python",
"2",
... | python | train |
n1analytics/python-paillier | phe/encoding.py | https://github.com/n1analytics/python-paillier/blob/955f8c0bfa9623be15b75462b121d28acf70f04b/phe/encoding.py#L235-L265 | def decrease_exponent_to(self, new_exp):
"""Return an `EncodedNumber` with same value but lower exponent.
If we multiply the encoded value by :attr:`BASE` and decrement
:attr:`exponent`, then the decoded value does not change. Thus
we can almost arbitrarily ratchet down the exponent of ... | [
"def",
"decrease_exponent_to",
"(",
"self",
",",
"new_exp",
")",
":",
"if",
"new_exp",
">",
"self",
".",
"exponent",
":",
"raise",
"ValueError",
"(",
"'New exponent %i should be more negative than'",
"'old exponent %i'",
"%",
"(",
"new_exp",
",",
"self",
".",
"exp... | Return an `EncodedNumber` with same value but lower exponent.
If we multiply the encoded value by :attr:`BASE` and decrement
:attr:`exponent`, then the decoded value does not change. Thus
we can almost arbitrarily ratchet down the exponent of an
:class:`EncodedNumber` - we only run into... | [
"Return",
"an",
"EncodedNumber",
"with",
"same",
"value",
"but",
"lower",
"exponent",
"."
] | python | train |
Stewori/pytypes | pytypes/type_util.py | https://github.com/Stewori/pytypes/blob/b814d38709e84c0e0825caf8b721c20eb5a8ab3b/pytypes/type_util.py#L1204-L1226 | def _select_Generic_superclass_parameters(subclass, superclass_origin):
"""Helper for _issubclass_Generic.
"""
subclass = _find_base_with_origin(subclass, superclass_origin)
if subclass is None:
return None
if subclass.__origin__ is superclass_origin:
return subclass.__args__
prm... | [
"def",
"_select_Generic_superclass_parameters",
"(",
"subclass",
",",
"superclass_origin",
")",
":",
"subclass",
"=",
"_find_base_with_origin",
"(",
"subclass",
",",
"superclass_origin",
")",
"if",
"subclass",
"is",
"None",
":",
"return",
"None",
"if",
"subclass",
"... | Helper for _issubclass_Generic. | [
"Helper",
"for",
"_issubclass_Generic",
"."
] | python | train |
saltstack/salt | salt/modules/yumpkg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/yumpkg.py#L1926-L1946 | def update(name=None,
pkgs=None,
refresh=True,
skip_verify=False,
normalize=True,
minimal=False,
obsoletes=False,
**kwargs):
'''
.. versionadded:: 2019.2.0
Calls :py:func:`pkg.upgrade <salt.modules.yumpkg.upgrade>` with
``obso... | [
"def",
"update",
"(",
"name",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"refresh",
"=",
"True",
",",
"skip_verify",
"=",
"False",
",",
"normalize",
"=",
"True",
",",
"minimal",
"=",
"False",
",",
"obsoletes",
"=",
"False",
",",
"*",
"*",
"kwargs",
... | .. versionadded:: 2019.2.0
Calls :py:func:`pkg.upgrade <salt.modules.yumpkg.upgrade>` with
``obsoletes=False``. Mirrors the CLI behavior of ``yum update``.
See :py:func:`pkg.upgrade <salt.modules.yumpkg.upgrade>` for
further documentation.
.. code-block:: bash
salt '*' pkg.update | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | python | train |
materialsproject/pymatgen | pymatgen/alchemy/materials.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/alchemy/materials.py#L250-L257 | def structures(self):
"""
Copy of all structures in the TransformedStructure. A
structure is stored after every single transformation.
"""
hstructs = [Structure.from_dict(s['input_structure'])
for s in self.history if 'input_structure' in s]
return hst... | [
"def",
"structures",
"(",
"self",
")",
":",
"hstructs",
"=",
"[",
"Structure",
".",
"from_dict",
"(",
"s",
"[",
"'input_structure'",
"]",
")",
"for",
"s",
"in",
"self",
".",
"history",
"if",
"'input_structure'",
"in",
"s",
"]",
"return",
"hstructs",
"+",... | Copy of all structures in the TransformedStructure. A
structure is stored after every single transformation. | [
"Copy",
"of",
"all",
"structures",
"in",
"the",
"TransformedStructure",
".",
"A",
"structure",
"is",
"stored",
"after",
"every",
"single",
"transformation",
"."
] | python | train |
shoebot/shoebot | lib/photobot/__init__.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/photobot/__init__.py#L412-L419 | def delete(self):
"""Removes this layer from the canvas.
"""
i = self.index()
if i != None: del self.canvas.layers[i] | [
"def",
"delete",
"(",
"self",
")",
":",
"i",
"=",
"self",
".",
"index",
"(",
")",
"if",
"i",
"!=",
"None",
":",
"del",
"self",
".",
"canvas",
".",
"layers",
"[",
"i",
"]"
] | Removes this layer from the canvas. | [
"Removes",
"this",
"layer",
"from",
"the",
"canvas",
"."
] | python | valid |
hobson/pug-dj | pug/dj/explore.py | https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/explore.py#L516-L577 | def index_model_field_batches(model_or_queryset, key_fields=['model_number', 'serial_number'], value_fields=['pk'],
key_formatter=lambda x: str.lstrip(str.strip(str(x or '')), '0'),
value_formatter=lambda x: str.strip(str(x)), batch_len=10000,
limit=100000000, verbosity=1):
'''Like index_model_field e... | [
"def",
"index_model_field_batches",
"(",
"model_or_queryset",
",",
"key_fields",
"=",
"[",
"'model_number'",
",",
"'serial_number'",
"]",
",",
"value_fields",
"=",
"[",
"'pk'",
"]",
",",
"key_formatter",
"=",
"lambda",
"x",
":",
"str",
".",
"lstrip",
"(",
"str... | Like index_model_field except uses 50x less memory and 10x more processing cycles
Returns 2 dicts where both the keys and values are tuples:
target_index = {(<key_fields[0]>, <key_fields[1]>, ...): (<value_fields[0]>,)} for all distinct model-serial pairs in the Sales queryset
target_dupes = {(<key_fields... | [
"Like",
"index_model_field",
"except",
"uses",
"50x",
"less",
"memory",
"and",
"10x",
"more",
"processing",
"cycles"
] | python | train |
thespacedoctor/HMpTy | HMpTy/htm/sets.py | https://github.com/thespacedoctor/HMpTy/blob/3ce2bdb7ce3351468962ab907ede9a6074c15912/HMpTy/htm/sets.py#L88-L130 | def _extract_all_sets_from_list(
self):
"""*Extract all of the sets from the list of coordinates*
**Return:**
- ``allMatches`` -- a list of lists. All of the assocaited sets of sources
"""
self.log.debug('starting the ``_extract_all_sets_from_list`` method')
... | [
"def",
"_extract_all_sets_from_list",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_extract_all_sets_from_list`` method'",
")",
"from",
"HMpTy",
"import",
"HTM",
"mesh",
"=",
"HTM",
"(",
"depth",
"=",
"12",
",",
"log",
"=",
"s... | *Extract all of the sets from the list of coordinates*
**Return:**
- ``allMatches`` -- a list of lists. All of the assocaited sets of sources | [
"*",
"Extract",
"all",
"of",
"the",
"sets",
"from",
"the",
"list",
"of",
"coordinates",
"*"
] | python | train |
opencobra/memote | memote/experimental/config.py | https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/experimental/config.py#L171-L178 | def get_path(self, obj, default):
"""Return a relative or absolute path to experimental data."""
path = obj.get("path")
if path is None:
path = join(self._base, default)
if not isabs(path):
path = join(self._base, path)
return path | [
"def",
"get_path",
"(",
"self",
",",
"obj",
",",
"default",
")",
":",
"path",
"=",
"obj",
".",
"get",
"(",
"\"path\"",
")",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"join",
"(",
"self",
".",
"_base",
",",
"default",
")",
"if",
"not",
"isabs"... | Return a relative or absolute path to experimental data. | [
"Return",
"a",
"relative",
"or",
"absolute",
"path",
"to",
"experimental",
"data",
"."
] | python | train |
Kane610/axis | axis/utils.py | https://github.com/Kane610/axis/blob/b2b44ce595c7b722b5e13eabcab7b91f048e1808/axis/utils.py#L11-L34 | def session_request(session, url, **kwargs):
"""Do HTTP/S request and return response as a string."""
try:
response = session(url, **kwargs)
response.raise_for_status()
return response.text
except requests.exceptions.HTTPError as errh:
_LOGGER.debug("%s, %s", response, err... | [
"def",
"session_request",
"(",
"session",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"response",
"=",
"session",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
"response",
".",
"raise_for_status",
"(",
")",
"return",
"response",
".",
"text",... | Do HTTP/S request and return response as a string. | [
"Do",
"HTTP",
"/",
"S",
"request",
"and",
"return",
"response",
"as",
"a",
"string",
"."
] | python | train |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L1759-L1773 | def Likelihood(self, data):
"""Computes the likelihood of the data.
Selects a random vector of probabilities from this distribution.
Returns: float probability
"""
m = len(data)
if self.n < m:
return 0
x = data
p = self.Random()
q = ... | [
"def",
"Likelihood",
"(",
"self",
",",
"data",
")",
":",
"m",
"=",
"len",
"(",
"data",
")",
"if",
"self",
".",
"n",
"<",
"m",
":",
"return",
"0",
"x",
"=",
"data",
"p",
"=",
"self",
".",
"Random",
"(",
")",
"q",
"=",
"p",
"[",
":",
"m",
"... | Computes the likelihood of the data.
Selects a random vector of probabilities from this distribution.
Returns: float probability | [
"Computes",
"the",
"likelihood",
"of",
"the",
"data",
"."
] | python | train |
mozilla/configman | configman/config_manager.py | https://github.com/mozilla/configman/blob/83159fed61cc4cbbe5a4a6a00d3acad8a0c39c96/configman/config_manager.py#L565-L603 | def _create_reference_value_options(self, keys, finished_keys):
"""this method steps through the option definitions looking for
alt paths. On finding one, it creates the 'reference_value_from' links
within the option definitions and populates it with copied options."""
# a set of known ... | [
"def",
"_create_reference_value_options",
"(",
"self",
",",
"keys",
",",
"finished_keys",
")",
":",
"# a set of known reference_value_from_links",
"set_of_reference_value_option_names",
"=",
"set",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
"in",
"finishe... | this method steps through the option definitions looking for
alt paths. On finding one, it creates the 'reference_value_from' links
within the option definitions and populates it with copied options. | [
"this",
"method",
"steps",
"through",
"the",
"option",
"definitions",
"looking",
"for",
"alt",
"paths",
".",
"On",
"finding",
"one",
"it",
"creates",
"the",
"reference_value_from",
"links",
"within",
"the",
"option",
"definitions",
"and",
"populates",
"it",
"wit... | python | train |
hydpy-dev/hydpy | hydpy/core/sequencetools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L1005-L1088 | def adjust_short_series(self, timegrid, values):
"""Adjust a short time series to a longer timegrid.
Normally, time series data to be read from a external data files
should span (at least) the whole initialization time period of a
HydPy project. However, for some variables which are on... | [
"def",
"adjust_short_series",
"(",
"self",
",",
"timegrid",
",",
"values",
")",
":",
"idxs",
"=",
"[",
"timegrid",
"[",
"hydpy",
".",
"pub",
".",
"timegrids",
".",
"init",
".",
"firstdate",
"]",
",",
"timegrid",
"[",
"hydpy",
".",
"pub",
".",
"timegrid... | Adjust a short time series to a longer timegrid.
Normally, time series data to be read from a external data files
should span (at least) the whole initialization time period of a
HydPy project. However, for some variables which are only used
for comparison (e.g. observed runoff used fo... | [
"Adjust",
"a",
"short",
"time",
"series",
"to",
"a",
"longer",
"timegrid",
"."
] | python | train |
sibirrer/lenstronomy | lenstronomy/Cosmo/nfw_param.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Cosmo/nfw_param.py#L52-L57 | def rho0_c(self, c):
"""
computes density normalization as a function of concentration parameter
:return: density normalization in h^2/Mpc^3 (comoving)
"""
return 200./3*self.rhoc*c**3/(np.log(1.+c)-c/(1.+c)) | [
"def",
"rho0_c",
"(",
"self",
",",
"c",
")",
":",
"return",
"200.",
"/",
"3",
"*",
"self",
".",
"rhoc",
"*",
"c",
"**",
"3",
"/",
"(",
"np",
".",
"log",
"(",
"1.",
"+",
"c",
")",
"-",
"c",
"/",
"(",
"1.",
"+",
"c",
")",
")"
] | computes density normalization as a function of concentration parameter
:return: density normalization in h^2/Mpc^3 (comoving) | [
"computes",
"density",
"normalization",
"as",
"a",
"function",
"of",
"concentration",
"parameter",
":",
"return",
":",
"density",
"normalization",
"in",
"h^2",
"/",
"Mpc^3",
"(",
"comoving",
")"
] | python | train |
frc1418/tbapy | tbapy/main.py | https://github.com/frc1418/tbapy/blob/3866d5a9971fe3dfaf1a1d83638bd6be6070f0c4/tbapy/main.py#L110-L118 | def team(self, team, simple=False):
"""
Get data on a single specified team.
:param team: Team to get data for.
:param simple: Get only vital data.
:return: Team object with data on specified team.
"""
return Team(self._get('team/%s%s' % (self.team_key(team), '/s... | [
"def",
"team",
"(",
"self",
",",
"team",
",",
"simple",
"=",
"False",
")",
":",
"return",
"Team",
"(",
"self",
".",
"_get",
"(",
"'team/%s%s'",
"%",
"(",
"self",
".",
"team_key",
"(",
"team",
")",
",",
"'/simple'",
"if",
"simple",
"else",
"''",
")"... | Get data on a single specified team.
:param team: Team to get data for.
:param simple: Get only vital data.
:return: Team object with data on specified team. | [
"Get",
"data",
"on",
"a",
"single",
"specified",
"team",
"."
] | python | train |
kodethon/KoDrive | kodrive/cli.py | https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L406-L410 | def start(**kwargs):
''' Start KodeDrive daemon. '''
output, err = cli_syncthing_adapter.start(**kwargs)
click.echo("%s" % output, err=err) | [
"def",
"start",
"(",
"*",
"*",
"kwargs",
")",
":",
"output",
",",
"err",
"=",
"cli_syncthing_adapter",
".",
"start",
"(",
"*",
"*",
"kwargs",
")",
"click",
".",
"echo",
"(",
"\"%s\"",
"%",
"output",
",",
"err",
"=",
"err",
")"
] | Start KodeDrive daemon. | [
"Start",
"KodeDrive",
"daemon",
"."
] | python | train |
horejsek/python-fastjsonschema | fastjsonschema/draft07.py | https://github.com/horejsek/python-fastjsonschema/blob/8c38d0f91fa5d928ff629080cdb75ab23f96590f/fastjsonschema/draft07.py#L29-L73 | def generate_if_then_else(self):
"""
Implementation of if-then-else.
.. code-block:: python
{
'if': {
'exclusiveMaximum': 0,
},
'then': {
'minimum': -10,
},
'else... | [
"def",
"generate_if_then_else",
"(",
"self",
")",
":",
"with",
"self",
".",
"l",
"(",
"'try:'",
")",
":",
"self",
".",
"generate_func_code_block",
"(",
"self",
".",
"_definition",
"[",
"'if'",
"]",
",",
"self",
".",
"_variable",
",",
"self",
".",
"_varia... | Implementation of if-then-else.
.. code-block:: python
{
'if': {
'exclusiveMaximum': 0,
},
'then': {
'minimum': -10,
},
'else': {
'multipleOf': 2,
... | [
"Implementation",
"of",
"if",
"-",
"then",
"-",
"else",
"."
] | python | train |
testing-cabal/systemfixtures | systemfixtures/executable.py | https://github.com/testing-cabal/systemfixtures/blob/adf1b822bf83dc2a2f6bf7b85b5d8055e5e6ccd4/systemfixtures/executable.py#L115-L127 | def allocate_port():
"""Allocate an unused port.
There is a small race condition here (between the time we allocate the
port, and the time it actually gets used), but for the purposes for which
this function gets used it isn't a problem in practice.
"""
sock = socket.socket()
try:
s... | [
"def",
"allocate_port",
"(",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
")",
"try",
":",
"sock",
".",
"bind",
"(",
"(",
"\"localhost\"",
",",
"0",
")",
")",
"return",
"get_port",
"(",
"sock",
")",
"finally",
":",
"sock",
".",
"close",
"("... | Allocate an unused port.
There is a small race condition here (between the time we allocate the
port, and the time it actually gets used), but for the purposes for which
this function gets used it isn't a problem in practice. | [
"Allocate",
"an",
"unused",
"port",
"."
] | python | train |
micahhausler/container-transform | container_transform/ecs.py | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/ecs.py#L70-L77 | def add_volume(self, volume):
"""
Add a volume to self.volumes if it isn't already present
"""
for old_vol in self.volumes:
if volume == old_vol:
return
self.volumes.append(volume) | [
"def",
"add_volume",
"(",
"self",
",",
"volume",
")",
":",
"for",
"old_vol",
"in",
"self",
".",
"volumes",
":",
"if",
"volume",
"==",
"old_vol",
":",
"return",
"self",
".",
"volumes",
".",
"append",
"(",
"volume",
")"
] | Add a volume to self.volumes if it isn't already present | [
"Add",
"a",
"volume",
"to",
"self",
".",
"volumes",
"if",
"it",
"isn",
"t",
"already",
"present"
] | python | train |
frmdstryr/enamlx | enamlx/widgets/abstract_item_view.py | https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/widgets/abstract_item_view.py#L194-L197 | def child_removed(self, child):
""" Reset the item cache when a child is removed """
super(AbstractItemView, self).child_removed(child)
self.get_member('_items').reset(self) | [
"def",
"child_removed",
"(",
"self",
",",
"child",
")",
":",
"super",
"(",
"AbstractItemView",
",",
"self",
")",
".",
"child_removed",
"(",
"child",
")",
"self",
".",
"get_member",
"(",
"'_items'",
")",
".",
"reset",
"(",
"self",
")"
] | Reset the item cache when a child is removed | [
"Reset",
"the",
"item",
"cache",
"when",
"a",
"child",
"is",
"removed"
] | python | train |
Chilipp/sphinx-nbexamples | sphinx_nbexamples/__init__.py | https://github.com/Chilipp/sphinx-nbexamples/blob/08e0319ff3c70f8a931dfa8890caf48add4d0470/sphinx_nbexamples/__init__.py#L244-L251 | def url(self):
"""The url on jupyter nbviewer for this notebook or None if unknown"""
if self._url is not None:
url = self._url
else:
url = getattr(self.nb.metadata, 'url', None)
if url is not None:
return nbviewer_link(url) | [
"def",
"url",
"(",
"self",
")",
":",
"if",
"self",
".",
"_url",
"is",
"not",
"None",
":",
"url",
"=",
"self",
".",
"_url",
"else",
":",
"url",
"=",
"getattr",
"(",
"self",
".",
"nb",
".",
"metadata",
",",
"'url'",
",",
"None",
")",
"if",
"url",... | The url on jupyter nbviewer for this notebook or None if unknown | [
"The",
"url",
"on",
"jupyter",
"nbviewer",
"for",
"this",
"notebook",
"or",
"None",
"if",
"unknown"
] | python | test |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L4313-L4333 | def ekopn(fname, ifname, ncomch):
"""
Open a new E-kernel file and prepare the file for writing.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopn_c.html
:param fname: Name of EK file.
:type fname: str
:param ifname: Internal file name.
:type ifname: str
:param ncomch: The ... | [
"def",
"ekopn",
"(",
"fname",
",",
"ifname",
",",
"ncomch",
")",
":",
"fname",
"=",
"stypes",
".",
"stringToCharP",
"(",
"fname",
")",
"ifname",
"=",
"stypes",
".",
"stringToCharP",
"(",
"ifname",
")",
"ncomch",
"=",
"ctypes",
".",
"c_int",
"(",
"ncomc... | Open a new E-kernel file and prepare the file for writing.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekopn_c.html
:param fname: Name of EK file.
:type fname: str
:param ifname: Internal file name.
:type ifname: str
:param ncomch: The number of characters to reserve for comments.
... | [
"Open",
"a",
"new",
"E",
"-",
"kernel",
"file",
"and",
"prepare",
"the",
"file",
"for",
"writing",
"."
] | python | train |
deepmind/sonnet | sonnet/python/modules/relational_memory.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/relational_memory.py#L236-L272 | def _build(self, inputs, memory, treat_input_as_matrix=False):
"""Adds relational memory to the TensorFlow graph.
Args:
inputs: Tensor input.
memory: Memory output from the previous time step.
treat_input_as_matrix: Optional, whether to treat `input` as a sequence
of matrices. Default... | [
"def",
"_build",
"(",
"self",
",",
"inputs",
",",
"memory",
",",
"treat_input_as_matrix",
"=",
"False",
")",
":",
"if",
"treat_input_as_matrix",
":",
"inputs",
"=",
"basic",
".",
"BatchFlatten",
"(",
"preserve_dims",
"=",
"2",
")",
"(",
"inputs",
")",
"inp... | Adds relational memory to the TensorFlow graph.
Args:
inputs: Tensor input.
memory: Memory output from the previous time step.
treat_input_as_matrix: Optional, whether to treat `input` as a sequence
of matrices. Defaulta to False, in which case the input is flattened
into a vector... | [
"Adds",
"relational",
"memory",
"to",
"the",
"TensorFlow",
"graph",
"."
] | python | train |
DataDog/integrations-core | datadog_checks_dev/datadog_checks/dev/tooling/commands/dep.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_dev/datadog_checks/dev/tooling/commands/dep.py#L60-L86 | def resolve(checks, lazy, quiet):
"""Resolve transient dependencies for any number of checks.
If you want to do this en masse, put `all`.
"""
root = get_root()
if 'all' in checks:
checks = os.listdir(root)
for check_name in sorted(checks):
pinned_reqs_file = os.path.join(root, c... | [
"def",
"resolve",
"(",
"checks",
",",
"lazy",
",",
"quiet",
")",
":",
"root",
"=",
"get_root",
"(",
")",
"if",
"'all'",
"in",
"checks",
":",
"checks",
"=",
"os",
".",
"listdir",
"(",
"root",
")",
"for",
"check_name",
"in",
"sorted",
"(",
"checks",
... | Resolve transient dependencies for any number of checks.
If you want to do this en masse, put `all`. | [
"Resolve",
"transient",
"dependencies",
"for",
"any",
"number",
"of",
"checks",
".",
"If",
"you",
"want",
"to",
"do",
"this",
"en",
"masse",
"put",
"all",
"."
] | python | train |
saltstack/salt | salt/utils/url.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/url.py#L182-L201 | def redact_http_basic_auth(output):
'''
Remove HTTP user and password
'''
# We can't use re.compile because re.compile(someregex).sub() doesn't
# support flags even in Python 2.7.
url_re = '(https?)://.*@'
redacted = r'\1://<redacted>@'
if sys.version_info >= (2, 7):
# re.sub() s... | [
"def",
"redact_http_basic_auth",
"(",
"output",
")",
":",
"# We can't use re.compile because re.compile(someregex).sub() doesn't",
"# support flags even in Python 2.7.",
"url_re",
"=",
"'(https?)://.*@'",
"redacted",
"=",
"r'\\1://<redacted>@'",
"if",
"sys",
".",
"version_info",
... | Remove HTTP user and password | [
"Remove",
"HTTP",
"user",
"and",
"password"
] | python | train |
apache/incubator-mxnet | ci/build.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/ci/build.py#L189-L205 | def default_ccache_dir() -> str:
""":return: ccache directory for the current platform"""
# Share ccache across containers
if 'CCACHE_DIR' in os.environ:
ccache_dir = os.path.realpath(os.environ['CCACHE_DIR'])
try:
os.makedirs(ccache_dir, exist_ok=True)
return ccache_... | [
"def",
"default_ccache_dir",
"(",
")",
"->",
"str",
":",
"# Share ccache across containers",
"if",
"'CCACHE_DIR'",
"in",
"os",
".",
"environ",
":",
"ccache_dir",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"environ",
"[",
"'CCACHE_DIR'",
"]",
")... | :return: ccache directory for the current platform | [
":",
"return",
":",
"ccache",
"directory",
"for",
"the",
"current",
"platform"
] | python | train |
nilp0inter/cpe | cpe/cpe2_2.py | https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe2_2.py#L195-L238 | def as_wfn(self):
"""
Returns the CPE Name as WFN string of version 2.3.
Only shows the first seven components.
:return: CPE Name as WFN string
:rtype: string
:exception: TypeError - incompatible version
"""
wfn = []
wfn.append(CPE2_3_WFN.CPE_PRE... | [
"def",
"as_wfn",
"(",
"self",
")",
":",
"wfn",
"=",
"[",
"]",
"wfn",
".",
"append",
"(",
"CPE2_3_WFN",
".",
"CPE_PREFIX",
")",
"for",
"ck",
"in",
"CPEComponent",
".",
"CPE_COMP_KEYS",
":",
"lc",
"=",
"self",
".",
"_get_attribute_components",
"(",
"ck",
... | Returns the CPE Name as WFN string of version 2.3.
Only shows the first seven components.
:return: CPE Name as WFN string
:rtype: string
:exception: TypeError - incompatible version | [
"Returns",
"the",
"CPE",
"Name",
"as",
"WFN",
"string",
"of",
"version",
"2",
".",
"3",
".",
"Only",
"shows",
"the",
"first",
"seven",
"components",
"."
] | python | train |
gmr/rejected | rejected/mcp.py | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/mcp.py#L273-L303 | def is_dead(self, proc, name):
"""Checks to see if the specified process is dead.
:param psutil.Process proc: The process to check
:param str name: The name of consumer
:rtype: bool
"""
LOGGER.debug('Checking %s (%r)', name, proc)
try:
status = proc.... | [
"def",
"is_dead",
"(",
"self",
",",
"proc",
",",
"name",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Checking %s (%r)'",
",",
"name",
",",
"proc",
")",
"try",
":",
"status",
"=",
"proc",
".",
"status",
"(",
")",
"except",
"psutil",
".",
"NoSuchProcess",
... | Checks to see if the specified process is dead.
:param psutil.Process proc: The process to check
:param str name: The name of consumer
:rtype: bool | [
"Checks",
"to",
"see",
"if",
"the",
"specified",
"process",
"is",
"dead",
"."
] | python | train |
wgnet/webium | webium/wait.py | https://github.com/wgnet/webium/blob/ccb09876a201e75f5c5810392d4db7a8708b90cb/webium/wait.py#L7-L16 | def wait(*args, **kwargs):
"""
Wrapping 'wait()' method of 'waiting' library with default parameter values.
WebDriverException is ignored in the expected exceptions by default.
"""
kwargs.setdefault('sleep_seconds', (1, None))
kwargs.setdefault('expected_exceptions', WebDriverException)
kwar... | [
"def",
"wait",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'sleep_seconds'",
",",
"(",
"1",
",",
"None",
")",
")",
"kwargs",
".",
"setdefault",
"(",
"'expected_exceptions'",
",",
"WebDriverException",
")",
"kwa... | Wrapping 'wait()' method of 'waiting' library with default parameter values.
WebDriverException is ignored in the expected exceptions by default. | [
"Wrapping",
"wait",
"()",
"method",
"of",
"waiting",
"library",
"with",
"default",
"parameter",
"values",
".",
"WebDriverException",
"is",
"ignored",
"in",
"the",
"expected",
"exceptions",
"by",
"default",
"."
] | python | train |
pysathq/pysat | pysat/_fileio.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/_fileio.py#L162-L179 | def get_compression_type(self, file_name):
"""
Determine compression type for a given file using its extension.
:param file_name: a given file name
:type file_name: str
"""
ext = os.path.splitext(file_name)[1]
if ext == '.gz':
self.ctype... | [
"def",
"get_compression_type",
"(",
"self",
",",
"file_name",
")",
":",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_name",
")",
"[",
"1",
"]",
"if",
"ext",
"==",
"'.gz'",
":",
"self",
".",
"ctype",
"=",
"'gzip'",
"elif",
"ext",
"==",
... | Determine compression type for a given file using its extension.
:param file_name: a given file name
:type file_name: str | [
"Determine",
"compression",
"type",
"for",
"a",
"given",
"file",
"using",
"its",
"extension",
"."
] | python | train |
oscarbranson/latools | latools/filtering/classifier_obj.py | https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/filtering/classifier_obj.py#L67-L87 | def fitting_data(self, data):
"""
Function to format data for cluster fitting.
Parameters
----------
data : dict
A dict of data, containing all elements of
`analytes` as items.
Returns
-------
A data array for initial cluster fitt... | [
"def",
"fitting_data",
"(",
"self",
",",
"data",
")",
":",
"ds_fit",
",",
"_",
"=",
"self",
".",
"format_data",
"(",
"data",
",",
"scale",
"=",
"False",
")",
"# define scaler",
"self",
".",
"scaler",
"=",
"preprocessing",
".",
"StandardScaler",
"(",
")",... | Function to format data for cluster fitting.
Parameters
----------
data : dict
A dict of data, containing all elements of
`analytes` as items.
Returns
-------
A data array for initial cluster fitting. | [
"Function",
"to",
"format",
"data",
"for",
"cluster",
"fitting",
"."
] | python | test |
haifengat/hf_ctp_py_proxy | py_ctp/trade.py | https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L203-L217 | def _OnRspQryPositionDetail(self, pInvestorPositionDetail: CThostFtdcInvestorPositionDetailField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool):
"""持仓明细"""
if pInvestorPositionDetail.getInstrumentID() == '':
return
detail = PositionDetail()
detail.Instrume... | [
"def",
"_OnRspQryPositionDetail",
"(",
"self",
",",
"pInvestorPositionDetail",
":",
"CThostFtdcInvestorPositionDetailField",
",",
"pRspInfo",
":",
"CThostFtdcRspInfoField",
",",
"nRequestID",
":",
"int",
",",
"bIsLast",
":",
"bool",
")",
":",
"if",
"pInvestorPositionDet... | 持仓明细 | [
"持仓明细"
] | python | train |
dnanexus/dx-toolkit | src/python/dxpy/api.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/api.py#L611-L617 | def file_set_visibility(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /file-xxxx/setVisibility API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Visibility#API-method%3A-%2Fclass-xxxx%2FsetVisibility
"""
return DXHTTPRequest('/%s/setVisib... | [
"def",
"file_set_visibility",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/setVisibility'",
"%",
"object_id",
",",
"input_params",
",",
"always_... | Invokes the /file-xxxx/setVisibility API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Visibility#API-method%3A-%2Fclass-xxxx%2FsetVisibility | [
"Invokes",
"the",
"/",
"file",
"-",
"xxxx",
"/",
"setVisibility",
"API",
"method",
"."
] | python | train |
MIT-LCP/wfdb-python | wfdb/io/_signal.py | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/_signal.py#L667-L700 | def wr_dat_files(self, expanded=False, write_dir=''):
"""
Write each of the specified dat files
"""
# Get the set of dat files to be written, and
# the channels to be written to each file.
file_names, dat_channels = describe_list_indices(self.file_name)
# Get th... | [
"def",
"wr_dat_files",
"(",
"self",
",",
"expanded",
"=",
"False",
",",
"write_dir",
"=",
"''",
")",
":",
"# Get the set of dat files to be written, and",
"# the channels to be written to each file.",
"file_names",
",",
"dat_channels",
"=",
"describe_list_indices",
"(",
"... | Write each of the specified dat files | [
"Write",
"each",
"of",
"the",
"specified",
"dat",
"files"
] | python | train |
TheHive-Project/TheHive4py | thehive4py/api.py | https://github.com/TheHive-Project/TheHive4py/blob/35762bbd50d8376943268464326b59c752d6241b/thehive4py/api.py#L90-L104 | def create_case(self, case):
"""
:param case: The case details
:type case: Case defined in models.py
:return: TheHive case
:rtype: json
"""
req = self.url + "/api/case"
data = case.jsonify()
try:
return requests.post(req, headers={'Co... | [
"def",
"create_case",
"(",
"self",
",",
"case",
")",
":",
"req",
"=",
"self",
".",
"url",
"+",
"\"/api/case\"",
"data",
"=",
"case",
".",
"jsonify",
"(",
")",
"try",
":",
"return",
"requests",
".",
"post",
"(",
"req",
",",
"headers",
"=",
"{",
"'Co... | :param case: The case details
:type case: Case defined in models.py
:return: TheHive case
:rtype: json | [
":",
"param",
"case",
":",
"The",
"case",
"details",
":",
"type",
"case",
":",
"Case",
"defined",
"in",
"models",
".",
"py",
":",
"return",
":",
"TheHive",
"case",
":",
"rtype",
":",
"json"
] | python | train |
google/grr | grr/server/grr_response_server/aff4.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4.py#L144-L169 | def MultiOpen(self, urns, aff4_type=None, mode="r"):
"""Opens many urns efficiently, returning cached objects when possible."""
not_opened_urns = []
_ValidateAFF4Type(aff4_type)
for urn in urns:
key = self._ObjectKey(urn, mode)
try:
result = self._objects_cache[key]
if aff4_... | [
"def",
"MultiOpen",
"(",
"self",
",",
"urns",
",",
"aff4_type",
"=",
"None",
",",
"mode",
"=",
"\"r\"",
")",
":",
"not_opened_urns",
"=",
"[",
"]",
"_ValidateAFF4Type",
"(",
"aff4_type",
")",
"for",
"urn",
"in",
"urns",
":",
"key",
"=",
"self",
".",
... | Opens many urns efficiently, returning cached objects when possible. | [
"Opens",
"many",
"urns",
"efficiently",
"returning",
"cached",
"objects",
"when",
"possible",
"."
] | python | train |
assamite/creamas | creamas/core/simulation.py | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/simulation.py#L282-L291 | def end(self, folder=None):
"""End the simulation and destroy the current simulation environment.
"""
ret = self.env.destroy(folder=folder)
self._end_time = time.time()
self._log(logging.DEBUG, "Simulation run with {} steps took {:.3f}s to"
" complete, while act... | [
"def",
"end",
"(",
"self",
",",
"folder",
"=",
"None",
")",
":",
"ret",
"=",
"self",
".",
"env",
".",
"destroy",
"(",
"folder",
"=",
"folder",
")",
"self",
".",
"_end_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_log",
"(",
"logging",... | End the simulation and destroy the current simulation environment. | [
"End",
"the",
"simulation",
"and",
"destroy",
"the",
"current",
"simulation",
"environment",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.