text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def copy(self):
""" Return a copy of the limit """
return Limit(self.scan_limit, self.item_limit, self.min_scan_limit,
self.strict, self.filter) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"Limit",
"(",
"self",
".",
"scan_limit",
",",
"self",
".",
"item_limit",
",",
"self",
".",
"min_scan_limit",
",",
"self",
".",
"strict",
",",
"self",
".",
"filter",
")"
] | 44.5 | 0.01105 |
def extract_references_from_wets(wet_files, metadata_dir, out_dir,
tmp_dir=None):
"""Extract references from WET files into sharded output files."""
# Setup output files
shard_files = make_ref_shard_files(out_dir)
num_refs = 0
for i, wet_file in enumerate(wet_files):
num_... | [
"def",
"extract_references_from_wets",
"(",
"wet_files",
",",
"metadata_dir",
",",
"out_dir",
",",
"tmp_dir",
"=",
"None",
")",
":",
"# Setup output files",
"shard_files",
"=",
"make_ref_shard_files",
"(",
"out_dir",
")",
"num_refs",
"=",
"0",
"for",
"i",
",",
"... | 30.557692 | 0.015244 |
def quiver(
x,
y,
z,
u,
v,
w,
size=default_size * 10,
size_selected=default_size_selected * 10,
color=default_color,
color_selected=default_color_selected,
marker="arrow",
**kwargs
):
"""Create a quiver plot, which is like a scatter plot but with arrows pointing in th... | [
"def",
"quiver",
"(",
"x",
",",
"y",
",",
"z",
",",
"u",
",",
"v",
",",
"w",
",",
"size",
"=",
"default_size",
"*",
"10",
",",
"size_selected",
"=",
"default_size_selected",
"*",
"10",
",",
"color",
"=",
"default_color",
",",
"color_selected",
"=",
"... | 24.94 | 0.001543 |
def __set_amount(self, value):
'''
Sets the amount of the payment operation.
@param value:float
'''
try:
self.__amount = quantize(Decimal(str(value)))
except:
raise ValueError('Invalid amount value') | [
"def",
"__set_amount",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"self",
".",
"__amount",
"=",
"quantize",
"(",
"Decimal",
"(",
"str",
"(",
"value",
")",
")",
")",
"except",
":",
"raise",
"ValueError",
"(",
"'Invalid amount value'",
")"
] | 29.222222 | 0.01107 |
def transform(self, X):
"""Use the model to transform new data to Shared Response space
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, timepoints_i]
Each element in the list contains the fMRI data of one subject.
Returns
-------... | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"# Check if the model exist",
"if",
"hasattr",
"(",
"self",
",",
"'w_'",
")",
"is",
"False",
":",
"raise",
"NotFittedError",
"(",
"\"The model fit has not been run yet.\"",
")",
"# Check the number of subjects",
"... | 35.2 | 0.00158 |
def conditionally_trigger(context, dag_run_obj):
"""This function decides whether or not to Trigger the remote DAG"""
c_p = context['params']['condition_param']
print("Controller DAG : conditionally_trigger = {}".format(c_p))
if context['params']['condition_param']:
dag_run_obj.payload = {'messa... | [
"def",
"conditionally_trigger",
"(",
"context",
",",
"dag_run_obj",
")",
":",
"c_p",
"=",
"context",
"[",
"'params'",
"]",
"[",
"'condition_param'",
"]",
"print",
"(",
"\"Controller DAG : conditionally_trigger = {}\"",
".",
"format",
"(",
"c_p",
")",
")",
"if",
... | 51.625 | 0.002381 |
def new_job(
self,
task,
person,
tank,
target_host,
target_port,
loadscheme=None,
detailed_time=None,
notify_list=None,
trace=False):
"""
:return: job_nr, upload_token
:rtype: ... | [
"def",
"new_job",
"(",
"self",
",",
"task",
",",
"person",
",",
"tank",
",",
"target_host",
",",
"target_port",
",",
"loadscheme",
"=",
"None",
",",
"detailed_time",
"=",
"None",
",",
"notify_list",
"=",
"None",
",",
"trace",
"=",
"False",
")",
":",
"i... | 35.431373 | 0.002154 |
def buckets(self, start, end):
'''
Calculate the buckets within a starting and ending timestamp.
'''
rval = [ self.to_bucket(start) ]
step = 1
# In theory there's already been a check that end>start
# TODO: Not a fan of an unbound while loop here
while True:
bucket = self.to_bucke... | [
"def",
"buckets",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"rval",
"=",
"[",
"self",
".",
"to_bucket",
"(",
"start",
")",
"]",
"step",
"=",
"1",
"# In theory there's already been a check that end>start",
"# TODO: Not a fan of an unbound while loop here",
"wh... | 26.35 | 0.029304 |
def chi_p_from_spherical(mass1, mass2, spin1_a, spin1_azimuthal, spin1_polar,
spin2_a, spin2_azimuthal, spin2_polar):
"""Returns the effective precession spin using spins in spherical
coordinates.
"""
spin1x, spin1y, _ = _spherical_to_cartesian(
spin1_a, spin1_azimuthal,... | [
"def",
"chi_p_from_spherical",
"(",
"mass1",
",",
"mass2",
",",
"spin1_a",
",",
"spin1_azimuthal",
",",
"spin1_polar",
",",
"spin2_a",
",",
"spin2_azimuthal",
",",
"spin2_polar",
")",
":",
"spin1x",
",",
"spin1y",
",",
"_",
"=",
"_spherical_to_cartesian",
"(",
... | 48.3 | 0.002033 |
def serialize(self, data, fmt='%10.7E'):
"""
Serialize a collection of ground motion fields to XML.
:param data:
An iterable of "GMF set" objects.
Each "GMF set" object should:
* have an `investigation_time` attribute
* have an `stochastic_event_... | [
"def",
"serialize",
"(",
"self",
",",
"data",
",",
"fmt",
"=",
"'%10.7E'",
")",
":",
"gmf_set_nodes",
"=",
"[",
"]",
"for",
"gmf_set",
"in",
"data",
":",
"gmf_set_node",
"=",
"Node",
"(",
"'gmfSet'",
")",
"if",
"gmf_set",
".",
"investigation_time",
":",
... | 38.888889 | 0.001115 |
def load_SUEWS_Forcing_met_df_pattern(path_input, forcingfile_met_pattern):
"""Short summary.
Parameters
----------
forcingfile_met_pattern : type
Description of parameter `forcingfile_met_pattern`.
Returns
-------
type
Description of returned object.
"""
# list o... | [
"def",
"load_SUEWS_Forcing_met_df_pattern",
"(",
"path_input",
",",
"forcingfile_met_pattern",
")",
":",
"# list of met forcing files",
"path_input",
"=",
"path_input",
".",
"resolve",
"(",
")",
"# forcingfile_met_pattern = os.path.abspath(forcingfile_met_pattern)",
"list_file_MetF... | 31.227273 | 0.00047 |
def parseArgs(): # pragma: no cover
"""Parses the command line options and arguments.
:returns: A :py:class:`argparse.Namespace` object created by the
:py:mod:`argparse` module. It contains the values of the
different options.
===================== ====== =====================... | [
"def",
"parseArgs",
"(",
")",
":",
"# pragma: no cover",
"# The INPUT files",
"group",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"Input File\"",
")",
"group",
".",
"add_argument",
"(",
"\"--file\"",
",",
"type",
"=",
"str",
",",
"metavar",
"=",
"\"FILE\""... | 43.166667 | 0.000472 |
def _translate_language_name(self, language_name):
"""
Translate a human readable langauge name into its Ideone
integer representation.
Keyword Arguments
-----------------
* langauge_name: a string of the language (e.g. "c++")
Returns
-------
A... | [
"def",
"_translate_language_name",
"(",
"self",
",",
"language_name",
")",
":",
"languages",
"=",
"self",
".",
"languages",
"(",
")",
"language_id",
"=",
"None",
"# Check for exact match first including the whole version",
"# string",
"for",
"ideone_index",
",",
"ideone... | 37.203125 | 0.002046 |
def deltas(self):
"""
Dictionary of relative offsets. The keys in the result are
pairs of keys from the offset vector, (a, b), and the
values are the relative offsets, (offset[b] - offset[a]).
Raises ValueError if the offsetvector is empty (WARNING:
this behaviour might change in the future).
Example:
... | [
"def",
"deltas",
"(",
"self",
")",
":",
"# FIXME: instead of raising ValueError when the",
"# offsetvector is empty this should return an empty",
"# dictionary. the inverse, .fromdeltas() accepts",
"# empty dictionaries",
"# NOTE: the arithmetic used to construct the offsets",
"# *must* mat... | 35.948718 | 0.024306 |
def create(conversion_finder, parsed_att: Any, attribute_type: Type[Any], errors: Dict[Type, Exception] = None):
"""
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param parsed_at... | [
"def",
"create",
"(",
"conversion_finder",
",",
"parsed_att",
":",
"Any",
",",
"attribute_type",
":",
"Type",
"[",
"Any",
"]",
",",
"errors",
":",
"Dict",
"[",
"Type",
",",
"Exception",
"]",
"=",
"None",
")",
":",
"if",
"conversion_finder",
"is",
"None",... | 59.76 | 0.008564 |
def do_d(self, line):
"""Send the Master a DoubleBitBinaryInput (group 4) value of DETERMINED_ON. Command syntax is: d index"""
index = self.index_from_line(line)
if index:
self.application.apply_update(opendnp3.DoubleBitBinary(opendnp3.DoubleBit.DETERMINED_ON), index) | [
"def",
"do_d",
"(",
"self",
",",
"line",
")",
":",
"index",
"=",
"self",
".",
"index_from_line",
"(",
"line",
")",
"if",
"index",
":",
"self",
".",
"application",
".",
"apply_update",
"(",
"opendnp3",
".",
"DoubleBitBinary",
"(",
"opendnp3",
".",
"Double... | 60.2 | 0.013115 |
def run_command(command, capture=None, check=False, encoding='utf-8', shell=False, env=None):
"""This function provides a convenient API wrapping subprocess.Popen. Captured output
is guaranteed not to deadlock, but will still reside in memory in the end.
:param command: The command to run in a subprocess.
... | [
"def",
"run_command",
"(",
"command",
",",
"capture",
"=",
"None",
",",
"check",
"=",
"False",
",",
"encoding",
"=",
"'utf-8'",
",",
"shell",
"=",
"False",
",",
"env",
"=",
"None",
")",
":",
"if",
"shell",
"==",
"'detect'",
":",
"shell",
"=",
"NEED_S... | 40.047619 | 0.002321 |
async def removeKeyPair(self, *args, **kwargs):
"""
Ensure a KeyPair for a given worker type does not exist
Ensure that a keypair of a given name does not exist.
This method is ``experimental``
"""
return await self._makeApiCall(self.funcinfo["removeKeyPair"], *args, *... | [
"async",
"def",
"removeKeyPair",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_makeApiCall",
"(",
"self",
".",
"funcinfo",
"[",
"\"removeKeyPair\"",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
... | 31.9 | 0.009146 |
def _compute_valid(self):
r"""Determines if the current surface is "valid".
Does this by checking if the Jacobian of the map from the
reference triangle is everywhere positive.
Returns:
bool: Flag indicating if the current surface is valid.
Raises:
NotI... | [
"def",
"_compute_valid",
"(",
"self",
")",
":",
"if",
"self",
".",
"_dimension",
"!=",
"2",
":",
"raise",
"NotImplementedError",
"(",
"\"Validity check only implemented in R^2\"",
")",
"poly_sign",
"=",
"None",
"if",
"self",
".",
"_degree",
"==",
"1",
":",
"# ... | 39.314286 | 0.001418 |
def tee(iterable, n=2):
"""Return n independent iterators from a single iterable.
Once tee() has made a split, the original iterable should not be used
anywhere else; otherwise, the iterable could get advanced without the tee
objects being informed.
This itertool may require significant auxiliary ... | [
"def",
"tee",
"(",
"iterable",
",",
"n",
"=",
"2",
")",
":",
"tees",
"=",
"tuple",
"(",
"AsyncTeeIterable",
"(",
"iterable",
")",
"for",
"_",
"in",
"range",
"(",
"n",
")",
")",
"for",
"tee",
"in",
"tees",
":",
"tee",
".",
"_siblings",
"=",
"tees"... | 36.333333 | 0.00149 |
def __fill_buffer(self, size=0):
"""Fills the internal buffer.
Args:
size: Number of bytes to read. Will be clamped to
[self.__buffer_size, MAX_BLOB_FETCH_SIZE].
"""
read_size = min(max(size, self.__buffer_size), MAX_BLOB_FETCH_SIZE)
self.__buffer = fetch_data(self.__blob_key, self._... | [
"def",
"__fill_buffer",
"(",
"self",
",",
"size",
"=",
"0",
")",
":",
"read_size",
"=",
"min",
"(",
"max",
"(",
"size",
",",
"self",
".",
"__buffer_size",
")",
",",
"MAX_BLOB_FETCH_SIZE",
")",
"self",
".",
"__buffer",
"=",
"fetch_data",
"(",
"self",
".... | 35.461538 | 0.002114 |
def all_finite(self,X):
"""returns true if X is finite, false, otherwise"""
# Adapted from sklearn utils: _assert_all_finite(X)
# First try an O(n) time, O(1) space solution for the common case that
# everything is finite; fall back to O(n) space np.isfinite to prevent
# false po... | [
"def",
"all_finite",
"(",
"self",
",",
"X",
")",
":",
"# Adapted from sklearn utils: _assert_all_finite(X)",
"# First try an O(n) time, O(1) space solution for the common case that",
"# everything is finite; fall back to O(n) space np.isfinite to prevent",
"# false positives from overflow in s... | 56.692308 | 0.009346 |
def find_python():
"""Search for Python automatically"""
python = (
_state.get("pythonExecutable") or
# Support for multiple executables.
next((
exe for exe in
os.getenv("PYBLISH_QML_PYTHON_EXECUTABLE", "").split(os.pathsep)
if os.path.isfile(exe)), N... | [
"def",
"find_python",
"(",
")",
":",
"python",
"=",
"(",
"_state",
".",
"get",
"(",
"\"pythonExecutable\"",
")",
"or",
"# Support for multiple executables.",
"next",
"(",
"(",
"exe",
"for",
"exe",
"in",
"os",
".",
"getenv",
"(",
"\"PYBLISH_QML_PYTHON_EXECUTABLE\... | 26.047619 | 0.001764 |
def get_entities_query(namespace, workspace, etype, page=1,
page_size=100, sort_direction="asc",
filter_terms=None):
"""Paginated version of get_entities_with_type.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace... | [
"def",
"get_entities_query",
"(",
"namespace",
",",
"workspace",
",",
"etype",
",",
"page",
"=",
"1",
",",
"page_size",
"=",
"100",
",",
"sort_direction",
"=",
"\"asc\"",
",",
"filter_terms",
"=",
"None",
")",
":",
"# Initial parameters for pagination",
"params"... | 29 | 0.009346 |
def _auth_required(method, validator):
"""Decorate a HTTP verb method and check the request is authenticated
:param method: a tornado.web.RequestHandler method
:param validator: a token validation coroutine, that should return
True/False depending if token is or is not valid
"""
@gen.coroutine
... | [
"def",
"_auth_required",
"(",
"method",
",",
"validator",
")",
":",
"@",
"gen",
".",
"coroutine",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"token",
"=",
... | 32.875 | 0.001232 |
def _compute(self):
"""Compute r min max and labels position"""
delta = 2 * pi / self._len if self._len else 0
self._x_pos = [.5 * pi + i * delta for i in range(self._len + 1)]
for serie in self.all_series:
serie.points = [(v, self._x_pos[i])
for i... | [
"def",
"_compute",
"(",
"self",
")",
":",
"delta",
"=",
"2",
"*",
"pi",
"/",
"self",
".",
"_len",
"if",
"self",
".",
"_len",
"else",
"0",
"self",
".",
"_x_pos",
"=",
"[",
".5",
"*",
"pi",
"+",
"i",
"*",
"delta",
"for",
"i",
"in",
"range",
"("... | 38.961538 | 0.001927 |
def _regex_flags_from_bits(self, bits):
"""Return the textual equivalent of numerically encoded regex flags."""
flags = 'ilmsuxa'
return ''.join(flags[i - 1] if (1 << i) & bits else '' for i in range(1, len(flags) + 1)) | [
"def",
"_regex_flags_from_bits",
"(",
"self",
",",
"bits",
")",
":",
"flags",
"=",
"'ilmsuxa'",
"return",
"''",
".",
"join",
"(",
"flags",
"[",
"i",
"-",
"1",
"]",
"if",
"(",
"1",
"<<",
"i",
")",
"&",
"bits",
"else",
"''",
"for",
"i",
"in",
"rang... | 60 | 0.012346 |
def initialize_particle(rng, domain, fitness_function):
""" Initializes a particle within a domain.
Args:
rng: numpy.random.RandomState: The random number generator.
domain: cipy.problems.core.Domain: The domain of the problem.
Returns:
cipy.algorithms.pso.Particle: A new, fully ini... | [
"def",
"initialize_particle",
"(",
"rng",
",",
"domain",
",",
"fitness_function",
")",
":",
"position",
"=",
"rng",
".",
"uniform",
"(",
"domain",
".",
"lower",
",",
"domain",
".",
"upper",
",",
"domain",
".",
"dimension",
")",
"fitness",
"=",
"fitness_fun... | 41.5 | 0.001473 |
def list_motors(name_pattern=Motor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs):
"""
This is a generator function that enumerates all tacho motors that match
the provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'motor*'. Default value: '*... | [
"def",
"list_motors",
"(",
"name_pattern",
"=",
"Motor",
".",
"SYSTEM_DEVICE_NAME_CONVENTION",
",",
"*",
"*",
"kwargs",
")",
":",
"class_path",
"=",
"abspath",
"(",
"Device",
".",
"DEVICE_ROOT_PATH",
"+",
"'/'",
"+",
"Motor",
".",
"SYSTEM_CLASS_NAME",
")",
"re... | 45.444444 | 0.002395 |
def GetAttachmentIdFromMediaId(media_id):
"""Gets attachment id from media id.
:param str media_id:
:return:
The attachment id from the media id.
:rtype: str
"""
altchars = '+-'
if not six.PY2:
altchars = altchars.encode('utf-8')
# altchars for '+' and '/'. We keep '+' ... | [
"def",
"GetAttachmentIdFromMediaId",
"(",
"media_id",
")",
":",
"altchars",
"=",
"'+-'",
"if",
"not",
"six",
".",
"PY2",
":",
"altchars",
"=",
"altchars",
".",
"encode",
"(",
"'utf-8'",
")",
"# altchars for '+' and '/'. We keep '+' but replace '/' with '-'",
"buffer",... | 29.76 | 0.001302 |
def set_error_callback(cbfun):
'''
Sets the error callback.
Wrapper for:
GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun);
'''
global _error_callback
previous_callback = _error_callback
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWerrorfun(cbfun)
_error_callback =... | [
"def",
"set_error_callback",
"(",
"cbfun",
")",
":",
"global",
"_error_callback",
"previous_callback",
"=",
"_error_callback",
"if",
"cbfun",
"is",
"None",
":",
"cbfun",
"=",
"0",
"c_cbfun",
"=",
"_GLFWerrorfun",
"(",
"cbfun",
")",
"_error_callback",
"=",
"(",
... | 28.411765 | 0.002004 |
def _merge(d, u):
"""Merge two dictionaries (or DotDicts) together.
Args:
d: The dictionary/DotDict to merge into.
u: The source of the data to merge.
"""
for k, v in u.items():
# if we have a mapping, recursively merge the values
if isinstance(v, collections.Mapping... | [
"def",
"_merge",
"(",
"d",
",",
"u",
")",
":",
"for",
"k",
",",
"v",
"in",
"u",
".",
"items",
"(",
")",
":",
"# if we have a mapping, recursively merge the values",
"if",
"isinstance",
"(",
"v",
",",
"collections",
".",
"Mapping",
")",
":",
"d",
"[",
"... | 34.821429 | 0.000998 |
def interpolate_xml_array(data, low_res_coords, shape, chunks):
"""Interpolate arbitrary size dataset to a full sized grid."""
xpoints, ypoints = low_res_coords
return interpolate_xarray_linear(xpoints, ypoints, data, shape, chunks=chunks) | [
"def",
"interpolate_xml_array",
"(",
"data",
",",
"low_res_coords",
",",
"shape",
",",
"chunks",
")",
":",
"xpoints",
",",
"ypoints",
"=",
"low_res_coords",
"return",
"interpolate_xarray_linear",
"(",
"xpoints",
",",
"ypoints",
",",
"data",
",",
"shape",
",",
... | 52 | 0.011364 |
def coarsen(self, dim: Optional[Mapping[Hashable, int]] = None,
boundary: str = 'exact',
side: Union[str, Mapping[Hashable, str]] = 'left',
coord_func: str = 'mean',
**dim_kwargs: int):
"""
Coarsen object.
Parameters
------... | [
"def",
"coarsen",
"(",
"self",
",",
"dim",
":",
"Optional",
"[",
"Mapping",
"[",
"Hashable",
",",
"int",
"]",
"]",
"=",
"None",
",",
"boundary",
":",
"str",
"=",
"'exact'",
",",
"side",
":",
"Union",
"[",
"str",
",",
"Mapping",
"[",
"Hashable",
","... | 38.564516 | 0.002447 |
def get_fileinfo(self, name: str):
'''
get a `FileInfo` for a file (without create actual file).
'''
return FileInfo(os.path.join(self._path, name)) | [
"def",
"get_fileinfo",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"return",
"FileInfo",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"name",
")",
")"
] | 35.2 | 0.011111 |
def searchPhotos(self, title, **kwargs):
""" Search for a photo. See :func:`~plexapi.library.LibrarySection.search()` for usage. """
return self.search(libtype='photo', title=title, **kwargs) | [
"def",
"searchPhotos",
"(",
"self",
",",
"title",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"search",
"(",
"libtype",
"=",
"'photo'",
",",
"title",
"=",
"title",
",",
"*",
"*",
"kwargs",
")"
] | 68.333333 | 0.014493 |
def create(self, index, doc_type, body, id=None, params=None):
"""
Adds a typed JSON document in a specific index, making it searchable.
Behind the scenes this method calls index(..., op_type='create')
`<http://elasticsearch.org/guide/reference/api/index_/>`_
:arg index: The nam... | [
"def",
"create",
"(",
"self",
",",
"index",
",",
"doc_type",
",",
"body",
",",
"id",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"result",
"=",
"yield",
"self",
".",
"index",
"(",
"index",
",",
"doc_type",
",",
"body",
",",
"id",
"=",
"id"... | 51.115385 | 0.001477 |
def install(self):
"""Create folder and copy agent and metrics scripts to remote host"""
logger.info(
"Installing monitoring agent at %s@%s...",
self.username,
self.host)
# create remote temp dir
cmd = self.python + ' -c "import tempfile; print tempfi... | [
"def",
"install",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Installing monitoring agent at %s@%s...\"",
",",
"self",
".",
"username",
",",
"self",
".",
"host",
")",
"# create remote temp dir",
"cmd",
"=",
"self",
".",
"python",
"+",
"' -c \"import te... | 41.1875 | 0.001693 |
def setRGB(self, pixel, r, g, b):
"""Set single pixel using individual RGB values instead of tuple"""
self._set_base(pixel, (r, g, b)) | [
"def",
"setRGB",
"(",
"self",
",",
"pixel",
",",
"r",
",",
"g",
",",
"b",
")",
":",
"self",
".",
"_set_base",
"(",
"pixel",
",",
"(",
"r",
",",
"g",
",",
"b",
")",
")"
] | 49.333333 | 0.013333 |
def create_asset_content(self, asset_content_form=None):
"""Creates new ``AssetContent`` for a given asset.
arg: asset_content_form (osid.repository.AssetContentForm):
the form for this ``AssetContent``
return: (osid.repository.AssetContent) - the new
``AssetC... | [
"def",
"create_asset_content",
"(",
"self",
",",
"asset_content_form",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"asset_content_form",
",",
"AssetContentForm",
")",
":",
"asset_content",
"=",
"self",
".",
"_provider_session",
".",
"create_asset_content",
"(",
... | 46.419355 | 0.002042 |
def best_representative(d1, d2):
"""
Given two objects each coerced to the most specific type possible, return the one
of the least restrictive type.
>>> best_representative(Decimal('-37.5'), Decimal('0.9999'))
Decimal('-99.9999')
>>> best_representative(None, Decimal('6.1'))
Decimal('6.1')... | [
"def",
"best_representative",
"(",
"d1",
",",
"d2",
")",
":",
"if",
"hasattr",
"(",
"d2",
",",
"'strip'",
")",
"and",
"not",
"d2",
".",
"strip",
"(",
")",
":",
"return",
"d1",
"if",
"d1",
"is",
"None",
":",
"return",
"d2",
"elif",
"d2",
"is",
"No... | 33.309524 | 0.002083 |
def get_dataset(dataset_id,**kwargs):
"""
Get a single dataset, by ID
"""
user_id = int(kwargs.get('user_id'))
if dataset_id is None:
return None
try:
dataset_rs = db.DBSession.query(Dataset.id,
Dataset.type,
Dataset.unit_id,
... | [
"def",
"get_dataset",
"(",
"dataset_id",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"int",
"(",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
")",
"if",
"dataset_id",
"is",
"None",
":",
"return",
"None",
"try",
":",
"dataset_rs",
"=",
"db",
".... | 34.840909 | 0.015228 |
def extract_constant(code, symbol, default=-1):
"""Extract the constant value of 'symbol' from 'code'
If the name 'symbol' is bound to a constant value by the Python code
object 'code', return that value. If 'symbol' is bound to an expression,
return 'default'. Otherwise, return 'None'.
Return v... | [
"def",
"extract_constant",
"(",
"code",
",",
"symbol",
",",
"default",
"=",
"-",
"1",
")",
":",
"if",
"symbol",
"not",
"in",
"code",
".",
"co_names",
":",
"# name's not there, can't possibly be an assignment",
"return",
"None",
"name_idx",
"=",
"list",
"(",
"c... | 32.676471 | 0.000874 |
def acquire_lock(self, name):
"""
Wait for a lock with name.
This will prevent other processes from acquiring the lock with
the name while it is held. Thus they will wait in the position
where they are acquiring the lock until the process that has it
releases it.
... | [
"def",
"acquire_lock",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"_remotelib",
":",
"try",
":",
"while",
"not",
"self",
".",
"_remotelib",
".",
"run_keyword",
"(",
"'acquire_lock'",
",",
"[",
"name",
",",
"self",
".",
"_my_id",
"]",
",",
... | 42.578947 | 0.002418 |
def mkstemp(*args, **kwargs):
"""
Context manager similar to tempfile.NamedTemporaryFile except the file is not deleted on close, and only the filepath
is returned
.. warnings:: Unlike tempfile.mkstemp, this is not secure
"""
fd, filename = tempfile.mkstemp(*args, **kwargs)
os.close(fd)
try:
yield f... | [
"def",
"mkstemp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"fd",
",",
"filename",
"=",
"tempfile",
".",
"mkstemp",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"os",
".",
"close",
"(",
"fd",
")",
"try",
":",
"yield",
"filename",
... | 29.25 | 0.019337 |
def common_parent(coords, parent_zoom):
"""
Return the common parent for coords
Also check that all coords do indeed share the same parent coordinate.
"""
parent = None
for coord in coords:
assert parent_zoom <= coord.zoom
coord_parent = coord.zoomTo(parent_zoom).container()
... | [
"def",
"common_parent",
"(",
"coords",
",",
"parent_zoom",
")",
":",
"parent",
"=",
"None",
"for",
"coord",
"in",
"coords",
":",
"assert",
"parent_zoom",
"<=",
"coord",
".",
"zoom",
"coord_parent",
"=",
"coord",
".",
"zoomTo",
"(",
"parent_zoom",
")",
".",... | 30 | 0.00202 |
def walk(
self,
fs, # type: FS
path="/", # type: Text
namespaces=None, # type: Optional[Collection[Text]]
):
# type: (...) -> Iterator[Step]
"""Walk the directory structure of a filesystem.
Arguments:
fs (FS): A filesystem instance.
... | [
"def",
"walk",
"(",
"self",
",",
"fs",
",",
"# type: FS",
"path",
"=",
"\"/\"",
",",
"# type: Text",
"namespaces",
"=",
"None",
",",
"# type: Optional[Collection[Text]]",
")",
":",
"# type: (...) -> Iterator[Step]",
"_path",
"=",
"abspath",
"(",
"normpath",
"(",
... | 40.170213 | 0.002068 |
def get_numeric_feature_names(example):
"""Returns a list of feature names for float and int64 type features.
Args:
example: An example.
Returns:
A list of strings of the names of numeric features.
"""
numeric_features = ('float_list', 'int64_list')
features = get_example_features(example)
retur... | [
"def",
"get_numeric_feature_names",
"(",
"example",
")",
":",
"numeric_features",
"=",
"(",
"'float_list'",
",",
"'int64_list'",
")",
"features",
"=",
"get_example_features",
"(",
"example",
")",
"return",
"sorted",
"(",
"[",
"feature_name",
"for",
"feature_name",
... | 29.333333 | 0.011013 |
def _do_identity_policy_create(args):
"""Executes the 'policy create' subcommand. Given a key file, and a
series of entries, it generates a batch of sawtooth_identity
transactions in a BatchList instance. The BatchList is either stored to a
file or submitted to a validator, depending on the supplied CL... | [
"def",
"_do_identity_policy_create",
"(",
"args",
")",
":",
"signer",
"=",
"_read_signer",
"(",
"args",
".",
"key",
")",
"txns",
"=",
"[",
"_create_policy_txn",
"(",
"signer",
",",
"args",
".",
"name",
",",
"args",
".",
"rule",
")",
"]",
"batch",
"=",
... | 37.061224 | 0.000536 |
def write_facades(captures, options):
"""
Write the Facades to the appropriate _client<version>.py
"""
for version in sorted(captures.keys()):
filename = "{}/_client{}.py".format(options.output_dir, version)
with open(filename, "w") as f:
f.write(HEADER)
f.write(... | [
"def",
"write_facades",
"(",
"captures",
",",
"options",
")",
":",
"for",
"version",
"in",
"sorted",
"(",
"captures",
".",
"keys",
"(",
")",
")",
":",
"filename",
"=",
"\"{}/_client{}.py\"",
".",
"format",
"(",
"options",
".",
"output_dir",
",",
"version",... | 39.882353 | 0.001441 |
def fulfill(self,
agreement_id,
amount,
receiver_address,
sender_address,
lock_condition_id,
release_condition_id,
account):
"""
Fulfill the escrow reward condition.
:param agreement_... | [
"def",
"fulfill",
"(",
"self",
",",
"agreement_id",
",",
"amount",
",",
"receiver_address",
",",
"sender_address",
",",
"lock_condition_id",
",",
"release_condition_id",
",",
"account",
")",
":",
"return",
"self",
".",
"_fulfill",
"(",
"agreement_id",
",",
"amou... | 33.833333 | 0.008621 |
def setContentsMargins(self, left, top, right, bottom):
"""
Sets the contents margins for this node to the inputed values.
:param left | <int>
top | <int>
right | <int>
bottom | <int>
"""
self._ma... | [
"def",
"setContentsMargins",
"(",
"self",
",",
"left",
",",
"top",
",",
"right",
",",
"bottom",
")",
":",
"self",
".",
"_margins",
"=",
"(",
"left",
",",
"top",
",",
"right",
",",
"bottom",
")",
"self",
".",
"adjustTitleFont",
"(",
")"
] | 34.272727 | 0.010336 |
def mongodb_drop_database(database_name):
"""Drop Database"""
try:
mongodb_client_url = getattr(settings, 'MONGODB_CLIENT',
'mongodb://localhost:27017/')
mc = MongoClient(mongodb_client_url,document_class=OrderedDict)
mc.drop_database(database_name)
... | [
"def",
"mongodb_drop_database",
"(",
"database_name",
")",
":",
"try",
":",
"mongodb_client_url",
"=",
"getattr",
"(",
"settings",
",",
"'MONGODB_CLIENT'",
",",
"'mongodb://localhost:27017/'",
")",
"mc",
"=",
"MongoClient",
"(",
"mongodb_client_url",
",",
"document_cl... | 31.133333 | 0.008316 |
def _in(self, *lst):
"""Build out the in clause. Using _in due to shadowing for in"""
self.terms.append('in (%s)' % ', '.join(['"%s"' % x for x in lst]))
return self | [
"def",
"_in",
"(",
"self",
",",
"*",
"lst",
")",
":",
"self",
".",
"terms",
".",
"append",
"(",
"'in (%s)'",
"%",
"', '",
".",
"join",
"(",
"[",
"'\"%s\"'",
"%",
"x",
"for",
"x",
"in",
"lst",
"]",
")",
")",
"return",
"self"
] | 46.5 | 0.010582 |
def parse(args):
"""Parse command-line arguments. Arguments may consist of any
combination of directories, files, and options."""
import argparse
parser = argparse.ArgumentParser(
add_help=False,
description="Remove spam and advertising from subtitle files.",
usage="%(prog)s [O... | [
"def",
"parse",
"(",
"args",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"add_help",
"=",
"False",
",",
"description",
"=",
"\"Remove spam and advertising from subtitle files.\"",
",",
"usage",
"=",
"\"%(prog)s [OPTION]... TA... | 28.015873 | 0.000547 |
def flp_nonlinear_soco(I,J,d,M,f,c):
"""flp_nonlinear_soco -- use
Parameters:
- I: set of customers
- J: set of facilities
- d[i]: demand for product i
- M[j]: capacity of facility j
- f[j]: fixed cost for using a facility in point j
- c[i,j]: unit cost of servic... | [
"def",
"flp_nonlinear_soco",
"(",
"I",
",",
"J",
",",
"d",
",",
"M",
",",
"f",
",",
"c",
")",
":",
"model",
"=",
"Model",
"(",
"\"nonlinear flp -- soco formulation\"",
")",
"x",
",",
"X",
",",
"u",
"=",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
"... | 38.411765 | 0.026886 |
def delocate_tree_libs(lib_dict, lib_path, root_path):
""" Move needed libraries in `lib_dict` into `lib_path`
`lib_dict` has keys naming libraries required by the files in the
corresponding value. Call the keys, "required libs". Call the values
"requiring objects".
Copy all the required libs to... | [
"def",
"delocate_tree_libs",
"(",
"lib_dict",
",",
"lib_path",
",",
"root_path",
")",
":",
"copied_libs",
"=",
"{",
"}",
"delocated_libs",
"=",
"set",
"(",
")",
"copied_basenames",
"=",
"set",
"(",
")",
"rp_root_path",
"=",
"realpath",
"(",
"root_path",
")",... | 45.56 | 0.000859 |
def applet_rename(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /applet-xxxx/rename API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Name#API-method%3A-%2Fclass-xxxx%2Frename
"""
return DXHTTPRequest('/%s/rename' % object_id, input_param... | [
"def",
"applet_rename",
"(",
"object_id",
",",
"input_params",
"=",
"{",
"}",
",",
"always_retry",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"DXHTTPRequest",
"(",
"'/%s/rename'",
"%",
"object_id",
",",
"input_params",
",",
"always_retry",
"="... | 50.428571 | 0.008357 |
def find(self, *args):
"""
Find a node in the tree. If the node is not found it is added first and then returned.
:param args: a tuple
:return: returns the node
"""
curr_node = self.__root
return self.__traverse(curr_node, 0, *args) | [
"def",
"find",
"(",
"self",
",",
"*",
"args",
")",
":",
"curr_node",
"=",
"self",
".",
"__root",
"return",
"self",
".",
"__traverse",
"(",
"curr_node",
",",
"0",
",",
"*",
"args",
")"
] | 31.333333 | 0.010345 |
def __mesh_coords(ax_type, coords, n, **kwargs):
'''Compute axis coordinates'''
if coords is not None:
if len(coords) < n:
raise ParameterError('Coordinate shape mismatch: '
'{}<{}'.format(len(coords), n))
return coords
coord_map = {'linear': __... | [
"def",
"__mesh_coords",
"(",
"ax_type",
",",
"coords",
",",
"n",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"coords",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"coords",
")",
"<",
"n",
":",
"raise",
"ParameterError",
"(",
"'Coordinate shape mismatch: '",... | 36.15625 | 0.000842 |
def get_characteristic_from_uuid(self, uuid):
"""Given a characteristic UUID, return a :class:`Characteristic` object
containing information about that characteristic
Args:
uuid (str): a string containing the hex-encoded UUID
Returns:
None if an error occurs, ot... | [
"def",
"get_characteristic_from_uuid",
"(",
"self",
",",
"uuid",
")",
":",
"if",
"uuid",
"in",
"self",
".",
"uuid_chars",
":",
"logger",
".",
"debug",
"(",
"'Returning cached info for char: {}'",
".",
"format",
"(",
"uuid",
")",
")",
"return",
"self",
".",
"... | 36.5 | 0.002225 |
def version(path):
"""Obtain the packge version from a python file e.g. pkg/__init__.py
See <https://packaging.python.org/en/latest/single_source_version.html>.
"""
version_file = read(path)
version_match = re.search(r"""^__version__ = ['"]([^'"]*)['"]""",
version_file,... | [
"def",
"version",
"(",
"path",
")",
":",
"version_file",
"=",
"read",
"(",
"path",
")",
"version_match",
"=",
"re",
".",
"search",
"(",
"r\"\"\"^__version__ = ['\"]([^'\"]*)['\"]\"\"\"",
",",
"version_file",
",",
"re",
".",
"M",
")",
"if",
"version_match",
":"... | 43.4 | 0.002257 |
def search_bm25(cls, term, weights=None, with_score=False,
score_alias='score', explicit_ordering=False):
"""Full-text search for selected `term` using BM25 algorithm."""
return cls._search(
term,
weights,
with_score,
score_alias,
... | [
"def",
"search_bm25",
"(",
"cls",
",",
"term",
",",
"weights",
"=",
"None",
",",
"with_score",
"=",
"False",
",",
"score_alias",
"=",
"'score'",
",",
"explicit_ordering",
"=",
"False",
")",
":",
"return",
"cls",
".",
"_search",
"(",
"term",
",",
"weights... | 35.8 | 0.008174 |
def ping(self, callback=None, **kwargs):
"""
Ping request to check status of elasticsearch host
"""
self.client.fetch(
self.mk_req('', method='HEAD', **kwargs),
callback = callback
) | [
"def",
"ping",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"client",
".",
"fetch",
"(",
"self",
".",
"mk_req",
"(",
"''",
",",
"method",
"=",
"'HEAD'",
",",
"*",
"*",
"kwargs",
")",
",",
"callback",
... | 29.875 | 0.01626 |
def quickplot_ax(ax, data, xmin, xmax, xlabel, title=None, ylabel="Counts",
counts=True, percentage=True, highlight=None):
'''
TODO: redundant with quickplot(), need to be refactored.
'''
if percentage:
total_length = sum(data.values())
data = dict((k, v * 100. / total_l... | [
"def",
"quickplot_ax",
"(",
"ax",
",",
"data",
",",
"xmin",
",",
"xmax",
",",
"xlabel",
",",
"title",
"=",
"None",
",",
"ylabel",
"=",
"\"Counts\"",
",",
"counts",
"=",
"True",
",",
"percentage",
"=",
"True",
",",
"highlight",
"=",
"None",
")",
":",
... | 32.857143 | 0.002111 |
def generator_telling_position(self) -> Iterator[Tuple[str, int]]:
"""
Create a generate that iterates the whole content of the file or string, and also tells which offset is now.
:return: An iterator iterating tuples, containing lines of the text stream,...
separated by ``'\\n'`` o... | [
"def",
"generator_telling_position",
"(",
"self",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"str",
",",
"int",
"]",
"]",
":",
"stream",
"=",
"self",
".",
"stream",
"# In case that ``self.stream`` is changed.",
"stream",
".",
"seek",
"(",
"0",
")",
"for",
"li... | 49 | 0.009107 |
def clean_files(files):
"""Generates tuples with a ``file``-like object and a close indicator.
This is a generator of tuples, where the first element is the file object
and the second element is a boolean which is True if this module opened the
file (and thus should close it).
Raises
------
... | [
"def",
"clean_files",
"(",
"files",
")",
":",
"if",
"isinstance",
"(",
"files",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"f",
"in",
"files",
":",
"yield",
"clean_file",
"(",
"f",
")",
"else",
":",
"yield",
"clean_file",
"(",
"files",
"... | 30.190476 | 0.001529 |
def dict_merge(dict_left, dict_right, merge_method='take_left_shallow'):
"""
Merge two dictionaries.
This method does NOT modify dict_left or dict_right!
Apply this method multiple times if the dictionary is nested.
Parameters
----------
dict_left : dict
dict_right: dict
merge_met... | [
"def",
"dict_merge",
"(",
"dict_left",
",",
"dict_right",
",",
"merge_method",
"=",
"'take_left_shallow'",
")",
":",
"new_dict",
"=",
"{",
"}",
"if",
"merge_method",
"in",
"[",
"'take_right_shallow'",
",",
"'take_right_deep'",
"]",
":",
"return",
"_dict_merge_righ... | 36.289474 | 0.000353 |
def getTriples(pointing):
"""Get all triples of a specified pointing ID.
Defaults is to return a complete list triples."""
sql="SELECT id FROM triples t join triple_members m ON t.id=m.triple"
sql+=" join bucket.exposure e on e.expnum=m.expnum "
sql+=" WHERE pointing=%s group by id order by e.ex... | [
"def",
"getTriples",
"(",
"pointing",
")",
":",
"sql",
"=",
"\"SELECT id FROM triples t join triple_members m ON t.id=m.triple\"",
"sql",
"+=",
"\" join bucket.exposure e on e.expnum=m.expnum \"",
"sql",
"+=",
"\" WHERE pointing=%s group by id order by e.expnum \"",
"cfeps",
".",
... | 38.6 | 0.01519 |
def add_resourcegroupitems(scenario_id, items, scenario=None, **kwargs):
"""
Get all the items in a group, in a scenario.
"""
user_id = int(kwargs.get('user_id'))
if scenario is None:
scenario = _get_scenario(scenario_id, user_id)
_check_network_ownership(scenario.network_id, user... | [
"def",
"add_resourcegroupitems",
"(",
"scenario_id",
",",
"items",
",",
"scenario",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"int",
"(",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
")",
"if",
"scenario",
"is",
"None",
":",
"scen... | 25.45 | 0.001894 |
def objective_to_model(self, x_objective):
''' This function serves as interface between objective input vectors and
model input vectors'''
x_model = []
for k in range(self.objective_dimensionality):
variable = self.space_expanded[k]
new_entry = variable.objecti... | [
"def",
"objective_to_model",
"(",
"self",
",",
"x_objective",
")",
":",
"x_model",
"=",
"[",
"]",
"for",
"k",
"in",
"range",
"(",
"self",
".",
"objective_dimensionality",
")",
":",
"variable",
"=",
"self",
".",
"space_expanded",
"[",
"k",
"]",
"new_entry",... | 32.916667 | 0.009852 |
def new_message_from_message_type(message_type):
"""Given an OpenFlow Message Type, return an empty message of that type.
Args:
messageType (:class:`~pyof.v0x01.common.header.Type`):
Python-openflow message.
Returns:
Empty OpenFlow message of the requested message type.
Ra... | [
"def",
"new_message_from_message_type",
"(",
"message_type",
")",
":",
"message_type",
"=",
"str",
"(",
"message_type",
")",
"if",
"message_type",
"not",
"in",
"MESSAGE_TYPES",
":",
"raise",
"ValueError",
"(",
"'\"{}\" is not known.'",
".",
"format",
"(",
"message_t... | 27.695652 | 0.001517 |
def create_dataset_version(self, dataset_id):
"""
Create a new data set version.
:param dataset_id: The ID of the dataset for which the version must be bumped.
:type dataset_id: int
:return: The new dataset version.
:rtype: :class:`DatasetVersion`
"""
fai... | [
"def",
"create_dataset_version",
"(",
"self",
",",
"dataset_id",
")",
":",
"failure_message",
"=",
"\"Failed to create dataset version for dataset {}\"",
".",
"format",
"(",
"dataset_id",
")",
"number",
"=",
"self",
".",
"_get_success_json",
"(",
"self",
".",
"_post_j... | 46.153846 | 0.00817 |
def clean(self):
"""
delete all confirmations for the same content_object and the same field
"""
EmailConfirmation.objects.filter(content_type=self.content_type, object_id=self.object_id, email_field_name=self.email_field_name).delete() | [
"def",
"clean",
"(",
"self",
")",
":",
"EmailConfirmation",
".",
"objects",
".",
"filter",
"(",
"content_type",
"=",
"self",
".",
"content_type",
",",
"object_id",
"=",
"self",
".",
"object_id",
",",
"email_field_name",
"=",
"self",
".",
"email_field_name",
... | 44 | 0.011152 |
def cast_pars_dict(pars_dict):
"""Cast the bool and float elements of a parameters dict to
the appropriate python types.
"""
o = {}
for pname, pdict in pars_dict.items():
o[pname] = {}
for k, v in pdict.items():
if k == 'free':
o[pname][k] = bool(int(... | [
"def",
"cast_pars_dict",
"(",
"pars_dict",
")",
":",
"o",
"=",
"{",
"}",
"for",
"pname",
",",
"pdict",
"in",
"pars_dict",
".",
"items",
"(",
")",
":",
"o",
"[",
"pname",
"]",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"pdict",
".",
"items",
"("... | 20.761905 | 0.002193 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AwsContext for this AwsInstance
:rtype: twilio.rest.accounts.v1.credential.aws.AwsContext
... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"AwsContext",
"(",
"self",
".",
"_version",
",",
"sid",
"=",
"self",
".",
"_solution",
"[",
"'sid'",
"]",
",",
")",
"return",
"s... | 41.818182 | 0.010638 |
def _validate_sub(claims, subject=None):
"""Validates that the 'sub' claim is valid.
The "sub" (subject) claim identifies the principal that is the
subject of the JWT. The claims in a JWT are normally statements
about the subject. The subject value MUST either be scoped to be
locally unique in th... | [
"def",
"_validate_sub",
"(",
"claims",
",",
"subject",
"=",
"None",
")",
":",
"if",
"'sub'",
"not",
"in",
"claims",
":",
"return",
"if",
"not",
"isinstance",
"(",
"claims",
"[",
"'sub'",
"]",
",",
"string_types",
")",
":",
"raise",
"JWTClaimsError",
"(",... | 37.16 | 0.001049 |
def on_train_begin(self, **kwargs):
"Add the metrics names to the `Recorder`."
self.names = ifnone(self.learn.loss_func.metric_names, [])
if not self.names: warn('LossMetrics requested but no loss_func.metric_names provided')
self.learn.recorder.add_metric_names(self.names) | [
"def",
"on_train_begin",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"names",
"=",
"ifnone",
"(",
"self",
".",
"learn",
".",
"loss_func",
".",
"metric_names",
",",
"[",
"]",
")",
"if",
"not",
"self",
".",
"names",
":",
"warn",
"(",... | 60.4 | 0.013072 |
def set_foregroundcolor(self, color):
'''For the specified axes, sets the color of the frame, major ticks,
tick labels, axis labels, title and legend
'''
ax = self.ax
for tl in ax.get_xticklines() + ax.get_yticklines():
tl.set_color(color)
for spi... | [
"def",
"set_foregroundcolor",
"(",
"self",
",",
"color",
")",
":",
"ax",
"=",
"self",
".",
"ax",
"for",
"tl",
"in",
"ax",
".",
"get_xticklines",
"(",
")",
"+",
"ax",
".",
"get_yticklines",
"(",
")",
":",
"tl",
".",
"set_color",
"(",
"color",
")",
"... | 37.8125 | 0.024174 |
def handle_api_explorer_request(self, request, start_response):
"""Handler for requests to {base_path}/explorer.
This calls start_response and returns the response body.
Args:
request: An ApiRequest, the request from the user.
start_response: A function with semantics defined in PEP-333.
... | [
"def",
"handle_api_explorer_request",
"(",
"self",
",",
"request",
",",
"start_response",
")",
":",
"redirect_url",
"=",
"self",
".",
"_get_explorer_redirect_url",
"(",
"request",
".",
"server",
",",
"request",
".",
"port",
",",
"request",
".",
"base_path",
")",... | 38.733333 | 0.001681 |
def markdown(
source: str = None,
source_path: str = None,
preserve_lines: bool = False,
font_size: float = None,
**kwargs
):
"""
Renders the specified source string or source file using markdown and
adds the resulting HTML to the notebook display.
:param source... | [
"def",
"markdown",
"(",
"source",
":",
"str",
"=",
"None",
",",
"source_path",
":",
"str",
"=",
"None",
",",
"preserve_lines",
":",
"bool",
"=",
"False",
",",
"font_size",
":",
"float",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"_ge... | 32.348837 | 0.001396 |
def find_config(revision):
"""Locate and return the default config for current revison."""
if not is_git_repo():
return None
cfg_path = f"{revision}:.cherry_picker.toml"
cmd = "git", "cat-file", "-t", cfg_path
try:
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
... | [
"def",
"find_config",
"(",
"revision",
")",
":",
"if",
"not",
"is_git_repo",
"(",
")",
":",
"return",
"None",
"cfg_path",
"=",
"f\"{revision}:.cherry_picker.toml\"",
"cmd",
"=",
"\"git\"",
",",
"\"cat-file\"",
",",
"\"-t\"",
",",
"cfg_path",
"try",
":",
"outpu... | 33.785714 | 0.002058 |
def email_link_expired(self, now=None):
""" Check if email link expired """
if not now: now = datetime.datetime.utcnow()
return self.email_link_expires < now | [
"def",
"email_link_expired",
"(",
"self",
",",
"now",
"=",
"None",
")",
":",
"if",
"not",
"now",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"return",
"self",
".",
"email_link_expires",
"<",
"now"
] | 44.5 | 0.016575 |
def is_empty_shape(sh: ShExJ.Shape) -> bool:
""" Determine whether sh has any value """
return sh.closed is None and sh.expression is None and sh.extra is None and \
sh.semActs is None | [
"def",
"is_empty_shape",
"(",
"sh",
":",
"ShExJ",
".",
"Shape",
")",
"->",
"bool",
":",
"return",
"sh",
".",
"closed",
"is",
"None",
"and",
"sh",
".",
"expression",
"is",
"None",
"and",
"sh",
".",
"extra",
"is",
"None",
"and",
"sh",
".",
"semActs",
... | 52.25 | 0.014151 |
def get_startups_filtered_by(self, filter_='raising'):
""" Get startups based on which companies are raising funding
"""
url = _STARTUP_RAISING.format(c_api=_C_API_BEGINNING,
api=_API_VERSION,
... | [
"def",
"get_startups_filtered_by",
"(",
"self",
",",
"filter_",
"=",
"'raising'",
")",
":",
"url",
"=",
"_STARTUP_RAISING",
".",
"format",
"(",
"c_api",
"=",
"_C_API_BEGINNING",
",",
"api",
"=",
"_API_VERSION",
",",
"filter_",
"=",
"filter_",
",",
"at",
"=",... | 60.5 | 0.014257 |
def _process_resp(request_id, response, is_success_func):
"""
:param request_id: campus url identifying the request
:param response: the GET method response object
:param is_success_func: the name of the function for
verifying a success code
:return: True if successful, False otherwise.
... | [
"def",
"_process_resp",
"(",
"request_id",
",",
"response",
",",
"is_success_func",
")",
":",
"if",
"response",
".",
"status",
"!=",
"200",
":",
"raise",
"DataFailureException",
"(",
"request_id",
",",
"response",
".",
"status",
",",
"response",
".",
"reason",... | 40.5 | 0.000928 |
def print_formatted(datas):
"""Pretty print JSON DATA
Argument:
datas: dictionary of data
"""
if not datas:
print("No data")
exit(1)
if isinstance(datas, list):
# get all zones
# API /zone without :identifier
hr()
print('%-20s %-8s %-12s'
... | [
"def",
"print_formatted",
"(",
"datas",
")",
":",
"if",
"not",
"datas",
":",
"print",
"(",
"\"No data\"",
")",
"exit",
"(",
"1",
")",
"if",
"isinstance",
"(",
"datas",
",",
"list",
")",
":",
"# get all zones",
"# API /zone without :identifier",
"hr",
"(",
... | 27.546218 | 0.000294 |
def p_mp_createClass(p):
"""mp_createClass : classDeclaration
"""
# pylint: disable=too-many-branches,too-many-statements,too-many-locals
ns = p.parser.handle.default_namespace
cc = p[1]
try:
fixedNS = fixedRefs = fixedSuper = False
while not fixedNS or not fix... | [
"def",
"p_mp_createClass",
"(",
"p",
")",
":",
"# pylint: disable=too-many-branches,too-many-statements,too-many-locals",
"ns",
"=",
"p",
".",
"parser",
".",
"handle",
".",
"default_namespace",
"cc",
"=",
"p",
"[",
"1",
"]",
"try",
":",
"fixedNS",
"=",
"fixedRefs"... | 46.4 | 0.000338 |
def _call_marginalizevperp(self,o,integrate_method='dopr54_c',**kwargs):
"""Call the DF, marginalizing over perpendicular velocity"""
#Get d, l, vlos
l= o.ll(obs=[1.,0.,0.],ro=1.)*_DEGTORAD
vlos= o.vlos(ro=1.,vo=1.,obs=[1.,0.,0.,0.,0.,0.])
R= o.R(use_physical=False)
phi= ... | [
"def",
"_call_marginalizevperp",
"(",
"self",
",",
"o",
",",
"integrate_method",
"=",
"'dopr54_c'",
",",
"*",
"*",
"kwargs",
")",
":",
"#Get d, l, vlos",
"l",
"=",
"o",
".",
"ll",
"(",
"obs",
"=",
"[",
"1.",
",",
"0.",
",",
"0.",
"]",
",",
"ro",
"=... | 50.860465 | 0.027367 |
def ungrab_keyboard(self, time, onerror = None):
"""Ungrab a grabbed keyboard and any queued events. See
XUngrabKeyboard(3X11)."""
request.UngrabKeyboard(display = self.display,
onerror = onerror,
time = time) | [
"def",
"ungrab_keyboard",
"(",
"self",
",",
"time",
",",
"onerror",
"=",
"None",
")",
":",
"request",
".",
"UngrabKeyboard",
"(",
"display",
"=",
"self",
".",
"display",
",",
"onerror",
"=",
"onerror",
",",
"time",
"=",
"time",
")"
] | 48.333333 | 0.033898 |
def _get_fields_info(self, cols, model_schema, filter_rel_fields, **kwargs):
"""
Returns a dict with fields detail
from a marshmallow schema
:param cols: list of columns to show info for
:param model_schema: Marshmallow model schema
:param filter_rel_fields: expe... | [
"def",
"_get_fields_info",
"(",
"self",
",",
"cols",
",",
"model_schema",
",",
"filter_rel_fields",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"list",
"(",
")",
"for",
"col",
"in",
"cols",
":",
"page",
"=",
"page_size",
"=",
"None",
"col_args",
"="... | 38.285714 | 0.00182 |
def begin_table(self, column_count):
"""Begins a table with the given 'column_count', required to automatically
create the right amount of columns when adding items to the rows"""
self.table_columns = column_count
self.table_columns_left = 0
self.write('<table>') | [
"def",
"begin_table",
"(",
"self",
",",
"column_count",
")",
":",
"self",
".",
"table_columns",
"=",
"column_count",
"self",
".",
"table_columns_left",
"=",
"0",
"self",
".",
"write",
"(",
"'<table>'",
")"
] | 50.166667 | 0.009804 |
def log_output(chan):
"""
logs the output from a remote command
the input should be an open channel in the case of synchronous better_exec_command
otherwise this will not log anything and simply return to the caller
:param chan:
:return:
"""
if hasattr(chan, "recv"):
str = chan.recv(1024)
... | [
"def",
"log_output",
"(",
"chan",
")",
":",
"if",
"hasattr",
"(",
"chan",
",",
"\"recv\"",
")",
":",
"str",
"=",
"chan",
".",
"recv",
"(",
"1024",
")",
"msgs",
"=",
"[",
"]",
"while",
"len",
"(",
"str",
")",
">",
"0",
":",
"msgs",
".",
"append"... | 27.941176 | 0.014257 |
def reqMktData(
self, contract: Contract, genericTickList: str = '',
snapshot: bool = False, regulatorySnapshot: bool = False,
mktDataOptions: List[TagValue] = None) -> Ticker:
"""
Subscribe to tick data or request a snapshot.
Returns the Ticker that holds the... | [
"def",
"reqMktData",
"(",
"self",
",",
"contract",
":",
"Contract",
",",
"genericTickList",
":",
"str",
"=",
"''",
",",
"snapshot",
":",
"bool",
"=",
"False",
",",
"regulatorySnapshot",
":",
"bool",
"=",
"False",
",",
"mktDataOptions",
":",
"List",
"[",
... | 46.660714 | 0.00075 |
def decode_utf8(f):
"""Decode a utf-8 string encoded as described in MQTT Version
3.1.1 section 1.5.3 line 177. This is a 16-bit unsigned length
followed by a utf-8 encoded string.
Parameters
----------
f: file
File-like object with read method.
Raises
------
UnderflowDeco... | [
"def",
"decode_utf8",
"(",
"f",
")",
":",
"decode",
"=",
"codecs",
".",
"getdecoder",
"(",
"'utf8'",
")",
"buf",
"=",
"f",
".",
"read",
"(",
"FIELD_U16",
".",
"size",
")",
"if",
"len",
"(",
"buf",
")",
"<",
"FIELD_U16",
".",
"size",
":",
"raise",
... | 25.340909 | 0.000864 |
def add(self, username, user_api, filename=None):
"""
Add SSH public key to a user's profile.
Args:
username: Username to attach SSH public key to
filename: Filename containing keys to add (optional)
Raises:
ldap3.core.exceptions.LDAPNoSuchAttributeR... | [
"def",
"add",
"(",
"self",
",",
"username",
",",
"user_api",
",",
"filename",
"=",
"None",
")",
":",
"keys",
"=",
"API",
".",
"__get_keys",
"(",
"filename",
")",
"user",
"=",
"user_api",
".",
"find",
"(",
"username",
")",
"[",
"0",
"]",
"distinguishe... | 38.7 | 0.001681 |
def get_gravatar(email, size=80, rating='g', default=None,
protocol=PROTOCOL):
"""
Return url for a Gravatar.
"""
gravatar_protocols = {'http': 'http://www',
'https': 'https://secure'}
url = '%s.gravatar.com/avatar/%s' % (
gravatar_protocols[protoco... | [
"def",
"get_gravatar",
"(",
"email",
",",
"size",
"=",
"80",
",",
"rating",
"=",
"'g'",
",",
"default",
"=",
"None",
",",
"protocol",
"=",
"PROTOCOL",
")",
":",
"gravatar_protocols",
"=",
"{",
"'http'",
":",
"'http://www'",
",",
"'https'",
":",
"'https:/... | 33.875 | 0.001795 |
def _download_log(self, url, output_file):
"""Saves log returned by the message bus."""
logger.info("Saving log %s to %s", url, output_file)
def _do_log_download():
try:
return self.session.get(url)
# pylint: disable=broad-except
except Except... | [
"def",
"_download_log",
"(",
"self",
",",
"url",
",",
"output_file",
")",
":",
"logger",
".",
"info",
"(",
"\"Saving log %s to %s\"",
",",
"url",
",",
"output_file",
")",
"def",
"_do_log_download",
"(",
")",
":",
"try",
":",
"return",
"self",
".",
"session... | 34.652174 | 0.002442 |
def process_json(json_dict):
"""Return an EidosProcessor by processing a Eidos JSON-LD dict.
Parameters
----------
json_dict : dict
The JSON-LD dict to be processed.
Returns
-------
ep : EidosProcessor
A EidosProcessor containing the extracted INDRA Statements
in it... | [
"def",
"process_json",
"(",
"json_dict",
")",
":",
"ep",
"=",
"EidosProcessor",
"(",
"json_dict",
")",
"ep",
".",
"extract_causal_relations",
"(",
")",
"ep",
".",
"extract_correlations",
"(",
")",
"ep",
".",
"extract_events",
"(",
")",
"return",
"ep"
] | 24.736842 | 0.002049 |
def admin_tools_render_menu_item(context, item, index=None):
"""
Template tag that renders a given menu item, it takes a ``MenuItem``
instance as unique parameter.
"""
item.init_with_context(context)
context.update({
'template': item.template,
'item': item,
'index': inde... | [
"def",
"admin_tools_render_menu_item",
"(",
"context",
",",
"item",
",",
"index",
"=",
"None",
")",
":",
"item",
".",
"init_with_context",
"(",
"context",
")",
"context",
".",
"update",
"(",
"{",
"'template'",
":",
"item",
".",
"template",
",",
"'item'",
"... | 31 | 0.002088 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.