text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def convert_softmax(net, node, module, builder):
"""Convert a softmax layer from mxnet to coreml.
Parameters
----------
network: net
A mxnet network object.
layer: node
Node to convert.
module: module
An module for MXNet
builder: NeuralNetworkBuilder
A neu... | [
"def",
"convert_softmax",
"(",
"net",
",",
"node",
",",
"module",
",",
"builder",
")",
":",
"input_name",
",",
"output_name",
"=",
"_get_input_output_name",
"(",
"net",
",",
"node",
")",
"name",
"=",
"node",
"[",
"'name'",
"]",
"builder",
".",
"add_softmax... | 25.136364 | 18 |
def update_screen(self):
"""Refresh the screen. You don't need to override this except to update only small portins of the screen."""
self.clock.tick(self.FPS)
pygame.display.update() | [
"def",
"update_screen",
"(",
"self",
")",
":",
"self",
".",
"clock",
".",
"tick",
"(",
"self",
".",
"FPS",
")",
"pygame",
".",
"display",
".",
"update",
"(",
")"
] | 51 | 8 |
def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
incremental_update
/content_view_versions/incremental_update
promote
/content_view_versions/<id>/promote
``su... | [
"def",
"path",
"(",
"self",
",",
"which",
"=",
"None",
")",
":",
"if",
"which",
"in",
"(",
"'incremental_update'",
",",
"'promote'",
")",
":",
"prefix",
"=",
"'base'",
"if",
"which",
"==",
"'incremental_update'",
"else",
"'self'",
"return",
"'{0}/{1}'",
".... | 33.1 | 20.15 |
def cross_v2(vec1, vec2):
"""Return the crossproduct of the two vectors as a Vec2.
Cross product doesn't really make sense in 2D, but return the Z component
of the 3d result.
"""
return vec1.y * vec2.x - vec1.x * vec2.y | [
"def",
"cross_v2",
"(",
"vec1",
",",
"vec2",
")",
":",
"return",
"vec1",
".",
"y",
"*",
"vec2",
".",
"x",
"-",
"vec1",
".",
"x",
"*",
"vec2",
".",
"y"
] | 33.428571 | 16.428571 |
def _init_map(self, record_types=None, **kwargs):
"""Initialize form map"""
osid_objects.OsidObjectForm._init_map(self, record_types=record_types)
self._my_map['assignedAgencyIds'] = [str(kwargs['agency_id'])] | [
"def",
"_init_map",
"(",
"self",
",",
"record_types",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"osid_objects",
".",
"OsidObjectForm",
".",
"_init_map",
"(",
"self",
",",
"record_types",
"=",
"record_types",
")",
"self",
".",
"_my_map",
"[",
"'assign... | 57.5 | 19.25 |
def blockingSave(self, path):
"""
saved session to file - returns after finish
only called by interactiveTutorial-save at the moment
"""
self.tmp_dir_save_session = self.tmp_dir_session.join('block').mkdir()
state = {'session': dict(self.opts),
'di... | [
"def",
"blockingSave",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"tmp_dir_save_session",
"=",
"self",
".",
"tmp_dir_session",
".",
"join",
"(",
"'block'",
")",
".",
"mkdir",
"(",
")",
"state",
"=",
"{",
"'session'",
":",
"dict",
"(",
"self",
"."... | 43.636364 | 14 |
def use_any_adapter(self, use_any_adapter):
"""
Allows GNS3 to use any VMware adapter on this instance.
:param use_any_adapter: boolean
"""
if use_any_adapter:
log.info("VMware VM '{name}' [{id}] is allowed to use any adapter".format(name=self.name, id=self.id))
... | [
"def",
"use_any_adapter",
"(",
"self",
",",
"use_any_adapter",
")",
":",
"if",
"use_any_adapter",
":",
"log",
".",
"info",
"(",
"\"VMware VM '{name}' [{id}] is allowed to use any adapter\"",
".",
"format",
"(",
"name",
"=",
"self",
".",
"name",
",",
"id",
"=",
"... | 40.5 | 25.5 |
def shortened_character_name(self_or_cls, c, eliminations=[], substitutions={}, transforms=[]):
"""
Given a unicode character c, return the shortened unicode name
(as a list of tokens) by applying the eliminations,
substitutions and transforms.
"""
name = unicodedata.name... | [
"def",
"shortened_character_name",
"(",
"self_or_cls",
",",
"c",
",",
"eliminations",
"=",
"[",
"]",
",",
"substitutions",
"=",
"{",
"}",
",",
"transforms",
"=",
"[",
"]",
")",
":",
"name",
"=",
"unicodedata",
".",
"name",
"(",
"c",
")",
".",
"lower",
... | 41.6875 | 13.0625 |
def on_start(self, host, port, channel, nickname, password):
"""
A WebSocket session has started - create a greenlet to host
the IRC client, and start it.
"""
self.client = WebSocketIRCClient(host, port, channel, nickname,
password, self)
... | [
"def",
"on_start",
"(",
"self",
",",
"host",
",",
"port",
",",
"channel",
",",
"nickname",
",",
"password",
")",
":",
"self",
".",
"client",
"=",
"WebSocketIRCClient",
"(",
"host",
",",
"port",
",",
"channel",
",",
"nickname",
",",
"password",
",",
"se... | 43.75 | 12.5 |
def clone(self, newname, config_path=None, flags=0, bdevtype=None,
bdevdata=None, newsize=0, hookargs=()):
"""
Clone the current container.
"""
args = {}
args['newname'] = newname
args['flags'] = flags
args['newsize'] = newsize
args['hoo... | [
"def",
"clone",
"(",
"self",
",",
"newname",
",",
"config_path",
"=",
"None",
",",
"flags",
"=",
"0",
",",
"bdevtype",
"=",
"None",
",",
"bdevdata",
"=",
"None",
",",
"newsize",
"=",
"0",
",",
"hookargs",
"=",
"(",
")",
")",
":",
"args",
"=",
"{"... | 29.954545 | 13.954545 |
def delete(self, path, data, **options):
"""
Parses DELETE request options and dispatches a request
"""
data, options = self._update_request(data, options)
return self.request('delete', path, data=data, **options) | [
"def",
"delete",
"(",
"self",
",",
"path",
",",
"data",
",",
"*",
"*",
"options",
")",
":",
"data",
",",
"options",
"=",
"self",
".",
"_update_request",
"(",
"data",
",",
"options",
")",
"return",
"self",
".",
"request",
"(",
"'delete'",
",",
"path",... | 41.333333 | 11 |
def _scan(positions):
"""get the region inside the vector with more expression"""
scores = []
for start in range(0, len(positions) - 17, 5):
end = start = 17
scores.add(_enrichment(positions[start:end], positions[:start], positions[end:])) | [
"def",
"_scan",
"(",
"positions",
")",
":",
"scores",
"=",
"[",
"]",
"for",
"start",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"positions",
")",
"-",
"17",
",",
"5",
")",
":",
"end",
"=",
"start",
"=",
"17",
"scores",
".",
"add",
"(",
"_enrichm... | 43.666667 | 19.833333 |
def kwargs_as_assignments(call_node, parent):
"""Yield NoDeclAssign nodes from kwargs in a Call node."""
if not isinstance(call_node, ast.Call):
raise TypeError('node must be an ast.Call')
if len(call_node.args) > 0:
raise ValueError('positional args not allowed')
for keyword in call_n... | [
"def",
"kwargs_as_assignments",
"(",
"call_node",
",",
"parent",
")",
":",
"if",
"not",
"isinstance",
"(",
"call_node",
",",
"ast",
".",
"Call",
")",
":",
"raise",
"TypeError",
"(",
"'node must be an ast.Call'",
")",
"if",
"len",
"(",
"call_node",
".",
"args... | 37.45 | 17.35 |
def increment(self, key, value=1):
"""
Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool
"""
self._store.increment(self.tagged_item_key(ke... | [
"def",
"increment",
"(",
"self",
",",
"key",
",",
"value",
"=",
"1",
")",
":",
"self",
".",
"_store",
".",
"increment",
"(",
"self",
".",
"tagged_item_key",
"(",
"key",
")",
",",
"value",
")"
] | 24.461538 | 16.615385 |
def split_by_connected_component(self, idents):
'''Split idents into equivalence classes based on connected
components.
'''
idents_remaining = set(idents)
connected_components = []
for ident in idents:
if ident not in idents_remaining:
continue... | [
"def",
"split_by_connected_component",
"(",
"self",
",",
"idents",
")",
":",
"idents_remaining",
"=",
"set",
"(",
"idents",
")",
"connected_components",
"=",
"[",
"]",
"for",
"ident",
"in",
"idents",
":",
"if",
"ident",
"not",
"in",
"idents_remaining",
":",
... | 36.363636 | 16.363636 |
def _paramiko_tunnel(lport, rport, server, remoteip, keyfile=None, password=None):
"""Function for actually starting a paramiko tunnel, to be passed
to multiprocessing.Process(target=this), and not called directly.
"""
username, server, port = _split_server(server)
client = paramiko.SSHClient()
... | [
"def",
"_paramiko_tunnel",
"(",
"lport",
",",
"rport",
",",
"server",
",",
"remoteip",
",",
"keyfile",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"username",
",",
"server",
",",
"port",
"=",
"_split_server",
"(",
"server",
")",
"client",
"=",
... | 40.34375 | 22.71875 |
def validate(self, instance, value):
"""Check the class of the container and validate each element
This returns a copy of the container to prevent unwanted sharing of
pointers.
"""
if not self.coerce and not isinstance(value, self._class_container):
self.error(instan... | [
"def",
"validate",
"(",
"self",
",",
"instance",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"coerce",
"and",
"not",
"isinstance",
"(",
"value",
",",
"self",
".",
"_class_container",
")",
":",
"self",
".",
"error",
"(",
"instance",
",",
"value",
... | 38.571429 | 16.952381 |
def scalar(cls, value):
"""Create an ArgumentType with a single scalar in range(value)."""
return lambda i, name: cls(i, name, (value,), lambda a: a[0], None) | [
"def",
"scalar",
"(",
"cls",
",",
"value",
")",
":",
"return",
"lambda",
"i",
",",
"name",
":",
"cls",
"(",
"i",
",",
"name",
",",
"(",
"value",
",",
")",
",",
"lambda",
"a",
":",
"a",
"[",
"0",
"]",
",",
"None",
")"
] | 54.666667 | 16 |
def register_dependency(self, data_src, data_sink):
""" registers a dependency of data_src -> data_sink
by placing appropriate entries in provides_for and depends_on
"""
pdebug("registering dependency %s -> %s" % (data_src, data_sink))
if (data_src not in self._gettask(data... | [
"def",
"register_dependency",
"(",
"self",
",",
"data_src",
",",
"data_sink",
")",
":",
"pdebug",
"(",
"\"registering dependency %s -> %s\"",
"%",
"(",
"data_src",
",",
"data_sink",
")",
")",
"if",
"(",
"data_src",
"not",
"in",
"self",
".",
"_gettask",
"(",
... | 44.083333 | 24.916667 |
def duration(cls, seconds, first=True):
"""
Constructs a human readable string to indicate the time duration for the given seconds
:param int seconds:
:param bool first: Just return the first unit instead of all
:rtype: str
"""
num_units = []
for unit in... | [
"def",
"duration",
"(",
"cls",
",",
"seconds",
",",
"first",
"=",
"True",
")",
":",
"num_units",
"=",
"[",
"]",
"for",
"unit",
"in",
"reversed",
"(",
"TimeUnit",
")",
":",
"if",
"seconds",
">=",
"unit",
".",
"seconds",
":",
"name",
"=",
"unit",
"."... | 32.285714 | 17.52381 |
def remap_index_fn(ref_file):
"""minimap2 can build indexes on the fly but will also store commons ones.
"""
index_dir = os.path.join(os.path.dirname(ref_file), os.pardir, "minimap2")
if os.path.exists(index_dir) and os.path.isdir(index_dir):
return index_dir
else:
return os.path.dir... | [
"def",
"remap_index_fn",
"(",
"ref_file",
")",
":",
"index_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"ref_file",
")",
",",
"os",
".",
"pardir",
",",
"\"minimap2\"",
")",
"if",
"os",
".",
"path",
".",
"e... | 40.875 | 14.75 |
def filename(self):
""" Name of the file on the client file system, but normalized to ensure
file system compatibility. An empty filename is returned as 'empty'.
Only ASCII letters, digits, dashes, underscores and dots are
allowed in the final filename. Accents are removed, ... | [
"def",
"filename",
"(",
"self",
")",
":",
"fname",
"=",
"self",
".",
"raw_filename",
"if",
"not",
"isinstance",
"(",
"fname",
",",
"unicode",
")",
":",
"fname",
"=",
"fname",
".",
"decode",
"(",
"'utf8'",
",",
"'ignore'",
")",
"fname",
"=",
"normalize"... | 52.333333 | 19.611111 |
def hide_zeroes(self):
'''
Sometimes it makes sense to hide the labels for subsets whose size is zero.
This utility method does this.
'''
for v in self.subset_labels:
if v is not None and v.get_text() == '0':
v.set_visible(False) | [
"def",
"hide_zeroes",
"(",
"self",
")",
":",
"for",
"v",
"in",
"self",
".",
"subset_labels",
":",
"if",
"v",
"is",
"not",
"None",
"and",
"v",
".",
"get_text",
"(",
")",
"==",
"'0'",
":",
"v",
".",
"set_visible",
"(",
"False",
")"
] | 36.25 | 17.75 |
def _maybe_validate_rightmost_transposed_ndims(
rightmost_transposed_ndims, validate_args, name=None):
"""Checks that `rightmost_transposed_ndims` is valid."""
with tf.name_scope(name or 'maybe_validate_rightmost_transposed_ndims'):
assertions = []
if not dtype_util.is_integer(rightmost_transposed_ndims... | [
"def",
"_maybe_validate_rightmost_transposed_ndims",
"(",
"rightmost_transposed_ndims",
",",
"validate_args",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"name",
"or",
"'maybe_validate_rightmost_transposed_ndims'",
")",
":",
"assertions",
"... | 44.741935 | 20.354839 |
def nonblock_recv(self):
"""Non blocking receive"""
if self.buffered_frames():
# Get a frame from the buffer
return self.get_frame()
# Set the non blocking flag, read from the socket, and unset the flag
self.set_nonblock(True)
pkt = L2bpfListenSocket.rec... | [
"def",
"nonblock_recv",
"(",
"self",
")",
":",
"if",
"self",
".",
"buffered_frames",
"(",
")",
":",
"# Get a frame from the buffer",
"return",
"self",
".",
"get_frame",
"(",
")",
"# Set the non blocking flag, read from the socket, and unset the flag",
"self",
".",
"set_... | 30.666667 | 15.5 |
def _get_url(url):
"""Retrieve requested URL"""
try:
data = HTTP_SESSION.get(url, stream=True)
data.raise_for_status()
except requests.exceptions.RequestException as exc:
raise FetcherException(exc)
return data | [
"def",
"_get_url",
"(",
"url",
")",
":",
"try",
":",
"data",
"=",
"HTTP_SESSION",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"data",
".",
"raise_for_status",
"(",
")",
"except",
"requests",
".",
"exceptions",
".",
"RequestException",
"as",
... | 27 | 17.444444 |
def tf_action_exploration(self, action, exploration, action_spec):
"""
Applies optional exploration to the action (post-processor for action outputs).
Args:
action (tf.Tensor): The original output action tensor (to be post-processed).
exploration (Exploration): The Exp... | [
"def",
"tf_action_exploration",
"(",
"self",
",",
"action",
",",
"exploration",
",",
"action_spec",
")",
":",
"action_shape",
"=",
"tf",
".",
"shape",
"(",
"input",
"=",
"action",
")",
"exploration_value",
"=",
"exploration",
".",
"tf_explore",
"(",
"episode",... | 40.931818 | 22.386364 |
def load(stream, fmt='lha'):
"""Load a parameter file in DSixTools SLHA-like format or its JSON or
YAML representation."""
if fmt == 'lha':
return pylha.load(stream)
elif fmt == 'json':
if isinstance(stream, str):
return json.loads(stream)
else:
return jso... | [
"def",
"load",
"(",
"stream",
",",
"fmt",
"=",
"'lha'",
")",
":",
"if",
"fmt",
"==",
"'lha'",
":",
"return",
"pylha",
".",
"load",
"(",
"stream",
")",
"elif",
"fmt",
"==",
"'json'",
":",
"if",
"isinstance",
"(",
"stream",
",",
"str",
")",
":",
"r... | 31.666667 | 10 |
def integer_list_file(cls, filename):
"""
Read a list of integers from a file.
The file format is:
- # anywhere in the line begins a comment
- leading and trailing spaces are ignored
- empty lines are ignored
- integers can be specified as:
- dec... | [
"def",
"integer_list_file",
"(",
"cls",
",",
"filename",
")",
":",
"count",
"=",
"0",
"result",
"=",
"list",
"(",
")",
"fd",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"for",
"line",
"in",
"fd",
":",
"count",
"=",
"count",
"+",
"1",
"if",
"'#... | 31.923077 | 12.282051 |
def calibrate_container_with_instrument(self,
container: Container,
instrument,
save: bool
):
'''Calibrates a container using the bottom... | [
"def",
"calibrate_container_with_instrument",
"(",
"self",
",",
"container",
":",
"Container",
",",
"instrument",
",",
"save",
":",
"bool",
")",
":",
"well",
"=",
"container",
"[",
"0",
"]",
"# Get the relative position of well with respect to instrument",
"delta",
"=... | 29.894737 | 18.842105 |
def groups_delete(self, room_id=None, group=None, **kwargs):
"""Delete a private group."""
if room_id:
return self.__call_api_post('groups.delete', roomId=room_id, kwargs=kwargs)
elif group:
return self.__call_api_post('groups.delete', roomName=group, kwargs=kwargs)
... | [
"def",
"groups_delete",
"(",
"self",
",",
"room_id",
"=",
"None",
",",
"group",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"room_id",
":",
"return",
"self",
".",
"__call_api_post",
"(",
"'groups.delete'",
",",
"roomId",
"=",
"room_id",
",",
... | 49.375 | 27 |
def fit(self, X, y=None, **fit_params):
"""Fit base estimators.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Training data.
y : array-like, optional
Target data if base estimators are supervised.
Returns
-------
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"fit_params",
")",
":",
"X",
"=",
"numpy",
".",
"asarray",
"(",
"X",
")",
"self",
".",
"_fit_estimators",
"(",
"X",
",",
"y",
",",
"*",
"*",
"fit_params",
")",
"Xt",
"... | 23.952381 | 18.142857 |
def prepare_samples(job, fastqs, univ_options):
"""
This module will accept a dict object holding the 3 input prefixes and the patient id and will
attempt to store the fastqs to the jobstore. The input files must satisfy the following
1. File extensions can only be fastq or fq (.gz is also allowed)
... | [
"def",
"prepare_samples",
"(",
"job",
",",
"fastqs",
",",
"univ_options",
")",
":",
"job",
".",
"fileStore",
".",
"logToMaster",
"(",
"'Downloading Inputs for %s'",
"%",
"univ_options",
"[",
"'patient'",
"]",
")",
"allowed_samples",
"=",
"{",
"'tumor_dna_fastq_pre... | 53.039474 | 23.828947 |
def writeWarp(self, warpDict):
""" Write a list of (in, out) values for a warpmap """
warpElement = ET.Element("warp")
axisNames = sorted(warpDict.keys())
for name in axisNames:
axisElement = ET.Element("axis")
axisElement.attrib['name'] = name
for a, ... | [
"def",
"writeWarp",
"(",
"self",
",",
"warpDict",
")",
":",
"warpElement",
"=",
"ET",
".",
"Element",
"(",
"\"warp\"",
")",
"axisNames",
"=",
"sorted",
"(",
"warpDict",
".",
"keys",
"(",
")",
")",
"for",
"name",
"in",
"axisNames",
":",
"axisElement",
"... | 42.285714 | 4.142857 |
def rev(self, i):
"""Return a clone with a different revision."""
on = copy(self)
on.revision = i
return on | [
"def",
"rev",
"(",
"self",
",",
"i",
")",
":",
"on",
"=",
"copy",
"(",
"self",
")",
"on",
".",
"revision",
"=",
"i",
"return",
"on"
] | 27 | 16 |
def __select_nearest_ws(jsondata, latitude, longitude):
"""Select the nearest weatherstation."""
log.debug("__select_nearest_ws: latitude: %s, longitude: %s",
latitude, longitude)
dist = 0
dist2 = 0
loc_data = None
try:
ws_json = jsondata[__ACTUAL]
ws_json = ws_jso... | [
"def",
"__select_nearest_ws",
"(",
"jsondata",
",",
"latitude",
",",
"longitude",
")",
":",
"log",
".",
"debug",
"(",
"\"__select_nearest_ws: latitude: %s, longitude: %s\"",
",",
"latitude",
",",
"longitude",
")",
"dist",
"=",
"0",
"dist2",
"=",
"0",
"loc_data",
... | 32.948718 | 17.410256 |
def dict(self, iss_list=None):
"""
Return the bundle of keys as a dictionary with the issuer IDs as
the keys and the key sets represented as JWKS instances.
:param iss_list: List of Issuer IDs that should be part of the
output
:rtype: Dictionary
"""
... | [
"def",
"dict",
"(",
"self",
",",
"iss_list",
"=",
"None",
")",
":",
"_int",
"=",
"{",
"}",
"for",
"iss",
",",
"kj",
"in",
"self",
".",
"bundle",
".",
"items",
"(",
")",
":",
"if",
"iss_list",
"is",
"None",
"or",
"iss",
"in",
"iss_list",
":",
"t... | 36.117647 | 17.294118 |
def create_message(self):
"""Returns a message body to send in this email. Should be from email.mime.*"""
body = dedent("""\
Received exception {exception} on {queue} from worker {worker}:
{traceback}
Payload:
{payload}
""").format(exception=self._exception,
... | [
"def",
"create_message",
"(",
"self",
")",
":",
"body",
"=",
"dedent",
"(",
"\"\"\"\\\n Received exception {exception} on {queue} from worker {worker}:\n\n {traceback}\n\n Payload:\n {payload}\n\n \"\"\"",
")",
".",
"format",
"(",
"exception",
"=",
... | 27.666667 | 18.611111 |
def make_proxy_method(cls, name):
"""Creates a proxy function that can be used by Flasks routing. The
proxy instantiates the Mocha subclass and calls the appropriate
method.
:param name: the name of the method to create a proxy for
"""
i = cls()
view = getattr(i,... | [
"def",
"make_proxy_method",
"(",
"cls",
",",
"name",
")",
":",
"i",
"=",
"cls",
"(",
")",
"view",
"=",
"getattr",
"(",
"i",
",",
"name",
")",
"for",
"decorator",
"in",
"cls",
".",
"decorators",
":",
"view",
"=",
"decorator",
"(",
"view",
")",
"@",
... | 38.971014 | 20.710145 |
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwa... | [
"def",
"transaction_search",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"plain",
"=",
"self",
".",
"_call",
"(",
"'TransactionSearch'",
",",
"*",
"*",
"kwargs",
")",
"return",
"PayPalResponseList",
"(",
"plain",
".",
"raw",
",",
"self",
".",
"config... | 33.722222 | 22.388889 |
def get(self, request, *args, **kwargs):
"""
Do the login and password protection.
"""
response = super(EntryProtectionMixin, self).get(
request, *args, **kwargs)
if self.object.login_required and not request.user.is_authenticated:
return self.login()
... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"super",
"(",
"EntryProtectionMixin",
",",
"self",
")",
".",
"get",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"... | 41.833333 | 12.5 |
def transform(self, maps):
""" This function transforms from component masses and caretsian spins
to chi_p.
Parameters
----------
maps : a mapping object
Examples
--------
Convert a dict of numpy.array:
Returns
-------
out : dict... | [
"def",
"transform",
"(",
"self",
",",
"maps",
")",
":",
"out",
"=",
"{",
"}",
"out",
"[",
"\"chi_p\"",
"]",
"=",
"conversions",
".",
"chi_p",
"(",
"maps",
"[",
"parameters",
".",
"mass1",
"]",
",",
"maps",
"[",
"parameters",
".",
"mass2",
"]",
",",... | 31.791667 | 21.583333 |
def _do_subst(node, subs):
"""
Fetch the node contents and replace all instances of the keys with
their values. For example, if subs is
{'%VERSION%': '1.2345', '%BASE%': 'MyProg', '%prefix%': '/bin'},
then all instances of %VERSION% in the file will be replaced with
1.2345 and so forth.
... | [
"def",
"_do_subst",
"(",
"node",
",",
"subs",
")",
":",
"contents",
"=",
"node",
".",
"get_text_contents",
"(",
")",
"if",
"subs",
":",
"for",
"(",
"k",
",",
"val",
")",
"in",
"subs",
":",
"contents",
"=",
"re",
".",
"sub",
"(",
"k",
",",
"val",
... | 34.238095 | 17 |
def date_map(doc, datemap_list, time_format=None):
'''
For all the datetime fields in "datemap" find that key in doc and map the datetime object to
a strftime string. This pprint and others will print out readable datetimes.
'''
if datemap_list:
for i in datemap_list:... | [
"def",
"date_map",
"(",
"doc",
",",
"datemap_list",
",",
"time_format",
"=",
"None",
")",
":",
"if",
"datemap_list",
":",
"for",
"i",
"in",
"datemap_list",
":",
"if",
"isinstance",
"(",
"i",
",",
"datetime",
")",
":",
"doc",
"=",
"CursorFormatter",
".",
... | 46.2 | 26.6 |
def stop_consumer(self):
"""Stop the consumer object and allow it to do a clean shutdown if it
has the ability to do so.
"""
try:
LOGGER.info('Shutting down the consumer')
self.consumer.shutdown()
except AttributeError:
LOGGER.debug('Consumer ... | [
"def",
"stop_consumer",
"(",
"self",
")",
":",
"try",
":",
"LOGGER",
".",
"info",
"(",
"'Shutting down the consumer'",
")",
"self",
".",
"consumer",
".",
"shutdown",
"(",
")",
"except",
"AttributeError",
":",
"LOGGER",
".",
"debug",
"(",
"'Consumer does not ha... | 34.4 | 14.6 |
def peng_mant(snum):
r"""
Return the mantissa of a number represented in engineering notation.
:param snum: Number
:type snum: :ref:`EngineeringNotationNumber`
:rtype: float
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.f... | [
"def",
"peng_mant",
"(",
"snum",
")",
":",
"snum",
"=",
"snum",
".",
"rstrip",
"(",
")",
"return",
"float",
"(",
"snum",
"if",
"snum",
"[",
"-",
"1",
"]",
".",
"isdigit",
"(",
")",
"else",
"snum",
"[",
":",
"-",
"1",
"]",
")"
] | 24.12 | 23.28 |
def iso_name_increment(name, is_dir=False, max_length=8):
"""Increment an ISO name to avoid name collision.
Example:
>>> iso_name_increment('foo.txt')
'foo1.txt'
>>> iso_name_increment('bar10')
'bar11'
>>> iso_name_increment('bar99', max_length=5)
'ba100'
"""... | [
"def",
"iso_name_increment",
"(",
"name",
",",
"is_dir",
"=",
"False",
",",
"max_length",
"=",
"8",
")",
":",
"# Split the extension if needed",
"if",
"not",
"is_dir",
"and",
"'.'",
"in",
"name",
":",
"name",
",",
"ext",
"=",
"name",
".",
"rsplit",
"(",
... | 29.333333 | 15.272727 |
def validate_bam(self, input_bam):
"""
Wrapper for Picard's ValidateSamFile.
:param str input_bam: Path to file to validate.
:return str: Command to run for the validation.
"""
cmd = self.tools.java + " -Xmx" + self.pm.javamem
cmd += " -jar " + self.tools.picard ... | [
"def",
"validate_bam",
"(",
"self",
",",
"input_bam",
")",
":",
"cmd",
"=",
"self",
".",
"tools",
".",
"java",
"+",
"\" -Xmx\"",
"+",
"self",
".",
"pm",
".",
"javamem",
"cmd",
"+=",
"\" -jar \"",
"+",
"self",
".",
"tools",
".",
"picard",
"+",
"\" Val... | 35.090909 | 13.454545 |
def format_mode(sres):
"""
Format a line in the directory list based on the file's type and other attributes.
"""
mode = sres.st_mode
root = (mode & 0o700) >> 6
group = (mode & 0o070) >> 3
user = (mode & 0o7)
def stat_type(md):
''' stat type'''
if stat.S_ISDIR(md):
return 'd'
elif st... | [
"def",
"format_mode",
"(",
"sres",
")",
":",
"mode",
"=",
"sres",
".",
"st_mode",
"root",
"=",
"(",
"mode",
"&",
"0o700",
")",
">>",
"6",
"group",
"=",
"(",
"mode",
"&",
"0o070",
")",
">>",
"3",
"user",
"=",
"(",
"mode",
"&",
"0o7",
")",
"def",... | 22.37037 | 21.111111 |
def com_google_fonts_check_kerning_for_non_ligated_sequences(ttFont, ligatures, has_kerning_info):
"""Is there kerning info for non-ligated sequences?"""
def look_for_nonligated_kern_info(table):
for pairpos in table.SubTable:
for i, glyph in enumerate(pairpos.Coverage.glyphs):
if not hasattr(pai... | [
"def",
"com_google_fonts_check_kerning_for_non_ligated_sequences",
"(",
"ttFont",
",",
"ligatures",
",",
"has_kerning_info",
")",
":",
"def",
"look_for_nonligated_kern_info",
"(",
"table",
")",
":",
"for",
"pairpos",
"in",
"table",
".",
"SubTable",
":",
"for",
"i",
... | 40.145833 | 17.479167 |
def manager_required(func=None):
"""
Decorator for views that require not only a team but also that a user be
logged in and be the manager or owner of that team.
"""
def decorator(view_func):
@team_required
@login_required
@functools.wraps(view_func, assigned=available_attrs(... | [
"def",
"manager_required",
"(",
"func",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"@",
"team_required",
"@",
"login_required",
"@",
"functools",
".",
"wraps",
"(",
"view_func",
",",
"assigned",
"=",
"available_attrs",
"(",
"view_... | 37.777778 | 16.222222 |
def makedirs_safe(fulldir):
"""Creates a directory if it does not exists. Takes into consideration
concurrent access support. Works like the shell's 'mkdir -p'.
"""
try:
if not os.path.exists(fulldir): os.makedirs(fulldir)
except OSError as exc: # Python >2.5
import errno
if exc.errno == errno.EE... | [
"def",
"makedirs_safe",
"(",
"fulldir",
")",
":",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fulldir",
")",
":",
"os",
".",
"makedirs",
"(",
"fulldir",
")",
"except",
"OSError",
"as",
"exc",
":",
"# Python >2.5",
"import",
"errno"... | 30.545455 | 16.272727 |
def sanitize(self, table_name, column_name, value):
"""
Sanitizes given value extracted from the database according to the
sanitation configuration.
TODO: Add support for dates, booleans and other types found in SQL than
string.
:param table_name: Name of the database t... | [
"def",
"sanitize",
"(",
"self",
",",
"table_name",
",",
"column_name",
",",
"value",
")",
":",
"sanitizer_callback",
"=",
"self",
".",
"get_sanitizer_for",
"(",
"table_name",
",",
"column_name",
")",
"return",
"sanitizer_callback",
"(",
"value",
")",
"if",
"sa... | 37.08 | 23 |
def _UnserializableObjectFallback(self, obj):
"""Handles sanitizing of unserializable objects for Json.
For instances of heap types, we take the class dict, augment it with the
instance's __dict__, tag it and transmit it over to the RPC client to be
reconstructed there. (Works with both old and new sty... | [
"def",
"_UnserializableObjectFallback",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"libpython",
".",
"PyInstanceObjectPtr",
")",
":",
"# old-style classes use 'classobj'/'instance'",
"# get class attribute dictionary",
"in_class",
"=",
"obj",
... | 44.015625 | 22.515625 |
def loadXMLGenericData(filename): # not tested
"""Read any type of vtk data object encoded in XML format. Return an ``Actor(vtkActor)`` object."""
reader = vtk.vtkXMLGenericDataObjectReader()
reader.SetFileName(filename)
reader.Update()
return Actor(reader.GetOutput()) | [
"def",
"loadXMLGenericData",
"(",
"filename",
")",
":",
"# not tested",
"reader",
"=",
"vtk",
".",
"vtkXMLGenericDataObjectReader",
"(",
")",
"reader",
".",
"SetFileName",
"(",
"filename",
")",
"reader",
".",
"Update",
"(",
")",
"return",
"Actor",
"(",
"reader... | 47.5 | 8 |
def parse_ls(out):
"""
Parser for Android's ls -lR output.
Takes a string, returns parsed structure.
"""
# assumed ls -lR line format:
# -rw-r--r-- root shell 0 2013-07-05 02:26 tasks
# drwxr-xr-x root root 2013-07-05 02:26 log
# brw------- root root ... | [
"def",
"parse_ls",
"(",
"out",
")",
":",
"# assumed ls -lR line format:",
"# -rw-r--r-- root shell 0 2013-07-05 02:26 tasks",
"# drwxr-xr-x root root 2013-07-05 02:26 log",
"# brw------- root root 179, 0 2013-07-05 02:26 mmcblk0",
"# lrwxrwxrwx root r... | 35.412371 | 14.443299 |
def verify_mass_range_options(opts, parser, nonSpin=False):
"""
Parses the metric calculation options given and verifies that they are
correct.
Parameters
----------
opts : argparse.Values instance
Result of parsing the input options with OptionParser
parser : object
The Opt... | [
"def",
"verify_mass_range_options",
"(",
"opts",
",",
"parser",
",",
"nonSpin",
"=",
"False",
")",
":",
"# Mass1 must be the heavier!",
"if",
"opts",
".",
"min_mass1",
"<",
"opts",
".",
"min_mass2",
":",
"parser",
".",
"error",
"(",
"\"min-mass1 cannot be less tha... | 53.512739 | 21.33121 |
def get_source(self, objtxt):
"""Get object source"""
from spyder_kernels.utils.dochelpers import getsource
obj, valid = self._eval(objtxt)
if valid:
return getsource(obj) | [
"def",
"get_source",
"(",
"self",
",",
"objtxt",
")",
":",
"from",
"spyder_kernels",
".",
"utils",
".",
"dochelpers",
"import",
"getsource",
"obj",
",",
"valid",
"=",
"self",
".",
"_eval",
"(",
"objtxt",
")",
"if",
"valid",
":",
"return",
"getsource",
"(... | 30 | 14.714286 |
def kill(self, exit_code: Any = None):
"""
Stops the behaviour
Args:
exit_code (object, optional): the exit code of the behaviour (Default value = None)
"""
self._force_kill.set()
if exit_code is not None:
self._exit_code = exit_code
logger... | [
"def",
"kill",
"(",
"self",
",",
"exit_code",
":",
"Any",
"=",
"None",
")",
":",
"self",
".",
"_force_kill",
".",
"set",
"(",
")",
"if",
"exit_code",
"is",
"not",
"None",
":",
"self",
".",
"_exit_code",
"=",
"exit_code",
"logger",
".",
"info",
"(",
... | 31.833333 | 20 |
def add_in_filter(self, *values):
"""
Add a filter using "IN" logic. This is typically the primary filter
that will be used to find a match and generally combines other
filters to get more granular. An example of usage would be searching
for an IP address (or addresses) in a spec... | [
"def",
"add_in_filter",
"(",
"self",
",",
"*",
"values",
")",
":",
"filt",
"=",
"InFilter",
"(",
"*",
"values",
")",
"self",
".",
"update_filter",
"(",
"filt",
")",
"return",
"filt"
] | 42.176471 | 20.176471 |
def _create_command_file(self, expect, send):
"""Internal function. Do not use.
Takes a long command, and puts it in an executable file ready to run. Returns the filename.
"""
shutit = self.shutit
random_id = shutit_util.random_id()
fname = shutit_global.shutit_global_object.shutit_state_dir + '/tmp_' + ra... | [
"def",
"_create_command_file",
"(",
"self",
",",
"expect",
",",
"send",
")",
":",
"shutit",
"=",
"self",
".",
"shutit",
"random_id",
"=",
"shutit_util",
".",
"random_id",
"(",
")",
"fname",
"=",
"shutit_global",
".",
"shutit_global_object",
".",
"shutit_state_... | 51.518519 | 22.037037 |
def config_value_keys(self, sortkey = False):
"""
Return configuration keys directly stored in this node. Configurations in child nodes are not included.
"""
if sortkey:
items = sorted(self.items())
else:
items = self.items()
return (k for k,v in i... | [
"def",
"config_value_keys",
"(",
"self",
",",
"sortkey",
"=",
"False",
")",
":",
"if",
"sortkey",
":",
"items",
"=",
"sorted",
"(",
"self",
".",
"items",
"(",
")",
")",
"else",
":",
"items",
"=",
"self",
".",
"items",
"(",
")",
"return",
"(",
"k",
... | 38.777778 | 17.666667 |
def wait_lock(path, lock_fn=None, timeout=5, sleep=0.1, time_start=None):
'''
Obtain a write lock. If one exists, wait for it to release first
'''
if not isinstance(path, six.string_types):
raise FileLockError('path must be a string')
if lock_fn is None:
lock_fn = path + '.w'
if ... | [
"def",
"wait_lock",
"(",
"path",
",",
"lock_fn",
"=",
"None",
",",
"timeout",
"=",
"5",
",",
"sleep",
"=",
"0.1",
",",
"time_start",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"six",
".",
"string_types",
")",
":",
"raise",
... | 33.445946 | 21.364865 |
def cmd_up(self, args):
'''adjust TRIM_PITCH_CD up by 5 degrees'''
if len(args) == 0:
adjust = 5.0
else:
adjust = float(args[0])
old_trim = self.get_mav_param('TRIM_PITCH_CD', None)
if old_trim is None:
print("Existing trim value unknown!")
... | [
"def",
"cmd_up",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"adjust",
"=",
"5.0",
"else",
":",
"adjust",
"=",
"float",
"(",
"args",
"[",
"0",
"]",
")",
"old_trim",
"=",
"self",
".",
"get_mav_param",
"(",
... | 41.5 | 18.375 |
def register(cls, name, klass, content_type='text/plain'):
"""
Register an emitter.
Parameters::
- `name`: The name of the emitter ('json', 'xml', 'yaml', ...)
- `klass`: The emitter class.
- `content_type`: The content type to serve response as.
"""
c... | [
"def",
"register",
"(",
"cls",
",",
"name",
",",
"klass",
",",
"content_type",
"=",
"'text/plain'",
")",
":",
"cls",
".",
"EMITTERS",
"[",
"name",
"]",
"=",
"(",
"klass",
",",
"content_type",
")"
] | 35.2 | 15.8 |
def commit_hash(dir='.'):
"""
Return commit hash for HEAD of checked out branch of the
specified directory.
"""
cmd = ['git', 'rev-parse', 'HEAD']
try:
with open(os.devnull, 'w') as devnull:
revision_hash = subprocess.check_output(
cmd,
cwd=d... | [
"def",
"commit_hash",
"(",
"dir",
"=",
"'.'",
")",
":",
"cmd",
"=",
"[",
"'git'",
",",
"'rev-parse'",
",",
"'HEAD'",
"]",
"try",
":",
"with",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
"as",
"devnull",
":",
"revision_hash",
"=",
"subprocess"... | 24.772727 | 17.318182 |
def read(self, uri=None, resources=None, index_only=False):
"""Read sitemap from a URI including handling sitemapindexes.
If index_only is True then individual sitemaps references in a sitemapindex
will not be read. This will result in no resources being returned and is
useful only to r... | [
"def",
"read",
"(",
"self",
",",
"uri",
"=",
"None",
",",
"resources",
"=",
"None",
",",
"index_only",
"=",
"False",
")",
":",
"try",
":",
"fh",
"=",
"URLopener",
"(",
")",
".",
"open",
"(",
"uri",
")",
"self",
".",
"num_files",
"+=",
"1",
"excep... | 44.483333 | 18.216667 |
def get_prefix():
"""Global prefix to identify ncluster created resources name used to identify ncluster created resources,
(name of EFS, VPC, keypair prefixes), can be changed through $NCLUSTER_PREFIX for debugging purposes. """
name = os.environ.get('NCLUSTER_PREFIX', DEFAULT_PREFIX)
if name != DEFAULT_PREFI... | [
"def",
"get_prefix",
"(",
")",
":",
"name",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'NCLUSTER_PREFIX'",
",",
"DEFAULT_PREFIX",
")",
"if",
"name",
"!=",
"DEFAULT_PREFIX",
":",
"validate_prefix",
"(",
"name",
")",
"return",
"name"
] | 44.375 | 16.875 |
def rgb_to_name(rgb_triplet, spec=u'css3'):
"""
Convert a 3-tuple of integers, 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 color names will be... | [
"def",
"rgb_to_name",
"(",
"rgb_triplet",
",",
"spec",
"=",
"u'css3'",
")",
":",
"return",
"hex_to_name",
"(",
"rgb_to_hex",
"(",
"normalize_integer_triplet",
"(",
"rgb_triplet",
")",
")",
",",
"spec",
"=",
"spec",
")"
] | 28.818182 | 22.181818 |
def get_change(self, change_id):
"""
Get information about a proposed set of changes, as submitted
by the change_rrsets method.
Returns a Python data structure with status information about the
changes.
:type change_id: str
:param change_id: The unique identifier... | [
"def",
"get_change",
"(",
"self",
",",
"change_id",
")",
":",
"uri",
"=",
"'/%s/change/%s'",
"%",
"(",
"self",
".",
"Version",
",",
"change_id",
")",
"response",
"=",
"self",
".",
"make_request",
"(",
"'GET'",
",",
"uri",
")",
"body",
"=",
"response",
... | 37.958333 | 17.041667 |
def GET_AUTH(self):
""" GET request """
return self.template_helper.get_renderer().queue(*self.submission_manager.get_job_queue_snapshot(), datetime.fromtimestamp) | [
"def",
"GET_AUTH",
"(",
"self",
")",
":",
"return",
"self",
".",
"template_helper",
".",
"get_renderer",
"(",
")",
".",
"queue",
"(",
"*",
"self",
".",
"submission_manager",
".",
"get_job_queue_snapshot",
"(",
")",
",",
"datetime",
".",
"fromtimestamp",
")"
... | 59 | 37.333333 |
def _upsert(context, params, data):
"""Insert or update data and add/update appropriate timestamps"""
table = params.get("table")
table = datastore.get_table(table, primary_id=False)
unique_keys = ensure_list(params.get("unique"))
data["__last_seen"] = datetime.datetime.utcnow()
if len(unique_ke... | [
"def",
"_upsert",
"(",
"context",
",",
"params",
",",
"data",
")",
":",
"table",
"=",
"params",
".",
"get",
"(",
"\"table\"",
")",
"table",
"=",
"datastore",
".",
"get_table",
"(",
"table",
",",
"primary_id",
"=",
"False",
")",
"unique_keys",
"=",
"ens... | 40.916667 | 13.666667 |
def _make_pkh_address(pubkey_hash, witness=False, cashaddr=True):
'''
bytes, bool -> str
'''
addr_bytes = bytearray()
if riemann.network.CASHADDR_P2PKH is not None and cashaddr:
addr_bytes.extend(riemann.network.CASHADDR_P2PKH)
addr_bytes.extend(pubkey_hash)
return riemann.ne... | [
"def",
"_make_pkh_address",
"(",
"pubkey_hash",
",",
"witness",
"=",
"False",
",",
"cashaddr",
"=",
"True",
")",
":",
"addr_bytes",
"=",
"bytearray",
"(",
")",
"if",
"riemann",
".",
"network",
".",
"CASHADDR_P2PKH",
"is",
"not",
"None",
"and",
"cashaddr",
... | 40.705882 | 19.294118 |
def gen_random_mobile():
"""
随机生成一个手机号
:return:
* str: (string) 手机号
举例如下::
print('--- gen_random_mobile demo ---')
print(gen_random_mobile())
print(gen_random_mobile())
print('---')
执行结果::
--- gen_random_mobile demo ---
16706146773
... | [
"def",
"gen_random_mobile",
"(",
")",
":",
"prefix_list",
"=",
"[",
"\"13\"",
",",
"\"1400\"",
",",
"\"1410\"",
",",
"\"1440\"",
",",
"\"145\"",
",",
"\"146\"",
",",
"\"147\"",
",",
"\"148\"",
",",
"\"15\"",
",",
"\"162\"",
",",
"\"165\"",
",",
"\"166\"",
... | 25.193548 | 22.032258 |
def create_cylinder(rows, cols, radius=[1.0, 1.0], length=1.0, offset=False):
"""Create a cylinder
Parameters
----------
rows : int
Number of rows.
cols : int
Number of columns.
radius : tuple of float
Cylinder radii.
length : float
Length of the cylinder.
... | [
"def",
"create_cylinder",
"(",
"rows",
",",
"cols",
",",
"radius",
"=",
"[",
"1.0",
",",
"1.0",
"]",
",",
"length",
"=",
"1.0",
",",
"offset",
"=",
"False",
")",
":",
"verts",
"=",
"np",
".",
"empty",
"(",
"(",
"rows",
"+",
"1",
",",
"cols",
",... | 36.365385 | 17.346154 |
def make_frame(self, frame, birthframe, startframe, stopframe, deathframe, noiseframe=None):
"""
:param frame: current frame
:param birthframe: frame where this animation starts returning something other than None
:param startframe: frame where animation starts to evolve
:param ... | [
"def",
"make_frame",
"(",
"self",
",",
"frame",
",",
"birthframe",
",",
"startframe",
",",
"stopframe",
",",
"deathframe",
",",
"noiseframe",
"=",
"None",
")",
":",
"newx",
"=",
"self",
".",
"anim_x",
".",
"make_frame",
"(",
"frame",
",",
"birthframe",
"... | 47.047619 | 23.238095 |
def get_valid_statements_for_modeling(sts: List[Influence]) -> List[Influence]:
""" Select INDRA statements that can be used to construct a Delphi model
from a given list of statements. """
return [
s
for s in sts
if is_grounded_statement(s)
and (s.subj_delta["polarity"] is ... | [
"def",
"get_valid_statements_for_modeling",
"(",
"sts",
":",
"List",
"[",
"Influence",
"]",
")",
"->",
"List",
"[",
"Influence",
"]",
":",
"return",
"[",
"s",
"for",
"s",
"in",
"sts",
"if",
"is_grounded_statement",
"(",
"s",
")",
"and",
"(",
"s",
".",
... | 34.090909 | 19.727273 |
def fulltext(search, lang=Lang.English, ignore_case=True):
"""Full text search.
Example::
filters = Text.fulltext("python pymongo_mate")
.. note::
This field doesn't need to specify field.
"""
return {
"$text": {
"$search": ... | [
"def",
"fulltext",
"(",
"search",
",",
"lang",
"=",
"Lang",
".",
"English",
",",
"ignore_case",
"=",
"True",
")",
":",
"return",
"{",
"\"$text\"",
":",
"{",
"\"$search\"",
":",
"search",
",",
"\"$language\"",
":",
"lang",
",",
"\"$caseSensitive\"",
":",
... | 24.473684 | 20.105263 |
def get_version_details(path):
"""Parses version file
:param path: path to version file
:return: version details
"""
with open(path, "r") as reader:
lines = reader.readlines()
data = {
line.split(" = ")[0].replace("__", ""):
line.split(" = ")[1].strip().... | [
"def",
"get_version_details",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"r\"",
")",
"as",
"reader",
":",
"lines",
"=",
"reader",
".",
"readlines",
"(",
")",
"data",
"=",
"{",
"line",
".",
"split",
"(",
"\" = \"",
")",
"[",
"0",
"]"... | 25.466667 | 15.666667 |
def get_snapshot(self, hosts, macromodulations, timeperiods): # pragma: no cover, not yet!
"""
Raise snapshot event handlers if NONE of the following conditions is met::
* snapshot_command is None
* snapshot_enabled is disabled
* snapshot_criteria does not matches current state... | [
"def",
"get_snapshot",
"(",
"self",
",",
"hosts",
",",
"macromodulations",
",",
"timeperiods",
")",
":",
"# pragma: no cover, not yet!",
"# We should have a snapshot_command, to be enabled and of course",
"# in the good time and state :D",
"if",
"self",
".",
"snapshot_command",
... | 39.6875 | 22 |
def run(self):
"""
Run the EventHubClient in blocking mode.
Opens the connection and starts running all Sender/Receiver clients.
Returns a list of the start up results. For a succcesful client start the
result will be `None`, otherwise the exception raised.
If all clients... | [
"def",
"run",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"%r: Starting %r clients\"",
",",
"self",
".",
"container_id",
",",
"len",
"(",
"self",
".",
"clients",
")",
")",
"try",
":",
"self",
".",
"_start_clients",
"(",
")",
"redirects",
"=",
"["... | 44.16129 | 22.032258 |
def add_pool(arg, opts, shell_opts):
""" Add a pool.
"""
p = Pool()
p.name = opts.get('name')
p.description = opts.get('description')
p.default_type = opts.get('default-type')
p.ipv4_default_prefix_length = opts.get('ipv4_default_prefix_length')
p.ipv6_default_prefix_length = opts.get('... | [
"def",
"add_pool",
"(",
"arg",
",",
"opts",
",",
"shell_opts",
")",
":",
"p",
"=",
"Pool",
"(",
")",
"p",
".",
"name",
"=",
"opts",
".",
"get",
"(",
"'name'",
")",
"p",
".",
"description",
"=",
"opts",
".",
"get",
"(",
"'description'",
")",
"p",
... | 30.941176 | 20.764706 |
def lint(fix_imports):
"""
Run flake8.
"""
from glob import glob
from subprocess import call
# FIXME: should support passing these in an option
skip = [
'ansible',
'db',
'flask_sessions',
'node_modules',
'requirements',
]
root_files = glob('*.... | [
"def",
"lint",
"(",
"fix_imports",
")",
":",
"from",
"glob",
"import",
"glob",
"from",
"subprocess",
"import",
"call",
"# FIXME: should support passing these in an option",
"skip",
"=",
"[",
"'ansible'",
",",
"'db'",
",",
"'flask_sessions'",
",",
"'node_modules'",
"... | 26.866667 | 18.266667 |
def mark(self, value=1):
"""Updates the dictionary."""
self['count'] += value
for m in self._meters:
m.update(value) | [
"def",
"mark",
"(",
"self",
",",
"value",
"=",
"1",
")",
":",
"self",
"[",
"'count'",
"]",
"+=",
"value",
"for",
"m",
"in",
"self",
".",
"_meters",
":",
"m",
".",
"update",
"(",
"value",
")"
] | 21.666667 | 17.166667 |
def retrieve_outputs(self):
""" Declare the outputs of the algorithms as attributes: x_final,
y_final, metrics.
"""
metrics = {}
for obs in self._observers['cv_metrics']:
metrics[obs.name] = obs.retrieve_metrics()
self.metrics = metrics | [
"def",
"retrieve_outputs",
"(",
"self",
")",
":",
"metrics",
"=",
"{",
"}",
"for",
"obs",
"in",
"self",
".",
"_observers",
"[",
"'cv_metrics'",
"]",
":",
"metrics",
"[",
"obs",
".",
"name",
"]",
"=",
"obs",
".",
"retrieve_metrics",
"(",
")",
"self",
... | 32.111111 | 13.444444 |
def read(self, length=1000, blocking=False):
"""
Read ``length`` bytes from current process output stream.
Note: This method is not fully non-blocking, however it
behaves like one.
"""
size_p = PLARGE_INTEGER(LARGE_INTEGER(0))
if not blocking:
windll.... | [
"def",
"read",
"(",
"self",
",",
"length",
"=",
"1000",
",",
"blocking",
"=",
"False",
")",
":",
"size_p",
"=",
"PLARGE_INTEGER",
"(",
"LARGE_INTEGER",
"(",
"0",
")",
")",
"if",
"not",
"blocking",
":",
"windll",
".",
"kernel32",
".",
"GetFileSizeEx",
"... | 38.058824 | 15.352941 |
def if_then_else(cls,
condition: 'TensorFluent',
true_case: 'TensorFluent',
false_case: 'TensorFluent') -> 'TensorFluent':
'''Returns a TensorFluent for the control op if-then-else.
Args:
condition: Boolean fluent for the if condition.
true_ca... | [
"def",
"if_then_else",
"(",
"cls",
",",
"condition",
":",
"'TensorFluent'",
",",
"true_case",
":",
"'TensorFluent'",
",",
"false_case",
":",
"'TensorFluent'",
")",
"->",
"'TensorFluent'",
":",
"true",
"=",
"TensorFluent",
".",
"constant",
"(",
"True",
",",
"tf... | 38.565217 | 22.478261 |
def svm_score(self, x):
x = x[1:]
'''
original_X = self.svm_processor.train_X[:, 1:]
score = 0
for i in range(len(self.svm_processor.sv_alpha)):
score += self.svm_processor.sv_alpha[i] * self.svm_processor.sv_Y[i] * utility.Kernel.gaussian_kernel(self, original_X[se... | [
"def",
"svm_score",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"x",
"[",
"1",
":",
"]",
"score",
"=",
"np",
".",
"sum",
"(",
"self",
".",
"svm_processor",
".",
"sv_alpha",
"*",
"self",
".",
"svm_processor",
".",
"sv_Y",
"*",
"utility",
".",
"Kern... | 40.133333 | 40.266667 |
def add_edge(self, id1, id2, weight=0.0, length=1.0, label="", properties={}):
""" Add weighted (0.0-1.0) edge between nodes, creating them if necessary.
The weight represents the importance of the connection (not the cost).
"""
if id1 == id2: return None
... | [
"def",
"add_edge",
"(",
"self",
",",
"id1",
",",
"id2",
",",
"weight",
"=",
"0.0",
",",
"length",
"=",
"1.0",
",",
"label",
"=",
"\"\"",
",",
"properties",
"=",
"{",
"}",
")",
":",
"if",
"id1",
"==",
"id2",
":",
"return",
"None",
"if",
"not",
"... | 32.518519 | 18.481481 |
def pseudo_with_symbol(self, symbol, allow_multi=False):
"""
Return the pseudo with the given chemical symbol.
Args:
symbols: String with the chemical symbol of the element
allow_multi: By default, the method raises ValueError
if multiple occurrences are ... | [
"def",
"pseudo_with_symbol",
"(",
"self",
",",
"symbol",
",",
"allow_multi",
"=",
"False",
")",
":",
"pseudos",
"=",
"self",
".",
"select_symbols",
"(",
"symbol",
",",
"ret_list",
"=",
"True",
")",
"if",
"not",
"pseudos",
"or",
"(",
"len",
"(",
"pseudos"... | 39.4 | 26 |
def is_consecutive(self):
"""
Determine whether or not the non-zero labels in the segmentation
image are consecutive (i.e. no missing values).
"""
if (self.labels[-1] - self.labels[0] + 1) == self.nlabels:
return True
else:
return False | [
"def",
"is_consecutive",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"labels",
"[",
"-",
"1",
"]",
"-",
"self",
".",
"labels",
"[",
"0",
"]",
"+",
"1",
")",
"==",
"self",
".",
"nlabels",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | 30 | 18.8 |
def get_stored_cert_serials(store):
'''
Get all of the certificate serials in the specified store
store
The store to get all the certificate serials from
CLI Example:
.. code-block:: bash
salt '*' certutil.get_stored_cert_serials <store>
'''
cmd = "certutil.exe -store {0}... | [
"def",
"get_stored_cert_serials",
"(",
"store",
")",
":",
"cmd",
"=",
"\"certutil.exe -store {0}\"",
".",
"format",
"(",
"store",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
"# match serial numbers by header position to work with multiple langua... | 28.277778 | 24.944444 |
def add_ref_annotation(self, id_tier, tier2, time, value='',
prev=None, svg=None):
"""Add a reference annotation.
.. note:: When a timepoint matches two annotations the new reference
annotation will reference to the first annotation. To circumvent this
it's alw... | [
"def",
"add_ref_annotation",
"(",
"self",
",",
"id_tier",
",",
"tier2",
",",
"time",
",",
"value",
"=",
"''",
",",
"prev",
"=",
"None",
",",
"svg",
"=",
"None",
")",
":",
"if",
"self",
".",
"tiers",
"[",
"id_tier",
"]",
"[",
"0",
"]",
":",
"raise... | 47.6875 | 17.78125 |
def C(w, Xs):
'''Calculate the cylinder center given the cylinder direction and
a list of data points.
'''
n = len(Xs)
P = projection_matrix(w)
Ys = [np.dot(P, X) for X in Xs]
A = calc_A(Ys)
A_hat = calc_A_hat(A, skew_matrix(w))
return np.dot(A_hat, sum(np.dot(Y, Y) * Y for Y in Ys... | [
"def",
"C",
"(",
"w",
",",
"Xs",
")",
":",
"n",
"=",
"len",
"(",
"Xs",
")",
"P",
"=",
"projection_matrix",
"(",
"w",
")",
"Ys",
"=",
"[",
"np",
".",
"dot",
"(",
"P",
",",
"X",
")",
"for",
"X",
"in",
"Xs",
"]",
"A",
"=",
"calc_A",
"(",
"... | 31 | 23.363636 |
def firmware_download_input_protocol_type_usb_protocol_usb_directory(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware_download = ET.Element("firmware_download")
config = firmware_download
input = ET.SubElement(firmware_download, "input")
... | [
"def",
"firmware_download_input_protocol_type_usb_protocol_usb_directory",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"firmware_download",
"=",
"ET",
".",
"Element",
"(",
"\"firmware_download\"",
")",... | 45.066667 | 15.4 |
def request(self, req_and_resp, opt=None, headers=None):
""" preprocess before performing a request, usually some patching.
authorization also applied here.
:param req_and_resp: tuple of Request and Response
:type req_and_resp: (Request, Response)
:param opt: customized options
... | [
"def",
"request",
"(",
"self",
",",
"req_and_resp",
",",
"opt",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"req",
",",
"resp",
"=",
"req_and_resp",
"# dump info for debugging",
"logger",
".",
"info",
"(",
"'request.url: {0}'",
".",
"format",
"(",
... | 38.814815 | 17 |
def make_class_method_decorator(classkey, modname=None):
"""
register a class to be injectable
classkey is a key that identifies the injected class
REMEMBER to call inject_instance in __init__
Args:
classkey : the class to be injected into
modname : the global __name__ of the module... | [
"def",
"make_class_method_decorator",
"(",
"classkey",
",",
"modname",
"=",
"None",
")",
":",
"global",
"__APP_MODNAME_REGISTER__",
"#if util_arg.VERBOSE or VERBOSE_CLASS:",
"if",
"VERBOSE_CLASS",
":",
"print",
"(",
"'[util_class] register via make_class_method_decorator classkey... | 42.830508 | 17.644068 |
def use_comparative_agent_view(self):
"""Pass through to provider ResourceAgentSession.use_comparative_agent_view"""
self._object_views['agent'] = COMPARATIVE
# self._get_provider_session('resource_agent_session') # To make sure the session is tracked
for session in self._get_provider_se... | [
"def",
"use_comparative_agent_view",
"(",
"self",
")",
":",
"self",
".",
"_object_views",
"[",
"'agent'",
"]",
"=",
"COMPARATIVE",
"# self._get_provider_session('resource_agent_session') # To make sure the session is tracked",
"for",
"session",
"in",
"self",
".",
"_get_provid... | 49.666667 | 16.333333 |
def async_mail_task(subject_or_message, to=None, template=None, **kwargs):
"""
Celery task to send emails asynchronously using the mail bundle.
"""
to = to or kwargs.pop('recipients', [])
msg = make_message(subject_or_message, to, template, **kwargs)
with mail.connect() as connection:
co... | [
"def",
"async_mail_task",
"(",
"subject_or_message",
",",
"to",
"=",
"None",
",",
"template",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"to",
"=",
"to",
"or",
"kwargs",
".",
"pop",
"(",
"'recipients'",
",",
"[",
"]",
")",
"msg",
"=",
"make_mess... | 41.375 | 13.125 |
def wait(self, task_id):
"""
Blocking method which wait end of task.
It's prefered to use :class:`carotte.Task` object directly
:param string task_id: Task ID
:returns: Task dict
:rtype: dict
"""
data = {
'action': 'wait',
'id': t... | [
"def",
"wait",
"(",
"self",
",",
"task_id",
")",
":",
"data",
"=",
"{",
"'action'",
":",
"'wait'",
",",
"'id'",
":",
"task_id",
"}",
"self",
".",
"__send_pyobj",
"(",
"data",
")",
"task",
"=",
"self",
".",
"__recv_pyobj",
"(",
"notimeout",
"=",
"True... | 24.764706 | 16.647059 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.