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 |
|---|---|---|---|---|---|---|---|---|
aiidalab/aiidalab-widgets-base | aiidalab_widgets_base/computers.py | https://github.com/aiidalab/aiidalab-widgets-base/blob/291a9b159eac902aee655862322670ec1b0cd5b1/aiidalab_widgets_base/computers.py#L351-L355 | def __proxy_password(self):
"""Returning the password and immediately destroying it"""
passwd = copy(self._inp_proxy_password.value)
self._inp_proxy_password.value = ''
return passwd | [
"def",
"__proxy_password",
"(",
"self",
")",
":",
"passwd",
"=",
"copy",
"(",
"self",
".",
"_inp_proxy_password",
".",
"value",
")",
"self",
".",
"_inp_proxy_password",
".",
"value",
"=",
"''",
"return",
"passwd"
] | Returning the password and immediately destroying it | [
"Returning",
"the",
"password",
"and",
"immediately",
"destroying",
"it"
] | python | train |
PmagPy/PmagPy | pmagpy/ipmag.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/ipmag.py#L1672-L1713 | def make_orthographic_map(central_longitude=0, central_latitude=0, figsize=(8, 8),
add_land=True, land_color='tan', add_ocean=False, ocean_color='lightblue', grid_lines=True,
lat_grid=[-80., -60., -30.,
0., 30., 60., 80.],
... | [
"def",
"make_orthographic_map",
"(",
"central_longitude",
"=",
"0",
",",
"central_latitude",
"=",
"0",
",",
"figsize",
"=",
"(",
"8",
",",
"8",
")",
",",
"add_land",
"=",
"True",
",",
"land_color",
"=",
"'tan'",
",",
"add_ocean",
"=",
"False",
",",
"ocea... | Function creates and returns an orthographic map projection using cartopy
Example
-------
>>> map_axis = make_orthographic_map(central_longitude=200,central_latitude=30)
Optional Parameters
-----------
central_longitude : central longitude of projection (default is 0)
central_latitude : ce... | [
"Function",
"creates",
"and",
"returns",
"an",
"orthographic",
"map",
"projection",
"using",
"cartopy"
] | python | train |
Azure/azure-sdk-for-python | azure-mgmt-containerservice/azure/mgmt/containerservice/v2018_08_01_preview/operations/managed_clusters_operations.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-mgmt-containerservice/azure/mgmt/containerservice/v2018_08_01_preview/operations/managed_clusters_operations.py#L850-L897 | def reset_service_principal_profile(
self, resource_group_name, resource_name, client_id, secret=None, custom_headers=None, raw=False, polling=True, **operation_config):
"""Reset Service Principal Profile of a managed cluster.
Update the service principal Profile for a managed cluster.
... | [
"def",
"reset_service_principal_profile",
"(",
"self",
",",
"resource_group_name",
",",
"resource_name",
",",
"client_id",
",",
"secret",
"=",
"None",
",",
"custom_headers",
"=",
"None",
",",
"raw",
"=",
"False",
",",
"polling",
"=",
"True",
",",
"*",
"*",
"... | Reset Service Principal Profile of a managed cluster.
Update the service principal Profile for a managed cluster.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param resource_name: The name of the managed cluster resource.
:type res... | [
"Reset",
"Service",
"Principal",
"Profile",
"of",
"a",
"managed",
"cluster",
"."
] | python | test |
jilljenn/tryalgo | tryalgo/huffman.py | https://github.com/jilljenn/tryalgo/blob/89a4dd9655e7b6b0a176f72b4c60d0196420dfe1/tryalgo/huffman.py#L29-L46 | def extract(code, tree, prefix=[]):
"""Extract Huffman code from a Huffman tree
:param tree: a node of the tree
:param prefix: a list with the 01 characters encoding the path from
the root to the node `tree`
:complexity: O(n)
"""
if isinstance(tree, list):
l, r = tre... | [
"def",
"extract",
"(",
"code",
",",
"tree",
",",
"prefix",
"=",
"[",
"]",
")",
":",
"if",
"isinstance",
"(",
"tree",
",",
"list",
")",
":",
"l",
",",
"r",
"=",
"tree",
"prefix",
".",
"append",
"(",
"'0'",
")",
"extract",
"(",
"code",
",",
"l",
... | Extract Huffman code from a Huffman tree
:param tree: a node of the tree
:param prefix: a list with the 01 characters encoding the path from
the root to the node `tree`
:complexity: O(n) | [
"Extract",
"Huffman",
"code",
"from",
"a",
"Huffman",
"tree"
] | python | train |
chaoss/grimoirelab-sigils | src/migration/to_kibana5.py | https://github.com/chaoss/grimoirelab-sigils/blob/33d395195acb316287143a535a2c6e4009bf0528/src/migration/to_kibana5.py#L40-L84 | def main():
"""Read a directory containing json files for Kibana panels,
beautify them and replace size value in aggregations as specified
through corresponding params params.
"""
args = parse_args()
configure_logging(args.debug)
src_path = args.src_path
dest_path = args.dest_path
o... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"configure_logging",
"(",
"args",
".",
"debug",
")",
"src_path",
"=",
"args",
".",
"src_path",
"dest_path",
"=",
"args",
".",
"dest_path",
"old_str1",
"=",
"'\\\\\"size\\\\\":'",
"+",
"args... | Read a directory containing json files for Kibana panels,
beautify them and replace size value in aggregations as specified
through corresponding params params. | [
"Read",
"a",
"directory",
"containing",
"json",
"files",
"for",
"Kibana",
"panels",
"beautify",
"them",
"and",
"replace",
"size",
"value",
"in",
"aggregations",
"as",
"specified",
"through",
"corresponding",
"params",
"params",
"."
] | python | train |
bitesofcode/projexui | projexui/widgets/xorbrecordbox.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordbox.py#L292-L309 | def dragEnterEvent(self, event):
"""
Listens for query's being dragged and dropped onto this tree.
:param event | <QDragEnterEvent>
"""
data = event.mimeData()
if data.hasFormat('application/x-orb-table') and \
data.hasFormat('application/... | [
"def",
"dragEnterEvent",
"(",
"self",
",",
"event",
")",
":",
"data",
"=",
"event",
".",
"mimeData",
"(",
")",
"if",
"data",
".",
"hasFormat",
"(",
"'application/x-orb-table'",
")",
"and",
"data",
".",
"hasFormat",
"(",
"'application/x-orb-query'",
")",
":",... | Listens for query's being dragged and dropped onto this tree.
:param event | <QDragEnterEvent> | [
"Listens",
"for",
"query",
"s",
"being",
"dragged",
"and",
"dropped",
"onto",
"this",
"tree",
".",
":",
"param",
"event",
"|",
"<QDragEnterEvent",
">"
] | python | train |
odlgroup/odl | odl/space/fspace.py | https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L698-L734 | def astype(self, out_dtype):
"""Return a copy of this space with new ``out_dtype``.
Parameters
----------
out_dtype :
Output data type of the returned space. Can be given in any
way `numpy.dtype` understands, e.g. as string (``'complex64'``)
or built-... | [
"def",
"astype",
"(",
"self",
",",
"out_dtype",
")",
":",
"out_dtype",
"=",
"np",
".",
"dtype",
"(",
"out_dtype",
")",
"if",
"out_dtype",
"==",
"self",
".",
"out_dtype",
":",
"return",
"self",
"# Try to use caching for real and complex versions (exact dtype",
"# m... | Return a copy of this space with new ``out_dtype``.
Parameters
----------
out_dtype :
Output data type of the returned space. Can be given in any
way `numpy.dtype` understands, e.g. as string (``'complex64'``)
or built-in type (``complex``). ``None`` is inter... | [
"Return",
"a",
"copy",
"of",
"this",
"space",
"with",
"new",
"out_dtype",
"."
] | python | train |
DeepHorizons/iarm | iarm/arm_instructions/arithmetic.py | https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/arithmetic.py#L301-L347 | def SUBS(self, params):
"""
SUBS [Ra,] Rb, Rc
SUBS [Ra,] Rb, #imm3
SUBS [Ra,] Ra, #imm8
Subtract Rc or an immediate from Rb and store the result in Ra
Ra, Rb, and Rc must be low registers
If Ra is omitted, then it is assumed to be Rb
"""
# This in... | [
"def",
"SUBS",
"(",
"self",
",",
"params",
")",
":",
"# This instruction allows for an optional destination register",
"# If it is omitted, then it is assumed to be Rb",
"# As defined in http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0662b/index.html",
"try",
":",
"Ra",
"... | SUBS [Ra,] Rb, Rc
SUBS [Ra,] Rb, #imm3
SUBS [Ra,] Ra, #imm8
Subtract Rc or an immediate from Rb and store the result in Ra
Ra, Rb, and Rc must be low registers
If Ra is omitted, then it is assumed to be Rb | [
"SUBS",
"[",
"Ra",
"]",
"Rb",
"Rc",
"SUBS",
"[",
"Ra",
"]",
"Rb",
"#imm3",
"SUBS",
"[",
"Ra",
"]",
"Ra",
"#imm8"
] | python | train |
inveniosoftware-attic/invenio-utils | invenio_utils/autodiscovery/helpers.py | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/autodiscovery/helpers.py#L27-L69 | def get_callable_signature_as_string(the_callable):
"""Return a string representing a callable.
It is executed as if it would have been declared on the prompt.
>>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd):
... pass
>>> get_callable_signature_as_string(foo)
def foo(arg1,... | [
"def",
"get_callable_signature_as_string",
"(",
"the_callable",
")",
":",
"args",
",",
"varargs",
",",
"varkw",
",",
"defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"the_callable",
")",
"tmp_args",
"=",
"list",
"(",
"args",
")",
"args_dict",
"=",
"{",
"}... | Return a string representing a callable.
It is executed as if it would have been declared on the prompt.
>>> def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd):
... pass
>>> get_callable_signature_as_string(foo)
def foo(arg1, arg2, arg3='val1', arg4='val2', *args, **argd)
:param... | [
"Return",
"a",
"string",
"representing",
"a",
"callable",
"."
] | python | train |
DolphDev/ezurl | ezurl/ezurllib.py | https://github.com/DolphDev/ezurl/blob/deaa755db2c0532c237f9eb4192aa51c7e928a07/ezurl/ezurllib.py#L13-L74 | def urlencode2(query, doseq=0, safe="", querydelimiter="&"):
"""Encode a sequence of two-element tuples or dictionary into a URL query string.
If any values in the query arg are sequences and doseq is true, each
sequence element is converted to a separate parameter.
If the query arg is a sequence of t... | [
"def",
"urlencode2",
"(",
"query",
",",
"doseq",
"=",
"0",
",",
"safe",
"=",
"\"\"",
",",
"querydelimiter",
"=",
"\"&\"",
")",
":",
"if",
"hasattr",
"(",
"query",
",",
"\"items\"",
")",
":",
"# mapping objects",
"query",
"=",
"query",
".",
"items",
"("... | Encode a sequence of two-element tuples or dictionary into a URL query string.
If any values in the query arg are sequences and doseq is true, each
sequence element is converted to a separate parameter.
If the query arg is a sequence of two-element tuples, the order of the
parameters in the output wil... | [
"Encode",
"a",
"sequence",
"of",
"two",
"-",
"element",
"tuples",
"or",
"dictionary",
"into",
"a",
"URL",
"query",
"string",
"."
] | python | train |
dschreij/python-mediadecoder | mediadecoder/decoder.py | https://github.com/dschreij/python-mediadecoder/blob/f01b02d790f2abc52d9792e43076cf4cb7d3ce51/mediadecoder/decoder.py#L404-L415 | def __render_videoframe(self):
""" Retrieves a new videoframe from the stream.
Sets the frame as the __current_video_frame and passes it on to
__videorenderfunc() if it is set. """
new_videoframe = self.clip.get_frame(self.clock.time)
# Pass it to the callback function if this is set
if callable(self.__vi... | [
"def",
"__render_videoframe",
"(",
"self",
")",
":",
"new_videoframe",
"=",
"self",
".",
"clip",
".",
"get_frame",
"(",
"self",
".",
"clock",
".",
"time",
")",
"# Pass it to the callback function if this is set",
"if",
"callable",
"(",
"self",
".",
"__videorenderf... | Retrieves a new videoframe from the stream.
Sets the frame as the __current_video_frame and passes it on to
__videorenderfunc() if it is set. | [
"Retrieves",
"a",
"new",
"videoframe",
"from",
"the",
"stream",
"."
] | python | train |
vsoch/helpme | helpme/main/base/__init__.py | https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/main/base/__init__.py#L257-L267 | def speak(self):
'''
a function for the helper to announce him or herself, depending
on the level specified. If you want your client to have additional
announced things here, then implement the class `_speak` for your
client.
'''
if self.quiet is Fals... | [
"def",
"speak",
"(",
"self",
")",
":",
"if",
"self",
".",
"quiet",
"is",
"False",
":",
"bot",
".",
"info",
"(",
"'[helper|%s]'",
"%",
"(",
"self",
".",
"name",
")",
")",
"self",
".",
"_speak",
"(",
")"
] | a function for the helper to announce him or herself, depending
on the level specified. If you want your client to have additional
announced things here, then implement the class `_speak` for your
client. | [
"a",
"function",
"for",
"the",
"helper",
"to",
"announce",
"him",
"or",
"herself",
"depending",
"on",
"the",
"level",
"specified",
".",
"If",
"you",
"want",
"your",
"client",
"to",
"have",
"additional",
"announced",
"things",
"here",
"then",
"implement",
"th... | python | train |
pydata/pandas-gbq | pandas_gbq/gbq.py | https://github.com/pydata/pandas-gbq/blob/e590317b3325939ede7563f49aa6b163bb803b77/pandas_gbq/gbq.py#L697-L722 | def _cast_empty_df_dtypes(schema_fields, df):
"""Cast any columns in an empty dataframe to correct type.
In an empty dataframe, pandas cannot choose a dtype unless one is
explicitly provided. The _bqschema_to_nullsafe_dtypes() function only
provides dtypes when the dtype safely handles null values. Thi... | [
"def",
"_cast_empty_df_dtypes",
"(",
"schema_fields",
",",
"df",
")",
":",
"if",
"not",
"df",
".",
"empty",
":",
"raise",
"ValueError",
"(",
"\"DataFrame must be empty in order to cast non-nullsafe dtypes\"",
")",
"dtype_map",
"=",
"{",
"\"BOOLEAN\"",
":",
"bool",
"... | Cast any columns in an empty dataframe to correct type.
In an empty dataframe, pandas cannot choose a dtype unless one is
explicitly provided. The _bqschema_to_nullsafe_dtypes() function only
provides dtypes when the dtype safely handles null values. This means
that empty int64 and boolean columns are ... | [
"Cast",
"any",
"columns",
"in",
"an",
"empty",
"dataframe",
"to",
"correct",
"type",
"."
] | python | train |
ClericPy/torequests | torequests/dummy.py | https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/dummy.py#L323-L329 | async def pendings(self, tasks=None):
"""Used for await in coroutines.
`await loop.pendings()`
`await loop.pendings(tasks)`
"""
tasks = tasks or self.todo_tasks
await asyncio.gather(*tasks, loop=self.loop) | [
"async",
"def",
"pendings",
"(",
"self",
",",
"tasks",
"=",
"None",
")",
":",
"tasks",
"=",
"tasks",
"or",
"self",
".",
"todo_tasks",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"tasks",
",",
"loop",
"=",
"self",
".",
"loop",
")"
] | Used for await in coroutines.
`await loop.pendings()`
`await loop.pendings(tasks)` | [
"Used",
"for",
"await",
"in",
"coroutines",
".",
"await",
"loop",
".",
"pendings",
"()",
"await",
"loop",
".",
"pendings",
"(",
"tasks",
")"
] | python | train |
Rapptz/discord.py | discord/user.py | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/user.py#L342-L349 | def friends(self):
r"""Returns a :class:`list` of :class:`User`\s that the user is friends with.
.. note::
This only applies to non-bot accounts.
"""
return [r.user for r in self._relationships.values() if r.type is RelationshipType.friend] | [
"def",
"friends",
"(",
"self",
")",
":",
"return",
"[",
"r",
".",
"user",
"for",
"r",
"in",
"self",
".",
"_relationships",
".",
"values",
"(",
")",
"if",
"r",
".",
"type",
"is",
"RelationshipType",
".",
"friend",
"]"
] | r"""Returns a :class:`list` of :class:`User`\s that the user is friends with.
.. note::
This only applies to non-bot accounts. | [
"r",
"Returns",
"a",
":",
"class",
":",
"list",
"of",
":",
"class",
":",
"User",
"\\",
"s",
"that",
"the",
"user",
"is",
"friends",
"with",
"."
] | python | train |
mbodenhamer/syn | syn/schema/b/sequence.py | https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/schema/b/sequence.py#L245-L251 | def enumerate(self, **kwargs):
'''Iterate through all possible sequences (lists). By default, will
stop after 50 items have been yielded. This value can be
change by supplying a different value via the max_enumerate kwarg.
'''
for item in self.set.enumerate(**kwargs):
... | [
"def",
"enumerate",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"item",
"in",
"self",
".",
"set",
".",
"enumerate",
"(",
"*",
"*",
"kwargs",
")",
":",
"yield",
"flattened",
"(",
"item",
")"
] | Iterate through all possible sequences (lists). By default, will
stop after 50 items have been yielded. This value can be
change by supplying a different value via the max_enumerate kwarg. | [
"Iterate",
"through",
"all",
"possible",
"sequences",
"(",
"lists",
")",
".",
"By",
"default",
"will",
"stop",
"after",
"50",
"items",
"have",
"been",
"yielded",
".",
"This",
"value",
"can",
"be",
"change",
"by",
"supplying",
"a",
"different",
"value",
"vi... | python | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/property_set.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/property_set.py#L307-L312 | def incidental (self):
""" Returns incidental properties.
"""
result = [p for p in self.lazy_properties if p.feature.incidental]
result.extend(self.incidental_)
return result | [
"def",
"incidental",
"(",
"self",
")",
":",
"result",
"=",
"[",
"p",
"for",
"p",
"in",
"self",
".",
"lazy_properties",
"if",
"p",
".",
"feature",
".",
"incidental",
"]",
"result",
".",
"extend",
"(",
"self",
".",
"incidental_",
")",
"return",
"result"
... | Returns incidental properties. | [
"Returns",
"incidental",
"properties",
"."
] | python | train |
msmbuilder/msmbuilder | msmbuilder/featurizer/featurizer.py | https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/featurizer/featurizer.py#L819-L853 | def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space via calculation
of dihedral (torsion) angles of alpha carbon backbone
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
... | [
"def",
"partial_transform",
"(",
"self",
",",
"traj",
")",
":",
"ca",
"=",
"[",
"a",
".",
"index",
"for",
"a",
"in",
"traj",
".",
"top",
".",
"atoms",
"if",
"a",
".",
"name",
"==",
"'CA'",
"]",
"if",
"len",
"(",
"ca",
")",
"<",
"4",
":",
"ret... | Featurize an MD trajectory into a vector space via calculation
of dihedral (torsion) angles of alpha carbon backbone
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features : np.ndarray, d... | [
"Featurize",
"an",
"MD",
"trajectory",
"into",
"a",
"vector",
"space",
"via",
"calculation",
"of",
"dihedral",
"(",
"torsion",
")",
"angles",
"of",
"alpha",
"carbon",
"backbone"
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/discovery_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L6159-L6174 | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'level') and self.level is not None:
_dict['level'] = self.level
if hasattr(self, 'min_size') and self.min_size is not None:
_dict['min_size'] = self.min_size
... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'level'",
")",
"and",
"self",
".",
"level",
"is",
"not",
"None",
":",
"_dict",
"[",
"'level'",
"]",
"=",
"self",
".",
"level",
"if",
"hasattr",
... | Return a json dictionary representing this model. | [
"Return",
"a",
"json",
"dictionary",
"representing",
"this",
"model",
"."
] | python | train |
dbcli/athenacli | athenacli/packages/special/iocommands.py | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/iocommands.py#L219-L235 | def save_favorite_query(arg, **_):
"""Save a new favorite query.
Returns (title, rows, headers, status)"""
usage = 'Syntax: \\fs name query.\n\n' + favoritequeries.usage
if not arg:
return [(None, None, None, usage)]
name, _, query = arg.partition(' ')
# If either name or query is mis... | [
"def",
"save_favorite_query",
"(",
"arg",
",",
"*",
"*",
"_",
")",
":",
"usage",
"=",
"'Syntax: \\\\fs name query.\\n\\n'",
"+",
"favoritequeries",
".",
"usage",
"if",
"not",
"arg",
":",
"return",
"[",
"(",
"None",
",",
"None",
",",
"None",
",",
"usage",
... | Save a new favorite query.
Returns (title, rows, headers, status) | [
"Save",
"a",
"new",
"favorite",
"query",
".",
"Returns",
"(",
"title",
"rows",
"headers",
"status",
")"
] | python | train |
ibm-watson-data-lab/ibmseti | ibmseti/features.py | https://github.com/ibm-watson-data-lab/ibmseti/blob/3361bc0adb4770dc7a554ed7cda292503892acee/ibmseti/features.py#L166-L174 | def maximum_variation(arr):
'''
return np.max(arr, axis=0) - np.min(arr, axis=0)
If `arr` is a 1D array, a scalar is returned.
If `arr` is a 2D array (N x M), an array of length M is returned.
'''
return np.max(arr, axis=0) - np.min(arr, axis=0) | [
"def",
"maximum_variation",
"(",
"arr",
")",
":",
"return",
"np",
".",
"max",
"(",
"arr",
",",
"axis",
"=",
"0",
")",
"-",
"np",
".",
"min",
"(",
"arr",
",",
"axis",
"=",
"0",
")"
] | return np.max(arr, axis=0) - np.min(arr, axis=0)
If `arr` is a 1D array, a scalar is returned.
If `arr` is a 2D array (N x M), an array of length M is returned. | [
"return",
"np",
".",
"max",
"(",
"arr",
"axis",
"=",
"0",
")",
"-",
"np",
".",
"min",
"(",
"arr",
"axis",
"=",
"0",
")"
] | python | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/remote_bridge.py#L129-L137 | def reset_script(self):
"""Clear any partially received script."""
self.remote_bridge.status = BRIDGE_STATUS.IDLE
self.remote_bridge.error = 0
self.remote_bridge.parsed_script = None
self._device.script = bytearray()
return [0] | [
"def",
"reset_script",
"(",
"self",
")",
":",
"self",
".",
"remote_bridge",
".",
"status",
"=",
"BRIDGE_STATUS",
".",
"IDLE",
"self",
".",
"remote_bridge",
".",
"error",
"=",
"0",
"self",
".",
"remote_bridge",
".",
"parsed_script",
"=",
"None",
"self",
"."... | Clear any partially received script. | [
"Clear",
"any",
"partially",
"received",
"script",
"."
] | python | train |
gem/oq-engine | openquake/commonlib/hazard_writers.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commonlib/hazard_writers.py#L218-L237 | def gen_gmfs(gmf_set):
"""
Generate GMF nodes from a gmf_set
:param gmf_set: a sequence of GMF objects with attributes
imt, sa_period, sa_damping, event_id and containing a list
of GMF nodes with attributes gmv and location. The nodes
are sorted by lon/lat.
"""
for gmf in gmf_set:
... | [
"def",
"gen_gmfs",
"(",
"gmf_set",
")",
":",
"for",
"gmf",
"in",
"gmf_set",
":",
"gmf_node",
"=",
"Node",
"(",
"'gmf'",
")",
"gmf_node",
"[",
"'IMT'",
"]",
"=",
"gmf",
".",
"imt",
"if",
"gmf",
".",
"imt",
"==",
"'SA'",
":",
"gmf_node",
"[",
"'saPer... | Generate GMF nodes from a gmf_set
:param gmf_set: a sequence of GMF objects with attributes
imt, sa_period, sa_damping, event_id and containing a list
of GMF nodes with attributes gmv and location. The nodes
are sorted by lon/lat. | [
"Generate",
"GMF",
"nodes",
"from",
"a",
"gmf_set",
":",
"param",
"gmf_set",
":",
"a",
"sequence",
"of",
"GMF",
"objects",
"with",
"attributes",
"imt",
"sa_period",
"sa_damping",
"event_id",
"and",
"containing",
"a",
"list",
"of",
"GMF",
"nodes",
"with",
"at... | python | train |
iotile/coretools | iotilecore/iotile/core/hw/transport/adapter/sync_wrapper.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/hw/transport/adapter/sync_wrapper.py#L218-L241 | def send_script_async(self, conn_id, data, progress_callback, callback):
"""Asynchronously send a script to the device."""
def monitor_callback(_conn_string, _conn_id, _event_name, event):
if event.get('operation') != 'script':
return
progress_callback(event.get... | [
"def",
"send_script_async",
"(",
"self",
",",
"conn_id",
",",
"data",
",",
"progress_callback",
",",
"callback",
")",
":",
"def",
"monitor_callback",
"(",
"_conn_string",
",",
"_conn_id",
",",
"_event_name",
",",
"event",
")",
":",
"if",
"event",
".",
"get",... | Asynchronously send a script to the device. | [
"Asynchronously",
"send",
"a",
"script",
"to",
"the",
"device",
"."
] | python | train |
novopl/peltak | src/peltak/logic/docs.py | https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/logic/docs.py#L32-L89 | def docs(recreate, gen_index, run_doctests):
# type: (bool, bool, bool) -> None
""" Build the documentation for the project.
Args:
recreate (bool):
If set to **True**, the build and output directories will be cleared
prior to generating the docs.
gen_index (bool):
... | [
"def",
"docs",
"(",
"recreate",
",",
"gen_index",
",",
"run_doctests",
")",
":",
"# type: (bool, bool, bool) -> None",
"build_dir",
"=",
"conf",
".",
"get_path",
"(",
"'build_dir'",
",",
"'.build'",
")",
"docs_dir",
"=",
"conf",
".",
"get_path",
"(",
"'docs.path... | Build the documentation for the project.
Args:
recreate (bool):
If set to **True**, the build and output directories will be cleared
prior to generating the docs.
gen_index (bool):
If set to **True**, it will generate top-level index file for the
refe... | [
"Build",
"the",
"documentation",
"for",
"the",
"project",
"."
] | python | train |
PSPC-SPAC-buyandsell/von_anchor | von_anchor/a2a/docutil.py | https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/a2a/docutil.py#L54-L82 | def canon_ref(did: str, ref: str, delimiter: str = None):
"""
Given a reference in a DID document, return it in its canonical form of a URI.
:param did: DID acting as the identifier of the DID document
:param ref: reference to canonicalize, either a DID or a fragment pointing to a location in the DID d... | [
"def",
"canon_ref",
"(",
"did",
":",
"str",
",",
"ref",
":",
"str",
",",
"delimiter",
":",
"str",
"=",
"None",
")",
":",
"if",
"not",
"ok_did",
"(",
"did",
")",
":",
"raise",
"BadIdentifier",
"(",
"'Bad DID {} cannot act as DID document identifier'",
".",
... | Given a reference in a DID document, return it in its canonical form of a URI.
:param did: DID acting as the identifier of the DID document
:param ref: reference to canonicalize, either a DID or a fragment pointing to a location in the DID doc
:param delimiter: delimiter character marking fragment (default... | [
"Given",
"a",
"reference",
"in",
"a",
"DID",
"document",
"return",
"it",
"in",
"its",
"canonical",
"form",
"of",
"a",
"URI",
"."
] | python | train |
kennknowles/python-jsonpath-rw | jsonpath_rw/jsonpath.py | https://github.com/kennknowles/python-jsonpath-rw/blob/f615451d7b405e23e0f80b15cad03b1427b0256d/jsonpath_rw/jsonpath.py#L36-L47 | def child(self, child):
"""
Equivalent to Child(self, next) but with some canonicalization
"""
if isinstance(self, This) or isinstance(self, Root):
return child
elif isinstance(child, This):
return self
elif isinstance(child, Root):
ret... | [
"def",
"child",
"(",
"self",
",",
"child",
")",
":",
"if",
"isinstance",
"(",
"self",
",",
"This",
")",
"or",
"isinstance",
"(",
"self",
",",
"Root",
")",
":",
"return",
"child",
"elif",
"isinstance",
"(",
"child",
",",
"This",
")",
":",
"return",
... | Equivalent to Child(self, next) but with some canonicalization | [
"Equivalent",
"to",
"Child",
"(",
"self",
"next",
")",
"but",
"with",
"some",
"canonicalization"
] | python | train |
DistrictDataLabs/yellowbrick | yellowbrick/features/pcoords.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/pcoords.py#L38-L127 | def parallel_coordinates(X, y, ax=None, features=None, classes=None,
normalize=None, sample=1.0, color=None, colormap=None,
alpha=None, fast=False, vlines=True, vlines_kwds=None,
**kwargs):
"""Displays each feature as a vertical axis and eac... | [
"def",
"parallel_coordinates",
"(",
"X",
",",
"y",
",",
"ax",
"=",
"None",
",",
"features",
"=",
"None",
",",
"classes",
"=",
"None",
",",
"normalize",
"=",
"None",
",",
"sample",
"=",
"1.0",
",",
"color",
"=",
"None",
",",
"colormap",
"=",
"None",
... | Displays each feature as a vertical axis and each instance as a line.
This helper function is a quick wrapper to utilize the ParallelCoordinates
Visualizer (Transformer) for one-off analysis.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m feat... | [
"Displays",
"each",
"feature",
"as",
"a",
"vertical",
"axis",
"and",
"each",
"instance",
"as",
"a",
"line",
"."
] | python | train |
glomex/gcdt | gcdt/utils.py | https://github.com/glomex/gcdt/blob/cd67cf416371337b83cb9ca3f696277125703339/gcdt/utils.py#L32-L47 | def version():
"""Output version of gcdt tools and plugins."""
log.info('gcdt version %s' % __version__)
tools = get_plugin_versions('gcdttool10')
if tools:
log.info('gcdt tools:')
for p, v in tools.items():
log.info(' * %s version %s' % (p, v))
log.info('gcdt plugins:')
... | [
"def",
"version",
"(",
")",
":",
"log",
".",
"info",
"(",
"'gcdt version %s'",
"%",
"__version__",
")",
"tools",
"=",
"get_plugin_versions",
"(",
"'gcdttool10'",
")",
"if",
"tools",
":",
"log",
".",
"info",
"(",
"'gcdt tools:'",
")",
"for",
"p",
",",
"v"... | Output version of gcdt tools and plugins. | [
"Output",
"version",
"of",
"gcdt",
"tools",
"and",
"plugins",
"."
] | python | train |
boundary/pulse-api-cli | boundary/metric_markdown.py | https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/metric_markdown.py#L150-L159 | def printMetrics(self, m, d):
"""
Prints out table rows based on the size of the data in columns
"""
for metric in self.metrics:
mstr = metric['displayName']
dstr = metric['description']
mlen = m - len(mstr)
dlen = d - len(dstr)
... | [
"def",
"printMetrics",
"(",
"self",
",",
"m",
",",
"d",
")",
":",
"for",
"metric",
"in",
"self",
".",
"metrics",
":",
"mstr",
"=",
"metric",
"[",
"'displayName'",
"]",
"dstr",
"=",
"metric",
"[",
"'description'",
"]",
"mlen",
"=",
"m",
"-",
"len",
... | Prints out table rows based on the size of the data in columns | [
"Prints",
"out",
"table",
"rows",
"based",
"on",
"the",
"size",
"of",
"the",
"data",
"in",
"columns"
] | python | test |
MLAB-project/pymlab | examples/I2CSPI_HBSTEP_chain.py | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/examples/I2CSPI_HBSTEP_chain.py#L75-L85 | def Move(self, units):
' Move some distance units from current position '
steps = units * self.SPU # translate units to steps
if steps > 0: # look for direction
spi.SPI_write(self.CS, [0x40 | (~self.Dir & 1), 0x40 | (~self.Dir & 1)])
... | [
"def",
"Move",
"(",
"self",
",",
"units",
")",
":",
"steps",
"=",
"units",
"*",
"self",
".",
"SPU",
"# translate units to steps ",
"if",
"steps",
">",
"0",
":",
"# look for direction",
"spi",
".",
"SPI_write",
"(",
"self",
".",
"CS",
",",
"[",
"0x40",
... | Move some distance units from current position | [
"Move",
"some",
"distance",
"units",
"from",
"current",
"position"
] | python | train |
d0c-s4vage/pfp | pfp/interp.py | https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1238-L1264 | def _handle_packed_metadata(self, node, scope, ctxt, stream):
"""Handle packed metadata
"""
keyvals = node.metadata.keyvals
if "packer" not in keyvals and ("pack" not in keyvals or "unpack" not in keyvals):
raise errors.PfpError("Packed fields require a packer function to be ... | [
"def",
"_handle_packed_metadata",
"(",
"self",
",",
"node",
",",
"scope",
",",
"ctxt",
",",
"stream",
")",
":",
"keyvals",
"=",
"node",
".",
"metadata",
".",
"keyvals",
"if",
"\"packer\"",
"not",
"in",
"keyvals",
"and",
"(",
"\"pack\"",
"not",
"in",
"key... | Handle packed metadata | [
"Handle",
"packed",
"metadata"
] | python | train |
boto/s3transfer | s3transfer/bandwidth.py | https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/bandwidth.py#L329-L338 | def process_scheduled_consumption(self, token):
"""Processes a scheduled consumption request that has completed
:type token: RequestToken
:param token: The token associated to the consumption
request that is used to identify the request.
"""
scheduled_retry = self._t... | [
"def",
"process_scheduled_consumption",
"(",
"self",
",",
"token",
")",
":",
"scheduled_retry",
"=",
"self",
".",
"_tokens_to_scheduled_consumption",
".",
"pop",
"(",
"token",
")",
"self",
".",
"_total_wait",
"=",
"max",
"(",
"self",
".",
"_total_wait",
"-",
"... | Processes a scheduled consumption request that has completed
:type token: RequestToken
:param token: The token associated to the consumption
request that is used to identify the request. | [
"Processes",
"a",
"scheduled",
"consumption",
"request",
"that",
"has",
"completed"
] | python | test |
xmikos/soapy_power | soapypower/psd.py | https://github.com/xmikos/soapy_power/blob/46e12659b8d08af764dc09a1f31b0e85a68f808f/soapypower/psd.py#L46-L62 | def result(self, psd_state):
"""Return freqs and averaged PSD for given center frequency"""
freq_array = numpy.fft.fftshift(psd_state['freq_array'])
pwr_array = numpy.fft.fftshift(psd_state['pwr_array'])
if self._crop_factor:
crop_bins_half = round((self._crop_factor * self.... | [
"def",
"result",
"(",
"self",
",",
"psd_state",
")",
":",
"freq_array",
"=",
"numpy",
".",
"fft",
".",
"fftshift",
"(",
"psd_state",
"[",
"'freq_array'",
"]",
")",
"pwr_array",
"=",
"numpy",
".",
"fft",
".",
"fftshift",
"(",
"psd_state",
"[",
"'pwr_array... | Return freqs and averaged PSD for given center frequency | [
"Return",
"freqs",
"and",
"averaged",
"PSD",
"for",
"given",
"center",
"frequency"
] | python | test |
honzamach/pydgets | pydgets/widgets.py | https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L599-L608 | def _render(self, content, **settings):
"""
Perform widget rendering, but do not print anything.
"""
result = self._render_content(content, **settings)
s = self._es_margin(settings)
result = self.fmt_margin(result, **s)
return result | [
"def",
"_render",
"(",
"self",
",",
"content",
",",
"*",
"*",
"settings",
")",
":",
"result",
"=",
"self",
".",
"_render_content",
"(",
"content",
",",
"*",
"*",
"settings",
")",
"s",
"=",
"self",
".",
"_es_margin",
"(",
"settings",
")",
"result",
"=... | Perform widget rendering, but do not print anything. | [
"Perform",
"widget",
"rendering",
"but",
"do",
"not",
"print",
"anything",
"."
] | python | train |
qzmfranklin/easyshell | easycompleter/python_default.py | https://github.com/qzmfranklin/easyshell/blob/00c2e90e7767d32e7e127fc8c6875845aa308295/easycompleter/python_default.py#L101-L141 | def attr_matches(self, text):
"""Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluable in self.namespace, it will be evaluated and its attributes
(as revealed by dir()) are used as possible completions. (For class
insta... | [
"def",
"attr_matches",
"(",
"self",
",",
"text",
")",
":",
"import",
"re",
"m",
"=",
"re",
".",
"match",
"(",
"r\"(\\w+(\\.\\w+)*)\\.(\\w*)\"",
",",
"text",
")",
"if",
"not",
"m",
":",
"return",
"[",
"]",
"expr",
",",
"attr",
"=",
"m",
".",
"group",
... | Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluable in self.namespace, it will be evaluated and its attributes
(as revealed by dir()) are used as possible completions. (For class
instances, class members are also considered.)... | [
"Compute",
"matches",
"when",
"text",
"contains",
"a",
"dot",
"."
] | python | train |
aparo/pyes | pyes/sort.py | https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/sort.py#L119-L124 | def serialize(self):
"""Serialize the search to a structure as passed for a search body."""
res = []
for _sort in self.sort_orders:
res.append(_sort.serialize())
return res or None | [
"def",
"serialize",
"(",
"self",
")",
":",
"res",
"=",
"[",
"]",
"for",
"_sort",
"in",
"self",
".",
"sort_orders",
":",
"res",
".",
"append",
"(",
"_sort",
".",
"serialize",
"(",
")",
")",
"return",
"res",
"or",
"None"
] | Serialize the search to a structure as passed for a search body. | [
"Serialize",
"the",
"search",
"to",
"a",
"structure",
"as",
"passed",
"for",
"a",
"search",
"body",
"."
] | python | train |
fastai/fastai | fastai/vision/image.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L434-L439 | def scale_flow(flow, to_unit=True):
"Scale the coords in `flow` to -1/1 or the image size depending on `to_unit`."
s = tensor([flow.size[0]/2,flow.size[1]/2])[None]
if to_unit: flow.flow = flow.flow/s-1
else: flow.flow = (flow.flow+1)*s
return flow | [
"def",
"scale_flow",
"(",
"flow",
",",
"to_unit",
"=",
"True",
")",
":",
"s",
"=",
"tensor",
"(",
"[",
"flow",
".",
"size",
"[",
"0",
"]",
"/",
"2",
",",
"flow",
".",
"size",
"[",
"1",
"]",
"/",
"2",
"]",
")",
"[",
"None",
"]",
"if",
"to_un... | Scale the coords in `flow` to -1/1 or the image size depending on `to_unit`. | [
"Scale",
"the",
"coords",
"in",
"flow",
"to",
"-",
"1",
"/",
"1",
"or",
"the",
"image",
"size",
"depending",
"on",
"to_unit",
"."
] | python | train |
tomplus/kubernetes_asyncio | kubernetes_asyncio/client/api/extensions_v1beta1_api.py | https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/extensions_v1beta1_api.py#L6607-L6629 | def read_namespaced_replica_set_status(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_replica_set_status # noqa: E501
read status of the specified ReplicaSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request,... | [
"def",
"read_namespaced_replica_set_status",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
... | read_namespaced_replica_set_status # noqa: E501
read status of the specified ReplicaSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_replica_set_status(name, name... | [
"read_namespaced_replica_set_status",
"#",
"noqa",
":",
"E501"
] | python | train |
boriel/zxbasic | arch/zx48k/backend/__init__.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/backend/__init__.py#L1582-L1588 | def _param32(ins):
""" Pushes 32bit param into the stack
"""
output = _32bit_oper(ins.quad[1])
output.append('push de')
output.append('push hl')
return output | [
"def",
"_param32",
"(",
"ins",
")",
":",
"output",
"=",
"_32bit_oper",
"(",
"ins",
".",
"quad",
"[",
"1",
"]",
")",
"output",
".",
"append",
"(",
"'push de'",
")",
"output",
".",
"append",
"(",
"'push hl'",
")",
"return",
"output"
] | Pushes 32bit param into the stack | [
"Pushes",
"32bit",
"param",
"into",
"the",
"stack"
] | python | train |
swharden/SWHLab | doc/oldcode/swhlab/core/common.py | https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/doc/oldcode/swhlab/core/common.py#L491-L499 | def originFormat(thing):
"""Try to format anything as a 2D matrix with column names."""
if type(thing) is list and type(thing[0]) is dict:
return originFormat_listOfDicts(thing)
if type(thing) is list and type(thing[0]) is list:
return originFormat_listOfDicts(dictFlat(thing))
else:
... | [
"def",
"originFormat",
"(",
"thing",
")",
":",
"if",
"type",
"(",
"thing",
")",
"is",
"list",
"and",
"type",
"(",
"thing",
"[",
"0",
"]",
")",
"is",
"dict",
":",
"return",
"originFormat_listOfDicts",
"(",
"thing",
")",
"if",
"type",
"(",
"thing",
")"... | Try to format anything as a 2D matrix with column names. | [
"Try",
"to",
"format",
"anything",
"as",
"a",
"2D",
"matrix",
"with",
"column",
"names",
"."
] | python | valid |
ampl/amplpy | amplpy/dataframe.py | https://github.com/ampl/amplpy/blob/39df6954049a11a8f666aed26853259b4687099a/amplpy/dataframe.py#L203-L220 | def setColumn(self, header, values):
"""
Set the values of a column.
Args:
header: The header of the column to be set.
values: The values to set.
"""
if any(isinstance(value, basestring) for value in values):
values = list(map(str, values))
... | [
"def",
"setColumn",
"(",
"self",
",",
"header",
",",
"values",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"for",
"value",
"in",
"values",
")",
":",
"values",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"values",
"... | Set the values of a column.
Args:
header: The header of the column to be set.
values: The values to set. | [
"Set",
"the",
"values",
"of",
"a",
"column",
"."
] | python | train |
yjzhang/uncurl_python | uncurl/zip_clustering.py | https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/zip_clustering.py#L46-L76 | def zip_cluster(data, k, init=None, max_iters=100):
"""
Performs hard EM clustering using the zero-inflated Poisson distribution.
Args:
data (array): A 2d array- genes x cells
k (int): Number of clusters
init (array, optional): Initial centers - genes x k array. Default: None, use k... | [
"def",
"zip_cluster",
"(",
"data",
",",
"k",
",",
"init",
"=",
"None",
",",
"max_iters",
"=",
"100",
")",
":",
"genes",
",",
"cells",
"=",
"data",
".",
"shape",
"init",
",",
"new_assignments",
"=",
"kmeans_pp",
"(",
"data",
"+",
"eps",
",",
"k",
",... | Performs hard EM clustering using the zero-inflated Poisson distribution.
Args:
data (array): A 2d array- genes x cells
k (int): Number of clusters
init (array, optional): Initial centers - genes x k array. Default: None, use kmeans++
max_iters (int, optional): Maximum number of ite... | [
"Performs",
"hard",
"EM",
"clustering",
"using",
"the",
"zero",
"-",
"inflated",
"Poisson",
"distribution",
"."
] | python | train |
googlefonts/glyphsLib | Lib/glyphsLib/builder/custom_params.py | https://github.com/googlefonts/glyphsLib/blob/9c12dc70c8d13f08d92b824e6710f6e3bb5037bb/Lib/glyphsLib/builder/custom_params.py#L113-L116 | def get_custom_values(self, key):
"""Return a set of values for the given customParameter name."""
self._handled.add(key)
return self._lookup[key] | [
"def",
"get_custom_values",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"_handled",
".",
"add",
"(",
"key",
")",
"return",
"self",
".",
"_lookup",
"[",
"key",
"]"
] | Return a set of values for the given customParameter name. | [
"Return",
"a",
"set",
"of",
"values",
"for",
"the",
"given",
"customParameter",
"name",
"."
] | python | train |
ARMmbed/mbed-cloud-sdk-python | src/mbed_cloud/connect/connect.py | https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/connect/connect.py#L576-L585 | def list_device_subscriptions(self, device_id, **kwargs):
"""Lists all subscribed resources from a single device
:param device_id: ID of the device (Required)
:returns: a list of subscribed resources
:rtype: list of str
"""
api = self._get_api(mds.SubscriptionsApi)
... | [
"def",
"list_device_subscriptions",
"(",
"self",
",",
"device_id",
",",
"*",
"*",
"kwargs",
")",
":",
"api",
"=",
"self",
".",
"_get_api",
"(",
"mds",
".",
"SubscriptionsApi",
")",
"resp",
"=",
"api",
".",
"get_endpoint_subscriptions",
"(",
"device_id",
",",... | Lists all subscribed resources from a single device
:param device_id: ID of the device (Required)
:returns: a list of subscribed resources
:rtype: list of str | [
"Lists",
"all",
"subscribed",
"resources",
"from",
"a",
"single",
"device"
] | python | train |
Ezhil-Language-Foundation/open-tamil | tamil/txt2unicode/unicode2encode.py | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/txt2unicode/unicode2encode.py#L151-L196 | def unicode2auto(unicode_text, encode_text):
"""
This function will convert unicode (first argument) text into other
encodes by auto find the encode (from available encodes) by using sample
encode text in second argument of this function.
unicode_text : Pass unicode string which has to conver... | [
"def",
"unicode2auto",
"(",
"unicode_text",
",",
"encode_text",
")",
":",
"_all_unique_encodes_",
",",
"_all_common_encodes_",
"=",
"_get_unique_common_encodes",
"(",
")",
"# get unique word which falls under any one of available encodes from\r",
"# user passed text lines\r",
"uniq... | This function will convert unicode (first argument) text into other
encodes by auto find the encode (from available encodes) by using sample
encode text in second argument of this function.
unicode_text : Pass unicode string which has to convert into other encode.
encode_text : Pass sample encode ... | [
"This",
"function",
"will",
"convert",
"unicode",
"(",
"first",
"argument",
")",
"text",
"into",
"other",
"encodes",
"by",
"auto",
"find",
"the",
"encode",
"(",
"from",
"available",
"encodes",
")",
"by",
"using",
"sample",
"encode",
"text",
"in",
"second",
... | python | train |
b3j0f/conf | b3j0f/conf/parser/resolver/registry.py | https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/parser/resolver/registry.py#L112-L131 | def default(self, value):
"""Change of resolver name.
:param value: new default value to use.
:type value: str or callable
:raises: KeyError if value is a string not already registered."""
if value is None:
if self:
value = list(self.keys())[0]
... | [
"def",
"default",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"if",
"self",
":",
"value",
"=",
"list",
"(",
"self",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
"elif",
"not",
"isinstance",
"(",
"value",
",",
"string_type... | Change of resolver name.
:param value: new default value to use.
:type value: str or callable
:raises: KeyError if value is a string not already registered. | [
"Change",
"of",
"resolver",
"name",
"."
] | python | train |
tk0miya/tk.phpautodoc | src/phply/phpparse.py | https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phpparse.py#L807-L809 | def p_function_call_variable(p):
'function_call : variable_without_objects LPAREN function_call_parameter_list RPAREN'
p[0] = ast.FunctionCall(p[1], p[3], lineno=p.lineno(2)) | [
"def",
"p_function_call_variable",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"FunctionCall",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"2",
")",
")"
] | function_call : variable_without_objects LPAREN function_call_parameter_list RPAREN | [
"function_call",
":",
"variable_without_objects",
"LPAREN",
"function_call_parameter_list",
"RPAREN"
] | python | train |
DBuildService/dockerfile-parse | dockerfile_parse/util.py | https://github.com/DBuildService/dockerfile-parse/blob/3d7b514d8b8eded1b33529cf0f6a0770a573aee0/dockerfile_parse/util.py#L272-L285 | def set_line_value(self, context_type, value):
"""
Set value defined on this line ('line_envs'/'line_labels')
and update 'envs'/'labels'.
:param context_type: "ENV" or "LABEL"
:param value: new value for this line
"""
if context_type.upper() == "ENV":
... | [
"def",
"set_line_value",
"(",
"self",
",",
"context_type",
",",
"value",
")",
":",
"if",
"context_type",
".",
"upper",
"(",
")",
"==",
"\"ENV\"",
":",
"self",
".",
"line_envs",
"=",
"value",
"self",
".",
"envs",
".",
"update",
"(",
"value",
")",
"elif"... | Set value defined on this line ('line_envs'/'line_labels')
and update 'envs'/'labels'.
:param context_type: "ENV" or "LABEL"
:param value: new value for this line | [
"Set",
"value",
"defined",
"on",
"this",
"line",
"(",
"line_envs",
"/",
"line_labels",
")",
"and",
"update",
"envs",
"/",
"labels",
"."
] | python | train |
hazelcast/hazelcast-python-client | hazelcast/protocol/codec/map_put_all_codec.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/protocol/codec/map_put_all_codec.py#L22-L33 | def encode_request(name, entries):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(name, entries))
client_message.set_message_type(REQUEST_TYPE)
client_message.set_retryable(RETRYABLE)
client_message.append_str(name)
client_message.append_int(... | [
"def",
"encode_request",
"(",
"name",
",",
"entries",
")",
":",
"client_message",
"=",
"ClientMessage",
"(",
"payload_size",
"=",
"calculate_size",
"(",
"name",
",",
"entries",
")",
")",
"client_message",
".",
"set_message_type",
"(",
"REQUEST_TYPE",
")",
"clien... | Encode request into client_message | [
"Encode",
"request",
"into",
"client_message"
] | python | train |
peopledoc/mock-services | mock_services/rules.py | https://github.com/peopledoc/mock-services/blob/fd3838280df8869725b538768357435eedf299c1/mock_services/rules.py#L33-L75 | def update_http_rules(rules, content_type='text/plain'):
"""Adds rules to global http mock.
It permits to set mock in a more global way than decorators, cf.:
https://github.com/openstack/requests-mock
Here we assume urls in the passed dict are regex we recompile before adding
a rule.
Rules ex... | [
"def",
"update_http_rules",
"(",
"rules",
",",
"content_type",
"=",
"'text/plain'",
")",
":",
"for",
"kw",
"in",
"deepcopy",
"(",
"rules",
")",
":",
"kw",
"[",
"'url'",
"]",
"=",
"re",
".",
"compile",
"(",
"kw",
"[",
"'url'",
"]",
")",
"# ensure header... | Adds rules to global http mock.
It permits to set mock in a more global way than decorators, cf.:
https://github.com/openstack/requests-mock
Here we assume urls in the passed dict are regex we recompile before adding
a rule.
Rules example:
>>> def fake_duckduckgo_cb(request):
... ret... | [
"Adds",
"rules",
"to",
"global",
"http",
"mock",
"."
] | python | train |
roll/interest-py | interest/service.py | https://github.com/roll/interest-py/blob/e6e1def4f2999222aac2fb1d290ae94250673b89/interest/service.py#L156-L163 | def log(self, level, *args, **kwargs):
"""Log something.
.. seealso:: Proxy:
:class:`.Logger`.level
"""
target = getattr(self.__logger, level)
target(*args, **kwargs) | [
"def",
"log",
"(",
"self",
",",
"level",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"target",
"=",
"getattr",
"(",
"self",
".",
"__logger",
",",
"level",
")",
"target",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Log something.
.. seealso:: Proxy:
:class:`.Logger`.level | [
"Log",
"something",
"."
] | python | train |
gbowerman/azurerm | azurerm/container.py | https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/azurerm/container.py#L75-L94 | def delete_container_instance_group(access_token, subscription_id, resource_group,
container_group_name):
'''Delete a container group from a resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscriptio... | [
"def",
"delete_container_instance_group",
"(",
"access_token",
",",
"subscription_id",
",",
"resource_group",
",",
"container_group_name",
")",
":",
"endpoint",
"=",
"''",
".",
"join",
"(",
"[",
"get_rm_endpoint",
"(",
")",
",",
"'/subscriptions/'",
",",
"subscripti... | Delete a container group from a resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
container_group_name (str): Name of container instance group.
Returns:
... | [
"Delete",
"a",
"container",
"group",
"from",
"a",
"resource",
"group",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py#L319-L338 | def hide_routemap_holder_route_map_content_match_as_path_as_path_access_list_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
route_m... | [
"def",
"hide_routemap_holder_route_map_content_match_as_path_as_path_access_list_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_routemap_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config",
... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
nchopin/particles | particles/distributions.py | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/distributions.py#L324-L327 | def posterior(self, x):
"""Model is X_1,...,X_n ~ N(0, 1/theta), theta ~ Gamma(a, b)"""
return Gamma(a=self.a + 0.5 * x.size,
b=self.b + 0.5 * np.sum(x**2)) | [
"def",
"posterior",
"(",
"self",
",",
"x",
")",
":",
"return",
"Gamma",
"(",
"a",
"=",
"self",
".",
"a",
"+",
"0.5",
"*",
"x",
".",
"size",
",",
"b",
"=",
"self",
".",
"b",
"+",
"0.5",
"*",
"np",
".",
"sum",
"(",
"x",
"**",
"2",
")",
")"
... | Model is X_1,...,X_n ~ N(0, 1/theta), theta ~ Gamma(a, b) | [
"Model",
"is",
"X_1",
"...",
"X_n",
"~",
"N",
"(",
"0",
"1",
"/",
"theta",
")",
"theta",
"~",
"Gamma",
"(",
"a",
"b",
")"
] | python | train |
flask-restful/flask-restful | flask_restful/__init__.py | https://github.com/flask-restful/flask-restful/blob/25544d697c1f82bafbd1320960df459f58a58e03/flask_restful/__init__.py#L348-L384 | def add_resource(self, resource, *urls, **kwargs):
"""Adds a resource to the api.
:param resource: the class name of your resource
:type resource: :class:`Type[Resource]`
:param urls: one or more url routes to match for the resource, standard
flask routing rules ap... | [
"def",
"add_resource",
"(",
"self",
",",
"resource",
",",
"*",
"urls",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"app",
"is",
"not",
"None",
":",
"self",
".",
"_register_view",
"(",
"self",
".",
"app",
",",
"resource",
",",
"*",
"urls",... | Adds a resource to the api.
:param resource: the class name of your resource
:type resource: :class:`Type[Resource]`
:param urls: one or more url routes to match for the resource, standard
flask routing rules apply. Any url variables will be
passed to... | [
"Adds",
"a",
"resource",
"to",
"the",
"api",
"."
] | python | train |
pingali/dgit | dgitcore/contrib/repomanagers/gitmanager.py | https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/repomanagers/gitmanager.py#L507-L546 | def config(self, what='get', params=None):
"""
Paramers:
---------
workspace: Directory to store the dataset repositories
email:
"""
if what == 'get':
return {
'name': 'git',
'nature': 'repomanager',
'va... | [
"def",
"config",
"(",
"self",
",",
"what",
"=",
"'get'",
",",
"params",
"=",
"None",
")",
":",
"if",
"what",
"==",
"'get'",
":",
"return",
"{",
"'name'",
":",
"'git'",
",",
"'nature'",
":",
"'repomanager'",
",",
"'variables'",
":",
"[",
"]",
",",
"... | Paramers:
---------
workspace: Directory to store the dataset repositories
email: | [
"Paramers",
":",
"---------"
] | python | valid |
zhmcclient/python-zhmcclient | zhmcclient/_logging.py | https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_logging.py#L102-L234 | def logged_api_call(func):
"""
Function decorator that causes the decorated API function or method to log
calls to itself to a logger.
The logger's name is the dotted module name of the module defining the
decorated function (e.g. 'zhmcclient._cpc').
Parameters:
func (function object): ... | [
"def",
"logged_api_call",
"(",
"func",
")",
":",
"# Note that in this decorator function, we are in a module loading context,",
"# where the decorated functions are being defined. When this decorator",
"# function is called, its call stack represents the definition of the",
"# decorated functions.... | Function decorator that causes the decorated API function or method to log
calls to itself to a logger.
The logger's name is the dotted module name of the module defining the
decorated function (e.g. 'zhmcclient._cpc').
Parameters:
func (function object): The original function being decorated.
... | [
"Function",
"decorator",
"that",
"causes",
"the",
"decorated",
"API",
"function",
"or",
"method",
"to",
"log",
"calls",
"to",
"itself",
"to",
"a",
"logger",
"."
] | python | train |
mgedmin/check-manifest | check_manifest.py | https://github.com/mgedmin/check-manifest/blob/7f787e8272f56c5750670bfb3223509e0df72708/check_manifest.py#L840-L946 | def check_manifest(source_tree='.', create=False, update=False,
python=sys.executable):
"""Compare a generated source distribution with list of files in a VCS.
Returns True if the manifest is fine.
"""
all_ok = True
if os.path.sep in python:
python = os.path.abspath(pytho... | [
"def",
"check_manifest",
"(",
"source_tree",
"=",
"'.'",
",",
"create",
"=",
"False",
",",
"update",
"=",
"False",
",",
"python",
"=",
"sys",
".",
"executable",
")",
":",
"all_ok",
"=",
"True",
"if",
"os",
".",
"path",
".",
"sep",
"in",
"python",
":"... | Compare a generated source distribution with list of files in a VCS.
Returns True if the manifest is fine. | [
"Compare",
"a",
"generated",
"source",
"distribution",
"with",
"list",
"of",
"files",
"in",
"a",
"VCS",
"."
] | python | train |
fake-name/ChromeController | ChromeController/Generator/Generated.py | https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/ChromeController/Generator/Generated.py#L5230-L5248 | def Input_setIgnoreInputEvents(self, ignore):
"""
Function path: Input.setIgnoreInputEvents
Domain: Input
Method name: setIgnoreInputEvents
Parameters:
Required arguments:
'ignore' (type: boolean) -> Ignores input events processing when set to true.
No return value.
Description: Ignore... | [
"def",
"Input_setIgnoreInputEvents",
"(",
"self",
",",
"ignore",
")",
":",
"assert",
"isinstance",
"(",
"ignore",
",",
"(",
"bool",
",",
")",
")",
",",
"\"Argument 'ignore' must be of type '['bool']'. Received type: '%s'\"",
"%",
"type",
"(",
"ignore",
")",
"subdom_... | Function path: Input.setIgnoreInputEvents
Domain: Input
Method name: setIgnoreInputEvents
Parameters:
Required arguments:
'ignore' (type: boolean) -> Ignores input events processing when set to true.
No return value.
Description: Ignores input events (useful while auditing page). | [
"Function",
"path",
":",
"Input",
".",
"setIgnoreInputEvents",
"Domain",
":",
"Input",
"Method",
"name",
":",
"setIgnoreInputEvents",
"Parameters",
":",
"Required",
"arguments",
":",
"ignore",
"(",
"type",
":",
"boolean",
")",
"-",
">",
"Ignores",
"input",
"ev... | python | train |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/web.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/web.py#L70-L85 | def compare_response_code(url, code):
'''
Compare the response code of url param with code param and returns boolean
@param url -> string e.g. http://127.0.0.1/index
@param content_type -> int e.g. 404, 500, 400 ..etc
'''
try:
response = urllib2.urlopen(url)
except HTTPError as... | [
"def",
"compare_response_code",
"(",
"url",
",",
"code",
")",
":",
"try",
":",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
")",
"except",
"HTTPError",
"as",
"e",
":",
"return",
"e",
".",
"code",
"==",
"code",
"except",
":",
"return",
"False... | Compare the response code of url param with code param and returns boolean
@param url -> string e.g. http://127.0.0.1/index
@param content_type -> int e.g. 404, 500, 400 ..etc | [
"Compare",
"the",
"response",
"code",
"of",
"url",
"param",
"with",
"code",
"param",
"and",
"returns",
"boolean"
] | python | test |
ontio/ontology-python-sdk | ontology/smart_contract/native_contract/ontid.py | https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/ontid.py#L208-L233 | def add_public_key(self, ont_id: str, operator: Account, hex_new_public_key: str, payer: Account, gas_limit: int,
gas_price: int, is_recovery: bool = False):
"""
This interface is used to send a Transaction object which is used to add public key.
:param ont_id: OntId.
... | [
"def",
"add_public_key",
"(",
"self",
",",
"ont_id",
":",
"str",
",",
"operator",
":",
"Account",
",",
"hex_new_public_key",
":",
"str",
",",
"payer",
":",
"Account",
",",
"gas_limit",
":",
"int",
",",
"gas_price",
":",
"int",
",",
"is_recovery",
":",
"b... | This interface is used to send a Transaction object which is used to add public key.
:param ont_id: OntId.
:param operator: an Account object which indicate who will sign for the transaction.
:param hex_new_public_key: the new hexadecimal public key in the form of string.
:param payer: ... | [
"This",
"interface",
"is",
"used",
"to",
"send",
"a",
"Transaction",
"object",
"which",
"is",
"used",
"to",
"add",
"public",
"key",
"."
] | python | train |
sbarham/dsrt | build/lib/dsrt/data/transform/Vectorizer.py | https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/build/lib/dsrt/data/transform/Vectorizer.py#L84-L92 | def vectorize_utterance(self, utterance):
"""
Take in a tokenized utterance and transform it into a sequence of indices
"""
for i, word in enumerate(utterance):
if not word in self.vocab_list:
utterance[i] = '<unk>'
return self.swap_pad_and_zero(self.... | [
"def",
"vectorize_utterance",
"(",
"self",
",",
"utterance",
")",
":",
"for",
"i",
",",
"word",
"in",
"enumerate",
"(",
"utterance",
")",
":",
"if",
"not",
"word",
"in",
"self",
".",
"vocab_list",
":",
"utterance",
"[",
"i",
"]",
"=",
"'<unk>'",
"retur... | Take in a tokenized utterance and transform it into a sequence of indices | [
"Take",
"in",
"a",
"tokenized",
"utterance",
"and",
"transform",
"it",
"into",
"a",
"sequence",
"of",
"indices"
] | python | train |
numenta/nupic | src/nupic/algorithms/temporal_memory.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/temporal_memory.py#L840-L850 | def columnForCell(self, cell):
"""
Returns the index of the column that a cell belongs to.
:param cell: (int) Cell index
:returns: (int) Column index
"""
self._validateCell(cell)
return int(cell / self.cellsPerColumn) | [
"def",
"columnForCell",
"(",
"self",
",",
"cell",
")",
":",
"self",
".",
"_validateCell",
"(",
"cell",
")",
"return",
"int",
"(",
"cell",
"/",
"self",
".",
"cellsPerColumn",
")"
] | Returns the index of the column that a cell belongs to.
:param cell: (int) Cell index
:returns: (int) Column index | [
"Returns",
"the",
"index",
"of",
"the",
"column",
"that",
"a",
"cell",
"belongs",
"to",
"."
] | python | valid |
chrisspen/burlap | burlap/debug.py | https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/debug.py#L284-L291 | def set_satchel_value(self, satchel, key, value):
"""
Sets a key/value pair in a satchel's local renderer.
"""
satchel = self.get_satchel(satchel)
r = satchel.local_renderer
setattr(r.env, key, value)
print('Set %s=%s in satchel %s.' % (key, value, satchel.name)) | [
"def",
"set_satchel_value",
"(",
"self",
",",
"satchel",
",",
"key",
",",
"value",
")",
":",
"satchel",
"=",
"self",
".",
"get_satchel",
"(",
"satchel",
")",
"r",
"=",
"satchel",
".",
"local_renderer",
"setattr",
"(",
"r",
".",
"env",
",",
"key",
",",
... | Sets a key/value pair in a satchel's local renderer. | [
"Sets",
"a",
"key",
"/",
"value",
"pair",
"in",
"a",
"satchel",
"s",
"local",
"renderer",
"."
] | python | valid |
dhylands/rshell | rshell/main.py | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L2640-L2651 | def do_rsync(self, line):
"""rsync [-m|--mirror] [-n|--dry-run] [-q|--quiet] SRC_DIR DEST_DIR
Synchronizes a destination directory tree with a source directory tree.
"""
args = self.line_to_args(line)
src_dir = resolve_path(args.src_dir)
dst_dir = resolve_path(args.ds... | [
"def",
"do_rsync",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"self",
".",
"line_to_args",
"(",
"line",
")",
"src_dir",
"=",
"resolve_path",
"(",
"args",
".",
"src_dir",
")",
"dst_dir",
"=",
"resolve_path",
"(",
"args",
".",
"dst_dir",
")",
"verb... | rsync [-m|--mirror] [-n|--dry-run] [-q|--quiet] SRC_DIR DEST_DIR
Synchronizes a destination directory tree with a source directory tree. | [
"rsync",
"[",
"-",
"m|",
"--",
"mirror",
"]",
"[",
"-",
"n|",
"--",
"dry",
"-",
"run",
"]",
"[",
"-",
"q|",
"--",
"quiet",
"]",
"SRC_DIR",
"DEST_DIR"
] | python | train |
apache/incubator-mxnet | example/ssd/train/train_net.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/ssd/train/train_net.py#L90-L279 | def train_net(net, train_path, num_classes, batch_size,
data_shape, mean_pixels, resume, finetune, pretrained, epoch,
prefix, ctx, begin_epoch, end_epoch, frequent, learning_rate,
momentum, weight_decay, lr_refactor_step, lr_refactor_ratio,
freeze_layer_pattern=''... | [
"def",
"train_net",
"(",
"net",
",",
"train_path",
",",
"num_classes",
",",
"batch_size",
",",
"data_shape",
",",
"mean_pixels",
",",
"resume",
",",
"finetune",
",",
"pretrained",
",",
"epoch",
",",
"prefix",
",",
"ctx",
",",
"begin_epoch",
",",
"end_epoch",... | Wrapper for training phase.
Parameters:
----------
net : str
symbol name for the network structure
train_path : str
record file path for training
num_classes : int
number of object classes, not including background
batch_size : int
training batch-size
data_sh... | [
"Wrapper",
"for",
"training",
"phase",
"."
] | python | train |
iotile/coretools | iotilecore/iotile/core/dev/iotileobj.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/dev/iotileobj.py#L345-L358 | def _ensure_product_string(cls, product):
"""Ensure that all product locations are strings.
Older components specify paths as lists of path components. Join
those paths into a normal path string.
"""
if isinstance(product, str):
return product
if isinstanc... | [
"def",
"_ensure_product_string",
"(",
"cls",
",",
"product",
")",
":",
"if",
"isinstance",
"(",
"product",
",",
"str",
")",
":",
"return",
"product",
"if",
"isinstance",
"(",
"product",
",",
"list",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"... | Ensure that all product locations are strings.
Older components specify paths as lists of path components. Join
those paths into a normal path string. | [
"Ensure",
"that",
"all",
"product",
"locations",
"are",
"strings",
"."
] | python | train |
calmjs/calmjs | src/calmjs/cli.py | https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/cli.py#L119-L127 | def node(self, source, args=(), env={}):
"""
Calls node with an inline source.
Returns decoded output of stdout and stderr; decoding determine
by locale.
"""
return self._exec(self.node_bin, source, args=args, env=env) | [
"def",
"node",
"(",
"self",
",",
"source",
",",
"args",
"=",
"(",
")",
",",
"env",
"=",
"{",
"}",
")",
":",
"return",
"self",
".",
"_exec",
"(",
"self",
".",
"node_bin",
",",
"source",
",",
"args",
"=",
"args",
",",
"env",
"=",
"env",
")"
] | Calls node with an inline source.
Returns decoded output of stdout and stderr; decoding determine
by locale. | [
"Calls",
"node",
"with",
"an",
"inline",
"source",
"."
] | python | train |
python-cmd2/cmd2 | examples/paged_output.py | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/examples/paged_output.py#L41-L51 | def do_page_truncate(self, args: List[str]):
"""Read in a text file and display its output in a pager, truncating long lines if they don't fit.
Truncated lines can still be accessed by scrolling to the right using the arrow keys.
Usage: page_chop <file_path>
"""
if not args:
... | [
"def",
"do_page_truncate",
"(",
"self",
",",
"args",
":",
"List",
"[",
"str",
"]",
")",
":",
"if",
"not",
"args",
":",
"self",
".",
"perror",
"(",
"'page_truncate requires a path to a file as an argument'",
",",
"traceback_war",
"=",
"False",
")",
"return",
"s... | Read in a text file and display its output in a pager, truncating long lines if they don't fit.
Truncated lines can still be accessed by scrolling to the right using the arrow keys.
Usage: page_chop <file_path> | [
"Read",
"in",
"a",
"text",
"file",
"and",
"display",
"its",
"output",
"in",
"a",
"pager",
"truncating",
"long",
"lines",
"if",
"they",
"don",
"t",
"fit",
"."
] | python | train |
ianepperson/telnetsrvlib | telnetsrv/telnetsrvlib.py | https://github.com/ianepperson/telnetsrvlib/blob/fac52a4a333c2d373d53d295a76a0bbd71e5d682/telnetsrv/telnetsrvlib.py#L550-L580 | def options_handler(self, sock, cmd, opt):
"Negotiate options"
if cmd == NOP:
self.sendcommand(NOP)
elif cmd == WILL or cmd == WONT:
if self.WILLACK.has_key(opt):
self.sendcommand(self.WILLACK[opt], opt)
else:
self.sendcommand(D... | [
"def",
"options_handler",
"(",
"self",
",",
"sock",
",",
"cmd",
",",
"opt",
")",
":",
"if",
"cmd",
"==",
"NOP",
":",
"self",
".",
"sendcommand",
"(",
"NOP",
")",
"elif",
"cmd",
"==",
"WILL",
"or",
"cmd",
"==",
"WONT",
":",
"if",
"self",
".",
"WIL... | Negotiate options | [
"Negotiate",
"options"
] | python | train |
bwohlberg/sporco | sporco/util.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L472-L496 | def spnoise(s, frc, smn=0.0, smx=1.0):
"""Return image with salt & pepper noise imposed on it.
Parameters
----------
s : ndarray
Input image
frc : float
Desired fraction of pixels corrupted by noise
smn : float, optional (default 0.0)
Lower value for noise (pepper)
smx : f... | [
"def",
"spnoise",
"(",
"s",
",",
"frc",
",",
"smn",
"=",
"0.0",
",",
"smx",
"=",
"1.0",
")",
":",
"sn",
"=",
"s",
".",
"copy",
"(",
")",
"spm",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"1.0",
",",
"1.0",
",",
"s",
".",
"shape",
... | Return image with salt & pepper noise imposed on it.
Parameters
----------
s : ndarray
Input image
frc : float
Desired fraction of pixels corrupted by noise
smn : float, optional (default 0.0)
Lower value for noise (pepper)
smx : float, optional (default 1.0)
Upper value... | [
"Return",
"image",
"with",
"salt",
"&",
"pepper",
"noise",
"imposed",
"on",
"it",
"."
] | python | train |
treycucco/bidon | bidon/data_table.py | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L118-L125 | def rows_to_dicts(self, serialize_cell=None):
"""Generates a sequence of dictionaries of {header[i] => row[i]} for each row."""
if serialize_cell is None:
serialize_cell = self.get_cell_value
# keys = [serialize_cell(cell) for cell in self.rows[0]]
keys = self.headers(serialize_cell)
for row i... | [
"def",
"rows_to_dicts",
"(",
"self",
",",
"serialize_cell",
"=",
"None",
")",
":",
"if",
"serialize_cell",
"is",
"None",
":",
"serialize_cell",
"=",
"self",
".",
"get_cell_value",
"# keys = [serialize_cell(cell) for cell in self.rows[0]]",
"keys",
"=",
"self",
".",
... | Generates a sequence of dictionaries of {header[i] => row[i]} for each row. | [
"Generates",
"a",
"sequence",
"of",
"dictionaries",
"of",
"{",
"header",
"[",
"i",
"]",
"=",
">",
"row",
"[",
"i",
"]",
"}",
"for",
"each",
"row",
"."
] | python | train |
vatlab/SoS | src/sos/section_analyzer.py | https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/section_analyzer.py#L514-L569 | def analyze_section(section: SoS_Step,
default_input: Optional[sos_targets] = None,
default_output: Optional[sos_targets] = None,
context={},
vars_and_output_only: bool = False) -> Dict[str, Any]:
'''Analyze a section for how it uses in... | [
"def",
"analyze_section",
"(",
"section",
":",
"SoS_Step",
",",
"default_input",
":",
"Optional",
"[",
"sos_targets",
"]",
"=",
"None",
",",
"default_output",
":",
"Optional",
"[",
"sos_targets",
"]",
"=",
"None",
",",
"context",
"=",
"{",
"}",
",",
"vars_... | Analyze a section for how it uses input and output, what variables
it uses, and input, output, etc. | [
"Analyze",
"a",
"section",
"for",
"how",
"it",
"uses",
"input",
"and",
"output",
"what",
"variables",
"it",
"uses",
"and",
"input",
"output",
"etc",
"."
] | python | train |
interedition/collatex | collatex-pythonport/collatex/linsuffarr.py | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-pythonport/collatex/linsuffarr.py#L161-L281 | def _suffixArrayWithTrace(s, SA, n, K, operations, totalOperations):
"""
This function is a rewrite in Python of the C implementation proposed in Kärkkäinen and Sanders paper.
Find the suffix array SA of s[0..n-1] in {1..K}^n
Require s[n]=s[n+1]=s[n+2]=0, n>=2
"""
if _trace:
_traceSuffi... | [
"def",
"_suffixArrayWithTrace",
"(",
"s",
",",
"SA",
",",
"n",
",",
"K",
",",
"operations",
",",
"totalOperations",
")",
":",
"if",
"_trace",
":",
"_traceSuffixArray",
"(",
"operations",
",",
"totalOperations",
")",
"n0",
"=",
"(",
"n",
"+",
"2",
")",
... | This function is a rewrite in Python of the C implementation proposed in Kärkkäinen and Sanders paper.
Find the suffix array SA of s[0..n-1] in {1..K}^n
Require s[n]=s[n+1]=s[n+2]=0, n>=2 | [
"This",
"function",
"is",
"a",
"rewrite",
"in",
"Python",
"of",
"the",
"C",
"implementation",
"proposed",
"in",
"Kärkkäinen",
"and",
"Sanders",
"paper",
"."
] | python | train |
MacHu-GWU/constant2-project | constant2/_constant2.py | https://github.com/MacHu-GWU/constant2-project/blob/ccf7e14b0e23f9f4bfd13a3e2ce4a1142e570d4f/constant2/_constant2.py#L531-L544 | def is_same_dict(d1, d2):
"""Test two dictionary is equal on values. (ignore order)
"""
for k, v in d1.items():
if isinstance(v, dict):
is_same_dict(v, d2[k])
else:
assert d1[k] == d2[k]
for k, v in d2.items():
if isinstance(v, dict):
is_same_... | [
"def",
"is_same_dict",
"(",
"d1",
",",
"d2",
")",
":",
"for",
"k",
",",
"v",
"in",
"d1",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"is_same_dict",
"(",
"v",
",",
"d2",
"[",
"k",
"]",
")",
"else",
":",
... | Test two dictionary is equal on values. (ignore order) | [
"Test",
"two",
"dictionary",
"is",
"equal",
"on",
"values",
".",
"(",
"ignore",
"order",
")"
] | python | train |
thespacedoctor/transientNamer | transientNamer/search.py | https://github.com/thespacedoctor/transientNamer/blob/39be410c84275ed4669632f5df67e728d66a318f/transientNamer/search.py#L779-L818 | def _get_tns_search_results(
self):
"""
*query the tns and result the response*
"""
self.log.info('starting the ``_get_tns_search_results`` method')
try:
response = requests.get(
url="http://wis-tns.weizmann.ac.il/search",
... | [
"def",
"_get_tns_search_results",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_get_tns_search_results`` method'",
")",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"\"http://wis-tns.weizmann.ac.il/search\"",
... | *query the tns and result the response* | [
"*",
"query",
"the",
"tns",
"and",
"result",
"the",
"response",
"*"
] | python | train |
PaulHancock/Aegean | AegeanTools/source_finder.py | https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/source_finder.py#L83-L154 | def _gen_flood_wrap(self, data, rmsimg, innerclip, outerclip=None, domask=False):
"""
Generator function.
Segment an image into islands and return one island at a time.
Needs to work for entire image, and also for components within an island.
Parameters
----------
... | [
"def",
"_gen_flood_wrap",
"(",
"self",
",",
"data",
",",
"rmsimg",
",",
"innerclip",
",",
"outerclip",
"=",
"None",
",",
"domask",
"=",
"False",
")",
":",
"if",
"outerclip",
"is",
"None",
":",
"outerclip",
"=",
"innerclip",
"# compute SNR image (data has alrea... | Generator function.
Segment an image into islands and return one island at a time.
Needs to work for entire image, and also for components within an island.
Parameters
----------
data : 2d-array
Image array.
rmsimg : 2d-array
Noise image.
... | [
"Generator",
"function",
".",
"Segment",
"an",
"image",
"into",
"islands",
"and",
"return",
"one",
"island",
"at",
"a",
"time",
"."
] | python | train |
JIC-CSB/jicbioimage.transform | appveyor/install.py | https://github.com/JIC-CSB/jicbioimage.transform/blob/494c282d964c3a9b54c2a1b3730f5625ea2a494b/appveyor/install.py#L19-L23 | def unzip_file(zip_fname):
"""Unzip the zip_fname in the current directory."""
print("Unzipping {}".format(zip_fname))
with zipfile.ZipFile(zip_fname) as zf:
zf.extractall() | [
"def",
"unzip_file",
"(",
"zip_fname",
")",
":",
"print",
"(",
"\"Unzipping {}\"",
".",
"format",
"(",
"zip_fname",
")",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"zip_fname",
")",
"as",
"zf",
":",
"zf",
".",
"extractall",
"(",
")"
] | Unzip the zip_fname in the current directory. | [
"Unzip",
"the",
"zip_fname",
"in",
"the",
"current",
"directory",
"."
] | python | train |
iotile/coretools | iotilegateway/iotilegateway/supervisor/client.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilegateway/iotilegateway/supervisor/client.py#L490-L522 | async def _on_rpc_command(self, event):
"""Received an RPC command that we should execute."""
payload = event['payload']
rpc_id = payload['rpc_id']
tag = payload['response_uuid']
args = payload['payload']
result = 'success'
response = b''
if self._rpc_d... | [
"async",
"def",
"_on_rpc_command",
"(",
"self",
",",
"event",
")",
":",
"payload",
"=",
"event",
"[",
"'payload'",
"]",
"rpc_id",
"=",
"payload",
"[",
"'rpc_id'",
"]",
"tag",
"=",
"payload",
"[",
"'response_uuid'",
"]",
"args",
"=",
"payload",
"[",
"'pay... | Received an RPC command that we should execute. | [
"Received",
"an",
"RPC",
"command",
"that",
"we",
"should",
"execute",
"."
] | python | train |
todbot/blink1-python | blink1/blink1.py | https://github.com/todbot/blink1-python/blob/7a5183becd9662f88da3c29afd3447403f4ef82f/blink1/blink1.py#L274-L282 | def readPattern(self):
"""Read the entire color pattern
:return List of pattern line tuples
"""
if ( self.dev == None ): return ''
pattern=[]
for i in range(0,16): # FIXME: adjustable for diff blink(1) models
pattern.append( self.readPatternLine(i) )
... | [
"def",
"readPattern",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"dev",
"==",
"None",
")",
":",
"return",
"''",
"pattern",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"16",
")",
":",
"# FIXME: adjustable for diff blink(1) models",
"pat... | Read the entire color pattern
:return List of pattern line tuples | [
"Read",
"the",
"entire",
"color",
"pattern",
":",
"return",
"List",
"of",
"pattern",
"line",
"tuples"
] | python | train |
garethr/cloth | src/cloth/tasks.py | https://github.com/garethr/cloth/blob/b50c7cd6b03f49a931ee55ec94212760c50694a9/src/cloth/tasks.py#L40-L44 | def list():
"List EC2 name and public and private ip address"
for node in env.nodes:
print "%s (%s, %s)" % (node.tags["Name"], node.ip_address,
node.private_ip_address) | [
"def",
"list",
"(",
")",
":",
"for",
"node",
"in",
"env",
".",
"nodes",
":",
"print",
"\"%s (%s, %s)\"",
"%",
"(",
"node",
".",
"tags",
"[",
"\"Name\"",
"]",
",",
"node",
".",
"ip_address",
",",
"node",
".",
"private_ip_address",
")"
] | List EC2 name and public and private ip address | [
"List",
"EC2",
"name",
"and",
"public",
"and",
"private",
"ip",
"address"
] | python | train |
iterative/dvc | dvc/config.py | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L319-L329 | def get_global_config_dir():
"""Returns global config location. E.g. ~/.config/dvc/config.
Returns:
str: path to the global config directory.
"""
from appdirs import user_config_dir
return user_config_dir(
appname=Config.APPNAME, appauthor=Config.APPAUTH... | [
"def",
"get_global_config_dir",
"(",
")",
":",
"from",
"appdirs",
"import",
"user_config_dir",
"return",
"user_config_dir",
"(",
"appname",
"=",
"Config",
".",
"APPNAME",
",",
"appauthor",
"=",
"Config",
".",
"APPAUTHOR",
")"
] | Returns global config location. E.g. ~/.config/dvc/config.
Returns:
str: path to the global config directory. | [
"Returns",
"global",
"config",
"location",
".",
"E",
".",
"g",
".",
"~",
"/",
".",
"config",
"/",
"dvc",
"/",
"config",
"."
] | python | train |
emory-libraries/eulfedora | eulfedora/api.py | https://github.com/emory-libraries/eulfedora/blob/161826f3fdcdab4007f6fa7dfd9f1ecabc4bcbe4/eulfedora/api.py#L583-L658 | def modifyDatastream(self, pid, dsID, dsLabel=None, mimeType=None, logMessage=None, dsLocation=None,
altIDs=None, versionable=None, dsState=None, formatURI=None, checksumType=None,
checksum=None, content=None, force=False):
'''Modify an existing datastream, similar to :meth:`addDatastraem`.
... | [
"def",
"modifyDatastream",
"(",
"self",
",",
"pid",
",",
"dsID",
",",
"dsLabel",
"=",
"None",
",",
"mimeType",
"=",
"None",
",",
"logMessage",
"=",
"None",
",",
"dsLocation",
"=",
"None",
",",
"altIDs",
"=",
"None",
",",
"versionable",
"=",
"None",
","... | Modify an existing datastream, similar to :meth:`addDatastraem`.
Content can be specified by either a URI location or as
string content or file-like object; if content is not specified,
datastream metadata will be updated without modifying the content.
On success, the returned response ... | [
"Modify",
"an",
"existing",
"datastream",
"similar",
"to",
":",
"meth",
":",
"addDatastraem",
".",
"Content",
"can",
"be",
"specified",
"by",
"either",
"a",
"URI",
"location",
"or",
"as",
"string",
"content",
"or",
"file",
"-",
"like",
"object",
";",
"if",... | python | train |
mezz64/pyEight | pyeight/eight.py | https://github.com/mezz64/pyEight/blob/e557e4e6876f490d0964298e9475d68b64222d4f/pyeight/eight.py#L241-L267 | async def api_get(self, url, params=None):
"""Make api fetch request."""
request = None
headers = DEFAULT_HEADERS.copy()
headers.update({'Session-Token': self._token})
try:
with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop):
request = ... | [
"async",
"def",
"api_get",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
")",
":",
"request",
"=",
"None",
"headers",
"=",
"DEFAULT_HEADERS",
".",
"copy",
"(",
")",
"headers",
".",
"update",
"(",
"{",
"'Session-Token'",
":",
"self",
".",
"_token... | Make api fetch request. | [
"Make",
"api",
"fetch",
"request",
"."
] | python | train |
Azure/Azure-MachineLearning-ClientLibrary-Python | azureml/services.py | https://github.com/Azure/Azure-MachineLearning-ClientLibrary-Python/blob/d1211b289747671898eb063013e0dc53d3c80acd/azureml/services.py#L989-L1001 | def attach(name, contents = None):
"""attaches a file to the payload to be uploaded.
If contents is omitted the file is read from disk.
If name is a tuple it specifies the on-disk filename and the destination filename.
"""
def do_attach(func):
if hasattr(func, '__attachments__'):
func.__att... | [
"def",
"attach",
"(",
"name",
",",
"contents",
"=",
"None",
")",
":",
"def",
"do_attach",
"(",
"func",
")",
":",
"if",
"hasattr",
"(",
"func",
",",
"'__attachments__'",
")",
":",
"func",
".",
"__attachments__",
".",
"append",
"(",
"(",
"name",
",",
"... | attaches a file to the payload to be uploaded.
If contents is omitted the file is read from disk.
If name is a tuple it specifies the on-disk filename and the destination filename. | [
"attaches",
"a",
"file",
"to",
"the",
"payload",
"to",
"be",
"uploaded",
"."
] | python | test |
thunder-project/thunder | thunder/base.py | https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/base.py#L254-L271 | def astype(self, dtype, casting='unsafe'):
"""
Cast values to the specified type.
Parameters
----------
dtype : str or dtype
Typecode or data-type to which the array is cast.
casting : ['no', 'equiv', 'safe', 'same_kind', 'unsafe'], optional
... | [
"def",
"astype",
"(",
"self",
",",
"dtype",
",",
"casting",
"=",
"'unsafe'",
")",
":",
"return",
"self",
".",
"_constructor",
"(",
"self",
".",
"values",
".",
"astype",
"(",
"dtype",
"=",
"dtype",
",",
"casting",
"=",
"casting",
")",
")",
".",
"__fin... | Cast values to the specified type.
Parameters
----------
dtype : str or dtype
Typecode or data-type to which the array is cast.
casting : ['no', 'equiv', 'safe', 'same_kind', 'unsafe'], optional
Controld what kind of data casting may occur. Defaluts to 'u... | [
"Cast",
"values",
"to",
"the",
"specified",
"type",
".",
"Parameters",
"----------",
"dtype",
":",
"str",
"or",
"dtype",
"Typecode",
"or",
"data",
"-",
"type",
"to",
"which",
"the",
"array",
"is",
"cast",
".",
"casting",
":",
"[",
"no",
"equiv",
"safe",
... | python | train |
heikomuller/sco-datastore | scodata/datastore.py | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/datastore.py#L517-L527 | def insert_object(self, db_object):
"""Create new entry in the database.
Parameters
----------
db_object : (Sub-class of)ObjectHandle
"""
# Create object using the to_dict() method.
obj = self.to_dict(db_object)
obj['active'] = True
self.collecti... | [
"def",
"insert_object",
"(",
"self",
",",
"db_object",
")",
":",
"# Create object using the to_dict() method.",
"obj",
"=",
"self",
".",
"to_dict",
"(",
"db_object",
")",
"obj",
"[",
"'active'",
"]",
"=",
"True",
"self",
".",
"collection",
".",
"insert_one",
... | Create new entry in the database.
Parameters
----------
db_object : (Sub-class of)ObjectHandle | [
"Create",
"new",
"entry",
"in",
"the",
"database",
"."
] | python | train |
fastai/fastai | fastai/vision/data.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/data.py#L291-L295 | def from_csv(cls, path:PathOrStr, csv_name:str, header:str='infer', **kwargs)->'ItemList':
"Get the filenames in `path/csv_name` opened with `header`."
path = Path(path)
df = pd.read_csv(path/csv_name, header=header)
return cls.from_df(df, path=path, **kwargs) | [
"def",
"from_csv",
"(",
"cls",
",",
"path",
":",
"PathOrStr",
",",
"csv_name",
":",
"str",
",",
"header",
":",
"str",
"=",
"'infer'",
",",
"*",
"*",
"kwargs",
")",
"->",
"'ItemList'",
":",
"path",
"=",
"Path",
"(",
"path",
")",
"df",
"=",
"pd",
"... | Get the filenames in `path/csv_name` opened with `header`. | [
"Get",
"the",
"filenames",
"in",
"path",
"/",
"csv_name",
"opened",
"with",
"header",
"."
] | python | train |
echonest/pyechonest | pyechonest/artist.py | https://github.com/echonest/pyechonest/blob/d8c7af6c1da699b50b2f4b1bd3c0febe72e7f1ee/pyechonest/artist.py#L281-L304 | def get_hotttnesss(self, cache=True):
"""Get our numerical description of how hottt an artist currently is
Args:
Kwargs:
cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.
Returns:... | [
"def",
"get_hotttnesss",
"(",
"self",
",",
"cache",
"=",
"True",
")",
":",
"if",
"not",
"(",
"cache",
"and",
"(",
"'hotttnesss'",
"in",
"self",
".",
"cache",
")",
")",
":",
"response",
"=",
"self",
".",
"get_attribute",
"(",
"'hotttnesss'",
")",
"self"... | Get our numerical description of how hottt an artist currently is
Args:
Kwargs:
cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.
Returns:
float: the hotttnesss value
... | [
"Get",
"our",
"numerical",
"description",
"of",
"how",
"hottt",
"an",
"artist",
"currently",
"is",
"Args",
":",
"Kwargs",
":",
"cache",
"(",
"bool",
")",
":",
"A",
"boolean",
"indicating",
"whether",
"or",
"not",
"the",
"cached",
"value",
"should",
"be",
... | python | train |
bitesofcode/projexui | projexui/widgets/xtreewidget/xtreewidgetitem.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtreewidget/xtreewidgetitem.py#L125-L144 | def destroy(self):
"""
Destroyes this item by disconnecting any signals that may exist. This
is called when the tree clears itself or is deleted. If you are
manually removing an item, you should call the destroy method yourself.
This is required since Python allows for non... | [
"def",
"destroy",
"(",
"self",
")",
":",
"try",
":",
"tree",
"=",
"self",
".",
"treeWidget",
"(",
")",
"tree",
".",
"destroyed",
".",
"disconnect",
"(",
"self",
".",
"destroy",
")",
"except",
"StandardError",
":",
"pass",
"for",
"movie",
"in",
"set",
... | Destroyes this item by disconnecting any signals that may exist. This
is called when the tree clears itself or is deleted. If you are
manually removing an item, you should call the destroy method yourself.
This is required since Python allows for non-QObject connections, and
since ... | [
"Destroyes",
"this",
"item",
"by",
"disconnecting",
"any",
"signals",
"that",
"may",
"exist",
".",
"This",
"is",
"called",
"when",
"the",
"tree",
"clears",
"itself",
"or",
"is",
"deleted",
".",
"If",
"you",
"are",
"manually",
"removing",
"an",
"item",
"you... | python | train |
bootphon/h5features | h5features/h5features.py | https://github.com/bootphon/h5features/blob/d5f95db0f1cee58ac1ba4575d1212e796c39e1f9/h5features/h5features.py#L91-L158 | def write(filename, groupname, items, times, features, properties=None,
dformat='dense', chunk_size='auto', sparsity=0.1, mode='a'):
"""Write h5features data in a HDF5 file.
This function is a wrapper to the Writer class. It has three purposes:
* Check parameters for errors (see details below),
... | [
"def",
"write",
"(",
"filename",
",",
"groupname",
",",
"items",
",",
"times",
",",
"features",
",",
"properties",
"=",
"None",
",",
"dformat",
"=",
"'dense'",
",",
"chunk_size",
"=",
"'auto'",
",",
"sparsity",
"=",
"0.1",
",",
"mode",
"=",
"'a'",
")",... | Write h5features data in a HDF5 file.
This function is a wrapper to the Writer class. It has three purposes:
* Check parameters for errors (see details below),
* Create Items, Times and Features objects
* Send them to the Writer.
:param str filename: HDF5 file to be writted, potentially serving
... | [
"Write",
"h5features",
"data",
"in",
"a",
"HDF5",
"file",
"."
] | python | train |
facelessuser/wcmatch | wcmatch/glob.py | https://github.com/facelessuser/wcmatch/blob/d153e7007cc73b994ae1ba553dc4584039f5c212/wcmatch/glob.py#L442-L456 | def globfilter(filenames, patterns, *, flags=0):
"""Filter names using pattern."""
matches = []
flags = _flag_transform(flags)
unix = _wcparse.is_unix_style(flags)
obj = _wcparse.compile(_wcparse.split(patterns, flags), flags)
for filename in filenames:
if not unix:
filena... | [
"def",
"globfilter",
"(",
"filenames",
",",
"patterns",
",",
"*",
",",
"flags",
"=",
"0",
")",
":",
"matches",
"=",
"[",
"]",
"flags",
"=",
"_flag_transform",
"(",
"flags",
")",
"unix",
"=",
"_wcparse",
".",
"is_unix_style",
"(",
"flags",
")",
"obj",
... | Filter names using pattern. | [
"Filter",
"names",
"using",
"pattern",
"."
] | python | train |
bmcfee/muda | muda/core.py | https://github.com/bmcfee/muda/blob/ff82efdfaeb98da0a9f9124845826eb20536a9ba/muda/core.py#L174-L203 | def serialize(transform, **kwargs):
'''Serialize a transformation object or pipeline.
Parameters
----------
transform : BaseTransform or Pipeline
The transformation object to be serialized
kwargs
Additional keyword arguments to `jsonpickle.encode()`
Returns
-------
jso... | [
"def",
"serialize",
"(",
"transform",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"transform",
".",
"get_params",
"(",
")",
"return",
"jsonpickle",
".",
"encode",
"(",
"params",
",",
"*",
"*",
"kwargs",
")"
] | Serialize a transformation object or pipeline.
Parameters
----------
transform : BaseTransform or Pipeline
The transformation object to be serialized
kwargs
Additional keyword arguments to `jsonpickle.encode()`
Returns
-------
json_str : str
A JSON encoding of the ... | [
"Serialize",
"a",
"transformation",
"object",
"or",
"pipeline",
"."
] | python | valid |
pneff/wsgiservice | wsgiservice/status.py | https://github.com/pneff/wsgiservice/blob/03c064ac2e8c53a1aac9c7b99970f23cf79e20f4/wsgiservice/status.py#L116-L127 | def raise_303(instance, location):
"""Abort the current request with a 303 (See Other) response code. Sets
the Location header correctly. If the location does not start with a
slash, the path of the current request is prepended.
:param instance: Resource instance (used to access the response)
:type... | [
"def",
"raise_303",
"(",
"instance",
",",
"location",
")",
":",
"_set_location",
"(",
"instance",
",",
"location",
")",
"instance",
".",
"response",
".",
"status",
"=",
"303",
"raise",
"ResponseException",
"(",
"instance",
".",
"response",
")"
] | Abort the current request with a 303 (See Other) response code. Sets
the Location header correctly. If the location does not start with a
slash, the path of the current request is prepended.
:param instance: Resource instance (used to access the response)
:type instance: :class:`webob.resource.Resource... | [
"Abort",
"the",
"current",
"request",
"with",
"a",
"303",
"(",
"See",
"Other",
")",
"response",
"code",
".",
"Sets",
"the",
"Location",
"header",
"correctly",
".",
"If",
"the",
"location",
"does",
"not",
"start",
"with",
"a",
"slash",
"the",
"path",
"of"... | python | train |
saltstack/salt | salt/modules/bigip.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bigip.py#L65-L77 | def _load_response(response):
'''
Load the response from json data, return the dictionary or raw text
'''
try:
data = salt.utils.json.loads(response.text)
except ValueError:
data = response.text
ret = {'code': response.status_code, 'content': data}
return ret | [
"def",
"_load_response",
"(",
"response",
")",
":",
"try",
":",
"data",
"=",
"salt",
".",
"utils",
".",
"json",
".",
"loads",
"(",
"response",
".",
"text",
")",
"except",
"ValueError",
":",
"data",
"=",
"response",
".",
"text",
"ret",
"=",
"{",
"'cod... | Load the response from json data, return the dictionary or raw text | [
"Load",
"the",
"response",
"from",
"json",
"data",
"return",
"the",
"dictionary",
"or",
"raw",
"text"
] | python | train |
paylogic/pip-accel | pip_accel/__init__.py | https://github.com/paylogic/pip-accel/blob/ccad1b784927a322d996db593403b1d2d2e22666/pip_accel/__init__.py#L365-L395 | def unpack_source_dists(self, arguments, use_wheels=False):
"""
Find and unpack local source distributions and discover their metadata.
:param arguments: The command line arguments to ``pip install ...`` (a
list of strings).
:param use_wheels: Whether pip and p... | [
"def",
"unpack_source_dists",
"(",
"self",
",",
"arguments",
",",
"use_wheels",
"=",
"False",
")",
":",
"unpack_timer",
"=",
"Timer",
"(",
")",
"logger",
".",
"info",
"(",
"\"Unpacking distribution(s) ..\"",
")",
"with",
"PatchedAttribute",
"(",
"pip_install_modul... | Find and unpack local source distributions and discover their metadata.
:param arguments: The command line arguments to ``pip install ...`` (a
list of strings).
:param use_wheels: Whether pip and pip-accel are allowed to use wheels_
(:data:`False` by... | [
"Find",
"and",
"unpack",
"local",
"source",
"distributions",
"and",
"discover",
"their",
"metadata",
"."
] | python | train |
fedora-infra/fedmsg_meta_fedora_infrastructure | fedmsg_meta_fedora_infrastructure/fasshim.py | https://github.com/fedora-infra/fedmsg_meta_fedora_infrastructure/blob/85bf4162692e3042c7dbcc12dfafaca4764b4ae6/fedmsg_meta_fedora_infrastructure/fasshim.py#L73-L91 | def avatar_url_from_email(email, size=64, default='retro', dns=False):
"""
Our own implementation since fas doesn't support this nicely yet.
"""
if dns:
# This makes an extra DNS SRV query, which can slow down our webapps.
# It is necessary for libravatar federation, though.
imp... | [
"def",
"avatar_url_from_email",
"(",
"email",
",",
"size",
"=",
"64",
",",
"default",
"=",
"'retro'",
",",
"dns",
"=",
"False",
")",
":",
"if",
"dns",
":",
"# This makes an extra DNS SRV query, which can slow down our webapps.",
"# It is necessary for libravatar federatio... | Our own implementation since fas doesn't support this nicely yet. | [
"Our",
"own",
"implementation",
"since",
"fas",
"doesn",
"t",
"support",
"this",
"nicely",
"yet",
"."
] | python | train |
NYUCCL/psiTurk | psiturk/psiturk_org_services.py | https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/psiturk_org_services.py#L182-L224 | def download_experiment(self, experiment_id):
"""
download_experiment:
"""
req = self.query_records_no_auth('experiment',
query='download/'+experiment_id)
if req.status_code == 404:
print "Sorry, no experiment matching id #... | [
"def",
"download_experiment",
"(",
"self",
",",
"experiment_id",
")",
":",
"req",
"=",
"self",
".",
"query_records_no_auth",
"(",
"'experiment'",
",",
"query",
"=",
"'download/'",
"+",
"experiment_id",
")",
"if",
"req",
".",
"status_code",
"==",
"404",
":",
... | download_experiment: | [
"download_experiment",
":"
] | python | train |
ambitioninc/django-query-builder | querybuilder/query.py | https://github.com/ambitioninc/django-query-builder/blob/113a7d845d3ddc6a45621b9880308e756f87c5bf/querybuilder/query.py#L1823-L1835 | def count(self, field='*'):
"""
Returns a COUNT of the query by wrapping the query and performing a COUNT
aggregate of the specified field
:param field: the field to pass to the COUNT aggregate. Defaults to '*'
:type field: str
:return: The number of rows that the query... | [
"def",
"count",
"(",
"self",
",",
"field",
"=",
"'*'",
")",
":",
"rows",
"=",
"self",
".",
"get_count_query",
"(",
")",
".",
"select",
"(",
"bypass_safe_limit",
"=",
"True",
")",
"return",
"list",
"(",
"rows",
"[",
"0",
"]",
".",
"values",
"(",
")"... | Returns a COUNT of the query by wrapping the query and performing a COUNT
aggregate of the specified field
:param field: the field to pass to the COUNT aggregate. Defaults to '*'
:type field: str
:return: The number of rows that the query will return
:rtype: int | [
"Returns",
"a",
"COUNT",
"of",
"the",
"query",
"by",
"wrapping",
"the",
"query",
"and",
"performing",
"a",
"COUNT",
"aggregate",
"of",
"the",
"specified",
"field"
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.