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 |
|---|---|---|---|---|---|---|---|---|
jjangsangy/py-translate | translate/translator.py | https://github.com/jjangsangy/py-translate/blob/fe6279b2ee353f42ce73333ffae104e646311956/translate/translator.py#L22-L57 | def push_url(interface):
'''
Decorates a function returning the url of translation API.
Creates and maintains HTTP connection state
Returns a dict response object from the server containing the translated
text and metadata of the request body
:param interface: Callable Request Interface
:t... | [
"def",
"push_url",
"(",
"interface",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"interface",
")",
"def",
"connection",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n Extends and wraps a HTTP interface.\n\n :return: Response Content\n ... | Decorates a function returning the url of translation API.
Creates and maintains HTTP connection state
Returns a dict response object from the server containing the translated
text and metadata of the request body
:param interface: Callable Request Interface
:type interface: Function | [
"Decorates",
"a",
"function",
"returning",
"the",
"url",
"of",
"translation",
"API",
".",
"Creates",
"and",
"maintains",
"HTTP",
"connection",
"state"
] | python | test |
bkjones/pyrabbit | pyrabbit/api.py | https://github.com/bkjones/pyrabbit/blob/e8a9f74ed5c6bba958994fb9a72c396e6a99ea0f/pyrabbit/api.py#L794-L801 | def delete_user(self, username):
"""
Deletes a user from the server.
:param string username: Name of the user to delete from the server.
"""
path = Client.urls['users_by_name'] % username
return self._call(path, 'DELETE') | [
"def",
"delete_user",
"(",
"self",
",",
"username",
")",
":",
"path",
"=",
"Client",
".",
"urls",
"[",
"'users_by_name'",
"]",
"%",
"username",
"return",
"self",
".",
"_call",
"(",
"path",
",",
"'DELETE'",
")"
] | Deletes a user from the server.
:param string username: Name of the user to delete from the server. | [
"Deletes",
"a",
"user",
"from",
"the",
"server",
"."
] | python | train |
genialis/resolwe | resolwe/permissions/utils.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/permissions/utils.py#L100-L112 | def check_owner_permission(payload, allow_user_owner):
"""Raise ``PermissionDenied``if ``owner`` found in ``data``."""
for entity_type in ['users', 'groups']:
for perm_type in ['add', 'remove']:
for perms in payload.get(entity_type, {}).get(perm_type, {}).values():
if 'owner'... | [
"def",
"check_owner_permission",
"(",
"payload",
",",
"allow_user_owner",
")",
":",
"for",
"entity_type",
"in",
"[",
"'users'",
",",
"'groups'",
"]",
":",
"for",
"perm_type",
"in",
"[",
"'add'",
",",
"'remove'",
"]",
":",
"for",
"perms",
"in",
"payload",
"... | Raise ``PermissionDenied``if ``owner`` found in ``data``. | [
"Raise",
"PermissionDenied",
"if",
"owner",
"found",
"in",
"data",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py#L146-L166 | def hide_routemap_holder_route_map_content_match_ipv6_route_source_ipv6_prefix_list_rmrs(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
... | [
"def",
"hide_routemap_holder_route_map_content_match_ipv6_route_source_ipv6_prefix_list_rmrs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_routemap_holder",
"=",
"ET",
".",
"SubElement",
"(",
"conf... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
stain/forgetSQL | lib/forgetSQL.py | https://github.com/stain/forgetSQL/blob/2e13f983020b121fd75a95fcafce3ea75573fb6b/lib/forgetSQL.py#L1001-L1122 | def generateFromTables(tables, cursor, getLinks=1, code=0):
"""Generates python code (or class objects if code is false)
based on SQL queries on the table names given in the list
tables.
code -- if given -- should be an dictionary containing these
keys to be inserted into generated code:
'... | [
"def",
"generateFromTables",
"(",
"tables",
",",
"cursor",
",",
"getLinks",
"=",
"1",
",",
"code",
"=",
"0",
")",
":",
"curs",
"=",
"cursor",
"(",
")",
"forgetters",
"=",
"{",
"}",
"class",
"_Wrapper",
"(",
"forgetSQL",
".",
"Forgetter",
")",
":",
"_... | Generates python code (or class objects if code is false)
based on SQL queries on the table names given in the list
tables.
code -- if given -- should be an dictionary containing these
keys to be inserted into generated code:
'database': database name
'module': database module nam... | [
"Generates",
"python",
"code",
"(",
"or",
"class",
"objects",
"if",
"code",
"is",
"false",
")",
"based",
"on",
"SQL",
"queries",
"on",
"the",
"table",
"names",
"given",
"in",
"the",
"list",
"tables",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L76-L93 | def _build_credentials(self, nexus_switches):
"""Build credential table for Rest API Client.
:param nexus_switches: switch config
:returns credentials: switch credentials list
"""
credentials = {}
for switch_ip, attrs in nexus_switches.items():
credentials[sw... | [
"def",
"_build_credentials",
"(",
"self",
",",
"nexus_switches",
")",
":",
"credentials",
"=",
"{",
"}",
"for",
"switch_ip",
",",
"attrs",
"in",
"nexus_switches",
".",
"items",
"(",
")",
":",
"credentials",
"[",
"switch_ip",
"]",
"=",
"(",
"attrs",
"[",
... | Build credential table for Rest API Client.
:param nexus_switches: switch config
:returns credentials: switch credentials list | [
"Build",
"credential",
"table",
"for",
"Rest",
"API",
"Client",
"."
] | python | train |
ccxt/ccxt | python/ccxt/base/exchange.py | https://github.com/ccxt/ccxt/blob/23062efd7a5892c79b370c9d951c03cf8c0ddf23/python/ccxt/base/exchange.py#L1000-L1006 | def check_address(self, address):
"""Checks an address is not the same character repeated or an empty sequence"""
if address is None:
self.raise_error(InvalidAddress, details='address is None')
if all(letter == address[0] for letter in address) or len(address) < self.minFundingAddres... | [
"def",
"check_address",
"(",
"self",
",",
"address",
")",
":",
"if",
"address",
"is",
"None",
":",
"self",
".",
"raise_error",
"(",
"InvalidAddress",
",",
"details",
"=",
"'address is None'",
")",
"if",
"all",
"(",
"letter",
"==",
"address",
"[",
"0",
"]... | Checks an address is not the same character repeated or an empty sequence | [
"Checks",
"an",
"address",
"is",
"not",
"the",
"same",
"character",
"repeated",
"or",
"an",
"empty",
"sequence"
] | python | train |
cltrudeau/django-flowr | flowr/models.py | https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L585-L594 | def connect_child(self, child_node):
"""Adds a connection to an existing rule in the :class`Flow` graph.
The given :class`Rule` subclass must be allowed to be connected at
this stage of the flow according to the hierarchy of rules.
:param child_node:
``FlowNodeData`` to att... | [
"def",
"connect_child",
"(",
"self",
",",
"child_node",
")",
":",
"self",
".",
"_child_allowed",
"(",
"child_node",
".",
"rule",
")",
"self",
".",
"node",
".",
"connect_child",
"(",
"child_node",
".",
"node",
")"
] | Adds a connection to an existing rule in the :class`Flow` graph.
The given :class`Rule` subclass must be allowed to be connected at
this stage of the flow according to the hierarchy of rules.
:param child_node:
``FlowNodeData`` to attach as a child | [
"Adds",
"a",
"connection",
"to",
"an",
"existing",
"rule",
"in",
"the",
":",
"class",
"Flow",
"graph",
".",
"The",
"given",
":",
"class",
"Rule",
"subclass",
"must",
"be",
"allowed",
"to",
"be",
"connected",
"at",
"this",
"stage",
"of",
"the",
"flow",
... | python | valid |
xhtml2pdf/xhtml2pdf | xhtml2pdf/paragraph.py | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/paragraph.py#L458-L481 | def wrap(self, availWidth, availHeight):
"""
Determine the rectangle this paragraph really needs.
"""
# memorize available space
self.avWidth = availWidth
self.avHeight = availHeight
logger.debug("*** wrap (%f, %f)", availWidth, availHeight)
if not self... | [
"def",
"wrap",
"(",
"self",
",",
"availWidth",
",",
"availHeight",
")",
":",
"# memorize available space",
"self",
".",
"avWidth",
"=",
"availWidth",
"self",
".",
"avHeight",
"=",
"availHeight",
"logger",
".",
"debug",
"(",
"\"*** wrap (%f, %f)\"",
",",
"availWi... | Determine the rectangle this paragraph really needs. | [
"Determine",
"the",
"rectangle",
"this",
"paragraph",
"really",
"needs",
"."
] | python | train |
ShenggaoZhu/midict | midict/__init__.py | https://github.com/ShenggaoZhu/midict/blob/2fad2edcfb753035b443a70fe15852affae1b5bb/midict/__init__.py#L1275-L1280 | def iteritems(self, indices=None):
'Iterate through items in the ``indices`` (defaults to all indices)'
if indices is None:
indices = force_list(self.indices.keys())
for x in self.itervalues(indices):
yield x | [
"def",
"iteritems",
"(",
"self",
",",
"indices",
"=",
"None",
")",
":",
"if",
"indices",
"is",
"None",
":",
"indices",
"=",
"force_list",
"(",
"self",
".",
"indices",
".",
"keys",
"(",
")",
")",
"for",
"x",
"in",
"self",
".",
"itervalues",
"(",
"in... | Iterate through items in the ``indices`` (defaults to all indices) | [
"Iterate",
"through",
"items",
"in",
"the",
"indices",
"(",
"defaults",
"to",
"all",
"indices",
")"
] | python | train |
pixelogik/NearPy | nearpy/hashes/randombinaryprojectiontree.py | https://github.com/pixelogik/NearPy/blob/1b534b864d320d875508e95cd2b76b6d8c07a90b/nearpy/hashes/randombinaryprojectiontree.py#L191-L203 | def get_config(self):
"""
Returns pickle-serializable configuration struct for storage.
"""
# Fill this dict with config data
return {
'hash_name': self.hash_name,
'dim': self.dim,
'projection_count': self.projection_count,
'normals... | [
"def",
"get_config",
"(",
"self",
")",
":",
"# Fill this dict with config data",
"return",
"{",
"'hash_name'",
":",
"self",
".",
"hash_name",
",",
"'dim'",
":",
"self",
".",
"dim",
",",
"'projection_count'",
":",
"self",
".",
"projection_count",
",",
"'normals'"... | Returns pickle-serializable configuration struct for storage. | [
"Returns",
"pickle",
"-",
"serializable",
"configuration",
"struct",
"for",
"storage",
"."
] | python | train |
williballenthin/python-evtx | Evtx/Views.py | https://github.com/williballenthin/python-evtx/blob/4e9e29544adde64c79ff9b743269ecb18c677eb4/Evtx/Views.py#L98-L177 | def render_root_node_with_subs(root_node, subs):
"""
render the given root node using the given substitutions into XML.
Args:
root_node (e_nodes.RootNode): the node to render.
subs (list[str]): the substitutions that maybe included in the XML.
Returns:
str: the rendered XML document.... | [
"def",
"render_root_node_with_subs",
"(",
"root_node",
",",
"subs",
")",
":",
"def",
"rec",
"(",
"node",
",",
"acc",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"e_nodes",
".",
"EndOfStreamNode",
")",
":",
"pass",
"# intended",
"elif",
"isinstance",
"(... | render the given root node using the given substitutions into XML.
Args:
root_node (e_nodes.RootNode): the node to render.
subs (list[str]): the substitutions that maybe included in the XML.
Returns:
str: the rendered XML document. | [
"render",
"the",
"given",
"root",
"node",
"using",
"the",
"given",
"substitutions",
"into",
"XML",
"."
] | python | train |
mozilla/treeherder | treeherder/webapp/api/note.py | https://github.com/mozilla/treeherder/blob/cc47bdec872e5c668d0f01df89517390a164cda3/treeherder/webapp/api/note.py#L64-L74 | def destroy(self, request, project, pk=None):
"""
Delete a note entry
"""
try:
note = JobNote.objects.get(id=pk)
note.delete()
return Response({"message": "Note deleted"})
except JobNote.DoesNotExist:
return Response("No note with i... | [
"def",
"destroy",
"(",
"self",
",",
"request",
",",
"project",
",",
"pk",
"=",
"None",
")",
":",
"try",
":",
"note",
"=",
"JobNote",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"pk",
")",
"note",
".",
"delete",
"(",
")",
"return",
"Response",
"("... | Delete a note entry | [
"Delete",
"a",
"note",
"entry"
] | python | train |
SmartTeleMax/iktomi | iktomi/cli/base.py | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/cli/base.py#L14-L114 | def manage(commands, argv=None, delim=':'):
'''
Parses argv and runs neccessary command. Is to be used in manage.py file.
Accept a dict with digest name as keys and instances of
:class:`Cli<iktomi.management.commands.Cli>`
objects as values.
The format of command is the following::
./... | [
"def",
"manage",
"(",
"commands",
",",
"argv",
"=",
"None",
",",
"delim",
"=",
"':'",
")",
":",
"commands",
"=",
"{",
"(",
"k",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"isinstance",
"(",
"k",
",",
"six",
".",
"binary_type",
")",
"else",
"k",
")... | Parses argv and runs neccessary command. Is to be used in manage.py file.
Accept a dict with digest name as keys and instances of
:class:`Cli<iktomi.management.commands.Cli>`
objects as values.
The format of command is the following::
./manage.py digest_name:command_name[ arg1[ arg2[...]]][ -... | [
"Parses",
"argv",
"and",
"runs",
"neccessary",
"command",
".",
"Is",
"to",
"be",
"used",
"in",
"manage",
".",
"py",
"file",
"."
] | python | train |
dswah/pyGAM | pygam/distributions.py | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/distributions.py#L535-L554 | def sample(self, mu):
"""
Return random samples from this Gamma distribution.
Parameters
----------
mu : array-like of shape n_samples or shape (n_simulations, n_samples)
expected values
Returns
-------
random_samples : np.array of same shape... | [
"def",
"sample",
"(",
"self",
",",
"mu",
")",
":",
"# in numpy.random.gamma, `shape` is the parameter sometimes denoted by",
"# `k` that corresponds to `nu` in S. Wood (2006) Table 2.1",
"shape",
"=",
"1.",
"/",
"self",
".",
"scale",
"# in numpy.random.gamma, `scale` is the paramet... | Return random samples from this Gamma distribution.
Parameters
----------
mu : array-like of shape n_samples or shape (n_simulations, n_samples)
expected values
Returns
-------
random_samples : np.array of same shape as mu | [
"Return",
"random",
"samples",
"from",
"this",
"Gamma",
"distribution",
"."
] | python | train |
WoLpH/python-statsd | statsd/client.py | https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/client.py#L88-L94 | def get_gauge(self, name=None):
'''Shortcut for getting a :class:`~statsd.gauge.Gauge` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str
'''
return self.get_client(name=name, class_=statsd.Gauge) | [
"def",
"get_gauge",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_client",
"(",
"name",
"=",
"name",
",",
"class_",
"=",
"statsd",
".",
"Gauge",
")"
] | Shortcut for getting a :class:`~statsd.gauge.Gauge` instance
:keyword name: See :func:`~statsd.client.Client.get_client`
:type name: str | [
"Shortcut",
"for",
"getting",
"a",
":",
"class",
":",
"~statsd",
".",
"gauge",
".",
"Gauge",
"instance"
] | python | train |
jim-easterbrook/pywws | src/pywws/conversions.py | https://github.com/jim-easterbrook/pywws/blob/4e4d74cee5a3ac5bf42286feaa251cd2ffcaf02c/src/pywws/conversions.py#L202-L210 | def cadhumidex(temp, humidity):
"Calculate Humidity Index as per Canadian Weather Standards"
if temp is None or humidity is None:
return None
# Formulas are adapted to not use e^(...) with no appreciable
# change in accuracy (0.0227%)
saturation_pressure = (6.112 * (10.0**(7.5 * temp / (237.... | [
"def",
"cadhumidex",
"(",
"temp",
",",
"humidity",
")",
":",
"if",
"temp",
"is",
"None",
"or",
"humidity",
"is",
"None",
":",
"return",
"None",
"# Formulas are adapted to not use e^(...) with no appreciable",
"# change in accuracy (0.0227%)",
"saturation_pressure",
"=",
... | Calculate Humidity Index as per Canadian Weather Standards | [
"Calculate",
"Humidity",
"Index",
"as",
"per",
"Canadian",
"Weather",
"Standards"
] | python | train |
allenai/allennlp | allennlp/data/vocabulary.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L270-L294 | def save_to_files(self, directory: str) -> None:
"""
Persist this Vocabulary to files so it can be reloaded later.
Each namespace corresponds to one file.
Parameters
----------
directory : ``str``
The directory where we save the serialized vocabulary.
... | [
"def",
"save_to_files",
"(",
"self",
",",
"directory",
":",
"str",
")",
"->",
"None",
":",
"os",
".",
"makedirs",
"(",
"directory",
",",
"exist_ok",
"=",
"True",
")",
"if",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"logging",
".",
"warning",
... | Persist this Vocabulary to files so it can be reloaded later.
Each namespace corresponds to one file.
Parameters
----------
directory : ``str``
The directory where we save the serialized vocabulary. | [
"Persist",
"this",
"Vocabulary",
"to",
"files",
"so",
"it",
"can",
"be",
"reloaded",
"later",
".",
"Each",
"namespace",
"corresponds",
"to",
"one",
"file",
"."
] | python | train |
Alignak-monitoring/alignak | alignak/objects/item.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1580-L1629 | def explode_host_groups_into_hosts(self, item, hosts, hostgroups):
"""
Get all hosts of hostgroups and add all in host_name container
:param item: the item object
:type item: alignak.objects.item.Item
:param hosts: hosts object
:type hosts: alignak.objects.host.Hosts
... | [
"def",
"explode_host_groups_into_hosts",
"(",
"self",
",",
"item",
",",
"hosts",
",",
"hostgroups",
")",
":",
"hnames_list",
"=",
"[",
"]",
"# Gets item's hostgroup_name",
"hgnames",
"=",
"getattr",
"(",
"item",
",",
"\"hostgroup_name\"",
",",
"''",
")",
"or",
... | Get all hosts of hostgroups and add all in host_name container
:param item: the item object
:type item: alignak.objects.item.Item
:param hosts: hosts object
:type hosts: alignak.objects.host.Hosts
:param hostgroups: hostgroups object
:type hostgroups: alignak.objects.hos... | [
"Get",
"all",
"hosts",
"of",
"hostgroups",
"and",
"add",
"all",
"in",
"host_name",
"container"
] | python | train |
PolyJIT/benchbuild | benchbuild/utils/user_interface.py | https://github.com/PolyJIT/benchbuild/blob/9ad2ec54d96e97b642b1f06eddcbad9ba7aeaf58/benchbuild/utils/user_interface.py#L46-L84 | def ask(question, default_answer=False, default_answer_str="no"):
"""
Ask for user input.
This asks a yes/no question with a preset default.
You can bypass the user-input and fetch the default answer, if
you set
Args:
question: The question to ask on stdout.
default_answer: The... | [
"def",
"ask",
"(",
"question",
",",
"default_answer",
"=",
"False",
",",
"default_answer_str",
"=",
"\"no\"",
")",
":",
"response",
"=",
"default_answer",
"def",
"should_ignore_tty",
"(",
")",
":",
"\"\"\"\n Check, if we want to ignore an opened tty result.\n ... | Ask for user input.
This asks a yes/no question with a preset default.
You can bypass the user-input and fetch the default answer, if
you set
Args:
question: The question to ask on stdout.
default_answer: The default value to return.
default_answer_str:
The default ... | [
"Ask",
"for",
"user",
"input",
"."
] | python | train |
lpantano/seqcluster | seqcluster/libs/thinkbayes.py | https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/libs/thinkbayes.py#L485-L506 | def Normalize(self, fraction=1.0):
"""Normalizes this PMF so the sum of all probs is fraction.
Args:
fraction: what the total should be after normalization
Returns: the total probability before normalizing
"""
if self.log:
raise ValueError("Pmf is under ... | [
"def",
"Normalize",
"(",
"self",
",",
"fraction",
"=",
"1.0",
")",
":",
"if",
"self",
".",
"log",
":",
"raise",
"ValueError",
"(",
"\"Pmf is under a log transform\"",
")",
"total",
"=",
"self",
".",
"Total",
"(",
")",
"if",
"total",
"==",
"0.0",
":",
"... | Normalizes this PMF so the sum of all probs is fraction.
Args:
fraction: what the total should be after normalization
Returns: the total probability before normalizing | [
"Normalizes",
"this",
"PMF",
"so",
"the",
"sum",
"of",
"all",
"probs",
"is",
"fraction",
"."
] | python | train |
saltstack/salt | salt/returners/multi_returner.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/multi_returner.py#L101-L109 | def get_jids():
'''
Return all job data from all returners
'''
ret = {}
for returner_ in __opts__[CONFIG_KEY]:
ret.update(_mminion().returners['{0}.get_jids'.format(returner_)]())
return ret | [
"def",
"get_jids",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"returner_",
"in",
"__opts__",
"[",
"CONFIG_KEY",
"]",
":",
"ret",
".",
"update",
"(",
"_mminion",
"(",
")",
".",
"returners",
"[",
"'{0}.get_jids'",
".",
"format",
"(",
"returner_",
")",
... | Return all job data from all returners | [
"Return",
"all",
"job",
"data",
"from",
"all",
"returners"
] | python | train |
ghukill/pyfc4 | pyfc4/models.py | https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/models.py#L357-L387 | def keep_alive(self):
'''
Keep current transaction alive, updates self.expires
Args:
None
Return:
None: sets new self.expires
'''
# keep transaction alive
txn_response = self.api.http_request('POST','%sfcr:tx' % self.root, data=None, headers=None)
# if 204, transaction kept alive
if txn_res... | [
"def",
"keep_alive",
"(",
"self",
")",
":",
"# keep transaction alive",
"txn_response",
"=",
"self",
".",
"api",
".",
"http_request",
"(",
"'POST'",
",",
"'%sfcr:tx'",
"%",
"self",
".",
"root",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
")",
... | Keep current transaction alive, updates self.expires
Args:
None
Return:
None: sets new self.expires | [
"Keep",
"current",
"transaction",
"alive",
"updates",
"self",
".",
"expires"
] | python | train |
senaite/senaite.core | bika/lims/content/worksheet.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/worksheet.py#L1277-L1298 | def setMethod(self, method, override_analyses=False):
""" Sets the specified method to the Analyses from the
Worksheet. Only sets the method if the Analysis
allows to keep the integrity.
If an analysis has already been assigned to a method, it won't
be overriden.
... | [
"def",
"setMethod",
"(",
"self",
",",
"method",
",",
"override_analyses",
"=",
"False",
")",
":",
"analyses",
"=",
"[",
"an",
"for",
"an",
"in",
"self",
".",
"getAnalyses",
"(",
")",
"if",
"(",
"not",
"an",
".",
"getMethod",
"(",
")",
"or",
"not",
... | Sets the specified method to the Analyses from the
Worksheet. Only sets the method if the Analysis
allows to keep the integrity.
If an analysis has already been assigned to a method, it won't
be overriden.
Returns the number of analyses affected. | [
"Sets",
"the",
"specified",
"method",
"to",
"the",
"Analyses",
"from",
"the",
"Worksheet",
".",
"Only",
"sets",
"the",
"method",
"if",
"the",
"Analysis",
"allows",
"to",
"keep",
"the",
"integrity",
".",
"If",
"an",
"analysis",
"has",
"already",
"been",
"as... | python | train |
whyscream/dspam-milter | dspam/client.py | https://github.com/whyscream/dspam-milter/blob/f9939b718eed02cb7e56f8c5b921db4cfe1cd85a/dspam/client.py#L295-L319 | def rcptto(self, recipients):
"""
Send LMTP RCPT TO command, and process the server response.
The DSPAM server expects to find one or more valid DSPAM users as
envelope recipients. The set recipient will be the user DSPAM
processes mail for.
When you need want DSPAM to ... | [
"def",
"rcptto",
"(",
"self",
",",
"recipients",
")",
":",
"for",
"rcpt",
"in",
"recipients",
":",
"self",
".",
"_send",
"(",
"'RCPT TO:<{}>\\r\\n'",
".",
"format",
"(",
"rcpt",
")",
")",
"resp",
"=",
"self",
".",
"_read",
"(",
")",
"if",
"not",
"res... | Send LMTP RCPT TO command, and process the server response.
The DSPAM server expects to find one or more valid DSPAM users as
envelope recipients. The set recipient will be the user DSPAM
processes mail for.
When you need want DSPAM to deliver the message itself, and need to
pa... | [
"Send",
"LMTP",
"RCPT",
"TO",
"command",
"and",
"process",
"the",
"server",
"response",
"."
] | python | train |
agoragames/haigha | haigha/classes/basic_class.py | https://github.com/agoragames/haigha/blob/7b004e1c0316ec14b94fec1c54554654c38b1a25/haigha/classes/basic_class.py#L96-L106 | def qos(self, prefetch_size=0, prefetch_count=0, is_global=False):
'''
Set QoS on this channel.
'''
args = Writer()
args.write_long(prefetch_size).\
write_short(prefetch_count).\
write_bit(is_global)
self.send_frame(MethodFrame(self.channel_id, 60,... | [
"def",
"qos",
"(",
"self",
",",
"prefetch_size",
"=",
"0",
",",
"prefetch_count",
"=",
"0",
",",
"is_global",
"=",
"False",
")",
":",
"args",
"=",
"Writer",
"(",
")",
"args",
".",
"write_long",
"(",
"prefetch_size",
")",
".",
"write_short",
"(",
"prefe... | Set QoS on this channel. | [
"Set",
"QoS",
"on",
"this",
"channel",
"."
] | python | train |
wuher/devil | devil/fields/fields.py | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/fields.py#L102-L128 | def clean(self, value):
""" Clean the data and validate the nested spec.
Implementation is the same as for other fields but in addition,
this will propagate the validation to the nested spec.
"""
obj = self.factory.create(value)
# todo: what if the field defines proper... | [
"def",
"clean",
"(",
"self",
",",
"value",
")",
":",
"obj",
"=",
"self",
".",
"factory",
".",
"create",
"(",
"value",
")",
"# todo: what if the field defines properties that have any of",
"# these names:",
"if",
"obj",
":",
"del",
"obj",
".",
"fields",
"del",
... | Clean the data and validate the nested spec.
Implementation is the same as for other fields but in addition,
this will propagate the validation to the nested spec. | [
"Clean",
"the",
"data",
"and",
"validate",
"the",
"nested",
"spec",
"."
] | python | train |
benmack/eo-box | eobox/raster/rasterprocessing.py | https://github.com/benmack/eo-box/blob/a291450c766bf50ea06adcdeb5729a4aad790ed5/eobox/raster/rasterprocessing.py#L252-L256 | def _process_window(self, ji_win, func, **kwargs):
"""Load (resampled) array of window ji_win and apply custom function on it. """
arr = self.get_arrays(ji_win)
result = func(arr, **kwargs)
return result | [
"def",
"_process_window",
"(",
"self",
",",
"ji_win",
",",
"func",
",",
"*",
"*",
"kwargs",
")",
":",
"arr",
"=",
"self",
".",
"get_arrays",
"(",
"ji_win",
")",
"result",
"=",
"func",
"(",
"arr",
",",
"*",
"*",
"kwargs",
")",
"return",
"result"
] | Load (resampled) array of window ji_win and apply custom function on it. | [
"Load",
"(",
"resampled",
")",
"array",
"of",
"window",
"ji_win",
"and",
"apply",
"custom",
"function",
"on",
"it",
"."
] | python | train |
sosy-lab/benchexec | benchexec/runexecutor.py | https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/runexecutor.py#L1186-L1192 | def _try_join_cancelled_thread(thread):
"""Join a thread, but if the thread doesn't terminate for some time, ignore it
instead of waiting infinitely."""
thread.join(10)
if thread.is_alive():
logging.warning("Thread %s did not terminate within grace period after cancellation",
... | [
"def",
"_try_join_cancelled_thread",
"(",
"thread",
")",
":",
"thread",
".",
"join",
"(",
"10",
")",
"if",
"thread",
".",
"is_alive",
"(",
")",
":",
"logging",
".",
"warning",
"(",
"\"Thread %s did not terminate within grace period after cancellation\"",
",",
"threa... | Join a thread, but if the thread doesn't terminate for some time, ignore it
instead of waiting infinitely. | [
"Join",
"a",
"thread",
"but",
"if",
"the",
"thread",
"doesn",
"t",
"terminate",
"for",
"some",
"time",
"ignore",
"it",
"instead",
"of",
"waiting",
"infinitely",
"."
] | python | train |
limpyd/redis-limpyd-jobs | limpyd_jobs/models.py | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/models.py#L125-L137 | def get_all_by_priority(cls, names):
"""
Return all the queues with the given names, sorted by priorities (higher
priority first), then by name
"""
names = cls._get_iterable_for_names(names)
queues = cls.get_all(names)
# sort all queues by priority
queue... | [
"def",
"get_all_by_priority",
"(",
"cls",
",",
"names",
")",
":",
"names",
"=",
"cls",
".",
"_get_iterable_for_names",
"(",
"names",
")",
"queues",
"=",
"cls",
".",
"get_all",
"(",
"names",
")",
"# sort all queues by priority",
"queues",
".",
"sort",
"(",
"k... | Return all the queues with the given names, sorted by priorities (higher
priority first), then by name | [
"Return",
"all",
"the",
"queues",
"with",
"the",
"given",
"names",
"sorted",
"by",
"priorities",
"(",
"higher",
"priority",
"first",
")",
"then",
"by",
"name"
] | python | train |
dev-pipeline/dev-pipeline-git | lib/devpipeline_git/git.py | https://github.com/dev-pipeline/dev-pipeline-git/blob/b604f1f89402502b8ad858f4f834baa9467ef380/lib/devpipeline_git/git.py#L118-L124 | def checkout(self, repo_dir, shared_dir, **kwargs):
"""This function checks out code from a Git SCM server."""
del kwargs
args = []
for checkout_fn in _CHECKOUT_ARG_BUILDERS:
args.extend(checkout_fn(shared_dir, repo_dir, self._args))
return args | [
"def",
"checkout",
"(",
"self",
",",
"repo_dir",
",",
"shared_dir",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"kwargs",
"args",
"=",
"[",
"]",
"for",
"checkout_fn",
"in",
"_CHECKOUT_ARG_BUILDERS",
":",
"args",
".",
"extend",
"(",
"checkout_fn",
"(",
"sha... | This function checks out code from a Git SCM server. | [
"This",
"function",
"checks",
"out",
"code",
"from",
"a",
"Git",
"SCM",
"server",
"."
] | python | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L7146-L7163 | def insrtc(item, inset):
"""
Insert an item into a character set.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/insrtc_c.html
:param item: Item to be inserted.
:type item: str or list of str
:param inset: Insertion set.
:type inset: spiceypy.utils.support_types.SpiceCell
"""
... | [
"def",
"insrtc",
"(",
"item",
",",
"inset",
")",
":",
"assert",
"isinstance",
"(",
"inset",
",",
"stypes",
".",
"SpiceCell",
")",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"for",
"c",
"in",
"item",
":",
"libspice",
".",
"insrtc_c",
"(",... | Insert an item into a character set.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/insrtc_c.html
:param item: Item to be inserted.
:type item: str or list of str
:param inset: Insertion set.
:type inset: spiceypy.utils.support_types.SpiceCell | [
"Insert",
"an",
"item",
"into",
"a",
"character",
"set",
"."
] | python | train |
refenv/cijoe | modules/cij/reporter.py | https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/modules/cij/reporter.py#L138-L150 | def aux_listing(aux_root):
"""Listing"""
listing = []
for root, _, fnames in os.walk(aux_root):
count = len(aux_root.split(os.sep))
prefix = root.split(os.sep)[count:]
for fname in fnames:
listing.append(os.sep.join(prefix + [fname]))
return listing | [
"def",
"aux_listing",
"(",
"aux_root",
")",
":",
"listing",
"=",
"[",
"]",
"for",
"root",
",",
"_",
",",
"fnames",
"in",
"os",
".",
"walk",
"(",
"aux_root",
")",
":",
"count",
"=",
"len",
"(",
"aux_root",
".",
"split",
"(",
"os",
".",
"sep",
")",... | Listing | [
"Listing"
] | python | valid |
open-mmlab/mmcv | mmcv/runner/checkpoint.py | https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/runner/checkpoint.py#L157-L187 | def save_checkpoint(model, filename, optimizer=None, meta=None):
"""Save checkpoint to file.
The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
``optimizer``. By default ``meta`` will contain version and time info.
Args:
model (Module): Module whose params are to be saved.
... | [
"def",
"save_checkpoint",
"(",
"model",
",",
"filename",
",",
"optimizer",
"=",
"None",
",",
"meta",
"=",
"None",
")",
":",
"if",
"meta",
"is",
"None",
":",
"meta",
"=",
"{",
"}",
"elif",
"not",
"isinstance",
"(",
"meta",
",",
"dict",
")",
":",
"ra... | Save checkpoint to file.
The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
``optimizer``. By default ``meta`` will contain version and time info.
Args:
model (Module): Module whose params are to be saved.
filename (str): Checkpoint filename.
optimizer (:obj:`Optimizer... | [
"Save",
"checkpoint",
"to",
"file",
"."
] | python | test |
limodou/uliweb | uliweb/contrib/csrf/__init__.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/csrf/__init__.py#L31-L44 | def check_csrf_token():
"""
Check token
"""
from uliweb import request, settings
token = (request.params.get(settings.CSRF.form_token_name, None) or
request.headers.get("X-Xsrftoken") or
request.headers.get("X-Csrftoken"))
if not token:
raise Forbidden("CSRF t... | [
"def",
"check_csrf_token",
"(",
")",
":",
"from",
"uliweb",
"import",
"request",
",",
"settings",
"token",
"=",
"(",
"request",
".",
"params",
".",
"get",
"(",
"settings",
".",
"CSRF",
".",
"form_token_name",
",",
"None",
")",
"or",
"request",
".",
"head... | Check token | [
"Check",
"token"
] | python | train |
nyergler/hieroglyph | src/hieroglyph/quickstart.py | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/quickstart.py#L16-L76 | def ask_user(d):
"""Wrap sphinx.quickstart.ask_user, and add additional questions."""
# Print welcome message
msg = bold('Welcome to the Hieroglyph %s quickstart utility.') % (
version(),
)
print(msg)
msg = """
This will ask questions for creating a Hieroglyph project, and then ask
some... | [
"def",
"ask_user",
"(",
"d",
")",
":",
"# Print welcome message",
"msg",
"=",
"bold",
"(",
"'Welcome to the Hieroglyph %s quickstart utility.'",
")",
"%",
"(",
"version",
"(",
")",
",",
")",
"print",
"(",
"msg",
")",
"msg",
"=",
"\"\"\"\nThis will ask questions fo... | Wrap sphinx.quickstart.ask_user, and add additional questions. | [
"Wrap",
"sphinx",
".",
"quickstart",
".",
"ask_user",
"and",
"add",
"additional",
"questions",
"."
] | python | train |
pgxcentre/geneparse | geneparse/readers/vcf.py | https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/vcf.py#L102-L105 | def iter_variants(self):
"""Iterate over marker information."""
for v in self.get_vcf():
yield Variant(v.ID, v.CHROM, v.POS, {v.REF} | set(v.ALT)) | [
"def",
"iter_variants",
"(",
"self",
")",
":",
"for",
"v",
"in",
"self",
".",
"get_vcf",
"(",
")",
":",
"yield",
"Variant",
"(",
"v",
".",
"ID",
",",
"v",
".",
"CHROM",
",",
"v",
".",
"POS",
",",
"{",
"v",
".",
"REF",
"}",
"|",
"set",
"(",
... | Iterate over marker information. | [
"Iterate",
"over",
"marker",
"information",
"."
] | python | train |
google/prettytensor | prettytensor/layers.py | https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/layers.py#L119-L144 | def xavier_init(n_inputs, n_outputs, uniform=True):
"""Set the parameter initialization using the method described.
This method is designed to keep the scale of the gradients roughly the same
in all layers.
Xavier Glorot and Yoshua Bengio (2010):
Understanding the difficulty of training deep feedfo... | [
"def",
"xavier_init",
"(",
"n_inputs",
",",
"n_outputs",
",",
"uniform",
"=",
"True",
")",
":",
"if",
"uniform",
":",
"# 6 was used in the paper.",
"init_range",
"=",
"math",
".",
"sqrt",
"(",
"6.0",
"/",
"(",
"n_inputs",
"+",
"n_outputs",
")",
")",
"retur... | Set the parameter initialization using the method described.
This method is designed to keep the scale of the gradients roughly the same
in all layers.
Xavier Glorot and Yoshua Bengio (2010):
Understanding the difficulty of training deep feedforward neural
networks. International conferenc... | [
"Set",
"the",
"parameter",
"initialization",
"using",
"the",
"method",
"described",
"."
] | python | train |
pythongssapi/python-gssapi | gssapi/_utils.py | https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/_utils.py#L10-L30 | def import_gssapi_extension(name):
"""Import a GSSAPI extension module
This method imports a GSSAPI extension module based
on the name of the extension (not including the
'ext_' prefix). If the extension is not available,
the method retuns None.
Args:
name (str): the name of the exten... | [
"def",
"import_gssapi_extension",
"(",
"name",
")",
":",
"try",
":",
"path",
"=",
"'gssapi.raw.ext_{0}'",
".",
"format",
"(",
"name",
")",
"__import__",
"(",
"path",
")",
"return",
"sys",
".",
"modules",
"[",
"path",
"]",
"except",
"ImportError",
":",
"ret... | Import a GSSAPI extension module
This method imports a GSSAPI extension module based
on the name of the extension (not including the
'ext_' prefix). If the extension is not available,
the method retuns None.
Args:
name (str): the name of the extension
Returns:
module: Either ... | [
"Import",
"a",
"GSSAPI",
"extension",
"module"
] | python | train |
bitesofcode/projexui | projexui/widgets/xscintillaedit/xscintillaedit.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xscintillaedit/xscintillaedit.py#L448-L478 | def removeComments( self, comment = None ):
"""
Inserts comments into the editor based on the current selection.\
If no comment string is supplied, then the comment from the language \
will be used.
:param comment | <str> || None
:return <bool> ... | [
"def",
"removeComments",
"(",
"self",
",",
"comment",
"=",
"None",
")",
":",
"if",
"(",
"not",
"comment",
")",
":",
"lang",
"=",
"self",
".",
"language",
"(",
")",
"if",
"(",
"lang",
")",
":",
"comment",
"=",
"lang",
".",
"lineComment",
"(",
")",
... | Inserts comments into the editor based on the current selection.\
If no comment string is supplied, then the comment from the language \
will be used.
:param comment | <str> || None
:return <bool> | success | [
"Inserts",
"comments",
"into",
"the",
"editor",
"based",
"on",
"the",
"current",
"selection",
".",
"\\",
"If",
"no",
"comment",
"string",
"is",
"supplied",
"then",
"the",
"comment",
"from",
"the",
"language",
"\\",
"will",
"be",
"used",
".",
":",
"param",
... | python | train |
misli/django-cms-articles | cms_articles/models/managers.py | https://github.com/misli/django-cms-articles/blob/d96ac77e049022deb4c70d268e4eab74d175145c/cms_articles/models/managers.py#L95-L124 | def set_or_create(self, request, article, form, language):
"""
set or create a title for a particular article and language
"""
base_fields = [
'slug',
'title',
'description',
'meta_description',
'page_title',
'menu_t... | [
"def",
"set_or_create",
"(",
"self",
",",
"request",
",",
"article",
",",
"form",
",",
"language",
")",
":",
"base_fields",
"=",
"[",
"'slug'",
",",
"'title'",
",",
"'description'",
",",
"'meta_description'",
",",
"'page_title'",
",",
"'menu_title'",
",",
"'... | set or create a title for a particular article and language | [
"set",
"or",
"create",
"a",
"title",
"for",
"a",
"particular",
"article",
"and",
"language"
] | python | train |
tensorflow/tensor2tensor | tensor2tensor/utils/optimize.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/optimize.py#L281-L298 | def weight_decay(decay_rate, var_list, skip_biases=True):
"""Apply weight decay to vars in var_list."""
if not decay_rate:
return 0.
tf.logging.info("Applying weight decay, decay_rate: %0.5f", decay_rate)
weight_decays = []
for v in var_list:
# Weight decay.
# This is a heuristic way to detect b... | [
"def",
"weight_decay",
"(",
"decay_rate",
",",
"var_list",
",",
"skip_biases",
"=",
"True",
")",
":",
"if",
"not",
"decay_rate",
":",
"return",
"0.",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Applying weight decay, decay_rate: %0.5f\"",
",",
"decay_rate",
")",
... | Apply weight decay to vars in var_list. | [
"Apply",
"weight",
"decay",
"to",
"vars",
"in",
"var_list",
"."
] | python | train |
T-002/pycast | pycast/common/matrix.py | https://github.com/T-002/pycast/blob/8a53505c6d8367e0ea572e8af768e80b29e1cc41/pycast/common/matrix.py#L530-L590 | def gauss_jordan(self):
"""Reduce :py:obj:`self` to row echelon form.
:return: Returns :py:obj:`self` in row echelon form for convenience.
:rtype: Matrix
:raise: Raises an :py:exc:`ValueError` if:
- the matrix rows < columns
- t... | [
"def",
"gauss_jordan",
"(",
"self",
")",
":",
"mArray",
"=",
"self",
".",
"get_array",
"(",
"rowBased",
"=",
"False",
")",
"width",
"=",
"self",
".",
"get_width",
"(",
")",
"height",
"=",
"self",
".",
"get_height",
"(",
")",
"if",
"not",
"height",
"<... | Reduce :py:obj:`self` to row echelon form.
:return: Returns :py:obj:`self` in row echelon form for convenience.
:rtype: Matrix
:raise: Raises an :py:exc:`ValueError` if:
- the matrix rows < columns
- the matrix is not invertible
... | [
"Reduce",
":",
"py",
":",
"obj",
":",
"self",
"to",
"row",
"echelon",
"form",
"."
] | python | train |
shoebot/shoebot | shoebot/data/geometry.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/shoebot/data/geometry.py#L39-L45 | def rotate(x, y, x0, y0, angle):
""" Returns the coordinates of (x,y) rotated around origin (x0,y0).
"""
x, y = x - x0, y - y0
a, b = cos(radians(angle)), sin(radians(angle))
return (x * a - y * b + x0,
y * a + x * b + y0) | [
"def",
"rotate",
"(",
"x",
",",
"y",
",",
"x0",
",",
"y0",
",",
"angle",
")",
":",
"x",
",",
"y",
"=",
"x",
"-",
"x0",
",",
"y",
"-",
"y0",
"a",
",",
"b",
"=",
"cos",
"(",
"radians",
"(",
"angle",
")",
")",
",",
"sin",
"(",
"radians",
"... | Returns the coordinates of (x,y) rotated around origin (x0,y0). | [
"Returns",
"the",
"coordinates",
"of",
"(",
"x",
"y",
")",
"rotated",
"around",
"origin",
"(",
"x0",
"y0",
")",
"."
] | python | valid |
nickmckay/LiPD-utilities | Python/lipd/directory.py | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L434-L449 | def rm_files_in_dir(path):
"""
Removes all files within a directory, but does not delete the directory
:param str path: Target directory
:return none:
"""
for f in os.listdir(path):
try:
os.remove(f)
except PermissionError:
os.chmod(f, 0o777)
t... | [
"def",
"rm_files_in_dir",
"(",
"path",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"f",
")",
"except",
"PermissionError",
":",
"os",
".",
"chmod",
"(",
"f",
",",
"0o777",
")",
"tr... | Removes all files within a directory, but does not delete the directory
:param str path: Target directory
:return none: | [
"Removes",
"all",
"files",
"within",
"a",
"directory",
"but",
"does",
"not",
"delete",
"the",
"directory",
":",
"param",
"str",
"path",
":",
"Target",
"directory",
":",
"return",
"none",
":"
] | python | train |
tanghaibao/jcvi | jcvi/algorithms/formula.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/formula.py#L198-L219 | def velvet(readsize, genomesize, numreads, K):
"""
Calculate velvet memory requirement.
<http://seqanswers.com/forums/showthread.php?t=2101>
Ram required for velvetg = -109635 + 18977*ReadSize + 86326*GenomeSize +
233353*NumReads - 51092*K
Read size is in bases.
Genome size is in millions ... | [
"def",
"velvet",
"(",
"readsize",
",",
"genomesize",
",",
"numreads",
",",
"K",
")",
":",
"ram",
"=",
"-",
"109635",
"+",
"18977",
"*",
"readsize",
"+",
"86326",
"*",
"genomesize",
"+",
"233353",
"*",
"numreads",
"-",
"51092",
"*",
"K",
"print",
"(",... | Calculate velvet memory requirement.
<http://seqanswers.com/forums/showthread.php?t=2101>
Ram required for velvetg = -109635 + 18977*ReadSize + 86326*GenomeSize +
233353*NumReads - 51092*K
Read size is in bases.
Genome size is in millions of bases (Mb)
Number of reads is in millions
K is t... | [
"Calculate",
"velvet",
"memory",
"requirement",
".",
"<http",
":",
"//",
"seqanswers",
".",
"com",
"/",
"forums",
"/",
"showthread",
".",
"php?t",
"=",
"2101",
">"
] | python | train |
phoebe-project/phoebe2 | phoebe/parameters/parameters.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/parameters/parameters.py#L4756-L4764 | def set_property(self, **kwargs):
"""
set any property of the underlying nparray object
"""
if not isinstance(self._value, nparray.ndarray):
raise ValueError("value is not a nparray object")
for property, value in kwargs.items():
setattr(self._value, prop... | [
"def",
"set_property",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_value",
",",
"nparray",
".",
"ndarray",
")",
":",
"raise",
"ValueError",
"(",
"\"value is not a nparray object\"",
")",
"for",
"property",
... | set any property of the underlying nparray object | [
"set",
"any",
"property",
"of",
"the",
"underlying",
"nparray",
"object"
] | python | train |
mitsei/dlkit | dlkit/json_/logging_/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/logging_/managers.py#L749-L772 | def get_log_entry_query_session_for_log(self, log_id, proxy):
"""Gets the ``OsidSession`` associated with the log entry query service for the given log.
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.logging.LogEntryQuerySe... | [
"def",
"get_log_entry_query_session_for_log",
"(",
"self",
",",
"log_id",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_log_entry_query",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"##",
"# Also include check to see if the catalo... | Gets the ``OsidSession`` associated with the log entry query service for the given log.
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.logging.LogEntryQuerySession) - a
``LogEntryQuerySession``
raise: NotFo... | [
"Gets",
"the",
"OsidSession",
"associated",
"with",
"the",
"log",
"entry",
"query",
"service",
"for",
"the",
"given",
"log",
"."
] | python | train |
quantumlib/Cirq | cirq/contrib/acquaintance/mutation_utils.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/contrib/acquaintance/mutation_utils.py#L36-L67 | def rectify_acquaintance_strategy(
circuit: circuits.Circuit,
acquaint_first: bool=True
) -> None:
"""Splits moments so that they contain either only acquaintance gates
or only permutation gates. Orders resulting moments so that the first one
is of the same type as the previous one.
... | [
"def",
"rectify_acquaintance_strategy",
"(",
"circuit",
":",
"circuits",
".",
"Circuit",
",",
"acquaint_first",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"if",
"not",
"is_acquaintance_strategy",
"(",
"circuit",
")",
":",
"raise",
"TypeError",
"(",
"'no... | Splits moments so that they contain either only acquaintance gates
or only permutation gates. Orders resulting moments so that the first one
is of the same type as the previous one.
Args:
circuit: The acquaintance strategy to rectify.
acquaint_first: Whether to make acquaintance moment firs... | [
"Splits",
"moments",
"so",
"that",
"they",
"contain",
"either",
"only",
"acquaintance",
"gates",
"or",
"only",
"permutation",
"gates",
".",
"Orders",
"resulting",
"moments",
"so",
"that",
"the",
"first",
"one",
"is",
"of",
"the",
"same",
"type",
"as",
"the",... | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/debugging.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/debugging.py#L158-L264 | def get_caller_stack_info(start_back: int = 1) -> List[str]:
r"""
Retrieves a textual representation of the call stack.
Args:
start_back: number of calls back in the frame stack (starting
from the frame stack as seen by :func:`get_caller_stack_info`)
to begin with
Retur... | [
"def",
"get_caller_stack_info",
"(",
"start_back",
":",
"int",
"=",
"1",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# \"0 back\" is debug_callers, so \"1 back\" its caller",
"# https://docs.python.org/3/library/inspect.html",
"callers",
"=",
"[",
"]",
"# type: List[str]",
... | r"""
Retrieves a textual representation of the call stack.
Args:
start_back: number of calls back in the frame stack (starting
from the frame stack as seen by :func:`get_caller_stack_info`)
to begin with
Returns:
list of descriptions
Example:
.. code-block... | [
"r",
"Retrieves",
"a",
"textual",
"representation",
"of",
"the",
"call",
"stack",
"."
] | python | train |
yandex/yandex-tank | yandextank/plugins/Telegraf/client.py | https://github.com/yandex/yandex-tank/blob/d71d63b6ab5de8b8a5ea2b728b6ab9ac0b1ba71b/yandextank/plugins/Telegraf/client.py#L141-L162 | def uninstall(self):
"""
Remove agent's files from remote host
"""
if self.session:
logger.info('Waiting monitoring data...')
self.session.terminate()
self.session.wait()
self.session = None
log_filename = "agent_{host}.log".format(... | [
"def",
"uninstall",
"(",
"self",
")",
":",
"if",
"self",
".",
"session",
":",
"logger",
".",
"info",
"(",
"'Waiting monitoring data...'",
")",
"self",
".",
"session",
".",
"terminate",
"(",
")",
"self",
".",
"session",
".",
"wait",
"(",
")",
"self",
".... | Remove agent's files from remote host | [
"Remove",
"agent",
"s",
"files",
"from",
"remote",
"host"
] | python | test |
hapylestat/apputils | apputils/settings/ast/cmd.py | https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/settings/ast/cmd.py#L142-L160 | def parse(self, argv, tokenizer=DefaultTokenizer):
"""
Parse command line to out tree
:type argv object
:type tokenizer AbstractTokenizer
"""
args = tokenizer.tokenize(argv)
_lang = tokenizer.language_definition()
#
# for param in self.__args:
# if self._is_default_arg(param)... | [
"def",
"parse",
"(",
"self",
",",
"argv",
",",
"tokenizer",
"=",
"DefaultTokenizer",
")",
":",
"args",
"=",
"tokenizer",
".",
"tokenize",
"(",
"argv",
")",
"_lang",
"=",
"tokenizer",
".",
"language_definition",
"(",
")",
"#",
"# for param in self.__args:",
"... | Parse command line to out tree
:type argv object
:type tokenizer AbstractTokenizer | [
"Parse",
"command",
"line",
"to",
"out",
"tree"
] | python | train |
rosenbrockc/ci | pyci/scripts/ci.py | https://github.com/rosenbrockc/ci/blob/4d5a60291424a83124d1d962d17fb4c7718cde2b/pyci/scripts/ci.py#L115-L122 | def _load_db():
"""Deserializes the script database from JSON."""
from os import path
from pyci.utility import get_json
global datapath, db
datapath = path.abspath(path.expanduser(settings.datafile))
vms("Deserializing DB from {}".format(datapath))
db = get_json(datapath, {"installed": [], "... | [
"def",
"_load_db",
"(",
")",
":",
"from",
"os",
"import",
"path",
"from",
"pyci",
".",
"utility",
"import",
"get_json",
"global",
"datapath",
",",
"db",
"datapath",
"=",
"path",
".",
"abspath",
"(",
"path",
".",
"expanduser",
"(",
"settings",
".",
"dataf... | Deserializes the script database from JSON. | [
"Deserializes",
"the",
"script",
"database",
"from",
"JSON",
"."
] | python | train |
cni/MRS | MRS/leastsqbound/leastsqbound.py | https://github.com/cni/MRS/blob/16098b3cf4830780efd787fee9efa46513850283/MRS/leastsqbound/leastsqbound.py#L89-L327 | def leastsqbound(func, x0, args=(), bounds=None, Dfun=None, full_output=0,
col_deriv=0, ftol=1.49012e-8, xtol=1.49012e-8,
gtol=0.0, maxfev=0, epsfcn=0.0, factor=100, diag=None):
"""
Bounded minimization of the sum of squares of a set of equations.
::
x = arg min(sum(func(y)... | [
"def",
"leastsqbound",
"(",
"func",
",",
"x0",
",",
"args",
"=",
"(",
")",
",",
"bounds",
"=",
"None",
",",
"Dfun",
"=",
"None",
",",
"full_output",
"=",
"0",
",",
"col_deriv",
"=",
"0",
",",
"ftol",
"=",
"1.49012e-8",
",",
"xtol",
"=",
"1.49012e-8... | Bounded minimization of the sum of squares of a set of equations.
::
x = arg min(sum(func(y)**2,axis=0))
y
Parameters
----------
func : callable
should take at least one (possibly length N vector) argument and
returns M floating point numbers.
x0 : ndarray... | [
"Bounded",
"minimization",
"of",
"the",
"sum",
"of",
"squares",
"of",
"a",
"set",
"of",
"equations",
"."
] | python | train |
tjcsl/cslbot | cslbot/commands/msg.py | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/msg.py#L23-L37 | def cmd(send, msg, args):
"""Sends a message to a channel
Syntax: {command} <channel> <message>
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('channel', action=arguments.ChanParser)
parser.add_argument('message', nargs='+')
try:
cmdargs = parser.parse_args(msg)... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'channel'",
",",
"action",
"=",
"arguments",
".",
"ChanParser",
")"... | Sends a message to a channel
Syntax: {command} <channel> <message> | [
"Sends",
"a",
"message",
"to",
"a",
"channel",
"Syntax",
":",
"{",
"command",
"}",
"<channel",
">",
"<message",
">"
] | python | train |
DataKitchen/DKCloudCommand | DKCloudCommand/modules/DKCloudAPI.py | https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudAPI.py#L1021-L1057 | def orderrun_detail(self, kitchen, pdict, return_all_data=False):
"""
api.add_resource(OrderDetailsV2, '/v2/order/details/<string:kitchenname>', methods=['POST'])
:param self: DKCloudAPI
:param kitchen: string
:param pdict: dict
:param return_all_data: boolean
:rt... | [
"def",
"orderrun_detail",
"(",
"self",
",",
"kitchen",
",",
"pdict",
",",
"return_all_data",
"=",
"False",
")",
":",
"rc",
"=",
"DKReturnCode",
"(",
")",
"if",
"kitchen",
"is",
"None",
"or",
"isinstance",
"(",
"kitchen",
",",
"basestring",
")",
"is",
"Fa... | api.add_resource(OrderDetailsV2, '/v2/order/details/<string:kitchenname>', methods=['POST'])
:param self: DKCloudAPI
:param kitchen: string
:param pdict: dict
:param return_all_data: boolean
:rtype: DKReturnCode | [
"api",
".",
"add_resource",
"(",
"OrderDetailsV2",
"/",
"v2",
"/",
"order",
"/",
"details",
"/",
"<string",
":",
"kitchenname",
">",
"methods",
"=",
"[",
"POST",
"]",
")",
":",
"param",
"self",
":",
"DKCloudAPI",
":",
"param",
"kitchen",
":",
"string",
... | python | train |
SmokinCaterpillar/pypet | pypet/utils/decorators.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/decorators.py#L105-L125 | def kwargs_mutual_exclusive(param1_name, param2_name, map2to1=None):
""" If there exist mutually exclusive parameters checks for them and maps param2 to 1."""
def wrapper(func):
@functools.wraps(func)
def new_func(*args, **kwargs):
if param2_name in kwargs:
if param1_... | [
"def",
"kwargs_mutual_exclusive",
"(",
"param1_name",
",",
"param2_name",
",",
"map2to1",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"... | If there exist mutually exclusive parameters checks for them and maps param2 to 1. | [
"If",
"there",
"exist",
"mutually",
"exclusive",
"parameters",
"checks",
"for",
"them",
"and",
"maps",
"param2",
"to",
"1",
"."
] | python | test |
GeorgeArgyros/symautomata | symautomata/flex2fst.py | https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/flex2fst.py#L219-L230 | def _add_sink_state(self, states):
"""
This function adds a sing state in the total states
Args:
states (list): The current states
Returns:
None
"""
cleared = []
for i in range(0, 128):
cleared.append(-1)
states.append(c... | [
"def",
"_add_sink_state",
"(",
"self",
",",
"states",
")",
":",
"cleared",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"128",
")",
":",
"cleared",
".",
"append",
"(",
"-",
"1",
")",
"states",
".",
"append",
"(",
"cleared",
")"
] | This function adds a sing state in the total states
Args:
states (list): The current states
Returns:
None | [
"This",
"function",
"adds",
"a",
"sing",
"state",
"in",
"the",
"total",
"states",
"Args",
":",
"states",
"(",
"list",
")",
":",
"The",
"current",
"states",
"Returns",
":",
"None"
] | python | train |
googleapis/google-cloud-python | bigquery/google/cloud/bigquery/job.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/job.py#L2518-L2528 | def to_api_repr(self):
"""Generate a resource for :meth:`_begin`."""
configuration = self._configuration.to_api_repr()
resource = {
"jobReference": self._properties["jobReference"],
"configuration": configuration,
}
configuration["query"]["query"] = self.... | [
"def",
"to_api_repr",
"(",
"self",
")",
":",
"configuration",
"=",
"self",
".",
"_configuration",
".",
"to_api_repr",
"(",
")",
"resource",
"=",
"{",
"\"jobReference\"",
":",
"self",
".",
"_properties",
"[",
"\"jobReference\"",
"]",
",",
"\"configuration\"",
"... | Generate a resource for :meth:`_begin`. | [
"Generate",
"a",
"resource",
"for",
":",
"meth",
":",
"_begin",
"."
] | python | train |
dhermes/bezier | src/bezier/_geometric_intersection.py | https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L1180-L1199 | def make_same_degree(nodes1, nodes2):
"""Degree-elevate a curve so two curves have matching degree.
Args:
nodes1 (numpy.ndarray): Set of control points for a
B |eacute| zier curve.
nodes2 (numpy.ndarray): Set of control points for a
B |eacute| zier curve.
Returns:
... | [
"def",
"make_same_degree",
"(",
"nodes1",
",",
"nodes2",
")",
":",
"_",
",",
"num_nodes1",
"=",
"nodes1",
".",
"shape",
"_",
",",
"num_nodes2",
"=",
"nodes2",
".",
"shape",
"for",
"_",
"in",
"six",
".",
"moves",
".",
"xrange",
"(",
"num_nodes2",
"-",
... | Degree-elevate a curve so two curves have matching degree.
Args:
nodes1 (numpy.ndarray): Set of control points for a
B |eacute| zier curve.
nodes2 (numpy.ndarray): Set of control points for a
B |eacute| zier curve.
Returns:
Tuple[numpy.ndarray, numpy.ndarray]: T... | [
"Degree",
"-",
"elevate",
"a",
"curve",
"so",
"two",
"curves",
"have",
"matching",
"degree",
"."
] | python | train |
Neurita/boyle | boyle/utils/strings.py | https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/utils/strings.py#L209-L238 | def where_is(strings, pattern, n=1, lookup_func=re.match):
"""Return index of the nth match found of pattern in strings
Parameters
----------
strings: list of str
List of strings
pattern: str
Pattern to be matched
nth: int
Number of times the match must happen to retur... | [
"def",
"where_is",
"(",
"strings",
",",
"pattern",
",",
"n",
"=",
"1",
",",
"lookup_func",
"=",
"re",
".",
"match",
")",
":",
"count",
"=",
"0",
"for",
"idx",
",",
"item",
"in",
"enumerate",
"(",
"strings",
")",
":",
"if",
"lookup_func",
"(",
"patt... | Return index of the nth match found of pattern in strings
Parameters
----------
strings: list of str
List of strings
pattern: str
Pattern to be matched
nth: int
Number of times the match must happen to return the item index.
lookup_func: callable
Function to m... | [
"Return",
"index",
"of",
"the",
"nth",
"match",
"found",
"of",
"pattern",
"in",
"strings"
] | python | valid |
dw/mitogen | ansible_mitogen/mixins.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/mixins.py#L404-L432 | def _low_level_execute_command(self, cmd, sudoable=True, in_data=None,
executable=None,
encoding_errors='surrogate_then_replace',
chdir=None):
"""
Override the base implementation by simply calling
... | [
"def",
"_low_level_execute_command",
"(",
"self",
",",
"cmd",
",",
"sudoable",
"=",
"True",
",",
"in_data",
"=",
"None",
",",
"executable",
"=",
"None",
",",
"encoding_errors",
"=",
"'surrogate_then_replace'",
",",
"chdir",
"=",
"None",
")",
":",
"LOG",
".",... | Override the base implementation by simply calling
target.exec_command() in the target context. | [
"Override",
"the",
"base",
"implementation",
"by",
"simply",
"calling",
"target",
".",
"exec_command",
"()",
"in",
"the",
"target",
"context",
"."
] | python | train |
saltstack/salt | salt/modules/glanceng.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glanceng.py#L188-L201 | def update_image_properties(auth=None, **kwargs):
'''
Update properties for an image
CLI Example:
.. code-block:: bash
salt '*' glanceng.update_image_properties name=image1 hw_scsi_model=virtio-scsi hw_disk_bus=scsi
salt '*' glanceng.update_image_properties name=0e4febc2a5ab4f2c8f374b... | [
"def",
"update_image_properties",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"update_image_propertie... | Update properties for an image
CLI Example:
.. code-block:: bash
salt '*' glanceng.update_image_properties name=image1 hw_scsi_model=virtio-scsi hw_disk_bus=scsi
salt '*' glanceng.update_image_properties name=0e4febc2a5ab4f2c8f374b054162506d min_ram=1024 | [
"Update",
"properties",
"for",
"an",
"image"
] | python | train |
zetaops/zengine | zengine/views/channel_management.py | https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/views/channel_management.py#L113-L123 | def save_new_channel(self):
"""
It saves new channel according to specified channel features.
"""
form_info = self.input['form']
channel = Channel(typ=15, name=form_info['name'],
description=form_info['description'],
owner_id=f... | [
"def",
"save_new_channel",
"(",
"self",
")",
":",
"form_info",
"=",
"self",
".",
"input",
"[",
"'form'",
"]",
"channel",
"=",
"Channel",
"(",
"typ",
"=",
"15",
",",
"name",
"=",
"form_info",
"[",
"'name'",
"]",
",",
"description",
"=",
"form_info",
"["... | It saves new channel according to specified channel features. | [
"It",
"saves",
"new",
"channel",
"according",
"to",
"specified",
"channel",
"features",
"."
] | python | train |
briancappello/flask-unchained | flask_unchained/bundles/security/services/security_service.py | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L229-L247 | def send_reset_password_instructions(self, user):
"""
Sends the reset password instructions email for the specified user.
Sends signal `reset_password_instructions_sent`.
:param user: The user to send the instructions to.
"""
token = self.security_utils_service.generate... | [
"def",
"send_reset_password_instructions",
"(",
"self",
",",
"user",
")",
":",
"token",
"=",
"self",
".",
"security_utils_service",
".",
"generate_reset_password_token",
"(",
"user",
")",
"reset_link",
"=",
"url_for",
"(",
"'security_controller.reset_password'",
",",
... | Sends the reset password instructions email for the specified user.
Sends signal `reset_password_instructions_sent`.
:param user: The user to send the instructions to. | [
"Sends",
"the",
"reset",
"password",
"instructions",
"email",
"for",
"the",
"specified",
"user",
"."
] | python | train |
openfisca/openfisca-core | openfisca_core/simulation_builder.py | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulation_builder.py#L59-L126 | def build_from_entities(self, tax_benefit_system, input_dict):
"""
Build a simulation from a Python dict ``input_dict`` fully specifying entities.
Examples:
>>> simulation_builder.build_from_entities({
'persons': {'Javier': { 'salary': {'2018-11': 2000}}},
... | [
"def",
"build_from_entities",
"(",
"self",
",",
"tax_benefit_system",
",",
"input_dict",
")",
":",
"input_dict",
"=",
"deepcopy",
"(",
"input_dict",
")",
"simulation",
"=",
"Simulation",
"(",
"tax_benefit_system",
",",
"tax_benefit_system",
".",
"instantiate_entities"... | Build a simulation from a Python dict ``input_dict`` fully specifying entities.
Examples:
>>> simulation_builder.build_from_entities({
'persons': {'Javier': { 'salary': {'2018-11': 2000}}},
'households': {'household': {'parents': ['Javier']}}
}) | [
"Build",
"a",
"simulation",
"from",
"a",
"Python",
"dict",
"input_dict",
"fully",
"specifying",
"entities",
"."
] | python | train |
ewels/MultiQC | multiqc/modules/picard/VariantCallingMetrics.py | https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/modules/picard/VariantCallingMetrics.py#L184-L230 | def compare_variant_type_plot(data):
""" Return HTML for the Variant Counts barplot """
keys = OrderedDict()
keys['snps'] = {'name': 'SNPs', 'color': '#7cb5ec'}
keys['indels'] = {'name': 'InDels', 'color': '#90ed7d'}
keys['multiallelic_snps'] = {'name': 'multi-allelic SNP', 'color': 'orange'}
ke... | [
"def",
"compare_variant_type_plot",
"(",
"data",
")",
":",
"keys",
"=",
"OrderedDict",
"(",
")",
"keys",
"[",
"'snps'",
"]",
"=",
"{",
"'name'",
":",
"'SNPs'",
",",
"'color'",
":",
"'#7cb5ec'",
"}",
"keys",
"[",
"'indels'",
"]",
"=",
"{",
"'name'",
":"... | Return HTML for the Variant Counts barplot | [
"Return",
"HTML",
"for",
"the",
"Variant",
"Counts",
"barplot"
] | python | train |
hubo1016/vlcp | vlcp/utils/flowupdater.py | https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/utils/flowupdater.py#L114-L127 | async def _dataobject_update_detect(self, _initialkeys, _savedresult):
"""
Coroutine that wait for retrieved value update notification
"""
def expr(newvalues, updatedvalues):
if any(v.getkey() in _initialkeys for v in updatedvalues if v is not None):
return Tr... | [
"async",
"def",
"_dataobject_update_detect",
"(",
"self",
",",
"_initialkeys",
",",
"_savedresult",
")",
":",
"def",
"expr",
"(",
"newvalues",
",",
"updatedvalues",
")",
":",
"if",
"any",
"(",
"v",
".",
"getkey",
"(",
")",
"in",
"_initialkeys",
"for",
"v",... | Coroutine that wait for retrieved value update notification | [
"Coroutine",
"that",
"wait",
"for",
"retrieved",
"value",
"update",
"notification"
] | python | train |
LogicalDash/LiSE | ELiDE/ELiDE/charmenu.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/charmenu.py#L140-L158 | def toggle_reciprocal(self):
"""Flip my ``reciprocal_portal`` boolean, and draw (or stop drawing)
an extra arrow on the appropriate button to indicate the
fact.
"""
self.screen.boardview.reciprocal_portal = not self.screen.boardview.reciprocal_portal
if self.screen.board... | [
"def",
"toggle_reciprocal",
"(",
"self",
")",
":",
"self",
".",
"screen",
".",
"boardview",
".",
"reciprocal_portal",
"=",
"not",
"self",
".",
"screen",
".",
"boardview",
".",
"reciprocal_portal",
"if",
"self",
".",
"screen",
".",
"boardview",
".",
"reciproc... | Flip my ``reciprocal_portal`` boolean, and draw (or stop drawing)
an extra arrow on the appropriate button to indicate the
fact. | [
"Flip",
"my",
"reciprocal_portal",
"boolean",
"and",
"draw",
"(",
"or",
"stop",
"drawing",
")",
"an",
"extra",
"arrow",
"on",
"the",
"appropriate",
"button",
"to",
"indicate",
"the",
"fact",
"."
] | python | train |
h2oai/h2o-3 | h2o-py/h2o/utils/debugging.py | https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/h2o-py/h2o/utils/debugging.py#L268-L304 | def _find_function_from_code(frame, code):
"""
Given a frame and a compiled function code, find the corresponding function object within the frame.
This function addresses the following problem: when handling a stacktrace, we receive information about
which piece of code was being executed in the form ... | [
"def",
"_find_function_from_code",
"(",
"frame",
",",
"code",
")",
":",
"def",
"find_code",
"(",
"iterable",
",",
"depth",
"=",
"0",
")",
":",
"if",
"depth",
">",
"3",
":",
"return",
"# Avoid potential infinite loops, or generally objects that are too deep.",
"for",... | Given a frame and a compiled function code, find the corresponding function object within the frame.
This function addresses the following problem: when handling a stacktrace, we receive information about
which piece of code was being executed in the form of a CodeType object. That objects contains function na... | [
"Given",
"a",
"frame",
"and",
"a",
"compiled",
"function",
"code",
"find",
"the",
"corresponding",
"function",
"object",
"within",
"the",
"frame",
"."
] | python | test |
sixty-north/cosmic-ray | src/cosmic_ray/plugins.py | https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/plugins.py#L78-L87 | def get_execution_engine(name):
"""Get the execution engine by name."""
manager = driver.DriverManager(
namespace='cosmic_ray.execution_engines',
name=name,
invoke_on_load=True,
on_load_failure_callback=_log_extension_loading_failure,
)
return manager.driver | [
"def",
"get_execution_engine",
"(",
"name",
")",
":",
"manager",
"=",
"driver",
".",
"DriverManager",
"(",
"namespace",
"=",
"'cosmic_ray.execution_engines'",
",",
"name",
"=",
"name",
",",
"invoke_on_load",
"=",
"True",
",",
"on_load_failure_callback",
"=",
"_log... | Get the execution engine by name. | [
"Get",
"the",
"execution",
"engine",
"by",
"name",
"."
] | python | train |
HumanCellAtlas/dcp-cli | hca/util/__init__.py | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/util/__init__.py#L335-L344 | def refresh_swagger(self):
"""
Manually refresh the swagger document. This can help resolve errors communicate with the API.
"""
try:
os.remove(self._get_swagger_filename(self.swagger_url))
except EnvironmentError as e:
logger.warn(os.strerror(e.errno))
... | [
"def",
"refresh_swagger",
"(",
"self",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"self",
".",
"_get_swagger_filename",
"(",
"self",
".",
"swagger_url",
")",
")",
"except",
"EnvironmentError",
"as",
"e",
":",
"logger",
".",
"warn",
"(",
"os",
".",
... | Manually refresh the swagger document. This can help resolve errors communicate with the API. | [
"Manually",
"refresh",
"the",
"swagger",
"document",
".",
"This",
"can",
"help",
"resolve",
"errors",
"communicate",
"with",
"the",
"API",
"."
] | python | train |
senaite/senaite.core | bika/lims/browser/partition_magic.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/partition_magic.py#L169-L174 | def get_preservation_data(self):
"""Returns a list of Preservation data
"""
for obj in self.get_preservations():
info = self.get_base_info(obj)
yield info | [
"def",
"get_preservation_data",
"(",
"self",
")",
":",
"for",
"obj",
"in",
"self",
".",
"get_preservations",
"(",
")",
":",
"info",
"=",
"self",
".",
"get_base_info",
"(",
"obj",
")",
"yield",
"info"
] | Returns a list of Preservation data | [
"Returns",
"a",
"list",
"of",
"Preservation",
"data"
] | python | train |
markchil/gptools | gptools/gaussian_process.py | https://github.com/markchil/gptools/blob/225db52bfe6baef1516529ad22177aa2cf7b71e4/gptools/gaussian_process.py#L247-L253 | def hyperprior(self):
"""Combined hyperprior for the kernel, noise kernel and (if present) mean function.
"""
hp = self.k.hyperprior * self.noise_k.hyperprior
if self.mu is not None:
hp *= self.mu.hyperprior
return hp | [
"def",
"hyperprior",
"(",
"self",
")",
":",
"hp",
"=",
"self",
".",
"k",
".",
"hyperprior",
"*",
"self",
".",
"noise_k",
".",
"hyperprior",
"if",
"self",
".",
"mu",
"is",
"not",
"None",
":",
"hp",
"*=",
"self",
".",
"mu",
".",
"hyperprior",
"return... | Combined hyperprior for the kernel, noise kernel and (if present) mean function. | [
"Combined",
"hyperprior",
"for",
"the",
"kernel",
"noise",
"kernel",
"and",
"(",
"if",
"present",
")",
"mean",
"function",
"."
] | python | train |
openstack/networking-arista | networking_arista/ml2/security_groups/arista_security_groups.py | https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/ml2/security_groups/arista_security_groups.py#L87-L100 | def _valid_baremetal_port(port):
"""Check if port is a baremetal port with exactly one security group"""
if port.get(portbindings.VNIC_TYPE) != portbindings.VNIC_BAREMETAL:
return False
sgs = port.get('security_groups', [])
if len(sgs) == 0:
# Nothing to do
... | [
"def",
"_valid_baremetal_port",
"(",
"port",
")",
":",
"if",
"port",
".",
"get",
"(",
"portbindings",
".",
"VNIC_TYPE",
")",
"!=",
"portbindings",
".",
"VNIC_BAREMETAL",
":",
"return",
"False",
"sgs",
"=",
"port",
".",
"get",
"(",
"'security_groups'",
",",
... | Check if port is a baremetal port with exactly one security group | [
"Check",
"if",
"port",
"is",
"a",
"baremetal",
"port",
"with",
"exactly",
"one",
"security",
"group"
] | python | train |
liftoff/pyminifier | pyminifier/minification.py | https://github.com/liftoff/pyminifier/blob/087ea7b0c8c964f1f907c3f350f5ce281798db86/pyminifier/minification.py#L281-L333 | def dedent(source, use_tabs=False):
"""
Minimizes indentation to save precious bytes. Optionally, *use_tabs*
may be specified if you want to use tabulators (\t) instead of spaces.
Example::
def foo(bar):
test = "This is a test"
Will become::
def foo(bar):
te... | [
"def",
"dedent",
"(",
"source",
",",
"use_tabs",
"=",
"False",
")",
":",
"if",
"use_tabs",
":",
"indent_char",
"=",
"'\\t'",
"else",
":",
"indent_char",
"=",
"' '",
"io_obj",
"=",
"io",
".",
"StringIO",
"(",
"source",
")",
"out",
"=",
"\"\"",
"last_lin... | Minimizes indentation to save precious bytes. Optionally, *use_tabs*
may be specified if you want to use tabulators (\t) instead of spaces.
Example::
def foo(bar):
test = "This is a test"
Will become::
def foo(bar):
test = "This is a test" | [
"Minimizes",
"indentation",
"to",
"save",
"precious",
"bytes",
".",
"Optionally",
"*",
"use_tabs",
"*",
"may",
"be",
"specified",
"if",
"you",
"want",
"to",
"use",
"tabulators",
"(",
"\\",
"t",
")",
"instead",
"of",
"spaces",
"."
] | python | train |
sorgerlab/indra | indra/assemblers/pysb/assembler.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/pysb/assembler.py#L792-L812 | def save_rst(self, file_name='pysb_model.rst', module_name='pysb_module'):
"""Save the assembled model as an RST file for literate modeling.
Parameters
----------
file_name : Optional[str]
The name of the file to save the RST in.
Default: pysb_model.rst
m... | [
"def",
"save_rst",
"(",
"self",
",",
"file_name",
"=",
"'pysb_model.rst'",
",",
"module_name",
"=",
"'pysb_module'",
")",
":",
"if",
"self",
".",
"model",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"file_name",
",",
"'wt'",
")",
"as",
"fh",
":",
"f... | Save the assembled model as an RST file for literate modeling.
Parameters
----------
file_name : Optional[str]
The name of the file to save the RST in.
Default: pysb_model.rst
module_name : Optional[str]
The name of the python function defining the mo... | [
"Save",
"the",
"assembled",
"model",
"as",
"an",
"RST",
"file",
"for",
"literate",
"modeling",
"."
] | python | train |
eandersson/amqpstorm | amqpstorm/io.py | https://github.com/eandersson/amqpstorm/blob/38330906c0af19eea482f43c5ce79bab98a1e064/amqpstorm/io.py#L152-L166 | def _get_socket_addresses(self):
"""Get Socket address information.
:rtype: list
"""
family = socket.AF_UNSPEC
if not socket.has_ipv6:
family = socket.AF_INET
try:
addresses = socket.getaddrinfo(self._parameters['hostname'],
... | [
"def",
"_get_socket_addresses",
"(",
"self",
")",
":",
"family",
"=",
"socket",
".",
"AF_UNSPEC",
"if",
"not",
"socket",
".",
"has_ipv6",
":",
"family",
"=",
"socket",
".",
"AF_INET",
"try",
":",
"addresses",
"=",
"socket",
".",
"getaddrinfo",
"(",
"self",... | Get Socket address information.
:rtype: list | [
"Get",
"Socket",
"address",
"information",
"."
] | python | train |
shaypal5/utilitime | utilitime/timestamp/timestamp.py | https://github.com/shaypal5/utilitime/blob/554ca05fa83c2dbf5d6cf9c9cfa6b03ee6cdb609/utilitime/timestamp/timestamp.py#L12-L32 | def timestamp_to_local_time(timestamp, timezone_name):
"""Convert epoch timestamp to a localized Delorean datetime object.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
Returns
-------... | [
"def",
"timestamp_to_local_time",
"(",
"timestamp",
",",
"timezone_name",
")",
":",
"# first convert timestamp to UTC",
"utc_time",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"float",
"(",
"timestamp",
")",
")",
"delo",
"=",
"Delorean",
"(",
"utc_time",
",",
"... | Convert epoch timestamp to a localized Delorean datetime object.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
Returns
-------
delorean.Delorean
A localized Delorean datetime o... | [
"Convert",
"epoch",
"timestamp",
"to",
"a",
"localized",
"Delorean",
"datetime",
"object",
"."
] | python | train |
mozilla-b2g/fxos-certsuite | mcts/utils/handlers/adb_b2g.py | https://github.com/mozilla-b2g/fxos-certsuite/blob/152a76c7c4c9d908524cf6e6fc25a498058f363d/mcts/utils/handlers/adb_b2g.py#L131-L189 | def wait_for_device_ready(self, timeout=None, wait_polling_interval=None, after_first=None):
"""Wait for the device to become ready for reliable interaction via adb.
NOTE: if the device is *already* ready this method will timeout.
:param timeout: Maximum time to wait for the device to become re... | [
"def",
"wait_for_device_ready",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"wait_polling_interval",
"=",
"None",
",",
"after_first",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"self",
".",
"_timeout",
"if",
"wait_polling_i... | Wait for the device to become ready for reliable interaction via adb.
NOTE: if the device is *already* ready this method will timeout.
:param timeout: Maximum time to wait for the device to become ready
:param wait_polling_interval: Interval at which to poll for device readiness.
:param... | [
"Wait",
"for",
"the",
"device",
"to",
"become",
"ready",
"for",
"reliable",
"interaction",
"via",
"adb",
".",
"NOTE",
":",
"if",
"the",
"device",
"is",
"*",
"already",
"*",
"ready",
"this",
"method",
"will",
"timeout",
"."
] | python | train |
niemasd/TreeSwift | treeswift/Node.py | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Node.py#L336-L349 | def traverse_preorder(self, leaves=True, internal=True):
'''Perform a preorder traversal starting at this ``Node`` object
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False`... | [
"def",
"traverse_preorder",
"(",
"self",
",",
"leaves",
"=",
"True",
",",
"internal",
"=",
"True",
")",
":",
"s",
"=",
"deque",
"(",
")",
"s",
".",
"append",
"(",
"self",
")",
"while",
"len",
"(",
"s",
")",
"!=",
"0",
":",
"n",
"=",
"s",
".",
... | Perform a preorder traversal starting at this ``Node`` object
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False`` | [
"Perform",
"a",
"preorder",
"traversal",
"starting",
"at",
"this",
"Node",
"object"
] | python | train |
pantsbuild/pants | contrib/python/src/python/pants/contrib/python/checks/checker/common.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/python/src/python/pants/contrib/python/checks/checker/common.py#L148-L159 | def from_statement(cls, statement, filename='<expr>'):
"""A helper to construct a PythonFile from a triple-quoted string, for testing.
:param statement: Python file contents
:return: Instance of PythonFile
"""
lines = textwrap.dedent(statement).split('\n')
if lines and not lines[0]: # Remove th... | [
"def",
"from_statement",
"(",
"cls",
",",
"statement",
",",
"filename",
"=",
"'<expr>'",
")",
":",
"lines",
"=",
"textwrap",
".",
"dedent",
"(",
"statement",
")",
".",
"split",
"(",
"'\\n'",
")",
"if",
"lines",
"and",
"not",
"lines",
"[",
"0",
"]",
"... | A helper to construct a PythonFile from a triple-quoted string, for testing.
:param statement: Python file contents
:return: Instance of PythonFile | [
"A",
"helper",
"to",
"construct",
"a",
"PythonFile",
"from",
"a",
"triple",
"-",
"quoted",
"string",
"for",
"testing",
".",
":",
"param",
"statement",
":",
"Python",
"file",
"contents",
":",
"return",
":",
"Instance",
"of",
"PythonFile"
] | python | train |
theiviaxx/python-perforce | perforce/models.py | https://github.com/theiviaxx/python-perforce/blob/01a3b01fe5949126fa0097d9a8ad386887823b5a/perforce/models.py#L320-L345 | def findChangelist(self, description=None):
"""Gets or creates a Changelist object with a description
:param description: The description to set or lookup
:type description: str
:returns: :class:`.Changelist`
"""
if description is None:
change = Default(self)... | [
"def",
"findChangelist",
"(",
"self",
",",
"description",
"=",
"None",
")",
":",
"if",
"description",
"is",
"None",
":",
"change",
"=",
"Default",
"(",
"self",
")",
"else",
":",
"if",
"isinstance",
"(",
"description",
",",
"six",
".",
"integer_types",
")... | Gets or creates a Changelist object with a description
:param description: The description to set or lookup
:type description: str
:returns: :class:`.Changelist` | [
"Gets",
"or",
"creates",
"a",
"Changelist",
"object",
"with",
"a",
"description"
] | python | train |
tbreitenfeldt/invisible_ui | invisible_ui/events/eventManager.py | https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/events/eventManager.py#L149-L163 | def change_event_actions(self, handler, actions):
"""
This allows the client to change the actions for an event, in the case that there is a desire for slightly different behavior, such as reasigning keys.
handler - the handler object that the desired changes are made to.
actions - The... | [
"def",
"change_event_actions",
"(",
"self",
",",
"handler",
",",
"actions",
")",
":",
"if",
"not",
"isinstance",
"(",
"handler",
",",
"Handler",
")",
":",
"raise",
"TypeError",
"(",
"\"given object must be of type Handler.\"",
")",
"if",
"not",
"self",
".",
"r... | This allows the client to change the actions for an event, in the case that there is a desire for slightly different behavior, such as reasigning keys.
handler - the handler object that the desired changes are made to.
actions - The methods that are called when this handler is varified against the cur... | [
"This",
"allows",
"the",
"client",
"to",
"change",
"the",
"actions",
"for",
"an",
"event",
"in",
"the",
"case",
"that",
"there",
"is",
"a",
"desire",
"for",
"slightly",
"different",
"behavior",
"such",
"as",
"reasigning",
"keys",
"."
] | python | train |
emirozer/bowshock | bowshock/maas.py | https://github.com/emirozer/bowshock/blob/9f5e053f1d54995b833b83616f37c67178c3e840/bowshock/maas.py#L45-L67 | def maas_archive(begin, end):
'''
This returns a collection of JSON objects for every weather report available for October 2012:
{
"count": 29,
"next": "http://marsweather.ingenology.com/v1/archive/?terrestrial_date_end=2012-10-31&terrestrial_date_start=2012-10-01&page=2",
"previous": null,
... | [
"def",
"maas_archive",
"(",
"begin",
",",
"end",
")",
":",
"base_url",
"=",
"'http://marsweather.ingenology.com/v1/archive/?'",
"try",
":",
"vali_date",
"(",
"begin",
")",
"vali_date",
"(",
"end",
")",
"base_url",
"+=",
"'terrestrial_date_start='",
"+",
"begin",
"... | This returns a collection of JSON objects for every weather report available for October 2012:
{
"count": 29,
"next": "http://marsweather.ingenology.com/v1/archive/?terrestrial_date_end=2012-10-31&terrestrial_date_start=2012-10-01&page=2",
"previous": null,
"results": [
...
]
} | [
"This",
"returns",
"a",
"collection",
"of",
"JSON",
"objects",
"for",
"every",
"weather",
"report",
"available",
"for",
"October",
"2012",
":"
] | python | train |
evhub/coconut | coconut/requirements.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/requirements.py#L157-L176 | def print_new_versions(strict=False):
"""Prints new requirement versions."""
new_updates = []
same_updates = []
for req in everything_in(all_reqs):
new_versions = []
same_versions = []
for ver_str in all_versions(req):
if newer(ver_str_to_tuple(ver_str), min_versions[... | [
"def",
"print_new_versions",
"(",
"strict",
"=",
"False",
")",
":",
"new_updates",
"=",
"[",
"]",
"same_updates",
"=",
"[",
"]",
"for",
"req",
"in",
"everything_in",
"(",
"all_reqs",
")",
":",
"new_versions",
"=",
"[",
"]",
"same_versions",
"=",
"[",
"]"... | Prints new requirement versions. | [
"Prints",
"new",
"requirement",
"versions",
"."
] | python | train |
quantopian/zipline | zipline/utils/api_support.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/api_support.py#L86-L105 | def require_initialized(exception):
"""
Decorator for API methods that should only be called after
TradingAlgorithm.initialize. `exception` will be raised if the method is
called before initialize has completed.
Examples
--------
@require_initialized(SomeException("Don't do that!"))
de... | [
"def",
"require_initialized",
"(",
"exception",
")",
":",
"def",
"decorator",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"wrapped_method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
"... | Decorator for API methods that should only be called after
TradingAlgorithm.initialize. `exception` will be raised if the method is
called before initialize has completed.
Examples
--------
@require_initialized(SomeException("Don't do that!"))
def method(self):
# Do stuff that should o... | [
"Decorator",
"for",
"API",
"methods",
"that",
"should",
"only",
"be",
"called",
"after",
"TradingAlgorithm",
".",
"initialize",
".",
"exception",
"will",
"be",
"raised",
"if",
"the",
"method",
"is",
"called",
"before",
"initialize",
"has",
"completed",
"."
] | python | train |
bgyori/pykqml | kqml/kqml_list.py | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L113-L124 | def push(self, obj):
"""Prepend an element to the beginnging of the list.
Parameters
----------
obj : KQMLObject or str
If a string is passed, it is instantiated as a
KQMLToken before being added to the list.
"""
if isinstance(obj, str):
... | [
"def",
"push",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"obj",
"=",
"KQMLToken",
"(",
"obj",
")",
"self",
".",
"data",
".",
"insert",
"(",
"0",
",",
"obj",
")"
] | Prepend an element to the beginnging of the list.
Parameters
----------
obj : KQMLObject or str
If a string is passed, it is instantiated as a
KQMLToken before being added to the list. | [
"Prepend",
"an",
"element",
"to",
"the",
"beginnging",
"of",
"the",
"list",
"."
] | python | train |
HumanBrainProject/hbp-service-client | hbp_service_client/storage_service/api.py | https://github.com/HumanBrainProject/hbp-service-client/blob/b338fb41a7f0e7b9d654ff28fcf13a56d03bff4d/hbp_service_client/storage_service/api.py#L527-L557 | def create_project(self, collab_id):
'''Create a new project.
Args:
collab_id (int): The id of the collab the project should be created in.
Returns:
A dictionary of details of the created project::
{
u'collab_id': 12998,
... | [
"def",
"create_project",
"(",
"self",
",",
"collab_id",
")",
":",
"return",
"self",
".",
"_authenticated_request",
".",
"to_endpoint",
"(",
"'project/'",
")",
".",
"with_json_body",
"(",
"self",
".",
"_prep_params",
"(",
"locals",
"(",
")",
")",
")",
".",
... | Create a new project.
Args:
collab_id (int): The id of the collab the project should be created in.
Returns:
A dictionary of details of the created project::
{
u'collab_id': 12998,
u'created_by': u'303447',
... | [
"Create",
"a",
"new",
"project",
"."
] | python | test |
SeattleTestbed/seash | pyreadline/unicode_helper.py | https://github.com/SeattleTestbed/seash/blob/40f9d2285662ff8b61e0468b4196acee089b273b/pyreadline/unicode_helper.py#L29-L36 | def ensure_str(text):
u"""Convert unicode to str using pyreadline_codepage"""
if isinstance(text, unicode):
try:
return text.encode(pyreadline_codepage, u"replace")
except (LookupError, TypeError):
return text.encode(u"ascii", u"replace")
return text | [
"def",
"ensure_str",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"unicode",
")",
":",
"try",
":",
"return",
"text",
".",
"encode",
"(",
"pyreadline_codepage",
",",
"u\"replace\"",
")",
"except",
"(",
"LookupError",
",",
"TypeError",
")",
... | u"""Convert unicode to str using pyreadline_codepage | [
"u",
"Convert",
"unicode",
"to",
"str",
"using",
"pyreadline_codepage"
] | python | train |
swimlane/swimlane-python | swimlane/core/fields/base/field.py | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/base/field.py#L101-L111 | def validate_value(self, value):
"""Validate value is an acceptable type during set_python operation"""
if self.readonly:
raise ValidationError(self.record, "Cannot set readonly field '{}'".format(self.name))
if value not in (None, self._unset):
if self.supported_types an... | [
"def",
"validate_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"readonly",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"record",
",",
"\"Cannot set readonly field '{}'\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"if",
"v... | Validate value is an acceptable type during set_python operation | [
"Validate",
"value",
"is",
"an",
"acceptable",
"type",
"during",
"set_python",
"operation"
] | python | train |
niklasf/python-chess | chess/gaviota.py | https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/gaviota.py#L1544-L1554 | def add_directory(self, directory: PathLike) -> None:
"""
Adds *.gtb.cp4* tables from a directory. The relevant files are lazily
opened when the tablebase is actually probed.
"""
directory = os.path.abspath(directory)
if not os.path.isdir(directory):
raise IOE... | [
"def",
"add_directory",
"(",
"self",
",",
"directory",
":",
"PathLike",
")",
"->",
"None",
":",
"directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"rai... | Adds *.gtb.cp4* tables from a directory. The relevant files are lazily
opened when the tablebase is actually probed. | [
"Adds",
"*",
".",
"gtb",
".",
"cp4",
"*",
"tables",
"from",
"a",
"directory",
".",
"The",
"relevant",
"files",
"are",
"lazily",
"opened",
"when",
"the",
"tablebase",
"is",
"actually",
"probed",
"."
] | python | train |
quodlibet/mutagen | mutagen/mp4/_as_entry.py | https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/mp4/_as_entry.py#L228-L245 | def parse(cls, fileobj):
"""Returns a parsed instance of the called type.
The file position is right after the descriptor after this returns.
Raises DescriptorError
"""
try:
length = cls._parse_desc_length_file(fileobj)
except ValueError as e:
ra... | [
"def",
"parse",
"(",
"cls",
",",
"fileobj",
")",
":",
"try",
":",
"length",
"=",
"cls",
".",
"_parse_desc_length_file",
"(",
"fileobj",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"DescriptorError",
"(",
"e",
")",
"pos",
"=",
"fileobj",
".",
... | Returns a parsed instance of the called type.
The file position is right after the descriptor after this returns.
Raises DescriptorError | [
"Returns",
"a",
"parsed",
"instance",
"of",
"the",
"called",
"type",
".",
"The",
"file",
"position",
"is",
"right",
"after",
"the",
"descriptor",
"after",
"this",
"returns",
"."
] | python | train |
pythongssapi/python-gssapi | gssapi/mechs.py | https://github.com/pythongssapi/python-gssapi/blob/b6efe72aa35a4c1fe21b397e15fcb41611e365ce/gssapi/mechs.py#L167-L200 | def from_attrs(cls, desired_attrs=None, except_attrs=None,
critical_attrs=None):
"""
Get a generator of mechanisms supporting the specified attributes. See
RFC 5587's :func:`indicate_mechs_by_attrs` for more information.
Args:
desired_attrs ([OID]): Desire... | [
"def",
"from_attrs",
"(",
"cls",
",",
"desired_attrs",
"=",
"None",
",",
"except_attrs",
"=",
"None",
",",
"critical_attrs",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"desired_attrs",
",",
"roids",
".",
"OID",
")",
":",
"desired_attrs",
"=",
"set",
... | Get a generator of mechanisms supporting the specified attributes. See
RFC 5587's :func:`indicate_mechs_by_attrs` for more information.
Args:
desired_attrs ([OID]): Desired attributes
except_attrs ([OID]): Except attributes
critical_attrs ([OID]): Critical attributes... | [
"Get",
"a",
"generator",
"of",
"mechanisms",
"supporting",
"the",
"specified",
"attributes",
".",
"See",
"RFC",
"5587",
"s",
":",
"func",
":",
"indicate_mechs_by_attrs",
"for",
"more",
"information",
"."
] | python | train |
cyrus-/cypy | cypy/cg.py | https://github.com/cyrus-/cypy/blob/04bb59e91fa314e8cf987743189c77a9b6bc371d/cypy/cg.py#L598-L619 | def trigger_staged_cg_hook(self, name, g, *args, **kwargs):
"""Calls a three-staged hook:
1. ``"pre_"+name``
2. ``"in_"+name``
3. ``"post_"+name``
"""
print_hooks = self._print_hooks
# TODO: document name lookup business
# TODO: refactor ... | [
"def",
"trigger_staged_cg_hook",
"(",
"self",
",",
"name",
",",
"g",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print_hooks",
"=",
"self",
".",
"_print_hooks",
"# TODO: document name lookup business",
"# TODO: refactor this context stuff, its confusing",
"h... | Calls a three-staged hook:
1. ``"pre_"+name``
2. ``"in_"+name``
3. ``"post_"+name`` | [
"Calls",
"a",
"three",
"-",
"staged",
"hook",
":",
"1",
".",
"pre_",
"+",
"name",
"2",
".",
"in_",
"+",
"name",
"3",
".",
"post_",
"+",
"name"
] | python | train |
gmr/flatdict | flatdict.py | https://github.com/gmr/flatdict/blob/40bfa64972b2dc148643116db786aa106e7d7d56/flatdict.py#L322-L338 | def set_delimiter(self, delimiter):
"""Override the default or passed in delimiter with a new value. If
the requested delimiter already exists in a key, a :exc:`ValueError`
will be raised.
:param str delimiter: The delimiter to use
:raises: ValueError
"""
for ke... | [
"def",
"set_delimiter",
"(",
"self",
",",
"delimiter",
")",
":",
"for",
"key",
"in",
"self",
".",
"keys",
"(",
")",
":",
"if",
"delimiter",
"in",
"key",
":",
"raise",
"ValueError",
"(",
"'Key {!r} collides with delimiter {!r}'",
",",
"key",
",",
"delimiter",... | Override the default or passed in delimiter with a new value. If
the requested delimiter already exists in a key, a :exc:`ValueError`
will be raised.
:param str delimiter: The delimiter to use
:raises: ValueError | [
"Override",
"the",
"default",
"or",
"passed",
"in",
"delimiter",
"with",
"a",
"new",
"value",
".",
"If",
"the",
"requested",
"delimiter",
"already",
"exists",
"in",
"a",
"key",
"a",
":",
"exc",
":",
"ValueError",
"will",
"be",
"raised",
"."
] | python | train |
inveniosoftware/invenio-oaiserver | invenio_oaiserver/response.py | https://github.com/inveniosoftware/invenio-oaiserver/blob/eae765e32bd816ddc5612d4b281caf205518b512/invenio_oaiserver/response.py#L296-L317 | def listrecords(**kwargs):
"""Create OAI-PMH response for verb ListRecords."""
record_dumper = serializer(kwargs['metadataPrefix'])
e_tree, e_listrecords = verb(**kwargs)
result = get_records(**kwargs)
for record in result.items:
pid = oaiid_fetcher(record['id'], record['json']['_source'])... | [
"def",
"listrecords",
"(",
"*",
"*",
"kwargs",
")",
":",
"record_dumper",
"=",
"serializer",
"(",
"kwargs",
"[",
"'metadataPrefix'",
"]",
")",
"e_tree",
",",
"e_listrecords",
"=",
"verb",
"(",
"*",
"*",
"kwargs",
")",
"result",
"=",
"get_records",
"(",
"... | Create OAI-PMH response for verb ListRecords. | [
"Create",
"OAI",
"-",
"PMH",
"response",
"for",
"verb",
"ListRecords",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/distlib/locators.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/locators.py#L1107-L1121 | def get_matcher(self, reqt):
"""
Get a version matcher for a requirement.
:param reqt: The requirement
:type reqt: str
:return: A version matcher (an instance of
:class:`distlib.version.Matcher`).
"""
try:
matcher = self.scheme.matcher... | [
"def",
"get_matcher",
"(",
"self",
",",
"reqt",
")",
":",
"try",
":",
"matcher",
"=",
"self",
".",
"scheme",
".",
"matcher",
"(",
"reqt",
")",
"except",
"UnsupportedVersionError",
":",
"# pragma: no cover",
"# XXX compat-mode if cannot read the version",
"name",
"... | Get a version matcher for a requirement.
:param reqt: The requirement
:type reqt: str
:return: A version matcher (an instance of
:class:`distlib.version.Matcher`). | [
"Get",
"a",
"version",
"matcher",
"for",
"a",
"requirement",
".",
":",
"param",
"reqt",
":",
"The",
"requirement",
":",
"type",
"reqt",
":",
"str",
":",
"return",
":",
"A",
"version",
"matcher",
"(",
"an",
"instance",
"of",
":",
"class",
":",
"distlib"... | python | train |
raamana/mrivis | mrivis/base.py | https://github.com/raamana/mrivis/blob/199ad096b8a1d825f69109e7218a81b2f1cec756/mrivis/base.py#L997-L1015 | def save(self, output_path=None, title=None):
"""Saves the current figure with carpet visualization to disk.
Parameters
----------
output_path : str
Path to where the figure needs to be saved to.
title : str
text to overlay and annotate the visualizatio... | [
"def",
"save",
"(",
"self",
",",
"output_path",
"=",
"None",
",",
"title",
"=",
"None",
")",
":",
"try",
":",
"save_figure",
"(",
"self",
".",
"fig",
",",
"output_path",
"=",
"output_path",
",",
"annot",
"=",
"title",
")",
"except",
":",
"print",
"("... | Saves the current figure with carpet visualization to disk.
Parameters
----------
output_path : str
Path to where the figure needs to be saved to.
title : str
text to overlay and annotate the visualization (done via plt.suptitle()) | [
"Saves",
"the",
"current",
"figure",
"with",
"carpet",
"visualization",
"to",
"disk",
"."
] | python | train |
ceph/ceph-deploy | ceph_deploy/util/system.py | https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/system.py#L167-L180 | def is_systemd_service_enabled(conn, service='ceph'):
"""
Detects if a systemd service is enabled or not.
"""
_, _, returncode = remoto.process.check(
conn,
[
'systemctl',
'is-enabled',
'--quiet',
'{service}'.format(service=service),
... | [
"def",
"is_systemd_service_enabled",
"(",
"conn",
",",
"service",
"=",
"'ceph'",
")",
":",
"_",
",",
"_",
",",
"returncode",
"=",
"remoto",
".",
"process",
".",
"check",
"(",
"conn",
",",
"[",
"'systemctl'",
",",
"'is-enabled'",
",",
"'--quiet'",
",",
"'... | Detects if a systemd service is enabled or not. | [
"Detects",
"if",
"a",
"systemd",
"service",
"is",
"enabled",
"or",
"not",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.