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 |
|---|---|---|---|---|---|---|---|---|
globality-corp/microcosm-flask | microcosm_flask/basic_auth.py | https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/basic_auth.py#L22-L34 | def encode_basic_auth(username, password):
"""
Encode basic auth credentials.
"""
return "Basic {}".format(
b64encode(
"{}:{}".format(
username,
password,
).encode("utf-8")
).decode("utf-8")
) | [
"def",
"encode_basic_auth",
"(",
"username",
",",
"password",
")",
":",
"return",
"\"Basic {}\"",
".",
"format",
"(",
"b64encode",
"(",
"\"{}:{}\"",
".",
"format",
"(",
"username",
",",
"password",
",",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
... | Encode basic auth credentials. | [
"Encode",
"basic",
"auth",
"credentials",
"."
] | python | train |
arne-cl/discoursegraphs | src/discoursegraphs/readwrite/mmax2.py | https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/mmax2.py#L361-L403 | def spanstring2tokens(docgraph, span_string):
"""
Converts a span string (e.g. 'word_88..word_91') into a list of token
IDs (e.g. ['word_88', 'word_89', 'word_90', 'word_91']. Token IDs that
do not occur in the given document graph will be filtered out.
Q: Why are some token IDs missing in a docume... | [
"def",
"spanstring2tokens",
"(",
"docgraph",
",",
"span_string",
")",
":",
"tokens",
"=",
"convert_spanstring",
"(",
"span_string",
")",
"existing_nodes",
"=",
"set",
"(",
"docgraph",
".",
"nodes",
"(",
")",
")",
"existing_tokens",
"=",
"[",
"]",
"for",
"tok... | Converts a span string (e.g. 'word_88..word_91') into a list of token
IDs (e.g. ['word_88', 'word_89', 'word_90', 'word_91']. Token IDs that
do not occur in the given document graph will be filtered out.
Q: Why are some token IDs missing in a document graph?
A: They either have been removed manually (e... | [
"Converts",
"a",
"span",
"string",
"(",
"e",
".",
"g",
".",
"word_88",
"..",
"word_91",
")",
"into",
"a",
"list",
"of",
"token",
"IDs",
"(",
"e",
".",
"g",
".",
"[",
"word_88",
"word_89",
"word_90",
"word_91",
"]",
".",
"Token",
"IDs",
"that",
"do"... | python | train |
Yelp/kafka-utils | kafka_utils/kafka_cluster_manager/cmds/command.py | https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cmds/command.py#L261-L302 | def _extract_actions_unique_topics(self, movement_counts, max_movements, cluster_topology, max_movement_size):
"""Extract actions limiting to given max value such that
the resultant has the minimum possible number of duplicate topics.
Algorithm:
1. Group actions by by topic-nam... | [
"def",
"_extract_actions_unique_topics",
"(",
"self",
",",
"movement_counts",
",",
"max_movements",
",",
"cluster_topology",
",",
"max_movement_size",
")",
":",
"# Group actions by topic",
"topic_actions",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"t_p",
",",
"repl... | Extract actions limiting to given max value such that
the resultant has the minimum possible number of duplicate topics.
Algorithm:
1. Group actions by by topic-name: {topic: action-list}
2. Iterate through the dictionary in circular fashion and keep
extracting... | [
"Extract",
"actions",
"limiting",
"to",
"given",
"max",
"value",
"such",
"that",
"the",
"resultant",
"has",
"the",
"minimum",
"possible",
"number",
"of",
"duplicate",
"topics",
"."
] | python | train |
CityOfZion/neo-python-core | neocore/KeyPair.py | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L171-L187 | def Export(self):
"""
Export this KeyPair's private key in WIF format.
Returns:
str: The key in wif format
"""
data = bytearray(38)
data[0] = 0x80
data[1:33] = self.PrivateKey[0:32]
data[33] = 0x01
checksum = Crypto.Default().Hash256(... | [
"def",
"Export",
"(",
"self",
")",
":",
"data",
"=",
"bytearray",
"(",
"38",
")",
"data",
"[",
"0",
"]",
"=",
"0x80",
"data",
"[",
"1",
":",
"33",
"]",
"=",
"self",
".",
"PrivateKey",
"[",
"0",
":",
"32",
"]",
"data",
"[",
"33",
"]",
"=",
"... | Export this KeyPair's private key in WIF format.
Returns:
str: The key in wif format | [
"Export",
"this",
"KeyPair",
"s",
"private",
"key",
"in",
"WIF",
"format",
"."
] | python | train |
apache/incubator-mxnet | python/mxnet/ndarray/ndarray.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L2615-L2659 | def _ufunc_helper(lhs, rhs, fn_array, fn_scalar, lfn_scalar, rfn_scalar=None):
""" Helper function for element-wise operation.
The function will perform numpy-like broadcasting if needed and call different functions.
Parameters
--------
lhs : NDArray or numeric value
Left-hand side operand.... | [
"def",
"_ufunc_helper",
"(",
"lhs",
",",
"rhs",
",",
"fn_array",
",",
"fn_scalar",
",",
"lfn_scalar",
",",
"rfn_scalar",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"lhs",
",",
"numeric_types",
")",
":",
"if",
"isinstance",
"(",
"rhs",
",",
"numeric_... | Helper function for element-wise operation.
The function will perform numpy-like broadcasting if needed and call different functions.
Parameters
--------
lhs : NDArray or numeric value
Left-hand side operand.
rhs : NDArray or numeric value
Right-hand operand,
fn_array : functi... | [
"Helper",
"function",
"for",
"element",
"-",
"wise",
"operation",
".",
"The",
"function",
"will",
"perform",
"numpy",
"-",
"like",
"broadcasting",
"if",
"needed",
"and",
"call",
"different",
"functions",
"."
] | python | train |
stitchfix/pyxley | pyxley/charts/mg/graphic.py | https://github.com/stitchfix/pyxley/blob/2dab00022d977d986169cd8a629b3a2f91be893f/pyxley/charts/mg/graphic.py#L164-L176 | def legend(self, values):
"""Set the legend labels.
Args:
values (list): list of labels.
Raises:
ValueError: legend must be a list of labels.
"""
if not isinstance(values, list):
raise TypeError("legend must be a list of label... | [
"def",
"legend",
"(",
"self",
",",
"values",
")",
":",
"if",
"not",
"isinstance",
"(",
"values",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"legend must be a list of labels\"",
")",
"self",
".",
"options",
"[",
"\"legend\"",
"]",
"=",
"values"
] | Set the legend labels.
Args:
values (list): list of labels.
Raises:
ValueError: legend must be a list of labels. | [
"Set",
"the",
"legend",
"labels",
"."
] | python | train |
ktdreyer/txkoji | txkoji/connection.py | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L117-L158 | def from_web(self, url):
"""
Reverse-engineer a kojiweb URL into an equivalent API response.
Only a few kojiweb URL endpoints work here.
See also connect_from_web().
:param url: ``str``, for example
"http://cbs.centos.org/koji/buildinfo?buildID=21155"
... | [
"def",
"from_web",
"(",
"self",
",",
"url",
")",
":",
"# Treat any input with whitespace as invalid:",
"if",
"re",
".",
"search",
"(",
"r'\\s'",
",",
"url",
")",
":",
"return",
"defer",
".",
"succeed",
"(",
"None",
")",
"o",
"=",
"urlparse",
"(",
"url",
... | Reverse-engineer a kojiweb URL into an equivalent API response.
Only a few kojiweb URL endpoints work here.
See also connect_from_web().
:param url: ``str``, for example
"http://cbs.centos.org/koji/buildinfo?buildID=21155"
:returns: deferred that when fired returns... | [
"Reverse",
"-",
"engineer",
"a",
"kojiweb",
"URL",
"into",
"an",
"equivalent",
"API",
"response",
"."
] | python | train |
mfcloud/python-zvm-sdk | zvmsdk/utils.py | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmsdk/utils.py#L410-L423 | def log_and_reraise_smt_request_failed(action=None):
"""Catch SDK base exception and print error log before reraise exception.
msg: the error message to be logged.
"""
try:
yield
except exception.SDKSMTRequestFailed as err:
msg = ''
if action is not None:
msg = "... | [
"def",
"log_and_reraise_smt_request_failed",
"(",
"action",
"=",
"None",
")",
":",
"try",
":",
"yield",
"except",
"exception",
".",
"SDKSMTRequestFailed",
"as",
"err",
":",
"msg",
"=",
"''",
"if",
"action",
"is",
"not",
"None",
":",
"msg",
"=",
"\"Failed to ... | Catch SDK base exception and print error log before reraise exception.
msg: the error message to be logged. | [
"Catch",
"SDK",
"base",
"exception",
"and",
"print",
"error",
"log",
"before",
"reraise",
"exception",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/assessment/objects.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/objects.py#L1150-L1154 | def set_children(self, child_ids):
"""Set the children IDs"""
if not self._supports_simple_sequencing():
raise errors.IllegalState()
self._my_map['childIds'] = [str(i) for i in child_ids] | [
"def",
"set_children",
"(",
"self",
",",
"child_ids",
")",
":",
"if",
"not",
"self",
".",
"_supports_simple_sequencing",
"(",
")",
":",
"raise",
"errors",
".",
"IllegalState",
"(",
")",
"self",
".",
"_my_map",
"[",
"'childIds'",
"]",
"=",
"[",
"str",
"("... | Set the children IDs | [
"Set",
"the",
"children",
"IDs"
] | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_ip_policy.py#L382-L401 | def hide_routemap_holder_route_map_content_match_protocol_protocol_static_container_static(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
... | [
"def",
"hide_routemap_holder_route_map_content_match_protocol_protocol_static_container_static",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_routemap_holder",
"=",
"ET",
".",
"SubElement",
"(",
"co... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
fastai/fastai | fastai/vision/image.py | https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/image.py#L426-L432 | def show_image(img:Image, ax:plt.Axes=None, figsize:tuple=(3,3), hide_axis:bool=True, cmap:str='binary',
alpha:float=None, **kwargs)->plt.Axes:
"Display `Image` in notebook."
if ax is None: fig,ax = plt.subplots(figsize=figsize)
ax.imshow(image2np(img.data), cmap=cmap, alpha=alpha, **kwargs)... | [
"def",
"show_image",
"(",
"img",
":",
"Image",
",",
"ax",
":",
"plt",
".",
"Axes",
"=",
"None",
",",
"figsize",
":",
"tuple",
"=",
"(",
"3",
",",
"3",
")",
",",
"hide_axis",
":",
"bool",
"=",
"True",
",",
"cmap",
":",
"str",
"=",
"'binary'",
",... | Display `Image` in notebook. | [
"Display",
"Image",
"in",
"notebook",
"."
] | python | train |
sibirrer/lenstronomy | lenstronomy/LensModel/Profiles/sersic.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/LensModel/Profiles/sersic.py#L39-L53 | def derivatives(self, x, y, n_sersic, R_sersic, k_eff, center_x=0, center_y=0):
"""
returns df/dx and df/dy of the function
"""
x_ = x - center_x
y_ = y - center_y
r = np.sqrt(x_**2 + y_**2)
if isinstance(r, int) or isinstance(r, float):
r = max(self._... | [
"def",
"derivatives",
"(",
"self",
",",
"x",
",",
"y",
",",
"n_sersic",
",",
"R_sersic",
",",
"k_eff",
",",
"center_x",
"=",
"0",
",",
"center_y",
"=",
"0",
")",
":",
"x_",
"=",
"x",
"-",
"center_x",
"y_",
"=",
"y",
"-",
"center_y",
"r",
"=",
"... | returns df/dx and df/dy of the function | [
"returns",
"df",
"/",
"dx",
"and",
"df",
"/",
"dy",
"of",
"the",
"function"
] | python | train |
pytroll/satpy | satpy/readers/iasi_l2.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/readers/iasi_l2.py#L125-L140 | def read_dataset(fid, key):
"""Read dataset"""
dsid = DSET_NAMES[key.name]
dset = fid["/PWLR/" + dsid]
if dset.ndim == 3:
dims = ['y', 'x', 'level']
else:
dims = ['y', 'x']
data = xr.DataArray(da.from_array(dset.value, chunks=CHUNK_SIZE),
name=key.name, di... | [
"def",
"read_dataset",
"(",
"fid",
",",
"key",
")",
":",
"dsid",
"=",
"DSET_NAMES",
"[",
"key",
".",
"name",
"]",
"dset",
"=",
"fid",
"[",
"\"/PWLR/\"",
"+",
"dsid",
"]",
"if",
"dset",
".",
"ndim",
"==",
"3",
":",
"dims",
"=",
"[",
"'y'",
",",
... | Read dataset | [
"Read",
"dataset"
] | python | train |
GetmeUK/MongoFrames | mongoframes/queries.py | https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/queries.py#L249-L258 | def SortBy(*qs):
"""Convert a list of Q objects into list of sort instructions"""
sort = []
for q in qs:
if q._path.endswith('.desc'):
sort.append((q._path[:-5], DESCENDING))
else:
sort.append((q._path, ASCENDING))
return sort | [
"def",
"SortBy",
"(",
"*",
"qs",
")",
":",
"sort",
"=",
"[",
"]",
"for",
"q",
"in",
"qs",
":",
"if",
"q",
".",
"_path",
".",
"endswith",
"(",
"'.desc'",
")",
":",
"sort",
".",
"append",
"(",
"(",
"q",
".",
"_path",
"[",
":",
"-",
"5",
"]",
... | Convert a list of Q objects into list of sort instructions | [
"Convert",
"a",
"list",
"of",
"Q",
"objects",
"into",
"list",
"of",
"sort",
"instructions"
] | python | train |
RJT1990/pyflux | pyflux/families/exponential.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/exponential.py#L251-L275 | def neg_loglikelihood(y, mean, scale, shape, skewness):
""" Negative loglikelihood function
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float... | [
"def",
"neg_loglikelihood",
"(",
"y",
",",
"mean",
",",
"scale",
",",
"shape",
",",
"skewness",
")",
":",
"return",
"-",
"np",
".",
"sum",
"(",
"ss",
".",
"expon",
".",
"logpdf",
"(",
"x",
"=",
"y",
",",
"scale",
"=",
"1",
"/",
"mean",
")",
")"... | Negative loglikelihood function
Parameters
----------
y : np.ndarray
univariate time series
mean : np.ndarray
array of location parameters for the Exponential distribution
scale : float
scale parameter for the Exponential distribution
... | [
"Negative",
"loglikelihood",
"function"
] | python | train |
predicador37/pyjstat | pyjstat/pyjstat.py | https://github.com/predicador37/pyjstat/blob/45d671835a99eb573e1058cd43ce93ac4f85f9fa/pyjstat/pyjstat.py#L254-L284 | def get_dim_index(js_dict, dim):
"""Get index from a given dimension.
Args:
js_dict (dict): dictionary containing dataset data and metadata.
dim (string): dimension name obtained from JSON file.
Returns:
dim_index (pandas.DataFrame): DataFrame with index-based dimension data.
"""
... | [
"def",
"get_dim_index",
"(",
"js_dict",
",",
"dim",
")",
":",
"try",
":",
"dim_index",
"=",
"js_dict",
"[",
"'dimension'",
"]",
"[",
"dim",
"]",
"[",
"'category'",
"]",
"[",
"'index'",
"]",
"except",
"KeyError",
":",
"dim_label",
"=",
"get_dim_label",
"(... | Get index from a given dimension.
Args:
js_dict (dict): dictionary containing dataset data and metadata.
dim (string): dimension name obtained from JSON file.
Returns:
dim_index (pandas.DataFrame): DataFrame with index-based dimension data. | [
"Get",
"index",
"from",
"a",
"given",
"dimension",
"."
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/profilers/visual/profilehooks.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/profilehooks.py#L137-L224 | def profile(fn=None, skip=0, filename=None, immediate=False, dirs=False,
sort=None, entries=40,
profiler=('cProfile', 'profile', 'hotshot')):
"""Mark `fn` for profiling.
If `skip` is > 0, first `skip` calls to `fn` will not be profiled.
If `immediate` is False, profiling results wi... | [
"def",
"profile",
"(",
"fn",
"=",
"None",
",",
"skip",
"=",
"0",
",",
"filename",
"=",
"None",
",",
"immediate",
"=",
"False",
",",
"dirs",
"=",
"False",
",",
"sort",
"=",
"None",
",",
"entries",
"=",
"40",
",",
"profiler",
"=",
"(",
"'cProfile'",
... | Mark `fn` for profiling.
If `skip` is > 0, first `skip` calls to `fn` will not be profiled.
If `immediate` is False, profiling results will be printed to
sys.stdout on program termination. Otherwise results will be printed
after each call.
If `dirs` is False only the name of the file will be pri... | [
"Mark",
"fn",
"for",
"profiling",
"."
] | python | train |
CiscoUcs/UcsPythonSDK | src/UcsSdk/utils/helper.py | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/utils/helper.py#L31-L41 | def create_dn_wcard_filter(filter_class, filter_value):
""" Creates wild card filter object for given class name, and values.
:param filter_class: class name
:param filter_value: filter property value
:return WcardFilter: WcardFilter object
"""
wcard_filter = WcardFilter()
wcard_filter.Cla... | [
"def",
"create_dn_wcard_filter",
"(",
"filter_class",
",",
"filter_value",
")",
":",
"wcard_filter",
"=",
"WcardFilter",
"(",
")",
"wcard_filter",
".",
"Class",
"=",
"filter_class",
"wcard_filter",
".",
"Property",
"=",
"\"dn\"",
"wcard_filter",
".",
"Value",
"=",... | Creates wild card filter object for given class name, and values.
:param filter_class: class name
:param filter_value: filter property value
:return WcardFilter: WcardFilter object | [
"Creates",
"wild",
"card",
"filter",
"object",
"for",
"given",
"class",
"name",
"and",
"values",
".",
":",
"param",
"filter_class",
":",
"class",
"name",
":",
"param",
"filter_value",
":",
"filter",
"property",
"value",
":",
"return",
"WcardFilter",
":",
"Wc... | python | train |
pmclanahan/django-celery-email | djcelery_email/utils.py | https://github.com/pmclanahan/django-celery-email/blob/6d0684b3d2d6751c4e5066f9215e130e6a91ea78/djcelery_email/utils.py#L10-L24 | def chunked(iterator, chunksize):
"""
Yields items from 'iterator' in chunks of size 'chunksize'.
>>> list(chunked([1, 2, 3, 4, 5], chunksize=2))
[(1, 2), (3, 4), (5,)]
"""
chunk = []
for idx, item in enumerate(iterator, 1):
chunk.append(item)
if idx % chunksize == 0:
... | [
"def",
"chunked",
"(",
"iterator",
",",
"chunksize",
")",
":",
"chunk",
"=",
"[",
"]",
"for",
"idx",
",",
"item",
"in",
"enumerate",
"(",
"iterator",
",",
"1",
")",
":",
"chunk",
".",
"append",
"(",
"item",
")",
"if",
"idx",
"%",
"chunksize",
"==",... | Yields items from 'iterator' in chunks of size 'chunksize'.
>>> list(chunked([1, 2, 3, 4, 5], chunksize=2))
[(1, 2), (3, 4), (5,)] | [
"Yields",
"items",
"from",
"iterator",
"in",
"chunks",
"of",
"size",
"chunksize",
"."
] | python | train |
pytroll/satpy | satpy/readers/hrit_jma.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/readers/hrit_jma.py#L191-L204 | def _check_sensor_platform_consistency(self, sensor):
"""Make sure sensor and platform are consistent
Args:
sensor (str) : Sensor name from YAML dataset definition
Raises:
ValueError if they don't match
"""
ref_sensor = SENSORS.get(self.platform, None)
... | [
"def",
"_check_sensor_platform_consistency",
"(",
"self",
",",
"sensor",
")",
":",
"ref_sensor",
"=",
"SENSORS",
".",
"get",
"(",
"self",
".",
"platform",
",",
"None",
")",
"if",
"ref_sensor",
"and",
"not",
"sensor",
"==",
"ref_sensor",
":",
"logger",
".",
... | Make sure sensor and platform are consistent
Args:
sensor (str) : Sensor name from YAML dataset definition
Raises:
ValueError if they don't match | [
"Make",
"sure",
"sensor",
"and",
"platform",
"are",
"consistent"
] | python | train |
fulfilio/fulfil-python-api | fulfil_client/client.py | https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/client.py#L333-L343 | def update(self, data=None, **kwargs):
"""
Update the record right away.
:param data: dictionary of changes
:param kwargs: possibly a list of keyword args to change
"""
if data is None:
data = {}
data.update(kwargs)
return self.model.write([se... | [
"def",
"update",
"(",
"self",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"{",
"}",
"data",
".",
"update",
"(",
"kwargs",
")",
"return",
"self",
".",
"model",
".",
"write",
"(",
"["... | Update the record right away.
:param data: dictionary of changes
:param kwargs: possibly a list of keyword args to change | [
"Update",
"the",
"record",
"right",
"away",
"."
] | python | train |
RJT1990/pyflux | pyflux/ssm/llm.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/ssm/llm.py#L264-L323 | def plot_fit(self, intervals=True, **kwargs):
""" Plots the fit of the model
Parameters
----------
intervals : Boolean
Whether to plot 95% confidence interval of states
Returns
----------
None (plots data and the fit)
"""
import matpl... | [
"def",
"plot_fit",
"(",
"self",
",",
"intervals",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"seaborn",
"as",
"sns",
"figsize",
"=",
"kwargs",
".",
"get",
"(",
"'figsize'",
",",
"(",
... | Plots the fit of the model
Parameters
----------
intervals : Boolean
Whether to plot 95% confidence interval of states
Returns
----------
None (plots data and the fit) | [
"Plots",
"the",
"fit",
"of",
"the",
"model"
] | python | train |
googlefonts/ufo2ft | Lib/ufo2ft/postProcessor.py | https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/postProcessor.py#L135-L168 | def _build_production_name(self, glyph):
"""Build a production name for a single glyph."""
# use PostScript names from UFO lib if available
if self._postscriptNames:
production_name = self._postscriptNames.get(glyph.name)
return production_name if production_name else gl... | [
"def",
"_build_production_name",
"(",
"self",
",",
"glyph",
")",
":",
"# use PostScript names from UFO lib if available",
"if",
"self",
".",
"_postscriptNames",
":",
"production_name",
"=",
"self",
".",
"_postscriptNames",
".",
"get",
"(",
"glyph",
".",
"name",
")",... | Build a production name for a single glyph. | [
"Build",
"a",
"production",
"name",
"for",
"a",
"single",
"glyph",
"."
] | python | train |
pacificclimate/cfmeta | cfmeta/cmipfile.py | https://github.com/pacificclimate/cfmeta/blob/a6eef78d0bce523bb44920ba96233f034b60316a/cfmeta/cmipfile.py#L176-L195 | def get_var_name(nc):
"""Guesses the variable_name of an open NetCDF file
"""
non_variable_names = [
'lat',
'lat_bnds',
'lon',
'lon_bnds',
'time',
'latitude',
'longitude',
'bnds'
]
_vars = set(nc.variables.keys())
_vars.difference... | [
"def",
"get_var_name",
"(",
"nc",
")",
":",
"non_variable_names",
"=",
"[",
"'lat'",
",",
"'lat_bnds'",
",",
"'lon'",
",",
"'lon_bnds'",
",",
"'time'",
",",
"'latitude'",
",",
"'longitude'",
",",
"'bnds'",
"]",
"_vars",
"=",
"set",
"(",
"nc",
".",
"varia... | Guesses the variable_name of an open NetCDF file | [
"Guesses",
"the",
"variable_name",
"of",
"an",
"open",
"NetCDF",
"file"
] | python | train |
JasonKessler/scattertext | scattertext/representations/Word2VecFromParsedCorpus.py | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/representations/Word2VecFromParsedCorpus.py#L59-L77 | def add_phrases(self, corpus):
'''
Parameters
----------
corpus: Corpus for phrase augmentation
Returns
-------
New ParsedCorpus containing unigrams in corpus and new phrases
'''
from gensim.models import Phrases
assert isinstance(corpus, ParsedCorpus)
self.phrases = [Phrases(CorpusAdapterForGen... | [
"def",
"add_phrases",
"(",
"self",
",",
"corpus",
")",
":",
"from",
"gensim",
".",
"models",
"import",
"Phrases",
"assert",
"isinstance",
"(",
"corpus",
",",
"ParsedCorpus",
")",
"self",
".",
"phrases",
"=",
"[",
"Phrases",
"(",
"CorpusAdapterForGensim",
"."... | Parameters
----------
corpus: Corpus for phrase augmentation
Returns
-------
New ParsedCorpus containing unigrams in corpus and new phrases | [
"Parameters",
"----------",
"corpus",
":",
"Corpus",
"for",
"phrase",
"augmentation"
] | python | train |
dougalsutherland/skl-groups | skl_groups/kernels/transform.py | https://github.com/dougalsutherland/skl-groups/blob/2584c10a413626c6d5f9078cdbf3dcc84e4e9a5b/skl_groups/kernels/transform.py#L259-L290 | def fit(self, X, y=None):
'''
Learn the linear transformation to clipped eigenvalues.
Note that if min_eig isn't zero and any of the original eigenvalues
were exactly zero, this will leave those eigenvalues as zero.
Parameters
----------
X : array, shape [n, n]
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"n",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"if",
"X",
".",
"shape",
"!=",
"(",
"n",
",",
"n",
")",
":",
"raise",
"TypeError",
"(",
"\"Input must be a square matrix.\"",
")",
... | Learn the linear transformation to clipped eigenvalues.
Note that if min_eig isn't zero and any of the original eigenvalues
were exactly zero, this will leave those eigenvalues as zero.
Parameters
----------
X : array, shape [n, n]
The *symmetric* input similarities... | [
"Learn",
"the",
"linear",
"transformation",
"to",
"clipped",
"eigenvalues",
"."
] | python | valid |
timkpaine/pyEX | pyEX/marketdata/http.py | https://github.com/timkpaine/pyEX/blob/91cf751dafdb208a0c8b5377945e5808b99f94ba/pyEX/marketdata/http.py#L132-L149 | def auction(symbol=None, token='', version=''):
'''DEEP broadcasts an Auction Information Message every one second between the Lock-in Time and the auction match for Opening and Closing Auctions,
and during the Display Only Period for IPO, Halt, and Volatility Auctions. Only IEX listed securities are eligible f... | [
"def",
"auction",
"(",
"symbol",
"=",
"None",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"_raiseIfNotStr",
"(",
"symbol",
")",
"if",
"symbol",
":",
"return",
"_getJson",
"(",
"'deep/auction?symbols='",
"+",
"symbol",
",",
"token",
",",... | DEEP broadcasts an Auction Information Message every one second between the Lock-in Time and the auction match for Opening and Closing Auctions,
and during the Display Only Period for IPO, Halt, and Volatility Auctions. Only IEX listed securities are eligible for IEX Auctions.
https://iexcloud.io/docs/api/#dee... | [
"DEEP",
"broadcasts",
"an",
"Auction",
"Information",
"Message",
"every",
"one",
"second",
"between",
"the",
"Lock",
"-",
"in",
"Time",
"and",
"the",
"auction",
"match",
"for",
"Opening",
"and",
"Closing",
"Auctions",
"and",
"during",
"the",
"Display",
"Only",... | python | valid |
jalanb/pysyte | pysyte/paths.py | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/paths.py#L855-L864 | def pyc_to_py(path_to_file):
"""Change some file extensions to those which are more likely to be text
>>> pyc_to_py('vim.pyc') == 'vim.py'
True
"""
stem, ext = os.path.splitext(path_to_file)
if ext == '.pyc':
return '%s.py' % stem
return path_to_file | [
"def",
"pyc_to_py",
"(",
"path_to_file",
")",
":",
"stem",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path_to_file",
")",
"if",
"ext",
"==",
"'.pyc'",
":",
"return",
"'%s.py'",
"%",
"stem",
"return",
"path_to_file"
] | Change some file extensions to those which are more likely to be text
>>> pyc_to_py('vim.pyc') == 'vim.py'
True | [
"Change",
"some",
"file",
"extensions",
"to",
"those",
"which",
"are",
"more",
"likely",
"to",
"be",
"text"
] | python | train |
harvard-nrg/yaxil | yaxil/__init__.py | https://github.com/harvard-nrg/yaxil/blob/af594082258e62d1904d6e6841fce0bb5c0bf309/yaxil/__init__.py#L151-L205 | def subjects(auth, label=None, project=None):
'''
Retrieve Subject tuples for subjects returned by this function.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.subjects(auth, 'AB1234C')
Subject(uri=u'/data/experi... | [
"def",
"subjects",
"(",
"auth",
",",
"label",
"=",
"None",
",",
"project",
"=",
"None",
")",
":",
"url",
"=",
"'{0}/data/subjects'",
".",
"format",
"(",
"auth",
".",
"url",
".",
"rstrip",
"(",
"'/'",
")",
")",
"logger",
".",
"debug",
"(",
"'issuing h... | Retrieve Subject tuples for subjects returned by this function.
Example:
>>> import yaxil
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.subjects(auth, 'AB1234C')
Subject(uri=u'/data/experiments/XNAT_S0001', label=u'AB1234C', id=u'XNAT_S0001',
... | [
"Retrieve",
"Subject",
"tuples",
"for",
"subjects",
"returned",
"by",
"this",
"function",
".",
"Example",
":",
">>>",
"import",
"yaxil",
">>>",
"auth",
"=",
"yaxil",
".",
"XnatAuth",
"(",
"url",
"=",
"...",
"username",
"=",
"...",
"password",
"=",
"...",
... | python | train |
ray-project/ray | python/ray/rllib/optimizers/rollout.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/optimizers/rollout.py#L43-L72 | def collect_samples_straggler_mitigation(agents, train_batch_size):
"""Collects at least train_batch_size samples.
This is the legacy behavior as of 0.6, and launches extra sample tasks to
potentially improve performance but can result in many wasted samples.
"""
num_timesteps_so_far = 0
traje... | [
"def",
"collect_samples_straggler_mitigation",
"(",
"agents",
",",
"train_batch_size",
")",
":",
"num_timesteps_so_far",
"=",
"0",
"trajectories",
"=",
"[",
"]",
"agent_dict",
"=",
"{",
"}",
"for",
"agent",
"in",
"agents",
":",
"fut_sample",
"=",
"agent",
".",
... | Collects at least train_batch_size samples.
This is the legacy behavior as of 0.6, and launches extra sample tasks to
potentially improve performance but can result in many wasted samples. | [
"Collects",
"at",
"least",
"train_batch_size",
"samples",
"."
] | python | train |
troeger/opensubmit | web/opensubmit/models/submission.py | https://github.com/troeger/opensubmit/blob/384a95b7c6fa41e3f949a129d25dafd9a1c54859/web/opensubmit/models/submission.py#L234-L244 | def qs_tobegraded(qs):
'''
A filtering of the given Submission queryset for all submissions that are gradeable. This includes the following cases:
- The submission was submitted and there are no tests.
- The submission was successfully validity-tested, regardless of the full... | [
"def",
"qs_tobegraded",
"(",
"qs",
")",
":",
"return",
"qs",
".",
"filter",
"(",
"state__in",
"=",
"[",
"Submission",
".",
"SUBMITTED",
",",
"Submission",
".",
"SUBMITTED_TESTED",
",",
"Submission",
".",
"TEST_FULL_FAILED",
",",
"Submission",
".",
"GRADING_IN_... | A filtering of the given Submission queryset for all submissions that are gradeable. This includes the following cases:
- The submission was submitted and there are no tests.
- The submission was successfully validity-tested, regardless of the full test status (not existent / failed / success).... | [
"A",
"filtering",
"of",
"the",
"given",
"Submission",
"queryset",
"for",
"all",
"submissions",
"that",
"are",
"gradeable",
".",
"This",
"includes",
"the",
"following",
"cases",
":"
] | python | train |
chrippa/ds4drv | ds4drv/uinput.py | https://github.com/chrippa/ds4drv/blob/be7327fc3f5abb8717815f2a1a2ad3d335535d8a/ds4drv/uinput.py#L452-L469 | def parse_uinput_mapping(name, mapping):
"""Parses a dict of mapping options."""
axes, buttons, mouse, mouse_options = {}, {}, {}, {}
description = "ds4drv custom mapping ({0})".format(name)
for key, attr in mapping.items():
key = key.upper()
if key.startswith("BTN_") or key.startswith(... | [
"def",
"parse_uinput_mapping",
"(",
"name",
",",
"mapping",
")",
":",
"axes",
",",
"buttons",
",",
"mouse",
",",
"mouse_options",
"=",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
"description",
"=",
"\"ds4drv custom mapping ({0})\"",
".",
"for... | Parses a dict of mapping options. | [
"Parses",
"a",
"dict",
"of",
"mapping",
"options",
"."
] | python | train |
gboeing/osmnx | osmnx/utils.py | https://github.com/gboeing/osmnx/blob/be59fd313bcb68af8fc79242c56194f1247e26e2/osmnx/utils.py#L863-L892 | def geocode(query):
"""
Geocode a query string to (lat, lon) with the Nominatim geocoder.
Parameters
----------
query : string
the query string to geocode
Returns
-------
point : tuple
the (lat, lon) coordinates returned by the geocoder
"""
# send the query to ... | [
"def",
"geocode",
"(",
"query",
")",
":",
"# send the query to the nominatim geocoder and parse the json response",
"url_template",
"=",
"'https://nominatim.openstreetmap.org/search?format=json&limit=1&q={}'",
"url",
"=",
"url_template",
".",
"format",
"(",
"query",
")",
"respons... | Geocode a query string to (lat, lon) with the Nominatim geocoder.
Parameters
----------
query : string
the query string to geocode
Returns
-------
point : tuple
the (lat, lon) coordinates returned by the geocoder | [
"Geocode",
"a",
"query",
"string",
"to",
"(",
"lat",
"lon",
")",
"with",
"the",
"Nominatim",
"geocoder",
"."
] | python | train |
gabstopper/smc-python | smc/core/interfaces.py | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/interfaces.py#L229-L255 | def set_backup_mgt(self, interface_id):
"""
Set this interface as a backup management interface.
Backup management interfaces cannot be placed on an interface with
only a CVI (requires node interface/s). To 'unset' the specified
interface address, set interface id to Non... | [
"def",
"set_backup_mgt",
"(",
"self",
",",
"interface_id",
")",
":",
"self",
".",
"interface",
".",
"set_unset",
"(",
"interface_id",
",",
"'backup_mgt'",
")",
"self",
".",
"_engine",
".",
"update",
"(",
")"
] | Set this interface as a backup management interface.
Backup management interfaces cannot be placed on an interface with
only a CVI (requires node interface/s). To 'unset' the specified
interface address, set interface id to None
::
engine.interface_options.s... | [
"Set",
"this",
"interface",
"as",
"a",
"backup",
"management",
"interface",
".",
"Backup",
"management",
"interfaces",
"cannot",
"be",
"placed",
"on",
"an",
"interface",
"with",
"only",
"a",
"CVI",
"(",
"requires",
"node",
"interface",
"/",
"s",
")",
".",
... | python | train |
glue-viz/glue-vispy-viewers | glue_vispy_viewers/extern/vispy/color/colormap.py | https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/color/colormap.py#L31-L40 | def _vector(x, type='row'):
"""Convert an object to a row or column vector."""
if isinstance(x, (list, tuple)):
x = np.array(x, dtype=np.float32)
elif not isinstance(x, np.ndarray):
x = np.array([x], dtype=np.float32)
assert x.ndim == 1
if type == 'column':
x = x[:, None]
... | [
"def",
"_vector",
"(",
"x",
",",
"type",
"=",
"'row'",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"x",
"=",
"np",
".",
"array",
"(",
"x",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"elif",
"not",... | Convert an object to a row or column vector. | [
"Convert",
"an",
"object",
"to",
"a",
"row",
"or",
"column",
"vector",
"."
] | python | train |
JoaoFelipe/pyposast | pyposast/visitor.py | https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L1054-L1071 | def visit_Print(self, node):
""" Python 2 """
start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8)
node.op_pos = [
NodeWithPosition(node.uid, (node.first_line, node.first_col))
]
subnodes = []
if node.dest:
min_first_max_last(nod... | [
"def",
"visit_Print",
"(",
"self",
",",
"node",
")",
":",
"start_by_keyword",
"(",
"node",
",",
"self",
".",
"operators",
"[",
"'print'",
"]",
",",
"self",
".",
"bytes_pos_to_utf8",
")",
"node",
".",
"op_pos",
"=",
"[",
"NodeWithPosition",
"(",
"node",
"... | Python 2 | [
"Python",
"2"
] | python | train |
tdryer/hangups | hangups/client.py | https://github.com/tdryer/hangups/blob/85c0bf0a57698d077461283895707260f9dbf931/hangups/client.py#L636-L644 | async def set_group_link_sharing_enabled(
self, set_group_link_sharing_enabled_request
):
"""Set whether group link sharing is enabled for a conversation."""
response = hangouts_pb2.SetGroupLinkSharingEnabledResponse()
await self._pb_request('conversations/setgrouplinksharingenab... | [
"async",
"def",
"set_group_link_sharing_enabled",
"(",
"self",
",",
"set_group_link_sharing_enabled_request",
")",
":",
"response",
"=",
"hangouts_pb2",
".",
"SetGroupLinkSharingEnabledResponse",
"(",
")",
"await",
"self",
".",
"_pb_request",
"(",
"'conversations/setgroupli... | Set whether group link sharing is enabled for a conversation. | [
"Set",
"whether",
"group",
"link",
"sharing",
"is",
"enabled",
"for",
"a",
"conversation",
"."
] | python | valid |
sibirrer/lenstronomy | lenstronomy/LensModel/Profiles/p_jaffe.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/LensModel/Profiles/p_jaffe.py#L14-L26 | def density(self, r, rho0, Ra, Rs):
"""
computes the density
:param x:
:param y:
:param rho0:
:param Ra:
:param Rs:
:return:
"""
Ra, Rs = self._sort_ra_rs(Ra, Rs)
rho = rho0 / ((1 + (r / Ra) ** 2) * (1 + (r / Rs) ** 2))
retu... | [
"def",
"density",
"(",
"self",
",",
"r",
",",
"rho0",
",",
"Ra",
",",
"Rs",
")",
":",
"Ra",
",",
"Rs",
"=",
"self",
".",
"_sort_ra_rs",
"(",
"Ra",
",",
"Rs",
")",
"rho",
"=",
"rho0",
"/",
"(",
"(",
"1",
"+",
"(",
"r",
"/",
"Ra",
")",
"**"... | computes the density
:param x:
:param y:
:param rho0:
:param Ra:
:param Rs:
:return: | [
"computes",
"the",
"density",
":",
"param",
"x",
":",
":",
"param",
"y",
":",
":",
"param",
"rho0",
":",
":",
"param",
"Ra",
":",
":",
"param",
"Rs",
":",
":",
"return",
":"
] | python | train |
dstufft/potpie | potpie/pseudo/__init__.py | https://github.com/dstufft/potpie/blob/1b12f25b77b8719418f88f49c45920c1eb8ee406/potpie/pseudo/__init__.py#L28-L50 | def _skip_char_around(self, string, char='\n'):
"""
Custom pseudo method for skipping a given char around a string.
The default char to be skipped is the new line (\n) one.
Example:
'\nHello\n' would call ``_base_compile`` with 'Hello' only.
"""
... | [
"def",
"_skip_char_around",
"(",
"self",
",",
"string",
",",
"char",
"=",
"'\\n'",
")",
":",
"starts",
",",
"ends",
"=",
"''",
",",
"''",
"n",
"=",
"len",
"(",
"char",
")",
"if",
"string",
".",
"startswith",
"(",
"char",
")",
":",
"starts",
"=",
... | Custom pseudo method for skipping a given char around a string.
The default char to be skipped is the new line (\n) one.
Example:
'\nHello\n' would call ``_base_compile`` with 'Hello' only. | [
"Custom",
"pseudo",
"method",
"for",
"skipping",
"a",
"given",
"char",
"around",
"a",
"string",
".",
"The",
"default",
"char",
"to",
"be",
"skipped",
"is",
"the",
"new",
"line",
"(",
"\\",
"n",
")",
"one",
".",
"Example",
":",
"\\",
"nHello",
"\\",
"... | python | train |
craffel/mir_eval | mir_eval/segment.py | https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/segment.py#L126-L173 | def validate_structure(reference_intervals, reference_labels,
estimated_intervals, estimated_labels):
"""Checks that the input annotations to a structure estimation metric (i.e.
one that takes in both segment boundaries and their labels) look like valid
segment times and labels, and t... | [
"def",
"validate_structure",
"(",
"reference_intervals",
",",
"reference_labels",
",",
"estimated_intervals",
",",
"estimated_labels",
")",
":",
"for",
"(",
"intervals",
",",
"labels",
")",
"in",
"[",
"(",
"reference_intervals",
",",
"reference_labels",
")",
",",
... | Checks that the input annotations to a structure estimation metric (i.e.
one that takes in both segment boundaries and their labels) look like valid
segment times and labels, and throws helpful errors if not.
Parameters
----------
reference_intervals : np.ndarray, shape=(n, 2)
reference seg... | [
"Checks",
"that",
"the",
"input",
"annotations",
"to",
"a",
"structure",
"estimation",
"metric",
"(",
"i",
".",
"e",
".",
"one",
"that",
"takes",
"in",
"both",
"segment",
"boundaries",
"and",
"their",
"labels",
")",
"look",
"like",
"valid",
"segment",
"tim... | python | train |
fermiPy/fermipy | fermipy/utils.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/utils.py#L190-L200 | def match_regex_list(patterns, string):
"""Perform a regex match of a string against a list of patterns.
Returns true if the string matches at least one pattern in the
list."""
for p in patterns:
if re.findall(p, string):
return True
return False | [
"def",
"match_regex_list",
"(",
"patterns",
",",
"string",
")",
":",
"for",
"p",
"in",
"patterns",
":",
"if",
"re",
".",
"findall",
"(",
"p",
",",
"string",
")",
":",
"return",
"True",
"return",
"False"
] | Perform a regex match of a string against a list of patterns.
Returns true if the string matches at least one pattern in the
list. | [
"Perform",
"a",
"regex",
"match",
"of",
"a",
"string",
"against",
"a",
"list",
"of",
"patterns",
".",
"Returns",
"true",
"if",
"the",
"string",
"matches",
"at",
"least",
"one",
"pattern",
"in",
"the",
"list",
"."
] | python | train |
SHTOOLS/SHTOOLS | pyshtools/shclasses/shwindow.py | https://github.com/SHTOOLS/SHTOOLS/blob/9a115cf83002df2ddec6b7f41aeb6be688e285de/pyshtools/shclasses/shwindow.py#L469-L525 | def multitaper_cross_spectrum(self, clm, slm, k, convention='power',
unit='per_l', **kwargs):
"""
Return the multitaper cross-spectrum estimate and standard error.
Usage
-----
mtse, sd = x.multitaper_cross_spectrum(clm, slm, k, [convention, unit... | [
"def",
"multitaper_cross_spectrum",
"(",
"self",
",",
"clm",
",",
"slm",
",",
"k",
",",
"convention",
"=",
"'power'",
",",
"unit",
"=",
"'per_l'",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_multitaper_cross_spectrum",
"(",
"clm",
",",
"s... | Return the multitaper cross-spectrum estimate and standard error.
Usage
-----
mtse, sd = x.multitaper_cross_spectrum(clm, slm, k, [convention, unit,
lmax, taper_wt,
clat, cl... | [
"Return",
"the",
"multitaper",
"cross",
"-",
"spectrum",
"estimate",
"and",
"standard",
"error",
"."
] | python | train |
log2timeline/dfvfs | dfvfs/vfs/tsk_file_entry.py | https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_entry.py#L119-L147 | def CopyToDateTimeString(self):
"""Copies the date time value to a date and time string.
Returns:
str: date and time value formatted as:
YYYY-MM-DD hh:mm:ss or
YYYY-MM-DD hh:mm:ss.####### or
YYYY-MM-DD hh:mm:ss.#########
"""
if self._timestamp is None:
return N... | [
"def",
"CopyToDateTimeString",
"(",
"self",
")",
":",
"if",
"self",
".",
"_timestamp",
"is",
"None",
":",
"return",
"None",
"number_of_days",
",",
"hours",
",",
"minutes",
",",
"seconds",
"=",
"self",
".",
"_GetTimeValues",
"(",
"self",
".",
"_timestamp",
... | Copies the date time value to a date and time string.
Returns:
str: date and time value formatted as:
YYYY-MM-DD hh:mm:ss or
YYYY-MM-DD hh:mm:ss.####### or
YYYY-MM-DD hh:mm:ss.######### | [
"Copies",
"the",
"date",
"time",
"value",
"to",
"a",
"date",
"and",
"time",
"string",
"."
] | python | train |
saltstack/salt | salt/modules/virt.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L767-L833 | def _zfs_image_create(vm_name,
pool,
disk_name,
hostname_property_name,
sparse_volume,
disk_size,
disk_image_name):
'''
Clones an existing image, or creates a new one.
When cl... | [
"def",
"_zfs_image_create",
"(",
"vm_name",
",",
"pool",
",",
"disk_name",
",",
"hostname_property_name",
",",
"sparse_volume",
",",
"disk_size",
",",
"disk_image_name",
")",
":",
"if",
"not",
"disk_image_name",
"and",
"not",
"disk_size",
":",
"raise",
"CommandExe... | Clones an existing image, or creates a new one.
When cloning an image, disk_image_name refers to the source
of the clone. If not specified, disk_size is used for creating
a new zvol, and sparse_volume determines whether to create
a thin provisioned volume.
The cloned or new volume can have a ZFS p... | [
"Clones",
"an",
"existing",
"image",
"or",
"creates",
"a",
"new",
"one",
"."
] | python | train |
nicolargo/glances | glances/amps/glances_nginx.py | https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/amps/glances_nginx.py#L76-L87 | def update(self, process_list):
"""Update the AMP"""
# Get the Nginx status
logger.debug('{}: Update stats using status URL {}'.format(self.NAME, self.get('status_url')))
res = requests.get(self.get('status_url'))
if res.ok:
# u'Active connections: 1 \nserver accepts ... | [
"def",
"update",
"(",
"self",
",",
"process_list",
")",
":",
"# Get the Nginx status",
"logger",
".",
"debug",
"(",
"'{}: Update stats using status URL {}'",
".",
"format",
"(",
"self",
".",
"NAME",
",",
"self",
".",
"get",
"(",
"'status_url'",
")",
")",
")",
... | Update the AMP | [
"Update",
"the",
"AMP"
] | python | train |
juju/charm-helpers | charmhelpers/contrib/hahelpers/cluster.py | https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L311-L351 | def valid_hacluster_config():
'''
Check that either vip or dns-ha is set. If dns-ha then one of os-*-hostname
must be set.
Note: ha-bindiface and ha-macastport both have defaults and will always
be set. We only care that either vip or dns-ha is set.
:returns: boolean: valid config returns true... | [
"def",
"valid_hacluster_config",
"(",
")",
":",
"vip",
"=",
"config_get",
"(",
"'vip'",
")",
"dns",
"=",
"config_get",
"(",
"'dns-ha'",
")",
"if",
"not",
"(",
"bool",
"(",
"vip",
")",
"^",
"bool",
"(",
"dns",
")",
")",
":",
"msg",
"=",
"(",
"'HA: E... | Check that either vip or dns-ha is set. If dns-ha then one of os-*-hostname
must be set.
Note: ha-bindiface and ha-macastport both have defaults and will always
be set. We only care that either vip or dns-ha is set.
:returns: boolean: valid config returns true.
raises: HAIncompatibileConfig if set... | [
"Check",
"that",
"either",
"vip",
"or",
"dns",
"-",
"ha",
"is",
"set",
".",
"If",
"dns",
"-",
"ha",
"then",
"one",
"of",
"os",
"-",
"*",
"-",
"hostname",
"must",
"be",
"set",
"."
] | python | train |
inonit/drf-haystack | drf_haystack/mixins.py | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/mixins.py#L47-L64 | def facets(self, request):
"""
Sets up a list route for ``faceted`` results.
This will add ie ^search/facets/$ to your existing ^search pattern.
"""
queryset = self.filter_facet_queryset(self.get_queryset())
for facet in request.query_params.getlist(self.facet_query_para... | [
"def",
"facets",
"(",
"self",
",",
"request",
")",
":",
"queryset",
"=",
"self",
".",
"filter_facet_queryset",
"(",
"self",
".",
"get_queryset",
"(",
")",
")",
"for",
"facet",
"in",
"request",
".",
"query_params",
".",
"getlist",
"(",
"self",
".",
"facet... | Sets up a list route for ``faceted`` results.
This will add ie ^search/facets/$ to your existing ^search pattern. | [
"Sets",
"up",
"a",
"list",
"route",
"for",
"faceted",
"results",
".",
"This",
"will",
"add",
"ie",
"^search",
"/",
"facets",
"/",
"$",
"to",
"your",
"existing",
"^search",
"pattern",
"."
] | python | train |
spyder-ide/spyder | spyder/preferences/languageserver.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/languageserver.py#L573-L579 | def next_row(self):
"""Move to next row from currently selected row."""
row = self.currentIndex().row()
rows = self.source_model.rowCount()
if row + 1 == rows:
row = -1
self.selectRow(row + 1) | [
"def",
"next_row",
"(",
"self",
")",
":",
"row",
"=",
"self",
".",
"currentIndex",
"(",
")",
".",
"row",
"(",
")",
"rows",
"=",
"self",
".",
"source_model",
".",
"rowCount",
"(",
")",
"if",
"row",
"+",
"1",
"==",
"rows",
":",
"row",
"=",
"-",
"... | Move to next row from currently selected row. | [
"Move",
"to",
"next",
"row",
"from",
"currently",
"selected",
"row",
"."
] | python | train |
apache/airflow | airflow/utils/cli_action_loggers.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/cli_action_loggers.py#L57-L69 | def on_pre_execution(**kwargs):
"""
Calls callbacks before execution.
Note that any exception from callback will be logged but won't be propagated.
:param kwargs:
:return: None
"""
logging.debug("Calling callbacks: %s", __pre_exec_callbacks)
for cb in __pre_exec_callbacks:
try:
... | [
"def",
"on_pre_execution",
"(",
"*",
"*",
"kwargs",
")",
":",
"logging",
".",
"debug",
"(",
"\"Calling callbacks: %s\"",
",",
"__pre_exec_callbacks",
")",
"for",
"cb",
"in",
"__pre_exec_callbacks",
":",
"try",
":",
"cb",
"(",
"*",
"*",
"kwargs",
")",
"except... | Calls callbacks before execution.
Note that any exception from callback will be logged but won't be propagated.
:param kwargs:
:return: None | [
"Calls",
"callbacks",
"before",
"execution",
".",
"Note",
"that",
"any",
"exception",
"from",
"callback",
"will",
"be",
"logged",
"but",
"won",
"t",
"be",
"propagated",
".",
":",
"param",
"kwargs",
":",
":",
"return",
":",
"None"
] | python | test |
sibirrer/lenstronomy | lenstronomy/LensModel/numeric_lens_differentials.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/LensModel/numeric_lens_differentials.py#L32-L39 | def magnification(self, x, y, kwargs, diff=diff):
"""
computes the magnification
:return: potential
"""
f_xx, f_xy, f_yx, f_yy = self.hessian(x, y, kwargs, diff=diff)
det_A = (1 - f_xx) * (1 - f_yy) - f_xy*f_yx
return 1/det_A | [
"def",
"magnification",
"(",
"self",
",",
"x",
",",
"y",
",",
"kwargs",
",",
"diff",
"=",
"diff",
")",
":",
"f_xx",
",",
"f_xy",
",",
"f_yx",
",",
"f_yy",
"=",
"self",
".",
"hessian",
"(",
"x",
",",
"y",
",",
"kwargs",
",",
"diff",
"=",
"diff",... | computes the magnification
:return: potential | [
"computes",
"the",
"magnification",
":",
"return",
":",
"potential"
] | python | train |
Netflix-Skunkworks/cloudaux | cloudaux/aws/elbv2.py | https://github.com/Netflix-Skunkworks/cloudaux/blob/c4b0870c3ac68b1c69e71d33cf78b6a8bdf437ea/cloudaux/aws/elbv2.py#L104-L111 | def describe_target_health(target_group_arn, targets=None, client=None):
"""
Permission: elasticloadbalancing:DescribeTargetHealth
"""
kwargs = dict(TargetGroupArn=target_group_arn)
if targets:
kwargs.update(Targets=targets)
return client.describe_target_health(**kwargs)['TargetHealthDes... | [
"def",
"describe_target_health",
"(",
"target_group_arn",
",",
"targets",
"=",
"None",
",",
"client",
"=",
"None",
")",
":",
"kwargs",
"=",
"dict",
"(",
"TargetGroupArn",
"=",
"target_group_arn",
")",
"if",
"targets",
":",
"kwargs",
".",
"update",
"(",
"Targ... | Permission: elasticloadbalancing:DescribeTargetHealth | [
"Permission",
":",
"elasticloadbalancing",
":",
"DescribeTargetHealth"
] | python | valid |
BlueBrain/hpcbench | hpcbench/benchmark/standard.py | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/standard.py#L286-L293 | def metrics(self):
"""
:return: Description of metrics extracted by this class
"""
return dict(
(name, getattr(Metrics, config['type']))
for name, config in six.iteritems(self._metrics)
) | [
"def",
"metrics",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"name",
",",
"getattr",
"(",
"Metrics",
",",
"config",
"[",
"'type'",
"]",
")",
")",
"for",
"name",
",",
"config",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_metrics",
")"... | :return: Description of metrics extracted by this class | [
":",
"return",
":",
"Description",
"of",
"metrics",
"extracted",
"by",
"this",
"class"
] | python | train |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/policy/policy_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/policy/policy_client.py#L239-L255 | def get_policy_type(self, project, type_id):
"""GetPolicyType.
Retrieve a specific policy type by ID.
:param str project: Project ID or project name
:param str type_id: The policy ID.
:rtype: :class:`<PolicyType> <azure.devops.v5_0.policy.models.PolicyType>`
"""
r... | [
"def",
"get_policy_type",
"(",
"self",
",",
"project",
",",
"type_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'project'"... | GetPolicyType.
Retrieve a specific policy type by ID.
:param str project: Project ID or project name
:param str type_id: The policy ID.
:rtype: :class:`<PolicyType> <azure.devops.v5_0.policy.models.PolicyType>` | [
"GetPolicyType",
".",
"Retrieve",
"a",
"specific",
"policy",
"type",
"by",
"ID",
".",
":",
"param",
"str",
"project",
":",
"Project",
"ID",
"or",
"project",
"name",
":",
"param",
"str",
"type_id",
":",
"The",
"policy",
"ID",
".",
":",
"rtype",
":",
":"... | python | train |
ssut/py-googletrans | googletrans/client.py | https://github.com/ssut/py-googletrans/blob/4aebfb18faa45a7d7817fbd4b8fe8ff502bf9e81/googletrans/client.py#L211-L262 | def detect(self, text):
"""Detect language of the input text
:param text: The source text(s) whose language you want to identify.
Batch detection is supported via sequence input.
:type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, gener... | [
"def",
"detect",
"(",
"self",
",",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"list",
")",
":",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"text",
":",
"lang",
"=",
"self",
".",
"detect",
"(",
"item",
")",
"result",
".",
"append",... | Detect language of the input text
:param text: The source text(s) whose language you want to identify.
Batch detection is supported via sequence input.
:type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, generator)
:rtype: Detected
... | [
"Detect",
"language",
"of",
"the",
"input",
"text"
] | python | train |
apache/airflow | airflow/models/variable.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/variable.py#L76-L99 | def setdefault(cls, key, default, deserialize_json=False):
"""
Like a Python builtin dict object, setdefault returns the current value
for a key, and if it isn't there, stores the default value and returns it.
:param key: Dict key for this Variable
:type key: str
:param ... | [
"def",
"setdefault",
"(",
"cls",
",",
"key",
",",
"default",
",",
"deserialize_json",
"=",
"False",
")",
":",
"obj",
"=",
"Variable",
".",
"get",
"(",
"key",
",",
"default_var",
"=",
"None",
",",
"deserialize_json",
"=",
"deserialize_json",
")",
"if",
"o... | Like a Python builtin dict object, setdefault returns the current value
for a key, and if it isn't there, stores the default value and returns it.
:param key: Dict key for this Variable
:type key: str
:param default: Default value to set and return if the variable
isn't alre... | [
"Like",
"a",
"Python",
"builtin",
"dict",
"object",
"setdefault",
"returns",
"the",
"current",
"value",
"for",
"a",
"key",
"and",
"if",
"it",
"isn",
"t",
"there",
"stores",
"the",
"default",
"value",
"and",
"returns",
"it",
"."
] | python | test |
saltstack/salt | salt/modules/kubernetesmod.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/kubernetesmod.py#L1279-L1327 | def replace_service(name,
metadata,
spec,
source,
template,
old_service,
saltenv,
namespace='default',
**kwargs):
'''
Replaces an existing service with ... | [
"def",
"replace_service",
"(",
"name",
",",
"metadata",
",",
"spec",
",",
"source",
",",
"template",
",",
"old_service",
",",
"saltenv",
",",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"body",
"=",
"__create_object_body",
"(",
"kind"... | Replaces an existing service with a new one defined by name and namespace,
having the specificed metadata and spec. | [
"Replaces",
"an",
"existing",
"service",
"with",
"a",
"new",
"one",
"defined",
"by",
"name",
"and",
"namespace",
"having",
"the",
"specificed",
"metadata",
"and",
"spec",
"."
] | python | train |
googledatalab/pydatalab | datalab/bigquery/commands/_bigquery.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/commands/_bigquery.py#L646-L660 | def _datasets_line(args):
"""Implements the BigQuery datasets magic used to display datasets in a project.
The supported syntax is:
%bigquery datasets [-f <filter>] [-p|--project <project_id>]
Args:
args: the arguments following '%bigquery datasets'.
Returns:
The HTML rendering for the table ... | [
"def",
"_datasets_line",
"(",
"args",
")",
":",
"filter_",
"=",
"args",
"[",
"'filter'",
"]",
"if",
"args",
"[",
"'filter'",
"]",
"else",
"'*'",
"return",
"_render_list",
"(",
"[",
"str",
"(",
"dataset",
")",
"for",
"dataset",
"in",
"datalab",
".",
"bi... | Implements the BigQuery datasets magic used to display datasets in a project.
The supported syntax is:
%bigquery datasets [-f <filter>] [-p|--project <project_id>]
Args:
args: the arguments following '%bigquery datasets'.
Returns:
The HTML rendering for the table of datasets. | [
"Implements",
"the",
"BigQuery",
"datasets",
"magic",
"used",
"to",
"display",
"datasets",
"in",
"a",
"project",
"."
] | python | train |
kristianfoerster/melodist | melodist/stationstatistics.py | https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L111-L116 | def calc_temperature_stats(self):
"""
Calculates statistics in order to derive diurnal patterns of temperature
"""
self.temp.max_delta = melodist.get_shift_by_data(self.data.temp, self._lon, self._lat, self._timezone)
self.temp.mean_course = melodist.util.calculate_mean_daily_cou... | [
"def",
"calc_temperature_stats",
"(",
"self",
")",
":",
"self",
".",
"temp",
".",
"max_delta",
"=",
"melodist",
".",
"get_shift_by_data",
"(",
"self",
".",
"data",
".",
"temp",
",",
"self",
".",
"_lon",
",",
"self",
".",
"_lat",
",",
"self",
".",
"_tim... | Calculates statistics in order to derive diurnal patterns of temperature | [
"Calculates",
"statistics",
"in",
"order",
"to",
"derive",
"diurnal",
"patterns",
"of",
"temperature"
] | python | train |
robhowley/nhlscrapi | nhlscrapi/scrapr/reportloader.py | https://github.com/robhowley/nhlscrapi/blob/2273683497ff27b0e92c8d1557ff0ce962dbf43b/nhlscrapi/scrapr/reportloader.py#L74-L86 | def parse_matchup(self):
"""
Parse the banner matchup meta info for the game.
:returns: ``self`` on success or ``None``
"""
lx_doc = self.html_doc()
try:
if not self.matchup:
self.matchup = self._fill_meta(lx_doc)
return se... | [
"def",
"parse_matchup",
"(",
"self",
")",
":",
"lx_doc",
"=",
"self",
".",
"html_doc",
"(",
")",
"try",
":",
"if",
"not",
"self",
".",
"matchup",
":",
"self",
".",
"matchup",
"=",
"self",
".",
"_fill_meta",
"(",
"lx_doc",
")",
"return",
"self",
"exce... | Parse the banner matchup meta info for the game.
:returns: ``self`` on success or ``None`` | [
"Parse",
"the",
"banner",
"matchup",
"meta",
"info",
"for",
"the",
"game",
".",
":",
"returns",
":",
"self",
"on",
"success",
"or",
"None"
] | python | train |
blink1073/oct2py | oct2py/thread_check.py | https://github.com/blink1073/oct2py/blob/bfc69d2168ae3d98258f95bbc55a858c21836b58/oct2py/thread_check.py#L39-L64 | def thread_check(nthreads=3):
"""
Start a number of threads and verify each has a unique Octave session.
Parameters
==========
nthreads : int
Number of threads to use.
Raises
======
Oct2PyError
If the thread does not sucessfully demonstrate independence.
... | [
"def",
"thread_check",
"(",
"nthreads",
"=",
"3",
")",
":",
"print",
"(",
"\"Starting {0} threads at {1}\"",
".",
"format",
"(",
"nthreads",
",",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
")",
"threads",
"=",
"[",
"]",
"for",
"i",
"in",
"... | Start a number of threads and verify each has a unique Octave session.
Parameters
==========
nthreads : int
Number of threads to use.
Raises
======
Oct2PyError
If the thread does not sucessfully demonstrate independence. | [
"Start",
"a",
"number",
"of",
"threads",
"and",
"verify",
"each",
"has",
"a",
"unique",
"Octave",
"session",
".",
"Parameters",
"==========",
"nthreads",
":",
"int",
"Number",
"of",
"threads",
"to",
"use",
".",
"Raises",
"======",
"Oct2PyError",
"If",
"the",... | python | valid |
Hackerfleet/hfos | hfos/database.py | https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/database.py#L102-L118 | def clear_all():
"""DANGER!
*This command is a maintenance tool and clears the complete database.*
"""
sure = input("Are you sure to drop the complete database content? (Type "
"in upppercase YES)")
if not (sure == 'YES'):
db_log('Not deleting the database.')
sys.ex... | [
"def",
"clear_all",
"(",
")",
":",
"sure",
"=",
"input",
"(",
"\"Are you sure to drop the complete database content? (Type \"",
"\"in upppercase YES)\"",
")",
"if",
"not",
"(",
"sure",
"==",
"'YES'",
")",
":",
"db_log",
"(",
"'Not deleting the database.'",
")",
"sys",... | DANGER!
*This command is a maintenance tool and clears the complete database.* | [
"DANGER!",
"*",
"This",
"command",
"is",
"a",
"maintenance",
"tool",
"and",
"clears",
"the",
"complete",
"database",
".",
"*"
] | python | train |
WoLpH/python-statsd | statsd/timer.py | https://github.com/WoLpH/python-statsd/blob/a757da04375c48d03d322246405b33382d37f03f/statsd/timer.py#L79-L89 | def stop(self, subname='total'):
'''Stop the timer and send the total since `start()` was run
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str
'''
assert self._stop is None, (
'Unable to stop, the timer ... | [
"def",
"stop",
"(",
"self",
",",
"subname",
"=",
"'total'",
")",
":",
"assert",
"self",
".",
"_stop",
"is",
"None",
",",
"(",
"'Unable to stop, the timer is already stopped'",
")",
"self",
".",
"_stop",
"=",
"time",
".",
"time",
"(",
")",
"return",
"self",... | Stop the timer and send the total since `start()` was run
:keyword subname: The subname to report the data to (appended to the
client name)
:type subname: str | [
"Stop",
"the",
"timer",
"and",
"send",
"the",
"total",
"since",
"start",
"()",
"was",
"run"
] | python | train |
shoebot/shoebot | lib/database/__init__.py | https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/database/__init__.py#L363-L372 | def remove(self, id, operator="=", key=None):
""" Deletes the row with given id.
"""
if key == None: key = self._key
try: id = unicode(id)
except: pass
sql = "delete from "+self._name+" where "+key+" "+operator+" ?"
self._db._cur.execute(sql, (id,)) | [
"def",
"remove",
"(",
"self",
",",
"id",
",",
"operator",
"=",
"\"=\"",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"==",
"None",
":",
"key",
"=",
"self",
".",
"_key",
"try",
":",
"id",
"=",
"unicode",
"(",
"id",
")",
"except",
":",
"pass",... | Deletes the row with given id. | [
"Deletes",
"the",
"row",
"with",
"given",
"id",
"."
] | python | valid |
brian-rose/climlab | climlab/dynamics/diffusion.py | https://github.com/brian-rose/climlab/blob/eae188a2ae9308229b8cbb8fe0b65f51b50ee1e6/climlab/dynamics/diffusion.py#L360-L381 | def _solve_implicit_banded(current, banded_matrix):
"""Uses a banded solver for matrix inversion of a tridiagonal matrix.
Converts the complete listed tridiagonal matrix *(nxn)* into a three row
matrix *(3xn)* and calls :py:func:`scipy.linalg.solve_banded()`.
:param array current: the curren... | [
"def",
"_solve_implicit_banded",
"(",
"current",
",",
"banded_matrix",
")",
":",
"# can improve performance by storing the banded form once and not",
"# recalculating it...",
"# but whatever",
"J",
"=",
"banded_matrix",
".",
"shape",
"[",
"0",
"]",
"diag",
"=",
"np",
"... | Uses a banded solver for matrix inversion of a tridiagonal matrix.
Converts the complete listed tridiagonal matrix *(nxn)* into a three row
matrix *(3xn)* and calls :py:func:`scipy.linalg.solve_banded()`.
:param array current: the current state of the variable for which
... | [
"Uses",
"a",
"banded",
"solver",
"for",
"matrix",
"inversion",
"of",
"a",
"tridiagonal",
"matrix",
"."
] | python | train |
emory-libraries/eulfedora | eulfedora/api.py | https://github.com/emory-libraries/eulfedora/blob/161826f3fdcdab4007f6fa7dfd9f1ecabc4bcbe4/eulfedora/api.py#L1045-L1054 | def get_predicates(self, subject, object):
"""
Search for all subjects related to the specified subject and object.
:param subject:
:param object:
:rtype: generator of RDF statements
"""
for statement in self.spo_search(subject=subject, object=object):
... | [
"def",
"get_predicates",
"(",
"self",
",",
"subject",
",",
"object",
")",
":",
"for",
"statement",
"in",
"self",
".",
"spo_search",
"(",
"subject",
"=",
"subject",
",",
"object",
"=",
"object",
")",
":",
"yield",
"str",
"(",
"statement",
"[",
"1",
"]",... | Search for all subjects related to the specified subject and object.
:param subject:
:param object:
:rtype: generator of RDF statements | [
"Search",
"for",
"all",
"subjects",
"related",
"to",
"the",
"specified",
"subject",
"and",
"object",
"."
] | python | train |
jjgomera/iapws | iapws/iapws97.py | https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L2198-L2217 | def _Backward3_v_Ph(P, h):
"""Backward equation for region 3, v=f(P,h)
Parameters
----------
P : float
Pressure, [MPa]
h : float
Specific enthalpy, [kJ/kg]
Returns
-------
v : float
Specific volume, [m³/kg]
"""
hf = _h_3ab(P)
if h <= hf:
retu... | [
"def",
"_Backward3_v_Ph",
"(",
"P",
",",
"h",
")",
":",
"hf",
"=",
"_h_3ab",
"(",
"P",
")",
"if",
"h",
"<=",
"hf",
":",
"return",
"_Backward3a_v_Ph",
"(",
"P",
",",
"h",
")",
"else",
":",
"return",
"_Backward3b_v_Ph",
"(",
"P",
",",
"h",
")"
] | Backward equation for region 3, v=f(P,h)
Parameters
----------
P : float
Pressure, [MPa]
h : float
Specific enthalpy, [kJ/kg]
Returns
-------
v : float
Specific volume, [m³/kg] | [
"Backward",
"equation",
"for",
"region",
"3",
"v",
"=",
"f",
"(",
"P",
"h",
")"
] | python | train |
theislab/anndata | anndata/base.py | https://github.com/theislab/anndata/blob/34f4eb63710628fbc15e7050e5efcac1d7806062/anndata/base.py#L2014-L2030 | def write_csvs(self, dirname: PathLike, skip_data: bool = True, sep: str = ','):
"""Write annotation to ``.csv`` files.
It is not possible to recover the full :class:`~anndata.AnnData` from the
output of this function. Use :meth:`~anndata.AnnData.write` for this.
Parameters
---... | [
"def",
"write_csvs",
"(",
"self",
",",
"dirname",
":",
"PathLike",
",",
"skip_data",
":",
"bool",
"=",
"True",
",",
"sep",
":",
"str",
"=",
"','",
")",
":",
"from",
".",
"readwrite",
".",
"write",
"import",
"write_csvs",
"write_csvs",
"(",
"dirname",
"... | Write annotation to ``.csv`` files.
It is not possible to recover the full :class:`~anndata.AnnData` from the
output of this function. Use :meth:`~anndata.AnnData.write` for this.
Parameters
----------
dirname
Name of directory to which to export.
skip_data
... | [
"Write",
"annotation",
"to",
".",
"csv",
"files",
"."
] | python | train |
Gandi/gandi.cli | gandi/cli/modules/datacenter.py | https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/modules/datacenter.py#L100-L108 | def from_dc_code(cls, dc_code):
"""Retrieve the datacenter id associated to a dc_code"""
result = cls.list()
dc_codes = {}
for dc in result:
if dc.get('dc_code'):
dc_codes[dc['dc_code']] = dc['id']
return dc_codes.get(dc_code) | [
"def",
"from_dc_code",
"(",
"cls",
",",
"dc_code",
")",
":",
"result",
"=",
"cls",
".",
"list",
"(",
")",
"dc_codes",
"=",
"{",
"}",
"for",
"dc",
"in",
"result",
":",
"if",
"dc",
".",
"get",
"(",
"'dc_code'",
")",
":",
"dc_codes",
"[",
"dc",
"[",... | Retrieve the datacenter id associated to a dc_code | [
"Retrieve",
"the",
"datacenter",
"id",
"associated",
"to",
"a",
"dc_code"
] | python | train |
wadda/gps3 | gps3/gps3.py | https://github.com/wadda/gps3/blob/91adcd7073b891b135b2a46d039ce2125cf09a09/gps3/gps3.py#L107-L124 | def next(self, timeout=0):
"""Return empty unless new data is ready for the client.
Arguments:
timeout: Default timeout=0 range zero to float specifies a time-out as a floating point
number in seconds. Will sit and wait for timeout seconds. When the timeout argument is omitted
... | [
"def",
"next",
"(",
"self",
",",
"timeout",
"=",
"0",
")",
":",
"try",
":",
"waitin",
",",
"_waitout",
",",
"_waiterror",
"=",
"select",
".",
"select",
"(",
"(",
"self",
".",
"streamSock",
",",
")",
",",
"(",
")",
",",
"(",
")",
",",
"timeout",
... | Return empty unless new data is ready for the client.
Arguments:
timeout: Default timeout=0 range zero to float specifies a time-out as a floating point
number in seconds. Will sit and wait for timeout seconds. When the timeout argument is omitted
the function blocks until at leas... | [
"Return",
"empty",
"unless",
"new",
"data",
"is",
"ready",
"for",
"the",
"client",
".",
"Arguments",
":",
"timeout",
":",
"Default",
"timeout",
"=",
"0",
"range",
"zero",
"to",
"float",
"specifies",
"a",
"time",
"-",
"out",
"as",
"a",
"floating",
"point"... | python | train |
dhain/potpy | potpy/wsgi.py | https://github.com/dhain/potpy/blob/e39a5a84f763fbf144b07a620afb02a5ff3741c9/potpy/wsgi.py#L136-L152 | def match(self, methods, request_method):
"""Check for a method match.
:param methods: A method or tuple of methods to match against.
:param request_method: The method to check for a match.
:returns: An empty :class:`dict` in the case of a match, or ``None``
if there is no m... | [
"def",
"match",
"(",
"self",
",",
"methods",
",",
"request_method",
")",
":",
"if",
"isinstance",
"(",
"methods",
",",
"basestring",
")",
":",
"return",
"{",
"}",
"if",
"request_method",
"==",
"methods",
"else",
"None",
"return",
"{",
"}",
"if",
"request... | Check for a method match.
:param methods: A method or tuple of methods to match against.
:param request_method: The method to check for a match.
:returns: An empty :class:`dict` in the case of a match, or ``None``
if there is no matching handler for the given method.
Exampl... | [
"Check",
"for",
"a",
"method",
"match",
"."
] | python | train |
IdentityPython/pyop | src/pyop/storage.py | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/storage.py#L173-L215 | def _format_mongodb_uri(parsed_uri):
"""
Painstakingly reconstruct a MongoDB URI parsed using pymongo.uri_parser.parse_uri.
:param parsed_uri: Result of pymongo.uri_parser.parse_uri
:type parsed_uri: dict
:return: New URI
:rtype: str | unicode
"""
user_pass = ''
if parsed_uri.get('... | [
"def",
"_format_mongodb_uri",
"(",
"parsed_uri",
")",
":",
"user_pass",
"=",
"''",
"if",
"parsed_uri",
".",
"get",
"(",
"'username'",
")",
"and",
"parsed_uri",
".",
"get",
"(",
"'password'",
")",
":",
"user_pass",
"=",
"'{username!s}:{password!s}@'",
".",
"for... | Painstakingly reconstruct a MongoDB URI parsed using pymongo.uri_parser.parse_uri.
:param parsed_uri: Result of pymongo.uri_parser.parse_uri
:type parsed_uri: dict
:return: New URI
:rtype: str | unicode | [
"Painstakingly",
"reconstruct",
"a",
"MongoDB",
"URI",
"parsed",
"using",
"pymongo",
".",
"uri_parser",
".",
"parse_uri",
"."
] | python | train |
PredixDev/predixpy | predix/security/uaa.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L413-L476 | def update_client_grants(self, client_id, scope=[], authorities=[],
grant_types=[], redirect_uri=[], replace=False):
"""
Will extend the client with additional scopes or
authorities. Any existing scopes and authorities will be left
as is unless asked to replace entirely.
... | [
"def",
"update_client_grants",
"(",
"self",
",",
"client_id",
",",
"scope",
"=",
"[",
"]",
",",
"authorities",
"=",
"[",
"]",
",",
"grant_types",
"=",
"[",
"]",
",",
"redirect_uri",
"=",
"[",
"]",
",",
"replace",
"=",
"False",
")",
":",
"self",
".",
... | Will extend the client with additional scopes or
authorities. Any existing scopes and authorities will be left
as is unless asked to replace entirely. | [
"Will",
"extend",
"the",
"client",
"with",
"additional",
"scopes",
"or",
"authorities",
".",
"Any",
"existing",
"scopes",
"and",
"authorities",
"will",
"be",
"left",
"as",
"is",
"unless",
"asked",
"to",
"replace",
"entirely",
"."
] | python | train |
nchopin/particles | particles/smc_samplers.py | https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/smc_samplers.py#L134-L155 | def all_distinct(l, idx):
"""
Returns the list [l[i] for i in idx]
When needed, objects l[i] are replaced by a copy, to make sure that
the elements of the list are all distinct
Parameters
---------
l: iterable
idx: iterable that generates ints (e.g. ndarray of ints)
Returns
--... | [
"def",
"all_distinct",
"(",
"l",
",",
"idx",
")",
":",
"out",
"=",
"[",
"]",
"deja_vu",
"=",
"[",
"False",
"for",
"_",
"in",
"l",
"]",
"for",
"i",
"in",
"idx",
":",
"to_add",
"=",
"cp",
".",
"deepcopy",
"(",
"l",
"[",
"i",
"]",
")",
"if",
"... | Returns the list [l[i] for i in idx]
When needed, objects l[i] are replaced by a copy, to make sure that
the elements of the list are all distinct
Parameters
---------
l: iterable
idx: iterable that generates ints (e.g. ndarray of ints)
Returns
-------
a list | [
"Returns",
"the",
"list",
"[",
"l",
"[",
"i",
"]",
"for",
"i",
"in",
"idx",
"]",
"When",
"needed",
"objects",
"l",
"[",
"i",
"]",
"are",
"replaced",
"by",
"a",
"copy",
"to",
"make",
"sure",
"that",
"the",
"elements",
"of",
"the",
"list",
"are",
"... | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/overlay/access_list/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/overlay/access_list/__init__.py#L92-L113 | def _set_type(self, v, load=False):
"""
Setter method for type, mapped from YANG variable /overlay/access_list/type (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_type is considered as a private
method. Backends looking to populate this variable should
... | [
"def",
"_set_type",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | Setter method for type, mapped from YANG variable /overlay/access_list/type (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_type is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_type() directl... | [
"Setter",
"method",
"for",
"type",
"mapped",
"from",
"YANG",
"variable",
"/",
"overlay",
"/",
"access_list",
"/",
"type",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",... | python | train |
yunojuno-archive/django-package-monitor | package_monitor/admin.py | https://github.com/yunojuno-archive/django-package-monitor/blob/534aa35ccfe187d2c55aeca0cb52b8278254e437/package_monitor/admin.py#L48-L72 | def queryset(self, request, queryset):
"""Filter based on whether an update (of any sort) is available."""
if self.value() == '-1':
return queryset.filter(latest_version__isnull=True)
elif self.value() == '0':
return (
queryset
.filter(
... | [
"def",
"queryset",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"if",
"self",
".",
"value",
"(",
")",
"==",
"'-1'",
":",
"return",
"queryset",
".",
"filter",
"(",
"latest_version__isnull",
"=",
"True",
")",
"elif",
"self",
".",
"value",
"(",... | Filter based on whether an update (of any sort) is available. | [
"Filter",
"based",
"on",
"whether",
"an",
"update",
"(",
"of",
"any",
"sort",
")",
"is",
"available",
"."
] | python | train |
libyal/dtfabric | dtfabric/runtime/data_maps.py | https://github.com/libyal/dtfabric/blob/0d2b5719fa257f6e5c661a406737ebcf8c8db266/dtfabric/runtime/data_maps.py#L186-L197 | def GetStructByteOrderString(self):
"""Retrieves the Python struct format string.
Returns:
str: format string as used by Python struct or None if format string
cannot be determined.
"""
if not self._data_type_definition:
return None
return self._BYTE_ORDER_STRINGS.get(
... | [
"def",
"GetStructByteOrderString",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_data_type_definition",
":",
"return",
"None",
"return",
"self",
".",
"_BYTE_ORDER_STRINGS",
".",
"get",
"(",
"self",
".",
"_data_type_definition",
".",
"byte_order",
",",
"None... | Retrieves the Python struct format string.
Returns:
str: format string as used by Python struct or None if format string
cannot be determined. | [
"Retrieves",
"the",
"Python",
"struct",
"format",
"string",
"."
] | python | train |
pingali/dgit | dgitcore/contrib/representations/tableformat.py | https://github.com/pingali/dgit/blob/ecde01f40b98f0719dbcfb54452270ed2f86686d/dgitcore/contrib/representations/tableformat.py#L58-L86 | def get_schema(self, filename):
"""
Guess schema using messytables
"""
table_set = self.read_file(filename)
# Have I been able to read the filename
if table_set is None:
return []
# Get the first table as rowset
row_set = table_... | [
"def",
"get_schema",
"(",
"self",
",",
"filename",
")",
":",
"table_set",
"=",
"self",
".",
"read_file",
"(",
"filename",
")",
"# Have I been able to read the filename",
"if",
"table_set",
"is",
"None",
":",
"return",
"[",
"]",
"# Get the first table as rowset",
"... | Guess schema using messytables | [
"Guess",
"schema",
"using",
"messytables"
] | python | valid |
RJT1990/pyflux | pyflux/gas/gasllt.py | https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/gas/gasllt.py#L450-L498 | def _sim_prediction_bayes(self, h, simulations):
""" Simulates a h-step ahead mean prediction
Parameters
----------
h : int
How many steps ahead for the prediction
simulations : int
How many simulations to perform
Returns
----------
... | [
"def",
"_sim_prediction_bayes",
"(",
"self",
",",
"h",
",",
"simulations",
")",
":",
"sim_vector",
"=",
"np",
".",
"zeros",
"(",
"[",
"simulations",
",",
"h",
"]",
")",
"for",
"n",
"in",
"range",
"(",
"0",
",",
"simulations",
")",
":",
"t_z",
"=",
... | Simulates a h-step ahead mean prediction
Parameters
----------
h : int
How many steps ahead for the prediction
simulations : int
How many simulations to perform
Returns
----------
Matrix of simulations | [
"Simulates",
"a",
"h",
"-",
"step",
"ahead",
"mean",
"prediction"
] | python | train |
dslackw/slpkg | slpkg/downloader.py | https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/downloader.py#L91-L97 | def _directory_prefix(self):
"""Downloader options for specific directory
"""
if self.downder == "wget":
self.dir_prefix = "--directory-prefix="
elif self.downder == "aria2c":
self.dir_prefix = "--dir=" | [
"def",
"_directory_prefix",
"(",
"self",
")",
":",
"if",
"self",
".",
"downder",
"==",
"\"wget\"",
":",
"self",
".",
"dir_prefix",
"=",
"\"--directory-prefix=\"",
"elif",
"self",
".",
"downder",
"==",
"\"aria2c\"",
":",
"self",
".",
"dir_prefix",
"=",
"\"--d... | Downloader options for specific directory | [
"Downloader",
"options",
"for",
"specific",
"directory"
] | python | train |
liminspace/dju-common | dju_common/tcache.py | https://github.com/liminspace/dju-common/blob/c68860bb84d454a35e66275841c20f38375c2135/dju_common/tcache.py#L35-L65 | def cache_invalidate_by_tags(tags, cache=None):
"""
Clear cache by tags.
"""
if isinstance(tags, basestring):
tags = [tags]
tag_keys = [CACHE_TAG_KEY % tag for tag in tags if tag]
if not tag_keys:
raise ValueError('Attr tags invalid')
if cache is None:
cache = default... | [
"def",
"cache_invalidate_by_tags",
"(",
"tags",
",",
"cache",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"tags",
",",
"basestring",
")",
":",
"tags",
"=",
"[",
"tags",
"]",
"tag_keys",
"=",
"[",
"CACHE_TAG_KEY",
"%",
"tag",
"for",
"tag",
"in",
"ta... | Clear cache by tags. | [
"Clear",
"cache",
"by",
"tags",
"."
] | python | train |
fifman/sockspy | sockspy/cli.py | https://github.com/fifman/sockspy/blob/9a925d5ce3ef63e1d8d2d56bf7cea0e5298d8c5b/sockspy/cli.py#L21-L44 | def main(host, port, timeout, itimeout, qsize, backlog, maxtry, bsize, verbose, logfile=None, logcfgfile=None, cfgfile=None):
"""Simple python implementation of a socks5 proxy server. """
dict_cfg = {}
if cfgfile:
dict_cfg = app_config.get_config_by_file(cfgfile)
def get_param(key, param, defa... | [
"def",
"main",
"(",
"host",
",",
"port",
",",
"timeout",
",",
"itimeout",
",",
"qsize",
",",
"backlog",
",",
"maxtry",
",",
"bsize",
",",
"verbose",
",",
"logfile",
"=",
"None",
",",
"logcfgfile",
"=",
"None",
",",
"cfgfile",
"=",
"None",
")",
":",
... | Simple python implementation of a socks5 proxy server. | [
"Simple",
"python",
"implementation",
"of",
"a",
"socks5",
"proxy",
"server",
"."
] | python | train |
edmondburnett/twitter-text-python | ttp/ttp.py | https://github.com/edmondburnett/twitter-text-python/blob/2a23ced35bfd34c4bc4b7148afd85771e9eb8669/ttp/ttp.py#L230-L253 | def _parse_tags(self, match):
'''Parse hashtags.'''
mat = match.group(0)
# Fix problems with the regex capturing stuff infront of the #
tag = None
for i in '#\uff03':
pos = mat.rfind(i)
if pos != -1:
tag = i
break
... | [
"def",
"_parse_tags",
"(",
"self",
",",
"match",
")",
":",
"mat",
"=",
"match",
".",
"group",
"(",
"0",
")",
"# Fix problems with the regex capturing stuff infront of the #",
"tag",
"=",
"None",
"for",
"i",
"in",
"'#\\uff03'",
":",
"pos",
"=",
"mat",
".",
"r... | Parse hashtags. | [
"Parse",
"hashtags",
"."
] | python | train |
Jajcus/pyxmpp2 | pyxmpp2/streamsasl.py | https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/streamsasl.py#L204-L227 | def _process_sasl_challenge(self, stream, element):
"""Process incoming <sasl:challenge/> element.
[initiating entity only]
"""
if not self.authenticator:
logger.debug("Unexpected SASL challenge")
return False
content = element.text.encode("us-ascii")
... | [
"def",
"_process_sasl_challenge",
"(",
"self",
",",
"stream",
",",
"element",
")",
":",
"if",
"not",
"self",
".",
"authenticator",
":",
"logger",
".",
"debug",
"(",
"\"Unexpected SASL challenge\"",
")",
"return",
"False",
"content",
"=",
"element",
".",
"text"... | Process incoming <sasl:challenge/> element.
[initiating entity only] | [
"Process",
"incoming",
"<sasl",
":",
"challenge",
"/",
">",
"element",
"."
] | python | valid |
PyMySQL/PyMySQL | pymysql/connections.py | https://github.com/PyMySQL/PyMySQL/blob/3674bc6fd064bf88524e839c07690e8c35223709/pymysql/connections.py#L344-L364 | def close(self):
"""
Send the quit message and close the socket.
See `Connection.close() <https://www.python.org/dev/peps/pep-0249/#Connection.close>`_
in the specification.
:raise Error: If the connection is already closed.
"""
if self._closed:
rais... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"raise",
"err",
".",
"Error",
"(",
"\"Already closed\"",
")",
"self",
".",
"_closed",
"=",
"True",
"if",
"self",
".",
"_sock",
"is",
"None",
":",
"return",
"send_data",
"=",
"s... | Send the quit message and close the socket.
See `Connection.close() <https://www.python.org/dev/peps/pep-0249/#Connection.close>`_
in the specification.
:raise Error: If the connection is already closed. | [
"Send",
"the",
"quit",
"message",
"and",
"close",
"the",
"socket",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/click/utils.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/utils.py#L264-L277 | def get_binary_stream(name):
"""Returns a system stream for byte processing. This essentially
returns the stream from the sys module with the given name but it
solves some compatibility issues between different Python versions.
Primarily this function is necessary for getting binary streams on
Pyth... | [
"def",
"get_binary_stream",
"(",
"name",
")",
":",
"opener",
"=",
"binary_streams",
".",
"get",
"(",
"name",
")",
"if",
"opener",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"'Unknown standard stream %r'",
"%",
"name",
")",
"return",
"opener",
"(",
")"
] | Returns a system stream for byte processing. This essentially
returns the stream from the sys module with the given name but it
solves some compatibility issues between different Python versions.
Primarily this function is necessary for getting binary streams on
Python 3.
:param name: the name of ... | [
"Returns",
"a",
"system",
"stream",
"for",
"byte",
"processing",
".",
"This",
"essentially",
"returns",
"the",
"stream",
"from",
"the",
"sys",
"module",
"with",
"the",
"given",
"name",
"but",
"it",
"solves",
"some",
"compatibility",
"issues",
"between",
"diffe... | python | train |
crs4/pydoop | pydoop/hdfs/file.py | https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/hdfs/file.py#L154-L163 | def close(self):
"""
Close the file.
"""
if not self.closed:
self.closed = True
retval = self.f.close()
if self.base_mode != "r":
self.__size = self.fs.get_path_info(self.name)["size"]
return retval | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"closed",
":",
"self",
".",
"closed",
"=",
"True",
"retval",
"=",
"self",
".",
"f",
".",
"close",
"(",
")",
"if",
"self",
".",
"base_mode",
"!=",
"\"r\"",
":",
"self",
".",
"__size"... | Close the file. | [
"Close",
"the",
"file",
"."
] | python | train |
MrYsLab/pymata-aio | pymata_aio/pymata_core.py | https://github.com/MrYsLab/pymata-aio/blob/015081a4628b9d47dfe3f8d6c698ff903f107810/pymata_aio/pymata_core.py#L758-L770 | async def get_capability_report(self):
"""
This method requests and returns a Firmata capability query report
:returns: A capability report in the form of a list
"""
if self.query_reply_data.get(
PrivateConstants.CAPABILITY_RESPONSE) is None:
await se... | [
"async",
"def",
"get_capability_report",
"(",
"self",
")",
":",
"if",
"self",
".",
"query_reply_data",
".",
"get",
"(",
"PrivateConstants",
".",
"CAPABILITY_RESPONSE",
")",
"is",
"None",
":",
"await",
"self",
".",
"_send_sysex",
"(",
"PrivateConstants",
".",
"... | This method requests and returns a Firmata capability query report
:returns: A capability report in the form of a list | [
"This",
"method",
"requests",
"and",
"returns",
"a",
"Firmata",
"capability",
"query",
"report"
] | python | train |
google/flatbuffers | python/flatbuffers/builder.py | https://github.com/google/flatbuffers/blob/6cc30b3272d79c85db7d4871ac0aa69541dc89de/python/flatbuffers/builder.py#L585-L594 | def PrependUOffsetTRelativeSlot(self, o, x, d):
"""
PrependUOffsetTRelativeSlot prepends an UOffsetT onto the object at
vtable slot `o`. If value `x` equals default `d`, then the slot will
be set to zero and no other data will be written.
"""
if x != d:
self.... | [
"def",
"PrependUOffsetTRelativeSlot",
"(",
"self",
",",
"o",
",",
"x",
",",
"d",
")",
":",
"if",
"x",
"!=",
"d",
":",
"self",
".",
"PrependUOffsetTRelative",
"(",
"x",
")",
"self",
".",
"Slot",
"(",
"o",
")"
] | PrependUOffsetTRelativeSlot prepends an UOffsetT onto the object at
vtable slot `o`. If value `x` equals default `d`, then the slot will
be set to zero and no other data will be written. | [
"PrependUOffsetTRelativeSlot",
"prepends",
"an",
"UOffsetT",
"onto",
"the",
"object",
"at",
"vtable",
"slot",
"o",
".",
"If",
"value",
"x",
"equals",
"default",
"d",
"then",
"the",
"slot",
"will",
"be",
"set",
"to",
"zero",
"and",
"no",
"other",
"data",
"w... | python | train |
iotile/coretools | iotilesensorgraph/iotile/sg/graph.py | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/graph.py#L199-L230 | def initialize_remaining_constants(self, value=0):
"""Ensure that all constant streams referenced in the sensor graph have a value.
Constant streams that are automatically created by the compiler are initialized
as part of the compilation process but it's possible that the user references
... | [
"def",
"initialize_remaining_constants",
"(",
"self",
",",
"value",
"=",
"0",
")",
":",
"remaining",
"=",
"[",
"]",
"for",
"node",
",",
"_inputs",
",",
"_outputs",
"in",
"self",
".",
"iterate_bfs",
"(",
")",
":",
"streams",
"=",
"node",
".",
"input_strea... | Ensure that all constant streams referenced in the sensor graph have a value.
Constant streams that are automatically created by the compiler are initialized
as part of the compilation process but it's possible that the user references
other constant streams but never assigns them an explicit i... | [
"Ensure",
"that",
"all",
"constant",
"streams",
"referenced",
"in",
"the",
"sensor",
"graph",
"have",
"a",
"value",
"."
] | python | train |
andycasey/ads | examples/monthly-institute-publications/stromlo.py | https://github.com/andycasey/ads/blob/928415e202db80658cd8532fa4c3a00d0296b5c5/examples/monthly-institute-publications/stromlo.py#L22-L64 | def get_pdf(article, debug=False):
"""
Download an article PDF from arXiv.
:param article:
The ADS article to retrieve.
:type article:
:class:`ads.search.Article`
:returns:
The binary content of the requested PDF.
"""
print('Retrieving {0}'.format(article))
i... | [
"def",
"get_pdf",
"(",
"article",
",",
"debug",
"=",
"False",
")",
":",
"print",
"(",
"'Retrieving {0}'",
".",
"format",
"(",
"article",
")",
")",
"identifier",
"=",
"[",
"_",
"for",
"_",
"in",
"article",
".",
"identifier",
"if",
"'arXiv'",
"in",
"_",
... | Download an article PDF from arXiv.
:param article:
The ADS article to retrieve.
:type article:
:class:`ads.search.Article`
:returns:
The binary content of the requested PDF. | [
"Download",
"an",
"article",
"PDF",
"from",
"arXiv",
"."
] | python | train |
networks-lab/tidyextractors | tidyextractors/tidytwitter/twitter_extractor.py | https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/tidytwitter/twitter_extractor.py#L180-L191 | def _make_user_dict(self, username):
"""
Processes a Twitter User object, exporting as a nested dictionary.
Complex values (i.e. objects that aren't int, bool, float, str, or
a collection of such) are converted to strings (i.e. using __str__
or __repr__). To access user data only... | [
"def",
"_make_user_dict",
"(",
"self",
",",
"username",
")",
":",
"user",
"=",
"self",
".",
"_api",
".",
"get_user",
"(",
"username",
")",
"return",
"self",
".",
"_make_object_dict",
"(",
"user",
")"
] | Processes a Twitter User object, exporting as a nested dictionary.
Complex values (i.e. objects that aren't int, bool, float, str, or
a collection of such) are converted to strings (i.e. using __str__
or __repr__). To access user data only, use make_user_dict(username)['_json'].
:param ... | [
"Processes",
"a",
"Twitter",
"User",
"object",
"exporting",
"as",
"a",
"nested",
"dictionary",
".",
"Complex",
"values",
"(",
"i",
".",
"e",
".",
"objects",
"that",
"aren",
"t",
"int",
"bool",
"float",
"str",
"or",
"a",
"collection",
"of",
"such",
")",
... | python | train |
ivankorobkov/python-inject | src/inject.py | https://github.com/ivankorobkov/python-inject/blob/e2f04f91fbcfd0b38e628cbeda97bd8449038d36/src/inject.py#L108-L114 | def configure_once(config=None, bind_in_runtime=True):
"""Create an injector with a callable config if not present, otherwise, do nothing."""
with _INJECTOR_LOCK:
if _INJECTOR:
return _INJECTOR
return configure(config, bind_in_runtime=bind_in_runtime) | [
"def",
"configure_once",
"(",
"config",
"=",
"None",
",",
"bind_in_runtime",
"=",
"True",
")",
":",
"with",
"_INJECTOR_LOCK",
":",
"if",
"_INJECTOR",
":",
"return",
"_INJECTOR",
"return",
"configure",
"(",
"config",
",",
"bind_in_runtime",
"=",
"bind_in_runtime"... | Create an injector with a callable config if not present, otherwise, do nothing. | [
"Create",
"an",
"injector",
"with",
"a",
"callable",
"config",
"if",
"not",
"present",
"otherwise",
"do",
"nothing",
"."
] | python | train |
GluuFederation/oxd-python | oxdpython/client.py | https://github.com/GluuFederation/oxd-python/blob/a0448cda03b4384bc50a8c20bd65eacd983bceb8/oxdpython/client.py#L538-L601 | def setup_client(self):
"""The command registers the client for communication protection. This
will be used to obtain an access token via the Get Client Token
command. The access token will be passed as a protection_access_token
parameter to other commands.
Note:
If ... | [
"def",
"setup_client",
"(",
"self",
")",
":",
"# add required params for the command",
"params",
"=",
"{",
"\"authorization_redirect_uri\"",
":",
"self",
".",
"authorization_redirect_uri",
",",
"\"oxd_rp_programming_language\"",
":",
"\"python\"",
",",
"}",
"# add other opt... | The command registers the client for communication protection. This
will be used to obtain an access token via the Get Client Token
command. The access token will be passed as a protection_access_token
parameter to other commands.
Note:
If you are using the oxd-https-extensi... | [
"The",
"command",
"registers",
"the",
"client",
"for",
"communication",
"protection",
".",
"This",
"will",
"be",
"used",
"to",
"obtain",
"an",
"access",
"token",
"via",
"the",
"Get",
"Client",
"Token",
"command",
".",
"The",
"access",
"token",
"will",
"be",
... | python | train |
bio2bel/bio2bel | src/bio2bel/manager/namespace_manager.py | https://github.com/bio2bel/bio2bel/blob/d80762d891fa18b248709ff0b0f97ebb65ec64c2/src/bio2bel/manager/namespace_manager.py#L470-L490 | def get_cli(cls) -> click.Group:
"""Get a :mod:`click` main function with added BEL namespace commands."""
main = super().get_cli()
if cls.is_namespace:
@main.group()
def belns():
"""Manage BEL namespace."""
cls._cli_add_to_bel_namespace(beln... | [
"def",
"get_cli",
"(",
"cls",
")",
"->",
"click",
".",
"Group",
":",
"main",
"=",
"super",
"(",
")",
".",
"get_cli",
"(",
")",
"if",
"cls",
".",
"is_namespace",
":",
"@",
"main",
".",
"group",
"(",
")",
"def",
"belns",
"(",
")",
":",
"\"\"\"Manag... | Get a :mod:`click` main function with added BEL namespace commands. | [
"Get",
"a",
":",
"mod",
":",
"click",
"main",
"function",
"with",
"added",
"BEL",
"namespace",
"commands",
"."
] | python | valid |
mabuchilab/QNET | src/qnet/algebra/core/scalar_algebra.py | https://github.com/mabuchilab/QNET/blob/cc20d26dad78691d34c67173e5cd67dcac94208a/src/qnet/algebra/core/scalar_algebra.py#L898-L905 | def create(cls, *operands, **kwargs):
"""Instantiate the product while applying simplification rules"""
converted_operands = []
for op in operands:
if not isinstance(op, Scalar):
op = ScalarValue.create(op)
converted_operands.append(op)
return supe... | [
"def",
"create",
"(",
"cls",
",",
"*",
"operands",
",",
"*",
"*",
"kwargs",
")",
":",
"converted_operands",
"=",
"[",
"]",
"for",
"op",
"in",
"operands",
":",
"if",
"not",
"isinstance",
"(",
"op",
",",
"Scalar",
")",
":",
"op",
"=",
"ScalarValue",
... | Instantiate the product while applying simplification rules | [
"Instantiate",
"the",
"product",
"while",
"applying",
"simplification",
"rules"
] | python | train |
buriburisuri/sugartensor | sugartensor/sg_transform.py | https://github.com/buriburisuri/sugartensor/blob/d2c039954777c7fbe3eb0c2ae40c45c9854deb40/sugartensor/sg_transform.py#L30-L45 | def sg_cast(tensor, opt):
r"""Casts a tensor to a new type.
See `tf.cast()` in tensorflow.
Args:
tensor: A `Tensor` or `SparseTensor` (automatically given by chain).
opt:
dtype : The destination type.
name : If provided, it replaces current tensor's name
Returns:
... | [
"def",
"sg_cast",
"(",
"tensor",
",",
"opt",
")",
":",
"assert",
"opt",
".",
"dtype",
"is",
"not",
"None",
",",
"'dtype is mandatory.'",
"return",
"tf",
".",
"cast",
"(",
"tensor",
",",
"opt",
".",
"dtype",
",",
"name",
"=",
"opt",
".",
"name",
")"
] | r"""Casts a tensor to a new type.
See `tf.cast()` in tensorflow.
Args:
tensor: A `Tensor` or `SparseTensor` (automatically given by chain).
opt:
dtype : The destination type.
name : If provided, it replaces current tensor's name
Returns:
A `Tensor` or `SparseTensor` ... | [
"r",
"Casts",
"a",
"tensor",
"to",
"a",
"new",
"type",
".",
"See",
"tf",
".",
"cast",
"()",
"in",
"tensorflow",
"."
] | python | train |
quantopian/zipline | zipline/lib/labelarray.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/lib/labelarray.py#L322-L338 | def as_categorical(self):
"""
Coerce self into a pandas categorical.
This is only defined on 1D arrays, since that's all pandas supports.
"""
if len(self.shape) > 1:
raise ValueError("Can't convert a 2D array to a categorical.")
with ignore_pandas_nan_catego... | [
"def",
"as_categorical",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"shape",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"Can't convert a 2D array to a categorical.\"",
")",
"with",
"ignore_pandas_nan_categorical_warning",
"(",
")",
":",
"return",... | Coerce self into a pandas categorical.
This is only defined on 1D arrays, since that's all pandas supports. | [
"Coerce",
"self",
"into",
"a",
"pandas",
"categorical",
"."
] | python | train |
nephila/djangocms-helper | djangocms_helper/runner.py | https://github.com/nephila/djangocms-helper/blob/3fe53aee7b06922112c5e4445b74afeb86f6d836/djangocms_helper/runner.py#L28-L52 | def cms(app, argv=sys.argv, extra_args=None):
"""
Run commands in a django cMS environment
:param app: application
:param argv: arguments (default to sys.argv)
:param extra_args: list of extra arguments
"""
try:
import cms # NOQA # nopyflakes
except ImportError:
print(... | [
"def",
"cms",
"(",
"app",
",",
"argv",
"=",
"sys",
".",
"argv",
",",
"extra_args",
"=",
"None",
")",
":",
"try",
":",
"import",
"cms",
"# NOQA # nopyflakes",
"except",
"ImportError",
":",
"print",
"(",
"'runner.cms is available only if django CMS is installed'",
... | Run commands in a django cMS environment
:param app: application
:param argv: arguments (default to sys.argv)
:param extra_args: list of extra arguments | [
"Run",
"commands",
"in",
"a",
"django",
"cMS",
"environment"
] | python | train |
dcaune/perseus-lib-python-common | majormode/perseus/model/locale.py | https://github.com/dcaune/perseus-lib-python-common/blob/ba48fe0fd9bb4a75b53e7d10c41ada36a72d4496/majormode/perseus/model/locale.py#L254-L288 | def decompose_locale(locale, strict=True):
"""
Return the decomposition of the specified locale into a language code
and a country code.
@param locale: a string representation of a locale, i.e., a ISO 639-3
alpha-3 code (or alpha-2 code), optionally followed by a dash
... | [
"def",
"decompose_locale",
"(",
"locale",
",",
"strict",
"=",
"True",
")",
":",
"if",
"locale",
"is",
"None",
":",
"return",
"(",
"'eng'",
",",
"None",
")",
"match",
"=",
"REGEX_LOCALE",
".",
"match",
"(",
"locale",
")",
"if",
"match",
"is",
"None",
... | Return the decomposition of the specified locale into a language code
and a country code.
@param locale: a string representation of a locale, i.e., a ISO 639-3
alpha-3 code (or alpha-2 code), optionally followed by a dash
character ``-`` and a ISO 3166-1 alpha-2 code. If ``Non... | [
"Return",
"the",
"decomposition",
"of",
"the",
"specified",
"locale",
"into",
"a",
"language",
"code",
"and",
"a",
"country",
"code",
"."
] | python | train |
pyblish/pyblish-nuke | pyblish_nuke/lib.py | https://github.com/pyblish/pyblish-nuke/blob/5fbd766774e999e5e3015201094a07a92d800c4f/pyblish_nuke/lib.py#L335-L379 | def dock(window):
""" Expecting a window to parent into a Nuke panel, that is dockable. """
# Deleting existing dock
# There is a bug where existing docks are kept in-memory when closed via UI
if self._dock:
print("Deleting existing dock...")
parent = self._dock
dialog = None
... | [
"def",
"dock",
"(",
"window",
")",
":",
"# Deleting existing dock",
"# There is a bug where existing docks are kept in-memory when closed via UI",
"if",
"self",
".",
"_dock",
":",
"print",
"(",
"\"Deleting existing dock...\"",
")",
"parent",
"=",
"self",
".",
"_dock",
"di... | Expecting a window to parent into a Nuke panel, that is dockable. | [
"Expecting",
"a",
"window",
"to",
"parent",
"into",
"a",
"Nuke",
"panel",
"that",
"is",
"dockable",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.