text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def is_optional(self):
"""
Returns whether the parameter is optional or required
:return: Return True if optional, False if required
"""
if (('optional' in self.attributes and bool(self.attributes['optional'].strip())) and
('minValue' in self.attributes and self.a... | [
"def",
"is_optional",
"(",
"self",
")",
":",
"if",
"(",
"(",
"'optional'",
"in",
"self",
".",
"attributes",
"and",
"bool",
"(",
"self",
".",
"attributes",
"[",
"'optional'",
"]",
".",
"strip",
"(",
")",
")",
")",
"and",
"(",
"'minValue'",
"in",
"self... | 40.3 | 21.7 |
def add_plot(fn: Path, cm, ax, alpha=1):
"""Astrometry.net makes file ".new" with the image and the WCS SIP 2-D polynomial fit coefficients in the FITS header
We use DECL as "x" and RA as "y".
pcolormesh() is used as it handles arbitrary pixel shapes.
Note that pcolormesh() cannot tolerate NaN in X or ... | [
"def",
"add_plot",
"(",
"fn",
":",
"Path",
",",
"cm",
",",
"ax",
",",
"alpha",
"=",
"1",
")",
":",
"with",
"fits",
".",
"open",
"(",
"fn",
",",
"mode",
"=",
"'readonly'",
",",
"memmap",
"=",
"False",
")",
"as",
"f",
":",
"img",
"=",
"f",
"[",... | 41.04 | 21.52 |
def create(cls, name, user=None, network_element=None, domain_name=None,
zone=None, executable=None):
"""
Create a match expression
:param str name: name of match expression
:param str user: name of user or user group
:param Element network_element: valid network ... | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"user",
"=",
"None",
",",
"network_element",
"=",
"None",
",",
"domain_name",
"=",
"None",
",",
"zone",
"=",
"None",
",",
"executable",
"=",
"None",
")",
":",
"ref_list",
"=",
"[",
"]",
"if",
"user",
"... | 33.612903 | 16.645161 |
def fetch_url(self, url):
"""
Retrieves the given url to the prefix
Args:
url(str): Url to retrieve
Returns:
str: path to the downloaded file
"""
url_path = urlparse.urlsplit(url).path
dst_path = os.path.basename(url_path)
dst_pat... | [
"def",
"fetch_url",
"(",
"self",
",",
"url",
")",
":",
"url_path",
"=",
"urlparse",
".",
"urlsplit",
"(",
"url",
")",
".",
"path",
"dst_path",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"url_path",
")",
"dst_path",
"=",
"self",
".",
"paths",
".",
... | 28.647059 | 16.294118 |
def _update_explicit_bucket_count(a_float, dist):
"""Adds `a_float` to `dist`, updating its explicit buckets.
Args:
a_float (float): a new value
dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):
the Distribution being updated
Raises:
ValueError: if... | [
"def",
"_update_explicit_bucket_count",
"(",
"a_float",
",",
"dist",
")",
":",
"buckets",
"=",
"dist",
".",
"explicitBuckets",
"if",
"buckets",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"_BAD_UNSET_BUCKETS",
"%",
"(",
"u'explicit buckets'",
")",
")",
"bucke... | 38.8 | 18 |
def get_latex(self):
"""Bibliographic entry in LaTeX format."""
if len(self.authors) > 1:
authors = _list_authors(self.authors)
else:
a = self.authors
authors = ' '.join([a.given_name, a.surname])
if self.volume and self.issueIdentifier:
vo... | [
"def",
"get_latex",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"authors",
")",
">",
"1",
":",
"authors",
"=",
"_list_authors",
"(",
"self",
".",
"authors",
")",
"else",
":",
"a",
"=",
"self",
".",
"authors",
"authors",
"=",
"' '",
".",
... | 46.52381 | 20.52381 |
def preview(request):
""" Render preview page.
:returns: A rendered preview
"""
if settings.MARKDOWN_PROTECT_PREVIEW:
user = getattr(request, 'user', None)
if not user or not user.is_staff:
from django.contrib.auth.views import redirect_to_login
return redirect_... | [
"def",
"preview",
"(",
"request",
")",
":",
"if",
"settings",
".",
"MARKDOWN_PROTECT_PREVIEW",
":",
"user",
"=",
"getattr",
"(",
"request",
",",
"'user'",
",",
"None",
")",
"if",
"not",
"user",
"or",
"not",
"user",
".",
"is_staff",
":",
"from",
"django",... | 31.411765 | 17.588235 |
def get_fragment(self, gp, **kwargs):
"""
Return a complete fragment for a given gp.
:param gp: A graph pattern
:return:
"""
collector = FragmentCollector(self.__host, gp)
return collector.get_fragment(**kwargs) | [
"def",
"get_fragment",
"(",
"self",
",",
"gp",
",",
"*",
"*",
"kwargs",
")",
":",
"collector",
"=",
"FragmentCollector",
"(",
"self",
".",
"__host",
",",
"gp",
")",
"return",
"collector",
".",
"get_fragment",
"(",
"*",
"*",
"kwargs",
")"
] | 32.5 | 8 |
def get_instance(self, payload):
"""
Build an instance of FunctionVersionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.serverless.v1.service.function.function_version.FunctionVersionInstance
:rtype: twilio.rest.serverless.v1.service.function.... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"FunctionVersionInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"function_sid",
"=",
"self",
"... | 37.866667 | 22.266667 |
def format_color(text, color, use_color_setting):
"""Format text with color.
Args:
text - Text to be formatted with color if `use_color`
color - The color start string
use_color_setting - Whether or not to color
"""
if not use_color_setting:
return text
else:
... | [
"def",
"format_color",
"(",
"text",
",",
"color",
",",
"use_color_setting",
")",
":",
"if",
"not",
"use_color_setting",
":",
"return",
"text",
"else",
":",
"return",
"'{}{}{}'",
".",
"format",
"(",
"color",
",",
"text",
",",
"NORMAL",
")"
] | 29.416667 | 15.666667 |
def run_commands(commands, settings):
"""
Runs the commands supplied as an argument
It will exit the program if the commands return a
non-zero code
Args:
the commands to run
The settings dictionary
"""
sprint = settings["sprint"]
quiet = settings["quiet"]
error = set... | [
"def",
"run_commands",
"(",
"commands",
",",
"settings",
")",
":",
"sprint",
"=",
"settings",
"[",
"\"sprint\"",
"]",
"quiet",
"=",
"settings",
"[",
"\"quiet\"",
"]",
"error",
"=",
"settings",
"[",
"\"error\"",
"]",
"enhanced_errors",
"=",
"True",
"the_shell... | 26.461538 | 16.384615 |
def p_invoke(p):
"""
invoke : INVOKE IDENTIFIER SLASH IDENTIFIER
| INVOKE IDENTIFIER SLASH IDENTIFIER OPEN_CURLY_BRACKET PRIORITY COLON NUMBER CLOSE_CURLY_BRACKET
"""
priority = None
if len(p) > 5:
priority = int(p[8])
p[0] = Trigger(p[2], p[4], priority) | [
"def",
"p_invoke",
"(",
"p",
")",
":",
"priority",
"=",
"None",
"if",
"len",
"(",
"p",
")",
">",
"5",
":",
"priority",
"=",
"int",
"(",
"p",
"[",
"8",
"]",
")",
"p",
"[",
"0",
"]",
"=",
"Trigger",
"(",
"p",
"[",
"2",
"]",
",",
"p",
"[",
... | 32.222222 | 17.111111 |
def q_vector(u, v, temperature, pressure, dx, dy, static_stability=1):
r"""Calculate Q-vector at a given pressure level using the u, v winds and temperature.
.. math:: \vec{Q} = (Q_1, Q_2)
= - \frac{R}{\sigma p}\left(
\frac{\partial \vec{v}_g}{\partial x} \... | [
"def",
"q_vector",
"(",
"u",
",",
"v",
",",
"temperature",
",",
"pressure",
",",
"dx",
",",
"dy",
",",
"static_stability",
"=",
"1",
")",
":",
"dudy",
",",
"dudx",
"=",
"gradient",
"(",
"u",
",",
"deltas",
"=",
"(",
"dy",
",",
"dx",
")",
",",
"... | 41.918033 | 27.147541 |
def script(name,
source=None,
template=None,
onlyif=None,
unless=None,
creates=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
timeout=None,
use_vt... | [
"def",
"script",
"(",
"name",
",",
"source",
"=",
"None",
",",
"template",
"=",
"None",
",",
"onlyif",
"=",
"None",
",",
"unless",
"=",
"None",
",",
"creates",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"runas",
"=",
"None",
",",
"shell",
"=",
"N... | 32.726316 | 23.533333 |
def _add_public_adder(self):
"""
Add a public ``add_x()`` method to the parent element class.
"""
def add_child(obj):
private_add_method = getattr(obj, self._add_method_name)
child = private_add_method()
return child
add_child.__doc__ = (
... | [
"def",
"_add_public_adder",
"(",
"self",
")",
":",
"def",
"add_child",
"(",
"obj",
")",
":",
"private_add_method",
"=",
"getattr",
"(",
"obj",
",",
"self",
".",
"_add_method_name",
")",
"child",
"=",
"private_add_method",
"(",
")",
"return",
"child",
"add_ch... | 36.571429 | 18.285714 |
def _request_login(self, login, password):
"""Sends Login request"""
return self._request_internal("Login",
login=login,
password=password) | [
"def",
"_request_login",
"(",
"self",
",",
"login",
",",
"password",
")",
":",
"return",
"self",
".",
"_request_internal",
"(",
"\"Login\"",
",",
"login",
"=",
"login",
",",
"password",
"=",
"password",
")"
] | 45.4 | 6.8 |
def require_dataset(self, name, shape, dtype=None, exact=False, **kwargs):
"""Obtain an array, creating if it doesn't exist. Other `kwargs` are
as per :func:`zarr.hierarchy.Group.create_dataset`.
Parameters
----------
name : string
Array name.
shape : int or ... | [
"def",
"require_dataset",
"(",
"self",
",",
"name",
",",
"shape",
",",
"dtype",
"=",
"None",
",",
"exact",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_write_op",
"(",
"self",
".",
"_require_dataset_nosync",
",",
"name",
",... | 35.95 | 20.2 |
def remove(self):
"""Remove a target
Raises a ``RuntimeError`` if the target does not exist.
"""
session = client.get_client().create_session()
if not self._base_query(session).count() > 0:
session.close()
raise RuntimeError("Target does not exist, name=... | [
"def",
"remove",
"(",
"self",
")",
":",
"session",
"=",
"client",
".",
"get_client",
"(",
")",
".",
"create_session",
"(",
")",
"if",
"not",
"self",
".",
"_base_query",
"(",
"session",
")",
".",
"count",
"(",
")",
">",
"0",
":",
"session",
".",
"cl... | 31.058824 | 20.529412 |
def split_path(path) :
"convenience routine for splitting a path into a list of components."
if isinstance(path, (tuple, list)) :
result = path # assume already split
elif path == "/" :
result = []
else :
if not path.startswith("/") or path.endswith("/") :
raise DBusE... | [
"def",
"split_path",
"(",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"result",
"=",
"path",
"# assume already split",
"elif",
"path",
"==",
"\"/\"",
":",
"result",
"=",
"[",
"]",
"else",
":",
"if... | 32.928571 | 21.357143 |
def dilate_obs(self, dilation_radius):
"""
Use a dilation filter to grow positive observation areas by a specified number of grid points
:param dilation_radius: Number of times to dilate the grid.
:return:
"""
for s in self.size_thresholds:
self.dilated_obs[s... | [
"def",
"dilate_obs",
"(",
"self",
",",
"dilation_radius",
")",
":",
"for",
"s",
"in",
"self",
".",
"size_thresholds",
":",
"self",
".",
"dilated_obs",
"[",
"s",
"]",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"window_obs",
"[",
"self",
".",
"mrms_varia... | 50.545455 | 28.181818 |
def build_api_error(response, blob=None):
"""Helper method for creating errors and attaching HTTP response/request
details to them.
"""
try:
blob = blob or response.json()
except json.JSONDecodeError:
blob = {}
error_list = blob.get('errors', None)
error = (error_list[0] if e... | [
"def",
"build_api_error",
"(",
"response",
",",
"blob",
"=",
"None",
")",
":",
"try",
":",
"blob",
"=",
"blob",
"or",
"response",
".",
"json",
"(",
")",
"except",
"json",
".",
"JSONDecodeError",
":",
"blob",
"=",
"{",
"}",
"error_list",
"=",
"blob",
... | 40.347826 | 15 |
def create_return_line_item(cls, return_line_item, **kwargs):
"""Create ReturnLineItem
Create a new ReturnLineItem
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_return_line_item(retur... | [
"def",
"create_return_line_item",
"(",
"cls",
",",
"return_line_item",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_create_return... | 44.333333 | 22.190476 |
def get_stop_words(self, language, fail_safe=False):
"""
Returns a StopWord object initialized with the stop words collection
requested by ``language``.
If the requested language is not available a StopWordError is raised.
If ``fail_safe`` is set to True, an empty StopWord object... | [
"def",
"get_stop_words",
"(",
"self",
",",
"language",
",",
"fail_safe",
"=",
"False",
")",
":",
"try",
":",
"language",
"=",
"self",
".",
"language_codes",
"[",
"language",
"]",
"except",
"KeyError",
":",
"pass",
"collection",
"=",
"self",
".",
"LOADED_LA... | 35.56 | 19.32 |
def xor(key, data):
"""
Perform cyclical exclusive or operations on ``data``.
The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If
the key is smaller than the provided ``data``, the ``key`` will be
repeated.
Args:
key(int or bytes): The key to xor ``data`` with.
... | [
"def",
"xor",
"(",
"key",
",",
"data",
")",
":",
"if",
"type",
"(",
"key",
")",
"is",
"int",
":",
"key",
"=",
"six",
".",
"int2byte",
"(",
"key",
")",
"key_len",
"=",
"len",
"(",
"key",
")",
"return",
"b''",
".",
"join",
"(",
"six",
".",
"int... | 27.6 | 21.714286 |
def clinsig_query(self, query, mongo_query):
""" Add clinsig filter values to the mongo query object
Args:
query(dict): a dictionary of query filters specified by the users
mongo_query(dict): the query that is going to be submitted to the database
Return... | [
"def",
"clinsig_query",
"(",
"self",
",",
"query",
",",
"mongo_query",
")",
":",
"LOG",
".",
"debug",
"(",
"'clinsig is a query parameter'",
")",
"trusted_revision_level",
"=",
"[",
"'mult'",
",",
"'single'",
",",
"'exp'",
",",
"'guideline'",
"]",
"rank",
"=",... | 39.206349 | 19.68254 |
def get_way(self, way_id, resolve_missing=False):
"""
Get a way by its ID.
:param way_id: The way ID
:type way_id: Integer
:param resolve_missing: Query the Overpass API if the way is missing in the result set.
:return: The way
:rtype: overpy.Way
:raises ... | [
"def",
"get_way",
"(",
"self",
",",
"way_id",
",",
"resolve_missing",
"=",
"False",
")",
":",
"ways",
"=",
"self",
".",
"get_ways",
"(",
"way_id",
"=",
"way_id",
")",
"if",
"len",
"(",
"ways",
")",
"==",
"0",
":",
"if",
"resolve_missing",
"is",
"Fals... | 35 | 20.235294 |
def prepare(self):
"""Method to check if the impact function can be run.
:return: A tuple with the status of the IF and an error message if
needed.
The status is PREPARE_SUCCESS if everything was fine.
The status is PREPARE_FAILED_BAD_INPUT if the client should fix
... | [
"def",
"prepare",
"(",
"self",
")",
":",
"self",
".",
"_provenance_ready",
"=",
"False",
"# save layer reference before preparing.",
"# used to display it in maps",
"original_exposure",
"=",
"self",
".",
"exposure",
"original_hazard",
"=",
"self",
".",
"hazard",
"origin... | 42.659091 | 16.659091 |
def calculate_gradient(self, batch_info, device, model, rollout):
""" Calculate loss of the supplied rollout """
evaluator = model.evaluate(rollout)
batch_size = rollout.frames()
dones_tensor = evaluator.get('rollout:dones')
rewards_tensor = evaluator.get('rollout:rewards')
... | [
"def",
"calculate_gradient",
"(",
"self",
",",
"batch_info",
",",
"device",
",",
"model",
",",
"rollout",
")",
":",
"evaluator",
"=",
"model",
".",
"evaluate",
"(",
"rollout",
")",
"batch_size",
"=",
"rollout",
".",
"frames",
"(",
")",
"dones_tensor",
"=",... | 42.361345 | 28.966387 |
def lfriedmanchisquare(*args):
"""
Friedman Chi-Square is a non-parametric, one-way within-subjects
ANOVA. This function calculates the Friedman Chi-square test for repeated
measures and returns the result, along with the associated probability
value. It assumes 3 or more repeated measures. Only 3 levels require... | [
"def",
"lfriedmanchisquare",
"(",
"*",
"args",
")",
":",
"k",
"=",
"len",
"(",
"args",
")",
"if",
"k",
"<",
"3",
":",
"raise",
"ValueError",
"(",
"'Less than 3 levels. Friedman test not appropriate.'",
")",
"n",
"=",
"len",
"(",
"args",
"[",
"0",
"]",
"... | 36.416667 | 18.25 |
def add(self, data):
"""
Add a single character to buffer. If one or more full lines are found,
print them (if desired) and pass to callback function.
"""
data = self._decoder.decode(data)
if not data:
return
self._buffer += data
if "\n" in dat... | [
"def",
"add",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"self",
".",
"_decoder",
".",
"decode",
"(",
"data",
")",
"if",
"not",
"data",
":",
"return",
"self",
".",
"_buffer",
"+=",
"data",
"if",
"\"\\n\"",
"in",
"data",
":",
"to_print",
",",
... | 39.909091 | 15.454545 |
def validate(self, export):
"""
Validates an Export.
:param Export export:
:rtype: ExportValidationResponse
"""
target_url = self.client.get_url(self._URL_KEY, 'POST', 'validate')
response_object = ExportValidationResponse()
r = self.client.request('POST... | [
"def",
"validate",
"(",
"self",
",",
"export",
")",
":",
"target_url",
"=",
"self",
".",
"client",
".",
"get_url",
"(",
"self",
".",
"_URL_KEY",
",",
"'POST'",
",",
"'validate'",
")",
"response_object",
"=",
"ExportValidationResponse",
"(",
")",
"r",
"=",
... | 33.583333 | 17.75 |
def _source_info():
"""
Get information from the user's code (two frames up)
to leave breadcrumbs for file, line, class and function.
"""
ofi = inspect.getouterframes(inspect.currentframe())[2]
try:
calling_class = ofi[0].f_locals['self'].__class__
except KeyError:
calling_cl... | [
"def",
"_source_info",
"(",
")",
":",
"ofi",
"=",
"inspect",
".",
"getouterframes",
"(",
"inspect",
".",
"currentframe",
"(",
")",
")",
"[",
"2",
"]",
"try",
":",
"calling_class",
"=",
"ofi",
"[",
"0",
"]",
".",
"f_locals",
"[",
"'self'",
"]",
".",
... | 35.083333 | 14.75 |
def remove_service_listener(self, listener):
"""Removes a listener from the set that is currently listening."""
for browser in self.browsers:
if browser.listener == listener:
browser.cancel()
del(browser) | [
"def",
"remove_service_listener",
"(",
"self",
",",
"listener",
")",
":",
"for",
"browser",
"in",
"self",
".",
"browsers",
":",
"if",
"browser",
".",
"listener",
"==",
"listener",
":",
"browser",
".",
"cancel",
"(",
")",
"del",
"(",
"browser",
")"
] | 43.166667 | 5.166667 |
def forward(ctx, x, dutyCycles, k, boostStrength):
"""
Use the boost strength to compute a boost factor for each unit represented
in x. These factors are used to increase the impact of each unit to improve
their chances of being chosen. This encourages participation of more columns
in the learning p... | [
"def",
"forward",
"(",
"ctx",
",",
"x",
",",
"dutyCycles",
",",
"k",
",",
"boostStrength",
")",
":",
"if",
"boostStrength",
">",
"0.0",
":",
"targetDensity",
"=",
"float",
"(",
"k",
")",
"/",
"x",
".",
"size",
"(",
"1",
")",
"boostFactors",
"=",
"t... | 35.808219 | 24.191781 |
def context(src):
"""
Used to add the source_id to the error message. To be used as
with context(src):
operation_with(src)
Typically the operation is filtering a source, that can fail for
tricky geometries.
"""
try:
yield
except Exception:
etype, err, tb = sys.e... | [
"def",
"context",
"(",
"src",
")",
":",
"try",
":",
"yield",
"except",
"Exception",
":",
"etype",
",",
"err",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'An error occurred with source id=%s. Error: %s'",
"msg",
"%=",
"(",
"src",
".",
... | 26.058824 | 18.882353 |
def games(years, months=None, days=None, home=None, away=None):
"""Return a list of lists of games for multiple days.
If home and away are the same team, it will return all games for that team.
"""
# put in data if months and days are not specified
if months is None:
months = list(range(1, ... | [
"def",
"games",
"(",
"years",
",",
"months",
"=",
"None",
",",
"days",
"=",
"None",
",",
"home",
"=",
"None",
",",
"away",
"=",
"None",
")",
":",
"# put in data if months and days are not specified",
"if",
"months",
"is",
"None",
":",
"months",
"=",
"list"... | 35.766667 | 14.5 |
def _handle_end_way(self):
"""
Handle closing way element
"""
self._result.append(Way(result=self._result, **self._curr))
self._curr = {} | [
"def",
"_handle_end_way",
"(",
"self",
")",
":",
"self",
".",
"_result",
".",
"append",
"(",
"Way",
"(",
"result",
"=",
"self",
".",
"_result",
",",
"*",
"*",
"self",
".",
"_curr",
")",
")",
"self",
".",
"_curr",
"=",
"{",
"}"
] | 28.666667 | 10.666667 |
def read_zipfile(self, encoding='utf8'):
"""
READ FIRST FILE IN ZIP FILE
:param encoding:
:return: STRING
"""
from zipfile import ZipFile
with ZipFile(self.abspath) as zipped:
for num, zip_name in enumerate(zipped.namelist()):
return zi... | [
"def",
"read_zipfile",
"(",
"self",
",",
"encoding",
"=",
"'utf8'",
")",
":",
"from",
"zipfile",
"import",
"ZipFile",
"with",
"ZipFile",
"(",
"self",
".",
"abspath",
")",
"as",
"zipped",
":",
"for",
"num",
",",
"zip_name",
"in",
"enumerate",
"(",
"zipped... | 35.4 | 9.8 |
def csv_to_list_of_dicts(lines: List[str],
csvheader: str,
quotechar: str = '"') -> List[Dict[str, str]]:
"""
Extracts data from a list of CSV lines (starting with a defined header
line) embedded in a longer text block but ending with a blank line.
Args... | [
"def",
"csv_to_list_of_dicts",
"(",
"lines",
":",
"List",
"[",
"str",
"]",
",",
"csvheader",
":",
"str",
",",
"quotechar",
":",
"str",
"=",
"'\"'",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
":",
"data",
"=",
"[",
"]",
"# t... | 35.785714 | 17.214286 |
def process_normal(_dict):
"""
this method process the _dict to correct dict to be called by class constructor
this method will be imported and called by main csv uploader function
"""
cooked_dict = group_raw_to_formatted_string_dict(_dict)
data_class = cooked_dict.pop('amaasclass', '')
chil... | [
"def",
"process_normal",
"(",
"_dict",
")",
":",
"cooked_dict",
"=",
"group_raw_to_formatted_string_dict",
"(",
"_dict",
")",
"data_class",
"=",
"cooked_dict",
".",
"pop",
"(",
"'amaasclass'",
",",
"''",
")",
"children_class_dict",
"=",
"direct_to_class",
"(",
"da... | 50.722222 | 23.5 |
def sessionize(user_events, cutoff=defaults.CUTOFF):
"""
Clusters user sessions from a sequence of user events. Note that,
`event` data will simply be returned in the case of a revert.
This function serves as a convenience wrapper around calls to
:class:`~mw.lib.sessions.Cache`'s :meth:`~mw.lib.se... | [
"def",
"sessionize",
"(",
"user_events",
",",
"cutoff",
"=",
"defaults",
".",
"CUTOFF",
")",
":",
"# Construct the session manager",
"sessionizer",
"=",
"Sessionizer",
"(",
"cutoff",
")",
"# Apply the events",
"for",
"user",
",",
"timestamp",
",",
"event",
"in",
... | 31.285714 | 22.785714 |
def write_to_file(self, file_path: str) -> None:
""" Serialize and write the data into a JSON file. """
data = self.encode()
with open(file_path, "w") as f:
json.dump(data, f, indent=1) | [
"def",
"write_to_file",
"(",
"self",
",",
"file_path",
":",
"str",
")",
"->",
"None",
":",
"data",
"=",
"self",
".",
"encode",
"(",
")",
"with",
"open",
"(",
"file_path",
",",
"\"w\"",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"data",
",",
"... | 43.4 | 4.2 |
def _whitelist_blacklist(self, os_name):
'''
Determines if the OS should be ignored,
depending on the whitelist-blacklist logic
configured by the user.
'''
return napalm_logs.ext.check_whitelist_blacklist(os_name,
w... | [
"def",
"_whitelist_blacklist",
"(",
"self",
",",
"os_name",
")",
":",
"return",
"napalm_logs",
".",
"ext",
".",
"check_whitelist_blacklist",
"(",
"os_name",
",",
"whitelist",
"=",
"self",
".",
"device_whitelist",
",",
"blacklist",
"=",
"self",
".",
"device_black... | 48.111111 | 23 |
def _build_cookie_jar(cls, session: AppSession):
'''Build the cookie jar'''
if not session.args.cookies:
return
if session.args.load_cookies or session.args.save_cookies:
session.factory.set('CookieJar', BetterMozillaCookieJar)
cookie_jar = session.factory.... | [
"def",
"_build_cookie_jar",
"(",
"cls",
",",
"session",
":",
"AppSession",
")",
":",
"if",
"not",
"session",
".",
"args",
".",
"cookies",
":",
"return",
"if",
"session",
".",
"args",
".",
"load_cookies",
"or",
"session",
".",
"args",
".",
"save_cookies",
... | 31.966667 | 24.366667 |
def addEnvPath(env, name, value):
""" concat a path for this name """
try:
oldval = env[name]
if not oldval.endswith(';'):
oldval = oldval + ';'
except KeyError:
oldval = ""
if not value.endswith(';'):
value = value + ';'
env[name] = oldval + value | [
"def",
"addEnvPath",
"(",
"env",
",",
"name",
",",
"value",
")",
":",
"try",
":",
"oldval",
"=",
"env",
"[",
"name",
"]",
"if",
"not",
"oldval",
".",
"endswith",
"(",
"';'",
")",
":",
"oldval",
"=",
"oldval",
"+",
"';'",
"except",
"KeyError",
":",
... | 27.454545 | 12.454545 |
def set_cookie(self, key, value, domain=None, path='/', secure=False,
httponly=True):
"""Set a cookie.
Args:
key (:obj:`str`): Cookie name
value (:obj:`str`): Cookie value
domain (:obj:`str`): Cookie domain
path (:obj:`str`): Cookie val... | [
"def",
"set_cookie",
"(",
"self",
",",
"key",
",",
"value",
",",
"domain",
"=",
"None",
",",
"path",
"=",
"'/'",
",",
"secure",
"=",
"False",
",",
"httponly",
"=",
"True",
")",
":",
"self",
".",
"_cookies",
"[",
"key",
"]",
"=",
"value",
"if",
"d... | 35.954545 | 14.545455 |
def visible_object_groups(self):
"""Return iterator of object group indexes that are set 'visible'
:rtype: Iterator
"""
return (i for (i, l) in enumerate(self.layers)
if l.visible and isinstance(l, TiledObjectGroup)) | [
"def",
"visible_object_groups",
"(",
"self",
")",
":",
"return",
"(",
"i",
"for",
"(",
"i",
",",
"l",
")",
"in",
"enumerate",
"(",
"self",
".",
"layers",
")",
"if",
"l",
".",
"visible",
"and",
"isinstance",
"(",
"l",
",",
"TiledObjectGroup",
")",
")"... | 37 | 14.714286 |
def isdir(self, relpath, rsc=None):
"""
Returns whether or not the resource is a directory.
:return <bool>
"""
filepath = self.find(relpath, rsc)
if filepath.startswith(':'):
resource = QtCore.QResource(filepath)
return not re... | [
"def",
"isdir",
"(",
"self",
",",
"relpath",
",",
"rsc",
"=",
"None",
")",
":",
"filepath",
"=",
"self",
".",
"find",
"(",
"relpath",
",",
"rsc",
")",
"if",
"filepath",
".",
"startswith",
"(",
"':'",
")",
":",
"resource",
"=",
"QtCore",
".",
"QReso... | 31.916667 | 9.416667 |
def _get_asym_alpha_tag(self,a,b):
"""
Find asymmetry from cryo oven with alpha detectors.
a: list of alpha detector histograms (each helicity)
b: list of beta detector histograms (each helicity) 1+ 1- 2+ 2-
"""
# beta in coincidence with alpha
c... | [
"def",
"_get_asym_alpha_tag",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"# beta in coincidence with alpha",
"coin",
"=",
"a",
"[",
":",
"4",
"]",
"# beta coincidence with no alpha",
"no_coin",
"=",
"a",
"[",
"4",
":",
"8",
"]",
"# get split helicity asym from "... | 34.44 | 17 |
def close(self):
"""Close all connections
"""
keys = set(self._conns.keys())
for key in keys:
self.stop_socket(key)
self._conns = {} | [
"def",
"close",
"(",
"self",
")",
":",
"keys",
"=",
"set",
"(",
"self",
".",
"_conns",
".",
"keys",
"(",
")",
")",
"for",
"key",
"in",
"keys",
":",
"self",
".",
"stop_socket",
"(",
"key",
")",
"self",
".",
"_conns",
"=",
"{",
"}"
] | 19.777778 | 16.111111 |
def emoji_list(server, n=1):
"""return a list of `n` random emoji"""
global EMOJI
if EMOJI is None:
EMOJI = EmojiCache(server)
return EMOJI.get(n) | [
"def",
"emoji_list",
"(",
"server",
",",
"n",
"=",
"1",
")",
":",
"global",
"EMOJI",
"if",
"EMOJI",
"is",
"None",
":",
"EMOJI",
"=",
"EmojiCache",
"(",
"server",
")",
"return",
"EMOJI",
".",
"get",
"(",
"n",
")"
] | 27.5 | 13 |
def get_disk_labels(self):
"""
Creates a mapping of device nodes to filesystem labels
"""
path = '/dev/disk/by-label/'
labels = {}
if not os.path.isdir(path):
return labels
for label in os.listdir(path):
label = label.replace('\\x2f', '/')... | [
"def",
"get_disk_labels",
"(",
"self",
")",
":",
"path",
"=",
"'/dev/disk/by-label/'",
"labels",
"=",
"{",
"}",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"labels",
"for",
"label",
"in",
"os",
".",
"listdir",
"(",
... | 28.133333 | 14.133333 |
def profile_detail(
request, username,
template_name=accounts_settings.ACCOUNTS_PROFILE_DETAIL_TEMPLATE,
extra_context=None, **kwargs):
"""
Detailed view of an user.
:param username:
String of the username of which the profile should be viewed.
:param template_name:
String ... | [
"def",
"profile_detail",
"(",
"request",
",",
"username",
",",
"template_name",
"=",
"accounts_settings",
".",
"ACCOUNTS_PROFILE_DETAIL_TEMPLATE",
",",
"extra_context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"user",
"=",
"get_object_or_404",
"(",
"get_use... | 33.692308 | 20.923077 |
def supported_tasks(self, lang=None):
"""Languages that are covered by a specific task.
Args:
lang (string): Language code name.
"""
if lang:
collection = self.get_collection(lang=lang)
return [x.id.split('.')[0] for x in collection.packages]
else:
return [x.name.split()[0] ... | [
"def",
"supported_tasks",
"(",
"self",
",",
"lang",
"=",
"None",
")",
":",
"if",
"lang",
":",
"collection",
"=",
"self",
".",
"get_collection",
"(",
"lang",
"=",
"lang",
")",
"return",
"[",
"x",
".",
"id",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
... | 33.818182 | 19.818182 |
def validate(self, value):
"""
Ensures that the password follows the following criteria:
:param value: <str>
:return: True
"""
if not isinstance(value, (str, unicode)):
raise orb.errors.ColumnValidationError(self, 'Invalid password.')
elif not self.... | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"raise",
"orb",
".",
"errors",
".",
"ColumnValidationError",
"(",
"self",
",",
"'Invalid password.'",
")",
... | 44.296296 | 29.777778 |
def get_datacenter(self, datacenter_id, depth=1):
"""
Retrieves a data center by its ID.
:param datacenter_id: The unique ID of the data center.
:type datacenter_id: ``str``
:param depth: The depth of the response data.
:type depth: ``int``
... | [
"def",
"get_datacenter",
"(",
"self",
",",
"datacenter_id",
",",
"depth",
"=",
"1",
")",
":",
"response",
"=",
"self",
".",
"_perform_request",
"(",
"'/datacenters/%s?depth=%s'",
"%",
"(",
"datacenter_id",
",",
"str",
"(",
"depth",
")",
")",
")",
"return",
... | 29.866667 | 18.133333 |
def debug_tag(self, tag):
"""Setter for the debug tag.
By default, the tag is the serial of the device, but sometimes it may
be more descriptive to use a different tag of the user's choice.
Changing debug tag changes part of the prefix of debug info emitted by
this object, like... | [
"def",
"debug_tag",
"(",
"self",
",",
"tag",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'Logging debug tag set to \"%s\"'",
",",
"tag",
")",
"self",
".",
"_debug_tag",
"=",
"tag",
"self",
".",
"log",
".",
"extra",
"[",
"'tag'",
"]",
"=",
"tag"
] | 43.388889 | 24.666667 |
def disconnect(self, token):
"""
Unregisters a callback for an event topic.
@param token: Token of the callback to unregister
@type token: dict
"""
topic = token['topic']
try:
arr = self._connects[topic]
except KeyError:
return
... | [
"def",
"disconnect",
"(",
"self",
",",
"token",
")",
":",
"topic",
"=",
"token",
"[",
"'topic'",
"]",
"try",
":",
"arr",
"=",
"self",
".",
"_connects",
"[",
"topic",
"]",
"except",
"KeyError",
":",
"return",
"arr",
".",
"remove",
"(",
"token",
"[",
... | 26.533333 | 13.2 |
def _h_function(self,h):
""" private method for the gaussian variogram "h" function
Parameters
----------
h : (float or numpy.ndarray)
distance(s)
Returns
-------
h_function : float or numpy.ndarray
the value of the "h" function implied b... | [
"def",
"_h_function",
"(",
"self",
",",
"h",
")",
":",
"hh",
"=",
"-",
"1.0",
"*",
"(",
"h",
"*",
"h",
")",
"/",
"(",
"self",
".",
"a",
"*",
"self",
".",
"a",
")",
"return",
"self",
".",
"contribution",
"*",
"np",
".",
"exp",
"(",
"hh",
")"... | 25.058824 | 19.470588 |
def get_argument_parser(name=None, **kwargs):
"""Returns the global ArgumentParser instance with the given name. The 1st
time this function is called, a new ArgumentParser instance will be created
for the given name, and any args other than "name" will be passed on to the
ArgumentParser constructor.
... | [
"def",
"get_argument_parser",
"(",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"\"default\"",
"if",
"len",
"(",
"kwargs",
")",
">",
"0",
"or",
"name",
"not",
"in",
"_parsers",
":",
"init_argum... | 36.846154 | 18 |
def alive(self):
'''Is this component alive?'''
with self._mutex:
if self.exec_contexts:
for ec in self.exec_contexts:
if self._obj.is_alive(ec):
return True
return False | [
"def",
"alive",
"(",
"self",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"self",
".",
"exec_contexts",
":",
"for",
"ec",
"in",
"self",
".",
"exec_contexts",
":",
"if",
"self",
".",
"_obj",
".",
"is_alive",
"(",
"ec",
")",
":",
"return",
"Tr... | 32.375 | 10.375 |
def from_json(cls, input_json: str) -> 'NistBeaconValue':
"""
Convert a string of JSON which represents a NIST randomness beacon
value into a 'NistBeaconValue' object.
:param input_json: JSON to build a 'Nist RandomnessBeaconValue' from
:return: A 'NistBeaconValue' object, 'None... | [
"def",
"from_json",
"(",
"cls",
",",
"input_json",
":",
"str",
")",
"->",
"'NistBeaconValue'",
":",
"try",
":",
"data_dict",
"=",
"json",
".",
"loads",
"(",
"input_json",
")",
"except",
"ValueError",
":",
"return",
"None",
"# Our required values are \"must haves... | 37.875 | 18.458333 |
def sys_path(self):
"""
The system path inside the environment
:return: The :data:`sys.path` from the environment
:rtype: list
"""
from .vendor.vistir.compat import JSONDecodeError
current_executable = vistir.compat.Path(sys.executable).as_posix()
if not... | [
"def",
"sys_path",
"(",
"self",
")",
":",
"from",
".",
"vendor",
".",
"vistir",
".",
"compat",
"import",
"JSONDecodeError",
"current_executable",
"=",
"vistir",
".",
"compat",
".",
"Path",
"(",
"sys",
".",
"executable",
")",
".",
"as_posix",
"(",
")",
"i... | 39.571429 | 23.095238 |
def threshold_monitor_hidden_threshold_monitor_sfp_pause(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshold_monito... | [
"def",
"threshold_monitor_hidden_threshold_monitor_sfp_pause",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"threshold_monitor_hidden",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"threshold-m... | 51.181818 | 24.181818 |
def get_value_from_state(self, path, head_hash=None, with_proof=False, multi_sig=None):
'''
Get a value (and proof optionally)for the given path in state trie.
Does not return the proof is there is no aggregate signature for it.
:param path: the path generate a state proof for
:p... | [
"def",
"get_value_from_state",
"(",
"self",
",",
"path",
",",
"head_hash",
"=",
"None",
",",
"with_proof",
"=",
"False",
",",
"multi_sig",
"=",
"None",
")",
":",
"root_hash",
"=",
"head_hash",
"if",
"head_hash",
"else",
"self",
".",
"state",
".",
"committe... | 47.081081 | 24.648649 |
def is_header(self):
"""
Whether or not the cell is a header
Any header cell will have "=" instead of "-" on its border.
For example, this is a header cell::
+-----+
| foo |
+=====+
while this cell is not::
+-----+
... | [
"def",
"is_header",
"(",
"self",
")",
":",
"bottom_line",
"=",
"self",
".",
"text",
".",
"split",
"(",
"'\\n'",
")",
"[",
"-",
"1",
"]",
"if",
"is_only",
"(",
"bottom_line",
",",
"[",
"'+'",
",",
"'='",
"]",
")",
":",
"return",
"True",
"return",
... | 19.482759 | 22.103448 |
def default_classification_value_maps(classification):
"""Helper to get default value maps from classification.
:param classification: Classification definition.
:type classification: dict
:returns: Dictionary with key = the class key and value = default strings.
:rtype: dict
"""
value_map... | [
"def",
"default_classification_value_maps",
"(",
"classification",
")",
":",
"value_maps",
"=",
"{",
"}",
"for",
"hazard_class",
"in",
"classification",
"[",
"'classes'",
"]",
":",
"value_maps",
"[",
"hazard_class",
"[",
"'key'",
"]",
"]",
"=",
"hazard_class",
"... | 32.066667 | 19.6 |
def _parse_triggered_hits(self, file_obj):
"""Parse and store triggered hits."""
for _ in range(self.n_triggered_hits):
dom_id, pmt_id = unpack('<ib', file_obj.read(5))
tdc_time = unpack('>I', file_obj.read(4))[0]
tot = unpack('<b', file_obj.read(1))[0]
tr... | [
"def",
"_parse_triggered_hits",
"(",
"self",
",",
"file_obj",
")",
":",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"n_triggered_hits",
")",
":",
"dom_id",
",",
"pmt_id",
"=",
"unpack",
"(",
"'<ib'",
",",
"file_obj",
".",
"read",
"(",
"5",
")",
")",
... | 47 | 12.1 |
def _robust_rmtree(path, logger=None, max_retries=5):
"""Try to delete paths robustly .
Retries several times (with increasing delays) if an OSError
occurs. If the final attempt fails, the Exception is propagated
to the caller. Taken from https://github.com/hashdist/hashdist/pull/116
"""
for i... | [
"def",
"_robust_rmtree",
"(",
"path",
",",
"logger",
"=",
"None",
",",
"max_retries",
"=",
"5",
")",
":",
"for",
"i",
"in",
"range",
"(",
"max_retries",
")",
":",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"return",
"except",
"OSError",
"... | 34.631579 | 18.526316 |
def read_value(self):
"""Reads the raw red, green, blue and clear channel values. Will return
a 4-tuple with the red, green, blue, clear color values (unsigned 16-bit
numbers).
"""
while not self._valid():
time.sleep((self._integration_time + 0.9)/1000.0)
# Re... | [
"def",
"read_value",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"_valid",
"(",
")",
":",
"time",
".",
"sleep",
"(",
"(",
"self",
".",
"_integration_time",
"+",
"0.9",
")",
"/",
"1000.0",
")",
"# Read each color register.",
"r",
"=",
"self",
".... | 42 | 17.368421 |
def prepare_destruction(self, recursive=True):
"""Prepares the model for destruction
Recursively un-registers all observers and removes references to child models
"""
if self.state is None:
logger.verbose("Multiple calls of prepare destruction for {0}".format(self))
... | [
"def",
"prepare_destruction",
"(",
"self",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"self",
".",
"state",
"is",
"None",
":",
"logger",
".",
"verbose",
"(",
"\"Multiple calls of prepare destruction for {0}\"",
".",
"format",
"(",
"self",
")",
")",
"self",... | 40.8125 | 15.8125 |
def timetopythonvalue(time_val):
"Convert a time or time range from ArcGIS REST server format to Python"
if isinstance(time_val, sequence):
return map(timetopythonvalue, time_val)
elif isinstance(time_val, numeric):
return datetime.datetime(*(time.gmtime(time_val))[:6])
elif isinstance(t... | [
"def",
"timetopythonvalue",
"(",
"time_val",
")",
":",
"if",
"isinstance",
"(",
"time_val",
",",
"sequence",
")",
":",
"return",
"map",
"(",
"timetopythonvalue",
",",
"time_val",
")",
"elif",
"isinstance",
"(",
"time_val",
",",
"numeric",
")",
":",
"return",... | 36.533333 | 14.666667 |
def all(cls, connection=None, **params):
"""
Returns first page if no params passed in as a list.
"""
request = cls._make_request('GET', cls._get_all_path(), connection, params=params)
return cls._create_object(request, connection=connection) | [
"def",
"all",
"(",
"cls",
",",
"connection",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"request",
"=",
"cls",
".",
"_make_request",
"(",
"'GET'",
",",
"cls",
".",
"_get_all_path",
"(",
")",
",",
"connection",
",",
"params",
"=",
"params",
")",
... | 40.142857 | 19.857143 |
def update_by_token(self, token, **kwargs):
"""
Updated the session info. Any type of known token can be used
:param token: code/access token/refresh token/...
:param kwargs: Key word arguements
"""
_sid = self.handler.sid(token)
return self.update(_sid, **kwargs... | [
"def",
"update_by_token",
"(",
"self",
",",
"token",
",",
"*",
"*",
"kwargs",
")",
":",
"_sid",
"=",
"self",
".",
"handler",
".",
"sid",
"(",
"token",
")",
"return",
"self",
".",
"update",
"(",
"_sid",
",",
"*",
"*",
"kwargs",
")"
] | 34.777778 | 10.555556 |
def get_all_project_owners(project_ids=None, **kwargs):
"""
Get the project owner entries for all the requested projects.
If the project_ids argument is None, return all the owner entries
for ALL projects
"""
projowner_qry = db.DBSession.query(ProjectOwner)
if project_ids is n... | [
"def",
"get_all_project_owners",
"(",
"project_ids",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"projowner_qry",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"ProjectOwner",
")",
"if",
"project_ids",
"is",
"not",
"None",
":",
"projowner_qry",
"=",
... | 32.8125 | 25.0625 |
def recv(self, bufsize=DEFAULT_PACKET_BUFFER_SIZE):
"""
Receives a diverted packet that matched the filter.
The remapped function is WinDivertRecv::
BOOL WinDivertRecv(
__in HANDLE handle,
__out PVOID pPacket,
__in UINT packetLen,
... | [
"def",
"recv",
"(",
"self",
",",
"bufsize",
"=",
"DEFAULT_PACKET_BUFFER_SIZE",
")",
":",
"if",
"self",
".",
"_handle",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"WinDivert handle is not open\"",
")",
"packet",
"=",
"bytearray",
"(",
"bufsize",
")",
"p... | 35.451613 | 18.16129 |
def _get_register_specs(bit_labels):
"""Get the number and size of unique registers from bit_labels list.
Args:
bit_labels (list): this list is of the form::
[['reg1', 0], ['reg1', 1], ['reg2', 0]]
which indicates a register named "reg1" of size 2
and a register na... | [
"def",
"_get_register_specs",
"(",
"bit_labels",
")",
":",
"it",
"=",
"itertools",
".",
"groupby",
"(",
"bit_labels",
",",
"operator",
".",
"itemgetter",
"(",
"0",
")",
")",
"for",
"register_name",
",",
"sub_it",
"in",
"it",
":",
"yield",
"register_name",
... | 34.368421 | 20.631579 |
def addr2line(self, addrq):
'''
Get the line number for a given bytecode offset
Analogous to PyCode_Addr2Line; translated from pseudocode in
Objects/lnotab_notes.txt
'''
co_lnotab = self.pyop_field('co_lnotab').proxyval(set())
# Initialize lineno to co_firstline... | [
"def",
"addr2line",
"(",
"self",
",",
"addrq",
")",
":",
"co_lnotab",
"=",
"self",
".",
"pyop_field",
"(",
"'co_lnotab'",
")",
".",
"proxyval",
"(",
"set",
"(",
")",
")",
"# Initialize lineno to co_firstlineno as per PyCode_Addr2Line",
"# not 0, as lnotab_notes.txt ha... | 33.85 | 21.35 |
def parse(self, nodes):
"""Given a stream of node data, try to parse the nodes according to the machine's graph."""
self.last_node_type = self.initial_node_type
for node_number, node in enumerate(nodes):
try:
self.step(node)
except Exception as ex:
raise Exception("An error occur... | [
"def",
"parse",
"(",
"self",
",",
"nodes",
")",
":",
"self",
".",
"last_node_type",
"=",
"self",
".",
"initial_node_type",
"for",
"node_number",
",",
"node",
"in",
"enumerate",
"(",
"nodes",
")",
":",
"try",
":",
"self",
".",
"step",
"(",
"node",
")",
... | 44.625 | 16.5 |
def output(self, _filename):
"""
_filename is not used
Args:
_filename(string)
"""
txt = ''
for c in self.contracts:
txt += "\nContract %s\n"%c.name
table = PrettyTable(['Variable', 'Dependencies'])
for v in c.s... | [
"def",
"output",
"(",
"self",
",",
"_filename",
")",
":",
"txt",
"=",
"''",
"for",
"c",
"in",
"self",
".",
"contracts",
":",
"txt",
"+=",
"\"\\nContract %s\\n\"",
"%",
"c",
".",
"name",
"table",
"=",
"PrettyTable",
"(",
"[",
"'Variable'",
",",
"'Depend... | 33.230769 | 15 |
def create_collection(self, collection_name, database_name=None):
"""
Creates a new collection in the CosmosDB database.
"""
if collection_name is None:
raise AirflowBadRequest("Collection name cannot be None.")
# We need to check to see if this container already exi... | [
"def",
"create_collection",
"(",
"self",
",",
"collection_name",
",",
"database_name",
"=",
"None",
")",
":",
"if",
"collection_name",
"is",
"None",
":",
"raise",
"AirflowBadRequest",
"(",
"\"Collection name cannot be None.\"",
")",
"# We need to check to see if this cont... | 42.727273 | 19.363636 |
def fetch(self):
"""
Fetch a UserChannelInstance
:returns: Fetched UserChannelInstance
:rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
... | [
"def",
"fetch",
"(",
"self",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"fetch",
"(",
"'GET'",
",",
"self",
".",
"_uri",
",",
"params",
"=",
"params",
",",
")",
"return",
"UserC... | 26.727273 | 18.090909 |
def set(self, language: str, value: str):
"""Sets the value in the specified language.
Arguments:
language:
The language to set the value in.
value:
The value to set.
"""
self[language] = value
self.__dict__.update(self)
... | [
"def",
"set",
"(",
"self",
",",
"language",
":",
"str",
",",
"value",
":",
"str",
")",
":",
"self",
"[",
"language",
"]",
"=",
"value",
"self",
".",
"__dict__",
".",
"update",
"(",
"self",
")",
"return",
"self"
] | 23.285714 | 16.928571 |
def get_subscriber_model():
"""
Attempt to pull settings.DJSTRIPE_SUBSCRIBER_MODEL.
Users have the option of specifying a custom subscriber model via the
DJSTRIPE_SUBSCRIBER_MODEL setting.
This methods falls back to AUTH_USER_MODEL if DJSTRIPE_SUBSCRIBER_MODEL is not set.
Returns the subscriber model that is a... | [
"def",
"get_subscriber_model",
"(",
")",
":",
"model_name",
"=",
"get_subscriber_model_string",
"(",
")",
"# Attempt a Django 1.7 app lookup",
"try",
":",
"subscriber_model",
"=",
"django_apps",
".",
"get_model",
"(",
"model_name",
")",
"except",
"ValueError",
":",
"r... | 33.170732 | 24.146341 |
def _get_userprofile_from_registry(user, sid):
'''
In case net user doesn't return the userprofile we can get it from the
registry
Args:
user (str): The user name, used in debug message
sid (str): The sid to lookup in the registry
Returns:
str: Profile directory
'''
... | [
"def",
"_get_userprofile_from_registry",
"(",
"user",
",",
"sid",
")",
":",
"profile_dir",
"=",
"__utils__",
"[",
"'reg.read_value'",
"]",
"(",
"'HKEY_LOCAL_MACHINE'",
",",
"'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\ProfileList\\\\{0}'",
".",
"format",
"(",
... | 27.652174 | 24.434783 |
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by queue consumers. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will res... | [
"def",
"task_done",
"(",
"self",
")",
":",
"self",
".",
"_parent",
".",
"_check_closing",
"(",
")",
"with",
"self",
".",
"_parent",
".",
"_all_tasks_done",
":",
"if",
"self",
".",
"_parent",
".",
"_unfinished_tasks",
"<=",
"0",
":",
"raise",
"ValueError",
... | 44 | 20.045455 |
def _make_argparser(self):
"""Makes a new argument parser."""
self.argparser = ShellArgumentParser(prog='')
subparsers = self.argparser.add_subparsers()
for name in self.get_names():
if name.startswith('parser_'):
parser = subparsers.add_parser(name[7:])
... | [
"def",
"_make_argparser",
"(",
"self",
")",
":",
"self",
".",
"argparser",
"=",
"ShellArgumentParser",
"(",
"prog",
"=",
"''",
")",
"subparsers",
"=",
"self",
".",
"argparser",
".",
"add_subparsers",
"(",
")",
"for",
"name",
"in",
"self",
".",
"get_names",... | 36 | 19.9 |
def build_full_day_ips(query, period_start, period_end):
"""Method to build an IP list for the case 1
when the IP was allocated before the period start
and is still allocated after the period end.
This method only looks at public IPv4 addresses.
"""
# Filter out only IPv4 that have not been dea... | [
"def",
"build_full_day_ips",
"(",
"query",
",",
"period_start",
",",
"period_end",
")",
":",
"# Filter out only IPv4 that have not been deallocated",
"ip_list",
"=",
"query",
".",
"filter",
"(",
"models",
".",
"IPAddress",
".",
"version",
"==",
"4L",
")",
".",
"fi... | 44.631579 | 18.684211 |
def getDateReceived(self):
"""Used to populate catalog values.
Returns the date the Analysis Request this analysis belongs to was
received. If the analysis was created after, then returns the date
the analysis was created.
"""
request = self.getRequest()
if reques... | [
"def",
"getDateReceived",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"getRequest",
"(",
")",
"if",
"request",
":",
"ar_date",
"=",
"request",
".",
"getDateReceived",
"(",
")",
"if",
"ar_date",
"and",
"self",
".",
"created",
"(",
")",
">",
"ar_... | 38.153846 | 13.230769 |
def _setup_imports(self):
"""
Ensure the local importer and PushFileService has everything for the
Ansible module before setup() completes, but before detach() is called
in an asynchronous task.
The master automatically streams modules towards us concurrent to the
runner... | [
"def",
"_setup_imports",
"(",
"self",
")",
":",
"for",
"fullname",
",",
"_",
",",
"_",
"in",
"self",
".",
"module_map",
"[",
"'custom'",
"]",
":",
"mitogen",
".",
"core",
".",
"import_module",
"(",
"fullname",
")",
"for",
"fullname",
"in",
"self",
".",... | 48.125 | 21.25 |
def queue(self):
"""Message queue queue."""
with self.connection_pool.acquire(block=True) as conn:
return Q(
self.routing_key,
exchange=self.exchange,
routing_key=self.routing_key
)(conn) | [
"def",
"queue",
"(",
"self",
")",
":",
"with",
"self",
".",
"connection_pool",
".",
"acquire",
"(",
"block",
"=",
"True",
")",
"as",
"conn",
":",
"return",
"Q",
"(",
"self",
".",
"routing_key",
",",
"exchange",
"=",
"self",
".",
"exchange",
",",
"rou... | 33.5 | 12.25 |
def decorate_with_validators(func,
func_signature=None, # type: Signature
**validators # type: Validator
):
"""
Utility method to decorate the provided function with the provided input and output Validator objects. ... | [
"def",
"decorate_with_validators",
"(",
"func",
",",
"func_signature",
"=",
"None",
",",
"# type: Signature",
"*",
"*",
"validators",
"# type: Validator",
")",
":",
"# first turn the dictionary values into lists only",
"for",
"arg_name",
",",
"validator",
"in",
"validator... | 46.15493 | 27.84507 |
def has_permission(self, user):
"""
Returns True if the given request has permission to use the tool.
Can be overriden by the user in subclasses.
"""
return user.has_perm(
self.model._meta.app_label + '.' + self.get_permission()
) | [
"def",
"has_permission",
"(",
"self",
",",
"user",
")",
":",
"return",
"user",
".",
"has_perm",
"(",
"self",
".",
"model",
".",
"_meta",
".",
"app_label",
"+",
"'.'",
"+",
"self",
".",
"get_permission",
"(",
")",
")"
] | 35.375 | 15.375 |
def simulate_custom_policy(PolicyInputList=None, ActionNames=None, ResourceArns=None, ResourcePolicy=None, ResourceOwner=None, CallerArn=None, ContextEntries=None, ResourceHandlingOption=None, MaxItems=None, Marker=None):
"""
Simulate how a set of IAM policies and optionally a resource-based policy works with a... | [
"def",
"simulate_custom_policy",
"(",
"PolicyInputList",
"=",
"None",
",",
"ActionNames",
"=",
"None",
",",
"ResourceArns",
"=",
"None",
",",
"ResourcePolicy",
"=",
"None",
",",
"ResourceOwner",
"=",
"None",
",",
"CallerArn",
"=",
"None",
",",
"ContextEntries",
... | 71.570588 | 56.794118 |
def html2vtml(vtmarkup):
""" Convert hypertext markup into vt markup.
The output can be given to `vtmlrender` for converstion to VT100
sequences. """
try:
htmlconv.feed(vtmarkup)
htmlconv.close()
return htmlconv.getvalue()
finally:
htmlconv.reset() | [
"def",
"html2vtml",
"(",
"vtmarkup",
")",
":",
"try",
":",
"htmlconv",
".",
"feed",
"(",
"vtmarkup",
")",
"htmlconv",
".",
"close",
"(",
")",
"return",
"htmlconv",
".",
"getvalue",
"(",
")",
"finally",
":",
"htmlconv",
".",
"reset",
"(",
")"
] | 29.1 | 15.1 |
def setup_ssh_tunnel(job_id, local_port, remote_port):
"""
Setup an ssh tunnel to the given job-id. This will establish
the port over the given local_port to the given remote_port
and then exit, keeping the tunnel in place until the job is
terminated.
"""
cmd = ['dx', 'ssh', '--suppress-run... | [
"def",
"setup_ssh_tunnel",
"(",
"job_id",
",",
"local_port",
",",
"remote_port",
")",
":",
"cmd",
"=",
"[",
"'dx'",
",",
"'ssh'",
",",
"'--suppress-running-check'",
",",
"job_id",
",",
"'-o'",
",",
"'StrictHostKeyChecking no'",
"]",
"cmd",
"+=",
"[",
"'-f'",
... | 47.9 | 21.5 |
def calculate_splits(sdf_file, split_size):
"""Retrieve
"""
counts = _sdfstats(sdf_file)["counts"]
splits = []
cur = 0
for i in range(counts // split_size + (0 if counts % split_size == 0 else 1)):
splits.append("%s-%s" % (cur, min(counts, cur + split_size)))
cur += split_size
... | [
"def",
"calculate_splits",
"(",
"sdf_file",
",",
"split_size",
")",
":",
"counts",
"=",
"_sdfstats",
"(",
"sdf_file",
")",
"[",
"\"counts\"",
"]",
"splits",
"=",
"[",
"]",
"cur",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"counts",
"//",
"split_size",
"... | 32.6 | 16.8 |
def protoWithProof():
"""
Run the full protocol including proof generation and verification.
"""
r, x = blind(m)
y,kw,tTilde = eval(w,t,x,msk,s)
pi = prove(x, tTilde, kw, y)
verify(x, t, y, pi, errorOnFail=True)
z = deblind(r, y) | [
"def",
"protoWithProof",
"(",
")",
":",
"r",
",",
"x",
"=",
"blind",
"(",
"m",
")",
"y",
",",
"kw",
",",
"tTilde",
"=",
"eval",
"(",
"w",
",",
"t",
",",
"x",
",",
"msk",
",",
"s",
")",
"pi",
"=",
"prove",
"(",
"x",
",",
"tTilde",
",",
"kw... | 23 | 16.636364 |
def datum_to_value(self, instance, datum):
"""Convert a given MAAS-side datum to a Python-side value.
:param instance: The `Object` instance on which this field is
currently operating. This method should treat it as read-only, for
example to perform validation with regards to ot... | [
"def",
"datum_to_value",
"(",
"self",
",",
"instance",
",",
"datum",
")",
":",
"datum",
"=",
"self",
".",
"map_func",
"(",
"instance",
",",
"datum",
")",
"if",
"datum",
"is",
"None",
":",
"return",
"None",
"local_data",
"=",
"None",
"if",
"self",
".",
... | 43.652174 | 15.695652 |
def connection_lost(self, exc: Exception=None):
"""连接丢失时触发的回调函数.
用于清理一些任务和关闭连接,包括:
+ 取消监听任务
+ 取消过期监控任务
+ 取消其他还没执行完的任务
+ 将流读写器都重置
+ 将本连接从当前的连接池中去除
Parameters:
exc (Exception): - 异常,如果是None的话说明不是因为异常而关闭的连接
"""
self._handlertask... | [
"def",
"connection_lost",
"(",
"self",
",",
"exc",
":",
"Exception",
"=",
"None",
")",
":",
"self",
".",
"_handlertask",
".",
"cancel",
"(",
")",
"super",
"(",
")",
".",
"connection_lost",
"(",
"exc",
")",
"if",
"self",
".",
"_timeout_handler",
":",
"s... | 26.04 | 16.64 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.