text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def order_expr(cls_or_alias, *columns):
"""
Forms expressions like [desc(User.first_name), asc(User.phone)]
from list like ['-first_name', 'phone']
Example for 1 column:
db.query(User).order_by(*User.order_expr('-first_name'))
# will compile to ORDER BY user.first_... | [
"def",
"order_expr",
"(",
"cls_or_alias",
",",
"*",
"columns",
")",
":",
"if",
"isinstance",
"(",
"cls_or_alias",
",",
"AliasedClass",
")",
":",
"mapper",
",",
"cls",
"=",
"cls_or_alias",
",",
"inspect",
"(",
"cls_or_alias",
")",
".",
"mapper",
".",
"class... | 38.612903 | 19.129032 |
def _set_django_attributes(span, request):
"""Set the django related attributes."""
django_user = getattr(request, 'user', None)
if django_user is None:
return
user_id = django_user.pk
try:
user_name = django_user.get_username()
except AttributeError:
# AnonymousUser in... | [
"def",
"_set_django_attributes",
"(",
"span",
",",
"request",
")",
":",
"django_user",
"=",
"getattr",
"(",
"request",
",",
"'user'",
",",
"None",
")",
"if",
"django_user",
"is",
"None",
":",
"return",
"user_id",
"=",
"django_user",
".",
"pk",
"try",
":",
... | 30.47619 | 21.238095 |
def _set_channel_group(self, v, load=False):
"""
Setter method for channel_group, mapped from YANG variable /interface/ethernet/channel_group (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_channel_group is considered as a private
method. Backends looking... | [
"def",
"_set_channel_group",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | 82.72 | 40.36 |
def render_tag(self, context, caller, **kwargs):
'''render content with "active" urls logic'''
# load configuration from passed options
self.load_configuration(**kwargs)
# get request from context
request = context['request']
# get full path from request
self.fu... | [
"def",
"render_tag",
"(",
"self",
",",
"context",
",",
"caller",
",",
"*",
"*",
"kwargs",
")",
":",
"# load configuration from passed options",
"self",
".",
"load_configuration",
"(",
"*",
"*",
"kwargs",
")",
"# get request from context",
"request",
"=",
"context"... | 28.68 | 14.84 |
def groupby2(records, kfield, vfield):
"""
:param records: a sequence of records with positional or named fields
:param kfield: the index/name/tuple specifying the field to use as a key
:param vfield: the index/name/tuple specifying the field to use as a value
:returns: an list of pairs of the form ... | [
"def",
"groupby2",
"(",
"records",
",",
"kfield",
",",
"vfield",
")",
":",
"if",
"isinstance",
"(",
"kfield",
",",
"tuple",
")",
":",
"kgetter",
"=",
"operator",
".",
"itemgetter",
"(",
"*",
"kfield",
")",
"else",
":",
"kgetter",
"=",
"operator",
".",
... | 40.28 | 19.72 |
def get_children(self):
"""Gets the children of this composition.
return: (osid.repository.CompositionList) - the composition
children
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
# ... | [
"def",
"get_children",
"(",
"self",
")",
":",
"# Implemented from template for osid.learning.Activity.get_assets_template",
"if",
"not",
"bool",
"(",
"self",
".",
"_my_map",
"[",
"'childIds'",
"]",
")",
":",
"raise",
"errors",
".",
"IllegalState",
"(",
"'no childIds'"... | 46.5 | 23.7 |
def get_detectors(self, name=None, tags=None, batch_size=100, **kwargs):
"""Retrieve all (v2) detectors matching the given name; all (v2)
detectors otherwise.
Note that this method will loop through the paging of the results and
accumulate all detectors that match the query. This may be... | [
"def",
"get_detectors",
"(",
"self",
",",
"name",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"batch_size",
"=",
"100",
",",
"*",
"*",
"kwargs",
")",
":",
"detectors",
"=",
"[",
"]",
"offset",
"=",
"0",
"while",
"True",
":",
"resp",
"=",
"self",
... | 35.730769 | 14.307692 |
def _installed_snpeff_genome(base_name, config):
"""Find the most recent installed genome for snpEff with the given name.
"""
snpeff_config_file = os.path.join(config_utils.get_program("snpeff", config, "dir"),
"snpEff.config")
if os.path.exists(snpeff_config_file):... | [
"def",
"_installed_snpeff_genome",
"(",
"base_name",
",",
"config",
")",
":",
"snpeff_config_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config_utils",
".",
"get_program",
"(",
"\"snpeff\"",
",",
"config",
",",
"\"dir\"",
")",
",",
"\"snpEff.config\"",
"... | 44.9375 | 20.625 |
def run(self):
""" Construct the document id from the date and the url. """
document = {}
document['_id'] = hashlib.sha1('%s:%s' % (
self.date, self.url)).hexdigest()
with self.input().open() as handle:
document['content'] = handle.read(... | [
"def",
"run",
"(",
"self",
")",
":",
"document",
"=",
"{",
"}",
"document",
"[",
"'_id'",
"]",
"=",
"hashlib",
".",
"sha1",
"(",
"'%s:%s'",
"%",
"(",
"self",
".",
"date",
",",
"self",
".",
"url",
")",
")",
".",
"hexdigest",
"(",
")",
"with",
"s... | 46.636364 | 13.363636 |
def checkout(self, paths=None, force=False, fprogress=lambda *args: None, **kwargs):
"""Checkout the given paths or all files from the version known to the index into
the working tree.
:note: Be sure you have written pending changes using the ``write`` method
in case you have altere... | [
"def",
"checkout",
"(",
"self",
",",
"paths",
"=",
"None",
",",
"force",
"=",
"False",
",",
"fprogress",
"=",
"lambda",
"*",
"args",
":",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"\"--index\"",
"]",
"if",
"force",
":",
"args",
... | 46.109677 | 21.709677 |
def shift_multi(
x, wrg=0.1, hrg=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0.,
order=1
):
"""Shift images with the same arguments, randomly or non-randomly.
Usually be used for image segmentation which x=[X, Y], X and Y should be matched.
Par... | [
"def",
"shift_multi",
"(",
"x",
",",
"wrg",
"=",
"0.1",
",",
"hrg",
"=",
"0.1",
",",
"is_random",
"=",
"False",
",",
"row_index",
"=",
"0",
",",
"col_index",
"=",
"1",
",",
"channel_index",
"=",
"2",
",",
"fill_mode",
"=",
"'nearest'",
",",
"cval",
... | 32.636364 | 25.878788 |
def delims(self, delims):
"""Set the delimiters for line splitting."""
expr = '[' + ''.join('\\'+ c for c in delims) + ']'
self._delim_re = re.compile(expr)
self._delims = delims
self._delim_expr = expr | [
"def",
"delims",
"(",
"self",
",",
"delims",
")",
":",
"expr",
"=",
"'['",
"+",
"''",
".",
"join",
"(",
"'\\\\'",
"+",
"c",
"for",
"c",
"in",
"delims",
")",
"+",
"']'",
"self",
".",
"_delim_re",
"=",
"re",
".",
"compile",
"(",
"expr",
")",
"sel... | 39.5 | 9.166667 |
def half_light_radius_lens(self, kwargs_lens_light, center_x=0, center_y=0, model_bool_list=None, deltaPix=None, numPix=None):
"""
computes numerically the half-light-radius of the deflector light and the total photon flux
:param kwargs_lens_light:
:return:
"""
if model_... | [
"def",
"half_light_radius_lens",
"(",
"self",
",",
"kwargs_lens_light",
",",
"center_x",
"=",
"0",
",",
"center_y",
"=",
"0",
",",
"model_bool_list",
"=",
"None",
",",
"deltaPix",
"=",
"None",
",",
"numPix",
"=",
"None",
")",
":",
"if",
"model_bool_list",
... | 44.631579 | 26.631579 |
def get_datetime_type(to_string):
""" Validates UTC datetime. Examples of accepted forms:
2017-12-31T01:11:59Z,2017-12-31T01:11Z or 2017-12-31T01Z or 2017-12-31 """
from datetime import datetime
def datetime_type(string):
""" Validates UTC datetime. Examples of accepted forms:
2017-12-3... | [
"def",
"get_datetime_type",
"(",
"to_string",
")",
":",
"from",
"datetime",
"import",
"datetime",
"def",
"datetime_type",
"(",
"string",
")",
":",
"\"\"\" Validates UTC datetime. Examples of accepted forms:\n 2017-12-31T01:11:59Z,2017-12-31T01:11Z or 2017-12-31T01Z or 2017-12-... | 43 | 18.238095 |
def getHook(self, repo_user, repo_name, hook_id):
"""
GET /repos/:owner/:repo/hooks/:id
Returns the Hook.
"""
return self.api.makeRequest(
['repos', repo_user, repo_name, 'hooks', str(hook_id)],
method='GET',
) | [
"def",
"getHook",
"(",
"self",
",",
"repo_user",
",",
"repo_name",
",",
"hook_id",
")",
":",
"return",
"self",
".",
"api",
".",
"makeRequest",
"(",
"[",
"'repos'",
",",
"repo_user",
",",
"repo_name",
",",
"'hooks'",
",",
"str",
"(",
"hook_id",
")",
"]"... | 27.8 | 13.8 |
def get_orga(self, orgaPk):
"""Return an organization speficied with orgaPk"""
r = self._request('orga/' + str(orgaPk))
if r:
# Set base properties and copy data inside the orga
o = Orga()
o.pk = o.id = orgaPk
o.__dict__.update(r.json())
... | [
"def",
"get_orga",
"(",
"self",
",",
"orgaPk",
")",
":",
"r",
"=",
"self",
".",
"_request",
"(",
"'orga/'",
"+",
"str",
"(",
"orgaPk",
")",
")",
"if",
"r",
":",
"# Set base properties and copy data inside the orga",
"o",
"=",
"Orga",
"(",
")",
"o",
".",
... | 34.1 | 13.9 |
def _handle_put(self, request):
# type: (Put) -> CallbackResponses
"""Called with the lock taken"""
attribute_name = request.path[1]
attribute = self._block[attribute_name]
assert isinstance(attribute, AttributeModel), \
"Cannot Put to %s which is a %s" % (attribute.... | [
"def",
"_handle_put",
"(",
"self",
",",
"request",
")",
":",
"# type: (Put) -> CallbackResponses",
"attribute_name",
"=",
"request",
".",
"path",
"[",
"1",
"]",
"attribute",
"=",
"self",
".",
"_block",
"[",
"attribute_name",
"]",
"assert",
"isinstance",
"(",
"... | 40.730769 | 18.038462 |
def parse_DID(did, name_type=None):
"""
Given a DID string, parse it into {'address': ..., 'index': ..., 'name_type'}
Raise on invalid DID
"""
did_pattern = '^did:stack:v0:({}{{25,35}})-([0-9]+)$'.format(OP_BASE58CHECK_CLASS)
m = re.match(did_pattern, did)
assert m, 'Invalid DID: {}'.format... | [
"def",
"parse_DID",
"(",
"did",
",",
"name_type",
"=",
"None",
")",
":",
"did_pattern",
"=",
"'^did:stack:v0:({}{{25,35}})-([0-9]+)$'",
".",
"format",
"(",
"OP_BASE58CHECK_CLASS",
")",
"m",
"=",
"re",
".",
"match",
"(",
"did_pattern",
",",
"did",
")",
"assert"... | 34.548387 | 24.290323 |
def mechanism(self, x):
"""Mechanism function."""
self.nb_step += 1
x = np.reshape(x, (x.shape[0], 1))
if(self.nb_step < 5):
cov = computeGaussKernel(x)
mean = np.zeros((1, self.points))[0, :]
y = np.random.multivariate_normal(mean, cov)
elif(... | [
"def",
"mechanism",
"(",
"self",
",",
"x",
")",
":",
"self",
".",
"nb_step",
"+=",
"1",
"x",
"=",
"np",
".",
"reshape",
"(",
"x",
",",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
",",
"1",
")",
")",
"if",
"(",
"self",
".",
"nb_step",
"<",
"5",
... | 32.7 | 13.45 |
def get_me(self):
"""
A simple method for testing your bot's auth token. Requires no parameters.
Returns basic information about the bot in form of a :class:`pytgbot.api_types.receivable.peer.User` object.
https://core.telegram.org/bots/api#getme
Returns:
:return: Ret... | [
"def",
"get_me",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"do",
"(",
"\"getMe\"",
")",
"if",
"self",
".",
"return_python_objects",
":",
"logger",
".",
"debug",
"(",
"\"Trying to parse {data}\"",
".",
"format",
"(",
"data",
"=",
"repr",
"(",
"re... | 39.846154 | 23.923077 |
def _write_jsonl(filepath, data, kwargs):
"""See documentation of mpu.io.write."""
with io_stl.open(filepath, 'w', encoding='utf8') as outfile:
kwargs['indent'] = None # JSON has to be on one line!
if 'sort_keys' not in kwargs:
kwargs['sort_keys'] = True
if 'separators' not ... | [
"def",
"_write_jsonl",
"(",
"filepath",
",",
"data",
",",
"kwargs",
")",
":",
"with",
"io_stl",
".",
"open",
"(",
"filepath",
",",
"'w'",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"outfile",
":",
"kwargs",
"[",
"'indent'",
"]",
"=",
"None",
"# JSON ha... | 40.8 | 7.866667 |
def build(self, build_execution_configuration, **kwargs):
"""
Triggers the build execution for a given configuration.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when rec... | [
"def",
"build",
"(",
"self",
",",
"build_execution_configuration",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"build_with_htt... | 49.703704 | 25.037037 |
def p_lpartselect_lpointer_minus(self, p):
'lpartselect : pointer LBRACKET expression MINUSCOLON expression RBRACKET'
p[0] = Partselect(p[1], p[3], Minus(p[3], p[5]), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_lpartselect_lpointer_minus",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Partselect",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"Minus",
"(",
"p",
"[",
"3",
"]",
",",
"p",
"[",
"5",
"]",
")",
",",
"line... | 59 | 21 |
def del_routing_area(self, routing_area, sync=True):
"""
delete routing area from this location
:param routing_area: the routing area to be deleted from this location
:param sync: If sync=True(default) synchronize with Ariane server. If sync=False,
add the routing area object on ... | [
"def",
"del_routing_area",
"(",
"self",
",",
"routing_area",
",",
"sync",
"=",
"True",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Location.del_routing_area\"",
")",
"if",
"not",
"sync",
":",
"self",
".",
"routing_areas_2_rm",
".",
"append",
"(",
"routing_area",... | 49.285714 | 23.571429 |
def compute_affinity_matrix(self, copy=False, **kwargs):
"""
This function will compute the affinity matrix. In order to
acquire the existing affinity matrix use self.affinity_matrix as
comptute_affinity_matrix() will re-compute the affinity matrix.
Parameters
----------... | [
"def",
"compute_affinity_matrix",
"(",
"self",
",",
"copy",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"adjacency_matrix",
"is",
"None",
":",
"self",
".",
"compute_adjacency_matrix",
"(",
")",
"kwds",
"=",
"self",
".",
"affinity_kw... | 38.806452 | 21.258065 |
def await_reservations(self):
"""Poll until all reservations completed, then return cluster_info."""
done = False
while not done:
done = self._request('QUERY')
time.sleep(1)
return self.get_reservations() | [
"def",
"await_reservations",
"(",
"self",
")",
":",
"done",
"=",
"False",
"while",
"not",
"done",
":",
"done",
"=",
"self",
".",
"_request",
"(",
"'QUERY'",
")",
"time",
".",
"sleep",
"(",
"1",
")",
"return",
"self",
".",
"get_reservations",
"(",
")"
] | 32.285714 | 12.571429 |
def _get_frag_constr_table(self, start_atom=None, predefined_table=None,
use_lookup=None, bond_dict=None):
"""Create a construction table for a Zmatrix.
A construction table is basically a Zmatrix without the values
for the bond lenghts, angles and dihedrals.
... | [
"def",
"_get_frag_constr_table",
"(",
"self",
",",
"start_atom",
"=",
"None",
",",
"predefined_table",
"=",
"None",
",",
"use_lookup",
"=",
"None",
",",
"bond_dict",
"=",
"None",
")",
":",
"if",
"use_lookup",
"is",
"None",
":",
"use_lookup",
"=",
"settings",... | 44.271429 | 18.328571 |
def make_filename(s, allow_whitespace=False, allow_underscore=False, allow_hyphen=False, limit=255, lower=False):
r"""Make sure the provided string is a valid filename, and optionally remove whitespace
>>> make_filename('Not so great!')
'Notsogreat'
>>> make_filename('')
'empty'
>>> make_filena... | [
"def",
"make_filename",
"(",
"s",
",",
"allow_whitespace",
"=",
"False",
",",
"allow_underscore",
"=",
"False",
",",
"allow_hyphen",
"=",
"False",
",",
"limit",
"=",
"255",
",",
"lower",
"=",
"False",
")",
":",
"s",
"=",
"stringify",
"(",
"s",
")",
"s"... | 30.92 | 17.32 |
def set_annotation_spdx_id(self, doc, spdx_id):
"""Sets the annotation SPDX Identifier.
Raises CardinalityError if already set. OrderError if no annotator
defined before.
"""
if len(doc.annotations) != 0:
if not self.annotation_spdx_id_set:
self.annota... | [
"def",
"set_annotation_spdx_id",
"(",
"self",
",",
"doc",
",",
"spdx_id",
")",
":",
"if",
"len",
"(",
"doc",
".",
"annotations",
")",
"!=",
"0",
":",
"if",
"not",
"self",
".",
"annotation_spdx_id_set",
":",
"self",
".",
"annotation_spdx_id_set",
"=",
"True... | 39.857143 | 13.285714 |
def coords_from_query(query):
"""Transform a query line into a (lng, lat) pair of coordinates."""
try:
coords = json.loads(query)
except ValueError:
vals = re.split(r'[,\s]+', query.strip())
coords = [float(v) for v in vals]
return tuple(coords[:2]) | [
"def",
"coords_from_query",
"(",
"query",
")",
":",
"try",
":",
"coords",
"=",
"json",
".",
"loads",
"(",
"query",
")",
"except",
"ValueError",
":",
"vals",
"=",
"re",
".",
"split",
"(",
"r'[,\\s]+'",
",",
"query",
".",
"strip",
"(",
")",
")",
"coord... | 35.25 | 11.125 |
def format_output(instances, flag):
"""return formatted string per instance"""
out = []
line_format = '{0}\t{1}\t{2}\t{3}'
name_len = _get_max_name_len(instances) + 3
if flag:
line_format = '{0:<' + str(name_len+5) + '}{1:<16}{2:<65}{3:<16}'
for i in instances:
endpoint = "{0}:{... | [
"def",
"format_output",
"(",
"instances",
",",
"flag",
")",
":",
"out",
"=",
"[",
"]",
"line_format",
"=",
"'{0}\\t{1}\\t{2}\\t{3}'",
"name_len",
"=",
"_get_max_name_len",
"(",
"instances",
")",
"+",
"3",
"if",
"flag",
":",
"line_format",
"=",
"'{0:<'",
"+",... | 39 | 24.230769 |
def html_to_rgb(html):
"""Convert the HTML color to (r, g, b).
Parameters:
:html:
the HTML definition of the color (#RRGGBB or #RGB or a color name).
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...1],
b[0...1]
Throws:
:ValueError:
If html is neither... | [
"def",
"html_to_rgb",
"(",
"html",
")",
":",
"html",
"=",
"html",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"html",
"[",
"0",
"]",
"==",
"'#'",
":",
"html",
"=",
"html",
"[",
"1",
":",
"]",
"elif",
"html",
"in",
"NAMED_COLOR",
":",
... | 23.977273 | 20.886364 |
def params(self):
"""
URL parameters for wq.io.loaders.NetLoader
"""
params, complex = self.get_params()
url_params = self.default_params.copy()
url_params.update(self.serialize_params(params, complex))
return url_params | [
"def",
"params",
"(",
"self",
")",
":",
"params",
",",
"complex",
"=",
"self",
".",
"get_params",
"(",
")",
"url_params",
"=",
"self",
".",
"default_params",
".",
"copy",
"(",
")",
"url_params",
".",
"update",
"(",
"self",
".",
"serialize_params",
"(",
... | 33.625 | 10.375 |
def read_config(ip, mac):
"""Read the current configuration of a myStrom device."""
click.echo("Read configuration from %s" % ip)
request = requests.get(
'http://{}/{}/{}/'.format(ip, URI, mac), timeout=TIMEOUT)
print(request.json()) | [
"def",
"read_config",
"(",
"ip",
",",
"mac",
")",
":",
"click",
".",
"echo",
"(",
"\"Read configuration from %s\"",
"%",
"ip",
")",
"request",
"=",
"requests",
".",
"get",
"(",
"'http://{}/{}/{}/'",
".",
"format",
"(",
"ip",
",",
"URI",
",",
"mac",
")",
... | 42 | 12.833333 |
def from_exception(cls, exc):
"""
Construct a new :class:`Error` payload from the attributes of the
exception.
:param exc: The exception to convert
:type exc: :class:`aioxmpp.errors.XMPPError`
:result: Newly constructed error payload
:rtype: :class:`Error`
... | [
"def",
"from_exception",
"(",
"cls",
",",
"exc",
")",
":",
"result",
"=",
"cls",
"(",
"condition",
"=",
"exc",
".",
"condition",
",",
"type_",
"=",
"exc",
".",
"TYPE",
",",
"text",
"=",
"exc",
".",
"text",
")",
"result",
".",
"application_condition",
... | 30.727273 | 18.181818 |
def elcm_session_list(irmc_info):
"""send an eLCM request to list all sessions
:param irmc_info: node info
:returns: dict object of sessions if succeed
{
'SessionList':
{
'Contains':
[
{ 'Id': id1, 'Name': name1 },
{ 'Id': id2,... | [
"def",
"elcm_session_list",
"(",
"irmc_info",
")",
":",
"# Send GET request to the server",
"resp",
"=",
"elcm_request",
"(",
"irmc_info",
",",
"method",
"=",
"'GET'",
",",
"path",
"=",
"'/sessionInformation/'",
")",
"if",
"resp",
".",
"status_code",
"==",
"200",
... | 30.142857 | 16.464286 |
def _revint(self, version):
'''
Internal function to convert a version string to an integer.
'''
intrev = 0
vsplit = version.split('.')
for c in range(len(vsplit)):
item = int(vsplit[c]) * (10 ** (((len(vsplit) - c - 1) * 2)))
intrev += item
... | [
"def",
"_revint",
"(",
"self",
",",
"version",
")",
":",
"intrev",
"=",
"0",
"vsplit",
"=",
"version",
".",
"split",
"(",
"'.'",
")",
"for",
"c",
"in",
"range",
"(",
"len",
"(",
"vsplit",
")",
")",
":",
"item",
"=",
"int",
"(",
"vsplit",
"[",
"... | 32.6 | 19.6 |
def get_lines_from_file(filename, lineno, context_lines, loader=None, module_name=None):
"""
Returns context_lines before and after lineno from file.
Returns (pre_context_lineno, pre_context, context_line, post_context).
"""
lineno = lineno - 1
lower_bound = max(0, lineno - context_lines)
up... | [
"def",
"get_lines_from_file",
"(",
"filename",
",",
"lineno",
",",
"context_lines",
",",
"loader",
"=",
"None",
",",
"module_name",
"=",
"None",
")",
":",
"lineno",
"=",
"lineno",
"-",
"1",
"lower_bound",
"=",
"max",
"(",
"0",
",",
"lineno",
"-",
"contex... | 41.825 | 20.575 |
def read_file(self, path, **kwargs):
"""Read file input into memory, returning deserialized objects
:param path: Path of file to read
"""
try:
parsed_data = Parser().parse_file(path)
return parsed_data
except (IOError, TypeError, ImportError):
... | [
"def",
"read_file",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"parsed_data",
"=",
"Parser",
"(",
")",
".",
"parse_file",
"(",
"path",
")",
"return",
"parsed_data",
"except",
"(",
"IOError",
",",
"TypeError",
",",
"ImportE... | 35 | 13.636364 |
def read(self, nodes=None, **kwargs):
"""Load datasets from the necessary reader.
Args:
nodes (iterable): DependencyTree Node objects
**kwargs: Keyword arguments to pass to the reader's `load` method.
Returns:
DatasetDict of loaded datasets
"""
... | [
"def",
"read",
"(",
"self",
",",
"nodes",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"nodes",
"is",
"None",
":",
"required_nodes",
"=",
"self",
".",
"wishlist",
"-",
"set",
"(",
"self",
".",
"datasets",
".",
"keys",
"(",
")",
")",
"nod... | 34.2 | 20.6 |
def parse(self, text):
"""Call the server and return the raw results."""
if isinstance(text, bytes):
text = text.decode("ascii")
text = re.sub("\s+", " ", unidecode(text))
return self.communicate(text + "\n") | [
"def",
"parse",
"(",
"self",
",",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"bytes",
")",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"\"ascii\"",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"\"\\s+\"",
",",
"\" \"",
",",
"unidecode",
... | 41.166667 | 6.333333 |
async def _perform_ping_timeout(self, delay: int):
""" Handle timeout gracefully.
Args:
delay (int): delay before raising the timeout (in seconds)
"""
# pause for delay seconds
await sleep(delay)
# then continue
error = TimeoutError(
'Pin... | [
"async",
"def",
"_perform_ping_timeout",
"(",
"self",
",",
"delay",
":",
"int",
")",
":",
"# pause for delay seconds",
"await",
"sleep",
"(",
"delay",
")",
"# then continue",
"error",
"=",
"TimeoutError",
"(",
"'Ping timeout: no data received from server in {timeout} seco... | 32.928571 | 17.571429 |
def get_app_template_dir(app_name):
"""
Get the template directory for an application
We do not use django.db.models.get_app, because this will fail if an
app does not have any models.
Returns a full path, or None if the app was not found.
"""
if app_name in _cache:
return _cache[a... | [
"def",
"get_app_template_dir",
"(",
"app_name",
")",
":",
"if",
"app_name",
"in",
"_cache",
":",
"return",
"_cache",
"[",
"app_name",
"]",
"template_dir",
"=",
"None",
"for",
"app",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"if",
"app",
".",
"split",
"... | 33.761905 | 15.571429 |
def copy_texture_memory_args(self, texmem_args):
"""adds texture memory arguments to the most recently compiled module, if using CUDA"""
if self.lang == "CUDA":
self.dev.copy_texture_memory_args(texmem_args)
else:
raise Exception("Error cannot copy texture memory argument... | [
"def",
"copy_texture_memory_args",
"(",
"self",
",",
"texmem_args",
")",
":",
"if",
"self",
".",
"lang",
"==",
"\"CUDA\"",
":",
"self",
".",
"dev",
".",
"copy_texture_memory_args",
"(",
"texmem_args",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Error canno... | 57.333333 | 20.166667 |
def sbo_network(self):
"""View slackbuilds packages
"""
flag = []
options = [
"-n",
"--network"
]
additional_options = [
"--checklist",
"--case-ins"
]
for add in additional_options:
if add in self... | [
"def",
"sbo_network",
"(",
"self",
")",
":",
"flag",
"=",
"[",
"]",
"options",
"=",
"[",
"\"-n\"",
",",
"\"--network\"",
"]",
"additional_options",
"=",
"[",
"\"--checklist\"",
",",
"\"--case-ins\"",
"]",
"for",
"add",
"in",
"additional_options",
":",
"if",
... | 27.619048 | 14.714286 |
def _get_prefix_length(number1, number2, bits):
"""Get the number of leading bits that are same for two numbers.
Args:
number1: an integer.
number2: another integer.
bits: the maximum number of bits to compare.
Returns:
The number of leading bits that are the same for two n... | [
"def",
"_get_prefix_length",
"(",
"number1",
",",
"number2",
",",
"bits",
")",
":",
"for",
"i",
"in",
"range",
"(",
"bits",
")",
":",
"if",
"number1",
">>",
"i",
"==",
"number2",
">>",
"i",
":",
"return",
"bits",
"-",
"i",
"return",
"0"
] | 26.8125 | 18.875 |
def get_cited_dois(file):
"""
Get the DOIs of the papers cited in a plaintext file. The file should \
have one citation per line.
.. note::
This function is also used as a backend tool by most of the others \
citations processors, to factorize the code.
:param file: Either... | [
"def",
"get_cited_dois",
"(",
"file",
")",
":",
"# If file is not a pre-processed list of plaintext citations",
"if",
"not",
"isinstance",
"(",
"file",
",",
"list",
")",
":",
"# It is either a path to a plaintext file or the content of a plaintext",
"# file, we need some pre-proces... | 42.265625 | 19.703125 |
def add_composite_field(self, name, field):
"""
Add a dynamic composite field to the already existing ones and
initialize it appropriatly.
"""
self.composite_fields[name] = field
self._init_composite_field(name, field) | [
"def",
"add_composite_field",
"(",
"self",
",",
"name",
",",
"field",
")",
":",
"self",
".",
"composite_fields",
"[",
"name",
"]",
"=",
"field",
"self",
".",
"_init_composite_field",
"(",
"name",
",",
"field",
")"
] | 37.142857 | 6.857143 |
def task_view_generator(job_descriptor):
"""Generator that yields a task-specific view of the job.
This generator exists to make it easy for callers to iterate over the tasks
in a JobDescriptor. Each pass yields a new JobDescriptor with a single task.
Args:
job_descriptor: A JobDescriptor with 1 or more t... | [
"def",
"task_view_generator",
"(",
"job_descriptor",
")",
":",
"for",
"task_descriptor",
"in",
"job_descriptor",
".",
"task_descriptors",
":",
"jd",
"=",
"JobDescriptor",
"(",
"job_descriptor",
".",
"job_metadata",
",",
"job_descriptor",
".",
"job_params",
",",
"job... | 36.8125 | 24.4375 |
def encipher(self,string):
"""Encipher string using Bifid cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Bifid('phqgmeaylnofdxkrcvszwbuti',5).encipher(plaintext)
:param string: The string to en... | [
"def",
"encipher",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"self",
".",
"remove_punctuation",
"(",
"string",
")",
"step1",
"=",
"self",
".",
"pb",
".",
"encipher",
"(",
"string",
")",
"evens",
"=",
"step1",
"[",
":",
":",
"2",
"]",
"od... | 36.8 | 15.05 |
def _read_para_route_dst(self, code, cbit, clen, *, desc, length, version):
"""Read HIP ROUTE_DST parameter.
Structure of HIP ROUTE_DST parameter [RFC 6028]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8... | [
"def",
"_read_para_route_dst",
"(",
"self",
",",
"code",
",",
"cbit",
",",
"clen",
",",
"*",
",",
"desc",
",",
"length",
",",
"version",
")",
":",
"if",
"(",
"clen",
"-",
"4",
")",
"%",
"16",
"!=",
"0",
":",
"raise",
"ProtocolError",
"(",
"f'HIPv{v... | 53.5 | 29.137931 |
def ReplacePermission(self, permission_link, permission, options=None):
"""Replaces a permission and return it.
:param str permission_link:
The link to the permission.
:param dict permission:
:param dict options:
The request options for the request.
:ret... | [
"def",
"ReplacePermission",
"(",
"self",
",",
"permission_link",
",",
"permission",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"CosmosClient",
".",
"__ValidateResource",
"(",
"permission",
")",
"path"... | 31.259259 | 15.555556 |
def fit(self, X, y=None):
"""
X : data matrix, (n x d)
y : unused
"""
X = self._prepare_inputs(X, ensure_min_samples=2)
M = np.cov(X, rowvar = False)
if M.ndim == 0:
M = 1./M
else:
M = np.linalg.inv(M)
self.transformer_ = transformer_from_metric(np.atleast_2d(M))
ret... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"X",
"=",
"self",
".",
"_prepare_inputs",
"(",
"X",
",",
"ensure_min_samples",
"=",
"2",
")",
"M",
"=",
"np",
".",
"cov",
"(",
"X",
",",
"rowvar",
"=",
"False",
")",
"if",
... | 22.5 | 18.214286 |
def SegmentMin(a, ids):
"""
Segmented min op.
"""
func = lambda idxs: np.amin(a[idxs], axis=0)
return seg_map(func, a, ids), | [
"def",
"SegmentMin",
"(",
"a",
",",
"ids",
")",
":",
"func",
"=",
"lambda",
"idxs",
":",
"np",
".",
"amin",
"(",
"a",
"[",
"idxs",
"]",
",",
"axis",
"=",
"0",
")",
"return",
"seg_map",
"(",
"func",
",",
"a",
",",
"ids",
")",
","
] | 23.166667 | 8.5 |
def runSearchContinuousSets(self, request):
"""
Returns a SearchContinuousSetsResponse for the specified
SearchContinuousSetsRequest object.
"""
return self.runSearchRequest(
request, protocol.SearchContinuousSetsRequest,
protocol.SearchContinuousSetsRespo... | [
"def",
"runSearchContinuousSets",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"runSearchRequest",
"(",
"request",
",",
"protocol",
".",
"SearchContinuousSetsRequest",
",",
"protocol",
".",
"SearchContinuousSetsResponse",
",",
"self",
".",
"continuo... | 39.777778 | 6.888889 |
def validate(path): # pragma: no cover
"""Validates Dynaconf settings based on rules defined in
dynaconf_validators.toml"""
# reads the 'dynaconf_validators.toml' from path
# for each section register the validator for specific env
# call validate
path = Path(path)
if not str(path).endswi... | [
"def",
"validate",
"(",
"path",
")",
":",
"# pragma: no cover",
"# reads the 'dynaconf_validators.toml' from path",
"# for each section register the validator for specific env",
"# call validate",
"path",
"=",
"Path",
"(",
"path",
")",
"if",
"not",
"str",
"(",
"path",
")",
... | 33.480769 | 18 |
def get_assessment_part_admin_session_for_bank(self, bank_id, proxy):
"""Gets the ``OsidSession`` associated with the assessment part administration service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
arg: proxy (osid.proxy.Proxy): a proxy
return: (os... | [
"def",
"get_assessment_part_admin_session_for_bank",
"(",
"self",
",",
"bank_id",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_assessment_part_admin",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"##",
"# Also include check to see... | 51.583333 | 21.791667 |
def get_cohp(self, spin=None, integrated=False):
"""
Returns the COHP or ICOHP for a particular spin.
Args:
spin: Spin. Can be parsed as spin object, integer (-1/1)
or str ("up"/"down")
integrated: Return COHP (False) or ICOHP (True)
Returns:
... | [
"def",
"get_cohp",
"(",
"self",
",",
"spin",
"=",
"None",
",",
"integrated",
"=",
"False",
")",
":",
"if",
"not",
"integrated",
":",
"populations",
"=",
"self",
".",
"cohp",
"else",
":",
"populations",
"=",
"self",
".",
"icohp",
"if",
"populations",
"i... | 31.9 | 16.166667 |
def uri(self):
"""Cache to prevent recalculating URI unless necessary"""
if self.__modified:
self.__uri = self.__parse_uri()
return self.__uri | [
"def",
"uri",
"(",
"self",
")",
":",
"if",
"self",
".",
"__modified",
":",
"self",
".",
"__uri",
"=",
"self",
".",
"__parse_uri",
"(",
")",
"return",
"self",
".",
"__uri"
] | 29 | 16.166667 |
def put(self, f, digest=None):
"""
Upload a blob
:param f:
File object to be uploaded (required to support seek if digest is
not provided).
:param digest:
Optional SHA-1 hex digest of the file contents. Gets computed
before actual upload i... | [
"def",
"put",
"(",
"self",
",",
"f",
",",
"digest",
"=",
"None",
")",
":",
"if",
"digest",
":",
"actual_digest",
"=",
"digest",
"else",
":",
"actual_digest",
"=",
"self",
".",
"_compute_digest",
"(",
"f",
")",
"created",
"=",
"self",
".",
"conn",
"."... | 33.307692 | 22.769231 |
def decompose_atom_list(atom_list):
"""
Return elements and/or atom ids and coordinates from an `atom list`.
Depending on input type of an atom list (version 1 or 2)
1. [[element, coordinates (x, y, z)], ...]
2. [[element, atom key, coordinates (x, y, z)], ...]
the function reverses w... | [
"def",
"decompose_atom_list",
"(",
"atom_list",
")",
":",
"transpose",
"=",
"list",
"(",
"zip",
"(",
"*",
"atom_list",
")",
")",
"if",
"len",
"(",
"transpose",
")",
"==",
"4",
":",
"elements",
"=",
"np",
".",
"array",
"(",
"transpose",
"[",
"0",
"]",... | 36.666667 | 19.377778 |
def get(self):
"""Returns existing value, or None if deadline has expired."""
if self.timer() > self.deadline:
self.value = None
return self.value | [
"def",
"get",
"(",
"self",
")",
":",
"if",
"self",
".",
"timer",
"(",
")",
">",
"self",
".",
"deadline",
":",
"self",
".",
"value",
"=",
"None",
"return",
"self",
".",
"value"
] | 35.6 | 10.4 |
def init_hidden(self, hidden):
"""
Converts flattened hidden state (from sequence generator) into a tuple
of hidden states.
:param hidden: None or flattened hidden state for decoder RNN layers
"""
if hidden is not None:
# per-layer chunks
hidden =... | [
"def",
"init_hidden",
"(",
"self",
",",
"hidden",
")",
":",
"if",
"hidden",
"is",
"not",
"None",
":",
"# per-layer chunks",
"hidden",
"=",
"hidden",
".",
"chunk",
"(",
"self",
".",
"num_layers",
")",
"# (h, c) chunks for LSTM layer",
"hidden",
"=",
"tuple",
... | 32.058824 | 16.882353 |
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
... | [
"def",
"show_deployment",
"(",
"kwargs",
"=",
"None",
",",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The get_deployment function must be called with -f or --function.'",
")"... | 26.441176 | 24.970588 |
def _walk(self, target, visitor):
"""Walks the dependency graph for the given target.
:param target: The target to start the walk from.
:param visitor: A function that takes a target and returns `True` if its dependencies should
also be visited.
"""
visited = set()
def walk... | [
"def",
"_walk",
"(",
"self",
",",
"target",
",",
"visitor",
")",
":",
"visited",
"=",
"set",
"(",
")",
"def",
"walk",
"(",
"current",
")",
":",
"if",
"current",
"not",
"in",
"visited",
":",
"visited",
".",
"add",
"(",
"current",
")",
"keep_going",
... | 29.944444 | 18.388889 |
def _parse_boolean(value):
"""Coerce value into an bool.
:param str value: Value to parse.
:returns: bool or None if the value is not a boolean string.
"""
value = value.lower()
if value in _true_strings:
return True
elif value in _false_strings:
return False
else:
... | [
"def",
"_parse_boolean",
"(",
"value",
")",
":",
"value",
"=",
"value",
".",
"lower",
"(",
")",
"if",
"value",
"in",
"_true_strings",
":",
"return",
"True",
"elif",
"value",
"in",
"_false_strings",
":",
"return",
"False",
"else",
":",
"return",
"None"
] | 24.769231 | 15.846154 |
def is_ready(self, service_name):
"""
Determine if a registered service is ready, by checking its 'required_data'.
A 'required_data' item can be any mapping type, and is considered ready
if `bool(item)` evaluates as True.
"""
service = self.get_service(service_name)
... | [
"def",
"is_ready",
"(",
"self",
",",
"service_name",
")",
":",
"service",
"=",
"self",
".",
"get_service",
"(",
"service_name",
")",
"reqs",
"=",
"service",
".",
"get",
"(",
"'required_data'",
",",
"[",
"]",
")",
"return",
"all",
"(",
"bool",
"(",
"req... | 40 | 15.2 |
def whereless(self, fieldname, value):
"""
Returns a new DataTable with rows only where the value at
`fieldname` < `value`.
"""
return self.mask([elem < value for elem in self[fieldname]]) | [
"def",
"whereless",
"(",
"self",
",",
"fieldname",
",",
"value",
")",
":",
"return",
"self",
".",
"mask",
"(",
"[",
"elem",
"<",
"value",
"for",
"elem",
"in",
"self",
"[",
"fieldname",
"]",
"]",
")"
] | 37.166667 | 10.833333 |
def check_password(self, raw_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
hashing formats behind the scenes.
"""
def setter(raw_password):
self.set_password(raw_password)
self.save(update_fields=[self.PASSWORD_FIELD])
... | [
"def",
"check_password",
"(",
"self",
",",
"raw_password",
")",
":",
"def",
"setter",
"(",
"raw_password",
")",
":",
"self",
".",
"set_password",
"(",
"raw_password",
")",
"self",
".",
"save",
"(",
"update_fields",
"=",
"[",
"self",
".",
"PASSWORD_FIELD",
... | 44.222222 | 12.444444 |
def _open_next(self):
"""Proceed to next volume."""
# is the file split over archives?
if (self._cur.flags & rarfile.RAR_FILE_SPLIT_AFTER) == 0:
return False
if self._fd:
self._fd.close()
self._fd = None
# open next part
self._volfil... | [
"def",
"_open_next",
"(",
"self",
")",
":",
"# is the file split over archives?",
"if",
"(",
"self",
".",
"_cur",
".",
"flags",
"&",
"rarfile",
".",
"RAR_FILE_SPLIT_AFTER",
")",
"==",
"0",
":",
"return",
"False",
"if",
"self",
".",
"_fd",
":",
"self",
".",... | 34.727273 | 17.363636 |
def _handleSmsStatusReport(self, notificationLine):
""" Handler for SMS status reports """
self.log.debug('SMS status report received')
cdsiMatch = self.CDSI_REGEX.match(notificationLine)
if cdsiMatch:
msgMemory = cdsiMatch.group(1)
msgIndex = cdsiMatch.group(2)
... | [
"def",
"_handleSmsStatusReport",
"(",
"self",
",",
"notificationLine",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'SMS status report received'",
")",
"cdsiMatch",
"=",
"self",
".",
"CDSI_REGEX",
".",
"match",
"(",
"notificationLine",
")",
"if",
"cdsiMatch... | 52.111111 | 16.444444 |
def save_model(self, request, obj, form, change):
"""
Sends a tweet with the title/short_url if applicable.
"""
super(TweetableAdminMixin, self).save_model(request, obj, form, change)
if Api and request.POST.get("send_tweet", False):
auth_settings = get_auth_settings(... | [
"def",
"save_model",
"(",
"self",
",",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
":",
"super",
"(",
"TweetableAdminMixin",
",",
"self",
")",
".",
"save_model",
"(",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
"if",
"Api",
"a... | 46.818182 | 14.272727 |
def _make_request_data(self, teststep_dict, entry_json):
""" parse HAR entry request data, and make teststep request data
Args:
entry_json (dict):
{
"request": {
"method": "POST",
"postData": {
... | [
"def",
"_make_request_data",
"(",
"self",
",",
"teststep_dict",
",",
"entry_json",
")",
":",
"method",
"=",
"entry_json",
"[",
"\"request\"",
"]",
".",
"get",
"(",
"\"method\"",
")",
"if",
"method",
"in",
"[",
"\"POST\"",
",",
"\"PUT\"",
",",
"\"PATCH\"",
... | 34.912281 | 18.754386 |
def init_remote(self):
'''
Initialize/attach to a remote using GitPython. Return a boolean
which will let the calling function know whether or not a new repo was
initialized by this function.
'''
new = False
if not os.listdir(self.cachedir):
# Repo cac... | [
"def",
"init_remote",
"(",
"self",
")",
":",
"new",
"=",
"False",
"if",
"not",
"os",
".",
"listdir",
"(",
"self",
".",
"cachedir",
")",
":",
"# Repo cachedir is empty, initialize a new repo there",
"self",
".",
"repo",
"=",
"git",
".",
"Repo",
".",
"init",
... | 36.391304 | 21.782609 |
def calc_cortices(subject, atlas_subject, worklog, hemis=None):
'''
calc_cortices extracts the hemisphere objects (of the subject) to which the atlas is being
applied. By default these are 'lh' and 'rh', but for HCP subjects other hemispheres may be
desired.
Afferent parameters:
@ hemis
... | [
"def",
"calc_cortices",
"(",
"subject",
",",
"atlas_subject",
",",
"worklog",
",",
"hemis",
"=",
"None",
")",
":",
"if",
"hemis",
"is",
"None",
"or",
"hemis",
"is",
"Ellipsis",
":",
"hemis",
"=",
"'lr'",
"if",
"pimms",
".",
"is_str",
"(",
"hemis",
")",... | 51.615385 | 27.769231 |
def fit(self, X, y=None):
'''
Fit the transform. Does nothing, for compatibility with sklearn API.
Parameters
----------
X : array-like, shape [n_series, ...]
Time series data and (optionally) contextual data
y : None
There is no need of a target ... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"self",
".",
"_check_data",
"(",
"X",
")",
"if",
"not",
"X",
"[",
"0",
"]",
".",
"ndim",
">=",
"2",
":",
"raise",
"ValueError",
"(",
"\"X input must be 2 dim array or greater\"",
"... | 29.428571 | 24.380952 |
def ruokuai_captcha_handler(self, params, image_url):
"""
若快自动识别验证码, 文档见: http://wiki.ruokuai.com/
"""
headers = {
'Connection': 'Keep-Alive',
'Expect': '100-continue',
'User-Agent': 'ben',
}
image_data = requests.get(image_url).co... | [
"def",
"ruokuai_captcha_handler",
"(",
"self",
",",
"params",
",",
"image_url",
")",
":",
"headers",
"=",
"{",
"'Connection'",
":",
"'Keep-Alive'",
",",
"'Expect'",
":",
"'100-continue'",
",",
"'User-Agent'",
":",
"'ben'",
",",
"}",
"image_data",
"=",
"request... | 30.62069 | 15.103448 |
def end_nodes(self):
"""
Yields `MatchVariable` instances for all the nodes having their end
position at the end of the input string.
"""
for varname, reg in self._nodes_to_regs():
# If this part goes until the end of the input string.
if reg[1] == len(sel... | [
"def",
"end_nodes",
"(",
"self",
")",
":",
"for",
"varname",
",",
"reg",
"in",
"self",
".",
"_nodes_to_regs",
"(",
")",
":",
"# If this part goes until the end of the input string.",
"if",
"reg",
"[",
"1",
"]",
"==",
"len",
"(",
"self",
".",
"string",
")",
... | 46.8 | 16.6 |
def setForeground(self, column, brush):
"""
Sets the default item foreground brush.
:param brush | <QtGui.QBrush> || None
"""
if brush:
self._foreground[column] = QtGui.QBrush(brush)
elif column in self._background:
self._for... | [
"def",
"setForeground",
"(",
"self",
",",
"column",
",",
"brush",
")",
":",
"if",
"brush",
":",
"self",
".",
"_foreground",
"[",
"column",
"]",
"=",
"QtGui",
".",
"QBrush",
"(",
"brush",
")",
"elif",
"column",
"in",
"self",
".",
"_background",
":",
"... | 33 | 9.2 |
def ystep(self):
r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{y}`.
"""
self.Y = np.asarray(sp.prox_l1(self.S - self.AX - self.U,
self.lmbda/self.rho), dtype=self.dtype) | [
"def",
"ystep",
"(",
"self",
")",
":",
"self",
".",
"Y",
"=",
"np",
".",
"asarray",
"(",
"sp",
".",
"prox_l1",
"(",
"self",
".",
"S",
"-",
"self",
".",
"AX",
"-",
"self",
".",
"U",
",",
"self",
".",
"lmbda",
"/",
"self",
".",
"rho",
")",
",... | 36.285714 | 20 |
def get(self, request, *args, **kwargs):
"""Wraps super().get(...) in order to return 404 status code if
the page parameter is invalid
"""
response = super().get(request, args, kwargs)
try:
response.render()
except Http404:
request.GET = request.GE... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"super",
"(",
")",
".",
"get",
"(",
"request",
",",
"args",
",",
"kwargs",
")",
"try",
":",
"response",
".",
"render",
"(",
")",
"e... | 33.928571 | 11.071429 |
def _set_default_params(ufo):
""" Set Glyphs.app's default parameters when different from ufo2ft ones.
"""
for _, ufo_name, default_value in DEFAULT_PARAMETERS:
if getattr(ufo.info, ufo_name) is None:
if isinstance(default_value, list):
# Prevent problem if the same defau... | [
"def",
"_set_default_params",
"(",
"ufo",
")",
":",
"for",
"_",
",",
"ufo_name",
",",
"default_value",
"in",
"DEFAULT_PARAMETERS",
":",
"if",
"getattr",
"(",
"ufo",
".",
"info",
",",
"ufo_name",
")",
"is",
"None",
":",
"if",
"isinstance",
"(",
"default_val... | 48.3 | 10.2 |
def init_hierarchy(cls, model_admin):
"""Initializes model admin with hierarchy data."""
hierarchy = getattr(model_admin, 'hierarchy')
if hierarchy:
if not isinstance(hierarchy, Hierarchy):
hierarchy = AdjacencyList() # For `True` and etc. TODO heuristics maybe.
... | [
"def",
"init_hierarchy",
"(",
"cls",
",",
"model_admin",
")",
":",
"hierarchy",
"=",
"getattr",
"(",
"model_admin",
",",
"'hierarchy'",
")",
"if",
"hierarchy",
":",
"if",
"not",
"isinstance",
"(",
"hierarchy",
",",
"Hierarchy",
")",
":",
"hierarchy",
"=",
... | 33.416667 | 20.583333 |
def _get_included_file_path(self, user_specified_path: str, current_processed_file_path: Path) -> Path:
'''Resolve user specified path to the local included file.
:param user_specified_path: User specified string that represents
the path to a local file
:param current_processed_fil... | [
"def",
"_get_included_file_path",
"(",
"self",
",",
"user_specified_path",
":",
"str",
",",
"current_processed_file_path",
":",
"Path",
")",
"->",
"Path",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"f'Currently processed Markdown file: {current_processed_file_path}'",... | 40.880952 | 33.595238 |
def get(self):
"""
Constructs a TaskQueueRealTimeStatisticsContext
:returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsContext
:rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueue... | [
"def",
"get",
"(",
"self",
")",
":",
"return",
"TaskQueueRealTimeStatisticsContext",
"(",
"self",
".",
"_version",
",",
"workspace_sid",
"=",
"self",
".",
"_solution",
"[",
"'workspace_sid'",
"]",
",",
"task_queue_sid",
"=",
"self",
".",
"_solution",
"[",
"'ta... | 46.166667 | 29.5 |
def analyze_bash_vars(job_input_file, job_homedir):
'''
This function examines the input file, and calculates variables to
instantiate in the shell environment. It is called right before starting the
execution of an app in a worker.
For each input key, we want to have
$var
$var_filename
... | [
"def",
"analyze_bash_vars",
"(",
"job_input_file",
",",
"job_homedir",
")",
":",
"_",
",",
"file_entries",
",",
"rest_hash",
"=",
"get_job_input_filenames",
"(",
"job_input_file",
")",
"patterns_dict",
"=",
"get_input_spec_patterns",
"(",
")",
"# Note: there may be mult... | 38.853333 | 18.24 |
def _transform_indices(self, key):
"""Snaps indices into the GridSpace to the closest coordinate.
Args:
key: Tuple index into the GridSpace
Returns:
Transformed key snapped to closest numeric coordinates
"""
ndims = self.ndims
if all(not (isinsta... | [
"def",
"_transform_indices",
"(",
"self",
",",
"key",
")",
":",
"ndims",
"=",
"self",
".",
"ndims",
"if",
"all",
"(",
"not",
"(",
"isinstance",
"(",
"el",
",",
"slice",
")",
"or",
"callable",
"(",
"el",
")",
")",
"for",
"el",
"in",
"key",
")",
":... | 45 | 18.309524 |
def write(self, filehandle, fileformat):
"""Write :class:`~nmrstarlib.plsimulator.PeakList` data into file.
:param filehandle: file-like object.
:type filehandle: :py:class:`io.TextIOWrapper`
:param str fileformat: Format to use to write data: `sparky`, `autoassign`, or `json`.
... | [
"def",
"write",
"(",
"self",
",",
"filehandle",
",",
"fileformat",
")",
":",
"try",
":",
"if",
"fileformat",
"==",
"\"sparky\"",
":",
"sparky_str",
"=",
"self",
".",
"_to_sparky",
"(",
")",
"filehandle",
".",
"write",
"(",
"sparky_str",
")",
"elif",
"fil... | 40.083333 | 12.791667 |
def _label__get(self):
"""
Get or set any <label> element associated with this element.
"""
id = self.get('id')
if not id:
return None
result = _label_xpath(self, id=id)
if not result:
return None
else:
return result[0] | [
"def",
"_label__get",
"(",
"self",
")",
":",
"id",
"=",
"self",
".",
"get",
"(",
"'id'",
")",
"if",
"not",
"id",
":",
"return",
"None",
"result",
"=",
"_label_xpath",
"(",
"self",
",",
"id",
"=",
"id",
")",
"if",
"not",
"result",
":",
"return",
"... | 25.666667 | 14.5 |
def fence_status_send(self, breach_status, breach_count, breach_type, breach_time, force_mavlink1=False):
'''
Status of geo-fencing. Sent in extended status stream when fencing
enabled
breach_status : 0 if currently inside fence, 1 if outside ... | [
"def",
"fence_status_send",
"(",
"self",
",",
"breach_status",
",",
"breach_count",
",",
"breach_type",
",",
"breach_time",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"fence_status_encode",
"(",
"breach_status... | 63.583333 | 46.75 |
def verify_file_exists(file_name, file_location):
"""
Function to verify if a file exists
Args:
file_name: The name of file to check
file_location: The location of the file, derive from the os module
Returns: returns boolean True or False
"""
return __os.path.isfile(__os.path.j... | [
"def",
"verify_file_exists",
"(",
"file_name",
",",
"file_location",
")",
":",
"return",
"__os",
".",
"path",
".",
"isfile",
"(",
"__os",
".",
"path",
".",
"join",
"(",
"file_location",
",",
"file_name",
")",
")"
] | 30.909091 | 17.272727 |
def packb(obj, **kwargs):
"""wrap msgpack.packb, setting use_bin_type=True by default"""
kwargs.setdefault('use_bin_type', True)
return msgpack.packb(obj, **kwargs) | [
"def",
"packb",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'use_bin_type'",
",",
"True",
")",
"return",
"msgpack",
".",
"packb",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")"
] | 43.25 | 4.75 |
def sign_statement(self, statement, node_name, key=None, key_file=None, node_id=None, id_attr=''):
"""Sign a SAML statement.
:param statement: The statement to be signed
:param node_name: string like 'urn:oasis:names:...:Assertion'
:param key: The key to be used for the signing, either ... | [
"def",
"sign_statement",
"(",
"self",
",",
"statement",
",",
"node_name",
",",
"key",
"=",
"None",
",",
"key_file",
"=",
"None",
",",
"node_id",
"=",
"None",
",",
"id_attr",
"=",
"''",
")",
":",
"if",
"not",
"id_attr",
":",
"id_attr",
"=",
"self",
".... | 35.185185 | 19.111111 |
def calc_ecg_grids(minsig, maxsig, sig_units, fs, maxt, time_units):
"""
Calculate tick intervals for ecg grids
- 5mm 0.2s major grids, 0.04s minor grids
- 0.5mV major grids, 0.125 minor grids
10 mm is equal to 1mV in voltage.
"""
# Get the grid interval of the x axis
if time_units == ... | [
"def",
"calc_ecg_grids",
"(",
"minsig",
",",
"maxsig",
",",
"sig_units",
",",
"fs",
",",
"maxt",
",",
"time_units",
")",
":",
"# Get the grid interval of the x axis",
"if",
"time_units",
"==",
"'samples'",
":",
"majorx",
"=",
"0.2",
"*",
"fs",
"minorx",
"=",
... | 31.955556 | 18.488889 |
def GetMessages(self, formatter_mediator, event):
"""Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
eve... | [
"def",
"GetMessages",
"(",
"self",
",",
"formatter_mediator",
",",
"event",
")",
":",
"if",
"self",
".",
"DATA_TYPE",
"!=",
"event",
".",
"data_type",
":",
"raise",
"errors",
".",
"WrongFormatter",
"(",
"'Unsupported data type: {0:s}.'",
".",
"format",
"(",
"e... | 34.892857 | 22.285714 |
def rol(sig, howMany) -> RtlSignalBase:
"Rotate left"
width = sig._dtype.bit_length()
return sig[(width - howMany):]._concat(sig[:(width - howMany)]) | [
"def",
"rol",
"(",
"sig",
",",
"howMany",
")",
"->",
"RtlSignalBase",
":",
"width",
"=",
"sig",
".",
"_dtype",
".",
"bit_length",
"(",
")",
"return",
"sig",
"[",
"(",
"width",
"-",
"howMany",
")",
":",
"]",
".",
"_concat",
"(",
"sig",
"[",
":",
"... | 39.5 | 14 |
def title_translations2marc(self, key, value):
"""Populate the ``242`` MARC field."""
return {
'a': value.get('title'),
'b': value.get('subtitle'),
'9': value.get('source'),
} | [
"def",
"title_translations2marc",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"return",
"{",
"'a'",
":",
"value",
".",
"get",
"(",
"'title'",
")",
",",
"'b'",
":",
"value",
".",
"get",
"(",
"'subtitle'",
")",
",",
"'9'",
":",
"value",
".",
"ge... | 29.285714 | 12.714286 |
def add_comment(self, table, column, comment):
"""Add a comment to an existing column in a table."""
col_def = self.get_column_definition(table, column)
query = "ALTER TABLE {0} MODIFY COLUMN {1} {2} COMMENT '{3}'".format(table, column, col_def, comment)
self.execute(query)
self.... | [
"def",
"add_comment",
"(",
"self",
",",
"table",
",",
"column",
",",
"comment",
")",
":",
"col_def",
"=",
"self",
".",
"get_column_definition",
"(",
"table",
",",
"column",
")",
"query",
"=",
"\"ALTER TABLE {0} MODIFY COLUMN {1} {2} COMMENT '{3}'\"",
".",
"format"... | 55.714286 | 22.428571 |
def write_batch(self, batch):
"""
Receives the batch and writes it. This method is usually called from a manager.
"""
for item in batch:
for key in item:
self.aggregated_info['occurrences'][key] += 1
self.increment_written_items()
if se... | [
"def",
"write_batch",
"(",
"self",
",",
"batch",
")",
":",
"for",
"item",
"in",
"batch",
":",
"for",
"key",
"in",
"item",
":",
"self",
".",
"aggregated_info",
"[",
"'occurrences'",
"]",
"[",
"key",
"]",
"+=",
"1",
"self",
".",
"increment_written_items",
... | 50.5 | 21.5 |
def dskstl(keywrd, dpval):
"""
Set the value of a specified DSK tolerance or margin parameter.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskstl_c.html
:param keywrd: Code specifying parameter to set.
:type keywrd: int
:param dpval: Value of parameter.
:type dpval: f... | [
"def",
"dskstl",
"(",
"keywrd",
",",
"dpval",
")",
":",
"keywrd",
"=",
"ctypes",
".",
"c_int",
"(",
"keywrd",
")",
"dpval",
"=",
"ctypes",
".",
"c_double",
"(",
"dpval",
")",
"libspice",
".",
"dskstl_c",
"(",
"keywrd",
",",
"dpval",
")"
] | 29.2 | 16.133333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.