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 |
|---|---|---|---|---|---|---|---|---|
bitesofcode/projexui | projexui/widgets/xorbgridedit/xorbgridedit.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbgridedit/xorbgridedit.py#L186-L194 | def refresh(self):
"""
Commits changes stored in the interface to the database.
"""
table = self.tableType()
if table:
table.markTableCacheExpired()
self.uiRecordTREE.searchRecords(self.uiSearchTXT.text()) | [
"def",
"refresh",
"(",
"self",
")",
":",
"table",
"=",
"self",
".",
"tableType",
"(",
")",
"if",
"table",
":",
"table",
".",
"markTableCacheExpired",
"(",
")",
"self",
".",
"uiRecordTREE",
".",
"searchRecords",
"(",
"self",
".",
"uiSearchTXT",
".",
"text... | Commits changes stored in the interface to the database. | [
"Commits",
"changes",
"stored",
"in",
"the",
"interface",
"to",
"the",
"database",
"."
] | python | train |
mitsei/dlkit | dlkit/aws_adapter/repository/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/aws_adapter/repository/sessions.py#L1272-L1291 | def delete_asset_content(self, asset_content_id=None):
"""Deletes content from an ``Asset``.
arg: asset_content_id (osid.id.Id): the ``Id`` of the
``AssetContent``
raise: NotFound - ``asset_content_id`` is not found
raise: NullArgument - ``asset_content_id`` is ``nu... | [
"def",
"delete_asset_content",
"(",
"self",
",",
"asset_content_id",
"=",
"None",
")",
":",
"asset_content",
"=",
"self",
".",
"_get_asset_content",
"(",
"asset_content_id",
")",
"if",
"asset_content",
".",
"has_url",
"(",
")",
"and",
"'amazonaws.com'",
"in",
"a... | Deletes content from an ``Asset``.
arg: asset_content_id (osid.id.Id): the ``Id`` of the
``AssetContent``
raise: NotFound - ``asset_content_id`` is not found
raise: NullArgument - ``asset_content_id`` is ``null``
raise: OperationFailed - unable to complete request
... | [
"Deletes",
"content",
"from",
"an",
"Asset",
"."
] | python | train |
portfors-lab/sparkle | sparkle/gui/dialogs/specgram_dlg.py | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/dialogs/specgram_dlg.py#L23-L34 | def values(self):
"""Gets the parameter values
:returns: dict of inputs:
| *'nfft'*: int -- length, in samples, of FFT chunks
| *'window'*: str -- name of window to apply to FFT chunks
| *'overlap'*: float -- percent overlap of windows
"""
s... | [
"def",
"values",
"(",
"self",
")",
":",
"self",
".",
"vals",
"[",
"'nfft'",
"]",
"=",
"self",
".",
"ui",
".",
"nfftSpnbx",
".",
"value",
"(",
")",
"self",
".",
"vals",
"[",
"'window'",
"]",
"=",
"str",
"(",
"self",
".",
"ui",
".",
"windowCmbx",
... | Gets the parameter values
:returns: dict of inputs:
| *'nfft'*: int -- length, in samples, of FFT chunks
| *'window'*: str -- name of window to apply to FFT chunks
| *'overlap'*: float -- percent overlap of windows | [
"Gets",
"the",
"parameter",
"values"
] | python | train |
multiformats/py-multicodec | multicodec/multicodec.py | https://github.com/multiformats/py-multicodec/blob/23213b8b40b21e17e2e1844224498cbd8e359bfa/multicodec/multicodec.py#L50-L60 | def remove_prefix(bytes_):
"""
Removes prefix from a prefixed data
:param bytes bytes_: multicodec prefixed data bytes
:return: prefix removed data bytes
:rtype: bytes
"""
prefix_int = extract_prefix(bytes_)
prefix = varint.encode(prefix_int)
return bytes_[len(prefix):] | [
"def",
"remove_prefix",
"(",
"bytes_",
")",
":",
"prefix_int",
"=",
"extract_prefix",
"(",
"bytes_",
")",
"prefix",
"=",
"varint",
".",
"encode",
"(",
"prefix_int",
")",
"return",
"bytes_",
"[",
"len",
"(",
"prefix",
")",
":",
"]"
] | Removes prefix from a prefixed data
:param bytes bytes_: multicodec prefixed data bytes
:return: prefix removed data bytes
:rtype: bytes | [
"Removes",
"prefix",
"from",
"a",
"prefixed",
"data"
] | python | valid |
CZ-NIC/yangson | yangson/datamodel.py | https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datamodel.py#L100-L110 | def from_raw(self, robj: RawObject) -> RootNode:
"""Create an instance node from a raw data tree.
Args:
robj: Dictionary representing a raw data tree.
Returns:
Root instance node.
"""
cooked = self.schema.from_raw(robj)
return RootNode(cooked, se... | [
"def",
"from_raw",
"(",
"self",
",",
"robj",
":",
"RawObject",
")",
"->",
"RootNode",
":",
"cooked",
"=",
"self",
".",
"schema",
".",
"from_raw",
"(",
"robj",
")",
"return",
"RootNode",
"(",
"cooked",
",",
"self",
".",
"schema",
",",
"cooked",
".",
"... | Create an instance node from a raw data tree.
Args:
robj: Dictionary representing a raw data tree.
Returns:
Root instance node. | [
"Create",
"an",
"instance",
"node",
"from",
"a",
"raw",
"data",
"tree",
"."
] | python | train |
speechinformaticslab/vfclust | vfclust/vfclust.py | https://github.com/speechinformaticslab/vfclust/blob/7ca733dea4782c828024765726cce65de095d33c/vfclust/vfclust.py#L213-L229 | def lemmatize(self):
"""Lemmatize all Units in self.unit_list.
Modifies:
- self.unit_list: converts the .text property into its lemmatized form.
This method lemmatizes all inflected variants of permissible words to
those words' respective canonical forms. This is done to en... | [
"def",
"lemmatize",
"(",
"self",
")",
":",
"for",
"unit",
"in",
"self",
".",
"unit_list",
":",
"if",
"lemmatizer",
".",
"lemmatize",
"(",
"unit",
".",
"text",
")",
"in",
"self",
".",
"lemmas",
":",
"unit",
".",
"text",
"=",
"lemmatizer",
".",
"lemmat... | Lemmatize all Units in self.unit_list.
Modifies:
- self.unit_list: converts the .text property into its lemmatized form.
This method lemmatizes all inflected variants of permissible words to
those words' respective canonical forms. This is done to ensure that
each instance ... | [
"Lemmatize",
"all",
"Units",
"in",
"self",
".",
"unit_list",
"."
] | python | train |
has2k1/mizani | mizani/utils.py | https://github.com/has2k1/mizani/blob/312d0550ee0136fd1b0384829b33f3b2065f47c8/mizani/utils.py#L257-L277 | def same_log10_order_of_magnitude(x, delta=0.1):
"""
Return true if range is approximately in same order of magnitude
For example these sequences are in the same order of magnitude:
- [1, 8, 5] # [1, 10)
- [35, 20, 80] # [10 100)
- [232, 730] # [100, 1000)
Parameters
... | [
"def",
"same_log10_order_of_magnitude",
"(",
"x",
",",
"delta",
"=",
"0.1",
")",
":",
"dmin",
"=",
"np",
".",
"log10",
"(",
"np",
".",
"min",
"(",
"x",
")",
"*",
"(",
"1",
"-",
"delta",
")",
")",
"dmax",
"=",
"np",
".",
"log10",
"(",
"np",
".",... | Return true if range is approximately in same order of magnitude
For example these sequences are in the same order of magnitude:
- [1, 8, 5] # [1, 10)
- [35, 20, 80] # [10 100)
- [232, 730] # [100, 1000)
Parameters
----------
x : array-like
Values in base 10. ... | [
"Return",
"true",
"if",
"range",
"is",
"approximately",
"in",
"same",
"order",
"of",
"magnitude"
] | python | valid |
Tanganelli/CoAPthon3 | coapthon/reverse_proxy/coap.py | https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/reverse_proxy/coap.py#L165-L180 | def discover_remote_results(self, response, name):
"""
Create a new remote server resource for each valid discover response.
:param response: the response to the discovery request
:param name: the server name
"""
host, port = response.source
if response.code == ... | [
"def",
"discover_remote_results",
"(",
"self",
",",
"response",
",",
"name",
")",
":",
"host",
",",
"port",
"=",
"response",
".",
"source",
"if",
"response",
".",
"code",
"==",
"defines",
".",
"Codes",
".",
"CONTENT",
".",
"number",
":",
"resource",
"=",... | Create a new remote server resource for each valid discover response.
:param response: the response to the discovery request
:param name: the server name | [
"Create",
"a",
"new",
"remote",
"server",
"resource",
"for",
"each",
"valid",
"discover",
"response",
"."
] | python | train |
barryp/py-amqplib | extras/generate_skeleton_0_8.py | https://github.com/barryp/py-amqplib/blob/2b3a47de34b4712c111d0a55d7ff109dffc2a7b2/extras/generate_skeleton_0_8.py#L83-L104 | def _reindent(s, indent, reformat=True):
"""
Remove the existing indentation from each line of a chunk of
text, s, and then prefix each line with a new indent string.
Also removes trailing whitespace from each line, and leading and
trailing blank lines.
"""
s = textwrap.dedent(s)
s = s... | [
"def",
"_reindent",
"(",
"s",
",",
"indent",
",",
"reformat",
"=",
"True",
")",
":",
"s",
"=",
"textwrap",
".",
"dedent",
"(",
"s",
")",
"s",
"=",
"s",
".",
"split",
"(",
"'\\n'",
")",
"s",
"=",
"[",
"x",
".",
"rstrip",
"(",
")",
"for",
"x",
... | Remove the existing indentation from each line of a chunk of
text, s, and then prefix each line with a new indent string.
Also removes trailing whitespace from each line, and leading and
trailing blank lines. | [
"Remove",
"the",
"existing",
"indentation",
"from",
"each",
"line",
"of",
"a",
"chunk",
"of",
"text",
"s",
"and",
"then",
"prefix",
"each",
"line",
"with",
"a",
"new",
"indent",
"string",
"."
] | python | train |
heuer/cablemap | cablemap.core/cablemap/core/c14n.py | https://github.com/heuer/cablemap/blob/42066c8fc2972d237a2c35578e14525aaf705f38/cablemap.core/cablemap/core/c14n.py#L174-L181 | def canonicalize_origin(origin):
"""\
"""
origin = origin.replace(u'USMISSION', u'') \
.replace(u'AMEMBASSY', u'') \
.replace(u'EMBASSY', u'').strip()
return _STATION_C14N.get(origin, origin) | [
"def",
"canonicalize_origin",
"(",
"origin",
")",
":",
"origin",
"=",
"origin",
".",
"replace",
"(",
"u'USMISSION'",
",",
"u''",
")",
".",
"replace",
"(",
"u'AMEMBASSY'",
",",
"u''",
")",
".",
"replace",
"(",
"u'EMBASSY'",
",",
"u''",
")",
".",
"strip",
... | \ | [
"\\"
] | python | train |
tropo/tropo-webapi-python | build/lib/tropo.py | https://github.com/tropo/tropo-webapi-python/blob/f87772644a6b45066a4c5218f0c1f6467b64ab3c/build/lib/tropo.py#L756-L768 | def message (self, say_obj, to, **options):
"""
A shortcut method to create a session, say something, and hang up, all in one step. This is particularly useful for sending out a quick SMS or IM.
Argument: "say_obj" is a Say object
Argument: "to" is a String
Argument: **options is... | [
"def",
"message",
"(",
"self",
",",
"say_obj",
",",
"to",
",",
"*",
"*",
"options",
")",
":",
"if",
"isinstance",
"(",
"say_obj",
",",
"basestring",
")",
":",
"say",
"=",
"Say",
"(",
"say_obj",
")",
".",
"obj",
"else",
":",
"say",
"=",
"say_obj",
... | A shortcut method to create a session, say something, and hang up, all in one step. This is particularly useful for sending out a quick SMS or IM.
Argument: "say_obj" is a Say object
Argument: "to" is a String
Argument: **options is a set of optional keyword arguments.
See https://www.tr... | [
"A",
"shortcut",
"method",
"to",
"create",
"a",
"session",
"say",
"something",
"and",
"hang",
"up",
"all",
"in",
"one",
"step",
".",
"This",
"is",
"particularly",
"useful",
"for",
"sending",
"out",
"a",
"quick",
"SMS",
"or",
"IM",
".",
"Argument",
":",
... | python | train |
senaite/senaite.core | bika/lims/browser/attachment.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/attachment.py#L451-L458 | def is_analysis_attachment_allowed(self, analysis):
"""Checks if the analysis
"""
if analysis.getAttachmentOption() not in ["p", "r"]:
return False
if api.get_workflow_status_of(analysis) in ["retracted"]:
return False
return True | [
"def",
"is_analysis_attachment_allowed",
"(",
"self",
",",
"analysis",
")",
":",
"if",
"analysis",
".",
"getAttachmentOption",
"(",
")",
"not",
"in",
"[",
"\"p\"",
",",
"\"r\"",
"]",
":",
"return",
"False",
"if",
"api",
".",
"get_workflow_status_of",
"(",
"a... | Checks if the analysis | [
"Checks",
"if",
"the",
"analysis"
] | python | train |
hamperbot/hamper | hamper/plugins/karma_adv.py | https://github.com/hamperbot/hamper/blob/6f841ec4dcc319fdd7bb3ca1f990e3b7a458771b/hamper/plugins/karma_adv.py#L101-L131 | def modify_karma(self, words):
"""
Given a regex object, look through the groups and modify karma
as necessary
"""
# 'user': karma
k = defaultdict(int)
if words:
# For loop through all of the group members
for word_tuple in words:
... | [
"def",
"modify_karma",
"(",
"self",
",",
"words",
")",
":",
"# 'user': karma",
"k",
"=",
"defaultdict",
"(",
"int",
")",
"if",
"words",
":",
"# For loop through all of the group members",
"for",
"word_tuple",
"in",
"words",
":",
"word",
"=",
"word_tuple",
"[",
... | Given a regex object, look through the groups and modify karma
as necessary | [
"Given",
"a",
"regex",
"object",
"look",
"through",
"the",
"groups",
"and",
"modify",
"karma",
"as",
"necessary"
] | python | train |
jjangsangy/py-translate | translate/languages.py | https://github.com/jjangsangy/py-translate/blob/fe6279b2ee353f42ce73333ffae104e646311956/translate/languages.py#L12-L32 | def translation_table(language, filepath='supported_translations.json'):
'''
Opens up file located under the etc directory containing language
codes and prints them out.
:param file: Path to location of json file
:type file: str
:return: language codes
:rtype: dict
'''
fullpath = a... | [
"def",
"translation_table",
"(",
"language",
",",
"filepath",
"=",
"'supported_translations.json'",
")",
":",
"fullpath",
"=",
"abspath",
"(",
"join",
"(",
"dirname",
"(",
"__file__",
")",
",",
"'etc'",
",",
"filepath",
")",
")",
"if",
"not",
"isfile",
"(",
... | Opens up file located under the etc directory containing language
codes and prints them out.
:param file: Path to location of json file
:type file: str
:return: language codes
:rtype: dict | [
"Opens",
"up",
"file",
"located",
"under",
"the",
"etc",
"directory",
"containing",
"language",
"codes",
"and",
"prints",
"them",
"out",
"."
] | python | test |
mseclab/PyJFuzz | pyjfuzz/core/pjf_decoretors.py | https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_decoretors.py#L34-L41 | def mutate_object_decorate(self, func):
"""
Mutate a generic object based on type
"""
def mutate():
obj = func()
return self.Mutators.get_mutator(obj, type(obj))
return mutate | [
"def",
"mutate_object_decorate",
"(",
"self",
",",
"func",
")",
":",
"def",
"mutate",
"(",
")",
":",
"obj",
"=",
"func",
"(",
")",
"return",
"self",
".",
"Mutators",
".",
"get_mutator",
"(",
"obj",
",",
"type",
"(",
"obj",
")",
")",
"return",
"mutate... | Mutate a generic object based on type | [
"Mutate",
"a",
"generic",
"object",
"based",
"on",
"type"
] | python | test |
indico/indico-plugins | livesync/indico_livesync/models/queue.py | https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/livesync/indico_livesync/models/queue.py#L213-L224 | def object(self):
"""Return the changed object."""
if self.type == EntryType.category:
return self.category
elif self.type == EntryType.event:
return self.event
elif self.type == EntryType.session:
return self.session
elif self.type == EntryTyp... | [
"def",
"object",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"==",
"EntryType",
".",
"category",
":",
"return",
"self",
".",
"category",
"elif",
"self",
".",
"type",
"==",
"EntryType",
".",
"event",
":",
"return",
"self",
".",
"event",
"elif",
... | Return the changed object. | [
"Return",
"the",
"changed",
"object",
"."
] | python | train |
gwastro/pycbc | pycbc/tmpltbank/partitioned_bank.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/partitioned_bank.py#L432-L495 | def add_point_by_chi_coords(self, chi_coords, mass1, mass2, spin1z, spin2z,
point_fupper=None, mus=None):
"""
Add a point to the partitioned template bank. The point_fupper and mus
kwargs must be provided for all templates if the vary fupper capability
is desire... | [
"def",
"add_point_by_chi_coords",
"(",
"self",
",",
"chi_coords",
",",
"mass1",
",",
"mass2",
",",
"spin1z",
",",
"spin2z",
",",
"point_fupper",
"=",
"None",
",",
"mus",
"=",
"None",
")",
":",
"chi1_bin",
",",
"chi2_bin",
"=",
"self",
".",
"find_point_bin"... | Add a point to the partitioned template bank. The point_fupper and mus
kwargs must be provided for all templates if the vary fupper capability
is desired. This requires that the chi_coords, as well as mus and
point_fupper if needed, to be precalculated. If you just have the
masses and do... | [
"Add",
"a",
"point",
"to",
"the",
"partitioned",
"template",
"bank",
".",
"The",
"point_fupper",
"and",
"mus",
"kwargs",
"must",
"be",
"provided",
"for",
"all",
"templates",
"if",
"the",
"vary",
"fupper",
"capability",
"is",
"desired",
".",
"This",
"requires... | python | train |
gwastro/pycbc | pycbc/distributions/arbitrary.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/distributions/arbitrary.py#L250-L286 | def get_arrays_from_file(params_file, params=None):
"""Reads the values of one or more parameters from an hdf file and
returns as a dictionary.
Parameters
----------
params_file : str
The hdf file that contains the values of the parameters.
params : {None, li... | [
"def",
"get_arrays_from_file",
"(",
"params_file",
",",
"params",
"=",
"None",
")",
":",
"try",
":",
"f",
"=",
"h5py",
".",
"File",
"(",
"params_file",
",",
"'r'",
")",
"except",
":",
"raise",
"ValueError",
"(",
"'File not found.'",
")",
"if",
"params",
... | Reads the values of one or more parameters from an hdf file and
returns as a dictionary.
Parameters
----------
params_file : str
The hdf file that contains the values of the parameters.
params : {None, list}
If provided, will just retrieve the given param... | [
"Reads",
"the",
"values",
"of",
"one",
"or",
"more",
"parameters",
"from",
"an",
"hdf",
"file",
"and",
"returns",
"as",
"a",
"dictionary",
"."
] | python | train |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/gloo/framebuffer.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/framebuffer.py#L123-L131 | def activate(self):
""" Activate/use this frame buffer.
"""
# Send command
self._glir.command('FRAMEBUFFER', self._id, True)
# Associate canvas now
canvas = get_current_canvas()
if canvas is not None:
canvas.context.glir.associate(self.glir) | [
"def",
"activate",
"(",
"self",
")",
":",
"# Send command",
"self",
".",
"_glir",
".",
"command",
"(",
"'FRAMEBUFFER'",
",",
"self",
".",
"_id",
",",
"True",
")",
"# Associate canvas now",
"canvas",
"=",
"get_current_canvas",
"(",
")",
"if",
"canvas",
"is",
... | Activate/use this frame buffer. | [
"Activate",
"/",
"use",
"this",
"frame",
"buffer",
"."
] | python | train |
3DLIRIOUS/MeshLabXML | meshlabxml/select.py | https://github.com/3DLIRIOUS/MeshLabXML/blob/177cce21e92baca500f56a932d66bd9a33257af8/meshlabxml/select.py#L6-L36 | def all(script, face=True, vert=True):
""" Select all the faces of the current mesh
Args:
script: the FilterScript object or script filename to write
the filter to.
faces (bool): If True the filter will select all the faces.
verts (bool): If True the filter will select all t... | [
"def",
"all",
"(",
"script",
",",
"face",
"=",
"True",
",",
"vert",
"=",
"True",
")",
":",
"filter_xml",
"=",
"''",
".",
"join",
"(",
"[",
"' <filter name=\"Select All\">\\n'",
",",
"' <Param name=\"allFaces\" '",
",",
"'value=\"{}\" '",
".",
"format",
"("... | Select all the faces of the current mesh
Args:
script: the FilterScript object or script filename to write
the filter to.
faces (bool): If True the filter will select all the faces.
verts (bool): If True the filter will select all the vertices.
Layer stack:
No impac... | [
"Select",
"all",
"the",
"faces",
"of",
"the",
"current",
"mesh"
] | python | test |
googleads/googleads-python-lib | googleads/adwords.py | https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/googleads/adwords.py#L2050-L2060 | def ContainsAll(self, *values):
"""Sets the type of the WHERE clause as "contains all".
Args:
*values: The values to be used in the WHERE condition.
Returns:
The query builder that this WHERE builder links to.
"""
self._awql = self._CreateMultipleValuesCondition(values, 'CONTAINS_ALL')... | [
"def",
"ContainsAll",
"(",
"self",
",",
"*",
"values",
")",
":",
"self",
".",
"_awql",
"=",
"self",
".",
"_CreateMultipleValuesCondition",
"(",
"values",
",",
"'CONTAINS_ALL'",
")",
"return",
"self",
".",
"_query_builder"
] | Sets the type of the WHERE clause as "contains all".
Args:
*values: The values to be used in the WHERE condition.
Returns:
The query builder that this WHERE builder links to. | [
"Sets",
"the",
"type",
"of",
"the",
"WHERE",
"clause",
"as",
"contains",
"all",
"."
] | python | train |
inveniosoftware-contrib/invenio-workflows | invenio_workflows/api.py | https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/api.py#L98-L136 | def save(self, status=None, callback_pos=None, id_workflow=None):
"""Save object to persistent storage."""
if self.model is None:
raise WorkflowsMissingModel()
with db.session.begin_nested():
workflow_object_before_save.send(self)
self.model.modified = datet... | [
"def",
"save",
"(",
"self",
",",
"status",
"=",
"None",
",",
"callback_pos",
"=",
"None",
",",
"id_workflow",
"=",
"None",
")",
":",
"if",
"self",
".",
"model",
"is",
"None",
":",
"raise",
"WorkflowsMissingModel",
"(",
")",
"with",
"db",
".",
"session"... | Save object to persistent storage. | [
"Save",
"object",
"to",
"persistent",
"storage",
"."
] | python | train |
saltstack/salt | salt/runners/smartos_vmadm.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/smartos_vmadm.py#L190-L247 | def list_vms(search=None, verbose=False):
'''
List all vms
search : string
filter vms, see the execution module
verbose : boolean
print additional information about the vm
CLI Example:
.. code-block:: bash
salt-run vmadm.list
salt-run vmadm.list search='type=K... | [
"def",
"list_vms",
"(",
"search",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"ret",
"=",
"OrderedDict",
"(",
")",
"if",
"verbose",
"else",
"[",
"]",
"client",
"=",
"salt",
".",
"client",
".",
"get_local_client",
"(",
"__opts__",
"[",
"'conf_f... | List all vms
search : string
filter vms, see the execution module
verbose : boolean
print additional information about the vm
CLI Example:
.. code-block:: bash
salt-run vmadm.list
salt-run vmadm.list search='type=KVM'
salt-run vmadm.list verbose=True | [
"List",
"all",
"vms"
] | python | train |
singularityhub/sregistry-cli | sregistry/main/google_drive/query.py | https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/main/google_drive/query.py#L30-L63 | def list_containers(self):
'''return a list of containers. Since Google Drive definitely has other
kinds of files, we look for containers in a special sregistry folder,
(meaning the parent folder is sregistry) and with properties of type
as container.
'''
# Get or create the base
fo... | [
"def",
"list_containers",
"(",
"self",
")",
":",
"# Get or create the base",
"folder",
"=",
"self",
".",
"_get_or_create_folder",
"(",
"self",
".",
"_base",
")",
"next_page",
"=",
"None",
"containers",
"=",
"[",
"]",
"# Parse the base for all containers, possibly over... | return a list of containers. Since Google Drive definitely has other
kinds of files, we look for containers in a special sregistry folder,
(meaning the parent folder is sregistry) and with properties of type
as container. | [
"return",
"a",
"list",
"of",
"containers",
".",
"Since",
"Google",
"Drive",
"definitely",
"has",
"other",
"kinds",
"of",
"files",
"we",
"look",
"for",
"containers",
"in",
"a",
"special",
"sregistry",
"folder",
"(",
"meaning",
"the",
"parent",
"folder",
"is",... | python | test |
rigetti/grove | grove/alpha/jordan_gradient/jordan_gradient.py | https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/jordan_gradient/jordan_gradient.py#L10-L25 | def gradient_program(f_h: float, precision: int) -> Program:
"""
Gradient estimation via Jordan's algorithm (10.1103/PhysRevLett.95.050501).
:param f_h: Oracle output at perturbation h.
:param precision: Bit precision of gradient.
:return: Quil program to estimate gradient of f.
"""
# enco... | [
"def",
"gradient_program",
"(",
"f_h",
":",
"float",
",",
"precision",
":",
"int",
")",
"->",
"Program",
":",
"# encode oracle values into phase",
"phase_factor",
"=",
"np",
".",
"exp",
"(",
"1.0j",
"*",
"2",
"*",
"np",
".",
"pi",
"*",
"abs",
"(",
"f_h",... | Gradient estimation via Jordan's algorithm (10.1103/PhysRevLett.95.050501).
:param f_h: Oracle output at perturbation h.
:param precision: Bit precision of gradient.
:return: Quil program to estimate gradient of f. | [
"Gradient",
"estimation",
"via",
"Jordan",
"s",
"algorithm",
"(",
"10",
".",
"1103",
"/",
"PhysRevLett",
".",
"95",
".",
"050501",
")",
"."
] | python | train |
jtpaasch/simplygithub | simplygithub/branches.py | https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/branches.py#L72-L95 | def create_branch(profile, name, branch_off):
"""Create a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
... | [
"def",
"create_branch",
"(",
"profile",
",",
"name",
",",
"branch_off",
")",
":",
"branch_off_sha",
"=",
"get_branch_sha",
"(",
"profile",
",",
"branch_off",
")",
"ref",
"=",
"\"heads/\"",
"+",
"name",
"data",
"=",
"refs",
".",
"create_ref",
"(",
"profile",
... | Create a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the new branch.
branch_... | [
"Create",
"a",
"branch",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/pipreqs/pipreqs.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipreqs/pipreqs.py#L307-L330 | def clean(file_, imports):
"""Remove modules that aren't imported in project from file."""
modules_not_imported = compare_modules(file_, imports)
re_remove = re.compile("|".join(modules_not_imported))
to_write = []
try:
f = open_func(file_, "r+")
except OSError:
logging.error("F... | [
"def",
"clean",
"(",
"file_",
",",
"imports",
")",
":",
"modules_not_imported",
"=",
"compare_modules",
"(",
"file_",
",",
"imports",
")",
"re_remove",
"=",
"re",
".",
"compile",
"(",
"\"|\"",
".",
"join",
"(",
"modules_not_imported",
")",
")",
"to_write",
... | Remove modules that aren't imported in project from file. | [
"Remove",
"modules",
"that",
"aren",
"t",
"imported",
"in",
"project",
"from",
"file",
"."
] | python | train |
saltstack/salt | salt/utils/gitfs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/gitfs.py#L2312-L2325 | def clear_cache(self):
'''
Completely clear cache
'''
errors = []
for rdir in (self.cache_root, self.file_list_cachedir):
if os.path.exists(rdir):
try:
shutil.rmtree(rdir)
except OSError as exc:
e... | [
"def",
"clear_cache",
"(",
"self",
")",
":",
"errors",
"=",
"[",
"]",
"for",
"rdir",
"in",
"(",
"self",
".",
"cache_root",
",",
"self",
".",
"file_list_cachedir",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"rdir",
")",
":",
"try",
":",
... | Completely clear cache | [
"Completely",
"clear",
"cache"
] | python | train |
facebook/pyre-check | sapp/sapp/analysis_output.py | https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/analysis_output.py#L121-L127 | def file_names(self) -> Iterable[str]:
"""Generates all file names that are used to generate file_handles.
"""
if self.is_sharded():
yield from ShardedFile(self.filename_spec).get_filenames()
elif self.filename_spec:
yield self.filename_spec | [
"def",
"file_names",
"(",
"self",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"if",
"self",
".",
"is_sharded",
"(",
")",
":",
"yield",
"from",
"ShardedFile",
"(",
"self",
".",
"filename_spec",
")",
".",
"get_filenames",
"(",
")",
"elif",
"self",
".",
... | Generates all file names that are used to generate file_handles. | [
"Generates",
"all",
"file",
"names",
"that",
"are",
"used",
"to",
"generate",
"file_handles",
"."
] | python | train |
macbre/data-flow-graph | sources/elasticsearch/logs2dataflow.py | https://github.com/macbre/data-flow-graph/blob/16164c3860f3defe3354c19b8536ed01b3bfdb61/sources/elasticsearch/logs2dataflow.py#L45-L52 | def format_timestamp(ts):
"""
Format the UTC timestamp for Elasticsearch
eg. 2014-07-09T08:37:18.000Z
@see https://docs.python.org/2/library/time.html#time.strftime
"""
tz_info = tz.tzutc()
return datetime.fromtimestamp(ts, tz=tz_info).strftime("%Y-%m-%dT%H:%M:%S.... | [
"def",
"format_timestamp",
"(",
"ts",
")",
":",
"tz_info",
"=",
"tz",
".",
"tzutc",
"(",
")",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"ts",
",",
"tz",
"=",
"tz_info",
")",
".",
"strftime",
"(",
"\"%Y-%m-%dT%H:%M:%S.000Z\"",
")"
] | Format the UTC timestamp for Elasticsearch
eg. 2014-07-09T08:37:18.000Z
@see https://docs.python.org/2/library/time.html#time.strftime | [
"Format",
"the",
"UTC",
"timestamp",
"for",
"Elasticsearch",
"eg",
".",
"2014",
"-",
"07",
"-",
"09T08",
":",
"37",
":",
"18",
".",
"000Z"
] | python | train |
gitpython-developers/GitPython | git/objects/tree.py | https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/objects/tree.py#L214-L244 | def join(self, file):
"""Find the named object in this tree's contents
:return: ``git.Blob`` or ``git.Tree`` or ``git.Submodule``
:raise KeyError: if given file or tree does not exist in tree"""
msg = "Blob or Tree named %r not found"
if '/' in file:
tree = self
... | [
"def",
"join",
"(",
"self",
",",
"file",
")",
":",
"msg",
"=",
"\"Blob or Tree named %r not found\"",
"if",
"'/'",
"in",
"file",
":",
"tree",
"=",
"self",
"item",
"=",
"self",
"tokens",
"=",
"file",
".",
"split",
"(",
"'/'",
")",
"for",
"i",
",",
"to... | Find the named object in this tree's contents
:return: ``git.Blob`` or ``git.Tree`` or ``git.Submodule``
:raise KeyError: if given file or tree does not exist in tree | [
"Find",
"the",
"named",
"object",
"in",
"this",
"tree",
"s",
"contents",
":",
"return",
":",
"git",
".",
"Blob",
"or",
"git",
".",
"Tree",
"or",
"git",
".",
"Submodule"
] | python | train |
pingali/dgit | dgitcore/helper.py | https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/helper.py#L232-L244 | def log_repo_action(func):
"""
Log all repo actions to .dgit/log.json
"""
def _inner(*args, **kwargs):
result = func(*args, **kwargs)
log_action(func, result, *args, **kwargs)
return result
_inner.__name__ = func.__name__
_inner.__doc__ = fun... | [
"def",
"log_repo_action",
"(",
"func",
")",
":",
"def",
"_inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"log_action",
"(",
"func",
",",
"result",
",",
"*",
"arg... | Log all repo actions to .dgit/log.json | [
"Log",
"all",
"repo",
"actions",
"to",
".",
"dgit",
"/",
"log",
".",
"json"
] | python | valid |
rfosterslo/wagtailplus | wagtailplus/wagtaillinks/views/links.py | https://github.com/rfosterslo/wagtailplus/blob/22cac857175d8a6f77e470751831c14a92ccd768/wagtailplus/wagtaillinks/views/links.py#L57-L78 | def post(self, request, *args, **kwargs):
"""
Returns POST response.
:param request: the request instance.
:rtype: django.http.HttpResponse.
"""
form = None
link_type = int(request.POST.get('link_type', 0))
if link_type == Link.LINK_TYPE_EMAIL:
... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"form",
"=",
"None",
"link_type",
"=",
"int",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'link_type'",
",",
"0",
")",
")",
"if",
"link_type",
"==... | Returns POST response.
:param request: the request instance.
:rtype: django.http.HttpResponse. | [
"Returns",
"POST",
"response",
"."
] | python | train |
vertexproject/synapse | synapse/common.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/common.py#L255-L270 | def listdir(*paths, glob=None):
'''
List the (optionally glob filtered) full paths from a dir.
Args:
*paths ([str,...]): A list of path elements
glob (str): An optional fnmatch glob str
'''
path = genpath(*paths)
names = os.listdir(path)
if glob is not None:
names =... | [
"def",
"listdir",
"(",
"*",
"paths",
",",
"glob",
"=",
"None",
")",
":",
"path",
"=",
"genpath",
"(",
"*",
"paths",
")",
"names",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"if",
"glob",
"is",
"not",
"None",
":",
"names",
"=",
"fnmatch",
".",
... | List the (optionally glob filtered) full paths from a dir.
Args:
*paths ([str,...]): A list of path elements
glob (str): An optional fnmatch glob str | [
"List",
"the",
"(",
"optionally",
"glob",
"filtered",
")",
"full",
"paths",
"from",
"a",
"dir",
"."
] | python | train |
airspeed-velocity/asv | asv/feed.py | https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/feed.py#L201-L217 | def _get_id(owner, date, content):
"""
Generate an unique Atom id for the given content
"""
h = hashlib.sha256()
# Hash still contains the original project url, keep as is
h.update("github.com/spacetelescope/asv".encode('utf-8'))
for x in content:
if x is None:
h.update("... | [
"def",
"_get_id",
"(",
"owner",
",",
"date",
",",
"content",
")",
":",
"h",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"# Hash still contains the original project url, keep as is",
"h",
".",
"update",
"(",
"\"github.com/spacetelescope/asv\"",
".",
"encode",
"(",
"'u... | Generate an unique Atom id for the given content | [
"Generate",
"an",
"unique",
"Atom",
"id",
"for",
"the",
"given",
"content"
] | python | train |
PrefPy/prefpy | prefpy/mov.py | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mov.py#L306-L346 | def AppMoVMaximin(profile):
"""
Returns an integer that is equal to the margin of victory of the election profile, that is,
the smallest number k such that changing k votes can change the winners.
:ivar Profile profile: A Profile object that represents an election profile.
"""
# Currently, we ... | [
"def",
"AppMoVMaximin",
"(",
"profile",
")",
":",
"# Currently, we expect the profile to contain complete ordering over candidates.",
"elecType",
"=",
"profile",
".",
"getElecType",
"(",
")",
"if",
"elecType",
"!=",
"\"soc\"",
"and",
"elecType",
"!=",
"\"toc\"",
":",
"p... | Returns an integer that is equal to the margin of victory of the election profile, that is,
the smallest number k such that changing k votes can change the winners.
:ivar Profile profile: A Profile object that represents an election profile. | [
"Returns",
"an",
"integer",
"that",
"is",
"equal",
"to",
"the",
"margin",
"of",
"victory",
"of",
"the",
"election",
"profile",
"that",
"is",
"the",
"smallest",
"number",
"k",
"such",
"that",
"changing",
"k",
"votes",
"can",
"change",
"the",
"winners",
"."
... | python | train |
rueckstiess/mtools | mtools/util/logevent.py | https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/util/logevent.py#L542-L552 | def nreturned(self):
"""
Extract counters if available (lazy).
Looks for nreturned, nReturned, or nMatched counter.
"""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._nreturned | [
"def",
"nreturned",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_counters_calculated",
":",
"self",
".",
"_counters_calculated",
"=",
"True",
"self",
".",
"_extract_counters",
"(",
")",
"return",
"self",
".",
"_nreturned"
] | Extract counters if available (lazy).
Looks for nreturned, nReturned, or nMatched counter. | [
"Extract",
"counters",
"if",
"available",
"(",
"lazy",
")",
"."
] | python | train |
openstack/proliantutils | proliantutils/ilo/ris.py | https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/ris.py#L1154-L1196 | def reset_bios_to_default(self):
"""Resets the BIOS settings to default values.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
# Check if the BIOS resource if exists.
head... | [
"def",
"reset_bios_to_default",
"(",
"self",
")",
":",
"# Check if the BIOS resource if exists.",
"headers_bios",
",",
"bios_uri",
",",
"bios_settings",
"=",
"self",
".",
"_check_bios_resource",
"(",
")",
"# Get the BaseConfig resource.",
"try",
":",
"base_config_uri",
"=... | Resets the BIOS settings to default values.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server. | [
"Resets",
"the",
"BIOS",
"settings",
"to",
"default",
"values",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_port_profile.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_port_profile.py#L529-L546 | def port_profile_qos_profile_qos_flowcontrol_pfc_pfc_tx(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile")
name_key = ET.SubElement(port_profile, "name")... | [
"def",
"port_profile_qos_profile_qos_flowcontrol_pfc_pfc_tx",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"port_profile",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"port-profile\"",
",",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
CalebBell/thermo | thermo/chemical.py | https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/chemical.py#L2505-L2520 | def Vm(self):
r'''Molar volume of the chemical at its current phase and
temperature and pressure, in units of [m^3/mol].
Utilizes the object oriented interfaces
:obj:`thermo.volume.VolumeSolid`,
:obj:`thermo.volume.VolumeLiquid`,
and :obj:`thermo.volume.VolumeGas` to per... | [
"def",
"Vm",
"(",
"self",
")",
":",
"return",
"phase_select_property",
"(",
"phase",
"=",
"self",
".",
"phase",
",",
"s",
"=",
"self",
".",
"Vms",
",",
"l",
"=",
"self",
".",
"Vml",
",",
"g",
"=",
"self",
".",
"Vmg",
")"
] | r'''Molar volume of the chemical at its current phase and
temperature and pressure, in units of [m^3/mol].
Utilizes the object oriented interfaces
:obj:`thermo.volume.VolumeSolid`,
:obj:`thermo.volume.VolumeLiquid`,
and :obj:`thermo.volume.VolumeGas` to perform the
actua... | [
"r",
"Molar",
"volume",
"of",
"the",
"chemical",
"at",
"its",
"current",
"phase",
"and",
"temperature",
"and",
"pressure",
"in",
"units",
"of",
"[",
"m^3",
"/",
"mol",
"]",
"."
] | python | valid |
FlaskGuys/Flask-Imagine-AzureAdapter | flask_imagine_azure_adapter/__init__.py | https://github.com/FlaskGuys/Flask-Imagine-AzureAdapter/blob/1ca83fb040602ba1be983a7d1cfd052323a86f1a/flask_imagine_azure_adapter/__init__.py#L111-L127 | def remove_cached_item(self, path):
"""
Remove cached resource item
:param path: str
:return: PIL.Image
"""
item_path = '%s/%s' % (
self.cache_folder,
path.strip('/')
)
self.blob_service.delete_blob(self.container_name,... | [
"def",
"remove_cached_item",
"(",
"self",
",",
"path",
")",
":",
"item_path",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"cache_folder",
",",
"path",
".",
"strip",
"(",
"'/'",
")",
")",
"self",
".",
"blob_service",
".",
"delete_blob",
"(",
"self",
".",
"co... | Remove cached resource item
:param path: str
:return: PIL.Image | [
"Remove",
"cached",
"resource",
"item",
":",
"param",
"path",
":",
"str",
":",
"return",
":",
"PIL",
".",
"Image"
] | python | train |
src-d/jgit-spark-connector | python/sourced/engine/engine.py | https://github.com/src-d/jgit-spark-connector/blob/79d05a0bcf0da435685d6118828a8884e2fe4b94/python/sourced/engine/engine.py#L359-L369 | def master_ref(self):
"""
Filters the current DataFrame to only contain those rows whose reference is master.
>>> master_df = refs_df.master_ref
:rtype: ReferencesDataFrame
"""
return ReferencesDataFrame(self._engine_dataframe.getMaster(),
... | [
"def",
"master_ref",
"(",
"self",
")",
":",
"return",
"ReferencesDataFrame",
"(",
"self",
".",
"_engine_dataframe",
".",
"getMaster",
"(",
")",
",",
"self",
".",
"_session",
",",
"self",
".",
"_implicits",
")",
"return",
"self",
".",
"ref",
"(",
"'refs/hea... | Filters the current DataFrame to only contain those rows whose reference is master.
>>> master_df = refs_df.master_ref
:rtype: ReferencesDataFrame | [
"Filters",
"the",
"current",
"DataFrame",
"to",
"only",
"contain",
"those",
"rows",
"whose",
"reference",
"is",
"master",
"."
] | python | train |
Azure/azure-sdk-for-python | azure-servicebus/azure/servicebus/control_client/models.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicebus/azure/servicebus/control_client/models.py#L202-L217 | def unlock(self):
''' Unlocks itself if find queue name or topic name and subscription
name. '''
if self._queue_name:
self.service_bus_service.unlock_queue_message(
self._queue_name,
self.broker_properties['SequenceNumber'],
self.broker... | [
"def",
"unlock",
"(",
"self",
")",
":",
"if",
"self",
".",
"_queue_name",
":",
"self",
".",
"service_bus_service",
".",
"unlock_queue_message",
"(",
"self",
".",
"_queue_name",
",",
"self",
".",
"broker_properties",
"[",
"'SequenceNumber'",
"]",
",",
"self",
... | Unlocks itself if find queue name or topic name and subscription
name. | [
"Unlocks",
"itself",
"if",
"find",
"queue",
"name",
"or",
"topic",
"name",
"and",
"subscription",
"name",
"."
] | python | test |
klorenz/python-argdeco | argdeco/command_decorator.py | https://github.com/klorenz/python-argdeco/blob/8d01acef8c19d6883873689d017b14857876412d/argdeco/command_decorator.py#L202-L213 | def update(self, command=None, **kwargs):
"""update data, which is usually passed in ArgumentParser initialization
e.g. command.update(prog="foo")
"""
if command is None:
argparser = self.argparser
else:
argparser = self[command]
for k,v in kwarg... | [
"def",
"update",
"(",
"self",
",",
"command",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"command",
"is",
"None",
":",
"argparser",
"=",
"self",
".",
"argparser",
"else",
":",
"argparser",
"=",
"self",
"[",
"command",
"]",
"for",
"k",
",... | update data, which is usually passed in ArgumentParser initialization
e.g. command.update(prog="foo") | [
"update",
"data",
"which",
"is",
"usually",
"passed",
"in",
"ArgumentParser",
"initialization"
] | python | train |
pylast/pylast | src/pylast/__init__.py | https://github.com/pylast/pylast/blob/a52f66d316797fc819b5f1d186d77f18ba97b4ff/src/pylast/__init__.py#L1610-L1621 | def get_mbid(self):
"""Returns the MusicBrainz ID of the album or track."""
doc = self._request(self.ws_prefix + ".getInfo", cacheable=True)
try:
lfm = doc.getElementsByTagName("lfm")[0]
opus = next(self._get_children_by_tag_name(lfm, self.ws_prefix))
mbid =... | [
"def",
"get_mbid",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"cacheable",
"=",
"True",
")",
"try",
":",
"lfm",
"=",
"doc",
".",
"getElementsByTagName",
"(",
"\"lfm\"",
")",
"[",... | Returns the MusicBrainz ID of the album or track. | [
"Returns",
"the",
"MusicBrainz",
"ID",
"of",
"the",
"album",
"or",
"track",
"."
] | python | train |
ionelmc/python-cogen | cogen/core/proactors/base.py | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/proactors/base.py#L186-L194 | def add_token(self, act, coro, performer):
"""
Adds a completion token `act` in the proactor with associated `coro`
corutine and perform callable.
"""
assert act not in self.tokens
act.coro = coro
self.tokens[act] = performer
self.register_fd(act, ... | [
"def",
"add_token",
"(",
"self",
",",
"act",
",",
"coro",
",",
"performer",
")",
":",
"assert",
"act",
"not",
"in",
"self",
".",
"tokens",
"act",
".",
"coro",
"=",
"coro",
"self",
".",
"tokens",
"[",
"act",
"]",
"=",
"performer",
"self",
".",
"regi... | Adds a completion token `act` in the proactor with associated `coro`
corutine and perform callable. | [
"Adds",
"a",
"completion",
"token",
"act",
"in",
"the",
"proactor",
"with",
"associated",
"coro",
"corutine",
"and",
"perform",
"callable",
"."
] | python | train |
apple/turicreate | deps/src/libxml2-2.9.1/python/libxml2.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L6567-L6575 | def CurrentNode(self):
"""Hacking interface allowing to get the xmlNodePtr
correponding to the current node being accessed by the
xmlTextReader. This is dangerous because the underlying
node may be destroyed on the next Reads. """
ret = libxml2mod.xmlTextReaderCurrentNode(... | [
"def",
"CurrentNode",
"(",
"self",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlTextReaderCurrentNode",
"(",
"self",
".",
"_o",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlTextReaderCurrentNode() failed'",
")",
"__tmp",
"=",
"xmlNode",... | Hacking interface allowing to get the xmlNodePtr
correponding to the current node being accessed by the
xmlTextReader. This is dangerous because the underlying
node may be destroyed on the next Reads. | [
"Hacking",
"interface",
"allowing",
"to",
"get",
"the",
"xmlNodePtr",
"correponding",
"to",
"the",
"current",
"node",
"being",
"accessed",
"by",
"the",
"xmlTextReader",
".",
"This",
"is",
"dangerous",
"because",
"the",
"underlying",
"node",
"may",
"be",
"destroy... | python | train |
datastax/python-driver | cassandra/metadata.py | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/metadata.py#L1140-L1166 | def export_as_string(self):
"""
Returns a string of CQL queries that can be used to recreate this table
along with all indexes on it. The returned string is formatted to
be human readable.
"""
if self._exc_info:
import traceback
ret = "/*\nWarning... | [
"def",
"export_as_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"_exc_info",
":",
"import",
"traceback",
"ret",
"=",
"\"/*\\nWarning: Table %s.%s is incomplete because of an error processing metadata.\\n\"",
"%",
"(",
"self",
".",
"keyspace_name",
",",
"self",
".",... | Returns a string of CQL queries that can be used to recreate this table
along with all indexes on it. The returned string is formatted to
be human readable. | [
"Returns",
"a",
"string",
"of",
"CQL",
"queries",
"that",
"can",
"be",
"used",
"to",
"recreate",
"this",
"table",
"along",
"with",
"all",
"indexes",
"on",
"it",
".",
"The",
"returned",
"string",
"is",
"formatted",
"to",
"be",
"human",
"readable",
"."
] | python | train |
benedictpaten/sonLib | tree.py | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/tree.py#L162-L172 | def transformByDistance(wV, subModel, alphabetSize=4):
"""
transform wV by given substitution matrix
"""
nc = [0.0]*alphabetSize
for i in xrange(0, alphabetSize):
j = wV[i]
k = subModel[i]
for l in xrange(0, alphabetSize):
nc[l] += j * k[l]
return nc | [
"def",
"transformByDistance",
"(",
"wV",
",",
"subModel",
",",
"alphabetSize",
"=",
"4",
")",
":",
"nc",
"=",
"[",
"0.0",
"]",
"*",
"alphabetSize",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"alphabetSize",
")",
":",
"j",
"=",
"wV",
"[",
"i",
"]",
... | transform wV by given substitution matrix | [
"transform",
"wV",
"by",
"given",
"substitution",
"matrix"
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L503-L512 | def dictlist_convert_to_string(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a
blank string, convert it to ``None``.
"""
for d in dict_list:
... | [
"def",
"dictlist_convert_to_string",
"(",
"dict_list",
":",
"Iterable",
"[",
"Dict",
"]",
",",
"key",
":",
"str",
")",
"->",
"None",
":",
"for",
"d",
"in",
"dict_list",
":",
"d",
"[",
"key",
"]",
"=",
"str",
"(",
"d",
"[",
"key",
"]",
")",
"if",
... | Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a
blank string, convert it to ``None``. | [
"Process",
"an",
"iterable",
"of",
"dictionaries",
".",
"For",
"each",
"dictionary",
"d",
"convert",
"(",
"in",
"place",
")",
"d",
"[",
"key",
"]",
"to",
"a",
"string",
"form",
"str",
"(",
"d",
"[",
"key",
"]",
")",
".",
"If",
"the",
"result",
"is"... | python | train |
tensorflow/tensor2tensor | tensor2tensor/layers/discretization.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L1399-L1426 | def isemhash_bottleneck(x,
bottleneck_bits,
bottleneck_noise,
discretize_warmup_steps,
mode,
isemhash_noise_dev=0.5,
isemhash_mix_prob=0.5):
"""Improved semantic hashing bott... | [
"def",
"isemhash_bottleneck",
"(",
"x",
",",
"bottleneck_bits",
",",
"bottleneck_noise",
",",
"discretize_warmup_steps",
",",
"mode",
",",
"isemhash_noise_dev",
"=",
"0.5",
",",
"isemhash_mix_prob",
"=",
"0.5",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
... | Improved semantic hashing bottleneck. | [
"Improved",
"semantic",
"hashing",
"bottleneck",
"."
] | python | train |
SFDO-Tooling/CumulusCI | cumulusci/core/keychain/BaseProjectKeychain.py | https://github.com/SFDO-Tooling/CumulusCI/blob/e19047921ca771a297e045f22f0bb201651bb6f7/cumulusci/core/keychain/BaseProjectKeychain.py#L151-L156 | def set_default_org(self, name):
""" set the default org for tasks by name key """
org = self.get_org(name)
self.unset_default_org()
org.config["default"] = True
self.set_org(org) | [
"def",
"set_default_org",
"(",
"self",
",",
"name",
")",
":",
"org",
"=",
"self",
".",
"get_org",
"(",
"name",
")",
"self",
".",
"unset_default_org",
"(",
")",
"org",
".",
"config",
"[",
"\"default\"",
"]",
"=",
"True",
"self",
".",
"set_org",
"(",
"... | set the default org for tasks by name key | [
"set",
"the",
"default",
"org",
"for",
"tasks",
"by",
"name",
"key"
] | python | train |
timmahrt/ProMo | promo/morph_utils/morph_sequence.py | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L98-L130 | def _getSmallestDifference(inputList, targetVal):
'''
Returns the value in inputList that is closest to targetVal
Iteratively splits the dataset in two, so it should be pretty fast
'''
targetList = inputList[:]
retVal = None
while True:
# If we're down to one value, stop iterati... | [
"def",
"_getSmallestDifference",
"(",
"inputList",
",",
"targetVal",
")",
":",
"targetList",
"=",
"inputList",
"[",
":",
"]",
"retVal",
"=",
"None",
"while",
"True",
":",
"# If we're down to one value, stop iterating",
"if",
"len",
"(",
"targetList",
")",
"==",
... | Returns the value in inputList that is closest to targetVal
Iteratively splits the dataset in two, so it should be pretty fast | [
"Returns",
"the",
"value",
"in",
"inputList",
"that",
"is",
"closest",
"to",
"targetVal",
"Iteratively",
"splits",
"the",
"dataset",
"in",
"two",
"so",
"it",
"should",
"be",
"pretty",
"fast"
] | python | train |
kubernetes-client/python | kubernetes/client/apis/certificates_v1beta1_api.py | https://github.com/kubernetes-client/python/blob/5e512ff564c244c50cab780d821542ed56aa965a/kubernetes/client/apis/certificates_v1beta1_api.py#L1157-L1180 | def replace_certificate_signing_request_approval(self, name, body, **kwargs):
"""
replace approval of the specified CertificateSigningRequest
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api... | [
"def",
"replace_certificate_signing_request_approval",
"(",
"self",
",",
"name",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
... | replace approval of the specified CertificateSigningRequest
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_certificate_signing_request_approval(name, body, async_req=True)
>>> result = thr... | [
"replace",
"approval",
"of",
"the",
"specified",
"CertificateSigningRequest",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"pass",
"async_req",
"=",
"True",... | python | train |
apache/airflow | airflow/contrib/hooks/mongo_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/mongo_hook.py#L93-L102 | def get_collection(self, mongo_collection, mongo_db=None):
"""
Fetches a mongo collection object for querying.
Uses connection schema as DB unless specified.
"""
mongo_db = mongo_db if mongo_db is not None else self.connection.schema
mongo_conn = self.get_conn()
... | [
"def",
"get_collection",
"(",
"self",
",",
"mongo_collection",
",",
"mongo_db",
"=",
"None",
")",
":",
"mongo_db",
"=",
"mongo_db",
"if",
"mongo_db",
"is",
"not",
"None",
"else",
"self",
".",
"connection",
".",
"schema",
"mongo_conn",
"=",
"self",
".",
"ge... | Fetches a mongo collection object for querying.
Uses connection schema as DB unless specified. | [
"Fetches",
"a",
"mongo",
"collection",
"object",
"for",
"querying",
"."
] | python | test |
gwastro/pycbc | pycbc/filter/matchedfilter.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/filter/matchedfilter.py#L1255-L1280 | def smear(idx, factor):
"""
This function will take as input an array of indexes and return every
unique index within the specified factor of the inputs.
E.g.: smear([5,7,100],2) = [3,4,5,6,7,8,9,98,99,100,101,102]
Parameters
-----------
idx : numpy.array of ints
The indexes to be ... | [
"def",
"smear",
"(",
"idx",
",",
"factor",
")",
":",
"s",
"=",
"[",
"idx",
"]",
"for",
"i",
"in",
"range",
"(",
"factor",
"+",
"1",
")",
":",
"a",
"=",
"i",
"-",
"factor",
"/",
"2",
"s",
"+=",
"[",
"idx",
"+",
"a",
"]",
"return",
"numpy",
... | This function will take as input an array of indexes and return every
unique index within the specified factor of the inputs.
E.g.: smear([5,7,100],2) = [3,4,5,6,7,8,9,98,99,100,101,102]
Parameters
-----------
idx : numpy.array of ints
The indexes to be smeared.
factor : idx
Th... | [
"This",
"function",
"will",
"take",
"as",
"input",
"an",
"array",
"of",
"indexes",
"and",
"return",
"every",
"unique",
"index",
"within",
"the",
"specified",
"factor",
"of",
"the",
"inputs",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/routing_system/router/router_bgp/router_bgp_attributes/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/routing_system/router/router_bgp/router_bgp_attributes/__init__.py#L349-L370 | def _set_cluster_id(self, v, load=False):
"""
Setter method for cluster_id, mapped from YANG variable /routing_system/router/router_bgp/router_bgp_attributes/cluster_id (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_cluster_id is considered as a private
... | [
"def",
"_set_cluster_id",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | Setter method for cluster_id, mapped from YANG variable /routing_system/router/router_bgp/router_bgp_attributes/cluster_id (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_cluster_id is considered as a private
method. Backends looking to populate this variable sho... | [
"Setter",
"method",
"for",
"cluster_id",
"mapped",
"from",
"YANG",
"variable",
"/",
"routing_system",
"/",
"router",
"/",
"router_bgp",
"/",
"router_bgp_attributes",
"/",
"cluster_id",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
... | python | train |
Azure/azure-uamqp-python | uamqp/authentication/cbs_auth_async.py | https://github.com/Azure/azure-uamqp-python/blob/b67e4fcaf2e8a337636947523570239c10a58ae2/uamqp/authentication/cbs_auth_async.py#L21-L54 | async def create_authenticator_async(self, connection, debug=False, loop=None, **kwargs):
"""Create the async AMQP session and the CBS channel with which
to negotiate the token.
:param connection: The underlying AMQP connection on which
to create the session.
:type connection: ... | [
"async",
"def",
"create_authenticator_async",
"(",
"self",
",",
"connection",
",",
"debug",
"=",
"False",
",",
"loop",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"loop",
"=",
"loop",
"or",
"asyncio",
".",
"get_event_loop",
"(",
")",
"... | Create the async AMQP session and the CBS channel with which
to negotiate the token.
:param connection: The underlying AMQP connection on which
to create the session.
:type connection: ~uamqp.async_ops.connection_async.ConnectionAsync
:param debug: Whether to emit network trace... | [
"Create",
"the",
"async",
"AMQP",
"session",
"and",
"the",
"CBS",
"channel",
"with",
"which",
"to",
"negotiate",
"the",
"token",
"."
] | python | train |
yfpeng/bioc | bioc/utils.py | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/utils.py#L11-L18 | def pad_char(text: str, width: int, char: str = '\n') -> str:
"""Pads a text until length width."""
dis = width - len(text)
if dis < 0:
raise ValueError
if dis > 0:
text += char * dis
return text | [
"def",
"pad_char",
"(",
"text",
":",
"str",
",",
"width",
":",
"int",
",",
"char",
":",
"str",
"=",
"'\\n'",
")",
"->",
"str",
":",
"dis",
"=",
"width",
"-",
"len",
"(",
"text",
")",
"if",
"dis",
"<",
"0",
":",
"raise",
"ValueError",
"if",
"dis... | Pads a text until length width. | [
"Pads",
"a",
"text",
"until",
"length",
"width",
"."
] | python | train |
baliame/http-hmac-python | httphmac/v1.py | https://github.com/baliame/http-hmac-python/blob/9884c0cbfdb712f9f37080a8efbfdce82850785f/httphmac/v1.py#L84-L99 | def check(self, request, secret):
"""Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature.
This verifies every element of the signature, including headers other than Authorization.
Keyword arguments:
request -- A request obje... | [
"def",
"check",
"(",
"self",
",",
"request",
",",
"secret",
")",
":",
"if",
"request",
".",
"get_header",
"(",
"\"Authorization\"",
")",
"==",
"\"\"",
":",
"return",
"False",
"ah",
"=",
"self",
".",
"parse_auth_headers",
"(",
"request",
".",
"get_header",
... | Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature.
This verifies every element of the signature, including headers other than Authorization.
Keyword arguments:
request -- A request object which can be consumed by this API.
... | [
"Verifies",
"whether",
"or",
"not",
"the",
"request",
"bears",
"an",
"authorization",
"appropriate",
"and",
"valid",
"for",
"this",
"version",
"of",
"the",
"signature",
".",
"This",
"verifies",
"every",
"element",
"of",
"the",
"signature",
"including",
"headers"... | python | train |
dnanexus/dx-toolkit | src/python/dxpy/api.py | https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/src/python/dxpy/api.py#L1148-L1154 | def record_rename(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /record-xxxx/rename API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Name#API-method%3A-%2Fclass-xxxx%2Frename
"""
return DXHTTPRequest('/%s/rename' % object_id, input_param... | [
"def",
"record_rename",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/rename'",
"%",
"object_id",
",",
"input_params",
",",
"always_retry",
"="... | Invokes the /record-xxxx/rename API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Name#API-method%3A-%2Fclass-xxxx%2Frename | [
"Invokes",
"the",
"/",
"record",
"-",
"xxxx",
"/",
"rename",
"API",
"method",
"."
] | python | train |
rbuffat/pyepw | pyepw/epw.py | https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L1350-L1370 | def ws004c(self, value=None):
"""Corresponds to IDD Field `ws004c`
Args:
value (float): value for IDD Field `ws004c`
Unit: m/s
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Ra... | [
"def",
"ws004c",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type float '... | Corresponds to IDD Field `ws004c`
Args:
value (float): value for IDD Field `ws004c`
Unit: m/s
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` ... | [
"Corresponds",
"to",
"IDD",
"Field",
"ws004c"
] | python | train |
jreese/aiosqlite | aiosqlite/core.py | https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L213-L219 | async def execute_insert(
self, sql: str, parameters: Iterable[Any] = None
) -> Optional[sqlite3.Row]:
"""Helper to insert and get the last_insert_rowid."""
if parameters is None:
parameters = []
return await self._execute(self._execute_insert, sql, parameters) | [
"async",
"def",
"execute_insert",
"(",
"self",
",",
"sql",
":",
"str",
",",
"parameters",
":",
"Iterable",
"[",
"Any",
"]",
"=",
"None",
")",
"->",
"Optional",
"[",
"sqlite3",
".",
"Row",
"]",
":",
"if",
"parameters",
"is",
"None",
":",
"parameters",
... | Helper to insert and get the last_insert_rowid. | [
"Helper",
"to",
"insert",
"and",
"get",
"the",
"last_insert_rowid",
"."
] | python | train |
trevisanj/a99 | a99/conversion.py | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/conversion.py#L169-L181 | def valid_fits_key(key):
"""
Makes valid key for a FITS header
"The keyword names may be up to 8 characters long and can only contain
uppercase letters A to Z, the digits 0 to 9, the hyphen, and the underscore
character." (http://fits.gsfc.nasa.gov/fits_primer.html)
"""
ret = re.s... | [
"def",
"valid_fits_key",
"(",
"key",
")",
":",
"ret",
"=",
"re",
".",
"sub",
"(",
"\"[^A-Z0-9\\-_]\"",
",",
"\"\"",
",",
"key",
".",
"upper",
"(",
")",
")",
"[",
":",
"8",
"]",
"if",
"len",
"(",
"ret",
")",
"==",
"0",
":",
"raise",
"RuntimeError"... | Makes valid key for a FITS header
"The keyword names may be up to 8 characters long and can only contain
uppercase letters A to Z, the digits 0 to 9, the hyphen, and the underscore
character." (http://fits.gsfc.nasa.gov/fits_primer.html) | [
"Makes",
"valid",
"key",
"for",
"a",
"FITS",
"header",
"The",
"keyword",
"names",
"may",
"be",
"up",
"to",
"8",
"characters",
"long",
"and",
"can",
"only",
"contain",
"uppercase",
"letters",
"A",
"to",
"Z",
"the",
"digits",
"0",
"to",
"9",
"the",
"hyph... | python | train |
Azure/azure-sdk-for-python | azure-servicemanagement-legacy/azure/servicemanagement/websitemanagementservice.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicemanagement-legacy/azure/servicemanagement/websitemanagementservice.py#L155-L179 | def delete_site(self, webspace_name, website_name,
delete_empty_server_farm=False, delete_metrics=False):
'''
Delete a website.
webspace_name:
The name of the webspace.
website_name:
The name of the website.
delete_empty_server_farm:
... | [
"def",
"delete_site",
"(",
"self",
",",
"webspace_name",
",",
"website_name",
",",
"delete_empty_server_farm",
"=",
"False",
",",
"delete_metrics",
"=",
"False",
")",
":",
"path",
"=",
"self",
".",
"_get_sites_details_path",
"(",
"webspace_name",
",",
"website_nam... | Delete a website.
webspace_name:
The name of the webspace.
website_name:
The name of the website.
delete_empty_server_farm:
If the site being deleted is the last web site in a server farm,
you can delete the server farm by setting this to True.
... | [
"Delete",
"a",
"website",
"."
] | python | test |
apache/airflow | airflow/models/dagrun.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/dagrun.py#L221-L229 | def get_previous_dagrun(self, session=None):
"""The previous DagRun, if there is one"""
return session.query(DagRun).filter(
DagRun.dag_id == self.dag_id,
DagRun.execution_date < self.execution_date
).order_by(
DagRun.execution_date.desc()
).first() | [
"def",
"get_previous_dagrun",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"return",
"session",
".",
"query",
"(",
"DagRun",
")",
".",
"filter",
"(",
"DagRun",
".",
"dag_id",
"==",
"self",
".",
"dag_id",
",",
"DagRun",
".",
"execution_date",
"<",
... | The previous DagRun, if there is one | [
"The",
"previous",
"DagRun",
"if",
"there",
"is",
"one"
] | python | test |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/depend/dylib.py | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/depend/dylib.py#L175-L222 | def mac_set_relative_dylib_deps(libname):
"""
On Mac OS X set relative paths to dynamic library dependencies of `libname`.
Relative paths allow to avoid using environment variable DYLD_LIBRARY_PATH.
There are known some issues with DYLD_LIBRARY_PATH. Relative paths is
more flexible mechanism.
... | [
"def",
"mac_set_relative_dylib_deps",
"(",
"libname",
")",
":",
"from",
"PyInstaller",
".",
"lib",
".",
"macholib",
"import",
"util",
"from",
"PyInstaller",
".",
"lib",
".",
"macholib",
".",
"MachO",
"import",
"MachO",
"# Ignore bootloader otherwise PyInstaller fails ... | On Mac OS X set relative paths to dynamic library dependencies of `libname`.
Relative paths allow to avoid using environment variable DYLD_LIBRARY_PATH.
There are known some issues with DYLD_LIBRARY_PATH. Relative paths is
more flexible mechanism.
Current location of dependend libraries is derived fro... | [
"On",
"Mac",
"OS",
"X",
"set",
"relative",
"paths",
"to",
"dynamic",
"library",
"dependencies",
"of",
"libname",
"."
] | python | train |
timothyb0912/pylogit | pylogit/estimation.py | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/estimation.py#L331-L351 | def convenience_calc_log_likelihood(self, params):
"""
Calculates the log-likelihood for this model and dataset.
"""
shapes, intercepts, betas = self.convenience_split_params(params)
args = [betas,
self.design,
self.alt_id_vector,
... | [
"def",
"convenience_calc_log_likelihood",
"(",
"self",
",",
"params",
")",
":",
"shapes",
",",
"intercepts",
",",
"betas",
"=",
"self",
".",
"convenience_split_params",
"(",
"params",
")",
"args",
"=",
"[",
"betas",
",",
"self",
".",
"design",
",",
"self",
... | Calculates the log-likelihood for this model and dataset. | [
"Calculates",
"the",
"log",
"-",
"likelihood",
"for",
"this",
"model",
"and",
"dataset",
"."
] | python | train |
tensorpack/tensorpack | examples/Saliency/saliency-maps.py | https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/examples/Saliency/saliency-maps.py#L40-L52 | def saliency_map(output, input, name="saliency_map"):
"""
Produce a saliency map as described in the paper:
`Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps
<https://arxiv.org/abs/1312.6034>`_.
The saliency map is the gradient of the max element in outpu... | [
"def",
"saliency_map",
"(",
"output",
",",
"input",
",",
"name",
"=",
"\"saliency_map\"",
")",
":",
"max_outp",
"=",
"tf",
".",
"reduce_max",
"(",
"output",
",",
"1",
")",
"saliency_op",
"=",
"tf",
".",
"gradients",
"(",
"max_outp",
",",
"input",
")",
... | Produce a saliency map as described in the paper:
`Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps
<https://arxiv.org/abs/1312.6034>`_.
The saliency map is the gradient of the max element in output w.r.t input.
Returns:
tf.Tensor: the saliency map. ... | [
"Produce",
"a",
"saliency",
"map",
"as",
"described",
"in",
"the",
"paper",
":",
"Deep",
"Inside",
"Convolutional",
"Networks",
":",
"Visualising",
"Image",
"Classification",
"Models",
"and",
"Saliency",
"Maps",
"<https",
":",
"//",
"arxiv",
".",
"org",
"/",
... | python | train |
petebachant/PXL | pxl/io.py | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/io.py#L70-L92 | def savehdf(filename, datadict, groupname="data", mode="a", metadata=None,
as_dataframe=False, append=False):
"""Save a dictionary of arrays to file--similar to how `scipy.io.savemat`
works. If `datadict` is a DataFrame, it will be converted automatically.
"""
if as_dataframe:
df = _... | [
"def",
"savehdf",
"(",
"filename",
",",
"datadict",
",",
"groupname",
"=",
"\"data\"",
",",
"mode",
"=",
"\"a\"",
",",
"metadata",
"=",
"None",
",",
"as_dataframe",
"=",
"False",
",",
"append",
"=",
"False",
")",
":",
"if",
"as_dataframe",
":",
"df",
"... | Save a dictionary of arrays to file--similar to how `scipy.io.savemat`
works. If `datadict` is a DataFrame, it will be converted automatically. | [
"Save",
"a",
"dictionary",
"of",
"arrays",
"to",
"file",
"--",
"similar",
"to",
"how",
"scipy",
".",
"io",
".",
"savemat",
"works",
".",
"If",
"datadict",
"is",
"a",
"DataFrame",
"it",
"will",
"be",
"converted",
"automatically",
"."
] | python | train |
klavinslab/coral | coral/analysis/_structure/nupack.py | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/nupack.py#L548-L572 | def count(self, strand, pseudo=False):
'''Enumerates the total number of secondary structures over the
structural ensemble Ω(π). Runs the \'count\' command.
:param strand: Strand on which to run count. Strands must be either
coral.DNA or coral.RNA).
:type strand: ... | [
"def",
"count",
"(",
"self",
",",
"strand",
",",
"pseudo",
"=",
"False",
")",
":",
"# Set up command flags",
"if",
"pseudo",
":",
"cmd_args",
"=",
"[",
"'-pseudo'",
"]",
"else",
":",
"cmd_args",
"=",
"[",
"]",
"# Set up the input file and run the command",
"st... | Enumerates the total number of secondary structures over the
structural ensemble Ω(π). Runs the \'count\' command.
:param strand: Strand on which to run count. Strands must be either
coral.DNA or coral.RNA).
:type strand: list
:param pseudo: Enable pseudoknots.
... | [
"Enumerates",
"the",
"total",
"number",
"of",
"secondary",
"structures",
"over",
"the",
"structural",
"ensemble",
"Ω",
"(",
"π",
")",
".",
"Runs",
"the",
"\\",
"count",
"\\",
"command",
"."
] | python | train |
ronhanson/python-tbx | tbx/process.py | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/process.py#L38-L51 | def synchronized(lock):
"""
Synchronization decorator; provide thread-safe locking on a function
http://code.activestate.com/recipes/465057/
"""
def wrap(f):
def synchronize(*args, **kw):
lock.acquire()
try:
return f(*args, **kw)
finally:
... | [
"def",
"synchronized",
"(",
"lock",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"def",
"synchronize",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"... | Synchronization decorator; provide thread-safe locking on a function
http://code.activestate.com/recipes/465057/ | [
"Synchronization",
"decorator",
";",
"provide",
"thread",
"-",
"safe",
"locking",
"on",
"a",
"function",
"http",
":",
"//",
"code",
".",
"activestate",
".",
"com",
"/",
"recipes",
"/",
"465057",
"/"
] | python | train |
saltstack/salt | salt/modules/nspawn.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nspawn.py#L333-L351 | def pid(name):
'''
Returns the PID of a container
name
Container name
CLI Example:
.. code-block:: bash
salt myminion nspawn.pid arch1
'''
try:
return int(info(name).get('PID'))
except (TypeError, ValueError) as exc:
raise CommandExecutionError(
... | [
"def",
"pid",
"(",
"name",
")",
":",
"try",
":",
"return",
"int",
"(",
"info",
"(",
"name",
")",
".",
"get",
"(",
"'PID'",
")",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
"as",
"exc",
":",
"raise",
"CommandExecutionError",
"(",
"'Unable... | Returns the PID of a container
name
Container name
CLI Example:
.. code-block:: bash
salt myminion nspawn.pid arch1 | [
"Returns",
"the",
"PID",
"of",
"a",
"container"
] | python | train |
pyviz/holoviews | holoviews/ipython/preprocessors.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/ipython/preprocessors.py#L75-L83 | def strip_magics(source):
"""
Given the source of a cell, filter out all cell and line magics.
"""
filtered=[]
for line in source.splitlines():
if not line.startswith('%') or line.startswith('%%'):
filtered.append(line)
return '\n'.join(filtered) | [
"def",
"strip_magics",
"(",
"source",
")",
":",
"filtered",
"=",
"[",
"]",
"for",
"line",
"in",
"source",
".",
"splitlines",
"(",
")",
":",
"if",
"not",
"line",
".",
"startswith",
"(",
"'%'",
")",
"or",
"line",
".",
"startswith",
"(",
"'%%'",
")",
... | Given the source of a cell, filter out all cell and line magics. | [
"Given",
"the",
"source",
"of",
"a",
"cell",
"filter",
"out",
"all",
"cell",
"and",
"line",
"magics",
"."
] | python | train |
apache/incubator-mxnet | example/ssd/detect/detector.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/detect/detector.py#L120-L142 | def im_detect(self, im_list, root_dir=None, extension=None, show_timer=False):
"""
wrapper for detecting multiple images
Parameters:
----------
im_list : list of str
image path or list of image paths
root_dir : str
directory of input images, optio... | [
"def",
"im_detect",
"(",
"self",
",",
"im_list",
",",
"root_dir",
"=",
"None",
",",
"extension",
"=",
"None",
",",
"show_timer",
"=",
"False",
")",
":",
"test_db",
"=",
"TestDB",
"(",
"im_list",
",",
"root_dir",
"=",
"root_dir",
",",
"extension",
"=",
... | wrapper for detecting multiple images
Parameters:
----------
im_list : list of str
image path or list of image paths
root_dir : str
directory of input images, optional if image path already
has full directory information
extension : str
... | [
"wrapper",
"for",
"detecting",
"multiple",
"images"
] | python | train |
zeroSteiner/smoke-zephyr | smoke_zephyr/argparse_types.py | https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/argparse_types.py#L78-L84 | def bin_b64_type(arg):
"""An argparse type representing binary data encoded in base64."""
try:
arg = base64.standard_b64decode(arg)
except (binascii.Error, TypeError):
raise argparse.ArgumentTypeError("{0} is invalid base64 data".format(repr(arg)))
return arg | [
"def",
"bin_b64_type",
"(",
"arg",
")",
":",
"try",
":",
"arg",
"=",
"base64",
".",
"standard_b64decode",
"(",
"arg",
")",
"except",
"(",
"binascii",
".",
"Error",
",",
"TypeError",
")",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"\"{0} is in... | An argparse type representing binary data encoded in base64. | [
"An",
"argparse",
"type",
"representing",
"binary",
"data",
"encoded",
"in",
"base64",
"."
] | python | train |
haikuginger/beekeeper | beekeeper/variables.py | https://github.com/haikuginger/beekeeper/blob/b647d3add0b407ec5dc3a2a39c4f6dac31243b18/beekeeper/variables.py#L17-L29 | def merge(var1, var2):
"""
Take two copies of a variable and reconcile them. var1 is assumed
to be the higher-level variable, and so will be overridden by var2
where such becomes necessary.
"""
out = {}
out['value'] = var2.get('value', var1.get('value', None))
out['mimetype'] = var2.get(... | [
"def",
"merge",
"(",
"var1",
",",
"var2",
")",
":",
"out",
"=",
"{",
"}",
"out",
"[",
"'value'",
"]",
"=",
"var2",
".",
"get",
"(",
"'value'",
",",
"var1",
".",
"get",
"(",
"'value'",
",",
"None",
")",
")",
"out",
"[",
"'mimetype'",
"]",
"=",
... | Take two copies of a variable and reconcile them. var1 is assumed
to be the higher-level variable, and so will be overridden by var2
where such becomes necessary. | [
"Take",
"two",
"copies",
"of",
"a",
"variable",
"and",
"reconcile",
"them",
".",
"var1",
"is",
"assumed",
"to",
"be",
"the",
"higher",
"-",
"level",
"variable",
"and",
"so",
"will",
"be",
"overridden",
"by",
"var2",
"where",
"such",
"becomes",
"necessary",... | python | train |
Alignak-monitoring/alignak | alignak/objects/schedulingitem.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L3233-L3241 | def unset_impact_state(self):
"""Unset impact, only if impact state change is set in configuration
:return: None
"""
cls = self.__class__
if cls.enable_problem_impacts_states_change and not self.state_changed_since_impact:
self.state = self.state_before_impact
... | [
"def",
"unset_impact_state",
"(",
"self",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"if",
"cls",
".",
"enable_problem_impacts_states_change",
"and",
"not",
"self",
".",
"state_changed_since_impact",
":",
"self",
".",
"state",
"=",
"self",
".",
"state_befor... | Unset impact, only if impact state change is set in configuration
:return: None | [
"Unset",
"impact",
"only",
"if",
"impact",
"state",
"change",
"is",
"set",
"in",
"configuration"
] | python | train |
DataDog/integrations-core | tokumx/datadog_checks/tokumx/vendor/pymongo/database.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/pymongo/database.py#L544-L569 | def collection_names(self, include_system_collections=True):
"""Get a list of all the collection names in this database.
:Parameters:
- `include_system_collections` (optional): if ``False`` list
will not include system collections (e.g ``system.indexes``)
"""
with ... | [
"def",
"collection_names",
"(",
"self",
",",
"include_system_collections",
"=",
"True",
")",
":",
"with",
"self",
".",
"__client",
".",
"_socket_for_reads",
"(",
"ReadPreference",
".",
"PRIMARY",
")",
"as",
"(",
"sock_info",
",",
"slave_okay",
")",
":",
"wire_... | Get a list of all the collection names in this database.
:Parameters:
- `include_system_collections` (optional): if ``False`` list
will not include system collections (e.g ``system.indexes``) | [
"Get",
"a",
"list",
"of",
"all",
"the",
"collection",
"names",
"in",
"this",
"database",
"."
] | python | train |
crm416/semantic | semantic/dates.py | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/dates.py#L476-L495 | def extractDates(inp, tz=None, now=None):
"""Extract semantic date information from an input string.
This is a convenience method which would only be used if
you'd rather not initialize a DateService object.
Args:
inp (str): The input string to be parsed.
tz: An optional Pytz timezone. ... | [
"def",
"extractDates",
"(",
"inp",
",",
"tz",
"=",
"None",
",",
"now",
"=",
"None",
")",
":",
"service",
"=",
"DateService",
"(",
"tz",
"=",
"tz",
",",
"now",
"=",
"now",
")",
"return",
"service",
".",
"extractDates",
"(",
"inp",
")"
] | Extract semantic date information from an input string.
This is a convenience method which would only be used if
you'd rather not initialize a DateService object.
Args:
inp (str): The input string to be parsed.
tz: An optional Pytz timezone. All datetime objects returned will
be... | [
"Extract",
"semantic",
"date",
"information",
"from",
"an",
"input",
"string",
".",
"This",
"is",
"a",
"convenience",
"method",
"which",
"would",
"only",
"be",
"used",
"if",
"you",
"d",
"rather",
"not",
"initialize",
"a",
"DateService",
"object",
"."
] | python | train |
Scifabric/pybossa-client | pbclient/__init__.py | https://github.com/Scifabric/pybossa-client/blob/998d7cb0207ff5030dc800f0c2577c5692316c2c/pbclient/__init__.py#L218-L233 | def find_project(**kwargs):
"""Return a list with matching project arguments.
:param kwargs: PYBOSSA Project members
:rtype: list
:returns: A list of projects that match the kwargs
"""
try:
res = _pybossa_req('get', 'project', params=kwargs)
if type(res).__name__ == 'list':
... | [
"def",
"find_project",
"(",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"res",
"=",
"_pybossa_req",
"(",
"'get'",
",",
"'project'",
",",
"params",
"=",
"kwargs",
")",
"if",
"type",
"(",
"res",
")",
".",
"__name__",
"==",
"'list'",
":",
"return",
"[",
... | Return a list with matching project arguments.
:param kwargs: PYBOSSA Project members
:rtype: list
:returns: A list of projects that match the kwargs | [
"Return",
"a",
"list",
"with",
"matching",
"project",
"arguments",
"."
] | python | valid |
etingof/pysnmp | pysnmp/smi/mibs/SNMPv2-SMI.py | https://github.com/etingof/pysnmp/blob/cde062dd42f67dfd2d7686286a322d40e9c3a4b7/pysnmp/smi/mibs/SNMPv2-SMI.py#L993-L1055 | def writeUndo(self, varBind, **context):
"""Finalize Managed Object Instance modification.
Implements the third (unsuccessful) step of the multi-step workflow
of the SNMP SET command processing (:RFC:`1905#section-4.2.5`).
The goal of the third phase is to roll the Managed Object Insta... | [
"def",
"writeUndo",
"(",
"self",
",",
"varBind",
",",
"*",
"*",
"context",
")",
":",
"name",
",",
"val",
"=",
"varBind",
"(",
"debug",
".",
"logger",
"&",
"debug",
".",
"FLAG_INS",
"and",
"debug",
".",
"logger",
"(",
"'%s: writeUndo(%s, %r)'",
"%",
"("... | Finalize Managed Object Instance modification.
Implements the third (unsuccessful) step of the multi-step workflow
of the SNMP SET command processing (:RFC:`1905#section-4.2.5`).
The goal of the third phase is to roll the Managed Object Instance
being modified back into its previous st... | [
"Finalize",
"Managed",
"Object",
"Instance",
"modification",
"."
] | python | train |
Azure/blobxfer | blobxfer/models/crypto.py | https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/models/crypto.py#L395-L405 | def initialize_hmac(self):
# type: (EncryptionMetadata) -> hmac.HMAC
"""Initialize an hmac from a signing key if it exists
:param EncryptionMetadata self: this
:rtype: hmac.HMAC or None
:return: hmac
"""
if self._signkey is not None:
return hmac.new(se... | [
"def",
"initialize_hmac",
"(",
"self",
")",
":",
"# type: (EncryptionMetadata) -> hmac.HMAC",
"if",
"self",
".",
"_signkey",
"is",
"not",
"None",
":",
"return",
"hmac",
".",
"new",
"(",
"self",
".",
"_signkey",
",",
"digestmod",
"=",
"hashlib",
".",
"sha256",
... | Initialize an hmac from a signing key if it exists
:param EncryptionMetadata self: this
:rtype: hmac.HMAC or None
:return: hmac | [
"Initialize",
"an",
"hmac",
"from",
"a",
"signing",
"key",
"if",
"it",
"exists",
":",
"param",
"EncryptionMetadata",
"self",
":",
"this",
":",
"rtype",
":",
"hmac",
".",
"HMAC",
"or",
"None",
":",
"return",
":",
"hmac"
] | python | train |
pantsbuild/pants | src/python/pants/util/desktop.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/desktop.py#L40-L51 | def ui_open(*files):
"""Attempts to open the given files using the preferred desktop viewer or editor.
:raises :class:`OpenError`: if there is a problem opening any of the files.
"""
if files:
osname = get_os_name()
opener = _OPENER_BY_OS.get(osname)
if opener:
opener(files)
else:
r... | [
"def",
"ui_open",
"(",
"*",
"files",
")",
":",
"if",
"files",
":",
"osname",
"=",
"get_os_name",
"(",
")",
"opener",
"=",
"_OPENER_BY_OS",
".",
"get",
"(",
"osname",
")",
"if",
"opener",
":",
"opener",
"(",
"files",
")",
"else",
":",
"raise",
"OpenEr... | Attempts to open the given files using the preferred desktop viewer or editor.
:raises :class:`OpenError`: if there is a problem opening any of the files. | [
"Attempts",
"to",
"open",
"the",
"given",
"files",
"using",
"the",
"preferred",
"desktop",
"viewer",
"or",
"editor",
"."
] | python | train |
python-openxml/python-docx | docx/oxml/shared.py | https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/oxml/shared.py#L24-L29 | def new(cls, nsptagname, val):
"""
Return a new ``CT_DecimalNumber`` element having tagname *nsptagname*
and ``val`` attribute set to *val*.
"""
return OxmlElement(nsptagname, attrs={qn('w:val'): str(val)}) | [
"def",
"new",
"(",
"cls",
",",
"nsptagname",
",",
"val",
")",
":",
"return",
"OxmlElement",
"(",
"nsptagname",
",",
"attrs",
"=",
"{",
"qn",
"(",
"'w:val'",
")",
":",
"str",
"(",
"val",
")",
"}",
")"
] | Return a new ``CT_DecimalNumber`` element having tagname *nsptagname*
and ``val`` attribute set to *val*. | [
"Return",
"a",
"new",
"CT_DecimalNumber",
"element",
"having",
"tagname",
"*",
"nsptagname",
"*",
"and",
"val",
"attribute",
"set",
"to",
"*",
"val",
"*",
"."
] | python | train |
census-instrumentation/opencensus-python | opencensus/metrics/export/gauge.py | https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/opencensus/metrics/export/gauge.py#L265-L277 | def remove_time_series(self, label_values):
"""Remove the time series for specific label values.
:type label_values: list(:class:`LabelValue`)
:param label_values: Label values of the time series to remove.
"""
if label_values is None:
raise ValueError
if any... | [
"def",
"remove_time_series",
"(",
"self",
",",
"label_values",
")",
":",
"if",
"label_values",
"is",
"None",
":",
"raise",
"ValueError",
"if",
"any",
"(",
"lv",
"is",
"None",
"for",
"lv",
"in",
"label_values",
")",
":",
"raise",
"ValueError",
"if",
"len",
... | Remove the time series for specific label values.
:type label_values: list(:class:`LabelValue`)
:param label_values: Label values of the time series to remove. | [
"Remove",
"the",
"time",
"series",
"for",
"specific",
"label",
"values",
"."
] | python | train |
awesmubarak/markdown_strings | markdown_strings/__init__.py | https://github.com/awesmubarak/markdown_strings/blob/569e225e7a8f23469efe8df244d3d3fd0e8c3b3e/markdown_strings/__init__.py#L141-L155 | def image(alt_text, link_url, title=""):
"""Return an inline image.
Keyword arguments:
title -- Specify the title of the image, as seen when hovering over it.
>>> image("This is an image", "https://tinyurl.com/bright-green-tree")
''
>>>... | [
"def",
"image",
"(",
"alt_text",
",",
"link_url",
",",
"title",
"=",
"\"\"",
")",
":",
"image_string",
"=",
"\"\"",
"if",
"title",
":",
"image_string",
"+=",
"' \"'"... | Return an inline image.
Keyword arguments:
title -- Specify the title of the image, as seen when hovering over it.
>>> image("This is an image", "https://tinyurl.com/bright-green-tree")
''
>>> image("This is an image", "https://tinyurl.com/... | [
"Return",
"an",
"inline",
"image",
"."
] | python | train |
sci-bots/dmf-device-ui | dmf_device_ui/canvas.py | https://github.com/sci-bots/dmf-device-ui/blob/05b480683c9fa43f91ce5a58de2fa90cdf363fc8/dmf_device_ui/canvas.py#L786-L810 | def render_registration(self):
'''
Render pinned points on video frame as red rectangle.
'''
surface = self.get_surface()
if self.canvas is None or self.df_canvas_corners.shape[0] == 0:
return surface
corners = self.df_canvas_corners.copy()
corners['w... | [
"def",
"render_registration",
"(",
"self",
")",
":",
"surface",
"=",
"self",
".",
"get_surface",
"(",
")",
"if",
"self",
".",
"canvas",
"is",
"None",
"or",
"self",
".",
"df_canvas_corners",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"surfac... | Render pinned points on video frame as red rectangle. | [
"Render",
"pinned",
"points",
"on",
"video",
"frame",
"as",
"red",
"rectangle",
"."
] | python | train |
Esri/ArcREST | src/arcrest/common/geometry.py | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/geometry.py#L48-L53 | def asDictionary(self):
"""returns the wkid id for use in json calls"""
if self._wkid == None and self._wkt is not None:
return {"wkt": self._wkt}
else:
return {"wkid": self._wkid} | [
"def",
"asDictionary",
"(",
"self",
")",
":",
"if",
"self",
".",
"_wkid",
"==",
"None",
"and",
"self",
".",
"_wkt",
"is",
"not",
"None",
":",
"return",
"{",
"\"wkt\"",
":",
"self",
".",
"_wkt",
"}",
"else",
":",
"return",
"{",
"\"wkid\"",
":",
"sel... | returns the wkid id for use in json calls | [
"returns",
"the",
"wkid",
"id",
"for",
"use",
"in",
"json",
"calls"
] | python | train |
vertexproject/synapse | synapse/lib/reflect.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/reflect.py#L11-L23 | def getClsNames(item):
'''
Return a list of "fully qualified" class names for an instance.
Example:
for name in getClsNames(foo):
print(name)
'''
mro = inspect.getmro(item.__class__)
mro = [c for c in mro if c not in clsskip]
return ['%s.%s' % (c.__module__, c.__name__... | [
"def",
"getClsNames",
"(",
"item",
")",
":",
"mro",
"=",
"inspect",
".",
"getmro",
"(",
"item",
".",
"__class__",
")",
"mro",
"=",
"[",
"c",
"for",
"c",
"in",
"mro",
"if",
"c",
"not",
"in",
"clsskip",
"]",
"return",
"[",
"'%s.%s'",
"%",
"(",
"c",... | Return a list of "fully qualified" class names for an instance.
Example:
for name in getClsNames(foo):
print(name) | [
"Return",
"a",
"list",
"of",
"fully",
"qualified",
"class",
"names",
"for",
"an",
"instance",
"."
] | python | train |
horazont/aioxmpp | aioxmpp/service.py | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1449-L1463 | def is_inbound_message_filter(cb):
"""
Return true if `cb` has been decorated with :func:`inbound_message_filter`.
"""
try:
handlers = get_magic_attr(cb)
except AttributeError:
return False
hs = HandlerSpec(
(_apply_inbound_message_filter, ())
)
return hs in ha... | [
"def",
"is_inbound_message_filter",
"(",
"cb",
")",
":",
"try",
":",
"handlers",
"=",
"get_magic_attr",
"(",
"cb",
")",
"except",
"AttributeError",
":",
"return",
"False",
"hs",
"=",
"HandlerSpec",
"(",
"(",
"_apply_inbound_message_filter",
",",
"(",
")",
")",... | Return true if `cb` has been decorated with :func:`inbound_message_filter`. | [
"Return",
"true",
"if",
"cb",
"has",
"been",
"decorated",
"with",
":",
"func",
":",
"inbound_message_filter",
"."
] | python | train |
twilio/twilio-python | twilio/rest/preview/deployed_devices/fleet/key.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/preview/deployed_devices/fleet/key.py#L342-L356 | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: KeyContext for this KeyInstance
:rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyContext... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"KeyContext",
"(",
"self",
".",
"_version",
",",
"fleet_sid",
"=",
"self",
".",
"_solution",
"[",
"'fleet_sid'",
"]",
",",
"sid",
... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: KeyContext for this KeyInstance
:rtype: twilio.rest.preview.deployed_devices.fleet.key.KeyContext | [
"Generate",
"an",
"instance",
"context",
"for",
"the",
"instance",
"the",
"context",
"is",
"capable",
"of",
"performing",
"various",
"actions",
".",
"All",
"instance",
"actions",
"are",
"proxied",
"to",
"the",
"context"
] | python | train |
numenta/nupic | src/nupic/algorithms/utils.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/utils.py#L26-L71 | def importAndRunFunction(
path,
moduleName,
funcName,
**keywords
):
"""
Run a named function specified by a filesystem path, module name
and function name.
Returns the value returned by the imported function.
Use this when access is needed to code that has
not been added to a package acc... | [
"def",
"importAndRunFunction",
"(",
"path",
",",
"moduleName",
",",
"funcName",
",",
"*",
"*",
"keywords",
")",
":",
"import",
"sys",
"originalPath",
"=",
"sys",
".",
"path",
"try",
":",
"augmentedPath",
"=",
"[",
"path",
"]",
"+",
"sys",
".",
"path",
... | Run a named function specified by a filesystem path, module name
and function name.
Returns the value returned by the imported function.
Use this when access is needed to code that has
not been added to a package accessible from the ordinary Python
path. Encapsulates the multiple lines usually needed to
s... | [
"Run",
"a",
"named",
"function",
"specified",
"by",
"a",
"filesystem",
"path",
"module",
"name",
"and",
"function",
"name",
"."
] | python | valid |
openstack/networking-cisco | networking_cisco/apps/saf/server/dfa_server.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/dfa_server.py#L697-L701 | def _get_segmentation_id(self, netid, segid, source):
"""Allocate segmentation id. """
return self.seg_drvr.allocate_segmentation_id(netid, seg_id=segid,
source=source) | [
"def",
"_get_segmentation_id",
"(",
"self",
",",
"netid",
",",
"segid",
",",
"source",
")",
":",
"return",
"self",
".",
"seg_drvr",
".",
"allocate_segmentation_id",
"(",
"netid",
",",
"seg_id",
"=",
"segid",
",",
"source",
"=",
"source",
")"
] | Allocate segmentation id. | [
"Allocate",
"segmentation",
"id",
"."
] | python | train |
azraq27/neural | neural/alignment.py | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/alignment.py#L120-L135 | def convert_coord(coord_from,matrix_file,base_to_aligned=True):
'''Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate
matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False... | [
"def",
"convert_coord",
"(",
"coord_from",
",",
"matrix_file",
",",
"base_to_aligned",
"=",
"True",
")",
":",
"with",
"open",
"(",
"matrix_file",
")",
"as",
"f",
":",
"try",
":",
"values",
"=",
"[",
"float",
"(",
"y",
")",
"for",
"y",
"in",
"' '",
".... | Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate
matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False`` | [
"Takes",
"an",
"XYZ",
"array",
"(",
"in",
"DICOM",
"coordinates",
")",
"and",
"uses",
"the",
"matrix",
"file",
"produced",
"by",
"3dAllineate",
"to",
"transform",
"it",
".",
"By",
"default",
"the",
"3dAllineate",
"matrix",
"transforms",
"from",
"base",
"to",... | python | train |
symphonyoss/python-symphony | symphony/Pod/streams.py | https://github.com/symphonyoss/python-symphony/blob/b939f35fbda461183ec0c01790c754f89a295be0/symphony/Pod/streams.py#L87-L93 | def promote_owner(self, stream_id, user_id):
''' promote user to owner in stream '''
req_hook = 'pod/v1/room/' + stream_id + '/membership/promoteOwner'
req_args = '{ "id": %s }' % user_id
status_code, response = self.__rest__.POST_query(req_hook, req_args)
self.logger.debug('%s: ... | [
"def",
"promote_owner",
"(",
"self",
",",
"stream_id",
",",
"user_id",
")",
":",
"req_hook",
"=",
"'pod/v1/room/'",
"+",
"stream_id",
"+",
"'/membership/promoteOwner'",
"req_args",
"=",
"'{ \"id\": %s }'",
"%",
"user_id",
"status_code",
",",
"response",
"=",
"self... | promote user to owner in stream | [
"promote",
"user",
"to",
"owner",
"in",
"stream"
] | python | train |
mbarkhau/tinypng | tinypng/api.py | https://github.com/mbarkhau/tinypng/blob/58e33cd5b46b26aab530a184b70856f7e936d79a/tinypng/api.py#L116-L122 | def shrink_data(in_data, api_key=None):
"""Shrink binary data of a png
returns (api_info, shrunk_data)
"""
info = get_shrink_data_info(in_data, api_key)
return info, get_shrunk_data(info) | [
"def",
"shrink_data",
"(",
"in_data",
",",
"api_key",
"=",
"None",
")",
":",
"info",
"=",
"get_shrink_data_info",
"(",
"in_data",
",",
"api_key",
")",
"return",
"info",
",",
"get_shrunk_data",
"(",
"info",
")"
] | Shrink binary data of a png
returns (api_info, shrunk_data) | [
"Shrink",
"binary",
"data",
"of",
"a",
"png"
] | python | train |
DataDog/integrations-core | datadog_checks_dev/datadog_checks/dev/tooling/commands/dep.py | https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_dev/datadog_checks/dev/tooling/commands/dep.py#L150-L168 | def freeze():
"""Combine all dependencies for the Agent's static environment."""
echo_waiting('Verifying collected packages...')
catalog, errors = make_catalog()
if errors:
for error in errors:
echo_failure(error)
abort()
static_file = get_agent_requirements()
echo_... | [
"def",
"freeze",
"(",
")",
":",
"echo_waiting",
"(",
"'Verifying collected packages...'",
")",
"catalog",
",",
"errors",
"=",
"make_catalog",
"(",
")",
"if",
"errors",
":",
"for",
"error",
"in",
"errors",
":",
"echo_failure",
"(",
"error",
")",
"abort",
"(",... | Combine all dependencies for the Agent's static environment. | [
"Combine",
"all",
"dependencies",
"for",
"the",
"Agent",
"s",
"static",
"environment",
"."
] | python | train |
quantopian/pyfolio | pyfolio/capacity.py | https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/capacity.py#L10-L42 | def daily_txns_with_bar_data(transactions, market_data):
"""
Sums the absolute value of shares traded in each name on each day.
Adds columns containing the closing price and total daily volume for
each day-ticker combination.
Parameters
----------
transactions : pd.DataFrame
Prices ... | [
"def",
"daily_txns_with_bar_data",
"(",
"transactions",
",",
"market_data",
")",
":",
"transactions",
".",
"index",
".",
"name",
"=",
"'date'",
"txn_daily",
"=",
"pd",
".",
"DataFrame",
"(",
"transactions",
".",
"assign",
"(",
"amount",
"=",
"abs",
"(",
"tra... | Sums the absolute value of shares traded in each name on each day.
Adds columns containing the closing price and total daily volume for
each day-ticker combination.
Parameters
----------
transactions : pd.DataFrame
Prices and amounts of executed trades. One row per trade.
- See full... | [
"Sums",
"the",
"absolute",
"value",
"of",
"shares",
"traded",
"in",
"each",
"name",
"on",
"each",
"day",
".",
"Adds",
"columns",
"containing",
"the",
"closing",
"price",
"and",
"total",
"daily",
"volume",
"for",
"each",
"day",
"-",
"ticker",
"combination",
... | python | valid |
CalebBell/fluids | fluids/control_valve.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/control_valve.py#L1183-L1473 | def control_valve_noise_g_2011(m, P1, P2, T1, rho, gamma, MW, Kv,
d, Di, t_pipe, Fd, FL, FLP=None, FP=None,
rho_pipe=7800.0, c_pipe=5000.0,
P_air=101325.0, rho_air=1.2, c_air=343.0,
An=-3.8, St... | [
"def",
"control_valve_noise_g_2011",
"(",
"m",
",",
"P1",
",",
"P2",
",",
"T1",
",",
"rho",
",",
"gamma",
",",
"MW",
",",
"Kv",
",",
"d",
",",
"Di",
",",
"t_pipe",
",",
"Fd",
",",
"FL",
",",
"FLP",
"=",
"None",
",",
"FP",
"=",
"None",
",",
"r... | r'''Calculates the sound made by a gas flowing through a control valve
according to the standard IEC 60534-8-3 (2011) [1]_.
Parameters
----------
m : float
Mass flow rate of gas through the control valve, [kg/s]
P1 : float
Inlet pressure of the gas before valves and reducers [Pa]
... | [
"r",
"Calculates",
"the",
"sound",
"made",
"by",
"a",
"gas",
"flowing",
"through",
"a",
"control",
"valve",
"according",
"to",
"the",
"standard",
"IEC",
"60534",
"-",
"8",
"-",
"3",
"(",
"2011",
")",
"[",
"1",
"]",
"_",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.