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 |
|---|---|---|---|---|---|---|---|---|
teepark/greenhouse | greenhouse/ext/psycopg2.py | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/ext/psycopg2.py#L12-L32 | def wait_callback(connection):
"""callback function suitable for ``psycopg2.set_wait_callback``
pass this function to ``psycopg2.extensions.set_wait_callack`` to force any
blocking operations from psycopg2 to only block the current coroutine,
rather than the entire thread or process
to undo the ch... | [
"def",
"wait_callback",
"(",
"connection",
")",
":",
"while",
"1",
":",
"state",
"=",
"connection",
".",
"poll",
"(",
")",
"if",
"state",
"==",
"extensions",
".",
"POLL_OK",
":",
"break",
"elif",
"state",
"==",
"extensions",
".",
"POLL_READ",
":",
"descr... | callback function suitable for ``psycopg2.set_wait_callback``
pass this function to ``psycopg2.extensions.set_wait_callack`` to force any
blocking operations from psycopg2 to only block the current coroutine,
rather than the entire thread or process
to undo the change and return to normal blocking ope... | [
"callback",
"function",
"suitable",
"for",
"psycopg2",
".",
"set_wait_callback"
] | python | train |
ulule/django-badgify | badgify/recipe.py | https://github.com/ulule/django-badgify/blob/1bf233ffeb6293ee659454de7b3794682128b6ca/badgify/recipe.py#L101-L119 | def can_perform_awarding(self):
"""
Checks if we can perform awarding process (is ``user_ids`` property
defined? Does Badge object exists? and so on). If we can perform db
operations safely, returns ``True``. Otherwise, ``False``.
"""
if not self.user_ids:
log... | [
"def",
"can_perform_awarding",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"user_ids",
":",
"logger",
".",
"debug",
"(",
"'✘ Badge %s: no users to check (empty user_ids property)',",
"",
"self",
".",
"slug",
")",
"return",
"False",
"if",
"not",
"self",
".",... | Checks if we can perform awarding process (is ``user_ids`` property
defined? Does Badge object exists? and so on). If we can perform db
operations safely, returns ``True``. Otherwise, ``False``. | [
"Checks",
"if",
"we",
"can",
"perform",
"awarding",
"process",
"(",
"is",
"user_ids",
"property",
"defined?",
"Does",
"Badge",
"object",
"exists?",
"and",
"so",
"on",
")",
".",
"If",
"we",
"can",
"perform",
"db",
"operations",
"safely",
"returns",
"True",
... | python | train |
ciena/afkak | afkak/kafkacodec.py | https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/kafkacodec.py#L348-L369 | def decode_offset_response(cls, data):
"""
Decode bytes to an :class:`OffsetResponse`
:param bytes data: bytes to decode
"""
((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0)
for _i in range(num_topics):
(topic, cur) = read_short_ascii(da... | [
"def",
"decode_offset_response",
"(",
"cls",
",",
"data",
")",
":",
"(",
"(",
"correlation_id",
",",
"num_topics",
")",
",",
"cur",
")",
"=",
"relative_unpack",
"(",
"'>ii'",
",",
"data",
",",
"0",
")",
"for",
"_i",
"in",
"range",
"(",
"num_topics",
")... | Decode bytes to an :class:`OffsetResponse`
:param bytes data: bytes to decode | [
"Decode",
"bytes",
"to",
"an",
":",
"class",
":",
"OffsetResponse"
] | python | train |
biocommons/hgvs | hgvs/normalizer.py | https://github.com/biocommons/hgvs/blob/4d16efb475e1802b2531a2f1c373e8819d8e533b/hgvs/normalizer.py#L179-L258 | def _get_boundary(self, var):
"""Get the position of exon-intron boundary for current variant
"""
if var.type == "r" or var.type == "n":
if self.cross_boundaries:
return 0, float("inf")
else:
# Get genomic sequence access number for this tr... | [
"def",
"_get_boundary",
"(",
"self",
",",
"var",
")",
":",
"if",
"var",
".",
"type",
"==",
"\"r\"",
"or",
"var",
".",
"type",
"==",
"\"n\"",
":",
"if",
"self",
".",
"cross_boundaries",
":",
"return",
"0",
",",
"float",
"(",
"\"inf\"",
")",
"else",
... | Get the position of exon-intron boundary for current variant | [
"Get",
"the",
"position",
"of",
"exon",
"-",
"intron",
"boundary",
"for",
"current",
"variant"
] | python | train |
mitsei/dlkit | dlkit/handcar/osid/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/osid/objects.py#L632-L650 | def set_journal_comment(self, comment=None):
"""Sets a comment.
arg: comment (string): the new comment
raise: InvalidArgument - comment is invalid
raise: NoAccess - metadata.is_readonly() is true
raise: NullArgument - comment is null
compliance: mandatory - This me... | [
"def",
"set_journal_comment",
"(",
"self",
",",
"comment",
"=",
"None",
")",
":",
"if",
"comment",
"is",
"None",
":",
"raise",
"NullArgument",
"(",
")",
"metadata",
"=",
"Metadata",
"(",
"*",
"*",
"settings",
".",
"METADATA",
"[",
"'comment'",
"]",
")",
... | Sets a comment.
arg: comment (string): the new comment
raise: InvalidArgument - comment is invalid
raise: NoAccess - metadata.is_readonly() is true
raise: NullArgument - comment is null
compliance: mandatory - This method must be implemented. | [
"Sets",
"a",
"comment",
"."
] | python | train |
elifesciences/elife-article | elifearticle/parse.py | https://github.com/elifesciences/elife-article/blob/99710c213cd81fe6fd1e5c150d6e20efe2d1e33b/elifearticle/parse.py#L356-L373 | def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
... | [
"def",
"build_pub_dates",
"(",
"article",
",",
"pub_dates",
")",
":",
"for",
"pub_date",
"in",
"pub_dates",
":",
"# always want a date type, take it from pub-type if must",
"if",
"pub_date",
".",
"get",
"(",
"'date-type'",
")",
":",
"date_instance",
"=",
"ea",
".",
... | convert pub_dates into ArticleDate objects and add them to article | [
"convert",
"pub_dates",
"into",
"ArticleDate",
"objects",
"and",
"add",
"them",
"to",
"article"
] | python | train |
sdispater/pendulum | pendulum/parser.py | https://github.com/sdispater/pendulum/blob/94d28b0d3cb524ae02361bd1ed7ea03e2e655e4e/pendulum/parser.py#L23-L112 | def _parse(text, **options):
"""
Parses a string with the given options.
:param text: The string to parse.
:type text: str
:rtype: mixed
"""
# Handling special cases
if text == "now":
return pendulum.now()
parsed = base_parse(text, **options)
if isinstance(parsed, dat... | [
"def",
"_parse",
"(",
"text",
",",
"*",
"*",
"options",
")",
":",
"# Handling special cases",
"if",
"text",
"==",
"\"now\"",
":",
"return",
"pendulum",
".",
"now",
"(",
")",
"parsed",
"=",
"base_parse",
"(",
"text",
",",
"*",
"*",
"options",
")",
"if",... | Parses a string with the given options.
:param text: The string to parse.
:type text: str
:rtype: mixed | [
"Parses",
"a",
"string",
"with",
"the",
"given",
"options",
"."
] | python | train |
iotile/coretools | transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/connection_manager.py#L508-L546 | def _finish_disconnection_action(self, action):
"""Finish a disconnection attempt
There are two possible outcomes:
- if we were successful at disconnecting, we transition to disconnected
- if we failed at disconnecting, we transition back to idle
Args:
action (Conne... | [
"def",
"_finish_disconnection_action",
"(",
"self",
",",
"action",
")",
":",
"success",
"=",
"action",
".",
"data",
"[",
"'success'",
"]",
"conn_key",
"=",
"action",
".",
"data",
"[",
"'id'",
"]",
"if",
"self",
".",
"_get_connection_state",
"(",
"conn_key",
... | Finish a disconnection attempt
There are two possible outcomes:
- if we were successful at disconnecting, we transition to disconnected
- if we failed at disconnecting, we transition back to idle
Args:
action (ConnectionAction): the action object describing what we are
... | [
"Finish",
"a",
"disconnection",
"attempt"
] | python | train |
hydpy-dev/hydpy | hydpy/core/devicetools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/devicetools.py#L2154-L2229 | def plot_inputseries(
self, names: Optional[Iterable[str]] = None,
average: bool = False, **kwargs: Any) \
-> None:
"""Plot (the selected) |InputSequence| |IOSequence.series| values.
We demonstrate the functionalities of method |Element.plot_inputseries|
base... | [
"def",
"plot_inputseries",
"(",
"self",
",",
"names",
":",
"Optional",
"[",
"Iterable",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"average",
":",
"bool",
"=",
"False",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"__plot"... | Plot (the selected) |InputSequence| |IOSequence.series| values.
We demonstrate the functionalities of method |Element.plot_inputseries|
based on the `Lahn` example project:
>>> from hydpy.core.examples import prepare_full_example_2
>>> hp, _, _ = prepare_full_example_2(lastdate='1997-0... | [
"Plot",
"(",
"the",
"selected",
")",
"|InputSequence|",
"|IOSequence",
".",
"series|",
"values",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/fw_mgr.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fw_mgr.py#L907-L919 | def fill_fw_dict_from_db(self, fw_data):
"""
This routine is called to create a local fw_dict with data from DB.
"""
rule_dict = fw_data.get('rules').get('rules')
fw_dict = {'fw_id': fw_data.get('fw_id'),
'fw_name': fw_data.get('name'),
'fire... | [
"def",
"fill_fw_dict_from_db",
"(",
"self",
",",
"fw_data",
")",
":",
"rule_dict",
"=",
"fw_data",
".",
"get",
"(",
"'rules'",
")",
".",
"get",
"(",
"'rules'",
")",
"fw_dict",
"=",
"{",
"'fw_id'",
":",
"fw_data",
".",
"get",
"(",
"'fw_id'",
")",
",",
... | This routine is called to create a local fw_dict with data from DB. | [
"This",
"routine",
"is",
"called",
"to",
"create",
"a",
"local",
"fw_dict",
"with",
"data",
"from",
"DB",
"."
] | python | train |
gem/oq-engine | openquake/hazardlib/gsim/bradley_2013b.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/bradley_2013b.py#L63-L96 | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
#... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# extracting dictionary of coefficients specific to required",
"# intensity measure type.",
"C",
"=",
"self",
".",
"COEFFS",
"[",
"imt",
"... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | [
"See",
":",
"meth",
":",
"superclass",
"method",
"<",
".",
"base",
".",
"GroundShakingIntensityModel",
".",
"get_mean_and_stddevs",
">",
"for",
"spec",
"of",
"input",
"and",
"result",
"values",
"."
] | python | train |
NerdWalletOSS/savage | src/savage/api/data.py | https://github.com/NerdWalletOSS/savage/blob/54f64ac1c912528710365107952967d31d56e60d/src/savage/api/data.py#L104-L144 | def _format_response(rows, fields, unique_col_names):
"""This function will look at the data column of rows and extract the specified fields. It
will also dedup changes where the specified fields have not changed. The list of rows should
be ordered by the compound primary key which versioning pivots around ... | [
"def",
"_format_response",
"(",
"rows",
",",
"fields",
",",
"unique_col_names",
")",
":",
"output",
"=",
"[",
"]",
"old_id",
"=",
"None",
"for",
"row",
"in",
"rows",
":",
"id_",
"=",
"{",
"k",
":",
"row",
"[",
"k",
"]",
"for",
"k",
"in",
"unique_co... | This function will look at the data column of rows and extract the specified fields. It
will also dedup changes where the specified fields have not changed. The list of rows should
be ordered by the compound primary key which versioning pivots around and be in ascending
version order.
This function wil... | [
"This",
"function",
"will",
"look",
"at",
"the",
"data",
"column",
"of",
"rows",
"and",
"extract",
"the",
"specified",
"fields",
".",
"It",
"will",
"also",
"dedup",
"changes",
"where",
"the",
"specified",
"fields",
"have",
"not",
"changed",
".",
"The",
"li... | python | train |
sebp/scikit-survival | sksurv/io/arffwrite.py | https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L130-L146 | def _write_data(data, fp):
"""Write the data section"""
fp.write("@data\n")
def to_str(x):
if pandas.isnull(x):
return '?'
else:
return str(x)
data = data.applymap(to_str)
n_rows = data.shape[0]
for i in range(n_rows):
str_values = list(data.iloc... | [
"def",
"_write_data",
"(",
"data",
",",
"fp",
")",
":",
"fp",
".",
"write",
"(",
"\"@data\\n\"",
")",
"def",
"to_str",
"(",
"x",
")",
":",
"if",
"pandas",
".",
"isnull",
"(",
"x",
")",
":",
"return",
"'?'",
"else",
":",
"return",
"str",
"(",
"x",... | Write the data section | [
"Write",
"the",
"data",
"section"
] | python | train |
PythonCharmers/python-future | src/future/backports/email/__init__.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/__init__.py#L64-L70 | def message_from_file(fp, *args, **kws):
"""Read a file and parse its contents into a Message object model.
Optional _class and strict are passed to the Parser constructor.
"""
from future.backports.email.parser import Parser
return Parser(*args, **kws).parse(fp) | [
"def",
"message_from_file",
"(",
"fp",
",",
"*",
"args",
",",
"*",
"*",
"kws",
")",
":",
"from",
"future",
".",
"backports",
".",
"email",
".",
"parser",
"import",
"Parser",
"return",
"Parser",
"(",
"*",
"args",
",",
"*",
"*",
"kws",
")",
".",
"par... | Read a file and parse its contents into a Message object model.
Optional _class and strict are passed to the Parser constructor. | [
"Read",
"a",
"file",
"and",
"parse",
"its",
"contents",
"into",
"a",
"Message",
"object",
"model",
"."
] | python | train |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/reader.py | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/reader.py#L99-L165 | def get_regular_expressions(taxonomy_name, rebuild=False, no_cache=False):
"""Return a list of patterns compiled from the RDF/SKOS ontology.
Uses cache if it exists and if the taxonomy hasn't changed.
"""
# Translate the ontology name into a local path. Check if the name
# relates to an existing on... | [
"def",
"get_regular_expressions",
"(",
"taxonomy_name",
",",
"rebuild",
"=",
"False",
",",
"no_cache",
"=",
"False",
")",
":",
"# Translate the ontology name into a local path. Check if the name",
"# relates to an existing ontology.",
"onto_name",
",",
"onto_path",
",",
"onto... | Return a list of patterns compiled from the RDF/SKOS ontology.
Uses cache if it exists and if the taxonomy hasn't changed. | [
"Return",
"a",
"list",
"of",
"patterns",
"compiled",
"from",
"the",
"RDF",
"/",
"SKOS",
"ontology",
"."
] | python | train |
saltstack/salt | salt/modules/wordpress.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/wordpress.py#L54-L82 | def show_plugin(name, path, user):
'''
Show a plugin in a wordpress install and check if it is installed
name
Wordpress plugin name
path
path to wordpress install location
user
user to run the command as
CLI Example:
.. code-block:: bash
salt '*' wordpre... | [
"def",
"show_plugin",
"(",
"name",
",",
"path",
",",
"user",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
"}",
"resp",
"=",
"__salt__",
"[",
"'cmd.shell'",
"]",
"(",
"(",
"'wp --path={0} plugin status {1}'",
")",
".",
"format",
"(",
"path",
",",
"... | Show a plugin in a wordpress install and check if it is installed
name
Wordpress plugin name
path
path to wordpress install location
user
user to run the command as
CLI Example:
.. code-block:: bash
salt '*' wordpress.show_plugin HyperDB /var/www/html apache | [
"Show",
"a",
"plugin",
"in",
"a",
"wordpress",
"install",
"and",
"check",
"if",
"it",
"is",
"installed"
] | python | train |
cloudera/cm_api | python/src/cm_api/endpoints/services.py | https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/python/src/cm_api/endpoints/services.py#L640-L648 | def get_all_role_config_groups(self):
"""
Get a list of role configuration groups in the service.
@return: A list of ApiRoleConfigGroup objects.
@since: API v3
"""
return role_config_groups.get_all_role_config_groups(
self._get_resource_root(), self.name, self._get_cluster_name()) | [
"def",
"get_all_role_config_groups",
"(",
"self",
")",
":",
"return",
"role_config_groups",
".",
"get_all_role_config_groups",
"(",
"self",
".",
"_get_resource_root",
"(",
")",
",",
"self",
".",
"name",
",",
"self",
".",
"_get_cluster_name",
"(",
")",
")"
] | Get a list of role configuration groups in the service.
@return: A list of ApiRoleConfigGroup objects.
@since: API v3 | [
"Get",
"a",
"list",
"of",
"role",
"configuration",
"groups",
"in",
"the",
"service",
"."
] | python | train |
adamrehn/ue4cli | ue4cli/UnrealManagerBase.py | https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L258-L268 | def getThirdPartyLibFiles(self, libs):
"""
Retrieves the list of library files for building against the Unreal-bundled versions of the specified third-party libraries
"""
platformDefaults = True
if libs[0] == '--nodefaults':
platformDefaults = False
libs = libs[1:]
details = self.getThirdpartyLibs(... | [
"def",
"getThirdPartyLibFiles",
"(",
"self",
",",
"libs",
")",
":",
"platformDefaults",
"=",
"True",
"if",
"libs",
"[",
"0",
"]",
"==",
"'--nodefaults'",
":",
"platformDefaults",
"=",
"False",
"libs",
"=",
"libs",
"[",
"1",
":",
"]",
"details",
"=",
"sel... | Retrieves the list of library files for building against the Unreal-bundled versions of the specified third-party libraries | [
"Retrieves",
"the",
"list",
"of",
"library",
"files",
"for",
"building",
"against",
"the",
"Unreal",
"-",
"bundled",
"versions",
"of",
"the",
"specified",
"third",
"-",
"party",
"libraries"
] | python | train |
apache/incubator-mxnet | python/mxnet/initializer.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/initializer.py#L171-L217 | def _legacy_init(self, name, arr):
"""Legacy initialization method.
Parameters
----------
name : str
Name of corresponding NDArray.
arr : NDArray
NDArray to be initialized.
"""
warnings.warn(
"\033[91mCalling initializer with ... | [
"def",
"_legacy_init",
"(",
"self",
",",
"name",
",",
"arr",
")",
":",
"warnings",
".",
"warn",
"(",
"\"\\033[91mCalling initializer with init(str, NDArray) has been deprecated.\"",
"\"please use init(mx.init.InitDesc(...), NDArray) instead.\\033[0m\"",
",",
"DeprecationWarning",
... | Legacy initialization method.
Parameters
----------
name : str
Name of corresponding NDArray.
arr : NDArray
NDArray to be initialized. | [
"Legacy",
"initialization",
"method",
"."
] | python | train |
inspirehep/inspire-crawler | inspire_crawler/cli.py | https://github.com/inspirehep/inspire-crawler/blob/36d5cc0cd87cc597ba80e680b7de7254b120173a/inspire_crawler/cli.py#L147-L153 | def get_job_results(id):
"""Get the crawl results from the job."""
crawler_job = models.CrawlerJob.query.filter_by(id=id).one()
_show_file(
file_path=crawler_job.results,
header_name='Results',
) | [
"def",
"get_job_results",
"(",
"id",
")",
":",
"crawler_job",
"=",
"models",
".",
"CrawlerJob",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"id",
")",
".",
"one",
"(",
")",
"_show_file",
"(",
"file_path",
"=",
"crawler_job",
".",
"results",
",",
"h... | Get the crawl results from the job. | [
"Get",
"the",
"crawl",
"results",
"from",
"the",
"job",
"."
] | python | train |
ga4gh/ga4gh-server | ga4gh/server/datamodel/datasets.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datamodel/datasets.py#L233-L240 | def getFeatureSetByName(self, name):
"""
Returns the FeatureSet with the specified name, or raises
an exception otherwise.
"""
if name not in self._featureSetNameMap:
raise exceptions.FeatureSetNameNotFoundException(name)
return self._featureSetNameMap[name] | [
"def",
"getFeatureSetByName",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_featureSetNameMap",
":",
"raise",
"exceptions",
".",
"FeatureSetNameNotFoundException",
"(",
"name",
")",
"return",
"self",
".",
"_featureSetNameMap",
"["... | Returns the FeatureSet with the specified name, or raises
an exception otherwise. | [
"Returns",
"the",
"FeatureSet",
"with",
"the",
"specified",
"name",
"or",
"raises",
"an",
"exception",
"otherwise",
"."
] | python | train |
zsimic/runez | src/runez/base.py | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/base.py#L39-L55 | def decode(value, strip=False):
"""Python 2/3 friendly decoding of output.
Args:
value (str | unicode | bytes | None): The value to decode.
strip (bool): If True, `strip()` the returned string. (Default value = False)
Returns:
str: Decoded value, if applicable.
"""
if value... | [
"def",
"decode",
"(",
"value",
",",
"strip",
"=",
"False",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"bytes",
")",
"and",
"not",
"isinstance",
"(",
"value",
",",
"unicode",
")",
":",
"value",... | Python 2/3 friendly decoding of output.
Args:
value (str | unicode | bytes | None): The value to decode.
strip (bool): If True, `strip()` the returned string. (Default value = False)
Returns:
str: Decoded value, if applicable. | [
"Python",
"2",
"/",
"3",
"friendly",
"decoding",
"of",
"output",
"."
] | python | train |
ericmjl/pyflatten | pyflatten/__init__.py | https://github.com/ericmjl/pyflatten/blob/2a8f4a9a3164e4799a4086abe4c69cc89afc3b67/pyflatten/__init__.py#L14-L74 | def flatten(value):
"""value can be any nesting of tuples, arrays, dicts.
returns 1D numpy array and an unflatten function."""
if isinstance(value, np.ndarray):
def unflatten(vector):
return np.reshape(vector, value.shape)
return np.ravel(value), unflatten
elif isinstance... | [
"def",
"flatten",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"np",
".",
"ndarray",
")",
":",
"def",
"unflatten",
"(",
"vector",
")",
":",
"return",
"np",
".",
"reshape",
"(",
"vector",
",",
"value",
".",
"shape",
")",
"return",
... | value can be any nesting of tuples, arrays, dicts.
returns 1D numpy array and an unflatten function. | [
"value",
"can",
"be",
"any",
"nesting",
"of",
"tuples",
"arrays",
"dicts",
".",
"returns",
"1D",
"numpy",
"array",
"and",
"an",
"unflatten",
"function",
"."
] | python | train |
honzajavorek/redis-collections | redis_collections/sortedsets.py | https://github.com/honzajavorek/redis-collections/blob/07ca8efe88fb128f7dc7319dfa6a26cd39b3776b/redis_collections/sortedsets.py#L237-L248 | def get_score(self, member, default=None, pipe=None):
"""
Return the score of *member*, or *default* if it is not in the
collection.
"""
pipe = self.redis if pipe is None else pipe
score = pipe.zscore(self.key, self._pickle(member))
if (score is None) and (defaul... | [
"def",
"get_score",
"(",
"self",
",",
"member",
",",
"default",
"=",
"None",
",",
"pipe",
"=",
"None",
")",
":",
"pipe",
"=",
"self",
".",
"redis",
"if",
"pipe",
"is",
"None",
"else",
"pipe",
"score",
"=",
"pipe",
".",
"zscore",
"(",
"self",
".",
... | Return the score of *member*, or *default* if it is not in the
collection. | [
"Return",
"the",
"score",
"of",
"*",
"member",
"*",
"or",
"*",
"default",
"*",
"if",
"it",
"is",
"not",
"in",
"the",
"collection",
"."
] | python | train |
pkkid/python-plexapi | plexapi/myplex.py | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/myplex.py#L336-L354 | def _getSectionIds(self, server, sections):
""" Converts a list of section objects or names to sectionIds needed for library sharing. """
if not sections: return []
# Get a list of all section ids for looking up each section.
allSectionIds = {}
machineIdentifier = server.machineI... | [
"def",
"_getSectionIds",
"(",
"self",
",",
"server",
",",
"sections",
")",
":",
"if",
"not",
"sections",
":",
"return",
"[",
"]",
"# Get a list of all section ids for looking up each section.",
"allSectionIds",
"=",
"{",
"}",
"machineIdentifier",
"=",
"server",
".",... | Converts a list of section objects or names to sectionIds needed for library sharing. | [
"Converts",
"a",
"list",
"of",
"section",
"objects",
"or",
"names",
"to",
"sectionIds",
"needed",
"for",
"library",
"sharing",
"."
] | python | train |
robmarkcole/HASS-data-detective | detective/config.py | https://github.com/robmarkcole/HASS-data-detective/blob/f67dfde9dd63a3af411944d1857b0835632617c5/detective/config.py#L16-L29 | def find_hass_config():
"""Try to find HASS config."""
if "HASSIO_TOKEN" in os.environ:
return "/config"
config_dir = default_hass_config_dir()
if os.path.isdir(config_dir):
return config_dir
raise ValueError(
"Unable to automatically find the location of Home Assistant "
... | [
"def",
"find_hass_config",
"(",
")",
":",
"if",
"\"HASSIO_TOKEN\"",
"in",
"os",
".",
"environ",
":",
"return",
"\"/config\"",
"config_dir",
"=",
"default_hass_config_dir",
"(",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"config_dir",
")",
":",
"return"... | Try to find HASS config. | [
"Try",
"to",
"find",
"HASS",
"config",
"."
] | python | train |
rgmining/ria | ria/bipartite.py | https://github.com/rgmining/ria/blob/39223c67b7e59e10bd8e3a9062fb13f8bf893a5d/ria/bipartite.py#L432-L460 | def retrieve_review(self, reviewer, product):
"""Retrieve review that the given reviewer put the given product.
Args:
reviewer: An instance of Reviewer.
product: An instance of Product.
Returns:
A review object.
Raises:
TypeError: when given rev... | [
"def",
"retrieve_review",
"(",
"self",
",",
"reviewer",
",",
"product",
")",
":",
"if",
"not",
"isinstance",
"(",
"reviewer",
",",
"self",
".",
"_reviewer_cls",
")",
":",
"raise",
"TypeError",
"(",
"\"Type of given reviewer isn't acceptable:\"",
",",
"reviewer",
... | Retrieve review that the given reviewer put the given product.
Args:
reviewer: An instance of Reviewer.
product: An instance of Product.
Returns:
A review object.
Raises:
TypeError: when given reviewer and product aren't instance of
specifie... | [
"Retrieve",
"review",
"that",
"the",
"given",
"reviewer",
"put",
"the",
"given",
"product",
"."
] | python | train |
log2timeline/plaso | plaso/output/shared_elastic.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/output/shared_elastic.py#L280-L287 | def SetUsername(self, username):
"""Sets the username.
Args:
username (str): username to authenticate with.
"""
self._username = username
logger.debug('Elasticsearch username: {0!s}'.format(username)) | [
"def",
"SetUsername",
"(",
"self",
",",
"username",
")",
":",
"self",
".",
"_username",
"=",
"username",
"logger",
".",
"debug",
"(",
"'Elasticsearch username: {0!s}'",
".",
"format",
"(",
"username",
")",
")"
] | Sets the username.
Args:
username (str): username to authenticate with. | [
"Sets",
"the",
"username",
"."
] | python | train |
python-odin/odinweb | odinweb/decorators.py | https://github.com/python-odin/odinweb/blob/198424133584acc18cb41c8d18d91f803abc810f/odinweb/decorators.py#L503-L514 | def create(callback=None, path=None, method=Method.POST, resource=None, tags=None, summary="Create a new resource",
middleware=None):
# type: (Callable, Path, Methods, Resource, Tags, str, List[Any]) -> Operation
"""
Decorator to configure an operation that creates a resource.
"""
def inn... | [
"def",
"create",
"(",
"callback",
"=",
"None",
",",
"path",
"=",
"None",
",",
"method",
"=",
"Method",
".",
"POST",
",",
"resource",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"summary",
"=",
"\"Create a new resource\"",
",",
"middleware",
"=",
"None",
... | Decorator to configure an operation that creates a resource. | [
"Decorator",
"to",
"configure",
"an",
"operation",
"that",
"creates",
"a",
"resource",
"."
] | python | train |
etal/biocma | biocma/utils.py | https://github.com/etal/biocma/blob/eac0c57eb83a9498e53ccdeb9cbc3fe21a5826a7/biocma/utils.py#L159-L200 | def get_inserts(block):
"""Identify the inserts in sequence in a block.
Inserts are relative to the consensus (theoretically), and identified by
lowercase letters in the sequence. The returned integer pairs represent the
insert start and end positions in the full-length sequence, using one-based
nu... | [
"def",
"get_inserts",
"(",
"block",
")",
":",
"def",
"find_inserts",
"(",
"seq",
",",
"head_len",
")",
":",
"\"\"\"Locate the lowercase regions in a character sequence.\n\n Yield the insert ranges as tuples using 1-based numbering, shifted by\n head_len.\n \"\"\"",
... | Identify the inserts in sequence in a block.
Inserts are relative to the consensus (theoretically), and identified by
lowercase letters in the sequence. The returned integer pairs represent the
insert start and end positions in the full-length sequence, using one-based
numbering.
The first sequenc... | [
"Identify",
"the",
"inserts",
"in",
"sequence",
"in",
"a",
"block",
"."
] | python | train |
dnanexus/dx-toolkit | src/python/dxpy/bindings/dxjob.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/bindings/dxjob.py#L175-L188 | def set_id(self, dxid):
'''
:param dxid: New job ID to be associated with the handler (localjob IDs also accepted for local runs)
:type dxid: string
Discards the currently stored ID and associates the handler with *dxid*
'''
if dxid is not None:
if not (isins... | [
"def",
"set_id",
"(",
"self",
",",
"dxid",
")",
":",
"if",
"dxid",
"is",
"not",
"None",
":",
"if",
"not",
"(",
"isinstance",
"(",
"dxid",
",",
"basestring",
")",
"and",
"dxid",
".",
"startswith",
"(",
"'localjob-'",
")",
")",
":",
"# localjob IDs (whic... | :param dxid: New job ID to be associated with the handler (localjob IDs also accepted for local runs)
:type dxid: string
Discards the currently stored ID and associates the handler with *dxid* | [
":",
"param",
"dxid",
":",
"New",
"job",
"ID",
"to",
"be",
"associated",
"with",
"the",
"handler",
"(",
"localjob",
"IDs",
"also",
"accepted",
"for",
"local",
"runs",
")",
":",
"type",
"dxid",
":",
"string"
] | python | train |
thiagopbueno/rddl2tf | rddl2tf/compiler.py | https://github.com/thiagopbueno/rddl2tf/blob/f7c03d3a74d2663807c1e23e04eeed2e85166b71/rddl2tf/compiler.py#L321-L338 | def compile_action_preconditions_checking(self,
state: Sequence[tf.Tensor],
action: Sequence[tf.Tensor]) -> tf.Tensor:
'''Combines the action preconditions into an applicability checking op.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
ac... | [
"def",
"compile_action_preconditions_checking",
"(",
"self",
",",
"state",
":",
"Sequence",
"[",
"tf",
".",
"Tensor",
"]",
",",
"action",
":",
"Sequence",
"[",
"tf",
".",
"Tensor",
"]",
")",
"->",
"tf",
".",
"Tensor",
":",
"with",
"self",
".",
"graph",
... | Combines the action preconditions into an applicability checking op.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
action (Sequence[tf.Tensor]): The action fluents.
Returns:
A boolean tensor for checking if `action` is application in `state`. | [
"Combines",
"the",
"action",
"preconditions",
"into",
"an",
"applicability",
"checking",
"op",
"."
] | python | train |
GNS3/gns3-server | gns3server/compute/vmware/__init__.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vmware/__init__.py#L190-L240 | def check_vmware_version(self):
"""
Check VMware version
"""
if sys.platform.startswith("win"):
# look for vmrun.exe using the directory listed in the registry
ws_version = self._find_vmware_version_registry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Workstation"... | [
"def",
"check_vmware_version",
"(",
"self",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"# look for vmrun.exe using the directory listed in the registry",
"ws_version",
"=",
"self",
".",
"_find_vmware_version_registry",
"(",
"r\"... | Check VMware version | [
"Check",
"VMware",
"version"
] | python | train |
ellmetha/django-machina | machina/apps/forum/views.py | https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/views.py#L80-L89 | def get_queryset(self):
""" Returns the list of items for this view. """
self.forum = self.get_forum()
qs = (
self.forum.topics
.exclude(type=Topic.TOPIC_ANNOUNCE)
.exclude(approved=False)
.select_related('poster', 'last_post', 'last_post__poster')... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"self",
".",
"forum",
"=",
"self",
".",
"get_forum",
"(",
")",
"qs",
"=",
"(",
"self",
".",
"forum",
".",
"topics",
".",
"exclude",
"(",
"type",
"=",
"Topic",
".",
"TOPIC_ANNOUNCE",
")",
".",
"exclude",
... | Returns the list of items for this view. | [
"Returns",
"the",
"list",
"of",
"items",
"for",
"this",
"view",
"."
] | python | train |
hugapi/hug | hug/output_format.py | https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/hug/output_format.py#L277-L295 | def on_content_type(handlers, default=None, error='The requested content type does not match any of those allowed'):
"""Returns a content in a different format based on the clients provided content type,
should pass in a dict with the following format:
{'[content-type]': action,
...... | [
"def",
"on_content_type",
"(",
"handlers",
",",
"default",
"=",
"None",
",",
"error",
"=",
"'The requested content type does not match any of those allowed'",
")",
":",
"def",
"output_type",
"(",
"data",
",",
"request",
",",
"response",
")",
":",
"handler",
"=",
"... | Returns a content in a different format based on the clients provided content type,
should pass in a dict with the following format:
{'[content-type]': action,
...
} | [
"Returns",
"a",
"content",
"in",
"a",
"different",
"format",
"based",
"on",
"the",
"clients",
"provided",
"content",
"type",
"should",
"pass",
"in",
"a",
"dict",
"with",
"the",
"following",
"format",
":"
] | python | train |
antiboredom/videogrep | videogrep/videogrep.py | https://github.com/antiboredom/videogrep/blob/faffd3446d96242677757f1af7db23b6dfc429cf/videogrep/videogrep.py#L309-L371 | def compose_from_srts(srts, search, searchtype):
"""Takes a list of subtitle (srt) filenames, search term and search type
and, returns a list of timestamps for composing a supercut.
"""
composition = []
foundSearchTerm = False
# Iterate over each subtitles file.
for srt in srts:
pr... | [
"def",
"compose_from_srts",
"(",
"srts",
",",
"search",
",",
"searchtype",
")",
":",
"composition",
"=",
"[",
"]",
"foundSearchTerm",
"=",
"False",
"# Iterate over each subtitles file.",
"for",
"srt",
"in",
"srts",
":",
"print",
"(",
"srt",
")",
"lines",
"=",
... | Takes a list of subtitle (srt) filenames, search term and search type
and, returns a list of timestamps for composing a supercut. | [
"Takes",
"a",
"list",
"of",
"subtitle",
"(",
"srt",
")",
"filenames",
"search",
"term",
"and",
"search",
"type",
"and",
"returns",
"a",
"list",
"of",
"timestamps",
"for",
"composing",
"a",
"supercut",
"."
] | python | train |
allenai/allennlp | scripts/check_requirements_and_setup.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/scripts/check_requirements_and_setup.py#L32-L60 | def parse_requirements() -> Tuple[PackagesType, PackagesType, Set[str]]:
"""Parse all dependencies out of the requirements.txt file."""
essential_packages: PackagesType = {}
other_packages: PackagesType = {}
duplicates: Set[str] = set()
with open("requirements.txt", "r") as req_file:
section... | [
"def",
"parse_requirements",
"(",
")",
"->",
"Tuple",
"[",
"PackagesType",
",",
"PackagesType",
",",
"Set",
"[",
"str",
"]",
"]",
":",
"essential_packages",
":",
"PackagesType",
"=",
"{",
"}",
"other_packages",
":",
"PackagesType",
"=",
"{",
"}",
"duplicates... | Parse all dependencies out of the requirements.txt file. | [
"Parse",
"all",
"dependencies",
"out",
"of",
"the",
"requirements",
".",
"txt",
"file",
"."
] | python | train |
Zsailer/kubeconf | kubeconf/kubeconf.py | https://github.com/Zsailer/kubeconf/blob/b4e81001b5d2fb8d461056f25eb8b03307d57a6b/kubeconf/kubeconf.py#L303-L309 | def get_context(self, name):
"""Get context from kubeconfig."""
contexts = self.data['contexts']
for context in contexts:
if context['name'] == name:
return context
raise KubeConfError("context name not found.") | [
"def",
"get_context",
"(",
"self",
",",
"name",
")",
":",
"contexts",
"=",
"self",
".",
"data",
"[",
"'contexts'",
"]",
"for",
"context",
"in",
"contexts",
":",
"if",
"context",
"[",
"'name'",
"]",
"==",
"name",
":",
"return",
"context",
"raise",
"Kube... | Get context from kubeconfig. | [
"Get",
"context",
"from",
"kubeconfig",
"."
] | python | train |
googleapis/google-cloud-python | pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/pubsub/google/cloud/pubsub_v1/subscriber/_protocol/dispatcher.py#L131-L138 | def lease(self, items):
"""Add the given messages to lease management.
Args:
items(Sequence[LeaseRequest]): The items to lease.
"""
self._manager.leaser.add(items)
self._manager.maybe_pause_consumer() | [
"def",
"lease",
"(",
"self",
",",
"items",
")",
":",
"self",
".",
"_manager",
".",
"leaser",
".",
"add",
"(",
"items",
")",
"self",
".",
"_manager",
".",
"maybe_pause_consumer",
"(",
")"
] | Add the given messages to lease management.
Args:
items(Sequence[LeaseRequest]): The items to lease. | [
"Add",
"the",
"given",
"messages",
"to",
"lease",
"management",
"."
] | python | train |
GNS3/gns3-server | gns3server/compute/vpcs/vpcs_vm.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/compute/vpcs/vpcs_vm.py#L442-L465 | def stop_capture(self, port_number):
"""
Stops a packet capture.
:param port_number: port number
"""
if not self._ethernet_adapter.port_exists(port_number):
raise VPCSError("Port {port_number} doesn't exist in adapter {adapter}".format(adapter=self._ethernet_adapter... | [
"def",
"stop_capture",
"(",
"self",
",",
"port_number",
")",
":",
"if",
"not",
"self",
".",
"_ethernet_adapter",
".",
"port_exists",
"(",
"port_number",
")",
":",
"raise",
"VPCSError",
"(",
"\"Port {port_number} doesn't exist in adapter {adapter}\"",
".",
"format",
... | Stops a packet capture.
:param port_number: port number | [
"Stops",
"a",
"packet",
"capture",
"."
] | python | train |
cloud-custodian/cloud-custodian | c7n/actions/network.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/c7n/actions/network.py#L152-L182 | def resolve_group_names(self, r, target_group_ids, groups):
"""Resolve any security group names to the corresponding group ids
With the context of a given network attached resource.
"""
names = self.get_group_names(target_group_ids)
if not names:
return target_group_... | [
"def",
"resolve_group_names",
"(",
"self",
",",
"r",
",",
"target_group_ids",
",",
"groups",
")",
":",
"names",
"=",
"self",
".",
"get_group_names",
"(",
"target_group_ids",
")",
"if",
"not",
"names",
":",
"return",
"target_group_ids",
"target_group_ids",
"=",
... | Resolve any security group names to the corresponding group ids
With the context of a given network attached resource. | [
"Resolve",
"any",
"security",
"group",
"names",
"to",
"the",
"corresponding",
"group",
"ids"
] | python | train |
wohlgejm/accountable | accountable/cli.py | https://github.com/wohlgejm/accountable/blob/20586365ccd319061e5548ce14fb0b8f449580fa/accountable/cli.py#L209-L216 | def update(accountable, options):
"""
Update an existing issue.
"""
issue = accountable.issue_update(options)
headers = issue.keys()
rows = [headers, [v for k, v in issue.items()]]
print_table(SingleTable(rows)) | [
"def",
"update",
"(",
"accountable",
",",
"options",
")",
":",
"issue",
"=",
"accountable",
".",
"issue_update",
"(",
"options",
")",
"headers",
"=",
"issue",
".",
"keys",
"(",
")",
"rows",
"=",
"[",
"headers",
",",
"[",
"v",
"for",
"k",
",",
"v",
... | Update an existing issue. | [
"Update",
"an",
"existing",
"issue",
"."
] | python | train |
pytroll/pyspectral | pyspectral/atm_correction_ir.py | https://github.com/pytroll/pyspectral/blob/fd296c0e0bdf5364fa180134a1292665d6bc50a3/pyspectral/atm_correction_ir.py#L98-L132 | def viewzen_corr(data, view_zen):
"""Apply atmospheric correction on the given *data* using the
specified satellite zenith angles (*view_zen*). Both input data
are given as 2-dimensional Numpy (masked) arrays, and they should
have equal shapes.
The *data* array will be changed in place and has to be... | [
"def",
"viewzen_corr",
"(",
"data",
",",
"view_zen",
")",
":",
"def",
"ratio",
"(",
"value",
",",
"v_null",
",",
"v_ref",
")",
":",
"return",
"(",
"value",
"-",
"v_null",
")",
"/",
"(",
"v_ref",
"-",
"v_null",
")",
"def",
"tau0",
"(",
"t",
")",
"... | Apply atmospheric correction on the given *data* using the
specified satellite zenith angles (*view_zen*). Both input data
are given as 2-dimensional Numpy (masked) arrays, and they should
have equal shapes.
The *data* array will be changed in place and has to be copied before. | [
"Apply",
"atmospheric",
"correction",
"on",
"the",
"given",
"*",
"data",
"*",
"using",
"the",
"specified",
"satellite",
"zenith",
"angles",
"(",
"*",
"view_zen",
"*",
")",
".",
"Both",
"input",
"data",
"are",
"given",
"as",
"2",
"-",
"dimensional",
"Numpy"... | python | train |
wtolson/gnsq | gnsq/consumer.py | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/consumer.py#L251-L265 | def close(self):
"""Immediately close all connections and stop workers."""
if not self.is_running:
return
self._state = CLOSED
self.logger.debug('killing %d worker(s)', len(self._killables))
self._killables.kill(block=False)
self.logger.debug('closing %d co... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_running",
":",
"return",
"self",
".",
"_state",
"=",
"CLOSED",
"self",
".",
"logger",
".",
"debug",
"(",
"'killing %d worker(s)'",
",",
"len",
"(",
"self",
".",
"_killables",
")",
")"... | Immediately close all connections and stop workers. | [
"Immediately",
"close",
"all",
"connections",
"and",
"stop",
"workers",
"."
] | python | train |
neovim/pynvim | scripts/logging_statement_modifier.py | https://github.com/neovim/pynvim/blob/5e577188e6d7133f597ad0ce60dc6a4b1314064a/scripts/logging_statement_modifier.py#L172-L197 | def get_logging_level(logging_stmt, commented_out=False):
"""Determines the level of logging in a given logging statement. The string
representing this level is returned. False is returned if the method is
not a logging statement and thus has no level. None is returned if a level
should have been fou... | [
"def",
"get_logging_level",
"(",
"logging_stmt",
",",
"commented_out",
"=",
"False",
")",
":",
"regexp",
"=",
"RE_LOGGING_START_IN_COMMENT",
"if",
"commented_out",
"else",
"RE_LOGGING_START",
"ret",
"=",
"regexp",
".",
"match",
"(",
"logging_stmt",
")",
"_",
",",
... | Determines the level of logging in a given logging statement. The string
representing this level is returned. False is returned if the method is
not a logging statement and thus has no level. None is returned if a level
should have been found but wasn't. | [
"Determines",
"the",
"level",
"of",
"logging",
"in",
"a",
"given",
"logging",
"statement",
".",
"The",
"string",
"representing",
"this",
"level",
"is",
"returned",
".",
"False",
"is",
"returned",
"if",
"the",
"method",
"is",
"not",
"a",
"logging",
"statement... | python | train |
inveniosoftware-contrib/invenio-classifier | invenio_classifier/normalizer.py | https://github.com/inveniosoftware-contrib/invenio-classifier/blob/3c758cf34dca6bf0548e7da5de34e5f72e3b255e/invenio_classifier/normalizer.py#L645-L653 | def _replace_greek_characters(line):
"""Replace greek characters in a string."""
for greek_char, replacement in iteritems(_GREEK_REPLACEMENTS):
try:
line = line.replace(greek_char, replacement)
except UnicodeDecodeError:
current_app.logger.exception("Unicode decoding erro... | [
"def",
"_replace_greek_characters",
"(",
"line",
")",
":",
"for",
"greek_char",
",",
"replacement",
"in",
"iteritems",
"(",
"_GREEK_REPLACEMENTS",
")",
":",
"try",
":",
"line",
"=",
"line",
".",
"replace",
"(",
"greek_char",
",",
"replacement",
")",
"except",
... | Replace greek characters in a string. | [
"Replace",
"greek",
"characters",
"in",
"a",
"string",
"."
] | python | train |
lemieuxl/pyGenClean | pyGenClean/SexCheck/sex_check.py | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/SexCheck/sex_check.py#L531-L565 | def checkArgs(args):
"""Checks the arguments and options.
:param args: an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` class... | [
"def",
"checkArgs",
"(",
"args",
")",
":",
"# Check if we have the tped and the tfam files",
"for",
"fileName",
"in",
"[",
"args",
".",
"bfile",
"+",
"i",
"for",
"i",
"in",
"[",
"\".bed\"",
",",
"\".bim\"",
",",
"\".fam\"",
"]",
"]",
":",
"if",
"not",
"os"... | Checks the arguments and options.
:param args: an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` class, a message is printed to th... | [
"Checks",
"the",
"arguments",
"and",
"options",
"."
] | python | train |
dropseed/combine | combine/cli.py | https://github.com/dropseed/combine/blob/b0d622d09fcb121bc12e65f6044cb3a940b6b052/combine/cli.py#L65-L73 | def highlight_info(ctx, style):
"""Outputs the CSS which can be customized for highlighted code"""
click.secho("The following styles are available to choose from:", fg="green")
click.echo(list(pygments.styles.get_all_styles()))
click.echo()
click.secho(
f'The following CSS for the "{style}" ... | [
"def",
"highlight_info",
"(",
"ctx",
",",
"style",
")",
":",
"click",
".",
"secho",
"(",
"\"The following styles are available to choose from:\"",
",",
"fg",
"=",
"\"green\"",
")",
"click",
".",
"echo",
"(",
"list",
"(",
"pygments",
".",
"styles",
".",
"get_al... | Outputs the CSS which can be customized for highlighted code | [
"Outputs",
"the",
"CSS",
"which",
"can",
"be",
"customized",
"for",
"highlighted",
"code"
] | python | test |
ppb/pursuedpybear | ppb/engine.py | https://github.com/ppb/pursuedpybear/blob/db3bfaaf86d14b4d1bb9e0b24cc8dc63f29c2191/ppb/engine.py#L160-L165 | def on_replace_scene(self, event: events.ReplaceScene, signal):
"""
Replace the running scene with a new one.
"""
self.stop_scene()
self.start_scene(event.new_scene, event.kwargs) | [
"def",
"on_replace_scene",
"(",
"self",
",",
"event",
":",
"events",
".",
"ReplaceScene",
",",
"signal",
")",
":",
"self",
".",
"stop_scene",
"(",
")",
"self",
".",
"start_scene",
"(",
"event",
".",
"new_scene",
",",
"event",
".",
"kwargs",
")"
] | Replace the running scene with a new one. | [
"Replace",
"the",
"running",
"scene",
"with",
"a",
"new",
"one",
"."
] | python | train |
OCHA-DAP/hdx-python-api | src/hdx/data/hdxobject.py | https://github.com/OCHA-DAP/hdx-python-api/blob/212440f54f73805826a16db77dbcb6033b18a313/src/hdx/data/hdxobject.py#L568-L583 | def _add_strings_to_commastring(self, field, strings):
# type: (str, List[str]) -> bool
"""Add a list of strings to a comma separated list of strings
Args:
field (str): Field containing comma separated list
strings (List[str]): list of strings to add
Returns:
... | [
"def",
"_add_strings_to_commastring",
"(",
"self",
",",
"field",
",",
"strings",
")",
":",
"# type: (str, List[str]) -> bool",
"allstringsadded",
"=",
"True",
"for",
"string",
"in",
"strings",
":",
"if",
"not",
"self",
".",
"_add_string_to_commastring",
"(",
"field"... | Add a list of strings to a comma separated list of strings
Args:
field (str): Field containing comma separated list
strings (List[str]): list of strings to add
Returns:
bool: True if all strings added or False if any already present. | [
"Add",
"a",
"list",
"of",
"strings",
"to",
"a",
"comma",
"separated",
"list",
"of",
"strings"
] | python | train |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_map/mp_tile.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_map/mp_tile.py#L519-L547 | def area_to_image(self, lat, lon, width, height, ground_width, zoom=None, ordered=True):
'''return an RGB image for an area of land, with ground_width
in meters, and width/height in pixels.
lat/lon is the top left corner. The zoom is automatically
chosen to avoid having to grow the tile... | [
"def",
"area_to_image",
"(",
"self",
",",
"lat",
",",
"lon",
",",
"width",
",",
"height",
",",
"ground_width",
",",
"zoom",
"=",
"None",
",",
"ordered",
"=",
"True",
")",
":",
"img",
"=",
"np",
".",
"zeros",
"(",
"(",
"height",
",",
"width",
",",
... | return an RGB image for an area of land, with ground_width
in meters, and width/height in pixels.
lat/lon is the top left corner. The zoom is automatically
chosen to avoid having to grow the tiles | [
"return",
"an",
"RGB",
"image",
"for",
"an",
"area",
"of",
"land",
"with",
"ground_width",
"in",
"meters",
"and",
"width",
"/",
"height",
"in",
"pixels",
"."
] | python | train |
vmonaco/pohmm | pohmm/utils.py | https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/pohmm/utils.py#L122-L134 | def steadystate(A, max_iter=100):
"""
Empirically determine the steady state probabilities from a stochastic matrix
"""
P = np.linalg.matrix_power(A, max_iter)
# Determine the unique rows in A
v = []
for i in range(len(P)):
if not np.any([np.allclose(P[i], vi, ) for vi in v]):
... | [
"def",
"steadystate",
"(",
"A",
",",
"max_iter",
"=",
"100",
")",
":",
"P",
"=",
"np",
".",
"linalg",
".",
"matrix_power",
"(",
"A",
",",
"max_iter",
")",
"# Determine the unique rows in A",
"v",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
... | Empirically determine the steady state probabilities from a stochastic matrix | [
"Empirically",
"determine",
"the",
"steady",
"state",
"probabilities",
"from",
"a",
"stochastic",
"matrix"
] | python | train |
sibirrer/lenstronomy | lenstronomy/LensModel/lens_model.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/LensModel/lens_model.py#L189-L210 | def flexion(self, x, y, kwargs, diff=0.000001):
"""
third derivatives (flexion)
:param x: x-position (preferentially arcsec)
:type x: numpy array
:param y: y-position (preferentially arcsec)
:type y: numpy array
:param kwargs: list of keyword arguments of lens mo... | [
"def",
"flexion",
"(",
"self",
",",
"x",
",",
"y",
",",
"kwargs",
",",
"diff",
"=",
"0.000001",
")",
":",
"f_xx",
",",
"f_xy",
",",
"f_yx",
",",
"f_yy",
"=",
"self",
".",
"hessian",
"(",
"x",
",",
"y",
",",
"kwargs",
")",
"f_xx_dx",
",",
"f_xy_... | third derivatives (flexion)
:param x: x-position (preferentially arcsec)
:type x: numpy array
:param y: y-position (preferentially arcsec)
:type y: numpy array
:param kwargs: list of keyword arguments of lens model parameters matching the lens model classes
:param diff: ... | [
"third",
"derivatives",
"(",
"flexion",
")"
] | python | train |
manns/pyspread | pyspread/src/actions/_grid_cell_actions.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/actions/_grid_cell_actions.py#L425-L445 | def get_new_cell_attr_state(self, key, attr_key):
"""Returns new attr cell state for toggles
Parameters
----------
key: 3-Tuple
\tCell for which attr toggle shall be returned
attr_key: Hashable
\tAttribute key
"""
cell_attributes = self.grid.cod... | [
"def",
"get_new_cell_attr_state",
"(",
"self",
",",
"key",
",",
"attr_key",
")",
":",
"cell_attributes",
"=",
"self",
".",
"grid",
".",
"code_array",
".",
"cell_attributes",
"attr_values",
"=",
"self",
".",
"attr_toggle_values",
"[",
"attr_key",
"]",
"# Map attr... | Returns new attr cell state for toggles
Parameters
----------
key: 3-Tuple
\tCell for which attr toggle shall be returned
attr_key: Hashable
\tAttribute key | [
"Returns",
"new",
"attr",
"cell",
"state",
"for",
"toggles"
] | python | train |
apache/incubator-mxnet | example/rcnn/symdata/anchor.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/rcnn/symdata/anchor.py#L44-L53 | def _generate_base_anchors(base_size, scales, ratios):
"""
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
"""
base_anchor = np.array([1, 1, base_size, base_size]) - 1
ratio_anchors = AnchorGenerator._ratio_... | [
"def",
"_generate_base_anchors",
"(",
"base_size",
",",
"scales",
",",
"ratios",
")",
":",
"base_anchor",
"=",
"np",
".",
"array",
"(",
"[",
"1",
",",
"1",
",",
"base_size",
",",
"base_size",
"]",
")",
"-",
"1",
"ratio_anchors",
"=",
"AnchorGenerator",
"... | Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window. | [
"Generate",
"anchor",
"(",
"reference",
")",
"windows",
"by",
"enumerating",
"aspect",
"ratios",
"X",
"scales",
"wrt",
"a",
"reference",
"(",
"0",
"0",
"15",
"15",
")",
"window",
"."
] | python | train |
tammoippen/iso4217parse | iso4217parse/__init__.py | https://github.com/tammoippen/iso4217parse/blob/dd2971bd66e83424c43d16d6b54b3f6d0c4201cf/iso4217parse/__init__.py#L157-L181 | def by_symbol(symbol, country_code=None):
"""Get list of possible currencies for symbol; filter by country_code
Look for all currencies that use the `symbol`. If there are currencies used
in the country of `country_code`, return only those; otherwise return all
found currencies.
Parameters:
... | [
"def",
"by_symbol",
"(",
"symbol",
",",
"country_code",
"=",
"None",
")",
":",
"res",
"=",
"_data",
"(",
")",
"[",
"'symbol'",
"]",
".",
"get",
"(",
"symbol",
")",
"if",
"res",
":",
"tmp_res",
"=",
"[",
"]",
"for",
"d",
"in",
"res",
":",
"if",
... | Get list of possible currencies for symbol; filter by country_code
Look for all currencies that use the `symbol`. If there are currencies used
in the country of `country_code`, return only those; otherwise return all
found currencies.
Parameters:
symbol: unicode Currency symbo... | [
"Get",
"list",
"of",
"possible",
"currencies",
"for",
"symbol",
";",
"filter",
"by",
"country_code"
] | python | train |
ronaldguillen/wave | wave/metadata.py | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/metadata.py#L115-L149 | def get_field_info(self, field):
"""
Given an instance of a serializer field, return a dictionary
of metadata about it.
"""
field_info = OrderedDict()
field_info['type'] = self.label_lookup[field]
field_info['required'] = getattr(field, 'required', False)
... | [
"def",
"get_field_info",
"(",
"self",
",",
"field",
")",
":",
"field_info",
"=",
"OrderedDict",
"(",
")",
"field_info",
"[",
"'type'",
"]",
"=",
"self",
".",
"label_lookup",
"[",
"field",
"]",
"field_info",
"[",
"'required'",
"]",
"=",
"getattr",
"(",
"f... | Given an instance of a serializer field, return a dictionary
of metadata about it. | [
"Given",
"an",
"instance",
"of",
"a",
"serializer",
"field",
"return",
"a",
"dictionary",
"of",
"metadata",
"about",
"it",
"."
] | python | train |
bitesofcode/projexui | projexui/xsettings.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xsettings.py#L156-L197 | def restoreValue(self, xelem):
"""
Stores the value for the inptued instance to the given xml element.
:param xelem | <xml.etree.Element>
:return <variant>
"""
typ = xelem.get('type')
if typ == 'color':
re... | [
"def",
"restoreValue",
"(",
"self",
",",
"xelem",
")",
":",
"typ",
"=",
"xelem",
".",
"get",
"(",
"'type'",
")",
"if",
"typ",
"==",
"'color'",
":",
"return",
"QtGui",
".",
"QColor",
"(",
"xelem",
".",
"text",
")",
"elif",
"typ",
"==",
"'point'",
":... | Stores the value for the inptued instance to the given xml element.
:param xelem | <xml.etree.Element>
:return <variant> | [
"Stores",
"the",
"value",
"for",
"the",
"inptued",
"instance",
"to",
"the",
"given",
"xml",
"element",
".",
":",
"param",
"xelem",
"|",
"<xml",
".",
"etree",
".",
"Element",
">",
":",
"return",
"<variant",
">"
] | python | train |
google/prettytensor | prettytensor/pretty_tensor_loss_methods.py | https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/pretty_tensor_loss_methods.py#L580-L600 | def _eval_metric(input_, topk, correct_predictions, examples, phase):
"""Creates the standard tracking varibles if in test and returns accuracy."""
my_parameters = {}
if phase in (Phase.test, Phase.infer):
dtype = tf.float32
# Create the variables using tf.Variable because we don't want to share.
coun... | [
"def",
"_eval_metric",
"(",
"input_",
",",
"topk",
",",
"correct_predictions",
",",
"examples",
",",
"phase",
")",
":",
"my_parameters",
"=",
"{",
"}",
"if",
"phase",
"in",
"(",
"Phase",
".",
"test",
",",
"Phase",
".",
"infer",
")",
":",
"dtype",
"=",
... | Creates the standard tracking varibles if in test and returns accuracy. | [
"Creates",
"the",
"standard",
"tracking",
"varibles",
"if",
"in",
"test",
"and",
"returns",
"accuracy",
"."
] | python | train |
pazz/alot | alot/helper.py | https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/helper.py#L416-L436 | def libmagic_version_at_least(version):
"""
checks if the libmagic library installed is more recent than a given
version.
:param version: minimum version expected in the form XYY (i.e. 5.14 -> 514)
with XYY >= 513
"""
if hasattr(magic, 'open'):
magic_wrapper = magic.... | [
"def",
"libmagic_version_at_least",
"(",
"version",
")",
":",
"if",
"hasattr",
"(",
"magic",
",",
"'open'",
")",
":",
"magic_wrapper",
"=",
"magic",
".",
"_libraries",
"[",
"'magic'",
"]",
"elif",
"hasattr",
"(",
"magic",
",",
"'from_buffer'",
")",
":",
"m... | checks if the libmagic library installed is more recent than a given
version.
:param version: minimum version expected in the form XYY (i.e. 5.14 -> 514)
with XYY >= 513 | [
"checks",
"if",
"the",
"libmagic",
"library",
"installed",
"is",
"more",
"recent",
"than",
"a",
"given",
"version",
"."
] | python | train |
edx/edx-enterprise | enterprise/api/v1/decorators.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/enterprise/api/v1/decorators.py#L14-L52 | def enterprise_customer_required(view):
"""
Ensure the user making the API request is associated with an EnterpriseCustomer.
This decorator attempts to find an EnterpriseCustomer associated with the requesting
user and passes that EnterpriseCustomer to the view as a parameter. It will return a
Perm... | [
"def",
"enterprise_customer_required",
"(",
"view",
")",
":",
"@",
"wraps",
"(",
"view",
")",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Checks for an enterprise customer associated with the user, calls the ... | Ensure the user making the API request is associated with an EnterpriseCustomer.
This decorator attempts to find an EnterpriseCustomer associated with the requesting
user and passes that EnterpriseCustomer to the view as a parameter. It will return a
PermissionDenied error if an EnterpriseCustomer cannot b... | [
"Ensure",
"the",
"user",
"making",
"the",
"API",
"request",
"is",
"associated",
"with",
"an",
"EnterpriseCustomer",
"."
] | python | valid |
dead-beef/markovchain | markovchain/image/scanner.py | https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/image/scanner.py#L271-L285 | def save(self):
"""Convert to JSON.
Returns
-------
`dict`
JSON data.
"""
data = super().save()
data['resize'] = list(self.resize) if self.resize is not None else None
data['traversal'] = [t.save() for t in self.traversal]
data['levels... | [
"def",
"save",
"(",
"self",
")",
":",
"data",
"=",
"super",
"(",
")",
".",
"save",
"(",
")",
"data",
"[",
"'resize'",
"]",
"=",
"list",
"(",
"self",
".",
"resize",
")",
"if",
"self",
".",
"resize",
"is",
"not",
"None",
"else",
"None",
"data",
"... | Convert to JSON.
Returns
-------
`dict`
JSON data. | [
"Convert",
"to",
"JSON",
"."
] | python | train |
StellarCN/py-stellar-base | stellar_base/operation.py | https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/operation.py#L443-L458 | def from_xdr_object(cls, op_xdr_object):
"""Creates a :class:`ChangeTrust` object from an XDR Operation
object.
"""
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
'account', op_xdr_object.sourceAccount[0].ed... | [
"def",
"from_xdr_object",
"(",
"cls",
",",
"op_xdr_object",
")",
":",
"if",
"not",
"op_xdr_object",
".",
"sourceAccount",
":",
"source",
"=",
"None",
"else",
":",
"source",
"=",
"encode_check",
"(",
"'account'",
",",
"op_xdr_object",
".",
"sourceAccount",
"[",... | Creates a :class:`ChangeTrust` object from an XDR Operation
object. | [
"Creates",
"a",
":",
"class",
":",
"ChangeTrust",
"object",
"from",
"an",
"XDR",
"Operation",
"object",
"."
] | python | train |
PythonCharmers/python-future | src/future/backports/urllib/robotparser.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/robotparser.py#L55-L58 | def set_url(self, url):
"""Sets the URL referring to a robots.txt file."""
self.url = url
self.host, self.path = urllib.parse.urlparse(url)[1:3] | [
"def",
"set_url",
"(",
"self",
",",
"url",
")",
":",
"self",
".",
"url",
"=",
"url",
"self",
".",
"host",
",",
"self",
".",
"path",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"[",
"1",
":",
"3",
"]"
] | Sets the URL referring to a robots.txt file. | [
"Sets",
"the",
"URL",
"referring",
"to",
"a",
"robots",
".",
"txt",
"file",
"."
] | python | train |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/debug.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/debug.py#L211-L264 | def attach(self, dwProcessId):
"""
Attaches to an existing process for debugging.
@see: L{detach}, L{execv}, L{execl}
@type dwProcessId: int
@param dwProcessId: Global ID of a process to attach to.
@rtype: L{Process}
@return: A new Process object. Normally yo... | [
"def",
"attach",
"(",
"self",
",",
"dwProcessId",
")",
":",
"# Get the Process object from the snapshot,",
"# if missing create a new one.",
"try",
":",
"aProcess",
"=",
"self",
".",
"system",
".",
"get_process",
"(",
"dwProcessId",
")",
"except",
"KeyError",
":",
"... | Attaches to an existing process for debugging.
@see: L{detach}, L{execv}, L{execl}
@type dwProcessId: int
@param dwProcessId: Global ID of a process to attach to.
@rtype: L{Process}
@return: A new Process object. Normally you don't need to use it now,
it's best t... | [
"Attaches",
"to",
"an",
"existing",
"process",
"for",
"debugging",
"."
] | python | train |
QInfer/python-qinfer | src/qinfer/abstract_model.py | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/abstract_model.py#L614-L630 | def domain(self, expparams):
"""
Returns a list of :class:`Domain` objects, one for each input expparam.
:param numpy.ndarray expparams: Array of experimental parameters. This
array must be of dtype agreeing with the ``expparams_dtype``
property, or, in the case where `... | [
"def",
"domain",
"(",
"self",
",",
"expparams",
")",
":",
"# As a convenience to most users, we define domain for them. If a ",
"# fancier domain is desired, this method can easily be overridden.",
"if",
"self",
".",
"is_n_outcomes_constant",
":",
"return",
"self",
".",
"_domain"... | Returns a list of :class:`Domain` objects, one for each input expparam.
:param numpy.ndarray expparams: Array of experimental parameters. This
array must be of dtype agreeing with the ``expparams_dtype``
property, or, in the case where ``n_outcomes_constant`` is ``True``,
`... | [
"Returns",
"a",
"list",
"of",
":",
"class",
":",
"Domain",
"objects",
"one",
"for",
"each",
"input",
"expparam",
"."
] | python | train |
push-things/wallabag_api | wallabag_api/wallabag.py | https://github.com/push-things/wallabag_api/blob/8d1e10a6ebc03d1ac9af2b38b57eb69f29b4216e/wallabag_api/wallabag.py#L179-L206 | async def post_entries(self, url, title='', tags='', starred=0, archive=0, content='', language='', published_at='',
authors='', public=1, original_url=''):
"""
POST /api/entries.{_format}
Create an entry
:param url: the url of the note to store
:para... | [
"async",
"def",
"post_entries",
"(",
"self",
",",
"url",
",",
"title",
"=",
"''",
",",
"tags",
"=",
"''",
",",
"starred",
"=",
"0",
",",
"archive",
"=",
"0",
",",
"content",
"=",
"''",
",",
"language",
"=",
"''",
",",
"published_at",
"=",
"''",
"... | POST /api/entries.{_format}
Create an entry
:param url: the url of the note to store
:param title: Optional, we'll get the title from the page.
:param tags: tag1,tag2,tag3 a comma-separated list of tags.
:param starred entry already starred
:param archive entry already ... | [
"POST",
"/",
"api",
"/",
"entries",
".",
"{",
"_format",
"}"
] | python | train |
projectatomic/osbs-client | osbs/build/plugins_configuration.py | https://github.com/projectatomic/osbs-client/blob/571fe035dab3a7c02e1dccd5d65ffd75be750458/osbs/build/plugins_configuration.py#L55-L64 | def remove_plugin(self, phase, name, reason=None):
"""
if config contains plugin, remove it
"""
for p in self.template[phase]:
if p.get('name') == name:
self.template[phase].remove(p)
if reason:
logger.info('Removing {}:{}, ... | [
"def",
"remove_plugin",
"(",
"self",
",",
"phase",
",",
"name",
",",
"reason",
"=",
"None",
")",
":",
"for",
"p",
"in",
"self",
".",
"template",
"[",
"phase",
"]",
":",
"if",
"p",
".",
"get",
"(",
"'name'",
")",
"==",
"name",
":",
"self",
".",
... | if config contains plugin, remove it | [
"if",
"config",
"contains",
"plugin",
"remove",
"it"
] | python | train |
openwisp/netjsonconfig | netjsonconfig/backends/base/backend.py | https://github.com/openwisp/netjsonconfig/blob/c23ce9732720856e2f6dc54060db71a8182c7d4b/netjsonconfig/backends/base/backend.py#L226-L244 | def _add_file(self, tar, name, contents, mode=DEFAULT_FILE_MODE):
"""
Adds a single file in tarfile instance.
:param tar: tarfile instance
:param name: string representing filename or path
:param contents: string representing file contents
:param mode: string representin... | [
"def",
"_add_file",
"(",
"self",
",",
"tar",
",",
"name",
",",
"contents",
",",
"mode",
"=",
"DEFAULT_FILE_MODE",
")",
":",
"byte_contents",
"=",
"BytesIO",
"(",
"contents",
".",
"encode",
"(",
"'utf8'",
")",
")",
"info",
"=",
"tarfile",
".",
"TarInfo",
... | Adds a single file in tarfile instance.
:param tar: tarfile instance
:param name: string representing filename or path
:param contents: string representing file contents
:param mode: string representing file mode, defaults to 644
:returns: None | [
"Adds",
"a",
"single",
"file",
"in",
"tarfile",
"instance",
"."
] | python | valid |
CivicSpleen/ambry | ambry/library/search_backends/whoosh_backend.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/whoosh_backend.py#L270-L276 | def all(self):
""" Returns list with all indexed partitions. """
partitions = []
for partition in self.index.searcher().documents():
partitions.append(
PartitionSearchResult(dataset_vid=partition['dataset_vid'], vid=partition['vid'], score=1))
return partition... | [
"def",
"all",
"(",
"self",
")",
":",
"partitions",
"=",
"[",
"]",
"for",
"partition",
"in",
"self",
".",
"index",
".",
"searcher",
"(",
")",
".",
"documents",
"(",
")",
":",
"partitions",
".",
"append",
"(",
"PartitionSearchResult",
"(",
"dataset_vid",
... | Returns list with all indexed partitions. | [
"Returns",
"list",
"with",
"all",
"indexed",
"partitions",
"."
] | python | train |
seleniumbase/SeleniumBase | seleniumbase/fixtures/email_manager.py | https://github.com/seleniumbase/SeleniumBase/blob/62e5b43ee1f90a9ed923841bdd53b1b38358f43a/seleniumbase/fixtures/email_manager.py#L430-L442 | def remove_whitespace(self, html):
"""
Clean whitespace from html
@Params
html - html source to remove whitespace from
@Returns
String html without whitespace
"""
# Does python have a better way to do exactly this?
clean_html = html
for cha... | [
"def",
"remove_whitespace",
"(",
"self",
",",
"html",
")",
":",
"# Does python have a better way to do exactly this?",
"clean_html",
"=",
"html",
"for",
"char",
"in",
"(",
"\"\\r\"",
",",
"\"\\n\"",
",",
"\"\\t\"",
")",
":",
"clean_html",
"=",
"clean_html",
".",
... | Clean whitespace from html
@Params
html - html source to remove whitespace from
@Returns
String html without whitespace | [
"Clean",
"whitespace",
"from",
"html"
] | python | train |
burnash/gspread | gspread/models.py | https://github.com/burnash/gspread/blob/0e8debe208095aeed3e3e7136c2fa5cd74090946/gspread/models.py#L580-L593 | def get_all_values(self):
"""Returns a list of lists containing all cells' values as strings.
.. note::
Empty trailing rows and columns will not be included.
"""
data = self.spreadsheet.values_get(self.title)
try:
return fill_gaps(data['values'])
... | [
"def",
"get_all_values",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"spreadsheet",
".",
"values_get",
"(",
"self",
".",
"title",
")",
"try",
":",
"return",
"fill_gaps",
"(",
"data",
"[",
"'values'",
"]",
")",
"except",
"KeyError",
":",
"return",
... | Returns a list of lists containing all cells' values as strings.
.. note::
Empty trailing rows and columns will not be included. | [
"Returns",
"a",
"list",
"of",
"lists",
"containing",
"all",
"cells",
"values",
"as",
"strings",
"."
] | python | train |
1flow/python-ftr | ftr/config.py | https://github.com/1flow/python-ftr/blob/90a2108c5ee005f1bf66dbe8cce68f2b7051b839/ftr/config.py#L127-L255 | def ftr_get_config(website_url, exact_host_match=False):
""" Download the Five Filters config from centralized repositories.
Repositories can be local if you need to override siteconfigs.
The first entry found is returned. If no configuration is found,
`None` is returned. If :mod:`cacheops` is install... | [
"def",
"ftr_get_config",
"(",
"website_url",
",",
"exact_host_match",
"=",
"False",
")",
":",
"def",
"check_requests_result",
"(",
"result",
")",
":",
"return",
"(",
"u'text/plain'",
"in",
"result",
".",
"headers",
".",
"get",
"(",
"'content-type'",
")",
"and"... | Download the Five Filters config from centralized repositories.
Repositories can be local if you need to override siteconfigs.
The first entry found is returned. If no configuration is found,
`None` is returned. If :mod:`cacheops` is installed, the result will
be cached with a default expiration delay... | [
"Download",
"the",
"Five",
"Filters",
"config",
"from",
"centralized",
"repositories",
"."
] | python | train |
abseil/abseil-py | absl/flags/_argument_parser.py | https://github.com/abseil/abseil-py/blob/9d73fdaa23a6b6726aa5731390f388c0c6250ee5/absl/flags/_argument_parser.py#L494-L510 | def parse(self, argument):
"""Parses argument as comma-separated list of strings."""
if isinstance(argument, list):
return argument
elif not argument:
return []
else:
try:
return [s.strip() for s in list(csv.reader([argument], strict=True))[0]]
except csv.Error as e:
... | [
"def",
"parse",
"(",
"self",
",",
"argument",
")",
":",
"if",
"isinstance",
"(",
"argument",
",",
"list",
")",
":",
"return",
"argument",
"elif",
"not",
"argument",
":",
"return",
"[",
"]",
"else",
":",
"try",
":",
"return",
"[",
"s",
".",
"strip",
... | Parses argument as comma-separated list of strings. | [
"Parses",
"argument",
"as",
"comma",
"-",
"separated",
"list",
"of",
"strings",
"."
] | python | train |
sandwichcloud/ingredients.tasks | ingredients_tasks/vmware.py | https://github.com/sandwichcloud/ingredients.tasks/blob/23d2772536f07aa5e4787b7ee67dee2f1faedb08/ingredients_tasks/vmware.py#L220-L238 | def get_obj(self, vimtype, name, folder=None):
"""
Return an object by name, if name is None the
first found object is returned
"""
obj = None
content = self.service_instance.RetrieveContent()
if folder is None:
folder = content.rootFolder
co... | [
"def",
"get_obj",
"(",
"self",
",",
"vimtype",
",",
"name",
",",
"folder",
"=",
"None",
")",
":",
"obj",
"=",
"None",
"content",
"=",
"self",
".",
"service_instance",
".",
"RetrieveContent",
"(",
")",
"if",
"folder",
"is",
"None",
":",
"folder",
"=",
... | Return an object by name, if name is None the
first found object is returned | [
"Return",
"an",
"object",
"by",
"name",
"if",
"name",
"is",
"None",
"the",
"first",
"found",
"object",
"is",
"returned"
] | python | train |
spyder-ide/spyder | spyder/plugins/help/plugin.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/help/plugin.py#L341-L344 | def toggle_wrap_mode(self, checked):
"""Toggle wrap mode"""
self.plain_text.editor.toggle_wrap_mode(checked)
self.set_option('wrap', checked) | [
"def",
"toggle_wrap_mode",
"(",
"self",
",",
"checked",
")",
":",
"self",
".",
"plain_text",
".",
"editor",
".",
"toggle_wrap_mode",
"(",
"checked",
")",
"self",
".",
"set_option",
"(",
"'wrap'",
",",
"checked",
")"
] | Toggle wrap mode | [
"Toggle",
"wrap",
"mode"
] | python | train |
dlintott/gns3-converter | gns3converter/main.py | https://github.com/dlintott/gns3-converter/blob/acbc55da51de86388dc5b5f6da55809b3c86b7ca/gns3converter/main.py#L197-L216 | def snapshot_name(topo_name):
"""
Get the snapshot name
:param str topo_name: topology file location. The name is taken from the
directory containing the topology file using the
following format: topology_NAME_snapshot_DATE_TIME
:return: snapshot name... | [
"def",
"snapshot_name",
"(",
"topo_name",
")",
":",
"topo_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"topology_dirname",
"(",
"topo_name",
")",
")",
"snap_re",
"=",
"re",
".",
"compile",
"(",
"'^topology_(.+)(_snapshot_)(\\d{6}_\\d{6})$'",
")",
"result... | Get the snapshot name
:param str topo_name: topology file location. The name is taken from the
directory containing the topology file using the
following format: topology_NAME_snapshot_DATE_TIME
:return: snapshot name
:raises ConvertError: when unable to ... | [
"Get",
"the",
"snapshot",
"name"
] | python | train |
seryl/Python-Cotendo | cotendo/__init__.py | https://github.com/seryl/Python-Cotendo/blob/a55e034f0845332319859f6276adc6ba35f5a121/cotendo/__init__.py#L129-L138 | def doFlush(self, cname, flushExpression, flushType):
"""
doFlush method enables specific content to be "flushed" from the
cache servers.
* Note: The flush API is limited to 1,000 flush invocations per hour
(each flush invocation may include several objects). *
"""
... | [
"def",
"doFlush",
"(",
"self",
",",
"cname",
",",
"flushExpression",
",",
"flushType",
")",
":",
"return",
"self",
".",
"client",
".",
"service",
".",
"doFlush",
"(",
"cname",
",",
"flushExpression",
",",
"flushType",
")"
] | doFlush method enables specific content to be "flushed" from the
cache servers.
* Note: The flush API is limited to 1,000 flush invocations per hour
(each flush invocation may include several objects). * | [
"doFlush",
"method",
"enables",
"specific",
"content",
"to",
"be",
"flushed",
"from",
"the",
"cache",
"servers",
"."
] | python | train |
log2timeline/plaso | plaso/output/rawpy.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/output/rawpy.py#L68-L75 | def WriteEventBody(self, event):
"""Writes the body of an event to the output.
Args:
event (EventObject): event.
"""
output_string = NativePythonFormatterHelper.GetFormattedEventObject(event)
self._output_writer.Write(output_string) | [
"def",
"WriteEventBody",
"(",
"self",
",",
"event",
")",
":",
"output_string",
"=",
"NativePythonFormatterHelper",
".",
"GetFormattedEventObject",
"(",
"event",
")",
"self",
".",
"_output_writer",
".",
"Write",
"(",
"output_string",
")"
] | Writes the body of an event to the output.
Args:
event (EventObject): event. | [
"Writes",
"the",
"body",
"of",
"an",
"event",
"to",
"the",
"output",
"."
] | python | train |
a1ezzz/wasp-general | wasp_general/network/clients/file.py | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/clients/file.py#L140-L152 | def upload_file(self, file_name, file_obj, *args, **kwargs):
""" :meth:`.WNetworkClientProto.upload_file` method implementation
"""
previous_path = self.session_path()
try:
self.session_path(file_name)
with open(self.full_path(), mode='wb') as f:
chunk = file_obj.read(io.DEFAULT_BUFFER_SIZE)
while... | [
"def",
"upload_file",
"(",
"self",
",",
"file_name",
",",
"file_obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"previous_path",
"=",
"self",
".",
"session_path",
"(",
")",
"try",
":",
"self",
".",
"session_path",
"(",
"file_name",
")",
"wit... | :meth:`.WNetworkClientProto.upload_file` method implementation | [
":",
"meth",
":",
".",
"WNetworkClientProto",
".",
"upload_file",
"method",
"implementation"
] | python | train |
ianmiell/shutit | shutit_class.py | https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1655-L1670 | def ls(self,
directory,
note=None,
loglevel=logging.DEBUG):
"""Helper proc to list files in a directory
@param directory: directory to list. If the directory doesn't exist, shutit.fail() is called (i.e. the build fails.)
@param note: See send()
@type directory: string
... | [
"def",
"ls",
"(",
"self",
",",
"directory",
",",
"note",
"=",
"None",
",",
"loglevel",
"=",
"logging",
".",
"DEBUG",
")",
":",
"shutit_global",
".",
"shutit_global_object",
".",
"yield_to_draw",
"(",
")",
"shutit_pexpect_session",
"=",
"self",
".",
"get_curr... | Helper proc to list files in a directory
@param directory: directory to list. If the directory doesn't exist, shutit.fail() is called (i.e. the build fails.)
@param note: See send()
@type directory: string
@rtype: list of strings | [
"Helper",
"proc",
"to",
"list",
"files",
"in",
"a",
"directory"
] | python | train |
Arvedui/picuplib | picuplib/upload.py | https://github.com/Arvedui/picuplib/blob/c8a5d1542dbd421e84afd5ee81fe76efec89fb95/picuplib/upload.py#L147-L170 | def remote_upload(self, picture_url, resize=None,
rotation=None, noexif=None):
"""
wraps remote_upload funktion
:param str picture_url: URL to picture allowd Protocols are: ftp,\
http, https
:param str resize: Aresolution in the folowing format: \
... | [
"def",
"remote_upload",
"(",
"self",
",",
"picture_url",
",",
"resize",
"=",
"None",
",",
"rotation",
"=",
"None",
",",
"noexif",
"=",
"None",
")",
":",
"if",
"not",
"resize",
":",
"resize",
"=",
"self",
".",
"_resize",
"if",
"not",
"rotation",
":",
... | wraps remote_upload funktion
:param str picture_url: URL to picture allowd Protocols are: ftp,\
http, https
:param str resize: Aresolution in the folowing format: \
'80x80'(optional)
:param str|degree rotation: The picture will be rotated by this Value. \
All... | [
"wraps",
"remote_upload",
"funktion"
] | python | train |
TrafficSenseMSD/SumoTools | traci/_vehicle.py | https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/traci/_vehicle.py#L1001-L1007 | def setLength(self, vehID, length):
"""setLength(string, double) -> None
Sets the length in m for the given vehicle.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_LENGTH, vehID, length) | [
"def",
"setLength",
"(",
"self",
",",
"vehID",
",",
"length",
")",
":",
"self",
".",
"_connection",
".",
"_sendDoubleCmd",
"(",
"tc",
".",
"CMD_SET_VEHICLE_VARIABLE",
",",
"tc",
".",
"VAR_LENGTH",
",",
"vehID",
",",
"length",
")"
] | setLength(string, double) -> None
Sets the length in m for the given vehicle. | [
"setLength",
"(",
"string",
"double",
")",
"-",
">",
"None"
] | python | train |
DataONEorg/d1_python | lib_common/src/d1_common/cert/jwt.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/cert/jwt.py#L104-L108 | def get_subject_with_file_validation(jwt_bu64, cert_path):
"""Same as get_subject_with_local_validation() except that the signing certificate
is read from a local PEM file."""
cert_obj = d1_common.cert.x509.deserialize_pem_file(cert_path)
return get_subject_with_local_validation(jwt_bu64, cert_obj) | [
"def",
"get_subject_with_file_validation",
"(",
"jwt_bu64",
",",
"cert_path",
")",
":",
"cert_obj",
"=",
"d1_common",
".",
"cert",
".",
"x509",
".",
"deserialize_pem_file",
"(",
"cert_path",
")",
"return",
"get_subject_with_local_validation",
"(",
"jwt_bu64",
",",
"... | Same as get_subject_with_local_validation() except that the signing certificate
is read from a local PEM file. | [
"Same",
"as",
"get_subject_with_local_validation",
"()",
"except",
"that",
"the",
"signing",
"certificate",
"is",
"read",
"from",
"a",
"local",
"PEM",
"file",
"."
] | python | train |
maaku/python-bitcoin | bitcoin/tools.py | https://github.com/maaku/python-bitcoin/blob/1b80c284170fd3f547cc45f4700ce169f3f99641/bitcoin/tools.py#L59-L80 | def decompress_amount(x):
"""\
Undo the value compression performed by x=compress_amount(n). The input
x matches one of the following patterns:
x = n = 0
x = 1+10*(9*n + d - 1) + e
x = 1+10*(n - 1) + 9"""
if not x: return 0;
x = x - 1;
# x = 10*(9*n + d - 1) + e
x, e... | [
"def",
"decompress_amount",
"(",
"x",
")",
":",
"if",
"not",
"x",
":",
"return",
"0",
"x",
"=",
"x",
"-",
"1",
"# x = 10*(9*n + d - 1) + e",
"x",
",",
"e",
"=",
"divmod",
"(",
"x",
",",
"10",
")",
"n",
"=",
"0",
"if",
"e",
"<",
"9",
":",
"# x =... | \
Undo the value compression performed by x=compress_amount(n). The input
x matches one of the following patterns:
x = n = 0
x = 1+10*(9*n + d - 1) + e
x = 1+10*(n - 1) + 9 | [
"\\",
"Undo",
"the",
"value",
"compression",
"performed",
"by",
"x",
"=",
"compress_amount",
"(",
"n",
")",
".",
"The",
"input",
"x",
"matches",
"one",
"of",
"the",
"following",
"patterns",
":",
"x",
"=",
"n",
"=",
"0",
"x",
"=",
"1",
"+",
"10",
"*... | python | train |
toomore/grs | grs/fetch_data.py | https://github.com/toomore/grs/blob/a1285cb57878284a886952968be9e31fbfa595dd/grs/fetch_data.py#L268-L277 | def out_putfile(self, fpath):
""" 輸出成 CSV 檔
:param path fpath: 檔案輸出位置
.. todo:: files output using `with` syntax.
"""
with open(fpath, 'w') as csv_file:
output = csv.writer(csv_file)
output.writerows(self.__raw_data) | [
"def",
"out_putfile",
"(",
"self",
",",
"fpath",
")",
":",
"with",
"open",
"(",
"fpath",
",",
"'w'",
")",
"as",
"csv_file",
":",
"output",
"=",
"csv",
".",
"writer",
"(",
"csv_file",
")",
"output",
".",
"writerows",
"(",
"self",
".",
"__raw_data",
")... | 輸出成 CSV 檔
:param path fpath: 檔案輸出位置
.. todo:: files output using `with` syntax. | [
"輸出成",
"CSV",
"檔"
] | python | train |
dougalsutherland/skl-groups | skl_groups/divergences/knn.py | https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/divergences/knn.py#L802-L818 | def tsallis(alphas, Ks, dim, required, clamp=True, to_self=False):
r'''
Estimate the Tsallis-alpha divergence between distributions, based on kNN
distances: (\int p^alpha q^(1-\alpha) - 1) / (\alpha - 1)
If clamp (the default), enforces the estimate is nonnegative.
Returns an array of shape (num_... | [
"def",
"tsallis",
"(",
"alphas",
",",
"Ks",
",",
"dim",
",",
"required",
",",
"clamp",
"=",
"True",
",",
"to_self",
"=",
"False",
")",
":",
"alphas",
"=",
"np",
".",
"reshape",
"(",
"alphas",
",",
"(",
"-",
"1",
",",
"1",
")",
")",
"alpha_est",
... | r'''
Estimate the Tsallis-alpha divergence between distributions, based on kNN
distances: (\int p^alpha q^(1-\alpha) - 1) / (\alpha - 1)
If clamp (the default), enforces the estimate is nonnegative.
Returns an array of shape (num_alphas, num_Ks). | [
"r",
"Estimate",
"the",
"Tsallis",
"-",
"alpha",
"divergence",
"between",
"distributions",
"based",
"on",
"kNN",
"distances",
":",
"(",
"\\",
"int",
"p^alpha",
"q^",
"(",
"1",
"-",
"\\",
"alpha",
")",
"-",
"1",
")",
"/",
"(",
"\\",
"alpha",
"-",
"1",... | python | valid |
PvtHaggard/pydarksky | pydarksky/darksky.py | https://github.com/PvtHaggard/pydarksky/blob/c2d68d311bf0a58125fbfe31eff124356899c75b/pydarksky/darksky.py#L255-L311 | def weather(self, latitude=None, longitude=None, date=None):
# type:(float, float, datetime) -> Weather
"""
:param float latitude: Locations latitude
:param float longitude: Locations longitude
:param datetime or str or int date: Date/time for historical weather data
:ra... | [
"def",
"weather",
"(",
"self",
",",
"latitude",
"=",
"None",
",",
"longitude",
"=",
"None",
",",
"date",
"=",
"None",
")",
":",
"# type:(float, float, datetime) -> Weather",
"# If params are default(None) check if latitude/longitude have already been defined(Not None)",
"# Ot... | :param float latitude: Locations latitude
:param float longitude: Locations longitude
:param datetime or str or int date: Date/time for historical weather data
:raises requests.exceptions.HTTPError: Raises on bad http response
:raises TypeError: Raises on invalid param types
:r... | [
":",
"param",
"float",
"latitude",
":",
"Locations",
"latitude",
":",
"param",
"float",
"longitude",
":",
"Locations",
"longitude",
":",
"param",
"datetime",
"or",
"str",
"or",
"int",
"date",
":",
"Date",
"/",
"time",
"for",
"historical",
"weather",
"data"
] | python | train |
codelv/enaml-native | src/enamlnative/core/eventloop/gen.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/core/eventloop/gen.py#L1057-L1061 | def is_ready(self, key):
"""Returns true if a result is available for ``key``."""
if self.pending_callbacks is None or key not in self.pending_callbacks:
raise UnknownKeyError("key %r is not pending" % (key,))
return key in self.results | [
"def",
"is_ready",
"(",
"self",
",",
"key",
")",
":",
"if",
"self",
".",
"pending_callbacks",
"is",
"None",
"or",
"key",
"not",
"in",
"self",
".",
"pending_callbacks",
":",
"raise",
"UnknownKeyError",
"(",
"\"key %r is not pending\"",
"%",
"(",
"key",
",",
... | Returns true if a result is available for ``key``. | [
"Returns",
"true",
"if",
"a",
"result",
"is",
"available",
"for",
"key",
"."
] | python | train |
RI-imaging/ODTbrain | odtbrain/_alg2d_bpp.py | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_alg2d_bpp.py#L8-L326 | def backpropagate_2d(uSin, angles, res, nm, lD=0, coords=None,
weight_angles=True,
onlyreal=False, padding=True, padval=0,
count=None, max_count=None, verbose=0):
r"""2D backpropagation with the Fourier diffraction theorem
Two-dimensional diffracti... | [
"def",
"backpropagate_2d",
"(",
"uSin",
",",
"angles",
",",
"res",
",",
"nm",
",",
"lD",
"=",
"0",
",",
"coords",
"=",
"None",
",",
"weight_angles",
"=",
"True",
",",
"onlyreal",
"=",
"False",
",",
"padding",
"=",
"True",
",",
"padval",
"=",
"0",
"... | r"""2D backpropagation with the Fourier diffraction theorem
Two-dimensional diffraction tomography reconstruction
algorithm for scattering of a plane wave
:math:`u_0(\mathbf{r}) = u_0(x,z)`
by a dielectric object with refractive index
:math:`n(x,z)`.
This method implements the 2D backpropagati... | [
"r",
"2D",
"backpropagation",
"with",
"the",
"Fourier",
"diffraction",
"theorem"
] | python | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_decision_tree.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_decision_tree.py#L373-L401 | def get_prediction_score(self, node_id):
"""
Return the prediction score (if leaf node) or None if its an
intermediate node.
Parameters
----------
node_id: id of the node to get the prediction value.
Returns
-------
float or None: returns float v... | [
"def",
"get_prediction_score",
"(",
"self",
",",
"node_id",
")",
":",
"_raise_error_if_not_of_type",
"(",
"node_id",
",",
"[",
"int",
",",
"long",
"]",
",",
"\"node_id\"",
")",
"_numeric_param_check_range",
"(",
"\"node_id\"",
",",
"node_id",
",",
"0",
",",
"s... | Return the prediction score (if leaf node) or None if its an
intermediate node.
Parameters
----------
node_id: id of the node to get the prediction value.
Returns
-------
float or None: returns float value of prediction if leaf node and None
if not.
... | [
"Return",
"the",
"prediction",
"score",
"(",
"if",
"leaf",
"node",
")",
"or",
"None",
"if",
"its",
"an",
"intermediate",
"node",
"."
] | python | train |
bcbio/bcbio-nextgen | bcbio/structural/gatkcnv.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/gatkcnv.py#L34-L54 | def _run_paired(paired):
"""Run somatic variant calling pipeline.
"""
from bcbio.structural import titancna
work_dir = _sv_workdir(paired.tumor_data)
seg_files = model_segments(tz.get_in(["depth", "bins", "normalized"], paired.tumor_data),
work_dir, paired)
call_fi... | [
"def",
"_run_paired",
"(",
"paired",
")",
":",
"from",
"bcbio",
".",
"structural",
"import",
"titancna",
"work_dir",
"=",
"_sv_workdir",
"(",
"paired",
".",
"tumor_data",
")",
"seg_files",
"=",
"model_segments",
"(",
"tz",
".",
"get_in",
"(",
"[",
"\"depth\"... | Run somatic variant calling pipeline. | [
"Run",
"somatic",
"variant",
"calling",
"pipeline",
"."
] | python | train |
mila-iqia/fuel | fuel/utils/parallel.py | https://github.com/mila-iqia/fuel/blob/1d6292dc25e3a115544237e392e61bff6631d23c/fuel/utils/parallel.py#L59-L113 | def producer_consumer(producer, consumer, addr='tcp://127.0.0.1',
port=None, context=None):
"""A producer-consumer pattern.
Parameters
----------
producer : callable
Callable that takes a single argument, a handle
for a ZeroMQ PUSH socket. Must be picklable.
co... | [
"def",
"producer_consumer",
"(",
"producer",
",",
"consumer",
",",
"addr",
"=",
"'tcp://127.0.0.1'",
",",
"port",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"context_created",
"=",
"False",
"if",
"context",
"is",
"None",
":",
"context_created",
"=",... | A producer-consumer pattern.
Parameters
----------
producer : callable
Callable that takes a single argument, a handle
for a ZeroMQ PUSH socket. Must be picklable.
consumer : callable
Callable that takes a single argument, a handle
for a ZeroMQ PULL socket.
addr : st... | [
"A",
"producer",
"-",
"consumer",
"pattern",
"."
] | python | train |
awslabs/sockeye | sockeye/image_captioning/utils.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/image_captioning/utils.py#L142-L155 | def save_features(paths: List[str], datas: List[np.ndarray],
compressed: bool = False) -> List:
"""
Save features specified with absolute paths.
:param paths: List of files specified with paths.
:param datas: List of numpy ndarrays to save into the respective files
:param compress... | [
"def",
"save_features",
"(",
"paths",
":",
"List",
"[",
"str",
"]",
",",
"datas",
":",
"List",
"[",
"np",
".",
"ndarray",
"]",
",",
"compressed",
":",
"bool",
"=",
"False",
")",
"->",
"List",
":",
"fnames",
"=",
"[",
"]",
"# type: List[str]",
"for",
... | Save features specified with absolute paths.
:param paths: List of files specified with paths.
:param datas: List of numpy ndarrays to save into the respective files
:param compressed: Use numpy compression
:return: A list of file names. | [
"Save",
"features",
"specified",
"with",
"absolute",
"paths",
"."
] | python | train |
numan/py-analytics | analytics/backends/redis.py | https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L280-L313 | def get_metric_by_month(self, unique_identifier, metric, from_date, limit=10, **kwargs):
"""
Returns the ``metric`` for ``unique_identifier`` segmented by month
starting from``from_date``. It will retrieve metrics data starting from the 1st of the
month specified in ``from_date``
... | [
"def",
"get_metric_by_month",
"(",
"self",
",",
"unique_identifier",
",",
"metric",
",",
"from_date",
",",
"limit",
"=",
"10",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"kwargs",
".",
"get",
"(",
"\"connection\"",
",",
"None",
")",
"first_of_month",
... | Returns the ``metric`` for ``unique_identifier`` segmented by month
starting from``from_date``. It will retrieve metrics data starting from the 1st of the
month specified in ``from_date``
:param unique_identifier: Unique string indetifying the object this metric is for
:param metric: A ... | [
"Returns",
"the",
"metric",
"for",
"unique_identifier",
"segmented",
"by",
"month",
"starting",
"from",
"from_date",
".",
"It",
"will",
"retrieve",
"metrics",
"data",
"starting",
"from",
"the",
"1st",
"of",
"the",
"month",
"specified",
"in",
"from_date"
] | python | train |
openstack/networking-cisco | networking_cisco/plugins/cisco/l3/schedulers/l3_routertype_aware_agent_scheduler.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/l3/schedulers/l3_routertype_aware_agent_scheduler.py#L58-L80 | def _filter_unscheduled_routers(self, plugin, context, routers):
"""Filter from list of routers the ones that are not scheduled.
Only for release < pike.
"""
if NEUTRON_VERSION.version[0] <= NEUTRON_NEWTON_VERSION.version[0]:
context, plugin = plugin, context
unsc... | [
"def",
"_filter_unscheduled_routers",
"(",
"self",
",",
"plugin",
",",
"context",
",",
"routers",
")",
":",
"if",
"NEUTRON_VERSION",
".",
"version",
"[",
"0",
"]",
"<=",
"NEUTRON_NEWTON_VERSION",
".",
"version",
"[",
"0",
"]",
":",
"context",
",",
"plugin",
... | Filter from list of routers the ones that are not scheduled.
Only for release < pike. | [
"Filter",
"from",
"list",
"of",
"routers",
"the",
"ones",
"that",
"are",
"not",
"scheduled",
"."
] | python | train |
geertj/gruvi | lib/gruvi/hub.py | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/hub.py#L133-L139 | def switch(self, value=None):
"""Switch back to the origin fiber. The fiber is switch in next time
the event loop runs."""
if self._hub is None or not self._fiber.is_alive():
return
self._hub.run_callback(self._fiber.switch, value)
self._hub = self._fiber = None | [
"def",
"switch",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"self",
".",
"_hub",
"is",
"None",
"or",
"not",
"self",
".",
"_fiber",
".",
"is_alive",
"(",
")",
":",
"return",
"self",
".",
"_hub",
".",
"run_callback",
"(",
"self",
".",
... | Switch back to the origin fiber. The fiber is switch in next time
the event loop runs. | [
"Switch",
"back",
"to",
"the",
"origin",
"fiber",
".",
"The",
"fiber",
"is",
"switch",
"in",
"next",
"time",
"the",
"event",
"loop",
"runs",
"."
] | python | train |
pvlib/pvlib-python | pvlib/singlediode.py | https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/singlediode.py#L174-L233 | def bishop88_i_from_v(voltage, photocurrent, saturation_current,
resistance_series, resistance_shunt, nNsVth,
method='newton'):
"""
Find current given any voltage.
Parameters
----------
voltage : numeric
voltage (V) in volts [V]
photocurrent :... | [
"def",
"bishop88_i_from_v",
"(",
"voltage",
",",
"photocurrent",
",",
"saturation_current",
",",
"resistance_series",
",",
"resistance_shunt",
",",
"nNsVth",
",",
"method",
"=",
"'newton'",
")",
":",
"# collect args",
"args",
"=",
"(",
"photocurrent",
",",
"satura... | Find current given any voltage.
Parameters
----------
voltage : numeric
voltage (V) in volts [V]
photocurrent : numeric
photogenerated current (Iph or IL) in amperes [A]
saturation_current : numeric
diode dark or saturation current (Io or Isat) in amperes [A]
resistance_... | [
"Find",
"current",
"given",
"any",
"voltage",
"."
] | python | train |
openstack/proliantutils | proliantutils/hpssa/manager.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/hpssa/manager.py#L300-L317 | def delete_configuration():
"""Delete a RAID configuration on this server.
:returns: the current RAID configuration after deleting all
the logical disks.
"""
server = objects.Server()
select_controllers = lambda x: not x.properties.get('HBA Mode Enabled',
... | [
"def",
"delete_configuration",
"(",
")",
":",
"server",
"=",
"objects",
".",
"Server",
"(",
")",
"select_controllers",
"=",
"lambda",
"x",
":",
"not",
"x",
".",
"properties",
".",
"get",
"(",
"'HBA Mode Enabled'",
",",
"False",
")",
"_select_controllers_by",
... | Delete a RAID configuration on this server.
:returns: the current RAID configuration after deleting all
the logical disks. | [
"Delete",
"a",
"RAID",
"configuration",
"on",
"this",
"server",
"."
] | python | train |
saltstack/salt | salt/states/file.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/file.py#L648-L667 | def _find_keep_files(root, keep):
'''
Compile a list of valid keep files (and directories).
Used by _clean_dir()
'''
real_keep = set()
real_keep.add(root)
if isinstance(keep, list):
for fn_ in keep:
if not os.path.isabs(fn_):
continue
fn_ = os.... | [
"def",
"_find_keep_files",
"(",
"root",
",",
"keep",
")",
":",
"real_keep",
"=",
"set",
"(",
")",
"real_keep",
".",
"add",
"(",
"root",
")",
"if",
"isinstance",
"(",
"keep",
",",
"list",
")",
":",
"for",
"fn_",
"in",
"keep",
":",
"if",
"not",
"os",... | Compile a list of valid keep files (and directories).
Used by _clean_dir() | [
"Compile",
"a",
"list",
"of",
"valid",
"keep",
"files",
"(",
"and",
"directories",
")",
".",
"Used",
"by",
"_clean_dir",
"()"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.