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 |
|---|---|---|---|---|---|---|---|---|
iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/jar.py#L72-L78 | def jarManifest(target, source, env, for_signature):
"""Look in sources for a manifest file, if any."""
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
return src
return '' | [
"def",
"jarManifest",
"(",
"target",
",",
"source",
",",
"env",
",",
"for_signature",
")",
":",
"for",
"src",
"in",
"source",
":",
"contents",
"=",
"src",
".",
"get_text_contents",
"(",
")",
"if",
"contents",
"[",
":",
"16",
"]",
"==",
"\"Manifest-Versio... | Look in sources for a manifest file, if any. | [
"Look",
"in",
"sources",
"for",
"a",
"manifest",
"file",
"if",
"any",
"."
] | python | train |
zerotk/easyfs | zerotk/easyfs/_easyfs.py | https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L696-L722 | def DeleteFile(target_filename):
'''
Deletes the given local filename.
.. note:: If file doesn't exist this method has no effect.
:param unicode target_filename:
A local filename
:raises NotImplementedForRemotePathError:
If trying to delete a non-local path
:raises FileOnlyAc... | [
"def",
"DeleteFile",
"(",
"target_filename",
")",
":",
"_AssertIsLocal",
"(",
"target_filename",
")",
"try",
":",
"if",
"IsLink",
"(",
"target_filename",
")",
":",
"DeleteLink",
"(",
"target_filename",
")",
"elif",
"IsFile",
"(",
"target_filename",
")",
":",
"... | Deletes the given local filename.
.. note:: If file doesn't exist this method has no effect.
:param unicode target_filename:
A local filename
:raises NotImplementedForRemotePathError:
If trying to delete a non-local path
:raises FileOnlyActionError:
Raised when filename refer... | [
"Deletes",
"the",
"given",
"local",
"filename",
"."
] | python | valid |
oscarlazoarjona/fast | fast/graphic.py | https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L758-L771 | def mirror(ax, p0, alpha=0, size=2.54, width=0.5, format=None):
r"""Draw a mirror."""
if format is None: format = 'k-'
x0 = [size/2, -size/2, -size/2, size/2, size/2]
y0 = [0, 0, -width, -width, 0]
x1 = [size/2, size/2-width]; y1 = [0, -width]
x2 = [-size/2+width, -size/2]; y2 = [0, -w... | [
"def",
"mirror",
"(",
"ax",
",",
"p0",
",",
"alpha",
"=",
"0",
",",
"size",
"=",
"2.54",
",",
"width",
"=",
"0.5",
",",
"format",
"=",
"None",
")",
":",
"if",
"format",
"is",
"None",
":",
"format",
"=",
"'k-'",
"x0",
"=",
"[",
"size",
"/",
"2... | r"""Draw a mirror. | [
"r",
"Draw",
"a",
"mirror",
"."
] | python | train |
pymupdf/PyMuPDF | fitz/fitz.py | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/fitz.py#L2959-L2961 | def _insertImage(self, filename=None, pixmap=None, stream=None, overlay=1, matrix=None, _imgname=None, _imgpointer=None):
"""_insertImage(self, filename=None, pixmap=None, stream=None, overlay=1, matrix=None, _imgname=None, _imgpointer=None) -> PyObject *"""
return _fitz.Page__insertImage(self, filename... | [
"def",
"_insertImage",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"pixmap",
"=",
"None",
",",
"stream",
"=",
"None",
",",
"overlay",
"=",
"1",
",",
"matrix",
"=",
"None",
",",
"_imgname",
"=",
"None",
",",
"_imgpointer",
"=",
"None",
")",
":",
... | _insertImage(self, filename=None, pixmap=None, stream=None, overlay=1, matrix=None, _imgname=None, _imgpointer=None) -> PyObject * | [
"_insertImage",
"(",
"self",
"filename",
"=",
"None",
"pixmap",
"=",
"None",
"stream",
"=",
"None",
"overlay",
"=",
"1",
"matrix",
"=",
"None",
"_imgname",
"=",
"None",
"_imgpointer",
"=",
"None",
")",
"-",
">",
"PyObject",
"*"
] | python | train |
dgketchum/satellite_image | sat_image/fmask.py | https://github.com/dgketchum/satellite_image/blob/0207fbb7b2bbf14f4307db65489bb4d4c5b92f52/sat_image/fmask.py#L300-L318 | def brightness_prob(self, clip=True):
"""The brightest water may have Band 5 reflectance
as high as LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF.11
Equation 10 (Zhu and Woodcock, 2012)
Parameters
----------
nir: ndarray
clip: boolean
Output
... | [
"def",
"brightness_prob",
"(",
"self",
",",
"clip",
"=",
"True",
")",
":",
"thresh",
"=",
"0.11",
"bp",
"=",
"np",
".",
"minimum",
"(",
"thresh",
",",
"self",
".",
"nir",
")",
"/",
"thresh",
"if",
"clip",
":",
"bp",
"[",
"bp",
">",
"1",
"]",
"=... | The brightest water may have Band 5 reflectance
as high as LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF.11
Equation 10 (Zhu and Woodcock, 2012)
Parameters
----------
nir: ndarray
clip: boolean
Output
------
ndarray:
brightness p... | [
"The",
"brightest",
"water",
"may",
"have",
"Band",
"5",
"reflectance",
"as",
"high",
"as",
"LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1",
".",
"TIF",
".",
"11",
"Equation",
"10",
"(",
"Zhu",
"and",
"Woodcock",
"2012",
")",
"Parameters",
"----------",
"nir",
... | python | train |
hydpy-dev/hydpy | hydpy/core/itemtools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/itemtools.py#L117-L207 | def collect_variables(self, selections) -> None:
"""Apply method |ExchangeItem.insert_variables| to collect the
relevant target variables handled by the devices of the given
|Selections| object.
We prepare the `LahnH` example project to be able to use its
|Selections| object:
... | [
"def",
"collect_variables",
"(",
"self",
",",
"selections",
")",
"->",
"None",
":",
"self",
".",
"insert_variables",
"(",
"self",
".",
"device2target",
",",
"self",
".",
"targetspecs",
",",
"selections",
")"
] | Apply method |ExchangeItem.insert_variables| to collect the
relevant target variables handled by the devices of the given
|Selections| object.
We prepare the `LahnH` example project to be able to use its
|Selections| object:
>>> from hydpy.core.examples import prepare_full_exam... | [
"Apply",
"method",
"|ExchangeItem",
".",
"insert_variables|",
"to",
"collect",
"the",
"relevant",
"target",
"variables",
"handled",
"by",
"the",
"devices",
"of",
"the",
"given",
"|Selections|",
"object",
"."
] | python | train |
angr/angr | angr/calling_conventions.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/calling_conventions.py#L448-L465 | def arg_locs(self, is_fp=None, sizes=None):
"""
Pass this a list of whether each parameter is floating-point or not, and get back a list of
SimFunctionArguments. Optionally, pass a list of argument sizes (in bytes) as well.
If you've customized this CC, this will sanity-check the provid... | [
"def",
"arg_locs",
"(",
"self",
",",
"is_fp",
"=",
"None",
",",
"sizes",
"=",
"None",
")",
":",
"session",
"=",
"self",
".",
"arg_session",
"if",
"self",
".",
"func_ty",
"is",
"None",
":",
"# No function prototype is provided. `is_fp` must be provided.",
"if",
... | Pass this a list of whether each parameter is floating-point or not, and get back a list of
SimFunctionArguments. Optionally, pass a list of argument sizes (in bytes) as well.
If you've customized this CC, this will sanity-check the provided locations with the given list. | [
"Pass",
"this",
"a",
"list",
"of",
"whether",
"each",
"parameter",
"is",
"floating",
"-",
"point",
"or",
"not",
"and",
"get",
"back",
"a",
"list",
"of",
"SimFunctionArguments",
".",
"Optionally",
"pass",
"a",
"list",
"of",
"argument",
"sizes",
"(",
"in",
... | python | train |
SpriteLink/NIPAP | nipap/nipap/backend.py | https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap/nipap/backend.py#L4196-L4254 | def _expand_tag_query(self, query, table_name = None):
""" Expand Tag query dict into a WHERE-clause.
If you need to prefix each column reference with a table
name, that can be supplied via the table_name argument.
"""
where = unicode()
opt = list()
# h... | [
"def",
"_expand_tag_query",
"(",
"self",
",",
"query",
",",
"table_name",
"=",
"None",
")",
":",
"where",
"=",
"unicode",
"(",
")",
"opt",
"=",
"list",
"(",
")",
"# handle table name, can be None",
"if",
"table_name",
"is",
"None",
":",
"col_prefix",
"=",
... | Expand Tag query dict into a WHERE-clause.
If you need to prefix each column reference with a table
name, that can be supplied via the table_name argument. | [
"Expand",
"Tag",
"query",
"dict",
"into",
"a",
"WHERE",
"-",
"clause",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py#L1351-L1362 | def get_media_detail_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
input = ET.SubElement(get_media_detail, "input")
rbridge_id = ET.SubElement(... | [
"def",
"get_media_detail_input_rbridge_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_media_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_media_detail\"",
")",
"config",
"=",
"get_media_... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
hannes-brt/hebel | hebel/pycuda_ops/cublas.py | https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/cublas.py#L3918-L3931 | def cublasSgemm(handle, transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc):
"""
Matrix-matrix product for real general matrix.
"""
status = _libcublas.cublasSgemm_v2(handle,
_CUBLAS_OP[transa],
_CUBLAS_OP[transb],... | [
"def",
"cublasSgemm",
"(",
"handle",
",",
"transa",
",",
"transb",
",",
"m",
",",
"n",
",",
"k",
",",
"alpha",
",",
"A",
",",
"lda",
",",
"B",
",",
"ldb",
",",
"beta",
",",
"C",
",",
"ldc",
")",
":",
"status",
"=",
"_libcublas",
".",
"cublasSge... | Matrix-matrix product for real general matrix. | [
"Matrix",
"-",
"matrix",
"product",
"for",
"real",
"general",
"matrix",
"."
] | python | train |
jason-weirather/py-seq-tools | seqtools/format/sam/__init__.py | https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/format/sam/__init__.py#L187-L192 | def query_sequence_length(self):
""" does not include hard clipped"""
if self.entries.seq: return len(self.entries.seq)
if not self.entries.cigar:
raise ValueError('Cannot give a query length if no cigar and no query sequence are present')
return sum([x[0] for x in self.cigar_array if re.match('[... | [
"def",
"query_sequence_length",
"(",
"self",
")",
":",
"if",
"self",
".",
"entries",
".",
"seq",
":",
"return",
"len",
"(",
"self",
".",
"entries",
".",
"seq",
")",
"if",
"not",
"self",
".",
"entries",
".",
"cigar",
":",
"raise",
"ValueError",
"(",
"... | does not include hard clipped | [
"does",
"not",
"include",
"hard",
"clipped"
] | python | train |
edx/edx-enterprise | consent/helpers.py | https://github.com/edx/edx-enterprise/blob/aea91379ab0a87cd3bc798961fce28b60ee49a80/consent/helpers.py#L34-L49 | def get_course_data_sharing_consent(username, course_id, enterprise_customer_uuid):
"""
Get the data sharing consent object associated with a certain user of a customer for a course.
:param username: The user that grants consent.
:param course_id: The course for which consent is granted.
:param ent... | [
"def",
"get_course_data_sharing_consent",
"(",
"username",
",",
"course_id",
",",
"enterprise_customer_uuid",
")",
":",
"# Prevent circular imports.",
"DataSharingConsent",
"=",
"apps",
".",
"get_model",
"(",
"'consent'",
",",
"'DataSharingConsent'",
")",
"# pylint: disable... | Get the data sharing consent object associated with a certain user of a customer for a course.
:param username: The user that grants consent.
:param course_id: The course for which consent is granted.
:param enterprise_customer_uuid: The consent requester.
:return: The data sharing consent object | [
"Get",
"the",
"data",
"sharing",
"consent",
"object",
"associated",
"with",
"a",
"certain",
"user",
"of",
"a",
"customer",
"for",
"a",
"course",
"."
] | python | valid |
softlayer/softlayer-python | SoftLayer/managers/firewall.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/firewall.py#L63-L80 | def get_dedicated_package(self, ha_enabled=False):
"""Retrieves the dedicated firewall package.
:param bool ha_enabled: True if HA is to be enabled on the firewall
False for No HA
:returns: A dictionary containing the dedicated virtual server firewall
... | [
"def",
"get_dedicated_package",
"(",
"self",
",",
"ha_enabled",
"=",
"False",
")",
":",
"fwl_filter",
"=",
"'Hardware Firewall (Dedicated)'",
"ha_fwl_filter",
"=",
"'Hardware Firewall (High Availability)'",
"_filter",
"=",
"utils",
".",
"NestedDict",
"(",
"{",
"}",
")... | Retrieves the dedicated firewall package.
:param bool ha_enabled: True if HA is to be enabled on the firewall
False for No HA
:returns: A dictionary containing the dedicated virtual server firewall
package | [
"Retrieves",
"the",
"dedicated",
"firewall",
"package",
"."
] | python | train |
QUANTAXIS/QUANTAXIS | QUANTAXIS/QAFetch/QATdx.py | https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L276-L297 | def get_mainmarket_ip(ip, port):
"""[summary]
Arguments:
ip {[type]} -- [description]
port {[type]} -- [description]
Returns:
[type] -- [description]
"""
global best_ip
if ip is None and port is None and best_ip['stock']['ip'] is None and best_ip['stock']['port'] is No... | [
"def",
"get_mainmarket_ip",
"(",
"ip",
",",
"port",
")",
":",
"global",
"best_ip",
"if",
"ip",
"is",
"None",
"and",
"port",
"is",
"None",
"and",
"best_ip",
"[",
"'stock'",
"]",
"[",
"'ip'",
"]",
"is",
"None",
"and",
"best_ip",
"[",
"'stock'",
"]",
"[... | [summary]
Arguments:
ip {[type]} -- [description]
port {[type]} -- [description]
Returns:
[type] -- [description] | [
"[",
"summary",
"]"
] | python | train |
robotools/fontParts | Lib/fontParts/base/kerning.py | https://github.com/robotools/fontParts/blob/d2ff106fe95f9d566161d936a645157626568712/Lib/fontParts/base/kerning.py#L157-L189 | def _interpolate(self, factor, minKerning, maxKerning,
round=True, suppressError=True):
"""
This is the environment implementation of :meth:`BaseKerning.interpolate`.
* **factor** will be an :ref:`type-int-float`, ``tuple`` or ``list``.
* **minKerning** will be a :c... | [
"def",
"_interpolate",
"(",
"self",
",",
"factor",
",",
"minKerning",
",",
"maxKerning",
",",
"round",
"=",
"True",
",",
"suppressError",
"=",
"True",
")",
":",
"import",
"fontMath",
"kerningGroupCompatibility",
"=",
"self",
".",
"_testKerningGroupCompatibility",
... | This is the environment implementation of :meth:`BaseKerning.interpolate`.
* **factor** will be an :ref:`type-int-float`, ``tuple`` or ``list``.
* **minKerning** will be a :class:`BaseKerning` object.
* **maxKerning** will be a :class:`BaseKerning` object.
* **round** will be a ``bool``... | [
"This",
"is",
"the",
"environment",
"implementation",
"of",
":",
"meth",
":",
"BaseKerning",
".",
"interpolate",
"."
] | python | train |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/build/build_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/build/build_client.py#L632-L646 | def delete_definition(self, project, definition_id):
"""DeleteDefinition.
Deletes a definition and all associated builds.
:param str project: Project ID or project name
:param int definition_id: The ID of the definition.
"""
route_values = {}
if project is not Non... | [
"def",
"delete_definition",
"(",
"self",
",",
"project",
",",
"definition_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'p... | DeleteDefinition.
Deletes a definition and all associated builds.
:param str project: Project ID or project name
:param int definition_id: The ID of the definition. | [
"DeleteDefinition",
".",
"Deletes",
"a",
"definition",
"and",
"all",
"associated",
"builds",
".",
":",
"param",
"str",
"project",
":",
"Project",
"ID",
"or",
"project",
"name",
":",
"param",
"int",
"definition_id",
":",
"The",
"ID",
"of",
"the",
"definition"... | python | train |
frictionlessdata/tabulator-py | tabulator/stream.py | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/stream.py#L307-L318 | def sample(self):
'''Returns the stream's rows used as sample.
These sample rows are used internally to infer characteristics of the
source file (e.g. encoding, headers, ...).
'''
sample = []
iterator = iter(self.__sample_extended_rows)
iterator = self.__apply_pr... | [
"def",
"sample",
"(",
"self",
")",
":",
"sample",
"=",
"[",
"]",
"iterator",
"=",
"iter",
"(",
"self",
".",
"__sample_extended_rows",
")",
"iterator",
"=",
"self",
".",
"__apply_processors",
"(",
"iterator",
")",
"for",
"row_number",
",",
"headers",
",",
... | Returns the stream's rows used as sample.
These sample rows are used internally to infer characteristics of the
source file (e.g. encoding, headers, ...). | [
"Returns",
"the",
"stream",
"s",
"rows",
"used",
"as",
"sample",
"."
] | python | train |
MartinThoma/mpu | mpu/path.py | https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/path.py#L35-L51 | def get_from_package(package_name, path):
"""
Get the absolute path to a file in a package.
Parameters
----------
package_name : str
e.g. 'mpu'
path : str
Path within a package
Returns
-------
filepath : str
"""
filepath = pkg_resources.resource_filename(pac... | [
"def",
"get_from_package",
"(",
"package_name",
",",
"path",
")",
":",
"filepath",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"package_name",
",",
"path",
")",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"filepath",
")"
] | Get the absolute path to a file in a package.
Parameters
----------
package_name : str
e.g. 'mpu'
path : str
Path within a package
Returns
-------
filepath : str | [
"Get",
"the",
"absolute",
"path",
"to",
"a",
"file",
"in",
"a",
"package",
"."
] | python | train |
tanghaibao/goatools | goatools/gosubdag/rpt/write_hierarchy.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/gosubdag/rpt/write_hierarchy.py#L34-L39 | def prt_hier_down(self, goid, prt=sys.stdout):
"""Write hierarchy for all GO IDs below GO ID in arg, goid."""
wrhiercfg = self._get_wrhiercfg()
obj = WrHierPrt(self.gosubdag.go2obj, self.gosubdag.go2nt, wrhiercfg, prt)
obj.prt_hier_rec(goid)
return obj.items_list | [
"def",
"prt_hier_down",
"(",
"self",
",",
"goid",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"wrhiercfg",
"=",
"self",
".",
"_get_wrhiercfg",
"(",
")",
"obj",
"=",
"WrHierPrt",
"(",
"self",
".",
"gosubdag",
".",
"go2obj",
",",
"self",
".",
"gos... | Write hierarchy for all GO IDs below GO ID in arg, goid. | [
"Write",
"hierarchy",
"for",
"all",
"GO",
"IDs",
"below",
"GO",
"ID",
"in",
"arg",
"goid",
"."
] | python | train |
iotile/coretools | iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/reference/controller_features/clock_manager.py#L143-L155 | def handle_tick(self):
"""Internal callback every time 1 second has passed."""
self.uptime += 1
for name, interval in self.ticks.items():
if interval == 0:
continue
self.tick_counters[name] += 1
if self.tick_counters[name] == interval:
... | [
"def",
"handle_tick",
"(",
"self",
")",
":",
"self",
".",
"uptime",
"+=",
"1",
"for",
"name",
",",
"interval",
"in",
"self",
".",
"ticks",
".",
"items",
"(",
")",
":",
"if",
"interval",
"==",
"0",
":",
"continue",
"self",
".",
"tick_counters",
"[",
... | Internal callback every time 1 second has passed. | [
"Internal",
"callback",
"every",
"time",
"1",
"second",
"has",
"passed",
"."
] | python | train |
Cue/scales | src/greplin/scales/__init__.py | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L173-L183 | def __getStatContainer(cls, context, parent=None):
"""Get the stat container for the given context under the given parent."""
container = parent
if container is None:
container = cls.stats
if context is not None:
context = str(context).lstrip('/')
for key in context.split('/'):
... | [
"def",
"__getStatContainer",
"(",
"cls",
",",
"context",
",",
"parent",
"=",
"None",
")",
":",
"container",
"=",
"parent",
"if",
"container",
"is",
"None",
":",
"container",
"=",
"cls",
".",
"stats",
"if",
"context",
"is",
"not",
"None",
":",
"context",
... | Get the stat container for the given context under the given parent. | [
"Get",
"the",
"stat",
"container",
"for",
"the",
"given",
"context",
"under",
"the",
"given",
"parent",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/io/abinit/tasks.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L2394-L2475 | def start(self, **kwargs):
"""
Starts the calculation by performing the following steps:
- build dirs and files
- call the _setup method
- execute the job file by executing/submitting the job script.
Main entry point for the `Launcher`.
============... | [
"def",
"start",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"status",
">=",
"self",
".",
"S_SUB",
":",
"raise",
"self",
".",
"Error",
"(",
"\"Task status: %s\"",
"%",
"str",
"(",
"self",
".",
"status",
")",
")",
"if",
"self",... | Starts the calculation by performing the following steps:
- build dirs and files
- call the _setup method
- execute the job file by executing/submitting the job script.
Main entry point for the `Launcher`.
============== ===========================================... | [
"Starts",
"the",
"calculation",
"by",
"performing",
"the",
"following",
"steps",
":"
] | python | train |
4Catalyzer/flask-resty | flask_resty/view.py | https://github.com/4Catalyzer/flask-resty/blob/a8b6502a799c270ca9ce41c6d8b7297713942097/flask_resty/view.py#L167-L188 | def request_args(self):
"""Use args_schema to parse request query arguments."""
args = flask.request.args
data_raw = {}
for field_name, field in self.args_schema.fields.items():
alternate_field_name = field.load_from if MA2 else field.data_key
if alternate_field... | [
"def",
"request_args",
"(",
"self",
")",
":",
"args",
"=",
"flask",
".",
"request",
".",
"args",
"data_raw",
"=",
"{",
"}",
"for",
"field_name",
",",
"field",
"in",
"self",
".",
"args_schema",
".",
"fields",
".",
"items",
"(",
")",
":",
"alternate_fiel... | Use args_schema to parse request query arguments. | [
"Use",
"args_schema",
"to",
"parse",
"request",
"query",
"arguments",
"."
] | python | train |
mfcloud/python-zvm-sdk | zvmsdk/sdkserver.py | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/sdkserver.py#L87-L109 | def send_results(self, client, addr, results):
""" send back results to client in the json format of:
{'overallRC': x, 'modID': x, 'rc': x, 'rs': x, 'errmsg': 'msg',
'output': 'out'}
"""
json_results = json.dumps(results)
json_results = json_results.encode()
sen... | [
"def",
"send_results",
"(",
"self",
",",
"client",
",",
"addr",
",",
"results",
")",
":",
"json_results",
"=",
"json",
".",
"dumps",
"(",
"results",
")",
"json_results",
"=",
"json_results",
".",
"encode",
"(",
")",
"sent",
"=",
"0",
"total_len",
"=",
... | send back results to client in the json format of:
{'overallRC': x, 'modID': x, 'rc': x, 'rs': x, 'errmsg': 'msg',
'output': 'out'} | [
"send",
"back",
"results",
"to",
"client",
"in",
"the",
"json",
"format",
"of",
":",
"{",
"overallRC",
":",
"x",
"modID",
":",
"x",
"rc",
":",
"x",
"rs",
":",
"x",
"errmsg",
":",
"msg",
"output",
":",
"out",
"}"
] | python | train |
MakerReduxCorp/PLOD | PLOD/__init__.py | https://github.com/MakerReduxCorp/PLOD/blob/707502cd928e5be6bd5e46d7f6de7da0e188cf1e/PLOD/__init__.py#L1301-L1331 | def returnValue(self, key, last=False):
'''Return the key's value for the first entry in the current list.
If 'last=True', then the last entry is referenced."
Returns None is the list is empty or the key is missing.
Example of use:
>>> test = [
... {"name": "Jim", ... | [
"def",
"returnValue",
"(",
"self",
",",
"key",
",",
"last",
"=",
"False",
")",
":",
"row",
"=",
"self",
".",
"returnOneEntry",
"(",
"last",
"=",
"last",
")",
"if",
"not",
"row",
":",
"return",
"None",
"dict_row",
"=",
"internal",
".",
"convert_to_dict"... | Return the key's value for the first entry in the current list.
If 'last=True', then the last entry is referenced."
Returns None is the list is empty or the key is missing.
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "order": 2},
.... | [
"Return",
"the",
"key",
"s",
"value",
"for",
"the",
"first",
"entry",
"in",
"the",
"current",
"list",
".",
"If",
"last",
"=",
"True",
"then",
"the",
"last",
"entry",
"is",
"referenced",
"."
] | python | train |
richardliaw/track | track/log.py | https://github.com/richardliaw/track/blob/7ac42ea34e5c1d7bb92fd813e938835a06a63fc7/track/log.py#L30-L57 | def init(track_log_handler):
"""
(Re)initialize track's file handler for track package logger.
Adds a stdout-printing handler automatically.
"""
logger = logging.getLogger(__package__)
# TODO (just document prominently)
# assume only one trial can run at once right now
# multi-concurr... | [
"def",
"init",
"(",
"track_log_handler",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__package__",
")",
"# TODO (just document prominently)",
"# assume only one trial can run at once right now",
"# multi-concurrent-trial support will require complex filter logic",
"... | (Re)initialize track's file handler for track package logger.
Adds a stdout-printing handler automatically. | [
"(",
"Re",
")",
"initialize",
"track",
"s",
"file",
"handler",
"for",
"track",
"package",
"logger",
"."
] | python | train |
marshallward/f90nml | f90nml/parser.py | https://github.com/marshallward/f90nml/blob/4932cabc5221afc844ee6a5b4a05ceb8bd4a2711/f90nml/parser.py#L107-L112 | def default_start_index(self, value):
"""Validate and set the default start index."""
if not isinstance(value, int):
raise TypeError('default_start_index attribute must be of int '
'type.')
self._default_start_index = value | [
"def",
"default_start_index",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"'default_start_index attribute must be of int '",
"'type.'",
")",
"self",
".",
"_default_start_index",
"="... | Validate and set the default start index. | [
"Validate",
"and",
"set",
"the",
"default",
"start",
"index",
"."
] | python | train |
AirtestProject/Poco | poco/pocofw.py | https://github.com/AirtestProject/Poco/blob/2c559a586adf3fd11ee81cabc446d4d3f6f2d119/poco/pocofw.py#L307-L323 | def long_click(self, pos, duration=2.0):
"""
Similar to click but press the screen for the given time interval and then release
Args:
pos (:obj:`2-list/2-tuple`): coordinates (x, y) in range from 0 to 1
duration: duration of press the screen
"""
try:
... | [
"def",
"long_click",
"(",
"self",
",",
"pos",
",",
"duration",
"=",
"2.0",
")",
":",
"try",
":",
"duration",
"=",
"float",
"(",
"duration",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'Argument `duration` should be <float>. Got {}'",
".",
"f... | Similar to click but press the screen for the given time interval and then release
Args:
pos (:obj:`2-list/2-tuple`): coordinates (x, y) in range from 0 to 1
duration: duration of press the screen | [
"Similar",
"to",
"click",
"but",
"press",
"the",
"screen",
"for",
"the",
"given",
"time",
"interval",
"and",
"then",
"release"
] | python | train |
AshleySetter/optoanalysis | optoanalysis/optoanalysis/Saleae/Saleae.py | https://github.com/AshleySetter/optoanalysis/blob/9d390acc834d70024d47b574aea14189a5a5714e/optoanalysis/optoanalysis/Saleae/Saleae.py#L82-L122 | def interpret_waveform(fileContent, RelativeChannelNo):
"""
Extracts the data for just 1 channel and computes the corresponding
time array (in seconds) starting from 0.
Important Note: RelativeChannelNo is NOT the channel number on the Saleae data logger
it is the relative number of the channe... | [
"def",
"interpret_waveform",
"(",
"fileContent",
",",
"RelativeChannelNo",
")",
":",
"(",
"ChannelData",
",",
"LenOf1Channel",
",",
"NumOfChannels",
",",
"SampleTime",
")",
"=",
"read_data_from_bytes",
"(",
"fileContent",
")",
"if",
"RelativeChannelNo",
">",
"NumOfC... | Extracts the data for just 1 channel and computes the corresponding
time array (in seconds) starting from 0.
Important Note: RelativeChannelNo is NOT the channel number on the Saleae data logger
it is the relative number of the channel that was saved. E.g. if you
save channels 3, 7 and 10, the co... | [
"Extracts",
"the",
"data",
"for",
"just",
"1",
"channel",
"and",
"computes",
"the",
"corresponding",
"time",
"array",
"(",
"in",
"seconds",
")",
"starting",
"from",
"0",
".",
"Important",
"Note",
":",
"RelativeChannelNo",
"is",
"NOT",
"the",
"channel",
"numb... | python | train |
qubole/qds-sdk-py | qds_sdk/cluster.py | https://github.com/qubole/qds-sdk-py/blob/77210fb64e5a7d567aedeea3b742a1d872fd0e5e/qds_sdk/cluster.py#L943-L956 | def set_security_settings(self,
encrypted_ephemerals=None,
customer_ssh_key=None,
persistent_security_group=None):
"""
Kwargs:
`encrypted_ephemerals`: Encrypt the ephemeral drives on the instance.
... | [
"def",
"set_security_settings",
"(",
"self",
",",
"encrypted_ephemerals",
"=",
"None",
",",
"customer_ssh_key",
"=",
"None",
",",
"persistent_security_group",
"=",
"None",
")",
":",
"self",
".",
"security_settings",
"[",
"'encrypted_ephemerals'",
"]",
"=",
"encrypte... | Kwargs:
`encrypted_ephemerals`: Encrypt the ephemeral drives on the instance.
`customer_ssh_key`: SSH key to use to login to the instances. | [
"Kwargs",
":"
] | python | train |
morse-talk/morse-talk | morse_talk/sound.py | https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/sound.py#L50-L65 | def write_wavefile(f, samples, nframes=None, nchannels=2, sampwidth=2, framerate=44100, bufsize=2048):
"Write samples to a wavefile."
if nframes is None:
nframes = 0
w = wave.open(f, 'wb')
w.setparams((nchannels, sampwidth, framerate, nframes, 'NONE', 'not compressed'))
max_amplitude = flo... | [
"def",
"write_wavefile",
"(",
"f",
",",
"samples",
",",
"nframes",
"=",
"None",
",",
"nchannels",
"=",
"2",
",",
"sampwidth",
"=",
"2",
",",
"framerate",
"=",
"44100",
",",
"bufsize",
"=",
"2048",
")",
":",
"if",
"nframes",
"is",
"None",
":",
"nframe... | Write samples to a wavefile. | [
"Write",
"samples",
"to",
"a",
"wavefile",
"."
] | python | train |
openspending/babbage | babbage/api.py | https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/api.py#L16-L22 | def configure_api(app, manager):
""" Configure the current Flask app with an instance of ``CubeManager`` that
will be used to load and query data. """
if not hasattr(app, 'extensions'):
app.extensions = {} # pragma: nocover
app.extensions['babbage'] = manager
return blueprint | [
"def",
"configure_api",
"(",
"app",
",",
"manager",
")",
":",
"if",
"not",
"hasattr",
"(",
"app",
",",
"'extensions'",
")",
":",
"app",
".",
"extensions",
"=",
"{",
"}",
"# pragma: nocover",
"app",
".",
"extensions",
"[",
"'babbage'",
"]",
"=",
"manager"... | Configure the current Flask app with an instance of ``CubeManager`` that
will be used to load and query data. | [
"Configure",
"the",
"current",
"Flask",
"app",
"with",
"an",
"instance",
"of",
"CubeManager",
"that",
"will",
"be",
"used",
"to",
"load",
"and",
"query",
"data",
"."
] | python | train |
koalalorenzo/python-digitalocean | digitalocean/Manager.py | https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L335-L349 | def get_all_volumes(self, region=None):
"""
This function returns a list of Volume objects.
"""
if region:
url = "volumes?region={}".format(region)
else:
url = "volumes"
data = self.get_data(url)
volumes = list()
for jsoned in d... | [
"def",
"get_all_volumes",
"(",
"self",
",",
"region",
"=",
"None",
")",
":",
"if",
"region",
":",
"url",
"=",
"\"volumes?region={}\"",
".",
"format",
"(",
"region",
")",
"else",
":",
"url",
"=",
"\"volumes\"",
"data",
"=",
"self",
".",
"get_data",
"(",
... | This function returns a list of Volume objects. | [
"This",
"function",
"returns",
"a",
"list",
"of",
"Volume",
"objects",
"."
] | python | valid |
pantsbuild/pants | src/python/pants/util/dirutil.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/dirutil.py#L35-L40 | def fast_relpath(path, start):
"""A prefix-based relpath, with no normalization or support for returning `..`."""
relpath = fast_relpath_optional(path, start)
if relpath is None:
raise ValueError('{} is not a directory containing {}'.format(start, path))
return relpath | [
"def",
"fast_relpath",
"(",
"path",
",",
"start",
")",
":",
"relpath",
"=",
"fast_relpath_optional",
"(",
"path",
",",
"start",
")",
"if",
"relpath",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'{} is not a directory containing {}'",
".",
"format",
"(",
"s... | A prefix-based relpath, with no normalization or support for returning `..`. | [
"A",
"prefix",
"-",
"based",
"relpath",
"with",
"no",
"normalization",
"or",
"support",
"for",
"returning",
"..",
"."
] | python | train |
pybel/pybel-tools | src/pybel_tools/analysis/heat.py | https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/heat.py#L464-L472 | def get_final_score(self) -> float:
"""Return the final score for the target node.
:return: The final score for the target node
"""
if not self.done_chomping():
raise ValueError('algorithm has not yet completed')
return self.graph.nodes[self.target_node][self.tag] | [
"def",
"get_final_score",
"(",
"self",
")",
"->",
"float",
":",
"if",
"not",
"self",
".",
"done_chomping",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'algorithm has not yet completed'",
")",
"return",
"self",
".",
"graph",
".",
"nodes",
"[",
"self",
".",
... | Return the final score for the target node.
:return: The final score for the target node | [
"Return",
"the",
"final",
"score",
"for",
"the",
"target",
"node",
"."
] | python | valid |
tensorflow/tensor2tensor | tensor2tensor/layers/common_layers.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/common_layers.py#L3045-L3062 | def recompute_grad(fn):
"""Decorator that recomputes the function on the backwards pass.
Args:
fn: a function that takes Tensors (all as positional arguments) and returns
a tuple of Tensors.
Returns:
A wrapped fn that is identical to fn when called, but its activations will
be discarded and re... | [
"def",
"recompute_grad",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapped",
"(",
"*",
"args",
")",
":",
"return",
"_recompute_grad",
"(",
"fn",
",",
"args",
")",
"return",
"wrapped"
] | Decorator that recomputes the function on the backwards pass.
Args:
fn: a function that takes Tensors (all as positional arguments) and returns
a tuple of Tensors.
Returns:
A wrapped fn that is identical to fn when called, but its activations will
be discarded and recomputed on the backwards pas... | [
"Decorator",
"that",
"recomputes",
"the",
"function",
"on",
"the",
"backwards",
"pass",
"."
] | python | train |
StackStorm/pybind | pybind/nos/v7_2_0/rbridge_id/evpn_instance/route_target/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v7_2_0/rbridge_id/evpn_instance/route_target/__init__.py#L96-L117 | def _set_import_(self, v, load=False):
"""
Setter method for import_, mapped from YANG variable /rbridge_id/evpn_instance/route_target/import (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_import_ is considered as a private
method. Backends looking to populat... | [
"def",
"_set_import_",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",... | Setter method for import_, mapped from YANG variable /rbridge_id/evpn_instance/route_target/import (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_import_ is considered as a private
method. Backends looking to populate this variable should
do so via calling thisOb... | [
"Setter",
"method",
"for",
"import_",
"mapped",
"from",
"YANG",
"variable",
"/",
"rbridge_id",
"/",
"evpn_instance",
"/",
"route_target",
"/",
"import",
"(",
"list",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")"... | python | train |
neo4j/neo4j-python-driver | neo4j/types/temporal.py | https://github.com/neo4j/neo4j-python-driver/blob/0c641e826765e86ff5454dae57c99521db8ca45c/neo4j/types/temporal.py#L100-L120 | def hydrate_datetime(seconds, nanoseconds, tz=None):
""" Hydrator for `DateTime` and `LocalDateTime` values.
:param seconds:
:param nanoseconds:
:param tz:
:return: datetime
"""
minutes, seconds = map(int, divmod(seconds, 60))
hours, minutes = map(int, divmod(minutes, 60))
days, hou... | [
"def",
"hydrate_datetime",
"(",
"seconds",
",",
"nanoseconds",
",",
"tz",
"=",
"None",
")",
":",
"minutes",
",",
"seconds",
"=",
"map",
"(",
"int",
",",
"divmod",
"(",
"seconds",
",",
"60",
")",
")",
"hours",
",",
"minutes",
"=",
"map",
"(",
"int",
... | Hydrator for `DateTime` and `LocalDateTime` values.
:param seconds:
:param nanoseconds:
:param tz:
:return: datetime | [
"Hydrator",
"for",
"DateTime",
"and",
"LocalDateTime",
"values",
"."
] | python | train |
gtaylor/python-route53 | route53/xml_parsers/list_resource_record_sets_by_zone_id.py | https://github.com/gtaylor/python-route53/blob/b9fc7e258a79551c9ed61e4a71668b7f06f9e774/route53/xml_parsers/list_resource_record_sets_by_zone_id.py#L119-L140 | def list_resource_record_sets_by_zone_id_parser(e_root, connection, zone_id):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.list_resource_record_sets_by_zone_id`
method.
:param lxml.etree._Element e_root: The root node of the etree parsed
response from ... | [
"def",
"list_resource_record_sets_by_zone_id_parser",
"(",
"e_root",
",",
"connection",
",",
"zone_id",
")",
":",
"# The rest of the list pagination tags are handled higher up in the stack.",
"# We'll just worry about the ResourceRecordSets tag, which has",
"# ResourceRecordSet tags nested b... | Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.list_resource_record_sets_by_zone_id`
method.
:param lxml.etree._Element e_root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: The connection instance used to
... | [
"Parses",
"the",
"API",
"responses",
"for",
"the",
":",
"py",
":",
"meth",
":",
"route53",
".",
"connection",
".",
"Route53Connection",
".",
"list_resource_record_sets_by_zone_id",
"method",
"."
] | python | test |
cloudendpoints/endpoints-management-python | endpoints_management/control/money.py | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/money.py#L133-L156 | def _sign_of(money):
"""Determines the amount sign of a money instance
Args:
money (:class:`endpoints_management.gen.servicecontrol_v1_messages.Money`): the
instance to test
Return:
int: 1, 0 or -1
"""
units = money.units
nanos = money.nanos
if units:
if units ... | [
"def",
"_sign_of",
"(",
"money",
")",
":",
"units",
"=",
"money",
".",
"units",
"nanos",
"=",
"money",
".",
"nanos",
"if",
"units",
":",
"if",
"units",
">",
"0",
":",
"return",
"1",
"elif",
"units",
"<",
"0",
":",
"return",
"-",
"1",
"if",
"nanos... | Determines the amount sign of a money instance
Args:
money (:class:`endpoints_management.gen.servicecontrol_v1_messages.Money`): the
instance to test
Return:
int: 1, 0 or -1 | [
"Determines",
"the",
"amount",
"sign",
"of",
"a",
"money",
"instance"
] | python | train |
blockstack/blockstack-core | blockstack/blockstackd.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L155-L160 | def get_logfile_path(working_dir):
"""
Get the logfile path for our service endpoint.
"""
logfile_filename = virtualchain_hooks.get_virtual_chain_name() + ".log"
return os.path.join( working_dir, logfile_filename ) | [
"def",
"get_logfile_path",
"(",
"working_dir",
")",
":",
"logfile_filename",
"=",
"virtualchain_hooks",
".",
"get_virtual_chain_name",
"(",
")",
"+",
"\".log\"",
"return",
"os",
".",
"path",
".",
"join",
"(",
"working_dir",
",",
"logfile_filename",
")"
] | Get the logfile path for our service endpoint. | [
"Get",
"the",
"logfile",
"path",
"for",
"our",
"service",
"endpoint",
"."
] | python | train |
geopy/geopy | geopy/geocoders/mapbox.py | https://github.com/geopy/geopy/blob/02c838d965e76497f3c3d61f53808c86b5c58224/geopy/geocoders/mapbox.py#L87-L159 | def geocode(
self,
query,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
proximity=None,
country=None,
bbox=None,
):
"""
Return a location point by address
:param str query: The address or query you wish to geo... | [
"def",
"geocode",
"(",
"self",
",",
"query",
",",
"exactly_one",
"=",
"True",
",",
"timeout",
"=",
"DEFAULT_SENTINEL",
",",
"proximity",
"=",
"None",
",",
"country",
"=",
"None",
",",
"bbox",
"=",
"None",
",",
")",
":",
"params",
"=",
"{",
"}",
"para... | Return a location point by address
:param str query: The address or query you wish to geocode.
:param bool exactly_one: Return one result or a list of results, if
available.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raisi... | [
"Return",
"a",
"location",
"point",
"by",
"address"
] | python | train |
tonioo/sievelib | sievelib/commands.py | https://github.com/tonioo/sievelib/blob/88822d1f1daf30ef3dd9ac74911301b0773ef3c8/sievelib/commands.py#L361-L387 | def __is_valid_value_for_arg(self, arg, value, check_extension=True):
"""Check if value is allowed for arg
Some commands only allow a limited set of values. The method
always returns True for methods that do not provide such a
set.
:param arg: the argument's name
:param... | [
"def",
"__is_valid_value_for_arg",
"(",
"self",
",",
"arg",
",",
"value",
",",
"check_extension",
"=",
"True",
")",
":",
"if",
"\"values\"",
"not",
"in",
"arg",
"and",
"\"extension_values\"",
"not",
"in",
"arg",
":",
"return",
"True",
"if",
"\"values\"",
"in... | Check if value is allowed for arg
Some commands only allow a limited set of values. The method
always returns True for methods that do not provide such a
set.
:param arg: the argument's name
:param value: the value to check
:param check_extension: check if value require... | [
"Check",
"if",
"value",
"is",
"allowed",
"for",
"arg"
] | python | train |
dsoprea/PySecure | pysecure/sftp_mirror.py | https://github.com/dsoprea/PySecure/blob/ff7e01a0a77e79564cb00b6e38b4e6f9f88674f0/pysecure/sftp_mirror.py#L253-L282 | def mirror_to_local_no_recursion(self, path_from, path_to,
log_files=False):
"""Mirror a directory without descending into directories. Return a
list of subdirectory names (do not include full path). We will unlink
existing files without determining if the... | [
"def",
"mirror_to_local_no_recursion",
"(",
"self",
",",
"path_from",
",",
"path_to",
",",
"log_files",
"=",
"False",
")",
":",
"self",
".",
"__log",
".",
"debug",
"(",
"\"Ensuring local target directory exists: %s\"",
"%",
"(",
"path_to",
")",
")",
"try",
":",
... | Mirror a directory without descending into directories. Return a
list of subdirectory names (do not include full path). We will unlink
existing files without determining if they're just going to be
rewritten and then truncating them because it is our belief, based on
what little we c... | [
"Mirror",
"a",
"directory",
"without",
"descending",
"into",
"directories",
".",
"Return",
"a",
"list",
"of",
"subdirectory",
"names",
"(",
"do",
"not",
"include",
"full",
"path",
")",
".",
"We",
"will",
"unlink",
"existing",
"files",
"without",
"determining",... | python | train |
LonamiWebs/Telethon | telethon/tl/custom/message.py | https://github.com/LonamiWebs/Telethon/blob/1ead9757d366b58c1e0567cddb0196e20f1a445f/telethon/tl/custom/message.py#L327-L343 | def buttons(self):
"""
Returns a matrix (list of lists) containing all buttons of the message
as `MessageButton <telethon.tl.custom.messagebutton.MessageButton>`
instances.
"""
if self._buttons is None and self.reply_markup:
if not self.input_chat:
... | [
"def",
"buttons",
"(",
"self",
")",
":",
"if",
"self",
".",
"_buttons",
"is",
"None",
"and",
"self",
".",
"reply_markup",
":",
"if",
"not",
"self",
".",
"input_chat",
":",
"return",
"try",
":",
"bot",
"=",
"self",
".",
"_needed_markup_bot",
"(",
")",
... | Returns a matrix (list of lists) containing all buttons of the message
as `MessageButton <telethon.tl.custom.messagebutton.MessageButton>`
instances. | [
"Returns",
"a",
"matrix",
"(",
"list",
"of",
"lists",
")",
"containing",
"all",
"buttons",
"of",
"the",
"message",
"as",
"MessageButton",
"<telethon",
".",
"tl",
".",
"custom",
".",
"messagebutton",
".",
"MessageButton",
">",
"instances",
"."
] | python | train |
tjcsl/ion | intranet/apps/preferences/fields.py | https://github.com/tjcsl/ion/blob/5d722b0725d572039bb0929fd5715a4070c82c72/intranet/apps/preferences/fields.py#L39-L44 | def to_python(self, value):
"""Returns a Unicode object."""
if value in self.empty_values:
return ""
value = force_text(value).strip()
return value | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"self",
".",
"empty_values",
":",
"return",
"\"\"",
"value",
"=",
"force_text",
"(",
"value",
")",
".",
"strip",
"(",
")",
"return",
"value"
] | Returns a Unicode object. | [
"Returns",
"a",
"Unicode",
"object",
"."
] | python | train |
numenta/nupic | src/nupic/database/connection.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/database/connection.py#L541-L558 | def acquireConnection(self):
""" Get a connection from the pool.
Parameters:
----------------------------------------------------------------
retval: A ConnectionWrapper instance. NOTE: Caller
is responsible for calling the ConnectionWrapper
instance's rel... | [
"def",
"acquireConnection",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"Acquiring connection\"",
")",
"dbConn",
"=",
"self",
".",
"_pool",
".",
"connection",
"(",
"shareable",
"=",
"False",
")",
"connWrap",
"=",
"ConnectionWrapper",
... | Get a connection from the pool.
Parameters:
----------------------------------------------------------------
retval: A ConnectionWrapper instance. NOTE: Caller
is responsible for calling the ConnectionWrapper
instance's release() method or use it in a context ... | [
"Get",
"a",
"connection",
"from",
"the",
"pool",
"."
] | python | valid |
openeventdata/mordecai | mordecai/geoparse.py | https://github.com/openeventdata/mordecai/blob/bd82b8bcc27621345c57cbe9ec7f8c8552620ffc/mordecai/geoparse.py#L595-L643 | def make_country_matrix(self, loc):
"""
Create features for all possible country labels, return as matrix for keras.
Parameters
----------
loc: dict
one entry from the list of locations and features that come out of make_country_features
Returns
----... | [
"def",
"make_country_matrix",
"(",
"self",
",",
"loc",
")",
":",
"top",
"=",
"loc",
"[",
"'features'",
"]",
"[",
"'ct_mention'",
"]",
"top_count",
"=",
"loc",
"[",
"'features'",
"]",
"[",
"'ctm_count1'",
"]",
"two",
"=",
"loc",
"[",
"'features'",
"]",
... | Create features for all possible country labels, return as matrix for keras.
Parameters
----------
loc: dict
one entry from the list of locations and features that come out of make_country_features
Returns
--------
keras_inputs: dict with two keys, "label" a... | [
"Create",
"features",
"for",
"all",
"possible",
"country",
"labels",
"return",
"as",
"matrix",
"for",
"keras",
"."
] | python | train |
marcharper/python-ternary | ternary/heatmapping.py | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/heatmapping.py#L17-L34 | def blend_value(data, i, j, k, keys=None):
"""Computes the average value of the three vertices of a triangle in the
simplex triangulation, where two of the vertices are on the lower
horizontal."""
key_size = len(list(data.keys())[0])
if not keys:
keys = triangle_coordinates(i, j, k)
# R... | [
"def",
"blend_value",
"(",
"data",
",",
"i",
",",
"j",
",",
"k",
",",
"keys",
"=",
"None",
")",
":",
"key_size",
"=",
"len",
"(",
"list",
"(",
"data",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
")",
"if",
"not",
"keys",
":",
"keys",
"=",
"t... | Computes the average value of the three vertices of a triangle in the
simplex triangulation, where two of the vertices are on the lower
horizontal. | [
"Computes",
"the",
"average",
"value",
"of",
"the",
"three",
"vertices",
"of",
"a",
"triangle",
"in",
"the",
"simplex",
"triangulation",
"where",
"two",
"of",
"the",
"vertices",
"are",
"on",
"the",
"lower",
"horizontal",
"."
] | python | train |
ael-code/pyFsdb | fsdb/config.py | https://github.com/ael-code/pyFsdb/blob/de33a0d41373307cb32cdd7ba1991b85ff495ee3/fsdb/config.py#L65-L78 | def normalize_conf(conf):
'''Check, convert and adjust user passed config
Given a user configuration it returns a verified configuration with
all parameters converted to the types that are needed at runtime.
'''
conf = conf.copy()
# check for type error
check_config(conf)
# conver... | [
"def",
"normalize_conf",
"(",
"conf",
")",
":",
"conf",
"=",
"conf",
".",
"copy",
"(",
")",
"# check for type error",
"check_config",
"(",
"conf",
")",
"# convert some fileds into python suitable format",
"from_json_format",
"(",
"conf",
")",
"if",
"'dmode'",
"not",... | Check, convert and adjust user passed config
Given a user configuration it returns a verified configuration with
all parameters converted to the types that are needed at runtime. | [
"Check",
"convert",
"and",
"adjust",
"user",
"passed",
"config"
] | python | train |
bolt-project/bolt | bolt/spark/shapes.py | https://github.com/bolt-project/bolt/blob/9cd7104aa085498da3097b72696184b9d3651c51/bolt/spark/shapes.py#L40-L64 | def reshape(self, *shape):
"""
Reshape just the keys of a BoltArraySpark, returning a
new BoltArraySpark.
Parameters
----------
shape : tuple
New proposed axes.
"""
new = argpack(shape)
old = self.shape
isreshapeable(new, old... | [
"def",
"reshape",
"(",
"self",
",",
"*",
"shape",
")",
":",
"new",
"=",
"argpack",
"(",
"shape",
")",
"old",
"=",
"self",
".",
"shape",
"isreshapeable",
"(",
"new",
",",
"old",
")",
"if",
"new",
"==",
"old",
":",
"return",
"self",
".",
"_barray",
... | Reshape just the keys of a BoltArraySpark, returning a
new BoltArraySpark.
Parameters
----------
shape : tuple
New proposed axes. | [
"Reshape",
"just",
"the",
"keys",
"of",
"a",
"BoltArraySpark",
"returning",
"a",
"new",
"BoltArraySpark",
"."
] | python | test |
keans/lmnotify | lmnotify/session.py | https://github.com/keans/lmnotify/blob/b0a5282a582e5090852dc20fea8a135ca258d0d3/lmnotify/session.py#L121-L129 | def get_token(self):
"""
get current oauth token
"""
self.token = self._session.fetch_token(
token_url=CLOUD_URLS["get_token"][1],
client_id=self._client_id,
client_secret=self._client_secret
) | [
"def",
"get_token",
"(",
"self",
")",
":",
"self",
".",
"token",
"=",
"self",
".",
"_session",
".",
"fetch_token",
"(",
"token_url",
"=",
"CLOUD_URLS",
"[",
"\"get_token\"",
"]",
"[",
"1",
"]",
",",
"client_id",
"=",
"self",
".",
"_client_id",
",",
"cl... | get current oauth token | [
"get",
"current",
"oauth",
"token"
] | python | train |
tensorflow/cleverhans | cleverhans/utils_pytorch.py | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_pytorch.py#L132-L156 | def get_or_guess_labels(model, x, **kwargs):
"""
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then ... | [
"def",
"get_or_guess_labels",
"(",
"model",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'y'",
"in",
"kwargs",
"and",
"'y_target'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"Can not set both 'y' and 'y_target'.\"",
")",
"if",
"'y'",
"in",
"k... | Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then assume it's a
targeted attack and use that as the l... | [
"Get",
"the",
"label",
"to",
"use",
"in",
"generating",
"an",
"adversarial",
"example",
"for",
"x",
".",
"The",
"kwargs",
"are",
"fed",
"directly",
"from",
"the",
"kwargs",
"of",
"the",
"attack",
".",
"If",
"y",
"is",
"in",
"kwargs",
"then",
"assume",
... | python | train |
senaite/senaite.core | bika/lims/upgrade/v01_03_000.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/upgrade/v01_03_000.py#L1406-L1437 | def hide_samples(portal):
"""Removes samples views from everywhere, related indexes, etc.
"""
logger.info("Removing Samples from navbar ...")
if "samples" in portal:
portal.manage_delObjects(["samples"])
def remove_samples_action(content_type):
type_info = content_type.getTypeInfo()... | [
"def",
"hide_samples",
"(",
"portal",
")",
":",
"logger",
".",
"info",
"(",
"\"Removing Samples from navbar ...\"",
")",
"if",
"\"samples\"",
"in",
"portal",
":",
"portal",
".",
"manage_delObjects",
"(",
"[",
"\"samples\"",
"]",
")",
"def",
"remove_samples_action"... | Removes samples views from everywhere, related indexes, etc. | [
"Removes",
"samples",
"views",
"from",
"everywhere",
"related",
"indexes",
"etc",
"."
] | python | train |
brocade/pynos | pynos/versions/base/yang/ietf_netconf.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/yang/ietf_netconf.py#L313-L323 | def copy_config_input_with_inactive(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
copy_config = ET.Element("copy_config")
config = copy_config
input = ET.SubElement(copy_config, "input")
with_inactive = ET.SubElement(input, "with-inacti... | [
"def",
"copy_config_input_with_inactive",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"copy_config",
"=",
"ET",
".",
"Element",
"(",
"\"copy_config\"",
")",
"config",
"=",
"copy_config",
"input... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
pandas-profiling/pandas-profiling | pandas_profiling/describe.py | https://github.com/pandas-profiling/pandas-profiling/blob/003d236daee8b7aca39c62708b18d59bced0bc03/pandas_profiling/describe.py#L133-L146 | def describe_constant_1d(series):
"""Compute summary statistics of a constant (`S_TYPE_CONST`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys... | [
"def",
"describe_constant_1d",
"(",
"series",
")",
":",
"return",
"pd",
".",
"Series",
"(",
"[",
"base",
".",
"S_TYPE_CONST",
"]",
",",
"index",
"=",
"[",
"'type'",
"]",
",",
"name",
"=",
"series",
".",
"name",
")"
] | Compute summary statistics of a constant (`S_TYPE_CONST`) variable (a Series).
Parameters
----------
series : Series
The variable to describe.
Returns
-------
Series
The description of the variable as a Series with index being stats keys. | [
"Compute",
"summary",
"statistics",
"of",
"a",
"constant",
"(",
"S_TYPE_CONST",
")",
"variable",
"(",
"a",
"Series",
")",
"."
] | python | train |
openid/JWTConnect-Python-OidcMsg | src/oidcmsg/time_util.py | https://github.com/openid/JWTConnect-Python-OidcMsg/blob/58ade5eb67131abfb99f38b6a92d43b697c9f2fa/src/oidcmsg/time_util.py#L291-L301 | def before(point):
""" True if point datetime specification is before now """
if not point:
return True
if isinstance(point, str):
point = str_to_time(point)
elif isinstance(point, int):
point = time.gmtime(point)
return time.gmtime() < point | [
"def",
"before",
"(",
"point",
")",
":",
"if",
"not",
"point",
":",
"return",
"True",
"if",
"isinstance",
"(",
"point",
",",
"str",
")",
":",
"point",
"=",
"str_to_time",
"(",
"point",
")",
"elif",
"isinstance",
"(",
"point",
",",
"int",
")",
":",
... | True if point datetime specification is before now | [
"True",
"if",
"point",
"datetime",
"specification",
"is",
"before",
"now"
] | python | train |
radjkarl/imgProcessor | imgProcessor/camera/flatField/vignettingFromSpotAverage.py | https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/camera/flatField/vignettingFromSpotAverage.py#L15-L85 | def vignettingFromSpotAverage(
images, bgImages=None, averageSpot=True, thresh=None):
'''
[images] --> list of images containing
small bright spots generated by the same
device images at different positions within image plane
depending on the calibrat... | [
"def",
"vignettingFromSpotAverage",
"(",
"images",
",",
"bgImages",
"=",
"None",
",",
"averageSpot",
"=",
"True",
",",
"thresh",
"=",
"None",
")",
":",
"fitimg",
",",
"mask",
"=",
"None",
",",
"None",
"mx",
"=",
"0",
"for",
"c",
",",
"img",
"in",
"en... | [images] --> list of images containing
small bright spots generated by the same
device images at different positions within image plane
depending on the calibrated waveband the device can be
a LCD display or PV 1-cell mini module
This method is refe... | [
"[",
"images",
"]",
"--",
">",
"list",
"of",
"images",
"containing",
"small",
"bright",
"spots",
"generated",
"by",
"the",
"same",
"device",
"images",
"at",
"different",
"positions",
"within",
"image",
"plane",
"depending",
"on",
"the",
"calibrated",
"waveband... | python | train |
pantsbuild/pants | contrib/cpp/src/python/pants/contrib/cpp/toolchain/cpp_toolchain.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/cpp/src/python/pants/contrib/cpp/toolchain/cpp_toolchain.py#L32-L67 | def register_tool(self, tool, name=None):
"""Check tool and see if it is installed in the local cpp toolchain.
All cpp tasks should request their tools using this method. Tools are validated
and cached for quick lookup.
:param string tool: Name or path of program tool, eg 'g++'
:param string name:... | [
"def",
"register_tool",
"(",
"self",
",",
"tool",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"or",
"os",
".",
"path",
".",
"basename",
"(",
"tool",
")",
"if",
"name",
"in",
"self",
".",
"_validated_tools",
":",
"return",
"self",
".",
... | Check tool and see if it is installed in the local cpp toolchain.
All cpp tasks should request their tools using this method. Tools are validated
and cached for quick lookup.
:param string tool: Name or path of program tool, eg 'g++'
:param string name: Logical name of tool, eg 'compiler'. If not supp... | [
"Check",
"tool",
"and",
"see",
"if",
"it",
"is",
"installed",
"in",
"the",
"local",
"cpp",
"toolchain",
"."
] | python | train |
hotdoc/hotdoc | hotdoc/extensions/c/clang/cindex.py | https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L1633-L1638 | def semantic_parent(self):
"""Return the semantic parent for this cursor."""
if not hasattr(self, '_semantic_parent'):
self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self)
return self._semantic_parent | [
"def",
"semantic_parent",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_semantic_parent'",
")",
":",
"self",
".",
"_semantic_parent",
"=",
"conf",
".",
"lib",
".",
"clang_getCursorSemanticParent",
"(",
"self",
")",
"return",
"self",
"."... | Return the semantic parent for this cursor. | [
"Return",
"the",
"semantic",
"parent",
"for",
"this",
"cursor",
"."
] | python | train |
Dallinger/Dallinger | dallinger/command_line.py | https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/command_line.py#L71-L78 | def error(msg, delay=0.5, chevrons=True, verbose=True):
"""Log a message to stdout."""
if verbose:
if chevrons:
click.secho("\n❯❯ " + msg, err=True, fg="red")
else:
click.secho(msg, err=True, fg="red")
time.sleep(delay) | [
"def",
"error",
"(",
"msg",
",",
"delay",
"=",
"0.5",
",",
"chevrons",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"verbose",
":",
"if",
"chevrons",
":",
"click",
".",
"secho",
"(",
"\"\\n❯❯ \" + m",
"g",
" er",
"r",
"Tru",
"e",
", fg... | Log a message to stdout. | [
"Log",
"a",
"message",
"to",
"stdout",
"."
] | python | train |
nwilming/ocupy | ocupy/simulator.py | https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/simulator.py#L305-L322 | def drawFrom(self, cumsum, r):
"""
Draws a value from a cumulative sum.
Parameters:
cumsum : array
Cumulative sum from which shall be drawn.
Returns:
int : Index of the cumulative sum element drawn.
"""
a = cumsum.rsplit(... | [
"def",
"drawFrom",
"(",
"self",
",",
"cumsum",
",",
"r",
")",
":",
"a",
"=",
"cumsum",
".",
"rsplit",
"(",
")",
"if",
"len",
"(",
"a",
")",
">",
"1",
":",
"b",
"=",
"eval",
"(",
"a",
"[",
"0",
"]",
")",
"[",
"int",
"(",
"a",
"[",
"1",
"... | Draws a value from a cumulative sum.
Parameters:
cumsum : array
Cumulative sum from which shall be drawn.
Returns:
int : Index of the cumulative sum element drawn. | [
"Draws",
"a",
"value",
"from",
"a",
"cumulative",
"sum",
".",
"Parameters",
":",
"cumsum",
":",
"array",
"Cumulative",
"sum",
"from",
"which",
"shall",
"be",
"drawn",
"."
] | python | train |
GPflow/GPflow | gpflow/training/natgrad_optimizer.py | https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/training/natgrad_optimizer.py#L174-L238 | def _build_natgrad_step_op(self, model, q_mu_param, q_sqrt_param, xi_transform):
"""
Implements equation 10 from
@inproceedings{salimbeni18,
title={Natural Gradients in Practice: Non-Conjugate Variational Inference in Gaussian Process Models},
author={Salimbeni, Hugh an... | [
"def",
"_build_natgrad_step_op",
"(",
"self",
",",
"model",
",",
"q_mu_param",
",",
"q_sqrt_param",
",",
"xi_transform",
")",
":",
"objective",
"=",
"model",
".",
"objective",
"q_mu",
",",
"q_sqrt",
"=",
"q_mu_param",
".",
"constrained_tensor",
",",
"q_sqrt_para... | Implements equation 10 from
@inproceedings{salimbeni18,
title={Natural Gradients in Practice: Non-Conjugate Variational Inference in Gaussian Process Models},
author={Salimbeni, Hugh and Eleftheriadis, Stefanos and Hensman, James},
booktitle={AISTATS},
year={201... | [
"Implements",
"equation",
"10",
"from"
] | python | train |
edx/edx-val | edxval/api.py | https://github.com/edx/edx-val/blob/30df48061e77641edb5272895b7c7f7f25eb7aa7/edxval/api.py#L477-L506 | def update_video_image(edx_video_id, course_id, image_data, file_name):
"""
Update video image for an existing video.
NOTE: If `image_data` is None then `file_name` value will be used as it is, otherwise
a new file name is constructed based on uuid and extension from `file_name` value.
`image_data`... | [
"def",
"update_video_image",
"(",
"edx_video_id",
",",
"course_id",
",",
"image_data",
",",
"file_name",
")",
":",
"try",
":",
"course_video",
"=",
"CourseVideo",
".",
"objects",
".",
"select_related",
"(",
"'video'",
")",
".",
"get",
"(",
"course_id",
"=",
... | Update video image for an existing video.
NOTE: If `image_data` is None then `file_name` value will be used as it is, otherwise
a new file name is constructed based on uuid and extension from `file_name` value.
`image_data` will be None in case of course re-run and export.
Arguments:
image_dat... | [
"Update",
"video",
"image",
"for",
"an",
"existing",
"video",
"."
] | python | train |
monero-ecosystem/monero-python | monero/wallet.py | https://github.com/monero-ecosystem/monero-python/blob/64149f6323af57a3924f45ed87997d64387c5ee0/monero/wallet.py#L65-L74 | def spend_key(self):
"""
Returns private spend key. None if wallet is view-only.
:rtype: str or None
"""
key = self._backend.spend_key()
if key == numbers.EMPTY_KEY:
return None
return key | [
"def",
"spend_key",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"_backend",
".",
"spend_key",
"(",
")",
"if",
"key",
"==",
"numbers",
".",
"EMPTY_KEY",
":",
"return",
"None",
"return",
"key"
] | Returns private spend key. None if wallet is view-only.
:rtype: str or None | [
"Returns",
"private",
"spend",
"key",
".",
"None",
"if",
"wallet",
"is",
"view",
"-",
"only",
"."
] | python | valid |
bcbio/bcbio-nextgen | bcbio/pipeline/run_info.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/pipeline/run_info.py#L369-L400 | def _clean_background(data):
"""Clean up background specification, remaining back compatible.
"""
allowed_keys = set(["variant", "cnv_reference"])
val = tz.get_in(["algorithm", "background"], data)
errors = []
if val:
out = {}
# old style specification, single string for variant
... | [
"def",
"_clean_background",
"(",
"data",
")",
":",
"allowed_keys",
"=",
"set",
"(",
"[",
"\"variant\"",
",",
"\"cnv_reference\"",
"]",
")",
"val",
"=",
"tz",
".",
"get_in",
"(",
"[",
"\"algorithm\"",
",",
"\"background\"",
"]",
",",
"data",
")",
"errors",
... | Clean up background specification, remaining back compatible. | [
"Clean",
"up",
"background",
"specification",
"remaining",
"back",
"compatible",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/assessment/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/objects.py#L2501-L2513 | def get_rubric_id(self):
"""Gets the ``Id`` of the rubric.
return: (osid.id.Id) - an assessment taken ``Id``
raise: IllegalState - ``has_rubric()`` is ``false``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resourc... | [
"def",
"get_rubric_id",
"(",
"self",
")",
":",
"# Implemented from template for osid.resource.Resource.get_avatar_id_template",
"if",
"not",
"bool",
"(",
"self",
".",
"_my_map",
"[",
"'rubricId'",
"]",
")",
":",
"raise",
"errors",
".",
"IllegalState",
"(",
"'this Asse... | Gets the ``Id`` of the rubric.
return: (osid.id.Id) - an assessment taken ``Id``
raise: IllegalState - ``has_rubric()`` is ``false``
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"the",
"Id",
"of",
"the",
"rubric",
"."
] | python | train |
stuaxo/vext | vext/env/__init__.py | https://github.com/stuaxo/vext/blob/fa98a21ecfbbc1c3d1b84085d69ec42defdd2f69/vext/env/__init__.py#L16-L46 | def run_in_syspy(f):
"""
Decorator to run a function in the system python
:param f:
:return:
"""
fname = f.__name__
code_lines = inspect.getsource(f).splitlines()
code = dedent("\n".join(code_lines[1:])) # strip this decorator
# add call to the function and print it's result
... | [
"def",
"run_in_syspy",
"(",
"f",
")",
":",
"fname",
"=",
"f",
".",
"__name__",
"code_lines",
"=",
"inspect",
".",
"getsource",
"(",
"f",
")",
".",
"splitlines",
"(",
")",
"code",
"=",
"dedent",
"(",
"\"\\n\"",
".",
"join",
"(",
"code_lines",
"[",
"1"... | Decorator to run a function in the system python
:param f:
:return: | [
"Decorator",
"to",
"run",
"a",
"function",
"in",
"the",
"system",
"python"
] | python | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/encoder.py#L541-L615 | def _FloatingPointEncoder(wire_type, format):
"""Return a constructor for an encoder for float fields.
This is like StructPackEncoder, but catches errors that may be due to
passing non-finite floating-point values to struct.pack, and makes a
second attempt to encode those values.
Args:
wire_type: The... | [
"def",
"_FloatingPointEncoder",
"(",
"wire_type",
",",
"format",
")",
":",
"value_size",
"=",
"struct",
".",
"calcsize",
"(",
"format",
")",
"if",
"value_size",
"==",
"4",
":",
"def",
"EncodeNonFiniteOrRaise",
"(",
"write",
",",
"value",
")",
":",
"# Remembe... | Return a constructor for an encoder for float fields.
This is like StructPackEncoder, but catches errors that may be due to
passing non-finite floating-point values to struct.pack, and makes a
second attempt to encode those values.
Args:
wire_type: The field's wire type, for encoding tags.
format... | [
"Return",
"a",
"constructor",
"for",
"an",
"encoder",
"for",
"float",
"fields",
"."
] | python | train |
LeastAuthority/txkube | src/txkube/_network.py | https://github.com/LeastAuthority/txkube/blob/a7e555d00535ff787d4b1204c264780da40cf736/src/txkube/_network.py#L424-L456 | def collection_location(obj):
"""
Get the URL for the collection of objects like ``obj``.
:param obj: Either a type representing a Kubernetes object kind or an
instance of such a type.
:return tuple[unicode]: Some path segments to stick on to a base URL to
construct the location of the... | [
"def",
"collection_location",
"(",
"obj",
")",
":",
"# TODO kind is not part of IObjectLoader and we should really be loading",
"# apiVersion off of this object too.",
"kind",
"=",
"obj",
".",
"kind",
"apiVersion",
"=",
"obj",
".",
"apiVersion",
"prefix",
"=",
"version_to_seg... | Get the URL for the collection of objects like ``obj``.
:param obj: Either a type representing a Kubernetes object kind or an
instance of such a type.
:return tuple[unicode]: Some path segments to stick on to a base URL to
construct the location of the collection of objects like the one
... | [
"Get",
"the",
"URL",
"for",
"the",
"collection",
"of",
"objects",
"like",
"obj",
"."
] | python | train |
bslatkin/dpxdt | dpxdt/server/api.py | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L109-L154 | def create_release():
"""Creates a new release candidate for a build."""
build = g.build
release_name = request.form.get('release_name')
utils.jsonify_assert(release_name, 'release_name required')
url = request.form.get('url')
utils.jsonify_assert(release_name, 'url required')
release = mod... | [
"def",
"create_release",
"(",
")",
":",
"build",
"=",
"g",
".",
"build",
"release_name",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'release_name'",
")",
"utils",
".",
"jsonify_assert",
"(",
"release_name",
",",
"'release_name required'",
")",
"url",
"="... | Creates a new release candidate for a build. | [
"Creates",
"a",
"new",
"release",
"candidate",
"for",
"a",
"build",
"."
] | python | train |
bids-standard/pybids | bids/analysis/hrf.py | https://github.com/bids-standard/pybids/blob/30d924ce770622bda0e390d613a8da42a2a20c32/bids/analysis/hrf.py#L199-L230 | def glover_dispersion_derivative(tr, oversampling=50, time_length=32.,
onset=0.):
"""Implementation of the Glover dispersion derivative hrf model
Parameters
----------
tr: float
scan repeat time, in seconds
oversampling: int, optional
temporal overs... | [
"def",
"glover_dispersion_derivative",
"(",
"tr",
",",
"oversampling",
"=",
"50",
",",
"time_length",
"=",
"32.",
",",
"onset",
"=",
"0.",
")",
":",
"dd",
"=",
".01",
"dhrf",
"=",
"1.",
"/",
"dd",
"*",
"(",
"-",
"_gamma_difference_hrf",
"(",
"tr",
",",... | Implementation of the Glover dispersion derivative hrf model
Parameters
----------
tr: float
scan repeat time, in seconds
oversampling: int, optional
temporal oversampling factor in seconds
time_length: float, optional
hrf kernel length, in seconds
onset : float, opti... | [
"Implementation",
"of",
"the",
"Glover",
"dispersion",
"derivative",
"hrf",
"model"
] | python | train |
scarface-4711/denonavr | denonavr/ssdp.py | https://github.com/scarface-4711/denonavr/blob/59a136e27b43cb1d1e140cf67705087b3aa377cd/denonavr/ssdp.py#L85-L135 | def send_ssdp_broadcast():
"""
Send SSDP broadcast message to discover UPnP devices.
Returns a list of dictionaries with "address" (IP, PORT) and "URL"
of SCPD XML for all discovered devices.
"""
# Send up to three different broadcast messages
for i, ssdp_query in enumerate(SSDP_QUERIES):
... | [
"def",
"send_ssdp_broadcast",
"(",
")",
":",
"# Send up to three different broadcast messages",
"for",
"i",
",",
"ssdp_query",
"in",
"enumerate",
"(",
"SSDP_QUERIES",
")",
":",
"# Prepare SSDP broadcast message",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".... | Send SSDP broadcast message to discover UPnP devices.
Returns a list of dictionaries with "address" (IP, PORT) and "URL"
of SCPD XML for all discovered devices. | [
"Send",
"SSDP",
"broadcast",
"message",
"to",
"discover",
"UPnP",
"devices",
"."
] | python | train |
RudolfCardinal/pythonlib | cardinal_pythonlib/openxml/find_bad_openxml.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/find_bad_openxml.py#L80-L139 | def is_openxml_good(filename: str) -> bool:
"""
Determines whether an OpenXML file appears to be good (not corrupted).
"""
try:
log.debug("Trying: {}", filename)
with ZipFile(filename, 'r') as zip_ref:
namelist = zip_ref.namelist() # type: List[str]
# log.critica... | [
"def",
"is_openxml_good",
"(",
"filename",
":",
"str",
")",
"->",
"bool",
":",
"try",
":",
"log",
".",
"debug",
"(",
"\"Trying: {}\"",
",",
"filename",
")",
"with",
"ZipFile",
"(",
"filename",
",",
"'r'",
")",
"as",
"zip_ref",
":",
"namelist",
"=",
"zi... | Determines whether an OpenXML file appears to be good (not corrupted). | [
"Determines",
"whether",
"an",
"OpenXML",
"file",
"appears",
"to",
"be",
"good",
"(",
"not",
"corrupted",
")",
"."
] | python | train |
codelv/enaml-native | src/enamlnative/android/android_notification.py | https://github.com/codelv/enaml-native/blob/c33986e9eda468c508806e0a3e73c771401e5718/src/enamlnative/android/android_notification.py#L164-L184 | def cancel_notification(cls, notification_or_id, tag=None):
""" Cancel the notification.
Parameters
----------
notification_or_id: Notification.Builder or int
The notification or id of a notification to clear
tag: String
The tag of the notificati... | [
"def",
"cancel_notification",
"(",
"cls",
",",
"notification_or_id",
",",
"tag",
"=",
"None",
")",
":",
"def",
"on_ready",
"(",
"mgr",
")",
":",
"if",
"isinstance",
"(",
"notification_or_id",
",",
"JavaBridgeObject",
")",
":",
"nid",
"=",
"notification_or_id",... | Cancel the notification.
Parameters
----------
notification_or_id: Notification.Builder or int
The notification or id of a notification to clear
tag: String
The tag of the notification to clear | [
"Cancel",
"the",
"notification",
".",
"Parameters",
"----------",
"notification_or_id",
":",
"Notification",
".",
"Builder",
"or",
"int",
"The",
"notification",
"or",
"id",
"of",
"a",
"notification",
"to",
"clear",
"tag",
":",
"String",
"The",
"tag",
"of",
"th... | python | train |
log2timeline/plaso | plaso/parsers/esedb_plugins/interface.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/esedb_plugins/interface.py#L99-L123 | def _ConvertValueBinaryDataToUBInt64(self, value):
"""Converts a binary data value into an integer.
Args:
value (bytes): binary data value containing an unsigned 64-bit big-endian
integer.
Returns:
int: integer representation of binary data value or None if value is
not set... | [
"def",
"_ConvertValueBinaryDataToUBInt64",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"integer_map",
"=",
"self",
".",
"_GetDataTypeMap",
"(",
"'uint64be'",
")",
"try",
":",
"return",
"self",
".",
"_ReadStructureFromByteStr... | Converts a binary data value into an integer.
Args:
value (bytes): binary data value containing an unsigned 64-bit big-endian
integer.
Returns:
int: integer representation of binary data value or None if value is
not set.
Raises:
ParseError: if the integer value cann... | [
"Converts",
"a",
"binary",
"data",
"value",
"into",
"an",
"integer",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/core/trajectory.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/trajectory.py#L195-L216 | def from_structures(cls, structures, constant_lattice=True, **kwargs):
"""
Convenience constructor to obtain trajectory from a list of structures.
Note: Assumes no atoms removed during simulation
Args:
structures (list): list of pymatgen Structure objects.
consta... | [
"def",
"from_structures",
"(",
"cls",
",",
"structures",
",",
"constant_lattice",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"frac_coords",
"=",
"[",
"structure",
".",
"frac_coords",
"for",
"structure",
"in",
"structures",
"]",
"if",
"constant_lattice",
... | Convenience constructor to obtain trajectory from a list of structures.
Note: Assumes no atoms removed during simulation
Args:
structures (list): list of pymatgen Structure objects.
constant_lattice (bool): Whether the lattice changes during the simulation, such as in an NPT MD
... | [
"Convenience",
"constructor",
"to",
"obtain",
"trajectory",
"from",
"a",
"list",
"of",
"structures",
".",
"Note",
":",
"Assumes",
"no",
"atoms",
"removed",
"during",
"simulation"
] | python | train |
joke2k/faker | faker/providers/address/en_CA/__init__.py | https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/address/en_CA/__init__.py#L319-L328 | def postcode(self):
"""
Replaces all question mark ('?') occurrences with a random letter
from postal_code_formats then passes result to
numerify to insert numbers
"""
temp = re.sub(r'\?',
lambda x: self.postal_code_letter(),
se... | [
"def",
"postcode",
"(",
"self",
")",
":",
"temp",
"=",
"re",
".",
"sub",
"(",
"r'\\?'",
",",
"lambda",
"x",
":",
"self",
".",
"postal_code_letter",
"(",
")",
",",
"self",
".",
"random_element",
"(",
"self",
".",
"postal_code_formats",
")",
")",
"return... | Replaces all question mark ('?') occurrences with a random letter
from postal_code_formats then passes result to
numerify to insert numbers | [
"Replaces",
"all",
"question",
"mark",
"(",
"?",
")",
"occurrences",
"with",
"a",
"random",
"letter",
"from",
"postal_code_formats",
"then",
"passes",
"result",
"to",
"numerify",
"to",
"insert",
"numbers"
] | python | train |
quantopian/empyrical | empyrical/stats.py | https://github.com/quantopian/empyrical/blob/badbdca75f5b293f28b5e947974894de041d6868/empyrical/stats.py#L995-L1046 | def alpha_beta(returns,
factor_returns,
risk_free=0.0,
period=DAILY,
annualization=None,
out=None):
"""Calculates annualized alpha and beta.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncum... | [
"def",
"alpha_beta",
"(",
"returns",
",",
"factor_returns",
",",
"risk_free",
"=",
"0.0",
",",
"period",
"=",
"DAILY",
",",
"annualization",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"returns",
",",
"factor_returns",
"=",
"_aligned_series",
"(",
"ret... | Calculates annualized alpha and beta.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series
Daily noncumulative returns of the factor to which beta is
... | [
"Calculates",
"annualized",
"alpha",
"and",
"beta",
"."
] | python | train |
OpenTreeOfLife/peyotl | peyotl/collections_store/__init__.py | https://github.com/OpenTreeOfLife/peyotl/blob/5e4e52a0fdbd17f490aa644ad79fda6ea2eda7c0/peyotl/collections_store/__init__.py#L45-L55 | def tree_is_in_collection(collection, study_id=None, tree_id=None):
"""Takes a collection object (or a filepath to collection object), returns
True if it includes a decision to include the specified tree
"""
included = collection_to_included_trees(collection)
study_id = study_id.strip()
tree_id ... | [
"def",
"tree_is_in_collection",
"(",
"collection",
",",
"study_id",
"=",
"None",
",",
"tree_id",
"=",
"None",
")",
":",
"included",
"=",
"collection_to_included_trees",
"(",
"collection",
")",
"study_id",
"=",
"study_id",
".",
"strip",
"(",
")",
"tree_id",
"="... | Takes a collection object (or a filepath to collection object), returns
True if it includes a decision to include the specified tree | [
"Takes",
"a",
"collection",
"object",
"(",
"or",
"a",
"filepath",
"to",
"collection",
"object",
")",
"returns",
"True",
"if",
"it",
"includes",
"a",
"decision",
"to",
"include",
"the",
"specified",
"tree"
] | python | train |
pinax/pinax-comments | pinax/comments/templatetags/pinax_comments_tags.py | https://github.com/pinax/pinax-comments/blob/3c239b929075d3843f6ed2d07c94b022e6c5b5ff/pinax/comments/templatetags/pinax_comments_tags.py#L26-L36 | def comment_count(object):
"""
Usage:
{% comment_count obj %}
or
{% comment_count obj as var %}
"""
return Comment.objects.filter(
object_id=object.pk,
content_type=ContentType.objects.get_for_model(object)
).count() | [
"def",
"comment_count",
"(",
"object",
")",
":",
"return",
"Comment",
".",
"objects",
".",
"filter",
"(",
"object_id",
"=",
"object",
".",
"pk",
",",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"object",
")",
")",
".",
... | Usage:
{% comment_count obj %}
or
{% comment_count obj as var %} | [
"Usage",
":",
"{",
"%",
"comment_count",
"obj",
"%",
"}",
"or",
"{",
"%",
"comment_count",
"obj",
"as",
"var",
"%",
"}"
] | python | train |
binux/pyspider | pyspider/scheduler/scheduler.py | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L661-L671 | def run_once(self):
'''comsume queues and feed tasks to fetcher, once'''
self._update_projects()
self._check_task_done()
self._check_request()
while self._check_cronjob():
pass
self._check_select()
self._check_delete()
self._try_dump_cnt() | [
"def",
"run_once",
"(",
"self",
")",
":",
"self",
".",
"_update_projects",
"(",
")",
"self",
".",
"_check_task_done",
"(",
")",
"self",
".",
"_check_request",
"(",
")",
"while",
"self",
".",
"_check_cronjob",
"(",
")",
":",
"pass",
"self",
".",
"_check_s... | comsume queues and feed tasks to fetcher, once | [
"comsume",
"queues",
"and",
"feed",
"tasks",
"to",
"fetcher",
"once"
] | python | train |
chemlab/chemlab | chemlab/core/spacegroup/cell.py | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/core/spacegroup/cell.py#L24-L34 | def cell_to_cellpar(cell):
"""Returns the cell parameters [a, b, c, alpha, beta, gamma] as a
numpy array."""
va, vb, vc = cell
a = np.linalg.norm(va)
b = np.linalg.norm(vb)
c = np.linalg.norm(vc)
alpha = 180.0/pi*arccos(dot(vb, vc)/(b*c))
beta = 180.0/pi*arccos(dot(vc, va)/(c*a))
ga... | [
"def",
"cell_to_cellpar",
"(",
"cell",
")",
":",
"va",
",",
"vb",
",",
"vc",
"=",
"cell",
"a",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"va",
")",
"b",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"vb",
")",
"c",
"=",
"np",
".",
"linalg",
... | Returns the cell parameters [a, b, c, alpha, beta, gamma] as a
numpy array. | [
"Returns",
"the",
"cell",
"parameters",
"[",
"a",
"b",
"c",
"alpha",
"beta",
"gamma",
"]",
"as",
"a",
"numpy",
"array",
"."
] | python | train |
python-security/pyt | pyt/core/node_types.py | https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/core/node_types.py#L57-L64 | def connect(self, successor):
"""Connect this node to its successor node by
setting its outgoing and the successors ingoing."""
if isinstance(self, ConnectToExitNode) and not isinstance(successor, EntryOrExitNode):
return
self.outgoing.append(successor)
successor.ing... | [
"def",
"connect",
"(",
"self",
",",
"successor",
")",
":",
"if",
"isinstance",
"(",
"self",
",",
"ConnectToExitNode",
")",
"and",
"not",
"isinstance",
"(",
"successor",
",",
"EntryOrExitNode",
")",
":",
"return",
"self",
".",
"outgoing",
".",
"append",
"("... | Connect this node to its successor node by
setting its outgoing and the successors ingoing. | [
"Connect",
"this",
"node",
"to",
"its",
"successor",
"node",
"by",
"setting",
"its",
"outgoing",
"and",
"the",
"successors",
"ingoing",
"."
] | python | train |
wummel/linkchecker | third_party/dnspython/dns/renderer.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/third_party/dnspython/dns/renderer.py#L103-L119 | def _rollback(self, where):
"""Truncate the output buffer at offset I{where}, and remove any
compression table entries that pointed beyond the truncation
point.
@param where: the offset
@type where: int
"""
self.output.seek(where)
self.output.truncate()
... | [
"def",
"_rollback",
"(",
"self",
",",
"where",
")",
":",
"self",
".",
"output",
".",
"seek",
"(",
"where",
")",
"self",
".",
"output",
".",
"truncate",
"(",
")",
"keys_to_delete",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"compress",
... | Truncate the output buffer at offset I{where}, and remove any
compression table entries that pointed beyond the truncation
point.
@param where: the offset
@type where: int | [
"Truncate",
"the",
"output",
"buffer",
"at",
"offset",
"I",
"{",
"where",
"}",
"and",
"remove",
"any",
"compression",
"table",
"entries",
"that",
"pointed",
"beyond",
"the",
"truncation",
"point",
"."
] | python | train |
agile4you/bottle-neck | example.py | https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/example.py#L45-L56 | def post(self):
"""Example POST method.
"""
resource_data = self.request.json
record = {'id': str(len(resource_db) + 1),
'name': resource_data.get('name')}
resource_db.append(record)
return self.response_factory.ok(data=record) | [
"def",
"post",
"(",
"self",
")",
":",
"resource_data",
"=",
"self",
".",
"request",
".",
"json",
"record",
"=",
"{",
"'id'",
":",
"str",
"(",
"len",
"(",
"resource_db",
")",
"+",
"1",
")",
",",
"'name'",
":",
"resource_data",
".",
"get",
"(",
"'nam... | Example POST method. | [
"Example",
"POST",
"method",
"."
] | python | train |
rbccps-iisc/ideam-python-sdk | ideam/entity.py | https://github.com/rbccps-iisc/ideam-python-sdk/blob/fd1fe46f1fbce9b90f4c384b8404522f9dcc1c98/ideam/entity.py#L246-L270 | async def asynchronously_get_data(self, url):
""" Asynchronously get data from Chunked transfer encoding of https://smartcity.rbccps.org/api/0.1.0/subscribe.
(Only this function requires Python 3. Rest of the functions can be run in python2.
Args:
url (string): url to subscribe
... | [
"async",
"def",
"asynchronously_get_data",
"(",
"self",
",",
"url",
")",
":",
"headers",
"=",
"{",
"\"apikey\"",
":",
"self",
".",
"entity_api_key",
"}",
"try",
":",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
"connector",
"=",
"aiohttp",
".",
"... | Asynchronously get data from Chunked transfer encoding of https://smartcity.rbccps.org/api/0.1.0/subscribe.
(Only this function requires Python 3. Rest of the functions can be run in python2.
Args:
url (string): url to subscribe | [
"Asynchronously",
"get",
"data",
"from",
"Chunked",
"transfer",
"encoding",
"of",
"https",
":",
"//",
"smartcity",
".",
"rbccps",
".",
"org",
"/",
"api",
"/",
"0",
".",
"1",
".",
"0",
"/",
"subscribe",
".",
"(",
"Only",
"this",
"function",
"requires",
... | python | train |
orbingol/NURBS-Python | geomdl/fitting.py | https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/fitting.py#L16-L53 | def interpolate_curve(points, degree, **kwargs):
""" Curve interpolation through the data points.
Please refer to Algorithm A9.1 on The NURBS Book (2nd Edition), pp.369-370 for details.
Keyword Arguments:
* ``centripetal``: activates centripetal parametrization method. *Default: False*
:param... | [
"def",
"interpolate_curve",
"(",
"points",
",",
"degree",
",",
"*",
"*",
"kwargs",
")",
":",
"# Keyword arguments",
"use_centripetal",
"=",
"kwargs",
".",
"get",
"(",
"'centripetal'",
",",
"False",
")",
"# Number of control points",
"num_points",
"=",
"len",
"("... | Curve interpolation through the data points.
Please refer to Algorithm A9.1 on The NURBS Book (2nd Edition), pp.369-370 for details.
Keyword Arguments:
* ``centripetal``: activates centripetal parametrization method. *Default: False*
:param points: data points
:type points: list, tuple
:p... | [
"Curve",
"interpolation",
"through",
"the",
"data",
"points",
"."
] | python | train |
trendmicro/flask-ini | flask_ini.py | https://github.com/trendmicro/flask-ini/blob/a1e4baa598c9a01021a1333d9c15e4d99c8334dd/flask_ini.py#L18-L23 | def readfp(self, *args, **kwargs):
'''Overridden readfp() method to call parse_flask_section() at the
end'''
ret = configparser.SafeConfigParser.readfp(self, *args, **kwargs)
self.parse_flask_section()
return ret | [
"def",
"readfp",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"configparser",
".",
"SafeConfigParser",
".",
"readfp",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"parse_flask_section",
"(... | Overridden readfp() method to call parse_flask_section() at the
end | [
"Overridden",
"readfp",
"()",
"method",
"to",
"call",
"parse_flask_section",
"()",
"at",
"the",
"end"
] | python | train |
jobovy/galpy | galpy/util/bovy_coords.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/bovy_coords.py#L1360-L1402 | def galcencyl_to_vxvyvz(vR,vT,vZ,phi,vsun=[0.,1.,0.],Xsun=1.,Zsun=0.,
_extra_rot=True):
"""
NAME:
galcencyl_to_vxvyvz
PURPOSE:
transform cylindrical Galactocentric coordinates to XYZ (wrt Sun) coordinates for velocities
INPUT:
vR - Galactocentric radial ... | [
"def",
"galcencyl_to_vxvyvz",
"(",
"vR",
",",
"vT",
",",
"vZ",
",",
"phi",
",",
"vsun",
"=",
"[",
"0.",
",",
"1.",
",",
"0.",
"]",
",",
"Xsun",
"=",
"1.",
",",
"Zsun",
"=",
"0.",
",",
"_extra_rot",
"=",
"True",
")",
":",
"vXg",
",",
"vYg",
",... | NAME:
galcencyl_to_vxvyvz
PURPOSE:
transform cylindrical Galactocentric coordinates to XYZ (wrt Sun) coordinates for velocities
INPUT:
vR - Galactocentric radial velocity
vT - Galactocentric tangential velocity
vZ - Galactocentric vertical velocity
phi - Galacto... | [
"NAME",
":"
] | python | train |
vinci1it2000/schedula | schedula/dispatcher.py | https://github.com/vinci1it2000/schedula/blob/addb9fd685be81544b796c51383ac00a31543ce9/schedula/dispatcher.py#L1148-L1381 | def get_sub_dsp_from_workflow(
self, sources, graph=None, reverse=False, add_missing=False,
check_inputs=True, blockers=None, wildcard=False,
_update_links=True):
"""
Returns the sub-dispatcher induced by the workflow from sources.
The induced sub-dispatcher ... | [
"def",
"get_sub_dsp_from_workflow",
"(",
"self",
",",
"sources",
",",
"graph",
"=",
"None",
",",
"reverse",
"=",
"False",
",",
"add_missing",
"=",
"False",
",",
"check_inputs",
"=",
"True",
",",
"blockers",
"=",
"None",
",",
"wildcard",
"=",
"False",
",",
... | Returns the sub-dispatcher induced by the workflow from sources.
The induced sub-dispatcher of the dsp contains the reachable nodes and
edges evaluated with breadth-first-search on the workflow graph from
source nodes.
:param sources:
Source nodes for the breadth-first-sear... | [
"Returns",
"the",
"sub",
"-",
"dispatcher",
"induced",
"by",
"the",
"workflow",
"from",
"sources",
"."
] | python | train |
monarch-initiative/dipper | dipper/sources/ZFIN.py | https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/ZFIN.py#L397-L639 | def process_fish(self, limit=None):
"""
Fish give identifiers to the "effective genotypes" that we create.
We can match these by:
Fish = (intrinsic) genotype + set of morpholinos
We assume here that the intrinsic genotypes and their parts
will be processed separately, pr... | [
"def",
"process_fish",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"LOG",
".",
"info",
"(",
"\"Processing Fish Parts\"",
")",
"raw",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"rawdir",
",",
"self",
".",
"files",
"[",
"'fish_components'",
"]... | Fish give identifiers to the "effective genotypes" that we create.
We can match these by:
Fish = (intrinsic) genotype + set of morpholinos
We assume here that the intrinsic genotypes and their parts
will be processed separately, prior to calling this function.
:param limit:
... | [
"Fish",
"give",
"identifiers",
"to",
"the",
"effective",
"genotypes",
"that",
"we",
"create",
".",
"We",
"can",
"match",
"these",
"by",
":",
"Fish",
"=",
"(",
"intrinsic",
")",
"genotype",
"+",
"set",
"of",
"morpholinos"
] | python | train |
pybel/pybel | src/pybel/manager/cache_manager.py | https://github.com/pybel/pybel/blob/c8a7a1bdae4c475fa2a8c77f3a9a5f6d79556ca0/src/pybel/manager/cache_manager.py#L1049-L1169 | def get_or_create_modification(self, graph: BELGraph, node: BaseEntity) -> Optional[List[Modification]]:
"""Create a list of node modification objects that belong to the node described by node_data.
Return ``None`` if the list can not be constructed, and the node should also be skipped.
:param... | [
"def",
"get_or_create_modification",
"(",
"self",
",",
"graph",
":",
"BELGraph",
",",
"node",
":",
"BaseEntity",
")",
"->",
"Optional",
"[",
"List",
"[",
"Modification",
"]",
"]",
":",
"modification_list",
"=",
"[",
"]",
"if",
"FUSION",
"in",
"node",
":",
... | Create a list of node modification objects that belong to the node described by node_data.
Return ``None`` if the list can not be constructed, and the node should also be skipped.
:param dict node: Describes the given node and contains is_variant information
:return: A list of modification obj... | [
"Create",
"a",
"list",
"of",
"node",
"modification",
"objects",
"that",
"belong",
"to",
"the",
"node",
"described",
"by",
"node_data",
"."
] | python | train |
rackerlabs/simpl | simpl/incubator/rest.py | https://github.com/rackerlabs/simpl/blob/60ed3336a931cd6a7a7246e60f26165d9dc7c99c/simpl/incubator/rest.py#L96-L112 | def coerce_one(schema=str):
"""Expect the input sequence to contain a single value.
:keyword schema:
Custom schema to apply to the input value. Defaults to just string,
since this is designed for query params.
"""
def validate(val):
"""Unpack a single item from the inputs sequen... | [
"def",
"coerce_one",
"(",
"schema",
"=",
"str",
")",
":",
"def",
"validate",
"(",
"val",
")",
":",
"\"\"\"Unpack a single item from the inputs sequence and run validation.\n\n NOTE(larsbutler): This code is highly opinionated for bottle, since\n bottle query params are wrap... | Expect the input sequence to contain a single value.
:keyword schema:
Custom schema to apply to the input value. Defaults to just string,
since this is designed for query params. | [
"Expect",
"the",
"input",
"sequence",
"to",
"contain",
"a",
"single",
"value",
"."
] | python | train |
mkouhei/tonicdnscli | src/tonicdnscli/connect.py | https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/connect.py#L210-L253 | def search_record(datas, keyword):
"""Search target JSON -> dictionary
Arguments:
datas: dictionary of record datas
keyword: search keyword (default is null)
Key target is "name" or "content" or "type". default null.
Either key and type, or on the other hand.
When keyword has inc... | [
"def",
"search_record",
"(",
"datas",
",",
"keyword",
")",
":",
"key_name",
",",
"key_type",
",",
"key_content",
"=",
"False",
",",
"False",
",",
"False",
"if",
"keyword",
".",
"find",
"(",
"','",
")",
">",
"-",
"1",
":",
"if",
"len",
"(",
"keyword",... | Search target JSON -> dictionary
Arguments:
datas: dictionary of record datas
keyword: search keyword (default is null)
Key target is "name" or "content" or "type". default null.
Either key and type, or on the other hand.
When keyword has include camma ",",
Separate keyword to na... | [
"Search",
"target",
"JSON",
"-",
">",
"dictionary"
] | python | train |
google/grr | grr/server/grr_response_server/flow_runner.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/flow_runner.py#L963-L978 | def Terminate(self, status=None):
"""Terminates this flow."""
try:
self.queue_manager.DestroyFlowStates(self.session_id)
except queue_manager.MoreDataException:
pass
# This flow might already not be running.
if not self.IsRunning():
return
self._SendTerminationMessage(status=... | [
"def",
"Terminate",
"(",
"self",
",",
"status",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"queue_manager",
".",
"DestroyFlowStates",
"(",
"self",
".",
"session_id",
")",
"except",
"queue_manager",
".",
"MoreDataException",
":",
"pass",
"# This flow might... | Terminates this flow. | [
"Terminates",
"this",
"flow",
"."
] | python | train |
DenisCarriere/geocoder | geocoder/ottawa_parcel.py | https://github.com/DenisCarriere/geocoder/blob/39b9999ec70e61da9fa52fe9fe82a261ad70fa8b/geocoder/ottawa_parcel.py#L47-L51 | def length(self):
"""Length in Feet (f)"""
length = self.parse['attributes'].get('Shape_Length')
if length:
return round(float(length)) | [
"def",
"length",
"(",
"self",
")",
":",
"length",
"=",
"self",
".",
"parse",
"[",
"'attributes'",
"]",
".",
"get",
"(",
"'Shape_Length'",
")",
"if",
"length",
":",
"return",
"round",
"(",
"float",
"(",
"length",
")",
")"
] | Length in Feet (f) | [
"Length",
"in",
"Feet",
"(",
"f",
")"
] | python | train |
bimbar/pykwb | pykwb/kwb.py | https://github.com/bimbar/pykwb/blob/3f607c064cc53b8310d22d42506ce817a5b735fe/pykwb/kwb.py#L211-L218 | def _add_to_checksum(self, checksum, value):
"""Add a byte to the checksum."""
checksum = self._byte_rot_left(checksum, 1)
checksum = checksum + value
if (checksum > 255):
checksum = checksum - 255
self._debug(PROP_LOGLEVEL_TRACE, "C: " + str(checksum) + " V: " + str(... | [
"def",
"_add_to_checksum",
"(",
"self",
",",
"checksum",
",",
"value",
")",
":",
"checksum",
"=",
"self",
".",
"_byte_rot_left",
"(",
"checksum",
",",
"1",
")",
"checksum",
"=",
"checksum",
"+",
"value",
"if",
"(",
"checksum",
">",
"255",
")",
":",
"ch... | Add a byte to the checksum. | [
"Add",
"a",
"byte",
"to",
"the",
"checksum",
"."
] | python | train |
buildbot/buildbot | master/buildbot/steps/subunit.py | https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/steps/subunit.py#L79-L82 | def issue(self, test, err):
"""An issue - failing, erroring etc test."""
self.step.setProgress('tests failed', len(self.failures) +
len(self.errors)) | [
"def",
"issue",
"(",
"self",
",",
"test",
",",
"err",
")",
":",
"self",
".",
"step",
".",
"setProgress",
"(",
"'tests failed'",
",",
"len",
"(",
"self",
".",
"failures",
")",
"+",
"len",
"(",
"self",
".",
"errors",
")",
")"
] | An issue - failing, erroring etc test. | [
"An",
"issue",
"-",
"failing",
"erroring",
"etc",
"test",
"."
] | python | train |
tritemio/PyBroMo | pybromo/utils/hdf5.py | https://github.com/tritemio/PyBroMo/blob/b75f82a4551ff37e7c7a7e6954c536451f3e6d06/pybromo/utils/hdf5.py#L34-L56 | def print_children(data_file, group='/'):
"""Print all the sub-groups in `group` and leaf-nodes children of `group`.
Parameters:
data_file (pytables HDF5 file object): the data file to print
group (string): path name of the group to be printed.
Default: '/', the root node.
"""
... | [
"def",
"print_children",
"(",
"data_file",
",",
"group",
"=",
"'/'",
")",
":",
"base",
"=",
"data_file",
".",
"get_node",
"(",
"group",
")",
"print",
"(",
"'Groups in:\\n %s\\n'",
"%",
"base",
")",
"for",
"node",
"in",
"base",
".",
"_f_walk_groups",
"(",
... | Print all the sub-groups in `group` and leaf-nodes children of `group`.
Parameters:
data_file (pytables HDF5 file object): the data file to print
group (string): path name of the group to be printed.
Default: '/', the root node. | [
"Print",
"all",
"the",
"sub",
"-",
"groups",
"in",
"group",
"and",
"leaf",
"-",
"nodes",
"children",
"of",
"group",
"."
] | python | valid |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.