text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get(self, sid):
"""
Constructs a IncomingPhoneNumberContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.incoming_phone_number.IncomingPhoneNumberContext
:rtype: twilio.rest.api.v2010.account.incoming_phone_number.Incomi... | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"IncomingPhoneNumberContext",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
"sid",
"=",
"sid",
",",
")"
] | 45.4 | 0.010799 |
def to_json(self):
"""Convert the Design Day to a dictionary."""
return {
'location': self.location.to_json(),
'design_days': [des_d.to_json() for des_d in self.design_days]
} | [
"def",
"to_json",
"(",
"self",
")",
":",
"return",
"{",
"'location'",
":",
"self",
".",
"location",
".",
"to_json",
"(",
")",
",",
"'design_days'",
":",
"[",
"des_d",
".",
"to_json",
"(",
")",
"for",
"des_d",
"in",
"self",
".",
"design_days",
"]",
"}... | 36.333333 | 0.008969 |
def process_op(self, rc, nbytes, overlap):
"""
Handles the possible completion or re-queueing if conditions haven't
been met (the `complete` callable returns false) of a overlapped request.
"""
act = overlap.object
overlap.object = None
if act in self.token... | [
"def",
"process_op",
"(",
"self",
",",
"rc",
",",
"nbytes",
",",
"overlap",
")",
":",
"act",
"=",
"overlap",
".",
"object",
"overlap",
".",
"object",
"=",
"None",
"if",
"act",
"in",
"self",
".",
"tokens",
":",
"ol",
",",
"perform",
",",
"complete",
... | 43 | 0.004665 |
def deprecated(message):
"""The decorator to mark deprecated functions."""
from traceback import extract_stack
assert message, "`message` argument in @deprecated is required."
def deprecated_decorator(fun):
def decorator_invisible(*args, **kwargs):
stack = extract_stack()
... | [
"def",
"deprecated",
"(",
"message",
")",
":",
"from",
"traceback",
"import",
"extract_stack",
"assert",
"message",
",",
"\"`message` argument in @deprecated is required.\"",
"def",
"deprecated_decorator",
"(",
"fun",
")",
":",
"def",
"decorator_invisible",
"(",
"*",
... | 42.809524 | 0.002176 |
def infer_declared_from_conditions(conds, namespace=None):
''' like infer_declared except that it is passed a set of first party
caveat conditions as a list of string rather than a set of macaroons.
'''
conflicts = []
# If we can't resolve that standard namespace, then we'll look for
# just bare... | [
"def",
"infer_declared_from_conditions",
"(",
"conds",
",",
"namespace",
"=",
"None",
")",
":",
"conflicts",
"=",
"[",
"]",
"# If we can't resolve that standard namespace, then we'll look for",
"# just bare \"declared\" caveats which will work OK for legacy",
"# macaroons with no nam... | 32.057143 | 0.000865 |
def repstring_penalty(reps, intensities, desired_reps, desired_intensity,
minimum_rep):
"""Penalty function which calculates how "bad" a set of
reps and intensities is, compared to the desired repetitions,
the desired intensity level and the minimum repetitions.
... | [
"def",
"repstring_penalty",
"(",
"reps",
",",
"intensities",
",",
"desired_reps",
",",
"desired_intensity",
",",
"minimum_rep",
")",
":",
"# Punish when the mean intensity is far from the desired one",
"desired",
"=",
"desired_intensity",
"error1",
"=",
"abs",
"(",
"stati... | 37.245614 | 0.005966 |
def check_thresholds(self, service=None, use_ta=True):
"""
Check all limits and current usage against their specified thresholds;
return all :py:class:`~.AwsLimit` instances that have crossed
one or more of their thresholds.
If ``service`` is specified, the returned dict has one... | [
"def",
"check_thresholds",
"(",
"self",
",",
"service",
"=",
"None",
",",
"use_ta",
"=",
"True",
")",
":",
"res",
"=",
"{",
"}",
"to_get",
"=",
"self",
".",
"services",
"if",
"service",
"is",
"not",
"None",
":",
"to_get",
"=",
"dict",
"(",
"(",
"ea... | 40.525 | 0.001205 |
def close(self):
"""Stops accepting new connections, cancels all currently running
requests. Request handlers are able to handle `CancelledError` and
exit properly.
"""
if self._server is None:
raise RuntimeError('Server is not started')
self._server.close()
... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Server is not started'",
")",
"self",
".",
"_server",
".",
"close",
"(",
")",
"for",
"handler",
"in",
"self",
".",
"_handlers",
":",
... | 37.6 | 0.005195 |
def fit_transform(self, features, class_labels):
"""Convenience function that fits the provided data then constructs a new feature from the provided features.
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
class_labels: array-like {... | [
"def",
"fit_transform",
"(",
"self",
",",
"features",
",",
"class_labels",
")",
":",
"self",
".",
"fit",
"(",
"features",
",",
"class_labels",
")",
"return",
"self",
".",
"transform",
"(",
"features",
")"
] | 32.333333 | 0.005008 |
def TransformedRandomVariable(random_variable, # pylint: disable=invalid-name
reversible_layer,
name=None,
sample_shape=(),
value=None):
"""Random variable for f(x), where x ~ p(x) and f is reversi... | [
"def",
"TransformedRandomVariable",
"(",
"random_variable",
",",
"# pylint: disable=invalid-name",
"reversible_layer",
",",
"name",
"=",
"None",
",",
"sample_shape",
"=",
"(",
")",
",",
"value",
"=",
"None",
")",
":",
"return",
"ed",
".",
"RandomVariable",
"(",
... | 48.75 | 0.005034 |
def link_pantsrefs(soups, precomputed):
"""Transorm soups: <a pantsref="foo"> becomes <a href="../foo_page.html#foo">"""
for (page, soup) in soups.items():
for a in soup.find_all('a'):
if not a.has_attr('pantsref'):
continue
pantsref = a['pantsref']
if not pantsref in precomputed.pants... | [
"def",
"link_pantsrefs",
"(",
"soups",
",",
"precomputed",
")",
":",
"for",
"(",
"page",
",",
"soup",
")",
"in",
"soups",
".",
"items",
"(",
")",
":",
"for",
"a",
"in",
"soup",
".",
"find_all",
"(",
"'a'",
")",
":",
"if",
"not",
"a",
".",
"has_at... | 47 | 0.018975 |
def dataReceived(self, data):
"""
Parses chunks of bytes into responses.
Whenever a complete response is received, this method extracts its
payload and calls L{responseReceived} to process it.
@param data: A chunk of data representing a (possibly partial) response
@type... | [
"def",
"dataReceived",
"(",
"self",
",",
"data",
")",
":",
"size",
"=",
"len",
"(",
"self",
".",
"_buffer",
")",
"+",
"len",
"(",
"data",
")",
"if",
"size",
">",
"self",
".",
"MAX_LENGTH",
":",
"self",
".",
"lengthLimitExceeded",
"(",
"size",
")",
... | 34.481481 | 0.00209 |
def negative_directional_movement(high_data, low_data):
"""
Negative Directional Movement (-DM).
-DM: if DWNMOVE > UPMOVE and DWNMOVE > 0 then -DM = DWNMOVE else -Dm = 0
"""
catch_errors.check_for_input_len_diff(high_data, low_data)
up_moves = calculate_up_moves(high_data)
down_moves = cal... | [
"def",
"negative_directional_movement",
"(",
"high_data",
",",
"low_data",
")",
":",
"catch_errors",
".",
"check_for_input_len_diff",
"(",
"high_data",
",",
"low_data",
")",
"up_moves",
"=",
"calculate_up_moves",
"(",
"high_data",
")",
"down_moves",
"=",
"calculate_do... | 28.894737 | 0.001764 |
def _get_sg_ids(self):
"""Get IDs for all defined security groups.
Returns:
list: security group IDs for all lambda_extras
"""
try:
lambda_extras = self.settings['security_groups']['lambda_extras']
except KeyError:
lambda_extras = []
... | [
"def",
"_get_sg_ids",
"(",
"self",
")",
":",
"try",
":",
"lambda_extras",
"=",
"self",
".",
"settings",
"[",
"'security_groups'",
"]",
"[",
"'lambda_extras'",
"]",
"except",
"KeyError",
":",
"lambda_extras",
"=",
"[",
"]",
"security_groups",
"=",
"[",
"self"... | 33.647059 | 0.005102 |
def interp(self):
"""Interpolation type of this discretization."""
if self.ndim == 0:
return 'nearest'
elif all(interp == self.interp_byaxis[0]
for interp in self.interp_byaxis):
return self.interp_byaxis[0]
else:
return self.interp_by... | [
"def",
"interp",
"(",
"self",
")",
":",
"if",
"self",
".",
"ndim",
"==",
"0",
":",
"return",
"'nearest'",
"elif",
"all",
"(",
"interp",
"==",
"self",
".",
"interp_byaxis",
"[",
"0",
"]",
"for",
"interp",
"in",
"self",
".",
"interp_byaxis",
")",
":",
... | 35.111111 | 0.006173 |
def getContent(self):
"""
Returns:
str: Content of tag (everything between `opener` and `endtag`).
"""
if not self.isTag() and self._element:
return self._element
if not self.childs:
return ""
output = ""
for c in self.childs:... | [
"def",
"getContent",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"isTag",
"(",
")",
"and",
"self",
".",
"_element",
":",
"return",
"self",
".",
"_element",
"if",
"not",
"self",
".",
"childs",
":",
"return",
"\"\"",
"output",
"=",
"\"\"",
"for",
... | 23.3 | 0.004124 |
def _GetReportService(self):
"""Lazily initializes a report service client."""
if not self._report_service:
self._report_service = self._ad_manager_client.GetService(
'ReportService', self._version, self._server)
return self._report_service | [
"def",
"_GetReportService",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_report_service",
":",
"self",
".",
"_report_service",
"=",
"self",
".",
"_ad_manager_client",
".",
"GetService",
"(",
"'ReportService'",
",",
"self",
".",
"_version",
",",
"self",
... | 43.833333 | 0.007463 |
def inverse_deriv(self, z):
"""
Derivative of the inverse of the power transform
Parameters
----------
z : array-like
`z` is usually the linear predictor for a GLM or GEE model.
Returns
-------
g^(-1)'(z) : array
The value of the ... | [
"def",
"inverse_deriv",
"(",
"self",
",",
"z",
")",
":",
"return",
"np",
".",
"power",
"(",
"z",
",",
"(",
"1",
"-",
"self",
".",
"power",
")",
"/",
"self",
".",
"power",
")",
"/",
"self",
".",
"power"
] | 28.1875 | 0.004292 |
def put(self, _url, **kwargs):
"""
This will perform a manual PUT request where the user will
supply the sub_url and request params (URN)
The connections class will add the base_uri and authentication
credentials.
PUT requests create data on the server
:param _ur... | [
"def",
"put",
"(",
"self",
",",
"_url",
",",
"*",
"*",
"kwargs",
")",
":",
"api_call",
"=",
"self",
".",
"request",
"(",
"'PUT'",
",",
"_url",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"cookies",
".",
"update",
"(",
"api_call",
".",
"response_cook... | 43.3125 | 0.002825 |
def new(params, event_shape=(), validate_args=False, name=None):
"""Create the distribution instance from a `params` vector."""
with tf.compat.v1.name_scope(name, 'IndependentPoisson',
[params, event_shape]):
params = tf.convert_to_tensor(value=params, name='params')
... | [
"def",
"new",
"(",
"params",
",",
"event_shape",
"=",
"(",
")",
",",
"validate_args",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'IndependentPoisson'",
",",
"[",
"pa... | 44.35 | 0.005519 |
def _appendGuideline(self, position, angle, name=None, color=None, identifier=None, **kwargs):
"""
position will be a valid position (x, y).
angle will be a valid angle.
name will be a valid guideline name or None.
color will be a valid color or None .
identifier will be ... | [
"def",
"_appendGuideline",
"(",
"self",
",",
"position",
",",
"angle",
",",
"name",
"=",
"None",
",",
"color",
"=",
"None",
",",
"identifier",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"raiseNotImplementedError",
"(",
")"
] | 37.384615 | 0.006024 |
def _from_arrays(self, x, y, z):
"""
Create VTK structured grid directly from numpy arrays.
Parameters
----------
x : np.ndarray
Position of the points in x direction.
y : np.ndarray
Position of the points in y direction.
z : np.ndarray
... | [
"def",
"_from_arrays",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"if",
"not",
"(",
"x",
".",
"shape",
"==",
"y",
".",
"shape",
"==",
"z",
".",
"shape",
")",
":",
"raise",
"Exception",
"(",
"'Input point array shapes must match exactly'",
")"... | 29.34375 | 0.002062 |
def _preconditions_snapshots_postconditions(checker: Callable) -> _PrePostSnaps:
"""Collect the preconditions, snapshots and postconditions from a contract checker of a function."""
preconditions = getattr(checker, "__preconditions__", []) # type: List[List[icontract._Contract]]
assert all(isinstance(prec... | [
"def",
"_preconditions_snapshots_postconditions",
"(",
"checker",
":",
"Callable",
")",
"->",
"_PrePostSnaps",
":",
"preconditions",
"=",
"getattr",
"(",
"checker",
",",
"\"__preconditions__\"",
",",
"[",
"]",
")",
"# type: List[List[icontract._Contract]]",
"assert",
"a... | 57.35 | 0.008576 |
def load(cls, build_file, name, target_aliases):
"""A BuildFileManipulator factory class method.
Note that BuildFileManipulator requires a very strict formatting of target declaration.
In particular, it wants to see a newline after `target_type(`, `dependencies = [`, and
the last param to the target co... | [
"def",
"load",
"(",
"cls",
",",
"build_file",
",",
"name",
",",
"target_aliases",
")",
":",
"with",
"open",
"(",
"build_file",
".",
"full_path",
",",
"'r'",
")",
"as",
"f",
":",
"source",
"=",
"f",
".",
"read",
"(",
")",
"source_lines",
"=",
"source"... | 49.457143 | 0.007038 |
def encrypt_binary(self, binary, *args, **kwargs):
"""
input: bytes, output: bytes
"""
return self.encrypt(binary, *args, **kwargs) | [
"def",
"encrypt_binary",
"(",
"self",
",",
"binary",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"encrypt",
"(",
"binary",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 31.8 | 0.01227 |
def schedule(self, materials=None, variables=None, secure_variables=None):
"""
Scheduling allows user to trigger a specific pipeline.
:param materials: material revisions to use.
:param variables: environment variables to set.
:param secure_variables: secure environment variable... | [
"def",
"schedule",
"(",
"self",
",",
"materials",
"=",
"None",
",",
"variables",
"=",
"None",
",",
"secure_variables",
"=",
"None",
")",
":",
"return",
"self",
".",
"_pipeline",
".",
"schedule",
"(",
"name",
"=",
"self",
".",
"data",
".",
"name",
",",
... | 37.333333 | 0.003484 |
def get_remote_file(self, remote_path, local_path):
"""Fetch remote File.
:param remote_path: remote path
:param local_path: local path
"""
sftp_client = self.transport.open_sftp_client()
LOG.debug('Get the remote file. '
'Source=%(src)s. Target=%(targe... | [
"def",
"get_remote_file",
"(",
"self",
",",
"remote_path",
",",
"local_path",
")",
":",
"sftp_client",
"=",
"self",
".",
"transport",
".",
"open_sftp_client",
"(",
")",
"LOG",
".",
"debug",
"(",
"'Get the remote file. '",
"'Source=%(src)s. Target=%(target)s.'",
"%",... | 38.6875 | 0.003155 |
def getDueDate(self):
"""Used to populate getDueDate index and metadata.
This calculates the difference between the time the analysis processing
started and the maximum turnaround time. If the analysis has no
turnaround time set or is not yet ready for proces, returns None
"""
... | [
"def",
"getDueDate",
"(",
"self",
")",
":",
"tat",
"=",
"self",
".",
"getMaxTimeAllowed",
"(",
")",
"if",
"not",
"tat",
":",
"return",
"None",
"start",
"=",
"self",
".",
"getStartProcessDate",
"(",
")",
"if",
"not",
"start",
":",
"return",
"None",
"# d... | 32.377778 | 0.001332 |
def store(hdu,dbase='cfeps',duser='cfhls',dtype='MYSQL',table='source'):
"""Write the contents of a MOP data structure to a SQL table"""
import MOPdbaccess
db=MOPdbaccess.connect(dbase,duser,dbSystem=dtype)
dbc=db.cursor()
### INSERT THE 'HEADER' in the meta-data table
file_id=hdu['header']['i... | [
"def",
"store",
"(",
"hdu",
",",
"dbase",
"=",
"'cfeps'",
",",
"duser",
"=",
"'cfhls'",
",",
"dtype",
"=",
"'MYSQL'",
",",
"table",
"=",
"'source'",
")",
":",
"import",
"MOPdbaccess",
"db",
"=",
"MOPdbaccess",
".",
"connect",
"(",
"dbase",
",",
"duser"... | 33.784314 | 0.026509 |
def date_time_this_century(
self,
before_now=True,
after_now=False,
tzinfo=None):
"""
Gets a DateTime object for the current century.
:param before_now: include days in current century before today
:param after_now: include days in current... | [
"def",
"date_time_this_century",
"(",
"self",
",",
"before_now",
"=",
"True",
",",
"after_now",
"=",
"False",
",",
"tzinfo",
"=",
"None",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
"tzinfo",
")",
"this_century_start",
"=",
"datetime",
"(",
"now",
... | 39.896552 | 0.003376 |
def merkle(hashes, hash_f=double_sha256):
"""Take a list of hashes, and return the root merkle hash."""
while len(hashes) > 1:
hashes = merkle_pair(hashes, hash_f)
return hashes[0] | [
"def",
"merkle",
"(",
"hashes",
",",
"hash_f",
"=",
"double_sha256",
")",
":",
"while",
"len",
"(",
"hashes",
")",
">",
"1",
":",
"hashes",
"=",
"merkle_pair",
"(",
"hashes",
",",
"hash_f",
")",
"return",
"hashes",
"[",
"0",
"]"
] | 39.2 | 0.005 |
def html(self) -> str:
"""Get whole html representation of this node."""
if self._inner_element:
return self.start_tag + self._inner_element.html + self.end_tag
return super().html | [
"def",
"html",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"_inner_element",
":",
"return",
"self",
".",
"start_tag",
"+",
"self",
".",
"_inner_element",
".",
"html",
"+",
"self",
".",
"end_tag",
"return",
"super",
"(",
")",
".",
"html"
] | 42.4 | 0.009259 |
def calc_qar_v1(self):
"""Calculate the discharge responses of the different AR processes.
Required derived parameters:
|Nmb|
|AR_Order|
|AR_Coefs|
Required log sequence:
|LogOut|
Calculated flux sequence:
|QAR|
Examples:
Assume there are four response func... | [
"def",
"calc_qar_v1",
"(",
"self",
")",
":",
"der",
"=",
"self",
".",
"parameters",
".",
"derived",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"log",
"=",
"self",
".",
"sequences",
".",
"logs",
".",
"fast... | 33 | 0.000467 |
def ensure_unicode_string(obj):
"""
Return a unicode string representation of the given obj.
:param obj:
The obj we want to represent in unicode
:type obj:
varies
:rtype:
`unicode`
"""
try:
return unicode_type(obj)
except UnicodeDecodeError:
if ha... | [
"def",
"ensure_unicode_string",
"(",
"obj",
")",
":",
"try",
":",
"return",
"unicode_type",
"(",
"obj",
")",
"except",
"UnicodeDecodeError",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'decode'",
")",
":",
"return",
"obj",
".",
"decode",
"(",
"'utf-8'",
",",
... | 25.058824 | 0.002262 |
def connect(self, sid, namespace):
"""Register a client connection to a namespace."""
self.enter_room(sid, namespace, None)
self.enter_room(sid, namespace, sid) | [
"def",
"connect",
"(",
"self",
",",
"sid",
",",
"namespace",
")",
":",
"self",
".",
"enter_room",
"(",
"sid",
",",
"namespace",
",",
"None",
")",
"self",
".",
"enter_room",
"(",
"sid",
",",
"namespace",
",",
"sid",
")"
] | 45.25 | 0.01087 |
def modify_member(row, key, value):
''' properly modifies a dict or class attribute '''
(target, tkey, tvalue) = dict_crawl(row, key)
if target:
target[tkey] = value
return row | [
"def",
"modify_member",
"(",
"row",
",",
"key",
",",
"value",
")",
":",
"(",
"target",
",",
"tkey",
",",
"tvalue",
")",
"=",
"dict_crawl",
"(",
"row",
",",
"key",
")",
"if",
"target",
":",
"target",
"[",
"tkey",
"]",
"=",
"value",
"return",
"row"
] | 32.5 | 0.005 |
def update_summary(self, w):
"""Update summary.
The new summary is a weighted average of reviews i.e.
.. math::
\\frac{\\sum_{r \\in R} \\mbox{weight}(r) \\times \\mbox{review}(r)}
{\\sum_{r \\in R} \\mbox{weight}(r)},
where :math:`R` is a set of reviewers... | [
"def",
"update_summary",
"(",
"self",
",",
"w",
")",
":",
"old",
"=",
"self",
".",
"summary",
".",
"v",
"# pylint: disable=no-member",
"reviewers",
"=",
"self",
".",
"_graph",
".",
"retrieve_reviewers",
"(",
"self",
")",
"reviews",
"=",
"[",
"self",
".",
... | 34.225806 | 0.00275 |
def start_app_and_connect(self):
"""Overrides superclass."""
# Check that sl4a is installed
out = self._adb.shell('pm list package')
if not utils.grep('com.googlecode.android_scripting', out):
raise jsonrpc_client_base.AppStartError(
self._ad, '%s is not insta... | [
"def",
"start_app_and_connect",
"(",
"self",
")",
":",
"# Check that sl4a is installed",
"out",
"=",
"self",
".",
"_adb",
".",
"shell",
"(",
"'pm list package'",
")",
"if",
"not",
"utils",
".",
"grep",
"(",
"'com.googlecode.android_scripting'",
",",
"out",
")",
... | 43.777778 | 0.001656 |
def auto_argparser(description=None):
"""Generate argparser from config file automatically (experimental)
"""
partial_parser = ArgumentParser(description=description)
partial_parser.add_argument('config', help='config file path')
cfg_file = partial_parser.parse_known_args()[0].co... | [
"def",
"auto_argparser",
"(",
"description",
"=",
"None",
")",
":",
"partial_parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"description",
")",
"partial_parser",
".",
"add_argument",
"(",
"'config'",
",",
"help",
"=",
"'config file path'",
")",
"cfg_file... | 48.363636 | 0.00369 |
def addModel(D, models):
"""
Insert model data into a LiPD dataset
Examples of model naming:
chron0model0
chron0model1
chron1model0
Example of 'models' variable:
{
chron0model0: {
"method": {...},
"summaryTable": [...],
... | [
"def",
"addModel",
"(",
"D",
",",
"models",
")",
":",
"try",
":",
"# Loop for each model that needs to be added",
"for",
"_model_name",
",",
"_model_data",
"in",
"models",
".",
"items",
"(",
")",
":",
"# split the table name into a path that we can use",
"_m",
"=",
... | 32.866667 | 0.00197 |
def add_environment_information(meta):
"""Record environment information."""
meta["timestamp"] = datetime.utcnow().isoformat(" ")
meta["platform"] = platform.system()
meta["release"] = platform.release()
meta["python"] = platform.python_version()
meta["packages"] = get_pk... | [
"def",
"add_environment_information",
"(",
"meta",
")",
":",
"meta",
"[",
"\"timestamp\"",
"]",
"=",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
"\" \"",
")",
"meta",
"[",
"\"platform\"",
"]",
"=",
"platform",
".",
"system",
"(",
")",
"me... | 47.142857 | 0.005952 |
def to_dict(self, delimiter=DEFAULT_DELIMITER, dict_type=collections.OrderedDict):
""" Get the dictionary representation of the current parser.
:param str delimiter: The delimiter used for nested dictionaries,
defaults to ":", optional
:param class dict_type: The dictionary type to ... | [
"def",
"to_dict",
"(",
"self",
",",
"delimiter",
"=",
"DEFAULT_DELIMITER",
",",
"dict_type",
"=",
"collections",
".",
"OrderedDict",
")",
":",
"root_key",
"=",
"self",
".",
"sections",
"(",
")",
"[",
"0",
"]",
"return",
"self",
".",
"_build_dict",
"(",
"... | 45.6 | 0.005731 |
def enter(self):
"""Send a StartRequest."""
self._communication.send(StartRequest,
self._communication.left_end_needle,
self._communication.right_end_needle) | [
"def",
"enter",
"(",
"self",
")",
":",
"self",
".",
"_communication",
".",
"send",
"(",
"StartRequest",
",",
"self",
".",
"_communication",
".",
"left_end_needle",
",",
"self",
".",
"_communication",
".",
"right_end_needle",
")"
] | 47 | 0.008368 |
def update_ssl_termination(self, loadbalancer, securePort=None, enabled=None,
secureTrafficOnly=None):
"""
Updates existing SSL termination information for the load balancer
without affecting the existing certificates/keys.
"""
return loadbalancer.update_ssl_terminati... | [
"def",
"update_ssl_termination",
"(",
"self",
",",
"loadbalancer",
",",
"securePort",
"=",
"None",
",",
"enabled",
"=",
"None",
",",
"secureTrafficOnly",
"=",
"None",
")",
":",
"return",
"loadbalancer",
".",
"update_ssl_termination",
"(",
"securePort",
"=",
"sec... | 51 | 0.009639 |
def line_oriented(cls, line_oriented_options, console):
"""Given Goal.Options and a Console, yields functions for writing to stdout and stderr, respectively.
The passed options instance will generally be the `Goal.Options` of a `LineOriented` `Goal`.
"""
if type(line_oriented_options) != cls.Options:
... | [
"def",
"line_oriented",
"(",
"cls",
",",
"line_oriented_options",
",",
"console",
")",
":",
"if",
"type",
"(",
"line_oriented_options",
")",
"!=",
"cls",
".",
"Options",
":",
"raise",
"AssertionError",
"(",
"'Expected Options for `{}`, got: {}'",
".",
"format",
"(... | 36.692308 | 0.015322 |
def get_auth_token(self, user_payload):
"""
Extracts token from the `user_payload`
"""
token = user_payload.get('token') or None
if not token:
raise ValueError('`user_payload` must provide api token')
return '{auth_header_prefix} {token}'.format(
... | [
"def",
"get_auth_token",
"(",
"self",
",",
"user_payload",
")",
":",
"token",
"=",
"user_payload",
".",
"get",
"(",
"'token'",
")",
"or",
"None",
"if",
"not",
"token",
":",
"raise",
"ValueError",
"(",
"'`user_payload` must provide api token'",
")",
"return",
"... | 36.7 | 0.005319 |
def plot_iso(axis, step, var):
"""Plot isocontours of scalar field.
Args:
axis (:class:`matplotlib.axes.Axes`): the axis handler of an
existing matplotlib figure where the isocontours should
be plotted.
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
... | [
"def",
"plot_iso",
"(",
"axis",
",",
"step",
",",
"var",
")",
":",
"xmesh",
",",
"ymesh",
",",
"fld",
"=",
"get_meshes_fld",
"(",
"step",
",",
"var",
")",
"if",
"conf",
".",
"field",
".",
"shift",
":",
"fld",
"=",
"np",
".",
"roll",
"(",
"fld",
... | 36.8 | 0.001767 |
def _select_sql(self, **kwargs):
"""
Overridden function to generate the SELECT part of the SQL statement,
with the addition of the a modifier if present.
"""
return 'SELECT {distinct}{modifier}{select}'.format(
distinct='DISTINCT ' if self._distinct else '',
... | [
"def",
"_select_sql",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"'SELECT {distinct}{modifier}{select}'",
".",
"format",
"(",
"distinct",
"=",
"'DISTINCT '",
"if",
"self",
".",
"_distinct",
"else",
"''",
",",
"modifier",
"=",
"'{} '",
".",
"fo... | 49.727273 | 0.007181 |
def _reaction_cartesion_expansion_unqualified_helper(
graph: BELGraph,
u: BaseEntity,
v: BaseEntity,
d: dict,
) -> None:
"""Helper to deal with cartension expansion in unqualified edges."""
if isinstance(u, Reaction) and isinstance(v, Reaction):
enzymes = _get_catalysts_i... | [
"def",
"_reaction_cartesion_expansion_unqualified_helper",
"(",
"graph",
":",
"BELGraph",
",",
"u",
":",
"BaseEntity",
",",
"v",
":",
"BaseEntity",
",",
"d",
":",
"dict",
",",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"u",
",",
"Reaction",
")",
"and... | 34.073529 | 0.001258 |
def build(tasks, worker_scheduler_factory=None, detailed_summary=False, **env_params):
"""
Run internally, bypassing the cmdline parsing.
Useful if you have some luigi code that you want to run internally.
Example:
.. code-block:: python
luigi.build([MyTask1(), MyTask2()], local_scheduler... | [
"def",
"build",
"(",
"tasks",
",",
"worker_scheduler_factory",
"=",
"None",
",",
"detailed_summary",
"=",
"False",
",",
"*",
"*",
"env_params",
")",
":",
"if",
"\"no_lock\"",
"not",
"in",
"env_params",
":",
"env_params",
"[",
"\"no_lock\"",
"]",
"=",
"True",... | 36.16 | 0.00431 |
def _update_known_atts(self, **kwargs):
"""Updates instance attributes with supplied keyword arguments.
"""
for k, v in kwargs.items():
if k not in ATTR_KEYS:
# Warn if passed in unknown kwargs
raise SyntaxWarning('Unknown argument: {}'.format(k))
... | [
"def",
"_update_known_atts",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"ATTR_KEYS",
":",
"# Warn if passed in unknown kwargs",
"raise",
"SyntaxWarning",
"(",
... | 41.363636 | 0.006452 |
def plot_neuron_on_density(population, # pylint: disable=too-many-arguments
bins=100, new_fig=True, subplot=111, levels=None, plane='xy',
colorlabel='Nodes per unit area', labelfontsize=16,
color_map='Reds', no_colorbar=False, threshold=0.... | [
"def",
"plot_neuron_on_density",
"(",
"population",
",",
"# pylint: disable=too-many-arguments",
"bins",
"=",
"100",
",",
"new_fig",
"=",
"True",
",",
"subplot",
"=",
"111",
",",
"levels",
"=",
"None",
",",
"plane",
"=",
"'xy'",
",",
"colorlabel",
"=",
"'Nodes... | 58.529412 | 0.005935 |
def get_checksum32(oqparam, hazard=False):
"""
Build an unsigned 32 bit integer from the input files of a calculation.
:param oqparam: an OqParam instance
:param hazard: if True, consider only the hazard files
:returns: the checkume
"""
# NB: using adler32 & 0xffffffff is the documented way... | [
"def",
"get_checksum32",
"(",
"oqparam",
",",
"hazard",
"=",
"False",
")",
":",
"# NB: using adler32 & 0xffffffff is the documented way to get a checksum",
"# which is the same between Python 2 and Python 3",
"checksum",
"=",
"0",
"for",
"fname",
"in",
"get_input_files",
"(",
... | 46.607143 | 0.000751 |
def _get(self):
"""get and parse data stored in self.path."""
data, stat = self.zk.get(self.path)
if not len(data):
return {}, stat.version
if self.OLD_SEPARATOR in data:
return self._get_old()
return json.loads(data), stat.version | [
"def",
"_get",
"(",
"self",
")",
":",
"data",
",",
"stat",
"=",
"self",
".",
"zk",
".",
"get",
"(",
"self",
".",
"path",
")",
"if",
"not",
"len",
"(",
"data",
")",
":",
"return",
"{",
"}",
",",
"stat",
".",
"version",
"if",
"self",
".",
"OLD_... | 32 | 0.006757 |
def create_configuration(name='Base'):
"""Create a configuration base class
It is built using :class:`ConfigurationMeta`. Subclassing such a base class
will register exposed methods
.. class:: Base
.. attribute:: configuration
Configuration dict that can be used by a Router or th... | [
"def",
"create_configuration",
"(",
"name",
"=",
"'Base'",
")",
":",
"@",
"classmethod",
"def",
"register",
"(",
"cls",
",",
"element",
",",
"action",
",",
"method",
")",
":",
"if",
"not",
"action",
"in",
"cls",
".",
"configuration",
":",
"cls",
".",
"... | 37.7 | 0.00431 |
def add_jenkins_job_options(parser):
"""Add a new job to Jenkins for updating chef-repo
:rtype: argparse.ArgumentParser
"""
cookbook = parser.add_parser('jenkins', help='Add a new cookbook job to '
'Jenkins')
cookbook.add_argument('jenkins', action=... | [
"def",
"add_jenkins_job_options",
"(",
"parser",
")",
":",
"cookbook",
"=",
"parser",
".",
"add_parser",
"(",
"'jenkins'",
",",
"help",
"=",
"'Add a new cookbook job to '",
"'Jenkins'",
")",
"cookbook",
".",
"add_argument",
"(",
"'jenkins'",
",",
"action",
"=",
... | 47 | 0.000772 |
def initialize_hashes(self):
"""Create new hashlib objects for each hash we are going to calculate."""
if ('md5' in self.hashes):
self.md5_calc = hashlib.md5()
if ('sha-1' in self.hashes):
self.sha1_calc = hashlib.sha1()
if ('sha-256' in self.hashes):
... | [
"def",
"initialize_hashes",
"(",
"self",
")",
":",
"if",
"(",
"'md5'",
"in",
"self",
".",
"hashes",
")",
":",
"self",
".",
"md5_calc",
"=",
"hashlib",
".",
"md5",
"(",
")",
"if",
"(",
"'sha-1'",
"in",
"self",
".",
"hashes",
")",
":",
"self",
".",
... | 43.5 | 0.008451 |
def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_low_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 3)
self.transmit_error_counter = data[0]
self.receive_error_counte... | [
"def",
"populate",
"(",
"self",
",",
"priority",
",",
"address",
",",
"rtr",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"self",
".",
"needs_low_priority",
"(",
"priority",
")",
"self",
".",
"needs_no_rtr",
"(",
"rtr",
... | 32.727273 | 0.005405 |
def username(proxy=None):
'''
Return the username.
.. versionadded:: 2017.7.0
CLI Example - select all devices using `foobar` as username for connection:
.. code-block:: bash
salt -G 'username:foobar' test.ping
Output:
.. code-block::yaml
device1:
True
... | [
"def",
"username",
"(",
"proxy",
"=",
"None",
")",
":",
"if",
"proxy",
"and",
"salt",
".",
"utils",
".",
"napalm",
".",
"is_proxy",
"(",
"__opts__",
")",
":",
"# only if proxy will override the username",
"# otherwise will use the default Salt grains",
"return",
"{"... | 22.56 | 0.001701 |
def save_html_with_metadata(fig, filename, fig_kwds, kwds):
""" Save a html output to file with metadata """
if isinstance(fig, str):
text = fig
else:
from mpld3 import fig_to_html
text = fig_to_html(fig, **fig_kwds)
f = open(filename, 'w')
for key, value in kwds.items():
... | [
"def",
"save_html_with_metadata",
"(",
"fig",
",",
"filename",
",",
"fig_kwds",
",",
"kwds",
")",
":",
"if",
"isinstance",
"(",
"fig",
",",
"str",
")",
":",
"text",
"=",
"fig",
"else",
":",
"from",
"mpld3",
"import",
"fig_to_html",
"text",
"=",
"fig_to_h... | 31.866667 | 0.004065 |
def fromordinal(cls, ordinal):
"""Return the week corresponding to the proleptic Gregorian ordinal,
where January 1 of year 1 starts the week with ordinal 1.
"""
if ordinal < 1:
raise ValueError("ordinal must be >= 1")
return super(Week, cls).__new__(cls, *(date.fromo... | [
"def",
"fromordinal",
"(",
"cls",
",",
"ordinal",
")",
":",
"if",
"ordinal",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"ordinal must be >= 1\"",
")",
"return",
"super",
"(",
"Week",
",",
"cls",
")",
".",
"__new__",
"(",
"cls",
",",
"*",
"(",
"date",... | 51.571429 | 0.008174 |
def write_grid_tpl(self,name,tpl_file,zn_array):
""" write a template file a for grid-based multiplier parameters
Parameters
----------
name : str
the base parameter name
tpl_file : str
the template file to write
zn_array : numpy.ndarray
... | [
"def",
"write_grid_tpl",
"(",
"self",
",",
"name",
",",
"tpl_file",
",",
"zn_array",
")",
":",
"parnme",
",",
"x",
",",
"y",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"... | 38 | 0.01796 |
def get_outcome_for_state_name(self, name):
""" Returns the final outcome of the child state specified by name.
Note: This is utility function that is used by the programmer to make a decision based on the final outcome
of its child states. A state is not uniquely specified by the name, but as ... | [
"def",
"get_outcome_for_state_name",
"(",
"self",
",",
"name",
")",
":",
"return_value",
"=",
"None",
"for",
"state_id",
",",
"name_outcome_tuple",
"in",
"self",
".",
"final_outcomes_dict",
".",
"items",
"(",
")",
":",
"if",
"name_outcome_tuple",
"[",
"0",
"]"... | 48.25 | 0.005083 |
def _create_skt(self):
'''
Create the authentication socket.
'''
log.debug('Creating the auth socket')
if ':' in self.auth_address:
self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
self.socket = socket.socket(socket.AF_INET, s... | [
"def",
"_create_skt",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"'Creating the auth socket'",
")",
"if",
"':'",
"in",
"self",
".",
"auth_address",
":",
"self",
".",
"socket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET6",
",",
"sock... | 43.666667 | 0.004484 |
def most_common(self, n=None):
'''List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
'''
# Emulate Bag.sortedByCoun... | [
"def",
"most_common",
"(",
"self",
",",
"n",
"=",
"None",
")",
":",
"# Emulate Bag.sortedByCount from Smalltalk",
"if",
"n",
"is",
"None",
":",
"return",
"sorted",
"(",
"self",
".",
"items",
"(",
")",
",",
"key",
"=",
"_itemgetter",
"(",
"1",
")",
",",
... | 40.75 | 0.004 |
def block_view(arr, block=(3, 3)):
"""Provide a 2D block view to 2D array.
No error checking made. Therefore meaningful (as implemented) only for
blocks strictly compatible with the shape of A.
"""
# simple shape and strides computations may seem at first strange
# unless one is able to recog... | [
"def",
"block_view",
"(",
"arr",
",",
"block",
"=",
"(",
"3",
",",
"3",
")",
")",
":",
"# simple shape and strides computations may seem at first strange",
"# unless one is able to recognize the 'tuple additions' involved ;-)",
"shape",
"=",
"(",
"arr",
".",
"shape",
"[",... | 42.538462 | 0.00354 |
def patch_namespaced_limit_range(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_limit_range # noqa: E501
partially update the specified LimitRange # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, ple... | [
"def",
"patch_namespaced_limit_range",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")... | 61.36 | 0.001284 |
def compute_node_sizes(self):
"""Compute the node sizes."""
if type(self.node_size) is str:
nodes = self.graph.nodes
self.node_sizes = [nodes[n][self.node_size] for n in self.nodes]
else:
self.node_sizes = self.node_size | [
"def",
"compute_node_sizes",
"(",
"self",
")",
":",
"if",
"type",
"(",
"self",
".",
"node_size",
")",
"is",
"str",
":",
"nodes",
"=",
"self",
".",
"graph",
".",
"nodes",
"self",
".",
"node_sizes",
"=",
"[",
"nodes",
"[",
"n",
"]",
"[",
"self",
".",... | 39.142857 | 0.007143 |
def residue_distances(res_1_num, res_1_chain, res_2_num, res_2_chain, model):
"""Distance between the last atom of 2 residues"""
res1 = model[res_1_chain][res_1_num].child_list[-1]
res2 = model[res_2_chain][res_2_num].child_list[-1]
distance = res1 - res2
return distance | [
"def",
"residue_distances",
"(",
"res_1_num",
",",
"res_1_chain",
",",
"res_2_num",
",",
"res_2_chain",
",",
"model",
")",
":",
"res1",
"=",
"model",
"[",
"res_1_chain",
"]",
"[",
"res_1_num",
"]",
".",
"child_list",
"[",
"-",
"1",
"]",
"res2",
"=",
"mod... | 35.75 | 0.003413 |
def slice_cardinal(self, key):
"""
Slice the container according to its (primary) cardinal axis.
The "cardinal" axis can have any name so long as the name matches a
data object attached to the container. The index name for this object
should also match the value of the cardinal ... | [
"def",
"slice_cardinal",
"(",
"self",
",",
"key",
")",
":",
"if",
"self",
".",
"_cardinal",
":",
"cls",
"=",
"self",
".",
"__class__",
"key",
"=",
"check_key",
"(",
"self",
"[",
"self",
".",
"_cardinal",
"]",
",",
"key",
",",
"cardinal",
"=",
"True",... | 50.213115 | 0.004163 |
def check(code):
"""Checks code for obvious errors."""
def safe_lookup(op):
try:
return instructions.lookup(op)
except Exception:
return op
for i, a in enumerate(code):
b = code[i+1] if i+1 < len(code) else None
# Does instruction exist?
if n... | [
"def",
"check",
"(",
"code",
")",
":",
"def",
"safe_lookup",
"(",
"op",
")",
":",
"try",
":",
"return",
"instructions",
".",
"lookup",
"(",
"op",
")",
"except",
"Exception",
":",
"return",
"op",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"code",
... | 34.27027 | 0.005368 |
def generate_rest_view(config, model_cls, attrs=None, es_based=True,
attr_view=False, singular=False):
""" Generate REST view for a model class.
:param model_cls: Generated DB model class.
:param attr: List of strings that represent names of view methods, new
generated view s... | [
"def",
"generate_rest_view",
"(",
"config",
",",
"model_cls",
",",
"attrs",
"=",
"None",
",",
"es_based",
"=",
"True",
",",
"attr_view",
"=",
"False",
",",
"singular",
"=",
"False",
")",
":",
"valid_attrs",
"=",
"(",
"list",
"(",
"collection_methods",
".",... | 37.844444 | 0.000572 |
def convert_formula_to_atomic_fractions(formula):
"""
Converts a chemical formula to an atomic fraction :class:`dict`.
Args:
formula (str): chemical formula, like Al2O3. No wildcard are accepted.
"""
mole_fractions = {}
total_mole_fraction = 0.0
for match in CHEMICAL_FORMULA_PATTER... | [
"def",
"convert_formula_to_atomic_fractions",
"(",
"formula",
")",
":",
"mole_fractions",
"=",
"{",
"}",
"total_mole_fraction",
"=",
"0.0",
"for",
"match",
"in",
"CHEMICAL_FORMULA_PATTERN",
".",
"finditer",
"(",
"formula",
")",
":",
"symbol",
",",
"mole_fraction",
... | 29.896552 | 0.001117 |
def copy_to_temp(object):
"""
Copy file-like object to temp file and return
path.
"""
temp_file = NamedTemporaryFile(delete=False)
_copy_and_close(object, temp_file)
return temp_file.name | [
"def",
"copy_to_temp",
"(",
"object",
")",
":",
"temp_file",
"=",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
")",
"_copy_and_close",
"(",
"object",
",",
"temp_file",
")",
"return",
"temp_file",
".",
"name"
] | 26 | 0.004651 |
def send(self, cmd, timeout, wait_for_string, password):
"""Send command to the target device."""
return self.target_device.send(cmd, timeout=timeout, wait_for_string=wait_for_string, password=password) | [
"def",
"send",
"(",
"self",
",",
"cmd",
",",
"timeout",
",",
"wait_for_string",
",",
"password",
")",
":",
"return",
"self",
".",
"target_device",
".",
"send",
"(",
"cmd",
",",
"timeout",
"=",
"timeout",
",",
"wait_for_string",
"=",
"wait_for_string",
",",... | 72 | 0.013761 |
async def wind_type_classe(self):
"""Retrieve translation for wind type."""
data = await self.retrieve(url=API_WIND_TYPE)
self.wind_type = dict()
for _type in data['data']:
self.wind_type[int(_type['classWindSpeed'])] = _type['descClassWindSpeedDailyPT']
return se... | [
"async",
"def",
"wind_type_classe",
"(",
"self",
")",
":",
"data",
"=",
"await",
"self",
".",
"retrieve",
"(",
"url",
"=",
"API_WIND_TYPE",
")",
"self",
".",
"wind_type",
"=",
"dict",
"(",
")",
"for",
"_type",
"in",
"data",
"[",
"'data'",
"]",
":",
"... | 29.272727 | 0.009036 |
def get_document_field_display(self, field_name, field):
""" Render a link to a document """
document = getattr(self.instance, field_name)
if document:
return mark_safe(
'<a href="%s">%s <span class="meta">(%s, %s)</span></a>' % (
document.url,
... | [
"def",
"get_document_field_display",
"(",
"self",
",",
"field_name",
",",
"field",
")",
":",
"document",
"=",
"getattr",
"(",
"self",
".",
"instance",
",",
"field_name",
")",
"if",
"document",
":",
"return",
"mark_safe",
"(",
"'<a href=\"%s\">%s <span class=\"meta... | 41.461538 | 0.00363 |
def forwards(self, orm):
"Write your forwards methods here."
for tag in orm['tagging.Tag'].objects.all():
if tag.tagtitle_set.all().count() == 0:
orm['tagging_translated.TagTitle'].objects.create(
trans_name=tag.name, tag=tag, language='en') | [
"def",
"forwards",
"(",
"self",
",",
"orm",
")",
":",
"for",
"tag",
"in",
"orm",
"[",
"'tagging.Tag'",
"]",
".",
"objects",
".",
"all",
"(",
")",
":",
"if",
"tag",
".",
"tagtitle_set",
".",
"all",
"(",
")",
".",
"count",
"(",
")",
"==",
"0",
":... | 50 | 0.006557 |
def set_bg_data(self, bg_data, which_data=None):
"""Set background amplitude and phase data
Parameters
----------
bg_data: 2d ndarray (float or complex), list, QPImage, or `None`
The background data (must be same type as `data`).
If set to `None`, the background ... | [
"def",
"set_bg_data",
"(",
"self",
",",
"bg_data",
",",
"which_data",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"bg_data",
",",
"QPImage",
")",
":",
"if",
"which_data",
"is",
"not",
"None",
":",
"msg",
"=",
"\"`which_data` must not be set if `bg_data` is... | 43.827586 | 0.00154 |
def _create_das_mapping(self):
"""
das_map = {'lookup' : [{params : {'param1' : 'required', 'param2' : 'optional', 'param3' : 'default_value' ...},
url : 'https://cmsweb.cern.ch:8443/dbs/prod/global/DBSReader/acquisitioneras/',
das_map : {'... | [
"def",
"_create_das_mapping",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"_mapfile",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"entry",
"in",
"yaml",
".",
"load_all",
"(",
"f",
")",
":",
"das2dbs_param_map",
"=",
"{",
"}",
"if",
"'lookup'... | 54.75 | 0.010772 |
def get_rightmost_index(byte_index=0, file_starts=[0]):
'''
Retrieve the highest-indexed file that starts at or before byte_index.
'''
i = 1
while i <= len(file_starts):
start = file_starts[-i]
if start <= byte_index:
return len(file_starts) - i
else:
... | [
"def",
"get_rightmost_index",
"(",
"byte_index",
"=",
"0",
",",
"file_starts",
"=",
"[",
"0",
"]",
")",
":",
"i",
"=",
"1",
"while",
"i",
"<=",
"len",
"(",
"file_starts",
")",
":",
"start",
"=",
"file_starts",
"[",
"-",
"i",
"]",
"if",
"start",
"<=... | 27.785714 | 0.002488 |
def drawQuad(self, quad):
"""Draw a Quad.
"""
q = Quad(quad)
return self.drawPolyline([q.ul, q.ll, q.lr, q.ur, q.ul]) | [
"def",
"drawQuad",
"(",
"self",
",",
"quad",
")",
":",
"q",
"=",
"Quad",
"(",
"quad",
")",
"return",
"self",
".",
"drawPolyline",
"(",
"[",
"q",
".",
"ul",
",",
"q",
".",
"ll",
",",
"q",
".",
"lr",
",",
"q",
".",
"ur",
",",
"q",
".",
"ul",
... | 29 | 0.013423 |
def symbol_targets_bottom(x, model_hparams, vocab_size):
"""Bottom transformation for target symbols."""
if (model_hparams.shared_embedding_and_softmax_weights or
model_hparams.get("shared_embedding")):
try:
return _symbol_bottom_simple(
x, model_hparams, vocab_size, "shared", reuse=True)
... | [
"def",
"symbol_targets_bottom",
"(",
"x",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"if",
"(",
"model_hparams",
".",
"shared_embedding_and_softmax_weights",
"or",
"model_hparams",
".",
"get",
"(",
"\"shared_embedding\"",
")",
")",
":",
"try",
":",
"return... | 42.785714 | 0.013072 |
def convert_to_article(request, entry_id):
"""
This method converts a tip entry to an unpublished article
:param entry_id: Tip entry to convert
:return: redirect to the edit page of the converted tip
"""
def get_entry_author(entry):
if not entry.optional_name:
return 'By Anon... | [
"def",
"convert_to_article",
"(",
"request",
",",
"entry_id",
")",
":",
"def",
"get_entry_author",
"(",
"entry",
")",
":",
"if",
"not",
"entry",
".",
"optional_name",
":",
"return",
"'By Anonymous'",
"return",
"'By %s'",
"%",
"entry",
".",
"optional_name",
"en... | 40.033333 | 0.000813 |
def cmd(send, msg, args):
"""Gets words of wisdom
Syntax: {command} (--author <author>|--search <topic>)
Powered by STANDS4, www.stands4.com
"""
uid = args['config']['api']['stands4uid']
token = args['config']['api']['stands4token']
parser = arguments.ArgParser(args['config'])
group = pa... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"uid",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'stands4uid'",
"]",
"token",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'stands4token'",
"]",
"parser"... | 31.591837 | 0.000627 |
def replace_pipe(self, name, component):
"""Replace a component in the pipeline.
name (unicode): Name of the component to replace.
component (callable): Pipeline component.
DOCS: https://spacy.io/api/language#replace_pipe
"""
if name not in self.pipe_names:
... | [
"def",
"replace_pipe",
"(",
"self",
",",
"name",
",",
"component",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"pipe_names",
":",
"raise",
"ValueError",
"(",
"Errors",
".",
"E001",
".",
"format",
"(",
"name",
"=",
"name",
",",
"opts",
"=",
"sel... | 40.909091 | 0.006522 |
def parse_attribute(tokens, is_merc):
""" Parse a token stream from inside an attribute selector.
Enter this function after a left-bracket is found:
http://www.w3.org/TR/CSS2/selector.html#attribute-selectors
"""
#
# Local helper functions
#
def next_scalar(tokens, op):
... | [
"def",
"parse_attribute",
"(",
"tokens",
",",
"is_merc",
")",
":",
"#",
"# Local helper functions",
"#",
"def",
"next_scalar",
"(",
"tokens",
",",
"op",
")",
":",
"\"\"\" Look for a scalar value just after an attribute selector operator.\n \"\"\"",
"while",
"True",
... | 38.931034 | 0.005398 |
def parse_group_address(addr):
"""Parse KNX group addresses and return the address as an integer.
This allows to convert x/x/x and x/x address syntax to a numeric
KNX group address
"""
if addr is None:
raise KNXException("No address given")
res = None
if re.match('[0-9]+$', addr)... | [
"def",
"parse_group_address",
"(",
"addr",
")",
":",
"if",
"addr",
"is",
"None",
":",
"raise",
"KNXException",
"(",
"\"No address given\"",
")",
"res",
"=",
"None",
"if",
"re",
".",
"match",
"(",
"'[0-9]+$'",
",",
"addr",
")",
":",
"res",
"=",
"int",
"... | 26.060606 | 0.001121 |
def __calculate_score(self, index_point, index_cluster):
"""!
@brief Calculates Silhouette score for the specific object defined by index_point.
@param[in] index_point (uint): Index point from input data for which Silhouette score should be calculated.
@param[in] index_cluster (uin... | [
"def",
"__calculate_score",
"(",
"self",
",",
"index_point",
",",
"index_cluster",
")",
":",
"difference",
"=",
"self",
".",
"__calculate_dataset_difference",
"(",
"index_point",
")",
"a_score",
"=",
"self",
".",
"__calculate_within_cluster_score",
"(",
"index_cluster... | 46.3125 | 0.009259 |
def plot_distributions(self, parameters=None, truth=None, extents=None, display=False,
filename=None, chains=None, col_wrap=4, figsize=None, blind=None): # pragma: no cover
""" Plots the 1D parameter distributions for verification purposes.
This plot is more for a sanity or ... | [
"def",
"plot_distributions",
"(",
"self",
",",
"parameters",
"=",
"None",
",",
"truth",
"=",
"None",
",",
"extents",
"=",
"None",
",",
"display",
"=",
"False",
",",
"filename",
"=",
"None",
",",
"chains",
"=",
"None",
",",
"col_wrap",
"=",
"4",
",",
... | 43.321101 | 0.004969 |
def get_gaf_gene_ontology_file(path):
"""Extract the gene ontology file associated with a GO annotation file.
Parameters
----------
path: str
The path name of the GO annotation file.
Returns
-------
str
The URL of the associated gene ontology file.
"""
assert isinst... | [
"def",
"get_gaf_gene_ontology_file",
"(",
"path",
")",
":",
"assert",
"isinstance",
"(",
"path",
",",
"str",
")",
"version",
"=",
"None",
"with",
"misc",
".",
"smart_open_read",
"(",
"path",
",",
"encoding",
"=",
"'UTF-8'",
",",
"try_gzip",
"=",
"True",
")... | 25.291667 | 0.003175 |
def is_modified_field(self, name):
"""
Returns whether a field is modified or not
"""
name = self.get_real_name(name)
if name in self.__modified_data__ or name in self.__deleted_fields__:
return True
try:
return self.get_field_value(name).is_modi... | [
"def",
"is_modified_field",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"self",
".",
"get_real_name",
"(",
"name",
")",
"if",
"name",
"in",
"self",
".",
"__modified_data__",
"or",
"name",
"in",
"self",
".",
"__deleted_fields__",
":",
"return",
"True",... | 28.076923 | 0.005305 |
def intersect_leaderboards(self, destination, keys, aggregate='SUM'):
'''
Intersect leaderboards given by keys with this leaderboard into a named destination leaderboard.
@param destination [String] Destination leaderboard name.
@param keys [Array] Leaderboards to be merged with the cur... | [
"def",
"intersect_leaderboards",
"(",
"self",
",",
"destination",
",",
"keys",
",",
"aggregate",
"=",
"'SUM'",
")",
":",
"keys",
".",
"insert",
"(",
"0",
",",
"self",
".",
"leaderboard_name",
")",
"self",
".",
"redis_connection",
".",
"zinterstore",
"(",
"... | 53.1 | 0.007407 |
def custom_to_radec(phi1,phi2,T=None,degree=False):
"""
NAME:
custom_to_radec
PURPOSE:
rotate a custom set of sky coordinates (phi1, phi2) to (ra, dec)
given the rotation matrix T for (ra, dec) -> (phi1, phi2)
INPUT:
phi1 - custom sky coord
phi2 - custom sky c... | [
"def",
"custom_to_radec",
"(",
"phi1",
",",
"phi2",
",",
"T",
"=",
"None",
",",
"degree",
"=",
"False",
")",
":",
"if",
"T",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Must set T= for custom_to_radec\"",
")",
"return",
"radec_to_custom",
"(",
"phi1",
... | 23.484848 | 0.006196 |
def menuitemenabled(self, window_name, object_name):
"""
Verify a menu item is enabled
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either ful... | [
"def",
"menuitemenabled",
"(",
"self",
",",
"window_name",
",",
"object_name",
")",
":",
"try",
":",
"menu_handle",
"=",
"self",
".",
"_get_menu_handle",
"(",
"window_name",
",",
"object_name",
",",
"False",
")",
"if",
"menu_handle",
".",
"AXEnabled",
":",
"... | 34.045455 | 0.002597 |
def _get_warped_mean(self, mean, std, pred_init=None, deg_gauss_hermite=20):
"""
Calculate the warped mean by using Gauss-Hermite quadrature.
"""
gh_samples, gh_weights = np.polynomial.hermite.hermgauss(deg_gauss_hermite)
gh_samples = gh_samples[:, None]
gh_weights = gh_w... | [
"def",
"_get_warped_mean",
"(",
"self",
",",
"mean",
",",
"std",
",",
"pred_init",
"=",
"None",
",",
"deg_gauss_hermite",
"=",
"20",
")",
":",
"gh_samples",
",",
"gh_weights",
"=",
"np",
".",
"polynomial",
".",
"hermite",
".",
"hermgauss",
"(",
"deg_gauss_... | 52.625 | 0.009346 |
def lowPassFilter(self, threshold):
'''
remove all high frequencies by setting boundary around a quarry in the middle
of the size (2*threshold)^2 to zero
threshold = 0...1
'''
if not threshold:
return
rows, cols = self.img.shape
tx = i... | [
"def",
"lowPassFilter",
"(",
"self",
",",
"threshold",
")",
":",
"if",
"not",
"threshold",
":",
"return",
"rows",
",",
"cols",
"=",
"self",
".",
"img",
".",
"shape",
"tx",
"=",
"int",
"(",
"cols",
"*",
"threshold",
"*",
"0.25",
")",
"ty",
"=",
"int... | 32.368421 | 0.004739 |
def process_input_line(self, line, store_history=True):
"""process the input, capturing stdout"""
#print "input='%s'"%self.input
stdout = sys.stdout
splitter = self.IP.input_splitter
try:
sys.stdout = self.cout
splitter.push(line)
more = splitt... | [
"def",
"process_input_line",
"(",
"self",
",",
"line",
",",
"store_history",
"=",
"True",
")",
":",
"#print \"input='%s'\"%self.input",
"stdout",
"=",
"sys",
".",
"stdout",
"splitter",
"=",
"self",
".",
"IP",
".",
"input_splitter",
"try",
":",
"sys",
".",
"s... | 38.357143 | 0.005455 |
def get_prefix_dir(archive):
"""
Often, all files are in a single directory. If so, they'll all have
the same prefix. Determine any such prefix.
archive is a ZipFile
"""
names = archive.namelist()
shortest_name = sorted(names, key=len)[0]
candidate_prefixes = [
shortest_name[:len... | [
"def",
"get_prefix_dir",
"(",
"archive",
")",
":",
"names",
"=",
"archive",
".",
"namelist",
"(",
")",
"shortest_name",
"=",
"sorted",
"(",
"names",
",",
"key",
"=",
"len",
")",
"[",
"0",
"]",
"candidate_prefixes",
"=",
"[",
"shortest_name",
"[",
":",
... | 31.75 | 0.001912 |
def get_event_public_discount(self, id, discount_id, **data):
"""
GET /events/:id/public_discounts/:discount_id/
Gets a public :format:`discount` by ID as the key ``discount``.
"""
return self.get("/events/{0}/public_discounts/{0}/".format(id,discount_id), data=data) | [
"def",
"get_event_public_discount",
"(",
"self",
",",
"id",
",",
"discount_id",
",",
"*",
"*",
"data",
")",
":",
"return",
"self",
".",
"get",
"(",
"\"/events/{0}/public_discounts/{0}/\"",
".",
"format",
"(",
"id",
",",
"discount_id",
")",
",",
"data",
"=",
... | 44.285714 | 0.015823 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.