text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def old_encode_aes(key, plaintext):
"""
Utility method to encode some given plaintext with the given key. Important thing to note:
This is not a general purpose encryption method - it has specific semantics (see below for
details).
Takes the given key, pads it to 32 bytes. Then takes the given pla... | [
"def",
"old_encode_aes",
"(",
"key",
",",
"plaintext",
")",
":",
"# generate 16 cryptographically secure random bytes for our IV (initial value)",
"iv",
"=",
"os",
".",
"urandom",
"(",
"16",
")",
"# set up an AES cipher object",
"cipher",
"=",
"AES",
".",
"new",
"(",
... | 46.083333 | 26.416667 |
def send_msg_to_webhook(
self,
json_payload,
log_msg
):
"""todo"""
if SILENCE_OVERRIDE:
return
params = {**json_payload, 'message': log_msg}
headers = {'Content-Type': 'application/json'}
try:
req = requests.post(
... | [
"def",
"send_msg_to_webhook",
"(",
"self",
",",
"json_payload",
",",
"log_msg",
")",
":",
"if",
"SILENCE_OVERRIDE",
":",
"return",
"params",
"=",
"{",
"*",
"*",
"json_payload",
",",
"'message'",
":",
"log_msg",
"}",
"headers",
"=",
"{",
"'Content-Type'",
":"... | 27.931034 | 17.310345 |
def diff_flux_threshold(self, skydir, fn, ts_thresh, min_counts):
"""Compute the differential flux threshold for a point source at
position ``skydir`` with spectral parameterization ``fn``.
Parameters
----------
skydir : `~astropy.coordinates.SkyCoord`
Sky coordinate... | [
"def",
"diff_flux_threshold",
"(",
"self",
",",
"skydir",
",",
"fn",
",",
"ts_thresh",
",",
"min_counts",
")",
":",
"sig",
",",
"bkg",
",",
"bkg_fit",
"=",
"self",
".",
"compute_counts",
"(",
"skydir",
",",
"fn",
")",
"norms",
"=",
"irfs",
".",
"comput... | 37.135135 | 21.27027 |
def incr(self, name, amount=1):
"""自增key的对应的值,当key不存在时则为默认值,否则在基础上自增整数amount
:param name: key
:param amount: 默认值
:return: 返回自增后的值
"""
return self.client.incr(name, amount=amount) | [
"def",
"incr",
"(",
"self",
",",
"name",
",",
"amount",
"=",
"1",
")",
":",
"return",
"self",
".",
"client",
".",
"incr",
"(",
"name",
",",
"amount",
"=",
"amount",
")"
] | 31.428571 | 9.571429 |
def _extract_median(image, mask = slice(None), size = 1, voxelspacing = None):
"""
Internal, single-image version of `median`.
"""
# set voxel spacing
if voxelspacing is None:
voxelspacing = [1.] * image.ndim
# determine structure element size in voxel units
size = _create_s... | [
"def",
"_extract_median",
"(",
"image",
",",
"mask",
"=",
"slice",
"(",
"None",
")",
",",
"size",
"=",
"1",
",",
"voxelspacing",
"=",
"None",
")",
":",
"# set voxel spacing",
"if",
"voxelspacing",
"is",
"None",
":",
"voxelspacing",
"=",
"[",
"1.",
"]",
... | 34.833333 | 15.833333 |
def vertex_fingerprints(self):
"""A fingerprint for each vertex
The result is invariant under permutation of the vertex indexes.
Vertices that are symmetrically equivalent will get the same
fingerprint, e.g. the hydrogens in methane would get the same
fingerprint.
... | [
"def",
"vertex_fingerprints",
"(",
"self",
")",
":",
"return",
"self",
".",
"get_vertex_fingerprints",
"(",
"[",
"self",
".",
"get_vertex_string",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"num_vertices",
")",
"]",
",",
"[",
"self",
"."... | 43.166667 | 21.916667 |
def get_fields_dict(self, row):
"""
Returns a dict of field name and cleaned value pairs to initialize the model.
Beware, it aligns the lists of fields and row values with Nones to allow for adding fields not found in the CSV.
Whitespace around the value of the cell is stripped.
... | [
"def",
"get_fields_dict",
"(",
"self",
",",
"row",
")",
":",
"return",
"{",
"k",
":",
"getattr",
"(",
"self",
",",
"'clean_{}'",
".",
"format",
"(",
"k",
")",
",",
"lambda",
"x",
":",
"x",
")",
"(",
"v",
".",
"strip",
"(",
")",
"if",
"isinstance"... | 62.111111 | 30.555556 |
def CheckLibWithHeader(context, libs, header, language,
call = None, autoadd = 1):
# ToDo: accept path for library. Support system header files.
"""
Another (more sophisticated) test for a library.
Checks, if library and header is available for language (may be 'C'
or 'CXX'). ... | [
"def",
"CheckLibWithHeader",
"(",
"context",
",",
"libs",
",",
"header",
",",
"language",
",",
"call",
"=",
"None",
",",
"autoadd",
"=",
"1",
")",
":",
"# ToDo: accept path for library. Support system header files.",
"prog_prefix",
",",
"dummy",
"=",
"createIncludes... | 37.863636 | 19.045455 |
def mean_samples(data, xcol, ycollist):
"""Create a sample list that contains
the mean of the original list.
>>> chart_data.mean_samples([ [1, 10, 15], [2, 5, 10], [3, 8, 33] ], 0, (1, 2))
[(1, 12.5), (2, 7.5), (3, 20.5)]
"""
out = []
numcol = len(ycollist)
try:
for elem in data:
... | [
"def",
"mean_samples",
"(",
"data",
",",
"xcol",
",",
"ycollist",
")",
":",
"out",
"=",
"[",
"]",
"numcol",
"=",
"len",
"(",
"ycollist",
")",
"try",
":",
"for",
"elem",
"in",
"data",
":",
"v",
"=",
"0",
"for",
"col",
"in",
"ycollist",
":",
"v",
... | 29.157895 | 19.368421 |
def add_external_reference_to_entity(self,entity_id, external_ref):
"""
Adds an external reference to the given entity identifier in the entity layer
@type entity_id: string
@param entity_id: the entity identifier
@param external_ref: an external reference object
@type ex... | [
"def",
"add_external_reference_to_entity",
"(",
"self",
",",
"entity_id",
",",
"external_ref",
")",
":",
"if",
"self",
".",
"entity_layer",
"is",
"not",
"None",
":",
"self",
".",
"entity_layer",
".",
"add_external_reference_to_entity",
"(",
"entity_id",
",",
"exte... | 48.5 | 16.1 |
def new_state(self):
"""Generates a state string to be used in authorizations."""
try:
self._state = self.state()
log.debug("Generated new state %s.", self._state)
except TypeError:
self._state = self.state
log.debug("Re-using previously supplied s... | [
"def",
"new_state",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_state",
"=",
"self",
".",
"state",
"(",
")",
"log",
".",
"debug",
"(",
"\"Generated new state %s.\"",
",",
"self",
".",
"_state",
")",
"except",
"TypeError",
":",
"self",
".",
"_stat... | 40.222222 | 15.555556 |
def propose_unif(self):
"""Propose a new live point by sampling *uniformly*
within the unit cube."""
u = self.unitcube.sample(rstate=self.rstate)
ax = np.identity(self.npdim)
return u, ax | [
"def",
"propose_unif",
"(",
"self",
")",
":",
"u",
"=",
"self",
".",
"unitcube",
".",
"sample",
"(",
"rstate",
"=",
"self",
".",
"rstate",
")",
"ax",
"=",
"np",
".",
"identity",
"(",
"self",
".",
"npdim",
")",
"return",
"u",
",",
"ax"
] | 27.75 | 16.625 |
def _predict_forest(model, X, joint_contribution=False):
"""
For a given RandomForestRegressor, RandomForestClassifier,
ExtraTreesRegressor, or ExtraTreesClassifier returns a triple of
[prediction, bias and feature_contributions], such that prediction ≈ bias +
feature_contributions.
"""
bias... | [
"def",
"_predict_forest",
"(",
"model",
",",
"X",
",",
"joint_contribution",
"=",
"False",
")",
":",
"biases",
"=",
"[",
"]",
"contributions",
"=",
"[",
"]",
"predictions",
"=",
"[",
"]",
"if",
"joint_contribution",
":",
"for",
"tree",
"in",
"model",
"."... | 31.901961 | 21.156863 |
def _parse_arguments(self, method, parameters):
"""Parse arguments to method, returning a dictionary."""
# TODO: Consider raising an exception if there are extra arguments.
arguments = _fetch_arguments(self, method)
arg_dict = {}
errors = []
for key, properties in parameters:
if key i... | [
"def",
"_parse_arguments",
"(",
"self",
",",
"method",
",",
"parameters",
")",
":",
"# TODO: Consider raising an exception if there are extra arguments.",
"arguments",
"=",
"_fetch_arguments",
"(",
"self",
",",
"method",
")",
"arg_dict",
"=",
"{",
"}",
"errors",
"=",
... | 33.575758 | 18.545455 |
def cookie_attr_value_check(attr_name, attr_value):
""" Check cookie attribute value for validity. Return True if value is valid
:param attr_name: attribute name to check
:param attr_value: attribute value to check
:return: bool
"""
attr_value.encode('us-ascii')
return WHTTPCookie.cookie_attr_value_compl... | [
"def",
"cookie_attr_value_check",
"(",
"attr_name",
",",
"attr_value",
")",
":",
"attr_value",
".",
"encode",
"(",
"'us-ascii'",
")",
"return",
"WHTTPCookie",
".",
"cookie_attr_value_compliance",
"[",
"attr_name",
"]",
".",
"match",
"(",
"attr_value",
")",
"is",
... | 39.777778 | 15.888889 |
def add_stroke(self, new_stroke):
"""
Update the beam so that it considers `new_stroke`.
When a `new_stroke` comes, it can either belong to a symbol for which
at least one other stroke was already made or belong to a symbol for
which `new_stroke` is the first stroke.
Th... | [
"def",
"add_stroke",
"(",
"self",
",",
"new_stroke",
")",
":",
"global",
"single_clf",
"if",
"len",
"(",
"self",
".",
"hypotheses",
")",
"==",
"0",
":",
"# Don't put this in the constructor!",
"self",
".",
"hypotheses",
"=",
"[",
"{",
"'segmentation'",
":",
... | 37.638095 | 18.704762 |
def register(classname, cls):
"""Add a class to the registry of serializer classes. When a class is
registered, an entry for both its classname and its full, module-qualified
path are added to the registry.
Example: ::
class MyClass:
pass
register('MyClass', MyClass)
... | [
"def",
"register",
"(",
"classname",
",",
"cls",
")",
":",
"# Module where the class is located",
"module",
"=",
"cls",
".",
"__module__",
"# Full module path to the class",
"# e.g. user.schemas.UserSchema",
"fullpath",
"=",
"'.'",
".",
"join",
"(",
"[",
"module",
","... | 32.358974 | 17.384615 |
def _TerminateFlow(rdf_flow,
reason=None,
flow_state=rdf_flow_objects.Flow.FlowState.ERROR):
"""Does the actual termination."""
flow_cls = registry.FlowRegistry.FlowClassByName(rdf_flow.flow_class_name)
flow_obj = flow_cls(rdf_flow)
if not flow_obj.IsRunning():
# Nothi... | [
"def",
"_TerminateFlow",
"(",
"rdf_flow",
",",
"reason",
"=",
"None",
",",
"flow_state",
"=",
"rdf_flow_objects",
".",
"Flow",
".",
"FlowState",
".",
"ERROR",
")",
":",
"flow_cls",
"=",
"registry",
".",
"FlowRegistry",
".",
"FlowClassByName",
"(",
"rdf_flow",
... | 32.481481 | 19.518519 |
def validate_bucket(self):
"""
Do a quick check to see if the s3 bucket is valid
:return:
"""
s3_check_cmd = "aws s3 ls s3://{} --profile '{}' --region '{}'".format(self.bucket_name, self.aws_project,
... | [
"def",
"validate_bucket",
"(",
"self",
")",
":",
"s3_check_cmd",
"=",
"\"aws s3 ls s3://{} --profile '{}' --region '{}'\"",
".",
"format",
"(",
"self",
".",
"bucket_name",
",",
"self",
".",
"aws_project",
",",
"self",
".",
"aws_regions",
"[",
"0",
"]",
")",
"pri... | 47.733333 | 23.066667 |
def tracking_error(self, benchmark, ddof=0):
"""Standard deviation of excess returns.
The standard deviation of the differences between
a portfolio's returns and its benchmark's returns.
[Source: CFA Institute]
Also known as: tracking risk; active risk
Parameters
... | [
"def",
"tracking_error",
"(",
"self",
",",
"benchmark",
",",
"ddof",
"=",
"0",
")",
":",
"er",
"=",
"self",
".",
"excess_ret",
"(",
"benchmark",
"=",
"benchmark",
")",
"return",
"er",
".",
"anlzd_stdev",
"(",
"ddof",
"=",
"ddof",
")"
] | 29.173913 | 19.73913 |
def portfolio_performance(self, verbose=False, risk_free_rate=0.02):
"""
After optimising, calculate (and optionally print) the performance of the optimal
portfolio. Currently calculates expected return, volatility, and the Sharpe ratio.
:param verbose: whether performance should be pri... | [
"def",
"portfolio_performance",
"(",
"self",
",",
"verbose",
"=",
"False",
",",
"risk_free_rate",
"=",
"0.02",
")",
":",
"return",
"base_optimizer",
".",
"portfolio_performance",
"(",
"self",
".",
"expected_returns",
",",
"self",
".",
"cov_matrix",
",",
"self",
... | 43.65 | 20.85 |
def parse(self,
raw_sections=None,
namespaces=True,
strip_comments=True,
strip_whitespaces=True,
strip_quotation_markers=True,
raise_parsing_errors=True):
"""
Process the file content and extracts the sections / attribut... | [
"def",
"parse",
"(",
"self",
",",
"raw_sections",
"=",
"None",
",",
"namespaces",
"=",
"True",
",",
"strip_comments",
"=",
"True",
",",
"strip_whitespaces",
"=",
"True",
",",
"strip_quotation_markers",
"=",
"True",
",",
"raise_parsing_errors",
"=",
"True",
")"... | 49.401575 | 25.968504 |
def allVariantAnnotationSets(self):
"""
Return an iterator over all variant annotation sets
in the data repo
"""
for dataset in self.getDatasets():
for variantSet in dataset.getVariantSets():
for vaSet in variantSet.getVariantAnnotationSets():
... | [
"def",
"allVariantAnnotationSets",
"(",
"self",
")",
":",
"for",
"dataset",
"in",
"self",
".",
"getDatasets",
"(",
")",
":",
"for",
"variantSet",
"in",
"dataset",
".",
"getVariantSets",
"(",
")",
":",
"for",
"vaSet",
"in",
"variantSet",
".",
"getVariantAnnot... | 37.222222 | 10.333333 |
def getFoundIn(self, foundin_name, projectarea_id=None,
projectarea_name=None, archived=False):
"""Get :class:`rtcclient.models.FoundIn` object by its name
:param foundin_name: the foundin name
:param projectarea_id: the :class:`rtcclient.project_area.ProjectArea`
... | [
"def",
"getFoundIn",
"(",
"self",
",",
"foundin_name",
",",
"projectarea_id",
"=",
"None",
",",
"projectarea_name",
"=",
"None",
",",
"archived",
"=",
"False",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Try to get <FoundIn %s>\"",
",",
"foundin_name",... | 43.75 | 20.0625 |
def get_view_nodes_from_indexes(self, *indexes):
"""
Returns the View Nodes from given indexes.
:param view: View.
:type view: QWidget
:param \*indexes: Indexes.
:type \*indexes: list
:return: View nodes.
:rtype: dict
"""
nodes = {}
... | [
"def",
"get_view_nodes_from_indexes",
"(",
"self",
",",
"*",
"indexes",
")",
":",
"nodes",
"=",
"{",
"}",
"model",
"=",
"self",
".",
"model",
"(",
")",
"if",
"not",
"model",
":",
"return",
"nodes",
"if",
"not",
"hasattr",
"(",
"model",
",",
"\"get_node... | 31.78125 | 18.28125 |
def _encode_item(self, item: str) -> str:
"""
If anonymization is on, an item gets salted and hashed here.
:param str item:
:return: Hashed item, if anonymization is on; the unmodified item otherwise
:rtype: str
"""
assert item is not None
if not self.__r... | [
"def",
"_encode_item",
"(",
"self",
",",
"item",
":",
"str",
")",
"->",
"str",
":",
"assert",
"item",
"is",
"not",
"None",
"if",
"not",
"self",
".",
"__redis_conf",
"[",
"'anonymization'",
"]",
":",
"return",
"item",
"connection",
"=",
"self",
".",
"__... | 38.222222 | 15.555556 |
def _connect():
'''
Return server object used to interact with Jenkins.
:return: server object used to interact with Jenkins
'''
jenkins_url = __salt__['config.get']('jenkins.url') or \
__salt__['config.get']('jenkins:url') or \
__salt__['pillar.get']('jenkins.url')
jenkins_use... | [
"def",
"_connect",
"(",
")",
":",
"jenkins_url",
"=",
"__salt__",
"[",
"'config.get'",
"]",
"(",
"'jenkins.url'",
")",
"or",
"__salt__",
"[",
"'config.get'",
"]",
"(",
"'jenkins:url'",
")",
"or",
"__salt__",
"[",
"'pillar.get'",
"]",
"(",
"'jenkins.url'",
")... | 35.458333 | 21.208333 |
def authenticate_unless_readonly(f, self, *args, **kwargs):
"""authenticate this page *unless* readonly view is active.
In read-only mode, the notebook list and print view should
be accessible without authentication.
"""
@web.authenticated
def auth_f(self, *args, **kwargs):
ret... | [
"def",
"authenticate_unless_readonly",
"(",
"f",
",",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"@",
"web",
".",
"authenticated",
"def",
"auth_f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"f",
"... | 31 | 14.466667 |
def update(self):
"""
rebuild the tree view of the history item tree store
:return:
"""
# with self._update_lock:
self._update_lock.acquire()
self._store_expansion_state()
self.history_tree_store.clear()
selected_sm_m = self.model.get_selected_stat... | [
"def",
"update",
"(",
"self",
")",
":",
"# with self._update_lock:",
"self",
".",
"_update_lock",
".",
"acquire",
"(",
")",
"self",
".",
"_store_expansion_state",
"(",
")",
"self",
".",
"history_tree_store",
".",
"clear",
"(",
")",
"selected_sm_m",
"=",
"self"... | 50.282051 | 24.692308 |
def setto(self, s):
""" set j+1...k to string s, readjusting k """
length = len(s)
self.b[self.j+1:self.j+1+length] = s
self.k = self.j + length | [
"def",
"setto",
"(",
"self",
",",
"s",
")",
":",
"length",
"=",
"len",
"(",
"s",
")",
"self",
".",
"b",
"[",
"self",
".",
"j",
"+",
"1",
":",
"self",
".",
"j",
"+",
"1",
"+",
"length",
"]",
"=",
"s",
"self",
".",
"k",
"=",
"self",
".",
... | 34.4 | 10 |
def _get_file_iterator(self, file_obj):
"""
For given `file_obj` return iterator, which will read the file in
`self.read_bs` chunks.
Args:
file_obj (file): File-like object.
Return:
iterator: Iterator reading the file-like object in chunks.
"""
... | [
"def",
"_get_file_iterator",
"(",
"self",
",",
"file_obj",
")",
":",
"file_obj",
".",
"seek",
"(",
"0",
")",
"return",
"iter",
"(",
"lambda",
":",
"file_obj",
".",
"read",
"(",
"self",
".",
"read_bs",
")",
",",
"''",
")"
] | 28 | 20.571429 |
def create(self, id):
""" Create a new tenant id """
resp = self.client.accounts.create(id=id)
self.display(resp) | [
"def",
"create",
"(",
"self",
",",
"id",
")",
":",
"resp",
"=",
"self",
".",
"client",
".",
"accounts",
".",
"create",
"(",
"id",
"=",
"id",
")",
"self",
".",
"display",
"(",
"resp",
")"
] | 33.5 | 10.5 |
def home_url():
"""Get project's home URL based on settings.PROJECT_HOME_NAMESPACE.
Returns None if PROJECT_HOME_NAMESPACE is not defined in settings.
"""
try:
return reverse(home_namespace)
except Exception:
url = home_namespace
try:
validate_url = URLValidator(... | [
"def",
"home_url",
"(",
")",
":",
"try",
":",
"return",
"reverse",
"(",
"home_namespace",
")",
"except",
"Exception",
":",
"url",
"=",
"home_namespace",
"try",
":",
"validate_url",
"=",
"URLValidator",
"(",
")",
"if",
"'://'",
"not",
"in",
"url",
":",
"u... | 28.588235 | 14.941176 |
def _proc_pax(self, tarfile):
"""Process an extended or global header as described in
POSIX.1-2008.
"""
# Read the header information.
buf = tarfile.fileobj.read(self._block(self.size))
# A pax header stores supplemental information for either
# the following ... | [
"def",
"_proc_pax",
"(",
"self",
",",
"tarfile",
")",
":",
"# Read the header information.",
"buf",
"=",
"tarfile",
".",
"fileobj",
".",
"read",
"(",
"self",
".",
"_block",
"(",
"self",
".",
"size",
")",
")",
"# A pax header stores supplemental information for eit... | 42.782178 | 21.039604 |
def get_dependency_element(self, symbol):
"""Checks if the specified symbol is the name of one of the methods
that this module depends on. If it is, search for the actual code
element and return it."""
for depend in self.dependencies:
if "." in depend:
#We kno... | [
"def",
"get_dependency_element",
"(",
"self",
",",
"symbol",
")",
":",
"for",
"depend",
"in",
"self",
".",
"dependencies",
":",
"if",
"\".\"",
"in",
"depend",
":",
"#We know the module name and the executable name, easy",
"if",
"depend",
".",
"split",
"(",
"\".\""... | 45.208333 | 19.291667 |
def upscale(file_name, scale=1.5, margin_x=0, margin_y=0, suffix='scaled', tempdir=None):
"""Upscale a PDF to a large size."""
def adjust(page):
info = PageMerge().add(page)
x1, y1, x2, y2 = info.xobj_box
viewrect = (margin_x, margin_y, x2 - x1 - 2 * margin_x, y2 - y1 - 2 * margin_y)
... | [
"def",
"upscale",
"(",
"file_name",
",",
"scale",
"=",
"1.5",
",",
"margin_x",
"=",
"0",
",",
"margin_y",
"=",
"0",
",",
"suffix",
"=",
"'scaled'",
",",
"tempdir",
"=",
"None",
")",
":",
"def",
"adjust",
"(",
"page",
")",
":",
"info",
"=",
"PageMer... | 38.6 | 21.4 |
def solve(self):
"""
Solve the cross.
"""
result = Formula(path_actions(a_star_search(
({f: self.cube[f] for f in "LUFDRB"},
self.cube.select_type("edge") & self.cube.has_colour(self.cube["D"].colour)),
self.cross_successors,
self.cross... | [
"def",
"solve",
"(",
"self",
")",
":",
"result",
"=",
"Formula",
"(",
"path_actions",
"(",
"a_star_search",
"(",
"(",
"{",
"f",
":",
"self",
".",
"cube",
"[",
"f",
"]",
"for",
"f",
"in",
"\"LUFDRB\"",
"}",
",",
"self",
".",
"cube",
".",
"select_typ... | 32 | 14.769231 |
def find_path_with_profiles(self, conversion_profiles, in_, out):
'''
Like find_path, except forces the conversion profiles to be the given
conversion profile setting. Useful for "temporarily overriding" the
global conversion profiles with your own.
'''
original_profiles ... | [
"def",
"find_path_with_profiles",
"(",
"self",
",",
"conversion_profiles",
",",
"in_",
",",
"out",
")",
":",
"original_profiles",
"=",
"dict",
"(",
"self",
".",
"conversion_profiles",
")",
"self",
".",
"_setup_profiles",
"(",
"conversion_profiles",
")",
"results",... | 46.454545 | 20.272727 |
def get_dimensions(**kwargs):
"""
Returns a list of objects describing all the dimensions with all the units.
"""
dimensions_list = db.DBSession.query(Dimension).options(load_only("id")).all()
return_list = []
for dimension in dimensions_list:
return_list.append(get_dimension(dimensi... | [
"def",
"get_dimensions",
"(",
"*",
"*",
"kwargs",
")",
":",
"dimensions_list",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Dimension",
")",
".",
"options",
"(",
"load_only",
"(",
"\"id\"",
")",
")",
".",
"all",
"(",
")",
"return_list",
"=",
"[",
... | 31.090909 | 21.090909 |
def _generate_anchors(base_size, scales, aspect_ratios):
"""Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, base_size - 1, base_size - 1) window.
"""
anchor = np.array([1, 1, base_size, base_size], dtype=np.float) - 1
anchors = _ratio_enum(anchor, asp... | [
"def",
"_generate_anchors",
"(",
"base_size",
",",
"scales",
",",
"aspect_ratios",
")",
":",
"anchor",
"=",
"np",
".",
"array",
"(",
"[",
"1",
",",
"1",
",",
"base_size",
",",
"base_size",
"]",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"-",
"1",
... | 46.8 | 17.8 |
def update(self):
"""Fetch updated information about devices"""
if self.device_time_check():
if not self.in_process:
outlets, switches, fans = self.get_devices()
self.outlets = helpers.resolve_updates(self.outlets, outlets)
self.switches = h... | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"device_time_check",
"(",
")",
":",
"if",
"not",
"self",
".",
"in_process",
":",
"outlets",
",",
"switches",
",",
"fans",
"=",
"self",
".",
"get_devices",
"(",
")",
"self",
".",
"outlets",
"=... | 35.357143 | 21.857143 |
def _singleton_method(name):
"""Return a function to the `name` method on a singleton `coverage` object.
The singleton object is created the first time one of these functions is
called.
"""
# Disable pylint msg W0612, because a bunch of variables look unused, but
# they're accessed via locals(... | [
"def",
"_singleton_method",
"(",
"name",
")",
":",
"# Disable pylint msg W0612, because a bunch of variables look unused, but",
"# they're accessed via locals().",
"# pylint: disable=W0612",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Singlet... | 31.277778 | 21.055556 |
def unregister(self, plugin=None, plugin_file=None):
"""
Unregister all plugins, or a specific plugin, via an instance, or file (path) containing plugin(s).
When this method is called without any arguments then all plugins will be deactivated.
:param plugin: Plugin to unregister.
... | [
"def",
"unregister",
"(",
"self",
",",
"plugin",
"=",
"None",
",",
"plugin_file",
"=",
"None",
")",
":",
"if",
"plugin",
"is",
"None",
"and",
"plugin_file",
"is",
"None",
":",
"for",
"name",
",",
"plugin",
"in",
"self",
".",
"plugins",
".",
"items",
... | 38.451613 | 18.967742 |
def write_shared_locations(self, paths, dry_run=False):
"""
Write shared location information to the SHARED file in .dist-info.
:param paths: A dictionary as described in the documentation for
:meth:`shared_locations`.
:param dry_run: If True, the action is logged but no file is ... | [
"def",
"write_shared_locations",
"(",
"self",
",",
"paths",
",",
"dry_run",
"=",
"False",
")",
":",
"shared_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"'SHARED'",
")",
"logger",
".",
"info",
"(",
"'creating %s'",
",",
"s... | 41.041667 | 15.375 |
def load(self, **kwargs):
"""Method to list the UCS on the system
Since this is only fixed in 12.1.0 and up
we implemented version check here
"""
# Check if we are using 12.1.0 version or above when using this method
self._is_version_supported_method('12.1.0')
n... | [
"def",
"load",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Check if we are using 12.1.0 version or above when using this method",
"self",
".",
"_is_version_supported_method",
"(",
"'12.1.0'",
")",
"newinst",
"=",
"self",
".",
"_stamp_out_core",
"(",
")",
"newin... | 30.615385 | 16.769231 |
def convert(*args, **kargs):
""" Wrapper around CountryConverter.convert()
Uses the same parameters. This function has the same performance as
CountryConverter.convert for one call; for multiple calls it is better to
instantiate a common CountryConverter (this avoid loading the source data
file mul... | [
"def",
"convert",
"(",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"init",
"=",
"{",
"'country_data'",
":",
"COUNTRY_DATA_FILE",
",",
"'additional_data'",
":",
"None",
",",
"'only_UNmember'",
":",
"False",
",",
"'include_obsolete'",
":",
"False",
"}",
"... | 37.177419 | 23.887097 |
def make_dataset_header(data, file_format, aminoacids):
"""Creates the dataset header for NEXUS files from ``#NEXUS`` to ``MATRIX``.
Parameters:
data (namedtuple): with necessary info for dataset creation.
file_format (str): TNT, PHYLIP, NEXUS, FASTA
aminoacids (boolean): If ``ami... | [
"def",
"make_dataset_header",
"(",
"data",
",",
"file_format",
",",
"aminoacids",
")",
":",
"if",
"aminoacids",
":",
"datatype",
"=",
"'PROTEIN'",
"else",
":",
"datatype",
"=",
"'DNA'",
"if",
"file_format",
"in",
"[",
"'NEXUS'",
",",
"'PHYLIP'",
",",
"'FASTA... | 28.315789 | 20.184211 |
def a2bits(chars: str) -> str:
"""Converts a string to its bits representation as a string of 0's and 1's.
>>> a2bits("Hello World!")
'010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001'
"""
return bin(reduce(lambda x, y: (x << 8) + y, (ord(c) for c in ... | [
"def",
"a2bits",
"(",
"chars",
":",
"str",
")",
"->",
"str",
":",
"return",
"bin",
"(",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"(",
"x",
"<<",
"8",
")",
"+",
"y",
",",
"(",
"ord",
"(",
"c",
")",
"for",
"c",
"in",
"chars",
")",
",",
... | 37.888889 | 25 |
def get_trace(
self,
project_id,
trace_id,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets a single trace by its ID.
Example:
>>> from google.cloud import t... | [
"def",
"get_trace",
"(",
"self",
",",
"project_id",
",",
"trace_id",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAU... | 40.114754 | 22.737705 |
def launch_instance(instance_name,
command,
existing_ip=None,
cpu=1,
mem=4,
code_dir=None,
setup_command=None):
"""Launch a GCE instance."""
# Create instance
ip = existing_ip or create_instance... | [
"def",
"launch_instance",
"(",
"instance_name",
",",
"command",
",",
"existing_ip",
"=",
"None",
",",
"cpu",
"=",
"1",
",",
"mem",
"=",
"4",
",",
"code_dir",
"=",
"None",
",",
"setup_command",
"=",
"None",
")",
":",
"# Create instance",
"ip",
"=",
"exist... | 32.5 | 18.642857 |
def get_outputs(self, out, max_plugins_output_length):
"""Get check outputs from single output (split perfdata etc).
Updates output, perf_data and long_output attributes.
:param out: output data of a check
:type out: str
:param max_output: max plugin data length
:type m... | [
"def",
"get_outputs",
"(",
"self",
",",
"out",
",",
"max_plugins_output_length",
")",
":",
"# Squeeze all output after max_plugins_output_length",
"out",
"=",
"out",
"[",
":",
"max_plugins_output_length",
"]",
"# manage escaped pipes",
"out",
"=",
"out",
".",
"replace",... | 42.333333 | 21.144928 |
def get_component_id_list(self, system_id):
'''get list of component IDs with parameters for a given system ID'''
ret = []
for (s,c) in self.mpstate.mav_param_by_sysid.keys():
if s == system_id:
ret.append(c)
return ret | [
"def",
"get_component_id_list",
"(",
"self",
",",
"system_id",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"(",
"s",
",",
"c",
")",
"in",
"self",
".",
"mpstate",
".",
"mav_param_by_sysid",
".",
"keys",
"(",
")",
":",
"if",
"s",
"==",
"system_id",
":",
"... | 39 | 18.142857 |
def _and_join(self, close_group=False):
"""Combine terms with AND.
There must be a term added before using this method.
Arguments:
close_group (bool): If ``True``, will end the current group and start a new one.
If ``False``, will continue current group.
... | [
"def",
"_and_join",
"(",
"self",
",",
"close_group",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"initialized",
":",
"raise",
"ValueError",
"(",
"\"You must add a search term before adding an operator.\"",
")",
"else",
":",
"self",
".",
"_operator",
"(",
"... | 35.590909 | 23 |
def sign(self, message):
"""Signs a message.
Args:
message: bytes, Message to be signed.
Returns:
string, The signature of the message for the given key.
"""
message = _helpers._to_bytes(message, encoding='utf-8')
return crypto.sign(self._key, me... | [
"def",
"sign",
"(",
"self",
",",
"message",
")",
":",
"message",
"=",
"_helpers",
".",
"_to_bytes",
"(",
"message",
",",
"encoding",
"=",
"'utf-8'",
")",
"return",
"crypto",
".",
"sign",
"(",
"self",
".",
"_key",
",",
"message",
",",
"'sha256'",
")"
] | 29.636364 | 20.181818 |
def load_xslt(filename=None, xsl=None):
'''Load and compile an XSLT document (specified by filename or string)
for repeated use in transforming XML.
'''
parser = _get_xmlparser()
if filename is not None:
xslt_doc = etree.parse(filename, parser=parser)
if xsl is not None:
xslt_doc... | [
"def",
"load_xslt",
"(",
"filename",
"=",
"None",
",",
"xsl",
"=",
"None",
")",
":",
"parser",
"=",
"_get_xmlparser",
"(",
")",
"if",
"filename",
"is",
"not",
"None",
":",
"xslt_doc",
"=",
"etree",
".",
"parse",
"(",
"filename",
",",
"parser",
"=",
"... | 34.727273 | 17.090909 |
def delete(self, req, driver):
"""Delete a network
Delete a specific netowrk with id on special cloud
with:
:Param req
:Type object Request
"""
response = driver.delete_network(req.params, id)
data = {
'action': "delete",
'contro... | [
"def",
"delete",
"(",
"self",
",",
"req",
",",
"driver",
")",
":",
"response",
"=",
"driver",
".",
"delete_network",
"(",
"req",
".",
"params",
",",
"id",
")",
"data",
"=",
"{",
"'action'",
":",
"\"delete\"",
",",
"'controller'",
":",
"\"network\"",
",... | 28.625 | 14.25 |
def on_module(self, node): # ():('body',)
"""Module def."""
out = None
for tnode in node.body:
out = self.run(tnode)
return out | [
"def",
"on_module",
"(",
"self",
",",
"node",
")",
":",
"# ():('body',)",
"out",
"=",
"None",
"for",
"tnode",
"in",
"node",
".",
"body",
":",
"out",
"=",
"self",
".",
"run",
"(",
"tnode",
")",
"return",
"out"
] | 28.166667 | 10.666667 |
def execCommand(g, command, timeout=10):
"""
Executes a command by sending it to the rack server
Arguments:
g : hcam_drivers.globals.Container
the Container object of application globals
command : (string)
the command (see below)
Possible commands are:
start : s... | [
"def",
"execCommand",
"(",
"g",
",",
"command",
",",
"timeout",
"=",
"10",
")",
":",
"if",
"not",
"g",
".",
"cpars",
"[",
"'hcam_server_on'",
"]",
":",
"g",
".",
"clog",
".",
"warn",
"(",
"'execCommand: servers are not active'",
")",
"return",
"False",
"... | 32.217391 | 18.478261 |
def _easteregg(app=None):
"""Like the name says. But who knows how it works?"""
def bzzzzzzz(gyver):
import base64
import zlib
return zlib.decompress(base64.b64decode(gyver)).decode('ascii')
gyver = u'\n'.join([x + (77 - len(x)) * u' ' for x in bzzzzzzz(b'''
eJyFlzuOJDkMRP06xRjymKgD... | [
"def",
"_easteregg",
"(",
"app",
"=",
"None",
")",
":",
"def",
"bzzzzzzz",
"(",
"gyver",
")",
":",
"import",
"base64",
"import",
"zlib",
"return",
"zlib",
".",
"decompress",
"(",
"base64",
".",
"b64decode",
"(",
"gyver",
")",
")",
".",
"decode",
"(",
... | 55.723077 | 27.692308 |
def action_cache_reset():
"""
Delete all contents from cache folder
Then re-generate cached version of all models in the local repo
"""
printDebug("""The existing cache will be erased and recreated.""")
printDebug(
"""This operation may take several minutes, depending on how man... | [
"def",
"action_cache_reset",
"(",
")",
":",
"printDebug",
"(",
"\"\"\"The existing cache will be erased and recreated.\"\"\"",
")",
"printDebug",
"(",
"\"\"\"This operation may take several minutes, depending on how many files exist in your local library.\"\"\"",
")",
"ONTOSPY_LOCAL_MODELS... | 38.428571 | 19.452381 |
def user_topic_ids(user):
"""Retrieve the list of topics IDs a user has access to."""
if user.is_super_admin() or user.is_read_only_user():
query = sql.select([models.TOPICS])
else:
query = (sql.select([models.JOINS_TOPICS_TEAMS.c.topic_id])
.select_from(
... | [
"def",
"user_topic_ids",
"(",
"user",
")",
":",
"if",
"user",
".",
"is_super_admin",
"(",
")",
"or",
"user",
".",
"is_read_only_user",
"(",
")",
":",
"query",
"=",
"sql",
".",
"select",
"(",
"[",
"models",
".",
"TOPICS",
"]",
")",
"else",
":",
"query... | 51.058824 | 27.352941 |
def run_interactive_command(command, env=None, **kwargs):
"""
Runs a command interactively, reusing the current stdin, stdout and stderr
Args:
command(list of str): args of the command to execute, including the
command itself as command[0] as `['ls', '-l']`
env(dict of str:str):... | [
"def",
"run_interactive_command",
"(",
"command",
",",
"env",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"command_result",
"=",
"_run_command",
"(",
"command",
"=",
"command",
",",
"out_pipe",
"=",
"sys",
".",
"stdout",
",",
"err_pipe",
"=",
"sys",
... | 32.375 | 21.708333 |
def restart(ctx, job_name, data, open_notebook, env, message, gpu, cpu, gpup, cpup, command):
"""
Restart a finished job as a new job.
"""
# Error early if more than one --env is passed. Then get the first/only
# --env out of the list so all other operations work normally (they don't
# expect an... | [
"def",
"restart",
"(",
"ctx",
",",
"job_name",
",",
"data",
",",
"open_notebook",
",",
"env",
",",
"message",
",",
"gpu",
",",
"cpu",
",",
"gpup",
",",
"cpup",
",",
"command",
")",
":",
"# Error early if more than one --env is passed. Then get the first/only",
"... | 29.774194 | 22.935484 |
def macro_network():
"""A network of micro elements which has greater integrated information
after coarse graining to a macro scale.
"""
tpm = np.array([[0.3, 0.3, 0.3, 0.3],
[0.3, 0.3, 0.3, 0.3],
[0.3, 0.3, 0.3, 0.3],
[0.3, 0.3, 1.0, 1.0],
... | [
"def",
"macro_network",
"(",
")",
":",
"tpm",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"0.3",
",",
"0.3",
",",
"0.3",
",",
"0.3",
"]",
",",
"[",
"0.3",
",",
"0.3",
",",
"0.3",
",",
"0.3",
"]",
",",
"[",
"0.3",
",",
"0.3",
",",
"0.3",
",",
... | 40.952381 | 2.761905 |
def _RunAndWaitForVFSFileUpdate(self, path):
"""Runs a flow on the client, and waits for it to finish."""
client_id = rdf_client.GetClientURNFromPath(path)
# If we're not actually in a directory on a client, no need to run a flow.
if client_id is None:
return
flow_utils.UpdateVFSFileAndWait... | [
"def",
"_RunAndWaitForVFSFileUpdate",
"(",
"self",
",",
"path",
")",
":",
"client_id",
"=",
"rdf_client",
".",
"GetClientURNFromPath",
"(",
"path",
")",
"# If we're not actually in a directory on a client, no need to run a flow.",
"if",
"client_id",
"is",
"None",
":",
"re... | 30.357143 | 19.357143 |
def url(url_pattern, view, kwargs=None, name=None):
"""
This is replacement for ``django.conf.urls.url`` function.
This url auto calls ``as_view`` method for Class based views and resolves
URLPattern objects.
If ``name`` is not specified it will try to guess it.
:param url_pattern: string with... | [
"def",
"url",
"(",
"url_pattern",
",",
"view",
",",
"kwargs",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"# Special handling for included view",
"if",
"isinstance",
"(",
"url_pattern",
",",
"URLPattern",
")",
"and",
"isinstance",
"(",
"view",
",",
"tup... | 33.607143 | 21.035714 |
def apply_refactor(self, call_id, payload):
"""Apply a refactor depending on its type."""
supported_refactorings = ["Rename", "InlineLocal", "AddImport", "OrganizeImports"]
if payload["refactorType"]["typehint"] in supported_refactorings:
diff_filepath = payload["diff"]
... | [
"def",
"apply_refactor",
"(",
"self",
",",
"call_id",
",",
"payload",
")",
":",
"supported_refactorings",
"=",
"[",
"\"Rename\"",
",",
"\"InlineLocal\"",
",",
"\"AddImport\"",
",",
"\"OrganizeImports\"",
"]",
"if",
"payload",
"[",
"\"refactorType\"",
"]",
"[",
"... | 53.684211 | 19.421053 |
def make_list(default_symbol_list, len_list_to_print):
'''
provide the list of symbols to use according for the list of
species/arrays to plot.
Parameters
----------
default_symbol_list : list
Symbols that the user choose to use.
len_list_to_print : integer
len of list of sp... | [
"def",
"make_list",
"(",
"default_symbol_list",
",",
"len_list_to_print",
")",
":",
"symbol_used",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len_list_to_print",
")",
":",
"symbol_used",
".",
"append",
"(",
"default_symbol_list",
"[",
"sc",
".",
"mod",
... | 26.421053 | 23.263158 |
def remove_shared_folder(self, name):
"""Removes the global shared folder with the given name previously
created by :py:func:`create_shared_folder` from the collection of
shared folders and stops sharing it.
In the current implementation, this operation is not
implement... | [
"def",
"remove_shared_folder",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"name can only be an instance of type basestring\"",
")",
"self",
".",
"_call",
"(",
"\"removeShare... | 37.875 | 16.9375 |
def _add_content_type(self, partname, content_type):
"""
Add a content type for the part with *partname* and *content_type*,
using a default or override as appropriate.
"""
ext = partname.ext
if (ext.lower(), content_type) in default_content_types:
self._defau... | [
"def",
"_add_content_type",
"(",
"self",
",",
"partname",
",",
"content_type",
")",
":",
"ext",
"=",
"partname",
".",
"ext",
"if",
"(",
"ext",
".",
"lower",
"(",
")",
",",
"content_type",
")",
"in",
"default_content_types",
":",
"self",
".",
"_defaults",
... | 40.1 | 14.1 |
def __rv_french(self, word, vowels):
"""
Return the region RV that is used by the French stemmer.
If the word begins with two vowels, RV is the region after
the third letter. Otherwise, it is the region after the first
vowel not at the beginning of the word, or the end of the wo... | [
"def",
"__rv_french",
"(",
"self",
",",
"word",
",",
"vowels",
")",
":",
"rv",
"=",
"\"\"",
"if",
"len",
"(",
"word",
")",
">=",
"2",
":",
"if",
"(",
"word",
".",
"startswith",
"(",
"(",
"\"par\"",
",",
"\"col\"",
",",
"\"tap\"",
")",
")",
"or",
... | 39.558824 | 19.441176 |
def _from_cfg(self, cfg):
"""
Initialize CFBlanket from a CFG instance.
:param cfg: A CFG instance.
:return: None
"""
# Let's first add all functions first
for func in cfg.kb.functions.values():
self.add_function(func)
self._mark_unknowns... | [
"def",
"_from_cfg",
"(",
"self",
",",
"cfg",
")",
":",
"# Let's first add all functions first",
"for",
"func",
"in",
"cfg",
".",
"kb",
".",
"functions",
".",
"values",
"(",
")",
":",
"self",
".",
"add_function",
"(",
"func",
")",
"self",
".",
"_mark_unknow... | 23.846154 | 14.769231 |
def model_to_dict(model, sort=False):
"""Convert model to a dict.
Parameters
----------
model : cobra.Model
The model to reformulate as a dict.
sort : bool, optional
Whether to sort the metabolites, reactions, and genes or maintain the
order defined in the model.
Return... | [
"def",
"model_to_dict",
"(",
"model",
",",
"sort",
"=",
"False",
")",
":",
"obj",
"=",
"OrderedDict",
"(",
")",
"obj",
"[",
"\"metabolites\"",
"]",
"=",
"list",
"(",
"map",
"(",
"metabolite_to_dict",
",",
"model",
".",
"metabolites",
")",
")",
"obj",
"... | 33.166667 | 19.888889 |
def serial_send(self, args):
'''send some bytes'''
mav = self.master.mav
flags = 0
if self.locked:
flags |= mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE
if self.serial_settings.timeout != 0:
flags |= mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND
if ... | [
"def",
"serial_send",
"(",
"self",
",",
"args",
")",
":",
"mav",
"=",
"self",
".",
"master",
".",
"mav",
"flags",
"=",
"0",
"if",
"self",
".",
"locked",
":",
"flags",
"|=",
"mavutil",
".",
"mavlink",
".",
"SERIAL_CONTROL_FLAG_EXCLUSIVE",
"if",
"self",
... | 39.857143 | 14.333333 |
def random_ucast_ip():
"""
Function to generate a random unicast ip address
:return:
A unicast IP Address
"""
first_octet = str(__random.randrange(1, 224))
def get_other_octetes():
return str(__random.randrange(0, 255))
return '{first_octet}.{second_octet}.{third_octe... | [
"def",
"random_ucast_ip",
"(",
")",
":",
"first_octet",
"=",
"str",
"(",
"__random",
".",
"randrange",
"(",
"1",
",",
"224",
")",
")",
"def",
"get_other_octetes",
"(",
")",
":",
"return",
"str",
"(",
"__random",
".",
"randrange",
"(",
"0",
",",
"255",
... | 43.125 | 30.375 |
def parse_result(line):
"""
Parse the result line of a phenomizer request.
Arguments:
line (str): A raw output line from phenomizer
Returns:
result (dict): A dictionary with the phenomizer info:
{
'p_value': float,
'gene_symbols': l... | [
"def",
"parse_result",
"(",
"line",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"\"Problem\"",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Login credentials seems to be wrong\"",
")",
"result",
"=",
"{",
"'p_value'",
":",
"None",
",",
"'gene_symbols'",
":",
... | 24.931034 | 19.862069 |
def bunkers_storm_motion(pressure, u, v, heights):
r"""Calculate the Bunkers right-mover and left-mover storm motions and sfc-6km mean flow.
Uses the storm motion calculation from [Bunkers2000]_.
Parameters
----------
pressure : array-like
Pressure from sounding
u : array-like
... | [
"def",
"bunkers_storm_motion",
"(",
"pressure",
",",
"u",
",",
"v",
",",
"heights",
")",
":",
"# mean wind from sfc-6km",
"wind_mean",
"=",
"concatenate",
"(",
"mean_pressure_weighted",
"(",
"pressure",
",",
"u",
",",
"v",
",",
"heights",
"=",
"heights",
",",
... | 37.037037 | 24.259259 |
def processing_blocks(self):
"""Return the a JSON dict encoding the PBs known to SDP."""
pb_list = ProcessingBlockList()
# TODO(BMo) realtime, offline etc.
return json.dumps(dict(active=pb_list.active,
completed=pb_list.completed,
... | [
"def",
"processing_blocks",
"(",
"self",
")",
":",
"pb_list",
"=",
"ProcessingBlockList",
"(",
")",
"# TODO(BMo) realtime, offline etc.",
"return",
"json",
".",
"dumps",
"(",
"dict",
"(",
"active",
"=",
"pb_list",
".",
"active",
",",
"completed",
"=",
"pb_list",... | 49.142857 | 9 |
def get_abs_filename_with_sub_path(sub_path, filename):
"""
生成当前路径下一级路径某文件的完整文件名;
:param:
* sub_path: (string) 下一级的某路径名称
* filename: (string) 下一级路径的某个文件名
:returns:
* 返回类型 (tuple),有两个值,第一个为 flag,第二个为文件名,说明见下
* flag: (bool) 如果文件存在,返回 True,文件不存在... | [
"def",
"get_abs_filename_with_sub_path",
"(",
"sub_path",
",",
"filename",
")",
":",
"try",
":",
"cur_path",
"=",
"pathlib",
".",
"Path",
".",
"cwd",
"(",
")",
"abs_filename",
"=",
"cur_path",
"/",
"pathlib",
".",
"Path",
"(",
"sub_path",
")",
"/",
"filena... | 29.54717 | 21.358491 |
def swaggerize_response(response, op):
"""
Delegate handling the Swagger concerns of the response to bravado-core.
:type response: :class:`pyramid.response.Response`
:type op: :class:`bravado_core.operation.Operation`
"""
response_spec = get_response_spec(response.status_int, op)
bravado_co... | [
"def",
"swaggerize_response",
"(",
"response",
",",
"op",
")",
":",
"response_spec",
"=",
"get_response_spec",
"(",
"response",
".",
"status_int",
",",
"op",
")",
"bravado_core",
".",
"response",
".",
"validate_response",
"(",
"response_spec",
",",
"op",
",",
... | 40.2 | 15.2 |
def convert_shaders(convert, shaders):
""" Modify shading code so that we can write code once
and make it run "everywhere".
"""
# New version of the shaders
out = []
if convert == 'es2':
for isfragment, shader in enumerate(shaders):
has_version = False
has_prec... | [
"def",
"convert_shaders",
"(",
"convert",
",",
"shaders",
")",
":",
"# New version of the shaders",
"out",
"=",
"[",
"]",
"if",
"convert",
"==",
"'es2'",
":",
"for",
"isfragment",
",",
"shader",
"in",
"enumerate",
"(",
"shaders",
")",
":",
"has_version",
"="... | 35.118644 | 15.711864 |
def bam2mat(args):
"""
%prog bam2mat input.bam
Convert bam file to .mat format, which is simply numpy 2D array. Important
parameter is the resolution, which is the cell size. Small cell size lead
to more fine-grained heatmap, but leads to large .mat size and slower
plotting.
"""
import ... | [
"def",
"bam2mat",
"(",
"args",
")",
":",
"import",
"pysam",
"from",
"jcvi",
".",
"utils",
".",
"cbook",
"import",
"percentage",
"p",
"=",
"OptionParser",
"(",
"bam2mat",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--resolution\"",
",",
"default",
... | 33.24 | 19.9 |
def system_monitor_cid_card_threshold_down_threshold(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
cid_card = ET.SubElement(system_monitor, "c... | [
"def",
"system_monitor_cid_card_threshold_down_threshold",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"system_monitor",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"system-monitor\"",
",",... | 49.416667 | 21.333333 |
def _bor16(ins):
''' Pops top 2 operands out of the stack, and performs
1st operand OR (bitwise) 2nd operand (top of the stack),
pushes result (16 bit in HL).
16 bit un/signed version
Optimizations:
If any of the operators are constants: Returns either 0 or
the oth... | [
"def",
"_bor16",
"(",
"ins",
")",
":",
"op1",
",",
"op2",
"=",
"tuple",
"(",
"ins",
".",
"quad",
"[",
"2",
":",
"]",
")",
"if",
"_int_ops",
"(",
"op1",
",",
"op2",
")",
"is",
"not",
"None",
":",
"op1",
",",
"op2",
"=",
"_int_ops",
"(",
"op1",... | 26.71875 | 18.15625 |
def converter(type_name):
"""Get a given converter by name, or raise an exception."""
converter = TYPES.get(type_name)
if converter is None:
raise ConverterError('Unknown converter: %r' % type_name)
return converter() | [
"def",
"converter",
"(",
"type_name",
")",
":",
"converter",
"=",
"TYPES",
".",
"get",
"(",
"type_name",
")",
"if",
"converter",
"is",
"None",
":",
"raise",
"ConverterError",
"(",
"'Unknown converter: %r'",
"%",
"type_name",
")",
"return",
"converter",
"(",
... | 39.333333 | 12.833333 |
def get_version_from_unpacked_sdist(path):
"""Assume path points to unpacked source distribution and get version."""
# This is a condensed version of the relevant code in pkginfo 1.4.1
try:
with open(os.path.join(path, 'PKG-INFO')) as f:
data = f.read()
except IOError:
# Coul... | [
"def",
"get_version_from_unpacked_sdist",
"(",
"path",
")",
":",
"# This is a condensed version of the relevant code in pkginfo 1.4.1",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'PKG-INFO'",
")",
")",
"as",
"f",
":",
"data... | 37.928571 | 16.857143 |
def alignment(self, align):
'''Sets the alignment of the printer.
Args:
align: desired alignment. Options are 'left', 'center', 'right', and 'justified'. Anything else
will throw an error.
Returns:
None
Raises:
RuntimeError: Invali... | [
"def",
"alignment",
"(",
"self",
",",
"align",
")",
":",
"if",
"align",
"==",
"'left'",
":",
"align",
"=",
"'0'",
"elif",
"align",
"==",
"'center'",
":",
"align",
"=",
"'1'",
"elif",
"align",
"==",
"'right'",
":",
"align",
"=",
"'2'",
"elif",
"align"... | 30.090909 | 19.818182 |
def modify_parameter_group(self, name, parameters=None):
"""
Modify a parameter group for your account.
:type name: string
:param name: The name of the new parameter group
:type parameters: list of :class:`boto.rds.parametergroup.Parameter`
:param parameters: The new pa... | [
"def",
"modify_parameter_group",
"(",
"self",
",",
"name",
",",
"parameters",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'DBParameterGroupName'",
":",
"name",
"}",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"parameters",
")",
")",
":",
"par... | 38.368421 | 15.842105 |
def jpath_parse_c(jpath):
"""
Caching variant of :py:func:`jpath_parse` function. Same arguments and return
value.
For performance reasons thee is no copying and all returned values are
references to internal cache. Treat the returned values as read only, or
suffer the consequences.
"""
... | [
"def",
"jpath_parse_c",
"(",
"jpath",
")",
":",
"if",
"not",
"jpath",
"in",
"_JPATH_CACHE",
":",
"_JPATH_CACHE",
"[",
"jpath",
"]",
"=",
"jpath_parse",
"(",
"jpath",
")",
"return",
"_JPATH_CACHE",
"[",
"jpath",
"]"
] | 34.916667 | 19.416667 |
def _get_value(self, var):
"""Return value of variable in solution."""
return self._problem._p.getVarByName(self._problem._variables[var]).x | [
"def",
"_get_value",
"(",
"self",
",",
"var",
")",
":",
"return",
"self",
".",
"_problem",
".",
"_p",
".",
"getVarByName",
"(",
"self",
".",
"_problem",
".",
"_variables",
"[",
"var",
"]",
")",
".",
"x"
] | 51.333333 | 17 |
def shrink_patch(patch_path, target_file):
"""
Shrinks a patch on patch_path to contain only changes for target_file.
:param patch_path: path to the shrinked patch file
:param target_file: filename of a file of which changes should be kept
:return: True if the is a section containing changes for ta... | [
"def",
"shrink_patch",
"(",
"patch_path",
",",
"target_file",
")",
":",
"logging",
".",
"debug",
"(",
"\"Shrinking patch file %s to keep only %s changes.\"",
",",
"patch_path",
",",
"target_file",
")",
"shrinked_lines",
"=",
"[",
"]",
"patch_file",
"=",
"None",
"try... | 34.575 | 18.325 |
def clear(self):
""""Removes all elements from the collection and resets the error handling
"""
self.bad = False
self.errors = {}
self._collection.clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"bad",
"=",
"False",
"self",
".",
"errors",
"=",
"{",
"}",
"self",
".",
"_collection",
".",
"clear",
"(",
")"
] | 31.5 | 10.666667 |
def validate_schema(schema_name):
"""Validate the JSON against a required schema_name."""
def decorator(f):
@wraps(f)
def wrapper(*args, **kw):
instance = args[0]
try:
instance.validator(instance.schemas[schema_name]).validate(request.get_json())
... | [
"def",
"validate_schema",
"(",
"schema_name",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"instance",
"=",
"args",
"[",
"0",
"]",
"try",
":",
... | 45.052632 | 18.473684 |
def wrapped_help_text(wrapped_func):
"""Decorator to pass through the documentation from a wrapped function.
"""
def decorator(wrapper_func):
"""The decorator.
Parameters
----------
f : callable
The wrapped function.
"""
wrapper_func.__doc__ = ('... | [
"def",
"wrapped_help_text",
"(",
"wrapped_func",
")",
":",
"def",
"decorator",
"(",
"wrapper_func",
")",
":",
"\"\"\"The decorator.\n\n Parameters\n ----------\n f : callable\n The wrapped function.\n\n \"\"\"",
"wrapper_func",
".",
"__doc__",
"... | 29.1875 | 16.3125 |
def ParCalculate(systems,calc,cleanup=True,block=True,prefix="Calc_"):
'''
Run calculators in parallel for all systems.
Calculators are executed in isolated processes and directories.
The resulting objects are returned in the list (one per input system).
'''
if type(systems) != type([]) :
... | [
"def",
"ParCalculate",
"(",
"systems",
",",
"calc",
",",
"cleanup",
"=",
"True",
",",
"block",
"=",
"True",
",",
"prefix",
"=",
"\"Calc_\"",
")",
":",
"if",
"type",
"(",
"systems",
")",
"!=",
"type",
"(",
"[",
"]",
")",
":",
"sysl",
"=",
"[",
"sy... | 33.016667 | 19.65 |
def setCenterLineColor(self, color):
"""
Sets the color for the center line.
:return <QColor>
"""
palette = self.palette()
palette.setColor(palette.GridCenterline, QColor(color)) | [
"def",
"setCenterLineColor",
"(",
"self",
",",
"color",
")",
":",
"palette",
"=",
"self",
".",
"palette",
"(",
")",
"palette",
".",
"setColor",
"(",
"palette",
".",
"GridCenterline",
",",
"QColor",
"(",
"color",
")",
")"
] | 29 | 10.25 |
def get_data(n_samples=100):
"""Get synthetic classification data with n_samples samples."""
X, y = make_classification(
n_samples=n_samples,
n_features=N_FEATURES,
n_classes=N_CLASSES,
random_state=0,
)
X = X.astype(np.float32)
return X, y | [
"def",
"get_data",
"(",
"n_samples",
"=",
"100",
")",
":",
"X",
",",
"y",
"=",
"make_classification",
"(",
"n_samples",
"=",
"n_samples",
",",
"n_features",
"=",
"N_FEATURES",
",",
"n_classes",
"=",
"N_CLASSES",
",",
"random_state",
"=",
"0",
",",
")",
"... | 28.3 | 14.4 |
def visit_any_conditionnal(self, node1, node2):
"""
Set and restore the in_cond variable before visiting subnode.
Compute correct dependencies on a value as both branch are possible
path.
"""
true_naming = false_naming = None
try:
tmp = self.naming.... | [
"def",
"visit_any_conditionnal",
"(",
"self",
",",
"node1",
",",
"node2",
")",
":",
"true_naming",
"=",
"false_naming",
"=",
"None",
"try",
":",
"tmp",
"=",
"self",
".",
"naming",
".",
"copy",
"(",
")",
"for",
"expr",
"in",
"node1",
":",
"self",
".",
... | 28.55814 | 15.44186 |
def insertUnorderedList(self):
"""
Inserts an ordered list into the editor.
"""
cursor = self.editor().textCursor()
currlist = cursor.currentList()
new_style = QTextListFormat.ListDisc
indent = 1
if currlist:
format = currlis... | [
"def",
"insertUnorderedList",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"editor",
"(",
")",
".",
"textCursor",
"(",
")",
"currlist",
"=",
"cursor",
".",
"currentList",
"(",
")",
"new_style",
"=",
"QTextListFormat",
".",
"ListDisc",
"indent",
"=",
... | 32.296296 | 11.703704 |
def timethis(what):
""""Utility function for making simple benchmarks (calculates time calls).
It can be used either as a context manager or as a decorator.
"""
@contextlib.contextmanager
def benchmark():
timer = time.clock if sys.platform == "win32" else time.time
start = timer()
... | [
"def",
"timethis",
"(",
"what",
")",
":",
"@",
"contextlib",
".",
"contextmanager",
"def",
"benchmark",
"(",
")",
":",
"timer",
"=",
"time",
".",
"clock",
"if",
"sys",
".",
"platform",
"==",
"\"win32\"",
"else",
"time",
".",
"time",
"start",
"=",
"time... | 30.35 | 15.6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.