repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
makinacorpus/django-tracking-fields | tracking_fields/decorators.py | https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L90-L107 | def _track_class(cls, fields):
""" Track fields on the specified model """
# Small tests to ensure everything is all right
assert not getattr(cls, '_is_tracked', False)
for field in fields:
_track_class_field(cls, field)
_add_signals_to_cls(cls)
# Mark the class as tracked
cls._is... | [
"def",
"_track_class",
"(",
"cls",
",",
"fields",
")",
":",
"# Small tests to ensure everything is all right",
"assert",
"not",
"getattr",
"(",
"cls",
",",
"'_is_tracked'",
",",
"False",
")",
"for",
"field",
"in",
"fields",
":",
"_track_class_field",
"(",
"cls",
... | Track fields on the specified model | [
"Track",
"fields",
"on",
"the",
"specified",
"model"
] | python | train |
wtolson/gnsq | gnsq/nsqd.py | https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L442-L445 | def ready(self, count):
"""Indicate you are ready to receive ``count`` messages."""
self.ready_count = count
self.send(nsq.ready(count)) | [
"def",
"ready",
"(",
"self",
",",
"count",
")",
":",
"self",
".",
"ready_count",
"=",
"count",
"self",
".",
"send",
"(",
"nsq",
".",
"ready",
"(",
"count",
")",
")"
] | Indicate you are ready to receive ``count`` messages. | [
"Indicate",
"you",
"are",
"ready",
"to",
"receive",
"count",
"messages",
"."
] | python | train |
maaku/python-bitcoin | bitcoin/authtree.py | https://github.com/maaku/python-bitcoin/blob/1b80c284170fd3f547cc45f4700ce169f3f99641/bitcoin/authtree.py#L429-L440 | def _forward_iterator(self):
"Returns a forward iterator over the trie"
path = [(self, 0, Bits())]
while path:
node, idx, prefix = path.pop()
if idx==0 and node.value is not None and not node.prune_value:
yield (self._unpickle_key(prefix), self._unpickle_v... | [
"def",
"_forward_iterator",
"(",
"self",
")",
":",
"path",
"=",
"[",
"(",
"self",
",",
"0",
",",
"Bits",
"(",
")",
")",
"]",
"while",
"path",
":",
"node",
",",
"idx",
",",
"prefix",
"=",
"path",
".",
"pop",
"(",
")",
"if",
"idx",
"==",
"0",
"... | Returns a forward iterator over the trie | [
"Returns",
"a",
"forward",
"iterator",
"over",
"the",
"trie"
] | python | train |
shmir/PyIxNetwork | ixnetwork/ixn_app.py | https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/ixn_app.py#L34-L52 | def init_ixn(api, logger, install_dir=None):
""" Create IXN object.
:param api: tcl/python/rest
:type api: trafficgenerator.tgn_utils.ApiType
:param logger: logger object
:param install_dir: IXN installation directory
:return: IXN object
"""
if api == ApiType.tcl:
api_wrapper =... | [
"def",
"init_ixn",
"(",
"api",
",",
"logger",
",",
"install_dir",
"=",
"None",
")",
":",
"if",
"api",
"==",
"ApiType",
".",
"tcl",
":",
"api_wrapper",
"=",
"IxnTclWrapper",
"(",
"logger",
",",
"install_dir",
")",
"elif",
"api",
"==",
"ApiType",
".",
"p... | Create IXN object.
:param api: tcl/python/rest
:type api: trafficgenerator.tgn_utils.ApiType
:param logger: logger object
:param install_dir: IXN installation directory
:return: IXN object | [
"Create",
"IXN",
"object",
"."
] | python | train |
minrk/findspark | findspark.py | https://github.com/minrk/findspark/blob/20c945d5136269ca56b1341786c49087faa7c75e/findspark.py#L41-L65 | def change_rc(spark_home, spark_python, py4j):
"""Persists changes to environment by changing shell config.
Adds lines to .bashrc to set environment variables
including the adding of dependencies to the system path. Will only
edit this file if they already exist. Currently only works for bash.
Par... | [
"def",
"change_rc",
"(",
"spark_home",
",",
"spark_python",
",",
"py4j",
")",
":",
"bashrc_location",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~/.bashrc\"",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"bashrc_location",
")",
":",
"with",
... | Persists changes to environment by changing shell config.
Adds lines to .bashrc to set environment variables
including the adding of dependencies to the system path. Will only
edit this file if they already exist. Currently only works for bash.
Parameters
----------
spark_home : str
Pa... | [
"Persists",
"changes",
"to",
"environment",
"by",
"changing",
"shell",
"config",
"."
] | python | train |
open-homeautomation/pknx | knxip/core.py | https://github.com/open-homeautomation/pknx/blob/a8aed8271563923c447aa330ba7c1c2927286f7a/knxip/core.py#L165-L193 | def from_frame(cls, frame):
"""Create a KNXMessage object from the frame format."""
message = cls()
# Check checksum first
checksum = 0
for i in range(0, len(frame) - 1):
checksum += frame[i]
if (checksum % 0x100) != frame[len(frame) - 1]:
raise ... | [
"def",
"from_frame",
"(",
"cls",
",",
"frame",
")",
":",
"message",
"=",
"cls",
"(",
")",
"# Check checksum first",
"checksum",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"frame",
")",
"-",
"1",
")",
":",
"checksum",
"+=",
"fra... | Create a KNXMessage object from the frame format. | [
"Create",
"a",
"KNXMessage",
"object",
"from",
"the",
"frame",
"format",
"."
] | python | train |
mfitzp/padua | padua/analysis.py | https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/analysis.py#L26-L48 | def correlation(df, rowvar=False):
"""
Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef``
Input data is masked to ignore NaNs when calculating correlations. Data is returned as
a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to
both axes.
... | [
"def",
"correlation",
"(",
"df",
",",
"rowvar",
"=",
"False",
")",
":",
"# Create a correlation matrix for all correlations",
"# of the columns (filled with na for all values)",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"maskv",
"=",
"np",
".",
"ma",
".",
"masked_wher... | Calculate column-wise Pearson correlations using ``numpy.ma.corrcoef``
Input data is masked to ignore NaNs when calculating correlations. Data is returned as
a Pandas ``DataFrame`` of column_n x column_n dimensions, with column index copied to
both axes.
:param df: Pandas DataFrame
:return: Pandas... | [
"Calculate",
"column",
"-",
"wise",
"Pearson",
"correlations",
"using",
"numpy",
".",
"ma",
".",
"corrcoef"
] | python | train |
rackerlabs/rackspace-python-neutronclient | neutronclient/v2_0/client.py | https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/v2_0/client.py#L1085-L1088 | def show_lbaas_healthmonitor(self, lbaas_healthmonitor, **_params):
"""Fetches information for a lbaas_healthmonitor."""
return self.get(self.lbaas_healthmonitor_path % (lbaas_healthmonitor),
params=_params) | [
"def",
"show_lbaas_healthmonitor",
"(",
"self",
",",
"lbaas_healthmonitor",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"get",
"(",
"self",
".",
"lbaas_healthmonitor_path",
"%",
"(",
"lbaas_healthmonitor",
")",
",",
"params",
"=",
"_params",
")"... | Fetches information for a lbaas_healthmonitor. | [
"Fetches",
"information",
"for",
"a",
"lbaas_healthmonitor",
"."
] | python | train |
enkore/i3pystatus | i3pystatus/core/modules.py | https://github.com/enkore/i3pystatus/blob/14cfde967cecf79b40e223e35a04600f4c875af7/i3pystatus/core/modules.py#L254-L276 | def text_to_pango(self):
"""
Replaces all ampersands in `full_text` and `short_text` attributes of
`self.output` with `&`.
It is called internally when pango markup is used.
Can be called multiple times (`&` won't change to `&`).
"""
def replace(... | [
"def",
"text_to_pango",
"(",
"self",
")",
":",
"def",
"replace",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"split",
"(",
"\"&\"",
")",
"out",
"=",
"s",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"s",
")",
"-",
"1",
")",
":",
... | Replaces all ampersands in `full_text` and `short_text` attributes of
`self.output` with `&`.
It is called internally when pango markup is used.
Can be called multiple times (`&` won't change to `&`). | [
"Replaces",
"all",
"ampersands",
"in",
"full_text",
"and",
"short_text",
"attributes",
"of",
"self",
".",
"output",
"with",
"&",
";",
"."
] | python | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/build_request.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/build_request.py#L31-L37 | def __x_product (property_sets):
""" Return the cross-product of all elements of property_sets, less any
that would contain conflicting values for single-valued features.
"""
assert is_iterable_typed(property_sets, property_set.PropertySet)
x_product_seen = set()
return __x_product_aux (prop... | [
"def",
"__x_product",
"(",
"property_sets",
")",
":",
"assert",
"is_iterable_typed",
"(",
"property_sets",
",",
"property_set",
".",
"PropertySet",
")",
"x_product_seen",
"=",
"set",
"(",
")",
"return",
"__x_product_aux",
"(",
"property_sets",
",",
"x_product_seen",... | Return the cross-product of all elements of property_sets, less any
that would contain conflicting values for single-valued features. | [
"Return",
"the",
"cross",
"-",
"product",
"of",
"all",
"elements",
"of",
"property_sets",
"less",
"any",
"that",
"would",
"contain",
"conflicting",
"values",
"for",
"single",
"-",
"valued",
"features",
"."
] | python | train |
opengisch/pum | pum/core/upgrader.py | https://github.com/opengisch/pum/blob/eaf6af92d723ace60b9e982d7f69b98e00606959/pum/core/upgrader.py#L429-L462 | def set_baseline(self, version):
"""Set the baseline into the creation information table
version: str
The version of the current database to set in the information
table. The baseline must be in the format x.x.x where x are numbers.
"""
pattern = re.compile(r"^\d... | [
"def",
"set_baseline",
"(",
"self",
",",
"version",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r\"^\\d+\\.\\d+\\.\\d+$\"",
")",
"if",
"not",
"re",
".",
"match",
"(",
"pattern",
",",
"version",
")",
":",
"raise",
"ValueError",
"(",
"'Wrong versio... | Set the baseline into the creation information table
version: str
The version of the current database to set in the information
table. The baseline must be in the format x.x.x where x are numbers. | [
"Set",
"the",
"baseline",
"into",
"the",
"creation",
"information",
"table"
] | python | train |
boriel/zxbasic | asmparse.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/asmparse.py#L1191-L1207 | def p_jrjp(p):
""" asm : JP expr
| JR expr
| CALL expr
| DJNZ expr
| JP pexpr
| JR pexpr
| CALL pexpr
| DJNZ pexpr
"""
if p[1] in ('JR', 'DJNZ'):
op = 'N'
p[2] = Expr.makenode(Container('-', p.lineno(1)), p[2... | [
"def",
"p_jrjp",
"(",
"p",
")",
":",
"if",
"p",
"[",
"1",
"]",
"in",
"(",
"'JR'",
",",
"'DJNZ'",
")",
":",
"op",
"=",
"'N'",
"p",
"[",
"2",
"]",
"=",
"Expr",
".",
"makenode",
"(",
"Container",
"(",
"'-'",
",",
"p",
".",
"lineno",
"(",
"1",
... | asm : JP expr
| JR expr
| CALL expr
| DJNZ expr
| JP pexpr
| JR pexpr
| CALL pexpr
| DJNZ pexpr | [
"asm",
":",
"JP",
"expr",
"|",
"JR",
"expr",
"|",
"CALL",
"expr",
"|",
"DJNZ",
"expr",
"|",
"JP",
"pexpr",
"|",
"JR",
"pexpr",
"|",
"CALL",
"pexpr",
"|",
"DJNZ",
"pexpr"
] | python | train |
mdgoldberg/sportsref | sportsref/nfl/pbp.py | https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nfl/pbp.py#L361-L480 | def _clean_features(struct):
"""Cleans up the features collected in parse_play_details.
:struct: Pandas Series of features parsed from details string.
:returns: the same dict, but with cleaner features (e.g., convert bools,
ints, etc.)
"""
struct = dict(struct)
# First, clean up play type b... | [
"def",
"_clean_features",
"(",
"struct",
")",
":",
"struct",
"=",
"dict",
"(",
"struct",
")",
"# First, clean up play type bools",
"ptypes",
"=",
"[",
"'isKickoff'",
",",
"'isTimeout'",
",",
"'isFieldGoal'",
",",
"'isPunt'",
",",
"'isKneel'",
",",
"'isSpike'",
"... | Cleans up the features collected in parse_play_details.
:struct: Pandas Series of features parsed from details string.
:returns: the same dict, but with cleaner features (e.g., convert bools,
ints, etc.) | [
"Cleans",
"up",
"the",
"features",
"collected",
"in",
"parse_play_details",
"."
] | python | test |
joyent/python-manta | manta/client.py | https://github.com/joyent/python-manta/blob/f68ef142bdbac058c981e3b28e18d77612f5b7c6/manta/client.py#L165-L220 | def _request(self,
path,
method="GET",
query=None,
body=None,
headers=None):
"""Make a Manta request
...
@returns (res, content)
"""
assert path.startswith('/'), "bogus path: %r" % path
... | [
"def",
"_request",
"(",
"self",
",",
"path",
",",
"method",
"=",
"\"GET\"",
",",
"query",
"=",
"None",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"assert",
"path",
".",
"startswith",
"(",
"'/'",
")",
",",
"\"bogus path: %r\"",
"... | Make a Manta request
...
@returns (res, content) | [
"Make",
"a",
"Manta",
"request"
] | python | train |
cs50/lib50 | lib50/_api.py | https://github.com/cs50/lib50/blob/941767f6c0a3b81af0cdea48c25c8d5a761086eb/lib50/_api.py#L260-L306 | def prepare(tool, branch, user, included):
"""
Prepare git for pushing
Check that there are no permission errors
Add necessities to git config
Stage files
Stage files via lfs if necessary
Check that atleast one file is staged
"""
with ProgressBar(_("Preparing")) as progress_bar, work... | [
"def",
"prepare",
"(",
"tool",
",",
"branch",
",",
"user",
",",
"included",
")",
":",
"with",
"ProgressBar",
"(",
"_",
"(",
"\"Preparing\"",
")",
")",
"as",
"progress_bar",
",",
"working_area",
"(",
"included",
")",
"as",
"area",
":",
"Git",
".",
"work... | Prepare git for pushing
Check that there are no permission errors
Add necessities to git config
Stage files
Stage files via lfs if necessary
Check that atleast one file is staged | [
"Prepare",
"git",
"for",
"pushing",
"Check",
"that",
"there",
"are",
"no",
"permission",
"errors",
"Add",
"necessities",
"to",
"git",
"config",
"Stage",
"files",
"Stage",
"files",
"via",
"lfs",
"if",
"necessary",
"Check",
"that",
"atleast",
"one",
"file",
"i... | python | train |
cqlengine/cqlengine | cqlengine/query.py | https://github.com/cqlengine/cqlengine/blob/7079eaf7071cbf5a045e1d1ab57f6d1b5ba3f9dc/cqlengine/query.py#L420-L461 | def iff(self, *args, **kwargs):
"""Adds IF statements to queryset"""
if len([x for x in kwargs.values() if x is None]):
raise CQLEngineException("None values on iff are not allowed")
clone = copy.deepcopy(self)
for operator in args:
if not isinstance(operator, Tr... | [
"def",
"iff",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"[",
"x",
"for",
"x",
"in",
"kwargs",
".",
"values",
"(",
")",
"if",
"x",
"is",
"None",
"]",
")",
":",
"raise",
"CQLEngineException",
"(",
"\"None... | Adds IF statements to queryset | [
"Adds",
"IF",
"statements",
"to",
"queryset"
] | python | train |
dslackw/slpkg | slpkg/pkg/manager.py | https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/pkg/manager.py#L429-L448 | def display(self):
"""Print the Slackware packages contents
"""
for pkg in self.binary:
name = GetFromInstalled(pkg).name()
ver = GetFromInstalled(pkg).version()
find = find_package("{0}{1}{2}".format(name, ver, self.meta.sp),
s... | [
"def",
"display",
"(",
"self",
")",
":",
"for",
"pkg",
"in",
"self",
".",
"binary",
":",
"name",
"=",
"GetFromInstalled",
"(",
"pkg",
")",
".",
"name",
"(",
")",
"ver",
"=",
"GetFromInstalled",
"(",
"pkg",
")",
".",
"version",
"(",
")",
"find",
"="... | Print the Slackware packages contents | [
"Print",
"the",
"Slackware",
"packages",
"contents"
] | python | train |
senaite/senaite.core | bika/lims/content/batch.py | https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/batch.py#L344-L353 | def BatchLabelVocabulary(self):
"""Return all batch labels as a display list
"""
bsc = getToolByName(self, 'bika_setup_catalog')
ret = []
for p in bsc(portal_type='BatchLabel',
is_active=True,
sort_on='sortable_title'):
ret.ap... | [
"def",
"BatchLabelVocabulary",
"(",
"self",
")",
":",
"bsc",
"=",
"getToolByName",
"(",
"self",
",",
"'bika_setup_catalog'",
")",
"ret",
"=",
"[",
"]",
"for",
"p",
"in",
"bsc",
"(",
"portal_type",
"=",
"'BatchLabel'",
",",
"is_active",
"=",
"True",
",",
... | Return all batch labels as a display list | [
"Return",
"all",
"batch",
"labels",
"as",
"a",
"display",
"list"
] | python | train |
ahobsonsayers/bthomehub5-devicelist | bthomehub5_devicelist/bthomehub5_devicelist.py | https://github.com/ahobsonsayers/bthomehub5-devicelist/blob/941b553fab7ce49b0c7ff7f1e10023d0a212d455/bthomehub5_devicelist/bthomehub5_devicelist.py#L25-L39 | def parse_devicelist(data_str):
"""Parse the BT Home Hub 5 data format."""
p = HTMLTableParser()
p.feed(data_str)
known_devices = p.tables[9]
devices = {}
for device in known_devices:
if len(device) == 5 and device[2] != '':
devices[device[2]] = device[1]
return devi... | [
"def",
"parse_devicelist",
"(",
"data_str",
")",
":",
"p",
"=",
"HTMLTableParser",
"(",
")",
"p",
".",
"feed",
"(",
"data_str",
")",
"known_devices",
"=",
"p",
".",
"tables",
"[",
"9",
"]",
"devices",
"=",
"{",
"}",
"for",
"device",
"in",
"known_device... | Parse the BT Home Hub 5 data format. | [
"Parse",
"the",
"BT",
"Home",
"Hub",
"5",
"data",
"format",
"."
] | python | train |
delph-in/pydelphin | delphin/interfaces/base.py | https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/interfaces/base.py#L100-L111 | def mrs(self):
"""
Deserialize and return an Mrs object for simplemrs or
JSON-formatted MRS data; otherwise return the original string.
"""
mrs = self.get('mrs')
if mrs is not None:
if isinstance(mrs, dict):
mrs = Mrs.from_dict(mrs)
... | [
"def",
"mrs",
"(",
"self",
")",
":",
"mrs",
"=",
"self",
".",
"get",
"(",
"'mrs'",
")",
"if",
"mrs",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"mrs",
",",
"dict",
")",
":",
"mrs",
"=",
"Mrs",
".",
"from_dict",
"(",
"mrs",
")",
"elif",
... | Deserialize and return an Mrs object for simplemrs or
JSON-formatted MRS data; otherwise return the original string. | [
"Deserialize",
"and",
"return",
"an",
"Mrs",
"object",
"for",
"simplemrs",
"or",
"JSON",
"-",
"formatted",
"MRS",
"data",
";",
"otherwise",
"return",
"the",
"original",
"string",
"."
] | python | train |
CyberZHG/keras-transformer | keras_transformer/transformer.py | https://github.com/CyberZHG/keras-transformer/blob/4c42baa030539c62ef5ace92df0408b13f26d928/keras_transformer/transformer.py#L418-L461 | def decode(model, tokens, start_token, end_token, pad_token, max_len=10000, max_repeat=10, max_repeat_block=10):
"""Decode with the given model and input tokens.
:param model: The trained model.
:param tokens: The input tokens of encoder.
:param start_token: The token that represents the start of a sen... | [
"def",
"decode",
"(",
"model",
",",
"tokens",
",",
"start_token",
",",
"end_token",
",",
"pad_token",
",",
"max_len",
"=",
"10000",
",",
"max_repeat",
"=",
"10",
",",
"max_repeat_block",
"=",
"10",
")",
":",
"is_single",
"=",
"not",
"isinstance",
"(",
"t... | Decode with the given model and input tokens.
:param model: The trained model.
:param tokens: The input tokens of encoder.
:param start_token: The token that represents the start of a sentence.
:param end_token: The token that represents the end of a sentence.
:param pad_token: The token that repre... | [
"Decode",
"with",
"the",
"given",
"model",
"and",
"input",
"tokens",
"."
] | python | train |
Unity-Technologies/ml-agents | ml-agents-envs/mlagents/envs/environment.py | https://github.com/Unity-Technologies/ml-agents/blob/37d139af636e4a2351751fbf0f2fca5a9ed7457f/ml-agents-envs/mlagents/envs/environment.py#L281-L451 | def step(self, vector_action=None, memory=None, text_action=None, value=None, custom_action=None) -> AllBrainInfo:
"""
Provides the environment with an action, moves the environment dynamics forward accordingly,
and returns observation, state, and reward information to the agent.
:param ... | [
"def",
"step",
"(",
"self",
",",
"vector_action",
"=",
"None",
",",
"memory",
"=",
"None",
",",
"text_action",
"=",
"None",
",",
"value",
"=",
"None",
",",
"custom_action",
"=",
"None",
")",
"->",
"AllBrainInfo",
":",
"vector_action",
"=",
"{",
"}",
"i... | Provides the environment with an action, moves the environment dynamics forward accordingly,
and returns observation, state, and reward information to the agent.
:param value: Value estimates provided by agents.
:param vector_action: Agent's vector action. Can be a scalar or vector of int/floats... | [
"Provides",
"the",
"environment",
"with",
"an",
"action",
"moves",
"the",
"environment",
"dynamics",
"forward",
"accordingly",
"and",
"returns",
"observation",
"state",
"and",
"reward",
"information",
"to",
"the",
"agent",
".",
":",
"param",
"value",
":",
"Value... | python | train |
MozillaSecurity/fuzzfetch | src/fuzzfetch/fetch.py | https://github.com/MozillaSecurity/fuzzfetch/blob/166cbfc71b679db019b9ac777dce12ccfdfc2c10/src/fuzzfetch/fetch.py#L81-L89 | def _get_url(url):
"""Retrieve requested URL"""
try:
data = HTTP_SESSION.get(url, stream=True)
data.raise_for_status()
except requests.exceptions.RequestException as exc:
raise FetcherException(exc)
return data | [
"def",
"_get_url",
"(",
"url",
")",
":",
"try",
":",
"data",
"=",
"HTTP_SESSION",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"data",
".",
"raise_for_status",
"(",
")",
"except",
"requests",
".",
"exceptions",
".",
"RequestException",
"as",
... | Retrieve requested URL | [
"Retrieve",
"requested",
"URL"
] | python | train |
duniter/duniter-python-api | duniterpy/documents/transaction.py | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/transaction.py#L321-L337 | def from_parameter(cls: Type[UnlockParameterType], parameter: str) -> Optional[Union[SIGParameter, XHXParameter]]:
"""
Return UnlockParameter instance from parameter string
:param parameter: Parameter string
:return:
"""
sig_param = SIGParameter.from_parameter(parameter... | [
"def",
"from_parameter",
"(",
"cls",
":",
"Type",
"[",
"UnlockParameterType",
"]",
",",
"parameter",
":",
"str",
")",
"->",
"Optional",
"[",
"Union",
"[",
"SIGParameter",
",",
"XHXParameter",
"]",
"]",
":",
"sig_param",
"=",
"SIGParameter",
".",
"from_parame... | Return UnlockParameter instance from parameter string
:param parameter: Parameter string
:return: | [
"Return",
"UnlockParameter",
"instance",
"from",
"parameter",
"string"
] | python | train |
log2timeline/dfvfs | dfvfs/vfs/ntfs_file_entry.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/ntfs_file_entry.py#L414-L417 | def change_time(self):
"""dfdatetime.DateTimeValues: change time or None if not available."""
timestamp = self._fsntfs_file_entry.get_entry_modification_time_as_integer()
return dfdatetime_filetime.Filetime(timestamp=timestamp) | [
"def",
"change_time",
"(",
"self",
")",
":",
"timestamp",
"=",
"self",
".",
"_fsntfs_file_entry",
".",
"get_entry_modification_time_as_integer",
"(",
")",
"return",
"dfdatetime_filetime",
".",
"Filetime",
"(",
"timestamp",
"=",
"timestamp",
")"
] | dfdatetime.DateTimeValues: change time or None if not available. | [
"dfdatetime",
".",
"DateTimeValues",
":",
"change",
"time",
"or",
"None",
"if",
"not",
"available",
"."
] | python | train |
ecordell/pymacaroons | pymacaroons/serializers/json_serializer.py | https://github.com/ecordell/pymacaroons/blob/c941614df15fe732ea432a62788e45410bcb868d/pymacaroons/serializers/json_serializer.py#L157-L169 | def _add_json_binary_field(b, serialized, field):
''' Set the given field to the given val (a bytearray) in the serialized
dictionary.
If the value isn't valid utf-8, we base64 encode it and use field+"64"
as the field name.
'''
try:
val = b.decode("utf-8")
serialized[field] = v... | [
"def",
"_add_json_binary_field",
"(",
"b",
",",
"serialized",
",",
"field",
")",
":",
"try",
":",
"val",
"=",
"b",
".",
"decode",
"(",
"\"utf-8\"",
")",
"serialized",
"[",
"field",
"]",
"=",
"val",
"except",
"UnicodeDecodeError",
":",
"val",
"=",
"utils"... | Set the given field to the given val (a bytearray) in the serialized
dictionary.
If the value isn't valid utf-8, we base64 encode it and use field+"64"
as the field name. | [
"Set",
"the",
"given",
"field",
"to",
"the",
"given",
"val",
"(",
"a",
"bytearray",
")",
"in",
"the",
"serialized",
"dictionary",
"."
] | python | train |
duniter/duniter-python-api | examples/create_and_publish_identity.py | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/examples/create_and_publish_identity.py#L20-L51 | def get_identity_document(current_block: dict, uid: str, salt: str, password: str) -> Identity:
"""
Get an Identity document
:param current_block: Current block data
:param uid: Unique IDentifier
:param salt: Passphrase of the account
:param password: Password of the account
:rtype: Identi... | [
"def",
"get_identity_document",
"(",
"current_block",
":",
"dict",
",",
"uid",
":",
"str",
",",
"salt",
":",
"str",
",",
"password",
":",
"str",
")",
"->",
"Identity",
":",
"# get current block BlockStamp",
"timestamp",
"=",
"BlockUID",
"(",
"current_block",
"... | Get an Identity document
:param current_block: Current block data
:param uid: Unique IDentifier
:param salt: Passphrase of the account
:param password: Password of the account
:rtype: Identity | [
"Get",
"an",
"Identity",
"document"
] | python | train |
PyCQA/pylint | pylint/checkers/base.py | https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/base.py#L997-L1001 | def open(self):
"""initialize visit variables and statistics
"""
self._tryfinallys = []
self.stats = self.linter.add_stats(module=0, function=0, method=0, class_=0) | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"_tryfinallys",
"=",
"[",
"]",
"self",
".",
"stats",
"=",
"self",
".",
"linter",
".",
"add_stats",
"(",
"module",
"=",
"0",
",",
"function",
"=",
"0",
",",
"method",
"=",
"0",
",",
"class_",
"=",... | initialize visit variables and statistics | [
"initialize",
"visit",
"variables",
"and",
"statistics"
] | python | test |
RRZE-HPC/kerncraft | kerncraft/intervals.py | https://github.com/RRZE-HPC/kerncraft/blob/c60baf8043e4da8d8d66da7575021c2f4c6c78af/kerncraft/intervals.py#L20-L32 | def _enforce_no_overlap(self, start_at=0):
"""Enforce that no ranges overlap in internal storage."""
i = start_at
while i+1 < len(self.data):
if self.data[i][1] >= self.data[i+1][0]:
# beginning of i+1-th range is contained in i-th range
if self.data[i... | [
"def",
"_enforce_no_overlap",
"(",
"self",
",",
"start_at",
"=",
"0",
")",
":",
"i",
"=",
"start_at",
"while",
"i",
"+",
"1",
"<",
"len",
"(",
"self",
".",
"data",
")",
":",
"if",
"self",
".",
"data",
"[",
"i",
"]",
"[",
"1",
"]",
">=",
"self",... | Enforce that no ranges overlap in internal storage. | [
"Enforce",
"that",
"no",
"ranges",
"overlap",
"in",
"internal",
"storage",
"."
] | python | test |
Alignak-monitoring/alignak | alignak/basemodule.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L189-L210 | def create_queues(self, manager=None):
"""
Create the shared queues that will be used by alignak daemon
process and this module process.
But clear queues if they were already set before recreating new one.
Note:
If manager is None, then we are running the unit tests for ... | [
"def",
"create_queues",
"(",
"self",
",",
"manager",
"=",
"None",
")",
":",
"self",
".",
"clear_queues",
"(",
"manager",
")",
"# If no Manager() object, go with classic Queue()",
"if",
"not",
"manager",
":",
"self",
".",
"from_q",
"=",
"Queue",
"(",
")",
"self... | Create the shared queues that will be used by alignak daemon
process and this module process.
But clear queues if they were already set before recreating new one.
Note:
If manager is None, then we are running the unit tests for the modules and
we must create some queues for the ... | [
"Create",
"the",
"shared",
"queues",
"that",
"will",
"be",
"used",
"by",
"alignak",
"daemon",
"process",
"and",
"this",
"module",
"process",
".",
"But",
"clear",
"queues",
"if",
"they",
"were",
"already",
"set",
"before",
"recreating",
"new",
"one",
"."
] | python | train |
bpsmith/tia | tia/analysis/perf.py | https://github.com/bpsmith/tia/blob/a7043b6383e557aeea8fc7112bbffd6e36a230e9/tia/analysis/perf.py#L339-L359 | def downside_deviation(rets, mar=0, expanding=0, full=0, ann=0):
"""Compute the downside deviation for the specifed return series
:param rets: periodic return series
:param mar: minimum acceptable rate of return (MAR)
:param full: If True, use the lenght of full series. If False, use only values below M... | [
"def",
"downside_deviation",
"(",
"rets",
",",
"mar",
"=",
"0",
",",
"expanding",
"=",
"0",
",",
"full",
"=",
"0",
",",
"ann",
"=",
"0",
")",
":",
"below",
"=",
"rets",
"[",
"rets",
"<",
"mar",
"]",
"if",
"expanding",
":",
"n",
"=",
"pd",
".",
... | Compute the downside deviation for the specifed return series
:param rets: periodic return series
:param mar: minimum acceptable rate of return (MAR)
:param full: If True, use the lenght of full series. If False, use only values below MAR
:param expanding:
:param ann: True if result should be annual... | [
"Compute",
"the",
"downside",
"deviation",
"for",
"the",
"specifed",
"return",
"series",
":",
"param",
"rets",
":",
"periodic",
"return",
"series",
":",
"param",
"mar",
":",
"minimum",
"acceptable",
"rate",
"of",
"return",
"(",
"MAR",
")",
":",
"param",
"f... | python | train |
odrling/peony-twitter | peony/utils.py | https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/peony/utils.py#L202-L232 | async def get_media_metadata(data, path=None):
"""
Get all the file's metadata and read any kind of file object
Parameters
----------
data : bytes
first bytes of the file (the mimetype shoudl be guessed from the
file headers
path : str, optional
path to the file
... | [
"async",
"def",
"get_media_metadata",
"(",
"data",
",",
"path",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"media_type",
"=",
"await",
"get_type",
"(",
"data",
",",
"path",
")",
"else",
":",
"raise",
"TypeError",
"(... | Get all the file's metadata and read any kind of file object
Parameters
----------
data : bytes
first bytes of the file (the mimetype shoudl be guessed from the
file headers
path : str, optional
path to the file
Returns
-------
str
The mimetype of the media
... | [
"Get",
"all",
"the",
"file",
"s",
"metadata",
"and",
"read",
"any",
"kind",
"of",
"file",
"object"
] | python | valid |
mbedmicro/pyOCD | pyocd/utility/server.py | https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/utility/server.py#L131-L146 | def _get_input(self, length):
"""! @brief Extract requested amount of data from the read buffer."""
self._buffer_lock.acquire()
try:
if length == -1:
actualLength = len(self._buffer)
else:
actualLength = min(length, len(self._buffer))
... | [
"def",
"_get_input",
"(",
"self",
",",
"length",
")",
":",
"self",
".",
"_buffer_lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"length",
"==",
"-",
"1",
":",
"actualLength",
"=",
"len",
"(",
"self",
".",
"_buffer",
")",
"else",
":",
"actualLengt... | ! @brief Extract requested amount of data from the read buffer. | [
"!"
] | python | train |
BlueBrain/nat | nat/scigraph_client.py | https://github.com/BlueBrain/nat/blob/0934f06e48e6efedf55a9617b15becae0d7b277c/nat/scigraph_client.py#L399-L422 | def annotatePost(self, content, includeCat=None, excludeCat=None, minLength=4, longestOnly='false', includeAbbrev='false', includeAcronym='false', includeNumbers='false', ignoreTag=None, stylesheet=None, scripts=None, targetId=None, targetClass=None):
""" Annotate text from: /annotations
Arguments:
... | [
"def",
"annotatePost",
"(",
"self",
",",
"content",
",",
"includeCat",
"=",
"None",
",",
"excludeCat",
"=",
"None",
",",
"minLength",
"=",
"4",
",",
"longestOnly",
"=",
"'false'",
",",
"includeAbbrev",
"=",
"'false'",
",",
"includeAcronym",
"=",
"'false'",
... | Annotate text from: /annotations
Arguments:
content: The content to annotate
includeCat: A set of categories to include
excludeCat: A set of categories to exclude
minLength: The minimum number of characters in annotated entities
longestOnly: Should... | [
"Annotate",
"text",
"from",
":",
"/",
"annotations",
"Arguments",
":",
"content",
":",
"The",
"content",
"to",
"annotate",
"includeCat",
":",
"A",
"set",
"of",
"categories",
"to",
"include",
"excludeCat",
":",
"A",
"set",
"of",
"categories",
"to",
"exclude",... | python | train |
googleapis/google-cloud-python | logging/docs/snippets.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/docs/snippets.py#L104-L112 | def client_list_entries_multi_project(
client, to_delete
): # pylint: disable=unused-argument
"""List entries via client across multiple projects."""
# [START client_list_entries_multi_project]
PROJECT_IDS = ["one-project", "another-project"]
for entry in client.list_entries(project_ids=PROJECT_ID... | [
"def",
"client_list_entries_multi_project",
"(",
"client",
",",
"to_delete",
")",
":",
"# pylint: disable=unused-argument",
"# [START client_list_entries_multi_project]",
"PROJECT_IDS",
"=",
"[",
"\"one-project\"",
",",
"\"another-project\"",
"]",
"for",
"entry",
"in",
"clien... | List entries via client across multiple projects. | [
"List",
"entries",
"via",
"client",
"across",
"multiple",
"projects",
"."
] | python | train |
bitlabstudio/django-development-fabfile | development_fabfile/fabfile/remote.py | https://github.com/bitlabstudio/django-development-fabfile/blob/a135c6eb5bdd0b496a7eccfd271aca558dd99243/development_fabfile/fabfile/remote.py#L287-L306 | def run_rsync_project():
"""
Copies the project from the git repository to it's destination folder.
This has the nice side effect of rsync deleting all ``.pyc`` files and
removing other files that might have been left behind by sys admins messing
around on the server.
Usage::
fab <ser... | [
"def",
"run_rsync_project",
"(",
")",
":",
"excludes",
"=",
"''",
"for",
"exclude",
"in",
"settings",
".",
"RSYNC_EXCLUDES",
":",
"excludes",
"+=",
"\" --exclude '{0}'\"",
".",
"format",
"(",
"exclude",
")",
"command",
"=",
"\"rsync -avz --stats --delete {0} {1} {2}... | Copies the project from the git repository to it's destination folder.
This has the nice side effect of rsync deleting all ``.pyc`` files and
removing other files that might have been left behind by sys admins messing
around on the server.
Usage::
fab <server> run_rsync_project | [
"Copies",
"the",
"project",
"from",
"the",
"git",
"repository",
"to",
"it",
"s",
"destination",
"folder",
"."
] | python | train |
PyMLGame/pymlgame | pymlgame/surface.py | https://github.com/PyMLGame/pymlgame/blob/450fe77d35f9a26c107586d6954f69c3895bf504/pymlgame/surface.py#L128-L142 | def blit(self, surface, pos=(0, 0)):
"""
Blits a surface on this surface at pos
:param surface: Surface to blit
:param pos: Top left point to start blitting
:type surface: Surface
:type pos: tuple
"""
for x in range(surface.width):
for y in ra... | [
"def",
"blit",
"(",
"self",
",",
"surface",
",",
"pos",
"=",
"(",
"0",
",",
"0",
")",
")",
":",
"for",
"x",
"in",
"range",
"(",
"surface",
".",
"width",
")",
":",
"for",
"y",
"in",
"range",
"(",
"surface",
".",
"height",
")",
":",
"px",
"=",
... | Blits a surface on this surface at pos
:param surface: Surface to blit
:param pos: Top left point to start blitting
:type surface: Surface
:type pos: tuple | [
"Blits",
"a",
"surface",
"on",
"this",
"surface",
"at",
"pos"
] | python | train |
DLR-RM/RAFCON | source/rafcon/core/states/container_state.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/container_state.py#L1431-L1446 | def remove_scoped_variable(self, scoped_variable_id, destroy=True):
"""Remove a scoped variable from the container state
:param scoped_variable_id: the id of the scoped variable to remove
:raises exceptions.AttributeError: if the id of the scoped variable already exists
"""
if s... | [
"def",
"remove_scoped_variable",
"(",
"self",
",",
"scoped_variable_id",
",",
"destroy",
"=",
"True",
")",
":",
"if",
"scoped_variable_id",
"not",
"in",
"self",
".",
"_scoped_variables",
":",
"raise",
"AttributeError",
"(",
"\"A scoped variable with id %s does not exist... | Remove a scoped variable from the container state
:param scoped_variable_id: the id of the scoped variable to remove
:raises exceptions.AttributeError: if the id of the scoped variable already exists | [
"Remove",
"a",
"scoped",
"variable",
"from",
"the",
"container",
"state"
] | python | train |
Robpol86/libnl | libnl/nl.py | https://github.com/Robpol86/libnl/blob/274e9fdaa39822d06ef70b799ed4a95937a4d923/libnl/nl.py#L646-L669 | def nl_recvmsgs(sk, cb):
"""Receive a set of messages from a Netlink socket.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L1023
Repeatedly calls nl_recv() or the respective replacement if provided by the application (see nl_cb_overwrite_recv())
and parses the received data as Netlink mes... | [
"def",
"nl_recvmsgs",
"(",
"sk",
",",
"cb",
")",
":",
"err",
"=",
"nl_recvmsgs_report",
"(",
"sk",
",",
"cb",
")",
"if",
"err",
">",
"0",
":",
"return",
"0",
"return",
"int",
"(",
"err",
")"
] | Receive a set of messages from a Netlink socket.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L1023
Repeatedly calls nl_recv() or the respective replacement if provided by the application (see nl_cb_overwrite_recv())
and parses the received data as Netlink messages. Stops reading if one of t... | [
"Receive",
"a",
"set",
"of",
"messages",
"from",
"a",
"Netlink",
"socket",
"."
] | python | train |
sernst/cauldron | cauldron/session/display/__init__.py | https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/display/__init__.py#L275-L298 | def image(
filename: str,
width: int = None,
height: int = None,
justify: str = 'left'
):
"""
Adds an image to the display. The image must be located within the
assets directory of the Cauldron notebook's folder.
:param filename:
Name of the file within the asset... | [
"def",
"image",
"(",
"filename",
":",
"str",
",",
"width",
":",
"int",
"=",
"None",
",",
"height",
":",
"int",
"=",
"None",
",",
"justify",
":",
"str",
"=",
"'left'",
")",
":",
"r",
"=",
"_get_report",
"(",
")",
"path",
"=",
"'/'",
".",
"join",
... | Adds an image to the display. The image must be located within the
assets directory of the Cauldron notebook's folder.
:param filename:
Name of the file within the assets directory,
:param width:
Optional width in pixels for the image.
:param height:
Optional height in pixels fo... | [
"Adds",
"an",
"image",
"to",
"the",
"display",
".",
"The",
"image",
"must",
"be",
"located",
"within",
"the",
"assets",
"directory",
"of",
"the",
"Cauldron",
"notebook",
"s",
"folder",
"."
] | python | train |
jmbeach/KEP.py | src/keppy/simulator_device.py | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L166-L174 | def process_string(self, tag):
"""Process string type tags"""
tag.set_address(self.string_register.current_address)
if self.is_sixteen_bit:
# each string address needs 1 byte = 1/2 an address
self.string_register.move_to_next_address(1)
return
# each s... | [
"def",
"process_string",
"(",
"self",
",",
"tag",
")",
":",
"tag",
".",
"set_address",
"(",
"self",
".",
"string_register",
".",
"current_address",
")",
"if",
"self",
".",
"is_sixteen_bit",
":",
"# each string address needs 1 byte = 1/2 an address",
"self",
".",
"... | Process string type tags | [
"Process",
"string",
"type",
"tags"
] | python | train |
jay-johnson/celery-loaders | celery_loaders/work_tasks/custom_task.py | https://github.com/jay-johnson/celery-loaders/blob/aca8169c774582af42a377c27cb3980020080814/celery_loaders/work_tasks/custom_task.py#L14-L32 | def on_success(self, retval, task_id, args, kwargs):
"""on_success
http://docs.celeryproject.org/en/latest/reference/celery.app.task.html
:param retval: return value
:param task_id: celery task id
:param args: arguments passed into task
:param kwargs: keyword arguments ... | [
"def",
"on_success",
"(",
"self",
",",
"retval",
",",
"task_id",
",",
"args",
",",
"kwargs",
")",
":",
"log",
".",
"info",
"(",
"(",
"\"{} SUCCESS - retval={} task_id={} \"",
"\"args={} kwargs={}\"",
")",
".",
"format",
"(",
"self",
".",
"log_label",
",",
"r... | on_success
http://docs.celeryproject.org/en/latest/reference/celery.app.task.html
:param retval: return value
:param task_id: celery task id
:param args: arguments passed into task
:param kwargs: keyword arguments passed into task | [
"on_success"
] | python | train |
materialsproject/pymatgen | pymatgen/core/structure.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/structure.py#L283-L300 | def is_valid(self, tol: float = DISTANCE_TOLERANCE) -> bool:
"""
True if SiteCollection does not contain atoms that are too close
together. Note that the distance definition is based on type of
SiteCollection. Cartesian distances are used for non-periodic
Molecules, while PBC is ... | [
"def",
"is_valid",
"(",
"self",
",",
"tol",
":",
"float",
"=",
"DISTANCE_TOLERANCE",
")",
"->",
"bool",
":",
"if",
"len",
"(",
"self",
".",
"sites",
")",
"==",
"1",
":",
"return",
"True",
"all_dists",
"=",
"self",
".",
"distance_matrix",
"[",
"np",
"... | True if SiteCollection does not contain atoms that are too close
together. Note that the distance definition is based on type of
SiteCollection. Cartesian distances are used for non-periodic
Molecules, while PBC is taken into account for periodic structures.
Args:
tol (float... | [
"True",
"if",
"SiteCollection",
"does",
"not",
"contain",
"atoms",
"that",
"are",
"too",
"close",
"together",
".",
"Note",
"that",
"the",
"distance",
"definition",
"is",
"based",
"on",
"type",
"of",
"SiteCollection",
".",
"Cartesian",
"distances",
"are",
"used... | python | train |
gleitz/howdoi | howdoi/howdoi.py | https://github.com/gleitz/howdoi/blob/94f0429b4e99cb914aadfca0f27257ea801471ac/howdoi/howdoi.py#L157-L163 | def get_text(element):
''' return inner text in pyquery element '''
_add_links_to_text(element)
try:
return element.text(squash_space=False)
except TypeError:
return element.text() | [
"def",
"get_text",
"(",
"element",
")",
":",
"_add_links_to_text",
"(",
"element",
")",
"try",
":",
"return",
"element",
".",
"text",
"(",
"squash_space",
"=",
"False",
")",
"except",
"TypeError",
":",
"return",
"element",
".",
"text",
"(",
")"
] | return inner text in pyquery element | [
"return",
"inner",
"text",
"in",
"pyquery",
"element"
] | python | train |
RusticiSoftware/TinCanPython | tincan/lrs_response.py | https://github.com/RusticiSoftware/TinCanPython/blob/424eedaa6d19221efb1108edb915fc332abbb317/tincan/lrs_response.py#L111-L119 | def data(self, value):
"""Setter for the _data attribute. Should be set from response.read()
:param value: The body of the response object for the LRSResponse
:type value: unicode
"""
if value is not None and not isinstance(value, unicode):
value = value.decode('utf-... | [
"def",
"data",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"value",
",",
"unicode",
")",
":",
"value",
"=",
"value",
".",
"decode",
"(",
"'utf-8'",
")",
"self",
".",
"_data",
"=",
"value... | Setter for the _data attribute. Should be set from response.read()
:param value: The body of the response object for the LRSResponse
:type value: unicode | [
"Setter",
"for",
"the",
"_data",
"attribute",
".",
"Should",
"be",
"set",
"from",
"response",
".",
"read",
"()"
] | python | train |
tBuLi/symfit | symfit/distributions.py | https://github.com/tBuLi/symfit/blob/759dd3d1d4270510d651f40b23dd26b1b10eee83/symfit/distributions.py#L11-L19 | def Gaussian(x, mu, sig):
"""
Gaussian pdf.
:param x: free variable.
:param mu: mean of the distribution.
:param sig: standard deviation of the distribution.
:return: sympy.Expr for a Gaussian pdf.
"""
return sympy.exp(-(x - mu)**2/(2*sig**2))/sympy.sqrt(2*sympy.pi*sig**2) | [
"def",
"Gaussian",
"(",
"x",
",",
"mu",
",",
"sig",
")",
":",
"return",
"sympy",
".",
"exp",
"(",
"-",
"(",
"x",
"-",
"mu",
")",
"**",
"2",
"/",
"(",
"2",
"*",
"sig",
"**",
"2",
")",
")",
"/",
"sympy",
".",
"sqrt",
"(",
"2",
"*",
"sympy",... | Gaussian pdf.
:param x: free variable.
:param mu: mean of the distribution.
:param sig: standard deviation of the distribution.
:return: sympy.Expr for a Gaussian pdf. | [
"Gaussian",
"pdf",
".",
":",
"param",
"x",
":",
"free",
"variable",
".",
":",
"param",
"mu",
":",
"mean",
"of",
"the",
"distribution",
".",
":",
"param",
"sig",
":",
"standard",
"deviation",
"of",
"the",
"distribution",
".",
":",
"return",
":",
"sympy"... | python | train |
Azure/azure-cosmos-table-python | azure-cosmosdb-table/azure/cosmosdb/table/tableservice.py | https://github.com/Azure/azure-cosmos-table-python/blob/a7b618f6bddc465c9fdf899ea2971dfe4d04fcf0/azure-cosmosdb-table/azure/cosmosdb/table/tableservice.py#L935-L967 | def update_entity(self, table_name, entity, if_match='*', timeout=None):
'''
Updates an existing entity in a table. Throws if the entity does not exist.
The update_entity operation replaces the entire entity and can be used to
remove properties.
:param str table_name:
... | [
"def",
"update_entity",
"(",
"self",
",",
"table_name",
",",
"entity",
",",
"if_match",
"=",
"'*'",
",",
"timeout",
"=",
"None",
")",
":",
"_validate_not_none",
"(",
"'table_name'",
",",
"table_name",
")",
"request",
"=",
"_update_entity",
"(",
"entity",
","... | Updates an existing entity in a table. Throws if the entity does not exist.
The update_entity operation replaces the entire entity and can be used to
remove properties.
:param str table_name:
The name of the table containing the entity to update.
:param entity:
... | [
"Updates",
"an",
"existing",
"entity",
"in",
"a",
"table",
".",
"Throws",
"if",
"the",
"entity",
"does",
"not",
"exist",
".",
"The",
"update_entity",
"operation",
"replaces",
"the",
"entire",
"entity",
"and",
"can",
"be",
"used",
"to",
"remove",
"properties"... | python | train |
hazelcast/hazelcast-python-client | hazelcast/proxy/list.py | https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/list.py#L35-L44 | def add(self, item):
"""
Adds the specified item to the end of this list.
:param item: (object), the specified item to be appended to this list.
:return: (bool), ``true`` if item is added, ``false`` otherwise.
"""
check_not_none(item, "Value can't be None")
eleme... | [
"def",
"add",
"(",
"self",
",",
"item",
")",
":",
"check_not_none",
"(",
"item",
",",
"\"Value can't be None\"",
")",
"element_data",
"=",
"self",
".",
"_to_data",
"(",
"item",
")",
"return",
"self",
".",
"_encode_invoke",
"(",
"list_add_codec",
",",
"value"... | Adds the specified item to the end of this list.
:param item: (object), the specified item to be appended to this list.
:return: (bool), ``true`` if item is added, ``false`` otherwise. | [
"Adds",
"the",
"specified",
"item",
"to",
"the",
"end",
"of",
"this",
"list",
"."
] | python | train |
dunovank/jupyter-themes | jupyterthemes/jtplot.py | https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L215-L223 | def figsize(x=8, y=7., aspect=1.):
""" manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar
"""
# update rcparams with adjusted figsize params
mpl.rcParams.update({'figure.figsize': (x*as... | [
"def",
"figsize",
"(",
"x",
"=",
"8",
",",
"y",
"=",
"7.",
",",
"aspect",
"=",
"1.",
")",
":",
"# update rcparams with adjusted figsize params",
"mpl",
".",
"rcParams",
".",
"update",
"(",
"{",
"'figure.figsize'",
":",
"(",
"x",
"*",
"aspect",
",",
"y",
... | manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar | [
"manually",
"set",
"the",
"default",
"figure",
"size",
"of",
"plots",
"::",
"Arguments",
"::",
"x",
"(",
"float",
")",
":",
"x",
"-",
"axis",
"size",
"y",
"(",
"float",
")",
":",
"y",
"-",
"axis",
"size",
"aspect",
"(",
"float",
")",
":",
"aspect",... | python | train |
treycucco/bidon | bidon/experimental/transfer_tracker.py | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/experimental/transfer_tracker.py#L144-L150 | def id_getter(self, relation_name, strict=False):
"""Returns a function that accepts an old_id and returns the new ID for the enclosed relation
name."""
def get_id(old_id):
"""Get the new ID for the enclosed relation, given an old ID."""
return self.get_new_id(relation_name, old_id, strict)
... | [
"def",
"id_getter",
"(",
"self",
",",
"relation_name",
",",
"strict",
"=",
"False",
")",
":",
"def",
"get_id",
"(",
"old_id",
")",
":",
"\"\"\"Get the new ID for the enclosed relation, given an old ID.\"\"\"",
"return",
"self",
".",
"get_new_id",
"(",
"relation_name",... | Returns a function that accepts an old_id and returns the new ID for the enclosed relation
name. | [
"Returns",
"a",
"function",
"that",
"accepts",
"an",
"old_id",
"and",
"returns",
"the",
"new",
"ID",
"for",
"the",
"enclosed",
"relation",
"name",
"."
] | python | train |
saltstack/salt | salt/utils/jinja.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jinja.py#L85-L90 | def cache_file(self, template):
'''
Cache a file from the salt master
'''
saltpath = salt.utils.url.create(template)
self.file_client().get_file(saltpath, '', True, self.saltenv) | [
"def",
"cache_file",
"(",
"self",
",",
"template",
")",
":",
"saltpath",
"=",
"salt",
".",
"utils",
".",
"url",
".",
"create",
"(",
"template",
")",
"self",
".",
"file_client",
"(",
")",
".",
"get_file",
"(",
"saltpath",
",",
"''",
",",
"True",
",",
... | Cache a file from the salt master | [
"Cache",
"a",
"file",
"from",
"the",
"salt",
"master"
] | python | train |
rushter/heamy | heamy/feature.py | https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/feature.py#L155-L166 | def xgb_to_features(model, X_train, X_test):
"""Converts xgboost model into categorical features.
Reference:
"Practical Lessons from Predicting Clicks on Ads at Facebook"
https://research.fb.com/publications/practical-lessons-from-predicting-clicks-on-ads-at-facebook/
"""
import xgboost as xgb
... | [
"def",
"xgb_to_features",
"(",
"model",
",",
"X_train",
",",
"X_test",
")",
":",
"import",
"xgboost",
"as",
"xgb",
"f_train",
"=",
"model",
".",
"predict",
"(",
"xgb",
".",
"DMatrix",
"(",
"X_train",
")",
",",
"pred_leaf",
"=",
"True",
")",
"f_test",
"... | Converts xgboost model into categorical features.
Reference:
"Practical Lessons from Predicting Clicks on Ads at Facebook"
https://research.fb.com/publications/practical-lessons-from-predicting-clicks-on-ads-at-facebook/ | [
"Converts",
"xgboost",
"model",
"into",
"categorical",
"features",
".",
"Reference",
":",
"Practical",
"Lessons",
"from",
"Predicting",
"Clicks",
"on",
"Ads",
"at",
"Facebook",
"https",
":",
"//",
"research",
".",
"fb",
".",
"com",
"/",
"publications",
"/",
... | python | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L7383-L7405 | def isrchi(value, ndim, array):
"""
Search for a given value within an integer array. Return
the index of the first matching array entry, or -1 if the key
value was not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrchi_c.html
:param value: Key value to be found in array.
... | [
"def",
"isrchi",
"(",
"value",
",",
"ndim",
",",
"array",
")",
":",
"value",
"=",
"ctypes",
".",
"c_int",
"(",
"value",
")",
"ndim",
"=",
"ctypes",
".",
"c_int",
"(",
"ndim",
")",
"array",
"=",
"stypes",
".",
"toIntVector",
"(",
"array",
")",
"retu... | Search for a given value within an integer array. Return
the index of the first matching array entry, or -1 if the key
value was not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrchi_c.html
:param value: Key value to be found in array.
:type value: int
:param ndim: Dimensio... | [
"Search",
"for",
"a",
"given",
"value",
"within",
"an",
"integer",
"array",
".",
"Return",
"the",
"index",
"of",
"the",
"first",
"matching",
"array",
"entry",
"or",
"-",
"1",
"if",
"the",
"key",
"value",
"was",
"not",
"found",
"."
] | python | train |
dslackw/slpkg | slpkg/__metadata__.py | https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/__metadata__.py#L39-L52 | def update_repositories(repositories, conf_path):
"""
Upadate with user custom repositories
"""
repo_file = "{0}custom-repositories".format(conf_path)
if os.path.isfile(repo_file):
f = open(repo_file, "r")
repositories_list = f.read()
f.close()
for line in repositorie... | [
"def",
"update_repositories",
"(",
"repositories",
",",
"conf_path",
")",
":",
"repo_file",
"=",
"\"{0}custom-repositories\"",
".",
"format",
"(",
"conf_path",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"repo_file",
")",
":",
"f",
"=",
"open",
"(",
... | Upadate with user custom repositories | [
"Upadate",
"with",
"user",
"custom",
"repositories"
] | python | train |
Alignak-monitoring/alignak | alignak/stats.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/stats.py#L224-L255 | def load_statsd(self):
"""Create socket connection to statsd host
Note that because of the UDP protocol used by StatsD, if no server is listening the
socket connection will be accepted anyway :)
:return: True if socket got created else False and an exception log is raised
"""
... | [
"def",
"load_statsd",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"statsd_enabled",
":",
"logger",
".",
"info",
"(",
"'Stats reporting is not enabled, connection is not allowed'",
")",
"return",
"False",
"if",
"self",
".",
"statsd_enabled",
"and",
"self",
"."... | Create socket connection to statsd host
Note that because of the UDP protocol used by StatsD, if no server is listening the
socket connection will be accepted anyway :)
:return: True if socket got created else False and an exception log is raised | [
"Create",
"socket",
"connection",
"to",
"statsd",
"host"
] | python | train |
bxlab/bx-python | lib/bx_extras/stats.py | https://github.com/bxlab/bx-python/blob/09cb725284803df90a468d910f2274628d8647de/lib/bx_extras/stats.py#L1054-L1069 | def lchisquare(f_obs,f_exp=None):
"""
Calculates a one-way chi square for list of observed frequencies and returns
the result. If no expected frequencies are given, the total N is assumed to
be equally distributed across all groups.
Usage: lchisquare(f_obs, f_exp=None) f_obs = list of observed cell freq.
Retu... | [
"def",
"lchisquare",
"(",
"f_obs",
",",
"f_exp",
"=",
"None",
")",
":",
"k",
"=",
"len",
"(",
"f_obs",
")",
"# number of groups",
"if",
"f_exp",
"==",
"None",
":",
"f_exp",
"=",
"[",
"sum",
"(",
"f_obs",
")",
"/",
"float",
"(",
"k",
")",
"]",
"*"... | Calculates a one-way chi square for list of observed frequencies and returns
the result. If no expected frequencies are given, the total N is assumed to
be equally distributed across all groups.
Usage: lchisquare(f_obs, f_exp=None) f_obs = list of observed cell freq.
Returns: chisquare-statistic, associated p-val... | [
"Calculates",
"a",
"one",
"-",
"way",
"chi",
"square",
"for",
"list",
"of",
"observed",
"frequencies",
"and",
"returns",
"the",
"result",
".",
"If",
"no",
"expected",
"frequencies",
"are",
"given",
"the",
"total",
"N",
"is",
"assumed",
"to",
"be",
"equally... | python | train |
PyGithub/PyGithub | github/GitRelease.py | https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/GitRelease.py#L219-L241 | def upload_asset(self, path, label="", content_type=""):
"""
:calls: `POST https://<upload_url>/repos/:owner/:repo/releases/:release_id/assets?name=foo.zip <https://developer.github.com/v3/repos/releases/#upload-a-release-asset>`_
:rtype: :class:`github.GitReleaseAsset.GitReleaseAsset`
"... | [
"def",
"upload_asset",
"(",
"self",
",",
"path",
",",
"label",
"=",
"\"\"",
",",
"content_type",
"=",
"\"\"",
")",
":",
"assert",
"isinstance",
"(",
"path",
",",
"(",
"str",
",",
"unicode",
")",
")",
",",
"path",
"assert",
"isinstance",
"(",
"label",
... | :calls: `POST https://<upload_url>/repos/:owner/:repo/releases/:release_id/assets?name=foo.zip <https://developer.github.com/v3/repos/releases/#upload-a-release-asset>`_
:rtype: :class:`github.GitReleaseAsset.GitReleaseAsset` | [
":",
"calls",
":",
"POST",
"https",
":",
"//",
"<upload_url",
">",
"/",
"repos",
"/",
":",
"owner",
"/",
":",
"repo",
"/",
"releases",
"/",
":",
"release_id",
"/",
"assets?name",
"=",
"foo",
".",
"zip",
"<https",
":",
"//",
"developer",
".",
"github"... | python | train |
tanghaibao/jcvi | jcvi/algorithms/lpsolve.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/lpsolve.py#L274-L283 | def edges_to_path(edges):
"""
Connect edges and return a path.
"""
if not edges:
return None
G = edges_to_graph(edges)
path = nx.topological_sort(G)
return path | [
"def",
"edges_to_path",
"(",
"edges",
")",
":",
"if",
"not",
"edges",
":",
"return",
"None",
"G",
"=",
"edges_to_graph",
"(",
"edges",
")",
"path",
"=",
"nx",
".",
"topological_sort",
"(",
"G",
")",
"return",
"path"
] | Connect edges and return a path. | [
"Connect",
"edges",
"and",
"return",
"a",
"path",
"."
] | python | train |
materialsvirtuallab/monty | monty/termcolor.py | https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/termcolor.py#L115-L145 | def colored(text, color=None, on_color=None, attrs=None):
"""Colorize text.
Available text colors:
red, green, yellow, blue, magenta, cyan, white.
Available text highlights:
on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.
Available attributes:
bold, dark, ... | [
"def",
"colored",
"(",
"text",
",",
"color",
"=",
"None",
",",
"on_color",
"=",
"None",
",",
"attrs",
"=",
"None",
")",
":",
"if",
"__ISON",
"and",
"os",
".",
"getenv",
"(",
"'ANSI_COLORS_DISABLED'",
")",
"is",
"None",
":",
"fmt_str",
"=",
"'\\033[%dm%... | Colorize text.
Available text colors:
red, green, yellow, blue, magenta, cyan, white.
Available text highlights:
on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.
Available attributes:
bold, dark, underline, blink, reverse, concealed.
Example:
color... | [
"Colorize",
"text",
"."
] | python | train |
saltstack/salt | salt/modules/lxc.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L702-L874 | def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or ex... | [
"def",
"_network_conf",
"(",
"conf_tuples",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"nic",
"=",
"kwargs",
".",
"get",
"(",
"'network_profile'",
",",
"None",
")",
"ret",
"=",
"[",
"]",
"nic_opts",
"=",
"kwargs",
".",
"get",
"(",
"'nic_opts'",
... | Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings} | [
"Network",
"configuration",
"defaults"
] | python | train |
datacats/datacats | datacats/cli/manage.py | https://github.com/datacats/datacats/blob/e4bae503efa997660fb3f34fe166699569653157/datacats/cli/manage.py#L74-L140 | def reload_(environment, opts):
"""Reload environment source and configuration
Usage:
datacats reload [-b] [-p|--no-watch] [--syslog] [-s NAME] [--site-url=SITE_URL]
[-i] [--address=IP] [ENVIRONMENT [PORT]]
datacats reload -r [-b] [--syslog] [-s NAME] [--address=IP] [--site-url=SITE... | [
"def",
"reload_",
"(",
"environment",
",",
"opts",
")",
":",
"if",
"opts",
"[",
"'--interactive'",
"]",
":",
"# We can't wait for the server if we're tty'd",
"opts",
"[",
"'--background'",
"]",
"=",
"True",
"if",
"opts",
"[",
"'--address'",
"]",
"and",
"is_boot2... | Reload environment source and configuration
Usage:
datacats reload [-b] [-p|--no-watch] [--syslog] [-s NAME] [--site-url=SITE_URL]
[-i] [--address=IP] [ENVIRONMENT [PORT]]
datacats reload -r [-b] [--syslog] [-s NAME] [--address=IP] [--site-url=SITE_URL]
[-i] ... | [
"Reload",
"environment",
"source",
"and",
"configuration"
] | python | train |
sanger-pathogens/Fastaq | pyfastaq/tasks.py | https://github.com/sanger-pathogens/Fastaq/blob/2c775c846d2491678a9637daa320592e02c26c72/pyfastaq/tasks.py#L686-L721 | def split_by_base_count(infile, outfiles_prefix, max_bases, max_seqs=None):
'''Splits a fasta/q file into separate files, file size determined by number of bases.
Puts <= max_bases in each split file The exception is a single sequence >=max_bases
is put in its own file. This does not split sequences.
... | [
"def",
"split_by_base_count",
"(",
"infile",
",",
"outfiles_prefix",
",",
"max_bases",
",",
"max_seqs",
"=",
"None",
")",
":",
"seq_reader",
"=",
"sequences",
".",
"file_reader",
"(",
"infile",
")",
"base_count",
"=",
"0",
"file_count",
"=",
"1",
"seq_count",
... | Splits a fasta/q file into separate files, file size determined by number of bases.
Puts <= max_bases in each split file The exception is a single sequence >=max_bases
is put in its own file. This does not split sequences. | [
"Splits",
"a",
"fasta",
"/",
"q",
"file",
"into",
"separate",
"files",
"file",
"size",
"determined",
"by",
"number",
"of",
"bases",
"."
] | python | valid |
earwig/mwparserfromhell | mwparserfromhell/wikicode.py | https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/wikicode.py#L390-L411 | def insert_before(self, obj, value, recursive=True):
"""Insert *value* immediately before *obj*.
*obj* can be either a string, a :class:`.Node`, or another
:class:`.Wikicode` object (as created by :meth:`get_sections`, for
example). If *obj* is a string, we will operate on all instances... | [
"def",
"insert_before",
"(",
"self",
",",
"obj",
",",
"value",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"Node",
",",
"Wikicode",
")",
")",
":",
"context",
",",
"index",
"=",
"self",
".",
"_do_strong_search",
... | Insert *value* immediately before *obj*.
*obj* can be either a string, a :class:`.Node`, or another
:class:`.Wikicode` object (as created by :meth:`get_sections`, for
example). If *obj* is a string, we will operate on all instances of
that string within the code, otherwise only on the s... | [
"Insert",
"*",
"value",
"*",
"immediately",
"before",
"*",
"obj",
"*",
"."
] | python | train |
rigetti/quantumflow | examples/state_prep_w16.py | https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/examples/state_prep_w16.py#L27-L114 | def w16_circuit() -> qf.Circuit:
"""
Return a circuit that prepares the the 16-qubit W state using\
sqrt(iswaps) and local gates, respecting linear topology
"""
gates = [
qf.X(7),
qf.ISWAP(7, 8) ** 0.5,
qf.S(8),
qf.Z(8),
qf.SWAP(7, 6),
qf.SWAP(6, 5)... | [
"def",
"w16_circuit",
"(",
")",
"->",
"qf",
".",
"Circuit",
":",
"gates",
"=",
"[",
"qf",
".",
"X",
"(",
"7",
")",
",",
"qf",
".",
"ISWAP",
"(",
"7",
",",
"8",
")",
"**",
"0.5",
",",
"qf",
".",
"S",
"(",
"8",
")",
",",
"qf",
".",
"Z",
"... | Return a circuit that prepares the the 16-qubit W state using\
sqrt(iswaps) and local gates, respecting linear topology | [
"Return",
"a",
"circuit",
"that",
"prepares",
"the",
"the",
"16",
"-",
"qubit",
"W",
"state",
"using",
"\\",
"sqrt",
"(",
"iswaps",
")",
"and",
"local",
"gates",
"respecting",
"linear",
"topology"
] | python | train |
rorr73/LifeSOSpy | lifesospy/util.py | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/util.py#L30-L49 | def from_ascii_hex(text: str) -> int:
"""Converts to an int value from both ASCII and regular hex.
The format used appears to vary based on whether the command was to
get an existing value (regular hex) or set a new value (ASCII hex
mirrored back from original command).
Regular hex: 012... | [
"def",
"from_ascii_hex",
"(",
"text",
":",
"str",
")",
"->",
"int",
":",
"value",
"=",
"0",
"for",
"index",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"text",
")",
")",
":",
"char_ord",
"=",
"ord",
"(",
"text",
"[",
"index",
":",
"index",
"+",
"... | Converts to an int value from both ASCII and regular hex.
The format used appears to vary based on whether the command was to
get an existing value (regular hex) or set a new value (ASCII hex
mirrored back from original command).
Regular hex: 0123456789abcdef
ASCII hex: 0123456789:... | [
"Converts",
"to",
"an",
"int",
"value",
"from",
"both",
"ASCII",
"and",
"regular",
"hex",
".",
"The",
"format",
"used",
"appears",
"to",
"vary",
"based",
"on",
"whether",
"the",
"command",
"was",
"to",
"get",
"an",
"existing",
"value",
"(",
"regular",
"h... | python | train |
log2timeline/dfwinreg | dfwinreg/fake.py | https://github.com/log2timeline/dfwinreg/blob/9d488bb1db562197dbfb48de9613d6b29dea056e/dfwinreg/fake.py#L208-L225 | def AddSubkey(self, registry_key):
"""Adds a subkey.
Args:
registry_key (WinRegistryKey): Windows Registry subkey.
Raises:
KeyError: if the subkey already exists.
"""
name = registry_key.name.upper()
if name in self._subkeys:
raise KeyError(
'Subkey: {0:s} already e... | [
"def",
"AddSubkey",
"(",
"self",
",",
"registry_key",
")",
":",
"name",
"=",
"registry_key",
".",
"name",
".",
"upper",
"(",
")",
"if",
"name",
"in",
"self",
".",
"_subkeys",
":",
"raise",
"KeyError",
"(",
"'Subkey: {0:s} already exists.'",
".",
"format",
... | Adds a subkey.
Args:
registry_key (WinRegistryKey): Windows Registry subkey.
Raises:
KeyError: if the subkey already exists. | [
"Adds",
"a",
"subkey",
"."
] | python | train |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_network_driver.py | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_network_driver.py#L747-L790 | def _remove_vlan_from_all_service_profiles(self, handle, vlan_id, ucsm_ip):
"""Deletes VLAN Profile config from server's ethernet ports."""
service_profile_list = []
for key, value in six.iteritems(self.ucsm_sp_dict):
if (ucsm_ip in key) and value:
service_profile_lis... | [
"def",
"_remove_vlan_from_all_service_profiles",
"(",
"self",
",",
"handle",
",",
"vlan_id",
",",
"ucsm_ip",
")",
":",
"service_profile_list",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"ucsm_sp_dict",
")",
":... | Deletes VLAN Profile config from server's ethernet ports. | [
"Deletes",
"VLAN",
"Profile",
"config",
"from",
"server",
"s",
"ethernet",
"ports",
"."
] | python | train |
IAMconsortium/pyam | pyam/core.py | https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L709-L747 | def check_aggregate(self, variable, components=None, exclude_on_fail=False,
multiplier=1, **kwargs):
"""Check whether a timeseries matches the aggregation of its components
Parameters
----------
variable: str
variable to be checked for matching aggreg... | [
"def",
"check_aggregate",
"(",
"self",
",",
"variable",
",",
"components",
"=",
"None",
",",
"exclude_on_fail",
"=",
"False",
",",
"multiplier",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"# compute aggregate from components, return None if no components",
"df_com... | Check whether a timeseries matches the aggregation of its components
Parameters
----------
variable: str
variable to be checked for matching aggregation of sub-categories
components: list of str, default None
list of variables, defaults to all sub-categories of `... | [
"Check",
"whether",
"a",
"timeseries",
"matches",
"the",
"aggregation",
"of",
"its",
"components"
] | python | train |
monkeython/scriba | scriba/schemes/scriba_ftps.py | https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/schemes/scriba_ftps.py#L27-L30 | def write(url, content, **args):
"""Put an object into a ftps URL."""
with FTPSResource(url, **args) as resource:
resource.write(content) | [
"def",
"write",
"(",
"url",
",",
"content",
",",
"*",
"*",
"args",
")",
":",
"with",
"FTPSResource",
"(",
"url",
",",
"*",
"*",
"args",
")",
"as",
"resource",
":",
"resource",
".",
"write",
"(",
"content",
")"
] | Put an object into a ftps URL. | [
"Put",
"an",
"object",
"into",
"a",
"ftps",
"URL",
"."
] | python | train |
ajyoon/blur | blur/rand.py | https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/rand.py#L106-L140 | def _clamp_value(value, minimum, maximum):
"""
Clamp a value to fit between a minimum and a maximum.
* If ``value`` is between ``minimum`` and ``maximum``, return ``value``
* If ``value`` is below ``minimum``, return ``minimum``
* If ``value is above ``maximum``, return ``maximum``
Args:
... | [
"def",
"_clamp_value",
"(",
"value",
",",
"minimum",
",",
"maximum",
")",
":",
"if",
"maximum",
"<",
"minimum",
":",
"raise",
"ValueError",
"if",
"value",
"<",
"minimum",
":",
"return",
"minimum",
"elif",
"value",
">",
"maximum",
":",
"return",
"maximum",
... | Clamp a value to fit between a minimum and a maximum.
* If ``value`` is between ``minimum`` and ``maximum``, return ``value``
* If ``value`` is below ``minimum``, return ``minimum``
* If ``value is above ``maximum``, return ``maximum``
Args:
value (float or int): The number to clamp
mi... | [
"Clamp",
"a",
"value",
"to",
"fit",
"between",
"a",
"minimum",
"and",
"a",
"maximum",
"."
] | python | train |
radjkarl/imgProcessor | imgProcessor/features/PatternRecognition.py | https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/features/PatternRecognition.py#L108-L196 | def findHomography(self, img, drawMatches=False):
'''
Find homography of the image through pattern
comparison with the base image
'''
print("\t Finding points...")
# Find points in the next frame
img = self._prepareImage(img)
features, descs = self... | [
"def",
"findHomography",
"(",
"self",
",",
"img",
",",
"drawMatches",
"=",
"False",
")",
":",
"print",
"(",
"\"\\t Finding points...\"",
")",
"# Find points in the next frame\r",
"img",
"=",
"self",
".",
"_prepareImage",
"(",
"img",
")",
"features",
",",
"descs"... | Find homography of the image through pattern
comparison with the base image | [
"Find",
"homography",
"of",
"the",
"image",
"through",
"pattern",
"comparison",
"with",
"the",
"base",
"image"
] | python | train |
gagneurlab/concise | concise/metrics.py | https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/metrics.py#L76-L80 | def fdr(y, z):
"""False discovery rate `fp / (tp + fp)`
"""
tp, tn, fp, fn = contingency_table(y, z)
return fp / (tp + fp) | [
"def",
"fdr",
"(",
"y",
",",
"z",
")",
":",
"tp",
",",
"tn",
",",
"fp",
",",
"fn",
"=",
"contingency_table",
"(",
"y",
",",
"z",
")",
"return",
"fp",
"/",
"(",
"tp",
"+",
"fp",
")"
] | False discovery rate `fp / (tp + fp)` | [
"False",
"discovery",
"rate",
"fp",
"/",
"(",
"tp",
"+",
"fp",
")"
] | python | train |
F5Networks/f5-common-python | f5/bigip/mixins.py | https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/mixins.py#L463-L468 | def _return_object(self, container, item_name):
"""Helper method to retrieve the object"""
coll = container.get_collection()
for item in coll:
if item.name == item_name:
return item | [
"def",
"_return_object",
"(",
"self",
",",
"container",
",",
"item_name",
")",
":",
"coll",
"=",
"container",
".",
"get_collection",
"(",
")",
"for",
"item",
"in",
"coll",
":",
"if",
"item",
".",
"name",
"==",
"item_name",
":",
"return",
"item"
] | Helper method to retrieve the object | [
"Helper",
"method",
"to",
"retrieve",
"the",
"object"
] | python | train |
serge-sans-paille/pythran | pythran/types/types.py | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/types.py#L564-L575 | def visit_Dict(self, node):
""" Define set type from all elements type (or empty_dict type). """
self.generic_visit(node)
if node.keys:
for key, value in zip(node.keys, node.values):
value_type = self.result[value]
self.combine(node, key,
... | [
"def",
"visit_Dict",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"generic_visit",
"(",
"node",
")",
"if",
"node",
".",
"keys",
":",
"for",
"key",
",",
"value",
"in",
"zip",
"(",
"node",
".",
"keys",
",",
"node",
".",
"values",
")",
":",
"val... | Define set type from all elements type (or empty_dict type). | [
"Define",
"set",
"type",
"from",
"all",
"elements",
"type",
"(",
"or",
"empty_dict",
"type",
")",
"."
] | python | train |
tonybaloney/wily | wily/config.py | https://github.com/tonybaloney/wily/blob/bae259354a91b57d56603f0ca7403186f086a84c/wily/config.py#L112-L143 | def load(config_path=DEFAULT_CONFIG_PATH):
"""
Load config file and set values to defaults where no present.
:return: The configuration ``WilyConfig``
:rtype: :class:`wily.config.WilyConfig`
"""
if not pathlib.Path(config_path).exists():
logger.debug(f"Could not locate {config_path}, us... | [
"def",
"load",
"(",
"config_path",
"=",
"DEFAULT_CONFIG_PATH",
")",
":",
"if",
"not",
"pathlib",
".",
"Path",
"(",
"config_path",
")",
".",
"exists",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"f\"Could not locate {config_path}, using default config.\"",
")",
"... | Load config file and set values to defaults where no present.
:return: The configuration ``WilyConfig``
:rtype: :class:`wily.config.WilyConfig` | [
"Load",
"config",
"file",
"and",
"set",
"values",
"to",
"defaults",
"where",
"no",
"present",
"."
] | python | train |
Microsoft/knack | knack/util.py | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/util.py#L60-L83 | def todict(obj, post_processor=None): # pylint: disable=too-many-return-statements
"""
Convert an object to a dictionary. Use 'post_processor(original_obj, dictionary)' to update the
dictionary in the process
"""
if isinstance(obj, dict):
result = {k: todict(v, post_processor) for (k, v) in... | [
"def",
"todict",
"(",
"obj",
",",
"post_processor",
"=",
"None",
")",
":",
"# pylint: disable=too-many-return-statements",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"result",
"=",
"{",
"k",
":",
"todict",
"(",
"v",
",",
"post_processor",
")",
... | Convert an object to a dictionary. Use 'post_processor(original_obj, dictionary)' to update the
dictionary in the process | [
"Convert",
"an",
"object",
"to",
"a",
"dictionary",
".",
"Use",
"post_processor",
"(",
"original_obj",
"dictionary",
")",
"to",
"update",
"the",
"dictionary",
"in",
"the",
"process"
] | python | train |
DistrictDataLabs/yellowbrick | yellowbrick/classifier/prcurve.py | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/classifier/prcurve.py#L329-L366 | def _get_y_scores(self, X):
"""
The ``precision_recall_curve`` metric requires target scores that
can either be the probability estimates of the positive class,
confidence values, or non-thresholded measures of decisions (as
returned by a "decision function").
"""
... | [
"def",
"_get_y_scores",
"(",
"self",
",",
"X",
")",
":",
"# TODO refactor shared method with ROCAUC",
"# Resolution order of scoring functions",
"attrs",
"=",
"(",
"'decision_function'",
",",
"'predict_proba'",
",",
")",
"# Return the first resolved function",
"for",
"attr",
... | The ``precision_recall_curve`` metric requires target scores that
can either be the probability estimates of the positive class,
confidence values, or non-thresholded measures of decisions (as
returned by a "decision function"). | [
"The",
"precision_recall_curve",
"metric",
"requires",
"target",
"scores",
"that",
"can",
"either",
"be",
"the",
"probability",
"estimates",
"of",
"the",
"positive",
"class",
"confidence",
"values",
"or",
"non",
"-",
"thresholded",
"measures",
"of",
"decisions",
"... | python | train |
josiahcarlson/rom | rom/query.py | https://github.com/josiahcarlson/rom/blob/8b5607a856341df85df33422accc30ba9294dbdb/rom/query.py#L691-L705 | def first(self):
'''
Returns only the first result from the query, if any.
'''
lim = [0, 1]
if self._limit:
lim[0] = self._limit[0]
if not self._filters and not self._order_by:
for ent in self:
return ent
return None
... | [
"def",
"first",
"(",
"self",
")",
":",
"lim",
"=",
"[",
"0",
",",
"1",
"]",
"if",
"self",
".",
"_limit",
":",
"lim",
"[",
"0",
"]",
"=",
"self",
".",
"_limit",
"[",
"0",
"]",
"if",
"not",
"self",
".",
"_filters",
"and",
"not",
"self",
".",
... | Returns only the first result from the query, if any. | [
"Returns",
"only",
"the",
"first",
"result",
"from",
"the",
"query",
"if",
"any",
"."
] | python | test |
Netuitive/netuitive-client-python | netuitive/element.py | https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/element.py#L43-L50 | def merge_metrics(self):
"""
Merge metrics in the internal _metrics dict to metrics list
and delete the internal _metrics
"""
self.metrics.extend(self._metrics.values())
del self._metrics | [
"def",
"merge_metrics",
"(",
"self",
")",
":",
"self",
".",
"metrics",
".",
"extend",
"(",
"self",
".",
"_metrics",
".",
"values",
"(",
")",
")",
"del",
"self",
".",
"_metrics"
] | Merge metrics in the internal _metrics dict to metrics list
and delete the internal _metrics | [
"Merge",
"metrics",
"in",
"the",
"internal",
"_metrics",
"dict",
"to",
"metrics",
"list",
"and",
"delete",
"the",
"internal",
"_metrics"
] | python | train |
lemieuxl/pyplink | pyplink/pyplink.py | https://github.com/lemieuxl/pyplink/blob/31d47c86f589064bda98206314a2d0b20e7fd2f0/pyplink/pyplink.py#L445-L471 | def iter_geno_marker(self, markers, return_index=False):
"""Iterates over genotypes for a list of markers.
Args:
markers (list): The list of markers to iterate onto.
return_index (bool): Wether to return the marker's index or not.
Returns:
tuple: The name of... | [
"def",
"iter_geno_marker",
"(",
"self",
",",
"markers",
",",
"return_index",
"=",
"False",
")",
":",
"if",
"self",
".",
"_mode",
"!=",
"\"r\"",
":",
"raise",
"UnsupportedOperation",
"(",
"\"not available in 'w' mode\"",
")",
"# If string, we change to list",
"if",
... | Iterates over genotypes for a list of markers.
Args:
markers (list): The list of markers to iterate onto.
return_index (bool): Wether to return the marker's index or not.
Returns:
tuple: The name of the marker as a string, and its genotypes as a
:py:clas... | [
"Iterates",
"over",
"genotypes",
"for",
"a",
"list",
"of",
"markers",
"."
] | python | train |
Azure/azure-sdk-for-python | build_package.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/build_package.py#L29-L67 | def travis_build_package():
"""Assumed called on Travis, to prepare a package to be deployed
This method prints on stdout for Travis.
Return is obj to pass to sys.exit() directly
"""
travis_tag = os.environ.get('TRAVIS_TAG')
if not travis_tag:
print("TRAVIS_TAG environment variable is ... | [
"def",
"travis_build_package",
"(",
")",
":",
"travis_tag",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAVIS_TAG'",
")",
"if",
"not",
"travis_tag",
":",
"print",
"(",
"\"TRAVIS_TAG environment variable is not present\"",
")",
"return",
"\"TRAVIS_TAG environment va... | Assumed called on Travis, to prepare a package to be deployed
This method prints on stdout for Travis.
Return is obj to pass to sys.exit() directly | [
"Assumed",
"called",
"on",
"Travis",
"to",
"prepare",
"a",
"package",
"to",
"be",
"deployed"
] | python | test |
pycontribs/jira | jira/client.py | https://github.com/pycontribs/jira/blob/397db5d78441ed6a680a9b7db4c62030ade1fd8a/jira/client.py#L3753-L3761 | def sprint_info(self, board_id, sprint_id):
"""Return the information about a sprint.
:param board_id: the board retrieving issues from. Deprecated and ignored.
:param sprint_id: the sprint retrieving issues from
"""
sprint = Sprint(self._options, self._session)
sprint.f... | [
"def",
"sprint_info",
"(",
"self",
",",
"board_id",
",",
"sprint_id",
")",
":",
"sprint",
"=",
"Sprint",
"(",
"self",
".",
"_options",
",",
"self",
".",
"_session",
")",
"sprint",
".",
"find",
"(",
"sprint_id",
")",
"return",
"sprint",
".",
"raw"
] | Return the information about a sprint.
:param board_id: the board retrieving issues from. Deprecated and ignored.
:param sprint_id: the sprint retrieving issues from | [
"Return",
"the",
"information",
"about",
"a",
"sprint",
"."
] | python | train |
opennode/waldur-core | waldur_core/cost_tracking/views.py | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/views.py#L79-L101 | def create(self, request, *args, **kwargs):
"""
Run **POST** request against */api/price-list-items/* to create new price list item.
Customer owner and staff can create price items.
Example of request:
.. code-block:: http
POST /api/price-list-items/ HTTP/1.1
... | [
"def",
"create",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"PriceListItemViewSet",
",",
"self",
")",
".",
"create",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Run **POST** request against */api/price-list-items/* to create new price list item.
Customer owner and staff can create price items.
Example of request:
.. code-block:: http
POST /api/price-list-items/ HTTP/1.1
Content-Type: application/json
Accept: applic... | [
"Run",
"**",
"POST",
"**",
"request",
"against",
"*",
"/",
"api",
"/",
"price",
"-",
"list",
"-",
"items",
"/",
"*",
"to",
"create",
"new",
"price",
"list",
"item",
".",
"Customer",
"owner",
"and",
"staff",
"can",
"create",
"price",
"items",
"."
] | python | train |
tanghaibao/jcvi | jcvi/formats/fasta.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/formats/fasta.py#L970-L1003 | def ids(args):
"""
%prog ids fastafiles
Generate the FASTA headers without the '>'.
"""
p = OptionParser(ids.__doc__)
p.add_option("--until", default=None,
help="Truncate the name and description at words [default: %default]")
p.add_option("--description", default=False, action... | [
"def",
"ids",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"ids",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--until\"",
",",
"default",
"=",
"None",
",",
"help",
"=",
"\"Truncate the name and description at words [default: %default]\"",
")",
... | %prog ids fastafiles
Generate the FASTA headers without the '>'. | [
"%prog",
"ids",
"fastafiles"
] | python | train |
listen-lavender/webcrawl | webcrawl/urlkit.py | https://github.com/listen-lavender/webcrawl/blob/905dcfa6e6934aac764045660c0efcef28eae1e6/webcrawl/urlkit.py#L12-L29 | def urljoin(refurl, objurl):
"""
>>> urljoin('http://www.homeinns.com/hotel', 'http://www.homeinns.com/beijing')
'http://www.homeinns.com/beijing'
>>> urljoin('http://www.homeinns.com/hotel', '/beijing')
'http://www.homeinns.com/beijing'
>>> urljoin('http://www.homeinns.com/hotel', 'beijing')
... | [
"def",
"urljoin",
"(",
"refurl",
",",
"objurl",
")",
":",
"if",
"objurl",
".",
"strip",
"(",
")",
"in",
"(",
"''",
",",
"'#'",
")",
":",
"return",
"''",
"elif",
"objurl",
".",
"startswith",
"(",
"'http'",
")",
":",
"return",
"objurl",
"elif",
"obju... | >>> urljoin('http://www.homeinns.com/hotel', 'http://www.homeinns.com/beijing')
'http://www.homeinns.com/beijing'
>>> urljoin('http://www.homeinns.com/hotel', '/beijing')
'http://www.homeinns.com/beijing'
>>> urljoin('http://www.homeinns.com/hotel', 'beijing')
'http://www.homeinns.com/beijing' | [
">>>",
"urljoin",
"(",
"http",
":",
"//",
"www",
".",
"homeinns",
".",
"com",
"/",
"hotel",
"http",
":",
"//",
"www",
".",
"homeinns",
".",
"com",
"/",
"beijing",
")",
"http",
":",
"//",
"www",
".",
"homeinns",
".",
"com",
"/",
"beijing",
">>>",
... | python | train |
pricingassistant/mrq | mrq/queue_raw.py | https://github.com/pricingassistant/mrq/blob/d0a5a34de9cba38afa94fb7c9e17f9b570b79a50/mrq/queue_raw.py#L97-L117 | def remove_raw_jobs(self, params_list):
""" Remove jobs from a raw queue with their raw params. """
if len(params_list) == 0:
return
# ZSET
if self.is_sorted:
context.connections.redis.zrem(self.redis_key, *iter(params_list))
# SET
elif self.is_... | [
"def",
"remove_raw_jobs",
"(",
"self",
",",
"params_list",
")",
":",
"if",
"len",
"(",
"params_list",
")",
"==",
"0",
":",
"return",
"# ZSET",
"if",
"self",
".",
"is_sorted",
":",
"context",
".",
"connections",
".",
"redis",
".",
"zrem",
"(",
"self",
"... | Remove jobs from a raw queue with their raw params. | [
"Remove",
"jobs",
"from",
"a",
"raw",
"queue",
"with",
"their",
"raw",
"params",
"."
] | python | train |
MisterWil/abodepy | abodepy/__init__.py | https://github.com/MisterWil/abodepy/blob/6f84bb428fd1da98855f55083cd427bebbcc57ae/abodepy/__init__.py#L107-L151 | def login(self, username=None, password=None):
"""Explicit Abode login."""
if username is not None:
self._cache[CONST.ID] = username
if password is not None:
self._cache[CONST.PASSWORD] = password
if (self._cache[CONST.ID] is None or
not isinstanc... | [
"def",
"login",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"username",
"is",
"not",
"None",
":",
"self",
".",
"_cache",
"[",
"CONST",
".",
"ID",
"]",
"=",
"username",
"if",
"password",
"is",
"not",
"Non... | Explicit Abode login. | [
"Explicit",
"Abode",
"login",
"."
] | python | train |
wonambi-python/wonambi | wonambi/trans/peaks.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/peaks.py#L9-L58 | def peaks(data, method='max', axis='time', limits=None):
"""Return the values of an index where the data is at max or min
Parameters
----------
method : str, optional
'max' or 'min'
axis : str, optional
the axis where you want to detect the peaks
limits : tuple of two values, op... | [
"def",
"peaks",
"(",
"data",
",",
"method",
"=",
"'max'",
",",
"axis",
"=",
"'time'",
",",
"limits",
"=",
"None",
")",
":",
"idx_axis",
"=",
"data",
".",
"index_of",
"(",
"axis",
")",
"output",
"=",
"data",
".",
"_copy",
"(",
")",
"output",
".",
... | Return the values of an index where the data is at max or min
Parameters
----------
method : str, optional
'max' or 'min'
axis : str, optional
the axis where you want to detect the peaks
limits : tuple of two values, optional
the lowest and highest limits where to search for... | [
"Return",
"the",
"values",
"of",
"an",
"index",
"where",
"the",
"data",
"is",
"at",
"max",
"or",
"min"
] | python | train |
bcbio/bcbio-nextgen | bcbio/bam/__init__.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/bam/__init__.py#L496-L511 | def filter_primary(bam_file, data):
"""Filter reads to primary only BAM.
Removes:
- not primary alignment (0x100) 256
- supplementary alignment (0x800) 2048
"""
stem, ext = os.path.splitext(bam_file)
out_file = stem + ".primary" + ext
if not utils.file_exists(out_file):
with... | [
"def",
"filter_primary",
"(",
"bam_file",
",",
"data",
")",
":",
"stem",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"bam_file",
")",
"out_file",
"=",
"stem",
"+",
"\".primary\"",
"+",
"ext",
"if",
"not",
"utils",
".",
"file_exists",
"(",... | Filter reads to primary only BAM.
Removes:
- not primary alignment (0x100) 256
- supplementary alignment (0x800) 2048 | [
"Filter",
"reads",
"to",
"primary",
"only",
"BAM",
"."
] | python | train |
watson-developer-cloud/python-sdk | ibm_watson/discovery_v1.py | https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/discovery_v1.py#L11789-L11802 | def _from_dict(cls, _dict):
"""Initialize a TrainingQuery object from a json dictionary."""
args = {}
if 'query_id' in _dict:
args['query_id'] = _dict.get('query_id')
if 'natural_language_query' in _dict:
args['natural_language_query'] = _dict.get('natural_languag... | [
"def",
"_from_dict",
"(",
"cls",
",",
"_dict",
")",
":",
"args",
"=",
"{",
"}",
"if",
"'query_id'",
"in",
"_dict",
":",
"args",
"[",
"'query_id'",
"]",
"=",
"_dict",
".",
"get",
"(",
"'query_id'",
")",
"if",
"'natural_language_query'",
"in",
"_dict",
"... | Initialize a TrainingQuery object from a json dictionary. | [
"Initialize",
"a",
"TrainingQuery",
"object",
"from",
"a",
"json",
"dictionary",
"."
] | python | train |
changhiskhan/poseidon | poseidon/ssh.py | https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/ssh.py#L213-L226 | def pip_r(self, requirements, raise_on_error=True):
"""
Install all requirements contained in the given file path
Waits for command to finish.
Parameters
----------
requirements: str
Path to requirements.txt
raise_on_error: bool, default True
... | [
"def",
"pip_r",
"(",
"self",
",",
"requirements",
",",
"raise_on_error",
"=",
"True",
")",
":",
"cmd",
"=",
"\"pip install -r %s\"",
"%",
"requirements",
"return",
"self",
".",
"wait",
"(",
"cmd",
",",
"raise_on_error",
"=",
"raise_on_error",
")"
] | Install all requirements contained in the given file path
Waits for command to finish.
Parameters
----------
requirements: str
Path to requirements.txt
raise_on_error: bool, default True
If True then raise ValueError if stderr is not empty | [
"Install",
"all",
"requirements",
"contained",
"in",
"the",
"given",
"file",
"path",
"Waits",
"for",
"command",
"to",
"finish",
"."
] | python | valid |
CalebBell/fluids | fluids/numerics/__init__.py | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L361-L392 | def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
'''Port of numpy's linspace to pure python. Does not support dtype, and
returns lists of floats.
'''
num = int(num)
start = start * 1.
stop = stop * 1.
if num <= 0:
return []
if endpoint:
if nu... | [
"def",
"linspace",
"(",
"start",
",",
"stop",
",",
"num",
"=",
"50",
",",
"endpoint",
"=",
"True",
",",
"retstep",
"=",
"False",
",",
"dtype",
"=",
"None",
")",
":",
"num",
"=",
"int",
"(",
"num",
")",
"start",
"=",
"start",
"*",
"1.",
"stop",
... | Port of numpy's linspace to pure python. Does not support dtype, and
returns lists of floats. | [
"Port",
"of",
"numpy",
"s",
"linspace",
"to",
"pure",
"python",
".",
"Does",
"not",
"support",
"dtype",
"and",
"returns",
"lists",
"of",
"floats",
"."
] | python | train |
iclab/centinel | centinel/primitives/dnslib.py | https://github.com/iclab/centinel/blob/9a25dcf30c6a1db3c046f7ccb8ab8873e455c1a4/centinel/primitives/dnslib.py#L264-L271 | def parse_out_ips(message):
"""Given a message, parse out the ips in the answer"""
ips = []
for entry in message.answer:
for rdata in entry.items:
ips.append(rdata.to_text())
return ips | [
"def",
"parse_out_ips",
"(",
"message",
")",
":",
"ips",
"=",
"[",
"]",
"for",
"entry",
"in",
"message",
".",
"answer",
":",
"for",
"rdata",
"in",
"entry",
".",
"items",
":",
"ips",
".",
"append",
"(",
"rdata",
".",
"to_text",
"(",
")",
")",
"retur... | Given a message, parse out the ips in the answer | [
"Given",
"a",
"message",
"parse",
"out",
"the",
"ips",
"in",
"the",
"answer"
] | python | train |
rosenbrockc/fortpy | fortpy/parsers/variable.py | https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/parsers/variable.py#L32-L78 | def _process_member(self, member, parent, string):
"""Extracts all the member info from the regex match; returns a ValueElements."""
#The modifiers regex is very greedy so we have some cleaning up to do
#to extract the mods.
modifiers = member.group("modifiers")
dimension = None
... | [
"def",
"_process_member",
"(",
"self",
",",
"member",
",",
"parent",
",",
"string",
")",
":",
"#The modifiers regex is very greedy so we have some cleaning up to do",
"#to extract the mods.",
"modifiers",
"=",
"member",
".",
"group",
"(",
"\"modifiers\"",
")",
"dimension"... | Extracts all the member info from the regex match; returns a ValueElements. | [
"Extracts",
"all",
"the",
"member",
"info",
"from",
"the",
"regex",
"match",
";",
"returns",
"a",
"ValueElements",
"."
] | python | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_oven.py | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_oven.py#L81-L117 | def macaroon(self, version, expiry, caveats, ops):
''' Takes a macaroon with the given version from the oven,
associates it with the given operations and attaches the given caveats.
There must be at least one operation specified.
The macaroon will expire at the given time - a time_before... | [
"def",
"macaroon",
"(",
"self",
",",
"version",
",",
"expiry",
",",
"caveats",
",",
"ops",
")",
":",
"if",
"len",
"(",
"ops",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'cannot mint a macaroon associated '",
"'with no operations'",
")",
"ops",
"=",
... | Takes a macaroon with the given version from the oven,
associates it with the given operations and attaches the given caveats.
There must be at least one operation specified.
The macaroon will expire at the given time - a time_before first party
caveat will be added with that time.
... | [
"Takes",
"a",
"macaroon",
"with",
"the",
"given",
"version",
"from",
"the",
"oven",
"associates",
"it",
"with",
"the",
"given",
"operations",
"and",
"attaches",
"the",
"given",
"caveats",
".",
"There",
"must",
"be",
"at",
"least",
"one",
"operation",
"specif... | python | train |
numenta/nupic | src/nupic/swarming/exp_generator/experiment_generator.py | https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/swarming/exp_generator/experiment_generator.py#L198-L229 | def _handleDescriptionFromFileOption(filename, outDir, usageStr, hsVersion,
claDescriptionTemplateFile):
"""
Parses and validates the --descriptionFromFile option and executes the
request
Parameters:
-----------------------------------------------------------------------
filena... | [
"def",
"_handleDescriptionFromFileOption",
"(",
"filename",
",",
"outDir",
",",
"usageStr",
",",
"hsVersion",
",",
"claDescriptionTemplateFile",
")",
":",
"try",
":",
"fileHandle",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"JSONStringFromFile",
"=",
"fileHand... | Parses and validates the --descriptionFromFile option and executes the
request
Parameters:
-----------------------------------------------------------------------
filename: File from which we'll extract description JSON
outDir: where to place generated experiment files
usageStr: program usage strin... | [
"Parses",
"and",
"validates",
"the",
"--",
"descriptionFromFile",
"option",
"and",
"executes",
"the",
"request"
] | python | valid |
sixty-north/asq | asq/queryables.py | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L240-L289 | def select_with_correspondence(
self,
selector,
result_selector=KeyedElement):
'''Apply a callable to each element in an input sequence, generating a new
sequence of 2-tuples where the first element is the input value and the
second is the transformed input va... | [
"def",
"select_with_correspondence",
"(",
"self",
",",
"selector",
",",
"result_selector",
"=",
"KeyedElement",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call select_with_correspondence() on a \"",
"\"closed Queryabl... | Apply a callable to each element in an input sequence, generating a new
sequence of 2-tuples where the first element is the input value and the
second is the transformed input value.
The generated sequence is lazily evaluated.
Note: This method uses deferred execution.
Args:
... | [
"Apply",
"a",
"callable",
"to",
"each",
"element",
"in",
"an",
"input",
"sequence",
"generating",
"a",
"new",
"sequence",
"of",
"2",
"-",
"tuples",
"where",
"the",
"first",
"element",
"is",
"the",
"input",
"value",
"and",
"the",
"second",
"is",
"the",
"t... | python | train |
JdeRobot/base | src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavextra.py | https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/mavextra.py#L708-L714 | def demix1(servo1, servo2, gain=0.5):
'''de-mix a mixed servo output'''
s1 = servo1 - 1500
s2 = servo2 - 1500
out1 = (s1+s2)*gain
out2 = (s1-s2)*gain
return out1+1500 | [
"def",
"demix1",
"(",
"servo1",
",",
"servo2",
",",
"gain",
"=",
"0.5",
")",
":",
"s1",
"=",
"servo1",
"-",
"1500",
"s2",
"=",
"servo2",
"-",
"1500",
"out1",
"=",
"(",
"s1",
"+",
"s2",
")",
"*",
"gain",
"out2",
"=",
"(",
"s1",
"-",
"s2",
")",... | de-mix a mixed servo output | [
"de",
"-",
"mix",
"a",
"mixed",
"servo",
"output"
] | python | train |
manns/pyspread | pyspread/src/gui/_chart_dialog.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_chart_dialog.py#L712-L721 | def get_code(self):
"""Returns code representation of value of widget"""
selection = self.GetSelection()
if selection == wx.NOT_FOUND:
selection = 0
# Return code string
return self.styles[selection][1] | [
"def",
"get_code",
"(",
"self",
")",
":",
"selection",
"=",
"self",
".",
"GetSelection",
"(",
")",
"if",
"selection",
"==",
"wx",
".",
"NOT_FOUND",
":",
"selection",
"=",
"0",
"# Return code string",
"return",
"self",
".",
"styles",
"[",
"selection",
"]",
... | Returns code representation of value of widget | [
"Returns",
"code",
"representation",
"of",
"value",
"of",
"widget"
] | python | train |
yfpeng/bioc | bioc/biocxml/encoder.py | https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocxml/encoder.py#L111-L122 | def encode_document(document):
"""Encode a single document."""
tree = etree.Element('document')
etree.SubElement(tree, 'id').text = document.id
encode_infons(tree, document.infons)
for passage in document.passages:
tree.append(encode_passage(passage))
for ann in document.annotatio... | [
"def",
"encode_document",
"(",
"document",
")",
":",
"tree",
"=",
"etree",
".",
"Element",
"(",
"'document'",
")",
"etree",
".",
"SubElement",
"(",
"tree",
",",
"'id'",
")",
".",
"text",
"=",
"document",
".",
"id",
"encode_infons",
"(",
"tree",
",",
"d... | Encode a single document. | [
"Encode",
"a",
"single",
"document",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.