nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kirthevasank/nasbot | 3c745dc986be30e3721087c8fa768099032a0802 | nn/syn_nn_functions.py | python | _degree_signal | (in_degrees, out_degrees, bias_val, decay) | return np.exp(-decay * abs(avg_degree - bias_val)) | Signal on the degrees. | Signal on the degrees. | [
"Signal",
"on",
"the",
"degrees",
"."
] | def _degree_signal(in_degrees, out_degrees, bias_val, decay):
""" Signal on the degrees. """
avg_degree = (in_degrees.mean() + out_degrees.mean())/2.0
return np.exp(-decay * abs(avg_degree - bias_val)) | [
"def",
"_degree_signal",
"(",
"in_degrees",
",",
"out_degrees",
",",
"bias_val",
",",
"decay",
")",
":",
"avg_degree",
"=",
"(",
"in_degrees",
".",
"mean",
"(",
")",
"+",
"out_degrees",
".",
"mean",
"(",
")",
")",
"/",
"2.0",
"return",
"np",
".",
"exp"... | https://github.com/kirthevasank/nasbot/blob/3c745dc986be30e3721087c8fa768099032a0802/nn/syn_nn_functions.py#L18-L21 | |
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/modules/mongodb.py | python | __virtual__ | () | Only load this module if pymongo is installed | Only load this module if pymongo is installed | [
"Only",
"load",
"this",
"module",
"if",
"pymongo",
"is",
"installed"
] | def __virtual__():
"""
Only load this module if pymongo is installed
"""
if HAS_MONGODB:
return "mongodb"
else:
return (
False,
"The mongodb execution module cannot be loaded: the pymongo library is not"
" available.",
) | [
"def",
"__virtual__",
"(",
")",
":",
"if",
"HAS_MONGODB",
":",
"return",
"\"mongodb\"",
"else",
":",
"return",
"(",
"False",
",",
"\"The mongodb execution module cannot be loaded: the pymongo library is not\"",
"\" available.\"",
",",
")"
] | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/mongodb.py#L33-L44 | ||
theotherp/nzbhydra | 4b03d7f769384b97dfc60dade4806c0fc987514e | libs/werkzeug/utils.py | python | redirect | (location, code=302, Response=None) | return response | Returns a response object (a WSGI application) that, if called,
redirects the client to the target location. Supported codes are 301,
302, 303, 305, and 307. 300 is not supported because it's not a real
redirect and 304 because it's the answer for a request with a request
with defined If-Modified-Since headers.
.. versionadded:: 0.6
The location can now be a unicode string that is encoded using
the :func:`iri_to_uri` function.
.. versionadded:: 0.10
The class used for the Response object can now be passed in.
:param location: the location the response should redirect to.
:param code: the redirect status code. defaults to 302.
:param class Response: a Response class to use when instantiating a
response. The default is :class:`werkzeug.wrappers.Response` if
unspecified. | Returns a response object (a WSGI application) that, if called,
redirects the client to the target location. Supported codes are 301,
302, 303, 305, and 307. 300 is not supported because it's not a real
redirect and 304 because it's the answer for a request with a request
with defined If-Modified-Since headers. | [
"Returns",
"a",
"response",
"object",
"(",
"a",
"WSGI",
"application",
")",
"that",
"if",
"called",
"redirects",
"the",
"client",
"to",
"the",
"target",
"location",
".",
"Supported",
"codes",
"are",
"301",
"302",
"303",
"305",
"and",
"307",
".",
"300",
"... | def redirect(location, code=302, Response=None):
"""Returns a response object (a WSGI application) that, if called,
redirects the client to the target location. Supported codes are 301,
302, 303, 305, and 307. 300 is not supported because it's not a real
redirect and 304 because it's the answer for a request with a request
with defined If-Modified-Since headers.
.. versionadded:: 0.6
The location can now be a unicode string that is encoded using
the :func:`iri_to_uri` function.
.. versionadded:: 0.10
The class used for the Response object can now be passed in.
:param location: the location the response should redirect to.
:param code: the redirect status code. defaults to 302.
:param class Response: a Response class to use when instantiating a
response. The default is :class:`werkzeug.wrappers.Response` if
unspecified.
"""
if Response is None:
from werkzeug.wrappers import Response
display_location = escape(location)
if isinstance(location, text_type):
# Safe conversion is necessary here as we might redirect
# to a broken URI scheme (for instance itms-services).
from werkzeug.urls import iri_to_uri
location = iri_to_uri(location, safe_conversion=True)
response = Response(
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
'<title>Redirecting...</title>\n'
'<h1>Redirecting...</h1>\n'
'<p>You should be redirected automatically to target URL: '
'<a href="%s">%s</a>. If not click the link.' %
(escape(location), display_location), code, mimetype='text/html')
response.headers['Location'] = location
return response | [
"def",
"redirect",
"(",
"location",
",",
"code",
"=",
"302",
",",
"Response",
"=",
"None",
")",
":",
"if",
"Response",
"is",
"None",
":",
"from",
"werkzeug",
".",
"wrappers",
"import",
"Response",
"display_location",
"=",
"escape",
"(",
"location",
")",
... | https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/werkzeug/utils.py#L338-L375 | |
deepmipt/DeepPavlov | 08555428388fed3c7b036c0a82a70a25efcabcff | deeppavlov/metrics/squad_metrics.py | python | squad_v2_f1 | (y_true: List[List[str]], y_predicted: List[str]) | return 100 * f1_total / len(y_true) if len(y_true) > 0 else 0 | Calculates F-1 score between y_true and y_predicted
F-1 score uses the best matching y_true answer
The same as in SQuAD-v2.0
Args:
y_true: list of correct answers (correct answers are represented by list of strings)
y_predicted: list of predicted answers
Returns:
F-1 score : float | Calculates F-1 score between y_true and y_predicted
F-1 score uses the best matching y_true answer | [
"Calculates",
"F",
"-",
"1",
"score",
"between",
"y_true",
"and",
"y_predicted",
"F",
"-",
"1",
"score",
"uses",
"the",
"best",
"matching",
"y_true",
"answer"
] | def squad_v2_f1(y_true: List[List[str]], y_predicted: List[str]) -> float:
""" Calculates F-1 score between y_true and y_predicted
F-1 score uses the best matching y_true answer
The same as in SQuAD-v2.0
Args:
y_true: list of correct answers (correct answers are represented by list of strings)
y_predicted: list of predicted answers
Returns:
F-1 score : float
"""
f1_total = 0.0
for ground_truth, prediction in zip(y_true, y_predicted):
prediction_tokens = normalize_answer(prediction).split()
f1s = []
for gt in ground_truth:
gt_tokens = normalize_answer(gt).split()
if len(gt_tokens) == 0 or len(prediction_tokens) == 0:
f1s.append(float(gt_tokens == prediction_tokens))
continue
common = Counter(prediction_tokens) & Counter(gt_tokens)
num_same = sum(common.values())
if num_same == 0:
f1s.append(0.0)
continue
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(gt_tokens)
f1 = (2 * precision * recall) / (precision + recall)
f1s.append(f1)
f1_total += max(f1s)
return 100 * f1_total / len(y_true) if len(y_true) > 0 else 0 | [
"def",
"squad_v2_f1",
"(",
"y_true",
":",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
",",
"y_predicted",
":",
"List",
"[",
"str",
"]",
")",
"->",
"float",
":",
"f1_total",
"=",
"0.0",
"for",
"ground_truth",
",",
"prediction",
"in",
"zip",
"(",
"y_tru... | https://github.com/deepmipt/DeepPavlov/blob/08555428388fed3c7b036c0a82a70a25efcabcff/deeppavlov/metrics/squad_metrics.py#L68-L100 | |
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-darwin/x64/qrcode/main.py | python | _check_box_size | (size) | [] | def _check_box_size(size):
if int(size) <= 0:
raise ValueError(
"Invalid box size (was %s, expected larger than 0)" % size) | [
"def",
"_check_box_size",
"(",
"size",
")",
":",
"if",
"int",
"(",
"size",
")",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Invalid box size (was %s, expected larger than 0)\"",
"%",
"size",
")"
] | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/qrcode/main.py#L20-L23 | ||||
TuuuNya/WebPocket | e0ba36be22e9aee0fd95f6e0a9bd716619629bf4 | lib/cmd2/cmd2.py | python | Cmd.delimiter_complete | (self, text: str, line: str, begidx: int, endidx: int, match_against: Iterable,
delimiter: str) | return matches | Performs tab completion against a list but each match is split on a delimiter and only
the portion of the match being tab completed is shown as the completion suggestions.
This is useful if you match against strings that are hierarchical in nature and have a
common delimiter.
An easy way to illustrate this concept is path completion since paths are just directories/files
delimited by a slash. If you are tab completing items in /home/user you don't get the following
as suggestions:
/home/user/file.txt /home/user/program.c
/home/user/maps/ /home/user/cmd2.py
Instead you are shown:
file.txt program.c
maps/ cmd2.py
For a large set of data, this can be visually more pleasing and easier to search.
Another example would be strings formatted with the following syntax: company::department::name
In this case the delimiter would be :: and the user could easily narrow down what they are looking
for if they were only shown suggestions in the category they are at in the string.
:param text: the string prefix we are attempting to match (all returned matches must begin with it)
:param line: the current input line with leading whitespace removed
:param begidx: the beginning index of the prefix text
:param endidx: the ending index of the prefix text
:param match_against: the list being matched against
:param delimiter: what delimits each portion of the matches (ex: paths are delimited by a slash)
:return: a list of possible tab completions | Performs tab completion against a list but each match is split on a delimiter and only
the portion of the match being tab completed is shown as the completion suggestions.
This is useful if you match against strings that are hierarchical in nature and have a
common delimiter. | [
"Performs",
"tab",
"completion",
"against",
"a",
"list",
"but",
"each",
"match",
"is",
"split",
"on",
"a",
"delimiter",
"and",
"only",
"the",
"portion",
"of",
"the",
"match",
"being",
"tab",
"completed",
"is",
"shown",
"as",
"the",
"completion",
"suggestions... | def delimiter_complete(self, text: str, line: str, begidx: int, endidx: int, match_against: Iterable,
delimiter: str) -> List[str]:
"""
Performs tab completion against a list but each match is split on a delimiter and only
the portion of the match being tab completed is shown as the completion suggestions.
This is useful if you match against strings that are hierarchical in nature and have a
common delimiter.
An easy way to illustrate this concept is path completion since paths are just directories/files
delimited by a slash. If you are tab completing items in /home/user you don't get the following
as suggestions:
/home/user/file.txt /home/user/program.c
/home/user/maps/ /home/user/cmd2.py
Instead you are shown:
file.txt program.c
maps/ cmd2.py
For a large set of data, this can be visually more pleasing and easier to search.
Another example would be strings formatted with the following syntax: company::department::name
In this case the delimiter would be :: and the user could easily narrow down what they are looking
for if they were only shown suggestions in the category they are at in the string.
:param text: the string prefix we are attempting to match (all returned matches must begin with it)
:param line: the current input line with leading whitespace removed
:param begidx: the beginning index of the prefix text
:param endidx: the ending index of the prefix text
:param match_against: the list being matched against
:param delimiter: what delimits each portion of the matches (ex: paths are delimited by a slash)
:return: a list of possible tab completions
"""
matches = self.basic_complete(text, line, begidx, endidx, match_against)
# Display only the portion of the match that's being completed based on delimiter
if matches:
# Set this to True for proper quoting of matches with spaces
self.matches_delimited = True
# Get the common beginning for the matches
common_prefix = os.path.commonprefix(matches)
prefix_tokens = common_prefix.split(delimiter)
# Calculate what portion of the match we are completing
display_token_index = 0
if prefix_tokens:
display_token_index = len(prefix_tokens) - 1
# Get this portion for each match and store them in self.display_matches
for cur_match in matches:
match_tokens = cur_match.split(delimiter)
display_token = match_tokens[display_token_index]
if not display_token:
display_token = delimiter
self.display_matches.append(display_token)
return matches | [
"def",
"delimiter_complete",
"(",
"self",
",",
"text",
":",
"str",
",",
"line",
":",
"str",
",",
"begidx",
":",
"int",
",",
"endidx",
":",
"int",
",",
"match_against",
":",
"Iterable",
",",
"delimiter",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",... | https://github.com/TuuuNya/WebPocket/blob/e0ba36be22e9aee0fd95f6e0a9bd716619629bf4/lib/cmd2/cmd2.py#L864-L923 | |
Source-Python-Dev-Team/Source.Python | d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb | addons/source-python/Python3/collections/__init__.py | python | OrderedDict.popitem | (self, last=True) | return key, value | od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false. | od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false. | [
"od",
".",
"popitem",
"()",
"-",
">",
"(",
"k",
"v",
")",
"return",
"and",
"remove",
"a",
"(",
"key",
"value",
")",
"pair",
".",
"Pairs",
"are",
"returned",
"in",
"LIFO",
"order",
"if",
"last",
"is",
"true",
"or",
"FIFO",
"order",
"if",
"false",
... | def popitem(self, last=True):
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.
'''
if not self:
raise KeyError('dictionary is empty')
root = self.__root
if last:
link = root.prev
link_prev = link.prev
link_prev.next = root
root.prev = link_prev
else:
link = root.next
link_next = link.next
root.next = link_next
link_next.prev = root
key = link.key
del self.__map[key]
value = dict.pop(self, key)
return key, value | [
"def",
"popitem",
"(",
"self",
",",
"last",
"=",
"True",
")",
":",
"if",
"not",
"self",
":",
"raise",
"KeyError",
"(",
"'dictionary is empty'",
")",
"root",
"=",
"self",
".",
"__root",
"if",
"last",
":",
"link",
"=",
"root",
".",
"prev",
"link_prev",
... | https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/collections/__init__.py#L159-L180 | |
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/cme/v20191029/models.py | python | VideoEncodingPresetAudioSettingForUpdate.__init__ | (self) | r"""
:param Bitrate: 音频码率,单位:bps。
不填则不修改。
:type Bitrate: str
:param Channels: 音频声道数,可选值:
<li>1:单声道;</li>
<li>2:双声道。</li>
不填则不修改。
:type Channels: int
:param SampleRate: 音频流的采样率,目前仅支持: 16000; 32000; 44100; 48000。单位:Hz。
不填则不修改。
:type SampleRate: int | r"""
:param Bitrate: 音频码率,单位:bps。
不填则不修改。
:type Bitrate: str
:param Channels: 音频声道数,可选值:
<li>1:单声道;</li>
<li>2:双声道。</li>
不填则不修改。
:type Channels: int
:param SampleRate: 音频流的采样率,目前仅支持: 16000; 32000; 44100; 48000。单位:Hz。
不填则不修改。
:type SampleRate: int | [
"r",
":",
"param",
"Bitrate",
":",
"音频码率,单位:bps。",
"不填则不修改。",
":",
"type",
"Bitrate",
":",
"str",
":",
"param",
"Channels",
":",
"音频声道数,可选值:",
"<li",
">",
"1:单声道;<",
"/",
"li",
">",
"<li",
">",
"2:双声道。<",
"/",
"li",
">",
"不填则不修改。",
":",
"type",
"Channe... | def __init__(self):
r"""
:param Bitrate: 音频码率,单位:bps。
不填则不修改。
:type Bitrate: str
:param Channels: 音频声道数,可选值:
<li>1:单声道;</li>
<li>2:双声道。</li>
不填则不修改。
:type Channels: int
:param SampleRate: 音频流的采样率,目前仅支持: 16000; 32000; 44100; 48000。单位:Hz。
不填则不修改。
:type SampleRate: int
"""
self.Bitrate = None
self.Channels = None
self.SampleRate = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"Bitrate",
"=",
"None",
"self",
".",
"Channels",
"=",
"None",
"self",
".",
"SampleRate",
"=",
"None"
] | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cme/v20191029/models.py#L6189-L6205 | ||
WerWolv/EdiZon_CheatsConfigsAndScripts | d16d36c7509c01dca770f402babd83ff2e9ae6e7 | Scripts/lib/python3.5/codecs.py | python | IncrementalEncoder.setstate | (self, state) | Set the current state of the encoder. state must have been
returned by getstate(). | Set the current state of the encoder. state must have been
returned by getstate(). | [
"Set",
"the",
"current",
"state",
"of",
"the",
"encoder",
".",
"state",
"must",
"have",
"been",
"returned",
"by",
"getstate",
"()",
"."
] | def setstate(self, state):
"""
Set the current state of the encoder. state must have been
returned by getstate().
""" | [
"def",
"setstate",
"(",
"self",
",",
"state",
")",
":"
] | https://github.com/WerWolv/EdiZon_CheatsConfigsAndScripts/blob/d16d36c7509c01dca770f402babd83ff2e9ae6e7/Scripts/lib/python3.5/codecs.py#L213-L217 | ||
DataDog/integrations-core | 934674b29d94b70ccc008f76ea172d0cdae05e1e | datadog_checks_base/datadog_checks/base/checks/prometheus/base_check.py | python | PrometheusScraper._metric_tags | (self, metric_name, val, metric, custom_tags=None, hostname=None) | return self._finalize_tags_to_submit(
_tags, metric_name, val, metric, custom_tags=custom_tags, hostname=hostname
) | [] | def _metric_tags(self, metric_name, val, metric, custom_tags=None, hostname=None):
_tags = []
if custom_tags is not None:
_tags += custom_tags
for label in metric.label:
if self.exclude_labels is None or label.name not in self.exclude_labels:
tag_name = label.name
if self.labels_mapper is not None and label.name in self.labels_mapper:
tag_name = self.labels_mapper[label.name]
_tags.append('{}:{}'.format(to_native_string(tag_name), to_native_string(label.value)))
return self._finalize_tags_to_submit(
_tags, metric_name, val, metric, custom_tags=custom_tags, hostname=hostname
) | [
"def",
"_metric_tags",
"(",
"self",
",",
"metric_name",
",",
"val",
",",
"metric",
",",
"custom_tags",
"=",
"None",
",",
"hostname",
"=",
"None",
")",
":",
"_tags",
"=",
"[",
"]",
"if",
"custom_tags",
"is",
"not",
"None",
":",
"_tags",
"+=",
"custom_ta... | https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/datadog_checks_base/datadog_checks/base/checks/prometheus/base_check.py#L57-L69 | |||
rembo10/headphones | b3199605be1ebc83a7a8feab6b1e99b64014187c | lib/ordereddict.py | python | OrderedDict.copy | (self) | return self.__class__(self) | [] | def copy(self):
return self.__class__(self) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"self",
")"
] | https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/ordereddict.py#L106-L107 | |||
openbmc/openbmc | 5f4109adae05f4d6925bfe960007d52f98c61086 | poky/bitbake/lib/bb/utils.py | python | is_semver | (version) | return True | Is the version string following the semver semantic?
https://semver.org/spec/v2.0.0.html | Is the version string following the semver semantic? | [
"Is",
"the",
"version",
"string",
"following",
"the",
"semver",
"semantic?"
] | def is_semver(version):
"""
Is the version string following the semver semantic?
https://semver.org/spec/v2.0.0.html
"""
regex = re.compile(
r"""
^
(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)
(?:-(
(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)
(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*
))?
(?:\+(
[0-9a-zA-Z-]+
(?:\.[0-9a-zA-Z-]+)*
))?
$
""", re.VERBOSE)
if regex.match(version) is None:
return False
return True | [
"def",
"is_semver",
"(",
"version",
")",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"r\"\"\"\n ^\n (0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\n (?:-(\n (?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)\n (?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*\n ))?\n (... | https://github.com/openbmc/openbmc/blob/5f4109adae05f4d6925bfe960007d52f98c61086/poky/bitbake/lib/bb/utils.py#L1647-L1671 | |
jgagneastro/coffeegrindsize | 22661ebd21831dba4cf32bfc6ba59fe3d49f879c | App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/scipy/stats/morestats.py | python | ppcc_plot | (x, a, b, dist='tukeylambda', plot=None, N=80) | return svals, ppcc | Calculate and optionally plot probability plot correlation coefficient.
The probability plot correlation coefficient (PPCC) plot can be used to
determine the optimal shape parameter for a one-parameter family of
distributions. It cannot be used for distributions without shape parameters
(like the normal distribution) or with multiple shape parameters.
By default a Tukey-Lambda distribution (`stats.tukeylambda`) is used. A
Tukey-Lambda PPCC plot interpolates from long-tailed to short-tailed
distributions via an approximately normal one, and is therefore particularly
useful in practice.
Parameters
----------
x : array_like
Input array.
a, b: scalar
Lower and upper bounds of the shape parameter to use.
dist : str or stats.distributions instance, optional
Distribution or distribution function name. Objects that look enough
like a stats.distributions instance (i.e. they have a ``ppf`` method)
are also accepted. The default is ``'tukeylambda'``.
plot : object, optional
If given, plots PPCC against the shape parameter.
`plot` is an object that has to have methods "plot" and "text".
The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
or a custom object with the same methods.
Default is None, which means that no plot is created.
N : int, optional
Number of points on the horizontal axis (equally distributed from
`a` to `b`).
Returns
-------
svals : ndarray
The shape values for which `ppcc` was calculated.
ppcc : ndarray
The calculated probability plot correlation coefficient values.
See also
--------
ppcc_max, probplot, boxcox_normplot, tukeylambda
References
----------
J.J. Filliben, "The Probability Plot Correlation Coefficient Test for
Normality", Technometrics, Vol. 17, pp. 111-117, 1975.
Examples
--------
First we generate some random data from a Tukey-Lambda distribution,
with shape parameter -0.7:
>>> from scipy import stats
>>> import matplotlib.pyplot as plt
>>> np.random.seed(1234567)
>>> x = stats.tukeylambda.rvs(-0.7, loc=2, scale=0.5, size=10000) + 1e4
Now we explore this data with a PPCC plot as well as the related
probability plot and Box-Cox normplot. A red line is drawn where we
expect the PPCC value to be maximal (at the shape parameter -0.7 used
above):
>>> fig = plt.figure(figsize=(12, 4))
>>> ax1 = fig.add_subplot(131)
>>> ax2 = fig.add_subplot(132)
>>> ax3 = fig.add_subplot(133)
>>> res = stats.probplot(x, plot=ax1)
>>> res = stats.boxcox_normplot(x, -5, 5, plot=ax2)
>>> res = stats.ppcc_plot(x, -5, 5, plot=ax3)
>>> ax3.vlines(-0.7, 0, 1, colors='r', label='Expected shape value')
>>> plt.show() | Calculate and optionally plot probability plot correlation coefficient. | [
"Calculate",
"and",
"optionally",
"plot",
"probability",
"plot",
"correlation",
"coefficient",
"."
] | def ppcc_plot(x, a, b, dist='tukeylambda', plot=None, N=80):
"""
Calculate and optionally plot probability plot correlation coefficient.
The probability plot correlation coefficient (PPCC) plot can be used to
determine the optimal shape parameter for a one-parameter family of
distributions. It cannot be used for distributions without shape parameters
(like the normal distribution) or with multiple shape parameters.
By default a Tukey-Lambda distribution (`stats.tukeylambda`) is used. A
Tukey-Lambda PPCC plot interpolates from long-tailed to short-tailed
distributions via an approximately normal one, and is therefore particularly
useful in practice.
Parameters
----------
x : array_like
Input array.
a, b: scalar
Lower and upper bounds of the shape parameter to use.
dist : str or stats.distributions instance, optional
Distribution or distribution function name. Objects that look enough
like a stats.distributions instance (i.e. they have a ``ppf`` method)
are also accepted. The default is ``'tukeylambda'``.
plot : object, optional
If given, plots PPCC against the shape parameter.
`plot` is an object that has to have methods "plot" and "text".
The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
or a custom object with the same methods.
Default is None, which means that no plot is created.
N : int, optional
Number of points on the horizontal axis (equally distributed from
`a` to `b`).
Returns
-------
svals : ndarray
The shape values for which `ppcc` was calculated.
ppcc : ndarray
The calculated probability plot correlation coefficient values.
See also
--------
ppcc_max, probplot, boxcox_normplot, tukeylambda
References
----------
J.J. Filliben, "The Probability Plot Correlation Coefficient Test for
Normality", Technometrics, Vol. 17, pp. 111-117, 1975.
Examples
--------
First we generate some random data from a Tukey-Lambda distribution,
with shape parameter -0.7:
>>> from scipy import stats
>>> import matplotlib.pyplot as plt
>>> np.random.seed(1234567)
>>> x = stats.tukeylambda.rvs(-0.7, loc=2, scale=0.5, size=10000) + 1e4
Now we explore this data with a PPCC plot as well as the related
probability plot and Box-Cox normplot. A red line is drawn where we
expect the PPCC value to be maximal (at the shape parameter -0.7 used
above):
>>> fig = plt.figure(figsize=(12, 4))
>>> ax1 = fig.add_subplot(131)
>>> ax2 = fig.add_subplot(132)
>>> ax3 = fig.add_subplot(133)
>>> res = stats.probplot(x, plot=ax1)
>>> res = stats.boxcox_normplot(x, -5, 5, plot=ax2)
>>> res = stats.ppcc_plot(x, -5, 5, plot=ax3)
>>> ax3.vlines(-0.7, 0, 1, colors='r', label='Expected shape value')
>>> plt.show()
"""
if b <= a:
raise ValueError("`b` has to be larger than `a`.")
svals = np.linspace(a, b, num=N)
ppcc = np.empty_like(svals)
for k, sval in enumerate(svals):
_, r2 = probplot(x, sval, dist=dist, fit=True)
ppcc[k] = r2[-1]
if plot is not None:
plot.plot(svals, ppcc, 'x')
_add_axis_labels_title(plot, xlabel='Shape Values',
ylabel='Prob Plot Corr. Coef.',
title='(%s) PPCC Plot' % dist)
return svals, ppcc | [
"def",
"ppcc_plot",
"(",
"x",
",",
"a",
",",
"b",
",",
"dist",
"=",
"'tukeylambda'",
",",
"plot",
"=",
"None",
",",
"N",
"=",
"80",
")",
":",
"if",
"b",
"<=",
"a",
":",
"raise",
"ValueError",
"(",
"\"`b` has to be larger than `a`.\"",
")",
"svals",
"... | https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/scipy/stats/morestats.py#L721-L812 | |
jesseweisberg/moveo_ros | b9282bdadbf2505a26d3b94b91e60a98d86efa34 | object_detector_app/object_detection/builders/optimizer_builder.py | python | _create_learning_rate | (learning_rate_config, global_summaries) | return learning_rate | Create optimizer learning rate based on config.
Args:
learning_rate_config: A LearningRate proto message.
global_summaries: A set to attach learning rate summary to.
Returns:
A learning rate.
Raises:
ValueError: when using an unsupported input data type. | Create optimizer learning rate based on config. | [
"Create",
"optimizer",
"learning",
"rate",
"based",
"on",
"config",
"."
] | def _create_learning_rate(learning_rate_config, global_summaries):
"""Create optimizer learning rate based on config.
Args:
learning_rate_config: A LearningRate proto message.
global_summaries: A set to attach learning rate summary to.
Returns:
A learning rate.
Raises:
ValueError: when using an unsupported input data type.
"""
learning_rate = None
learning_rate_type = learning_rate_config.WhichOneof('learning_rate')
if learning_rate_type == 'constant_learning_rate':
config = learning_rate_config.constant_learning_rate
learning_rate = config.learning_rate
if learning_rate_type == 'exponential_decay_learning_rate':
config = learning_rate_config.exponential_decay_learning_rate
learning_rate = tf.train.exponential_decay(
config.initial_learning_rate,
slim.get_or_create_global_step(),
config.decay_steps,
config.decay_factor,
staircase=config.staircase)
if learning_rate_type == 'manual_step_learning_rate':
config = learning_rate_config.manual_step_learning_rate
if not config.schedule:
raise ValueError('Empty learning rate schedule.')
learning_rate_step_boundaries = [x.step for x in config.schedule]
learning_rate_sequence = [config.initial_learning_rate]
learning_rate_sequence += [x.learning_rate for x in config.schedule]
learning_rate = learning_schedules.manual_stepping(
slim.get_or_create_global_step(), learning_rate_step_boundaries,
learning_rate_sequence)
if learning_rate is None:
raise ValueError('Learning_rate %s not supported.' % learning_rate_type)
global_summaries.add(tf.summary.scalar('Learning Rate', learning_rate))
return learning_rate | [
"def",
"_create_learning_rate",
"(",
"learning_rate_config",
",",
"global_summaries",
")",
":",
"learning_rate",
"=",
"None",
"learning_rate_type",
"=",
"learning_rate_config",
".",
"WhichOneof",
"(",
"'learning_rate'",
")",
"if",
"learning_rate_type",
"==",
"'constant_le... | https://github.com/jesseweisberg/moveo_ros/blob/b9282bdadbf2505a26d3b94b91e60a98d86efa34/object_detector_app/object_detection/builders/optimizer_builder.py#L69-L112 | |
pwnieexpress/pwn_plug_sources | 1a23324f5dc2c3de20f9c810269b6a29b2758cad | src/metagoofil/hachoir_parser/container/mkv.py | python | UTF8 | (parent) | return _String(parent,'unicode', parent['size'].value, charset='UTF-8') | [] | def UTF8(parent):
return _String(parent,'unicode', parent['size'].value, charset='UTF-8') | [
"def",
"UTF8",
"(",
"parent",
")",
":",
"return",
"_String",
"(",
"parent",
",",
"'unicode'",
",",
"parent",
"[",
"'size'",
"]",
".",
"value",
",",
"charset",
"=",
"'UTF-8'",
")"
] | https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/metagoofil/hachoir_parser/container/mkv.py#L103-L104 | |||
vim-vdebug/vdebug | a5121a28335cf7f561d111031e69baac52eed035 | python3/vdebug/util.py | python | ExceptionHandler.handle_socket_end | (self) | Handle a socket closing, which is pretty normal. | Handle a socket closing, which is pretty normal. | [
"Handle",
"a",
"socket",
"closing",
"which",
"is",
"pretty",
"normal",
"."
] | def handle_socket_end(self):
"""Handle a socket closing, which is pretty normal.
"""
self._session_handler.ui().say(
"Connection to the debugger has been closed"
)
self._session_handler.stop() | [
"def",
"handle_socket_end",
"(",
"self",
")",
":",
"self",
".",
"_session_handler",
".",
"ui",
"(",
")",
".",
"say",
"(",
"\"Connection to the debugger has been closed\"",
")",
"self",
".",
"_session_handler",
".",
"stop",
"(",
")"
] | https://github.com/vim-vdebug/vdebug/blob/a5121a28335cf7f561d111031e69baac52eed035/python3/vdebug/util.py#L44-L50 | ||
ucaiado/rl_trading | f4168c69f44fe5a11a06461387d4591426a43735 | market_gym/utils/util.py | python | ElapsedList_old.count | (self) | return len(self.l) | Return and item from the list according to the id passed | Return and item from the list according to the id passed | [
"Return",
"and",
"item",
"from",
"the",
"list",
"according",
"to",
"the",
"id",
"passed"
] | def count(self):
'''
Return and item from the list according to the id passed
'''
return len(self.l) | [
"def",
"count",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"l",
")"
] | https://github.com/ucaiado/rl_trading/blob/f4168c69f44fe5a11a06461387d4591426a43735/market_gym/utils/util.py#L132-L136 | |
viewfinderco/viewfinder | 453845b5d64ab5b3b826c08b02546d1ca0a07c14 | backend/logs/get_server_logs.py | python | _Start | (callback) | Grab the job lock and call RunOnce if acquired. We do not write a job summary as we currently do not use it. | Grab the job lock and call RunOnce if acquired. We do not write a job summary as we currently do not use it. | [
"Grab",
"the",
"job",
"lock",
"and",
"call",
"RunOnce",
"if",
"acquired",
".",
"We",
"do",
"not",
"write",
"a",
"job",
"summary",
"as",
"we",
"currently",
"do",
"not",
"use",
"it",
"."
] | def _Start(callback):
"""Grab the job lock and call RunOnce if acquired. We do not write a job summary as we currently do not use it."""
client = db_client.DBClient.Instance()
job = Job(client, 'merge_logs')
if options.options.require_lock:
got_lock = yield gen.Task(job.AcquireLock)
if got_lock == False:
logging.warning('Failed to acquire job lock: exiting.')
callback()
return
try:
yield gen.Task(RunOnce)
finally:
yield gen.Task(job.ReleaseLock)
callback() | [
"def",
"_Start",
"(",
"callback",
")",
":",
"client",
"=",
"db_client",
".",
"DBClient",
".",
"Instance",
"(",
")",
"job",
"=",
"Job",
"(",
"client",
",",
"'merge_logs'",
")",
"if",
"options",
".",
"options",
".",
"require_lock",
":",
"got_lock",
"=",
... | https://github.com/viewfinderco/viewfinder/blob/453845b5d64ab5b3b826c08b02546d1ca0a07c14/backend/logs/get_server_logs.py#L229-L246 | ||
LinOTP/LinOTP | bb3940bbaccea99550e6c063ff824f258dd6d6d7 | linotp/lib/security/default.py | python | DefaultSecurityModule.hmac_digest | (self, bkey, data_input, hash_algo) | return digest | simple hmac with implicit digest
:param bkey: the private shared secret
:param data_input: the data
:param hash_algo: one of the hashing algorithms | simple hmac with implicit digest | [
"simple",
"hmac",
"with",
"implicit",
"digest"
] | def hmac_digest(self, bkey, data_input, hash_algo):
"""
simple hmac with implicit digest
:param bkey: the private shared secret
:param data_input: the data
:param hash_algo: one of the hashing algorithms
"""
digest = hmac.new(bkey, data_input, hash_algo).digest()
return digest | [
"def",
"hmac_digest",
"(",
"self",
",",
"bkey",
",",
"data_input",
",",
"hash_algo",
")",
":",
"digest",
"=",
"hmac",
".",
"new",
"(",
"bkey",
",",
"data_input",
",",
"hash_algo",
")",
".",
"digest",
"(",
")",
"return",
"digest"
] | https://github.com/LinOTP/LinOTP/blob/bb3940bbaccea99550e6c063ff824f258dd6d6d7/linotp/lib/security/default.py#L483-L494 | |
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/components/accuweather/weather.py | python | AccuWeatherEntity.wind_bearing | (self) | return cast(int, self.coordinator.data["Wind"]["Direction"]["Degrees"]) | Return the wind bearing. | Return the wind bearing. | [
"Return",
"the",
"wind",
"bearing",
"."
] | def wind_bearing(self) -> int:
"""Return the wind bearing."""
return cast(int, self.coordinator.data["Wind"]["Direction"]["Degrees"]) | [
"def",
"wind_bearing",
"(",
"self",
")",
"->",
"int",
":",
"return",
"cast",
"(",
"int",
",",
"self",
".",
"coordinator",
".",
"data",
"[",
"\"Wind\"",
"]",
"[",
"\"Direction\"",
"]",
"[",
"\"Degrees\"",
"]",
")"
] | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/accuweather/weather.py#L123-L125 | |
SheffieldML/GPy | bb1bc5088671f9316bc92a46d356734e34c2d5c0 | GPy/models/warped_gp.py | python | WarpedGP.parameters_changed | (self) | Notice that we update the warping function gradients here. | Notice that we update the warping function gradients here. | [
"Notice",
"that",
"we",
"update",
"the",
"warping",
"function",
"gradients",
"here",
"."
] | def parameters_changed(self):
"""
Notice that we update the warping function gradients here.
"""
self.Y_normalized[:] = self.transform_data()
super(WarpedGP, self).parameters_changed()
Kiy = self.posterior.woodbury_vector.flatten()
self.warping_function.update_grads(self.Y_untransformed, Kiy) | [
"def",
"parameters_changed",
"(",
"self",
")",
":",
"self",
".",
"Y_normalized",
"[",
":",
"]",
"=",
"self",
".",
"transform_data",
"(",
")",
"super",
"(",
"WarpedGP",
",",
"self",
")",
".",
"parameters_changed",
"(",
")",
"Kiy",
"=",
"self",
".",
"pos... | https://github.com/SheffieldML/GPy/blob/bb1bc5088671f9316bc92a46d356734e34c2d5c0/GPy/models/warped_gp.py#L38-L45 | ||
gepd/Deviot | 150caea06108369b30210eb287a580fcff4904af | libraries/pyserial/tools/miniterm.py | python | Miniterm.change_encoding | (self) | change encoding on the serial port | change encoding on the serial port | [
"change",
"encoding",
"on",
"the",
"serial",
"port"
] | def change_encoding(self):
"""change encoding on the serial port"""
sys.stderr.write('\n--- Enter new encoding name [{}]: '.format(self.input_encoding))
with self.console:
new_encoding = sys.stdin.readline().strip()
if new_encoding:
try:
codecs.lookup(new_encoding)
except LookupError:
sys.stderr.write('--- invalid encoding name: {}\n'.format(new_encoding))
else:
self.set_rx_encoding(new_encoding)
self.set_tx_encoding(new_encoding)
sys.stderr.write('--- serial input encoding: {}\n'.format(self.input_encoding))
sys.stderr.write('--- serial output encoding: {}\n'.format(self.output_encoding)) | [
"def",
"change_encoding",
"(",
"self",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'\\n--- Enter new encoding name [{}]: '",
".",
"format",
"(",
"self",
".",
"input_encoding",
")",
")",
"with",
"self",
".",
"console",
":",
"new_encoding",
"=",
"sys",
... | https://github.com/gepd/Deviot/blob/150caea06108369b30210eb287a580fcff4904af/libraries/pyserial/tools/miniterm.py#L621-L635 | ||
hakril/PythonForWindows | 61e027a678d5b87aa64fcf8a37a6661a86236589 | windows/winproxy/apis/advapi32.py | python | GetSidSubAuthority | (pSid, nSubAuthority) | return GetSidSubAuthority.ctypes_function(pSid, nSubAuthority) | [] | def GetSidSubAuthority(pSid, nSubAuthority):
return GetSidSubAuthority.ctypes_function(pSid, nSubAuthority) | [
"def",
"GetSidSubAuthority",
"(",
"pSid",
",",
"nSubAuthority",
")",
":",
"return",
"GetSidSubAuthority",
".",
"ctypes_function",
"(",
"pSid",
",",
"nSubAuthority",
")"
] | https://github.com/hakril/PythonForWindows/blob/61e027a678d5b87aa64fcf8a37a6661a86236589/windows/winproxy/apis/advapi32.py#L144-L145 | |||
Tautulli/Tautulli | 2410eb33805aaac4bd1c5dad0f71e4f15afaf742 | lib/dateutil/parser/_parser.py | python | _timelex.__init__ | (self, instream) | [] | def __init__(self, instream):
if isinstance(instream, (bytes, bytearray)):
instream = instream.decode()
if isinstance(instream, text_type):
instream = StringIO(instream)
elif getattr(instream, 'read', None) is None:
raise TypeError('Parser must be a string or character stream, not '
'{itype}'.format(itype=instream.__class__.__name__))
self.instream = instream
self.charstack = []
self.tokenstack = []
self.eof = False | [
"def",
"__init__",
"(",
"self",
",",
"instream",
")",
":",
"if",
"isinstance",
"(",
"instream",
",",
"(",
"bytes",
",",
"bytearray",
")",
")",
":",
"instream",
"=",
"instream",
".",
"decode",
"(",
")",
"if",
"isinstance",
"(",
"instream",
",",
"text_ty... | https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/dateutil/parser/_parser.py#L62-L75 | ||||
kyb3r/modmail | a1aacbfb817f6410d9c8b4fce41bbd0e1e55b6b3 | core/utils.py | python | truncate | (text: str, max: int = 50) | return text[: max - 3].strip() + "..." if len(text) > max else text | Reduces the string to `max` length, by trimming the message into "...".
Parameters
----------
text : str
The text to trim.
max : int, optional
The max length of the text.
Defaults to 50.
Returns
-------
str
The truncated text. | Reduces the string to `max` length, by trimming the message into "...". | [
"Reduces",
"the",
"string",
"to",
"max",
"length",
"by",
"trimming",
"the",
"message",
"into",
"...",
"."
] | def truncate(text: str, max: int = 50) -> str: # pylint: disable=redefined-builtin
"""
Reduces the string to `max` length, by trimming the message into "...".
Parameters
----------
text : str
The text to trim.
max : int, optional
The max length of the text.
Defaults to 50.
Returns
-------
str
The truncated text.
"""
text = text.strip()
return text[: max - 3].strip() + "..." if len(text) > max else text | [
"def",
"truncate",
"(",
"text",
":",
"str",
",",
"max",
":",
"int",
"=",
"50",
")",
"->",
"str",
":",
"# pylint: disable=redefined-builtin",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"return",
"text",
"[",
":",
"max",
"-",
"3",
"]",
".",
"strip",
... | https://github.com/kyb3r/modmail/blob/a1aacbfb817f6410d9c8b4fce41bbd0e1e55b6b3/core/utils.py#L74-L92 | |
bitcraze/crazyflie-clients-python | 65d433a945b097333e5681a937354045dd4b66f4 | src/cfclient/ui/widgets/plotwidget.py | python | PlotWidget.set_title | (self, title) | Set the title of the plot.
title - the new title | Set the title of the plot. | [
"Set",
"the",
"title",
"of",
"the",
"plot",
"."
] | def set_title(self, title):
"""
Set the title of the plot.
title - the new title
"""
self._plot_widget.setTitle(title) | [
"def",
"set_title",
"(",
"self",
",",
"title",
")",
":",
"self",
".",
"_plot_widget",
".",
"setTitle",
"(",
"title",
")"
] | https://github.com/bitcraze/crazyflie-clients-python/blob/65d433a945b097333e5681a937354045dd4b66f4/src/cfclient/ui/widgets/plotwidget.py#L232-L238 | ||
larryhastings/gilectomy | 4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a | Lib/tkinter/__init__.py | python | Misc._configure | (self, cmd, cnf, kw) | Internal function. | Internal function. | [
"Internal",
"function",
"."
] | def _configure(self, cmd, cnf, kw):
"""Internal function."""
if kw:
cnf = _cnfmerge((cnf, kw))
elif cnf:
cnf = _cnfmerge(cnf)
if cnf is None:
return self._getconfigure(_flatten((self._w, cmd)))
if isinstance(cnf, str):
return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf)))
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) | [
"def",
"_configure",
"(",
"self",
",",
"cmd",
",",
"cnf",
",",
"kw",
")",
":",
"if",
"kw",
":",
"cnf",
"=",
"_cnfmerge",
"(",
"(",
"cnf",
",",
"kw",
")",
")",
"elif",
"cnf",
":",
"cnf",
"=",
"_cnfmerge",
"(",
"cnf",
")",
"if",
"cnf",
"is",
"N... | https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/tkinter/__init__.py#L1304-L1314 | ||
arjunvekariyagithub/camelyon16-grand-challenge | 660000a79775fbc5cfa8c5b44a591e62ce714089 | camelyon16/postprocess/build_heatmap.py | python | generate_all_heatmap | (model_name, heatmap_name_postfix, heatmap_prob_name_postfix) | special case: Tumor_018
Failded case: Tumor_20, Tumor_25, | special case: Tumor_018 | [
"special",
"case",
":",
"Tumor_018"
] | def generate_all_heatmap(model_name, heatmap_name_postfix, heatmap_prob_name_postfix):
"""
special case: Tumor_018
Failded case: Tumor_20, Tumor_25,
"""
global heat_map_prob
assert model_name in utils.heatmap_models, utils.heatmap_models
# tf_records_file_names = sorted(os.listdir(utils.HEAT_MAP_TF_RECORDS_DIR))
# tf_records_file_names = tf_records_file_names[1:]
# print(tf_records_file_names)
wsi_names = utils.test_wsi_names[45:48]
print('Generating heatmap for:', wsi_names)
for wsi_filename in wsi_names:
if 'est' not in wsi_filename:
continue
print('Generating heatmap for: %s' % wsi_filename)
heatmap_filename = str(os.path.join(utils.HEAT_MAP_DIR, wsi_filename)) + heatmap_name_postfix
if os.path.exists(heatmap_filename):
print('%s heatmap already generated for: %s' % (model_name, wsi_filename))
continue
tf_records_dir = os.path.join(utils.HEAT_MAP_TF_RECORDS_DIR, wsi_filename)
assert os.path.exists(tf_records_dir), 'tf-records directory %s does not exist' % tf_records_dir
# raw_patches_dir = os.path.join(utils.HEAT_MAP_RAW_PATCHES_DIR, wsi_filename)
# assert os.path.exists(raw_patches_dir), 'heatmap raw_patches_dir %s does not exist' % raw_patches_dir
heatmap_rgb_path = os.path.join(utils.HEAT_MAP_WSIs_PATH, wsi_filename)
assert os.path.exists(heatmap_rgb_path), 'heatmap rgb image %s does not exist' % heatmap_rgb_path
heatmap_rgb = cv2.imread(heatmap_rgb_path)
heatmap_rgb = heatmap_rgb[:, :, :3]
heat_map = np.zeros((heatmap_rgb.shape[0], heatmap_rgb.shape[1]), dtype=np.float32)
heat_map_prob = np.zeros((heatmap_rgb.shape[0], heatmap_rgb.shape[1]), dtype=np.float32)
# assert os.path.exists(raw_patches_dir), 'raw patches directory %s does not exist' % raw_patches_dir
# num_patches = len(os.listdir(raw_patches_dir))
num_patches = utils.n_patches_dic[wsi_filename]
dataset = Dataset(DATA_SET_NAME, utils.data_subset[4], tf_records_dir=tf_records_dir, num_patches=num_patches)
heat_map = build_heatmap(dataset, heat_map, model_name, wsi_filename)
if not utils.is_running_on_server():
plt.imshow(heat_map, cmap='jet', interpolation='nearest')
plt.colorbar()
plt.clim(0.00, 1.00)
plt.axis([0, heatmap_rgb.shape[1], 0, heatmap_rgb.shape[0]])
plt.savefig(heatmap_filename)
plt.clf()
cv2.imwrite(os.path.join(utils.HEAT_MAP_DIR, wsi_filename) + heatmap_prob_name_postfix, heat_map_prob * 255) | [
"def",
"generate_all_heatmap",
"(",
"model_name",
",",
"heatmap_name_postfix",
",",
"heatmap_prob_name_postfix",
")",
":",
"global",
"heat_map_prob",
"assert",
"model_name",
"in",
"utils",
".",
"heatmap_models",
",",
"utils",
".",
"heatmap_models",
"# tf_records_file_name... | https://github.com/arjunvekariyagithub/camelyon16-grand-challenge/blob/660000a79775fbc5cfa8c5b44a591e62ce714089/camelyon16/postprocess/build_heatmap.py#L178-L226 | ||
bubbliiiing/Semantic-Segmentation | 4cc89a22ffc9018d2b44e69e85672c7bdd1ab706 | deeplab_Xception/nets/Xception.py | python | _conv2d_same | (x, filters, prefix, stride=1, kernel_size=3, rate=1) | [] | def _conv2d_same(x, filters, prefix, stride=1, kernel_size=3, rate=1):
# 计算padding的数量,hw是否需要收缩
if stride == 1:
return Conv2D(filters,
(kernel_size, kernel_size),
strides=(stride, stride),
padding='same', use_bias=False,
dilation_rate=(rate, rate),
name=prefix)(x)
else:
kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1)
pad_total = kernel_size_effective - 1
pad_beg = pad_total // 2
pad_end = pad_total - pad_beg
x = ZeroPadding2D((pad_beg, pad_end))(x)
return Conv2D(filters,
(kernel_size, kernel_size),
strides=(stride, stride),
padding='valid', use_bias=False,
dilation_rate=(rate, rate),
name=prefix)(x) | [
"def",
"_conv2d_same",
"(",
"x",
",",
"filters",
",",
"prefix",
",",
"stride",
"=",
"1",
",",
"kernel_size",
"=",
"3",
",",
"rate",
"=",
"1",
")",
":",
"# 计算padding的数量,hw是否需要收缩",
"if",
"stride",
"==",
"1",
":",
"return",
"Conv2D",
"(",
"filters",
",",
... | https://github.com/bubbliiiing/Semantic-Segmentation/blob/4cc89a22ffc9018d2b44e69e85672c7bdd1ab706/deeplab_Xception/nets/Xception.py#L8-L28 | ||||
lbryio/lbry-sdk | f78e3825ca0f130834d3876a824f9d380501ced8 | lbry/wallet/rpc/session.py | python | Server.close | (self) | Close the listening socket. This does not close any ServerSession
objects created to handle incoming connections. | Close the listening socket. This does not close any ServerSession
objects created to handle incoming connections. | [
"Close",
"the",
"listening",
"socket",
".",
"This",
"does",
"not",
"close",
"any",
"ServerSession",
"objects",
"created",
"to",
"handle",
"incoming",
"connections",
"."
] | async def close(self):
"""Close the listening socket. This does not close any ServerSession
objects created to handle incoming connections.
"""
if self.server:
self.server.close()
await self.server.wait_closed()
self.server = None | [
"async",
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"server",
":",
"self",
".",
"server",
".",
"close",
"(",
")",
"await",
"self",
".",
"server",
".",
"wait_closed",
"(",
")",
"self",
".",
"server",
"=",
"None"
] | https://github.com/lbryio/lbry-sdk/blob/f78e3825ca0f130834d3876a824f9d380501ced8/lbry/wallet/rpc/session.py#L543-L550 | ||
zynga/jasy | 8a2ec2c2ca3f6c0f73cba4306e581c89b30f1b18 | jasy/item/Translation.py | python | TranslationItem.getTable | (self) | return self.table | Returns the translation table | Returns the translation table | [
"Returns",
"the",
"translation",
"table"
] | def getTable(self):
"""Returns the translation table"""
return self.table | [
"def",
"getTable",
"(",
"self",
")",
":",
"return",
"self",
".",
"table"
] | https://github.com/zynga/jasy/blob/8a2ec2c2ca3f6c0f73cba4306e581c89b30f1b18/jasy/item/Translation.py#L130-L132 | |
IJDykeman/wangTiles | 7c1ee2095ebdf7f72bce07d94c6484915d5cae8b | experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pkg_resources/_vendor/six.py | python | remove_move | (name) | Remove item from six.moves. | Remove item from six.moves. | [
"Remove",
"item",
"from",
"six",
".",
"moves",
"."
] | def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,)) | [
"def",
"remove_move",
"(",
"name",
")",
":",
"try",
":",
"delattr",
"(",
"_MovedItems",
",",
"name",
")",
"except",
"AttributeError",
":",
"try",
":",
"del",
"moves",
".",
"__dict__",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"AttributeError",
... | https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac/lib/python2.7/site-packages/pkg_resources/_vendor/six.py#L491-L499 | ||
openstack/freezer | 3eb84784c668ed9f442322abee4e48bd1bc51fd4 | freezer/job.py | python | Job._validate | (self) | Method that validates if all arguments available to execute the job
or not
:return: True or raise an error | Method that validates if all arguments available to execute the job
or not
:return: True or raise an error | [
"Method",
"that",
"validates",
"if",
"all",
"arguments",
"available",
"to",
"execute",
"the",
"job",
"or",
"not",
":",
"return",
":",
"True",
"or",
"raise",
"an",
"error"
] | def _validate(self):
"""
Method that validates if all arguments available to execute the job
or not
:return: True or raise an error
"""
pass | [
"def",
"_validate",
"(",
"self",
")",
":",
"pass"
] | https://github.com/openstack/freezer/blob/3eb84784c668ed9f442322abee4e48bd1bc51fd4/freezer/job.py#L81-L87 | ||
decalage2/ViperMonkey | 631d242f43108226bb25ed91e773a274012dc8c2 | vipermonkey/core/excel.py | python | ExcelSheet.cell | (self, row, col) | Get a cell from the sheet.
@param row (int) The cell's row index.
@param col (int) The cell's column index.
@return (str) The cell value if the cell is found.
@throws KeyError This is thrown if the cell is not found. | Get a cell from the sheet. | [
"Get",
"a",
"cell",
"from",
"the",
"sheet",
"."
] | def cell(self, row, col):
"""Get a cell from the sheet.
@param row (int) The cell's row index.
@param col (int) The cell's column index.
@return (str) The cell value if the cell is found.
@throws KeyError This is thrown if the cell is not found.
"""
if ((row, col) in self.cells):
return self.cells[(row, col)]
raise KeyError("Cell (" + str(row) + ", " + str(col) + ") not found.") | [
"def",
"cell",
"(",
"self",
",",
"row",
",",
"col",
")",
":",
"if",
"(",
"(",
"row",
",",
"col",
")",
"in",
"self",
".",
"cells",
")",
":",
"return",
"self",
".",
"cells",
"[",
"(",
"row",
",",
"col",
")",
"]",
"raise",
"KeyError",
"(",
"\"Ce... | https://github.com/decalage2/ViperMonkey/blob/631d242f43108226bb25ed91e773a274012dc8c2/vipermonkey/core/excel.py#L669-L683 | ||
davidbau/ganseeing | 93cea2c8f391aef001ddf9dcb35c43990681a47c | seeing/train_onelayer_inv.py | python | encoder_loss | (z_batch, s_maker, r_maker, encoder) | return (cor_square_error(true_s, recovered_s)
+ 0.01 * cor_square_error(true_r, recovered_r)) | [] | def encoder_loss(z_batch, s_maker, r_maker, encoder):
true_s = s_maker(z_batch)
true_r = r_maker(true_s)
recovered_s = encoder(true_r)
recovered_r = r_maker(recovered_s)
return (cor_square_error(true_s, recovered_s)
+ 0.01 * cor_square_error(true_r, recovered_r)) | [
"def",
"encoder_loss",
"(",
"z_batch",
",",
"s_maker",
",",
"r_maker",
",",
"encoder",
")",
":",
"true_s",
"=",
"s_maker",
"(",
"z_batch",
")",
"true_r",
"=",
"r_maker",
"(",
"true_s",
")",
"recovered_s",
"=",
"encoder",
"(",
"true_r",
")",
"recovered_r",
... | https://github.com/davidbau/ganseeing/blob/93cea2c8f391aef001ddf9dcb35c43990681a47c/seeing/train_onelayer_inv.py#L163-L169 | |||
iBelieveCJM/Tricks-of-Semi-supervisedDeepLeanring-Pytorch | be90060b3017e99b8c53a596110cb5931ec9f38c | utils/mixup.py | python | mixup_two_targets | (x, y, alpha=1.0, device='cuda', is_bias=False) | return mixed_x, y_a, y_b, lam | Returns mixed inputs, pairs of targets, and lambda | Returns mixed inputs, pairs of targets, and lambda | [
"Returns",
"mixed",
"inputs",
"pairs",
"of",
"targets",
"and",
"lambda"
] | def mixup_two_targets(x, y, alpha=1.0, device='cuda', is_bias=False):
"""Returns mixed inputs, pairs of targets, and lambda
"""
if alpha > 0:
lam = np.random.beta(alpha, alpha)
else:
lam = 1
if is_bias: lam = max(lam, 1-lam)
index = torch.randperm(x.size(0)).to(device)
mixed_x = lam*x + (1-lam)*x[index, :]
y_a, y_b = y, y[index]
return mixed_x, y_a, y_b, lam | [
"def",
"mixup_two_targets",
"(",
"x",
",",
"y",
",",
"alpha",
"=",
"1.0",
",",
"device",
"=",
"'cuda'",
",",
"is_bias",
"=",
"False",
")",
":",
"if",
"alpha",
">",
"0",
":",
"lam",
"=",
"np",
".",
"random",
".",
"beta",
"(",
"alpha",
",",
"alpha"... | https://github.com/iBelieveCJM/Tricks-of-Semi-supervisedDeepLeanring-Pytorch/blob/be90060b3017e99b8c53a596110cb5931ec9f38c/utils/mixup.py#L23-L36 | |
krintoxi/NoobSec-Toolkit | 38738541cbc03cedb9a3b3ed13b629f781ad64f6 | NoobSecToolkit - MAC OSX/tools/inject/thirdparty/gprof2dot/gprof2dot.py | python | CallgrindParser.parse_cost_summary | (self) | return True | [] | def parse_cost_summary(self):
pair = self.parse_keys(('summary', 'totals'))
if pair is None:
return False
return True | [
"def",
"parse_cost_summary",
"(",
"self",
")",
":",
"pair",
"=",
"self",
".",
"parse_keys",
"(",
"(",
"'summary'",
",",
"'totals'",
")",
")",
"if",
"pair",
"is",
"None",
":",
"return",
"False",
"return",
"True"
] | https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/inject/thirdparty/gprof2dot/gprof2dot.py#L1126-L1130 | |||
bcbio/bcbio-nextgen | c80f9b6b1be3267d1f981b7035e3b72441d258f2 | bcbio/illumina/machine.py | python | _remap_dirname | (local, remote) | return do | Remap directory names from local to remote. | Remap directory names from local to remote. | [
"Remap",
"directory",
"names",
"from",
"local",
"to",
"remote",
"."
] | def _remap_dirname(local, remote):
"""Remap directory names from local to remote.
"""
def do(x):
return x.replace(local, remote, 1)
return do | [
"def",
"_remap_dirname",
"(",
"local",
",",
"remote",
")",
":",
"def",
"do",
"(",
"x",
")",
":",
"return",
"x",
".",
"replace",
"(",
"local",
",",
"remote",
",",
"1",
")",
"return",
"do"
] | https://github.com/bcbio/bcbio-nextgen/blob/c80f9b6b1be3267d1f981b7035e3b72441d258f2/bcbio/illumina/machine.py#L57-L62 | |
enthought/traitsui | b7c38c7a47bf6ae7971f9ddab70c8a358647dd25 | traitsui/wx/list_str_editor.py | python | _ListStrEditor.wx_dropped_on | (self, x, y, data, drag_result) | return wx.DragNone | Handles a Python object being dropped on the list control. | Handles a Python object being dropped on the list control. | [
"Handles",
"a",
"Python",
"object",
"being",
"dropped",
"on",
"the",
"list",
"control",
"."
] | def wx_dropped_on(self, x, y, data, drag_result):
"""Handles a Python object being dropped on the list control."""
index, flags = self.control.HitTest(wx.Point(x, y))
# If the user dropped it on an empty list, set the target as past the
# end of the list:
if (
(index == -1)
and ((flags & wx.LIST_HITTEST_NOWHERE) != 0)
and (self.control.GetItemCount() == 0)
):
index = 0
# If we have a valid drop target index, proceed:
if index != -1:
if not isinstance(data, list):
# Handle the case of just a single item being dropped:
self._wx_dropped_on(index, data)
else:
# Handles the case of a list of items being dropped, being
# careful to preserve the original order of the source items if
# possible:
data.reverse()
for item in data:
self._wx_dropped_on(index, item)
# If this was an inter-list drag, mark it as 'local':
if self._drag_indices is not None:
self._drag_local = True
# Return a successful drop result:
return drag_result
# Indicate we could not process the drop:
return wx.DragNone | [
"def",
"wx_dropped_on",
"(",
"self",
",",
"x",
",",
"y",
",",
"data",
",",
"drag_result",
")",
":",
"index",
",",
"flags",
"=",
"self",
".",
"control",
".",
"HitTest",
"(",
"wx",
".",
"Point",
"(",
"x",
",",
"y",
")",
")",
"# If the user dropped it o... | https://github.com/enthought/traitsui/blob/b7c38c7a47bf6ae7971f9ddab70c8a358647dd25/traitsui/wx/list_str_editor.py#L602-L636 | |
BigBrotherBot/big-brother-bot | 848823c71413c86e7f1ff9584f43e08d40a7f2c0 | b3/plugins/scheduler/__init__.py | python | CronTask.schedule | (self) | schedule this task | schedule this task | [
"schedule",
"this",
"task"
] | def schedule(self):
"""
schedule this task
"""
self._getScheduledTime(self.config.attrib)
self.cronTab = b3.cron.PluginCronTab(self.plugin, self.runcommands,
self.seconds, self.minutes, self.plugin._convertCronHourToUTC(self.hour), self.day, self.month, self.dow)
self.plugin.console.cron + self.cronTab | [
"def",
"schedule",
"(",
"self",
")",
":",
"self",
".",
"_getScheduledTime",
"(",
"self",
".",
"config",
".",
"attrib",
")",
"self",
".",
"cronTab",
"=",
"b3",
".",
"cron",
".",
"PluginCronTab",
"(",
"self",
".",
"plugin",
",",
"self",
".",
"runcommands... | https://github.com/BigBrotherBot/big-brother-bot/blob/848823c71413c86e7f1ff9584f43e08d40a7f2c0/b3/plugins/scheduler/__init__.py#L309-L316 | ||
deanishe/alfred-convert | 97407f4ec8dbca5abbc6952b2b56cf3918624177 | src/convert.py | python | Conversion.__repr__ | (self) | return ('Conversion(from_number={!r}, from_unit={!r}, '
'to_number={!r}, to_unit={!r}, dimensionality={!r}').format(
self.from_number, self.from_unit, self.to_number,
self.to_unit, self.dimensionality) | Code-like representation. | Code-like representation. | [
"Code",
"-",
"like",
"representation",
"."
] | def __repr__(self):
"""Code-like representation."""
return ('Conversion(from_number={!r}, from_unit={!r}, '
'to_number={!r}, to_unit={!r}, dimensionality={!r}').format(
self.from_number, self.from_unit, self.to_number,
self.to_unit, self.dimensionality) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"(",
"'Conversion(from_number={!r}, from_unit={!r}, '",
"'to_number={!r}, to_unit={!r}, dimensionality={!r}'",
")",
".",
"format",
"(",
"self",
".",
"from_number",
",",
"self",
".",
"from_unit",
",",
"self",
".",
"to... | https://github.com/deanishe/alfred-convert/blob/97407f4ec8dbca5abbc6952b2b56cf3918624177/src/convert.py#L278-L283 | |
rembo10/headphones | b3199605be1ebc83a7a8feab6b1e99b64014187c | lib/pythontwitter/__init__.py | python | Hashtag.NewFromJsonDict | (data) | return Hashtag(text = data.get('text', None)) | Create a new instance based on a JSON dict.
Args:
data:
A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.Hashtag instance | Create a new instance based on a JSON dict. | [
"Create",
"a",
"new",
"instance",
"based",
"on",
"a",
"JSON",
"dict",
"."
] | def NewFromJsonDict(data):
'''Create a new instance based on a JSON dict.
Args:
data:
A JSON dict, as converted from the JSON in the twitter API
Returns:
A twitter.Hashtag instance
'''
return Hashtag(text = data.get('text', None)) | [
"def",
"NewFromJsonDict",
"(",
"data",
")",
":",
"return",
"Hashtag",
"(",
"text",
"=",
"data",
".",
"get",
"(",
"'text'",
",",
"None",
")",
")"
] | https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/pythontwitter/__init__.py#L2163-L2173 | |
yuxiaokui/Intranet-Penetration | f57678a204840c83cbf3308e3470ae56c5ff514b | proxy/XX-Net/code/default/python27/1.0/lib/xml/sax/_exceptions.py | python | SAXException.__init__ | (self, msg, exception=None) | Creates an exception. The message is required, but the exception
is optional. | Creates an exception. The message is required, but the exception
is optional. | [
"Creates",
"an",
"exception",
".",
"The",
"message",
"is",
"required",
"but",
"the",
"exception",
"is",
"optional",
"."
] | def __init__(self, msg, exception=None):
"""Creates an exception. The message is required, but the exception
is optional."""
self._msg = msg
self._exception = exception
Exception.__init__(self, msg) | [
"def",
"__init__",
"(",
"self",
",",
"msg",
",",
"exception",
"=",
"None",
")",
":",
"self",
".",
"_msg",
"=",
"msg",
"self",
".",
"_exception",
"=",
"exception",
"Exception",
".",
"__init__",
"(",
"self",
",",
"msg",
")"
] | https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/python27/1.0/lib/xml/sax/_exceptions.py#L19-L24 | ||
kylebebak/Requester | 4a9f9f051fa5fc951a8f7ad098a328261ca2db97 | commands/request.py | python | RequesterCommand.run | (self, edit, concurrency=10) | Allow user to specify concurrency. | Allow user to specify concurrency. | [
"Allow",
"user",
"to",
"specify",
"concurrency",
"."
] | def run(self, edit, concurrency=10):
"""Allow user to specify concurrency.
"""
self.MAX_WORKERS = max(1, concurrency)
super().run(edit) | [
"def",
"run",
"(",
"self",
",",
"edit",
",",
"concurrency",
"=",
"10",
")",
":",
"self",
".",
"MAX_WORKERS",
"=",
"max",
"(",
"1",
",",
"concurrency",
")",
"super",
"(",
")",
".",
"run",
"(",
"edit",
")"
] | https://github.com/kylebebak/Requester/blob/4a9f9f051fa5fc951a8f7ad098a328261ca2db97/commands/request.py#L338-L342 | ||
aptonic/dropzone4-actions | 936ab89868ba8c79094a3577c2055fe376bfc488 | YouTube Downloader.dzbundle/youtube-dl/youtube_dl/utils.py | python | expand_path | (s) | return os.path.expandvars(compat_expanduser(s)) | Expand shell variables and ~ | Expand shell variables and ~ | [
"Expand",
"shell",
"variables",
"and",
"~"
] | def expand_path(s):
"""Expand shell variables and ~"""
return os.path.expandvars(compat_expanduser(s)) | [
"def",
"expand_path",
"(",
"s",
")",
":",
"return",
"os",
".",
"path",
".",
"expandvars",
"(",
"compat_expanduser",
"(",
"s",
")",
")"
] | https://github.com/aptonic/dropzone4-actions/blob/936ab89868ba8c79094a3577c2055fe376bfc488/YouTube Downloader.dzbundle/youtube-dl/youtube_dl/utils.py#L2161-L2163 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/pip/_vendor/pyparsing.py | python | ParserElement.setParseAction | ( self, *fns, **kwargs ) | return self | Define action to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)},
C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:
- s = the original string being parsed (see note below)
- loc = the location of the matching substring
- toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object
If the functions in fns modify the tokens, they can return them as the return
value from fn, and the modified list of tokens will replace the original.
Otherwise, fn does not need to return any value.
Optional keyword arguments:
- callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{parseString}<parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
Example::
integer = Word(nums)
date_str = integer + '/' + integer + '/' + integer
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# use parse action to convert to ints at parse time
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
date_str = integer + '/' + integer + '/' + integer
# note that integer fields are now ints, not strings
date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31] | Define action to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)},
C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:
- s = the original string being parsed (see note below)
- loc = the location of the matching substring
- toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object
If the functions in fns modify the tokens, they can return them as the return
value from fn, and the modified list of tokens will replace the original.
Otherwise, fn does not need to return any value. | [
"Define",
"action",
"to",
"perform",
"when",
"successfully",
"matching",
"parse",
"element",
"definition",
".",
"Parse",
"action",
"fn",
"is",
"a",
"callable",
"method",
"with",
"0",
"-",
"3",
"arguments",
"called",
"as",
"C",
"{",
"fn",
"(",
"s",
"loc",
... | def setParseAction( self, *fns, **kwargs ):
"""
Define action to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)},
C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:
- s = the original string being parsed (see note below)
- loc = the location of the matching substring
- toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object
If the functions in fns modify the tokens, they can return them as the return
value from fn, and the modified list of tokens will replace the original.
Otherwise, fn does not need to return any value.
Optional keyword arguments:
- callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{parseString}<parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
Example::
integer = Word(nums)
date_str = integer + '/' + integer + '/' + integer
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# use parse action to convert to ints at parse time
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
date_str = integer + '/' + integer + '/' + integer
# note that integer fields are now ints, not strings
date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31]
"""
self.parseAction = list(map(_trim_arity, list(fns)))
self.callDuringTry = kwargs.get("callDuringTry", False)
return self | [
"def",
"setParseAction",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"parseAction",
"=",
"list",
"(",
"map",
"(",
"_trim_arity",
",",
"list",
"(",
"fns",
")",
")",
")",
"self",
".",
"callDuringTry",
"=",
"kwargs",
... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/_vendor/pyparsing.py#L1227-L1263 | |
olist/correios | 5494d7457665fa9a8dffbffa976cdbd2885c54e4 | correios/models/user.py | python | PostingCard.unit | (self, number) | [] | def unit(self, number):
self._unit = to_integer(number) | [
"def",
"unit",
"(",
"self",
",",
"number",
")",
":",
"self",
".",
"_unit",
"=",
"to_integer",
"(",
"number",
")"
] | https://github.com/olist/correios/blob/5494d7457665fa9a8dffbffa976cdbd2885c54e4/correios/models/user.py#L379-L380 | ||||
googleads/google-ads-python | 2a1d6062221f6aad1992a6bcca0e7e4a93d2db86 | google/ads/googleads/v8/services/services/hotel_group_view_service/client.py | python | HotelGroupViewServiceClient.common_folder_path | (folder: str,) | return "folders/{folder}".format(folder=folder,) | Return a fully-qualified folder string. | Return a fully-qualified folder string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"folder",
"string",
"."
] | def common_folder_path(folder: str,) -> str:
"""Return a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,) | [
"def",
"common_folder_path",
"(",
"folder",
":",
"str",
",",
")",
"->",
"str",
":",
"return",
"\"folders/{folder}\"",
".",
"format",
"(",
"folder",
"=",
"folder",
",",
")"
] | https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/hotel_group_view_service/client.py#L192-L194 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/combinat/symmetric_group_algebra.py | python | SymmetricGroupAlgebra_n.monomial_from_smaller_permutation | (self, permutation) | return self.monomial(P(permutation)) | Convert ``permutation`` into a permutation, possibly extending it
to the appropriate size, and return the corresponding basis
element of ``self``.
EXAMPLES::
sage: QS5 = SymmetricGroupAlgebra(QQ, 5)
sage: QS5.monomial_from_smaller_permutation([])
[1, 2, 3, 4, 5]
sage: QS5.monomial_from_smaller_permutation(Permutation([3,1,2]))
[3, 1, 2, 4, 5]
sage: QS5.monomial_from_smaller_permutation([5,3,4,1,2])
[5, 3, 4, 1, 2]
sage: QS5.monomial_from_smaller_permutation(SymmetricGroup(2)((1,2)))
[2, 1, 3, 4, 5]
sage: QS5g = SymmetricGroup(5).algebra(QQ)
sage: QS5g.monomial_from_smaller_permutation([2,1])
(1,2)
TESTS::
sage: QS5.monomial_from_smaller_permutation([5,3,4,1,2]).parent()
Symmetric group algebra of order 5 over Rational Field | Convert ``permutation`` into a permutation, possibly extending it
to the appropriate size, and return the corresponding basis
element of ``self``. | [
"Convert",
"permutation",
"into",
"a",
"permutation",
"possibly",
"extending",
"it",
"to",
"the",
"appropriate",
"size",
"and",
"return",
"the",
"corresponding",
"basis",
"element",
"of",
"self",
"."
] | def monomial_from_smaller_permutation(self, permutation):
"""
Convert ``permutation`` into a permutation, possibly extending it
to the appropriate size, and return the corresponding basis
element of ``self``.
EXAMPLES::
sage: QS5 = SymmetricGroupAlgebra(QQ, 5)
sage: QS5.monomial_from_smaller_permutation([])
[1, 2, 3, 4, 5]
sage: QS5.monomial_from_smaller_permutation(Permutation([3,1,2]))
[3, 1, 2, 4, 5]
sage: QS5.monomial_from_smaller_permutation([5,3,4,1,2])
[5, 3, 4, 1, 2]
sage: QS5.monomial_from_smaller_permutation(SymmetricGroup(2)((1,2)))
[2, 1, 3, 4, 5]
sage: QS5g = SymmetricGroup(5).algebra(QQ)
sage: QS5g.monomial_from_smaller_permutation([2,1])
(1,2)
TESTS::
sage: QS5.monomial_from_smaller_permutation([5,3,4,1,2]).parent()
Symmetric group algebra of order 5 over Rational Field
"""
P = self.basis().keys()
return self.monomial(P(permutation)) | [
"def",
"monomial_from_smaller_permutation",
"(",
"self",
",",
"permutation",
")",
":",
"P",
"=",
"self",
".",
"basis",
"(",
")",
".",
"keys",
"(",
")",
"return",
"self",
".",
"monomial",
"(",
"P",
"(",
"permutation",
")",
")"
] | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/symmetric_group_algebra.py#L615-L643 | |
explosion/thinc | 95d418925b25277a92291005318710b86b2bbb41 | thinc/backends/ops.py | python | Ops.minibatch | (
self,
size: Union[int, Generator],
sequence: Batchable,
*,
shuffle: bool = False,
buffer: int = 1,
) | return SizedGenerator(_iter_items, len(sizes)) | Iterate slices from a sequence, optionally shuffled. Slices
may be either views or copies of the underlying data.
The `size` argument may be either an integer, or a sequence of integers.
If a sequence, a new size is drawn before every output.
If shuffle is True, shuffled batches are produced by first generating
an index array, shuffling it, and then using it to slice into the
sequence.
An internal queue of `buffer` items is accumulated before being each
output. Buffering is useful for some devices, to allow the
network to run asynchronously without blocking on every batch. | Iterate slices from a sequence, optionally shuffled. Slices
may be either views or copies of the underlying data. | [
"Iterate",
"slices",
"from",
"a",
"sequence",
"optionally",
"shuffled",
".",
"Slices",
"may",
"be",
"either",
"views",
"or",
"copies",
"of",
"the",
"underlying",
"data",
"."
] | def minibatch(
self,
size: Union[int, Generator],
sequence: Batchable,
*,
shuffle: bool = False,
buffer: int = 1,
) -> SizedGenerator:
"""Iterate slices from a sequence, optionally shuffled. Slices
may be either views or copies of the underlying data.
The `size` argument may be either an integer, or a sequence of integers.
If a sequence, a new size is drawn before every output.
If shuffle is True, shuffled batches are produced by first generating
an index array, shuffling it, and then using it to slice into the
sequence.
An internal queue of `buffer` items is accumulated before being each
output. Buffering is useful for some devices, to allow the
network to run asynchronously without blocking on every batch.
"""
if not hasattr(sequence, "__len__"):
err = f"Can't minibatch data. Expected sequence, got {type(sequence)}"
raise ValueError(err)
sizes = self._get_batch_sizes(
len(sequence), itertools.repeat(size) if isinstance(size, int) else size
)
indices = numpy.arange(len(sequence))
# This is a bit convoluted, but it's a time where convenience makes
# trickery worthwhile: instead of being an actual generator, we
# return our SizedGenerator object, which provides a __len__.
def _iter_items():
if shuffle:
numpy.random.shuffle(indices)
queue = []
i = 0
for size in sizes:
size = int(size)
queue.append(self._get_batch(sequence, indices[i : i + size]))
if len(queue) >= buffer:
yield from queue
queue = []
i += size
yield from queue
return SizedGenerator(_iter_items, len(sizes)) | [
"def",
"minibatch",
"(",
"self",
",",
"size",
":",
"Union",
"[",
"int",
",",
"Generator",
"]",
",",
"sequence",
":",
"Batchable",
",",
"*",
",",
"shuffle",
":",
"bool",
"=",
"False",
",",
"buffer",
":",
"int",
"=",
"1",
",",
")",
"->",
"SizedGenera... | https://github.com/explosion/thinc/blob/95d418925b25277a92291005318710b86b2bbb41/thinc/backends/ops.py#L40-L87 | |
aws/aws-cli | d697e0ed79fca0f853ce53efe1f83ee41a478134 | awscli/customizations/s3/utils.py | python | RequestParamsMapper.map_create_multipart_upload_params | (cls, request_params, cli_params) | Map CLI params to CreateMultipartUpload request params | Map CLI params to CreateMultipartUpload request params | [
"Map",
"CLI",
"params",
"to",
"CreateMultipartUpload",
"request",
"params"
] | def map_create_multipart_upload_params(cls, request_params, cli_params):
"""Map CLI params to CreateMultipartUpload request params"""
cls._set_general_object_params(request_params, cli_params)
cls._set_sse_request_params(request_params, cli_params)
cls._set_sse_c_request_params(request_params, cli_params)
cls._set_metadata_params(request_params, cli_params)
cls._set_request_payer_param(request_params, cli_params) | [
"def",
"map_create_multipart_upload_params",
"(",
"cls",
",",
"request_params",
",",
"cli_params",
")",
":",
"cls",
".",
"_set_general_object_params",
"(",
"request_params",
",",
"cli_params",
")",
"cls",
".",
"_set_sse_request_params",
"(",
"request_params",
",",
"cl... | https://github.com/aws/aws-cli/blob/d697e0ed79fca0f853ce53efe1f83ee41a478134/awscli/customizations/s3/utils.py#L503-L509 | ||
conan-io/conan | 28ec09f6cbf1d7e27ec27393fd7bbc74891e74a8 | conans/client/rest/client_routes.py | python | ClientV2Router.package_revisions | (self, pref) | return self.base_url + _format_pref(self.routes.package_revisions, pref) | get revisions for a package url | get revisions for a package url | [
"get",
"revisions",
"for",
"a",
"package",
"url"
] | def package_revisions(self, pref):
"""get revisions for a package url"""
return self.base_url + _format_pref(self.routes.package_revisions, pref) | [
"def",
"package_revisions",
"(",
"self",
",",
"pref",
")",
":",
"return",
"self",
".",
"base_url",
"+",
"_format_pref",
"(",
"self",
".",
"routes",
".",
"package_revisions",
",",
"pref",
")"
] | https://github.com/conan-io/conan/blob/28ec09f6cbf1d7e27ec27393fd7bbc74891e74a8/conans/client/rest/client_routes.py#L211-L213 | |
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/lib-python/3/encodings/bz2_codec.py | python | Codec.encode | (self, input, errors='strict') | return bz2_encode(input, errors) | [] | def encode(self, input, errors='strict'):
return bz2_encode(input, errors) | [
"def",
"encode",
"(",
"self",
",",
"input",
",",
"errors",
"=",
"'strict'",
")",
":",
"return",
"bz2_encode",
"(",
"input",
",",
"errors",
")"
] | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/encodings/bz2_codec.py#L24-L25 | |||
TesterlifeRaymond/doraemon | d5cb6e34bd5f2aa97273ce0c0c9303e32beaa333 | venv/lib/python3.6/site-packages/setuptools/launch.py | python | run | () | Run the script in sys.argv[1] as if it had
been invoked naturally. | Run the script in sys.argv[1] as if it had
been invoked naturally. | [
"Run",
"the",
"script",
"in",
"sys",
".",
"argv",
"[",
"1",
"]",
"as",
"if",
"it",
"had",
"been",
"invoked",
"naturally",
"."
] | def run():
"""
Run the script in sys.argv[1] as if it had
been invoked naturally.
"""
__builtins__
script_name = sys.argv[1]
namespace = dict(
__file__=script_name,
__name__='__main__',
__doc__=None,
)
sys.argv[:] = sys.argv[1:]
open_ = getattr(tokenize, 'open', open)
script = open_(script_name).read()
norm_script = script.replace('\\r\\n', '\\n')
code = compile(norm_script, script_name, 'exec')
exec(code, namespace) | [
"def",
"run",
"(",
")",
":",
"__builtins__",
"script_name",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"namespace",
"=",
"dict",
"(",
"__file__",
"=",
"script_name",
",",
"__name__",
"=",
"'__main__'",
",",
"__doc__",
"=",
"None",
",",
")",
"sys",
".",
... | https://github.com/TesterlifeRaymond/doraemon/blob/d5cb6e34bd5f2aa97273ce0c0c9303e32beaa333/venv/lib/python3.6/site-packages/setuptools/launch.py#L13-L31 | ||
thu-coai/ConvLab-2 | ad32b76022fa29cbc2f24cbefbb855b60492985e | convlab2/policy/hdsa/multiwoz/train_predictor.py | python | DataProcessor.get_train_examples | (self, data_dir) | Gets a collection of `InputExample`s for the train set. | Gets a collection of `InputExample`s for the train set. | [
"Gets",
"a",
"collection",
"of",
"InputExample",
"s",
"for",
"the",
"train",
"set",
"."
] | def get_train_examples(self, data_dir):
"""Gets a collection of `InputExample`s for the train set."""
raise NotImplementedError() | [
"def",
"get_train_examples",
"(",
"self",
",",
"data_dir",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/thu-coai/ConvLab-2/blob/ad32b76022fa29cbc2f24cbefbb855b60492985e/convlab2/policy/hdsa/multiwoz/train_predictor.py#L88-L90 | ||
sympy/sympy | d822fcba181155b85ff2b29fe525adbafb22b448 | sympy/combinatorics/prufer.py | python | Prufer.prev | (self, delta=1) | return Prufer.unrank(self.rank -delta, self.nodes) | Generates the Prufer sequence that is -delta before the current one.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
>>> a = Prufer([[0, 1], [1, 2], [2, 3], [1, 4]])
>>> a.rank
36
>>> b = a.prev()
>>> b
Prufer([1, 2, 0])
>>> b.rank
35
See Also
========
prufer_rank, rank, next, size | Generates the Prufer sequence that is -delta before the current one. | [
"Generates",
"the",
"Prufer",
"sequence",
"that",
"is",
"-",
"delta",
"before",
"the",
"current",
"one",
"."
] | def prev(self, delta=1):
"""Generates the Prufer sequence that is -delta before the current one.
Examples
========
>>> from sympy.combinatorics.prufer import Prufer
>>> a = Prufer([[0, 1], [1, 2], [2, 3], [1, 4]])
>>> a.rank
36
>>> b = a.prev()
>>> b
Prufer([1, 2, 0])
>>> b.rank
35
See Also
========
prufer_rank, rank, next, size
"""
return Prufer.unrank(self.rank -delta, self.nodes) | [
"def",
"prev",
"(",
"self",
",",
"delta",
"=",
"1",
")",
":",
"return",
"Prufer",
".",
"unrank",
"(",
"self",
".",
"rank",
"-",
"delta",
",",
"self",
".",
"nodes",
")"
] | https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/combinatorics/prufer.py#L414-L436 | |
Komodo/KomodoEdit | 61edab75dce2bdb03943b387b0608ea36f548e8e | src/codeintel/play/core.py | python | Rect.__ne__ | (*args, **kwargs) | return _core.Rect___ne__(*args, **kwargs) | __ne__(Rect rect) -> bool
Test for inequality. | __ne__(Rect rect) -> bool | [
"__ne__",
"(",
"Rect",
"rect",
")",
"-",
">",
"bool"
] | def __ne__(*args, **kwargs):
"""
__ne__(Rect rect) -> bool
Test for inequality.
"""
return _core.Rect___ne__(*args, **kwargs) | [
"def",
"__ne__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_core",
".",
"Rect___ne__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/src/codeintel/play/core.py#L1187-L1193 | |
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/CPython/27/Lib/plistlib.py | python | Plist.write | (self, pathOrFile) | Deprecated. Use the writePlist() function instead. | Deprecated. Use the writePlist() function instead. | [
"Deprecated",
".",
"Use",
"the",
"writePlist",
"()",
"function",
"instead",
"."
] | def write(self, pathOrFile):
"""Deprecated. Use the writePlist() function instead."""
writePlist(self, pathOrFile) | [
"def",
"write",
"(",
"self",
",",
"pathOrFile",
")",
":",
"writePlist",
"(",
"self",
",",
"pathOrFile",
")"
] | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/plistlib.py#L351-L353 | ||
twitter/zktraffic | 82db04d9aafa13f694d4f5c7265069db42c0307c | zktraffic/cli/printer.py | python | LatencyPrinter.reply_handler | (self, rep) | [] | def reply_handler(self, rep):
if not self._include_pings and rep.is_ping:
return
self._replies.append(rep)
self._seen_replies += 1 | [
"def",
"reply_handler",
"(",
"self",
",",
"rep",
")",
":",
"if",
"not",
"self",
".",
"_include_pings",
"and",
"rep",
".",
"is_ping",
":",
"return",
"self",
".",
"_replies",
".",
"append",
"(",
"rep",
")",
"self",
".",
"_seen_replies",
"+=",
"1"
] | https://github.com/twitter/zktraffic/blob/82db04d9aafa13f694d4f5c7265069db42c0307c/zktraffic/cli/printer.py#L424-L429 | ||||
baidu/DuReader | 43577e29435f5abcb7b02ce6a0019b3f42b1221d | ACL2019-KTNET/retrieve_concepts/tokenization_record/do_tokenization.py | python | _improve_entity_span | (doc_tokens, input_start, input_end, tokenizer,
orig_entity_text) | return (input_start, input_end) | Returns token-level tokenized entity spans that better match the annotated entity. | Returns token-level tokenized entity spans that better match the annotated entity. | [
"Returns",
"token",
"-",
"level",
"tokenized",
"entity",
"spans",
"that",
"better",
"match",
"the",
"annotated",
"entity",
"."
] | def _improve_entity_span(doc_tokens, input_start, input_end, tokenizer,
orig_entity_text):
"""Returns token-level tokenized entity spans that better match the annotated entity."""
tok_entity_text = " ".join(tokenizer.basic_tokenizer.tokenize(orig_entity_text))
for new_start in range(input_start, input_end + 1):
for new_end in range(input_end, new_start - 1, -1):
text_span = " ".join(doc_tokens[new_start:(new_end + 1)])
if text_span == tok_entity_text:
return (new_start, new_end)
return (input_start, input_end) | [
"def",
"_improve_entity_span",
"(",
"doc_tokens",
",",
"input_start",
",",
"input_end",
",",
"tokenizer",
",",
"orig_entity_text",
")",
":",
"tok_entity_text",
"=",
"\" \"",
".",
"join",
"(",
"tokenizer",
".",
"basic_tokenizer",
".",
"tokenize",
"(",
"orig_entity_... | https://github.com/baidu/DuReader/blob/43577e29435f5abcb7b02ce6a0019b3f42b1221d/ACL2019-KTNET/retrieve_concepts/tokenization_record/do_tokenization.py#L150-L161 | |
theotherp/nzbhydra | 4b03d7f769384b97dfc60dade4806c0fc987514e | libs/enum/__init__.py | python | _is_dunder | (name) | return (name[:2] == name[-2:] == '__' and
name[2:3] != '_' and
name[-3:-2] != '_' and
len(name) > 4) | Returns True if a __dunder__ name, False otherwise. | Returns True if a __dunder__ name, False otherwise. | [
"Returns",
"True",
"if",
"a",
"__dunder__",
"name",
"False",
"otherwise",
"."
] | def _is_dunder(name):
"""Returns True if a __dunder__ name, False otherwise."""
return (name[:2] == name[-2:] == '__' and
name[2:3] != '_' and
name[-3:-2] != '_' and
len(name) > 4) | [
"def",
"_is_dunder",
"(",
"name",
")",
":",
"return",
"(",
"name",
"[",
":",
"2",
"]",
"==",
"name",
"[",
"-",
"2",
":",
"]",
"==",
"'__'",
"and",
"name",
"[",
"2",
":",
"3",
"]",
"!=",
"'_'",
"and",
"name",
"[",
"-",
"3",
":",
"-",
"2",
... | https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/enum/__init__.py#L70-L75 | |
facebookresearch/Mask-Predict | 11c753526ebbbf5b946d1305a613b830f4f29232 | fairseq/data/iterators.py | python | EpochBatchIterator.state_dict | (self) | return {
'epoch': self.epoch,
'iterations_in_epoch': self.iterations_in_epoch,
} | Returns a dictionary containing a whole state of the iterator. | Returns a dictionary containing a whole state of the iterator. | [
"Returns",
"a",
"dictionary",
"containing",
"a",
"whole",
"state",
"of",
"the",
"iterator",
"."
] | def state_dict(self):
"""Returns a dictionary containing a whole state of the iterator."""
return {
'epoch': self.epoch,
'iterations_in_epoch': self.iterations_in_epoch,
} | [
"def",
"state_dict",
"(",
"self",
")",
":",
"return",
"{",
"'epoch'",
":",
"self",
".",
"epoch",
",",
"'iterations_in_epoch'",
":",
"self",
".",
"iterations_in_epoch",
",",
"}"
] | https://github.com/facebookresearch/Mask-Predict/blob/11c753526ebbbf5b946d1305a613b830f4f29232/fairseq/data/iterators.py#L199-L204 | |
Antergos/Cnchi | 13ac2209da9432d453e0097cf48a107640b563a9 | src/pages/user_info.py | python | UserInfo.show_password_toggled | (self, _widget) | show/hide user password | show/hide user password | [
"show",
"/",
"hide",
"user",
"password"
] | def show_password_toggled(self, _widget):
""" show/hide user password """
btn = self.gui.get_object('checkbutton_show_password')
shown = btn.get_active()
self.widgets['password']['entry'].set_visibility(shown)
self.widgets['verified_password']['entry'].set_visibility(shown) | [
"def",
"show_password_toggled",
"(",
"self",
",",
"_widget",
")",
":",
"btn",
"=",
"self",
".",
"gui",
".",
"get_object",
"(",
"'checkbutton_show_password'",
")",
"shown",
"=",
"btn",
".",
"get_active",
"(",
")",
"self",
".",
"widgets",
"[",
"'password'",
... | https://github.com/Antergos/Cnchi/blob/13ac2209da9432d453e0097cf48a107640b563a9/src/pages/user_info.py#L315-L320 | ||
aaronjanse/asciidots | 9c6a7d6a68c5e7870d574ab8ae94aa9ad7f53012 | dots/dot.py | python | Dot.simulate_tick | (self, run_until_waiting) | Update the dot to its next state.
:param bool run_until_waiting: if false, the dot will perform only one tick, else it will run untill waiting | Update the dot to its next state. | [
"Update",
"the",
"dot",
"to",
"its",
"next",
"state",
"."
] | def simulate_tick(self, run_until_waiting):
"""
Update the dot to its next state.
:param bool run_until_waiting: if false, the dot will perform only one tick, else it will run untill waiting
"""
past_locations = []
while True:
# we need to update the screen if we keep this dot running, nobody will ever do it otherwise
if run_until_waiting:
self.env.io.on_microtick(self)
# If it was already at this location, run someone else (prevent infinite loops)
if self.pos in past_locations:
return
past_locations.append(self.pos)
# If outside the map, he dies.
if not self.env.world.does_loc_exist(self.pos):
self.state = DeadState(self)
return
char = self.env.world.get_char_at(self.pos)
# update the dot
self.state = self.state.next(char)
self.state.run(char)
if self.state.is_dead():
return
if not self.env.world.does_loc_exist(self.pos):
self.state = DeadState(self)
return
if self.env.world.is_char_at(self.pos, ' ') and not isinstance(self.state, PrintState):
self.state = DeadState(self)
return
if self.state.isWaiting:
break
if not run_until_waiting:
break | [
"def",
"simulate_tick",
"(",
"self",
",",
"run_until_waiting",
")",
":",
"past_locations",
"=",
"[",
"]",
"while",
"True",
":",
"# we need to update the screen if we keep this dot running, nobody will ever do it otherwise",
"if",
"run_until_waiting",
":",
"self",
".",
"env"... | https://github.com/aaronjanse/asciidots/blob/9c6a7d6a68c5e7870d574ab8ae94aa9ad7f53012/dots/dot.py#L47-L93 | ||
AstroPrint/AstroBox | e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75 | src/astroprint/camera/v4l2/gstreamer/__init__.py | python | GStreamerManager._freeApPipeline | (self) | [] | def _freeApPipeline(self):
if self._apPipeline:
self._apPipeline.stop()
self._apPipeline = None | [
"def",
"_freeApPipeline",
"(",
"self",
")",
":",
"if",
"self",
".",
"_apPipeline",
":",
"self",
".",
"_apPipeline",
".",
"stop",
"(",
")",
"self",
".",
"_apPipeline",
"=",
"None"
] | https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/astroprint/camera/v4l2/gstreamer/__init__.py#L80-L83 | ||||
binaryage/drydrop | 2f27e15befd247255d89f9120eeee44851b82c4a | dryapp/jinja2/utils.py | python | LRUCache.__len__ | (self) | return len(self._mapping) | Return the current size of the cache. | Return the current size of the cache. | [
"Return",
"the",
"current",
"size",
"of",
"the",
"cache",
"."
] | def __len__(self):
"""Return the current size of the cache."""
return len(self._mapping) | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"_mapping",
")"
] | https://github.com/binaryage/drydrop/blob/2f27e15befd247255d89f9120eeee44851b82c4a/dryapp/jinja2/utils.py#L574-L576 | |
JacquesLucke/animation_nodes | b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1 | animation_nodes/sockets/struct.py | python | StructSocket.getDefaultValueCode | (cls) | return "ANStruct()" | [] | def getDefaultValueCode(cls):
return "ANStruct()" | [
"def",
"getDefaultValueCode",
"(",
"cls",
")",
":",
"return",
"\"ANStruct()\""
] | https://github.com/JacquesLucke/animation_nodes/blob/b1e3ace8dcb0a771fd882fc3ac4e490b009fa0d1/animation_nodes/sockets/struct.py#L18-L19 | |||
marinho/geraldo | 868ebdce67176d9b6205cddc92476f642c783fff | site/newsite/site-geraldo/django/contrib/sessions/backends/base.py | python | SessionBase.get_expiry_age | (self) | return delta.days * 86400 + delta.seconds | Get the number of seconds until the session expires. | Get the number of seconds until the session expires. | [
"Get",
"the",
"number",
"of",
"seconds",
"until",
"the",
"session",
"expires",
"."
] | def get_expiry_age(self):
"""Get the number of seconds until the session expires."""
expiry = self.get('_session_expiry')
if not expiry: # Checks both None and 0 cases
return settings.SESSION_COOKIE_AGE
if not isinstance(expiry, datetime):
return expiry
delta = expiry - datetime.now()
return delta.days * 86400 + delta.seconds | [
"def",
"get_expiry_age",
"(",
"self",
")",
":",
"expiry",
"=",
"self",
".",
"get",
"(",
"'_session_expiry'",
")",
"if",
"not",
"expiry",
":",
"# Checks both None and 0 cases",
"return",
"settings",
".",
"SESSION_COOKIE_AGE",
"if",
"not",
"isinstance",
"(",
"expi... | https://github.com/marinho/geraldo/blob/868ebdce67176d9b6205cddc92476f642c783fff/site/newsite/site-geraldo/django/contrib/sessions/backends/base.py#L177-L185 | |
EFForg/starttls-everywhere | 1ac62c425674e450ab9063be674ef80f54ed04c3 | tools/CheckSTARTTLS.py | python | valid_cert | (filename) | Return true if the certificate is valid.
Note: CApath must have hashed symlinks to the trust roots.
TODO: Include the -attime flag based on file modification time. | Return true if the certificate is valid. | [
"Return",
"true",
"if",
"the",
"certificate",
"is",
"valid",
"."
] | def valid_cert(filename):
"""Return true if the certificate is valid.
Note: CApath must have hashed symlinks to the trust roots.
TODO: Include the -attime flag based on file modification time."""
if open(filename).read().find("-----BEGIN CERTIFICATE-----") == -1:
return False
try:
# The file contains both the leaf cert and any intermediates, so we pass it
# as both the cert to validate and as the "untrusted" chain.
output = subprocess.check_output("""openssl verify -CApath /home/jsha/mozilla/ -purpose sslserver \
-untrusted "%s" \
"%s"
""" % (filename, filename), shell = True)
return True
except subprocess.CalledProcessError:
return False | [
"def",
"valid_cert",
"(",
"filename",
")",
":",
"if",
"open",
"(",
"filename",
")",
".",
"read",
"(",
")",
".",
"find",
"(",
"\"-----BEGIN CERTIFICATE-----\"",
")",
"==",
"-",
"1",
":",
"return",
"False",
"try",
":",
"# The file contains both the leaf cert and... | https://github.com/EFForg/starttls-everywhere/blob/1ac62c425674e450ab9063be674ef80f54ed04c3/tools/CheckSTARTTLS.py#L70-L87 | ||
etactica/mqtt-malaria | 559930d894fb49e5e444e62788e1d9f1a817ac03 | fabfile.py | python | _presplit | (keyfile) | magically split the file into ram and tack it into the fab.env.... | magically split the file into ram and tack it into the fab.env.... | [
"magically",
"split",
"the",
"file",
"into",
"ram",
"and",
"tack",
"it",
"into",
"the",
"fab",
".",
"env",
"...."
] | def _presplit(keyfile):
"""magically split the file into ram and tack it into the fab.env...."""
with open(keyfile, "r") as f:
inputs = f.readlines()
count = len(fab.env.hosts)
fab.env.malaria_split_keys = dict(zip(fab.env.hosts,
keygen.chunks(inputs, count))) | [
"def",
"_presplit",
"(",
"keyfile",
")",
":",
"with",
"open",
"(",
"keyfile",
",",
"\"r\"",
")",
"as",
"f",
":",
"inputs",
"=",
"f",
".",
"readlines",
"(",
")",
"count",
"=",
"len",
"(",
"fab",
".",
"env",
".",
"hosts",
")",
"fab",
".",
"env",
... | https://github.com/etactica/mqtt-malaria/blob/559930d894fb49e5e444e62788e1d9f1a817ac03/fabfile.py#L329-L335 | ||
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/combinat/k_regular_sequence.py | python | RecurrenceParser.ind | (self, M, m, ll, uu) | return ind | r"""
Determine the index operator corresponding to the recursive
sequence as defined in [HKL2021]_.
INPUT:
- ``M``, ``m`` -- parameters of the recursive sequences,
see [HKL2021]_, Definition 3.1
- ``ll``, ``uu`` -- parameters of the resulting linear representation,
see [HKL2021]_, Theorem A
OUTPUT:
A dictionary which maps both row numbers to subsequence parameters and
vice versa, i.e.,
- ``ind[i]`` -- a pair ``(j, d)`` representing the sequence `x(k^j n + d)`
in the `i`-th component (0-based) of the resulting linear representation,
- ``ind[(j, d)]`` -- the (0-based) row number of the sequence
`x(k^j n + d)` in the linear representation.
EXAMPLES::
sage: from sage.combinat.k_regular_sequence import RecurrenceParser
sage: RP = RecurrenceParser(2, ZZ)
sage: RP.ind(3, 1, -3, 3)
{(0, 0): 0, (1, -1): 3, (1, -2): 2, (1, -3): 1,
(1, 0): 4, (1, 1): 5, (1, 2): 6, (1, 3): 7, (2, -1): 10,
(2, -2): 9, (2, -3): 8, (2, 0): 11, (2, 1): 12, (2, 2): 13,
(2, 3): 14, (2, 4): 15, (2, 5): 16, 0: (0, 0), 1: (1, -3),
10: (2, -1), 11: (2, 0), 12: (2, 1), 13: (2, 2), 14: (2, 3),
15: (2, 4), 16: (2, 5), 2: (1, -2), 3: (1, -1), 4: (1, 0),
5: (1, 1), 6: (1, 2), 7: (1, 3), 8: (2, -3), 9: (2, -2)}
.. SEEALSO::
:meth:`kRegularSequenceSpace.from_recurrence` | r"""
Determine the index operator corresponding to the recursive
sequence as defined in [HKL2021]_. | [
"r",
"Determine",
"the",
"index",
"operator",
"corresponding",
"to",
"the",
"recursive",
"sequence",
"as",
"defined",
"in",
"[",
"HKL2021",
"]",
"_",
"."
] | def ind(self, M, m, ll, uu):
r"""
Determine the index operator corresponding to the recursive
sequence as defined in [HKL2021]_.
INPUT:
- ``M``, ``m`` -- parameters of the recursive sequences,
see [HKL2021]_, Definition 3.1
- ``ll``, ``uu`` -- parameters of the resulting linear representation,
see [HKL2021]_, Theorem A
OUTPUT:
A dictionary which maps both row numbers to subsequence parameters and
vice versa, i.e.,
- ``ind[i]`` -- a pair ``(j, d)`` representing the sequence `x(k^j n + d)`
in the `i`-th component (0-based) of the resulting linear representation,
- ``ind[(j, d)]`` -- the (0-based) row number of the sequence
`x(k^j n + d)` in the linear representation.
EXAMPLES::
sage: from sage.combinat.k_regular_sequence import RecurrenceParser
sage: RP = RecurrenceParser(2, ZZ)
sage: RP.ind(3, 1, -3, 3)
{(0, 0): 0, (1, -1): 3, (1, -2): 2, (1, -3): 1,
(1, 0): 4, (1, 1): 5, (1, 2): 6, (1, 3): 7, (2, -1): 10,
(2, -2): 9, (2, -3): 8, (2, 0): 11, (2, 1): 12, (2, 2): 13,
(2, 3): 14, (2, 4): 15, (2, 5): 16, 0: (0, 0), 1: (1, -3),
10: (2, -1), 11: (2, 0), 12: (2, 1), 13: (2, 2), 14: (2, 3),
15: (2, 4), 16: (2, 5), 2: (1, -2), 3: (1, -1), 4: (1, 0),
5: (1, 1), 6: (1, 2), 7: (1, 3), 8: (2, -3), 9: (2, -2)}
.. SEEALSO::
:meth:`kRegularSequenceSpace.from_recurrence`
"""
from sage.arith.srange import srange
k = self.k
ind = {}
pos = 0
for j in srange(m):
for d in srange(k**j):
ind.update({(j, d): pos, pos: (j, d)})
pos += 1
for j in srange(m, M):
for d in srange(ll, k**j - k**m + uu + 1):
ind.update({(j, d): pos, pos: (j, d)})
pos += 1
return ind | [
"def",
"ind",
"(",
"self",
",",
"M",
",",
"m",
",",
"ll",
",",
"uu",
")",
":",
"from",
"sage",
".",
"arith",
".",
"srange",
"import",
"srange",
"k",
"=",
"self",
".",
"k",
"ind",
"=",
"{",
"}",
"pos",
"=",
"0",
"for",
"j",
"in",
"srange",
"... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/k_regular_sequence.py#L1463-L1519 | |
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_objectvalidator.py | python | Yedit.update | (self, path, value, index=None, curr_value=None) | return (False, self.yaml_dict) | put path, value into a dict | put path, value into a dict | [
"put",
"path",
"value",
"into",
"a",
"dict"
] | def update(self, path, value, index=None, curr_value=None):
''' put path, value into a dict '''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if isinstance(entry, dict):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
if not isinstance(value, dict):
raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' +
'value=[{}] type=[{}]'.format(value, type(value)))
entry.update(value)
return (True, self.yaml_dict)
elif isinstance(entry, list):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
ind = None
if curr_value:
try:
ind = entry.index(curr_value)
except ValueError:
return (False, self.yaml_dict)
elif index is not None:
ind = index
if ind is not None and entry[ind] != value:
entry[ind] = value
return (True, self.yaml_dict)
# see if it exists in the list
try:
ind = entry.index(value)
except ValueError:
# doesn't exist, append it
entry.append(value)
return (True, self.yaml_dict)
# already exists, return
if ind is not None:
return (False, self.yaml_dict)
return (False, self.yaml_dict) | [
"def",
"update",
"(",
"self",
",",
"path",
",",
"value",
",",
"index",
"=",
"None",
",",
"curr_value",
"=",
"None",
")",
":",
"try",
":",
"entry",
"=",
"Yedit",
".",
"get_entry",
"(",
"self",
".",
"yaml_dict",
",",
"path",
",",
"self",
".",
"separa... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_objectvalidator.py#L493-L538 | |
numba/numba | bf480b9e0da858a65508c2b17759a72ee6a44c51 | numba/cuda/simulator/cudadrv/devicearray.py | python | FakeCUDAArray.__gt__ | (self, other) | return FakeCUDAArray(self._ary > other) | [] | def __gt__(self, other):
return FakeCUDAArray(self._ary > other) | [
"def",
"__gt__",
"(",
"self",
",",
"other",
")",
":",
"return",
"FakeCUDAArray",
"(",
"self",
".",
"_ary",
">",
"other",
")"
] | https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/cuda/simulator/cudadrv/devicearray.py#L192-L193 | |||
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/stringprep.py | python | in_table_d1 | (code) | return unicodedata.bidirectional(code) in ("R","AL") | [] | def in_table_d1(code):
return unicodedata.bidirectional(code) in ("R","AL") | [
"def",
"in_table_d1",
"(",
"code",
")",
":",
"return",
"unicodedata",
".",
"bidirectional",
"(",
"code",
")",
"in",
"(",
"\"R\"",
",",
"\"AL\"",
")"
] | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/stringprep.py#L267-L268 | |||
kubernetes-client/python | 47b9da9de2d02b2b7a34fbe05afb44afd130d73a | kubernetes/client/models/v1_daemon_endpoint.py | python | V1DaemonEndpoint.__init__ | (self, port=None, local_vars_configuration=None) | V1DaemonEndpoint - a model defined in OpenAPI | V1DaemonEndpoint - a model defined in OpenAPI | [
"V1DaemonEndpoint",
"-",
"a",
"model",
"defined",
"in",
"OpenAPI"
] | def __init__(self, port=None, local_vars_configuration=None): # noqa: E501
"""V1DaemonEndpoint - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._port = None
self.discriminator = None
self.port = port | [
"def",
"__init__",
"(",
"self",
",",
"port",
"=",
"None",
",",
"local_vars_configuration",
"=",
"None",
")",
":",
"# noqa: E501",
"# noqa: E501",
"if",
"local_vars_configuration",
"is",
"None",
":",
"local_vars_configuration",
"=",
"Configuration",
"(",
")",
"self... | https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_daemon_endpoint.py#L43-L52 | ||
python-telegram-bot/python-telegram-bot | ade1529986f5b6d394a65372d6a27045a70725b2 | examples/inlinekeyboard.py | python | button | (update: Update, context: CallbackContext) | Parses the CallbackQuery and updates the message text. | Parses the CallbackQuery and updates the message text. | [
"Parses",
"the",
"CallbackQuery",
"and",
"updates",
"the",
"message",
"text",
"."
] | def button(update: Update, context: CallbackContext) -> None:
"""Parses the CallbackQuery and updates the message text."""
query = update.callback_query
# CallbackQueries need to be answered, even if no notification to the user is needed
# Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
query.answer()
query.edit_message_text(text=f"Selected option: {query.data}") | [
"def",
"button",
"(",
"update",
":",
"Update",
",",
"context",
":",
"CallbackContext",
")",
"->",
"None",
":",
"query",
"=",
"update",
".",
"callback_query",
"# CallbackQueries need to be answered, even if no notification to the user is needed",
"# Some clients may have troub... | https://github.com/python-telegram-bot/python-telegram-bot/blob/ade1529986f5b6d394a65372d6a27045a70725b2/examples/inlinekeyboard.py#L35-L43 | ||
POSTECH-CVLab/PyTorch-StudioGAN | bebb33f612759b86a224392f6fe941d0cc81d3c4 | src/models/big_resnet.py | python | GenBlock.__init__ | (self, in_channels, out_channels, g_cond_mtd, hier_z_dim, MODULES) | [] | def __init__(self, in_channels, out_channels, g_cond_mtd, hier_z_dim, MODULES):
super(GenBlock, self).__init__()
self.g_cond_mtd = g_cond_mtd
if self.g_cond_mtd == "W/O":
self.bn1 = MODULES.g_bn(in_features=in_channels)
self.bn2 = MODULES.g_bn(in_features=out_channels)
elif self.g_cond_mtd == "cBN":
self.bn1 = MODULES.g_bn(hier_z_dim, in_channels, MODULES)
self.bn2 = MODULES.g_bn(hier_z_dim, out_channels, MODULES)
else:
raise NotImplementedError
self.activation = MODULES.g_act_fn
self.conv2d0 = MODULES.g_conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0)
self.conv2d1 = MODULES.g_conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1)
self.conv2d2 = MODULES.g_conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1) | [
"def",
"__init__",
"(",
"self",
",",
"in_channels",
",",
"out_channels",
",",
"g_cond_mtd",
",",
"hier_z_dim",
",",
"MODULES",
")",
":",
"super",
"(",
"GenBlock",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"g_cond_mtd",
"=",
"g_cond_mtd",
... | https://github.com/POSTECH-CVLab/PyTorch-StudioGAN/blob/bebb33f612759b86a224392f6fe941d0cc81d3c4/src/models/big_resnet.py#L16-L32 | ||||
deanishe/alfred-fakeum | 12a7e64d9c099c0f11416ee99fae064d6360aab2 | src/libs/faker/providers/misc/__init__.py | python | Provider.md5 | (self, raw_output=False) | return res.hexdigest() | Calculates the md5 hash of a given string
:example 'cfcd208495d565ef66e7dff9f98764da' | Calculates the md5 hash of a given string
:example 'cfcd208495d565ef66e7dff9f98764da' | [
"Calculates",
"the",
"md5",
"hash",
"of",
"a",
"given",
"string",
":",
"example",
"cfcd208495d565ef66e7dff9f98764da"
] | def md5(self, raw_output=False):
"""
Calculates the md5 hash of a given string
:example 'cfcd208495d565ef66e7dff9f98764da'
"""
res = hashlib.md5(str(self.generator.random.random()).encode('utf-8'))
if raw_output:
return res.digest()
return res.hexdigest() | [
"def",
"md5",
"(",
"self",
",",
"raw_output",
"=",
"False",
")",
":",
"res",
"=",
"hashlib",
".",
"md5",
"(",
"str",
"(",
"self",
".",
"generator",
".",
"random",
".",
"random",
"(",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"if",
"raw_o... | https://github.com/deanishe/alfred-fakeum/blob/12a7e64d9c099c0f11416ee99fae064d6360aab2/src/libs/faker/providers/misc/__init__.py#L31-L39 | |
tahoe-lafs/tahoe-lafs | 766a53b5208c03c45ca0a98e97eee76870276aa1 | src/allmydata/util/deferredutil.py | python | _with_log | (op, res) | The default behaviour on firing an already-fired Deferred is unhelpful for
debugging, because the AlreadyCalledError can easily get lost or be raised
in a context that results in a different error. So make sure it is logged
(for the abstractions defined here). If we are in a test, log.err will cause
the test to fail. | The default behaviour on firing an already-fired Deferred is unhelpful for
debugging, because the AlreadyCalledError can easily get lost or be raised
in a context that results in a different error. So make sure it is logged
(for the abstractions defined here). If we are in a test, log.err will cause
the test to fail. | [
"The",
"default",
"behaviour",
"on",
"firing",
"an",
"already",
"-",
"fired",
"Deferred",
"is",
"unhelpful",
"for",
"debugging",
"because",
"the",
"AlreadyCalledError",
"can",
"easily",
"get",
"lost",
"or",
"be",
"raised",
"in",
"a",
"context",
"that",
"result... | def _with_log(op, res):
"""
The default behaviour on firing an already-fired Deferred is unhelpful for
debugging, because the AlreadyCalledError can easily get lost or be raised
in a context that results in a different error. So make sure it is logged
(for the abstractions defined here). If we are in a test, log.err will cause
the test to fail.
"""
try:
op(res)
except defer.AlreadyCalledError as e:
log.err(e, op=repr(op), level=log.WEIRD) | [
"def",
"_with_log",
"(",
"op",
",",
"res",
")",
":",
"try",
":",
"op",
"(",
"res",
")",
"except",
"defer",
".",
"AlreadyCalledError",
"as",
"e",
":",
"log",
".",
"err",
"(",
"e",
",",
"op",
"=",
"repr",
"(",
"op",
")",
",",
"level",
"=",
"log",... | https://github.com/tahoe-lafs/tahoe-lafs/blob/766a53b5208c03c45ca0a98e97eee76870276aa1/src/allmydata/util/deferredutil.py#L101-L112 | ||
douban/graph-index | cc60ac25edf167efb768ee9b93eaf4b9523671e5 | bottle.py | python | BaseResponse.iter_headers | (self) | return self.headerlist | Yield (header, value) tuples, skipping headers that are not
allowed with the current response status code. | Yield (header, value) tuples, skipping headers that are not
allowed with the current response status code. | [
"Yield",
"(",
"header",
"value",
")",
"tuples",
"skipping",
"headers",
"that",
"are",
"not",
"allowed",
"with",
"the",
"current",
"response",
"status",
"code",
"."
] | def iter_headers(self):
''' Yield (header, value) tuples, skipping headers that are not
allowed with the current response status code. '''
return self.headerlist | [
"def",
"iter_headers",
"(",
"self",
")",
":",
"return",
"self",
".",
"headerlist"
] | https://github.com/douban/graph-index/blob/cc60ac25edf167efb768ee9b93eaf4b9523671e5/bottle.py#L1370-L1373 | |
open-mmlab/mmdetection3d | c7272063e818bcf33aebc498a017a95c8d065143 | tools/misc/browse_dataset.py | python | to_depth_mode | (points, bboxes) | return points, bboxes | Convert points and bboxes to Depth Coord and Depth Box mode. | Convert points and bboxes to Depth Coord and Depth Box mode. | [
"Convert",
"points",
"and",
"bboxes",
"to",
"Depth",
"Coord",
"and",
"Depth",
"Box",
"mode",
"."
] | def to_depth_mode(points, bboxes):
"""Convert points and bboxes to Depth Coord and Depth Box mode."""
if points is not None:
points = Coord3DMode.convert_point(points.copy(), Coord3DMode.LIDAR,
Coord3DMode.DEPTH)
if bboxes is not None:
bboxes = Box3DMode.convert(bboxes.clone(), Box3DMode.LIDAR,
Box3DMode.DEPTH)
return points, bboxes | [
"def",
"to_depth_mode",
"(",
"points",
",",
"bboxes",
")",
":",
"if",
"points",
"is",
"not",
"None",
":",
"points",
"=",
"Coord3DMode",
".",
"convert_point",
"(",
"points",
".",
"copy",
"(",
")",
",",
"Coord3DMode",
".",
"LIDAR",
",",
"Coord3DMode",
".",... | https://github.com/open-mmlab/mmdetection3d/blob/c7272063e818bcf33aebc498a017a95c8d065143/tools/misc/browse_dataset.py#L75-L83 | |
OpenAgricultureFoundation/openag-device-software | a51d2de399c0a6781ae51d0dcfaae1583d75f346 | app/models.py | python | CultivationMethodModel.save | (self, *args: Any, **kwargs: Any) | Extracts uuid and name from json on save. | Extracts uuid and name from json on save. | [
"Extracts",
"uuid",
"and",
"name",
"from",
"json",
"on",
"save",
"."
] | def save(self, *args: Any, **kwargs: Any) -> None:
""" Extracts uuid and name from json on save. """
dict_ = json_.loads(self.json)
self.uuid = dict_["uuid"]
self.name = dict_["name"]
super(CultivationMethodModel, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"dict_",
"=",
"json_",
".",
"loads",
"(",
"self",
".",
"json",
")",
"self",
".",
"uuid",
"=",
"dict_",
"[",
"\"uuid\"",
"]",
... | https://github.com/OpenAgricultureFoundation/openag-device-software/blob/a51d2de399c0a6781ae51d0dcfaae1583d75f346/app/models.py#L161-L166 | ||
yt-project/yt | dc7b24f9b266703db4c843e329c6c8644d47b824 | yt/data_objects/construction_data_containers.py | python | YTCoveringGrid.to_fits_data | (self, fields, length_unit=None) | return fid | r"""Export a set of gridded fields to a FITS file.
This will export a set of FITS images of either the fields specified
or all the fields already in the object.
Parameters
----------
fields : list of strings
These fields will be pixelized and output. If "None", the keys of the
FRB will be used.
length_unit : string, optional
the length units that the coordinates are written in. The default
is to use the default length unit of the dataset. | r"""Export a set of gridded fields to a FITS file. | [
"r",
"Export",
"a",
"set",
"of",
"gridded",
"fields",
"to",
"a",
"FITS",
"file",
"."
] | def to_fits_data(self, fields, length_unit=None):
r"""Export a set of gridded fields to a FITS file.
This will export a set of FITS images of either the fields specified
or all the fields already in the object.
Parameters
----------
fields : list of strings
These fields will be pixelized and output. If "None", the keys of the
FRB will be used.
length_unit : string, optional
the length units that the coordinates are written in. The default
is to use the default length unit of the dataset.
"""
from yt.visualization.fits_image import FITSImageData
if length_unit is None:
length_unit = self.ds.length_unit
fields = list(iter_fields(fields))
fid = FITSImageData(self, fields, length_unit=length_unit)
return fid | [
"def",
"to_fits_data",
"(",
"self",
",",
"fields",
",",
"length_unit",
"=",
"None",
")",
":",
"from",
"yt",
".",
"visualization",
".",
"fits_image",
"import",
"FITSImageData",
"if",
"length_unit",
"is",
"None",
":",
"length_unit",
"=",
"self",
".",
"ds",
"... | https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/yt/data_objects/construction_data_containers.py#L1143-L1164 | |
inkandswitch/livebook | 93c8d467734787366ad084fc3566bf5cbe249c51 | public/pypyjs/modules/zipfile.py | python | ZipFile.write | (self, filename, arcname=None, compress_type=None) | Put the bytes from filename into the archive under the name
arcname. | Put the bytes from filename into the archive under the name
arcname. | [
"Put",
"the",
"bytes",
"from",
"filename",
"into",
"the",
"archive",
"under",
"the",
"name",
"arcname",
"."
] | def write(self, filename, arcname=None, compress_type=None):
"""Put the bytes from filename into the archive under the name
arcname."""
if not self.fp:
raise RuntimeError(
"Attempt to write to ZIP archive that was already closed")
st = os.stat(filename)
isdir = stat.S_ISDIR(st.st_mode)
mtime = time.localtime(st.st_mtime)
date_time = mtime[0:6]
# Create ZipInfo instance to store file information
if arcname is None:
arcname = filename
arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
while arcname[0] in (os.sep, os.altsep):
arcname = arcname[1:]
if isdir:
arcname += '/'
zinfo = ZipInfo(arcname, date_time)
zinfo.external_attr = (st[0] & 0xFFFF) << 16L # Unix attributes
if compress_type is None:
zinfo.compress_type = self.compression
else:
zinfo.compress_type = compress_type
zinfo.file_size = st.st_size
zinfo.flag_bits = 0x00
zinfo.header_offset = self.fp.tell() # Start of header bytes
self._writecheck(zinfo)
self._didModify = True
if isdir:
zinfo.file_size = 0
zinfo.compress_size = 0
zinfo.CRC = 0
zinfo.external_attr |= 0x10 # MS-DOS directory flag
self.filelist.append(zinfo)
self.NameToInfo[zinfo.filename] = zinfo
self.fp.write(zinfo.FileHeader(False))
return
with open(filename, "rb") as fp:
# Must overwrite CRC and sizes with correct data later
zinfo.CRC = CRC = 0
zinfo.compress_size = compress_size = 0
# Compressed size can be larger than uncompressed size
zip64 = self._allowZip64 and \
zinfo.file_size * 1.05 > ZIP64_LIMIT
self.fp.write(zinfo.FileHeader(zip64))
if zinfo.compress_type == ZIP_DEFLATED:
cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
zlib.DEFLATED, -15)
else:
cmpr = None
file_size = 0
while 1:
buf = fp.read(1024 * 8)
if not buf:
break
file_size = file_size + len(buf)
CRC = crc32(buf, CRC) & 0xffffffff
if cmpr:
buf = cmpr.compress(buf)
compress_size = compress_size + len(buf)
self.fp.write(buf)
if cmpr:
buf = cmpr.flush()
compress_size = compress_size + len(buf)
self.fp.write(buf)
zinfo.compress_size = compress_size
else:
zinfo.compress_size = file_size
zinfo.CRC = CRC
zinfo.file_size = file_size
if not zip64 and self._allowZip64:
if file_size > ZIP64_LIMIT:
raise RuntimeError('File size has increased during compressing')
if compress_size > ZIP64_LIMIT:
raise RuntimeError('Compressed size larger than uncompressed size')
# Seek backwards and write file header (which will now include
# correct CRC and file sizes)
position = self.fp.tell() # Preserve current position in file
self.fp.seek(zinfo.header_offset, 0)
self.fp.write(zinfo.FileHeader(zip64))
self.fp.seek(position, 0)
self.filelist.append(zinfo)
self.NameToInfo[zinfo.filename] = zinfo | [
"def",
"write",
"(",
"self",
",",
"filename",
",",
"arcname",
"=",
"None",
",",
"compress_type",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"fp",
":",
"raise",
"RuntimeError",
"(",
"\"Attempt to write to ZIP archive that was already closed\"",
")",
"st",
... | https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/zipfile.py#L1117-L1205 | ||
qLab/qLib | a34f45d22fe7315991bb822824c035fbc9a2a5e8 | scripts/python/qlibmenutools.py | python | select_target_nodes | (kwargs) | . | . | [
"."
] | def select_target_nodes(kwargs):
""".
"""
parms = get_all_parms(kwargs)
for parm in parms:
nodes = parm.node().glob(parm.evalAsString())
for node in nodes:
node.setSelected(True) | [
"def",
"select_target_nodes",
"(",
"kwargs",
")",
":",
"parms",
"=",
"get_all_parms",
"(",
"kwargs",
")",
"for",
"parm",
"in",
"parms",
":",
"nodes",
"=",
"parm",
".",
"node",
"(",
")",
".",
"glob",
"(",
"parm",
".",
"evalAsString",
"(",
")",
")",
"f... | https://github.com/qLab/qLib/blob/a34f45d22fe7315991bb822824c035fbc9a2a5e8/scripts/python/qlibmenutools.py#L118-L125 | ||
collinsctk/PyQYT | 7af3673955f94ff1b2df2f94220cd2dab2e252af | ExtentionPackages/tornado/log.py | python | enable_pretty_logging | (options=None, logger=None) | Turns on formatted logging output as configured.
This is called automatically by `tornado.options.parse_command_line`
and `tornado.options.parse_config_file`. | Turns on formatted logging output as configured. | [
"Turns",
"on",
"formatted",
"logging",
"output",
"as",
"configured",
"."
] | def enable_pretty_logging(options=None, logger=None):
"""Turns on formatted logging output as configured.
This is called automatically by `tornado.options.parse_command_line`
and `tornado.options.parse_config_file`.
"""
if options is None:
from tornado.options import options
if options.logging is None or options.logging.lower() == 'none':
return
if logger is None:
logger = logging.getLogger()
logger.setLevel(getattr(logging, options.logging.upper()))
if options.log_file_prefix:
rotate_mode = options.log_rotate_mode
if rotate_mode == 'size':
channel = logging.handlers.RotatingFileHandler(
filename=options.log_file_prefix,
maxBytes=options.log_file_max_size,
backupCount=options.log_file_num_backups)
elif rotate_mode == 'time':
channel = logging.handlers.TimedRotatingFileHandler(
filename=options.log_file_prefix,
when=options.log_rotate_when,
interval=options.log_rotate_interval,
backupCount=options.log_file_num_backups)
else:
error_message = 'The value of log_rotate_mode option should be ' +\
'"size" or "time", not "%s".' % rotate_mode
raise ValueError(error_message)
channel.setFormatter(LogFormatter(color=False))
logger.addHandler(channel)
if (options.log_to_stderr or
(options.log_to_stderr is None and not logger.handlers)):
# Set up color if we are in a tty and curses is installed
channel = logging.StreamHandler()
channel.setFormatter(LogFormatter())
logger.addHandler(channel) | [
"def",
"enable_pretty_logging",
"(",
"options",
"=",
"None",
",",
"logger",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"from",
"tornado",
".",
"options",
"import",
"options",
"if",
"options",
".",
"logging",
"is",
"None",
"or",
"options",
... | https://github.com/collinsctk/PyQYT/blob/7af3673955f94ff1b2df2f94220cd2dab2e252af/ExtentionPackages/tornado/log.py#L179-L217 | ||
OpenEndedGroup/Field | 4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c | Contents/lib/python/urllib.py | python | splittag | (url) | return url, None | splittag('/path#tag') --> '/path', 'tag'. | splittag('/path#tag') --> '/path', 'tag'. | [
"splittag",
"(",
"/",
"path#tag",
")",
"--",
">",
"/",
"path",
"tag",
"."
] | def splittag(url):
"""splittag('/path#tag') --> '/path', 'tag'."""
global _tagprog
if _tagprog is None:
import re
_tagprog = re.compile('^(.*)#([^#]*)$')
match = _tagprog.match(url)
if match: return match.group(1, 2)
return url, None | [
"def",
"splittag",
"(",
"url",
")",
":",
"global",
"_tagprog",
"if",
"_tagprog",
"is",
"None",
":",
"import",
"re",
"_tagprog",
"=",
"re",
".",
"compile",
"(",
"'^(.*)#([^#]*)$'",
")",
"match",
"=",
"_tagprog",
".",
"match",
"(",
"url",
")",
"if",
"mat... | https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/urllib.py#L1113-L1122 | |
natashamjaques/neural_chat | ddb977bb4602a67c460d02231e7bbf7b2cb49a97 | ParlAI/parlai/mturk/tasks/light/light_chats/graph.py | python | Graph.add_edge | (
self,
id1,
edge,
id2,
edge_label=None,
locked_with=None,
edge_desc=None,
full_label=False,
) | Add an edge of the given type from id1 to id2. Optionally can set
a label for that edge | Add an edge of the given type from id1 to id2. Optionally can set
a label for that edge | [
"Add",
"an",
"edge",
"of",
"the",
"given",
"type",
"from",
"id1",
"to",
"id2",
".",
"Optionally",
"can",
"set",
"a",
"label",
"for",
"that",
"edge"
] | def add_edge(
self,
id1,
edge,
id2,
edge_label=None,
locked_with=None,
edge_desc=None,
full_label=False,
):
"""Add an edge of the given type from id1 to id2. Optionally can set
a label for that edge
"""
if edge_desc is None:
edge_desc = self.get_props_from_either(id2, id1, 'path_desc')[0]
if (edge, id2) not in self._node_to_edges[id1]:
self._node_to_edges[id1][(edge, id2)] = {
'label': edge_label,
'examine_desc': edge_desc,
# TODO get these from the lock or something idk
'locked_desc': edge_desc,
'unlocked_desc': edge_desc,
'locked_with': locked_with,
'is_locked': False,
'full_label': full_label,
} | [
"def",
"add_edge",
"(",
"self",
",",
"id1",
",",
"edge",
",",
"id2",
",",
"edge_label",
"=",
"None",
",",
"locked_with",
"=",
"None",
",",
"edge_desc",
"=",
"None",
",",
"full_label",
"=",
"False",
",",
")",
":",
"if",
"edge_desc",
"is",
"None",
":",... | https://github.com/natashamjaques/neural_chat/blob/ddb977bb4602a67c460d02231e7bbf7b2cb49a97/ParlAI/parlai/mturk/tasks/light/light_chats/graph.py#L3004-L3029 | ||
Abjad/abjad | d0646dfbe83db3dc5ab268f76a0950712b87b7fd | abjad/duration.py | python | Duration.__reduce_ex__ | (self, protocol) | return type(self), (self.numerator, self.denominator) | Documentation required. | Documentation required. | [
"Documentation",
"required",
"."
] | def __reduce_ex__(self, protocol):
"""
Documentation required.
"""
return type(self), (self.numerator, self.denominator) | [
"def",
"__reduce_ex__",
"(",
"self",
",",
"protocol",
")",
":",
"return",
"type",
"(",
"self",
")",
",",
"(",
"self",
".",
"numerator",
",",
"self",
".",
"denominator",
")"
] | https://github.com/Abjad/abjad/blob/d0646dfbe83db3dc5ab268f76a0950712b87b7fd/abjad/duration.py#L391-L395 | |
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_adm_policy_user.py | python | SecurityContextConstraints.remove_user | (self, inc_user) | return True | remove a user | remove a user | [
"remove",
"a",
"user"
] | def remove_user(self, inc_user):
''' remove a user '''
try:
self.users.remove(inc_user)
except ValueError as _:
return False
return True | [
"def",
"remove_user",
"(",
"self",
",",
"inc_user",
")",
":",
"try",
":",
"self",
".",
"users",
".",
"remove",
"(",
"inc_user",
")",
"except",
"ValueError",
"as",
"_",
":",
"return",
"False",
"return",
"True"
] | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_adm_policy_user.py#L1928-L1935 | |
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/vpc/v20170312/models.py | python | DescribeNetworkInterfaceLimitResponse.__init__ | (self) | r"""
:param EniQuantity: 标准型弹性网卡配额
:type EniQuantity: int
:param EniPrivateIpAddressQuantity: 每个标准型弹性网卡可以分配的IP配额
:type EniPrivateIpAddressQuantity: int
:param ExtendEniQuantity: 扩展型网卡配额
注意:此字段可能返回 null,表示取不到有效值。
:type ExtendEniQuantity: int
:param ExtendEniPrivateIpAddressQuantity: 每个扩展型弹性网卡可以分配的IP配额
注意:此字段可能返回 null,表示取不到有效值。
:type ExtendEniPrivateIpAddressQuantity: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | r"""
:param EniQuantity: 标准型弹性网卡配额
:type EniQuantity: int
:param EniPrivateIpAddressQuantity: 每个标准型弹性网卡可以分配的IP配额
:type EniPrivateIpAddressQuantity: int
:param ExtendEniQuantity: 扩展型网卡配额
注意:此字段可能返回 null,表示取不到有效值。
:type ExtendEniQuantity: int
:param ExtendEniPrivateIpAddressQuantity: 每个扩展型弹性网卡可以分配的IP配额
注意:此字段可能返回 null,表示取不到有效值。
:type ExtendEniPrivateIpAddressQuantity: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | [
"r",
":",
"param",
"EniQuantity",
":",
"标准型弹性网卡配额",
":",
"type",
"EniQuantity",
":",
"int",
":",
"param",
"EniPrivateIpAddressQuantity",
":",
"每个标准型弹性网卡可以分配的IP配额",
":",
"type",
"EniPrivateIpAddressQuantity",
":",
"int",
":",
"param",
"ExtendEniQuantity",
":",
"扩展型网卡... | def __init__(self):
r"""
:param EniQuantity: 标准型弹性网卡配额
:type EniQuantity: int
:param EniPrivateIpAddressQuantity: 每个标准型弹性网卡可以分配的IP配额
:type EniPrivateIpAddressQuantity: int
:param ExtendEniQuantity: 扩展型网卡配额
注意:此字段可能返回 null,表示取不到有效值。
:type ExtendEniQuantity: int
:param ExtendEniPrivateIpAddressQuantity: 每个扩展型弹性网卡可以分配的IP配额
注意:此字段可能返回 null,表示取不到有效值。
:type ExtendEniPrivateIpAddressQuantity: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.EniQuantity = None
self.EniPrivateIpAddressQuantity = None
self.ExtendEniQuantity = None
self.ExtendEniPrivateIpAddressQuantity = None
self.RequestId = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"EniQuantity",
"=",
"None",
"self",
".",
"EniPrivateIpAddressQuantity",
"=",
"None",
"self",
".",
"ExtendEniQuantity",
"=",
"None",
"self",
".",
"ExtendEniPrivateIpAddressQuantity",
"=",
"None",
"self",
".",... | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/vpc/v20170312/models.py#L9352-L9371 | ||
Gandi/gandi.cli | 5de0605126247e986f8288b467a52710a78e1794 | gandi/cli/commands/certstore.py | python | list | (gandi, id, vhosts, dates, fqdns, limit) | return result | List hosted certificates. | List hosted certificates. | [
"List",
"hosted",
"certificates",
"."
] | def list(gandi, id, vhosts, dates, fqdns, limit):
""" List hosted certificates. """
justify = 10
options = {'items_per_page': limit, 'state': 'created'}
output_keys = []
if id:
output_keys.append('id')
output_keys.append('subject')
if dates:
output_keys.extend(['date_created', 'date_expire'])
justify = 12
if fqdns:
output_keys.append('fqdns')
if vhosts:
output_keys.append('vhosts')
result = gandi.hostedcert.list(options)
for num, hcert in enumerate(result):
if num:
gandi.separator_line()
if fqdns or vhosts:
hcert = gandi.hostedcert.info(hcert['id'])
output_hostedcert(gandi, hcert, output_keys, justify)
return result | [
"def",
"list",
"(",
"gandi",
",",
"id",
",",
"vhosts",
",",
"dates",
",",
"fqdns",
",",
"limit",
")",
":",
"justify",
"=",
"10",
"options",
"=",
"{",
"'items_per_page'",
":",
"limit",
",",
"'state'",
":",
"'created'",
"}",
"output_keys",
"=",
"[",
"]... | https://github.com/Gandi/gandi.cli/blob/5de0605126247e986f8288b467a52710a78e1794/gandi/cli/commands/certstore.py#L33-L66 | |
kodi-community-addons/plugin.audio.spotify | 15cb070120a375613ca45c2a3129ea2abe43a1e8 | resources/lib/osd.py | python | SpotifyOSDUpdateThread.update_info | (self, track=None) | scrape results for search query | scrape results for search query | [
"scrape",
"results",
"for",
"search",
"query"
] | def update_info(self, track=None):
'''scrape results for search query'''
# set cover image
thumb = ""
if track.get("images"):
thumb = track["images"][0]['url']
elif track['album'].get("images"):
thumb = track['album']["images"][0]['url']
self.dialog.getControl(3110).setImage(thumb)
# set track title
lbl_control = self.dialog.getControl(3111)
title = track["name"]
lbl_control.setLabel(title)
# set artist label
lbl_control = self.dialog.getControl(3112)
artist = " / ".join([artist["name"] for artist in track["artists"]])
lbl_control.setLabel(artist)
# set album label
lbl_control = self.dialog.getControl(3113)
album = track['album']["name"]
lbl_control.setLabel(album)
# set genre label
lbl_control = self.dialog.getControl(3114)
genre = " / ".join(track["album"].get("genres", []))
lbl_control.setLabel(genre)
# set rating label
lbl_control = self.dialog.getControl(3115)
rating = str(get_track_rating(track["popularity"]))
lbl_control.setLabel(rating)
# get additional artwork
artwork = self.dialog.metadatautils.get_music_artwork(artist, album, title)
fanart = artwork["art"].get("fanart", "special://home/addons/plugin.audio.spotify/fanart.jpg")
self.dialog.getControl(3300).setImage(fanart)
efa = artwork["art"].get("extrafanart", "")
self.dialog.getControl(3301).setLabel(efa)
clearlogo = artwork["art"].get("clearlogo", "")
self.dialog.getControl(3303).setImage(clearlogo)
banner = artwork["art"].get("banner", "")
self.dialog.getControl(3304).setImage(banner)
albumthumb = artwork["art"].get("albumthumb", "")
self.dialog.getControl(3305).setImage(albumthumb)
artistthumb = artwork["art"].get("artistthumb", "")
self.dialog.getControl(3306).setImage(artistthumb)
discart = artwork["art"].get("discart", "disc.png")
self.dialog.getControl(3307).setImage(discart) | [
"def",
"update_info",
"(",
"self",
",",
"track",
"=",
"None",
")",
":",
"# set cover image",
"thumb",
"=",
"\"\"",
"if",
"track",
".",
"get",
"(",
"\"images\"",
")",
":",
"thumb",
"=",
"track",
"[",
"\"images\"",
"]",
"[",
"0",
"]",
"[",
"'url'",
"]"... | https://github.com/kodi-community-addons/plugin.audio.spotify/blob/15cb070120a375613ca45c2a3129ea2abe43a1e8/resources/lib/osd.py#L165-L216 | ||
jantman/misc-scripts | dba5680bafbc5c5d2d9d4abcc305c57df373cd26 | jira2trello.py | python | JiraToTrello.gen_config | (confpath) | write sample config file | write sample config file | [
"write",
"sample",
"config",
"file"
] | def gen_config(confpath):
"""write sample config file"""
if os.path.exists(confpath):
sys.stderr.write("ERROR: file already exists at: {p}\n".format(p=confpath))
raise SystemExit(1)
with open(confpath, 'w') as fh:
fh.write(textwrap.dedent("""
# sample config file for jira2trello.py
# see: https://github.com/jantman/misc-scripts/blob/master/jira2trello.py
# Jira credentials
JIRA_URL = 'https://jira.example.com'
JIRA_USER = 'myuser'
JIRA_PASS = 'mypass'
# regular expression to match against the upper-cased card name;
# first capture group should be the Jira ticket ID
JIRA_TICKET_RE = '.*((project1|project2|project3)-\d+):.*'
# Note: the format that the card names will be converted to is:
# <time tracking> <Issue Id>: <Issue Summary>
# This is in line with <https://github.com/jantman/userscripts/blob/master/TrelloContextMenu.user.js>
# Trello Developer/Application key - you can get this from <https://trello.com/app-key>
TRELLO_APP_KEY = 'd141cd6874d46ba92770697e7721a614'
# Trello token (secret) - get this from:
# <https://trello.com/1/authorize?key=d141cd6874d46ba92770697e7721a614&name=jira2trello.py&expiration=never&response_type=token&scope=read,write>
TRELLO_TOKEN = 'myToken'
# Trello board to search; get this ID from the URL to the board
TRELLO_BOARD_ID = 'myBoardId'
# List on that board to move closed cards to
TRELLO_DONE_LIST_NAME = 'Done'
"""))
raise SystemExit(0) | [
"def",
"gen_config",
"(",
"confpath",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"confpath",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"ERROR: file already exists at: {p}\\n\"",
".",
"format",
"(",
"p",
"=",
"confpath",
")",
")",
"... | https://github.com/jantman/misc-scripts/blob/dba5680bafbc5c5d2d9d4abcc305c57df373cd26/jira2trello.py#L207-L240 | ||
apple/coremltools | 141a83af482fcbdd5179807c9eaff9a7999c2c49 | deps/protobuf/python/google/protobuf/internal/encoder.py | python | _SimpleEncoder | (wire_type, encode_value, compute_value_size) | return SpecificEncoder | Return a constructor for an encoder for fields of a particular type.
Args:
wire_type: The field's wire type, for encoding tags.
encode_value: A function which encodes an individual value, e.g.
_EncodeVarint().
compute_value_size: A function which computes the size of an individual
value, e.g. _VarintSize(). | Return a constructor for an encoder for fields of a particular type. | [
"Return",
"a",
"constructor",
"for",
"an",
"encoder",
"for",
"fields",
"of",
"a",
"particular",
"type",
"."
] | def _SimpleEncoder(wire_type, encode_value, compute_value_size):
"""Return a constructor for an encoder for fields of a particular type.
Args:
wire_type: The field's wire type, for encoding tags.
encode_value: A function which encodes an individual value, e.g.
_EncodeVarint().
compute_value_size: A function which computes the size of an individual
value, e.g. _VarintSize().
"""
def SpecificEncoder(field_number, is_repeated, is_packed):
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value):
write(tag_bytes)
size = 0
for element in value:
size += compute_value_size(element)
local_EncodeVarint(write, size)
for element in value:
encode_value(write, element)
return EncodePackedField
elif is_repeated:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeRepeatedField(write, value):
for element in value:
write(tag_bytes)
encode_value(write, element)
return EncodeRepeatedField
else:
tag_bytes = TagBytes(field_number, wire_type)
def EncodeField(write, value):
write(tag_bytes)
return encode_value(write, value)
return EncodeField
return SpecificEncoder | [
"def",
"_SimpleEncoder",
"(",
"wire_type",
",",
"encode_value",
",",
"compute_value_size",
")",
":",
"def",
"SpecificEncoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
")",
":",
"if",
"is_packed",
":",
"tag_bytes",
"=",
"TagBytes",
"(",
"field_... | https://github.com/apple/coremltools/blob/141a83af482fcbdd5179807c9eaff9a7999c2c49/deps/protobuf/python/google/protobuf/internal/encoder.py#L428-L466 | |
aosp-mirror/tools_repo | 1f20776dbb3b87ba39928dc4baba58f9c2d17c80 | subcmds/forall.py | python | DoWorkWrapper | (args) | A wrapper around the DoWork() method.
Catch the KeyboardInterrupt exceptions here and re-raise them as a different,
``Exception``-based exception to stop it flooding the console with stacktraces
and making the parent hang indefinitely. | A wrapper around the DoWork() method. | [
"A",
"wrapper",
"around",
"the",
"DoWork",
"()",
"method",
"."
] | def DoWorkWrapper(args):
""" A wrapper around the DoWork() method.
Catch the KeyboardInterrupt exceptions here and re-raise them as a different,
``Exception``-based exception to stop it flooding the console with stacktraces
and making the parent hang indefinitely.
"""
project = args.pop()
try:
return DoWork(project, *args)
except KeyboardInterrupt:
print('%s: Worker interrupted' % project['name'])
raise WorkerKeyboardInterrupt() | [
"def",
"DoWorkWrapper",
"(",
"args",
")",
":",
"project",
"=",
"args",
".",
"pop",
"(",
")",
"try",
":",
"return",
"DoWork",
"(",
"project",
",",
"*",
"args",
")",
"except",
"KeyboardInterrupt",
":",
"print",
"(",
"'%s: Worker interrupted'",
"%",
"project"... | https://github.com/aosp-mirror/tools_repo/blob/1f20776dbb3b87ba39928dc4baba58f9c2d17c80/subcmds/forall.py#L293-L306 | ||
sio2project/oioioi | adeb6a7b278b6bed853405e525f87fd2726c06ac | oioioi/base/menu.py | python | MenuRegistry.unregister | (self, name) | Unregisters a menu item.
Does nothing if not found. | Unregisters a menu item. | [
"Unregisters",
"a",
"menu",
"item",
"."
] | def unregister(self, name):
"""Unregisters a menu item.
Does nothing if not found.
"""
for item in self._registry:
if item.name == name:
pos = self._registry.index(item)
del self._registry[pos]
break | [
"def",
"unregister",
"(",
"self",
",",
"name",
")",
":",
"for",
"item",
"in",
"self",
".",
"_registry",
":",
"if",
"item",
".",
"name",
"==",
"name",
":",
"pos",
"=",
"self",
".",
"_registry",
".",
"index",
"(",
"item",
")",
"del",
"self",
".",
"... | https://github.com/sio2project/oioioi/blob/adeb6a7b278b6bed853405e525f87fd2726c06ac/oioioi/base/menu.py#L156-L166 | ||
pulp/pulp | a0a28d804f997b6f81c391378aff2e4c90183df9 | bindings/pulp/bindings/server.py | python | PulpConnection._request | (self, method, path, queries=(), body=None, ensure_encoding=True,
log_request_body=True, ignore_prefix=False) | return Response(response_code, body) | make a HTTP request to the pulp server and return the response
:param method: name of an HTTP method such as GET, POST, PUT, HEAD
or DELETE
:type method: basestring
:param path: URL for this request
:type path: basestring
:param queries: mapping object or a sequence of 2-element tuples,
in either case representing key-value pairs to be used
as query parameters on the URL.
:type queries: mapping object or sequence of 2-element tuples
:param body: Data structure that will be JSON serialized and send as
the request's body.
:type body: Anything that is JSON-serializable.
:param ensure_encoding: toggle proper string encoding for the body
:type ensure_encoding: bool
:param log_request_body: Toggle logging of the request body, defaults to true
:type log_request_body: bool
:param ignore_prefix: when building the url, disregard the self.path_prefix
:type ignore_prefix: bool
:return: Response object
:rtype: pulp.bindings.responses.Response
:raises: ConnectionException or one of the RequestExceptions
(depending on response codes) in case of unsuccessful
request | make a HTTP request to the pulp server and return the response | [
"make",
"a",
"HTTP",
"request",
"to",
"the",
"pulp",
"server",
"and",
"return",
"the",
"response"
] | def _request(self, method, path, queries=(), body=None, ensure_encoding=True,
log_request_body=True, ignore_prefix=False):
"""
make a HTTP request to the pulp server and return the response
:param method: name of an HTTP method such as GET, POST, PUT, HEAD
or DELETE
:type method: basestring
:param path: URL for this request
:type path: basestring
:param queries: mapping object or a sequence of 2-element tuples,
in either case representing key-value pairs to be used
as query parameters on the URL.
:type queries: mapping object or sequence of 2-element tuples
:param body: Data structure that will be JSON serialized and send as
the request's body.
:type body: Anything that is JSON-serializable.
:param ensure_encoding: toggle proper string encoding for the body
:type ensure_encoding: bool
:param log_request_body: Toggle logging of the request body, defaults to true
:type log_request_body: bool
:param ignore_prefix: when building the url, disregard the self.path_prefix
:type ignore_prefix: bool
:return: Response object
:rtype: pulp.bindings.responses.Response
:raises: ConnectionException or one of the RequestExceptions
(depending on response codes) in case of unsuccessful
request
"""
url = self._build_url(path, queries, ignore_prefix)
if ensure_encoding:
body = self._process_body(body)
if not isinstance(body, (NoneType, basestring)):
body = json.dumps(body)
self.log.debug('sending %s request to %s' % (method, url))
response_code, response_body = self.server_wrapper.request(method, url, body)
if self.api_responses_logger:
if log_request_body:
self.api_responses_logger.info(
'%s request to %s with parameters %s' % (method, url, body))
else:
self.api_responses_logger.info(
'%s request to %s' % (method, url))
self.api_responses_logger.info("Response status : %s \n" % response_code)
self.api_responses_logger.info(
"Response body :\n %s\n" % json.dumps(response_body, indent=2))
if response_code >= 300:
self._handle_exceptions(response_code, response_body)
elif response_code == 200 or response_code == 201:
body = response_body
elif response_code == 202:
if isinstance(response_body, list):
body = [Task(t) for t in response_body]
else:
body = Task(response_body)
return Response(response_code, body) | [
"def",
"_request",
"(",
"self",
",",
"method",
",",
"path",
",",
"queries",
"=",
"(",
")",
",",
"body",
"=",
"None",
",",
"ensure_encoding",
"=",
"True",
",",
"log_request_body",
"=",
"True",
",",
"ignore_prefix",
"=",
"False",
")",
":",
"url",
"=",
... | https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/bindings/pulp/bindings/server.py#L114-L181 | |
mrkipling/maraschino | c6be9286937783ae01df2d6d8cebfc8b2734a7d7 | lib/sqlalchemy/ext/associationproxy.py | python | AssociationProxy.has | (self, criterion=None, **kwargs) | return self._comparator.has(
getattr(self.target_class, self.value_attr).\
has(criterion, **kwargs)
) | Produce a proxied 'has' expression using EXISTS.
This expression will be a composed product
using the :meth:`.RelationshipProperty.Comparator.any`
and/or :meth:`.RelationshipProperty.Comparator.has`
operators of the underlying proxied attributes. | Produce a proxied 'has' expression using EXISTS.
This expression will be a composed product
using the :meth:`.RelationshipProperty.Comparator.any`
and/or :meth:`.RelationshipProperty.Comparator.has`
operators of the underlying proxied attributes. | [
"Produce",
"a",
"proxied",
"has",
"expression",
"using",
"EXISTS",
".",
"This",
"expression",
"will",
"be",
"a",
"composed",
"product",
"using",
"the",
":",
"meth",
":",
".",
"RelationshipProperty",
".",
"Comparator",
".",
"any",
"and",
"/",
"or",
":",
"me... | def has(self, criterion=None, **kwargs):
"""Produce a proxied 'has' expression using EXISTS.
This expression will be a composed product
using the :meth:`.RelationshipProperty.Comparator.any`
and/or :meth:`.RelationshipProperty.Comparator.has`
operators of the underlying proxied attributes.
"""
return self._comparator.has(
getattr(self.target_class, self.value_attr).\
has(criterion, **kwargs)
) | [
"def",
"has",
"(",
"self",
",",
"criterion",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_comparator",
".",
"has",
"(",
"getattr",
"(",
"self",
".",
"target_class",
",",
"self",
".",
"value_attr",
")",
".",
"has",
"(",
"... | https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/sqlalchemy/ext/associationproxy.py#L361-L374 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/embed/server.py | python | _clean_url | (url) | return url.rstrip("/") | Produce a canonical Bokeh server URL.
Args:
url (str)
A URL to clean, or "defatul". If "default" then the
``BOKEH_SERVER_HTTP_URL`` will be returned.
Returns:
str | Produce a canonical Bokeh server URL. | [
"Produce",
"a",
"canonical",
"Bokeh",
"server",
"URL",
"."
] | def _clean_url(url):
''' Produce a canonical Bokeh server URL.
Args:
url (str)
A URL to clean, or "defatul". If "default" then the
``BOKEH_SERVER_HTTP_URL`` will be returned.
Returns:
str
'''
if url == 'default':
url = DEFAULT_SERVER_HTTP_URL
if url.startswith("ws"):
raise ValueError("url should be the http or https URL for the server, not the websocket URL")
return url.rstrip("/") | [
"def",
"_clean_url",
"(",
"url",
")",
":",
"if",
"url",
"==",
"'default'",
":",
"url",
"=",
"DEFAULT_SERVER_HTTP_URL",
"if",
"url",
".",
"startswith",
"(",
"\"ws\"",
")",
":",
"raise",
"ValueError",
"(",
"\"url should be the http or https URL for the server, not the... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/bokeh-1.4.0-py3.7.egg/bokeh/embed/server.py#L236-L254 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.