text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get(self, name: str, sig: Tuple) -> Optional[object]:
"""
Return the object representing name if it is cached
:param name: name of object
:param sig: unique signature of object
:return: object if exists and signature matches
"""
if name not in self._cache:
... | [
"def",
"get",
"(",
"self",
",",
"name",
":",
"str",
",",
"sig",
":",
"Tuple",
")",
"->",
"Optional",
"[",
"object",
"]",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_cache",
":",
"return",
"None",
"if",
"self",
".",
"_cache",
"[",
"name",
"]",
... | 35.933333 | 9.4 |
def compute_wcs(key, challenge):
"""
Compute an WAMP-CRA authentication signature from an authentication
challenge and a (derived) key.
:param key: The key derived (via PBKDF2) from the secret.
:type key: str/bytes
:param challenge: The authentication challenge to sign.
:type challenge: str... | [
"def",
"compute_wcs",
"(",
"key",
",",
"challenge",
")",
":",
"key",
"=",
"key",
".",
"encode",
"(",
"'utf8'",
")",
"challenge",
"=",
"challenge",
".",
"encode",
"(",
"'utf8'",
")",
"sig",
"=",
"hmac",
".",
"new",
"(",
"key",
",",
"challenge",
",",
... | 32.588235 | 14.705882 |
def set_dict_value(dictionary, keys, value):
"""
Set a value in a (nested) dictionary by defining a list of keys.
.. note:: Side-effects
This function does not make a copy of dictionary, but directly
edits it.
Parameters
----------
dictionary : dict
keys : List[... | [
"def",
"set_dict_value",
"(",
"dictionary",
",",
"keys",
",",
"value",
")",
":",
"orig",
"=",
"dictionary",
"for",
"key",
"in",
"keys",
"[",
":",
"-",
"1",
"]",
":",
"dictionary",
"=",
"dictionary",
".",
"setdefault",
"(",
"key",
",",
"{",
"}",
")",
... | 23.533333 | 21.533333 |
def tag_structure(tag, site):
"""
A tag structure.
"""
return {'tag_id': tag.pk,
'name': tag.name,
'count': tag.count,
'slug': tag.name,
'html_url': '%s://%s%s' % (
PROTOCOL, site.domain,
reverse('zinnia:tag_detail', args=[t... | [
"def",
"tag_structure",
"(",
"tag",
",",
"site",
")",
":",
"return",
"{",
"'tag_id'",
":",
"tag",
".",
"pk",
",",
"'name'",
":",
"tag",
".",
"name",
",",
"'count'",
":",
"tag",
".",
"count",
",",
"'slug'",
":",
"tag",
".",
"name",
",",
"'html_url'"... | 31.333333 | 10 |
def from_labeled_point(rdd, categorical=False, nb_classes=None):
"""Convert a LabeledPoint RDD back to a pair of numpy arrays
:param rdd: LabeledPoint RDD
:param categorical: boolean, if labels should be one-hot encode when returned
:param nb_classes: optional int, indicating the number of class labels... | [
"def",
"from_labeled_point",
"(",
"rdd",
",",
"categorical",
"=",
"False",
",",
"nb_classes",
"=",
"None",
")",
":",
"features",
"=",
"np",
".",
"asarray",
"(",
"rdd",
".",
"map",
"(",
"lambda",
"lp",
":",
"from_vector",
"(",
"lp",
".",
"features",
")"... | 42.210526 | 17.210526 |
def get_config_h_filename():
"""Return the path of pyconfig.h."""
if _PYTHON_BUILD:
if os.name == "nt":
inc_dir = os.path.join(_PROJECT_BASE, "PC")
else:
inc_dir = _PROJECT_BASE
else:
inc_dir = get_path('platinclude')
return os.path.join(inc_dir, 'pyconfig... | [
"def",
"get_config_h_filename",
"(",
")",
":",
"if",
"_PYTHON_BUILD",
":",
"if",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"inc_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_PROJECT_BASE",
",",
"\"PC\"",
")",
"else",
":",
"inc_dir",
"=",
"_PROJECT_BASE... | 31.5 | 12.9 |
def save(self):
"""
Apply a series of actions from a set of (action, arg) tuples, probably
as parsed from a URL. Each action is a code into PROCESSORS.
Then save the mogrified image.
"""
from settings import PROCESSORS
from .filesystem import makedirs
if... | [
"def",
"save",
"(",
"self",
")",
":",
"from",
"settings",
"import",
"PROCESSORS",
"from",
".",
"filesystem",
"import",
"makedirs",
"if",
"self",
".",
"im",
"is",
"None",
":",
"# If we got here something very strange is going on that I can't even",
"# predict.",
"retur... | 33.64 | 15.68 |
def plot_ebands(self, **kwargs):
"""
Plot the band structure. kwargs are passed to the plot method of :class:`ElectronBands`.
Returns:
`matplotlib` figure
"""
with self.nscf_task.open_gsr() as gsr:
return gsr.ebands.plot(**kwargs) | [
"def",
"plot_ebands",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"nscf_task",
".",
"open_gsr",
"(",
")",
"as",
"gsr",
":",
"return",
"gsr",
".",
"ebands",
".",
"plot",
"(",
"*",
"*",
"kwargs",
")"
] | 31.888889 | 16.333333 |
def is_upstart(conn):
"""
This helper should only used as a fallback (last resort) as it is not
guaranteed that it will be absolutely correct.
"""
# it may be possible that we may be systemd and the caller never checked
# before so lets do that
if is_systemd(conn):
return False
... | [
"def",
"is_upstart",
"(",
"conn",
")",
":",
"# it may be possible that we may be systemd and the caller never checked",
"# before so lets do that",
"if",
"is_systemd",
"(",
"conn",
")",
":",
"return",
"False",
"# get the initctl executable, if it doesn't exist we can't proceed so we"... | 31.857143 | 19.5 |
def sigma(htilde, psd = None, low_frequency_cutoff=None,
high_frequency_cutoff=None):
""" Return the sigma of the waveform. See sigmasq for more details.
Parameters
----------
htilde : TimeSeries or FrequencySeries
The input vector containing a waveform.
psd : {None, FrequencySeries... | [
"def",
"sigma",
"(",
"htilde",
",",
"psd",
"=",
"None",
",",
"low_frequency_cutoff",
"=",
"None",
",",
"high_frequency_cutoff",
"=",
"None",
")",
":",
"return",
"sqrt",
"(",
"sigmasq",
"(",
"htilde",
",",
"psd",
",",
"low_frequency_cutoff",
",",
"high_freque... | 36.05 | 17.75 |
def replace_wrep(t:str) -> str:
"Replace word repetitions in `t`."
def _replace_wrep(m:Collection[str]) -> str:
c,cc = m.groups()
return f' {TK_WREP} {len(cc.split())+1} {c} '
re_wrep = re.compile(r'(\b\w+\W+)(\1{3,})')
return re_wrep.sub(_replace_wrep, t) | [
"def",
"replace_wrep",
"(",
"t",
":",
"str",
")",
"->",
"str",
":",
"def",
"_replace_wrep",
"(",
"m",
":",
"Collection",
"[",
"str",
"]",
")",
"->",
"str",
":",
"c",
",",
"cc",
"=",
"m",
".",
"groups",
"(",
")",
"return",
"f' {TK_WREP} {len(cc.split(... | 40.285714 | 7.714286 |
def upload(self, params={}):
"""start uploading the file until upload is complete or error.
This is the main method to used, If you do not care about
state of process.
Args:
params: a dict object describe video info, eg title,
tags, description, ... | [
"def",
"upload",
"(",
"self",
",",
"params",
"=",
"{",
"}",
")",
":",
"if",
"self",
".",
"upload_token",
"is",
"not",
"None",
":",
"# resume upload",
"status",
"=",
"self",
".",
"check",
"(",
")",
"if",
"status",
"[",
"'status'",
"]",
"!=",
"4",
":... | 34.935484 | 13.612903 |
def get_stp_mst_detail_output_msti_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti =... | [
"def",
"get_stp_mst_detail_output_msti_port_if_state",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_stp_mst_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_stp_mst_detail\"",
")",
"config",
"="... | 42.8125 | 12.375 |
def yml_fnc(fname, *args, **options):
"""
:param fname:
"load" or "dump", not checked but it should be OK.
see also :func:`yml_load` and :func:`yml_dump`
:param args: [stream] for load or [cnf, stream] for dump
:param options: keyword args may contain "ac_safe" to load/dump safely
""... | [
"def",
"yml_fnc",
"(",
"fname",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"options",
"=",
"common",
".",
"filter_from_options",
"(",
"\"ac_dict\"",
",",
"options",
")",
"if",
"\"ac_safe\"",
"in",
"options",
":",
"options",
"[",
"\"typ\"",
"]"... | 36.238095 | 20.047619 |
def find_release(package, releases, dependencies=None):
"""Return the best release."""
dependencies = dependencies if dependencies is not None else {}
for release in releases:
url = release['url']
old_priority = dependencies.get(package, {}).get('priority', 0)
for suffix, priority i... | [
"def",
"find_release",
"(",
"package",
",",
"releases",
",",
"dependencies",
"=",
"None",
")",
":",
"dependencies",
"=",
"dependencies",
"if",
"dependencies",
"is",
"not",
"None",
"else",
"{",
"}",
"for",
"release",
"in",
"releases",
":",
"url",
"=",
"rele... | 38.421053 | 13.473684 |
def _prepare_io_handler(self, handler):
"""Call the `interfaces.IOHandler.prepare` method and
remove the handler from unprepared handler list when done.
"""
logger.debug(" preparing handler: {0!r}".format(handler))
self._unprepared_pending.discard(handler)
ret = handler.p... | [
"def",
"_prepare_io_handler",
"(",
"self",
",",
"handler",
")",
":",
"logger",
".",
"debug",
"(",
"\" preparing handler: {0!r}\"",
".",
"format",
"(",
"handler",
")",
")",
"self",
".",
"_unprepared_pending",
".",
"discard",
"(",
"handler",
")",
"ret",
"=",
"... | 44.517241 | 13.827586 |
def videoWrite(path, imgs, levels=None, shape=None, frames=15,
annotate_names=None,
lut=None, updateFn=None):
'''
TODO
'''
frames = int(frames)
if annotate_names is not None:
assert len(annotate_names) == len(imgs)
if levels is None:
if i... | [
"def",
"videoWrite",
"(",
"path",
",",
"imgs",
",",
"levels",
"=",
"None",
",",
"shape",
"=",
"None",
",",
"frames",
"=",
"15",
",",
"annotate_names",
"=",
"None",
",",
"lut",
"=",
"None",
",",
"updateFn",
"=",
"None",
")",
":",
"frames",
"=",
"int... | 29.691176 | 18.191176 |
def derive(self, peerkey, **kwargs):
"""
Derives shared key (DH,ECDH,VKO 34.10). Requires
private key available
@param peerkey - other key (may be public only)
Keyword parameters are algorithm-specific
"""
if not self.cansign:
raise ValueError("No pr... | [
"def",
"derive",
"(",
"self",
",",
"peerkey",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"cansign",
":",
"raise",
"ValueError",
"(",
"\"No private key available\"",
")",
"ctx",
"=",
"libcrypto",
".",
"EVP_PKEY_CTX_new",
"(",
"self",
".",
... | 43.5 | 16.777778 |
def recv_loop(stream):
"""Yield Erlang terms from an input stream."""
message = recv(stream)
while message:
yield message
message = recv(stream) | [
"def",
"recv_loop",
"(",
"stream",
")",
":",
"message",
"=",
"recv",
"(",
"stream",
")",
"while",
"message",
":",
"yield",
"message",
"message",
"=",
"recv",
"(",
"stream",
")"
] | 27.833333 | 13.833333 |
def log_all(self, file):
"""Log all data received from RFLink to file."""
global rflink_log
if file == None:
rflink_log = None
else:
log.debug('logging to: %s', file)
rflink_log = open(file, 'a') | [
"def",
"log_all",
"(",
"self",
",",
"file",
")",
":",
"global",
"rflink_log",
"if",
"file",
"==",
"None",
":",
"rflink_log",
"=",
"None",
"else",
":",
"log",
".",
"debug",
"(",
"'logging to: %s'",
",",
"file",
")",
"rflink_log",
"=",
"open",
"(",
"file... | 32 | 11.25 |
def parse(self, date, **kwargs):
'''
:param **kwargs: any kwargs accepted by dateutil.parse function.
'''
qualifiers = []
if dateutil_parser is None:
return None
date = orig_date = date.strip()
# various normalizations
# TODO: call .lower() fi... | [
"def",
"parse",
"(",
"self",
",",
"date",
",",
"*",
"*",
"kwargs",
")",
":",
"qualifiers",
"=",
"[",
"]",
"if",
"dateutil_parser",
"is",
"None",
":",
"return",
"None",
"date",
"=",
"orig_date",
"=",
"date",
".",
"strip",
"(",
")",
"# various normalizat... | 34.876543 | 17.518519 |
def _add_to_conf(self, new_conf):
"""Add new configuration to self.conf.
Adds configuration parameters in new_con to self.conf.
If they already existed in conf, overwrite them.
:param new_conf: new configuration, to add
"""
for section in new_conf:
if secti... | [
"def",
"_add_to_conf",
"(",
"self",
",",
"new_conf",
")",
":",
"for",
"section",
"in",
"new_conf",
":",
"if",
"section",
"not",
"in",
"self",
".",
"conf",
":",
"self",
".",
"conf",
"[",
"section",
"]",
"=",
"new_conf",
"[",
"section",
"]",
"else",
":... | 34.666667 | 17.266667 |
def allow_port(port, proto='tcp', direction='both'):
'''
Like allow_ports, but it will append to the
existing entry instead of replacing it.
Takes a single port instead of a list of ports.
CLI Example:
.. code-block:: bash
salt '*' csf.allow_port 22 proto='tcp' direction='in'
'''
... | [
"def",
"allow_port",
"(",
"port",
",",
"proto",
"=",
"'tcp'",
",",
"direction",
"=",
"'both'",
")",
":",
"ports",
"=",
"get_ports",
"(",
"proto",
"=",
"proto",
",",
"direction",
"=",
"direction",
")",
"direction",
"=",
"direction",
".",
"upper",
"(",
"... | 29.956522 | 20.130435 |
def plot_roc(y_true, y_probas, title='ROC Curves',
plot_micro=True, plot_macro=True, classes_to_plot=None,
ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
"""Generates the ROC curves from labels and predicted scor... | [
"def",
"plot_roc",
"(",
"y_true",
",",
"y_probas",
",",
"title",
"=",
"'ROC Curves'",
",",
"plot_micro",
"=",
"True",
",",
"plot_macro",
"=",
"True",
",",
"classes_to_plot",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"cmap",
... | 38.692308 | 23.069231 |
def __compose(self):
""" Compose the message, pulling together body, attachments etc
"""
msg = MIMEMultipart()
msg['Subject'] = self.config['shutit.core.alerting.emailer.subject']
msg['To'] = self.config['shutit.core.alerting.emailer.mailto']
msg['From'] = self.config['shutit.core.alerting.emailer.... | [
"def",
"__compose",
"(",
"self",
")",
":",
"msg",
"=",
"MIMEMultipart",
"(",
")",
"msg",
"[",
"'Subject'",
"]",
"=",
"self",
".",
"config",
"[",
"'shutit.core.alerting.emailer.subject'",
"]",
"msg",
"[",
"'To'",
"]",
"=",
"self",
".",
"config",
"[",
"'sh... | 45.421053 | 21.526316 |
def to_dataframe(self, dtypes=None):
"""Create a :class:`pandas.DataFrame` of all rows in the stream.
This method requires the pandas libary to create a data frame and the
fastavro library to parse row blocks.
.. warning::
DATETIME columns are not supported. They are curren... | [
"def",
"to_dataframe",
"(",
"self",
",",
"dtypes",
"=",
"None",
")",
":",
"if",
"pandas",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"_PANDAS_REQUIRED",
")",
"frames",
"=",
"[",
"]",
"for",
"page",
"in",
"self",
".",
"pages",
":",
"frames",
".",
... | 35.3 | 21.466667 |
def create_articles(self, project, articleset, json_data=None, **options):
"""
Create one or more articles in the set. Provide the needed arguments
using the json_data or with key-value pairs
@param json_data: A dictionary or list of dictionaries. Each dict
can ... | [
"def",
"create_articles",
"(",
"self",
",",
"project",
",",
"articleset",
",",
"json_data",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"url",
"=",
"URL",
".",
"article",
".",
"format",
"(",
"*",
"*",
"locals",
"(",
")",
")",
"# TODO duplicated fr... | 50.894737 | 19 |
def t_istringapostrophe_css_string(self, t):
r'[^\'@]+'
t.lexer.lineno += t.value.count('\n')
return t | [
"def",
"t_istringapostrophe_css_string",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"lexer",
".",
"lineno",
"+=",
"t",
".",
"value",
".",
"count",
"(",
"'\\n'",
")",
"return",
"t"
] | 30.75 | 13.75 |
def find(self, name, required):
"""
Finds all matching dependencies by their name.
:param name: the dependency name to locate.
:param required: true to raise an exception when no dependencies are found.
:return: a list of found dependencies
"""
if name == None:... | [
"def",
"find",
"(",
"self",
",",
"name",
",",
"required",
")",
":",
"if",
"name",
"==",
"None",
":",
"raise",
"Exception",
"(",
"\"Name cannot be null\"",
")",
"locator",
"=",
"self",
".",
"_locate",
"(",
"name",
")",
"if",
"locator",
"==",
"None",
":"... | 29.65 | 18.45 |
def download_extract(url):
"""download and extract file."""
logger.info("Downloading %s", url)
request = urllib2.Request(url)
request.add_header('User-Agent',
'caelum/0.1 +https://github.com/nrcharles/caelum')
opener = urllib2.build_opener()
with tempfile.TemporaryFile(suf... | [
"def",
"download_extract",
"(",
"url",
")",
":",
"logger",
".",
"info",
"(",
"\"Downloading %s\"",
",",
"url",
")",
"request",
"=",
"urllib2",
".",
"Request",
"(",
"url",
")",
"request",
".",
"add_header",
"(",
"'User-Agent'",
",",
"'caelum/0.1 +https://github... | 46.333333 | 14.466667 |
def _reldiff(a, b):
"""
Computes the relative difference of two floating-point numbers
rel = abs(a-b)/min(abs(a), abs(b))
If a == 0 and b == 0, then 0.0 is returned
Otherwise if a or b is 0.0, inf is returned.
"""
a = float(a)
b = float(b)
aa = abs(a)
ba = abs(b)
if a == ... | [
"def",
"_reldiff",
"(",
"a",
",",
"b",
")",
":",
"a",
"=",
"float",
"(",
"a",
")",
"b",
"=",
"float",
"(",
"b",
")",
"aa",
"=",
"abs",
"(",
"a",
")",
"ba",
"=",
"abs",
"(",
"b",
")",
"if",
"a",
"==",
"0.0",
"and",
"b",
"==",
"0.0",
":",... | 20.47619 | 20.190476 |
def turn_right(self, angle_degrees, rate=RATE):
"""
Turn to the right, staying on the spot
:param angle_degrees: How far to turn (degrees)
:param rate: The trurning speed (degrees/second)
:return:
"""
flight_time = angle_degrees / rate
self.start_turn_ri... | [
"def",
"turn_right",
"(",
"self",
",",
"angle_degrees",
",",
"rate",
"=",
"RATE",
")",
":",
"flight_time",
"=",
"angle_degrees",
"/",
"rate",
"self",
".",
"start_turn_right",
"(",
"rate",
")",
"time",
".",
"sleep",
"(",
"flight_time",
")",
"self",
".",
"... | 28.384615 | 14.230769 |
def api_call(self, opts, args=None, body=None, **kwargs):
"""Setup the request"""
if args:
path = opts['name'] % args
else:
path = opts['name']
path = '/api/v1%s' % path
return self._request(
opts['method'], path=path, payload=body, **kwargs) | [
"def",
"api_call",
"(",
"self",
",",
"opts",
",",
"args",
"=",
"None",
",",
"body",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
":",
"path",
"=",
"opts",
"[",
"'name'",
"]",
"%",
"args",
"else",
":",
"path",
"=",
"opts",
"[",
... | 34.444444 | 13.222222 |
def stop_receive(self, fd):
"""
Stop yielding readability events for `fd`.
Redundant calls to :meth:`stop_receive` are silently ignored, this may
change in future.
"""
self._rfds.pop(fd, None)
self._update(fd) | [
"def",
"stop_receive",
"(",
"self",
",",
"fd",
")",
":",
"self",
".",
"_rfds",
".",
"pop",
"(",
"fd",
",",
"None",
")",
"self",
".",
"_update",
"(",
"fd",
")"
] | 28.666667 | 15.555556 |
def cythonize(*args, **kwargs):
'''
dirty hack, only import cythonize at the time you use it.
if you don't write Cython extension,
you won't fail even if you don't install Cython.
'''
global cythonize
from Cython.Build import cythonize
return cythonize(*args, **kwargs) | [
"def",
"cythonize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"cythonize",
"from",
"Cython",
".",
"Build",
"import",
"cythonize",
"return",
"cythonize",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 29.3 | 17.3 |
def arrows(self):
"""Iterate over all my arrows."""
for o in self.arrow.values():
for arro in o.values():
yield arro | [
"def",
"arrows",
"(",
"self",
")",
":",
"for",
"o",
"in",
"self",
".",
"arrow",
".",
"values",
"(",
")",
":",
"for",
"arro",
"in",
"o",
".",
"values",
"(",
")",
":",
"yield",
"arro"
] | 31.2 | 9 |
def is_dir(self, follow_symlinks=True):
"""
Return True if this entry is a directory or a symbolic link pointing to
a directory; return False if the entry is or points to any other kind
of file, or if it doesn’t exist anymore.
The result is cached on the os.DirEntry object.
... | [
"def",
"is_dir",
"(",
"self",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"try",
":",
"return",
"(",
"self",
".",
"_system",
".",
"isdir",
"(",
"path",
"=",
"self",
".",
"_path",
",",
"client_kwargs",
"=",
"self",
".",
"_client_kwargs",
",",
"virtua... | 34.857143 | 20.214286 |
def unprotect(self, **kwargs):
"""Unprotect the branch.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabProtectError: If the branch could not be unprotected
"""... | [
"def",
"unprotect",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"id",
"=",
"self",
".",
"get_id",
"(",
")",
".",
"replace",
"(",
"'/'",
",",
"'%2F'",
")",
"path",
"=",
"'%s/%s/unprotect'",
"%",
"(",
"self",
".",
"manager",
".",
"path",
",",
"... | 36.214286 | 19.142857 |
def sexagesimal(sexathang, latlon, form='DDD'):
"""
Arguments:
sexathang: (float), -15.560615 (negative = South), -146.241122 (negative = West) # Apataki Carenage
latlon: (str) 'lat' | 'lon'
form: (str), 'DDD'|'DMM'|'DMS', decimal Degrees, decimal Minutes, decimal Seconds
Returns:
... | [
"def",
"sexagesimal",
"(",
"sexathang",
",",
"latlon",
",",
"form",
"=",
"'DDD'",
")",
":",
"cardinal",
"=",
"'O'",
"if",
"not",
"isinstance",
"(",
"sexathang",
",",
"float",
")",
":",
"sexathang",
"=",
"'n/a'",
"return",
"sexathang",
"if",
"latlon",
"==... | 31.791667 | 21.291667 |
def avail_images(call=None):
'''
Return available Packet os images.
CLI Example:
.. code-block:: bash
salt-cloud --list-images packet-provider
salt-cloud -f avail_images packet-provider
'''
if call == 'action':
raise SaltCloudException(
'The avail_images fu... | [
"def",
"avail_images",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudException",
"(",
"'The avail_images function must be called with -f or --function.'",
")",
"ret",
"=",
"{",
"}",
"vm_",
"=",
"get_configured_provider",
... | 21.814815 | 24.851852 |
def read_from_file(filename):
"""
Arguments:
| ``filename`` -- the filename of the input file
Use as follows::
>>> if = CP2KInputFile.read_from_file("somefile.inp")
>>> for section in if:
... print section.name
"""
... | [
"def",
"read_from_file",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"result",
"=",
"CP2KInputFile",
"(",
")",
"try",
":",
"while",
"True",
":",
"result",
".",
"load_children",
"(",
"f",
")",
"except",
"EOFError",
"... | 27.631579 | 14.684211 |
def next_line(self):
"""Read the next line from the line generator and split it"""
self.line = next(self.lines) # Will raise StopIteration when there are no more lines
self.values = self.line.split() | [
"def",
"next_line",
"(",
"self",
")",
":",
"self",
".",
"line",
"=",
"next",
"(",
"self",
".",
"lines",
")",
"# Will raise StopIteration when there are no more lines",
"self",
".",
"values",
"=",
"self",
".",
"line",
".",
"split",
"(",
")"
] | 55.25 | 18.5 |
def _set_labels(self, axes, dimensions, xlabel=None, ylabel=None, zlabel=None):
"""
Sets the labels of the axes using the supplied list of dimensions.
Optionally explicit labels may be supplied to override the dimension
label.
"""
xlabel, ylabel, zlabel = self._get_axis_l... | [
"def",
"_set_labels",
"(",
"self",
",",
"axes",
",",
"dimensions",
",",
"xlabel",
"=",
"None",
",",
"ylabel",
"=",
"None",
",",
"zlabel",
"=",
"None",
")",
":",
"xlabel",
",",
"ylabel",
",",
"zlabel",
"=",
"self",
".",
"_get_axis_labels",
"(",
"dimensi... | 52.6 | 21.533333 |
def to_number(obj):
'''
Cast an arbitrary object or sequence to a number type
'''
if isinstance(obj, LiteralWrapper):
val = obj.obj
elif isinstance(obj, Iterable) and not isinstance(obj, str):
val = next(obj, None)
else:
val = obj
if val is None:
#FIXME: Shoul... | [
"def",
"to_number",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"LiteralWrapper",
")",
":",
"val",
"=",
"obj",
".",
"obj",
"elif",
"isinstance",
"(",
"obj",
",",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"obj",
",",
"str",
")",... | 29.428571 | 19.809524 |
def vm_get_network_by_name(vm, network_name):
"""
Try to find Network scanning all attached to VM networks
:param vm: <vim.vm>
:param network_name: <str> name of network
:return: <vim.vm.Network or None>
"""
# return None
for network in vm.network:
... | [
"def",
"vm_get_network_by_name",
"(",
"vm",
",",
"network_name",
")",
":",
"# return None",
"for",
"network",
"in",
"vm",
".",
"network",
":",
"if",
"hasattr",
"(",
"network",
",",
"\"name\"",
")",
"and",
"network_name",
"==",
"network",
".",
"name",
":",
... | 35.5 | 11.833333 |
def union(self, a, b):
"""Merges the set that contains ``a`` with the set that contains ``b``.
Parameters
----------
a, b : objects
Two objects whose sets are to be merged.
"""
s1, s2 = self.find(a), self.find(b)
if s1 != s2:
r1, r2 = sel... | [
"def",
"union",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"s1",
",",
"s2",
"=",
"self",
".",
"find",
"(",
"a",
")",
",",
"self",
".",
"find",
"(",
"b",
")",
"if",
"s1",
"!=",
"s2",
":",
"r1",
",",
"r2",
"=",
"self",
".",
"_rank",
"[",
... | 29.55 | 14.15 |
def interrupt_then_kill(self, delay=2.0):
"""Send INT, wait a delay and then send KILL."""
try:
self.signal(SIGINT)
except Exception:
self.log.debug("interrupt failed")
pass
self.killer = ioloop.DelayedCallback(lambda : self.signal(SIGKILL), delay*100... | [
"def",
"interrupt_then_kill",
"(",
"self",
",",
"delay",
"=",
"2.0",
")",
":",
"try",
":",
"self",
".",
"signal",
"(",
"SIGINT",
")",
"except",
"Exception",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"interrupt failed\"",
")",
"pass",
"self",
".",
"... | 39.222222 | 17.222222 |
def resolve_response_data(head_key, data_key, data):
"""
Resolves the responses you get from billomat
If you have done a get_one_element request then you will get a dictionary
If you have done a get_all_elements request then you will get a list with all elements in it
:param hea... | [
"def",
"resolve_response_data",
"(",
"head_key",
",",
"data_key",
",",
"data",
")",
":",
"new_data",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"for",
"data_row",
"in",
"data",
":",
"if",
"head_key",
"in",
"data_row",
"and",
... | 42.178571 | 17.678571 |
def get_anniversary_periods(start, finish, anniversary=1):
"""
Return a list of anniversaries periods between start and finish.
"""
import sys
current = start
periods = []
while current <= finish:
(period_start, period_finish) = date_period(DATE_FREQUENCY_MONTHLY, anniversary, curre... | [
"def",
"get_anniversary_periods",
"(",
"start",
",",
"finish",
",",
"anniversary",
"=",
"1",
")",
":",
"import",
"sys",
"current",
"=",
"start",
"periods",
"=",
"[",
"]",
"while",
"current",
"<=",
"finish",
":",
"(",
"period_start",
",",
"period_finish",
"... | 42 | 21.714286 |
def site_content(self, election_day):
"""
Site content represents content for the entire site on a
given election day.
"""
from electionnight.models import PageType
page_type = PageType.objects.get(
model_type=ContentType.objects.get(
app_labe... | [
"def",
"site_content",
"(",
"self",
",",
"election_day",
")",
":",
"from",
"electionnight",
".",
"models",
"import",
"PageType",
"page_type",
"=",
"PageType",
".",
"objects",
".",
"get",
"(",
"model_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",... | 34.578947 | 14.578947 |
def make_cutter(self):
"""
Makes a shape to be used as a negative; it can be cut away from other
shapes to make a perfectly shaped pocket for this part.
For example, for a countersunk screw with a neck, the following
cutter would be generated.
.. image:: /_static/img/fa... | [
"def",
"make_cutter",
"(",
"self",
")",
":",
"# head",
"obj",
"=",
"self",
".",
"head",
".",
"make_cutter",
"(",
")",
"# neck",
"if",
"self",
".",
"neck_length",
":",
"# neck cut diameter (if thread is larger than the neck, thread must fit through)",
"(",
"inner_radiu... | 36.242424 | 23.333333 |
def lotus_root_data():
"""Tomographic X-ray data of a lotus root.
Notes
-----
See the article `Tomographic X-ray data of a lotus root filled with
attenuating objects`_ for further information.
See Also
--------
lotus_root_geometry
References
----------
.. _Tomographic X-ra... | [
"def",
"lotus_root_data",
"(",
")",
":",
"# TODO: Store data in some ODL controlled url",
"url",
"=",
"'http://www.fips.fi/dataset/CT_Lotus_v1/sinogram.mat'",
"dct",
"=",
"get_data",
"(",
"'lotus_root.mat'",
",",
"subset",
"=",
"DATA_SUBSET",
",",
"url",
"=",
"url",
")",
... | 27.807692 | 22.692308 |
def _normalizePoint(self, x, y):
"""Check if a point is in bounds and make minor adjustments.
Respects Pythons negative indexes. -1 starts at the bottom right.
Replaces the _drawable function
"""
# cast to int, always faster than type checking
x = int(x)
y = int... | [
"def",
"_normalizePoint",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"# cast to int, always faster than type checking",
"x",
"=",
"int",
"(",
"x",
")",
"y",
"=",
"int",
"(",
"y",
")",
"assert",
"(",
"-",
"self",
".",
"width",
"<=",
"x",
"<",
"self",
... | 35.6875 | 18.25 |
def parse_v3_unit_placement(placement_str):
"""Return a UnitPlacement for bundles version 3, given a placement string.
See https://github.com/juju/charmstore/blob/v4/docs/bundles.md
Raise a ValueError if the placement is not valid.
"""
placement = placement_str
container = machine = service = u... | [
"def",
"parse_v3_unit_placement",
"(",
"placement_str",
")",
":",
"placement",
"=",
"placement_str",
"container",
"=",
"machine",
"=",
"service",
"=",
"unit",
"=",
"''",
"if",
"':'",
"in",
"placement",
":",
"try",
":",
"container",
",",
"placement",
"=",
"pl... | 39.771429 | 14.828571 |
def update_contributions(sender, instance, action, model, pk_set, **kwargs):
"""Creates a contribution for each author added to an article.
"""
if action != 'pre_add':
return
else:
for author in model.objects.filter(pk__in=pk_set):
update_content_contributions(instance, autho... | [
"def",
"update_contributions",
"(",
"sender",
",",
"instance",
",",
"action",
",",
"model",
",",
"pk_set",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action",
"!=",
"'pre_add'",
":",
"return",
"else",
":",
"for",
"author",
"in",
"model",
".",
"objects",
... | 39.375 | 17.75 |
def create_tarfile(self):
"""
Create a tar file with the contents of the current directory
"""
floyd_logger.info("Compressing data...")
# Show progress bar (file_compressed/file_to_compress)
self.__compression_bar = ProgressBar(expected_size=self.__files_to_compress, fill... | [
"def",
"create_tarfile",
"(",
"self",
")",
":",
"floyd_logger",
".",
"info",
"(",
"\"Compressing data...\"",
")",
"# Show progress bar (file_compressed/file_to_compress)",
"self",
".",
"__compression_bar",
"=",
"ProgressBar",
"(",
"expected_size",
"=",
"self",
".",
"__f... | 52.327586 | 23.672414 |
def example_exc_handler(tries_remaining, exception, delay):
"""Example exception handler; prints a warning to stderr.
tries_remaining: The number of tries remaining.
exception: The exception instance which was raised.
"""
print >> sys.stderr, "Caught '%s', %d tries remaining, sleeping for %s second... | [
"def",
"example_exc_handler",
"(",
"tries_remaining",
",",
"exception",
",",
"delay",
")",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"Caught '%s', %d tries remaining, sleeping for %s seconds\"",
"%",
"(",
"exception",
",",
"tries_remaining",
",",
"delay",
")"
] | 45.25 | 16.75 |
def writeTicks(self, ticks):
''' read quotes '''
tName = self.tableName(HBaseDAM.TICK)
if tName not in self.__hbase.getTableNames():
self.__hbase.createTable(tName, [ColumnDescriptor(name=HBaseDAM.TICK, maxVersions=5)])
for tick in ticks:
self.__hbase.upda... | [
"def",
"writeTicks",
"(",
"self",
",",
"ticks",
")",
":",
"tName",
"=",
"self",
".",
"tableName",
"(",
"HBaseDAM",
".",
"TICK",
")",
"if",
"tName",
"not",
"in",
"self",
".",
"__hbase",
".",
"getTableNames",
"(",
")",
":",
"self",
".",
"__hbase",
".",... | 53.272727 | 26.909091 |
def process_star(filename, output, *, extension, star_name, period, shift,
parameters, period_label, shift_label, **kwargs):
"""Processes a star's lightcurve, prints its coefficients, and saves
its plotted lightcurve to a file. Returns the result of get_lightcurve.
"""
if star_name is N... | [
"def",
"process_star",
"(",
"filename",
",",
"output",
",",
"*",
",",
"extension",
",",
"star_name",
",",
"period",
",",
"shift",
",",
"parameters",
",",
"period_label",
",",
"shift_label",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"star_name",
"is",
"Non... | 37.352941 | 18.676471 |
def _progress(bytes_received, bytes_total, worker):
"""Return download progress."""
worker.sig_download_progress.emit(
worker.url, worker.path, bytes_received, bytes_total) | [
"def",
"_progress",
"(",
"bytes_received",
",",
"bytes_total",
",",
"worker",
")",
":",
"worker",
".",
"sig_download_progress",
".",
"emit",
"(",
"worker",
".",
"url",
",",
"worker",
".",
"path",
",",
"bytes_received",
",",
"bytes_total",
")"
] | 49.25 | 9.5 |
def mro(*bases):
"""Calculate the Method Resolution Order of bases using the C3 algorithm.
Suppose you intended creating a class K with the given base classes. This
function returns the MRO which K would have, *excluding* K itself (since
it doesn't yet exist), as if you had actually created the class.
... | [
"def",
"mro",
"(",
"*",
"bases",
")",
":",
"seqs",
"=",
"[",
"list",
"(",
"C",
".",
"__mro__",
")",
"for",
"C",
"in",
"bases",
"]",
"+",
"[",
"list",
"(",
"bases",
")",
"]",
"res",
"=",
"[",
"]",
"while",
"True",
":",
"non_empty",
"=",
"list"... | 38.285714 | 20.571429 |
def createFromURL(urlOfXMLDefinition):
"""Factory method to create a DeviceTR64 from an URL to the XML device definitions.
:param str urlOfXMLDefinition:
:return: the new object
:rtype: Wifi
"""
url = urlparse(urlOfXMLDefinition)
if not url.port:
if ... | [
"def",
"createFromURL",
"(",
"urlOfXMLDefinition",
")",
":",
"url",
"=",
"urlparse",
"(",
"urlOfXMLDefinition",
")",
"if",
"not",
"url",
".",
"port",
":",
"if",
"url",
".",
"scheme",
".",
"lower",
"(",
")",
"==",
"\"https\"",
":",
"port",
"=",
"443",
"... | 27.722222 | 15.5 |
def parse(grid_str, mode=MODE_ZINC, charset='utf-8'):
'''
Parse the given Zinc text and return the equivalent data.
'''
# Decode incoming text (or python3 will whine!)
if isinstance(grid_str, six.binary_type):
grid_str = grid_str.decode(encoding=charset)
# Split the separate grids up, t... | [
"def",
"parse",
"(",
"grid_str",
",",
"mode",
"=",
"MODE_ZINC",
",",
"charset",
"=",
"'utf-8'",
")",
":",
"# Decode incoming text (or python3 will whine!)",
"if",
"isinstance",
"(",
"grid_str",
",",
"six",
".",
"binary_type",
")",
":",
"grid_str",
"=",
"grid_str... | 37.5 | 19.25 |
def Enable(self, value):
"enable or disable all top menus"
for i in range(self.GetMenuCount()):
self.EnableTop(i, value) | [
"def",
"Enable",
"(",
"self",
",",
"value",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"GetMenuCount",
"(",
")",
")",
":",
"self",
".",
"EnableTop",
"(",
"i",
",",
"value",
")"
] | 37 | 6.5 |
def get_lines_data(self):
"""
Returns string:line_numbers list
Since all strings are unique it is OK to get line numbers this way.
Since same string can occur several times inside single .json file the values should be popped(FIFO) from the list
:rtype: list
"""
... | [
"def",
"get_lines_data",
"(",
"self",
")",
":",
"encoding",
"=",
"'utf-8'",
"for",
"token",
"in",
"tokenize",
"(",
"self",
".",
"data",
".",
"decode",
"(",
"encoding",
")",
")",
":",
"if",
"token",
".",
"type",
"==",
"'operator'",
":",
"if",
"token",
... | 41.7 | 20.2 |
def subsample(self, down_to=1, new_path=None):
"""Pick a number of sequences from the file pseudo-randomly."""
# Auto path #
if new_path is None: subsampled = self.__class__(new_temp_path())
elif isinstance(new_path, FASTA): subsampled = new_path
else: subsampled =... | [
"def",
"subsample",
"(",
"self",
",",
"down_to",
"=",
"1",
",",
"new_path",
"=",
"None",
")",
":",
"# Auto path #",
"if",
"new_path",
"is",
"None",
":",
"subsampled",
"=",
"self",
".",
"__class__",
"(",
"new_temp_path",
"(",
")",
")",
"elif",
"isinstance... | 43.105263 | 18.210526 |
def get_interpolated_fd_waveform(dtype=numpy.complex64, return_hc=True,
**params):
""" Return a fourier domain waveform approximant, using interpolation
"""
def rulog2(val):
return 2.0 ** numpy.ceil(numpy.log2(float(val)))
orig_approx = params['approximant']
... | [
"def",
"get_interpolated_fd_waveform",
"(",
"dtype",
"=",
"numpy",
".",
"complex64",
",",
"return_hc",
"=",
"True",
",",
"*",
"*",
"params",
")",
":",
"def",
"rulog2",
"(",
"val",
")",
":",
"return",
"2.0",
"**",
"numpy",
".",
"ceil",
"(",
"numpy",
"."... | 34.47541 | 19.196721 |
def get_command_class(self, cmd):
"""
Returns command class from the registry for a given ``cmd``.
:param cmd: command to run (key at the registry)
"""
try:
cmdpath = self.registry[cmd]
except KeyError:
raise CommandError("No such command %r" % cm... | [
"def",
"get_command_class",
"(",
"self",
",",
"cmd",
")",
":",
"try",
":",
"cmdpath",
"=",
"self",
".",
"registry",
"[",
"cmd",
"]",
"except",
"KeyError",
":",
"raise",
"CommandError",
"(",
"\"No such command %r\"",
"%",
"cmd",
")",
"if",
"isinstance",
"("... | 30.866667 | 14.333333 |
def addresses_for_key(gpg, key):
"""
Takes a key and extracts the email addresses for it.
"""
fingerprint = key["fingerprint"]
addresses = []
for key in gpg.list_keys():
if key["fingerprint"] == fingerprint:
addresses.extend([address.split("<")[-1].strip(">")
... | [
"def",
"addresses_for_key",
"(",
"gpg",
",",
"key",
")",
":",
"fingerprint",
"=",
"key",
"[",
"\"fingerprint\"",
"]",
"addresses",
"=",
"[",
"]",
"for",
"key",
"in",
"gpg",
".",
"list_keys",
"(",
")",
":",
"if",
"key",
"[",
"\"fingerprint\"",
"]",
"=="... | 35.818182 | 12.363636 |
def cast_bytes(s, encoding=None):
"""Source: https://github.com/ipython/ipython_genutils"""
if not isinstance(s, bytes):
return encode(s, encoding)
return s | [
"def",
"cast_bytes",
"(",
"s",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"return",
"encode",
"(",
"s",
",",
"encoding",
")",
"return",
"s"
] | 34.4 | 9.8 |
def _dataset_merge_filestore_resource(self, resource, updated_resource, filestore_resources, ignore_fields):
# type: (hdx.data.Resource, hdx.data.Resource, List[hdx.data.Resource], List[str]) -> None
"""Helper method to merge updated resource from dataset into HDX resource read from HDX including filest... | [
"def",
"_dataset_merge_filestore_resource",
"(",
"self",
",",
"resource",
",",
"updated_resource",
",",
"filestore_resources",
",",
"ignore_fields",
")",
":",
"# type: (hdx.data.Resource, hdx.data.Resource, List[hdx.data.Resource], List[str]) -> None",
"if",
"updated_resource",
"."... | 55.7 | 28.85 |
def _get_cores_memory(data, downscale=2):
"""Retrieve cores and memory, using samtools as baseline.
For memory, scaling down because we share with alignment and de-duplication.
"""
resources = config_utils.get_resources("samtools", data["config"])
num_cores = data["config"]["algorithm"].get("num_co... | [
"def",
"_get_cores_memory",
"(",
"data",
",",
"downscale",
"=",
"2",
")",
":",
"resources",
"=",
"config_utils",
".",
"get_resources",
"(",
"\"samtools\"",
",",
"data",
"[",
"\"config\"",
"]",
")",
"num_cores",
"=",
"data",
"[",
"\"config\"",
"]",
"[",
"\"... | 49.3 | 20.7 |
def _parse(batch_cmd):
"""
:rtype: (sh_cmd, batch_to_file_s, batch_from_file)
:returns: parsed result like below:
.. code-block:: python
# when parsing 'diff IN_BATCH0 IN_BATCH1 > OUT_BATCH'
(
'diff /tmp/relshell-AbCDeF /tmp/relshell-uVwXyz',
... | [
"def",
"_parse",
"(",
"batch_cmd",
")",
":",
"cmd_array",
"=",
"shlex",
".",
"split",
"(",
"batch_cmd",
")",
"(",
"cmd_array",
",",
"batch_to_file_s",
")",
"=",
"BatchCommand",
".",
"_parse_in_batches",
"(",
"cmd_array",
")",
"(",
"cmd_array",
",",
"batch_fr... | 41.777778 | 24.666667 |
def parse_content(self, content):
"""
Use all the defined scanners to search the log file, setting the
properties defined in the scanner.
"""
self.lines = content
for scanner in self.scanners:
scanner(self) | [
"def",
"parse_content",
"(",
"self",
",",
"content",
")",
":",
"self",
".",
"lines",
"=",
"content",
"for",
"scanner",
"in",
"self",
".",
"scanners",
":",
"scanner",
"(",
"self",
")"
] | 32.375 | 8.875 |
def scatter(self, x, y, **kwargs):
"""Plot a scatter chart using metadata columns
see pyam.plotting.scatter() for all available options
"""
variables = self.data['variable'].unique()
xisvar = x in variables
yisvar = y in variables
if not xisvar and not yisvar:
... | [
"def",
"scatter",
"(",
"self",
",",
"x",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"variables",
"=",
"self",
".",
"data",
"[",
"'variable'",
"]",
".",
"unique",
"(",
")",
"xisvar",
"=",
"x",
"in",
"variables",
"yisvar",
"=",
"y",
"in",
"variab... | 36.414634 | 14.146341 |
def write(self)->None:
"Writes model gradient statistics to Tensorboard."
if len(self.gradients) == 0: return
norms = [x.data.norm() for x in self.gradients]
self._write_avg_norm(norms=norms)
self._write_median_norm(norms=norms)
self._write_max_norm(norms=norms)
s... | [
"def",
"write",
"(",
"self",
")",
"->",
"None",
":",
"if",
"len",
"(",
"self",
".",
"gradients",
")",
"==",
"0",
":",
"return",
"norms",
"=",
"[",
"x",
".",
"data",
".",
"norm",
"(",
")",
"for",
"x",
"in",
"self",
".",
"gradients",
"]",
"self",... | 39.615385 | 7 |
def get_all_supported_exts_for_type(self, type_to_match: Type[Any], strict: bool) -> Set[str]:
"""
Utility method to return the set of all supported file extensions that may be converted to objects of the given
type. type=JOKER is a joker that means all types
:param type_to_match:
... | [
"def",
"get_all_supported_exts_for_type",
"(",
"self",
",",
"type_to_match",
":",
"Type",
"[",
"Any",
"]",
",",
"strict",
":",
"bool",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"matching",
"=",
"self",
".",
"find_all_matching_parsers",
"(",
"desired_type",
"="... | 48.833333 | 30.5 |
def lowpass_fir(self, frequency, order, beta=5.0, remove_corrupted=True):
""" Lowpass filter the time series using an FIR filtered generated from
the ideal response passed through a kaiser window (beta = 5.0)
Parameters
----------
Time Series: TimeSeries
The time ser... | [
"def",
"lowpass_fir",
"(",
"self",
",",
"frequency",
",",
"order",
",",
"beta",
"=",
"5.0",
",",
"remove_corrupted",
"=",
"True",
")",
":",
"from",
"pycbc",
".",
"filter",
"import",
"lowpass_fir",
"ts",
"=",
"lowpass_fir",
"(",
"self",
",",
"frequency",
... | 44.041667 | 19.208333 |
def _set_level_1(self, v, load=False):
"""
Setter method for level_1, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/isis/level_1 (container)
If this variable is read-only (config: false) ... | [
"def",
"_set_level_1",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",... | 75.181818 | 37.772727 |
def listsdm(sdm, file=None):
"""Generate a standard "listsdm" listing of(A)SDM dataset contents.
sdm (str)
The path to the (A)SDM dataset to parse
file (stream-like object, such as an opened file)
Where to print the human-readable listing. If unspecified, results
go to :data:`sys.stdout`.... | [
"def",
"listsdm",
"(",
"sdm",
",",
"file",
"=",
"None",
")",
":",
"from",
"xml",
".",
"dom",
"import",
"minidom",
"import",
"string",
"def",
"printf",
"(",
"fmt",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
":",
"s",
"=",
"fmt",
... | 39.333333 | 20.324201 |
def get_choices(cli, prog_name, args, incomplete):
"""
:param cli: command definition
:param prog_name: the program that is running
:param args: full list of args
:param incomplete: the incomplete text to autocomplete
:return: all the possible completions for the incomplete
"""
all_args ... | [
"def",
"get_choices",
"(",
"cli",
",",
"prog_name",
",",
"args",
",",
"incomplete",
")",
":",
"all_args",
"=",
"copy",
".",
"deepcopy",
"(",
"args",
")",
"ctx",
"=",
"resolve_ctx",
"(",
"cli",
",",
"prog_name",
",",
"args",
")",
"if",
"ctx",
"is",
"N... | 43.522727 | 19.659091 |
def query_by_attribute(self, key, value, **kwargs):
"""
Get Build Records by attribute.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>... | [
"def",
"query_by_attribute",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"query_by_... | 41.733333 | 15.6 |
def verify_password(password, password_hash):
"""Returns ``True`` if the password matches the supplied hash.
:param password: A plaintext password to verify
:param password_hash: The expected hash value of the password
(usually from your database)
"""
if use_double_hash(pa... | [
"def",
"verify_password",
"(",
"password",
",",
"password_hash",
")",
":",
"if",
"use_double_hash",
"(",
"password_hash",
")",
":",
"password",
"=",
"get_hmac",
"(",
"password",
")",
"return",
"_pwd_context",
".",
"verify",
"(",
"password",
",",
"password_hash",... | 38 | 14.090909 |
def work_in(dirname=None):
"""Context manager version of os.chdir.
When exited, returns to the working directory prior to entering.
"""
curdir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
yield
finally:
os.chdir(curdir) | [
"def",
"work_in",
"(",
"dirname",
"=",
"None",
")",
":",
"curdir",
"=",
"os",
".",
"getcwd",
"(",
")",
"try",
":",
"if",
"dirname",
"is",
"not",
"None",
":",
"os",
".",
"chdir",
"(",
"dirname",
")",
"yield",
"finally",
":",
"os",
".",
"chdir",
"(... | 23.75 | 18.416667 |
def save_named_query(self, alias, querystring, afterwards=None):
"""
add an alias for a query string.
These are stored in the notmuch database and can be used as part of
more complex queries using the syntax "query:alias".
See :manpage:`notmuch-search-terms(7)` for more info.
... | [
"def",
"save_named_query",
"(",
"self",
",",
"alias",
",",
"querystring",
",",
"afterwards",
"=",
"None",
")",
":",
"if",
"self",
".",
"ro",
":",
"raise",
"DatabaseROError",
"(",
")",
"self",
".",
"writequeue",
".",
"append",
"(",
"(",
"'setconfig'",
","... | 40 | 17.157895 |
def make_random_models_table(n_sources, param_ranges, random_state=None):
"""
Make a `~astropy.table.Table` containing randomly generated
parameters for an Astropy model to simulate a set of sources.
Each row of the table corresponds to a source whose parameters are
defined by the column names. Th... | [
"def",
"make_random_models_table",
"(",
"n_sources",
",",
"param_ranges",
",",
"random_state",
"=",
"None",
")",
":",
"prng",
"=",
"check_random_state",
"(",
"random_state",
")",
"sources",
"=",
"Table",
"(",
")",
"for",
"param_name",
",",
"(",
"lower",
",",
... | 39.911392 | 23.860759 |
def run(self):
"""
Called by the threading system
"""
try:
self._connect()
self._register()
while True:
try:
body = self.command_queue.get(block=True, timeout=1 * SECOND)
except queue.Empty:
... | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_connect",
"(",
")",
"self",
".",
"_register",
"(",
")",
"while",
"True",
":",
"try",
":",
"body",
"=",
"self",
".",
"command_queue",
".",
"get",
"(",
"block",
"=",
"True",
",",
"time... | 36.105263 | 16.684211 |
def get(self, name):
"""Returns a Notification by name.
"""
if not self.loaded:
raise RegistryNotLoaded(self)
if not self._registry.get(name):
raise NotificationNotRegistered(
f"Notification not registered. Got '{name}'."
)
retu... | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"self",
".",
"loaded",
":",
"raise",
"RegistryNotLoaded",
"(",
"self",
")",
"if",
"not",
"self",
".",
"_registry",
".",
"get",
"(",
"name",
")",
":",
"raise",
"NotificationNotRegistered",
"... | 33.8 | 8.7 |
def get_inactive() -> List[str]:
"""Return the list of inactive subarrays."""
inactive = []
for i in range(__num_subarrays__):
key = Subarray.get_key(i)
if DB.get_hash_value(key, 'active').upper() == 'FALSE':
inactive.append(Subarray.get_id(i))
ret... | [
"def",
"get_inactive",
"(",
")",
"->",
"List",
"[",
"str",
"]",
":",
"inactive",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"__num_subarrays__",
")",
":",
"key",
"=",
"Subarray",
".",
"get_key",
"(",
"i",
")",
"if",
"DB",
".",
"get_hash_value",
... | 40.625 | 10.875 |
def _zeo_key(self, key, new_type=OOBTree):
"""
Get key from the :attr:`zeo` database root. If the key doesn't exist,
create it by calling `new_type` argument.
Args:
key (str): Key in the root dict.
new_type (func/obj): Object/function returning the new instance.
... | [
"def",
"_zeo_key",
"(",
"self",
",",
"key",
",",
"new_type",
"=",
"OOBTree",
")",
":",
"zeo_key",
"=",
"self",
".",
"zeo",
".",
"get",
"(",
"key",
",",
"None",
")",
"if",
"zeo_key",
"is",
"None",
":",
"zeo_key",
"=",
"new_type",
"(",
")",
"self",
... | 28.526316 | 18.421053 |
def parse(cls, fptr, offset, length):
"""Parse JPX free box.
Parameters
----------
f : file
Open file object.
offset : int
Start position of box in bytes.
length : int
Length of the box in bytes.
Returns
-------
... | [
"def",
"parse",
"(",
"cls",
",",
"fptr",
",",
"offset",
",",
"length",
")",
":",
"# Must seek to end of box.",
"nbytes",
"=",
"offset",
"+",
"length",
"-",
"fptr",
".",
"tell",
"(",
")",
"fptr",
".",
"read",
"(",
"nbytes",
")",
"return",
"cls",
"(",
... | 24.952381 | 15.285714 |
def set_tmp_folder():
""" Create a temporary folder using the current time in which
the zip can be extracted and which should be destroyed afterward.
"""
output = "%s" % datetime.datetime.now()
for char in [' ', ':', '.', '-']:
output = output.replace(char, '')
output.strip()
tmp_fol... | [
"def",
"set_tmp_folder",
"(",
")",
":",
"output",
"=",
"\"%s\"",
"%",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"for",
"char",
"in",
"[",
"' '",
",",
"':'",
",",
"'.'",
",",
"'-'",
"]",
":",
"output",
"=",
"output",
".",
"replace",
"(",
... | 38.2 | 11.6 |
def from_where(cls, where):
""" Factory method for creating the top-level expression """
if where.conjunction:
return Conjunction.from_clause(where)
else:
return cls.from_clause(where[0]) | [
"def",
"from_where",
"(",
"cls",
",",
"where",
")",
":",
"if",
"where",
".",
"conjunction",
":",
"return",
"Conjunction",
".",
"from_clause",
"(",
"where",
")",
"else",
":",
"return",
"cls",
".",
"from_clause",
"(",
"where",
"[",
"0",
"]",
")"
] | 38.333333 | 10.666667 |
def distribution_present(name, region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Ensure the given CloudFront distribution exists in the described state.
The implementation of this function, and all those following, is orthagonal
to that of :py:mod:`boto_cloudfront.present
<salt.states... | [
"def",
"distribution_present",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":"... | 46.249211 | 23.283912 |
def fulfill(self, method, *args, **kwargs):
""" Fulfill an HTTP request to Keen's API. """
return getattr(self.session, method)(*args, **kwargs) | [
"def",
"fulfill",
"(",
"self",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"session",
",",
"method",
")",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 31.6 | 20.8 |
def generate_options():
'''Helper coroutine to identify short options that haven't been used
yet. Yields lists of short option (if available) and long option for
the given name, keeping track of which short options have been previously
used.
If you aren't familiar with coroutines, use similar to a ... | [
"def",
"generate_options",
"(",
")",
":",
"used_short_options",
"=",
"set",
"(",
")",
"param_name",
"=",
"yield",
"while",
"True",
":",
"names",
"=",
"[",
"'--'",
"+",
"param_name",
"]",
"for",
"letter",
"in",
"param_name",
":",
"if",
"letter",
"not",
"i... | 36.952381 | 19.428571 |
def routedResource(f, routerAttribute='router'):
"""
Decorate a router-producing callable to instead produce a resource.
This simply produces a new callable that invokes the original callable, and
calls ``resource`` on the ``routerAttribute``.
If the router producer has multiple routers the attrib... | [
"def",
"routedResource",
"(",
"f",
",",
"routerAttribute",
"=",
"'router'",
")",
":",
"return",
"wraps",
"(",
"f",
")",
"(",
"lambda",
"*",
"a",
",",
"*",
"*",
"kw",
":",
"getattr",
"(",
"f",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
",",
"route... | 32.8 | 21.35 |
def smartypants(text):
"""
Transforms sequences of characters into HTML entities.
=================================== ===================== =========
Markdown HTML Result
=================================== ===================== =========
``'s``... | [
"def",
"smartypants",
"(",
"text",
")",
":",
"byte_str",
"=",
"text",
".",
"encode",
"(",
"'utf-8'",
")",
"ob",
"=",
"lib",
".",
"hoedown_buffer_new",
"(",
"OUNIT",
")",
"lib",
".",
"hoedown_html_smartypants",
"(",
"ob",
",",
"byte_str",
",",
"len",
"(",... | 47.896552 | 22.655172 |
def load_tool(result):
"""
Load the module with the tool-specific code.
"""
def load_tool_module(tool_module):
if not tool_module:
logging.warning('Cannot extract values from log files for benchmark results %s '
'(missing attribute "toolmodule" on tag "res... | [
"def",
"load_tool",
"(",
"result",
")",
":",
"def",
"load_tool_module",
"(",
"tool_module",
")",
":",
"if",
"not",
"tool_module",
":",
"logging",
".",
"warning",
"(",
"'Cannot extract values from log files for benchmark results %s '",
"'(missing attribute \"toolmodule\" on ... | 40.774194 | 19.354839 |
def _hash(expr, func=None):
"""
Calculate the hash value.
:param expr:
:param func: hash function
:return:
"""
if func is None:
func = lambda x: hash(x)
return _map(expr, func=func, rtype=types.int64) | [
"def",
"_hash",
"(",
"expr",
",",
"func",
"=",
"None",
")",
":",
"if",
"func",
"is",
"None",
":",
"func",
"=",
"lambda",
"x",
":",
"hash",
"(",
"x",
")",
"return",
"_map",
"(",
"expr",
",",
"func",
"=",
"func",
",",
"rtype",
"=",
"types",
".",
... | 19.25 | 17.083333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.