text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def sub_dfs_by_size(df, size):
"""Get a generator yielding consecutive sub-dataframes of the given size.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
size : int
The size of each sub-dataframe.
Returns
-------
generator
... | [
"def",
"sub_dfs_by_size",
"(",
"df",
",",
"size",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"df",
")",
",",
"size",
")",
":",
"yield",
"(",
"df",
".",
"iloc",
"[",
"i",
":",
"i",
"+",
"size",
"]",
")"
] | 26.586207 | 0.001252 |
def topological_sort(dependency_pairs):
"Sort values subject to dependency constraints"
num_heads = defaultdict(int) # num arrows pointing in
tails = defaultdict(list) # list of arrows going out
heads = [] # unique list of heads in order first seen
for h, t in dependency_pairs:
num_heads[... | [
"def",
"topological_sort",
"(",
"dependency_pairs",
")",
":",
"num_heads",
"=",
"defaultdict",
"(",
"int",
")",
"# num arrows pointing in",
"tails",
"=",
"defaultdict",
"(",
"list",
")",
"# list of arrows going out",
"heads",
"=",
"[",
"]",
"# unique list of heads in ... | 34.666667 | 0.001337 |
def find(self, pattern):
"""
Searches for a pattern in the current memory segment
"""
pos = self.current_segment.data.find(pattern)
if pos == -1:
return -1
return pos + self.current_position | [
"def",
"find",
"(",
"self",
",",
"pattern",
")",
":",
"pos",
"=",
"self",
".",
"current_segment",
".",
"data",
".",
"find",
"(",
"pattern",
")",
"if",
"pos",
"==",
"-",
"1",
":",
"return",
"-",
"1",
"return",
"pos",
"+",
"self",
".",
"current_posit... | 24.75 | 0.043902 |
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the g... | [
"def",
"run_migrations_offline",
"(",
")",
":",
"# for the --sql use case, run migrations for each URL into",
"# individual files.",
"engines",
"=",
"{",
"''",
":",
"{",
"'url'",
":",
"context",
".",
"config",
".",
"get_main_option",
"(",
"'sqlalchemy.url'",
")",
"}",
... | 32.72973 | 0.000802 |
def _get_entry_point(runtime, debug_options=None): # pylint: disable=too-many-branches
"""
Returns the entry point for the container. The default value for the entry point is already configured in the
Dockerfile. We override this default specifically when enabling debugging. The overridden entr... | [
"def",
"_get_entry_point",
"(",
"runtime",
",",
"debug_options",
"=",
"None",
")",
":",
"# pylint: disable=too-many-branches",
"if",
"not",
"debug_options",
":",
"return",
"None",
"if",
"runtime",
"not",
"in",
"LambdaContainer",
".",
"_supported_runtimes",
"(",
")",... | 41.151724 | 0.002455 |
def get_stock_dividends(self, sid, trading_days):
"""
Returns all the stock dividends for a specific sid that occur
in the given trading range.
Parameters
----------
sid: int
The asset whose stock dividends should be returned.
trading_days: pd.Dateti... | [
"def",
"get_stock_dividends",
"(",
"self",
",",
"sid",
",",
"trading_days",
")",
":",
"if",
"self",
".",
"_adjustment_reader",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"len",
"(",
"trading_days",
")",
"==",
"0",
":",
"return",
"[",
"]",
"start_dt",
... | 32.391304 | 0.001303 |
def crypto_aead_chacha20poly1305_ietf_encrypt(message, aad, nonce, key):
"""
Encrypt the given ``message`` using the IETF ratified chacha20poly1305
construction described in RFC7539.
:param message:
:type message: bytes
:param aad:
:type aad: bytes
:param nonce:
:type nonce: bytes
... | [
"def",
"crypto_aead_chacha20poly1305_ietf_encrypt",
"(",
"message",
",",
"aad",
",",
"nonce",
",",
"key",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"message",
",",
"bytes",
")",
",",
"'Input message type must be bytes'",
",",
"raising",
"=",
"exc",
".",
"TypeE... | 35.119403 | 0.000413 |
def flatten_op_tree(root: OP_TREE,
preserve_moments: bool = False
) -> Iterable[Union[Operation, Moment]]:
"""Performs an in-order iteration of the operations (leaves) in an OP_TREE.
Args:
root: The operation or tree of operations to iterate.
preserve_mom... | [
"def",
"flatten_op_tree",
"(",
"root",
":",
"OP_TREE",
",",
"preserve_moments",
":",
"bool",
"=",
"False",
")",
"->",
"Iterable",
"[",
"Union",
"[",
"Operation",
",",
"Moment",
"]",
"]",
":",
"if",
"(",
"isinstance",
"(",
"root",
",",
"Operation",
")",
... | 31.413793 | 0.001065 |
def save_segments(outfile, boundaries, beat_intervals, labels=None):
"""Save detected segments to a .lab file.
:parameters:
- outfile : str
Path to output file
- boundaries : list of int
Beat indices of detected segment boundaries
- beat_intervals : np.ndarray ... | [
"def",
"save_segments",
"(",
"outfile",
",",
"boundaries",
",",
"beat_intervals",
",",
"labels",
"=",
"None",
")",
":",
"if",
"labels",
"is",
"None",
":",
"labels",
"=",
"[",
"(",
"'Seg#%03d'",
"%",
"idx",
")",
"for",
"idx",
"in",
"range",
"(",
"1",
... | 32.857143 | 0.001056 |
def generate(ctx, url, *args, **kwargs):
"""
Generate preview for URL.
"""
file_previews = ctx.obj['file_previews']
options = {}
metadata = kwargs['metadata']
width = kwargs['width']
height = kwargs['height']
output_format = kwargs['format']
if metadata:
options['metada... | [
"def",
"generate",
"(",
"ctx",
",",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"file_previews",
"=",
"ctx",
".",
"obj",
"[",
"'file_previews'",
"]",
"options",
"=",
"{",
"}",
"metadata",
"=",
"kwargs",
"[",
"'metadata'",
"]",
"width"... | 22.586207 | 0.001464 |
def _sliced_shape(shape, keys):
"""
Returns the shape that results from slicing an array of the given
shape by the given keys.
>>> _sliced_shape(shape=(52350, 70, 90, 180),
... keys=(np.newaxis, slice(None, 10), 3,
... slice(None), slice(2, 3)))
(1, 10, 90,... | [
"def",
"_sliced_shape",
"(",
"shape",
",",
"keys",
")",
":",
"keys",
"=",
"_full_keys",
"(",
"keys",
",",
"len",
"(",
"shape",
")",
")",
"sliced_shape",
"=",
"[",
"]",
"shape_dim",
"=",
"-",
"1",
"for",
"key",
"in",
"keys",
":",
"shape_dim",
"+=",
... | 31.8 | 0.000872 |
def debug(self, msg):
'''
Handle the debugging to a file
'''
# If debug is not disabled
if self.__debug is not False:
# If never was set, try to set it up
if self.__debug is None:
# Check what do we have inside settings
de... | [
"def",
"debug",
"(",
"self",
",",
"msg",
")",
":",
"# If debug is not disabled",
"if",
"self",
".",
"__debug",
"is",
"not",
"False",
":",
"# If never was set, try to set it up",
"if",
"self",
".",
"__debug",
"is",
"None",
":",
"# Check what do we have inside setting... | 33.956522 | 0.002491 |
def get_algorithm(algorithm):
"""Returns the wire format string and the hash module to use for the
specified TSIG algorithm
@rtype: (string, hash constructor)
@raises NotImplementedError: I{algorithm} is not supported
"""
global _hashes
if _hashes is None:
_setup_hashes()
if i... | [
"def",
"get_algorithm",
"(",
"algorithm",
")",
":",
"global",
"_hashes",
"if",
"_hashes",
"is",
"None",
":",
"_setup_hashes",
"(",
")",
"if",
"isinstance",
"(",
"algorithm",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"algorithm",
"=",
"dns",
".",
... | 33.92 | 0.001147 |
def local_voxelize(mesh, point, pitch, radius, fill=True, **kwargs):
"""
Voxelize a mesh in the region of a cube around a point. When fill=True,
uses proximity.contains to fill the resulting voxels so may be meaningless
for non-watertight meshes. Useful to reduce memory cost for small values of
pitc... | [
"def",
"local_voxelize",
"(",
"mesh",
",",
"point",
",",
"pitch",
",",
"radius",
",",
"fill",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"scipy",
"import",
"ndimage",
"# make sure point is correct type/shape",
"point",
"=",
"np",
".",
"asanyarra... | 35.393258 | 0.000926 |
def _evil_apply_with_dataframes(self, func, preserves_cols=False):
"""Convert the underlying SchmeaRDD to an RDD of DataFrames.
apply the provide function and convert the result back.
This is hella slow."""
source_rdd = self._rdd()
result_rdd = func(source_rdd)
# By defau... | [
"def",
"_evil_apply_with_dataframes",
"(",
"self",
",",
"func",
",",
"preserves_cols",
"=",
"False",
")",
":",
"source_rdd",
"=",
"self",
".",
"_rdd",
"(",
")",
"result_rdd",
"=",
"func",
"(",
"source_rdd",
")",
"# By default we don't know what the columns & indexes... | 50 | 0.002454 |
def evaluate_call_args(self, calculator):
"""Interpreting this literal as a function call, return a 2-tuple of
``(args, kwargs)``.
"""
args = []
kwargs = OrderedDict() # Sass kwargs preserve order
for var_node, value_node in self.argpairs:
value = value_node.... | [
"def",
"evaluate_call_args",
"(",
"self",
",",
"calculator",
")",
":",
"args",
"=",
"[",
"]",
"kwargs",
"=",
"OrderedDict",
"(",
")",
"# Sass kwargs preserve order",
"for",
"var_node",
",",
"value_node",
"in",
"self",
".",
"argpairs",
":",
"value",
"=",
"val... | 37.478261 | 0.002262 |
def add_create_update_args(parser, required_args, optional_args, create=False):
"""Wrapper around ``add_parser_arguments``.
If ``create`` is True, one argument group will be created for each of
``required_args`` and ``optional_args``. Each required argument will have
the ``required`` parameter set to T... | [
"def",
"add_create_update_args",
"(",
"parser",
",",
"required_args",
",",
"optional_args",
",",
"create",
"=",
"False",
")",
":",
"if",
"create",
":",
"for",
"key",
"in",
"required_args",
":",
"required_args",
"[",
"key",
"]",
"[",
"'required'",
"]",
"=",
... | 40.65 | 0.001202 |
def parse_response(self, response):
"""Parses the API response and raises appropriate
errors if raise_errors was set to True
:param response: response from requests http call
:returns: dictionary of response
:rtype: dict
"""
payload = None
try:
... | [
"def",
"parse_response",
"(",
"self",
",",
"response",
")",
":",
"payload",
"=",
"None",
"try",
":",
"if",
"isinstance",
"(",
"response",
".",
"json",
",",
"collections",
".",
"Callable",
")",
":",
"payload",
"=",
"response",
".",
"json",
"(",
")",
"el... | 36 | 0.001803 |
def send_email(self, to):
"""
Do work.
"""
body = self.body()
subject = self.subject()
import letter
class Message(letter.Letter):
Postie = letter.DjangoPostman()
From = getattr(settings, 'DEFAULT_FROM_EMAIL', 'contact@example.com')
... | [
"def",
"send_email",
"(",
"self",
",",
"to",
")",
":",
"body",
"=",
"self",
".",
"body",
"(",
")",
"subject",
"=",
"self",
".",
"subject",
"(",
")",
"import",
"letter",
"class",
"Message",
"(",
"letter",
".",
"Letter",
")",
":",
"Postie",
"=",
"let... | 22.863636 | 0.01145 |
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_2_0):
"""
Write the Attributes structure encoding to the data stream.
Args:
output_stream (stream): A data stream in which to encode
Attributes structure data, supporting a write method.
k... | [
"def",
"write",
"(",
"self",
",",
"output_stream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_2_0",
")",
":",
"if",
"kmip_version",
"<",
"enums",
".",
"KMIPVersion",
".",
"KMIP_2_0",
":",
"raise",
"exceptions",
".",
"VersionNotSupported"... | 41.9 | 0.001166 |
def generate_grid(horiz_dim, bbox):
r"""Generate a meshgrid based on bounding box and x & y resolution.
Parameters
----------
horiz_dim: integer
Horizontal resolution
bbox: dictionary
Dictionary containing coordinates for corners of study area.
Returns
-------
grid_x: (... | [
"def",
"generate_grid",
"(",
"horiz_dim",
",",
"bbox",
")",
":",
"x_steps",
",",
"y_steps",
"=",
"get_xy_steps",
"(",
"bbox",
",",
"horiz_dim",
")",
"grid_x",
"=",
"np",
".",
"linspace",
"(",
"bbox",
"[",
"'west'",
"]",
",",
"bbox",
"[",
"'east'",
"]",... | 27.038462 | 0.001374 |
def validate_checksum( filename, md5sum ):
"""
Compares the md5 checksum of a file with an expected value.
If the calculated and expected checksum values are not equal,
ValueError is raised.
If the filename `foo` is not found, will try to read a gzipped file named
`foo.gz`. In this case, the ch... | [
"def",
"validate_checksum",
"(",
"filename",
",",
"md5sum",
")",
":",
"filename",
"=",
"match_filename",
"(",
"filename",
")",
"md5_hash",
"=",
"file_md5",
"(",
"filename",
"=",
"filename",
")",
"if",
"md5_hash",
"!=",
"md5sum",
":",
"raise",
"ValueError",
"... | 36.736842 | 0.015363 |
def end_address(self):
"""Get basic block end address.
"""
if self._instrs is []:
return None
return self._instrs[-1].address + self._instrs[-1].size - 1 | [
"def",
"end_address",
"(",
"self",
")",
":",
"if",
"self",
".",
"_instrs",
"is",
"[",
"]",
":",
"return",
"None",
"return",
"self",
".",
"_instrs",
"[",
"-",
"1",
"]",
".",
"address",
"+",
"self",
".",
"_instrs",
"[",
"-",
"1",
"]",
".",
"size",
... | 27.428571 | 0.010101 |
def start_vm(access_token, subscription_id, resource_group, vm_name):
'''Start a virtual machine.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
vm_name (str): Name of t... | [
"def",
"start_vm",
"(",
"access_token",
",",
"subscription_id",
",",
"resource_group",
",",
"vm_name",
")",
":",
"endpoint",
"=",
"''",
".",
"join",
"(",
"[",
"get_rm_endpoint",
"(",
")",
",",
"'/subscriptions/'",
",",
"subscription_id",
",",
"'/resourceGroups/'... | 38.35 | 0.001272 |
def setup_splittable_workflow(workflow, input_tables, out_dir=None, tags=None):
'''
This function aims to be the gateway for code that is responsible for taking
some input file containing some table, and splitting into multiple files
containing different parts of that table. For now the only supported o... | [
"def",
"setup_splittable_workflow",
"(",
"workflow",
",",
"input_tables",
",",
"out_dir",
"=",
"None",
",",
"tags",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"logging",
".",
"info",
"(",
"\"Entering split output files mod... | 39.804348 | 0.002132 |
def abort_copy_file(self, share_name, directory_name, file_name, copy_id, timeout=None):
'''
Aborts a pending copy_file operation, and leaves a destination file
with zero length and full metadata.
:param str share_name:
Name of destination share.
:param str direct... | [
"def",
"abort_copy_file",
"(",
"self",
",",
"share_name",
",",
"directory_name",
",",
"file_name",
",",
"copy_id",
",",
"timeout",
"=",
"None",
")",
":",
"_validate_not_none",
"(",
"'share_name'",
",",
"share_name",
")",
"_validate_not_none",
"(",
"'file_name'",
... | 36.647059 | 0.002346 |
def pool_stop(name, **kwargs):
'''
Stop a defined libvirt storage pool.
:param name: libvirt storage pool name
:param connection: libvirt connection URI, overriding defaults
:param username: username to connect with, overriding defaults
:param password: password to connect with, overriding defa... | [
"def",
"pool_stop",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"conn",
"=",
"__get_conn",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"pool",
"=",
"conn",
".",
"storagePoolLookupByName",
"(",
"name",
")",
"return",
"not",
"bool",
"(",
"pool",
".",... | 25.73913 | 0.001629 |
def hash_algo(self):
"""
:return:
A unicode string of "md2", "md5", "sha1", "sha224", "sha256",
"sha384", "sha512", "sha512_224", "sha512_256"
"""
algorithm = self['algorithm'].native
algo_map = {
'md2_rsa': 'md2',
'md5_rsa': 'md5... | [
"def",
"hash_algo",
"(",
"self",
")",
":",
"algorithm",
"=",
"self",
"[",
"'algorithm'",
"]",
".",
"native",
"algo_map",
"=",
"{",
"'md2_rsa'",
":",
"'md2'",
",",
"'md5_rsa'",
":",
"'md5'",
",",
"'sha1_rsa'",
":",
"'sha1'",
",",
"'sha224_rsa'",
":",
"'sh... | 28.763158 | 0.00177 |
def properties(self) -> dict:
"""
Returns the properties of the current node in the iteration.
"""
if isinstance(self._last_node, dict):
return self._last_node.keys()
else:
return {} | [
"def",
"properties",
"(",
"self",
")",
"->",
"dict",
":",
"if",
"isinstance",
"(",
"self",
".",
"_last_node",
",",
"dict",
")",
":",
"return",
"self",
".",
"_last_node",
".",
"keys",
"(",
")",
"else",
":",
"return",
"{",
"}"
] | 29.875 | 0.00813 |
def has_variation(self, move: chess.Move) -> bool:
"""Checks if the given *move* appears as a variation."""
return move in (variation.move for variation in self.variations) | [
"def",
"has_variation",
"(",
"self",
",",
"move",
":",
"chess",
".",
"Move",
")",
"->",
"bool",
":",
"return",
"move",
"in",
"(",
"variation",
".",
"move",
"for",
"variation",
"in",
"self",
".",
"variations",
")"
] | 62 | 0.010638 |
def native(self, value, context=None):
"""Convert a value from a foriegn type (i.e. web-safe) to Python-native."""
value = super().native(value, context)
if value is None: return
try:
return self.ingress(value)
except Exception as e:
raise Concern("Unable to transform incoming value: {0}", str(... | [
"def",
"native",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"value",
"=",
"super",
"(",
")",
".",
"native",
"(",
"value",
",",
"context",
")",
"if",
"value",
"is",
"None",
":",
"return",
"try",
":",
"return",
"self",
".",
"... | 28.454545 | 0.049536 |
def find_assign_to_builtin(node):
"""Finds assigning to built-ins"""
# The list of forbidden builtins is constant and not determined at
# runtime anyomre. The reason behind this change is that certain
# modules (like `gettext` for instance) would mess with the
# builtins module making this practice... | [
"def",
"find_assign_to_builtin",
"(",
"node",
")",
":",
"# The list of forbidden builtins is constant and not determined at",
"# runtime anyomre. The reason behind this change is that certain",
"# modules (like `gettext` for instance) would mess with the",
"# builtins module making this practice y... | 54.954545 | 0.000406 |
def _FilterOutPathInfoDuplicates(path_infos):
"""Filters out duplicates from passed PathInfo objects.
Args:
path_infos: An iterable with PathInfo objects.
Returns:
A list of PathInfo objects with duplicates removed. Duplicates are
removed following this logic: they're sorted by (ctime, mtime, atime,... | [
"def",
"_FilterOutPathInfoDuplicates",
"(",
"path_infos",
")",
":",
"pi_dict",
"=",
"{",
"}",
"for",
"pi",
"in",
"path_infos",
":",
"path_key",
"=",
"(",
"pi",
".",
"path_type",
",",
"pi",
".",
"GetPathID",
"(",
")",
")",
"pi_dict",
".",
"setdefault",
"(... | 27.709677 | 0.008999 |
def find_pix_borders(sp, sought_value):
"""Find useful region of a given spectrum
Detemine the useful region of a given spectrum by skipping
the initial (final) pixels with values equal to 'sought_value'.
Parameters
----------
sp : 1D numpy array
Input spectrum.
sought_value : int,... | [
"def",
"find_pix_borders",
"(",
"sp",
",",
"sought_value",
")",
":",
"if",
"sp",
".",
"ndim",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'Unexpected number of dimensions:'",
",",
"sp",
".",
"ndim",
")",
"naxis1",
"=",
"len",
"(",
"sp",
")",
"jborder_min"... | 28.045455 | 0.002349 |
def _determine_os_workload_status(
configs, required_interfaces, charm_func=None,
services=None, ports=None):
"""Determine the state of the workload status for the charm.
This function returns the new workload status for the charm based
on the state of the interfaces, the paused state and w... | [
"def",
"_determine_os_workload_status",
"(",
"configs",
",",
"required_interfaces",
",",
"charm_func",
"=",
"None",
",",
"services",
"=",
"None",
",",
"ports",
"=",
"None",
")",
":",
"state",
",",
"message",
"=",
"_ows_check_if_paused",
"(",
"services",
",",
"... | 40.693878 | 0.00049 |
def getSensorData(self, name, channel=None):
""" Returns a sensor node """
return self._getNodeData(name, self._SENSORNODE, channel) | [
"def",
"getSensorData",
"(",
"self",
",",
"name",
",",
"channel",
"=",
"None",
")",
":",
"return",
"self",
".",
"_getNodeData",
"(",
"name",
",",
"self",
".",
"_SENSORNODE",
",",
"channel",
")"
] | 48.666667 | 0.013514 |
def notify(self, *args, **kwargs):
'''Call all the callback handlers with given arguments.'''
for handler in tuple(self.handlers):
handler(*args, **kwargs) | [
"def",
"notify",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"handler",
"in",
"tuple",
"(",
"self",
".",
"handlers",
")",
":",
"handler",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 45 | 0.010929 |
def routeAnswer(self, originalSender, originalTarget, value, messageID):
"""
Route an incoming answer to a message originally sent by this queue.
"""
def txn():
qm = self._messageFromSender(originalSender, messageID)
if qm is None:
return
... | [
"def",
"routeAnswer",
"(",
"self",
",",
"originalSender",
",",
"originalTarget",
",",
"value",
",",
"messageID",
")",
":",
"def",
"txn",
"(",
")",
":",
"qm",
"=",
"self",
".",
"_messageFromSender",
"(",
"originalSender",
",",
"messageID",
")",
"if",
"qm",
... | 44.351351 | 0.002385 |
def ITS90_68_difference(T):
r'''Calculates the difference between ITS-90 and ITS-68 scales using a
series of models listed in [1]_, [2]_, and [3]_.
The temperature difference is given by the following equations:
From 13.8 K to 73.15 K:
.. math::
T_{90} - T_{68} = a_0 + \sum_{i=1}^{12} a_i... | [
"def",
"ITS90_68_difference",
"(",
"T",
")",
":",
"ais",
"=",
"[",
"-",
"0.005903",
",",
"0.008174",
",",
"-",
"0.061924",
",",
"-",
"0.193388",
",",
"1.490793",
",",
"1.252347",
",",
"-",
"9.835868",
",",
"1.411912",
",",
"25.277595",
",",
"-",
"19.18... | 36.783333 | 0.000441 |
def rotations(self, region):
"""
Returns champion rotations, including free-to-play and low-level free-to-play rotations.
:returns: ChampionInfo
"""
url, query = ChampionApiV3Urls.rotations(region=region)
return self._raw_request(self.rotations.__name__, region, url, que... | [
"def",
"rotations",
"(",
"self",
",",
"region",
")",
":",
"url",
",",
"query",
"=",
"ChampionApiV3Urls",
".",
"rotations",
"(",
"region",
"=",
"region",
")",
"return",
"self",
".",
"_raw_request",
"(",
"self",
".",
"rotations",
".",
"__name__",
",",
"reg... | 39.5 | 0.009288 |
def tran(inimage,outimage,direction='forward',x=None,y=None,
coords=None, coordfile=None,colnames=None,separator=None,
precision=6, output=None,verbose=True):
""" Primary interface to perform coordinate transformations in pixel
coordinates between 2 images using STWCS and full distortion mod... | [
"def",
"tran",
"(",
"inimage",
",",
"outimage",
",",
"direction",
"=",
"'forward'",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"coords",
"=",
"None",
",",
"coordfile",
"=",
"None",
",",
"colnames",
"=",
"None",
",",
"separator",
"=",
"None",
... | 34.931373 | 0.016103 |
def find(cls, *args, **kwargs):
"""
Find notifications.
Optional kwargs are:
since:
datetime instance
until:
datetime instance
If not specified, until will default to now(), and since will default
to 30 days prior to until... | [
"def",
"find",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"seconds",
"=",
"60",
"*",
"60",
"*",
"24",
"*",
"30",
"# seconds in 30 days",
"until",
"=",
"kwargs",
".",
"pop",
"(",
"'until'",
",",
"None",
")",
"since",
"=",
"kw... | 28.969697 | 0.002024 |
def defocus_blur(x, severity=1):
"""Defocus blurring to images.
Apply defocus blurring to images using Gaussian kernel.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,2... | [
"def",
"defocus_blur",
"(",
"x",
",",
"severity",
"=",
"1",
")",
":",
"c",
"=",
"[",
"(",
"3",
",",
"0.1",
")",
",",
"(",
"4",
",",
"0.5",
")",
",",
"(",
"6",
",",
"0.5",
")",
",",
"(",
"8",
",",
"0.5",
")",
",",
"(",
"10",
",",
"0.5",
... | 35.619048 | 0.014323 |
def route(self, path, routinemethod, container = None, host = None, vhost = None, method = [b'GET', b'HEAD']):
'''
Route specified path to a WSGI-styled routine factory
:param path: path to match, can be a regular expression
:param routinemethod: factory function routi... | [
"def",
"route",
"(",
"self",
",",
"path",
",",
"routinemethod",
",",
"container",
"=",
"None",
",",
"host",
"=",
"None",
",",
"vhost",
"=",
"None",
",",
"method",
"=",
"[",
"b'GET'",
",",
"b'HEAD'",
"]",
")",
":",
"self",
".",
"routeevent",
"(",
"p... | 46.789474 | 0.022051 |
def start_router(router_class, router_name):
"""Wrapper for starting a router and register it.
Args:
router_class: The router class to instantiate.
router_name: The name to give to the router.
Returns:
A handle to newly started router actor.
"""
handle = router_class.remote... | [
"def",
"start_router",
"(",
"router_class",
",",
"router_name",
")",
":",
"handle",
"=",
"router_class",
".",
"remote",
"(",
"router_name",
")",
"ray",
".",
"experimental",
".",
"register_actor",
"(",
"router_name",
",",
"handle",
")",
"handle",
".",
"start",
... | 30.071429 | 0.002304 |
def _compute_value(self, dest, kwargs, flag_val_strs):
"""Compute the value to use for an option.
The source of the default value is chosen according to the ranking in RankedValue.
"""
# Helper function to convert a string to a value of the option's type.
def to_value_type(val_str):
if val_st... | [
"def",
"_compute_value",
"(",
"self",
",",
"dest",
",",
"kwargs",
",",
"flag_val_strs",
")",
":",
"# Helper function to convert a string to a value of the option's type.",
"def",
"to_value_type",
"(",
"val_str",
")",
":",
"if",
"val_str",
"is",
"None",
":",
"return",
... | 47.907104 | 0.011621 |
def payload_class_for_element_name(element_name):
"""Return a payload class for given element name."""
logger.debug(" looking up payload class for element: {0!r}".format(
element_name))
logger.debug(" known: {0!r}".format(STANZA_PAYLOAD_CLASSE... | [
"def",
"payload_class_for_element_name",
"(",
"element_name",
")",
":",
"logger",
".",
"debug",
"(",
"\" looking up payload class for element: {0!r}\"",
".",
"format",
"(",
"element_name",
")",
")",
"logger",
".",
"debug",
"(",
"\" known: {0!r}\"",
".",
"format",
"("... | 50 | 0.002183 |
def ConsumeBool(self):
"""Consumes a boolean value.
Returns:
The bool parsed.
Raises:
ParseError: If a boolean value couldn't be consumed.
"""
try:
result = ParseBool(self.token)
except ValueError as e:
raise self._ParseError(str(e))
self.NextToken()
return resu... | [
"def",
"ConsumeBool",
"(",
"self",
")",
":",
"try",
":",
"result",
"=",
"ParseBool",
"(",
"self",
".",
"token",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"self",
".",
"_ParseError",
"(",
"str",
"(",
"e",
")",
")",
"self",
".",
"NextToken"... | 20.533333 | 0.009317 |
def handle(client, request):
"""
Handle format request
request struct:
{
'data': 'data_need_format',
'formaters': [
{
'name': 'formater_name',
'config': {} # None or dict
},
... # forma... | [
"def",
"handle",
"(",
"client",
",",
"request",
")",
":",
"formaters",
"=",
"request",
".",
"get",
"(",
"'formaters'",
",",
"None",
")",
"if",
"not",
"formaters",
":",
"formaters",
"=",
"[",
"{",
"'name'",
":",
"'autopep8'",
"}",
"]",
"logging",
".",
... | 31.577778 | 0.000683 |
def line_join_type(self):
"""Join type, one of `miter`, `round`, `bevel`."""
key = self._data.get(b'strokeStyleLineJoinType').enum
return self.STROKE_STYLE_LINE_JOIN_TYPES.get(key, str(key)) | [
"def",
"line_join_type",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"_data",
".",
"get",
"(",
"b'strokeStyleLineJoinType'",
")",
".",
"enum",
"return",
"self",
".",
"STROKE_STYLE_LINE_JOIN_TYPES",
".",
"get",
"(",
"key",
",",
"str",
"(",
"key",
")",
... | 52.75 | 0.009346 |
def _get_choices(self, gandi):
""" Internal method to get choices list """
kernel_families = list(gandi.kernel.list().values())
return [kernel for klist in kernel_families for kernel in klist] | [
"def",
"_get_choices",
"(",
"self",
",",
"gandi",
")",
":",
"kernel_families",
"=",
"list",
"(",
"gandi",
".",
"kernel",
".",
"list",
"(",
")",
".",
"values",
"(",
")",
")",
"return",
"[",
"kernel",
"for",
"klist",
"in",
"kernel_families",
"for",
"kern... | 53.25 | 0.009259 |
def _define_absl_flag(self, flag_instance, suppress):
"""Defines a flag from the flag_instance."""
flag_name = flag_instance.name
short_name = flag_instance.short_name
argument_names = ['--' + flag_name]
if short_name:
argument_names.insert(0, '-' + short_name)
if suppress:
helptext ... | [
"def",
"_define_absl_flag",
"(",
"self",
",",
"flag_instance",
",",
"suppress",
")",
":",
"flag_name",
"=",
"flag_instance",
".",
"name",
"short_name",
"=",
"flag_instance",
".",
"short_name",
"argument_names",
"=",
"[",
"'--'",
"+",
"flag_name",
"]",
"if",
"s... | 39.208333 | 0.009336 |
def addRating(self, rating=5.0):
"""Adds a rating to an item between 1.0 and 5.0"""
if rating > 5.0:
rating = 5.0
elif rating < 1.0:
rating = 1.0
url = "%s/addRating" % self.root
params = {
"f": "json",
"rating" : "%s" % rating
... | [
"def",
"addRating",
"(",
"self",
",",
"rating",
"=",
"5.0",
")",
":",
"if",
"rating",
">",
"5.0",
":",
"rating",
"=",
"5.0",
"elif",
"rating",
"<",
"1.0",
":",
"rating",
"=",
"1.0",
"url",
"=",
"\"%s/addRating\"",
"%",
"self",
".",
"root",
"params",
... | 35 | 0.012174 |
def _is_excluded(self, path, dir_only):
"""Check if file is excluded."""
return self.npatterns and self._match_excluded(path, self.npatterns) | [
"def",
"_is_excluded",
"(",
"self",
",",
"path",
",",
"dir_only",
")",
":",
"return",
"self",
".",
"npatterns",
"and",
"self",
".",
"_match_excluded",
"(",
"path",
",",
"self",
".",
"npatterns",
")"
] | 38.75 | 0.012658 |
def _connection_defaults(user=None, host=None, port=None, maintenance_db=None):
'''
Returns a tuple of (user, host, port, db) with config, pillar, or default
values assigned to missing values.
'''
if not user:
user = __salt__['config.option']('postgres.user')
if not host:
host = ... | [
"def",
"_connection_defaults",
"(",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
")",
":",
"if",
"not",
"user",
":",
"user",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'postgres.use... | 38.333333 | 0.001698 |
def respond(self):
"""Process the current request.
From :pep:`333`:
The start_response callable must not actually transmit
the response headers. Instead, it must store them for the
server or gateway to transmit only after the first
iteration of the appli... | [
"def",
"respond",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"req",
".",
"server",
".",
"wsgi_app",
"(",
"self",
".",
"env",
",",
"self",
".",
"start_response",
")",
"try",
":",
"for",
"chunk",
"in",
"filter",
"(",
"None",
",",
"response",
... | 40.913043 | 0.002077 |
def set_pixel_size(self, deltaPix):
"""
update pixel size
:param deltaPix:
:return:
"""
self._pixel_size = deltaPix
if self.psf_type == 'GAUSSIAN':
try:
del self._kernel_point_source
except:
pass | [
"def",
"set_pixel_size",
"(",
"self",
",",
"deltaPix",
")",
":",
"self",
".",
"_pixel_size",
"=",
"deltaPix",
"if",
"self",
".",
"psf_type",
"==",
"'GAUSSIAN'",
":",
"try",
":",
"del",
"self",
".",
"_kernel_point_source",
"except",
":",
"pass"
] | 22.769231 | 0.00974 |
def _generate_neuron_files_from_neuroml(network, verbose=False, dir_for_mod_files = None):
"""
Generate NEURON hoc/mod files from the NeuroML files which are marked as
included in the NeuroMLlite description; also compiles the mod files
"""
print_v("------------- Generating NEURON files from Neu... | [
"def",
"_generate_neuron_files_from_neuroml",
"(",
"network",
",",
"verbose",
"=",
"False",
",",
"dir_for_mod_files",
"=",
"None",
")",
":",
"print_v",
"(",
"\"------------- Generating NEURON files from NeuroML for %s (default dir: %s)...\"",
"%",
"(",
"network",
".",
"id... | 46.111111 | 0.012091 |
def store_announcement( working_dir, announcement_hash, announcement_text, force=False ):
"""
Store a new announcement locally, atomically.
"""
if not force:
# don't store unless we haven't seen it before
if announcement_hash in ANNOUNCEMENTS:
return
announce_filename = get_ann... | [
"def",
"store_announcement",
"(",
"working_dir",
",",
"announcement_hash",
",",
"announcement_text",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"force",
":",
"# don't store unless we haven't seen it before",
"if",
"announcement_hash",
"in",
"ANNOUNCEMENTS",
":",... | 30.666667 | 0.042119 |
def set_xml(self):
"""Set document xml just rendered already
validated against xsd to be signed.
:params boolean debug_mode: Either if you want
the rendered template to be saved either it
is valid or not with the given schema.
:returns boolean: Either was valid or no... | [
"def",
"set_xml",
"(",
"self",
")",
":",
"cached",
"=",
"StringIO",
"(",
")",
"document",
"=",
"u''",
"try",
":",
"document",
"=",
"self",
".",
"template",
".",
"render",
"(",
"inv",
"=",
"self",
")",
"except",
"UndefinedError",
"as",
"ups",
":",
"se... | 41.566667 | 0.001567 |
def non_null(t):
'''Generates non-null type (t!)
>>> class TypeWithNonNullFields(Type):
... a_int = non_null(int)
... a_float = non_null(Float)
... a_string = Field(non_null(String))
...
>>> TypeWithNonNullFields
type TypeWithNonNullFields {
aInt: Int!
aFloat: Fl... | [
"def",
"non_null",
"(",
"t",
")",
":",
"if",
"isinstance",
"(",
"t",
",",
"str",
")",
":",
"return",
"Lazy",
"(",
"t",
",",
"t",
"+",
"'!'",
",",
"non_null",
")",
"elif",
"isinstance",
"(",
"t",
",",
"Lazy",
")",
":",
"return",
"Lazy",
"(",
"t"... | 30.625 | 0.000439 |
def safe_mkdir_for_all(paths):
"""Make directories which would contain all of the passed paths.
This avoids attempting to re-make the same directories, which may be noticeably expensive if many
paths mostly fall in the same set of directories.
:param list of str paths: The paths for which containing directori... | [
"def",
"safe_mkdir_for_all",
"(",
"paths",
")",
":",
"created_dirs",
"=",
"set",
"(",
")",
"for",
"path",
"in",
"paths",
":",
"dir_to_make",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"if",
"dir_to_make",
"not",
"in",
"created_dirs",
":",
... | 37.428571 | 0.014898 |
def get_bilinear_residuals_stepp(input_params, xvals, yvals, slope1_fit):
'''
Returns the residual sum-of-squares value of a bilinear fit to a data
set - with a segment - 1 gradient fixed by an input value (slope_1_fit)
:param list input_params:
Input parameters for the bilinear model [slope2, ... | [
"def",
"get_bilinear_residuals_stepp",
"(",
"input_params",
",",
"xvals",
",",
"yvals",
",",
"slope1_fit",
")",
":",
"params",
"=",
"np",
".",
"hstack",
"(",
"[",
"slope1_fit",
",",
"input_params",
"]",
")",
"num_x",
"=",
"len",
"(",
"xvals",
")",
"y_model... | 35.571429 | 0.000978 |
def find_files(directory, pattern):
"""
Recusively finds files in a directory re
:param directory: base directory
:param pattern: wildcard pattern
:return: generator with filenames matching pattern
"""
for root, __, files in os.walk(directory):
for basename in files:
if f... | [
"def",
"find_files",
"(",
"directory",
",",
"pattern",
")",
":",
"for",
"root",
",",
"__",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory",
")",
":",
"for",
"basename",
"in",
"files",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"basename",
","... | 35.833333 | 0.002268 |
def install(self, tmp_container, font_tmpdir, css_content):
"""
Install extracted files and builded css
"""
# Write builded css file to its destination
with open(self.webfont_settings['csspart_path'], 'w') as css_file:
css_file.write(css_content)
# Clean prev... | [
"def",
"install",
"(",
"self",
",",
"tmp_container",
",",
"font_tmpdir",
",",
"css_content",
")",
":",
"# Write builded css file to its destination",
"with",
"open",
"(",
"self",
".",
"webfont_settings",
"[",
"'csspart_path'",
"]",
",",
"'w'",
")",
"as",
"css_file... | 44.172414 | 0.001528 |
def recordcomplement(a, b, buffersize=None, tempdir=None, cache=True,
strict=False):
"""
Find records in `a` that are not in `b`. E.g.::
>>> import petl as etl
>>> a = [['foo', 'bar', 'baz'],
... ['A', 1, True],
... ['C', 7, False],
... ... | [
"def",
"recordcomplement",
"(",
"a",
",",
"b",
",",
"buffersize",
"=",
"None",
",",
"tempdir",
"=",
"None",
",",
"cache",
"=",
"True",
",",
"strict",
"=",
"False",
")",
":",
"# TODO possible with only one pass?",
"ha",
"=",
"header",
"(",
"a",
")",
"hb",... | 31.962963 | 0.001124 |
def list_issues(context, id, sort, limit, where):
"""list_issues(context, id)
List all job attached issues.
>>> dcictl job-list-issue [OPTIONS]
:param string id: ID of the job to retrieve issues from [required]
:param string sort: Field to apply sort
:param integer limit: Max number of rows t... | [
"def",
"list_issues",
"(",
"context",
",",
"id",
",",
"sort",
",",
"limit",
",",
"where",
")",
":",
"result",
"=",
"job",
".",
"list_issues",
"(",
"context",
",",
"id",
"=",
"id",
",",
"sort",
"=",
"sort",
",",
"limit",
"=",
"limit",
",",
"where",
... | 36.058824 | 0.00159 |
def categorize(
data, col_name: str = None, new_col_name: str = None,
categories: dict = None, max_categories: float = 0.15
):
"""
:param data:
:param col_name:
:param new_col_name:
:param categories:
:param max_categories: max proportion threshold of categories
:return: new categori... | [
"def",
"categorize",
"(",
"data",
",",
"col_name",
":",
"str",
"=",
"None",
",",
"new_col_name",
":",
"str",
"=",
"None",
",",
"categories",
":",
"dict",
"=",
"None",
",",
"max_categories",
":",
"float",
"=",
"0.15",
")",
":",
"_categories",
"=",
"{",
... | 31.648148 | 0.000568 |
def get_function(rule, domain, normalize, **parameters):
"""
Create a quadrature function and set default parameter values.
Args:
rule (str):
Name of quadrature rule defined in ``QUAD_FUNCTIONS``.
domain (Dist, numpy.ndarray):
Defines ``lower`` and ``upper`` that is ... | [
"def",
"get_function",
"(",
"rule",
",",
"domain",
",",
"normalize",
",",
"*",
"*",
"parameters",
")",
":",
"from",
".",
".",
".",
"distributions",
".",
"baseclass",
"import",
"Dist",
"if",
"isinstance",
"(",
"domain",
",",
"Dist",
")",
":",
"lower",
"... | 37.616667 | 0.000432 |
def safe_list_set(plist, idx, fill_with, value):
"""
Sets:
```
plist[idx] = value
```
If len(plist) is smaller than what idx is trying
to dereferece, we first grow plist to get the needed
capacity and fill the new elements with fill_with
(or fill_with(), if it's a callable).
""... | [
"def",
"safe_list_set",
"(",
"plist",
",",
"idx",
",",
"fill_with",
",",
"value",
")",
":",
"try",
":",
"plist",
"[",
"idx",
"]",
"=",
"value",
"return",
"except",
"IndexError",
":",
"pass",
"# Fill in the missing positions. Handle negative indexes.",
"end",
"="... | 23.068966 | 0.001435 |
def _parseline(line):
"""
Parse a line of Java properties file.
:param line:
A string to parse, must not start with ' ', '#' or '!' (comment)
:return: A tuple of (key, value), both key and value may be None
>>> _parseline(" ")
(None, '')
>>> _parseline("aaa:")
('aaa', '')
>... | [
"def",
"_parseline",
"(",
"line",
")",
":",
"pair",
"=",
"re",
".",
"split",
"(",
"r\"(?:\\s+)?(?:(?<!\\\\)[=:])\"",
",",
"line",
".",
"strip",
"(",
")",
",",
"1",
")",
"key",
"=",
"pair",
"[",
"0",
"]",
".",
"rstrip",
"(",
")",
"if",
"len",
"(",
... | 28.310345 | 0.001178 |
def rect(self, x, y, width, height, color):
"""
See the Processing function rect():
https://processing.org/reference/rect_.html
"""
self.context.set_source_rgb(*color)
self.context.rectangle(self.tx(x), self.ty(y), self.tx(width), self.ty(height))
self.context.fil... | [
"def",
"rect",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"color",
")",
":",
"self",
".",
"context",
".",
"set_source_rgb",
"(",
"*",
"color",
")",
"self",
".",
"context",
".",
"rectangle",
"(",
"self",
".",
"tx",
"(",
"x"... | 39.5 | 0.009288 |
def ser_a_trous(C0, filter, scale):
"""
The following is a serial implementation of the a trous algorithm. Accepts the following parameters:
INPUTS:
filter (no default): The filter-bank which is applied to the components of the transform.
C0 (no default): The current array on whic... | [
"def",
"ser_a_trous",
"(",
"C0",
",",
"filter",
",",
"scale",
")",
":",
"tmp",
"=",
"filter",
"[",
"2",
"]",
"*",
"C0",
"tmp",
"[",
"(",
"2",
"**",
"(",
"scale",
"+",
"1",
")",
")",
":",
",",
":",
"]",
"+=",
"filter",
"[",
"0",
"]",
"*",
... | 38.292683 | 0.023602 |
def writer(fo,
schema,
records,
codec='null',
sync_interval=1000 * SYNC_SIZE,
metadata=None,
validator=None,
sync_marker=None):
"""Write records to fo (stream) according to schema
Parameters
----------
fo: file-like
Ou... | [
"def",
"writer",
"(",
"fo",
",",
"schema",
",",
"records",
",",
"codec",
"=",
"'null'",
",",
"sync_interval",
"=",
"1000",
"*",
"SYNC_SIZE",
",",
"metadata",
"=",
"None",
",",
"validator",
"=",
"None",
",",
"sync_marker",
"=",
"None",
")",
":",
"# Sani... | 32.956044 | 0.000324 |
def console_fill_char(con: tcod.console.Console, arr: Sequence[int]) -> None:
"""Fill the character tiles of a console with an array.
`arr` is an array of integers with a length of the consoles width and
height.
.. deprecated:: 8.4
You should assign to :any:`tcod.console.Console.ch` instead.
... | [
"def",
"console_fill_char",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"arr",
":",
"Sequence",
"[",
"int",
"]",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"arr",
",",
"np",
".",
"ndarray",
")",
":",
"# numpy arrays, use numpy's c... | 36.777778 | 0.001473 |
def lspcn(body, et, abcorr):
"""
Compute L_s, the planetocentric longitude of the sun, as seen
from a specified body.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lspcn_c.html
:param body: Name of central body.
:type body: str
:param et: Epoch in seconds past J2000 TDB.
:typ... | [
"def",
"lspcn",
"(",
"body",
",",
"et",
",",
"abcorr",
")",
":",
"body",
"=",
"stypes",
".",
"stringToCharP",
"(",
"body",
")",
"et",
"=",
"ctypes",
".",
"c_double",
"(",
"et",
")",
"abcorr",
"=",
"stypes",
".",
"stringToCharP",
"(",
"abcorr",
")",
... | 30.3 | 0.0016 |
def create_customer(cls, customer, **kwargs):
"""Create Customer
Create a new Customer
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_customer(customer, async=True)
>>> result ... | [
"def",
"create_customer",
"(",
"cls",
",",
"customer",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_create_customer_with_http_inf... | 39.47619 | 0.002356 |
def new_worker(self, name: str):
"""Creates a new Worker and start a new Thread with it. Returns the Worker."""
if not self.running:
return self.immediate_worker
worker = self._new_worker(name)
self._start_worker(worker)
return worker | [
"def",
"new_worker",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"if",
"not",
"self",
".",
"running",
":",
"return",
"self",
".",
"immediate_worker",
"worker",
"=",
"self",
".",
"_new_worker",
"(",
"name",
")",
"self",
".",
"_start_worker",
"(",
"w... | 40 | 0.01049 |
def interp1d(x,Z,xout,spline=False,kind='linear',fill_value=np.NaN,**kwargs):
"""
INTERP1D : Interpolate values from a 1D vector at given positions
@param x: 1st dimension vector of size NX
@author: Renaud DUSSURGET, LER/PAC, Ifremer La Seyne
"""
linear = not spline
... | [
"def",
"interp1d",
"(",
"x",
",",
"Z",
",",
"xout",
",",
"spline",
"=",
"False",
",",
"kind",
"=",
"'linear'",
",",
"fill_value",
"=",
"np",
".",
"NaN",
",",
"*",
"*",
"kwargs",
")",
":",
"linear",
"=",
"not",
"spline",
"nx",
"=",
"len",
"(",
"... | 28.62963 | 0.045056 |
def extraction(self, event_collection, timeframe=None, timezone=None, filters=None, latest=None,
email=None, property_names=None):
""" Performs a data extraction
Returns either a JSON object of events or a response
indicating an email will be sent to you with data.
... | [
"def",
"extraction",
"(",
"self",
",",
"event_collection",
",",
"timeframe",
"=",
"None",
",",
"timezone",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"latest",
"=",
"None",
",",
"email",
"=",
"None",
",",
"property_names",
"=",
"None",
")",
":",
"p... | 60.681818 | 0.008112 |
async def run(websession: ClientSession):
"""Run."""
try:
# Create a client:
client = Client(
'<API_KEY>',
39.7974509,
-104.8887227,
websession,
altitude=1609.3)
# Get current UV info:
print('CURRENT UV DATA:')
... | [
"async",
"def",
"run",
"(",
"websession",
":",
"ClientSession",
")",
":",
"try",
":",
"# Create a client:",
"client",
"=",
"Client",
"(",
"'<API_KEY>'",
",",
"39.7974509",
",",
"-",
"104.8887227",
",",
"websession",
",",
"altitude",
"=",
"1609.3",
")",
"# Ge... | 24.923077 | 0.001486 |
def build_markdown_table(headers, rows, row_keys=None):
"""Build a lined up markdown table.
Args:
headers (dict): A key -> value pairing fo the headers.
rows (list): List of dictionaries that contain all the keys listed in
the headers.
row_keys (list): A sorted list of keys to d... | [
"def",
"build_markdown_table",
"(",
"headers",
",",
"rows",
",",
"row_keys",
"=",
"None",
")",
":",
"row_maxes",
"=",
"_find_row_maxes",
"(",
"headers",
",",
"rows",
")",
"row_keys",
"=",
"row_keys",
"or",
"[",
"key",
"for",
"key",
",",
"value",
"in",
"h... | 32.590909 | 0.001355 |
def _input_as_lines(self, data):
"""Writes data to tempfile and sets -i parameter
data -- list of lines, ready to be written to file
"""
if data:
self.Parameters['-i']\
.on(super(CD_HIT,self)._input_as_lines(data))
return '' | [
"def",
"_input_as_lines",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
":",
"self",
".",
"Parameters",
"[",
"'-i'",
"]",
".",
"on",
"(",
"super",
"(",
"CD_HIT",
",",
"self",
")",
".",
"_input_as_lines",
"(",
"data",
")",
")",
"return",
"''"
] | 32.111111 | 0.010101 |
def db_list(**connection_args):
'''
Return a list of databases of a MySQL server using the output
from the ``SHOW DATABASES`` query.
CLI Example:
.. code-block:: bash
salt '*' mysql.db_list
'''
dbc = _connect(**connection_args)
if dbc is None:
return []
cur = dbc.c... | [
"def",
"db_list",
"(",
"*",
"*",
"connection_args",
")",
":",
"dbc",
"=",
"_connect",
"(",
"*",
"*",
"connection_args",
")",
"if",
"dbc",
"is",
"None",
":",
"return",
"[",
"]",
"cur",
"=",
"dbc",
".",
"cursor",
"(",
")",
"qry",
"=",
"'SHOW DATABASES'... | 21.612903 | 0.001429 |
def match_note_offsets(ref_intervals, est_intervals, offset_ratio=0.2,
offset_min_tolerance=0.05, strict=False):
"""Compute a maximum matching between reference and estimated notes,
only taking note offsets into account.
Given two note sequences represented by ``ref_intervals`` and
... | [
"def",
"match_note_offsets",
"(",
"ref_intervals",
",",
"est_intervals",
",",
"offset_ratio",
"=",
"0.2",
",",
"offset_min_tolerance",
"=",
"0.05",
",",
"strict",
"=",
"False",
")",
":",
"# set the comparison function",
"if",
"strict",
":",
"cmp_func",
"=",
"np",
... | 43.609195 | 0.000258 |
def apply_reserve_resource_constraint(machine, constraint):
"""Apply the changes implied by a reserve resource constraint to a
machine model."""
if constraint.location is None:
# Compensate for globally reserved resources
machine.chip_resources \
= resources_after_reservation(
... | [
"def",
"apply_reserve_resource_constraint",
"(",
"machine",
",",
"constraint",
")",
":",
"if",
"constraint",
".",
"location",
"is",
"None",
":",
"# Compensate for globally reserved resources",
"machine",
".",
"chip_resources",
"=",
"resources_after_reservation",
"(",
"mac... | 48.423077 | 0.000779 |
def plot_time_series(sdat, lovs):
"""Plot requested time series.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
lovs (nested list of str): nested list of series names such as
the one produced by :func:`stagpy.misc.list_of_vars`.
Other Parameters:
... | [
"def",
"plot_time_series",
"(",
"sdat",
",",
"lovs",
")",
":",
"sovs",
"=",
"misc",
".",
"set_of_vars",
"(",
"lovs",
")",
"tseries",
"=",
"{",
"}",
"times",
"=",
"{",
"}",
"metas",
"=",
"{",
"}",
"for",
"tvar",
"in",
"sovs",
":",
"series",
",",
"... | 31.777778 | 0.001131 |
def copy(self):
"""
Make a copy. This means, we delete all observers and return a copy of this
array. It will still be an ObsAr!
"""
from .lists_and_dicts import ObserverList
memo = {}
memo[id(self)] = self
memo[id(self.observers)] = ObserverList()
... | [
"def",
"copy",
"(",
"self",
")",
":",
"from",
".",
"lists_and_dicts",
"import",
"ObserverList",
"memo",
"=",
"{",
"}",
"memo",
"[",
"id",
"(",
"self",
")",
"]",
"=",
"self",
"memo",
"[",
"id",
"(",
"self",
".",
"observers",
")",
"]",
"=",
"Observer... | 34.2 | 0.008547 |
def origination_urls(self):
"""
Access the origination_urls
:returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList
:rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlList
"""
if self._origination_urls is None:
self._origin... | [
"def",
"origination_urls",
"(",
"self",
")",
":",
"if",
"self",
".",
"_origination_urls",
"is",
"None",
":",
"self",
".",
"_origination_urls",
"=",
"OriginationUrlList",
"(",
"self",
".",
"_version",
",",
"trunk_sid",
"=",
"self",
".",
"_solution",
"[",
"'si... | 43 | 0.01139 |
def upload_process_reach_files(output_dir, pmid_info_dict, reader_version,
num_cores):
# At this point, we have a directory full of JSON files
# Collect all the prefixes into a set, then iterate over the prefixes
# Collect prefixes
json_files = glob.glob(os.path.join(outp... | [
"def",
"upload_process_reach_files",
"(",
"output_dir",
",",
"pmid_info_dict",
",",
"reader_version",
",",
"num_cores",
")",
":",
"# At this point, we have a directory full of JSON files",
"# Collect all the prefixes into a set, then iterate over the prefixes",
"# Collect prefixes",
"j... | 39.86 | 0.00049 |
def _assert_same_base_type(items, expected_type=None):
r"""Asserts all items are of the same base type.
Args:
items: List of graph items (e.g., `Variable`, `Tensor`, `SparseTensor`,
`Operation`, or `IndexedSlices`). Can include `None` elements, which
will be ignored.
expected_type: Expected... | [
"def",
"_assert_same_base_type",
"(",
"items",
",",
"expected_type",
"=",
"None",
")",
":",
"original_expected_type",
"=",
"expected_type",
"mismatch",
"=",
"False",
"for",
"item",
"in",
"items",
":",
"if",
"item",
"is",
"not",
"None",
":",
"item_type",
"=",
... | 34.77551 | 0.008562 |
def attr_set(args):
''' Set key=value attributes: if entity name & type are specified then
attributes will be set upon that entity, otherwise the attribute will
be set at the workspace level'''
if args.entity_type and args.entity:
prompt = "Set {0}={1} for {2}:{3} in {4}/{5}?\n[Y\\n]: ".format(... | [
"def",
"attr_set",
"(",
"args",
")",
":",
"if",
"args",
".",
"entity_type",
"and",
"args",
".",
"entity",
":",
"prompt",
"=",
"\"Set {0}={1} for {2}:{3} in {4}/{5}?\\n[Y\\\\n]: \"",
".",
"format",
"(",
"args",
".",
"attribute",
",",
"args",
".",
"value",
",",
... | 42.4 | 0.002306 |
def get(self, *args, **kwargs):
#: Render view for get request, view is cached for websocket
""" Execute the correct handler depending on what is connecting. """
if self.is_websocket():
return super(DemoHandler, self).get(*args, **kwargs)
else:
#return tornado.web... | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#: Render view for get request, view is cached for websocket",
"if",
"self",
".",
"is_websocket",
"(",
")",
":",
"return",
"super",
"(",
"DemoHandler",
",",
"self",
")",
".",
"g... | 49.75 | 0.009877 |
def simxUnpackInts(intsPackedInString):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
b=[]
for i in range(int(len(intsPackedInString)/4)):
b.append(struct.unpack('<i',intsPackedInString[4*i:4*(i+1)])[0])
return b | [
"def",
"simxUnpackInts",
"(",
"intsPackedInString",
")",
":",
"b",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"int",
"(",
"len",
"(",
"intsPackedInString",
")",
"/",
"4",
")",
")",
":",
"b",
".",
"append",
"(",
"struct",
".",
"unpack",
"(",
"'<... | 35.625 | 0.013699 |
def reset(self):
""" Reseting duration for throttling """
if self._call_later_handler is not None:
self._call_later_handler.cancel()
self._call_later_handler = None
self._wait_done_cb() | [
"def",
"reset",
"(",
"self",
")",
":",
"if",
"self",
".",
"_call_later_handler",
"is",
"not",
"None",
":",
"self",
".",
"_call_later_handler",
".",
"cancel",
"(",
")",
"self",
".",
"_call_later_handler",
"=",
"None",
"self",
".",
"_wait_done_cb",
"(",
")"
... | 38.666667 | 0.008439 |
def check_stoplimit_prices(price, label):
"""
Check to make sure the stop/limit prices are reasonable and raise
a BadOrderParameters exception if not.
"""
try:
if not isfinite(price):
raise BadOrderParameters(
msg="Attempted to place an order with a {} price "
... | [
"def",
"check_stoplimit_prices",
"(",
"price",
",",
"label",
")",
":",
"try",
":",
"if",
"not",
"isfinite",
"(",
"price",
")",
":",
"raise",
"BadOrderParameters",
"(",
"msg",
"=",
"\"Attempted to place an order with a {} price \"",
"\"of {}.\"",
".",
"format",
"("... | 32.636364 | 0.001353 |
def from_pickle(cls, filename):
"""Loads and Returns a Camera from a pickle file, given a filename."""
with open(filename, 'rb') as f:
cam = pickle.load(f)
projection = cam.projection.copy()
return cls(projection=projection, position=cam.position.xyz, rotation=cam.rotation._... | [
"def",
"from_pickle",
"(",
"cls",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"cam",
"=",
"pickle",
".",
"load",
"(",
"f",
")",
"projection",
"=",
"cam",
".",
"projection",
".",
"copy",
"(",
")",
... | 48.714286 | 0.008646 |
def create(cls, bucket, key, size, chunk_size):
"""Create a new object in a bucket."""
bucket = as_bucket(bucket)
if bucket.locked:
raise BucketLockedError()
# Validate chunk size.
if not cls.is_valid_chunksize(chunk_size):
raise MultipartInvalidChunkSiz... | [
"def",
"create",
"(",
"cls",
",",
"bucket",
",",
"key",
",",
"size",
",",
"chunk_size",
")",
":",
"bucket",
"=",
"as_bucket",
"(",
"bucket",
")",
"if",
"bucket",
".",
"locked",
":",
"raise",
"BucketLockedError",
"(",
")",
"# Validate chunk size.",
"if",
... | 32.119048 | 0.001439 |
def get_country(self):
"""
:return: Country or None
"""
response = self._session.fetch("users.get", user_ids=self.id, fields="country")[0]
if response.get('country'):
return Country.from_json(self._session, response.get('country')) | [
"def",
"get_country",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_session",
".",
"fetch",
"(",
"\"users.get\"",
",",
"user_ids",
"=",
"self",
".",
"id",
",",
"fields",
"=",
"\"country\"",
")",
"[",
"0",
"]",
"if",
"response",
".",
"get",
"... | 39.571429 | 0.010601 |
def route(self):
"""Used to select the L2 address"""
dst = self.dst
if isinstance(dst, Gen):
dst = next(iter(dst))
return conf.route6.route(dst) | [
"def",
"route",
"(",
"self",
")",
":",
"dst",
"=",
"self",
".",
"dst",
"if",
"isinstance",
"(",
"dst",
",",
"Gen",
")",
":",
"dst",
"=",
"next",
"(",
"iter",
"(",
"dst",
")",
")",
"return",
"conf",
".",
"route6",
".",
"route",
"(",
"dst",
")"
] | 30.5 | 0.010638 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.