text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def text2sentences(text, labels):
'''
Splits given text at predicted positions from `labels`
'''
sentence = ''
for i, label in enumerate(labels):
if label == '1':
if sentence:
yield sentence
sentence = ''
else:
sentence += text[i]
... | [
"def",
"text2sentences",
"(",
"text",
",",
"labels",
")",
":",
"sentence",
"=",
"''",
"for",
"i",
",",
"label",
"in",
"enumerate",
"(",
"labels",
")",
":",
"if",
"label",
"==",
"'1'",
":",
"if",
"sentence",
":",
"yield",
"sentence",
"sentence",
"=",
... | 24.642857 | 17.928571 |
def contraction_conical_Crane(Di1, Di2, l=None, angle=None):
r'''Returns loss coefficient for a conical pipe contraction
as shown in Crane TP 410M [1]_ between 0 and 180 degrees.
If :math:`\theta < 45^{\circ}`:
.. math::
K_2 = {0.8 \sin \frac{\theta}{2}(1 - \beta^2)}
otherwise:
... | [
"def",
"contraction_conical_Crane",
"(",
"Di1",
",",
"Di2",
",",
"l",
"=",
"None",
",",
"angle",
"=",
"None",
")",
":",
"if",
"l",
"is",
"None",
"and",
"angle",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'One of `l` or `angle` must be specified'",
")",
... | 28.913043 | 25.115942 |
def run(self):
"""Continously scan for BLE advertisements."""
self.socket = self.bluez.hci_open_dev(self.bt_device_id)
filtr = self.bluez.hci_filter_new()
self.bluez.hci_filter_all_events(filtr)
self.bluez.hci_filter_set_ptype(filtr, self.bluez.HCI_EVENT_PKT)
self.socket... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"socket",
"=",
"self",
".",
"bluez",
".",
"hci_open_dev",
"(",
"self",
".",
"bt_device_id",
")",
"filtr",
"=",
"self",
".",
"bluez",
".",
"hci_filter_new",
"(",
")",
"self",
".",
"bluez",
".",
"hci_fi... | 38.55 | 17.35 |
def _update_rr_ce_entry(self, rec):
# type: (dr.DirectoryRecord) -> int
'''
An internal method to update the Rock Ridge CE entry for the given
record.
Parameters:
rec - The record to update the Rock Ridge CE entry for (if it exists).
Returns:
The number... | [
"def",
"_update_rr_ce_entry",
"(",
"self",
",",
"rec",
")",
":",
"# type: (dr.DirectoryRecord) -> int",
"if",
"rec",
".",
"rock_ridge",
"is",
"not",
"None",
"and",
"rec",
".",
"rock_ridge",
".",
"dr_entries",
".",
"ce_record",
"is",
"not",
"None",
":",
"celen"... | 41.15 | 26.15 |
def image_id_from_registry(image_name):
"""Get the docker id from a public or private registry"""
registry, repository, tag = parse(image_name)
try:
token = auth_token(registry, repository).get("token")
# dockerhub is crazy
if registry == "index.docker.io":
registry = "re... | [
"def",
"image_id_from_registry",
"(",
"image_name",
")",
":",
"registry",
",",
"repository",
",",
"tag",
"=",
"parse",
"(",
"image_name",
")",
"try",
":",
"token",
"=",
"auth_token",
"(",
"registry",
",",
"repository",
")",
".",
"get",
"(",
"\"token\"",
")... | 47.944444 | 18.888889 |
def _set_conf(self):
"""
Set configuration parameters from the Conf object into the detector
object.
Time values are converted to samples, and amplitude values are in mV.
"""
self.rr_init = 60 * self.fs / self.conf.hr_init
self.rr_max = 60 * self.fs / self.conf.h... | [
"def",
"_set_conf",
"(",
"self",
")",
":",
"self",
".",
"rr_init",
"=",
"60",
"*",
"self",
".",
"fs",
"/",
"self",
".",
"conf",
".",
"hr_init",
"self",
".",
"rr_max",
"=",
"60",
"*",
"self",
".",
"fs",
"/",
"self",
".",
"conf",
".",
"hr_min",
"... | 39.4 | 22.8 |
def _notify_add_at(self, index, length=1):
"""Notify about an AddChange at a caertain index and length."""
slice_ = self._slice_at(index, length)
self._notify_add(slice_) | [
"def",
"_notify_add_at",
"(",
"self",
",",
"index",
",",
"length",
"=",
"1",
")",
":",
"slice_",
"=",
"self",
".",
"_slice_at",
"(",
"index",
",",
"length",
")",
"self",
".",
"_notify_add",
"(",
"slice_",
")"
] | 47.75 | 4 |
def _run_configure(subcmd, args):
"""Runs the configuration step for the specified sub-command.
"""
maps = {
"packages": _conf_packages
}
if subcmd in maps:
maps[subcmd](args)
else:
msg.warn("'configure' sub-command {} is not supported.".format(subcmd)) | [
"def",
"_run_configure",
"(",
"subcmd",
",",
"args",
")",
":",
"maps",
"=",
"{",
"\"packages\"",
":",
"_conf_packages",
"}",
"if",
"subcmd",
"in",
"maps",
":",
"maps",
"[",
"subcmd",
"]",
"(",
"args",
")",
"else",
":",
"msg",
".",
"warn",
"(",
"\"'co... | 29.6 | 17.4 |
def _move(self, speed=0, steering=0, seconds=None):
"""Move robot."""
self.drive_queue.put((speed, steering))
if seconds is not None:
time.sleep(seconds)
self.drive_queue.put((0, 0))
self.drive_queue.join() | [
"def",
"_move",
"(",
"self",
",",
"speed",
"=",
"0",
",",
"steering",
"=",
"0",
",",
"seconds",
"=",
"None",
")",
":",
"self",
".",
"drive_queue",
".",
"put",
"(",
"(",
"speed",
",",
"steering",
")",
")",
"if",
"seconds",
"is",
"not",
"None",
":"... | 36.571429 | 6.428571 |
def from_api_repr(cls, resource):
"""Factory: construct a model reference given its API representation
Args:
resource (Dict[str, object]):
Model reference representation returned from the API
Returns:
google.cloud.bigquery.model.ModelReference:
... | [
"def",
"from_api_repr",
"(",
"cls",
",",
"resource",
")",
":",
"ref",
"=",
"cls",
"(",
")",
"ref",
".",
"_proto",
"=",
"json_format",
".",
"ParseDict",
"(",
"resource",
",",
"types",
".",
"ModelReference",
"(",
")",
")",
"return",
"ref"
] | 34.571429 | 19.857143 |
def update_pass(user_id, newpass):
'''
Update the password of a user.
'''
out_dic = {'success': False, 'code': '00'}
entry = TabMember.update(user_pass=tools.md5(newpass)).where(TabMember.uid == user_id)
entry.execute()
out_dic['success'] = True
return... | [
"def",
"update_pass",
"(",
"user_id",
",",
"newpass",
")",
":",
"out_dic",
"=",
"{",
"'success'",
":",
"False",
",",
"'code'",
":",
"'00'",
"}",
"entry",
"=",
"TabMember",
".",
"update",
"(",
"user_pass",
"=",
"tools",
".",
"md5",
"(",
"newpass",
")",
... | 24.307692 | 25.538462 |
def read(self):
"""
Read the target value
Use $project aggregate operator in order to support nested objects
"""
result = self.get_collection().aggregate([
{'$match': {'_id': self._document_id}},
{'$project': {'_value': '$' + self._path, '_id': False}}
... | [
"def",
"read",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"get_collection",
"(",
")",
".",
"aggregate",
"(",
"[",
"{",
"'$match'",
":",
"{",
"'_id'",
":",
"self",
".",
"_document_id",
"}",
"}",
",",
"{",
"'$project'",
":",
"{",
"'_value'",
... | 28.866667 | 18.333333 |
def _find_flats_edges(self, data, mag, direction):
"""
Extend flats 1 square downstream
Flats on the downstream side of the flat might find a valid angle,
but that doesn't mean that it's a correct angle. We have to find
these and then set them equal to a flat
"""
... | [
"def",
"_find_flats_edges",
"(",
"self",
",",
"data",
",",
"mag",
",",
"direction",
")",
":",
"i12",
"=",
"np",
".",
"arange",
"(",
"data",
".",
"size",
")",
".",
"reshape",
"(",
"data",
".",
"shape",
")",
"flat",
"=",
"mag",
"==",
"FLAT_ID_INT",
"... | 33.375 | 15.708333 |
def move_odict_item(odict, key, newpos):
"""
References:
http://stackoverflow.com/questions/22663966/changing-order-of-ordered-dictionary-in-python
CommandLine:
python -m utool.util_dict --exec-move_odict_item
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict impor... | [
"def",
"move_odict_item",
"(",
"odict",
",",
"key",
",",
"newpos",
")",
":",
"odict",
"[",
"key",
"]",
"=",
"odict",
".",
"pop",
"(",
"key",
")",
"for",
"i",
",",
"otherkey",
"in",
"enumerate",
"(",
"list",
"(",
"odict",
".",
"keys",
"(",
")",
")... | 33.588235 | 12.588235 |
def list_themes_user():
"""List user theme files."""
themes = [*os.scandir(os.path.join(CONF_DIR, "colorschemes/dark/")),
*os.scandir(os.path.join(CONF_DIR, "colorschemes/light/"))]
return [t for t in themes if os.path.isfile(t.path)] | [
"def",
"list_themes_user",
"(",
")",
":",
"themes",
"=",
"[",
"*",
"os",
".",
"scandir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"CONF_DIR",
",",
"\"colorschemes/dark/\"",
")",
")",
",",
"*",
"os",
".",
"scandir",
"(",
"os",
".",
"path",
".",
"jo... | 51.2 | 19.6 |
def sum(x, weights=None):
'''
sum(x) yields either a potential-sum object if x is a potential function or the sum of x if x
is not. If x is not a potential-field then it must be a vector.
sum(x, weights=w) uses the given weights to produce a weighted sum.
'''
x = to_potential(x)
if is_cons... | [
"def",
"sum",
"(",
"x",
",",
"weights",
"=",
"None",
")",
":",
"x",
"=",
"to_potential",
"(",
"x",
")",
"if",
"is_const_potential",
"(",
"x",
")",
":",
"return",
"PotentialConstant",
"(",
"np",
".",
"sum",
"(",
"x",
".",
"c",
")",
")",
"else",
":... | 48.333333 | 30.111111 |
def save_output(results, output_directory="output"):
"""
Save report data in the given directory
Args:
results (OrderedDict): Parsing results
output_directory: The patch to the directory to save in
"""
aggregate_reports = results["aggregate_reports"]
forensic_reports = results[... | [
"def",
"save_output",
"(",
"results",
",",
"output_directory",
"=",
"\"output\"",
")",
":",
"aggregate_reports",
"=",
"results",
"[",
"\"aggregate_reports\"",
"]",
"forensic_reports",
"=",
"results",
"[",
"\"forensic_reports\"",
"]",
"if",
"os",
".",
"path",
".",
... | 38.65 | 20.816667 |
def find_and_remove(self, f: Callable):
"""
Removes any and all fields for which `f(field)` returns `True`.
"""
self._table = [fld for fld in self._table if not f(fld)] | [
"def",
"find_and_remove",
"(",
"self",
",",
"f",
":",
"Callable",
")",
":",
"self",
".",
"_table",
"=",
"[",
"fld",
"for",
"fld",
"in",
"self",
".",
"_table",
"if",
"not",
"f",
"(",
"fld",
")",
"]"
] | 39.2 | 11.2 |
def vrange(start, stop, step=1, dtype='f8'):
"""Creates a virtual column which is the equivalent of numpy.arange, but uses 0 memory"""
from .column import ColumnVirtualRange
return ColumnVirtualRange(start, stop, step, dtype) | [
"def",
"vrange",
"(",
"start",
",",
"stop",
",",
"step",
"=",
"1",
",",
"dtype",
"=",
"'f8'",
")",
":",
"from",
".",
"column",
"import",
"ColumnVirtualRange",
"return",
"ColumnVirtualRange",
"(",
"start",
",",
"stop",
",",
"step",
",",
"dtype",
")"
] | 58.5 | 5.25 |
def connectedVertices(self, index, returnIds=False):
"""Find all vertices connected to an input vertex specified by its index.
:param bool returnIds: return vertex IDs instead of vertex coordinates.
.. hint:: |connVtx| |connVtx.py|_
"""
mesh = self.polydata()
cellIdLis... | [
"def",
"connectedVertices",
"(",
"self",
",",
"index",
",",
"returnIds",
"=",
"False",
")",
":",
"mesh",
"=",
"self",
".",
"polydata",
"(",
")",
"cellIdList",
"=",
"vtk",
".",
"vtkIdList",
"(",
")",
"mesh",
".",
"GetPointCells",
"(",
"index",
",",
"cel... | 31.575758 | 16.060606 |
def ind_zero_freq(self):
"""
Index of the first point for which the freqencies are equal or greater than zero.
"""
ind = np.searchsorted(self.frequencies, 0)
if ind >= len(self.frequencies):
raise ValueError("No positive frequencies found")
return ind | [
"def",
"ind_zero_freq",
"(",
"self",
")",
":",
"ind",
"=",
"np",
".",
"searchsorted",
"(",
"self",
".",
"frequencies",
",",
"0",
")",
"if",
"ind",
">=",
"len",
"(",
"self",
".",
"frequencies",
")",
":",
"raise",
"ValueError",
"(",
"\"No positive frequenc... | 38 | 14.75 |
def ConvCnstrMODMaskOptions(opt=None, method='fista'):
"""A wrapper function that dynamically defines a class derived from
the Options class associated with one of the implementations of
the Convolutional Constrained MOD problem, and returns an object
instantiated with the provided parameters. The wrapp... | [
"def",
"ConvCnstrMODMaskOptions",
"(",
"opt",
"=",
"None",
",",
"method",
"=",
"'fista'",
")",
":",
"# Assign base class depending on method selection argument",
"base",
"=",
"ccmodmsk_class_label_lookup",
"(",
"method",
")",
".",
"Options",
"# Nested class with dynamically... | 46.8 | 20.4 |
def json(self):
"""Custom JSON encoder"""
attributes = {
'type': self.type,
'filename': self.filename,
'line_number': self.lineno,
'hashed_secret': self.secret_hash,
}
if self.is_secret is not None:
attributes['is_secret'] = se... | [
"def",
"json",
"(",
"self",
")",
":",
"attributes",
"=",
"{",
"'type'",
":",
"self",
".",
"type",
",",
"'filename'",
":",
"self",
".",
"filename",
",",
"'line_number'",
":",
"self",
".",
"lineno",
",",
"'hashed_secret'",
":",
"self",
".",
"secret_hash",
... | 26.692308 | 15.538462 |
def get(self, sid):
"""
Constructs a InviteContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.chat.v2.service.channel.invite.InviteContext
:rtype: twilio.rest.chat.v2.service.channel.invite.InviteContext
"""
return InviteCon... | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"InviteContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"channel_sid",
"=",
"self",
".",
"_solution",
"[",
"'channel_sid'",... | 31.933333 | 20.2 |
def update_membership_memberships(self, group_id, membership_id, moderator=None, workflow_state=None):
"""
Update a membership.
Accept a membership request, or add/remove moderator rights.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH -... | [
"def",
"update_membership_memberships",
"(",
"self",
",",
"group_id",
",",
"membership_id",
",",
"moderator",
"=",
"None",
",",
"workflow_state",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PA... | 38.870968 | 23.483871 |
def _resolve_reference_sample(self, reference_samples=None,
service_uids=None):
"""Returns the reference sample from reference_samples passed in that fits
better with the service uid requirements. This is, the reference sample
that covers most (or all) of the se... | [
"def",
"_resolve_reference_sample",
"(",
"self",
",",
"reference_samples",
"=",
"None",
",",
"service_uids",
"=",
"None",
")",
":",
"if",
"not",
"reference_samples",
":",
"return",
"None",
",",
"list",
"(",
")",
"if",
"not",
"service_uids",
":",
"# Since no se... | 41.914894 | 18.914894 |
def _make_signature(self):
"""
Create a signature for `execute` based on the minimizers this
`ChainedMinimizer` was initiated with. For the format, see the docstring
of :meth:`ChainedMinimizer.execute`.
:return: :class:`inspect.Signature` instance.
"""
# Create K... | [
"def",
"_make_signature",
"(",
"self",
")",
":",
"# Create KEYWORD_ONLY arguments with the names of the minimizers.",
"name",
"=",
"lambda",
"x",
":",
"x",
".",
"__class__",
".",
"__name__",
"count",
"=",
"Counter",
"(",
"[",
"name",
"(",
"minimizer",
")",
"for",
... | 41.515152 | 19.757576 |
def ms_contrast_restore(self, viewer, event, data_x, data_y, msg=True):
"""An interactive way to restore the colormap contrast settings after
a warp operation.
"""
if self.cancmap and (event.state == 'down'):
self.restore_contrast(viewer, msg=msg)
return True | [
"def",
"ms_contrast_restore",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
",",
"msg",
"=",
"True",
")",
":",
"if",
"self",
".",
"cancmap",
"and",
"(",
"event",
".",
"state",
"==",
"'down'",
")",
":",
"self",
".",
"restore_... | 43.571429 | 12.714286 |
def path_exists(path):
"""
Check if file exists either remote or local.
Parameters:
-----------
path : path to file
Returns:
--------
exists : bool
"""
if path.startswith(("http://", "https://")):
try:
urlopen(path).info()
return True
exc... | [
"def",
"path_exists",
"(",
"path",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"(",
"\"http://\"",
",",
"\"https://\"",
")",
")",
":",
"try",
":",
"urlopen",
"(",
"path",
")",
".",
"info",
"(",
")",
"return",
"True",
"except",
"HTTPError",
"as",
... | 25.125 | 17.1875 |
def find_lemma(self, verb):
""" Returns the base form of the given inflected verb, using a rule-based approach.
"""
v = verb.lower()
# Common prefixes: be-finden and emp-finden probably inflect like finden.
if not (v.startswith("ge") and v.endswith("t")): # Probably gerund.
... | [
"def",
"find_lemma",
"(",
"self",
",",
"verb",
")",
":",
"v",
"=",
"verb",
".",
"lower",
"(",
")",
"# Common prefixes: be-finden and emp-finden probably inflect like finden.",
"if",
"not",
"(",
"v",
".",
"startswith",
"(",
"\"ge\"",
")",
"and",
"v",
".",
"ends... | 48.857143 | 17.857143 |
def dependency_list(self, tkn: str) -> List[str]:
"""Return a list all of the grammarelts that depend on tkn
:param tkn:
:return:
"""
if tkn not in self.dependency_map:
self.dependency_map[tkn] = [tkn] # Force a circular reference
self.dependency_... | [
"def",
"dependency_list",
"(",
"self",
",",
"tkn",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"tkn",
"not",
"in",
"self",
".",
"dependency_map",
":",
"self",
".",
"dependency_map",
"[",
"tkn",
"]",
"=",
"[",
"tkn",
"]",
"# Force a cir... | 39.9 | 17.2 |
def get_third_party(self, third_party):
"""Return the account for the given third-party. Raise <something> if the third party doesn't belong to this bookset."""
actual_account = third_party.get_account()
assert actual_account.get_bookset() == self
return ThirdPartySubAccount(actual_acco... | [
"def",
"get_third_party",
"(",
"self",
",",
"third_party",
")",
":",
"actual_account",
"=",
"third_party",
".",
"get_account",
"(",
")",
"assert",
"actual_account",
".",
"get_bookset",
"(",
")",
"==",
"self",
"return",
"ThirdPartySubAccount",
"(",
"actual_account"... | 69 | 11.6 |
def NewFromJSON(data):
"""
Create a new Shake instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a Shake.
Returns:
A Shake instance.
"""
s = Shake(
id=data.get('id', None),
name=data.get('name', Non... | [
"def",
"NewFromJSON",
"(",
"data",
")",
":",
"s",
"=",
"Shake",
"(",
"id",
"=",
"data",
".",
"get",
"(",
"'id'",
",",
"None",
")",
",",
"name",
"=",
"data",
".",
"get",
"(",
"'name'",
",",
"None",
")",
",",
"url",
"=",
"data",
".",
"get",
"("... | 31.608696 | 15.695652 |
def authenticate(session, username, password):
"""
Authenticate a PasswordUser with the specified
username/password.
:param session: An active SQLAlchemy session
:param username: The username
:param password: The password
:raise AuthenticationError: if an error occurred
:return: a Pass... | [
"def",
"authenticate",
"(",
"session",
",",
"username",
",",
"password",
")",
":",
"if",
"not",
"username",
"or",
"not",
"password",
":",
"raise",
"AuthenticationError",
"(",
")",
"user",
"=",
"session",
".",
"query",
"(",
"PasswordUser",
")",
".",
"filter... | 26.615385 | 16.384615 |
def delete_entity_alias(self, alias_id, mount_point=DEFAULT_MOUNT_POINT):
"""Delete a entity alias.
Supported methods:
DELETE: /{mount_point}/entity-alias/id/{alias_id}. Produces: 204 (empty body)
:param alias_id: Identifier of the entity.
:type alias_id: str | unicode
... | [
"def",
"delete_entity_alias",
"(",
"self",
",",
"alias_id",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"api_path",
"=",
"'/v1/{mount_point}/entity-alias/id/{id}'",
".",
"format",
"(",
"mount_point",
"=",
"mount_point",
",",
"id",
"=",
"alias_id",
",",... | 35.8 | 18.1 |
def get(self,identity,params=None, headers=None):
"""Get a single creditor bank account.
Retrieves the details of an existing creditor bank account.
Args:
identity (string): Unique identifier, beginning with "BA".
params (dict, optional): Query string parameters.
... | [
"def",
"get",
"(",
"self",
",",
"identity",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"path",
"=",
"self",
".",
"_sub_url_params",
"(",
"'/creditor_bank_accounts/:identity'",
",",
"{",
"'identity'",
":",
"identity",
",",
"}",
")",
... | 33.666667 | 24.095238 |
def L_diffuser_inner(sed_inputs=sed_dict):
"""Return the inner length of each diffuser in the sedimentation tank.
Parameters
----------
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can be found in sed.yaml
Returns
-------... | [
"def",
"L_diffuser_inner",
"(",
"sed_inputs",
"=",
"sed_dict",
")",
":",
"return",
"L_diffuser_outer",
"(",
"sed_inputs",
"[",
"'tank'",
"]",
"[",
"'W'",
"]",
")",
"-",
"(",
"2",
"*",
"(",
"sed_inputs",
"[",
"'manifold'",
"]",
"[",
"'diffuser'",
"]",
"["... | 33.555556 | 21.5 |
def runs_done():
"""Marks a release candidate as having all runs reported."""
build = g.build
release_name, release_number = _get_release_params()
release = (
models.Release.query
.filter_by(build_id=build.id, name=release_name, number=release_number)
.with_lockmode('update')
... | [
"def",
"runs_done",
"(",
")",
":",
"build",
"=",
"g",
".",
"build",
"release_name",
",",
"release_number",
"=",
"_get_release_params",
"(",
")",
"release",
"=",
"(",
"models",
".",
"Release",
".",
"query",
".",
"filter_by",
"(",
"build_id",
"=",
"build",
... | 30.4375 | 22 |
def send_message(self, message):
"""
Prepare a message to send on the UDP socket. Eventually set retransmissions.
:param message: the message to send
"""
if isinstance(message, Request):
request = self._requestLayer.send_request(message)
request = self._o... | [
"def",
"send_message",
"(",
"self",
",",
"message",
")",
":",
"if",
"isinstance",
"(",
"message",
",",
"Request",
")",
":",
"request",
"=",
"self",
".",
"_requestLayer",
".",
"send_request",
"(",
"message",
")",
"request",
"=",
"self",
".",
"_observeLayer"... | 48.611111 | 17.277778 |
def _pad(self, text):
"""Pad the text."""
top_bottom = ("\n" * self._padding) + " "
right_left = " " * self._padding * self.PAD_WIDTH
return top_bottom + right_left + text + right_left + top_bottom | [
"def",
"_pad",
"(",
"self",
",",
"text",
")",
":",
"top_bottom",
"=",
"(",
"\"\\n\"",
"*",
"self",
".",
"_padding",
")",
"+",
"\" \"",
"right_left",
"=",
"\" \"",
"*",
"self",
".",
"_padding",
"*",
"self",
".",
"PAD_WIDTH",
"return",
"top_bottom",
"+",... | 45 | 15.2 |
def maybe_call_fn_and_grads(fn,
fn_arg_list,
result=None,
grads=None,
check_non_none_grads=True,
name=None):
"""Calls `fn` and computes the gradient of the result wrt `args_list`... | [
"def",
"maybe_call_fn_and_grads",
"(",
"fn",
",",
"fn_arg_list",
",",
"result",
"=",
"None",
",",
"grads",
"=",
"None",
",",
"check_non_none_grads",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope... | 52.75 | 15.208333 |
def _not(cls, operation):
"""not operation"""
def _wrap(*args, **kwargs):
return not operation(*args, **kwargs)
return _wrap | [
"def",
"_not",
"(",
"cls",
",",
"operation",
")",
":",
"def",
"_wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"not",
"operation",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrap"
] | 22.285714 | 18.428571 |
def plot_eq(fignum, DIblock, s):
"""
plots directions on eqarea projection
Parameters
__________
fignum : matplotlib figure number
DIblock : nested list of dec/inc pairs
s : specimen name
"""
# make the stereonet
plt.figure(num=fignum)
if len(DIblock) < 1:
return
# pl... | [
"def",
"plot_eq",
"(",
"fignum",
",",
"DIblock",
",",
"s",
")",
":",
"# make the stereonet",
"plt",
".",
"figure",
"(",
"num",
"=",
"fignum",
")",
"if",
"len",
"(",
"DIblock",
")",
"<",
"1",
":",
"return",
"# plt.clf()",
"if",
"not",
"isServer",
":",
... | 22.166667 | 16.083333 |
def get_chunks(sequence, chunk_size):
"""Split sequence into chunks.
:param list sequence:
:param int chunk_size:
"""
return [
sequence[idx:idx + chunk_size]
for idx in range(0, len(sequence), chunk_size)
] | [
"def",
"get_chunks",
"(",
"sequence",
",",
"chunk_size",
")",
":",
"return",
"[",
"sequence",
"[",
"idx",
":",
"idx",
"+",
"chunk_size",
"]",
"for",
"idx",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"sequence",
")",
",",
"chunk_size",
")",
"]"
] | 23.8 | 15.1 |
def _sample(self, position, trajectory_length, stepsize, lsteps=None):
"""
Runs a single sampling iteration to return a sample
"""
# Resampling momentum
momentum = np.reshape(np.random.normal(0, 1, len(position)), position.shape)
# position_m here will be the previous sa... | [
"def",
"_sample",
"(",
"self",
",",
"position",
",",
"trajectory_length",
",",
"stepsize",
",",
"lsteps",
"=",
"None",
")",
":",
"# Resampling momentum",
"momentum",
"=",
"np",
".",
"reshape",
"(",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"1",
... | 40.53125 | 25.40625 |
def _hugoniot_p(self, v):
"""
calculate static pressure at 300 K.
:param v: unit-cell volume in A^3
:return: static pressure at t_ref (=300 K) in GPa
"""
rho = self._get_rho(v)
params = self._set_params(self.params_hugoniot)
if self.nonlinear:
... | [
"def",
"_hugoniot_p",
"(",
"self",
",",
"v",
")",
":",
"rho",
"=",
"self",
".",
"_get_rho",
"(",
"v",
")",
"params",
"=",
"self",
".",
"_set_params",
"(",
"self",
".",
"params_hugoniot",
")",
"if",
"self",
".",
"nonlinear",
":",
"return",
"hugoniot_p_n... | 31 | 11.769231 |
def load_and_preprocess_imdb_data(n_gram=None):
"""Load IMDb data and augment with hashed n-gram features."""
X_train, y_train, X_test, y_test = tl.files.load_imdb_dataset(nb_words=VOCAB_SIZE)
if n_gram is not None:
X_train = np.array([augment_with_ngrams(x, VOCAB_SIZE, N_BUCKETS, n=n_gram) for x i... | [
"def",
"load_and_preprocess_imdb_data",
"(",
"n_gram",
"=",
"None",
")",
":",
"X_train",
",",
"y_train",
",",
"X_test",
",",
"y_test",
"=",
"tl",
".",
"files",
".",
"load_imdb_dataset",
"(",
"nb_words",
"=",
"VOCAB_SIZE",
")",
"if",
"n_gram",
"is",
"not",
... | 52.111111 | 30.222222 |
def get_by_uri(self, uri):
'''Get a concept or collection by its uri.
Returns a single concept or collection if one exists with this uri.
Returns False otherwise.
:param string uri: The uri to find a concept or collection for.
:raises ValueError: The uri is invalid.
:rt... | [
"def",
"get_by_uri",
"(",
"self",
",",
"uri",
")",
":",
"if",
"not",
"is_uri",
"(",
"uri",
")",
":",
"raise",
"ValueError",
"(",
"'%s is not a valid URI.'",
"%",
"uri",
")",
"# Check if there's a provider that's more likely to have the URI",
"csuris",
"=",
"[",
"c... | 38.36 | 20.12 |
def get_links_of_type(self, s_type=''):
"""Return the `s_type` satellite list (eg. schedulers)
If s_type is None, returns a dictionary of all satellites, else returns the dictionary
of the s_type satellites
The returned dict is indexed with the satellites uuid.
:param s_type: ... | [
"def",
"get_links_of_type",
"(",
"self",
",",
"s_type",
"=",
"''",
")",
":",
"satellites",
"=",
"{",
"'arbiter'",
":",
"getattr",
"(",
"self",
",",
"'arbiters'",
",",
"[",
"]",
")",
",",
"'scheduler'",
":",
"getattr",
"(",
"self",
",",
"'schedulers'",
... | 35.545455 | 16.909091 |
def resolve(self, current_file, rel_path):
"""Search the filesystem."""
p = path.join(path.dirname(current_file), rel_path)
if p not in self.file_dict:
raise RuntimeError('No such fake file: %r' % p)
return p, p | [
"def",
"resolve",
"(",
"self",
",",
"current_file",
",",
"rel_path",
")",
":",
"p",
"=",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"current_file",
")",
",",
"rel_path",
")",
"if",
"p",
"not",
"in",
"self",
".",
"file_dict",
":",
"raise",... | 38 | 10.666667 |
def simPrepare(unit: Unit, modelCls: Optional[SimModel]=None,
targetPlatform=DummyPlatform(),
dumpModelIn: str=None, onAfterToRtl=None):
"""
Create simulation model and connect it with interfaces of original unit
and decorate it with agents
:param unit: interface level uni... | [
"def",
"simPrepare",
"(",
"unit",
":",
"Unit",
",",
"modelCls",
":",
"Optional",
"[",
"SimModel",
"]",
"=",
"None",
",",
"targetPlatform",
"=",
"DummyPlatform",
"(",
")",
",",
"dumpModelIn",
":",
"str",
"=",
"None",
",",
"onAfterToRtl",
"=",
"None",
")",... | 37.828571 | 19.257143 |
def collect_variables(self, selections) -> None:
"""Apply method |ChangeItem.collect_variables| of the base class
|ChangeItem| and also apply method |ExchangeItem.insert_variables|
of class |ExchangeItem| to collect the relevant base variables
handled by the devices of the given |Selecti... | [
"def",
"collect_variables",
"(",
"self",
",",
"selections",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"collect_variables",
"(",
"selections",
")",
"self",
".",
"insert_variables",
"(",
"self",
".",
"device2base",
",",
"self",
".",
"basespecs",
",",
"... | 43.592593 | 18.962963 |
def get_info(df, group, info=['mean', 'std']):
"""
Aggregate mean and std with the given group.
"""
agg = df.groupby(group).agg(info)
agg.columns = agg.columns.droplevel(0)
return agg | [
"def",
"get_info",
"(",
"df",
",",
"group",
",",
"info",
"=",
"[",
"'mean'",
",",
"'std'",
"]",
")",
":",
"agg",
"=",
"df",
".",
"groupby",
"(",
"group",
")",
".",
"agg",
"(",
"info",
")",
"agg",
".",
"columns",
"=",
"agg",
".",
"columns",
".",... | 28.714286 | 6.428571 |
def _default_handlers(self):
""" Generate the handlers for this site """
static_path = os.path.abspath(os.path.join(os.path.dirname(__file__),"static"))
urls = [
(r"/static/(.*)", cyclone.web.StaticFileHandler, {"path": static_path}),
]
for p in self.pages:
... | [
"def",
"_default_handlers",
"(",
"self",
")",
":",
"static_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"static\"",
")",
")",
"urls",
"=",
"... | 38.083333 | 18.833333 |
def pubsub_pub(self, topic, payload, **kwargs):
"""Publish a message to a given pubsub topic
Publishing will publish the given payload (string) to
everyone currently subscribed to the given topic.
All data (including the id of the publisher) is automatically
base64 encoded when... | [
"def",
"pubsub_pub",
"(",
"self",
",",
"topic",
",",
"payload",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"topic",
",",
"payload",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/pubsub/pub'",
",",
"args",
",",
"decoder",
"=... | 30.107143 | 20.857143 |
def authenticate(api_key, api_url, **kwargs):
"""Returns a muddle instance, with API key and url set for requests."""
muddle = Muddle(**kwargs)
# Login.
muddle.authenticate(api_key, api_url)
return muddle | [
"def",
"authenticate",
"(",
"api_key",
",",
"api_url",
",",
"*",
"*",
"kwargs",
")",
":",
"muddle",
"=",
"Muddle",
"(",
"*",
"*",
"kwargs",
")",
"# Login.",
"muddle",
".",
"authenticate",
"(",
"api_key",
",",
"api_url",
")",
"return",
"muddle"
] | 27.375 | 18.5 |
def default_job_name(self):
"""Slurm job name if not already specified
in the `sbatch` section"""
name = ''
if not self.root.existing_campaign:
campaign_file = osp.basename(self.root.campaign_file)
campaign = osp.splitext(campaign_file)[0]
name += camp... | [
"def",
"default_job_name",
"(",
"self",
")",
":",
"name",
"=",
"''",
"if",
"not",
"self",
".",
"root",
".",
"existing_campaign",
":",
"campaign_file",
"=",
"osp",
".",
"basename",
"(",
"self",
".",
"root",
".",
"campaign_file",
")",
"campaign",
"=",
"osp... | 36.6 | 12 |
def S(Document, *fields):
"""Generate a MongoDB sort order list using the Django ORM style."""
result = []
for field in fields:
if isinstance(field, tuple): # Unpack existing tuple.
field, direction = field
result.append((field, direction))
continue
direction = ASCENDING
if not field.starts... | [
"def",
"S",
"(",
"Document",
",",
"*",
"fields",
")",
":",
"result",
"=",
"[",
"]",
"for",
"field",
"in",
"fields",
":",
"if",
"isinstance",
"(",
"field",
",",
"tuple",
")",
":",
"# Unpack existing tuple.",
"field",
",",
"direction",
"=",
"field",
"res... | 21.481481 | 23 |
def to_task(self):
"""Return a task object representing this async job."""
from google.appengine.api.taskqueue import Task
from google.appengine.api.taskqueue import TaskRetryOptions
self._increment_recursion_level()
self.check_recursion_depth()
url = "%s/%s" % (ASYNC_E... | [
"def",
"to_task",
"(",
"self",
")",
":",
"from",
"google",
".",
"appengine",
".",
"api",
".",
"taskqueue",
"import",
"Task",
"from",
"google",
".",
"appengine",
".",
"api",
".",
"taskqueue",
"import",
"TaskRetryOptions",
"self",
".",
"_increment_recursion_leve... | 34.478261 | 21.043478 |
def get_cdk_stacks(module_path, env_vars, context_opts):
"""Return list of CDK stacks."""
LOGGER.debug('Listing stacks in the CDK app prior to '
'diff')
return subprocess.check_output(
generate_node_command(
command='cdk',
command_opts=['list'] + context_opts... | [
"def",
"get_cdk_stacks",
"(",
"module_path",
",",
"env_vars",
",",
"context_opts",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Listing stacks in the CDK app prior to '",
"'diff'",
")",
"return",
"subprocess",
".",
"check_output",
"(",
"generate_node_command",
"(",
"comma... | 35.363636 | 12.090909 |
def get_estimates(estimators_tuple, positions, num_workers=1):
"""
Estimates densities, and probabilities for paragraph positions.
Parameters
----------
estimators_tuple : (float, KernelDensity, KernelDensity)
An estimate of the prior probability P(relevant), an estimator of the prior densi... | [
"def",
"get_estimates",
"(",
"estimators_tuple",
",",
"positions",
",",
"num_workers",
"=",
"1",
")",
":",
"estimators",
"=",
"dict",
"(",
")",
"estimators",
"[",
"\"P(relevant)\"",
"]",
",",
"estimators",
"[",
"\"p(position)\"",
"]",
",",
"estimators",
"[",
... | 49.547619 | 26.02381 |
def bruteforce(users, domain, password, host):
"""
Performs a bruteforce for the given users, password, domain on the given host.
"""
cs = CredentialSearch(use_pipe=False)
print_notification("Connecting to {}".format(host))
s = Server(host)
c = Connection(s)
for user in users:
... | [
"def",
"bruteforce",
"(",
"users",
",",
"domain",
",",
"password",
",",
"host",
")",
":",
"cs",
"=",
"CredentialSearch",
"(",
"use_pipe",
"=",
"False",
")",
"print_notification",
"(",
"\"Connecting to {}\"",
".",
"format",
"(",
"host",
")",
")",
"s",
"=",
... | 40.37037 | 24.888889 |
def geo_distance_range(cls, field, center, from_distance, to_distance, distance_type=None):
'''
http://www.elasticsearch.org/guide/reference/query-dsl/geo-distance-range-filter.html
Filters documents that exists within a range from a specific point
'''
instance = cls(geo_distan... | [
"def",
"geo_distance_range",
"(",
"cls",
",",
"field",
",",
"center",
",",
"from_distance",
",",
"to_distance",
",",
"distance_type",
"=",
"None",
")",
":",
"instance",
"=",
"cls",
"(",
"geo_distance_range",
"=",
"{",
"'from'",
":",
"from_distance",
",",
"'t... | 46.818182 | 35.545455 |
def set_ram(self, ram):
"""
Set the RAM amount for the GNS3 VM.
:param ram: amount of memory
"""
yield from self._execute("modifyvm", [self._vmname, "--memory", str(ram)], timeout=3)
log.info("GNS3 VM RAM amount set to {}".format(ram)) | [
"def",
"set_ram",
"(",
"self",
",",
"ram",
")",
":",
"yield",
"from",
"self",
".",
"_execute",
"(",
"\"modifyvm\"",
",",
"[",
"self",
".",
"_vmname",
",",
"\"--memory\"",
",",
"str",
"(",
"ram",
")",
"]",
",",
"timeout",
"=",
"3",
")",
"log",
".",
... | 30.777778 | 19.666667 |
def enqueue(self, message, *, delay=None):
"""Enqueue a message.
Parameters:
message(Message): The message to enqueue.
delay(int): The minimum amount of time, in milliseconds, to
delay the message by. Must be less than 7 days.
Raises:
ValueError: If `... | [
"def",
"enqueue",
"(",
"self",
",",
"message",
",",
"*",
",",
"delay",
"=",
"None",
")",
":",
"queue_name",
"=",
"message",
".",
"queue_name",
"# Each enqueued message must have a unique id in Redis so",
"# using the Message's id isn't safe because messages may be",
"# retr... | 35.314286 | 19.314286 |
async def verify_proof(self, proof_req: dict, proof: dict) -> str:
"""
Verify proof as Verifier. Raise AbsentRevReg if a proof cites a revocation registry
that does not exist on the distributed ledger.
:param proof_req: proof request as Verifier creates, as per proof_req_json above
... | [
"async",
"def",
"verify_proof",
"(",
"self",
",",
"proof_req",
":",
"dict",
",",
"proof",
":",
"dict",
")",
"->",
"str",
":",
"LOGGER",
".",
"debug",
"(",
"'Verifier.verify_proof >>> proof_req: %s, proof: %s'",
",",
"proof_req",
",",
"proof",
")",
"if",
"not",... | 44.471264 | 21.689655 |
def which(program):
"""
returns the path to an executable or None if it can't be found
"""
def is_exe(_fpath):
return os.path.isfile(_fpath) and os.access(_fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
... | [
"def",
"which",
"(",
"program",
")",
":",
"def",
"is_exe",
"(",
"_fpath",
")",
":",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"_fpath",
")",
"and",
"os",
".",
"access",
"(",
"_fpath",
",",
"os",
".",
"X_OK",
")",
"fpath",
",",
"fname",
"="... | 28.882353 | 16.882353 |
def Add(self, request, callback=None):
"""Add a new request.
Args:
request: A http_wrapper.Request to add to the batch.
callback: A callback to be called for this response, of the
form callback(response, exception). The first parameter is the
deserialized... | [
"def",
"Add",
"(",
"self",
",",
"request",
",",
"callback",
"=",
"None",
")",
":",
"handler",
"=",
"RequestResponseAndHandler",
"(",
"request",
",",
"None",
",",
"callback",
")",
"self",
".",
"__request_response_handlers",
"[",
"self",
".",
"_NewId",
"(",
... | 40.647059 | 23.705882 |
def put(self, key, value):
"""
>>> c = MemSizeLRUCache(maxmem=24*4)
>>> c.put(1, 1)
>>> c.mem() # 24-bytes per integer
24
>>> c.put(2, 2)
>>> c.put(3, 3)
>>> c.put(4, 4)
>>> c.get(1)
1
>>> c.mem()
96
>>> c.size()
... | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"mem",
"=",
"sys",
".",
"getsizeof",
"(",
"value",
")",
"if",
"self",
".",
"_mem",
"+",
"mem",
">",
"self",
".",
"_maxmem",
":",
"self",
".",
"delete",
"(",
"self",
".",
"last",
"("... | 23.285714 | 15.714286 |
def sci(x, precision=2, base=10, exp_only=False):
"""
Convert the given floating point number into scientific notation, using
unicode superscript characters to nicely render the exponent.
"""
# Handle the corner cases of zero and non-finite numbers, which can't be
# represented using scientif... | [
"def",
"sci",
"(",
"x",
",",
"precision",
"=",
"2",
",",
"base",
"=",
"10",
",",
"exp_only",
"=",
"False",
")",
":",
"# Handle the corner cases of zero and non-finite numbers, which can't be ",
"# represented using scientific notation.",
"if",
"x",
"==",
"0",
"or",
... | 37.814815 | 22.407407 |
def _generate_base_namespace_module(self, api, namespace):
"""Creates a module for the namespace. All data types and routes are
represented as Python classes."""
self.cur_namespace = namespace
generate_module_header(self)
if namespace.doc is not None:
self.emit('"""... | [
"def",
"_generate_base_namespace_module",
"(",
"self",
",",
"api",
",",
"namespace",
")",
":",
"self",
".",
"cur_namespace",
"=",
"namespace",
"generate_module_header",
"(",
"self",
")",
"if",
"namespace",
".",
"doc",
"is",
"not",
"None",
":",
"self",
".",
"... | 42.06383 | 19.191489 |
def non_tag_chars_from_raw(html):
'''generator that yields clean visible as it transitions through
states in the raw `html`
'''
n = 0
while n < len(html):
# find start of tag
angle = html.find('<', n)
if angle == -1:
yield html[n:]
n = len(html)
... | [
"def",
"non_tag_chars_from_raw",
"(",
"html",
")",
":",
"n",
"=",
"0",
"while",
"n",
"<",
"len",
"(",
"html",
")",
":",
"# find start of tag",
"angle",
"=",
"html",
".",
"find",
"(",
"'<'",
",",
"n",
")",
"if",
"angle",
"==",
"-",
"1",
":",
"yield"... | 39.362069 | 13.258621 |
def hooi(X, rank, **kwargs):
"""
Compute Tucker decomposition of a tensor using Higher-Order Orthogonal
Iterations.
Parameters
----------
X : tensor_mixin
The tensor to be decomposed
rank : array_like
The rank of the decomposition for each mode of the tensor.
The len... | [
"def",
"hooi",
"(",
"X",
",",
"rank",
",",
"*",
"*",
"kwargs",
")",
":",
"# init options",
"ainit",
"=",
"kwargs",
".",
"pop",
"(",
"'init'",
",",
"__DEF_INIT",
")",
"maxIter",
"=",
"kwargs",
".",
"pop",
"(",
"'maxIter'",
",",
"__DEF_MAXITER",
")",
"... | 29.795455 | 21.340909 |
def save(self, doc):
"""Save a doc to cache
"""
self.log.debug('save()')
self.docs.append(doc)
self.commit() | [
"def",
"save",
"(",
"self",
",",
"doc",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'save()'",
")",
"self",
".",
"docs",
".",
"append",
"(",
"doc",
")",
"self",
".",
"commit",
"(",
")"
] | 23.833333 | 9.666667 |
def _compute_nfps_uniform(cum_counts, sizes):
"""Computes the matrix of expected false positives for all possible
sub-intervals of the complete domain of set sizes, assuming uniform
distribution of set_sizes within each sub-intervals.
Args:
cum_counts: the complete cummulative distribution of s... | [
"def",
"_compute_nfps_uniform",
"(",
"cum_counts",
",",
"sizes",
")",
":",
"nfps",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"sizes",
")",
",",
"len",
"(",
"sizes",
")",
")",
")",
"# All u an l are inclusive bounds for intervals.",
"# Compute p = 1, the NFP... | 40.8 | 19.2 |
def set_value(self, name, value):
"""Set value for a variable"""
value = to_text_string(value)
code = u"get_ipython().kernel.set_value('%s', %s, %s)" % (name, value,
PY2)
if self._reading:
self.kernel_client.i... | [
"def",
"set_value",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"value",
"=",
"to_text_string",
"(",
"value",
")",
"code",
"=",
"u\"get_ipython().kernel.set_value('%s', %s, %s)\"",
"%",
"(",
"name",
",",
"value",
",",
"PY2",
")",
"if",
"self",
".",
"... | 38 | 17.2 |
def saveSnapshot(self):
'''
Saves the current shanpshot to the specified file.
Current snapshot is the image being displayed on the main window.
'''
filename = self.snapshotDir + os.sep + '${serialno}-${focusedwindowname}-${timestamp}' + '.' + self.snapshotFormat.lower()
... | [
"def",
"saveSnapshot",
"(",
"self",
")",
":",
"filename",
"=",
"self",
".",
"snapshotDir",
"+",
"os",
".",
"sep",
"+",
"'${serialno}-${focusedwindowname}-${timestamp}'",
"+",
"'.'",
"+",
"self",
".",
"snapshotFormat",
".",
"lower",
"(",
")",
"# We have the snaps... | 59.882353 | 35.058824 |
def zoom_blur(x, severity=1):
"""Zoom blurring to images.
Applying zoom blurring to images by zooming the central part of the images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 ... | [
"def",
"zoom_blur",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"np",
".",
"arange",
"(",
"1",
",",
"1.11",
",",
"0.01",
")",
",",
"np",
".",
"arange",
"(",
"1",
",",
"1.16",
",",
"0.01",
")",
",",
"np",
".",
"arange",
"("... | 29.153846 | 18.076923 |
def list_deployments(jboss_config):
'''
List all deployments on the jboss instance
jboss_config
Configuration dictionary with properties specified above.
CLI Example:
.. code-block:: bash
salt '*' jboss7.list_deployments '{"cli_path": "integration.modules.sysmod.SysModuleTest.... | [
"def",
"list_deployments",
"(",
"jboss_config",
")",
":",
"log",
".",
"debug",
"(",
"\"======================== MODULE FUNCTION: jboss7.list_deployments\"",
")",
"command_result",
"=",
"__salt__",
"[",
"'jboss7_cli.run_command'",
"]",
"(",
"jboss_config",
",",
"'deploy'",
... | 36.47619 | 32.285714 |
def _getitem_normalized(self, index):
"""Builds the more compact fmtstrs by using fromstr( of the control sequences)"""
index = normalize_slice(len(self), index)
counter = 0
output = ''
for fs in self.chunks:
if index.start < counter + len(fs) and index.stop > counter... | [
"def",
"_getitem_normalized",
"(",
"self",
",",
"index",
")",
":",
"index",
"=",
"normalize_slice",
"(",
"len",
"(",
"self",
")",
",",
"index",
")",
"counter",
"=",
"0",
"output",
"=",
"''",
"for",
"fs",
"in",
"self",
".",
"chunks",
":",
"if",
"index... | 42.785714 | 14.714286 |
def append(self, record):
"""
Adds the passed +record+ to satisfy the query. Only intended to be
used in conjunction with associations (i.e. do not use if self.record
is None).
Intended use case (DO THIS):
post.comments.append(comment)
NOT THIS:
Query(... | [
"def",
"append",
"(",
"self",
",",
"record",
")",
":",
"if",
"self",
".",
"record",
":",
"self",
".",
"_validate_record",
"(",
"record",
")",
"if",
"self",
".",
"join_args",
":",
"# As always, the related record is created when the primary",
"# record is saved",
"... | 46.36 | 21.72 |
def stop(self, precision=0):
""" Stops the timer, adds it as an interval to :prop:intervals
@precision: #int number of decimal places to round to
-> #str formatted interval time
"""
self._stop = time.perf_counter()
return self.add_interval(precision) | [
"def",
"stop",
"(",
"self",
",",
"precision",
"=",
"0",
")",
":",
"self",
".",
"_stop",
"=",
"time",
".",
"perf_counter",
"(",
")",
"return",
"self",
".",
"add_interval",
"(",
"precision",
")"
] | 37.5 | 10.375 |
def getskyimg(self,chip):
"""
Notes
=====
Return an array representing the sky image for the detector. The value
of the sky is what would actually be subtracted from the exposure by
the skysub step.
:units: electrons
"""
sci_chip = self._image[s... | [
"def",
"getskyimg",
"(",
"self",
",",
"chip",
")",
":",
"sci_chip",
"=",
"self",
".",
"_image",
"[",
"self",
".",
"scienceExt",
",",
"chip",
"]",
"return",
"np",
".",
"ones",
"(",
"sci_chip",
".",
"image_shape",
",",
"dtype",
"=",
"sci_chip",
".",
"i... | 32.538462 | 24.692308 |
def sorted_errors(self):
"""
Generator for (rank, name, MSE, MAE) sorted by increasing MAE
"""
for i, (name, mae) in enumerate(
sorted(self.mae_dict.items(), key=lambda x: x[1])):
yield(i + 1, name, self.mse_dict[name], self.mae_dict[name],) | [
"def",
"sorted_errors",
"(",
"self",
")",
":",
"for",
"i",
",",
"(",
"name",
",",
"mae",
")",
"in",
"enumerate",
"(",
"sorted",
"(",
"self",
".",
"mae_dict",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
")",
... | 42.142857 | 15 |
def image_to_pdf_or_hocr(image,
lang=None,
config='',
nice=0,
extension='pdf'):
'''
Returns the result of a Tesseract OCR run on the provided image to pdf/hocr
'''
if extension not in {'pdf', 'hocr'}:
raise ValueErr... | [
"def",
"image_to_pdf_or_hocr",
"(",
"image",
",",
"lang",
"=",
"None",
",",
"config",
"=",
"''",
",",
"nice",
"=",
"0",
",",
"extension",
"=",
"'pdf'",
")",
":",
"if",
"extension",
"not",
"in",
"{",
"'pdf'",
",",
"'hocr'",
"}",
":",
"raise",
"ValueEr... | 32.142857 | 20 |
def execute_command(self):
"""
The run command implements the web content extractor corresponding to the given \
configuration file.
The execute_command() validates the input project name and opens the JSON \
configuration file. The run() method handles the execution of the ext... | [
"def",
"execute_command",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"args",
"[",
"'--verbosity'",
"]",
"=",
"int",
"(",
"self",
".",
"args",
"[",
"'--verbosity'",
"]",
")",
"if",
"self",
".",
"args",
"[",
"'--verbosity'",
"]",
"not",
"in",
"[",... | 48.173913 | 27.608696 |
def disconnect(self, frame):
"""
Handles the DISCONNECT command: Unbinds the connection.
Clients are supposed to send this command, but in practice it should not be
relied upon.
"""
self.engine.log.debug("Disconnect")
self.engine.unbind() | [
"def",
"disconnect",
"(",
"self",
",",
"frame",
")",
":",
"self",
".",
"engine",
".",
"log",
".",
"debug",
"(",
"\"Disconnect\"",
")",
"self",
".",
"engine",
".",
"unbind",
"(",
")"
] | 31.888889 | 17 |
def fasta_from_biom(table, fasta_file_name):
'''Save sequences from a biom table to a fasta file
Parameters
----------
table : biom.Table
The biom table containing the sequences
fasta_file_name : str
Name of the fasta output file
'''
logger = logging.getLogger(__name__)
... | [
"def",
"fasta_from_biom",
"(",
"table",
",",
"fasta_file_name",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'saving biom table sequences to fasta file %s'",
"%",
"fasta_file_name",
")",
"with",
"open",
... | 35.588235 | 19.235294 |
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidProgressBar, self).init_widget()
d = self.declaration
self.set_indeterminate(self.indeterminate)
if not self.indeterminate:
if d.max:
self.set_max(d.max)
... | [
"def",
"init_widget",
"(",
"self",
")",
":",
"super",
"(",
"AndroidProgressBar",
",",
"self",
")",
".",
"init_widget",
"(",
")",
"d",
"=",
"self",
".",
"declaration",
"self",
".",
"set_indeterminate",
"(",
"self",
".",
"indeterminate",
")",
"if",
"not",
... | 27.611111 | 16.5 |
def _remove_nulls(managed_clusters):
"""
Remove some often-empty fields from a list of ManagedClusters, so the JSON representation
doesn't contain distracting null fields.
This works around a quirk of the SDK for python behavior. These fields are not sent
by the server, but get recreated by the CLI... | [
"def",
"_remove_nulls",
"(",
"managed_clusters",
")",
":",
"attrs",
"=",
"[",
"'tags'",
"]",
"ap_attrs",
"=",
"[",
"'os_disk_size_gb'",
",",
"'vnet_subnet_id'",
"]",
"sp_attrs",
"=",
"[",
"'secret'",
"]",
"for",
"managed_cluster",
"in",
"managed_clusters",
":",
... | 45.130435 | 18.782609 |
def get_exception():
"""Return full formatted traceback as a string."""
trace = ""
exception = ""
exc_list = traceback.format_exception_only(
sys.exc_info()[0], sys.exc_info()[1]
)
for entry in exc_list:
exception += entry
tb_list = traceback.format_tb(sys.exc_info()[2])
... | [
"def",
"get_exception",
"(",
")",
":",
"trace",
"=",
"\"\"",
"exception",
"=",
"\"\"",
"exc_list",
"=",
"traceback",
".",
"format_exception_only",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"0",
"]",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
... | 30.230769 | 14.384615 |
def get(self, key, mem_map=True):
"""
Read and return the data stored for the given key.
Args:
key (str): The key to read the data from.
mem_map (bool): If ``True`` returns the data as
memory-mapped array, otherwise a copy is returned.
... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"mem_map",
"=",
"True",
")",
":",
"self",
".",
"raise_error_if_not_open",
"(",
")",
"if",
"key",
"in",
"self",
".",
"_file",
":",
"data",
"=",
"self",
".",
"_file",
"[",
"key",
"]",
"if",
"not",
"mem_map"... | 25.384615 | 20.461538 |
def merge(a, b):
"""Merge two ranges with step == 1.
Parameters
----------
a : range
The first range.
b : range
The second range.
"""
_check_steps(a, b)
return range(min(a.start, b.start), max(a.stop, b.stop)) | [
"def",
"merge",
"(",
"a",
",",
"b",
")",
":",
"_check_steps",
"(",
"a",
",",
"b",
")",
"return",
"range",
"(",
"min",
"(",
"a",
".",
"start",
",",
"b",
".",
"start",
")",
",",
"max",
"(",
"a",
".",
"stop",
",",
"b",
".",
"stop",
")",
")"
] | 20.583333 | 19.916667 |
def addSubsequenceOfFeature(self, parentid):
"""
This will add reciprocal triples like:
feature <is subsequence of> parent
parent has_subsequence feature
:param graph:
:param parentid:
:return:
"""
self.graph.addTriple(self.fid, self.globaltt['is... | [
"def",
"addSubsequenceOfFeature",
"(",
"self",
",",
"parentid",
")",
":",
"self",
".",
"graph",
".",
"addTriple",
"(",
"self",
".",
"fid",
",",
"self",
".",
"globaltt",
"[",
"'is subsequence of'",
"]",
",",
"parentid",
")",
"# this should be expected to be done ... | 31.125 | 20.625 |
def subtype_ids(elements, subtype):
"""
returns the ids of all elements of a list that have a certain type,
e.g. show all the nodes that are ``TokenNode``\s.
"""
return [i for (i, element) in enumerate(elements)
if isinstance(element, subtype)] | [
"def",
"subtype_ids",
"(",
"elements",
",",
"subtype",
")",
":",
"return",
"[",
"i",
"for",
"(",
"i",
",",
"element",
")",
"in",
"enumerate",
"(",
"elements",
")",
"if",
"isinstance",
"(",
"element",
",",
"subtype",
")",
"]"
] | 38.571429 | 9.428571 |
def rgb_percent_to_name(rgb_percent_triplet, spec=u'css3'):
"""
Convert a 3-tuple of percentages, suitable for use in an ``rgb()``
color triplet, to its corresponding normalized color name, if any
such name exists.
The optional keyword argument ``spec`` determines which
specification's list of ... | [
"def",
"rgb_percent_to_name",
"(",
"rgb_percent_triplet",
",",
"spec",
"=",
"u'css3'",
")",
":",
"return",
"rgb_to_name",
"(",
"rgb_percent_to_rgb",
"(",
"normalize_percent_triplet",
"(",
"rgb_percent_triplet",
")",
")",
",",
"spec",
"=",
"spec",
")"
] | 30.409091 | 22.318182 |
def _transfer_data(self, remote_path, data):
"""
Used by the base _execute_module(), and in <2.4 also by the template
action module, and probably others.
"""
if isinstance(data, dict):
data = jsonify(data)
if not isinstance(data, bytes):
data = to_... | [
"def",
"_transfer_data",
"(",
"self",
",",
"remote_path",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"data",
"=",
"jsonify",
"(",
"data",
")",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"data",... | 38.428571 | 12.428571 |
def update_event(self, id, **kwargs): # noqa: E501
"""Update a specific event # noqa: E501
The following fields are readonly and will be ignored when passed in the request: <code>id</code>, <code>isEphemeral</code>, <code>isUserEvent</code>, <code>runningState</code>, <code>canDelete</code>, <code>ca... | [
"def",
"update_event",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"update_event_wi... | 72.272727 | 47.318182 |
def search_list(kb, value=None, match_type=None,
page=None, per_page=None, unique=False):
"""Search "mappings to" for knowledge."""
# init
page = page or 1
per_page = per_page or 10
if kb.kbtype == models.KnwKB.KNWKB_TYPES['written_as']:
# get the... | [
"def",
"search_list",
"(",
"kb",
",",
"value",
"=",
"None",
",",
"match_type",
"=",
"None",
",",
"page",
"=",
"None",
",",
"per_page",
"=",
"None",
",",
"unique",
"=",
"False",
")",
":",
"# init",
"page",
"=",
"page",
"or",
"1",
"per_page",
"=",
"p... | 39.2 | 11.5 |
def process_msg(self, msg):
"""Process messages from the event stream."""
jmsg = json.loads(msg)
msgtype = jmsg['MessageType']
msgdata = jmsg['Data']
_LOGGER.debug('New websocket message recieved of type: %s', msgtype)
if msgtype == 'Sessions':
self._sessions... | [
"def",
"process_msg",
"(",
"self",
",",
"msg",
")",
":",
"jmsg",
"=",
"json",
".",
"loads",
"(",
"msg",
")",
"msgtype",
"=",
"jmsg",
"[",
"'MessageType'",
"]",
"msgdata",
"=",
"jmsg",
"[",
"'Data'",
"]",
"_LOGGER",
".",
"debug",
"(",
"'New websocket me... | 33.777778 | 12.388889 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.