repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
klahnakoski/mo-times | mo_times/durations.py | https://github.com/klahnakoski/mo-times/blob/e64a720b9796e076adeb0d5773ec6915ca045b9d/mo_times/durations.py#L313-L338 | def _string2Duration(text):
"""
CONVERT SIMPLE <float><type> TO A DURATION OBJECT
"""
if text == "" or text == "zero":
return ZERO
amount, interval = re.match(r"([\d\.]*)(.*)", text).groups()
amount = int(amount) if amount else 1
if MILLI_VALUES[interval] == None:
from mo_l... | [
"def",
"_string2Duration",
"(",
"text",
")",
":",
"if",
"text",
"==",
"\"\"",
"or",
"text",
"==",
"\"zero\"",
":",
"return",
"ZERO",
"amount",
",",
"interval",
"=",
"re",
".",
"match",
"(",
"r\"([\\d\\.]*)(.*)\"",
",",
"text",
")",
".",
"groups",
"(",
... | CONVERT SIMPLE <float><type> TO A DURATION OBJECT | [
"CONVERT",
"SIMPLE",
"<float",
">",
"<type",
">",
"TO",
"A",
"DURATION",
"OBJECT"
] | python | train | 30.538462 |
klavinslab/coral | coral/analysis/_structure/nupack.py | https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/analysis/_structure/nupack.py#L153-L213 | def pairs(self, strand, cutoff=0.001, temp=37.0, pseudo=False,
material=None, dangles='some', sodium=1.0, magnesium=0.0):
'''Compute the pair probabilities for an ordered complex of strands.
Runs the \'pairs\' command.
:param strand: Strand on which to run pairs. Strands must be e... | [
"def",
"pairs",
"(",
"self",
",",
"strand",
",",
"cutoff",
"=",
"0.001",
",",
"temp",
"=",
"37.0",
",",
"pseudo",
"=",
"False",
",",
"material",
"=",
"None",
",",
"dangles",
"=",
"'some'",
",",
"sodium",
"=",
"1.0",
",",
"magnesium",
"=",
"0.0",
")... | Compute the pair probabilities for an ordered complex of strands.
Runs the \'pairs\' command.
:param strand: Strand on which to run pairs. Strands must be either
coral.DNA or coral.RNA).
:type strand: list
:param cutoff: Only probabilities above this cutoff appear... | [
"Compute",
"the",
"pair",
"probabilities",
"for",
"an",
"ordered",
"complex",
"of",
"strands",
".",
"Runs",
"the",
"\\",
"pairs",
"\\",
"command",
"."
] | python | train | 48.540984 |
miguelgrinberg/python-engineio | engineio/async_drivers/sanic.py | https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/async_drivers/sanic.py#L29-L89 | def translate_request(request):
"""This function takes the arguments passed to the request handler and
uses them to generate a WSGI compatible environ dictionary.
"""
class AwaitablePayload(object):
def __init__(self, payload):
self.payload = payload or b''
async def read(se... | [
"def",
"translate_request",
"(",
"request",
")",
":",
"class",
"AwaitablePayload",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"payload",
")",
":",
"self",
".",
"payload",
"=",
"payload",
"or",
"b''",
"async",
"def",
"read",
"(",
"self"... | This function takes the arguments passed to the request handler and
uses them to generate a WSGI compatible environ dictionary. | [
"This",
"function",
"takes",
"the",
"arguments",
"passed",
"to",
"the",
"request",
"handler",
"and",
"uses",
"them",
"to",
"generate",
"a",
"WSGI",
"compatible",
"environ",
"dictionary",
"."
] | python | train | 30.868852 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L274-L308 | def dump_handler_config_data(self):
''' Return capture handler configuration data.
Return a dictionary of capture handler configuration data of the form:
.. code-block:: none
[{
'handler': <handler configuration dictionary>,
'log_file_path': <Path ... | [
"def",
"dump_handler_config_data",
"(",
"self",
")",
":",
"ignored_keys",
"=",
"[",
"'logger'",
",",
"'log_rot_time'",
",",
"'reads'",
",",
"'data_read'",
"]",
"config_data",
"=",
"[",
"]",
"for",
"h",
"in",
"self",
".",
"capture_handlers",
":",
"config_data",... | Return capture handler configuration data.
Return a dictionary of capture handler configuration data of the form:
.. code-block:: none
[{
'handler': <handler configuration dictionary>,
'log_file_path': <Path to the current log file that the logger
... | [
"Return",
"capture",
"handler",
"configuration",
"data",
"."
] | python | train | 35.114286 |
mrstephenneal/dirutility | dirutility/walk/filter.py | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/filter.py#L49-L74 | def validate(self, path):
"""Run path against filter sets and return True if all pass"""
# Exclude hidden files and folders with '.' prefix
if os.path.basename(path).startswith('.'):
return False
# Check that current path level is more than min path and less than max path
... | [
"def",
"validate",
"(",
"self",
",",
"path",
")",
":",
"# Exclude hidden files and folders with '.' prefix",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
".",
"startswith",
"(",
"'.'",
")",
":",
"return",
"False",
"# Check that current path level is... | Run path against filter sets and return True if all pass | [
"Run",
"path",
"against",
"filter",
"sets",
"and",
"return",
"True",
"if",
"all",
"pass"
] | python | train | 34.692308 |
iamteem/redisco | redisco/containers.py | https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L475-L482 | def gt(self, v, limit=None, offset=None):
"""Returns the list of the members of the set that have scores
greater than v.
"""
if limit is not None and offset is None:
offset = 0
return self.zrangebyscore("(%f" % v, self._max_score,
start=offset, num=lim... | [
"def",
"gt",
"(",
"self",
",",
"v",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"if",
"limit",
"is",
"not",
"None",
"and",
"offset",
"is",
"None",
":",
"offset",
"=",
"0",
"return",
"self",
".",
"zrangebyscore",
"(",
"\"(%f\"",... | Returns the list of the members of the set that have scores
greater than v. | [
"Returns",
"the",
"list",
"of",
"the",
"members",
"of",
"the",
"set",
"that",
"have",
"scores",
"greater",
"than",
"v",
"."
] | python | train | 39.5 |
craffel/mir_eval | mir_eval/chord.py | https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/chord.py#L143-L168 | def pitch_class_to_semitone(pitch_class):
r'''Convert a pitch class to semitone.
Parameters
----------
pitch_class : str
Spelling of a given pitch class, e.g. 'C#', 'Gbb'
Returns
-------
semitone : int
Semitone value of the pitch class.
'''
semitone = 0
for idx... | [
"def",
"pitch_class_to_semitone",
"(",
"pitch_class",
")",
":",
"semitone",
"=",
"0",
"for",
"idx",
",",
"char",
"in",
"enumerate",
"(",
"pitch_class",
")",
":",
"if",
"char",
"==",
"'#'",
"and",
"idx",
">",
"0",
":",
"semitone",
"+=",
"1",
"elif",
"ch... | r'''Convert a pitch class to semitone.
Parameters
----------
pitch_class : str
Spelling of a given pitch class, e.g. 'C#', 'Gbb'
Returns
-------
semitone : int
Semitone value of the pitch class. | [
"r",
"Convert",
"a",
"pitch",
"class",
"to",
"semitone",
"."
] | python | train | 25.807692 |
zerotk/easyfs | zerotk/easyfs/_easyfs.py | https://github.com/zerotk/easyfs/blob/140923db51fb91d5a5847ad17412e8bce51ba3da/zerotk/easyfs/_easyfs.py#L1451-L1491 | def CreateLink(target_path, link_path, override=True):
'''
Create a symbolic link at `link_path` pointing to `target_path`.
:param unicode target_path:
Link target
:param unicode link_path:
Fullpath to link name
:param bool override:
If True and `link_path` already exists ... | [
"def",
"CreateLink",
"(",
"target_path",
",",
"link_path",
",",
"override",
"=",
"True",
")",
":",
"_AssertIsLocal",
"(",
"target_path",
")",
"_AssertIsLocal",
"(",
"link_path",
")",
"if",
"override",
"and",
"IsLink",
"(",
"link_path",
")",
":",
"DeleteLink",
... | Create a symbolic link at `link_path` pointing to `target_path`.
:param unicode target_path:
Link target
:param unicode link_path:
Fullpath to link name
:param bool override:
If True and `link_path` already exists as a link, that link is overridden. | [
"Create",
"a",
"symbolic",
"link",
"at",
"link_path",
"pointing",
"to",
"target_path",
"."
] | python | valid | 31.756098 |
Kozea/cairocffi | cairocffi/patterns.py | https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/patterns.py#L266-L283 | def get_color_stops(self):
"""Return this gradient’s color stops so far.
:returns:
A list of ``(offset, red, green, blue, alpha)`` tuples of floats.
"""
count = ffi.new('int *')
_check_status(cairo.cairo_pattern_get_color_stop_count(
self._pointer, count... | [
"def",
"get_color_stops",
"(",
"self",
")",
":",
"count",
"=",
"ffi",
".",
"new",
"(",
"'int *'",
")",
"_check_status",
"(",
"cairo",
".",
"cairo_pattern_get_color_stop_count",
"(",
"self",
".",
"_pointer",
",",
"count",
")",
")",
"stops",
"=",
"[",
"]",
... | Return this gradient’s color stops so far.
:returns:
A list of ``(offset, red, green, blue, alpha)`` tuples of floats. | [
"Return",
"this",
"gradient’s",
"color",
"stops",
"so",
"far",
"."
] | python | train | 34.5 |
PyFilesystem/pyfilesystem2 | fs/copy.py | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/copy.py#L22-L47 | def copy_fs(
src_fs, # type: Union[FS, Text]
dst_fs, # type: Union[FS, Text]
walker=None, # type: Optional[Walker]
on_copy=None, # type: Optional[_OnCopy]
workers=0, # type: int
):
# type: (...) -> None
"""Copy the contents of one filesystem to another.
Arguments:
src_fs (F... | [
"def",
"copy_fs",
"(",
"src_fs",
",",
"# type: Union[FS, Text]",
"dst_fs",
",",
"# type: Union[FS, Text]",
"walker",
"=",
"None",
",",
"# type: Optional[Walker]",
"on_copy",
"=",
"None",
",",
"# type: Optional[_OnCopy]",
"workers",
"=",
"0",
",",
"# type: int",
")",
... | Copy the contents of one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (URL or instance).
dst_fs (FS or str): Destination filesystem (URL or instance).
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for files in ``src_fs``... | [
"Copy",
"the",
"contents",
"of",
"one",
"filesystem",
"to",
"another",
"."
] | python | train | 40.115385 |
radjkarl/imgProcessor | imgProcessor/camera/CameraCalibration.py | https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/camera/CameraCalibration.py#L324-L349 | def transpose(self):
'''
transpose all calibration arrays
in case different array shape orders were used (x,y) vs. (y,x)
'''
def _t(item):
if type(item) == list:
for n, it in enumerate(item):
if type(it) == tuple:
... | [
"def",
"transpose",
"(",
"self",
")",
":",
"def",
"_t",
"(",
"item",
")",
":",
"if",
"type",
"(",
"item",
")",
"==",
"list",
":",
"for",
"n",
",",
"it",
"in",
"enumerate",
"(",
"item",
")",
":",
"if",
"type",
"(",
"it",
")",
"==",
"tuple",
":... | transpose all calibration arrays
in case different array shape orders were used (x,y) vs. (y,x) | [
"transpose",
"all",
"calibration",
"arrays",
"in",
"case",
"different",
"array",
"shape",
"orders",
"were",
"used",
"(",
"x",
"y",
")",
"vs",
".",
"(",
"y",
"x",
")"
] | python | train | 31.730769 |
datadotworld/data.world-py | datadotworld/datadotworld.py | https://github.com/datadotworld/data.world-py/blob/ffaeb115f358731ab0b805b0c43b7ff2e3cf0a77/datadotworld/datadotworld.py#L116-L199 | def load_dataset(self, dataset_key, force_update=False, auto_update=False):
"""Load a dataset from the local filesystem, downloading it from
data.world first, if necessary.
This function returns an object of type `LocalDataset`. The object
allows access to metedata via it's `describe()`... | [
"def",
"load_dataset",
"(",
"self",
",",
"dataset_key",
",",
"force_update",
"=",
"False",
",",
"auto_update",
"=",
"False",
")",
":",
"owner_id",
",",
"dataset_id",
"=",
"parse_dataset_key",
"(",
"dataset_key",
")",
"cache_dir",
"=",
"path",
".",
"join",
"(... | Load a dataset from the local filesystem, downloading it from
data.world first, if necessary.
This function returns an object of type `LocalDataset`. The object
allows access to metedata via it's `describe()` method and to all the
data via three properties `raw_data`, `tables` and `data... | [
"Load",
"a",
"dataset",
"from",
"the",
"local",
"filesystem",
"downloading",
"it",
"from",
"data",
".",
"world",
"first",
"if",
"necessary",
"."
] | python | train | 47.964286 |
SpotlightData/preprocessing | preprocessing/spellcheck.py | https://github.com/SpotlightData/preprocessing/blob/180c6472bc2642afbd7a1ece08d0b0d14968a708/preprocessing/spellcheck.py#L103-L116 | def validate_words(word_list):
'''
Checks for each edited word in word_list if that word is a valid english word.abs
Returns all validated words as a set instance.
'''
if word_list is None:
return {}
elif isinstance(word_list, list):
if not word_list:
return {}
... | [
"def",
"validate_words",
"(",
"word_list",
")",
":",
"if",
"word_list",
"is",
"None",
":",
"return",
"{",
"}",
"elif",
"isinstance",
"(",
"word_list",
",",
"list",
")",
":",
"if",
"not",
"word_list",
":",
"return",
"{",
"}",
"else",
":",
"return",
"set... | Checks for each edited word in word_list if that word is a valid english word.abs
Returns all validated words as a set instance. | [
"Checks",
"for",
"each",
"edited",
"word",
"in",
"word_list",
"if",
"that",
"word",
"is",
"a",
"valid",
"english",
"word",
".",
"abs",
"Returns",
"all",
"validated",
"words",
"as",
"a",
"set",
"instance",
"."
] | python | train | 34.785714 |
cmorisse/ikp3db | ikp3db.py | https://github.com/cmorisse/ikp3db/blob/a0f318d4e8494b2e6f2f07ec0f1202ca023c920f/ikp3db.py#L1179-L1298 | def _line_tracer(self, frame, exc_info=False):
"""This function is called when debugger has decided that it must
stop or break at this frame."""
# next logging statement commented for performance
_logger.f_debug("user_line() with "
"threadName=%s, frame=%s, frame... | [
"def",
"_line_tracer",
"(",
"self",
",",
"frame",
",",
"exc_info",
"=",
"False",
")",
":",
"# next logging statement commented for performance",
"_logger",
".",
"f_debug",
"(",
"\"user_line() with \"",
"\"threadName=%s, frame=%s, frame.f_code=%s, self.mainpyfile=%s,\"",
"\"self... | This function is called when debugger has decided that it must
stop or break at this frame. | [
"This",
"function",
"is",
"called",
"when",
"debugger",
"has",
"decided",
"that",
"it",
"must",
"stop",
"or",
"break",
"at",
"this",
"frame",
"."
] | python | train | 45.733333 |
wummel/linkchecker | linkcheck/logger/text.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/logger/text.py#L155-L165 | def write_parent (self, url_data):
"""Write url_data.parent_url."""
self.write(self.part('parenturl') + self.spaces("parenturl"))
txt = url_data.parent_url
if url_data.line > 0:
txt += _(", line %d") % url_data.line
if url_data.column > 0:
txt += _(", col ... | [
"def",
"write_parent",
"(",
"self",
",",
"url_data",
")",
":",
"self",
".",
"write",
"(",
"self",
".",
"part",
"(",
"'parenturl'",
")",
"+",
"self",
".",
"spaces",
"(",
"\"parenturl\"",
")",
")",
"txt",
"=",
"url_data",
".",
"parent_url",
"if",
"url_da... | Write url_data.parent_url. | [
"Write",
"url_data",
".",
"parent_url",
"."
] | python | train | 42 |
openstax/cnx-archive | cnxarchive/search.py | https://github.com/openstax/cnx-archive/blob/d31d34aa8bbc8a9fde6cd4227a0df92726e8daf4/cnxarchive/search.py#L177-L192 | def highlighted_abstract(self):
"""Highlight the found terms in the abstract text."""
abstract_terms = self.fields.get('abstract', [])
if abstract_terms:
sql = _read_sql_file('highlighted-abstract')
else:
sql = _read_sql_file('get-abstract')
arguments = {'... | [
"def",
"highlighted_abstract",
"(",
"self",
")",
":",
"abstract_terms",
"=",
"self",
".",
"fields",
".",
"get",
"(",
"'abstract'",
",",
"[",
"]",
")",
"if",
"abstract_terms",
":",
"sql",
"=",
"_read_sql_file",
"(",
"'highlighted-abstract'",
")",
"else",
":",... | Highlight the found terms in the abstract text. | [
"Highlight",
"the",
"found",
"terms",
"in",
"the",
"abstract",
"text",
"."
] | python | train | 40.625 |
jrief/djangocms-cascade | cmsplugin_cascade/plugin_base.py | https://github.com/jrief/djangocms-cascade/blob/58996f990c4068e5d50f0db6030a5c0e06b682e5/cmsplugin_cascade/plugin_base.py#L282-L295 | def _get_parent_classes_transparent(cls, slot, page, instance=None):
"""
Return all parent classes including those marked as "transparent".
"""
parent_classes = super(CascadePluginBase, cls).get_parent_classes(slot, page, instance)
if parent_classes is None:
if cls.ge... | [
"def",
"_get_parent_classes_transparent",
"(",
"cls",
",",
"slot",
",",
"page",
",",
"instance",
"=",
"None",
")",
":",
"parent_classes",
"=",
"super",
"(",
"CascadePluginBase",
",",
"cls",
")",
".",
"get_parent_classes",
"(",
"slot",
",",
"page",
",",
"inst... | Return all parent classes including those marked as "transparent". | [
"Return",
"all",
"parent",
"classes",
"including",
"those",
"marked",
"as",
"transparent",
"."
] | python | train | 45.428571 |
gnosis/gnosis-py | gnosis/safe/safe_service.py | https://github.com/gnosis/gnosis-py/blob/2a9a5d75a375fc9813ac04df133e6910c82f9d49/gnosis/safe/safe_service.py#L230-L270 | def deploy_master_contract(self, deployer_account=None, deployer_private_key=None) -> str:
"""
Deploy master contract. Takes deployer_account (if unlocked in the node) or the deployer private key
:param deployer_account: Unlocked ethereum account
:param deployer_private_key: Private key ... | [
"def",
"deploy_master_contract",
"(",
"self",
",",
"deployer_account",
"=",
"None",
",",
"deployer_private_key",
"=",
"None",
")",
"->",
"str",
":",
"assert",
"deployer_account",
"or",
"deployer_private_key",
"deployer_address",
"=",
"deployer_account",
"or",
"self",
... | Deploy master contract. Takes deployer_account (if unlocked in the node) or the deployer private key
:param deployer_account: Unlocked ethereum account
:param deployer_private_key: Private key of an ethereum account
:return: deployed contract address | [
"Deploy",
"master",
"contract",
".",
"Takes",
"deployer_account",
"(",
"if",
"unlocked",
"in",
"the",
"node",
")",
"or",
"the",
"deployer",
"private",
"key",
":",
"param",
"deployer_account",
":",
"Unlocked",
"ethereum",
"account",
":",
"param",
"deployer_privat... | python | test | 52.804878 |
rigetti/quantumflow | quantumflow/paulialgebra.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/paulialgebra.py#L239-L242 | def sI(qubit: Qubit, coefficient: complex = 1.0) -> Pauli:
"""Return the Pauli sigma_I (identity) operator. The qubit is irrelevant,
but kept as an argument for consistency"""
return Pauli.sigma(qubit, 'I', coefficient) | [
"def",
"sI",
"(",
"qubit",
":",
"Qubit",
",",
"coefficient",
":",
"complex",
"=",
"1.0",
")",
"->",
"Pauli",
":",
"return",
"Pauli",
".",
"sigma",
"(",
"qubit",
",",
"'I'",
",",
"coefficient",
")"
] | Return the Pauli sigma_I (identity) operator. The qubit is irrelevant,
but kept as an argument for consistency | [
"Return",
"the",
"Pauli",
"sigma_I",
"(",
"identity",
")",
"operator",
".",
"The",
"qubit",
"is",
"irrelevant",
"but",
"kept",
"as",
"an",
"argument",
"for",
"consistency"
] | python | train | 57.25 |
chaoss/grimoirelab-sortinghat | sortinghat/db/api.py | https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/db/api.py#L40-L56 | def find_unique_identity(session, uuid):
"""Find a unique identity.
Find a unique identity by its UUID using the given `session`.
When the unique identity does not exist the function will
return `None`.
:param session: database session
:param uuid: id of the unique identity to find
:retur... | [
"def",
"find_unique_identity",
"(",
"session",
",",
"uuid",
")",
":",
"uidentity",
"=",
"session",
".",
"query",
"(",
"UniqueIdentity",
")",
".",
"filter",
"(",
"UniqueIdentity",
".",
"uuid",
"==",
"uuid",
")",
".",
"first",
"(",
")",
"return",
"uidentity"... | Find a unique identity.
Find a unique identity by its UUID using the given `session`.
When the unique identity does not exist the function will
return `None`.
:param session: database session
:param uuid: id of the unique identity to find
:returns: a unique identity object; `None` when the un... | [
"Find",
"a",
"unique",
"identity",
"."
] | python | train | 30.529412 |
googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/_helpers.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/_helpers.py#L104-L137 | def verify_path(path, is_collection):
"""Verifies that a ``path`` has the correct form.
Checks that all of the elements in ``path`` are strings.
Args:
path (Tuple[str, ...]): The components in a collection or
document path.
is_collection (bool): Indicates if the ``path`` repres... | [
"def",
"verify_path",
"(",
"path",
",",
"is_collection",
")",
":",
"num_elements",
"=",
"len",
"(",
"path",
")",
"if",
"num_elements",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Document or collection path cannot be empty\"",
")",
"if",
"is_collection",
":",
... | Verifies that a ``path`` has the correct form.
Checks that all of the elements in ``path`` are strings.
Args:
path (Tuple[str, ...]): The components in a collection or
document path.
is_collection (bool): Indicates if the ``path`` represents
a document or a collection.
... | [
"Verifies",
"that",
"a",
"path",
"has",
"the",
"correct",
"form",
"."
] | python | train | 34.970588 |
UCSBarchlab/PyRTL | pyrtl/inputoutput.py | https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/inputoutput.py#L26-L206 | def input_from_blif(blif, block=None, merge_io_vectors=True):
""" Read an open blif file or string as input, updating the block appropriately
Assumes the blif has been flattened and their is only a single module.
Assumes that there is only one single shared clock and reset
Assumes that output is genera... | [
"def",
"input_from_blif",
"(",
"blif",
",",
"block",
"=",
"None",
",",
"merge_io_vectors",
"=",
"True",
")",
":",
"import",
"pyparsing",
"import",
"six",
"from",
"pyparsing",
"import",
"(",
"Word",
",",
"Literal",
",",
"OneOrMore",
",",
"ZeroOrMore",
",",
... | Read an open blif file or string as input, updating the block appropriately
Assumes the blif has been flattened and their is only a single module.
Assumes that there is only one single shared clock and reset
Assumes that output is generated by Yosys with formals in a particular order
Ignores reset sign... | [
"Read",
"an",
"open",
"blif",
"file",
"or",
"string",
"as",
"input",
"updating",
"the",
"block",
"appropriately"
] | python | train | 43.839779 |
wummel/linkchecker | linkcheck/network/__init__.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/network/__init__.py#L14-L19 | def pipecmd (cmd1, cmd2):
"""Return output of "cmd1 | cmd2"."""
p1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE)
p2 = subprocess.Popen(cmd2, stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
return p2.communicate()[0] | [
"def",
"pipecmd",
"(",
"cmd1",
",",
"cmd2",
")",
":",
"p1",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd1",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
"p2",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd2",
",",
"stdin",
"=",
"p1",
".",
"stdout"... | Return output of "cmd1 | cmd2". | [
"Return",
"output",
"of",
"cmd1",
"|",
"cmd2",
"."
] | python | train | 48.333333 |
fulfilio/python-magento | magento/checkout.py | https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/checkout.py#L327-L340 | def update(self, quote_id, product_data, store_view=None):
"""
Allows you to update one or several products in the shopping cart
(quote).
:param quote_id: Shopping cart ID (quote ID)
:param product_data, list of dicts of product details, see def add()
:param store_view: ... | [
"def",
"update",
"(",
"self",
",",
"quote_id",
",",
"product_data",
",",
"store_view",
"=",
"None",
")",
":",
"return",
"bool",
"(",
"self",
".",
"call",
"(",
"'cart_product.update'",
",",
"[",
"quote_id",
",",
"product_data",
",",
"store_view",
"]",
")",
... | Allows you to update one or several products in the shopping cart
(quote).
:param quote_id: Shopping cart ID (quote ID)
:param product_data, list of dicts of product details, see def add()
:param store_view: Store view ID or code
:return: boolean, True if the product is updated ... | [
"Allows",
"you",
"to",
"update",
"one",
"or",
"several",
"products",
"in",
"the",
"shopping",
"cart",
"(",
"quote",
")",
"."
] | python | train | 37.785714 |
pmacosta/peng | peng/wave_functions.py | https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/peng/wave_functions.py#L1905-L1924 | def wcomplex(wave):
r"""
Convert a waveform's dependent variable vector to complex.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
... | [
"def",
"wcomplex",
"(",
"wave",
")",
":",
"ret",
"=",
"copy",
".",
"copy",
"(",
"wave",
")",
"ret",
".",
"_dep_vector",
"=",
"ret",
".",
"_dep_vector",
".",
"astype",
"(",
"np",
".",
"complex",
")",
"return",
"ret"
] | r"""
Convert a waveform's dependent variable vector to complex.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_function... | [
"r",
"Convert",
"a",
"waveform",
"s",
"dependent",
"variable",
"vector",
"to",
"complex",
"."
] | python | test | 25.95 |
ktbyers/netmiko | netmiko/cisco_base_connection.py | https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/cisco_base_connection.py#L183-L205 | def _autodetect_fs(self, cmd="dir", pattern=r"Directory of (.*)/"):
"""Autodetect the file system on the remote device. Used by SCP operations."""
if not self.check_enable_mode():
raise ValueError("Must be in enable mode to auto-detect the file-system.")
output = self.send_command_ex... | [
"def",
"_autodetect_fs",
"(",
"self",
",",
"cmd",
"=",
"\"dir\"",
",",
"pattern",
"=",
"r\"Directory of (.*)/\"",
")",
":",
"if",
"not",
"self",
".",
"check_enable_mode",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Must be in enable mode to auto-detect the file-sy... | Autodetect the file system on the remote device. Used by SCP operations. | [
"Autodetect",
"the",
"file",
"system",
"on",
"the",
"remote",
"device",
".",
"Used",
"by",
"SCP",
"operations",
"."
] | python | train | 43.347826 |
rigetti/pyquil | pyquil/pyqvm.py | https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/pyqvm.py#L335-L500 | def transition(self):
"""
Implements a QAM-like transition.
This function assumes ``program`` and ``program_counter`` instance variables are set
appropriately, and that the wavefunction simulator and classical memory ``ram`` instance
variables are in the desired QAM input state.... | [
"def",
"transition",
"(",
"self",
")",
":",
"instruction",
"=",
"self",
".",
"program",
"[",
"self",
".",
"program_counter",
"]",
"if",
"isinstance",
"(",
"instruction",
",",
"Gate",
")",
":",
"if",
"instruction",
".",
"name",
"in",
"self",
".",
"defined... | Implements a QAM-like transition.
This function assumes ``program`` and ``program_counter`` instance variables are set
appropriately, and that the wavefunction simulator and classical memory ``ram`` instance
variables are in the desired QAM input state.
:return: whether the QAM should ... | [
"Implements",
"a",
"QAM",
"-",
"like",
"transition",
"."
] | python | train | 45.560241 |
Richienb/quilt | src/quilt_lang/__init__.py | https://github.com/Richienb/quilt/blob/4a659cac66f5286ad046d54a12fd850be5606643/src/quilt_lang/__init__.py#L846-L917 | def shapesides(inputtocheck, inputtype='shape'):
"""
Get the sides of a shape.
inputtocheck:
The amount of sides or the shape to be checked,
depending on the value of inputtype.
inputtype:
The type of input provided.
Can be: 'shape', 'sides'.
"""
# Define the array of sides to... | [
"def",
"shapesides",
"(",
"inputtocheck",
",",
"inputtype",
"=",
"'shape'",
")",
":",
"# Define the array of sides to a shape",
"shapestosides",
"=",
"{",
"'triangle'",
":",
"3",
",",
"'square'",
":",
"4",
",",
"'pentagon'",
":",
"5",
",",
"'hexagon'",
":",
"6... | Get the sides of a shape.
inputtocheck:
The amount of sides or the shape to be checked,
depending on the value of inputtype.
inputtype:
The type of input provided.
Can be: 'shape', 'sides'. | [
"Get",
"the",
"sides",
"of",
"a",
"shape",
"."
] | python | train | 27.375 |
pyokagan/pyglreg | glreg.py | https://github.com/pyokagan/pyglreg/blob/68fa5a6c6cee8667879840fbbcc7d30f52852915/glreg.py#L220-L226 | def text(self):
"""Formatted Command declaration.
This is the C declaration for the command.
"""
params = ', '.join(x.text for x in self.params)
return '{0} ({1})'.format(self.proto_text, params) | [
"def",
"text",
"(",
"self",
")",
":",
"params",
"=",
"', '",
".",
"join",
"(",
"x",
".",
"text",
"for",
"x",
"in",
"self",
".",
"params",
")",
"return",
"'{0} ({1})'",
".",
"format",
"(",
"self",
".",
"proto_text",
",",
"params",
")"
] | Formatted Command declaration.
This is the C declaration for the command. | [
"Formatted",
"Command",
"declaration",
"."
] | python | train | 32.857143 |
fabric-bolt/fabric-bolt | fabric_bolt/projects/models.py | https://github.com/fabric-bolt/fabric-bolt/blob/0f434783026f1b9ce16a416fa496d76921fe49ca/fabric_bolt/projects/models.py#L240-L248 | def set_value(self, value):
"""Determine the proper value based on the data_type"""
if self.data_type == self.BOOLEAN_TYPE:
self.value_boolean = bool(value)
elif self.data_type == self.NUMBER_TYPE:
self.value_number = float(value)
else:
self.value = v... | [
"def",
"set_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"data_type",
"==",
"self",
".",
"BOOLEAN_TYPE",
":",
"self",
".",
"value_boolean",
"=",
"bool",
"(",
"value",
")",
"elif",
"self",
".",
"data_type",
"==",
"self",
".",
"NUMBER_... | Determine the proper value based on the data_type | [
"Determine",
"the",
"proper",
"value",
"based",
"on",
"the",
"data_type"
] | python | train | 35.111111 |
fridex/json2sql | json2sql/select.py | https://github.com/fridex/json2sql/blob/a0851dd79827a684319b03fb899e129f81ff2d3a/json2sql/select.py#L32-L40 | def _expand_join(join_definition):
"""Expand join definition to `join' call.
:param join_definition: join definition
:return: expanded join definition
"""
join_table_name = join_definition.pop('table')
join_func = getattr(mosql_query, join_definition.pop('join_type', 'join'))
return join_fu... | [
"def",
"_expand_join",
"(",
"join_definition",
")",
":",
"join_table_name",
"=",
"join_definition",
".",
"pop",
"(",
"'table'",
")",
"join_func",
"=",
"getattr",
"(",
"mosql_query",
",",
"join_definition",
".",
"pop",
"(",
"'join_type'",
",",
"'join'",
")",
")... | Expand join definition to `join' call.
:param join_definition: join definition
:return: expanded join definition | [
"Expand",
"join",
"definition",
"to",
"join",
"call",
"."
] | python | train | 38.888889 |
twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py#L92-L106 | def get_instance(self, payload):
"""
Build an instance of TaskQueueRealTimeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance
:rtype: ... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"TaskQueueRealTimeStatisticsInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_sid'",
"]",
",",
"task_queue_sid",
... | Build an instance of TaskQueueRealTimeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_q... | [
"Build",
"an",
"instance",
"of",
"TaskQueueRealTimeStatisticsInstance"
] | python | train | 44.133333 |
reingart/pyafipws | wslsp.py | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslsp.py#L702-L715 | def ConsultarCaracteres(self, sep="||"):
"Retorna listado de caracteres emisor/receptor (código, descripción)"
ret = self.client.consultarCaracteresParticipante(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cu... | [
"def",
"ConsultarCaracteres",
"(",
"self",
",",
"sep",
"=",
"\"||\"",
")",
":",
"ret",
"=",
"self",
".",
"client",
".",
"consultarCaracteresParticipante",
"(",
"auth",
"=",
"{",
"'token'",
":",
"self",
".",
"Token",
",",
"'sign'",
":",
"self",
".",
"Sign... | Retorna listado de caracteres emisor/receptor (código, descripción) | [
"Retorna",
"listado",
"de",
"caracteres",
"emisor",
"/",
"receptor",
"(",
"código",
"descripción",
")"
] | python | train | 50.928571 |
PyHDI/Pyverilog | pyverilog/vparser/parser.py | https://github.com/PyHDI/Pyverilog/blob/b852cc5ed6a7a2712e33639f9d9782d0d1587a53/pyverilog/vparser/parser.py#L947-L950 | def p_expression_unor(self, p):
'expression : NOR expression %prec UNOR'
p[0] = Unor(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_expression_unor",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Unor",
"(",
"p",
"[",
"2",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(... | expression : NOR expression %prec UNOR | [
"expression",
":",
"NOR",
"expression",
"%prec",
"UNOR"
] | python | train | 40 |
PeerAssets/pypeerassets | pypeerassets/provider/rpcnode.py | https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/rpcnode.py#L67-L79 | def listunspent(
self,
address: str="",
minconf: int=1,
maxconf: int=999999,
) -> list:
'''list UTXOs
modified version to allow filtering by address.
'''
if address:
return self.req("listunspent", [minconf, maxconf, [address]])
ret... | [
"def",
"listunspent",
"(",
"self",
",",
"address",
":",
"str",
"=",
"\"\"",
",",
"minconf",
":",
"int",
"=",
"1",
",",
"maxconf",
":",
"int",
"=",
"999999",
",",
")",
"->",
"list",
":",
"if",
"address",
":",
"return",
"self",
".",
"req",
"(",
"\"... | list UTXOs
modified version to allow filtering by address. | [
"list",
"UTXOs",
"modified",
"version",
"to",
"allow",
"filtering",
"by",
"address",
"."
] | python | train | 27.307692 |
port-zero/mite | mite/mite.py | https://github.com/port-zero/mite/blob/b5fa941f60bf43e04ef654ed580ed7ef91211c22/mite/mite.py#L275-L284 | def create_project(self, name, **kwargs):
"""
Creates a project with a name. All other parameters are optional. They
are: `note`, `customer_id`, `budget`, `budget_type`,
`active_hourly_rate`, `hourly_rate`, `hourly_rates_per_service`, and
`archived`.
"""
data = s... | [
"def",
"create_project",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"self",
".",
"_wrap_dict",
"(",
"\"project\"",
",",
"kwargs",
")",
"data",
"[",
"\"customer\"",
"]",
"[",
"\"name\"",
"]",
"=",
"name",
"return",
"self",... | Creates a project with a name. All other parameters are optional. They
are: `note`, `customer_id`, `budget`, `budget_type`,
`active_hourly_rate`, `hourly_rate`, `hourly_rates_per_service`, and
`archived`. | [
"Creates",
"a",
"project",
"with",
"a",
"name",
".",
"All",
"other",
"parameters",
"are",
"optional",
".",
"They",
"are",
":",
"note",
"customer_id",
"budget",
"budget_type",
"active_hourly_rate",
"hourly_rate",
"hourly_rates_per_service",
"and",
"archived",
"."
] | python | train | 43.8 |
scanny/python-pptx | pptx/oxml/slide.py | https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/oxml/slide.py#L88-L97 | def get_or_add_bgPr(self):
"""Return `p:bg/p:bgPr` grandchild.
If no such grandchild is present, any existing `p:bg` child is first
removed and a new default `p:bg` with noFill settings is added.
"""
bg = self.bg
if bg is None or bg.bgPr is None:
self._change... | [
"def",
"get_or_add_bgPr",
"(",
"self",
")",
":",
"bg",
"=",
"self",
".",
"bg",
"if",
"bg",
"is",
"None",
"or",
"bg",
".",
"bgPr",
"is",
"None",
":",
"self",
".",
"_change_to_noFill_bg",
"(",
")",
"return",
"self",
".",
"bg",
".",
"bgPr"
] | Return `p:bg/p:bgPr` grandchild.
If no such grandchild is present, any existing `p:bg` child is first
removed and a new default `p:bg` with noFill settings is added. | [
"Return",
"p",
":",
"bg",
"/",
"p",
":",
"bgPr",
"grandchild",
"."
] | python | train | 35.4 |
archman/beamline | beamline/ui/main.py | https://github.com/archman/beamline/blob/417bc5dc13e754bc89d246427984590fced64d07/beamline/ui/main.py#L19-L31 | def run(icon=None):
"""
.. versionchanged:: 2.0.0
Remove parameter *debug*.
"""
app = wx.App()
frame = myappframe.MyAppFrame(None,
u'Lattice Viewer \u2014 Accelerator Online Modeling Tool')
frame.SetSize((1024, 768))
frame.Show()
if icon is not No... | [
"def",
"run",
"(",
"icon",
"=",
"None",
")",
":",
"app",
"=",
"wx",
".",
"App",
"(",
")",
"frame",
"=",
"myappframe",
".",
"MyAppFrame",
"(",
"None",
",",
"u'Lattice Viewer \\u2014 Accelerator Online Modeling Tool'",
")",
"frame",
".",
"SetSize",
"(",
"(",
... | .. versionchanged:: 2.0.0
Remove parameter *debug*. | [
"..",
"versionchanged",
"::",
"2",
".",
"0",
".",
"0",
"Remove",
"parameter",
"*",
"debug",
"*",
"."
] | python | train | 27.538462 |
6809/MC6809 | MC6809/components/mc6809_ops_logic.py | https://github.com/6809/MC6809/blob/6ba2f5106df46689017b5d0b6d84d43b7ee6a240/MC6809/components/mc6809_ops_logic.py#L303-L311 | def instruction_ROL_register(self, opcode, register):
""" Rotate accumulator left """
a = register.value
r = self.ROL(a)
# log.debug("$%x ROL %s value $%x << 1 | Carry = $%x" % (
# self.program_counter,
# register.name, a, r
# ))
register.set(r) | [
"def",
"instruction_ROL_register",
"(",
"self",
",",
"opcode",
",",
"register",
")",
":",
"a",
"=",
"register",
".",
"value",
"r",
"=",
"self",
".",
"ROL",
"(",
"a",
")",
"# log.debug(\"$%x ROL %s value $%x << 1 | Carry = $%x\" % (",
"# self.program_... | Rotate accumulator left | [
"Rotate",
"accumulator",
"left"
] | python | train | 33.888889 |
materialsproject/pymatgen | pymatgen/analysis/wulff.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/wulff.py#L543-L549 | def area_fraction_dict(self):
"""
Returns:
(dict): {hkl: area_hkl/total area on wulff}
"""
return {hkl: self.miller_area_dict[hkl] / self.surface_area
for hkl in self.miller_area_dict.keys()} | [
"def",
"area_fraction_dict",
"(",
"self",
")",
":",
"return",
"{",
"hkl",
":",
"self",
".",
"miller_area_dict",
"[",
"hkl",
"]",
"/",
"self",
".",
"surface_area",
"for",
"hkl",
"in",
"self",
".",
"miller_area_dict",
".",
"keys",
"(",
")",
"}"
] | Returns:
(dict): {hkl: area_hkl/total area on wulff} | [
"Returns",
":",
"(",
"dict",
")",
":",
"{",
"hkl",
":",
"area_hkl",
"/",
"total",
"area",
"on",
"wulff",
"}"
] | python | train | 35 |
cloudendpoints/endpoints-python | endpoints/api_config_manager.py | https://github.com/cloudendpoints/endpoints-python/blob/00dd7c7a52a9ee39d5923191c2604b8eafdb3f24/endpoints/api_config_manager.py#L79-L150 | def _get_sorted_methods(self, methods):
"""Get a copy of 'methods' sorted the way they would be on the live server.
Args:
methods: JSON configuration of an API's methods.
Returns:
The same configuration with the methods sorted based on what order
they'll be checked by the server.
"""... | [
"def",
"_get_sorted_methods",
"(",
"self",
",",
"methods",
")",
":",
"if",
"not",
"methods",
":",
"return",
"methods",
"# Comparison function we'll use to sort the methods:",
"def",
"_sorted_methods_comparison",
"(",
"method_info1",
",",
"method_info2",
")",
":",
"\"\"\... | Get a copy of 'methods' sorted the way they would be on the live server.
Args:
methods: JSON configuration of an API's methods.
Returns:
The same configuration with the methods sorted based on what order
they'll be checked by the server. | [
"Get",
"a",
"copy",
"of",
"methods",
"sorted",
"the",
"way",
"they",
"would",
"be",
"on",
"the",
"live",
"server",
"."
] | python | train | 36.013889 |
LuminosoInsight/python-ftfy | ftfy/bad_codecs/utf8_variants.py | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/bad_codecs/utf8_variants.py#L131-L170 | def _buffer_decode_step(self, input, errors, final):
"""
There are three possibilities for each decoding step:
- Decode as much real UTF-8 as possible.
- Decode a six-byte CESU-8 sequence at the current position.
- Decode a Java-style null at the current position.
This ... | [
"def",
"_buffer_decode_step",
"(",
"self",
",",
"input",
",",
"errors",
",",
"final",
")",
":",
"# Get a reference to the superclass method that we'll be using for",
"# most of the real work.",
"sup",
"=",
"UTF8IncrementalDecoder",
".",
"_buffer_decode",
"# Find the next byte p... | There are three possibilities for each decoding step:
- Decode as much real UTF-8 as possible.
- Decode a six-byte CESU-8 sequence at the current position.
- Decode a Java-style null at the current position.
This method figures out which step is appropriate, and does it. | [
"There",
"are",
"three",
"possibilities",
"for",
"each",
"decoding",
"step",
":"
] | python | train | 38.95 |
bitesofcode/projexui | projexui/widgets/xorbrecordedit.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbrecordedit.py#L344-L389 | def create( cls, model, parent = None, uifile = '', commit = True ):
"""
Prompts the user to create a new record for the inputed table.
:param model | <subclass of orb.Table>
parent | <QWidget>
:return <orb.Table> || None/ | instan... | [
"def",
"create",
"(",
"cls",
",",
"model",
",",
"parent",
"=",
"None",
",",
"uifile",
"=",
"''",
",",
"commit",
"=",
"True",
")",
":",
"# create the dialog\r",
"dlg",
"=",
"QDialog",
"(",
"parent",
")",
"dlg",
".",
"setWindowTitle",
"(",
"'Create %s'",
... | Prompts the user to create a new record for the inputed table.
:param model | <subclass of orb.Table>
parent | <QWidget>
:return <orb.Table> || None/ | instance of the inputed table class | [
"Prompts",
"the",
"user",
"to",
"create",
"a",
"new",
"record",
"for",
"the",
"inputed",
"table",
".",
":",
"param",
"model",
"|",
"<subclass",
"of",
"orb",
".",
"Table",
">",
"parent",
"|",
"<QWidget",
">",
":",
"return",
"<orb",
".",
"Table",
">",
... | python | train | 31.608696 |
echinopsii/net.echinopsii.ariane.community.cli.python3 | ariane_clip3/rabbitmq/driver.py | https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/rabbitmq/driver.py#L482-L499 | def stop(self):
"""
Stop services and requestors and then connection.
:return: self
"""
LOGGER.debug("rabbitmq.Driver.stop")
for requester in self.requester_registry:
requester.stop()
self.requester_registry.clear()
for service in self.service... | [
"def",
"stop",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"rabbitmq.Driver.stop\"",
")",
"for",
"requester",
"in",
"self",
".",
"requester_registry",
":",
"requester",
".",
"stop",
"(",
")",
"self",
".",
"requester_registry",
".",
"clear",
"(",
... | Stop services and requestors and then connection.
:return: self | [
"Stop",
"services",
"and",
"requestors",
"and",
"then",
"connection",
".",
":",
"return",
":",
"self"
] | python | train | 26.666667 |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/scene/node.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/node.py#L572-L591 | def node_path_transforms(self, node):
"""Return the list of transforms along the path to another node.
The transforms are listed in reverse order, such that the last
transform should be applied first when mapping from this node to
the other.
Parameters
-------... | [
"def",
"node_path_transforms",
"(",
"self",
",",
"node",
")",
":",
"a",
",",
"b",
"=",
"self",
".",
"node_path",
"(",
"node",
")",
"return",
"(",
"[",
"n",
".",
"transform",
"for",
"n",
"in",
"a",
"[",
":",
"-",
"1",
"]",
"]",
"+",
"[",
"n",
... | Return the list of transforms along the path to another node.
The transforms are listed in reverse order, such that the last
transform should be applied first when mapping from this node to
the other.
Parameters
----------
node : instance of Node
T... | [
"Return",
"the",
"list",
"of",
"transforms",
"along",
"the",
"path",
"to",
"another",
"node",
".",
"The",
"transforms",
"are",
"listed",
"in",
"reverse",
"order",
"such",
"that",
"the",
"last",
"transform",
"should",
"be",
"applied",
"first",
"when",
"mappin... | python | train | 30.95 |
Fantomas42/django-blog-zinnia | zinnia/templating.py | https://github.com/Fantomas42/django-blog-zinnia/blob/b4949304b104a8e1a7a7a0773cbfd024313c3a15/zinnia/templating.py#L16-L42 | def loop_template_list(loop_positions, instance, instance_type,
default_template, registry):
"""
Build a list of templates from a position within a loop
and a registry of templates.
"""
templates = []
local_loop_position = loop_positions[1]
global_loop_position = loop_... | [
"def",
"loop_template_list",
"(",
"loop_positions",
",",
"instance",
",",
"instance_type",
",",
"default_template",
",",
"registry",
")",
":",
"templates",
"=",
"[",
"]",
"local_loop_position",
"=",
"loop_positions",
"[",
"1",
"]",
"global_loop_position",
"=",
"lo... | Build a list of templates from a position within a loop
and a registry of templates. | [
"Build",
"a",
"list",
"of",
"templates",
"from",
"a",
"position",
"within",
"a",
"loop",
"and",
"a",
"registry",
"of",
"templates",
"."
] | python | train | 32.222222 |
basecrm/basecrm-python | basecrm/services.py | https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L2122-L2135 | def list(self, **params):
"""
Retrieve visit outcomes
Returns Visit Outcomes, according to the parameters provided
:calls: ``get /visit_outcomes``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which rep... | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"visit_outcomes",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/visit_outcomes\"",
",",
"params",
"=",
"params",
")",
"return",
"visit_outcomes"
] | Retrieve visit outcomes
Returns Visit Outcomes, according to the parameters provided
:calls: ``get /visit_outcomes``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of VisitOutcomes.
:r... | [
"Retrieve",
"visit",
"outcomes"
] | python | train | 35.142857 |
pybel/pybel-tools | src/pybel_tools/analysis/neurommsig/algorithm.py | https://github.com/pybel/pybel-tools/blob/3491adea0ac4ee60f57275ef72f9b73da6dbfe0c/src/pybel_tools/analysis/neurommsig/algorithm.py#L39-L85 | def get_neurommsig_scores(graph: BELGraph,
genes: List[Gene],
annotation: str = 'Subgraph',
ora_weight: Optional[float] = None,
hub_weight: Optional[float] = None,
top_percent: Optional[floa... | [
"def",
"get_neurommsig_scores",
"(",
"graph",
":",
"BELGraph",
",",
"genes",
":",
"List",
"[",
"Gene",
"]",
",",
"annotation",
":",
"str",
"=",
"'Subgraph'",
",",
"ora_weight",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
",",
"hub_weight",
":",
"Opt... | Preprocess the graph, stratify by the given annotation, then run the NeuroMMSig algorithm on each.
:param graph: A BEL graph
:param genes: A list of gene nodes
:param annotation: The annotation to use to stratify the graph to subgraphs
:param ora_weight: The relative weight of the over-enrichment analy... | [
"Preprocess",
"the",
"graph",
"stratify",
"by",
"the",
"given",
"annotation",
"then",
"run",
"the",
"NeuroMMSig",
"algorithm",
"on",
"each",
"."
] | python | valid | 43.638298 |
ff0000/scarlet | scarlet/accounts/views.py | https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/accounts/views.py#L99-L147 | def email_confirm(request, confirmation_key,
template_name='accounts/email_confirm_fail.html',
success_url=None, extra_context=None):
"""
Confirms an email address with a confirmation key.
Confirms a new email address by running :func:`User.objects.confirm_email`
met... | [
"def",
"email_confirm",
"(",
"request",
",",
"confirmation_key",
",",
"template_name",
"=",
"'accounts/email_confirm_fail.html'",
",",
"success_url",
"=",
"None",
",",
"extra_context",
"=",
"None",
")",
":",
"user",
"=",
"AccountsSignup",
".",
"objects",
".",
"con... | Confirms an email address with a confirmation key.
Confirms a new email address by running :func:`User.objects.confirm_email`
method. If the method returns an :class:`User` the user will have his new
e-mail address set and redirected to ``success_url``. If no ``User`` is
returned the user will be repre... | [
"Confirms",
"an",
"email",
"address",
"with",
"a",
"confirmation",
"key",
"."
] | python | train | 41.040816 |
mnick/scikit-tensor | sktensor/pyutils.py | https://github.com/mnick/scikit-tensor/blob/fe517e9661a08164b8d30d2dddf7c96aeeabcf36/sktensor/pyutils.py#L36-L46 | def func_attr(f, attr):
"""
Helper function to get the attribute of a function
like, name, code, defaults across Python 2.x and 3.x
"""
if hasattr(f, 'func_%s' % attr):
return getattr(f, 'func_%s' % attr)
elif hasattr(f, '__%s__' % attr):
return getattr(f, '__%s__' % attr)
el... | [
"def",
"func_attr",
"(",
"f",
",",
"attr",
")",
":",
"if",
"hasattr",
"(",
"f",
",",
"'func_%s'",
"%",
"attr",
")",
":",
"return",
"getattr",
"(",
"f",
",",
"'func_%s'",
"%",
"attr",
")",
"elif",
"hasattr",
"(",
"f",
",",
"'__%s__'",
"%",
"attr",
... | Helper function to get the attribute of a function
like, name, code, defaults across Python 2.x and 3.x | [
"Helper",
"function",
"to",
"get",
"the",
"attribute",
"of",
"a",
"function",
"like",
"name",
"code",
"defaults",
"across",
"Python",
"2",
".",
"x",
"and",
"3",
".",
"x"
] | python | train | 34.545455 |
bachya/regenmaschine | regenmaschine/client.py | https://github.com/bachya/regenmaschine/blob/99afb648fe454dc4a7d5db85a02a8b3b5d26f8bc/regenmaschine/client.py#L151-L163 | async def login(
host: str,
password: str,
websession: ClientSession,
*,
port: int = 8080,
ssl: bool = True,
request_timeout: int = DEFAULT_TIMEOUT) -> Controller:
"""Authenticate against a RainMachine device."""
print('regenmaschine.client.login() is depr... | [
"async",
"def",
"login",
"(",
"host",
":",
"str",
",",
"password",
":",
"str",
",",
"websession",
":",
"ClientSession",
",",
"*",
",",
"port",
":",
"int",
"=",
"8080",
",",
"ssl",
":",
"bool",
"=",
"True",
",",
"request_timeout",
":",
"int",
"=",
"... | Authenticate against a RainMachine device. | [
"Authenticate",
"against",
"a",
"RainMachine",
"device",
"."
] | python | train | 37.769231 |
python-hyper/wsproto | example/synchronous_server.py | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/example/synchronous_server.py#L44-L106 | def handle_connection(stream):
'''
Handle a connection.
The server operates a request/response cycle, so it performs a synchronous
loop:
1) Read data from network into wsproto
2) Get next wsproto event
3) Handle event
4) Send data from wsproto to network
:param stream: a socket st... | [
"def",
"handle_connection",
"(",
"stream",
")",
":",
"ws",
"=",
"WSConnection",
"(",
"ConnectionType",
".",
"SERVER",
")",
"# events is a generator that yields websocket event objects. Usually you",
"# would say `for event in ws.events()`, but the synchronous nature of this",
"# serv... | Handle a connection.
The server operates a request/response cycle, so it performs a synchronous
loop:
1) Read data from network into wsproto
2) Get next wsproto event
3) Handle event
4) Send data from wsproto to network
:param stream: a socket stream | [
"Handle",
"a",
"connection",
"."
] | python | train | 36.31746 |
SAP/PyHDB | pyhdb/protocol/parts.py | https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/protocol/parts.py#L225-L235 | def unpack_rows(self, parameters_metadata, connection):
"""Unpack output or input/output parameters from the stored procedure call result
:parameters_metadata: a stored procedure parameters metadata
:returns: parameter values
"""
values = []
for param in parameters_metada... | [
"def",
"unpack_rows",
"(",
"self",
",",
"parameters_metadata",
",",
"connection",
")",
":",
"values",
"=",
"[",
"]",
"for",
"param",
"in",
"parameters_metadata",
":",
"# Unpack OUT or INOUT parameters' values",
"if",
"param",
".",
"iotype",
"!=",
"parameter_directio... | Unpack output or input/output parameters from the stored procedure call result
:parameters_metadata: a stored procedure parameters metadata
:returns: parameter values | [
"Unpack",
"output",
"or",
"input",
"/",
"output",
"parameters",
"from",
"the",
"stored",
"procedure",
"call",
"result",
":",
"parameters_metadata",
":",
"a",
"stored",
"procedure",
"parameters",
"metadata",
":",
"returns",
":",
"parameter",
"values"
] | python | train | 49.090909 |
marcharper/python-ternary | ternary/heatmapping.py | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/heatmapping.py#L114-L135 | def hexagon_coordinates(i, j, k):
"""
Computes coordinates of the constituent hexagons of a hexagonal heatmap.
Parameters
----------
i, j, k: enumeration of the desired hexagon
Returns
-------
A numpy array of coordinates of the hexagon (unprojected)
"""
signature = ""
for... | [
"def",
"hexagon_coordinates",
"(",
"i",
",",
"j",
",",
"k",
")",
":",
"signature",
"=",
"\"\"",
"for",
"x",
"in",
"[",
"i",
",",
"j",
",",
"k",
"]",
":",
"if",
"x",
"==",
"0",
":",
"signature",
"+=",
"\"0\"",
"else",
":",
"signature",
"+=",
"\"... | Computes coordinates of the constituent hexagons of a hexagonal heatmap.
Parameters
----------
i, j, k: enumeration of the desired hexagon
Returns
-------
A numpy array of coordinates of the hexagon (unprojected) | [
"Computes",
"coordinates",
"of",
"the",
"constituent",
"hexagons",
"of",
"a",
"hexagonal",
"heatmap",
"."
] | python | train | 24.272727 |
spacetelescope/stsci.tools | lib/stsci/tools/wcsutil.py | https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/wcsutil.py#L866-L920 | def read_archive(self,header,prepend=None):
""" Extract a copy of WCS keywords from an open file header,
if they have already been created and remember the prefix
used for those keywords. Otherwise, setup the current WCS
keywords as the archive values.
"""
# S... | [
"def",
"read_archive",
"(",
"self",
",",
"header",
",",
"prepend",
"=",
"None",
")",
":",
"# Start by looking for the any backup WCS keywords to",
"# determine whether archived values are present and to set",
"# the prefix used.",
"_prefix",
"=",
"None",
"_archive",
"=",
"Fal... | Extract a copy of WCS keywords from an open file header,
if they have already been created and remember the prefix
used for those keywords. Otherwise, setup the current WCS
keywords as the archive values. | [
"Extract",
"a",
"copy",
"of",
"WCS",
"keywords",
"from",
"an",
"open",
"file",
"header",
"if",
"they",
"have",
"already",
"been",
"created",
"and",
"remember",
"the",
"prefix",
"used",
"for",
"those",
"keywords",
".",
"Otherwise",
"setup",
"the",
"current",
... | python | train | 39.363636 |
peerplays-network/python-peerplays | peerplays/cli/proposal.py | https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplays/cli/proposal.py#L39-L86 | def proposals(ctx, account):
""" List proposals
"""
proposals = Proposals(account)
t = PrettyTable(
[
"id",
"expiration",
"proposer",
"required approvals",
"available approvals",
"review period time",
"proposal",... | [
"def",
"proposals",
"(",
"ctx",
",",
"account",
")",
":",
"proposals",
"=",
"Proposals",
"(",
"account",
")",
"t",
"=",
"PrettyTable",
"(",
"[",
"\"id\"",
",",
"\"expiration\"",
",",
"\"proposer\"",
",",
"\"required approvals\"",
",",
"\"available approvals\"",
... | List proposals | [
"List",
"proposals"
] | python | train | 28.895833 |
bigchaindb/bigchaindb-driver | bigchaindb_driver/common/transaction.py | https://github.com/bigchaindb/bigchaindb-driver/blob/c294a535f0696bd19483ae11a4882b74e6fc061e/bigchaindb_driver/common/transaction.py#L945-L975 | def inputs_valid(self, outputs=None):
"""Validates the Inputs in the Transaction against given
Outputs.
Note:
Given a `CREATE` Transaction is passed,
dummy values for Outputs are submitted for validation that
evaluate parts of the validation-c... | [
"def",
"inputs_valid",
"(",
"self",
",",
"outputs",
"=",
"None",
")",
":",
"if",
"self",
".",
"operation",
"==",
"Transaction",
".",
"CREATE",
":",
"# NOTE: Since in the case of a `CREATE`-transaction we do not have",
"# to check for outputs, we're just submitting dummy... | Validates the Inputs in the Transaction against given
Outputs.
Note:
Given a `CREATE` Transaction is passed,
dummy values for Outputs are submitted for validation that
evaluate parts of the validation-checks to `True`.
Args:
... | [
"Validates",
"the",
"Inputs",
"in",
"the",
"Transaction",
"against",
"given",
"Outputs",
"."
] | python | train | 46.225806 |
Azure/azure-sdk-for-python | azure-servicemanagement-legacy/azure/servicemanagement/servicemanagementservice.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicemanagement-legacy/azure/servicemanagement/servicemanagementservice.py#L1211-L1220 | def delete_reserved_ip_address(self, name):
'''
Deletes a reserved IP address from the specified subscription.
name:
Required. Name of the reserved IP address.
'''
_validate_not_none('name', name)
return self._perform_delete(self._get_reserved_ip_path(name),
... | [
"def",
"delete_reserved_ip_address",
"(",
"self",
",",
"name",
")",
":",
"_validate_not_none",
"(",
"'name'",
",",
"name",
")",
"return",
"self",
".",
"_perform_delete",
"(",
"self",
".",
"_get_reserved_ip_path",
"(",
"name",
")",
",",
"as_async",
"=",
"True",... | Deletes a reserved IP address from the specified subscription.
name:
Required. Name of the reserved IP address. | [
"Deletes",
"a",
"reserved",
"IP",
"address",
"from",
"the",
"specified",
"subscription",
"."
] | python | test | 36.1 |
Legobot/Legobot | Legobot/Connectors/Slack.py | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L204-L227 | def get_users(self, condensed=False):
'''Grabs all users in the slack team
This should should only be used for getting list of all users. Do not
use it for searching users. Use get_user_info instead.
Args:
condensed (bool): if true triggers list condensing functionality
... | [
"def",
"get_users",
"(",
"self",
",",
"condensed",
"=",
"False",
")",
":",
"user_list",
"=",
"self",
".",
"slack_client",
".",
"api_call",
"(",
"'users.list'",
")",
"if",
"not",
"user_list",
".",
"get",
"(",
"'ok'",
")",
":",
"return",
"None",
"if",
"c... | Grabs all users in the slack team
This should should only be used for getting list of all users. Do not
use it for searching users. Use get_user_info instead.
Args:
condensed (bool): if true triggers list condensing functionality
Returns:
dict: Dict of users in... | [
"Grabs",
"all",
"users",
"in",
"the",
"slack",
"team"
] | python | train | 35.666667 |
arne-cl/discoursegraphs | src/discoursegraphs/util.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/util.py#L265-L275 | def xmlprint(element):
"""
pretty prints an ElementTree (or an Element of it), or the XML
representation of a SaltDocument (or an element
thereof, e.g. a node, edge, layer etc.)
"""
if isinstance(element, (etree._Element, etree._ElementTree)):
print etree.tostring(element, pretty_print=T... | [
"def",
"xmlprint",
"(",
"element",
")",
":",
"if",
"isinstance",
"(",
"element",
",",
"(",
"etree",
".",
"_Element",
",",
"etree",
".",
"_ElementTree",
")",
")",
":",
"print",
"etree",
".",
"tostring",
"(",
"element",
",",
"pretty_print",
"=",
"True",
... | pretty prints an ElementTree (or an Element of it), or the XML
representation of a SaltDocument (or an element
thereof, e.g. a node, edge, layer etc.) | [
"pretty",
"prints",
"an",
"ElementTree",
"(",
"or",
"an",
"Element",
"of",
"it",
")",
"or",
"the",
"XML",
"representation",
"of",
"a",
"SaltDocument",
"(",
"or",
"an",
"element",
"thereof",
"e",
".",
"g",
".",
"a",
"node",
"edge",
"layer",
"etc",
".",
... | python | train | 38.636364 |
nilp0inter/cpe | cpe/cpe2_3_fs.py | https://github.com/nilp0inter/cpe/blob/670d947472a7652af5149324977b50f9a7af9bcf/cpe/cpe2_3_fs.py#L201-L233 | def get_attribute_values(self, att_name):
"""
Returns the values of attribute "att_name" of CPE Name.
By default a only element in each part.
:param string att_name: Attribute name to get
:returns: List of attribute values
:rtype: list
:exception: ValueError - in... | [
"def",
"get_attribute_values",
"(",
"self",
",",
"att_name",
")",
":",
"lc",
"=",
"[",
"]",
"if",
"not",
"CPEComponent",
".",
"is_valid_attribute",
"(",
"att_name",
")",
":",
"errmsg",
"=",
"\"Invalid attribute name: {0}\"",
".",
"format",
"(",
"att_name",
")"... | Returns the values of attribute "att_name" of CPE Name.
By default a only element in each part.
:param string att_name: Attribute name to get
:returns: List of attribute values
:rtype: list
:exception: ValueError - invalid attribute name | [
"Returns",
"the",
"values",
"of",
"attribute",
"att_name",
"of",
"CPE",
"Name",
".",
"By",
"default",
"a",
"only",
"element",
"in",
"each",
"part",
"."
] | python | train | 30.636364 |
datastax/python-driver | cassandra/metadata.py | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/metadata.py#L1634-L1640 | def from_string(cls, token_string):
""" `token_string` should be the string representation from the server. """
# unhexlify works fine with unicode input in everythin but pypy3, where it Raises "TypeError: 'str' does not support the buffer interface"
if isinstance(token_string, six.text_type):
... | [
"def",
"from_string",
"(",
"cls",
",",
"token_string",
")",
":",
"# unhexlify works fine with unicode input in everythin but pypy3, where it Raises \"TypeError: 'str' does not support the buffer interface\"",
"if",
"isinstance",
"(",
"token_string",
",",
"six",
".",
"text_type",
")... | `token_string` should be the string representation from the server. | [
"token_string",
"should",
"be",
"the",
"string",
"representation",
"from",
"the",
"server",
"."
] | python | train | 64.285714 |
weso/CWR-DataApi | cwr/parser/encoder/standart/record.py | https://github.com/weso/CWR-DataApi/blob/f3b6ba8308c901b6ab87073c155c08e30692333c/cwr/parser/encoder/standart/record.py#L108-L121 | def try_encode(field_encoders, entity_dict):
"""
Inner encoding and try return string from entity dictionary
:param field_encoders:
:param entity_dict:
:return:
"""
result = ''
for field_encoder in field_encoders:
try:
result +=... | [
"def",
"try_encode",
"(",
"field_encoders",
",",
"entity_dict",
")",
":",
"result",
"=",
"''",
"for",
"field_encoder",
"in",
"field_encoders",
":",
"try",
":",
"result",
"+=",
"field_encoder",
".",
"encode",
"(",
"entity_dict",
")",
"except",
"KeyError",
"as",... | Inner encoding and try return string from entity dictionary
:param field_encoders:
:param entity_dict:
:return: | [
"Inner",
"encoding",
"and",
"try",
"return",
"string",
"from",
"entity",
"dictionary",
":",
"param",
"field_encoders",
":",
":",
"param",
"entity_dict",
":",
":",
"return",
":"
] | python | train | 30.428571 |
michaelpb/omnic | omnic/worker/manager.py | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/worker/manager.py#L32-L41 | def enqueue_sync(self, func, *func_args):
'''
Enqueue an arbitrary synchronous function.
Deprecated: Use async version instead
'''
worker = self.pick_sticky(0) # just pick first always
args = (func,) + func_args
coro = worker.enqueue(enums.Task.FUNC, args)
... | [
"def",
"enqueue_sync",
"(",
"self",
",",
"func",
",",
"*",
"func_args",
")",
":",
"worker",
"=",
"self",
".",
"pick_sticky",
"(",
"0",
")",
"# just pick first always",
"args",
"=",
"(",
"func",
",",
")",
"+",
"func_args",
"coro",
"=",
"worker",
".",
"e... | Enqueue an arbitrary synchronous function.
Deprecated: Use async version instead | [
"Enqueue",
"an",
"arbitrary",
"synchronous",
"function",
"."
] | python | train | 34.1 |
xflows/rdm | rdm/wrappers/wordification/wordification.py | https://github.com/xflows/rdm/blob/d984e2a0297e5fa8d799953bbd0dba79b05d403d/rdm/wrappers/wordification/wordification.py#L255-L270 | def prune(self, minimum_word_frequency_percentage=1):
"""
Filter out words that occur less than minimum_word_frequency times.
:param minimum_word_frequency_percentage: minimum frequency of words to keep
"""
pruned_resulting_documents = []
for document in self.result... | [
"def",
"prune",
"(",
"self",
",",
"minimum_word_frequency_percentage",
"=",
"1",
")",
":",
"pruned_resulting_documents",
"=",
"[",
"]",
"for",
"document",
"in",
"self",
".",
"resulting_documents",
":",
"new_document",
"=",
"[",
"]",
"for",
"word",
"in",
"docum... | Filter out words that occur less than minimum_word_frequency times.
:param minimum_word_frequency_percentage: minimum frequency of words to keep | [
"Filter",
"out",
"words",
"that",
"occur",
"less",
"than",
"minimum_word_frequency",
"times",
"."
] | python | train | 44.375 |
Erotemic/utool | utool/util_profile.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_profile.py#L123-L138 | def parse_timemap_from_blocks(profile_block_list):
"""
Build a map from times to line_profile blocks
"""
prefix_list = []
timemap = ut.ddict(list)
for ix in range(len(profile_block_list)):
block = profile_block_list[ix]
total_time = get_block_totaltime(block)
# Blocks wit... | [
"def",
"parse_timemap_from_blocks",
"(",
"profile_block_list",
")",
":",
"prefix_list",
"=",
"[",
"]",
"timemap",
"=",
"ut",
".",
"ddict",
"(",
"list",
")",
"for",
"ix",
"in",
"range",
"(",
"len",
"(",
"profile_block_list",
")",
")",
":",
"block",
"=",
"... | Build a map from times to line_profile blocks | [
"Build",
"a",
"map",
"from",
"times",
"to",
"line_profile",
"blocks"
] | python | train | 36.5625 |
IvanMalison/okcupyd | okcupyd/util/misc.py | https://github.com/IvanMalison/okcupyd/blob/46f4eaa9419098f6c299738ce148af55c64deb64/okcupyd/util/misc.py#L46-L64 | def add_command_line_options(add_argument, use_short_options=True):
"""
:param add_argument: The add_argument method of an ArgParser.
:param use_short_options: Whether or not to add short options.
"""
logger_args = ("--enable-logger",)
credentials_args = ("--credentials",)
if use_short_optio... | [
"def",
"add_command_line_options",
"(",
"add_argument",
",",
"use_short_options",
"=",
"True",
")",
":",
"logger_args",
"=",
"(",
"\"--enable-logger\"",
",",
")",
"credentials_args",
"=",
"(",
"\"--credentials\"",
",",
")",
"if",
"use_short_options",
":",
"logger_ar... | :param add_argument: The add_argument method of an ArgParser.
:param use_short_options: Whether or not to add short options. | [
":",
"param",
"add_argument",
":",
"The",
"add_argument",
"method",
"of",
"an",
"ArgParser",
".",
":",
"param",
"use_short_options",
":",
"Whether",
"or",
"not",
"to",
"add",
"short",
"options",
"."
] | python | train | 45.736842 |
aws/sagemaker-python-sdk | src/sagemaker/session.py | https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/session.py#L937-L985 | def endpoint_from_job(self, job_name, initial_instance_count, instance_type,
deployment_image=None, name=None, role=None, wait=True,
model_environment_vars=None, vpc_config_override=vpc_utils.VPC_CONFIG_DEFAULT,
accelerator_type=None):
... | [
"def",
"endpoint_from_job",
"(",
"self",
",",
"job_name",
",",
"initial_instance_count",
",",
"instance_type",
",",
"deployment_image",
"=",
"None",
",",
"name",
"=",
"None",
",",
"role",
"=",
"None",
",",
"wait",
"=",
"True",
",",
"model_environment_vars",
"=... | Create an ``Endpoint`` using the results of a successful training job.
Specify the job name, Docker image containing the inference code, and hardware configuration to deploy
the model. Internally the API, creates an Amazon SageMaker model (that describes the model artifacts and
the Docker image... | [
"Create",
"an",
"Endpoint",
"using",
"the",
"results",
"of",
"a",
"successful",
"training",
"job",
"."
] | python | train | 76.857143 |
bcbio/bcbio-nextgen | bcbio/cwl/main.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/main.py#L6-L12 | def run(args):
"""Run a CWL preparation pipeline.
"""
dirs, config, run_info_yaml = run_info.prep_system(args.sample_config, args.systemconfig)
integrations = args.integrations if hasattr(args, "integrations") else {}
world = run_info.organize(dirs, config, run_info_yaml, is_cwl=True, integrations=i... | [
"def",
"run",
"(",
"args",
")",
":",
"dirs",
",",
"config",
",",
"run_info_yaml",
"=",
"run_info",
".",
"prep_system",
"(",
"args",
".",
"sample_config",
",",
"args",
".",
"systemconfig",
")",
"integrations",
"=",
"args",
".",
"integrations",
"if",
"hasatt... | Run a CWL preparation pipeline. | [
"Run",
"a",
"CWL",
"preparation",
"pipeline",
"."
] | python | train | 62.714286 |
ArduPilot/MAVProxy | MAVProxy/modules/mavproxy_restserver.py | https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_restserver.py#L18-L25 | def mavlink_to_json(msg):
'''Translate mavlink python messages in json string'''
ret = '\"%s\": {' % msg._type
for fieldname in msg._fieldnames:
data = getattr(msg, fieldname)
ret += '\"%s\" : \"%s\", ' % (fieldname, data)
ret = ret[0:-2] + '}'
return ret | [
"def",
"mavlink_to_json",
"(",
"msg",
")",
":",
"ret",
"=",
"'\\\"%s\\\": {'",
"%",
"msg",
".",
"_type",
"for",
"fieldname",
"in",
"msg",
".",
"_fieldnames",
":",
"data",
"=",
"getattr",
"(",
"msg",
",",
"fieldname",
")",
"ret",
"+=",
"'\\\"%s\\\" : \\\"%s... | Translate mavlink python messages in json string | [
"Translate",
"mavlink",
"python",
"messages",
"in",
"json",
"string"
] | python | train | 35.5 |
TurboGears/gearbox | gearbox/commandmanager.py | https://github.com/TurboGears/gearbox/blob/df496ab28050ce6a4cc4c502488f5c5812f2baff/gearbox/commandmanager.py#L63-L89 | def find_command(self, argv):
"""Given an argument list, find a command and
return the processor and any remaining arguments.
"""
search_args = argv[:]
name = ''
while search_args:
if search_args[0].startswith('-'):
name = '%s %s' % (name, sear... | [
"def",
"find_command",
"(",
"self",
",",
"argv",
")",
":",
"search_args",
"=",
"argv",
"[",
":",
"]",
"name",
"=",
"''",
"while",
"search_args",
":",
"if",
"search_args",
"[",
"0",
"]",
".",
"startswith",
"(",
"'-'",
")",
":",
"name",
"=",
"'%s %s'",... | Given an argument list, find a command and
return the processor and any remaining arguments. | [
"Given",
"an",
"argument",
"list",
"find",
"a",
"command",
"and",
"return",
"the",
"processor",
"and",
"any",
"remaining",
"arguments",
"."
] | python | train | 44.37037 |
ManiacalLabs/BiblioPixel | bibliopixel/util/exception.py | https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/exception.py#L19-L24 | def report(function, *args, **kwds):
"""Run a function, catch, report and discard exceptions"""
try:
function(*args, **kwds)
except Exception:
traceback.print_exc() | [
"def",
"report",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"try",
":",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"except",
"Exception",
":",
"traceback",
".",
"print_exc",
"(",
")"
] | Run a function, catch, report and discard exceptions | [
"Run",
"a",
"function",
"catch",
"report",
"and",
"discard",
"exceptions"
] | python | valid | 31.166667 |
Grunny/zap-cli | zapcli/helpers.py | https://github.com/Grunny/zap-cli/blob/d58d4850ecfc5467badfac5e5bcc841d064bd419/zapcli/helpers.py#L19-L29 | def validate_ids(ctx, param, value):
"""Validate a list of IDs and convert them to a list."""
if not value:
return None
ids = [x.strip() for x in value.split(',')]
for id_item in ids:
if not id_item.isdigit():
raise click.BadParameter('Non-numeric value "{0}" provided for an... | [
"def",
"validate_ids",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"ids",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"value",
".",
"split",
"(",
"','",
")",
"]",
"for",
"id_item",
... | Validate a list of IDs and convert them to a list. | [
"Validate",
"a",
"list",
"of",
"IDs",
"and",
"convert",
"them",
"to",
"a",
"list",
"."
] | python | train | 31.636364 |
cloudera/impyla | impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py | https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L2692-L2700 | def append_partition_by_name(self, db_name, tbl_name, part_name):
"""
Parameters:
- db_name
- tbl_name
- part_name
"""
self.send_append_partition_by_name(db_name, tbl_name, part_name)
return self.recv_append_partition_by_name() | [
"def",
"append_partition_by_name",
"(",
"self",
",",
"db_name",
",",
"tbl_name",
",",
"part_name",
")",
":",
"self",
".",
"send_append_partition_by_name",
"(",
"db_name",
",",
"tbl_name",
",",
"part_name",
")",
"return",
"self",
".",
"recv_append_partition_by_name",... | Parameters:
- db_name
- tbl_name
- part_name | [
"Parameters",
":",
"-",
"db_name",
"-",
"tbl_name",
"-",
"part_name"
] | python | train | 28.222222 |
Metatab/tableintuit | tableintuit/types.py | https://github.com/Metatab/tableintuit/blob/9a3d500d5d90e44e6637dd17ca4c8dae474d6d4c/tableintuit/types.py#L242-L293 | def _resolved_type(self):
"""Return the type for the columns, and a flag to indicate that the
column has codes."""
import datetime
self.type_ratios = {test: (float(self.type_counts[test]) / float(self.count)) if self.count else None
for test, testf in tests +... | [
"def",
"_resolved_type",
"(",
"self",
")",
":",
"import",
"datetime",
"self",
".",
"type_ratios",
"=",
"{",
"test",
":",
"(",
"float",
"(",
"self",
".",
"type_counts",
"[",
"test",
"]",
")",
"/",
"float",
"(",
"self",
".",
"count",
")",
")",
"if",
... | Return the type for the columns, and a flag to indicate that the
column has codes. | [
"Return",
"the",
"type",
"for",
"the",
"columns",
"and",
"a",
"flag",
"to",
"indicate",
"that",
"the",
"column",
"has",
"codes",
"."
] | python | train | 30.038462 |
blockstack/blockstack-core | blockstack/blockstackd.py | https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L805-L826 | def rpc_get_DID_record(self, did, **con_info):
"""
Given a DID, return the name or subdomain it corresponds to
"""
if not isinstance(did, (str,unicode)):
return {'error': 'Invalid DID: not a string', 'http_status': 400}
try:
did_info = parse_DID(did)
... | [
"def",
"rpc_get_DID_record",
"(",
"self",
",",
"did",
",",
"*",
"*",
"con_info",
")",
":",
"if",
"not",
"isinstance",
"(",
"did",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"return",
"{",
"'error'",
":",
"'Invalid DID: not a string'",
",",
"'http_st... | Given a DID, return the name or subdomain it corresponds to | [
"Given",
"a",
"DID",
"return",
"the",
"name",
"or",
"subdomain",
"it",
"corresponds",
"to"
] | python | train | 35.363636 |
miguelgrinberg/python-socketio | socketio/base_manager.py | https://github.com/miguelgrinberg/python-socketio/blob/c0c1bf8d21e3597389b18938550a0724dd9676b7/socketio/base_manager.py#L97-L106 | def leave_room(self, sid, namespace, room):
"""Remove a client from a room."""
try:
del self.rooms[namespace][room][sid]
if len(self.rooms[namespace][room]) == 0:
del self.rooms[namespace][room]
if len(self.rooms[namespace]) == 0:
... | [
"def",
"leave_room",
"(",
"self",
",",
"sid",
",",
"namespace",
",",
"room",
")",
":",
"try",
":",
"del",
"self",
".",
"rooms",
"[",
"namespace",
"]",
"[",
"room",
"]",
"[",
"sid",
"]",
"if",
"len",
"(",
"self",
".",
"rooms",
"[",
"namespace",
"]... | Remove a client from a room. | [
"Remove",
"a",
"client",
"from",
"a",
"room",
"."
] | python | train | 38.1 |
SBRG/ssbio | ssbio/utils.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/utils.py#L660-L678 | def force_string(val=None):
"""Force a string representation of an object
Args:
val: object to parse into a string
Returns:
str: String representation
"""
if val is None:
return ''
if isinstance(val, list):
newval = [str(x) for x in val]
return ';'.join... | [
"def",
"force_string",
"(",
"val",
"=",
"None",
")",
":",
"if",
"val",
"is",
"None",
":",
"return",
"''",
"if",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"newval",
"=",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"val",
"]",
"return",
"... | Force a string representation of an object
Args:
val: object to parse into a string
Returns:
str: String representation | [
"Force",
"a",
"string",
"representation",
"of",
"an",
"object"
] | python | train | 20.631579 |
cackharot/suds-py3 | suds/client.py | https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/client.py#L763-L785 | def invoke(self, args, kwargs):
"""
Send the required soap message to invoke the specified method
@param args: A list of args for the method invoked.
@type args: list
@param kwargs: Named (keyword) args for the method invoked.
@type kwargs: dict
@return: The resul... | [
"def",
"invoke",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"simulation",
"=",
"kwargs",
"[",
"self",
".",
"injkey",
"]",
"msg",
"=",
"simulation",
".",
"get",
"(",
"'msg'",
")",
"reply",
"=",
"simulation",
".",
"get",
"(",
"'reply'",
")",
... | Send the required soap message to invoke the specified method
@param args: A list of args for the method invoked.
@type args: list
@param kwargs: Named (keyword) args for the method invoked.
@type kwargs: dict
@return: The result of the method invocation.
@rtype: I{builti... | [
"Send",
"the",
"required",
"soap",
"message",
"to",
"invoke",
"the",
"specified",
"method"
] | python | train | 39.043478 |
Jajcus/pyxmpp2 | pyxmpp2/streambase.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streambase.py#L556-L591 | def _got_features(self, features):
"""Process incoming <stream:features/> element.
[initiating entity only]
The received features node is available in `features`."""
self.features = features
logger.debug("got features, passing to event handlers...")
handled = self.event... | [
"def",
"_got_features",
"(",
"self",
",",
"features",
")",
":",
"self",
".",
"features",
"=",
"features",
"logger",
".",
"debug",
"(",
"\"got features, passing to event handlers...\"",
")",
"handled",
"=",
"self",
".",
"event",
"(",
"GotFeaturesEvent",
"(",
"sel... | Process incoming <stream:features/> element.
[initiating entity only]
The received features node is available in `features`. | [
"Process",
"incoming",
"<stream",
":",
"features",
"/",
">",
"element",
"."
] | python | valid | 47.305556 |
UCL-INGI/INGInious | inginious/agent/docker_agent/__init__.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/__init__.py#L157-L297 | def __new_job_sync(self, message, future_results):
""" Synchronous part of _new_job. Creates needed directories, copy files, and starts the container. """
course_id = message.course_id
task_id = message.task_id
debug = message.debug
environment_name = message.environment
... | [
"def",
"__new_job_sync",
"(",
"self",
",",
"message",
",",
"future_results",
")",
":",
"course_id",
"=",
"message",
".",
"course_id",
"task_id",
"=",
"message",
".",
"task_id",
"debug",
"=",
"message",
".",
"debug",
"environment_name",
"=",
"message",
".",
"... | Synchronous part of _new_job. Creates needed directories, copy files, and starts the container. | [
"Synchronous",
"part",
"of",
"_new_job",
".",
"Creates",
"needed",
"directories",
"copy",
"files",
"and",
"starts",
"the",
"container",
"."
] | python | train | 44.659574 |
csparpa/pyowm | pyowm/utils/xmlutils.py | https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/utils/xmlutils.py#L35-L50 | def DOM_node_to_XML(tree, xml_declaration=True):
"""
Prints a DOM tree to its Unicode representation.
:param tree: the input DOM tree
:type tree: an ``xml.etree.ElementTree.Element`` object
:param xml_declaration: if ``True`` (default) prints a leading XML
declaration line
:type xml_dec... | [
"def",
"DOM_node_to_XML",
"(",
"tree",
",",
"xml_declaration",
"=",
"True",
")",
":",
"result",
"=",
"ET",
".",
"tostring",
"(",
"tree",
",",
"encoding",
"=",
"'utf8'",
",",
"method",
"=",
"'xml'",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"not",
... | Prints a DOM tree to its Unicode representation.
:param tree: the input DOM tree
:type tree: an ``xml.etree.ElementTree.Element`` object
:param xml_declaration: if ``True`` (default) prints a leading XML
declaration line
:type xml_declaration: bool
:returns: Unicode object | [
"Prints",
"a",
"DOM",
"tree",
"to",
"its",
"Unicode",
"representation",
"."
] | python | train | 34.8125 |
tensorflow/probability | tensorflow_probability/python/distributions/zipf.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/zipf.py#L306-L322 | def _hat_integral(self, x):
"""Integral of the `hat` function, used for sampling.
We choose a `hat` function, h(x) = x^(-power), which is a continuous
(unnormalized) density touching each positive integer at the (unnormalized)
pmf. This function implements `hat` integral: H(x) = int_x^inf h(t) dt;
... | [
"def",
"_hat_integral",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"tf",
".",
"cast",
"(",
"x",
",",
"self",
".",
"power",
".",
"dtype",
")",
"t",
"=",
"self",
".",
"power",
"-",
"1.",
"return",
"tf",
".",
"exp",
"(",
"(",
"-",
"t",
")",
"*... | Integral of the `hat` function, used for sampling.
We choose a `hat` function, h(x) = x^(-power), which is a continuous
(unnormalized) density touching each positive integer at the (unnormalized)
pmf. This function implements `hat` integral: H(x) = int_x^inf h(t) dt;
which is needed for sampling purpos... | [
"Integral",
"of",
"the",
"hat",
"function",
"used",
"for",
"sampling",
"."
] | python | test | 35.647059 |
mitsei/dlkit | dlkit/handcar/repository/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/repository/managers.py#L2386-L2417 | def get_asset_temporal_assignment_session_for_repository(self, repository_id, proxy):
"""Gets the session for assigning temporal coverage of an asset for
the given repository.
arg: repository_id (osid.id.Id): the Id of the repository
arg proxy (osid.proxy.Proxy): a proxy
... | [
"def",
"get_asset_temporal_assignment_session_for_repository",
"(",
"self",
",",
"repository_id",
",",
"proxy",
")",
":",
"if",
"not",
"repository_id",
":",
"raise",
"NullArgument",
"(",
")",
"if",
"not",
"self",
".",
"supports_asset_temporal_assignment",
"(",
")",
... | Gets the session for assigning temporal coverage of an asset for
the given repository.
arg: repository_id (osid.id.Id): the Id of the repository
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetTemporalAssignmentSession) - an
AssetTemporalAssign... | [
"Gets",
"the",
"session",
"for",
"assigning",
"temporal",
"coverage",
"of",
"an",
"asset",
"for",
"the",
"given",
"repository",
"."
] | python | train | 45 |
rodionovd/machobot | machobot/common/macho_helpers.py | https://github.com/rodionovd/machobot/blob/60e10b63c2538a73dc8ec3ce636b3ed5bf09f524/machobot/common/macho_helpers.py#L13-L26 | def modify_macho_file_headers(macho_file_path, modificator_func):
""" Modifies headers of a Mach-O file at the given path by calling
the modificator function on each header.
Returns True on success, otherwise rises an exeption (e.g. from macholib)
"""
if not os.path.isfile(macho_file_path):
raise Exception("Yo... | [
"def",
"modify_macho_file_headers",
"(",
"macho_file_path",
",",
"modificator_func",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"macho_file_path",
")",
":",
"raise",
"Exception",
"(",
"\"You must specify a real executable path as a target\"",
")",
"... | Modifies headers of a Mach-O file at the given path by calling
the modificator function on each header.
Returns True on success, otherwise rises an exeption (e.g. from macholib) | [
"Modifies",
"headers",
"of",
"a",
"Mach",
"-",
"O",
"file",
"at",
"the",
"given",
"path",
"by",
"calling",
"the",
"modificator",
"function",
"on",
"each",
"header",
".",
"Returns",
"True",
"on",
"success",
"otherwise",
"rises",
"an",
"exeption",
"(",
"e",
... | python | train | 34.857143 |
ThreatConnect-Inc/tcex | tcex/tcex_bin_package.py | https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_bin_package.py#L135-L159 | def commit_hash(self):
"""Return the current commit hash if available.
This is not a required task so best effort is fine. In other words this is not guaranteed
to work 100% of the time.
"""
commit_hash = None
branch = None
branch_file = '.git/HEAD' # ref: refs/... | [
"def",
"commit_hash",
"(",
"self",
")",
":",
"commit_hash",
"=",
"None",
"branch",
"=",
"None",
"branch_file",
"=",
"'.git/HEAD'",
"# ref: refs/heads/develop",
"# get current branch",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"branch_file",
")",
":",
"with",
... | Return the current commit hash if available.
This is not a required task so best effort is fine. In other words this is not guaranteed
to work 100% of the time. | [
"Return",
"the",
"current",
"commit",
"hash",
"if",
"available",
"."
] | python | train | 34.56 |
mgraffg/EvoDAG | EvoDAG/gp.py | https://github.com/mgraffg/EvoDAG/blob/e11fa1fd1ca9e69cca92696c86661a3dc7b3a1d5/EvoDAG/gp.py#L43-L56 | def _eval(self):
"Evaluates a individual using recursion and self._pos as pointer"
pos = self._pos
self._pos += 1
node = self._ind[pos]
if isinstance(node, Function):
args = [self._eval() for x in range(node.nargs)]
node.eval(args)
for x in arg... | [
"def",
"_eval",
"(",
"self",
")",
":",
"pos",
"=",
"self",
".",
"_pos",
"self",
".",
"_pos",
"+=",
"1",
"node",
"=",
"self",
".",
"_ind",
"[",
"pos",
"]",
"if",
"isinstance",
"(",
"node",
",",
"Function",
")",
":",
"args",
"=",
"[",
"self",
"."... | Evaluates a individual using recursion and self._pos as pointer | [
"Evaluates",
"a",
"individual",
"using",
"recursion",
"and",
"self",
".",
"_pos",
"as",
"pointer"
] | python | train | 31.071429 |
HDI-Project/MLBlocks | mlblocks/mlpipeline.py | https://github.com/HDI-Project/MLBlocks/blob/e1ca77bce3c4537c0800a4c1395e1b6bbde5465d/mlblocks/mlpipeline.py#L191-L236 | def fit(self, X=None, y=None, **kwargs):
"""Fit the blocks of this pipeline.
Sequentially call the `fit` and the `produce` methods of each block,
capturing the outputs each `produce` method before calling the `fit`
method of the next one.
During the whole process a context dict... | [
"def",
"fit",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"{",
"'X'",
":",
"X",
",",
"'y'",
":",
"y",
"}",
"context",
".",
"update",
"(",
"kwargs",
")",
"last_block_name",
"=",
... | Fit the blocks of this pipeline.
Sequentially call the `fit` and the `produce` methods of each block,
capturing the outputs each `produce` method before calling the `fit`
method of the next one.
During the whole process a context dictionary is built, where both the
passed argum... | [
"Fit",
"the",
"blocks",
"of",
"this",
"pipeline",
"."
] | python | train | 42.608696 |
GPflow/GPflow | gpflow/multioutput/conditionals.py | https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/multioutput/conditionals.py#L274-L339 | def independent_interdomain_conditional(Kmn, Kmm, Knn, f, *, full_cov=False, full_output_cov=False,
q_sqrt=None, white=False):
"""
The inducing outputs live in the g-space (R^L).
Interdomain conditional calculation.
:param Kmn: M x L x N x P
:param Kmm: L x M... | [
"def",
"independent_interdomain_conditional",
"(",
"Kmn",
",",
"Kmm",
",",
"Knn",
",",
"f",
",",
"*",
",",
"full_cov",
"=",
"False",
",",
"full_output_cov",
"=",
"False",
",",
"q_sqrt",
"=",
"None",
",",
"white",
"=",
"False",
")",
":",
"logger",
".",
... | The inducing outputs live in the g-space (R^L).
Interdomain conditional calculation.
:param Kmn: M x L x N x P
:param Kmm: L x M x M
:param Knn: N x P or N x N or P x N x N or N x P x N x P
:param f: data matrix, M x L
:param q_sqrt: L x M x M or M x L
:param full_cov: calculate cov... | [
"The",
"inducing",
"outputs",
"live",
"in",
"the",
"g",
"-",
"space",
"(",
"R^L",
")",
".",
"Interdomain",
"conditional",
"calculation",
"."
] | python | train | 47.484848 |
oscarbranson/latools | latools/helpers/helpers.py | https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/helpers/helpers.py#L220-L237 | def bool_2_indices(a):
"""
Convert boolean array into a 2D array of (start, stop) pairs.
"""
if any(a):
lims = []
lims.append(np.where(a[:-1] != a[1:])[0])
if a[0]:
lims.append([0])
if a[-1]:
lims.append([len(a) - 1])
lims = np.concatenate... | [
"def",
"bool_2_indices",
"(",
"a",
")",
":",
"if",
"any",
"(",
"a",
")",
":",
"lims",
"=",
"[",
"]",
"lims",
".",
"append",
"(",
"np",
".",
"where",
"(",
"a",
"[",
":",
"-",
"1",
"]",
"!=",
"a",
"[",
"1",
":",
"]",
")",
"[",
"0",
"]",
"... | Convert boolean array into a 2D array of (start, stop) pairs. | [
"Convert",
"boolean",
"array",
"into",
"a",
"2D",
"array",
"of",
"(",
"start",
"stop",
")",
"pairs",
"."
] | python | test | 22.944444 |
OSSOS/MOP | src/ossos/core/ossos/storage.py | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/storage.py#L428-L436 | def get_process_tag(program, ccd, version='p'):
"""
make a process tag have a suffix indicating which ccd its for.
@param program: Name of the process that a tag is built for.
@param ccd: the CCD number that this process ran on.
@param version: The version of the exposure (s, p, o) that the process ... | [
"def",
"get_process_tag",
"(",
"program",
",",
"ccd",
",",
"version",
"=",
"'p'",
")",
":",
"return",
"\"%s_%s%s\"",
"%",
"(",
"program",
",",
"str",
"(",
"version",
")",
",",
"str",
"(",
"ccd",
")",
".",
"zfill",
"(",
"2",
")",
")"
] | make a process tag have a suffix indicating which ccd its for.
@param program: Name of the process that a tag is built for.
@param ccd: the CCD number that this process ran on.
@param version: The version of the exposure (s, p, o) that the process ran on.
@return: The string that represents the processi... | [
"make",
"a",
"process",
"tag",
"have",
"a",
"suffix",
"indicating",
"which",
"ccd",
"its",
"for",
"."
] | python | train | 50.333333 |
sourcesimian/pyPlugin | pyplugin/pluginloader.py | https://github.com/sourcesimian/pyPlugin/blob/6a7c31e40b30a418865a3b2de19291da341ddcc8/pyplugin/pluginloader.py#L104-L125 | def __find_child_classes(self, file):
"""
Return a list of all <__base_class> based classes found in <file>
"""
child_classes = []
folder, name = os.path.split(file)
name = os.path.splitext(name)[0]
import imp
module = imp.load_source(name, file)
... | [
"def",
"__find_child_classes",
"(",
"self",
",",
"file",
")",
":",
"child_classes",
"=",
"[",
"]",
"folder",
",",
"name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"file",
")",
"name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
"["... | Return a list of all <__base_class> based classes found in <file> | [
"Return",
"a",
"list",
"of",
"all",
"<__base_class",
">",
"based",
"classes",
"found",
"in",
"<file",
">"
] | python | train | 27.954545 |
dhylands/rshell | rshell/main.py | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1808-L1815 | def print(self, *args, end='\n', file=None):
"""Convenience function so you don't need to remember to put the \n
at the end of the line.
"""
if file is None:
file = self.stdout
s = ' '.join(str(arg) for arg in args) + end
file.write(s) | [
"def",
"print",
"(",
"self",
",",
"*",
"args",
",",
"end",
"=",
"'\\n'",
",",
"file",
"=",
"None",
")",
":",
"if",
"file",
"is",
"None",
":",
"file",
"=",
"self",
".",
"stdout",
"s",
"=",
"' '",
".",
"join",
"(",
"str",
"(",
"arg",
")",
"for"... | Convenience function so you don't need to remember to put the \n
at the end of the line. | [
"Convenience",
"function",
"so",
"you",
"don",
"t",
"need",
"to",
"remember",
"to",
"put",
"the",
"\\",
"n",
"at",
"the",
"end",
"of",
"the",
"line",
"."
] | python | train | 36.375 |
yjzhang/uncurl_python | uncurl/dimensionality_reduction.py | https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/dimensionality_reduction.py#L64-L91 | def dim_reduce_data(data, d):
"""
Does a MDS on the data directly, not on the means.
Args:
data (array): genes x cells
d (int): desired dimensionality
Returns:
X, a cells x d matrix
"""
genes, cells = data.shape
distances = np.zeros((cells, cells))
for i in rang... | [
"def",
"dim_reduce_data",
"(",
"data",
",",
"d",
")",
":",
"genes",
",",
"cells",
"=",
"data",
".",
"shape",
"distances",
"=",
"np",
".",
"zeros",
"(",
"(",
"cells",
",",
"cells",
")",
")",
"for",
"i",
"in",
"range",
"(",
"cells",
")",
":",
"for"... | Does a MDS on the data directly, not on the means.
Args:
data (array): genes x cells
d (int): desired dimensionality
Returns:
X, a cells x d matrix | [
"Does",
"a",
"MDS",
"on",
"the",
"data",
"directly",
"not",
"on",
"the",
"means",
"."
] | python | train | 30.285714 |
Kozea/pygal | pygal/util.py | https://github.com/Kozea/pygal/blob/5e25c98a59a0642eecd9fcc5dbfeeb2190fbb5e7/pygal/util.py#L301-L305 | def compose(f, g):
"""Chain functions"""
fun = lambda *args, **kwargs: f(g(*args, **kwargs))
fun.__name__ = "%s o %s" % (f.__name__, g.__name__)
return fun | [
"def",
"compose",
"(",
"f",
",",
"g",
")",
":",
"fun",
"=",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"f",
"(",
"g",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"fun",
".",
"__name__",
"=",
"\"%s o %s\"",
"%",
"(",
"f",
... | Chain functions | [
"Chain",
"functions"
] | python | train | 33.4 |
wichmannpas/django-rest-authtoken | rest_authtoken/auth.py | https://github.com/wichmannpas/django-rest-authtoken/blob/ef9153a64bfa5c30be10b0c53a74bd1d11f02cc6/rest_authtoken/auth.py#L13-L35 | def authenticate(self, request):
"""
Authenticate the request and return a two-tuple of (user, token).
"""
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'token':
return None
if len(auth) == 1:
msg = _('Invali... | [
"def",
"authenticate",
"(",
"self",
",",
"request",
")",
":",
"auth",
"=",
"get_authorization_header",
"(",
"request",
")",
".",
"split",
"(",
")",
"if",
"not",
"auth",
"or",
"auth",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"!=",
"b'token'",
":",
"retu... | Authenticate the request and return a two-tuple of (user, token). | [
"Authenticate",
"the",
"request",
"and",
"return",
"a",
"two",
"-",
"tuple",
"of",
"(",
"user",
"token",
")",
"."
] | python | train | 32.217391 |
genialis/resolwe | resolwe/flow/utils/stats.py | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/utils/stats.py#L30-L46 | def update(self, num):
"""Update metrics with the new number."""
num = float(num)
self.count += 1
self.low = min(self.low, num)
self.high = max(self.high, num)
# Welford's online mean and variance algorithm.
delta = num - self.mean
self.mean = self.mean +... | [
"def",
"update",
"(",
"self",
",",
"num",
")",
":",
"num",
"=",
"float",
"(",
"num",
")",
"self",
".",
"count",
"+=",
"1",
"self",
".",
"low",
"=",
"min",
"(",
"self",
".",
"low",
",",
"num",
")",
"self",
".",
"high",
"=",
"max",
"(",
"self",... | Update metrics with the new number. | [
"Update",
"metrics",
"with",
"the",
"new",
"number",
"."
] | python | train | 34.470588 |
crytic/slither | slither/core/dominators/utils.py | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/dominators/utils.py#L11-L45 | def compute_dominators(nodes):
'''
Naive implementation of Cooper, Harvey, Kennedy algo
See 'A Simple,Fast Dominance Algorithm'
Compute strict domniators
'''
changed = True
for n in nodes:
n.dominators = set(nodes)
while changed:
changed = False
fo... | [
"def",
"compute_dominators",
"(",
"nodes",
")",
":",
"changed",
"=",
"True",
"for",
"n",
"in",
"nodes",
":",
"n",
".",
"dominators",
"=",
"set",
"(",
"nodes",
")",
"while",
"changed",
":",
"changed",
"=",
"False",
"for",
"node",
"in",
"nodes",
":",
"... | Naive implementation of Cooper, Harvey, Kennedy algo
See 'A Simple,Fast Dominance Algorithm'
Compute strict domniators | [
"Naive",
"implementation",
"of",
"Cooper",
"Harvey",
"Kennedy",
"algo",
"See",
"A",
"Simple",
"Fast",
"Dominance",
"Algorithm"
] | python | train | 29.142857 |
gem/oq-engine | openquake/calculators/export/hazard.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/calculators/export/hazard.py#L333-L373 | def export_hcurves_csv(ekey, dstore):
"""
Exports the hazard curves into several .csv files
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object
"""
oq = dstore['oqparam']
info = get_info(dstore)
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
R... | [
"def",
"export_hcurves_csv",
"(",
"ekey",
",",
"dstore",
")",
":",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"info",
"=",
"get_info",
"(",
"dstore",
")",
"rlzs_assoc",
"=",
"dstore",
"[",
"'csm_info'",
"]",
".",
"get_rlzs_assoc",
"(",
")",
"R",
"=",
... | Exports the hazard curves into several .csv files
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object | [
"Exports",
"the",
"hazard",
"curves",
"into",
"several",
".",
"csv",
"files"
] | python | train | 42.317073 |
yougov/mongo-connector | mongo_connector/namespace_config.py | https://github.com/yougov/mongo-connector/blob/557cafd4b54c848cd54ef28a258391a154650cb4/mongo_connector/namespace_config.py#L261-L283 | def unmap_namespace(self, plain_target_ns):
"""Given a plain target namespace, return the corresponding source
namespace.
"""
# Return the same namespace if there are no included namespaces.
if not self._regex_map and not self._plain:
return plain_target_ns
s... | [
"def",
"unmap_namespace",
"(",
"self",
",",
"plain_target_ns",
")",
":",
"# Return the same namespace if there are no included namespaces.",
"if",
"not",
"self",
".",
"_regex_map",
"and",
"not",
"self",
".",
"_plain",
":",
"return",
"plain_target_ns",
"src_name_set",
"=... | Given a plain target namespace, return the corresponding source
namespace. | [
"Given",
"a",
"plain",
"target",
"namespace",
"return",
"the",
"corresponding",
"source",
"namespace",
"."
] | python | train | 39.478261 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.