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 |
|---|---|---|---|---|---|---|---|---|
fusepy/fusepy | fusell.py | https://github.com/fusepy/fusepy/blob/5d997d6706cc0204e1b3ca679651485a7e7dda49/fusell.py#L747-L754 | def mkdir(self, req, parent, name, mode):
"""Create a directory
Valid replies:
reply_entry
reply_err
"""
self.reply_err(req, errno.EROFS) | [
"def",
"mkdir",
"(",
"self",
",",
"req",
",",
"parent",
",",
"name",
",",
"mode",
")",
":",
"self",
".",
"reply_err",
"(",
"req",
",",
"errno",
".",
"EROFS",
")"
] | Create a directory
Valid replies:
reply_entry
reply_err | [
"Create",
"a",
"directory"
] | python | train |
joestump/django-ajax | ajax/endpoints.py | https://github.com/joestump/django-ajax/blob/b71619d5c00d8e0bb990ddbea2c93cf303dc2c80/ajax/endpoints.py#L231-L233 | def _extract_value(self, value):
"""If the value is true/false/null replace with Python equivalent."""
return ModelEndpoint._value_map.get(smart_str(value).lower(), value) | [
"def",
"_extract_value",
"(",
"self",
",",
"value",
")",
":",
"return",
"ModelEndpoint",
".",
"_value_map",
".",
"get",
"(",
"smart_str",
"(",
"value",
")",
".",
"lower",
"(",
")",
",",
"value",
")"
] | If the value is true/false/null replace with Python equivalent. | [
"If",
"the",
"value",
"is",
"true",
"/",
"false",
"/",
"null",
"replace",
"with",
"Python",
"equivalent",
"."
] | python | train |
mickybart/python-atlasapi | atlasapi/specs.py | https://github.com/mickybart/python-atlasapi/blob/2962c37740998694cb55f82b375b81cc604b953e/atlasapi/specs.py#L114-L125 | def remove_roles(self, databaseName, roleNames, collectionName=None):
"""Remove multiple roles
Args:
databaseName (str): Database Name
roleNames (list of RoleSpecs): roles
Keyword Args:
collectionName (str): Collection
"""
... | [
"def",
"remove_roles",
"(",
"self",
",",
"databaseName",
",",
"roleNames",
",",
"collectionName",
"=",
"None",
")",
":",
"for",
"roleName",
"in",
"roleNames",
":",
"self",
".",
"remove_role",
"(",
"databaseName",
",",
"roleName",
",",
"collectionName",
")"
] | Remove multiple roles
Args:
databaseName (str): Database Name
roleNames (list of RoleSpecs): roles
Keyword Args:
collectionName (str): Collection | [
"Remove",
"multiple",
"roles",
"Args",
":",
"databaseName",
"(",
"str",
")",
":",
"Database",
"Name",
"roleNames",
"(",
"list",
"of",
"RoleSpecs",
")",
":",
"roles",
"Keyword",
"Args",
":",
"collectionName",
"(",
"str",
")",
":",
"Collection"
] | python | train |
tanghaibao/goatools | goatools/godag/obo_optional_attributes.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/godag/obo_optional_attributes.py#L91-L107 | def _init_compile_patterns(optional_attrs):
"""Compile search patterns for optional attributes if needed."""
attr2cmp = {}
if optional_attrs is None:
return attr2cmp
# "peptidase inhibitor complex" EXACT [GOC:bf, GOC:pr]
# "blood vessel formation from pre-existing blo... | [
"def",
"_init_compile_patterns",
"(",
"optional_attrs",
")",
":",
"attr2cmp",
"=",
"{",
"}",
"if",
"optional_attrs",
"is",
"None",
":",
"return",
"attr2cmp",
"# \"peptidase inhibitor complex\" EXACT [GOC:bf, GOC:pr]",
"# \"blood vessel formation from pre-existing blood vessels\" ... | Compile search patterns for optional attributes if needed. | [
"Compile",
"search",
"patterns",
"for",
"optional",
"attributes",
"if",
"needed",
"."
] | python | train |
chrisrink10/basilisp | src/basilisp/lang/reader.py | https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/reader.py#L636-L661 | def _read_meta(ctx: ReaderContext) -> IMeta:
"""Read metadata and apply that to the next object in the
input stream."""
start = ctx.reader.advance()
assert start == "^"
meta = _read_next_consuming_comment(ctx)
meta_map: Optional[lmap.Map[LispForm, LispForm]] = None
if isinstance(meta, symbo... | [
"def",
"_read_meta",
"(",
"ctx",
":",
"ReaderContext",
")",
"->",
"IMeta",
":",
"start",
"=",
"ctx",
".",
"reader",
".",
"advance",
"(",
")",
"assert",
"start",
"==",
"\"^\"",
"meta",
"=",
"_read_next_consuming_comment",
"(",
"ctx",
")",
"meta_map",
":",
... | Read metadata and apply that to the next object in the
input stream. | [
"Read",
"metadata",
"and",
"apply",
"that",
"to",
"the",
"next",
"object",
"in",
"the",
"input",
"stream",
"."
] | python | test |
zagaran/mongobackup | mongobackup/backups.py | https://github.com/zagaran/mongobackup/blob/d090d0cca44ecd066974c4de80edca5f26b7eeea/mongobackup/backups.py#L155-L176 | def mongorestore(mongo_user, mongo_password, backup_directory_path, drop_database=False, silent=False):
""" Warning: Setting drop_database to True will drop the ENTIRE
CURRENTLY RUNNING DATABASE before restoring.
Mongorestore requires a running mongod process, in addition the provided
... | [
"def",
"mongorestore",
"(",
"mongo_user",
",",
"mongo_password",
",",
"backup_directory_path",
",",
"drop_database",
"=",
"False",
",",
"silent",
"=",
"False",
")",
":",
"if",
"not",
"path",
".",
"exists",
"(",
"backup_directory_path",
")",
":",
"raise",
"Exce... | Warning: Setting drop_database to True will drop the ENTIRE
CURRENTLY RUNNING DATABASE before restoring.
Mongorestore requires a running mongod process, in addition the provided
user must have restore permissions for the database. A mongolia superuser
will have more than a... | [
"Warning",
":",
"Setting",
"drop_database",
"to",
"True",
"will",
"drop",
"the",
"ENTIRE",
"CURRENTLY",
"RUNNING",
"DATABASE",
"before",
"restoring",
".",
"Mongorestore",
"requires",
"a",
"running",
"mongod",
"process",
"in",
"addition",
"the",
"provided",
"user",... | python | train |
MuhammedHasan/sklearn_utils | sklearn_utils/utils/data_utils.py | https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/utils/data_utils.py#L62-L71 | def check_reference_label(y, ref_label):
'''
:param list y: label
:param ref_label: reference label
'''
set_y = set(y)
if ref_label not in set_y:
raise ValueError('There is not reference label in dataset. '
"Reference label: '%s' "
'Label... | [
"def",
"check_reference_label",
"(",
"y",
",",
"ref_label",
")",
":",
"set_y",
"=",
"set",
"(",
"y",
")",
"if",
"ref_label",
"not",
"in",
"set_y",
":",
"raise",
"ValueError",
"(",
"'There is not reference label in dataset. '",
"\"Reference label: '%s' \"",
"'Labels ... | :param list y: label
:param ref_label: reference label | [
":",
"param",
"list",
"y",
":",
"label",
":",
"param",
"ref_label",
":",
"reference",
"label"
] | python | test |
TrafficSenseMSD/SumoTools | traci/_poi.py | https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/traci/_poi.py#L77-L86 | def setColor(self, poiID, color):
"""setColor(string, (integer, integer, integer, integer)) -> None
Sets the rgba color of the poi.
"""
self._connection._beginMessage(
tc.CMD_SET_POI_VARIABLE, tc.VAR_COLOR, poiID, 1 + 1 + 1 + 1 + 1)
self._connection._string += struct... | [
"def",
"setColor",
"(",
"self",
",",
"poiID",
",",
"color",
")",
":",
"self",
".",
"_connection",
".",
"_beginMessage",
"(",
"tc",
".",
"CMD_SET_POI_VARIABLE",
",",
"tc",
".",
"VAR_COLOR",
",",
"poiID",
",",
"1",
"+",
"1",
"+",
"1",
"+",
"1",
"+",
... | setColor(string, (integer, integer, integer, integer)) -> None
Sets the rgba color of the poi. | [
"setColor",
"(",
"string",
"(",
"integer",
"integer",
"integer",
"integer",
"))",
"-",
">",
"None"
] | python | train |
contentful/contentful-management.py | contentful_management/content_type.py | https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/content_type.py#L107-L121 | def editor_interfaces(self):
"""
Provides access to editor interface management methods for the given content type.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface
:return: :class:`ContentTypeEditorInterfacesProxy... | [
"def",
"editor_interfaces",
"(",
"self",
")",
":",
"return",
"ContentTypeEditorInterfacesProxy",
"(",
"self",
".",
"_client",
",",
"self",
".",
"space",
".",
"id",
",",
"self",
".",
"_environment_id",
",",
"self",
".",
"id",
")"
] | Provides access to editor interface management methods for the given content type.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/editor-interface
:return: :class:`ContentTypeEditorInterfacesProxy <contentful_management.content_type_editor_inter... | [
"Provides",
"access",
"to",
"editor",
"interface",
"management",
"methods",
"for",
"the",
"given",
"content",
"type",
"."
] | python | train |
Damgaard/PyImgur | pyimgur/__init__.py | https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L476-L485 | def downvote(self):
"""
Dislike this.
A downvote will replace a neutral vote or an upvote. Downvoting
something the authenticated user has already downvoted will set the
vote to neutral.
"""
url = self._imgur._base_url + "/3/gallery/{0}/vote/down".format(self.id)... | [
"def",
"downvote",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_imgur",
".",
"_base_url",
"+",
"\"/3/gallery/{0}/vote/down\"",
".",
"format",
"(",
"self",
".",
"id",
")",
"return",
"self",
".",
"_imgur",
".",
"_send_request",
"(",
"url",
",",
"needs... | Dislike this.
A downvote will replace a neutral vote or an upvote. Downvoting
something the authenticated user has already downvoted will set the
vote to neutral. | [
"Dislike",
"this",
"."
] | python | train |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/system.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/system.py#L135-L162 | def find_window(className = None, windowName = None):
"""
Find the first top-level window in the current desktop to match the
given class name and/or window name. If neither are provided any
top-level window will match.
@see: L{get_window_at}
@type className: str
... | [
"def",
"find_window",
"(",
"className",
"=",
"None",
",",
"windowName",
"=",
"None",
")",
":",
"# I'd love to reverse the order of the parameters",
"# but that might create some confusion. :(",
"hWnd",
"=",
"win32",
".",
"FindWindow",
"(",
"className",
",",
"windowName",
... | Find the first top-level window in the current desktop to match the
given class name and/or window name. If neither are provided any
top-level window will match.
@see: L{get_window_at}
@type className: str
@param className: (Optional) Class name of the window to find.
... | [
"Find",
"the",
"first",
"top",
"-",
"level",
"window",
"in",
"the",
"current",
"desktop",
"to",
"match",
"the",
"given",
"class",
"name",
"and",
"/",
"or",
"window",
"name",
".",
"If",
"neither",
"are",
"provided",
"any",
"top",
"-",
"level",
"window",
... | python | train |
fermiPy/fermipy | fermipy/diffuse/catalog_src_manager.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/catalog_src_manager.py#L53-L67 | def select_sources(cat_table, cuts):
"""Select only rows passing a set of cuts from catalog table
"""
nsrc = len(cat_table)
full_mask = np.ones((nsrc), bool)
for cut in cuts:
if cut == 'mask_extended':
full_mask *= mask_extended(cat_table)
elif cut == 'select_extended':
... | [
"def",
"select_sources",
"(",
"cat_table",
",",
"cuts",
")",
":",
"nsrc",
"=",
"len",
"(",
"cat_table",
")",
"full_mask",
"=",
"np",
".",
"ones",
"(",
"(",
"nsrc",
")",
",",
"bool",
")",
"for",
"cut",
"in",
"cuts",
":",
"if",
"cut",
"==",
"'mask_ex... | Select only rows passing a set of cuts from catalog table | [
"Select",
"only",
"rows",
"passing",
"a",
"set",
"of",
"cuts",
"from",
"catalog",
"table"
] | python | train |
J535D165/recordlinkage | recordlinkage/api.py | https://github.com/J535D165/recordlinkage/blob/87a5f4af904e0834047cd07ff1c70146b1e6d693/recordlinkage/api.py#L58-L72 | def sortedneighbourhood(self, *args, **kwargs):
"""Add a Sorted Neighbourhood Index.
Shortcut of :class:`recordlinkage.index.SortedNeighbourhood`::
from recordlinkage.index import SortedNeighbourhood
indexer = recordlinkage.Index()
indexer.add(SortedNeighbourhood()... | [
"def",
"sortedneighbourhood",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"indexer",
"=",
"SortedNeighbourhood",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"add",
"(",
"indexer",
")",
"return",
"self"
] | Add a Sorted Neighbourhood Index.
Shortcut of :class:`recordlinkage.index.SortedNeighbourhood`::
from recordlinkage.index import SortedNeighbourhood
indexer = recordlinkage.Index()
indexer.add(SortedNeighbourhood()) | [
"Add",
"a",
"Sorted",
"Neighbourhood",
"Index",
"."
] | python | train |
LuminosoInsight/python-ftfy | ftfy/fixes.py | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/fixes.py#L642-L664 | def fix_partial_utf8_punct_in_1252(text):
"""
Fix particular characters that seem to be found in the wild encoded in
UTF-8 and decoded in Latin-1 or Windows-1252, even when this fix can't be
consistently applied.
One form of inconsistency we need to deal with is that some character might
be fro... | [
"def",
"fix_partial_utf8_punct_in_1252",
"(",
"text",
")",
":",
"def",
"latin1_to_w1252",
"(",
"match",
")",
":",
"\"The function to apply when this regex matches.\"",
"return",
"match",
".",
"group",
"(",
"0",
")",
".",
"encode",
"(",
"'latin-1'",
")",
".",
"deco... | Fix particular characters that seem to be found in the wild encoded in
UTF-8 and decoded in Latin-1 or Windows-1252, even when this fix can't be
consistently applied.
One form of inconsistency we need to deal with is that some character might
be from the Latin-1 C1 control character set, while others a... | [
"Fix",
"particular",
"characters",
"that",
"seem",
"to",
"be",
"found",
"in",
"the",
"wild",
"encoded",
"in",
"UTF",
"-",
"8",
"and",
"decoded",
"in",
"Latin",
"-",
"1",
"or",
"Windows",
"-",
"1252",
"even",
"when",
"this",
"fix",
"can",
"t",
"be",
"... | python | train |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/publisher/plos.py | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/publisher/plos.py#L298-L348 | def make_heading_abstracts(self, heading_div):
"""
An article may contain data for various kinds of abstracts. This method
works on those that are included in the Heading. This is displayed
after the Authors and Affiliations.
Metadata element, content derived from FrontMatter
... | [
"def",
"make_heading_abstracts",
"(",
"self",
",",
"heading_div",
")",
":",
"for",
"abstract",
"in",
"self",
".",
"article",
".",
"root",
".",
"xpath",
"(",
"'./front/article-meta/abstract'",
")",
":",
"#Make a copy of the abstract",
"abstract_copy",
"=",
"deepcopy"... | An article may contain data for various kinds of abstracts. This method
works on those that are included in the Heading. This is displayed
after the Authors and Affiliations.
Metadata element, content derived from FrontMatter | [
"An",
"article",
"may",
"contain",
"data",
"for",
"various",
"kinds",
"of",
"abstracts",
".",
"This",
"method",
"works",
"on",
"those",
"that",
"are",
"included",
"in",
"the",
"Heading",
".",
"This",
"is",
"displayed",
"after",
"the",
"Authors",
"and",
"Af... | python | train |
chaoss/grimoirelab-perceval | perceval/backends/core/meetup.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/meetup.py#L124-L168 | def fetch_items(self, category, **kwargs):
"""Fetch the events
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
from_date = kwargs['from_date']
to_date = kwargs['to_date']
logger.info("F... | [
"def",
"fetch_items",
"(",
"self",
",",
"category",
",",
"*",
"*",
"kwargs",
")",
":",
"from_date",
"=",
"kwargs",
"[",
"'from_date'",
"]",
"to_date",
"=",
"kwargs",
"[",
"'to_date'",
"]",
"logger",
".",
"info",
"(",
"\"Fetching events of '%s' group from %s to... | Fetch the events
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items | [
"Fetch",
"the",
"events"
] | python | test |
ibm-watson-iot/iot-python | tmp/src/things/things.py | https://github.com/ibm-watson-iot/iot-python/blob/195f05adce3fba4ec997017e41e02ebd85c0c4cc/tmp/src/things/things.py#L1468-L1488 | def getLogicalInterfacesOnThingType(self, thingTypeId, draft=False):
"""
Get all logical interfaces for a thing type.
Parameters:
- thingTypeId (string)
- draft (boolean)
Returns:
- list of logical interface ids
- HTTP response object
T... | [
"def",
"getLogicalInterfacesOnThingType",
"(",
"self",
",",
"thingTypeId",
",",
"draft",
"=",
"False",
")",
":",
"if",
"draft",
":",
"req",
"=",
"ApiClient",
".",
"allThingTypeLogicalInterfacesUrl",
"%",
"(",
"self",
".",
"host",
",",
"\"/draft\"",
",",
"thing... | Get all logical interfaces for a thing type.
Parameters:
- thingTypeId (string)
- draft (boolean)
Returns:
- list of logical interface ids
- HTTP response object
Throws APIException on failure. | [
"Get",
"all",
"logical",
"interfaces",
"for",
"a",
"thing",
"type",
".",
"Parameters",
":",
"-",
"thingTypeId",
"(",
"string",
")",
"-",
"draft",
"(",
"boolean",
")",
"Returns",
":",
"-",
"list",
"of",
"logical",
"interface",
"ids",
"-",
"HTTP",
"respons... | python | test |
ioos/compliance-checker | compliance_checker/cf/cf.py | https://github.com/ioos/compliance-checker/blob/ee89c27b0daade58812489a2da3aa3b6859eafd9/compliance_checker/cf/cf.py#L398-L419 | def check_data_types(self, ds):
'''
Checks the data type of all netCDF variables to ensure they are valid
data types under CF.
CF §2.2 The netCDF data types char, byte, short, int, float or real, and
double are all acceptable
:param netCDF4.Dataset ds: An open netCDF da... | [
"def",
"check_data_types",
"(",
"self",
",",
"ds",
")",
":",
"fails",
"=",
"[",
"]",
"total",
"=",
"len",
"(",
"ds",
".",
"variables",
")",
"for",
"k",
",",
"v",
"in",
"ds",
".",
"variables",
".",
"items",
"(",
")",
":",
"if",
"(",
"v",
".",
... | Checks the data type of all netCDF variables to ensure they are valid
data types under CF.
CF §2.2 The netCDF data types char, byte, short, int, float or real, and
double are all acceptable
:param netCDF4.Dataset ds: An open netCDF dataset
:rtype: compliance_checker.base.Result | [
"Checks",
"the",
"data",
"type",
"of",
"all",
"netCDF",
"variables",
"to",
"ensure",
"they",
"are",
"valid",
"data",
"types",
"under",
"CF",
"."
] | python | train |
PyCQA/pylint | pylint/reporters/ureports/nodes.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/reporters/ureports/nodes.py#L30-L33 | def insert(self, index, child):
"""insert a child node"""
self.children.insert(index, child)
child.parent = self | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"child",
")",
":",
"self",
".",
"children",
".",
"insert",
"(",
"index",
",",
"child",
")",
"child",
".",
"parent",
"=",
"self"
] | insert a child node | [
"insert",
"a",
"child",
"node"
] | python | test |
wdecoster/nanoget | nanoget/extraction_functions.py | https://github.com/wdecoster/nanoget/blob/fb7306220e261849b96785fab02dd2f35a0e3b60/nanoget/extraction_functions.py#L142-L168 | def process_bam(bam, **kwargs):
"""Combines metrics from bam after extraction.
Processing function: calls pool of worker functions
to extract from a bam file the following metrics:
-lengths
-aligned lengths
-qualities
-aligned qualities
-mapping qualities
-edit distances to the refe... | [
"def",
"process_bam",
"(",
"bam",
",",
"*",
"*",
"kwargs",
")",
":",
"logging",
".",
"info",
"(",
"\"Nanoget: Starting to collect statistics from bam file {}.\"",
".",
"format",
"(",
"bam",
")",
")",
"samfile",
"=",
"check_bam",
"(",
"bam",
")",
"chromosomes",
... | Combines metrics from bam after extraction.
Processing function: calls pool of worker functions
to extract from a bam file the following metrics:
-lengths
-aligned lengths
-qualities
-aligned qualities
-mapping qualities
-edit distances to the reference genome scaled by read length
... | [
"Combines",
"metrics",
"from",
"bam",
"after",
"extraction",
"."
] | python | train |
ayoungprogrammer/Lango | lango/matcher.py | https://github.com/ayoungprogrammer/Lango/blob/0c4284c153abc2d8de4b03a86731bd84385e6afa/lango/matcher.py#L274-L288 | def get_raw(tree):
"""Get the exact words in lowercase in the tree object.
Args:
tree (Tree): Parsed tree structure
Returns:
Resulting string of tree ``(Ex: "The red car")``
"""
if isinstance(tree, Tree):
words = []
for child in tree:
words.append(get... | [
"def",
"get_raw",
"(",
"tree",
")",
":",
"if",
"isinstance",
"(",
"tree",
",",
"Tree",
")",
":",
"words",
"=",
"[",
"]",
"for",
"child",
"in",
"tree",
":",
"words",
".",
"append",
"(",
"get_raw",
"(",
"child",
")",
")",
"return",
"' '",
".",
"joi... | Get the exact words in lowercase in the tree object.
Args:
tree (Tree): Parsed tree structure
Returns:
Resulting string of tree ``(Ex: "The red car")`` | [
"Get",
"the",
"exact",
"words",
"in",
"lowercase",
"in",
"the",
"tree",
"object",
".",
"Args",
":",
"tree",
"(",
"Tree",
")",
":",
"Parsed",
"tree",
"structure",
"Returns",
":",
"Resulting",
"string",
"of",
"tree",
"(",
"Ex",
":",
"The",
"red",
"car",
... | python | train |
ph4r05/monero-serialize | monero_serialize/xmrboost.py | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrboost.py#L514-L536 | async def dump_tuple(self, elem, elem_type, params=None):
"""
Dumps tuple of elements to the writer.
:param elem:
:param elem_type:
:param params:
:return:
"""
if len(elem) != len(elem_type.f_specs()):
raise ValueError('Fixed size tuple has no... | [
"async",
"def",
"dump_tuple",
"(",
"self",
",",
"elem",
",",
"elem_type",
",",
"params",
"=",
"None",
")",
":",
"if",
"len",
"(",
"elem",
")",
"!=",
"len",
"(",
"elem_type",
".",
"f_specs",
"(",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Fixed size... | Dumps tuple of elements to the writer.
:param elem:
:param elem_type:
:param params:
:return: | [
"Dumps",
"tuple",
"of",
"elements",
"to",
"the",
"writer",
"."
] | python | train |
HewlettPackard/python-hpOneView | hpOneView/resources/uncategorized/unmanaged_devices.py | https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/uncategorized/unmanaged_devices.py#L160-L174 | def get_environmental_configuration(self, id_or_uri):
"""
Returns a description of the environmental configuration (supported feature set, calibrated minimum & maximum
power, location & dimensions, ...) of the resource.
Args:
id_or_uri:
Can be either the Unma... | [
"def",
"get_environmental_configuration",
"(",
"self",
",",
"id_or_uri",
")",
":",
"uri",
"=",
"self",
".",
"_client",
".",
"build_uri",
"(",
"id_or_uri",
")",
"+",
"\"/environmentalConfiguration\"",
"return",
"self",
".",
"_client",
".",
"get",
"(",
"uri",
")... | Returns a description of the environmental configuration (supported feature set, calibrated minimum & maximum
power, location & dimensions, ...) of the resource.
Args:
id_or_uri:
Can be either the Unmanaged Device id or the uri
Returns:
dict:
... | [
"Returns",
"a",
"description",
"of",
"the",
"environmental",
"configuration",
"(",
"supported",
"feature",
"set",
"calibrated",
"minimum",
"&",
"maximum",
"power",
"location",
"&",
"dimensions",
"...",
")",
"of",
"the",
"resource",
"."
] | python | train |
ambv/flake8-pyi | pyi.py | https://github.com/ambv/flake8-pyi/blob/19e8028b44b6305dff1bfb9a51a23a029c546993/pyi.py#L45-L66 | def ANNASSIGN(self, node):
"""
Annotated assignments don't have annotations evaluated on function
scope, hence the custom implementation. Compared to the pyflakes
version, we defer evaluation of the annotations (and values on
module level).
"""
if node.value:
... | [
"def",
"ANNASSIGN",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"value",
":",
"# Only bind the *target* if the assignment has value.",
"# Otherwise it's not really ast.Store and shouldn't silence",
"# UndefinedLocal warnings.",
"self",
".",
"handleNode",
"(",
"node... | Annotated assignments don't have annotations evaluated on function
scope, hence the custom implementation. Compared to the pyflakes
version, we defer evaluation of the annotations (and values on
module level). | [
"Annotated",
"assignments",
"don",
"t",
"have",
"annotations",
"evaluated",
"on",
"function",
"scope",
"hence",
"the",
"custom",
"implementation",
".",
"Compared",
"to",
"the",
"pyflakes",
"version",
"we",
"defer",
"evaluation",
"of",
"the",
"annotations",
"(",
... | python | train |
quantumlib/Cirq | cirq/contrib/acquaintance/executor.py | https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/contrib/acquaintance/executor.py#L184-L197 | def canonicalize_gates(gates: LogicalGates
) -> Dict[frozenset, LogicalGates]:
"""Canonicalizes a set of gates by the qubits they act on.
Takes a set of gates specified by ordered sequences of logical
indices, and groups those that act on the same qubits regardless of
order."""
... | [
"def",
"canonicalize_gates",
"(",
"gates",
":",
"LogicalGates",
")",
"->",
"Dict",
"[",
"frozenset",
",",
"LogicalGates",
"]",
":",
"canonicalized_gates",
"=",
"defaultdict",
"(",
"dict",
")",
"# type: DefaultDict[frozenset, LogicalGates]",
"for",
"indices",
",",
"g... | Canonicalizes a set of gates by the qubits they act on.
Takes a set of gates specified by ordered sequences of logical
indices, and groups those that act on the same qubits regardless of
order. | [
"Canonicalizes",
"a",
"set",
"of",
"gates",
"by",
"the",
"qubits",
"they",
"act",
"on",
"."
] | python | train |
csparpa/pyowm | pyowm/weatherapi25/owm25.py | https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/weatherapi25/owm25.py#L822-L874 | def weather_history_at_coords(self, lat, lon, start=None, end=None):
"""
Queries the OWM Weather API for weather history for the specified at the
specified geographic (eg: 51.503614, -0.107331). A list of *Weather*
objects is returned. It is possible to query for weather history in a
... | [
"def",
"weather_history_at_coords",
"(",
"self",
",",
"lat",
",",
"lon",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"geo",
".",
"assert_is_lon",
"(",
"lon",
")",
"geo",
".",
"assert_is_lat",
"(",
"lat",
")",
"params",
"=",
"{",
"'l... | Queries the OWM Weather API for weather history for the specified at the
specified geographic (eg: 51.503614, -0.107331). A list of *Weather*
objects is returned. It is possible to query for weather history in a
closed time period, whose boundaries can be passed as optional
parameters.
... | [
"Queries",
"the",
"OWM",
"Weather",
"API",
"for",
"weather",
"history",
"for",
"the",
"specified",
"at",
"the",
"specified",
"geographic",
"(",
"eg",
":",
"51",
".",
"503614",
"-",
"0",
".",
"107331",
")",
".",
"A",
"list",
"of",
"*",
"Weather",
"*",
... | python | train |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/security/security_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/security/security_client.py#L150-L177 | def has_permissions(self, security_namespace_id, permissions=None, tokens=None, always_allow_administrators=None, delimiter=None):
"""HasPermissions.
Evaluates whether the caller has the specified permissions on the specified set of security tokens.
:param str security_namespace_id: Security nam... | [
"def",
"has_permissions",
"(",
"self",
",",
"security_namespace_id",
",",
"permissions",
"=",
"None",
",",
"tokens",
"=",
"None",
",",
"always_allow_administrators",
"=",
"None",
",",
"delimiter",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"... | HasPermissions.
Evaluates whether the caller has the specified permissions on the specified set of security tokens.
:param str security_namespace_id: Security namespace identifier.
:param int permissions: Permissions to evaluate.
:param str tokens: One or more security tokens to evaluate... | [
"HasPermissions",
".",
"Evaluates",
"whether",
"the",
"caller",
"has",
"the",
"specified",
"permissions",
"on",
"the",
"specified",
"set",
"of",
"security",
"tokens",
".",
":",
"param",
"str",
"security_namespace_id",
":",
"Security",
"namespace",
"identifier",
".... | python | train |
mozilla/configman | configman/converters.py | https://github.com/mozilla/configman/blob/83159fed61cc4cbbe5a4a6a00d3acad8a0c39c96/configman/converters.py#L127-L133 | def str_to_boolean(input_str):
""" a conversion function for boolean
"""
if not isinstance(input_str, six.string_types):
raise ValueError(input_str)
input_str = str_quote_stripper(input_str)
return input_str.lower() in ("true", "t", "1", "y", "yes") | [
"def",
"str_to_boolean",
"(",
"input_str",
")",
":",
"if",
"not",
"isinstance",
"(",
"input_str",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"input_str",
")",
"input_str",
"=",
"str_quote_stripper",
"(",
"input_str",
")",
"return",
... | a conversion function for boolean | [
"a",
"conversion",
"function",
"for",
"boolean"
] | python | train |
mushkevych/scheduler | synergy/db/manager/db_manager.py | https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/db/manager/db_manager.py#L58-L95 | def reset_db():
""" drops the *scheduler* database, resets schema """
logger = get_logger(PROCESS_SCHEDULER)
logger.info('Starting *scheduler* DB reset')
ds = ds_manager.ds_factory(logger)
ds._db_client.drop_database(settings.settings['mongo_db_name'])
logger.info('*scheduler* db has been dropp... | [
"def",
"reset_db",
"(",
")",
":",
"logger",
"=",
"get_logger",
"(",
"PROCESS_SCHEDULER",
")",
"logger",
".",
"info",
"(",
"'Starting *scheduler* DB reset'",
")",
"ds",
"=",
"ds_manager",
".",
"ds_factory",
"(",
"logger",
")",
"ds",
".",
"_db_client",
".",
"d... | drops the *scheduler* database, resets schema | [
"drops",
"the",
"*",
"scheduler",
"*",
"database",
"resets",
"schema"
] | python | train |
brocade/pynos | pynos/versions/ver_7/ver_7_1_0/yang/brocade_lldp_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_7/ver_7_1_0/yang/brocade_lldp_ext.py#L284-L300 | def get_lldp_neighbor_detail_output_lldp_neighbor_detail_dead_interval(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail")
config = get_lldp_neighbor_detail
output = ET.SubElement(get_... | [
"def",
"get_lldp_neighbor_detail_output_lldp_neighbor_detail_dead_interval",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_lldp_neighbor_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_lldp_neighbor_d... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
ynop/audiomate | audiomate/utils/naming.py | https://github.com/ynop/audiomate/blob/61727920b23a708293c3d526fa3000d4de9c6c21/audiomate/utils/naming.py#L33-L49 | def generate_name(length=15, not_in=None):
"""
Generates a random string of lowercase letters with the given length.
Parameters:
length (int): Length of the string to output.
not_in (list): Only return a string not in the given iterator.
Returns:
str: A new name thats not in th... | [
"def",
"generate_name",
"(",
"length",
"=",
"15",
",",
"not_in",
"=",
"None",
")",
":",
"value",
"=",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"string",
".",
"ascii_lowercase",
")",
"for",
"i",
"in",
"range",
"(",
"length",
")",
")",
"... | Generates a random string of lowercase letters with the given length.
Parameters:
length (int): Length of the string to output.
not_in (list): Only return a string not in the given iterator.
Returns:
str: A new name thats not in the given list. | [
"Generates",
"a",
"random",
"string",
"of",
"lowercase",
"letters",
"with",
"the",
"given",
"length",
"."
] | python | train |
zerotk/easyfs | zerotk/easyfs/_easyfs.py | https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L954-L989 | def ListFiles(directory):
'''
Lists the files in the given directory
:type directory: unicode | unicode
:param directory:
A directory or URL
:rtype: list(unicode) | list(unicode)
:returns:
List of filenames/directories found in the given directory.
Returns None if the g... | [
"def",
"ListFiles",
"(",
"directory",
")",
":",
"from",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
"import",
"urlparse",
"directory_url",
"=",
"urlparse",
"(",
"directory",
")",
"# Handle local",
"if",
"_UrlIsLocal",
"(",
"directory_url",
")",
":",
"i... | Lists the files in the given directory
:type directory: unicode | unicode
:param directory:
A directory or URL
:rtype: list(unicode) | list(unicode)
:returns:
List of filenames/directories found in the given directory.
Returns None if the given directory does not exists.
... | [
"Lists",
"the",
"files",
"in",
"the",
"given",
"directory"
] | python | valid |
pyca/pynacl | src/nacl/bindings/crypto_shorthash.py | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/bindings/crypto_shorthash.py#L46-L62 | def crypto_shorthash_siphashx24(data, key):
"""Compute a fast, cryptographic quality, keyed hash of the input data
:param data:
:type data: bytes
:param key: len(key) must be equal to
:py:data:`.XKEYBYTES` (16)
:type key: bytes
"""
if len(key) != XKEYBYTES:
raise exc... | [
"def",
"crypto_shorthash_siphashx24",
"(",
"data",
",",
"key",
")",
":",
"if",
"len",
"(",
"key",
")",
"!=",
"XKEYBYTES",
":",
"raise",
"exc",
".",
"ValueError",
"(",
"\"Key length must be exactly {0} bytes\"",
".",
"format",
"(",
"XKEYBYTES",
")",
")",
"diges... | Compute a fast, cryptographic quality, keyed hash of the input data
:param data:
:type data: bytes
:param key: len(key) must be equal to
:py:data:`.XKEYBYTES` (16)
:type key: bytes | [
"Compute",
"a",
"fast",
"cryptographic",
"quality",
"keyed",
"hash",
"of",
"the",
"input",
"data"
] | python | train |
rocky/python-spark | spark_parser/spark.py | https://github.com/rocky/python-spark/blob/8899954bcf0e166726841a43e87c23790eb3441f/spark_parser/spark.py#L267-L303 | def remove_rules(self, doc):
"""Remove a grammar rules from _self.rules_, _self.rule2func_,
and _self.rule2name_
"""
# remove blanks lines and comment lines, e.g. lines starting with "#"
doc = os.linesep.join([s for s in doc.splitlines() if s and not re.match("^\s*#", s)])
... | [
"def",
"remove_rules",
"(",
"self",
",",
"doc",
")",
":",
"# remove blanks lines and comment lines, e.g. lines starting with \"#\"",
"doc",
"=",
"os",
".",
"linesep",
".",
"join",
"(",
"[",
"s",
"for",
"s",
"in",
"doc",
".",
"splitlines",
"(",
")",
"if",
"s",
... | Remove a grammar rules from _self.rules_, _self.rule2func_,
and _self.rule2name_ | [
"Remove",
"a",
"grammar",
"rules",
"from",
"_self",
".",
"rules_",
"_self",
".",
"rule2func_",
"and",
"_self",
".",
"rule2name_"
] | python | train |
samfoo/vt102 | vt102/__init__.py | https://github.com/samfoo/vt102/blob/ff5be883bc9a880a422b09bb87b210d7c408cf2c/vt102/__init__.py#L307-L325 | def add_event_listener(self, event, function):
"""
Add an event listen for a particular event. Depending on the event
there may or may not be parameters passed to function. Most escape
streams also allow for an empty set of parameters (with a default
value). Providing these defa... | [
"def",
"add_event_listener",
"(",
"self",
",",
"event",
",",
"function",
")",
":",
"if",
"event",
"not",
"in",
"self",
".",
"listeners",
":",
"self",
".",
"listeners",
"[",
"event",
"]",
"=",
"[",
"]",
"self",
".",
"listeners",
"[",
"event",
"]",
"."... | Add an event listen for a particular event. Depending on the event
there may or may not be parameters passed to function. Most escape
streams also allow for an empty set of parameters (with a default
value). Providing these default values and accepting variable arguments
is the responsi... | [
"Add",
"an",
"event",
"listen",
"for",
"a",
"particular",
"event",
".",
"Depending",
"on",
"the",
"event",
"there",
"may",
"or",
"may",
"not",
"be",
"parameters",
"passed",
"to",
"function",
".",
"Most",
"escape",
"streams",
"also",
"allow",
"for",
"an",
... | python | train |
pygobject/pgi | pgi/overrides/Gdk.py | https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/overrides/Gdk.py#L74-L79 | def from_floats(red, green, blue):
"""Return a new Color object from red/green/blue values from 0.0 to 1.0."""
return Color(int(red * Color.MAX_VALUE),
int(green * Color.MAX_VALUE),
int(blue * Color.MAX_VALUE)) | [
"def",
"from_floats",
"(",
"red",
",",
"green",
",",
"blue",
")",
":",
"return",
"Color",
"(",
"int",
"(",
"red",
"*",
"Color",
".",
"MAX_VALUE",
")",
",",
"int",
"(",
"green",
"*",
"Color",
".",
"MAX_VALUE",
")",
",",
"int",
"(",
"blue",
"*",
"C... | Return a new Color object from red/green/blue values from 0.0 to 1.0. | [
"Return",
"a",
"new",
"Color",
"object",
"from",
"red",
"/",
"green",
"/",
"blue",
"values",
"from",
"0",
".",
"0",
"to",
"1",
".",
"0",
"."
] | python | train |
caseyjlaw/rtpipe | rtpipe/interactive.py | https://github.com/caseyjlaw/rtpipe/blob/ac33e4332cf215091a63afbb3137850876d73ec0/rtpipe/interactive.py#L575-L588 | def calcontime(data, inds=None):
""" Given indices of good times, calculate total time per scan with indices. """
if not inds:
inds = range(len(data['time']))
logger.info('No indices provided. Assuming all are valid.')
scans = set([data['scan'][i] for i in inds])
total = 0.
for sca... | [
"def",
"calcontime",
"(",
"data",
",",
"inds",
"=",
"None",
")",
":",
"if",
"not",
"inds",
":",
"inds",
"=",
"range",
"(",
"len",
"(",
"data",
"[",
"'time'",
"]",
")",
")",
"logger",
".",
"info",
"(",
"'No indices provided. Assuming all are valid.'",
")"... | Given indices of good times, calculate total time per scan with indices. | [
"Given",
"indices",
"of",
"good",
"times",
"calculate",
"total",
"time",
"per",
"scan",
"with",
"indices",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_aaa.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_aaa.py#L577-L585 | def password_attributes_admin_lockout_enable(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
password_attributes = ET.SubElement(config, "password-attributes", xmlns="urn:brocade.com:mgmt:brocade-aaa")
admin_lockout_enable = ET.SubElement(password_attrib... | [
"def",
"password_attributes_admin_lockout_enable",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"password_attributes",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"password-attributes\"",
",... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
phaethon/kamene | kamene/contrib/gsm_um.py | https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/contrib/gsm_um.py#L1335-L1341 | def authenticationResponse():
"""AUTHENTICATION RESPONSE Section 9.2.3"""
a = TpPd(pd=0x5)
b = MessageType(mesType=0x14) # 00010100
c = AuthenticationParameterSRES()
packet = a / b / c
return packet | [
"def",
"authenticationResponse",
"(",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"0x5",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"0x14",
")",
"# 00010100",
"c",
"=",
"AuthenticationParameterSRES",
"(",
")",
"packet",
"=",
"a",
"/",
"b",
"/",... | AUTHENTICATION RESPONSE Section 9.2.3 | [
"AUTHENTICATION",
"RESPONSE",
"Section",
"9",
".",
"2",
".",
"3"
] | python | train |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsHandle_Edit.py | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsHandle_Edit.py#L1064-L1109 | def StartGuiSession(self):
""" Launches the UCSM GUI via specific UCS handle. """
from UcsBase import WriteUcsWarning, UcsUtils, UcsValidationException
import urllib, tempfile, fileinput, os, subprocess, platform
osSupport = ["Windows", "Linux", "Microsoft"]
if platform.system() not in osSupport:
raise U... | [
"def",
"StartGuiSession",
"(",
"self",
")",
":",
"from",
"UcsBase",
"import",
"WriteUcsWarning",
",",
"UcsUtils",
",",
"UcsValidationException",
"import",
"urllib",
",",
"tempfile",
",",
"fileinput",
",",
"os",
",",
"subprocess",
",",
"platform",
"osSupport",
"=... | Launches the UCSM GUI via specific UCS handle. | [
"Launches",
"the",
"UCSM",
"GUI",
"via",
"specific",
"UCS",
"handle",
"."
] | python | train |
softlayer/softlayer-python | SoftLayer/managers/load_balancer.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/load_balancer.py#L73-L86 | def _get_location(self, datacenter_name):
"""Returns the location of the specified datacenter.
:param string datacenter_name: The datacenter to create
the loadbalancer in
:returns: the location id of the given datacenter
"""
datacenters =... | [
"def",
"_get_location",
"(",
"self",
",",
"datacenter_name",
")",
":",
"datacenters",
"=",
"self",
".",
"client",
"[",
"'Location'",
"]",
".",
"getDataCenters",
"(",
")",
"for",
"datacenter",
"in",
"datacenters",
":",
"if",
"datacenter",
"[",
"'name'",
"]",
... | Returns the location of the specified datacenter.
:param string datacenter_name: The datacenter to create
the loadbalancer in
:returns: the location id of the given datacenter | [
"Returns",
"the",
"location",
"of",
"the",
"specified",
"datacenter",
"."
] | python | train |
gholt/swiftly | swiftly/cli/iomanager.py | https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/iomanager.py#L221-L251 | def with_stdin(self, os_path=None, skip_sub_command=False,
disk_closed_callback=None):
"""
A context manager yielding a stdin-suitable file-like object
based on the optional os_path and optionally skipping any
configured sub-command.
:param os_path: Optional p... | [
"def",
"with_stdin",
"(",
"self",
",",
"os_path",
"=",
"None",
",",
"skip_sub_command",
"=",
"False",
",",
"disk_closed_callback",
"=",
"None",
")",
":",
"sub_command",
"=",
"None",
"if",
"skip_sub_command",
"else",
"self",
".",
"stdin_sub_command",
"inn",
","... | A context manager yielding a stdin-suitable file-like object
based on the optional os_path and optionally skipping any
configured sub-command.
:param os_path: Optional path to base the file-like object
on.
:param skip_sub_command: Set True to skip any configured
... | [
"A",
"context",
"manager",
"yielding",
"a",
"stdin",
"-",
"suitable",
"file",
"-",
"like",
"object",
"based",
"on",
"the",
"optional",
"os_path",
"and",
"optionally",
"skipping",
"any",
"configured",
"sub",
"-",
"command",
"."
] | python | test |
PyThaiNLP/pythainlp | pythainlp/corpus/__init__.py | https://github.com/PyThaiNLP/pythainlp/blob/e9a300b8a99dfd1a67a955e7c06f62e4afe0fbca/pythainlp/corpus/__init__.py#L54-L72 | def get_corpus_path(name: str) -> [str, None]:
"""
Get corpus path
:param string name: corpus name
"""
db = TinyDB(corpus_db_path())
temp = Query()
if len(db.search(temp.name == name)) > 0:
path = get_full_data_path(db.search(temp.name == name)[0]["file"])
db.close()
... | [
"def",
"get_corpus_path",
"(",
"name",
":",
"str",
")",
"->",
"[",
"str",
",",
"None",
"]",
":",
"db",
"=",
"TinyDB",
"(",
"corpus_db_path",
"(",
")",
")",
"temp",
"=",
"Query",
"(",
")",
"if",
"len",
"(",
"db",
".",
"search",
"(",
"temp",
".",
... | Get corpus path
:param string name: corpus name | [
"Get",
"corpus",
"path"
] | python | train |
helixyte/everest | everest/utils.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/utils.py#L203-L232 | def app_name_from_ini_parser(ini_parser):
"""
Returns the name of the main application from the given ini file parser.
The name is found as follows:
* If the ini file contains only one app:<app name> section,
return this app name;
* Else, if the ini file contains a pipeline:main section, us... | [
"def",
"app_name_from_ini_parser",
"(",
"ini_parser",
")",
":",
"app_names",
"=",
"[",
"sect",
".",
"split",
"(",
"':'",
")",
"[",
"-",
"1",
"]",
"for",
"sect",
"in",
"ini_parser",
".",
"sections",
"(",
")",
"if",
"sect",
"[",
":",
"4",
"]",
"==",
... | Returns the name of the main application from the given ini file parser.
The name is found as follows:
* If the ini file contains only one app:<app name> section,
return this app name;
* Else, if the ini file contains a pipeline:main section, use
the name of the innermost app;
* Else ra... | [
"Returns",
"the",
"name",
"of",
"the",
"main",
"application",
"from",
"the",
"given",
"ini",
"file",
"parser",
".",
"The",
"name",
"is",
"found",
"as",
"follows",
":",
"*",
"If",
"the",
"ini",
"file",
"contains",
"only",
"one",
"app",
":",
"<app",
"nam... | python | train |
marcomusy/vtkplotter | vtkplotter/addons.py | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/addons.py#L362-L441 | def addSlider3D(
sliderfunc,
pos1,
pos2,
xmin,
xmax,
value=None,
s=0.03,
title="",
rotation=0,
c=None,
showValue=True,
):
"""Add a 3D slider widget which can call an external custom function.
:param sliderfunc: external function to be called by the widget
:param ... | [
"def",
"addSlider3D",
"(",
"sliderfunc",
",",
"pos1",
",",
"pos2",
",",
"xmin",
",",
"xmax",
",",
"value",
"=",
"None",
",",
"s",
"=",
"0.03",
",",
"title",
"=",
"\"\"",
",",
"rotation",
"=",
"0",
",",
"c",
"=",
"None",
",",
"showValue",
"=",
"Tr... | Add a 3D slider widget which can call an external custom function.
:param sliderfunc: external function to be called by the widget
:param list pos1: first position coordinates
:param list pos2: second position coordinates
:param float xmin: lower value
:param float xmax: upper value
:param fl... | [
"Add",
"a",
"3D",
"slider",
"widget",
"which",
"can",
"call",
"an",
"external",
"custom",
"function",
"."
] | python | train |
seb-m/pyinotify | python2/pyinotify.py | https://github.com/seb-m/pyinotify/blob/0f3f8950d12e4a6534320153eed1a90a778da4ae/python2/pyinotify.py#L308-L320 | def set_val(self, nval):
"""
Sets new attribute's value.
@param nval: replaces current value by nval.
@type nval: int
@raise IOError: if corresponding file in /proc/sys cannot be written.
"""
file_obj = file(os.path.join(self._base, self._attr), 'w')
try:... | [
"def",
"set_val",
"(",
"self",
",",
"nval",
")",
":",
"file_obj",
"=",
"file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_base",
",",
"self",
".",
"_attr",
")",
",",
"'w'",
")",
"try",
":",
"file_obj",
".",
"write",
"(",
"str",
"(... | Sets new attribute's value.
@param nval: replaces current value by nval.
@type nval: int
@raise IOError: if corresponding file in /proc/sys cannot be written. | [
"Sets",
"new",
"attribute",
"s",
"value",
"."
] | python | train |
Phylliade/ikpy | src/ikpy/geometry_utils.py | https://github.com/Phylliade/ikpy/blob/60e36d6163136942bf520d952db17123c658d0b6/src/ikpy/geometry_utils.py#L61-L70 | def axis_rotation_matrix(axis, theta):
"""Returns a rotation matrix around the given axis"""
[x, y, z] = axis
c = np.cos(theta)
s = np.sin(theta)
return np.array([
[x**2 + (1 - x**2) * c, x * y * (1 - c) - z * s, x * z * (1 - c) + y * s],
[x * y * (1 - c) + z * s, y ** 2 + (1 - y**2)... | [
"def",
"axis_rotation_matrix",
"(",
"axis",
",",
"theta",
")",
":",
"[",
"x",
",",
"y",
",",
"z",
"]",
"=",
"axis",
"c",
"=",
"np",
".",
"cos",
"(",
"theta",
")",
"s",
"=",
"np",
".",
"sin",
"(",
"theta",
")",
"return",
"np",
".",
"array",
"(... | Returns a rotation matrix around the given axis | [
"Returns",
"a",
"rotation",
"matrix",
"around",
"the",
"given",
"axis"
] | python | train |
jorgenkg/python-neural-network | nimblenet/activation_functions.py | https://github.com/jorgenkg/python-neural-network/blob/617b9940fa157d54d7831c42c0f7ba6857239b9a/nimblenet/activation_functions.py#L74-L85 | def LReLU_function( signal, derivative=False, leakage = 0.01 ):
"""
Leaky Rectified Linear Unit
"""
if derivative:
# Return the partial derivation of the activation function
return np.clip(signal > 0, leakage, 1.0)
else:
# Return the activation signal
output = np.copy... | [
"def",
"LReLU_function",
"(",
"signal",
",",
"derivative",
"=",
"False",
",",
"leakage",
"=",
"0.01",
")",
":",
"if",
"derivative",
":",
"# Return the partial derivation of the activation function",
"return",
"np",
".",
"clip",
"(",
"signal",
">",
"0",
",",
"lea... | Leaky Rectified Linear Unit | [
"Leaky",
"Rectified",
"Linear",
"Unit"
] | python | train |
vfilimonov/pydatastream | pydatastream/pydatastream.py | https://github.com/vfilimonov/pydatastream/blob/15d2adac1c83501715db1542373fa8428542816e/pydatastream/pydatastream.py#L528-L540 | def get_OHLCV(self, ticker, date=None, date_from=None, date_to=None):
"""Get Open, High, Low, Close prices and daily Volume for a given ticker.
ticker - ticker or symbol
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specifie... | [
"def",
"get_OHLCV",
"(",
"self",
",",
"ticker",
",",
"date",
"=",
"None",
",",
"date_from",
"=",
"None",
",",
"date_to",
"=",
"None",
")",
":",
"data",
",",
"meta",
"=",
"self",
".",
"fetch",
"(",
"ticker",
"+",
"\"~OHLCV\"",
",",
"None",
",",
"dat... | Get Open, High, Low, Close prices and daily Volume for a given ticker.
ticker - ticker or symbol
date - date for a single-date query
date_from, date_to - date range (used only if "date" is not specified)
Returns pandas.Dataframe with data. If error occurs, then it is pr... | [
"Get",
"Open",
"High",
"Low",
"Close",
"prices",
"and",
"daily",
"Volume",
"for",
"a",
"given",
"ticker",
"."
] | python | train |
dw/mitogen | ansible_mitogen/connection.py | https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/ansible_mitogen/connection.py#L516-L536 | def on_action_run(self, task_vars, delegate_to_hostname, loader_basedir):
"""
Invoked by ActionModuleMixin to indicate a new task is about to start
executing. We use the opportunity to grab relevant bits from the
task-specific data.
:param dict task_vars:
Task variab... | [
"def",
"on_action_run",
"(",
"self",
",",
"task_vars",
",",
"delegate_to_hostname",
",",
"loader_basedir",
")",
":",
"self",
".",
"inventory_hostname",
"=",
"task_vars",
"[",
"'inventory_hostname'",
"]",
"self",
".",
"_task_vars",
"=",
"task_vars",
"self",
".",
... | Invoked by ActionModuleMixin to indicate a new task is about to start
executing. We use the opportunity to grab relevant bits from the
task-specific data.
:param dict task_vars:
Task variable dictionary.
:param str delegate_to_hostname:
:data:`None`, or the templ... | [
"Invoked",
"by",
"ActionModuleMixin",
"to",
"indicate",
"a",
"new",
"task",
"is",
"about",
"to",
"start",
"executing",
".",
"We",
"use",
"the",
"opportunity",
"to",
"grab",
"relevant",
"bits",
"from",
"the",
"task",
"-",
"specific",
"data",
"."
] | python | train |
ARMmbed/autoversion | src/auto_version/auto_version_tool.py | https://github.com/ARMmbed/autoversion/blob/c5b127d2059c8219f5637fe45bf9e1be3a0af2aa/src/auto_version/auto_version_tool.py#L122-L136 | def get_lock_behaviour(triggers, all_data, lock):
"""Binary state lock protects from version increments if set"""
updates = {}
lock_key = config._forward_aliases.get(Constants.VERSION_LOCK_FIELD)
# if we are explicitly setting or locking the version, then set the lock field True anyway
if lock:
... | [
"def",
"get_lock_behaviour",
"(",
"triggers",
",",
"all_data",
",",
"lock",
")",
":",
"updates",
"=",
"{",
"}",
"lock_key",
"=",
"config",
".",
"_forward_aliases",
".",
"get",
"(",
"Constants",
".",
"VERSION_LOCK_FIELD",
")",
"# if we are explicitly setting or loc... | Binary state lock protects from version increments if set | [
"Binary",
"state",
"lock",
"protects",
"from",
"version",
"increments",
"if",
"set"
] | python | train |
Jammy2211/PyAutoLens | autolens/model/galaxy/galaxy_model.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/galaxy/galaxy_model.py#L277-L297 | def gaussian_prior_model_for_arguments(self, arguments):
"""
Create a new galaxy prior from a set of arguments, replacing the priors of some of this galaxy prior's prior
models with new arguments.
Parameters
----------
arguments: dict
A dictionary mapping_mat... | [
"def",
"gaussian_prior_model_for_arguments",
"(",
"self",
",",
"arguments",
")",
":",
"new_model",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"for",
"key",
",",
"value",
"in",
"filter",
"(",
"lambda",
"t",
":",
"isinstance",
"(",
"t",
"[",
"1",
"]",... | Create a new galaxy prior from a set of arguments, replacing the priors of some of this galaxy prior's prior
models with new arguments.
Parameters
----------
arguments: dict
A dictionary mapping_matrix between old priors and their replacements.
Returns
-----... | [
"Create",
"a",
"new",
"galaxy",
"prior",
"from",
"a",
"set",
"of",
"arguments",
"replacing",
"the",
"priors",
"of",
"some",
"of",
"this",
"galaxy",
"prior",
"s",
"prior",
"models",
"with",
"new",
"arguments",
"."
] | python | valid |
googleapis/google-auth-library-python | google/auth/jwt.py | https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/auth/jwt.py#L115-L142 | def _unverified_decode(token):
"""Decodes a token and does no verification.
Args:
token (Union[str, bytes]): The encoded JWT.
Returns:
Tuple[str, str, str, str]: header, payload, signed_section, and
signature.
Raises:
ValueError: if there are an incorrect amount of... | [
"def",
"_unverified_decode",
"(",
"token",
")",
":",
"token",
"=",
"_helpers",
".",
"to_bytes",
"(",
"token",
")",
"if",
"token",
".",
"count",
"(",
"b'.'",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'Wrong number of segments in token: {0}'",
".",
"fo... | Decodes a token and does no verification.
Args:
token (Union[str, bytes]): The encoded JWT.
Returns:
Tuple[str, str, str, str]: header, payload, signed_section, and
signature.
Raises:
ValueError: if there are an incorrect amount of segments in the token. | [
"Decodes",
"a",
"token",
"and",
"does",
"no",
"verification",
"."
] | python | train |
tanghaibao/jcvi | jcvi/projects/str.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L425-L430 | def in_region(rname, rstart, target_chr, target_start, target_end):
"""
Quick check if a point is within the target region.
"""
return (rname == target_chr) and \
(target_start <= rstart <= target_end) | [
"def",
"in_region",
"(",
"rname",
",",
"rstart",
",",
"target_chr",
",",
"target_start",
",",
"target_end",
")",
":",
"return",
"(",
"rname",
"==",
"target_chr",
")",
"and",
"(",
"target_start",
"<=",
"rstart",
"<=",
"target_end",
")"
] | Quick check if a point is within the target region. | [
"Quick",
"check",
"if",
"a",
"point",
"is",
"within",
"the",
"target",
"region",
"."
] | python | train |
joar/mig | mig/__init__.py | https://github.com/joar/mig/blob/e1a7a8b9ea5941a05a27d5afbb5952965bb20ae5/mig/__init__.py#L130-L144 | def migrations_to_run(self):
"""
Get a list of migrations to run still, if any.
Note that this will fail if there's no migration record for
this class!
"""
assert self.database_current_migration is not None
db_current_migration = self.database_current_migration
... | [
"def",
"migrations_to_run",
"(",
"self",
")",
":",
"assert",
"self",
".",
"database_current_migration",
"is",
"not",
"None",
"db_current_migration",
"=",
"self",
".",
"database_current_migration",
"return",
"[",
"(",
"migration_number",
",",
"migration_func",
")",
"... | Get a list of migrations to run still, if any.
Note that this will fail if there's no migration record for
this class! | [
"Get",
"a",
"list",
"of",
"migrations",
"to",
"run",
"still",
"if",
"any",
"."
] | python | train |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L469-L477 | def write_config(self, cfg, slot=1):
""" Write a configuration to the YubiKey. """
cfg_req_ver = cfg.version_required()
if cfg_req_ver > self.version_num():
raise yubikey_base.YubiKeyVersionError('Configuration requires YubiKey version %i.%i (this is %s)' % \
... | [
"def",
"write_config",
"(",
"self",
",",
"cfg",
",",
"slot",
"=",
"1",
")",
":",
"cfg_req_ver",
"=",
"cfg",
".",
"version_required",
"(",
")",
"if",
"cfg_req_ver",
">",
"self",
".",
"version_num",
"(",
")",
":",
"raise",
"yubikey_base",
".",
"YubiKeyVers... | Write a configuration to the YubiKey. | [
"Write",
"a",
"configuration",
"to",
"the",
"YubiKey",
"."
] | python | train |
awslabs/sockeye | sockeye/utils.py | https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/utils.py#L78-L86 | def parse_version(version_string: str) -> Tuple[str, str, str]:
"""
Parse version string into release, major, minor version.
:param version_string: Version string.
:return: Tuple of strings.
"""
release, major, minor = version_string.split(".", 2)
return release, major, minor | [
"def",
"parse_version",
"(",
"version_string",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
",",
"str",
"]",
":",
"release",
",",
"major",
",",
"minor",
"=",
"version_string",
".",
"split",
"(",
"\".\"",
",",
"2",
")",
"return",
"release",
... | Parse version string into release, major, minor version.
:param version_string: Version string.
:return: Tuple of strings. | [
"Parse",
"version",
"string",
"into",
"release",
"major",
"minor",
"version",
"."
] | python | train |
KelSolaar/Foundations | foundations/nodes.py | https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/nodes.py#L468-L489 | def attribute_exists(self, name):
"""
Returns if given attribute exists in the node.
Usage::
>>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute())
>>> node_a.attribute_exists("attributeA")
True
>>> node_a.attribute_... | [
"def",
"attribute_exists",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"in",
"self",
":",
"if",
"issubclass",
"(",
"self",
"[",
"name",
"]",
".",
"__class__",
",",
"Attribute",
")",
":",
"return",
"True",
"return",
"False"
] | Returns if given attribute exists in the node.
Usage::
>>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute())
>>> node_a.attribute_exists("attributeA")
True
>>> node_a.attribute_exists("attributeC")
False
:param... | [
"Returns",
"if",
"given",
"attribute",
"exists",
"in",
"the",
"node",
"."
] | python | train |
PmagPy/PmagPy | programs/pmag_gui.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/pmag_gui.py#L142-L154 | def get_wd_data2(self):
"""
Get 2.5 data from self.WD and put it into
ErMagicBuilder object.
Called by get_dm_and_wd
"""
wait = wx.BusyInfo('Reading in data from current working directory, please wait...')
#wx.Yield()
print('-I- Read in any available data ... | [
"def",
"get_wd_data2",
"(",
"self",
")",
":",
"wait",
"=",
"wx",
".",
"BusyInfo",
"(",
"'Reading in data from current working directory, please wait...'",
")",
"#wx.Yield()",
"print",
"(",
"'-I- Read in any available data from working directory (data model 2)'",
")",
"self",
... | Get 2.5 data from self.WD and put it into
ErMagicBuilder object.
Called by get_dm_and_wd | [
"Get",
"2",
".",
"5",
"data",
"from",
"self",
".",
"WD",
"and",
"put",
"it",
"into",
"ErMagicBuilder",
"object",
".",
"Called",
"by",
"get_dm_and_wd"
] | python | train |
dmirecki/pyMorfologik | pymorfologik/output_parser.py | https://github.com/dmirecki/pyMorfologik/blob/e4d93a82e8b4c7a108f01e0456fbeb8024df0259/pymorfologik/output_parser.py#L19-L49 | def parse_for_simple_stems(output, skip_empty=False, skip_same_stems=True):
"""
Parses the output stem lines to produce a list with possible stems
for each word in the output.
:param skip_empty: set True to skip lines without stems (default is False)
:returns: a list of tuples, each containing an o... | [
"def",
"parse_for_simple_stems",
"(",
"output",
",",
"skip_empty",
"=",
"False",
",",
"skip_same_stems",
"=",
"True",
")",
":",
"lines_with_stems",
"=",
"_get_lines_with_stems",
"(",
"output",
")",
"stems",
"=",
"list",
"(",
")",
"last_word",
"=",
"None",
"for... | Parses the output stem lines to produce a list with possible stems
for each word in the output.
:param skip_empty: set True to skip lines without stems (default is False)
:returns: a list of tuples, each containing an original text word and
a list of stems for the given word | [
"Parses",
"the",
"output",
"stem",
"lines",
"to",
"produce",
"a",
"list",
"with",
"possible",
"stems",
"for",
"each",
"word",
"in",
"the",
"output",
"."
] | python | train |
quantopian/zipline | zipline/pipeline/loaders/earnings_estimates.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/loaders/earnings_estimates.py#L1117-L1215 | def collect_post_asof_split_adjustments(self,
post_adjustments,
requested_qtr_data,
sid,
sid_idx,
si... | [
"def",
"collect_post_asof_split_adjustments",
"(",
"self",
",",
"post_adjustments",
",",
"requested_qtr_data",
",",
"sid",
",",
"sid_idx",
",",
"sid_estimates",
",",
"requested_split_adjusted_columns",
")",
":",
"col_to_split_adjustments",
"=",
"{",
"}",
"if",
"post_adj... | Collect split adjustments that occur after the
split-adjusted-asof-date. Each adjustment needs to be applied to all
dates on which knowledge for the requested quarter was older than the
date of the adjustment.
Parameters
----------
post_adjustments : tuple(list(float), l... | [
"Collect",
"split",
"adjustments",
"that",
"occur",
"after",
"the",
"split",
"-",
"adjusted",
"-",
"asof",
"-",
"date",
".",
"Each",
"adjustment",
"needs",
"to",
"be",
"applied",
"to",
"all",
"dates",
"on",
"which",
"knowledge",
"for",
"the",
"requested",
... | python | train |
edx/ecommerce-worker | ecommerce_worker/cache.py | https://github.com/edx/ecommerce-worker/blob/55246961d805b1f64d661a5c0bae0a216589401f/ecommerce_worker/cache.py#L23-L51 | def get(self, key):
"""Get an object from the cache
Arguments:
key (str): Cache key
Returns:
Cached object
"""
lock.acquire()
try:
if key not in self:
return None
current_time = time.time()
if ... | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"key",
"not",
"in",
"self",
":",
"return",
"None",
"current_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"self",
"[",
"key",
"]",
".",
"exp... | Get an object from the cache
Arguments:
key (str): Cache key
Returns:
Cached object | [
"Get",
"an",
"object",
"from",
"the",
"cache"
] | python | test |
smarie/python-parsyfiles | parsyfiles/plugins_base/support_for_objects.py | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_base/support_for_objects.py#L77-L91 | def create(obj: PersistedObject, obj_type: Type[Any], arg_name: str):
"""
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param obj:
:param obj_type:
:param arg_nam... | [
"def",
"create",
"(",
"obj",
":",
"PersistedObject",
",",
"obj_type",
":",
"Type",
"[",
"Any",
"]",
",",
"arg_name",
":",
"str",
")",
":",
"return",
"MissingMandatoryAttributeFiles",
"(",
"'Multifile object '",
"+",
"str",
"(",
"obj",
")",
"+",
"' cannot be ... | Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param obj:
:param obj_type:
:param arg_name:
:return: | [
"Helper",
"method",
"provided",
"because",
"we",
"actually",
"can",
"t",
"put",
"that",
"in",
"the",
"constructor",
"it",
"creates",
"a",
"bug",
"in",
"Nose",
"tests",
"https",
":",
"//",
"github",
".",
"com",
"/",
"nose",
"-",
"devs",
"/",
"nose",
"/"... | python | train |
swevm/scaleio-py | scaleiopy/api/scaleio/cluster/faultset.py | https://github.com/swevm/scaleio-py/blob/d043a0137cb925987fd5c895a3210968ce1d9028/scaleiopy/api/scaleio/cluster/faultset.py#L45-L61 | def set_faultset_name(self, name, fsObj):
"""
Set name for Faultset
:param name: Name of Faultset
:param fsObj: ScaleIO FS object
:return: POST request response
:rtype: Requests POST response object
"""
# Set name of FaultSet
self.conn.connection._... | [
"def",
"set_faultset_name",
"(",
"self",
",",
"name",
",",
"fsObj",
")",
":",
"# Set name of FaultSet",
"self",
".",
"conn",
".",
"connection",
".",
"_check_login",
"(",
")",
"faultSetNameDict",
"=",
"{",
"'Name'",
":",
"name",
"}",
"# This one is the most logic... | Set name for Faultset
:param name: Name of Faultset
:param fsObj: ScaleIO FS object
:return: POST request response
:rtype: Requests POST response object | [
"Set",
"name",
"for",
"Faultset",
":",
"param",
"name",
":",
"Name",
"of",
"Faultset",
":",
"param",
"fsObj",
":",
"ScaleIO",
"FS",
"object",
":",
"return",
":",
"POST",
"request",
"response",
":",
"rtype",
":",
"Requests",
"POST",
"response",
"object"
] | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/lib/clipboard.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/clipboard.py#L26-L34 | def osx_clipboard_get():
""" Get the clipboard's text on OS X.
"""
p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],
stdout=subprocess.PIPE)
text, stderr = p.communicate()
# Text comes in with old Mac \r line endings. Change them to \n.
text = text.replace('\r', '\n')
return text | [
"def",
"osx_clipboard_get",
"(",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'pbpaste'",
",",
"'-Prefer'",
",",
"'ascii'",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"text",
",",
"stderr",
"=",
"p",
".",
"communicate",
"(",... | Get the clipboard's text on OS X. | [
"Get",
"the",
"clipboard",
"s",
"text",
"on",
"OS",
"X",
"."
] | python | test |
crs4/hl7apy | hl7apy/core.py | https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L228-L246 | def insert(self, index, child, by_name_index=-1):
"""
Add the child at the given index
:type index: ``int``
:param index: child position
:type child: :class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass
... | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"child",
",",
"by_name_index",
"=",
"-",
"1",
")",
":",
"if",
"self",
".",
"_can_add_child",
"(",
"child",
")",
":",
"try",
":",
"if",
"by_name_index",
"==",
"-",
"1",
":",
"self",
".",
"indexes",
"[... | Add the child at the given index
:type index: ``int``
:param index: child position
:type child: :class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass | [
"Add",
"the",
"child",
"at",
"the",
"given",
"index"
] | python | train |
gbiggs/rtsprofile | rtsprofile/exec_context.py | https://github.com/gbiggs/rtsprofile/blob/fded6eddcb0b25fe9808b1b12336a4413ea00905/rtsprofile/exec_context.py#L246-L261 | def save_xml(self, doc, element):
'''Save this execution context into an xml.dom.Element object.'''
element.setAttributeNS(XSI_NS, XSI_NS_S + 'type', 'rtsExt:execution_context_ext')
element.setAttributeNS(RTS_NS, RTS_NS_S + 'id', self.id)
element.setAttributeNS(RTS_NS, RTS_NS_S + 'kind',... | [
"def",
"save_xml",
"(",
"self",
",",
"doc",
",",
"element",
")",
":",
"element",
".",
"setAttributeNS",
"(",
"XSI_NS",
",",
"XSI_NS_S",
"+",
"'type'",
",",
"'rtsExt:execution_context_ext'",
")",
"element",
".",
"setAttributeNS",
"(",
"RTS_NS",
",",
"RTS_NS_S",... | Save this execution context into an xml.dom.Element object. | [
"Save",
"this",
"execution",
"context",
"into",
"an",
"xml",
".",
"dom",
".",
"Element",
"object",
"."
] | python | train |
timofurrer/colorful | colorful/core.py | https://github.com/timofurrer/colorful/blob/919fa6da17865cc5e01e6b16119193a97d180dc9/colorful/core.py#L111-L134 | def resolve_modifier_to_ansi_code(modifiername, colormode):
"""
Resolve the given modifier name to a valid
ANSI escape code.
:param str modifiername: the name of the modifier to resolve
:param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``
:returns str: the ANSI escap... | [
"def",
"resolve_modifier_to_ansi_code",
"(",
"modifiername",
",",
"colormode",
")",
":",
"if",
"colormode",
"==",
"terminal",
".",
"NO_COLORS",
":",
"# return empty string if colors are disabled",
"return",
"''",
",",
"''",
"try",
":",
"start_code",
",",
"end_code",
... | Resolve the given modifier name to a valid
ANSI escape code.
:param str modifiername: the name of the modifier to resolve
:param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code``
:returns str: the ANSI escape code for the modifier
:raises ColorfulError: if the given modifie... | [
"Resolve",
"the",
"given",
"modifier",
"name",
"to",
"a",
"valid",
"ANSI",
"escape",
"code",
"."
] | python | valid |
trailofbits/manticore | manticore/native/cpu/abstractcpu.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/abstractcpu.py#L655-L675 | def read_int(self, where, size=None, force=False):
"""
Reads int from memory
:param int where: address to read from
:param size: number of bits to read
:return: the value read
:rtype: int or BitVec
:param force: whether to ignore memory permissions
"""
... | [
"def",
"read_int",
"(",
"self",
",",
"where",
",",
"size",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"size",
"is",
"None",
":",
"size",
"=",
"self",
".",
"address_bit_size",
"assert",
"size",
"in",
"SANE_SIZES",
"self",
".",
"_publish",
... | Reads int from memory
:param int where: address to read from
:param size: number of bits to read
:return: the value read
:rtype: int or BitVec
:param force: whether to ignore memory permissions | [
"Reads",
"int",
"from",
"memory"
] | python | valid |
mitsei/dlkit | dlkit/json_/relationship/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/relationship/sessions.py#L1612-L1636 | def can_create_family_with_record_types(self, family_record_types):
"""Tests if this user can create a single ``Family`` using the desired record types.
While ``RelationshipManager.getFamilyRecordTypes()`` can be used
to examine which records are supported, this method tests which
recor... | [
"def",
"can_create_family_with_record_types",
"(",
"self",
",",
"family_record_types",
")",
":",
"# Implemented from template for",
"# osid.resource.BinAdminSession.can_create_bin_with_record_types",
"# NOTE: It is expected that real authentication hints will be",
"# handled in a service adapt... | Tests if this user can create a single ``Family`` using the desired record types.
While ``RelationshipManager.getFamilyRecordTypes()`` can be used
to examine which records are supported, this method tests which
record(s) are required for creating a specific ``Family``.
Providing an empt... | [
"Tests",
"if",
"this",
"user",
"can",
"create",
"a",
"single",
"Family",
"using",
"the",
"desired",
"record",
"types",
"."
] | python | train |
jayme-github/steamweb | steamweb/steamwebbrowser.py | https://github.com/jayme-github/steamweb/blob/39f85ac546d009ed8791bf7a467734dfb788ef8a/steamweb/steamwebbrowser.py#L265-L281 | def _get_rsa_key(self):
''' get steam RSA key, build and return cipher '''
url = 'https://steamcommunity.com/mobilelogin/getrsakey/'
values = {
'username': self._username,
'donotcache' : self._get_donotcachetime(),
}
req = self.post(url, data=value... | [
"def",
"_get_rsa_key",
"(",
"self",
")",
":",
"url",
"=",
"'https://steamcommunity.com/mobilelogin/getrsakey/'",
"values",
"=",
"{",
"'username'",
":",
"self",
".",
"_username",
",",
"'donotcache'",
":",
"self",
".",
"_get_donotcachetime",
"(",
")",
",",
"}",
"r... | get steam RSA key, build and return cipher | [
"get",
"steam",
"RSA",
"key",
"build",
"and",
"return",
"cipher"
] | python | train |
pybel/pybel | src/pybel/manager/cache_manager.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/cache_manager.py#L610-L663 | def _store_graph_parts(self, graph: BELGraph, use_tqdm: bool = False) -> Tuple[List[Node], List[Edge]]:
"""Store the given graph into the edge store.
:raises: pybel.resources.exc.ResourceError
:raises: EdgeAddError
"""
log.debug('inserting %s into edge store', graph)
log... | [
"def",
"_store_graph_parts",
"(",
"self",
",",
"graph",
":",
"BELGraph",
",",
"use_tqdm",
":",
"bool",
"=",
"False",
")",
"->",
"Tuple",
"[",
"List",
"[",
"Node",
"]",
",",
"List",
"[",
"Edge",
"]",
"]",
":",
"log",
".",
"debug",
"(",
"'inserting %s ... | Store the given graph into the edge store.
:raises: pybel.resources.exc.ResourceError
:raises: EdgeAddError | [
"Store",
"the",
"given",
"graph",
"into",
"the",
"edge",
"store",
"."
] | python | train |
benoitguigal/python-epson-printer | epson_printer/epsonprinter.py | https://github.com/benoitguigal/python-epson-printer/blob/7d89b2f21bc76d2cc4d5ad548e19a356ca92fbc5/epson_printer/epsonprinter.py#L199-L207 | def write_this(func):
"""
Decorator that writes the bytes to the wire
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
byte_array = func(self, *args, **kwargs)
self.write_bytes(byte_array)
return wrapper | [
"def",
"write_this",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"byte_array",
"=",
"func",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
"... | Decorator that writes the bytes to the wire | [
"Decorator",
"that",
"writes",
"the",
"bytes",
"to",
"the",
"wire"
] | python | train |
nilp0inter/cpe | cpe/cpe.py | https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe.py#L433-L505 | def _pack_edition(self):
"""
Pack the values of the five arguments into the simple edition
component. If all the values are blank, just return a blank.
:returns: "edition", "sw_edition", "target_sw", "target_hw" and "other"
attributes packed in a only value
:rtype: s... | [
"def",
"_pack_edition",
"(",
"self",
")",
":",
"COMP_KEYS",
"=",
"(",
"CPEComponent",
".",
"ATT_EDITION",
",",
"CPEComponent",
".",
"ATT_SW_EDITION",
",",
"CPEComponent",
".",
"ATT_TARGET_SW",
",",
"CPEComponent",
".",
"ATT_TARGET_HW",
",",
"CPEComponent",
".",
... | Pack the values of the five arguments into the simple edition
component. If all the values are blank, just return a blank.
:returns: "edition", "sw_edition", "target_sw", "target_hw" and "other"
attributes packed in a only value
:rtype: string
:exception: TypeError - incompa... | [
"Pack",
"the",
"values",
"of",
"the",
"five",
"arguments",
"into",
"the",
"simple",
"edition",
"component",
".",
"If",
"all",
"the",
"values",
"are",
"blank",
"just",
"return",
"a",
"blank",
"."
] | python | train |
twisted/twistedchecker | twistedchecker/core/runner.py | https://github.com/twisted/twistedchecker/blob/80060e1c07cf5d67d747dbec8ec0e5ee913e8929/twistedchecker/core/runner.py#L388-L415 | def parseWarnings(self, result):
"""
Transform result in string to a dict object.
@param result: a list of warnings in string
@return: a dict of warnings
"""
warnings = {}
currentModule = None
warningsCurrentModule = []
for line in result.splitlin... | [
"def",
"parseWarnings",
"(",
"self",
",",
"result",
")",
":",
"warnings",
"=",
"{",
"}",
"currentModule",
"=",
"None",
"warningsCurrentModule",
"=",
"[",
"]",
"for",
"line",
"in",
"result",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
".",
"startswith... | Transform result in string to a dict object.
@param result: a list of warnings in string
@return: a dict of warnings | [
"Transform",
"result",
"in",
"string",
"to",
"a",
"dict",
"object",
"."
] | python | train |
lowandrew/OLCTools | coreGenome/coretyper.py | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/coreGenome/coretyper.py#L19-L38 | def handler(self):
"""Run the required analyses"""
printtime('Creating and populating objects', self.start)
self.populate()
printtime('Populating {} sequence profiles'.format(self.analysistype), self.start)
self.profiler()
# Annotate sequences with prokka
self.ann... | [
"def",
"handler",
"(",
"self",
")",
":",
"printtime",
"(",
"'Creating and populating objects'",
",",
"self",
".",
"start",
")",
"self",
".",
"populate",
"(",
")",
"printtime",
"(",
"'Populating {} sequence profiles'",
".",
"format",
"(",
"self",
".",
"analysisty... | Run the required analyses | [
"Run",
"the",
"required",
"analyses"
] | python | train |
limix/limix-core | limix_core/mean/linear.py | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/mean/linear.py#L275-L283 | def Lc(self,value):
""" set col rotation """
assert value.shape[0]==self._P, 'Lc dimension mismatch'
assert value.shape[1]==self._P, 'Lc dimension mismatch'
self._Lc = value
self.clear_cache('Astar','Ystar','Yhat','Xstar','Xhat',
'Areml','Areml_eigh','Are... | [
"def",
"Lc",
"(",
"self",
",",
"value",
")",
":",
"assert",
"value",
".",
"shape",
"[",
"0",
"]",
"==",
"self",
".",
"_P",
",",
"'Lc dimension mismatch'",
"assert",
"value",
".",
"shape",
"[",
"1",
"]",
"==",
"self",
".",
"_P",
",",
"'Lc dimension mi... | set col rotation | [
"set",
"col",
"rotation"
] | python | train |
biocore/burrito-fillings | bfillings/infernal.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/infernal.py#L1319-L1399 | def cmalign_from_alignment(aln, structure_string, seqs, moltype=DNA,\
include_aln=True,refine=False, return_stdout=False,params=None,\
cmbuild_params=None):
"""Uses cmbuild to build a CM file, then cmalign to build an alignment.
- aln: an Alignment object or something that can be used to construct
... | [
"def",
"cmalign_from_alignment",
"(",
"aln",
",",
"structure_string",
",",
"seqs",
",",
"moltype",
"=",
"DNA",
",",
"include_aln",
"=",
"True",
",",
"refine",
"=",
"False",
",",
"return_stdout",
"=",
"False",
",",
"params",
"=",
"None",
",",
"cmbuild_params"... | Uses cmbuild to build a CM file, then cmalign to build an alignment.
- aln: an Alignment object or something that can be used to construct
one. All sequences must be the same length.
- structure_string: vienna structure string representing the consensus
stucture for the sequenc... | [
"Uses",
"cmbuild",
"to",
"build",
"a",
"CM",
"file",
"then",
"cmalign",
"to",
"build",
"an",
"alignment",
"."
] | python | train |
CiscoDevNet/webexteamssdk | webexteamssdk/api/roles.py | https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/roles.py#L76-L100 | def list(self, **request_parameters):
"""List all roles.
Args:
**request_parameters: Additional request parameters (provides
support for parameters that may be added in the future).
Returns:
GeneratorContainer: A GeneratorContainer which, when iterated,
... | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"request_parameters",
")",
":",
"# API request - get items",
"items",
"=",
"self",
".",
"_session",
".",
"get_items",
"(",
"API_ENDPOINT",
",",
"params",
"=",
"request_parameters",
")",
"# Yield role objects created from th... | List all roles.
Args:
**request_parameters: Additional request parameters (provides
support for parameters that may be added in the future).
Returns:
GeneratorContainer: A GeneratorContainer which, when iterated,
yields the roles returned by the Webe... | [
"List",
"all",
"roles",
"."
] | python | test |
SmokinCaterpillar/pypet | examples/example_24_large_scale_brian2_simulation/clusternet.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/examples/example_24_large_scale_brian2_simulation/clusternet.py#L255-L284 | def add_parameters(traj):
"""Adds all neuron group parameters to `traj`."""
assert(isinstance(traj,Trajectory))
traj.v_standard_parameter = Brian2Parameter
scale = traj.simulation.scale
traj.f_add_parameter('connections.R_ee', 1.0, comment='Scaling factor for clustering')
... | [
"def",
"add_parameters",
"(",
"traj",
")",
":",
"assert",
"(",
"isinstance",
"(",
"traj",
",",
"Trajectory",
")",
")",
"traj",
".",
"v_standard_parameter",
"=",
"Brian2Parameter",
"scale",
"=",
"traj",
".",
"simulation",
".",
"scale",
"traj",
".",
"f_add_par... | Adds all neuron group parameters to `traj`. | [
"Adds",
"all",
"neuron",
"group",
"parameters",
"to",
"traj",
"."
] | python | test |
6809/MC6809 | MC6809/components/mc6809_ops_load_store.py | https://github.com/6809/MC6809/blob/6ba2f5106df46689017b5d0b6d84d43b7ee6a240/MC6809/components/mc6809_ops_load_store.py#L109-L125 | def instruction_ST8(self, opcode, ea, register):
"""
Writes the contents of an 8-bit register into a memory location.
source code forms: STA P; STB P
CC bits "HNZVC": -aa0-
"""
value = register.value
# log.debug("$%x ST8 store value $%x from %s at $%x \t| %s" % (... | [
"def",
"instruction_ST8",
"(",
"self",
",",
"opcode",
",",
"ea",
",",
"register",
")",
":",
"value",
"=",
"register",
".",
"value",
"# log.debug(\"$%x ST8 store value $%x from %s at $%x \\t| %s\" % (",
"# self.program_counter,",
"# value, register... | Writes the contents of an 8-bit register into a memory location.
source code forms: STA P; STB P
CC bits "HNZVC": -aa0- | [
"Writes",
"the",
"contents",
"of",
"an",
"8",
"-",
"bit",
"register",
"into",
"a",
"memory",
"location",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/__init__.py#L4691-L4714 | def _set_queues_state(self, v, load=False):
"""
Setter method for queues_state, mapped from YANG variable /queues_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_queues_state is considered as a private
method. Backends looking to populate this varia... | [
"def",
"_set_queues_state",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"b... | Setter method for queues_state, mapped from YANG variable /queues_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_queues_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_queues_sta... | [
"Setter",
"method",
"for",
"queues_state",
"mapped",
"from",
"YANG",
"variable",
"/",
"queues_state",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file",
"then... | python | train |
samuraisam/pyapns | pyapns/client.py | https://github.com/samuraisam/pyapns/blob/78c1875f28f8af51c7dd7f60d4436a8b282b0394/pyapns/client.py#L44-L68 | def reprovision_and_retry(func):
"""
Wraps the `errback` callback of the API functions, automatically trying to
re-provision if the app ID can not be found during the operation. If that's
unsuccessful, it will raise the UnknownAppID error.
"""
@functools.wraps(func)
def wrapper(*a, **kw):
errback = kw... | [
"def",
"reprovision_and_retry",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"errback",
"=",
"kw",
".",
"get",
"(",
"'errback'",
",",
"None",
")",
"if",
"... | Wraps the `errback` callback of the API functions, automatically trying to
re-provision if the app ID can not be found during the operation. If that's
unsuccessful, it will raise the UnknownAppID error. | [
"Wraps",
"the",
"errback",
"callback",
"of",
"the",
"API",
"functions",
"automatically",
"trying",
"to",
"re",
"-",
"provision",
"if",
"the",
"app",
"ID",
"can",
"not",
"be",
"found",
"during",
"the",
"operation",
".",
"If",
"that",
"s",
"unsuccessful",
"i... | python | train |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/flask/app.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/flask/app.py#L1412-L1423 | def log_exception(self, exc_info):
"""Logs an exception. This is called by :meth:`handle_exception`
if debugging is disabled and right before the handler is called.
The default implementation logs the exception as error on the
:attr:`logger`.
.. versionadded:: 0.8
"""
... | [
"def",
"log_exception",
"(",
"self",
",",
"exc_info",
")",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'Exception on %s [%s]'",
"%",
"(",
"request",
".",
"path",
",",
"request",
".",
"method",
")",
",",
"exc_info",
"=",
"exc_info",
")"
] | Logs an exception. This is called by :meth:`handle_exception`
if debugging is disabled and right before the handler is called.
The default implementation logs the exception as error on the
:attr:`logger`.
.. versionadded:: 0.8 | [
"Logs",
"an",
"exception",
".",
"This",
"is",
"called",
"by",
":",
"meth",
":",
"handle_exception",
"if",
"debugging",
"is",
"disabled",
"and",
"right",
"before",
"the",
"handler",
"is",
"called",
".",
"The",
"default",
"implementation",
"logs",
"the",
"exce... | python | test |
numenta/htmresearch | htmresearch/algorithms/column_pooler.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/column_pooler.py#L455-L468 | def numberOfConnectedProximalSynapses(self, cells=None):
"""
Returns the number of proximal connected synapses on these cells.
Parameters:
----------------------------
@param cells (iterable)
Indices of the cells. If None return count for all cells.
"""
if cells is None:
... | [
"def",
"numberOfConnectedProximalSynapses",
"(",
"self",
",",
"cells",
"=",
"None",
")",
":",
"if",
"cells",
"is",
"None",
":",
"cells",
"=",
"xrange",
"(",
"self",
".",
"numberOfCells",
"(",
")",
")",
"return",
"_countWhereGreaterEqualInRows",
"(",
"self",
... | Returns the number of proximal connected synapses on these cells.
Parameters:
----------------------------
@param cells (iterable)
Indices of the cells. If None return count for all cells. | [
"Returns",
"the",
"number",
"of",
"proximal",
"connected",
"synapses",
"on",
"these",
"cells",
"."
] | python | train |
jaraco/jaraco.itertools | jaraco/itertools.py | https://github.com/jaraco/jaraco.itertools/blob/0dc47c8924fa3d9ab676c3a6e195f03f728b72c6/jaraco/itertools.py#L573-L586 | def every_other(iterable):
"""
Yield every other item from the iterable
>>> ' '.join(every_other('abcdefg'))
'a c e g'
"""
items = iter(iterable)
while True:
try:
yield next(items)
next(items)
except StopIteration:
return | [
"def",
"every_other",
"(",
"iterable",
")",
":",
"items",
"=",
"iter",
"(",
"iterable",
")",
"while",
"True",
":",
"try",
":",
"yield",
"next",
"(",
"items",
")",
"next",
"(",
"items",
")",
"except",
"StopIteration",
":",
"return"
] | Yield every other item from the iterable
>>> ' '.join(every_other('abcdefg'))
'a c e g' | [
"Yield",
"every",
"other",
"item",
"from",
"the",
"iterable"
] | python | test |
evhub/coconut | coconut/compiler/grammar.py | https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/grammar.py#L630-L646 | def split_func_name_args_params_handle(tokens):
"""Process splitting a function into name, params, and args."""
internal_assert(len(tokens) == 2, "invalid function definition splitting tokens", tokens)
func_name = tokens[0]
func_args = []
func_params = []
for arg in tokens[1]:
if len(arg... | [
"def",
"split_func_name_args_params_handle",
"(",
"tokens",
")",
":",
"internal_assert",
"(",
"len",
"(",
"tokens",
")",
"==",
"2",
",",
"\"invalid function definition splitting tokens\"",
",",
"tokens",
")",
"func_name",
"=",
"tokens",
"[",
"0",
"]",
"func_args",
... | Process splitting a function into name, params, and args. | [
"Process",
"splitting",
"a",
"function",
"into",
"name",
"params",
"and",
"args",
"."
] | python | train |
mar10/wsgidav | wsgidav/samples/hg_dav_provider.py | https://github.com/mar10/wsgidav/blob/cec0d84222fc24bea01be1cea91729001963f172/wsgidav/samples/hg_dav_provider.py#L579-L629 | def get_resource_inst(self, path, environ):
"""Return HgResource object for path.
See DAVProvider.get_resource_inst()
"""
self._count_get_resource_inst += 1
# HG expects the resource paths without leading '/'
localHgPath = path.strip("/")
rev = None
cmd,... | [
"def",
"get_resource_inst",
"(",
"self",
",",
"path",
",",
"environ",
")",
":",
"self",
".",
"_count_get_resource_inst",
"+=",
"1",
"# HG expects the resource paths without leading '/'",
"localHgPath",
"=",
"path",
".",
"strip",
"(",
"\"/\"",
")",
"rev",
"=",
"Non... | Return HgResource object for path.
See DAVProvider.get_resource_inst() | [
"Return",
"HgResource",
"object",
"for",
"path",
"."
] | python | valid |
pyca/pynacl | src/nacl/pwhash/argon2i.py | https://github.com/pyca/pynacl/blob/0df0c2c7693fa5d316846111ce510702756f5feb/src/nacl/pwhash/argon2i.py#L57-L110 | def kdf(size, password, salt,
opslimit=OPSLIMIT_SENSITIVE,
memlimit=MEMLIMIT_SENSITIVE,
encoder=nacl.encoding.RawEncoder):
"""
Derive a ``size`` bytes long key from a caller-supplied
``password`` and ``salt`` pair using the argon2i
memory-hard construct.
the enclosing module... | [
"def",
"kdf",
"(",
"size",
",",
"password",
",",
"salt",
",",
"opslimit",
"=",
"OPSLIMIT_SENSITIVE",
",",
"memlimit",
"=",
"MEMLIMIT_SENSITIVE",
",",
"encoder",
"=",
"nacl",
".",
"encoding",
".",
"RawEncoder",
")",
":",
"return",
"encoder",
".",
"encode",
... | Derive a ``size`` bytes long key from a caller-supplied
``password`` and ``salt`` pair using the argon2i
memory-hard construct.
the enclosing module provides the constants
- :py:const:`.OPSLIMIT_INTERACTIVE`
- :py:const:`.MEMLIMIT_INTERACTIVE`
- :py:const:`.OPSLIMIT_MODERATE`
... | [
"Derive",
"a",
"size",
"bytes",
"long",
"key",
"from",
"a",
"caller",
"-",
"supplied",
"password",
"and",
"salt",
"pair",
"using",
"the",
"argon2i",
"memory",
"-",
"hard",
"construct",
"."
] | python | train |
mishbahr/djangocms-twitter2 | djangocms_twitter/templatetags/djangocms_twitter.py | https://github.com/mishbahr/djangocms-twitter2/blob/01b6f63f812ceee80c0b6ffe8bddbd52723fd71a/djangocms_twitter/templatetags/djangocms_twitter.py#L26-L64 | def urlize_tweet(tweet):
""" Turn #hashtag and @username in a text to Twitter hyperlinks,
similar to the ``urlize()`` function in Django.
Replace shortened URLs with long URLs in the twitter status,
and add the "RT" flag. Should be used before urlize_tweet
"""
if tweet['retweeted']:... | [
"def",
"urlize_tweet",
"(",
"tweet",
")",
":",
"if",
"tweet",
"[",
"'retweeted'",
"]",
":",
"text",
"=",
"'RT {user}: {text}'",
".",
"format",
"(",
"user",
"=",
"TWITTER_USERNAME_URL",
".",
"format",
"(",
"screen_name",
"=",
"tweet",
"[",
"'user'",
"]",
"[... | Turn #hashtag and @username in a text to Twitter hyperlinks,
similar to the ``urlize()`` function in Django.
Replace shortened URLs with long URLs in the twitter status,
and add the "RT" flag. Should be used before urlize_tweet | [
"Turn",
"#hashtag",
"and",
"@username",
"in",
"a",
"text",
"to",
"Twitter",
"hyperlinks",
"similar",
"to",
"the",
"urlize",
"()",
"function",
"in",
"Django",
"."
] | python | train |
scidash/sciunit | setup.py | https://github.com/scidash/sciunit/blob/41b2e38c45c0776727ab1f281a572b65be19cea1/setup.py#L21-L26 | def read_requirements():
'''parses requirements from requirements.txt'''
reqs_path = os.path.join('.', 'requirements.txt')
install_reqs = parse_requirements(reqs_path, session=PipSession())
reqs = [str(ir.req) for ir in install_reqs]
return reqs | [
"def",
"read_requirements",
"(",
")",
":",
"reqs_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'.'",
",",
"'requirements.txt'",
")",
"install_reqs",
"=",
"parse_requirements",
"(",
"reqs_path",
",",
"session",
"=",
"PipSession",
"(",
")",
")",
"reqs",
... | parses requirements from requirements.txt | [
"parses",
"requirements",
"from",
"requirements",
".",
"txt"
] | python | train |
saltstack/salt | salt/beacons/__init__.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/__init__.py#L263-L286 | def validate_beacon(self, name, beacon_data):
'''
Return available beacon functions
'''
validate_str = '{}.validate'.format(name)
# Run the validate function if it's available,
# otherwise there is a warning about it being missing
if validate_str in self.beacons:
... | [
"def",
"validate_beacon",
"(",
"self",
",",
"name",
",",
"beacon_data",
")",
":",
"validate_str",
"=",
"'{}.validate'",
".",
"format",
"(",
"name",
")",
"# Run the validate function if it's available,",
"# otherwise there is a warning about it being missing",
"if",
"validat... | Return available beacon functions | [
"Return",
"available",
"beacon",
"functions"
] | python | train |
materialsproject/pymatgen | pymatgen/analysis/nmr.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/nmr.py#L149-L153 | def principal_axis_system(self):
"""
Returns a electric field gradient tensor aligned to the principle axis system so that only the 3 diagnol components are non-zero
"""
return ElectricFieldGradient(np.diag(np.sort(np.linalg.eigvals(self)))) | [
"def",
"principal_axis_system",
"(",
"self",
")",
":",
"return",
"ElectricFieldGradient",
"(",
"np",
".",
"diag",
"(",
"np",
".",
"sort",
"(",
"np",
".",
"linalg",
".",
"eigvals",
"(",
"self",
")",
")",
")",
")"
] | Returns a electric field gradient tensor aligned to the principle axis system so that only the 3 diagnol components are non-zero | [
"Returns",
"a",
"electric",
"field",
"gradient",
"tensor",
"aligned",
"to",
"the",
"principle",
"axis",
"system",
"so",
"that",
"only",
"the",
"3",
"diagnol",
"components",
"are",
"non",
"-",
"zero"
] | python | train |
ethereum/py-geth | geth/utils/filesystem.py | https://github.com/ethereum/py-geth/blob/ad462e7c841ebd9363b318889252e1f7d7c09c56/geth/utils/filesystem.py#L21-L28 | def ensure_path_exists(dir_path):
"""
Make sure that a path exists
"""
if not os.path.exists(dir_path):
mkdir(dir_path)
return True
return False | [
"def",
"ensure_path_exists",
"(",
"dir_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dir_path",
")",
":",
"mkdir",
"(",
"dir_path",
")",
"return",
"True",
"return",
"False"
] | Make sure that a path exists | [
"Make",
"sure",
"that",
"a",
"path",
"exists"
] | python | train |
limodou/uliweb | uliweb/lib/werkzeug/wrappers.py | https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L885-L906 | def _ensure_sequence(self, mutable=False):
"""This method can be called by methods that need a sequence. If
`mutable` is true, it will also ensure that the response sequence
is a standard Python list.
.. versionadded:: 0.6
"""
if self.is_sequence:
# if we ne... | [
"def",
"_ensure_sequence",
"(",
"self",
",",
"mutable",
"=",
"False",
")",
":",
"if",
"self",
".",
"is_sequence",
":",
"# if we need a mutable object, we ensure it's a list.",
"if",
"mutable",
"and",
"not",
"isinstance",
"(",
"self",
".",
"response",
",",
"list",
... | This method can be called by methods that need a sequence. If
`mutable` is true, it will also ensure that the response sequence
is a standard Python list.
.. versionadded:: 0.6 | [
"This",
"method",
"can",
"be",
"called",
"by",
"methods",
"that",
"need",
"a",
"sequence",
".",
"If",
"mutable",
"is",
"true",
"it",
"will",
"also",
"ensure",
"that",
"the",
"response",
"sequence",
"is",
"a",
"standard",
"Python",
"list",
"."
] | python | train |
watchforstock/evohome-client | evohomeclient/__init__.py | https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L135-L139 | def get_modes(self, zone):
"""Returns the set of modes the device can be assigned."""
self._populate_full_data()
device = self._get_device(zone)
return device['thermostat']['allowedModes'] | [
"def",
"get_modes",
"(",
"self",
",",
"zone",
")",
":",
"self",
".",
"_populate_full_data",
"(",
")",
"device",
"=",
"self",
".",
"_get_device",
"(",
"zone",
")",
"return",
"device",
"[",
"'thermostat'",
"]",
"[",
"'allowedModes'",
"]"
] | Returns the set of modes the device can be assigned. | [
"Returns",
"the",
"set",
"of",
"modes",
"the",
"device",
"can",
"be",
"assigned",
"."
] | python | train |
atlassian-api/atlassian-python-api | atlassian/confluence.py | https://github.com/atlassian-api/atlassian-python-api/blob/540d269905c3e7547b666fe30c647b2d512cf358/atlassian/confluence.py#L119-L139 | def get_page_labels(self, page_id, prefix=None, start=None, limit=None):
"""
Returns the list of labels on a piece of Content.
:param page_id: A string containing the id of the labels content container.
:param prefix: OPTIONAL: The prefixes to filter the labels with {@see Label.Prefix}.
... | [
"def",
"get_page_labels",
"(",
"self",
",",
"page_id",
",",
"prefix",
"=",
"None",
",",
"start",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"url",
"=",
"'rest/api/content/{id}/label'",
".",
"format",
"(",
"id",
"=",
"page_id",
")",
"params",
"=",
... | Returns the list of labels on a piece of Content.
:param page_id: A string containing the id of the labels content container.
:param prefix: OPTIONAL: The prefixes to filter the labels with {@see Label.Prefix}.
Default: None.
:param start: OPTIONAL: The start poin... | [
"Returns",
"the",
"list",
"of",
"labels",
"on",
"a",
"piece",
"of",
"Content",
".",
":",
"param",
"page_id",
":",
"A",
"string",
"containing",
"the",
"id",
"of",
"the",
"labels",
"content",
"container",
".",
":",
"param",
"prefix",
":",
"OPTIONAL",
":",
... | python | train |
chaoss/grimoirelab-perceval | perceval/backends/core/launchpad.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/launchpad.py#L307-L331 | def user(self, user_name):
"""Get the user data by URL"""
user = None
if user_name in self._users:
return self._users[user_name]
url_user = self.__get_url("~" + user_name)
logger.info("Getting info for %s" % (url_user))
try:
raw_user = self.__... | [
"def",
"user",
"(",
"self",
",",
"user_name",
")",
":",
"user",
"=",
"None",
"if",
"user_name",
"in",
"self",
".",
"_users",
":",
"return",
"self",
".",
"_users",
"[",
"user_name",
"]",
"url_user",
"=",
"self",
".",
"__get_url",
"(",
"\"~\"",
"+",
"u... | Get the user data by URL | [
"Get",
"the",
"user",
"data",
"by",
"URL"
] | python | test |
PythonCharmers/python-future | src/future/backports/datetime.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/datetime.py#L1448-L1455 | def utctimetuple(self):
"Return UTC time tuple compatible with time.gmtime()."
offset = self.utcoffset()
if offset:
self -= offset
y, m, d = self.year, self.month, self.day
hh, mm, ss = self.hour, self.minute, self.second
return _build_struct_time(y, m, d, hh,... | [
"def",
"utctimetuple",
"(",
"self",
")",
":",
"offset",
"=",
"self",
".",
"utcoffset",
"(",
")",
"if",
"offset",
":",
"self",
"-=",
"offset",
"y",
",",
"m",
",",
"d",
"=",
"self",
".",
"year",
",",
"self",
".",
"month",
",",
"self",
".",
"day",
... | Return UTC time tuple compatible with time.gmtime(). | [
"Return",
"UTC",
"time",
"tuple",
"compatible",
"with",
"time",
".",
"gmtime",
"()",
"."
] | python | train |
cdeboever3/cdpybio | cdpybio/featureCounts.py | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/featureCounts.py#L3-L35 | def combine_counts(
fns,
define_sample_name=None,
):
"""
Combine featureCounts output files for multiple samples.
Parameters
----------
fns : list of strings
Filenames of featureCounts output files to combine.
define_sample_name : function
A function mapping the featur... | [
"def",
"combine_counts",
"(",
"fns",
",",
"define_sample_name",
"=",
"None",
",",
")",
":",
"counts",
"=",
"[",
"]",
"for",
"fn",
"in",
"fns",
":",
"df",
"=",
"pd",
".",
"read_table",
"(",
"fn",
",",
"skiprows",
"=",
"1",
",",
"index_col",
"=",
"0"... | Combine featureCounts output files for multiple samples.
Parameters
----------
fns : list of strings
Filenames of featureCounts output files to combine.
define_sample_name : function
A function mapping the featureCounts output filenames to sample names.
If this is not provided... | [
"Combine",
"featureCounts",
"output",
"files",
"for",
"multiple",
"samples",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.