text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def write_csv_header(mol, csv_writer):
"""
Write the csv header
"""
# create line list where line elements for writing will be stored
line = []
# ID
line.append('id')
# status
line.append('status')
# query labels
queryList = mol.properties.keys()
for queryLabel in queryList... | [
"def",
"write_csv_header",
"(",
"mol",
",",
"csv_writer",
")",
":",
"# create line list where line elements for writing will be stored",
"line",
"=",
"[",
"]",
"# ID",
"line",
".",
"append",
"(",
"'id'",
")",
"# status",
"line",
".",
"append",
"(",
"'status'",
")"... | 18.142857 | 0.012469 |
def do_usufy(self, query, **kwargs):
"""
Verifying a usufy query in this platform.
This might be redefined in any class inheriting from Platform.
Args:
-----
query: The element to be searched.
Return:
-------
A list of elements to be app... | [
"def",
"do_usufy",
"(",
"self",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"[",
"]",
"test",
"=",
"self",
".",
"check_usufy",
"(",
"query",
",",
"*",
"*",
"kwargs",
")",
"if",
"test",
":",
"r",
"=",
"{",
"\"type\"",
":",
"... | 27.708333 | 0.001452 |
def lm_tfinal(damping_times, modes):
"""Return the maximum t_final of the modes given, with t_final the time
at which the amplitude falls to 1/1000 of the peak amplitude
"""
t_max = {}
for lmn in modes:
l, m, nmodes = int(lmn[0]), int(lmn[1]), int(lmn[2])
for n in range(nmodes):
... | [
"def",
"lm_tfinal",
"(",
"damping_times",
",",
"modes",
")",
":",
"t_max",
"=",
"{",
"}",
"for",
"lmn",
"in",
"modes",
":",
"l",
",",
"m",
",",
"nmodes",
"=",
"int",
"(",
"lmn",
"[",
"0",
"]",
")",
",",
"int",
"(",
"lmn",
"[",
"1",
"]",
")",
... | 34.384615 | 0.017429 |
def depth(args):
"""
%prog depth reads.bed features.bed
Calculate depth depth per feature using coverageBed.
"""
p = OptionParser(depth.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
readsbed, featsbed = args
fp... | [
"def",
"depth",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"depth",
".",
"__doc__",
")",
"p",
".",
"set_outfile",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
... | 29.9 | 0.001621 |
def _runner(self, classpath, main, jvm_options, args, cwd=None):
"""Runner factory. Called via Executor.execute()."""
command = self._create_command(classpath, main, jvm_options, args)
class Runner(self.Runner):
@property
def executor(this):
return self
@property
def comman... | [
"def",
"_runner",
"(",
"self",
",",
"classpath",
",",
"main",
",",
"jvm_options",
",",
"args",
",",
"cwd",
"=",
"None",
")",
":",
"command",
"=",
"self",
".",
"_create_command",
"(",
"classpath",
",",
"main",
",",
"jvm_options",
",",
"args",
")",
"clas... | 40.142857 | 0.013901 |
def update(self, **kwargs):
"Update document not update index."
kw = dict(index=self.name, doc_type=self.doc_type, ignore=[404])
kw.update(**kwargs)
return self._client.update(**kw) | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kw",
"=",
"dict",
"(",
"index",
"=",
"self",
".",
"name",
",",
"doc_type",
"=",
"self",
".",
"doc_type",
",",
"ignore",
"=",
"[",
"404",
"]",
")",
"kw",
".",
"update",
"(",
"*",
... | 41.8 | 0.00939 |
def ckw03(handle, begtim, endtim, inst, ref, avflag, segid, nrec, sclkdp, quats,
avvs, nints, starts):
"""
Add a type 3 segment to a C-kernel.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw03_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param begti... | [
"def",
"ckw03",
"(",
"handle",
",",
"begtim",
",",
"endtim",
",",
"inst",
",",
"ref",
",",
"avflag",
",",
"segid",
",",
"nrec",
",",
"sclkdp",
",",
"quats",
",",
"avvs",
",",
"nints",
",",
"starts",
")",
":",
"handle",
"=",
"ctypes",
".",
"c_int",
... | 37 | 0.001075 |
def perform(self, agent_indices, observ):
"""Compute batch of actions and a summary for a batch of observation.
Args:
agent_indices: Tensor containing current batch indices.
observ: Tensor of a batch of observations for all agents.
Returns:
Tuple of action batch tensor and summary tensor... | [
"def",
"perform",
"(",
"self",
",",
"agent_indices",
",",
"observ",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"'perform/'",
")",
":",
"observ",
"=",
"self",
".",
"_observ_filter",
".",
"transform",
"(",
"observ",
")",
"if",
"self",
".",
"_last_stat... | 45.266667 | 0.00865 |
def validate_bytes(data, length=4):
'''
Raises ValueError if data is not bytes.
Raises ValueError if len(data) is not length.
Length may be None for unknown lengths (e.g. scripts).
length=None will allow 0 length data.
'''
if (not isinstance(data, ByteData)
... | [
"def",
"validate_bytes",
"(",
"data",
",",
"length",
"=",
"4",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"data",
",",
"ByteData",
")",
"and",
"not",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"and",
"not",
"isinstance",
"(",
"data",
",",
"byt... | 39.55 | 0.002469 |
def get_version(self, layer_id, version_id, expand=[]):
"""
Get a specific version of a layer.
"""
target_url = self.client.get_url('VERSION', 'GET', 'single', {'layer_id': layer_id, 'version_id': version_id})
return self._get(target_url, expand=expand) | [
"def",
"get_version",
"(",
"self",
",",
"layer_id",
",",
"version_id",
",",
"expand",
"=",
"[",
"]",
")",
":",
"target_url",
"=",
"self",
".",
"client",
".",
"get_url",
"(",
"'VERSION'",
",",
"'GET'",
",",
"'single'",
",",
"{",
"'layer_id'",
":",
"laye... | 48 | 0.010239 |
def add_triple(self, p, o, auto_refresh=True):
'''
add triple by providing p,o, assumes s = subject
Args:
p (rdflib.term.URIRef): predicate
o (): object
auto_refresh (bool): whether or not to update object-like self.rdf.triples
Returns:
None: adds triple to self.rdf.graph
'''
self.rdf.graph.... | [
"def",
"add_triple",
"(",
"self",
",",
"p",
",",
"o",
",",
"auto_refresh",
"=",
"True",
")",
":",
"self",
".",
"rdf",
".",
"graph",
".",
"add",
"(",
"(",
"self",
".",
"uri",
",",
"p",
",",
"self",
".",
"_handle_object",
"(",
"o",
")",
")",
")",... | 23.611111 | 0.031674 |
def get_file_list(self):
"""Retrieve the list of absolute paths to all the files in this data source.
Returns:
List[str] List of absolute paths.
"""
if os.path.isdir(self.root_path):
return [os.path.join(self.root_path, f) for f in os.listdir(self.root_path)
... | [
"def",
"get_file_list",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"root_path",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"root_path",
",",
"f",
")",
"for",
"f",
"in",
"os",
... | 38.909091 | 0.009132 |
def argmaxMulti(a, groupKeys, assumeSorted=False):
"""
This is like numpy's argmax, but it returns multiple maximums.
It gets the indices of the max values of each group in 'a', grouping the
elements by their corresponding value in 'groupKeys'.
@param a (numpy array)
An array of values that will be compar... | [
"def",
"argmaxMulti",
"(",
"a",
",",
"groupKeys",
",",
"assumeSorted",
"=",
"False",
")",
":",
"if",
"not",
"assumeSorted",
":",
"# Use a stable sort algorithm",
"sorter",
"=",
"np",
".",
"argsort",
"(",
"groupKeys",
",",
"kind",
"=",
"\"mergesort\"",
")",
"... | 29.583333 | 0.00818 |
def fit(self, p, x, y):
"""
fit the regression method and also Krige the residual
Parameters
----------
p: ndarray
(Ns, d) array of predictor variables (Ns samples, d dimensions)
for regression
x: ndarray
ndarray of (x, y) points. Need... | [
"def",
"fit",
"(",
"self",
",",
"p",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"regression_model",
".",
"fit",
"(",
"p",
",",
"y",
")",
"ml_pred",
"=",
"self",
".",
"regression_model",
".",
"predict",
"(",
"p",
")",
"print",
"(",
"'Finished learni... | 36.409091 | 0.002433 |
def getProjectionMatrix(self, eEye, fNearZ, fFarZ):
"""The projection matrix for the specified eye"""
fn = self.function_table.getProjectionMatrix
result = fn(eEye, fNearZ, fFarZ)
return result | [
"def",
"getProjectionMatrix",
"(",
"self",
",",
"eEye",
",",
"fNearZ",
",",
"fFarZ",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getProjectionMatrix",
"result",
"=",
"fn",
"(",
"eEye",
",",
"fNearZ",
",",
"fFarZ",
")",
"return",
"result"
] | 36.833333 | 0.00885 |
def splay(vec):
""" Determine two lengths to split stride the input vector by
"""
N2 = 2 ** int(numpy.log2( len(vec) ) / 2)
N1 = len(vec) / N2
return N1, N2 | [
"def",
"splay",
"(",
"vec",
")",
":",
"N2",
"=",
"2",
"**",
"int",
"(",
"numpy",
".",
"log2",
"(",
"len",
"(",
"vec",
")",
")",
"/",
"2",
")",
"N1",
"=",
"len",
"(",
"vec",
")",
"/",
"N2",
"return",
"N1",
",",
"N2"
] | 28.5 | 0.017045 |
def write_skycatalog(self,filename):
""" Write out the all_radec catalog for this image to a file.
"""
if self.all_radec is None:
return
ralist = self.all_radec[0]#.tolist()
declist = self.all_radec[1]#.tolist()
f = open(filename,'w')
f.write("#Sky pos... | [
"def",
"write_skycatalog",
"(",
"self",
",",
"filename",
")",
":",
"if",
"self",
".",
"all_radec",
"is",
"None",
":",
"return",
"ralist",
"=",
"self",
".",
"all_radec",
"[",
"0",
"]",
"#.tolist()",
"declist",
"=",
"self",
".",
"all_radec",
"[",
"1",
"]... | 37.714286 | 0.018484 |
def get_valid_directory_list(input_directory):
"""
Get a list of folders
"""
valid_input_directories = []
for directory in os.listdir(input_directory):
if os.path.isdir(os.path.join(input_directory, directory)):
valid_input_directories.append(directory)
else:
... | [
"def",
"get_valid_directory_list",
"(",
"input_directory",
")",
":",
"valid_input_directories",
"=",
"[",
"]",
"for",
"directory",
"in",
"os",
".",
"listdir",
"(",
"input_directory",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
... | 36.818182 | 0.00241 |
def repr_args(args):
"""formats a list of function arguments prettily but as working code
(kwargs are tuples (argname, argvalue)
"""
res = []
for x in args:
if isinstance(x, tuple) and len(x) == 2:
key, value = x
# todo: exclude this key if value is its default
... | [
"def",
"repr_args",
"(",
"args",
")",
":",
"res",
"=",
"[",
"]",
"for",
"x",
"in",
"args",
":",
"if",
"isinstance",
"(",
"x",
",",
"tuple",
")",
"and",
"len",
"(",
"x",
")",
"==",
"2",
":",
"key",
",",
"value",
"=",
"x",
"# todo: exclude this key... | 30.571429 | 0.002268 |
def _add_trace_frame(self, graph: TraceGraph, trace_frame: TraceFrame) -> None:
""" Copies the trace frame from 'graph' to this (self) graph.
Also copies all the trace_frame-leaf assocs since we don't
know which ones are needed until we know the issue that reaches it
"""
trace_fr... | [
"def",
"_add_trace_frame",
"(",
"self",
",",
"graph",
":",
"TraceGraph",
",",
"trace_frame",
":",
"TraceFrame",
")",
"->",
"None",
":",
"trace_frame_id",
"=",
"trace_frame",
".",
"id",
".",
"local_id",
"self",
".",
"add_trace_frame",
"(",
"trace_frame",
")",
... | 57.8 | 0.00227 |
def start(self):
"""Start the receiver.
"""
if not self._is_running:
self._do_run = True
self._thread.start()
return self | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_is_running",
":",
"self",
".",
"_do_run",
"=",
"True",
"self",
".",
"_thread",
".",
"start",
"(",
")",
"return",
"self"
] | 24.428571 | 0.011299 |
def estimate_hr(self,R,z=0.,dR=10.**-8.,**kwargs):
"""
NAME:
estimate_hr
PURPOSE:
estimate the exponential scale length at R
INPUT:
R - Galactocentric radius (can be Quantity)
z= height (default: 0 pc) (can be Quantity)
dR- ra... | [
"def",
"estimate_hr",
"(",
"self",
",",
"R",
",",
"z",
"=",
"0.",
",",
"dR",
"=",
"10.",
"**",
"-",
"8.",
",",
"*",
"*",
"kwargs",
")",
":",
"Rs",
"=",
"[",
"R",
"-",
"dR",
"/",
"2.",
",",
"R",
"+",
"dR",
"/",
"2.",
"]",
"if",
"z",
"is"... | 22.625 | 0.014831 |
def update_particle(position_update, velocity_update, state, nbest_topology,
idx_particle):
""" Update function for a particle.
Calculates and updates the velocity and position of a particle for a
single iteration of the PSO algorithm. Social best particle is determined
by the state... | [
"def",
"update_particle",
"(",
"position_update",
",",
"velocity_update",
",",
"state",
",",
"nbest_topology",
",",
"idx_particle",
")",
":",
"(",
"idx",
",",
"particle",
")",
"=",
"idx_particle",
"nbest",
"=",
"state",
".",
"swarm",
"[",
"nbest_topology",
"["... | 37.555556 | 0.000962 |
async def get_module_data(request):
"""
Query a module (by its serial number) for its live data
"""
hw = hw_from_req(request)
requested_serial = request.match_info['serial']
res = None
if ff.use_protocol_api_v2():
hw_mods = await hw.discover_modules()
else:
hw_mods = hw.... | [
"async",
"def",
"get_module_data",
"(",
"request",
")",
":",
"hw",
"=",
"hw_from_req",
"(",
"request",
")",
"requested_serial",
"=",
"request",
".",
"match_info",
"[",
"'serial'",
"]",
"res",
"=",
"None",
"if",
"ff",
".",
"use_protocol_api_v2",
"(",
")",
"... | 30.818182 | 0.001431 |
def register(self, key_or_tag, f_val):
"""Register a custom transit tag and decoder/parser function for use
during reads.
"""
self.reader.decoder.register(key_or_tag, f_val) | [
"def",
"register",
"(",
"self",
",",
"key_or_tag",
",",
"f_val",
")",
":",
"self",
".",
"reader",
".",
"decoder",
".",
"register",
"(",
"key_or_tag",
",",
"f_val",
")"
] | 40.2 | 0.009756 |
def should_do_final_get(self):
"""Check whether the polling should end doing a final GET.
:param requests.Response response: latest REST call response.
:rtype: bool
"""
return ((self.async_url or not self.resource) and self.method in {'PUT', 'PATCH'}) \
or (self.... | [
"def",
"should_do_final_get",
"(",
"self",
")",
":",
"return",
"(",
"(",
"self",
".",
"async_url",
"or",
"not",
"self",
".",
"resource",
")",
"and",
"self",
".",
"method",
"in",
"{",
"'PUT'",
",",
"'PATCH'",
"}",
")",
"or",
"(",
"self",
".",
"lro_opt... | 54.5 | 0.011287 |
def record_modify_subfield(rec, tag, subfield_code, value, subfield_position,
field_position_global=None,
field_position_local=None):
"""Modify subfield at specified position.
Specify the subfield by tag, field number and subfield position.
"""
subf... | [
"def",
"record_modify_subfield",
"(",
"rec",
",",
"tag",
",",
"subfield_code",
",",
"value",
",",
"subfield_position",
",",
"field_position_global",
"=",
"None",
",",
"field_position_local",
"=",
"None",
")",
":",
"subfields",
"=",
"record_get_subfields",
"(",
"re... | 39.294118 | 0.001462 |
def base_type(self, value):
"""The base_type property.
Args:
value (string). the property value.
"""
if value == self._defaults['baseType'] and 'baseType' in self._values:
del self._values['baseType']
else:
self._values['baseType'] = v... | [
"def",
"base_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"_defaults",
"[",
"'baseType'",
"]",
"and",
"'baseType'",
"in",
"self",
".",
"_values",
":",
"del",
"self",
".",
"_values",
"[",
"'baseType'",
"]",
"else",
":",
... | 31.5 | 0.009259 |
def get_iscsi_initiator_info(self):
"""Give iSCSI initiator information of iLO.
:returns: iSCSI initiator information.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the system is
in the bios boot mode.
"""
headers, bio... | [
"def",
"get_iscsi_initiator_info",
"(",
"self",
")",
":",
"headers",
",",
"bios_uri",
",",
"bios_settings",
"=",
"self",
".",
"_check_bios_resource",
"(",
")",
"if",
"(",
"'links'",
"in",
"bios_settings",
"and",
"'iScsi'",
"in",
"bios_settings",
"[",
"'links'",
... | 43.904762 | 0.002123 |
def sum_fields(layer, output_field_key, input_fields):
"""Sum the value of input_fields and put it as output_field.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param output_field_key: The output field definition key.
:type output_field_key: basestring
:param input_fields: Lis... | [
"def",
"sum_fields",
"(",
"layer",
",",
"output_field_key",
",",
"input_fields",
")",
":",
"field_definition",
"=",
"definition",
"(",
"output_field_key",
")",
"output_field_name",
"=",
"field_definition",
"[",
"'field_name'",
"]",
"# If the fields only has one element",
... | 38.075472 | 0.000483 |
def cone_beam_geometry(space, src_radius, det_radius, num_angles=None,
short_scan=False, det_shape=None):
r"""Create a default fan or cone beam geometry from ``space``.
This function is intended for simple test cases where users do not
need the full flexibility of the geometries, but... | [
"def",
"cone_beam_geometry",
"(",
"space",
",",
"src_radius",
",",
"det_radius",
",",
"num_angles",
"=",
"None",
",",
"short_scan",
"=",
"False",
",",
"det_shape",
"=",
"None",
")",
":",
"# Find maximum distance from rotation axis",
"corners",
"=",
"space",
".",
... | 38.269406 | 0.000116 |
def pitch(ax, ay, az):
'''Angle of x-axis relative to ground (theta)
Args
----
ax: ndarray
x-axis acceleration values
ay: ndarray
y-axis acceleration values
az: ndarray
z-axis acceleration values
Returns
-------
pitch: ndarray
Pitch angle in radians
... | [
"def",
"pitch",
"(",
"ax",
",",
"ay",
",",
"az",
")",
":",
"import",
"numpy",
"# arctan2 not needed here to cover all quadrants, just for consistency",
"return",
"numpy",
".",
"arctan",
"(",
"ax",
",",
"numpy",
".",
"sqrt",
"(",
"ay",
"**",
"2",
"+",
"az",
"... | 22.65 | 0.002119 |
def get_arp_table(self, switch_ip, ip=None, mac=None, interf=None, arp_type=None):
'''
Get the ARP table from a switch.
Args:
switch_ip IP address of the device
ip Filter results by IP (regex)
mac Filter results by M... | [
"def",
"get_arp_table",
"(",
"self",
",",
"switch_ip",
",",
"ip",
"=",
"None",
",",
"mac",
"=",
"None",
",",
"interf",
"=",
"None",
",",
"arp_type",
"=",
"None",
")",
":",
"node",
"=",
"natlas_node",
"(",
"switch_ip",
")",
"if",
"(",
"node",
".",
"... | 33.090909 | 0.011341 |
def execute(mp):
"""
Example process for testing.
Inputs:
-------
file1
raster file
Parameters:
-----------
Output:
-------
np.ndarray
"""
# Reading and writing data works like this:
with mp.open("file1", resampling="bilinear") as raster_file:
if ra... | [
"def",
"execute",
"(",
"mp",
")",
":",
"# Reading and writing data works like this:",
"with",
"mp",
".",
"open",
"(",
"\"file1\"",
",",
"resampling",
"=",
"\"bilinear\"",
")",
"as",
"raster_file",
":",
"if",
"raster_file",
".",
"is_empty",
"(",
")",
":",
"retu... | 21.708333 | 0.001838 |
def add_unique_id(self):
"""
Adds a unique id property to each feature.
Raises:
- An Exception if any of the features already
have an "id" field.
"""
uid = 0
for feature in self._data["features"]:
if feature["properties"... | [
"def",
"add_unique_id",
"(",
"self",
")",
":",
"uid",
"=",
"0",
"for",
"feature",
"in",
"self",
".",
"_data",
"[",
"\"features\"",
"]",
":",
"if",
"feature",
"[",
"\"properties\"",
"]",
".",
"get",
"(",
"\"id\"",
")",
":",
"raise",
"Exception",
"(",
... | 28.9375 | 0.01046 |
def f_supports(self, data):
"""Checks if input data is supported by the parameter."""
dtype = type(data)
if dtype is tuple or dtype is list and len(data) == 0:
return True # ArrayParameter does support empty tuples
elif dtype is np.ndarray and data.size == 0 and data.ndim =... | [
"def",
"f_supports",
"(",
"self",
",",
"data",
")",
":",
"dtype",
"=",
"type",
"(",
"data",
")",
"if",
"dtype",
"is",
"tuple",
"or",
"dtype",
"is",
"list",
"and",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"True",
"# ArrayParameter does suppor... | 52.111111 | 0.010482 |
def task_status(request, task_id):
"""Returns task status and result in JSON format."""
result = AsyncResult(task_id)
state, retval = result.state, result.result
response_data = {'id': task_id, 'status': state, 'result': retval}
if state in states.EXCEPTION_STATES:
traceback = result.traceba... | [
"def",
"task_status",
"(",
"request",
",",
"task_id",
")",
":",
"result",
"=",
"AsyncResult",
"(",
"task_id",
")",
"state",
",",
"retval",
"=",
"result",
".",
"state",
",",
"result",
".",
"result",
"response_data",
"=",
"{",
"'id'",
":",
"task_id",
",",
... | 49.909091 | 0.001789 |
def dbserver(cmd, dbhostport=None,
dbpath=os.path.expanduser(config.dbserver.file)):
"""
start/stop/restart the database server, or return its status
"""
if config.dbserver.multi_user and getpass.getuser() != 'openquake':
sys.exit('oq dbserver only works in single user mode')
s... | [
"def",
"dbserver",
"(",
"cmd",
",",
"dbhostport",
"=",
"None",
",",
"dbpath",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"config",
".",
"dbserver",
".",
"file",
")",
")",
":",
"if",
"config",
".",
"dbserver",
".",
"multi_user",
"and",
"getpass",
... | 35.444444 | 0.001017 |
def end_timing(self):
"""
Completes measuring time interval and updates counter.
"""
if self._callback != None:
elapsed = time.clock() * 1000 - self._start
self._callback.end_timing(self._counter, elapsed) | [
"def",
"end_timing",
"(",
"self",
")",
":",
"if",
"self",
".",
"_callback",
"!=",
"None",
":",
"elapsed",
"=",
"time",
".",
"clock",
"(",
")",
"*",
"1000",
"-",
"self",
".",
"_start",
"self",
".",
"_callback",
".",
"end_timing",
"(",
"self",
".",
"... | 32.75 | 0.011152 |
def split_input(img):
"""
img: an RGB image of shape (s, 2s, 3).
:return: [input, output]
"""
# split the image into left + right pairs
s = img.shape[0]
assert img.shape[1] == 2 * s
input, output = img[:, :s, :], img[:, s:, :]
if args.mode == 'BtoA':
input, output = output, i... | [
"def",
"split_input",
"(",
"img",
")",
":",
"# split the image into left + right pairs",
"s",
"=",
"img",
".",
"shape",
"[",
"0",
"]",
"assert",
"img",
".",
"shape",
"[",
"1",
"]",
"==",
"2",
"*",
"s",
"input",
",",
"output",
"=",
"img",
"[",
":",
",... | 32.8125 | 0.001852 |
def handle_model_generation(config, raml_resource):
""" Generates model name and runs `setup_data_model` to get
or generate actual model class.
:param raml_resource: Instance of ramlfications.raml.ResourceNode.
"""
model_name = generate_model_name(raml_resource)
try:
return setup_data_m... | [
"def",
"handle_model_generation",
"(",
"config",
",",
"raml_resource",
")",
":",
"model_name",
"=",
"generate_model_name",
"(",
"raml_resource",
")",
"try",
":",
"return",
"setup_data_model",
"(",
"config",
",",
"raml_resource",
",",
"model_name",
")",
"except",
"... | 40.090909 | 0.002217 |
def get_X_slice(self, rmind):
'''get X with slicing'''
if self.forest.optimize_memory_use:
return self.forest.X[:, rmind][self.subsample]
else:
return self.X[:, rmind] | [
"def",
"get_X_slice",
"(",
"self",
",",
"rmind",
")",
":",
"if",
"self",
".",
"forest",
".",
"optimize_memory_use",
":",
"return",
"self",
".",
"forest",
".",
"X",
"[",
":",
",",
"rmind",
"]",
"[",
"self",
".",
"subsample",
"]",
"else",
":",
"return"... | 35 | 0.009302 |
def master_config(opts, vm_):
'''
Return a master's configuration for the provided options and VM
'''
# Let's get a copy of the salt master default options
master = copy.deepcopy(salt.config.DEFAULT_MASTER_OPTS)
# Some default options are Null, let's set a reasonable default
master.update(
... | [
"def",
"master_config",
"(",
"opts",
",",
"vm_",
")",
":",
"# Let's get a copy of the salt master default options",
"master",
"=",
"copy",
".",
"deepcopy",
"(",
"salt",
".",
"config",
".",
"DEFAULT_MASTER_OPTS",
")",
"# Some default options are Null, let's set a reasonable ... | 30.391304 | 0.001387 |
def wfdb_strptime(time_string):
"""
Given a time string in an acceptable wfdb format, return
a datetime.time object.
Valid formats: SS, MM:SS, HH:MM:SS, all with and without microsec.
"""
n_colons = time_string.count(':')
if n_colons == 0:
time_fmt = '%S'
elif n_colons == 1:
... | [
"def",
"wfdb_strptime",
"(",
"time_string",
")",
":",
"n_colons",
"=",
"time_string",
".",
"count",
"(",
"':'",
")",
"if",
"n_colons",
"==",
"0",
":",
"time_fmt",
"=",
"'%S'",
"elif",
"n_colons",
"==",
"1",
":",
"time_fmt",
"=",
"'%M:%S'",
"elif",
"n_col... | 25.1 | 0.001919 |
def int2str(self, int_value):
"""Conversion integer => class name string."""
if self._int2str:
# Maybe should support batched np array/eager tensors, to allow things
# like
# out_ids = model(inputs)
# labels = cifar10.info.features['label'].int2str(out_ids)
return self._int2str[int... | [
"def",
"int2str",
"(",
"self",
",",
"int_value",
")",
":",
"if",
"self",
".",
"_int2str",
":",
"# Maybe should support batched np array/eager tensors, to allow things",
"# like",
"# out_ids = model(inputs)",
"# labels = cifar10.info.features['label'].int2str(out_ids)",
"return",
... | 39.846154 | 0.013208 |
def visit_importfrom(self, node):
"""return an astroid.ImportFrom node as string"""
return "from %s import %s" % (
"." * (node.level or 0) + node.modname,
_import_string(node.names),
) | [
"def",
"visit_importfrom",
"(",
"self",
",",
"node",
")",
":",
"return",
"\"from %s import %s\"",
"%",
"(",
"\".\"",
"*",
"(",
"node",
".",
"level",
"or",
"0",
")",
"+",
"node",
".",
"modname",
",",
"_import_string",
"(",
"node",
".",
"names",
")",
","... | 37.833333 | 0.008621 |
def submit_work_and_wait(self, work, workunit_parent=None):
"""Submit work to be executed on this pool, but wait for it to complete.
- work: The work to execute.
- workunit_parent: If specified, work is accounted for under this workunit.
Returns a list of return values of each invocation, in order. T... | [
"def",
"submit_work_and_wait",
"(",
"self",
",",
"work",
",",
"workunit_parent",
"=",
"None",
")",
":",
"if",
"work",
"is",
"None",
"or",
"len",
"(",
"work",
".",
"args_tuples",
")",
"==",
"0",
":",
"# map hangs on 0-length iterables.",
"return",
"[",
"]",
... | 52.411765 | 0.012128 |
def multiply(lhs, rhs):
"""Returns element-wise product of the input arrays with broadcasting.
Equivalent to ``lhs * rhs`` and ``mx.nd.broadcast_mul(lhs, rhs)``
when shapes of lhs and rhs do not match. If lhs.shape == rhs.shape,
this is equivalent to ``mx.nd.elemwise_mul(lhs, rhs)``
..... | [
"def",
"multiply",
"(",
"lhs",
",",
"rhs",
")",
":",
"# pylint: disable= no-member, protected-access",
"if",
"isinstance",
"(",
"lhs",
",",
"NDArray",
")",
"and",
"isinstance",
"(",
"rhs",
",",
"NDArray",
")",
"and",
"lhs",
".",
"shape",
"==",
"rhs",
".",
... | 30.493827 | 0.001176 |
def gammatone(freq, bandwidth):
"""
``Slaney, M. "An Efficient Implementation of the Patterson-Holdsworth
Auditory Filter Bank", Apple Computer Technical Report #35, 1993.``
"""
A = exp(-bandwidth)
cosw = cos(freq)
sinw = sin(freq)
sig = [1., -1.]
coeff = [cosw + s1 * (sqrt(2) + s2) * sinw for s1 ... | [
"def",
"gammatone",
"(",
"freq",
",",
"bandwidth",
")",
":",
"A",
"=",
"exp",
"(",
"-",
"bandwidth",
")",
"cosw",
"=",
"cos",
"(",
"freq",
")",
"sinw",
"=",
"sin",
"(",
"freq",
")",
"sig",
"=",
"[",
"1.",
",",
"-",
"1.",
"]",
"coeff",
"=",
"[... | 38.2 | 0.018739 |
def vm_detach_nic(name, kwargs=None, call=None):
'''
Detaches a disk from a virtual machine.
.. versionadded:: 2016.3.0
name
The name of the VM from which to detach the network interface.
nic_id
The ID of the nic to detach.
CLI Example:
.. code-block:: bash
salt... | [
"def",
"vm_detach_nic",
"(",
"name",
",",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The vm_detach_nic action must be called with -a or --action.'",
")",
"if",
"kwargs",
"i... | 23.777778 | 0.000898 |
def _fail(self, request_id, failure, duration):
"""Publish a CommandFailedEvent."""
self.listeners.publish_command_failure(
duration, failure, self.name,
request_id, self.sock_info.address, self.op_id) | [
"def",
"_fail",
"(",
"self",
",",
"request_id",
",",
"failure",
",",
"duration",
")",
":",
"self",
".",
"listeners",
".",
"publish_command_failure",
"(",
"duration",
",",
"failure",
",",
"self",
".",
"name",
",",
"request_id",
",",
"self",
".",
"sock_info"... | 47.4 | 0.008299 |
def get_supported_permissions(self):
"""
Get permissions which this handler can treat.
Specified with :attr:`includes` and :attr:`excludes` of this instance.
Returns
-------
set
A set instance of `app_label.codename` formatted permission strings
"""
... | [
"def",
"get_supported_permissions",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_perms_cache'",
")",
":",
"if",
"(",
"self",
".",
"includes",
"and",
"isinstance",
"(",
"self",
".",
"includes",
",",
"collections",
".",
"Callable",
")"... | 37.384615 | 0.002006 |
def _max(self):
"""Getter for the maximum series value"""
return (
self.range[1] if (self.range and self.range[1] is not None) else
(max(self._values) if self._values else None)
) | [
"def",
"_max",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"range",
"[",
"1",
"]",
"if",
"(",
"self",
".",
"range",
"and",
"self",
".",
"range",
"[",
"1",
"]",
"is",
"not",
"None",
")",
"else",
"(",
"max",
"(",
"self",
".",
"_values",
... | 37 | 0.008811 |
def toggle_settings(
toolbar=False, nbname=False, hideprompt=False, kernellogo=False):
"""Toggle main notebook toolbar (e.g., buttons), filename,
and kernel logo."""
toggle = ''
if toolbar:
toggle += 'div#maintoolbar {margin-left: 8px !important;}\n'
toggle += '.toolbar.containe... | [
"def",
"toggle_settings",
"(",
"toolbar",
"=",
"False",
",",
"nbname",
"=",
"False",
",",
"hideprompt",
"=",
"False",
",",
"kernellogo",
"=",
"False",
")",
":",
"toggle",
"=",
"''",
"if",
"toolbar",
":",
"toggle",
"+=",
"'div#maintoolbar {margin-left: 8px !imp... | 48.166667 | 0.002261 |
def read_hip(self, length, extension):
"""Read Host Identity Protocol.
Structure of HIP header [RFC 5201][RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-... | [
"def",
"read_hip",
"(",
"self",
",",
"length",
",",
"extension",
")",
":",
"if",
"length",
"is",
"None",
":",
"length",
"=",
"len",
"(",
"self",
")",
"_next",
"=",
"self",
".",
"_read_protos",
"(",
"1",
")",
"_hlen",
"=",
"self",
".",
"_read_unpack",... | 49.22619 | 0.001185 |
def small_parts(script, ratio=0.2, non_closed_only=False):
""" Select & delete the small disconnected parts (components) of a mesh.
Args:
script: the FilterScript object or script filename to write
the filter to.
ratio (float): This ratio (between 0 and 1) defines the meaning of
... | [
"def",
"small_parts",
"(",
"script",
",",
"ratio",
"=",
"0.2",
",",
"non_closed_only",
"=",
"False",
")",
":",
"select",
".",
"small_parts",
"(",
"script",
",",
"ratio",
",",
"non_closed_only",
")",
"selected",
"(",
"script",
")",
"return",
"None"
] | 33.636364 | 0.001314 |
def listdir(self, relpath, rsc=None):
"""
Returns a list of the files within a path. When compiled, it will
list the files within a QResource, otherwise will list the files
within the directory.
:param relpath | <str>
rsc | <str> || N... | [
"def",
"listdir",
"(",
"self",
",",
"relpath",
",",
"rsc",
"=",
"None",
")",
":",
"filepath",
"=",
"self",
".",
"find",
"(",
"relpath",
",",
"rsc",
")",
"# parse a resource object\r",
"if",
"filepath",
".",
"startswith",
"(",
"':'",
")",
":",
"resource",... | 31.08 | 0.009988 |
def geometry_range(crd_range, elev, crd_type):
"""
Range of coordinates. (e.g. 2 latitude coordinates, and 0 longitude coordinates)
:param crd_range: Latitude or Longitude values
:param elev: Elevation value
:param crd_type: Coordinate type, lat or lon
:return dict:
"""
d = OrderedDict(... | [
"def",
"geometry_range",
"(",
"crd_range",
",",
"elev",
",",
"crd_type",
")",
":",
"d",
"=",
"OrderedDict",
"(",
")",
"coordinates",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"crd_range",
")",
")",
"]",
"# latitude",
"if",
"crd_... | 27.966667 | 0.002304 |
def number_to_lower_endian(n, base):
"""Helper function: convert a number to a list of digits in the given base."""
if n < base:
return [n]
return [n % base] + number_to_lower_endian(n // base, base) | [
"def",
"number_to_lower_endian",
"(",
"n",
",",
"base",
")",
":",
"if",
"n",
"<",
"base",
":",
"return",
"[",
"n",
"]",
"return",
"[",
"n",
"%",
"base",
"]",
"+",
"number_to_lower_endian",
"(",
"n",
"//",
"base",
",",
"base",
")"
] | 41 | 0.023923 |
def cprint(
text,
fg=Color.normal,
bg=Color.normal,
fg_dark=False,
bg_dark=False,
underlined=False,
parse=False,
):
"""Print string in to stdout using colored font.
See L{set_color} for more details about colors.
Args:
text (str): Text that needs to be pri... | [
"def",
"cprint",
"(",
"text",
",",
"fg",
"=",
"Color",
".",
"normal",
",",
"bg",
"=",
"Color",
".",
"normal",
",",
"fg_dark",
"=",
"False",
",",
"bg_dark",
"=",
"False",
",",
"underlined",
"=",
"False",
",",
"parse",
"=",
"False",
",",
")",
":",
... | 29.157895 | 0.001747 |
def enqueue_event(self, event):
"""Enqueue the given event.
The event contains host data (ip, mac, port) which will be used to
update the spoofing rule for the host in the iptables.
"""
LOG.debug('Enqueue iptable event %s.', event)
if event.get('status') == 'up':
... | [
"def",
"enqueue_event",
"(",
"self",
",",
"event",
")",
":",
"LOG",
".",
"debug",
"(",
"'Enqueue iptable event %s.'",
",",
"event",
")",
"if",
"event",
".",
"get",
"(",
"'status'",
")",
"==",
"'up'",
":",
"for",
"rule",
"in",
"self",
".",
"rule_info",
... | 42.47619 | 0.002193 |
def get_sentences_for_agent(text, stmts, max_sentences=None):
"""Returns evidence sentences with a given agent text from a list of statements
Parameters
----------
text : str
An agent text
stmts : list of :py:class:`indra.statements.Statement`
INDRA Statements to search in for evid... | [
"def",
"get_sentences_for_agent",
"(",
"text",
",",
"stmts",
",",
"max_sentences",
"=",
"None",
")",
":",
"sentences",
"=",
"[",
"]",
"for",
"stmt",
"in",
"stmts",
":",
"for",
"agent",
"in",
"stmt",
".",
"agent_list",
"(",
")",
":",
"if",
"agent",
"is"... | 33.566667 | 0.001931 |
def _convert_endpoint(endpoint):
"""Converts py_zipkin's Endpoint to Protobuf's Endpoint.
:param endpoint: py_zipkins' endpoint to convert.
:type endpoint: py_zipkin.encoding.Endpoint
:return: corresponding protobuf's endpoint.
:rtype: zipkin_pb2.Endpoint
"""
pb_endpoint = zipkin_pb2.Endpoi... | [
"def",
"_convert_endpoint",
"(",
"endpoint",
")",
":",
"pb_endpoint",
"=",
"zipkin_pb2",
".",
"Endpoint",
"(",
")",
"if",
"endpoint",
".",
"service_name",
":",
"pb_endpoint",
".",
"service_name",
"=",
"endpoint",
".",
"service_name",
"if",
"endpoint",
".",
"po... | 34.9 | 0.001395 |
def get_display(unicode_or_str, encoding='utf-8', upper_is_rtl=False,
base_dir=None, debug=False):
"""Accepts unicode or string. In case it's a string, `encoding`
is needed as it works on unicode ones (default:"utf-8").
Set `upper_is_rtl` to True to treat upper case chars as strong 'R'
... | [
"def",
"get_display",
"(",
"unicode_or_str",
",",
"encoding",
"=",
"'utf-8'",
",",
"upper_is_rtl",
"=",
"False",
",",
"base_dir",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"storage",
"=",
"get_empty_storage",
"(",
")",
"# utf-8 ? we need unicode",
"if... | 30.62 | 0.000633 |
def from_package(cls, parse_context, pkg='', rev='', **kwargs):
"""
:param string pkg: The package import paths within the remote library; by default just the
root package will be available (equivalent to passing `pkg=''`).
:param string rev: Identifies which version of the remote lib... | [
"def",
"from_package",
"(",
"cls",
",",
"parse_context",
",",
"pkg",
"=",
"''",
",",
"rev",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'name'",
"in",
"kwargs",
":",
"raise",
"TargetDefinitionException",
"(",
"Address",
"(",
"parse_context",
"."... | 71.296296 | 0.009739 |
def url(self, pattern, method=None, name=None):
"""Decorator to map url pattern to the callable.
Args:
pattern (:obj:`str`): URL pattern to add. This is usually '/'
separated path. Parts of the URL can be parameterised using
curly braces.
Exam... | [
"def",
"url",
"(",
"self",
",",
"pattern",
",",
"method",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"def",
"_inner",
"(",
"call",
")",
":",
"self",
".",
"_url_manager",
".",
"add",
"(",
"pattern",
",",
"method",
",",
"call",
",",
"name",
"... | 40.066667 | 0.001625 |
def range_merge(ranges, dist=0):
"""
Returns merged range. Similar to range_union, except this returns
new ranges.
>>> ranges = [("1", 30, 45), ("1", 40, 50), ("1", 10, 50)]
>>> range_merge(ranges)
[('1', 10, 50)]
>>> ranges = [("1", 30, 40), ("1", 45, 50)]
>>> range_merge(ranges)
[... | [
"def",
"range_merge",
"(",
"ranges",
",",
"dist",
"=",
"0",
")",
":",
"if",
"not",
"ranges",
":",
"return",
"[",
"]",
"ranges",
".",
"sort",
"(",
")",
"cur_range",
"=",
"list",
"(",
"ranges",
"[",
"0",
"]",
")",
"merged_ranges",
"=",
"[",
"]",
"f... | 28.53125 | 0.001059 |
def populate(dataset_name, data_web_service_url=DATA_WEB_SERVICE + "CFHT"):
"""Given a dataset_name created the desired dbimages directories
and links to the raw data files stored at CADC.
@param dataset_name: the name of the CFHT dataset to make a link to.
@param data_web_servica_url: the URL of the da... | [
"def",
"populate",
"(",
"dataset_name",
",",
"data_web_service_url",
"=",
"DATA_WEB_SERVICE",
"+",
"\"CFHT\"",
")",
":",
"data_dest",
"=",
"get_uri",
"(",
"dataset_name",
",",
"version",
"=",
"'o'",
",",
"ext",
"=",
"FITS_EXT",
")",
"data_source",
"=",
"\"%s/%... | 31.976744 | 0.001411 |
def _rgb_randomize(x, channel:int=None, thresh:float=0.3):
"Randomize one of the channels of the input image"
if channel is None: channel = np.random.randint(0, x.shape[0] - 1)
x[channel] = torch.rand(x.shape[1:]) * np.random.uniform(0, thresh)
return x | [
"def",
"_rgb_randomize",
"(",
"x",
",",
"channel",
":",
"int",
"=",
"None",
",",
"thresh",
":",
"float",
"=",
"0.3",
")",
":",
"if",
"channel",
"is",
"None",
":",
"channel",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"x",
".",
"shap... | 53 | 0.02974 |
def get_roles(username, **kwargs):
'''
Get roles assigned to a username.
.. code-block: bash
salt '*' nxos.cmd get_roles username=admin
'''
user = get_user(username)
if not user:
return []
command = 'show user-account {0}'.format(username)
info = ''
info = show(comm... | [
"def",
"get_roles",
"(",
"username",
",",
"*",
"*",
"kwargs",
")",
":",
"user",
"=",
"get_user",
"(",
"username",
")",
"if",
"not",
"user",
":",
"return",
"[",
"]",
"command",
"=",
"'show user-account {0}'",
".",
"format",
"(",
"username",
")",
"info",
... | 24.5 | 0.001786 |
def get_levels_of_description(self):
"""
Returns an array of all levels of description defined in this AtoM instance.
"""
if not hasattr(self, "levels_of_description"):
self.levels_of_description = [
item["name"]
for item in self._get(urljoin(s... | [
"def",
"get_levels_of_description",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"levels_of_description\"",
")",
":",
"self",
".",
"levels_of_description",
"=",
"[",
"item",
"[",
"\"name\"",
"]",
"for",
"item",
"in",
"self",
".",
"_get"... | 36.818182 | 0.009639 |
def canonicalize(lig, preserve_bond_order=False):
"""Get the canonical atom order for the ligand."""
atomorder = None
# Get canonical atom order
lig = pybel.ob.OBMol(lig.OBMol)
if not preserve_bond_order:
for bond in pybel.ob.OBMolBondIter(lig):
if bond.GetBondOrder() != 1:
... | [
"def",
"canonicalize",
"(",
"lig",
",",
"preserve_bond_order",
"=",
"False",
")",
":",
"atomorder",
"=",
"None",
"# Get canonical atom order",
"lig",
"=",
"pybel",
".",
"ob",
".",
"OBMol",
"(",
"lig",
".",
"OBMol",
")",
"if",
"not",
"preserve_bond_order",
":... | 35.966667 | 0.001805 |
def param(self,key,default=None):
"""for accessing global parameters"""
if key in self.parameters:
return self.parameters[key]
return default | [
"def",
"param",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"key",
"in",
"self",
".",
"parameters",
":",
"return",
"self",
".",
"parameters",
"[",
"key",
"]",
"return",
"default"
] | 34.6 | 0.022599 |
def by_identifier_secret(self, request):
"""
Authenticates a client by its identifier and secret (aka password).
:param request: The incoming request
:type request: oauth2.web.Request
:return: The identified client
:rtype: oauth2.datatype.Client
:raises OAuthIn... | [
"def",
"by_identifier_secret",
"(",
"self",
",",
"request",
")",
":",
"client_id",
",",
"client_secret",
"=",
"self",
".",
"source",
"(",
"request",
"=",
"request",
")",
"try",
":",
"client",
"=",
"self",
".",
"client_store",
".",
"fetch_by_client_id",
"(",
... | 40.787879 | 0.001451 |
def _fill_cdata(cls):
"""Add struct pack/unpack functions"""
funcs = {}
for key, name in [("b", "char"), ("h", "short"),
("i", "int"), ("q", "longlong")]:
for echar, esuffix in [("<", "le"), (">", "be")]:
esuffix = "_" + esuffix
for unsigned in [True, F... | [
"def",
"_fill_cdata",
"(",
"cls",
")",
":",
"funcs",
"=",
"{",
"}",
"for",
"key",
",",
"name",
"in",
"[",
"(",
"\"b\"",
",",
"\"char\"",
")",
",",
"(",
"\"h\"",
",",
"\"short\"",
")",
",",
"(",
"\"i\"",
",",
"\"int\"",
")",
",",
"(",
"\"q\"",
"... | 41.041667 | 0.000992 |
def watch_module_cache_get(cache, module):
"""
When we ask to fetch a module with optional config file, check time stamps
and dependencies to determine if it should be reloaded or not.
:param cache: the cache object that stores whether to check for config
files and which files have be... | [
"def",
"watch_module_cache_get",
"(",
"cache",
",",
"module",
")",
":",
"imp",
".",
"acquire_lock",
"(",
")",
"try",
":",
"if",
"not",
"hasattr",
"(",
"cache",
",",
"\"timestamps\"",
")",
":",
"cache",
".",
"timestamps",
"=",
"{",
"}",
"mtime",
"=",
"o... | 49.413043 | 0.001294 |
def create_pairwise_bilateral(sdims, schan, img, chdim=-1):
"""
Util function that create pairwise bilateral potentials. This works for
all image dimensions. For the 2D case does the same as
`DenseCRF2D.addPairwiseBilateral`.
Parameters
----------
sdims: list or tuple
The scaling fa... | [
"def",
"create_pairwise_bilateral",
"(",
"sdims",
",",
"schan",
",",
"img",
",",
"chdim",
"=",
"-",
"1",
")",
":",
"# Put channel dim in right position",
"if",
"chdim",
"==",
"-",
"1",
":",
"# We don't have a channel, add a new axis",
"im_feat",
"=",
"img",
"[",
... | 35.285714 | 0.000563 |
def _extract_datasets_to_harvest(cls, report):
"""Extrae de un reporte los datos necesarios para reconocer qué
datasets marcar para cosecha en cualquier generador.
Args:
report (str o list): Reporte (lista de dicts) o path a uno.
Returns:
list: Lista de tuplas c... | [
"def",
"_extract_datasets_to_harvest",
"(",
"cls",
",",
"report",
")",
":",
"assert",
"isinstance",
"(",
"report",
",",
"string_types",
"+",
"(",
"list",
",",
")",
")",
"# Si `report` es una lista de tuplas con longitud 2, asumimos que es un",
"# reporte procesado para extr... | 39.681818 | 0.001118 |
def get_key(self, match_key, num_results=1, best=True, **dfilter):
"""Get multiple fully-specified keys that match the provided query.
Args:
key (DatasetID): DatasetID of query parameters to use for
searching. Any parameter that is `None`
... | [
"def",
"get_key",
"(",
"self",
",",
"match_key",
",",
"num_results",
"=",
"1",
",",
"best",
"=",
"True",
",",
"*",
"*",
"dfilter",
")",
":",
"return",
"get_key",
"(",
"match_key",
",",
"self",
".",
"keys",
"(",
")",
",",
"num_results",
"=",
"num_resu... | 53.833333 | 0.002028 |
def facebook_request(self, path, callback, access_token=None,
post_args=None, **args):
"""Fetches the given relative API path, e.g., "/btaylor/picture"
If the request is a POST, post_args should be provided. Query
string arguments should be given as keyword arguments.... | [
"def",
"facebook_request",
"(",
"self",
",",
"path",
",",
"callback",
",",
"access_token",
"=",
"None",
",",
"post_args",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"url",
"=",
"\"https://graph.facebook.com\"",
"+",
"path",
"all_args",
"=",
"{",
"}",
... | 44.530612 | 0.002242 |
def loc_observations(self, request):
"""
Return location-specific observation data, including a list of sites
(time step will be HOURLY).
request:
metoffer.SITELIST Returns available sites
metoffer.CAPABILITIES Returns available times
... | [
"def",
"loc_observations",
"(",
"self",
",",
"request",
")",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"_query",
"(",
"VAL",
",",
"OBSERVATIONS",
",",
"ALL",
",",
"request",
",",
"HOURLY",
")",
".",
"decode",
"(",
"errors",
"=",
"\"replace... | 46.916667 | 0.008711 |
def chi2comb_cdf(q, chi2s, gcoef, lim=1000, atol=1e-4):
r"""Function distribution of combination of chi-squared distributions.
Parameters
----------
q : float
Value point at which distribution function is to be evaluated.
chi2s : ChiSquared
Chi-squared distributions.
gcoef : flo... | [
"def",
"chi2comb_cdf",
"(",
"q",
",",
"chi2s",
",",
"gcoef",
",",
"lim",
"=",
"1000",
",",
"atol",
"=",
"1e-4",
")",
":",
"int_type",
"=",
"\"i\"",
"if",
"array",
"(",
"int_type",
",",
"[",
"0",
"]",
")",
".",
"itemsize",
"!=",
"ffi",
".",
"sizeo... | 32.629032 | 0.00144 |
def set_power(self, powerstate, wait=False):
"""Request power state change (helper)
:param powerstate:
* on -- Request system turn on
* off -- Request system turn off without waiting
for OS to shutdown
... | [
"def",
"set_power",
"(",
"self",
",",
"powerstate",
",",
"wait",
"=",
"False",
")",
":",
"if",
"powerstate",
"not",
"in",
"power_states",
":",
"raise",
"exc",
".",
"InvalidParameterValue",
"(",
"\"Unknown power state %s requested\"",
"%",
"powerstate",
")",
"new... | 48.310345 | 0.0007 |
def transport_service(self, **kwargs):
"""Configure VLAN Transport Service.
Args:
vlan (str): The VLAN ID.
service_id (str): The transport-service ID.
callback (function): A function executed upon completion of the
method. The only parameter passed t... | [
"def",
"transport_service",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"vlan",
"=",
"kwargs",
".",
"pop",
"(",
"'vlan'",
")",
"service_id",
"=",
"kwargs",
".",
"pop",
"(",
"'service_id'",
")",
"callback",
"=",
"kwargs",
".",
"pop",
"(",
"'callback... | 43.431373 | 0.000883 |
def update(access_key, resource_policy, is_admin, is_active, rate_limit):
'''
Update an existing keypair.
ACCESS_KEY: Access key of an existing key pair.
'''
with Session() as session:
try:
data = session.KeyPair.update(
access_key,
is_active=is_... | [
"def",
"update",
"(",
"access_key",
",",
"resource_policy",
",",
"is_admin",
",",
"is_active",
",",
"rate_limit",
")",
":",
"with",
"Session",
"(",
")",
"as",
"session",
":",
"try",
":",
"data",
"=",
"session",
".",
"KeyPair",
".",
"update",
"(",
"access... | 33.333333 | 0.001389 |
def get_version_fields(self):
""" Get field that are tracked in object history versions. """
options = reversion._get_options(self)
return options.fields or [f.name for f in self._meta.fields if f not in options.exclude] | [
"def",
"get_version_fields",
"(",
"self",
")",
":",
"options",
"=",
"reversion",
".",
"_get_options",
"(",
"self",
")",
"return",
"options",
".",
"fields",
"or",
"[",
"f",
".",
"name",
"for",
"f",
"in",
"self",
".",
"_meta",
".",
"fields",
"if",
"f",
... | 60.25 | 0.012295 |
async def stop(self):
"""Stop playback?"""
state = await self.state()
res = await self.call("X_Stop", MasterSessionID=state.MasterSessionID)
return res | [
"async",
"def",
"stop",
"(",
"self",
")",
":",
"state",
"=",
"await",
"self",
".",
"state",
"(",
")",
"res",
"=",
"await",
"self",
".",
"call",
"(",
"\"X_Stop\"",
",",
"MasterSessionID",
"=",
"state",
".",
"MasterSessionID",
")",
"return",
"res"
] | 35.8 | 0.010929 |
def tobinary(series, path, prefix='series', overwrite=False, credentials=None):
"""
Writes out data to binary format.
Parameters
----------
series : Series
The data to write
path : string path or URI to directory to be created
Output files will be written underneath path.
... | [
"def",
"tobinary",
"(",
"series",
",",
"path",
",",
"prefix",
"=",
"'series'",
",",
"overwrite",
"=",
"False",
",",
"credentials",
"=",
"None",
")",
":",
"from",
"six",
"import",
"BytesIO",
"from",
"thunder",
".",
"utils",
"import",
"check_path",
"from",
... | 29.095238 | 0.001583 |
def send(self, endpoint, json_message):
"""
Queues the message to be sent.
"""
_send_event_task.spool(endpoint=endpoint, json_message=json_message) | [
"def",
"send",
"(",
"self",
",",
"endpoint",
",",
"json_message",
")",
":",
"_send_event_task",
".",
"spool",
"(",
"endpoint",
"=",
"endpoint",
",",
"json_message",
"=",
"json_message",
")"
] | 35 | 0.011173 |
def is_special_string(obj):
"""Is special string."""
import bs4
return isinstance(obj, (bs4.Comment, bs4.Declaration, bs4.CData, bs4.ProcessingInstruction)) | [
"def",
"is_special_string",
"(",
"obj",
")",
":",
"import",
"bs4",
"return",
"isinstance",
"(",
"obj",
",",
"(",
"bs4",
".",
"Comment",
",",
"bs4",
".",
"Declaration",
",",
"bs4",
".",
"CData",
",",
"bs4",
".",
"ProcessingInstruction",
")",
")"
] | 35.4 | 0.016575 |
def get_itemstr_list(list_, **listkw):
"""
TODO: have this replace dict_itemstr list or at least most functionality in
it. have it make two itemstr lists over keys and values and then combine
them.
"""
import utool as ut
_valstr = _make_valstr(**listkw)
def make_item_str(item):
... | [
"def",
"get_itemstr_list",
"(",
"list_",
",",
"*",
"*",
"listkw",
")",
":",
"import",
"utool",
"as",
"ut",
"_valstr",
"=",
"_make_valstr",
"(",
"*",
"*",
"listkw",
")",
"def",
"make_item_str",
"(",
"item",
")",
":",
"item_str",
"=",
"_valstr",
"(",
"it... | 33.5625 | 0.000905 |
def _find_outOfBound(self, data, lowBound, highBound):
""" Mask for selecting data that is out of bounds.
Parameters
----------
data : pd.DataFrame()
Input dataframe.
lowBound : float
Lower bound for dataframe.
highBound : flo... | [
"def",
"_find_outOfBound",
"(",
"self",
",",
"data",
",",
"lowBound",
",",
"highBound",
")",
":",
"data",
"=",
"(",
"(",
"data",
"<",
"lowBound",
")",
"|",
"(",
"data",
">",
"highBound",
")",
")",
"return",
"data"
] | 24.05 | 0.01 |
def register_plugin(self, name):
"""Load and register a plugin given its package name."""
logger.info("Registering plugin: " + name)
module = importlib.import_module(name)
module.register_plugin(self) | [
"def",
"register_plugin",
"(",
"self",
",",
"name",
")",
":",
"logger",
".",
"info",
"(",
"\"Registering plugin: \"",
"+",
"name",
")",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"name",
")",
"module",
".",
"register_plugin",
"(",
"self",
")"
] | 45.6 | 0.008621 |
def _sort(self):
"""sort sprites by z_order"""
self.__dict__['_z_ordered_sprites'] = sorted(self.sprites, key=lambda sprite:sprite.z_order) | [
"def",
"_sort",
"(",
"self",
")",
":",
"self",
".",
"__dict__",
"[",
"'_z_ordered_sprites'",
"]",
"=",
"sorted",
"(",
"self",
".",
"sprites",
",",
"key",
"=",
"lambda",
"sprite",
":",
"sprite",
".",
"z_order",
")"
] | 51 | 0.025806 |
def vpn_sites(self):
"""Instance depends on the API version:
* 2018-04-01: :class:`VpnSitesOperations<azure.mgmt.network.v2018_04_01.operations.VpnSitesOperations>`
"""
api_version = self._get_api_version('vpn_sites')
if api_version == '2018-04-01':
from .v2018_04... | [
"def",
"vpn_sites",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'vpn_sites'",
")",
"if",
"api_version",
"==",
"'2018-04-01'",
":",
"from",
".",
"v2018_04_01",
".",
"operations",
"import",
"VpnSitesOperations",
"as",
"Operati... | 56.454545 | 0.009509 |
def publish(self, **kwargs):
"""
Publishes the global workflow, so all users can find it and use it on the platform.
The current user must be a developer of the workflow.
"""
if self._dxid is not None:
return dxpy.api.global_workflow_publish(self._dxid, **kwargs)
... | [
"def",
"publish",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_dxid",
"is",
"not",
"None",
":",
"return",
"dxpy",
".",
"api",
".",
"global_workflow_publish",
"(",
"self",
".",
"_dxid",
",",
"*",
"*",
"kwargs",
")",
"else",
"... | 43.4 | 0.009029 |
def longest_increasing_subsequence(xs):
'''Return a longest increasing subsequence of xs.
(Note that there may be more than one such subsequence.)
>>> longest_increasing_subsequence(range(3))
[0, 1, 2]
>>> longest_increasing_subsequence([3, 1, 2, 0])
[1, 2]
'''
# Patience sort xs, stack... | [
"def",
"longest_increasing_subsequence",
"(",
"xs",
")",
":",
"# Patience sort xs, stacking (x, prev_ix) pairs on the piles.",
"# Prev_ix indexes the element at the top of the previous pile,",
"# which has a lower x value than the current x value.",
"piles",
"=",
"[",
"[",
"]",
"]",
"#... | 34.814815 | 0.001035 |
def eklef(fname):
"""
Load an EK file, making it accessible to the EK readers.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eklef_c.html
:param fname: Name of EK file to load.
:type fname: str
:return: File handle of loaded EK file.
:rtype: int
"""
fname = stypes.stringT... | [
"def",
"eklef",
"(",
"fname",
")",
":",
"fname",
"=",
"stypes",
".",
"stringToCharP",
"(",
"fname",
")",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"libspice",
".",
"eklef_c",
"(",
"fname",
",",
"ctypes",
".",
"byref",
"(",
"handle",
")",
")",
... | 28.066667 | 0.002299 |
def postgis_path_to_uri(path):
"""Convert layer path from QgsBrowserModel to full QgsDataSourceUri.
:param path: The layer path from QgsBrowserModel
:type path: string
:returns: layer uri.
:rtype: QgsDataSourceUri
"""
connection_name = path.split('/')[1]
... | [
"def",
"postgis_path_to_uri",
"(",
"path",
")",
":",
"connection_name",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"]",
"schema",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"2",
"]",
"table_name",
"=",
"path",
".",
"split",
"(",
"'... | 34.813559 | 0.000947 |
def pfadd(self, key, *elements):
"""Adds all the element arguments to the HyperLogLog data structure
stored at the variable name specified as first argument.
As a side effect of this command the HyperLogLog internals may be
updated to reflect a different estimation of the number of uniq... | [
"def",
"pfadd",
"(",
"self",
",",
"key",
",",
"*",
"elements",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"[",
"b'PFADD'",
",",
"key",
"]",
"+",
"list",
"(",
"elements",
")",
",",
"1",
")"
] | 45.857143 | 0.00122 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.