repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
bitesofcode/projex | projex/text.py | https://github.com/bitesofcode/projex/blob/d31743ec456a41428709968ab11a2cf6c6c76247/projex/text.py#L119-L132 | def capitalize(text):
"""
Capitalizes the word using the normal string capitalization
method, however if the word contains only capital letters and
numbers, then it will not be affected.
:param text | <str>
:return <str>
"""
text = nativestring(t... | [
"def",
"capitalize",
"(",
"text",
")",
":",
"text",
"=",
"nativestring",
"(",
"text",
")",
"if",
"EXPR_CAPITALS",
".",
"match",
"(",
"text",
")",
":",
"return",
"text",
"return",
"text",
".",
"capitalize",
"(",
")"
] | Capitalizes the word using the normal string capitalization
method, however if the word contains only capital letters and
numbers, then it will not be affected.
:param text | <str>
:return <str> | [
"Capitalizes",
"the",
"word",
"using",
"the",
"normal",
"string",
"capitalization",
"method",
"however",
"if",
"the",
"word",
"contains",
"only",
"capital",
"letters",
"and",
"numbers",
"then",
"it",
"will",
"not",
"be",
"affected",
".",
":",
"param",
"text",
... | python | train |
zeromake/aiko | aiko/response.py | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/response.py#L352-L361 | def flush_body(self) -> bool:
"""
发送内容体
"""
if self._body is None:
return False
elif isinstance(self._body, bytes):
self.write(self._body)
return True
return False | [
"def",
"flush_body",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"_body",
"is",
"None",
":",
"return",
"False",
"elif",
"isinstance",
"(",
"self",
".",
"_body",
",",
"bytes",
")",
":",
"self",
".",
"write",
"(",
"self",
".",
"_body",
")... | 发送内容体 | [
"发送内容体"
] | python | train |
tango-controls/pytango | tango/encoded_attribute.py | https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/encoded_attribute.py#L358-L430 | def __EncodedAttribute_encode_jpeg_rgb32(self, rgb32, width=0, height=0, quality=100.0):
"""Encode a 32 bit rgb color image as JPEG format.
:param rgb32: an object containning image information
:type rgb32: :py:obj:`str` or :class:`numpy.ndarray` or seq< seq<element> >
:param width... | [
"def",
"__EncodedAttribute_encode_jpeg_rgb32",
"(",
"self",
",",
"rgb32",
",",
"width",
"=",
"0",
",",
"height",
"=",
"0",
",",
"quality",
"=",
"100.0",
")",
":",
"if",
"not",
"is_seq",
"(",
"rgb32",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected sequenc... | Encode a 32 bit rgb color image as JPEG format.
:param rgb32: an object containning image information
:type rgb32: :py:obj:`str` or :class:`numpy.ndarray` or seq< seq<element> >
:param width: image width. **MUST** be given if rgb32 is a string or
if it is a :cl... | [
"Encode",
"a",
"32",
"bit",
"rgb",
"color",
"image",
"as",
"JPEG",
"format",
"."
] | python | train |
gmr/tredis | tredis/client.py | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/client.py#L358-L368 | def ready(self):
"""Indicates that the client is connected to the Redis server or
cluster and is ready for use.
:rtype: bool
"""
if self._clustering:
return (all([c.connected for c in self._cluster.values()])
and len(self._cluster))
retur... | [
"def",
"ready",
"(",
"self",
")",
":",
"if",
"self",
".",
"_clustering",
":",
"return",
"(",
"all",
"(",
"[",
"c",
".",
"connected",
"for",
"c",
"in",
"self",
".",
"_cluster",
".",
"values",
"(",
")",
"]",
")",
"and",
"len",
"(",
"self",
".",
"... | Indicates that the client is connected to the Redis server or
cluster and is ready for use.
:rtype: bool | [
"Indicates",
"that",
"the",
"client",
"is",
"connected",
"to",
"the",
"Redis",
"server",
"or",
"cluster",
"and",
"is",
"ready",
"for",
"use",
"."
] | python | train |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/breakpoint.py | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/breakpoint.py#L2112-L2137 | def __cleanup_thread(self, event):
"""
Auxiliary method for L{_notify_exit_thread}
and L{_notify_exit_process}.
"""
tid = event.get_tid()
# Cleanup running breakpoints
try:
for bp in self.__runningBP[tid]:
self.__cleanup_breakpoint(eve... | [
"def",
"__cleanup_thread",
"(",
"self",
",",
"event",
")",
":",
"tid",
"=",
"event",
".",
"get_tid",
"(",
")",
"# Cleanup running breakpoints",
"try",
":",
"for",
"bp",
"in",
"self",
".",
"__runningBP",
"[",
"tid",
"]",
":",
"self",
".",
"__cleanup_breakpo... | Auxiliary method for L{_notify_exit_thread}
and L{_notify_exit_process}. | [
"Auxiliary",
"method",
"for",
"L",
"{",
"_notify_exit_thread",
"}",
"and",
"L",
"{",
"_notify_exit_process",
"}",
"."
] | python | train |
brainiak/brainiak | brainiak/funcalign/sssrm.py | https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/funcalign/sssrm.py#L584-L638 | def _objective_function(self, data_align, data_sup, labels, w, s, theta,
bias):
"""Compute the objective function of the Semi-Supervised SRM
See :eq:`sssrm-eq`.
Parameters
----------
data_align : list of 2D arrays, element i has shape=[voxels_i, n_a... | [
"def",
"_objective_function",
"(",
"self",
",",
"data_align",
",",
"data_sup",
",",
"labels",
",",
"w",
",",
"s",
",",
"theta",
",",
"bias",
")",
":",
"subjects",
"=",
"len",
"(",
"data_align",
")",
"# Compute the SRM loss",
"f_val",
"=",
"0.0",
"for",
... | Compute the objective function of the Semi-Supervised SRM
See :eq:`sssrm-eq`.
Parameters
----------
data_align : list of 2D arrays, element i has shape=[voxels_i, n_align]
Each element in the list contains the fMRI data for alignment of
one subject. There are n... | [
"Compute",
"the",
"objective",
"function",
"of",
"the",
"Semi",
"-",
"Supervised",
"SRM"
] | python | train |
rasky/geventconnpool | src/geventconnpool/pool.py | https://github.com/rasky/geventconnpool/blob/47c65c64e051cb62061f3ed072991d6b0a83bbf5/src/geventconnpool/pool.py#L112-L144 | def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None,
retry_log_level=logging.INFO,
retry_log_message="Connection broken in '{f}' (error: '{e}'); "
"retrying with new connection.",
max_failures=None, interval=0,
max_failure_log_level=logging.ERROR... | [
"def",
"retry",
"(",
"f",
",",
"exc_classes",
"=",
"DEFAULT_EXC_CLASSES",
",",
"logger",
"=",
"None",
",",
"retry_log_level",
"=",
"logging",
".",
"INFO",
",",
"retry_log_message",
"=",
"\"Connection broken in '{f}' (error: '{e}'); \"",
"\"retrying with new connection.\""... | Decorator to automatically reexecute a function if the connection is
broken for any reason. | [
"Decorator",
"to",
"automatically",
"reexecute",
"a",
"function",
"if",
"the",
"connection",
"is",
"broken",
"for",
"any",
"reason",
"."
] | python | train |
tylertreat/BigQuery-Python | bigquery/client.py | https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L528-L552 | def get_dataset(self, dataset_id, project_id=None):
"""Retrieve a dataset if it exists, otherwise return an empty dict.
Parameters
----------
dataset_id : str
Dataset unique id
project_id: str, optional
The project the dataset is in
Returns
... | [
"def",
"get_dataset",
"(",
"self",
",",
"dataset_id",
",",
"project_id",
"=",
"None",
")",
":",
"project_id",
"=",
"self",
".",
"_get_project_id",
"(",
"project_id",
")",
"try",
":",
"dataset",
"=",
"self",
".",
"bigquery",
".",
"datasets",
"(",
")",
"."... | Retrieve a dataset if it exists, otherwise return an empty dict.
Parameters
----------
dataset_id : str
Dataset unique id
project_id: str, optional
The project the dataset is in
Returns
-------
dict
Contains dataset object if ... | [
"Retrieve",
"a",
"dataset",
"if",
"it",
"exists",
"otherwise",
"return",
"an",
"empty",
"dict",
"."
] | python | train |
collectiveacuity/labPack | labpack/records/time.py | https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/records/time.py#L145-L178 | def humanFriendly(self, time_zone='', include_day=True, include_time=True):
''' a method to report a human friendly string from a labDT object
:param time_zone: [optional] string with timezone to report in
:return: string with date and time info
'''
# validate inputs
... | [
"def",
"humanFriendly",
"(",
"self",
",",
"time_zone",
"=",
"''",
",",
"include_day",
"=",
"True",
",",
"include_time",
"=",
"True",
")",
":",
"# validate inputs\r",
"zeroHourPattern",
"=",
"re",
".",
"compile",
"(",
"'\\s0\\d:'",
")",
"title",
"=",
"'Timezo... | a method to report a human friendly string from a labDT object
:param time_zone: [optional] string with timezone to report in
:return: string with date and time info | [
"a",
"method",
"to",
"report",
"a",
"human",
"friendly",
"string",
"from",
"a",
"labDT",
"object",
":",
"param",
"time_zone",
":",
"[",
"optional",
"]",
"string",
"with",
"timezone",
"to",
"report",
"in",
":",
"return",
":",
"string",
"with",
"date",
"an... | python | train |
NeuroML/NeuroMLlite | neuromllite/SonataReader.py | https://github.com/NeuroML/NeuroMLlite/blob/f3fa2ff662e40febfa97c045e7f0e6915ad04161/neuromllite/SonataReader.py#L699-L831 | def add_neuroml_components(self, nml_doc):
"""
Based on cell & synapse properties found, create the corresponding NeuroML components
"""
is_nest = False
print_v("Adding NeuroML cells to: %s"%nml_doc.id)
#pp.pprint(self.pop_comp_info)
for c in... | [
"def",
"add_neuroml_components",
"(",
"self",
",",
"nml_doc",
")",
":",
"is_nest",
"=",
"False",
"print_v",
"(",
"\"Adding NeuroML cells to: %s\"",
"%",
"nml_doc",
".",
"id",
")",
"#pp.pprint(self.pop_comp_info)",
"for",
"c",
"in",
"self",
".",
"pop_comp_info",
":... | Based on cell & synapse properties found, create the corresponding NeuroML components | [
"Based",
"on",
"cell",
"&",
"synapse",
"properties",
"found",
"create",
"the",
"corresponding",
"NeuroML",
"components"
] | python | train |
wakatime/wakatime | wakatime/packages/ntlm_auth/compute_keys.py | https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/ntlm_auth/compute_keys.py#L76-L96 | def get_seal_key(negotiate_flags, exported_session_key, magic_constant):
"""
3.4.5.3. SEALKEY
Main method to use to calculate the seal_key used to seal (encrypt) messages. This will determine
the correct method below to use based on the compatibility flags set and should be called instead
of the oth... | [
"def",
"get_seal_key",
"(",
"negotiate_flags",
",",
"exported_session_key",
",",
"magic_constant",
")",
":",
"if",
"negotiate_flags",
"&",
"NegotiateFlags",
".",
"NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY",
":",
"seal_key",
"=",
"_get_seal_key_ntlm2",
"(",
"negotiate_flags... | 3.4.5.3. SEALKEY
Main method to use to calculate the seal_key used to seal (encrypt) messages. This will determine
the correct method below to use based on the compatibility flags set and should be called instead
of the others
@param exported_session_key: A 128-bit session key used to derive signing an... | [
"3",
".",
"4",
".",
"5",
".",
"3",
".",
"SEALKEY",
"Main",
"method",
"to",
"use",
"to",
"calculate",
"the",
"seal_key",
"used",
"to",
"seal",
"(",
"encrypt",
")",
"messages",
".",
"This",
"will",
"determine",
"the",
"correct",
"method",
"below",
"to",
... | python | train |
sdispater/eloquent | eloquent/query/builder.py | https://github.com/sdispater/eloquent/blob/0638b688d5fd0c1a46b7471dd465eeb4c2f84666/eloquent/query/builder.py#L1365-L1380 | def delete(self, id=None):
"""
Delete a record from the database
:param id: The id of the row to delete
:type id: mixed
:return: The number of rows deleted
:rtype: int
"""
if id is not None:
self.where('id', '=', id)
sql = self._gram... | [
"def",
"delete",
"(",
"self",
",",
"id",
"=",
"None",
")",
":",
"if",
"id",
"is",
"not",
"None",
":",
"self",
".",
"where",
"(",
"'id'",
",",
"'='",
",",
"id",
")",
"sql",
"=",
"self",
".",
"_grammar",
".",
"compile_delete",
"(",
"self",
")",
"... | Delete a record from the database
:param id: The id of the row to delete
:type id: mixed
:return: The number of rows deleted
:rtype: int | [
"Delete",
"a",
"record",
"from",
"the",
"database"
] | python | train |
potash/drain | drain/drake.py | https://github.com/potash/drain/blob/ddd62081cb9317beb5d21f86c8b4bb196ca3d222/drain/drake.py#L52-L77 | def to_drake_step(inputs, output):
"""
Args:
inputs: collection of input Steps
output: output Step
Returns: a string of the drake step for the given inputs and output
"""
i = [output._yaml_filename]
i.extend(map(lambda i: i._target_filename, list(inputs)))
i.extend(output.de... | [
"def",
"to_drake_step",
"(",
"inputs",
",",
"output",
")",
":",
"i",
"=",
"[",
"output",
".",
"_yaml_filename",
"]",
"i",
".",
"extend",
"(",
"map",
"(",
"lambda",
"i",
":",
"i",
".",
"_target_filename",
",",
"list",
"(",
"inputs",
")",
")",
")",
"... | Args:
inputs: collection of input Steps
output: output Step
Returns: a string of the drake step for the given inputs and output | [
"Args",
":",
"inputs",
":",
"collection",
"of",
"input",
"Steps",
"output",
":",
"output",
"Step"
] | python | train |
coagulant/cleanweb | cleanweb.py | https://github.com/coagulant/cleanweb/blob/cc8f368d917037bf77772cd9fb068f898fd63d7e/cleanweb.py#L22-L32 | def request(self, *args, **kwargs):
""" Error handling in requests
http://api.yandex.ru/cleanweb/doc/dg/concepts/error-codes.xml
"""
r = self.session.request(*args, **kwargs)
if r.status_code != requests.codes.ok:
error = ET.fromstring(r.content)
messa... | [
"def",
"request",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"self",
".",
"session",
".",
"request",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"r",
".",
"status_code",
"!=",
"requests",
".",
"codes",
... | Error handling in requests
http://api.yandex.ru/cleanweb/doc/dg/concepts/error-codes.xml | [
"Error",
"handling",
"in",
"requests",
"http",
":",
"//",
"api",
".",
"yandex",
".",
"ru",
"/",
"cleanweb",
"/",
"doc",
"/",
"dg",
"/",
"concepts",
"/",
"error",
"-",
"codes",
".",
"xml"
] | python | train |
CenturyLinkCloud/clc-python-sdk | src/clc/APIv2/public_ip.py | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/public_ip.py#L233-L246 | def AddSourceRestrictions(self,cidrs):
"""Create one or more CIDR source restriction policies.
Include a list of CIDR strings.
>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0]
.AddSourceRestrictions(cidrs=["132.200.20.1/32","132.200.20.100/32"]).WaitUntilComplete()
0
"""
for cidr in cidrs: ... | [
"def",
"AddSourceRestrictions",
"(",
"self",
",",
"cidrs",
")",
":",
"for",
"cidr",
"in",
"cidrs",
":",
"self",
".",
"source_restrictions",
".",
"append",
"(",
"SourceRestriction",
"(",
"self",
",",
"cidr",
")",
")",
"return",
"(",
"self",
".",
"Update",
... | Create one or more CIDR source restriction policies.
Include a list of CIDR strings.
>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0]
.AddSourceRestrictions(cidrs=["132.200.20.1/32","132.200.20.100/32"]).WaitUntilComplete()
0 | [
"Create",
"one",
"or",
"more",
"CIDR",
"source",
"restriction",
"policies",
"."
] | python | train |
spacetelescope/pysynphot | pysynphot/spectrum.py | https://github.com/spacetelescope/pysynphot/blob/a125ff956f4d94beb157bd51899747a13234bb97/pysynphot/spectrum.py#L906-L919 | def GetWaveSet(self):
"""Obtain the wavelength set for the composite spectrum.
This is done by using :func:`MergeWaveSets` to form a union of
wavelength sets from its components.
Returns
-------
waveset : array_like
Composite wavelength set.
"""
... | [
"def",
"GetWaveSet",
"(",
"self",
")",
":",
"waveset1",
"=",
"self",
".",
"component1",
".",
"GetWaveSet",
"(",
")",
"waveset2",
"=",
"self",
".",
"component2",
".",
"GetWaveSet",
"(",
")",
"return",
"MergeWaveSets",
"(",
"waveset1",
",",
"waveset2",
")"
] | Obtain the wavelength set for the composite spectrum.
This is done by using :func:`MergeWaveSets` to form a union of
wavelength sets from its components.
Returns
-------
waveset : array_like
Composite wavelength set. | [
"Obtain",
"the",
"wavelength",
"set",
"for",
"the",
"composite",
"spectrum",
".",
"This",
"is",
"done",
"by",
"using",
":",
"func",
":",
"MergeWaveSets",
"to",
"form",
"a",
"union",
"of",
"wavelength",
"sets",
"from",
"its",
"components",
"."
] | python | train |
Azure/msrestazure-for-python | msrestazure/azure_operation.py | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L166-L190 | def _deserialize(self, response):
"""Attempt to deserialize resource from response.
:param requests.Response response: latest REST call response.
"""
# Hacking response with initial status_code
previous_status = response.status_code
response.status_code = self.initial_st... | [
"def",
"_deserialize",
"(",
"self",
",",
"response",
")",
":",
"# Hacking response with initial status_code",
"previous_status",
"=",
"response",
".",
"status_code",
"response",
".",
"status_code",
"=",
"self",
".",
"initial_status_code",
"resource",
"=",
"self",
".",... | Attempt to deserialize resource from response.
:param requests.Response response: latest REST call response. | [
"Attempt",
"to",
"deserialize",
"resource",
"from",
"response",
"."
] | python | train |
base4sistemas/satcfe | satcfe/clientelocal.py | https://github.com/base4sistemas/satcfe/blob/cb8e8815f4133d3e3d94cf526fa86767b4521ed9/satcfe/clientelocal.py#L89-L96 | def consultar_sat(self):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_sat`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT
"""
retorno = super(ClienteSATLocal, self).consultar_sat()
return RespostaSAT.consultar_sat(retorno) | [
"def",
"consultar_sat",
"(",
"self",
")",
":",
"retorno",
"=",
"super",
"(",
"ClienteSATLocal",
",",
"self",
")",
".",
"consultar_sat",
"(",
")",
"return",
"RespostaSAT",
".",
"consultar_sat",
"(",
"retorno",
")"
] | Sobrepõe :meth:`~satcfe.base.FuncoesSAT.consultar_sat`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT | [
"Sobrepõe",
":",
"meth",
":",
"~satcfe",
".",
"base",
".",
"FuncoesSAT",
".",
"consultar_sat",
"."
] | python | train |
mrcagney/gtfstk | gtfstk/miscellany.py | https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/miscellany.py#L258-L286 | def convert_dist(feed: "Feed", new_dist_units: str) -> "Feed":
"""
Convert the distances recorded in the ``shape_dist_traveled``
columns of the given Feed to the given distance units.
New distance units must lie in :const:`.constants.DIST_UNITS`.
Return the resulting feed.
"""
feed = feed.co... | [
"def",
"convert_dist",
"(",
"feed",
":",
"\"Feed\"",
",",
"new_dist_units",
":",
"str",
")",
"->",
"\"Feed\"",
":",
"feed",
"=",
"feed",
".",
"copy",
"(",
")",
"if",
"feed",
".",
"dist_units",
"==",
"new_dist_units",
":",
"# Nothing to do",
"return",
"feed... | Convert the distances recorded in the ``shape_dist_traveled``
columns of the given Feed to the given distance units.
New distance units must lie in :const:`.constants.DIST_UNITS`.
Return the resulting feed. | [
"Convert",
"the",
"distances",
"recorded",
"in",
"the",
"shape_dist_traveled",
"columns",
"of",
"the",
"given",
"Feed",
"to",
"the",
"given",
"distance",
"units",
".",
"New",
"distance",
"units",
"must",
"lie",
"in",
":",
"const",
":",
".",
"constants",
".",... | python | train |
yyuu/botornado | boto/rds/__init__.py | https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/rds/__init__.py#L884-L939 | def restore_dbinstance_from_point_in_time(self, source_instance_id,
target_instance_id,
use_latest=False,
restore_time=None,
dbinstance_... | [
"def",
"restore_dbinstance_from_point_in_time",
"(",
"self",
",",
"source_instance_id",
",",
"target_instance_id",
",",
"use_latest",
"=",
"False",
",",
"restore_time",
"=",
"None",
",",
"dbinstance_class",
"=",
"None",
",",
"port",
"=",
"None",
",",
"availability_z... | Create a new DBInstance from a point in time.
:type source_instance_id: string
:param source_instance_id: The identifier for the source DBInstance.
:type target_instance_id: string
:param target_instance_id: The identifier of the new DBInstance.
:type use_latest: bool
... | [
"Create",
"a",
"new",
"DBInstance",
"from",
"a",
"point",
"in",
"time",
"."
] | python | train |
RSEmail/smtp-health-check | smtphealth/__init__.py | https://github.com/RSEmail/smtp-health-check/blob/7407ba4239dc609caeceec720f33c5d664e739cf/smtphealth/__init__.py#L207-L233 | def run(self, host, port=25, with_ssl=False):
"""Executes a single health check against a remote host and port. This
method may only be called once per object.
:param host: The hostname or IP address of the SMTP server to check.
:type host: str
:param port: The port number of th... | [
"def",
"run",
"(",
"self",
",",
"host",
",",
"port",
"=",
"25",
",",
"with_ssl",
"=",
"False",
")",
":",
"try",
":",
"dns_rec",
"=",
"self",
".",
"_lookup",
"(",
"host",
",",
"port",
")",
"self",
".",
"_connect",
"(",
"dns_rec",
")",
"if",
"with_... | Executes a single health check against a remote host and port. This
method may only be called once per object.
:param host: The hostname or IP address of the SMTP server to check.
:type host: str
:param port: The port number of the SMTP server to check.
:type port: int
:... | [
"Executes",
"a",
"single",
"health",
"check",
"against",
"a",
"remote",
"host",
"and",
"port",
".",
"This",
"method",
"may",
"only",
"be",
"called",
"once",
"per",
"object",
"."
] | python | train |
chaoss/grimoirelab-perceval | perceval/client.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/client.py#L225-L248 | def setup_rate_limit_handler(self, sleep_for_rate=False, min_rate_to_sleep=MIN_RATE_LIMIT,
rate_limit_header=RATE_LIMIT_HEADER,
rate_limit_reset_header=RATE_LIMIT_RESET_HEADER):
"""Setup the rate limit handler.
:param sleep_for_rate: sle... | [
"def",
"setup_rate_limit_handler",
"(",
"self",
",",
"sleep_for_rate",
"=",
"False",
",",
"min_rate_to_sleep",
"=",
"MIN_RATE_LIMIT",
",",
"rate_limit_header",
"=",
"RATE_LIMIT_HEADER",
",",
"rate_limit_reset_header",
"=",
"RATE_LIMIT_RESET_HEADER",
")",
":",
"self",
".... | Setup the rate limit handler.
:param sleep_for_rate: sleep until rate limit is reset
:param min_rate_to_sleep: minimun rate needed to make the fecthing process sleep
:param rate_limit_header: header from where extract the rate limit data
:param rate_limit_reset_header: header from where... | [
"Setup",
"the",
"rate",
"limit",
"handler",
"."
] | python | test |
draperjames/qtpandas | qtpandas/ui/fallback/easygui/boxes/derived_boxes.py | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/ui/fallback/easygui/boxes/derived_boxes.py#L30-L69 | def ynbox(msg="Shall I continue?", title=" ",
choices=("[<F1>]Yes", "[<F2>]No"), image=None,
default_choice='[<F1>]Yes', cancel_choice='[<F2>]No'):
"""
Display a msgbox with choices of Yes and No.
The returned value is calculated this way::
if the first choice ("Yes") is chosen... | [
"def",
"ynbox",
"(",
"msg",
"=",
"\"Shall I continue?\"",
",",
"title",
"=",
"\" \"",
",",
"choices",
"=",
"(",
"\"[<F1>]Yes\"",
",",
"\"[<F2>]No\"",
")",
",",
"image",
"=",
"None",
",",
"default_choice",
"=",
"'[<F1>]Yes'",
",",
"cancel_choice",
"=",
"'[<F2... | Display a msgbox with choices of Yes and No.
The returned value is calculated this way::
if the first choice ("Yes") is chosen, or if the dialog is cancelled:
return True
else:
return False
If invoked without a msg argument, displays a generic
request for a confirm... | [
"Display",
"a",
"msgbox",
"with",
"choices",
"of",
"Yes",
"and",
"No",
"."
] | python | train |
projectshift/shift-boiler | boiler/collections/paginated_collection.py | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/collections/paginated_collection.py#L66-L74 | def fetch_items(self):
"""
Fetch items
Performs a query to retrieve items based on current query and
pagination settings.
"""
offset = self.per_page * (self.page - 1)
items = self._query.limit(self.per_page).offset(offset).all()
return items | [
"def",
"fetch_items",
"(",
"self",
")",
":",
"offset",
"=",
"self",
".",
"per_page",
"*",
"(",
"self",
".",
"page",
"-",
"1",
")",
"items",
"=",
"self",
".",
"_query",
".",
"limit",
"(",
"self",
".",
"per_page",
")",
".",
"offset",
"(",
"offset",
... | Fetch items
Performs a query to retrieve items based on current query and
pagination settings. | [
"Fetch",
"items",
"Performs",
"a",
"query",
"to",
"retrieve",
"items",
"based",
"on",
"current",
"query",
"and",
"pagination",
"settings",
"."
] | python | train |
shmir/PyIxExplorer | ixexplorer/ixe_port.py | https://github.com/shmir/PyIxExplorer/blob/d6946b9ce0e8961507cc912062e10c365d4beee2/ixexplorer/ixe_port.py#L268-L274 | def start_transmit(self, blocking=False):
""" Start transmit on port.
:param blocking: True - wait for traffic end, False - return after traffic start.
"""
self.session.start_transmit(blocking, False, self) | [
"def",
"start_transmit",
"(",
"self",
",",
"blocking",
"=",
"False",
")",
":",
"self",
".",
"session",
".",
"start_transmit",
"(",
"blocking",
",",
"False",
",",
"self",
")"
] | Start transmit on port.
:param blocking: True - wait for traffic end, False - return after traffic start. | [
"Start",
"transmit",
"on",
"port",
"."
] | python | train |
jadolg/rocketchat_API | rocketchat_API/rocketchat.py | https://github.com/jadolg/rocketchat_API/blob/f220d094434991cb9892418245f054ea06f28aad/rocketchat_API/rocketchat.py#L348-L350 | def channels_leave(self, room_id, **kwargs):
"""Causes the callee to be removed from the channel."""
return self.__call_api_post('channels.leave', roomId=room_id, kwargs=kwargs) | [
"def",
"channels_leave",
"(",
"self",
",",
"room_id",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'channels.leave'",
",",
"roomId",
"=",
"room_id",
",",
"kwargs",
"=",
"kwargs",
")"
] | Causes the callee to be removed from the channel. | [
"Causes",
"the",
"callee",
"to",
"be",
"removed",
"from",
"the",
"channel",
"."
] | python | train |
kxgames/vecrec | vecrec/shapes.py | https://github.com/kxgames/vecrec/blob/18b0841419de21a644b4511e2229af853ed09529/vecrec/shapes.py#L418-L423 | def get_interpolated(self, target, extent):
""" Return a new vector that has been moved towards the given target by
the given extent. The extent should be between 0 and 1. """
result = self.copy()
result.interpolate(target, extent)
return result | [
"def",
"get_interpolated",
"(",
"self",
",",
"target",
",",
"extent",
")",
":",
"result",
"=",
"self",
".",
"copy",
"(",
")",
"result",
".",
"interpolate",
"(",
"target",
",",
"extent",
")",
"return",
"result"
] | Return a new vector that has been moved towards the given target by
the given extent. The extent should be between 0 and 1. | [
"Return",
"a",
"new",
"vector",
"that",
"has",
"been",
"moved",
"towards",
"the",
"given",
"target",
"by",
"the",
"given",
"extent",
".",
"The",
"extent",
"should",
"be",
"between",
"0",
"and",
"1",
"."
] | python | train |
JarryShaw/PyPCAPKit | src/protocols/internet/hopopt.py | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/hopopt.py#L494-L622 | def _read_opt_smf_dpd(self, code, *, desc):
"""Read HOPOPT SMF_DPD option.
Structure of HOPOPT SMF_DPD option [RFC 5570]:
* IPv6 SMF_DPD Option Header in I-DPD mode
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 ... | [
"def",
"_read_opt_smf_dpd",
"(",
"self",
",",
"code",
",",
"*",
",",
"desc",
")",
":",
"_type",
"=",
"self",
".",
"_read_opt_type",
"(",
"code",
")",
"_size",
"=",
"self",
".",
"_read_unpack",
"(",
"1",
")",
"_tidd",
"=",
"self",
".",
"_read_binary",
... | Read HOPOPT SMF_DPD option.
Structure of HOPOPT SMF_DPD option [RFC 5570]:
* IPv6 SMF_DPD Option Header in I-DPD mode
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+... | [
"Read",
"HOPOPT",
"SMF_DPD",
"option",
"."
] | python | train |
6809/MC6809 | MC6809/components/mc6809_stack.py | https://github.com/6809/MC6809/blob/6ba2f5106df46689017b5d0b6d84d43b7ee6a240/MC6809/components/mc6809_stack.py#L149-L186 | def instruction_PUL(self, opcode, m, register):
"""
All, some, or none of the processor registers are pulled from stack
(with the exception of stack pointer itself).
A single register may be pulled from the stack with condition codes set
by doing an autoincrement load from the s... | [
"def",
"instruction_PUL",
"(",
"self",
",",
"opcode",
",",
"m",
",",
"register",
")",
":",
"assert",
"register",
"in",
"(",
"self",
".",
"system_stack_pointer",
",",
"self",
".",
"user_stack_pointer",
")",
"def",
"pull",
"(",
"register_str",
",",
"stack_poin... | All, some, or none of the processor registers are pulled from stack
(with the exception of stack pointer itself).
A single register may be pulled from the stack with condition codes set
by doing an autoincrement load from the stack (example: LDX ,S++).
source code forms: b7 b6 b5 b4 b3... | [
"All",
"some",
"or",
"none",
"of",
"the",
"processor",
"registers",
"are",
"pulled",
"from",
"stack",
"(",
"with",
"the",
"exception",
"of",
"stack",
"pointer",
"itself",
")",
"."
] | python | train |
wbond/asn1crypto | asn1crypto/x509.py | https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/x509.py#L976-L1034 | def build(cls, name_dict, use_printable=False):
"""
Creates a Name object from a dict of unicode string keys and values.
The keys should be from NameType._map, or a dotted-integer OID unicode
string.
:param name_dict:
A dict of name information, e.g. {"common_name": ... | [
"def",
"build",
"(",
"cls",
",",
"name_dict",
",",
"use_printable",
"=",
"False",
")",
":",
"rdns",
"=",
"[",
"]",
"if",
"not",
"use_printable",
":",
"encoding_name",
"=",
"'utf8_string'",
"encoding_class",
"=",
"UTF8String",
"else",
":",
"encoding_name",
"=... | Creates a Name object from a dict of unicode string keys and values.
The keys should be from NameType._map, or a dotted-integer OID unicode
string.
:param name_dict:
A dict of name information, e.g. {"common_name": "Will Bond",
"country_name": "US", "organization": "Code... | [
"Creates",
"a",
"Name",
"object",
"from",
"a",
"dict",
"of",
"unicode",
"string",
"keys",
"and",
"values",
".",
"The",
"keys",
"should",
"be",
"from",
"NameType",
".",
"_map",
"or",
"a",
"dotted",
"-",
"integer",
"OID",
"unicode",
"string",
"."
] | python | train |
opencobra/memote | memote/support/consistency_helpers.py | https://github.com/opencobra/memote/blob/276630fcd4449fb7b914186edfd38c239e7052df/memote/support/consistency_helpers.py#L197-L212 | def get_interface(model):
"""
Return the interface specific classes.
Parameters
----------
model : cobra.Model
The metabolic model under investigation.
"""
return (
model.solver.interface.Model,
model.solver.interface.Constraint,
model.solver.interface.Varia... | [
"def",
"get_interface",
"(",
"model",
")",
":",
"return",
"(",
"model",
".",
"solver",
".",
"interface",
".",
"Model",
",",
"model",
".",
"solver",
".",
"interface",
".",
"Constraint",
",",
"model",
".",
"solver",
".",
"interface",
".",
"Variable",
",",
... | Return the interface specific classes.
Parameters
----------
model : cobra.Model
The metabolic model under investigation. | [
"Return",
"the",
"interface",
"specific",
"classes",
"."
] | python | train |
DancingQuanta/pyusbiss | usbiss/spi.py | https://github.com/DancingQuanta/pyusbiss/blob/fc64e123f1c97f53ad153c474d230ad38044c3cb/usbiss/spi.py#L118-L140 | def exchange(self, data):
"""
Perform SPI transaction.
The first received byte is either ACK or NACK.
:TODO: enforce rule that up to 63 bytes of data can be sent.
:TODO: enforce rule that there is no gaps in data bytes (what define a gap?)
:param data: List of bytes
... | [
"def",
"exchange",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_usbiss",
".",
"write_data",
"(",
"[",
"self",
".",
"_usbiss",
".",
"SPI_CMD",
"]",
"+",
"data",
")",
"response",
"=",
"self",
".",
"_usbiss",
".",
"read_data",
"(",
"1",
"+",
"le... | Perform SPI transaction.
The first received byte is either ACK or NACK.
:TODO: enforce rule that up to 63 bytes of data can be sent.
:TODO: enforce rule that there is no gaps in data bytes (what define a gap?)
:param data: List of bytes
:returns: List of bytes
:rtype: ... | [
"Perform",
"SPI",
"transaction",
"."
] | python | train |
splunk/splunk-sdk-python | splunklib/results.py | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/results.py#L129-L154 | def read(self, n=None):
"""Read at most *n* characters from this stream.
If *n* is ``None``, return all available characters.
"""
response = b""
while n is None or n > 0:
c = self.stream.read(1)
if c == b"":
break
elif c == b"<... | [
"def",
"read",
"(",
"self",
",",
"n",
"=",
"None",
")",
":",
"response",
"=",
"b\"\"",
"while",
"n",
"is",
"None",
"or",
"n",
">",
"0",
":",
"c",
"=",
"self",
".",
"stream",
".",
"read",
"(",
"1",
")",
"if",
"c",
"==",
"b\"\"",
":",
"break",
... | Read at most *n* characters from this stream.
If *n* is ``None``, return all available characters. | [
"Read",
"at",
"most",
"*",
"n",
"*",
"characters",
"from",
"this",
"stream",
"."
] | python | train |
rbarrois/mpdlcd | mpdlcd/vendor/lcdproc/screen.py | https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L94-L99 | def set_timeout(self, timeout):
""" Set Screen Timeout Duration """
if timeout > 0:
self.timeout = timeout
self.server.request("screen_set %s timeout %i" % (self.ref, (self.timeout * 8))) | [
"def",
"set_timeout",
"(",
"self",
",",
"timeout",
")",
":",
"if",
"timeout",
">",
"0",
":",
"self",
".",
"timeout",
"=",
"timeout",
"self",
".",
"server",
".",
"request",
"(",
"\"screen_set %s timeout %i\"",
"%",
"(",
"self",
".",
"ref",
",",
"(",
"se... | Set Screen Timeout Duration | [
"Set",
"Screen",
"Timeout",
"Duration"
] | python | train |
LuqueDaniel/pybooru | pybooru/api_danbooru.py | https://github.com/LuqueDaniel/pybooru/blob/60cd5254684d293b308f0b11b8f4ac2dce101479/pybooru/api_danbooru.py#L487-L494 | def dmail_delete(self, dmail_id):
"""Delete a dmail. You can only delete dmails you own (Requires login).
Parameters:
dmail_id (int): where dmail_id is the dmail id.
"""
return self._get('dmails/{0}.json'.format(dmail_id), method='DELETE',
auth=True) | [
"def",
"dmail_delete",
"(",
"self",
",",
"dmail_id",
")",
":",
"return",
"self",
".",
"_get",
"(",
"'dmails/{0}.json'",
".",
"format",
"(",
"dmail_id",
")",
",",
"method",
"=",
"'DELETE'",
",",
"auth",
"=",
"True",
")"
] | Delete a dmail. You can only delete dmails you own (Requires login).
Parameters:
dmail_id (int): where dmail_id is the dmail id. | [
"Delete",
"a",
"dmail",
".",
"You",
"can",
"only",
"delete",
"dmails",
"you",
"own",
"(",
"Requires",
"login",
")",
"."
] | python | train |
benmoran56/esper | esper.py | https://github.com/benmoran56/esper/blob/5b6cd0c51718d5dcfa0e5613f824b5251cf092ac/esper.py#L67-L75 | def remove_processor(self, processor_type: Processor) -> None:
"""Remove a Processor from the World, by type.
:param processor_type: The class type of the Processor to remove.
"""
for processor in self._processors:
if type(processor) == processor_type:
proces... | [
"def",
"remove_processor",
"(",
"self",
",",
"processor_type",
":",
"Processor",
")",
"->",
"None",
":",
"for",
"processor",
"in",
"self",
".",
"_processors",
":",
"if",
"type",
"(",
"processor",
")",
"==",
"processor_type",
":",
"processor",
".",
"world",
... | Remove a Processor from the World, by type.
:param processor_type: The class type of the Processor to remove. | [
"Remove",
"a",
"Processor",
"from",
"the",
"World",
"by",
"type",
"."
] | python | train |
pymupdf/PyMuPDF | fitz/utils.py | https://github.com/pymupdf/PyMuPDF/blob/917f2d83482510e26ba0ff01fd2392c26f3a8e90/fitz/utils.py#L528-L571 | def getToC(doc, simple = True):
"""Create a table of contents.
Args:
simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation.
"""
def recurse(olItem, liste... | [
"def",
"getToC",
"(",
"doc",
",",
"simple",
"=",
"True",
")",
":",
"def",
"recurse",
"(",
"olItem",
",",
"liste",
",",
"lvl",
")",
":",
"'''Recursively follow the outline item chain and record item information in a list.'''",
"while",
"olItem",
":",
"if",
"olItem",
... | Create a table of contents.
Args:
simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation. | [
"Create",
"a",
"table",
"of",
"contents",
"."
] | python | train |
praekelt/panya | panya/view_modifiers/items.py | https://github.com/praekelt/panya/blob/0fd621e15a7c11a2716a9554a2f820d6259818e5/panya/view_modifiers/items.py#L33-L38 | def modify(self, view):
"""
adds the get item as extra context
"""
view.params['extra_context'][self.get['name']] = self.get['value']
return view | [
"def",
"modify",
"(",
"self",
",",
"view",
")",
":",
"view",
".",
"params",
"[",
"'extra_context'",
"]",
"[",
"self",
".",
"get",
"[",
"'name'",
"]",
"]",
"=",
"self",
".",
"get",
"[",
"'value'",
"]",
"return",
"view"
] | adds the get item as extra context | [
"adds",
"the",
"get",
"item",
"as",
"extra",
"context"
] | python | train |
axltxl/m2bk | m2bk/config.py | https://github.com/axltxl/m2bk/blob/980083dfd17e6e783753a946e9aa809714551141/m2bk/config.py#L62-L72 | def set_entry(key, value):
"""
Set a configuration entry
:param key: key name
:param value: value for this key
:raises KeyError: if key is not str
"""
if type(key) != str:
raise KeyError('key must be str')
_config[key] = value | [
"def",
"set_entry",
"(",
"key",
",",
"value",
")",
":",
"if",
"type",
"(",
"key",
")",
"!=",
"str",
":",
"raise",
"KeyError",
"(",
"'key must be str'",
")",
"_config",
"[",
"key",
"]",
"=",
"value"
] | Set a configuration entry
:param key: key name
:param value: value for this key
:raises KeyError: if key is not str | [
"Set",
"a",
"configuration",
"entry"
] | python | train |
ARMmbed/mbed-connector-api-python | mbed_connector_api/mbed_connector_api.py | https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L688-L715 | def debug(self,onOff,level='DEBUG'):
'''
Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none
'''
if onOff:
if level == 'DEBUG':
self.log.setLevel(logging.DEBUG)
self._ch.setLevel(logging.DEBUG)
self.log.debug("Debugging level DEBUG enabled")
elif level =... | [
"def",
"debug",
"(",
"self",
",",
"onOff",
",",
"level",
"=",
"'DEBUG'",
")",
":",
"if",
"onOff",
":",
"if",
"level",
"==",
"'DEBUG'",
":",
"self",
".",
"log",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"self",
".",
"_ch",
".",
"setLevel",... | Enable / Disable debugging
:param bool onOff: turn debugging on / off
:return: none | [
"Enable",
"/",
"Disable",
"debugging",
":",
"param",
"bool",
"onOff",
":",
"turn",
"debugging",
"on",
"/",
"off",
":",
"return",
":",
"none"
] | python | train |
apache/incubator-mxnet | python/mxnet/rtc.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/rtc.py#L112-L171 | def get_kernel(self, name, signature):
r"""Get CUDA kernel from compiled module.
Parameters
----------
name : str
String name of the kernel.
signature : str
Function signature for the kernel. For example, if a kernel is
declared as::
... | [
"def",
"get_kernel",
"(",
"self",
",",
"name",
",",
"signature",
")",
":",
"hdl",
"=",
"CudaKernelHandle",
"(",
")",
"is_ndarray",
"=",
"[",
"]",
"is_const",
"=",
"[",
"]",
"dtypes",
"=",
"[",
"]",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r\"\"\"^... | r"""Get CUDA kernel from compiled module.
Parameters
----------
name : str
String name of the kernel.
signature : str
Function signature for the kernel. For example, if a kernel is
declared as::
extern "C" __global__ void axpy(const f... | [
"r",
"Get",
"CUDA",
"kernel",
"from",
"compiled",
"module",
"."
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_system_monitor_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_system_monitor_ext.py#L81-L93 | def show_system_monitor_output_switch_status_switch_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_system_monitor = ET.Element("show_system_monitor")
config = show_system_monitor
output = ET.SubElement(show_system_monitor, "output")
... | [
"def",
"show_system_monitor_output_switch_status_switch_state",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_system_monitor",
"=",
"ET",
".",
"Element",
"(",
"\"show_system_monitor\"",
")",
"con... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
wummel/dosage | dosagelib/util.py | https://github.com/wummel/dosage/blob/a0109c3a46219f280e6e5e77183674e40da0f304/dosagelib/util.py#L132-L163 | def tagre(tag, attribute, value, quote='"', before="", after=""):
"""Return a regular expression matching the given HTML tag, attribute
and value. It matches the tag and attribute names case insensitive,
and skips arbitrary whitespace and leading HTML attributes. The "<>" at
the start and end of the HTM... | [
"def",
"tagre",
"(",
"tag",
",",
"attribute",
",",
"value",
",",
"quote",
"=",
"'\"'",
",",
"before",
"=",
"\"\"",
",",
"after",
"=",
"\"\"",
")",
":",
"if",
"before",
":",
"prefix",
"=",
"r\"[^>]*%s[^>]*\\s+\"",
"%",
"before",
"else",
":",
"prefix",
... | Return a regular expression matching the given HTML tag, attribute
and value. It matches the tag and attribute names case insensitive,
and skips arbitrary whitespace and leading HTML attributes. The "<>" at
the start and end of the HTML tag is also matched.
@param tag: the tag name
@ptype tag: strin... | [
"Return",
"a",
"regular",
"expression",
"matching",
"the",
"given",
"HTML",
"tag",
"attribute",
"and",
"value",
".",
"It",
"matches",
"the",
"tag",
"and",
"attribute",
"names",
"case",
"insensitive",
"and",
"skips",
"arbitrary",
"whitespace",
"and",
"leading",
... | python | train |
tensorlayer/tensorlayer | examples/data_process/tutorial_fast_affine_transform.py | https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/examples/data_process/tutorial_fast_affine_transform.py#L52-L59 | def example2():
""" Example 2: Applying all transforms in one is very FAST ! """
st = time.time()
for _ in range(100): # Repeat 100 times and compute the averaged speed
transform_matrix = create_transformation_matrix()
result = tl.prepro.affine_transform_cv2(image, transform_matrix) # Tran... | [
"def",
"example2",
"(",
")",
":",
"st",
"=",
"time",
".",
"time",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"100",
")",
":",
"# Repeat 100 times and compute the averaged speed",
"transform_matrix",
"=",
"create_transformation_matrix",
"(",
")",
"result",
"=",
... | Example 2: Applying all transforms in one is very FAST ! | [
"Example",
"2",
":",
"Applying",
"all",
"transforms",
"in",
"one",
"is",
"very",
"FAST",
"!"
] | python | valid |
chaoss/grimoirelab-perceval | perceval/archive.py | https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/archive.py#L285-L302 | def _verify_archive(self):
"""Check whether the archive is valid or not.
This method will check if tables were created and if they
contain valid data.
"""
nentries = self._count_table_rows(self.ARCHIVE_TABLE)
nmetadata = self._count_table_rows(self.METADATA_TABLE)
... | [
"def",
"_verify_archive",
"(",
"self",
")",
":",
"nentries",
"=",
"self",
".",
"_count_table_rows",
"(",
"self",
".",
"ARCHIVE_TABLE",
")",
"nmetadata",
"=",
"self",
".",
"_count_table_rows",
"(",
"self",
".",
"METADATA_TABLE",
")",
"if",
"nmetadata",
">",
"... | Check whether the archive is valid or not.
This method will check if tables were created and if they
contain valid data. | [
"Check",
"whether",
"the",
"archive",
"is",
"valid",
"or",
"not",
"."
] | python | test |
RaRe-Technologies/smart_open | smart_open/smart_open_lib.py | https://github.com/RaRe-Technologies/smart_open/blob/2dc8d60f223fc7b00a2000c56362a7bd6cd0850e/smart_open/smart_open_lib.py#L504-L568 | def _open_binary_stream(uri, mode, transport_params):
"""Open an arbitrary URI in the specified binary mode.
Not all modes are supported for all protocols.
:arg uri: The URI to open. May be a string, or something else.
:arg str mode: The mode to open with. Must be rb, wb or ab.
:arg transport_pa... | [
"def",
"_open_binary_stream",
"(",
"uri",
",",
"mode",
",",
"transport_params",
")",
":",
"if",
"mode",
"not",
"in",
"(",
"'rb'",
",",
"'rb+'",
",",
"'wb'",
",",
"'wb+'",
",",
"'ab'",
",",
"'ab+'",
")",
":",
"#",
"# This should really be a ValueError, but fo... | Open an arbitrary URI in the specified binary mode.
Not all modes are supported for all protocols.
:arg uri: The URI to open. May be a string, or something else.
:arg str mode: The mode to open with. Must be rb, wb or ab.
:arg transport_params: Keyword argumens for the transport layer.
:returns:... | [
"Open",
"an",
"arbitrary",
"URI",
"in",
"the",
"specified",
"binary",
"mode",
"."
] | python | train |
HazyResearch/fonduer | src/fonduer/utils/data_model_utils/visual.py | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/data_model_utils/visual.py#L285-L326 | def get_page_vert_percentile(
mention, page_width=DEFAULT_WIDTH, page_height=DEFAULT_HEIGHT
):
"""Return which percentile from the TOP in the page the Mention is located in.
Percentile is calculated where the top of the page is 0.0, and the bottom
of the page is 1.0. For example, a Mention in at the to... | [
"def",
"get_page_vert_percentile",
"(",
"mention",
",",
"page_width",
"=",
"DEFAULT_WIDTH",
",",
"page_height",
"=",
"DEFAULT_HEIGHT",
")",
":",
"span",
"=",
"_to_span",
"(",
"mention",
")",
"return",
"bbox_from_span",
"(",
"span",
")",
".",
"top",
"/",
"page_... | Return which percentile from the TOP in the page the Mention is located in.
Percentile is calculated where the top of the page is 0.0, and the bottom
of the page is 1.0. For example, a Mention in at the top 1/4 of the page
will have a percentile of 0.25.
Page width and height are based on pt values::
... | [
"Return",
"which",
"percentile",
"from",
"the",
"TOP",
"in",
"the",
"page",
"the",
"Mention",
"is",
"located",
"in",
"."
] | python | train |
astropy/photutils | photutils/detection/core.py | https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/detection/core.py#L18-L126 | def detect_threshold(data, snr, background=None, error=None, mask=None,
mask_value=None, sigclip_sigma=3.0, sigclip_iters=None):
"""
Calculate a pixel-wise threshold image that can be used to detect
sources.
Parameters
----------
data : array_like
The 2D array of th... | [
"def",
"detect_threshold",
"(",
"data",
",",
"snr",
",",
"background",
"=",
"None",
",",
"error",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"mask_value",
"=",
"None",
",",
"sigclip_sigma",
"=",
"3.0",
",",
"sigclip_iters",
"=",
"None",
")",
":",
"if"... | Calculate a pixel-wise threshold image that can be used to detect
sources.
Parameters
----------
data : array_like
The 2D array of the image.
snr : float
The signal-to-noise ratio per pixel above the ``background`` for
which to consider a pixel as possibly being part of a s... | [
"Calculate",
"a",
"pixel",
"-",
"wise",
"threshold",
"image",
"that",
"can",
"be",
"used",
"to",
"detect",
"sources",
"."
] | python | train |
BYU-PCCL/holodeck | holodeck/environments.py | https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/environments.py#L327-L333 | def teleport_camera(self, location, rotation):
"""Queue up a teleport camera command to stop the day cycle.
By the next tick, the camera's location and rotation will be updated
"""
self._should_write_to_command_buffer = True
command_to_send = TeleportCameraCommand(location, rotat... | [
"def",
"teleport_camera",
"(",
"self",
",",
"location",
",",
"rotation",
")",
":",
"self",
".",
"_should_write_to_command_buffer",
"=",
"True",
"command_to_send",
"=",
"TeleportCameraCommand",
"(",
"location",
",",
"rotation",
")",
"self",
".",
"_commands",
".",
... | Queue up a teleport camera command to stop the day cycle.
By the next tick, the camera's location and rotation will be updated | [
"Queue",
"up",
"a",
"teleport",
"camera",
"command",
"to",
"stop",
"the",
"day",
"cycle",
".",
"By",
"the",
"next",
"tick",
"the",
"camera",
"s",
"location",
"and",
"rotation",
"will",
"be",
"updated"
] | python | train |
juju/charm-helpers | charmhelpers/contrib/network/ufw.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ufw.py#L122-L151 | def enable(soft_fail=False):
"""
Enable ufw
:param soft_fail: If set to True silently disables IPv6 support in ufw,
otherwise a UFWIPv6Error exception is raised when IP6
support is broken.
:returns: True if ufw is successfully enabled
"""
if is_enable... | [
"def",
"enable",
"(",
"soft_fail",
"=",
"False",
")",
":",
"if",
"is_enabled",
"(",
")",
":",
"return",
"True",
"if",
"not",
"is_ipv6_ok",
"(",
"soft_fail",
")",
":",
"disable_ipv6",
"(",
")",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
... | Enable ufw
:param soft_fail: If set to True silently disables IPv6 support in ufw,
otherwise a UFWIPv6Error exception is raised when IP6
support is broken.
:returns: True if ufw is successfully enabled | [
"Enable",
"ufw"
] | python | train |
thespacedoctor/sherlock | sherlock/transient_classifier.py | https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/transient_classifier.py#L1613-L1823 | def _create_tables_if_not_exist(
self):
"""*create the sherlock helper tables if they don't yet exist*
**Key Arguments:**
# -
**Return:**
- None
**Usage:**
.. todo::
- add usage info
- create a sublime s... | [
"def",
"_create_tables_if_not_exist",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_create_tables_if_not_exist`` method'",
")",
"transientTable",
"=",
"self",
".",
"settings",
"[",
"\"database settings\"",
"]",
"[",
"\"transients\"",
... | *create the sherlock helper tables if they don't yet exist*
**Key Arguments:**
# -
**Return:**
- None
**Usage:**
.. todo::
- add usage info
- create a sublime snippet for usage
- write a command-line tool fo... | [
"*",
"create",
"the",
"sherlock",
"helper",
"tables",
"if",
"they",
"don",
"t",
"yet",
"exist",
"*"
] | python | train |
CyberReboot/vent | vent/menus/main.py | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/main.py#L68-L72 | def add_form(self, form, form_name, form_args):
""" Add new form and switch to it """
self.parentApp.addForm(form_name, form, **form_args)
self.parentApp.change_form(form_name)
return | [
"def",
"add_form",
"(",
"self",
",",
"form",
",",
"form_name",
",",
"form_args",
")",
":",
"self",
".",
"parentApp",
".",
"addForm",
"(",
"form_name",
",",
"form",
",",
"*",
"*",
"form_args",
")",
"self",
".",
"parentApp",
".",
"change_form",
"(",
"for... | Add new form and switch to it | [
"Add",
"new",
"form",
"and",
"switch",
"to",
"it"
] | python | train |
woolfson-group/isambard | isambard/ampal/interactions.py | https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/interactions.py#L264-L293 | def generate_bond_subgraphs_from_break(bond_graph, atom1, atom2):
"""Splits the bond graph between two atoms to producing subgraphs.
Notes
-----
This will not work if there are cycles in the bond graph.
Parameters
----------
bond_graph: networkx.Graph
Graph of covalent bond network... | [
"def",
"generate_bond_subgraphs_from_break",
"(",
"bond_graph",
",",
"atom1",
",",
"atom2",
")",
":",
"bond_graph",
".",
"remove_edge",
"(",
"atom1",
",",
"atom2",
")",
"try",
":",
"subgraphs",
"=",
"list",
"(",
"networkx",
".",
"connected_component_subgraphs",
... | Splits the bond graph between two atoms to producing subgraphs.
Notes
-----
This will not work if there are cycles in the bond graph.
Parameters
----------
bond_graph: networkx.Graph
Graph of covalent bond network
atom1: isambard.ampal.Atom
First atom in the bond.
atom2... | [
"Splits",
"the",
"bond",
"graph",
"between",
"two",
"atoms",
"to",
"producing",
"subgraphs",
"."
] | python | train |
JIC-CSB/jicimagelib | jicimagelib/image.py | https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/image.py#L186-L208 | def parse_manifest(self, fpath):
"""Parse manifest file to build up the collection of images.
:param fpath: path to the manifest file
"""
with open(fpath, 'r') as fh:
for entry in json.load(fh):
# Every entry of a manifest file needs to have a "filen... | [
"def",
"parse_manifest",
"(",
"self",
",",
"fpath",
")",
":",
"with",
"open",
"(",
"fpath",
",",
"'r'",
")",
"as",
"fh",
":",
"for",
"entry",
"in",
"json",
".",
"load",
"(",
"fh",
")",
":",
"# Every entry of a manifest file needs to have a \"filename\"",
"# ... | Parse manifest file to build up the collection of images.
:param fpath: path to the manifest file | [
"Parse",
"manifest",
"file",
"to",
"build",
"up",
"the",
"collection",
"of",
"images",
".",
":",
"param",
"fpath",
":",
"path",
"to",
"the",
"manifest",
"file"
] | python | train |
twilio/twilio-python | twilio/rest/api/v2010/account/call/__init__.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/call/__init__.py#L297-L309 | def feedback_summaries(self):
"""
Access the feedback_summaries
:returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList
:rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList
"""
if self._feedback_summaries is None:
... | [
"def",
"feedback_summaries",
"(",
"self",
")",
":",
"if",
"self",
".",
"_feedback_summaries",
"is",
"None",
":",
"self",
".",
"_feedback_summaries",
"=",
"FeedbackSummaryList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[... | Access the feedback_summaries
:returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList
:rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList | [
"Access",
"the",
"feedback_summaries"
] | python | train |
numenta/htmresearch | projects/sequence_prediction/discrete_sequences/lstm/suite.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/sequence_prediction/discrete_sequences/lstm/suite.py#L263-L320 | def killCells(self, killCellPercent):
"""
kill a fraction of LSTM cells from the network
:param killCellPercent:
:return:
"""
if killCellPercent <= 0:
return
inputLayer = self.net['in']
lstmLayer = self.net['hidden0']
numLSTMCell = lstmLayer.outdim
numDead = round(killCel... | [
"def",
"killCells",
"(",
"self",
",",
"killCellPercent",
")",
":",
"if",
"killCellPercent",
"<=",
"0",
":",
"return",
"inputLayer",
"=",
"self",
".",
"net",
"[",
"'in'",
"]",
"lstmLayer",
"=",
"self",
".",
"net",
"[",
"'hidden0'",
"]",
"numLSTMCell",
"="... | kill a fraction of LSTM cells from the network
:param killCellPercent:
:return: | [
"kill",
"a",
"fraction",
"of",
"LSTM",
"cells",
"from",
"the",
"network",
":",
"param",
"killCellPercent",
":",
":",
"return",
":"
] | python | train |
saltstack/salt | salt/modules/aptpkg.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1464-L1469 | def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps | [
"def",
"_split_repo_str",
"(",
"repo",
")",
":",
"split",
"=",
"sourceslist",
".",
"SourceEntry",
"(",
"repo",
")",
"return",
"split",
".",
"type",
",",
"split",
".",
"architectures",
",",
"split",
".",
"uri",
",",
"split",
".",
"dist",
",",
"split",
"... | Return APT source entry as a tuple. | [
"Return",
"APT",
"source",
"entry",
"as",
"a",
"tuple",
"."
] | python | train |
HewlettPackard/python-hpOneView | hpOneView/resources/task_monitor.py | https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/task_monitor.py#L225-L261 | def get_associated_resource(self, task):
"""
Retrieve a resource associated with a task.
Args:
task: task dict
Returns:
tuple: task (updated), the entity found (dict)
"""
if not task:
raise HPOneViewUnknownType(MSG_INVALID_TASK)
... | [
"def",
"get_associated_resource",
"(",
"self",
",",
"task",
")",
":",
"if",
"not",
"task",
":",
"raise",
"HPOneViewUnknownType",
"(",
"MSG_INVALID_TASK",
")",
"if",
"task",
"[",
"'category'",
"]",
"!=",
"'tasks'",
"and",
"task",
"[",
"'category'",
"]",
"!=",... | Retrieve a resource associated with a task.
Args:
task: task dict
Returns:
tuple: task (updated), the entity found (dict) | [
"Retrieve",
"a",
"resource",
"associated",
"with",
"a",
"task",
"."
] | python | train |
django-extensions/django-extensions | django_extensions/templatetags/widont.py | https://github.com/django-extensions/django-extensions/blob/7e0bef97ea6cb7f9eea5e2528e3a985a83a7b9b8/django_extensions/templatetags/widont.py#L15-L35 | def widont(value, count=1):
"""
Add an HTML non-breaking space between the final two words of the string to
avoid "widowed" words.
Examples:
>>> print(widont('Test me out'))
Test me out
>>> print("'",widont('It works with trailing spaces too '), "'")
' It works with traili... | [
"def",
"widont",
"(",
"value",
",",
"count",
"=",
"1",
")",
":",
"def",
"replace",
"(",
"matchobj",
")",
":",
"return",
"force_text",
"(",
"' %s'",
"%",
"matchobj",
".",
"group",
"(",
"1",
")",
")",
"for",
"i",
"in",
"range",
"(",
"count",
")"... | Add an HTML non-breaking space between the final two words of the string to
avoid "widowed" words.
Examples:
>>> print(widont('Test me out'))
Test me out
>>> print("'",widont('It works with trailing spaces too '), "'")
' It works with trailing spaces too '
>>> print(wi... | [
"Add",
"an",
"HTML",
"non",
"-",
"breaking",
"space",
"between",
"the",
"final",
"two",
"words",
"of",
"the",
"string",
"to",
"avoid",
"widowed",
"words",
"."
] | python | train |
althonos/moclo | moclo/moclo/core/vectors.py | https://github.com/althonos/moclo/blob/28a03748df8a2fa43f0c0c8098ca64d11559434e/moclo/moclo/core/vectors.py#L39-L60 | def structure(cls):
# type: () -> Text
"""Get the vector structure, as a DNA regex pattern.
Warning:
If overloading this method, the returned pattern must include 3
capture groups to capture the following features:
1. The downstream (3') overhang sequence
... | [
"def",
"structure",
"(",
"cls",
")",
":",
"# type: () -> Text",
"downstream",
"=",
"cls",
".",
"cutter",
".",
"elucidate",
"(",
")",
"upstream",
"=",
"str",
"(",
"Seq",
"(",
"downstream",
")",
".",
"reverse_complement",
"(",
")",
")",
"return",
"\"\"",
"... | Get the vector structure, as a DNA regex pattern.
Warning:
If overloading this method, the returned pattern must include 3
capture groups to capture the following features:
1. The downstream (3') overhang sequence
2. The vector placeholder sequence
3... | [
"Get",
"the",
"vector",
"structure",
"as",
"a",
"DNA",
"regex",
"pattern",
"."
] | python | train |
DinoTools/python-overpy | overpy/__init__.py | https://github.com/DinoTools/python-overpy/blob/db8f80eeb1b4d1405816bd62c16ddb3364e0c46d/overpy/__init__.py#L1521-L1535 | def _handle_start_area(self, attrs):
"""
Handle opening area element
:param attrs: Attributes of the element
:type attrs: Dict
"""
self._curr = {
'attributes': dict(attrs),
'tags': {},
'area_id': None
}
if attrs.get('id... | [
"def",
"_handle_start_area",
"(",
"self",
",",
"attrs",
")",
":",
"self",
".",
"_curr",
"=",
"{",
"'attributes'",
":",
"dict",
"(",
"attrs",
")",
",",
"'tags'",
":",
"{",
"}",
",",
"'area_id'",
":",
"None",
"}",
"if",
"attrs",
".",
"get",
"(",
"'id... | Handle opening area element
:param attrs: Attributes of the element
:type attrs: Dict | [
"Handle",
"opening",
"area",
"element"
] | python | train |
sentinel-hub/eo-learn | features/eolearn/features/hog.py | https://github.com/sentinel-hub/eo-learn/blob/b8c390b9f553c561612fe9eb64e720611633a035/features/eolearn/features/hog.py#L80-L94 | def execute(self, eopatch):
""" Execute computation of HoG features on input eopatch
:param eopatch: Input eopatch
:type eopatch: eolearn.core.EOPatch
:return: EOPatch instance with new keys holding the HoG features and HoG image for visualisation.
:rtype: eolear... | [
"def",
"execute",
"(",
"self",
",",
"eopatch",
")",
":",
"for",
"feature_type",
",",
"feature_name",
",",
"new_feature_name",
"in",
"self",
".",
"feature",
":",
"result",
"=",
"self",
".",
"_compute_hog",
"(",
"eopatch",
"[",
"feature_type",
"]",
"[",
"fea... | Execute computation of HoG features on input eopatch
:param eopatch: Input eopatch
:type eopatch: eolearn.core.EOPatch
:return: EOPatch instance with new keys holding the HoG features and HoG image for visualisation.
:rtype: eolearn.core.EOPatch | [
"Execute",
"computation",
"of",
"HoG",
"features",
"on",
"input",
"eopatch"
] | python | train |
fastai/fastai | fastai/vision/transform.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/transform.py#L15-L17 | def _brightness(x, change:uniform):
"Apply `change` in brightness of image `x`."
return x.add_(scipy.special.logit(change)) | [
"def",
"_brightness",
"(",
"x",
",",
"change",
":",
"uniform",
")",
":",
"return",
"x",
".",
"add_",
"(",
"scipy",
".",
"special",
".",
"logit",
"(",
"change",
")",
")"
] | Apply `change` in brightness of image `x`. | [
"Apply",
"change",
"in",
"brightness",
"of",
"image",
"x",
"."
] | python | train |
allenai/allennlp | allennlp/state_machines/transition_functions/basic_transition_function.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/transition_functions/basic_transition_function.py#L393-L412 | def attend_on_question(self,
query: torch.Tensor,
encoder_outputs: torch.Tensor,
encoder_output_mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Given a query (which is typically the decoder hidden state), comp... | [
"def",
"attend_on_question",
"(",
"self",
",",
"query",
":",
"torch",
".",
"Tensor",
",",
"encoder_outputs",
":",
"torch",
".",
"Tensor",
",",
"encoder_output_mask",
":",
"torch",
".",
"Tensor",
")",
"->",
"Tuple",
"[",
"torch",
".",
"Tensor",
",",
"torch"... | Given a query (which is typically the decoder hidden state), compute an attention over the
output of the question encoder, and return a weighted sum of the question representations
given this attention. We also return the attention weights themselves.
This is a simple computation, but we have ... | [
"Given",
"a",
"query",
"(",
"which",
"is",
"typically",
"the",
"decoder",
"hidden",
"state",
")",
"compute",
"an",
"attention",
"over",
"the",
"output",
"of",
"the",
"question",
"encoder",
"and",
"return",
"a",
"weighted",
"sum",
"of",
"the",
"question",
"... | python | train |
pyviz/holoviews | holoviews/core/spaces.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/spaces.py#L962-L978 | def unbounded(self):
"""
Returns a list of key dimensions that are unbounded, excluding
stream parameters. If any of theses key dimensions are
unbounded, the DynamicMap as a whole is also unbounded.
"""
unbounded_dims = []
# Dimensioned streams do not need to be b... | [
"def",
"unbounded",
"(",
"self",
")",
":",
"unbounded_dims",
"=",
"[",
"]",
"# Dimensioned streams do not need to be bounded",
"stream_params",
"=",
"set",
"(",
"util",
".",
"stream_parameters",
"(",
"self",
".",
"streams",
")",
")",
"for",
"kdim",
"in",
"self",... | Returns a list of key dimensions that are unbounded, excluding
stream parameters. If any of theses key dimensions are
unbounded, the DynamicMap as a whole is also unbounded. | [
"Returns",
"a",
"list",
"of",
"key",
"dimensions",
"that",
"are",
"unbounded",
"excluding",
"stream",
"parameters",
".",
"If",
"any",
"of",
"theses",
"key",
"dimensions",
"are",
"unbounded",
"the",
"DynamicMap",
"as",
"a",
"whole",
"is",
"also",
"unbounded",
... | python | train |
singularityhub/singularity-cli | spython/oci/cmd/actions.py | https://github.com/singularityhub/singularity-cli/blob/cb36b4504812ca87e29c6a40b222a545d1865799/spython/oci/cmd/actions.py#L40-L75 | def create(self, bundle,
container_id=None,
empty_process=False,
log_path=None,
pid_file=None,
sync_socket=None,
log_format="kubernetes"):
''' use the client to create a container from a bundle directory. The bun... | [
"def",
"create",
"(",
"self",
",",
"bundle",
",",
"container_id",
"=",
"None",
",",
"empty_process",
"=",
"False",
",",
"log_path",
"=",
"None",
",",
"pid_file",
"=",
"None",
",",
"sync_socket",
"=",
"None",
",",
"log_format",
"=",
"\"kubernetes\"",
")",
... | use the client to create a container from a bundle directory. The bundle
directory should have a config.json. You must be the root user to
create a runtime.
Equivalent command line example:
singularity oci create [create options...] <container_ID>
Parameters
==... | [
"use",
"the",
"client",
"to",
"create",
"a",
"container",
"from",
"a",
"bundle",
"directory",
".",
"The",
"bundle",
"directory",
"should",
"have",
"a",
"config",
".",
"json",
".",
"You",
"must",
"be",
"the",
"root",
"user",
"to",
"create",
"a",
"runtime"... | python | train |
ergo/ziggurat_foundations | ziggurat_foundations/models/services/resource_tree.py | https://github.com/ergo/ziggurat_foundations/blob/9eeec894d08e8d7defa60ddc04b63f69cd4cbeba/ziggurat_foundations/models/services/resource_tree.py#L125-L143 | def shift_ordering_down(
self, parent_id, position, db_session=None, *args, **kwargs
):
"""
Shifts ordering to "close gaps" after node deletion or being moved
to another branch, begins the shift from given position
:param parent_id:
:param position:
:param db... | [
"def",
"shift_ordering_down",
"(",
"self",
",",
"parent_id",
",",
"position",
",",
"db_session",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"service",
".",
"shift_ordering_down",
"(",
"parent_id",
"=",
"parent_... | Shifts ordering to "close gaps" after node deletion or being moved
to another branch, begins the shift from given position
:param parent_id:
:param position:
:param db_session:
:return: | [
"Shifts",
"ordering",
"to",
"close",
"gaps",
"after",
"node",
"deletion",
"or",
"being",
"moved",
"to",
"another",
"branch",
"begins",
"the",
"shift",
"from",
"given",
"position"
] | python | train |
georgemarshall/django-cryptography | django_cryptography/utils/crypto.py | https://github.com/georgemarshall/django-cryptography/blob/4c5f60fec98bcf71495d6084f801ea9c01c9a725/django_cryptography/utils/crypto.py#L21-L56 | def salted_hmac(key_salt, value, secret=None):
"""
Returns the HMAC-HASH of 'value', using a key generated from key_salt and a
secret (which defaults to settings.SECRET_KEY).
A different key_salt should be passed in for every application of HMAC.
:type key_salt: any
:type value: any
:type ... | [
"def",
"salted_hmac",
"(",
"key_salt",
",",
"value",
",",
"secret",
"=",
"None",
")",
":",
"if",
"secret",
"is",
"None",
":",
"secret",
"=",
"settings",
".",
"SECRET_KEY",
"key_salt",
"=",
"force_bytes",
"(",
"key_salt",
")",
"secret",
"=",
"force_bytes",
... | Returns the HMAC-HASH of 'value', using a key generated from key_salt and a
secret (which defaults to settings.SECRET_KEY).
A different key_salt should be passed in for every application of HMAC.
:type key_salt: any
:type value: any
:type secret: any
:rtype: HMAC | [
"Returns",
"the",
"HMAC",
"-",
"HASH",
"of",
"value",
"using",
"a",
"key",
"generated",
"from",
"key_salt",
"and",
"a",
"secret",
"(",
"which",
"defaults",
"to",
"settings",
".",
"SECRET_KEY",
")",
"."
] | python | valid |
PSPC-SPAC-buyandsell/von_anchor | von_anchor/cache.py | https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/cache.py#L169-L179 | def schemata(self) -> list:
"""
Return list with schemata in cache.
:return: list of schemata
"""
LOGGER.debug('SchemaCache.schemata >>>')
LOGGER.debug('SchemaCache.schemata <<<')
return [self._schema_key2schema[seq_no] for seq_no in self._schema_key2schema] | [
"def",
"schemata",
"(",
"self",
")",
"->",
"list",
":",
"LOGGER",
".",
"debug",
"(",
"'SchemaCache.schemata >>>'",
")",
"LOGGER",
".",
"debug",
"(",
"'SchemaCache.schemata <<<'",
")",
"return",
"[",
"self",
".",
"_schema_key2schema",
"[",
"seq_no",
"]",
"for",... | Return list with schemata in cache.
:return: list of schemata | [
"Return",
"list",
"with",
"schemata",
"in",
"cache",
"."
] | python | train |
googledatalab/pydatalab | google/datalab/ml/_summary.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_summary.py#L44-L62 | def _glob_events_files(self, paths, recursive):
"""Find all tf events files under a list of paths recursively. """
event_files = []
for path in paths:
dirs = tf.gfile.Glob(path)
dirs = filter(lambda x: tf.gfile.IsDirectory(x), dirs)
for dir in dirs:
if recursive:
dir_fil... | [
"def",
"_glob_events_files",
"(",
"self",
",",
"paths",
",",
"recursive",
")",
":",
"event_files",
"=",
"[",
"]",
"for",
"path",
"in",
"paths",
":",
"dirs",
"=",
"tf",
".",
"gfile",
".",
"Glob",
"(",
"path",
")",
"dirs",
"=",
"filter",
"(",
"lambda",... | Find all tf events files under a list of paths recursively. | [
"Find",
"all",
"tf",
"events",
"files",
"under",
"a",
"list",
"of",
"paths",
"recursively",
"."
] | python | train |
ella/ella | ella/core/cache/utils.py | https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/cache/utils.py#L70-L107 | def get_cached_object(model, timeout=CACHE_TIMEOUT, **kwargs):
"""
Return a cached object. If the object does not exist in the cache, create it.
Params:
model - ContentType instance representing the model's class or the model class itself
timeout - TTL for the item in cache, defaults to CAC... | [
"def",
"get_cached_object",
"(",
"model",
",",
"timeout",
"=",
"CACHE_TIMEOUT",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"ContentType",
")",
":",
"model_ct",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
... | Return a cached object. If the object does not exist in the cache, create it.
Params:
model - ContentType instance representing the model's class or the model class itself
timeout - TTL for the item in cache, defaults to CACHE_TIMEOUT
**kwargs - lookup parameters for content_type.get_object... | [
"Return",
"a",
"cached",
"object",
".",
"If",
"the",
"object",
"does",
"not",
"exist",
"in",
"the",
"cache",
"create",
"it",
"."
] | python | train |
mitsei/dlkit | dlkit/authz_adapter/osid/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/authz_adapter/osid/sessions.py#L52-L72 | def _can(self, func_name, qualifier_id=None):
"""Tests if the named function is authorized with agent and qualifier.
Also, caches authz's in a dict. It is expected that this will not grow to big, as
there are typically only a small number of qualifier + function combinations to
store f... | [
"def",
"_can",
"(",
"self",
",",
"func_name",
",",
"qualifier_id",
"=",
"None",
")",
":",
"function_id",
"=",
"self",
".",
"_get_function_id",
"(",
"func_name",
")",
"if",
"qualifier_id",
"is",
"None",
":",
"qualifier_id",
"=",
"self",
".",
"_qualifier_id",
... | Tests if the named function is authorized with agent and qualifier.
Also, caches authz's in a dict. It is expected that this will not grow to big, as
there are typically only a small number of qualifier + function combinations to
store for the agent. However, if this becomes an issue, we can ... | [
"Tests",
"if",
"the",
"named",
"function",
"is",
"authorized",
"with",
"agent",
"and",
"qualifier",
"."
] | python | train |
kyuupichan/aiorpcX | aiorpcx/session.py | https://github.com/kyuupichan/aiorpcX/blob/707c989ed1c67ac9a40cd20b0161b1ce1f4d7db0/aiorpcx/session.py#L393-L414 | async def _throttled_message(self, message):
'''Process a single request, respecting the concurrency limit.'''
try:
timeout = self.processing_timeout
async with timeout_after(timeout):
async with self._incoming_concurrency:
if self._cost_fracti... | [
"async",
"def",
"_throttled_message",
"(",
"self",
",",
"message",
")",
":",
"try",
":",
"timeout",
"=",
"self",
".",
"processing_timeout",
"async",
"with",
"timeout_after",
"(",
"timeout",
")",
":",
"async",
"with",
"self",
".",
"_incoming_concurrency",
":",
... | Process a single request, respecting the concurrency limit. | [
"Process",
"a",
"single",
"request",
"respecting",
"the",
"concurrency",
"limit",
"."
] | python | train |
timothyb0912/pylogit | pylogit/choice_calcs.py | https://github.com/timothyb0912/pylogit/blob/f83b0fd6debaa7358d87c3828428f6d4ead71357/pylogit/choice_calcs.py#L492-L520 | def create_matrix_block_indices(row_to_obs):
"""
Parameters
----------
row_to_obs: 2D ndarray.
There should be one row per observation per available alternative and
one column per observation. This matrix maps the rows of the design
matrix to the unique observations (on the colum... | [
"def",
"create_matrix_block_indices",
"(",
"row_to_obs",
")",
":",
"# Initialize the list of index arrays to be returned",
"output_indices",
"=",
"[",
"]",
"# Determine the number of observations in the dataset",
"num_obs",
"=",
"row_to_obs",
".",
"shape",
"[",
"1",
"]",
"# G... | Parameters
----------
row_to_obs: 2D ndarray.
There should be one row per observation per available alternative and
one column per observation. This matrix maps the rows of the design
matrix to the unique observations (on the columns).
Returns
-------
output_indices : list o... | [
"Parameters",
"----------",
"row_to_obs",
":",
"2D",
"ndarray",
".",
"There",
"should",
"be",
"one",
"row",
"per",
"observation",
"per",
"available",
"alternative",
"and",
"one",
"column",
"per",
"observation",
".",
"This",
"matrix",
"maps",
"the",
"rows",
"of... | python | train |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L784-L803 | def distance(cls, q0, q1):
"""Quaternion intrinsic distance.
Find the intrinsic geodesic distance between q0 and q1.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive amount corresponding to the length of the geodesic arc... | [
"def",
"distance",
"(",
"cls",
",",
"q0",
",",
"q1",
")",
":",
"q",
"=",
"Quaternion",
".",
"log_map",
"(",
"q0",
",",
"q1",
")",
"return",
"q",
".",
"norm"
] | Quaternion intrinsic distance.
Find the intrinsic geodesic distance between q0 and q1.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive amount corresponding to the length of the geodesic arc
connecting q0 to q1.
... | [
"Quaternion",
"intrinsic",
"distance",
"."
] | python | train |
its-rigs/Trolly | trolly/organisation.py | https://github.com/its-rigs/Trolly/blob/483dc94c352df40dc05ead31820b059b2545cf82/trolly/organisation.py#L38-L53 | def get_members(self, **query_params):
'''
Get all members attached to this organisation. Returns a list of
Member objects
Returns:
list(Member): The members attached to this organisation
'''
members = self.get_members_json(self.base_uri,
... | [
"def",
"get_members",
"(",
"self",
",",
"*",
"*",
"query_params",
")",
":",
"members",
"=",
"self",
".",
"get_members_json",
"(",
"self",
".",
"base_uri",
",",
"query_params",
"=",
"query_params",
")",
"members_list",
"=",
"[",
"]",
"for",
"member_json",
"... | Get all members attached to this organisation. Returns a list of
Member objects
Returns:
list(Member): The members attached to this organisation | [
"Get",
"all",
"members",
"attached",
"to",
"this",
"organisation",
".",
"Returns",
"a",
"list",
"of",
"Member",
"objects"
] | python | test |
DataONEorg/d1_python | lib_common/src/d1_common/types/exceptions.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/types/exceptions.py#L155-L186 | def create_exception_by_name(
name,
detailCode='0',
description='',
traceInformation=None,
identifier=None,
nodeId=None,
):
"""Create a DataONEException based object by name.
Args:
name: str
The type name of a DataONE Exception. E.g. NotFound.
If an unknown type n... | [
"def",
"create_exception_by_name",
"(",
"name",
",",
"detailCode",
"=",
"'0'",
",",
"description",
"=",
"''",
",",
"traceInformation",
"=",
"None",
",",
"identifier",
"=",
"None",
",",
"nodeId",
"=",
"None",
",",
")",
":",
"try",
":",
"dataone_exception",
... | Create a DataONEException based object by name.
Args:
name: str
The type name of a DataONE Exception. E.g. NotFound.
If an unknown type name is used, it is automatically set to ServiceFailure. As
the XML Schema for DataONE Exceptions does not restrict the type names, this
may... | [
"Create",
"a",
"DataONEException",
"based",
"object",
"by",
"name",
"."
] | python | train |
ssato/python-anyconfig | src/anyconfig/backend/base.py | https://github.com/ssato/python-anyconfig/blob/f2f4fb8d8e232aadea866c202e1dd7a5967e2877/src/anyconfig/backend/base.py#L328-L336 | def dump_to_path(self, cnf, filepath, **kwargs):
"""
Dump config 'cnf' to a file 'filepath'.
:param cnf: Configuration data to dump
:param filepath: Config file path
:param kwargs: optional keyword parameters to be sanitized :: dict
"""
_not_implemented(self, cnf... | [
"def",
"dump_to_path",
"(",
"self",
",",
"cnf",
",",
"filepath",
",",
"*",
"*",
"kwargs",
")",
":",
"_not_implemented",
"(",
"self",
",",
"cnf",
",",
"filepath",
",",
"*",
"*",
"kwargs",
")"
] | Dump config 'cnf' to a file 'filepath'.
:param cnf: Configuration data to dump
:param filepath: Config file path
:param kwargs: optional keyword parameters to be sanitized :: dict | [
"Dump",
"config",
"cnf",
"to",
"a",
"file",
"filepath",
"."
] | python | train |
modin-project/modin | modin/pandas/__init__.py | https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/__init__.py#L133-L168 | def initialize_ray():
"""Initializes ray based on environment variables and internal defaults."""
if threading.current_thread().name == "MainThread":
plasma_directory = None
object_store_memory = os.environ.get("MODIN_MEMORY", None)
if os.environ.get("MODIN_OUT_OF_CORE", "False").title()... | [
"def",
"initialize_ray",
"(",
")",
":",
"if",
"threading",
".",
"current_thread",
"(",
")",
".",
"name",
"==",
"\"MainThread\"",
":",
"plasma_directory",
"=",
"None",
"object_store_memory",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"MODIN_MEMORY\"",
",",
... | Initializes ray based on environment variables and internal defaults. | [
"Initializes",
"ray",
"based",
"on",
"environment",
"variables",
"and",
"internal",
"defaults",
"."
] | python | train |
hydpy-dev/hydpy | hydpy/models/dam/dam_model.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/dam/dam_model.py#L933-L999 | def calc_possibleremoterelieve_v1(self):
"""Calculate the highest possible water release that can be routed to
a remote location based on an artificial neural network describing the
relationship between possible release and water stage.
Required control parameter:
|WaterLevel2PossibleRemoteReliev... | [
"def",
"calc_possibleremoterelieve_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"aid",
"=",
"self",
".",
"sequences",
".",
"aid... | Calculate the highest possible water release that can be routed to
a remote location based on an artificial neural network describing the
relationship between possible release and water stage.
Required control parameter:
|WaterLevel2PossibleRemoteRelieve|
Required aide sequence:
|WaterLeve... | [
"Calculate",
"the",
"highest",
"possible",
"water",
"release",
"that",
"can",
"be",
"routed",
"to",
"a",
"remote",
"location",
"based",
"on",
"an",
"artificial",
"neural",
"network",
"describing",
"the",
"relationship",
"between",
"possible",
"release",
"and",
"... | python | train |
BernardFW/bernard | src/bernard/engine/request.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/engine/request.py#L229-L240 | async def get_locale(self) -> Text:
"""
Get the locale to use for this request. It's either the overridden
locale or the locale provided by the platform.
:return: Locale to use for this request
"""
if self._locale_override:
return self._locale_override
... | [
"async",
"def",
"get_locale",
"(",
"self",
")",
"->",
"Text",
":",
"if",
"self",
".",
"_locale_override",
":",
"return",
"self",
".",
"_locale_override",
"else",
":",
"return",
"await",
"self",
".",
"user",
".",
"get_locale",
"(",
")"
] | Get the locale to use for this request. It's either the overridden
locale or the locale provided by the platform.
:return: Locale to use for this request | [
"Get",
"the",
"locale",
"to",
"use",
"for",
"this",
"request",
".",
"It",
"s",
"either",
"the",
"overridden",
"locale",
"or",
"the",
"locale",
"provided",
"by",
"the",
"platform",
"."
] | python | train |
happyleavesaoc/python-fedexdeliverymanager | fedexdeliverymanager/__init__.py | https://github.com/happyleavesaoc/python-fedexdeliverymanager/blob/cff2f1104a86573569500d41e69be54b90b596c6/fedexdeliverymanager/__init__.py#L90-L123 | def get_packages(session):
"""Get packages."""
resp = session.post(TRACKING_URL, {
'data': json.dumps(SHIPMENT_LIST_REQUEST),
'action': SHIPMENT_LIST_ACTION,
'format': SHIPMENT_LIST_FORMAT,
'locale': session.auth.locale,
'version': 1
})
data = resp.json().get('Shi... | [
"def",
"get_packages",
"(",
"session",
")",
":",
"resp",
"=",
"session",
".",
"post",
"(",
"TRACKING_URL",
",",
"{",
"'data'",
":",
"json",
".",
"dumps",
"(",
"SHIPMENT_LIST_REQUEST",
")",
",",
"'action'",
":",
"SHIPMENT_LIST_ACTION",
",",
"'format'",
":",
... | Get packages. | [
"Get",
"packages",
"."
] | python | train |
prometheus/client_python | prometheus_client/metrics.py | https://github.com/prometheus/client_python/blob/31f5557e2e84ca4ffa9a03abf6e3f4d0c8b8c3eb/prometheus_client/metrics.py#L525-L531 | def observe(self, amount):
"""Observe the given amount."""
self._sum.inc(amount)
for i, bound in enumerate(self._upper_bounds):
if amount <= bound:
self._buckets[i].inc(1)
break | [
"def",
"observe",
"(",
"self",
",",
"amount",
")",
":",
"self",
".",
"_sum",
".",
"inc",
"(",
"amount",
")",
"for",
"i",
",",
"bound",
"in",
"enumerate",
"(",
"self",
".",
"_upper_bounds",
")",
":",
"if",
"amount",
"<=",
"bound",
":",
"self",
".",
... | Observe the given amount. | [
"Observe",
"the",
"given",
"amount",
"."
] | python | train |
ly0/baidupcsapi | baidupcsapi/api.py | https://github.com/ly0/baidupcsapi/blob/6f6feeef0767a75b3b968924727460eb09242d76/baidupcsapi/api.py#L1281-L1301 | def rename(self, rename_pair_list, **kwargs):
"""重命名
:param rename_pair_list: 需要重命名的文件(夹)pair (路径,新名称)列表,如[('/aa.txt','bb.txt')]
:type rename_pair_list: list
"""
foo = []
for path, newname in rename_pair_list:
foo.append({'path': path,
... | [
"def",
"rename",
"(",
"self",
",",
"rename_pair_list",
",",
"*",
"*",
"kwargs",
")",
":",
"foo",
"=",
"[",
"]",
"for",
"path",
",",
"newname",
"in",
"rename_pair_list",
":",
"foo",
".",
"append",
"(",
"{",
"'path'",
":",
"path",
",",
"'newname'",
":"... | 重命名
:param rename_pair_list: 需要重命名的文件(夹)pair (路径,新名称)列表,如[('/aa.txt','bb.txt')]
:type rename_pair_list: list | [
"重命名"
] | python | train |
SpamScope/mail-parser | mailparser/mailparser.py | https://github.com/SpamScope/mail-parser/blob/814b56d0b803feab9dea04f054b802ce138097e2/mailparser/mailparser.py#L586-L591 | def date_json(self):
"""
Return the JSON of date
"""
if self.date:
return json.dumps(self.date.isoformat(), ensure_ascii=False) | [
"def",
"date_json",
"(",
"self",
")",
":",
"if",
"self",
".",
"date",
":",
"return",
"json",
".",
"dumps",
"(",
"self",
".",
"date",
".",
"isoformat",
"(",
")",
",",
"ensure_ascii",
"=",
"False",
")"
] | Return the JSON of date | [
"Return",
"the",
"JSON",
"of",
"date"
] | python | train |
HumanCellAtlas/dcp-cli | hca/upload/lib/s3_agent.py | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/s3_agent.py#L16-L28 | def sizeof_fmt(num, suffix='B'):
"""
Adapted from https://stackoverflow.com/a/1094933
Re: precision - display enough decimals to show progress on a slow (<5 MB/s) Internet connection
"""
precision = {'': 0, 'Ki': 0, 'Mi': 0, 'Gi': 3, 'Ti': 6, 'Pi': 9, 'Ei': 12, 'Zi': 15}
for unit in ['', 'Ki', ... | [
"def",
"sizeof_fmt",
"(",
"num",
",",
"suffix",
"=",
"'B'",
")",
":",
"precision",
"=",
"{",
"''",
":",
"0",
",",
"'Ki'",
":",
"0",
",",
"'Mi'",
":",
"0",
",",
"'Gi'",
":",
"3",
",",
"'Ti'",
":",
"6",
",",
"'Pi'",
":",
"9",
",",
"'Ei'",
":"... | Adapted from https://stackoverflow.com/a/1094933
Re: precision - display enough decimals to show progress on a slow (<5 MB/s) Internet connection | [
"Adapted",
"from",
"https",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"1094933",
"Re",
":",
"precision",
"-",
"display",
"enough",
"decimals",
"to",
"show",
"progress",
"on",
"a",
"slow",
"(",
"<5",
"MB",
"/",
"s",
")",
"Internet",
"connec... | python | train |
OpenHydrology/floodestimation | floodestimation/analysis.py | https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L324-L346 | def _qmed_from_descriptors_1999(self, as_rural=False):
"""
Return QMED estimation based on FEH catchment descriptors, 1999 methodology.
Methodology source: FEH, Vol. 3, p. 14
:param as_rural: assume catchment is fully rural. Default: false.
:type as_rural: bool
:return:... | [
"def",
"_qmed_from_descriptors_1999",
"(",
"self",
",",
"as_rural",
"=",
"False",
")",
":",
"try",
":",
"qmed_rural",
"=",
"1.172",
"*",
"self",
".",
"catchment",
".",
"descriptors",
".",
"dtm_area",
"**",
"self",
".",
"_area_exponent",
"(",
")",
"*",
"(",... | Return QMED estimation based on FEH catchment descriptors, 1999 methodology.
Methodology source: FEH, Vol. 3, p. 14
:param as_rural: assume catchment is fully rural. Default: false.
:type as_rural: bool
:return: QMED in m³/s
:rtype: float | [
"Return",
"QMED",
"estimation",
"based",
"on",
"FEH",
"catchment",
"descriptors",
"1999",
"methodology",
"."
] | python | train |
basecrm/basecrm-python | basecrm/services.py | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L653-L666 | def list(self, **params):
"""
Retrieve all leads
Returns all leads available to the user, according to the parameters provided
:calls: ``get /leads``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which ... | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"leads",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/leads\"",
",",
"params",
"=",
"params",
")",
"return",
"leads"
] | Retrieve all leads
Returns all leads available to the user, according to the parameters provided
:calls: ``get /leads``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of Leads.
:rtype:... | [
"Retrieve",
"all",
"leads"
] | python | train |
jmgilman/Neolib | neolib/pyamf/amf3.py | https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/amf3.py#L1212-L1222 | def serialiseString(self, s):
"""
Writes a raw string to the stream.
@type s: C{str}
@param s: The string data to be encoded to the AMF3 data stream.
"""
if type(s) is unicode:
s = self.context.getBytesForString(s)
self.serialiseBytes(s) | [
"def",
"serialiseString",
"(",
"self",
",",
"s",
")",
":",
"if",
"type",
"(",
"s",
")",
"is",
"unicode",
":",
"s",
"=",
"self",
".",
"context",
".",
"getBytesForString",
"(",
"s",
")",
"self",
".",
"serialiseBytes",
"(",
"s",
")"
] | Writes a raw string to the stream.
@type s: C{str}
@param s: The string data to be encoded to the AMF3 data stream. | [
"Writes",
"a",
"raw",
"string",
"to",
"the",
"stream",
"."
] | python | train |
radjkarl/fancyTools | fancytools/pystructure/getMembers.py | https://github.com/radjkarl/fancyTools/blob/4c4d961003dc4ed6e46429a0c24f7e2bb52caa8b/fancytools/pystructure/getMembers.py#L11-L18 | def getAvailableClassesInModule(prooveModule):
"""
return a list of all classes in the given module
that dont begin with '_'
"""
l = tuple(x[1] for x in inspect.getmembers(prooveModule, inspect.isclass))
l = [x for x in l if x.__name__[0] != "_"]
return l | [
"def",
"getAvailableClassesInModule",
"(",
"prooveModule",
")",
":",
"l",
"=",
"tuple",
"(",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"inspect",
".",
"getmembers",
"(",
"prooveModule",
",",
"inspect",
".",
"isclass",
")",
")",
"l",
"=",
"[",
"x",
"for",
... | return a list of all classes in the given module
that dont begin with '_' | [
"return",
"a",
"list",
"of",
"all",
"classes",
"in",
"the",
"given",
"module",
"that",
"dont",
"begin",
"with",
"_"
] | python | train |
gpoulter/fablib | fablib.py | https://github.com/gpoulter/fablib/blob/5d14c4d998f79dd1aa3207063c3d06e30e3e2bf9/fablib.py#L19-L32 | def default_roles(*role_list):
"""Decorate task with these roles by default, but override with -R, -H"""
def selectively_attach(func):
"""Only decorate if nothing specified on command line"""
# pylint: disable=W0142
if not env.roles and not env.hosts:
return roles(*role_list)... | [
"def",
"default_roles",
"(",
"*",
"role_list",
")",
":",
"def",
"selectively_attach",
"(",
"func",
")",
":",
"\"\"\"Only decorate if nothing specified on command line\"\"\"",
"# pylint: disable=W0142",
"if",
"not",
"env",
".",
"roles",
"and",
"not",
"env",
".",
"hosts... | Decorate task with these roles by default, but override with -R, -H | [
"Decorate",
"task",
"with",
"these",
"roles",
"by",
"default",
"but",
"override",
"with",
"-",
"R",
"-",
"H"
] | python | train |
OpenGov/carpenter | carpenter/blocks/tableanalyzer.py | https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/tableanalyzer.py#L198-L223 | def _find_valid_block(self, table, worksheet, flags, units, used_cells, start_pos, end_pos):
'''
Searches for the next location where a valid block could reside and constructs the block
object representing that location.
'''
for row_index in range(len(table)):
if row_... | [
"def",
"_find_valid_block",
"(",
"self",
",",
"table",
",",
"worksheet",
",",
"flags",
",",
"units",
",",
"used_cells",
",",
"start_pos",
",",
"end_pos",
")",
":",
"for",
"row_index",
"in",
"range",
"(",
"len",
"(",
"table",
")",
")",
":",
"if",
"row_i... | Searches for the next location where a valid block could reside and constructs the block
object representing that location. | [
"Searches",
"for",
"the",
"next",
"location",
"where",
"a",
"valid",
"block",
"could",
"reside",
"and",
"constructs",
"the",
"block",
"object",
"representing",
"that",
"location",
"."
] | python | train |
dhhagan/py-opc | opc/__init__.py | https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L1041-L1103 | def read_histogram(self):
"""Read and reset the histogram. The expected return is a dictionary
containing the counts per bin, MToF for bins 1, 3, 5, and 7, temperature,
pressure, the sampling period, the checksum, PM1, PM2.5, and PM10.
**NOTE:** The sampling period for the OPCN1 seems t... | [
"def",
"read_histogram",
"(",
"self",
")",
":",
"resp",
"=",
"[",
"]",
"data",
"=",
"{",
"}",
"# command byte",
"command",
"=",
"0x30",
"# Send the command byte",
"self",
".",
"cnxn",
".",
"xfer",
"(",
"[",
"command",
"]",
")",
"# Wait 10 ms",
"sleep",
"... | Read and reset the histogram. The expected return is a dictionary
containing the counts per bin, MToF for bins 1, 3, 5, and 7, temperature,
pressure, the sampling period, the checksum, PM1, PM2.5, and PM10.
**NOTE:** The sampling period for the OPCN1 seems to be incorrect.
:returns: di... | [
"Read",
"and",
"reset",
"the",
"histogram",
".",
"The",
"expected",
"return",
"is",
"a",
"dictionary",
"containing",
"the",
"counts",
"per",
"bin",
"MToF",
"for",
"bins",
"1",
"3",
"5",
"and",
"7",
"temperature",
"pressure",
"the",
"sampling",
"period",
"t... | python | valid |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/visuals/transforms/_util.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/_util.py#L143-L164 | def get(self, path):
""" Get a transform from the cache that maps along *path*, which must
be a list of Transforms to apply in reverse order (last transform is
applied first).
Accessed items have their age reset to 0.
"""
key = tuple(map(id, path))
item = self._c... | [
"def",
"get",
"(",
"self",
",",
"path",
")",
":",
"key",
"=",
"tuple",
"(",
"map",
"(",
"id",
",",
"path",
")",
")",
"item",
"=",
"self",
".",
"_cache",
".",
"get",
"(",
"key",
",",
"None",
")",
"if",
"item",
"is",
"None",
":",
"logger",
".",... | Get a transform from the cache that maps along *path*, which must
be a list of Transforms to apply in reverse order (last transform is
applied first).
Accessed items have their age reset to 0. | [
"Get",
"a",
"transform",
"from",
"the",
"cache",
"that",
"maps",
"along",
"*",
"path",
"*",
"which",
"must",
"be",
"a",
"list",
"of",
"Transforms",
"to",
"apply",
"in",
"reverse",
"order",
"(",
"last",
"transform",
"is",
"applied",
"first",
")",
"."
] | python | train |
mongodb/mongo-python-driver | pymongo/collection.py | https://github.com/mongodb/mongo-python-driver/blob/c29c21449e3aae74154207058cf85fd94018d4cd/pymongo/collection.py#L1625-L1702 | def count_documents(self, filter, session=None, **kwargs):
"""Count the number of documents in this collection.
The :meth:`count_documents` method is supported in a transaction.
All optional parameters should be passed as keyword arguments
to this method. Valid options include:
... | [
"def",
"count_documents",
"(",
"self",
",",
"filter",
",",
"session",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"pipeline",
"=",
"[",
"{",
"'$match'",
":",
"filter",
"}",
"]",
"if",
"'skip'",
"in",
"kwargs",
":",
"pipeline",
".",
"append",
"(",... | Count the number of documents in this collection.
The :meth:`count_documents` method is supported in a transaction.
All optional parameters should be passed as keyword arguments
to this method. Valid options include:
- `skip` (int): The number of matching documents to skip before
... | [
"Count",
"the",
"number",
"of",
"documents",
"in",
"this",
"collection",
"."
] | python | train |
biosustain/optlang | optlang/interface.py | https://github.com/biosustain/optlang/blob/13673ac26f6b3ba37a2ef392489722c52e3c5ff1/optlang/interface.py#L229-L241 | def set_bounds(self, lb, ub):
"""
Change the lower and upper bounds of a variable.
"""
if lb is not None and ub is not None and lb > ub:
raise ValueError(
"The provided lower bound {} is larger than the provided upper bound {}".format(lb, ub)
)
... | [
"def",
"set_bounds",
"(",
"self",
",",
"lb",
",",
"ub",
")",
":",
"if",
"lb",
"is",
"not",
"None",
"and",
"ub",
"is",
"not",
"None",
"and",
"lb",
">",
"ub",
":",
"raise",
"ValueError",
"(",
"\"The provided lower bound {} is larger than the provided upper bound... | Change the lower and upper bounds of a variable. | [
"Change",
"the",
"lower",
"and",
"upper",
"bounds",
"of",
"a",
"variable",
"."
] | python | train |
AkihikoITOH/capybara | capybara/virtualenv/lib/python2.7/site-packages/setuptools/command/easy_install.py | https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/setuptools/command/easy_install.py#L758-L766 | def install_script(self, dist, script_name, script_text, dev_path=None):
"""Generate a legacy script wrapper and install it"""
spec = str(dist.as_requirement())
is_script = is_python_script(script_text, script_name)
if is_script:
script_text = (ScriptWriter.get_header(script... | [
"def",
"install_script",
"(",
"self",
",",
"dist",
",",
"script_name",
",",
"script_text",
",",
"dev_path",
"=",
"None",
")",
":",
"spec",
"=",
"str",
"(",
"dist",
".",
"as_requirement",
"(",
")",
")",
"is_script",
"=",
"is_python_script",
"(",
"script_tex... | Generate a legacy script wrapper and install it | [
"Generate",
"a",
"legacy",
"script",
"wrapper",
"and",
"install",
"it"
] | python | test |
eventbrite/eventbrite-sdk-python | eventbrite/access_methods.py | https://github.com/eventbrite/eventbrite-sdk-python/blob/f2e5dc5aa1aa3e45766de13f16fd65722163d91a/eventbrite/access_methods.py#L213-L222 | def get_event_questions(self, id, **data):
"""
GET /events/:id/questions/
Eventbrite allows event organizers to add custom questions that attendees fill
out upon registration. This endpoint can be helpful for determining what
custom information is collected and available per even... | [
"def",
"get_event_questions",
"(",
"self",
",",
"id",
",",
"*",
"*",
"data",
")",
":",
"return",
"self",
".",
"get",
"(",
"\"/events/{0}/questions/\"",
".",
"format",
"(",
"id",
")",
",",
"data",
"=",
"data",
")"
] | GET /events/:id/questions/
Eventbrite allows event organizers to add custom questions that attendees fill
out upon registration. This endpoint can be helpful for determining what
custom information is collected and available per event.
This endpoint will return :format:`question`. | [
"GET",
"/",
"events",
"/",
":",
"id",
"/",
"questions",
"/",
"Eventbrite",
"allows",
"event",
"organizers",
"to",
"add",
"custom",
"questions",
"that",
"attendees",
"fill",
"out",
"upon",
"registration",
".",
"This",
"endpoint",
"can",
"be",
"helpful",
"for"... | python | train |
pysathq/pysat | pysat/solvers.py | https://github.com/pysathq/pysat/blob/522742e8f2d4c6ac50ecd9087f7a346206774c67/pysat/solvers.py#L1046-L1052 | def conf_budget(self, budget):
"""
Set limit on the number of conflicts.
"""
if self.glucose:
pysolvers.glucose3_cbudget(self.glucose, budget) | [
"def",
"conf_budget",
"(",
"self",
",",
"budget",
")",
":",
"if",
"self",
".",
"glucose",
":",
"pysolvers",
".",
"glucose3_cbudget",
"(",
"self",
".",
"glucose",
",",
"budget",
")"
] | Set limit on the number of conflicts. | [
"Set",
"limit",
"on",
"the",
"number",
"of",
"conflicts",
"."
] | python | train |
limpyd/redis-limpyd-jobs | limpyd_jobs/models.py | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/models.py#L298-L372 | def add_job(cls, identifier, queue_name=None, priority=0, queue_model=None,
prepend=False, delayed_for=None, delayed_until=None,
**fields_if_new):
"""
Add a job to a queue.
If this job already exists, check it's current priority. If its higher
than the new... | [
"def",
"add_job",
"(",
"cls",
",",
"identifier",
",",
"queue_name",
"=",
"None",
",",
"priority",
"=",
"0",
",",
"queue_model",
"=",
"None",
",",
"prepend",
"=",
"False",
",",
"delayed_for",
"=",
"None",
",",
"delayed_until",
"=",
"None",
",",
"*",
"*"... | Add a job to a queue.
If this job already exists, check it's current priority. If its higher
than the new one, don't touch it, else move the job to the wanted queue.
Before setting/moving the job to the queue, check for a `delayed_for`
(int/foat/timedelta) or `delayed_until` (datetime) a... | [
"Add",
"a",
"job",
"to",
"a",
"queue",
".",
"If",
"this",
"job",
"already",
"exists",
"check",
"it",
"s",
"current",
"priority",
".",
"If",
"its",
"higher",
"than",
"the",
"new",
"one",
"don",
"t",
"touch",
"it",
"else",
"move",
"the",
"job",
"to",
... | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.