content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Dict
from typing import Any
from typing import List
def dereference_json_pointer(root: n.SerializableType, ptr: str) -> Dict[str, Any]:
"""Given a dictionary or list, return the element referred to by the
given JSON pointer (RFC-6901)."""
cursor = root
components = ptr.lstrip("#"... | 529f77e5bdfb49d9914a7610e48bc23171e303d0 | 3,622,500 |
def port_exponential_moving_average(asset_indicator, close_arr, n):
"""Calculate the exponential weighted moving average for the given data.
:param close_arr: close price of the bar, expect series from cudf
:param n: time steps
:return: expoential weighted moving average in cu.Series
"""
EMA = ... | 8f4ae8a45312a7bf2c9cd1c5fc394ddf6247c131 | 3,622,501 |
import typing
import logging
def crop_to(arr: np.ndarray, target_shape: typing.Tuple[int]) -> np.ndarray:
"""
Center-crops an array to a desired shape. If the difference in shapes is not even the offset of the resulting array
will be rounded down, i.e. the removed area "in front" will be smaller than the ... | 77155fa571517ee59441a0714836076eb5d8f6af | 3,622,502 |
from typing import Set
from typing import Mapping
from typing import Sequence
def expand_related_tasks(tasks: Set[str],
expand_map: Mapping[str, Sequence[str]]) -> Set[str]:
"""The inverse of `collapse_related_tasks`.
Args:
tasks: a list of tasks to expand.
expand_map: map from a... | 16abd2160dc972e89ade3e5cb2b40e8451a932a7 | 3,622,503 |
import sympy
def antal_h_coefficient(index, game_matrix):
"""
Returns the H_index coefficient, according to Antal et al. (2009), as given by equation 2.
H_k = \frac{1}{n^2} \sum_{i=1}^{n} \sum_{j=1}^{n} (a_{kj}-a_{jj})
Parameters
----------
index: int
game_matrix: sympy.Matrix
Ret... | 0e05a6a622ef24ff63b18b9c8b80348b860a16c3 | 3,622,504 |
import logging
def setup_logging(
logger_or_name=None,
logfile=None,
log_to_console=True,
level=logging.INFO
):
"""
Sets up a logger for logging
Args:
logger_or_name: Either a logging.Logger object or a string
used to reference the logger name. If None, root logger is a... | 6c2443ca113c6264ce19bd4a9752684053a99cd5 | 3,622,505 |
import hashlib
def getcertpubhash(certobj):
"""
Method 1: Hash from public key
:param certobj:
:return:
"""
if certobj:
pubkey = certobj.get_pubkey().as_der()
pubkeyhash = hashlib.sha256(pubkey).hexdigest()
return pubkeyhash
else:
return None | 3002a8ddba6522acf7de0c1cfa225e68a1e3f141 | 3,622,506 |
def greedy_value_per_weight_unit(I: list, w: list, v: list, K: int) -> tuple:
"""
Solve knapsack problem with value per weight unit greedness.
Takes most beneficial first.
Parameters:
-----------
- I : items
- w : items' weights
- v : items' value
- K... | fd81de5f066d6918f17effdc0b6c72659fb19391 | 3,622,507 |
def _wrap_output_like_matching_units(result, match):
"""Convert result to be like match with matching units for output wrapper."""
output_xarray = isinstance(match, xr.DataArray)
match_units = str(match.metpy.units if output_xarray else getattr(match, 'units', ''))
if isinstance(result, xr.DataArray):
... | f902539a216f9c28e42471aacd29fc84d4d45228 | 3,622,508 |
import json
def get_mnest_results(root_name, parameters):
"""
Parameters
----------
root_name : str
The directory and base name of the MultiNest output.
parameters : list or array
A list of strings with the parameter names to be displayed.
There should be one name for each... | e133b8ad2120fa7940441e89d80fc30c2d7f5e33 | 3,622,509 |
from typing import List
import random
def _get_list_of_test_resources() -> List[Resource]:
"""The subset of all Resources that can be tested
Returns:
List[Resource] -- A list of TesTItems
"""
resources = [
resource
for resource in database.RESOURCES
if database.resourc... | fe40bbc2f8ccec9a57cbbcee7a327608714b32e5 | 3,622,510 |
from datetime import datetime
import sys
def set_globals(options_file=None, args=None):
"""
Parses the options in the file specified in the command-line
if no options file is passed.
Args:
options_file (str): an optional file name of an options file
"""
def valid_date(s):
"""... | ea0005ddc468338c57baf4ed79ef67d8ac477ed0 | 3,622,511 |
from typing import Union
from typing import List
from typing import Optional
def convert_units(
data: Union[tb.BeliefsSeries, pd.Series, List[Union[int, float]], int, float],
from_unit: str,
to_unit: str,
event_resolution: Optional[timedelta] = None,
capacity: Optional[str] = None,
) -> Union[pd.S... | f3a0cb87599c1f86c7995052fb3b42e16c96459b | 3,622,512 |
from datetime import datetime
def add_delta_to_time(timestamp, delta):
"""Utility to add a datetime.timedelta object to a datetime.time one"""
return (
datetime.datetime.combine(datetime.date(2012, 1, 1), timestamp)
+ datetime.timedelta(seconds=delta)
).time() | 9971f103afd2c439b36e29db1b167fed80fb66a3 | 3,622,513 |
def raDecFromAltAz(alt, az, obs, includeRefraction=True):
"""
Convert altitude and azimuth to RA and Dec
@param [in] alt is the altitude in degrees. Can be a numpy array or a single value.
@param [in] az is the azimuth in degrees. Cant be a numpy array or a single value.
@param [in] obs is an O... | 69567a3ec34f068d56aa48edf0e24e2f5f766acf | 3,622,514 |
def _is_convertible_to_tensor(value):
"""Returns true if `value` is convertible to a `Tensor`."""
if value is None:
return True
if isinstance(value,
(ops.Tensor, variables.Variable, np.ndarray, int, float, str)):
return True
elif isinstance(value, (sparse_tensor.SparseTensor,)):
retu... | 5500eb345cedccffad9c5c58c6499d00f8caa5f2 | 3,622,515 |
def add_ball(space, position):
"""Ajoute une balle dans l'espace à une position donnée"""
mass = 1
radius = 14
moment = pymunk.moment_for_circle(mass, 0, radius)
body = pymunk.Body(mass, moment)
body.position = position
shape = pymunk.Circle(body, radius)
space.add(body, shape)
retur... | cef5333d8a8bcad337fbe0d0a2c03233fa36ced4 | 3,622,516 |
def add_to_cart_view(request, **kwargs):
"""Add a product to the cart"""
validator = ValidateCart(data=request.data)
validator.is_valid(raise_exception=True)
session_id, queryset = validator.save(request)
return simple_api_response(build_cart_response(queryset, session_id)) | 8f79798063df912c300fcf1b9154cb3250baafd3 | 3,622,517 |
from typing import List
from typing import Dict
def _cx_to_dict(list_of_dicts: List[Dict], key_tag: str = "k", value_tag: str = "v") -> Dict:
"""Convert a CX list of dictionaries to a flat dictionary."""
return {d[key_tag]: d[value_tag] for d in list_of_dicts} | ea80e9a50ea04536c2ed068d19220b56a9bdf3ed | 3,622,518 |
from typing import Tuple
from typing import Any
import pathlib
import logging
import os
def load_memmap(filename: str, mode: str = 'r') -> Tuple[Any, Tuple, int]:
""" Load a memory mapped file created by the function save_memmap
Args:
filename: str
path of the file to be loaded
mod... | 0fc2d643efbd51e03c9c8ecb61c6aea6fb30437f | 3,622,519 |
def im_list_to_blob(ims):
"""Convert a list of images into a network input."""
max_shape = np.array([im.shape for im in ims]).max(axis=0)
num_images = len(ims)
blob = np.zeros((num_images, max_shape[0], max_shape[1], max_shape[2]),
dtype=ims[0].dtype)
for i in xrange(num_ima... | 705d27e0fe7cde9fda50baf7a4a733fb7c0baa22 | 3,622,520 |
def get_bitmasks(enumid):
""" Return list of bitmasks used in enum. """
bmasks = []
bid = idc.get_first_bmask(enumid)
while bid != idaapi.BADADDR:
bmasks.append(bid)
bid = idc.get_next_bmask(enumid, bid)
return bmasks | dcd9ad692274bf6eced0270830222acb73e025d5 | 3,622,521 |
def get_discrete_physical_eigenvalues_and_amplitudes(lamdas, amps, re_lower):
"""Find and print only physical eigenvalues.
Eigenvalue :math:`\lambda` is called nonnegative here
if :math:`\Re \lambda >=` -`re_lower` and :math:`\Im \lambda >= 0`.
Parameters
----------
lamdas : ndarray
Ar... | b0f04f22a2ff6214448ab5a132fa6efdbbd17a5b | 3,622,522 |
from rstoolbox.components import DesignFrame, DesignSeries
import operator
def label_sequence( df, seqID, label, complete=False ):
"""Gets the sequence of a ``label``.
Depends on label data for the ``seqID``.
Adds a new column to the data container:
=========================== ====================... | db3cb7fe7e1735b62c7c620368f32c93dde1e33a | 3,622,523 |
import random
from datetime import datetime
def MSF_config(BIM):
"""
Rules to identify a HAZUS MSF configuration based on BIM data
Parameters
----------
BIM: dictionary
Information about the building characteristics.
Returns
-------
config: str
A string that identifie... | 6dc3d529bf478091ded0ac9c83f4003b36d18b50 | 3,622,524 |
def get_bond(mol, bond_idx):
"""
Get oebond object
Parameters
----------
mol : oemol
Molecule to extract bond from
bond_idx : tuple of ints
tuple of map indices of atoms in bond
Returns
-------
bond: oebond
"""
atoms = [mol.GetAtom(oechem.OEHasMapIdx(i)) for... | 9f89921ebe14bf8ecf9c183f90393b00ffcf1054 | 3,622,525 |
import typing
import pathlib
import itertools
def find_pyfiles() -> typing.Iterator[pathlib.Path]:
"""Return an iterator of the files to format."""
return itertools.chain(
pathlib.Path("../gdbmongo").rglob("*.py"),
pathlib.Path("../gdbmongo").rglob("*.pyi"),
pathlib.Path("../stubs").rg... | 74b0c11771799fba6090569595d24e70ec68899d | 3,622,526 |
def compare_angle(attr_a, attr_b=0, operation=0):
"""Create math_CompareAngle-node to get boolean of logical comparison between given attrs.
Args:
attr_a (NcNode or NcAttrs or string): Maya node attribute.
attr_b (NcNode or NcAttrs or float): Maya node attribute.
operation (NcNode or Nc... | b92777ed952c790af8fd8433d8cd367b1a959cc0 | 3,622,527 |
def _power_off(ssh_obj, driver_info):
"""Power OFF this node.
:param ssh_obj: paramiko.SSHClient, an active ssh connection.
:param driver_info: information for accessing the node.
:returns: one of ironic.common.states POWER_OFF or ERROR.
"""
current_pstate = _get_power_status(ssh_obj, driver_i... | 02f12753c43bdba2849dc7199e98f0e59419a2e1 | 3,622,528 |
def train_valid_test_generator():
"""Loading mnist dataset from tensorflow.keras and scaling the pixels between 0 to 1
Args:
NA
Returns:
nd array: Train, Test and Validation datasets
"""
mnist = tf.keras.datasets.mnist
(x_train_full, y_train_full), (x_test,y_test)= mnist.load_dat... | 8bb1f7c12d35d06a10d4a6dccdc0a0ec50a0df77 | 3,622,529 |
import argparse
def main() -> None:
""" The entry point """
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--create", metavar = "FOLDER", help = "Create the index", type=str)
arg_parser.add_argument("--search", metavar = "TERM", help = "Search a term")
args = arg_parser.parse_ar... | 0129d4744e58a0ac799d12e96bb860c1a9cc5fcd | 3,622,530 |
def merge_args(args, cloud_args):
"""merge_args"""
args_dict = vars(args)
if isinstance(cloud_args, dict):
for key in cloud_args.keys():
val = cloud_args[key]
if key in args_dict and val:
arg_type = type(args_dict[key])
if arg_type is not type(... | 06f84376e23535e9d291eb9bc9514fa27582faa2 | 3,622,531 |
import os
def java_path():
"""
get the java path using JAVA_HOME if set
"""
if os.environ.get('JAVA_HOME') == None:
return "java"
else:
return os.path.join(os.environ.get('JAVA_HOME'), "bin", "java") | 5b4a3fc2b906b963f34cfb87e499f4d059750b48 | 3,622,532 |
def has_permission(obj, actor, codename, roles=None):
"""Checks whether the passed actor has passed permission for passed object.
**Parameters:**
obj
The object for which the permission should be checked.
codename
The permission's codename which should be checked.
request
... | 2f5d71ce73efb4c38874d1d12a453dc7cda9ad00 | 3,622,533 |
import os
def create_df_with_errors(all_dfs):
"""
used in run_bias_experiments.py, only for mt5.
all_dfs : a list of paths to .csvs for various seeds
returns a final dataframe that includes statistical significance
"""
size = str(all_dfs[0])[28:34].strip('_')
lang = str(all_dfs[0])[34:37].... | a751892a9655cdc7377e330e00bd5e7c930ee9cc | 3,622,534 |
def OD2RGB(OD):
"""Convert optical density back to RGB"""
return 255 * np.exp(-OD) | 7f0d395e8ebdd83376798507210ab8381a4c6380 | 3,622,535 |
def get_caqi_no2_1h(no2_max_1h: float) -> float:
"""
Calculates NO2 (max in 1h) CAQI Europe
:param no2_max_1h: NO2 (max in 1h), ppm
:return: NO2 CAQI Europe
"""
cp = __round_down(no2_max_1h * 1000)
return __get_aqi_general_formula(cp, EU_NO2_1H, EU_CAQI) | 29e83ee8627905df6f592c120514d35b7b1b732c | 3,622,536 |
def visibility_define(config):
"""Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
string)."""
hide = '__attribute__((visibility("hidden")))'
if config.check_gcc_function_attribute(hide, 'hideme'):
return hide
else:
return '' | b08e8515440c4bf1ebec51c4100e55fe9f14b17d | 3,622,537 |
def get_best_path(digraph, start, end, path, max_buildings, best_dist,
best_path):
"""
Finds the shortest path between buildings subject to constraints.
Parameters:
digraph: instance of Digraph or one of its subclasses
The graph on which to carry out the search
... | d0e06d81abafa013fdbb1422e6f88298039a5a01 | 3,622,538 |
import os
import pathlib
def get_callbacks(data_path, sess_id, config, bot_config_file):
"""
Get a list of callbacks to use for training.
"""
# Get config values
mode = config['mode']
tb_logdir = config['tb_logdir']
save_best_only = config['save_best_only']
use_earlystopping = config[... | e78296afc122adb599e65eb9e5c65fde8ed6580d | 3,622,539 |
def calculate_num_points_in_solution(solution):
"""Calculates the number of data points in the given solution."""
return sum(len(points) for points in solution.values()) | c75f7cb7d9c8c2731e4698040954c559b6b5d4ec | 3,622,540 |
from typing import List
def _create_dataset(
mesh: salvus.mesh.unstructured_mesh.UnstructuredMesh,
mask: np.ndarray,
parameters: List[str],
coords: str,
):
"""
Create an xarray dataset with relevant information from mesh
:param mesh: Salvus UnstructuredMesh object
:type mesh: salvus.m... | 60c17af1a190e210eabd561a604c5abe2b8fca5d | 3,622,541 |
def binarize_labels(labels):
"""
Change the labels to binary
:param labels: np array of digit labels
:return:
"""
labels = np.where(labels == 0, labels, 1)
return labels | e5e1d63898e1f682fdacf90e7540872a1f4c03cf | 3,622,542 |
def match_datasets(base_dataset, dataset_tomatch):
"""" Match two datasets defined on different grid.
Given a base dataset and a dataset to be matched, find for each point in
the dataset to mathc the closest cell in the base dataset and return its
index.
Parameters
----------
base_dataset:... | 3f7edf0e47dc4018e58f041e2a3ea610b41cb0b7 | 3,622,543 |
from typing import Tuple
from typing import Dict
import traceback
def rest_invalid_arguments_error_handler(exception: Exception) -> Tuple[Dict, int]:
"""Handle invalid arguments errors.
:param exception: Python Exception
:return: tuple with response and status code
"""
logger.warning(traceback.fo... | f32d6a686e2db2aae279aaca7ac9cb3c52a67f81 | 3,622,544 |
def _capabilities_semantic_checks(caps_dict):
""" Early check of capabilities """
# Get supported capabilities
valid_data = {}
for key in caps_dict:
if key in CAPABILITIES['backend']:
valid_data[key] = caps_dict[key]
continue
for svc in constants.SB_CEPH_SVCS_SUP... | 95584c7f06f91ab0d2fc0c72d011873790c374db | 3,622,545 |
import torch
def generate_spirals(n_samples=100, noise=1e-4, **kwargs):
"""Creates a *spirals* dataset of `n_samples` data points.
:param n_samples: number of data points in the generated dataset
:type n_samples: int
:param noise: standard deviation of noise magnitude added to each data point
:ty... | e1a6ffd7c3c0532bf9f443b9b64b6447b4ebfae6 | 3,622,546 |
def register_feature(fn, name=""):
"""
Decorator that can be used to register a feature.
:param function fn: The function to register.
:param str name: Optional string with the name of the function
as it should be registered. If not provided the name of the
function is used.
"""
... | 88a420dbabc3ac372ee1c7a71038916c8671c246 | 3,622,547 |
def apply_rotation_on_vector(q, v):
"""q is the quaternion describing the rotation to apply, v is the vector on
which to apply the rotation"""
quaternion_v = transform_vector_to_quaternion(v)
transposed_q = conjugate_quaternion(q)
r = quaternion_product(quaternion_product(q, quaternion_v), transpo... | 72e64e8e36580d7ccf3e2876ae397fce616d2f3c | 3,622,548 |
import re
def get_polygon_speed(polygon_name):
"""Returns speed unit within a polygon."""
result = re.search(r"\(([0-9.]+)\)", polygon_name)
return float(result.group(1)) if result else None | 2d2cc99f30153c4fbc9ac358ad3debc15fc3227e | 3,622,549 |
def pt_in_ploy(poly, x, y):
""" 判断 点(x,y) 是否 在 poly 最大和最小坐标之外,粗略 判断点是否在图形之内 """
n = len(poly)
if n < 3:
return False
xmax = xmin = poly[0]['x']
ymax = ymin = poly[0]['y']
for i in range(1, n):
if poly[i]['x'] > xmax:
xmax = poly[i]['x']
elif poly[i]['x'] < x... | 2e07429edd6929a7e5747e6ba113f4186413dab8 | 3,622,550 |
async def indexer_get_merkle_proof(request: web.Request) -> web.Response:
"""
Optional endpoint if running an indexer.
Give the client access to arbitrary merkle proofs from any running indexer.
"""
# TODO(1.4.0) This should be monetised with a free quota.
query_params: dict[str, str] = {}
... | 660a8ba575bbe6495ea4f3a00c993714203b15c8 | 3,622,551 |
def random_node_presence(t_windows, rep, plac, dur):
"""
Generate the occurrence and the presence of a node given occurrence_law(occurrence_param)
and presence_law(presence_param).
:param t_windows: Time window of the Stream Graph
:param rep: Number of segmented nodes
:param plac: Emplacement o... | 416ea50c4cdd1280dde90816ec735b8eff6f81f1 | 3,622,552 |
def action_details(request, test_id, action_id):
"""
Generate HTML page with detail data about test action
**Template:**
:template:`test_report/action_details.html`
"""
action_aggregate_data = list(
TestActionAggregateData.objects.annotate(
test_name=F('test__name')).filte... | 0ef73debe1031cc34fd41575ee19d9b29bd3a311 | 3,622,553 |
import pdb
import torch
def batch_hard_triplet_loss(labels, embeddings, k, margin=0, margin_type='soft'):
"""Build the triplet loss over a batch of embeddings.
For each anchor, we get the hardest positive and hardest negative to form a triplet.
Args:
labels: labels of the batch, of size (batch_s... | 2853124d06688eaca4f7da2a5bc19819490656c9 | 3,622,554 |
def rebin(x: VariableLike, dim: str, bins: _cpp.Variable) -> VariableLike:
"""
Rebin a dimension of a data array or dataset.
The input must contain bin edges for the given dimension `dim`.
:param x: Data to rebin.
:param dim: Dimension to rebin over.
:param bins: New bin edges.
:raises: If... | 8810775aa7a1f5ddfa9ee13f2f2f7cd0853fbde0 | 3,622,555 |
import sys
from pathlib import Path
import os
def resource_path(relative_path):
""" Return absolute path for provided relative item based on location
of program.
"""
# If compiled with pyinstaller then sys._MEIPASS points to the location
# of the bundle. Otherwise path of python script is used.
... | 303418a0d61ae2107d7ac4f8e3503c71bac090bf | 3,622,556 |
def scalar_div(x: Number, y: Number) -> Number:
"""Implement `scalar_div`."""
_assert_scalar(x, y)
if isinstance(x, (float, np.floating)):
return x / y
else:
return int(x / y) | c05cc4657ae250e8db8da0770fde80892e864987 | 3,622,557 |
def _set_default_voltage_ratio(
voltage_ratio: float, subcategory_id: int, type_id: int
) -> float:
"""Set the default voltage ratio for semiconductors.
:param voltage_ratio: the current voltage ratio.
:param subcategory_id: the subcategory ID of the semiconductor with missing
defaults.
:pa... | d084f157c4d105193693af722e72028129e17821 | 3,622,558 |
def PureMultiHeadedAttention(x, params, n_heads=8, dropout=0.0, mode='train',
**kwargs):
"""Pure transformer-style multi-headed attention.
Args:
x: inputs (q, k, v, mask)
params: parameters (none)
n_heads: int: number of attention heads
dropout: float: dropout rate
... | e15a42d748a548a508f50c910f7aa25ca9ccffbc | 3,622,559 |
import functools
def flatten_factory(flatten_children, is_internal):
"""
Adaptor for single_filter_proc to accept multiple elements
"""
return single_to_multiple(functools.partial(single_filter_proc, should_filter))
return single_to_multiple(functools.partial(single_flatten_proc, flatten_children... | 1d90453ecf775f72f8c379d7dfb836e9345e34cc | 3,622,560 |
from typing import Dict
def parse_sentence(obj: Dict) -> BioCSentence:
"""Deserialize a dict obj to a BioCSentence object"""
sentence = BioCSentence()
sentence.offset = obj['offset']
sentence.infons = obj['infons']
sentence.text = obj['text']
for annotation in obj['annotations']:
sente... | 3cf53fb059a367f2200a444735c272883aff8e3e | 3,622,561 |
def _test_for_licensing(esh_machine, identity):
"""
Used to determine whether or not an instance should launch
Returns True OR raise Exception with reason for failure
"""
try:
core_machine = ProviderMachine.objects.get(
instance_source__identifier=esh_machine.id,
inst... | e319ba47a5b9a4ed0f016c1bd995f6e0a5f00fa5 | 3,622,562 |
def numba_find_phys(x, y, bdyx, bdyy):
"""
Computes whether the points x, y are inside of the polygon defined by the
x-coordinates bdyx and the y-coordinates bdyy
The polgon is assumed not to be closed (the last point is not replicated)
"""
inside = np.zeros(x.shape, dtype=bool)
vecPointInPa... | 442ae67606bea4cb6d797e08c2e6382b9eff2579 | 3,622,563 |
from unittest.mock import patch
def _get_session_client_inject_error_and_call_handler(
handler_name: str,
error_name: str = None,
) -> ProgressEvent:
"""Inject a given botocore client error and call a given handler"""
if error_name:
side_effect = botocore.exceptions.ClientError(
... | 7802daf27ab50a9ac99bfe308f02626f381c4eb7 | 3,622,564 |
import inspect
import six
def stream_text(text, chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming text.
Returns a buffered generator which encodes a string as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
text : str
The data bytes to stream
c... | 20b62a77b2db501a1d8bb9f0bf6876f0d650b080 | 3,622,565 |
def put_number(image, num):
"""アイコンサイズの画像imageの上に
numの値を表示する。
"""
image = image.convert_alpha()
s = str(num)
if len(s) == 1:
font = cw.cwpy.rsrc.fonts["statusimg1"]
elif len(s) == 2:
font = cw.cwpy.rsrc.fonts["statusimg2"]
else:
font = cw.cwpy.rsrc.fonts["statusim... | e09b49ae5c4d0c71cc6556a64a17a38970dd4493 | 3,622,566 |
import multiprocessing
import requests
def generate_sequences(fuzzing_requests, checkers, fuzzing_jobs=1):
""" Implements core restler algorithm.
@param fuzzing_requests: The collection of requests that will be fuzzed
@type fuzzing_requests: FuzzingRequestCollection
@param checkers: The list of chec... | 041ba055f31556aea11696e63abc5a177270f517 | 3,622,567 |
import json
def linechart():
"""Fake endpoint."""
return json.dumps({
"line1": [1, 4, 3, 10, 12, 14, 18, 10],
"line2": [1, 2, 10, 20, 30, 6, 10, 12, 18, 2],
"line3": rr_list(),
}) | f3de5d176d48f18e987318214ff208f48dafa20c | 3,622,568 |
def server_static(filename):
"""定义/assets/下的静态(css,js,图片)资源路径"""
return static_file(filename, root='./images') | c0e9831200ec73951f1e2aaf45b6f08791ec23be | 3,622,569 |
import tensorflow as tf
import psutil
def build_execution_summary(execution_timestamp, execution_id,
ml_framework_build_label, execution_label,
platform_name, system_name, output_gcs_url,
benchmark_result, env_vars, flags, harness_inf... | 79212ca7e6a7c95123b84af72270476d95a29342 | 3,622,570 |
def retrieve_one(loc_id):
"""
Return one record from the collection matching given ID
:param loc_id: record ID for localization data
:return: matching data object
"""
query = Geolocation.query.filter(Geolocation.visible == 1).filter(
Geolocation.id == loc_id).one_or_none()... | efed22a515de3a271839c9e8fccaa85404a941b4 | 3,622,571 |
def get_seed(seed):
"""Returns the local seeds an operation should use given an op-specific seed.
See @{tf.get_seed} for more details. This wrapper adds support for the case
where `seed` may be a tensor.
Args:
seed: An integer or a @{tf.int64} scalar tensor.
Returns:
A tuple of two @{tf.int64} scal... | cf0405ba0fd6163fdafcf93410e0a306a35eb6c1 | 3,622,572 |
def _SendInsertRequest(client, resources, url_map_ref, url_map):
"""Sends a URL map insert request and waits for the operation to finish.
Args:
client: The API client.
resources: The resource parser.
url_map_ref: The URL map reference.
url_map: The URL map to insert.
Returns:
The operation r... | 9a217297d991fe35b5438e31f100c9d12ee9e2b7 | 3,622,573 |
from typing import Union
from typing import Set
from typing import Tuple
import itertools
def make_request_with_cancellation_test(
test_name: str,
reactor: MemoryReactorClock,
site: Site,
method: str,
path: str,
content: Union[bytes, str, JsonDict] = b"",
) -> FakeChannel:
"""Performs a re... | e8f6e5c4601a70fbb78b01123e44be37d4e6dfd0 | 3,622,574 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_utilities package"""
reload_params = {"package": u"fn_utilities",
"incident_fields": [],
"action_fields": [u"excel_named_range", u"excel_range", u"extract_file_path", u"parallel_timers", u"utilit... | 2f6a1086183bbc46cd8d310f4afe5887065cd42b | 3,622,575 |
import copy
def random_reset_mutation(random, candidate, args):
"""Return the mutants produced by randomly choosing new values.
This function performs random-reset mutation. It assumes that
candidate solutions are composed of discrete values. This function
makes use of the bounder function as specif... | c357237e22e34b7496f8cc17f4ad0efa2bd4621d | 3,622,576 |
from typing import Dict
def plot_lines_and_violins(
all_version_stats: Dict[str, VersionStats], # {version: version_stats}
all_resource_type_stats: Dict[
str, ResourceTypeStats
], # {resource_type: resource_type_stats}
) -> go.Figure:
"""
Plots 2 subfigures in 1 column
top row: a (ve... | 8b46724dce8a748d018c94734089d671186dea3a | 3,622,577 |
import sys
def get_ipv6_addrs(ip, count):
"""
Get N IPv6 addresses in a subnet.
Args:
subnet (str): IPv6 subnet, e.g., '2001::1/64'
number_of_ip (int): Number of IP addresses to get
Return:
Return n IPv6 addresses in this subnet in a list.
"""
subnet = str(IPNetwork(ip)... | f1562113eb2ea3ce3ccda5febbb421c883e2c8b6 | 3,622,578 |
def true_positive_rate(prediction: np.ndarray, ground_truth: np.ndarray) -> float:
"""A.k.a. recall or sensitivity. From the actual positives, how many did I classify as positive?"""
tp = true_positives(prediction, ground_truth)
fn = false_negatives(prediction, ground_truth)
return tp / (tp + fn) | 7fe9ed40b30a104d0b5e628e10e6f105a7d0831a | 3,622,579 |
import sys
def command_dump(opts):
"""Unpack some or all of the contents of a .zs file.
Usage:
zs dump <zs_file>
zs dump [--start=START] [--stop=STOP] [--prefix=PREFIX]
[--terminator=TERMINATOR | --length-prefixed=TYPE]
[-j PARALLELISM]
[-o FILE]
[--] <zs_file>
zs du... | 9ca17075b2b58aa170fefed2964c22ed4c9c5e23 | 3,622,580 |
def is_same_data(data1, data2, precision=10**-5):
"""
Compare two data to be the same.
:param data1: given data1
:type data1: list
:param data2: given data2
:type data2: list
:param precision: comparing precision
:type precision: float
:return: True if they are the same
"""
... | 16e786a552d9190eebb44721ab75ddd45d7086cf | 3,622,581 |
def get_highest_score(league_id):
"""
Gets the highest score of the week
:param league_id: Int league_id
:return: List [score, team_name]
"""
week = get_current_week()
scoreboards = get_league_scoreboards(league_id, week)
max_score = [0, None]
for matchup_id in scoreboards:
... | b2fc905b909169742c960bbc0b8c5c897dc158f6 | 3,622,582 |
import re
def normalise_name(raw_name):
"""
Normalise the name to be used in python package allowable names.
conforms to PEP-423 package naming conventions
:param raw_name: raw string
:return: normalised string
"""
return re.sub(r"[-_. ]+", "_", raw_name).lower() | 2c9aea4a3e83fdb52f952d2308de29d8948f6917 | 3,622,583 |
def webhooks_settings():
"""
Shows the settings page
"""
with get_db() as DB:
c = DB.cursor()
results = c.execute(
"""
SELECT
id,
type,
endpointUrl,
authorizationHeader,
enabled
FROM webhooks
... | 341c26083ea7918db2409604f5a0c137dcd6a66f | 3,622,584 |
def build_parameters(integration_config: dict, instance_config: dict) -> dict:
"""Gets configurations and building the parameters to context
Args:
integration_config: The integration's configuration
instance_config: The instance's config
Returns:
A dictionary of parameters to check... | cb2871f35235df8999e85e46882b944d0595fac3 | 3,622,585 |
def decodeall(b):
"""Decode all CBOR items present in an iterable of bytes.
In addition to regular decode errors, raises CBORDecodeError if the
entirety of the passed buffer does not fully decode to complete CBOR
values. This includes failure to decode any value, incomplete collection
types, incomp... | 15fa36714710350e893faa77f96cc3e515f29aca | 3,622,586 |
def ensemble_architecture(result):
"""Extracts the ensemble architecture from evaluation results."""
architecture = result["architecture/adanet/ensembles"]
# The architecture is a serialized Summary proto for TensorBoard.
summary_proto = tf.summary.Summary.FromString(architecture)
return summary_pr... | 2715f5fdc0b92a80f7af630f3464ec0eb0e9f230 | 3,622,587 |
def average_nifti_list(input_path_list):
"""Averages NIfTIs given as a list of image file paths, into the space of the first. Returns the average NIfTI (does not save).
Images must be the same shape.
"""
return divide(add_nifti_list(input_path_list), np.float(len(input_path_list)))
# ... | 368ae3ee64a4661d8b64425167c614ad0e3ba174 | 3,622,588 |
import importlib.util
import sys
from pydantic import BaseModel # noqa: E0611
def copy():
"""copy message from source to destination
use this to transfer file input to database, or from a database to another
database.
"""
class CopyProcessorSettings(ProcessorSettings):
model_definition:... | b2a8f1f9efd8bfb5f6c71801e75f0496e19587b3 | 3,622,589 |
def transform_inv(T):
"""
Calculates the inverse of the input homogeneous transformation.
This method is more efficient than using C{numpy.linalg.inv}, given
the special properties of the homogeneous transformations.
@type T: array, shape (4,4)
@param T: The input homogeneous transformation
@rtype: array... | 232ef1ba6683856c6d92880f4236b635d10edc6f | 3,622,590 |
def pandas_to_etable(df):
"""
returns a pyet.eTable constructed from given pandas DataFrame
"""
pt = eTable()
pt.Rows = len(df.index)
for cn in df.columns:
dc = df.loc[:, cn].values
pt.AddCol(dc, cn)
return pt | d9632197e79ec1f45c9967167a8ef413efab5eb7 | 3,622,591 |
def db_details_without_password(db_connection_id):
"""
To generate a dictionary for data base details.
Args:
db_connection_id(int):data base connection id.
Returns:
Returns a dictionary containing data base details for a particular
data base connection id.
"""
db_deta... | e3bf353352a768e14849e16b6697a002a99e7c02 | 3,622,592 |
def std_of_displacements(stops, distf=lambda a, b: geodesic(a, b).meters):
"""
Compute standard deviation of displacements feature from stops.
The standard deviation of distances between subsequent stops.
:param stops: dataframe of stops.
:param distf: distance function of the form: ((lat, lon),(l... | acce08afb6d7ec3c0d87ef08e1d822c88cc4b969 | 3,622,593 |
def main(args):
"""The main process of profile-based features.
:param args: an object of the arguments.
"""
file_list = args.inputfiles
label_list = args.labels
output_format = args.f
if len(file_list) == 0:
print 'Input files not found.'
return False
if output_format ==... | 70a3e5eaa0cd688401f5ecc8edfe78d333be8547 | 3,622,594 |
def class_amount(data_amount: int) -> int:
"""Compute class amount (k) of a data size"""
return ceil(1 + 3.3 * log10(data_amount)) | 52a1f4c28d31b9e7f5847728033760f72cce0e1b | 3,622,595 |
def _wrap_coord(tensors):
"""wrap positions to unit cell"""
cell = tf.gather_nd(tensors['cell'], tensors['ind_1'])
coord = tf.expand_dims(tensors['coord'], -1)
frac_coord = tf.linalg.solve(tf.transpose(cell, perm=[0, 2, 1]), coord)
frac_coord %= 1
coord = tf.matmul(tf.transpose(cell, perm=[0, 2,... | 71aa52a518f89688162f846eb18dfa37aad281a8 | 3,622,596 |
def two_linear_model_loss_regularized_dy1dx_lp(w0, w1, x, y, reg_coeff,
norm_type):
"""Penalize by ||dy1/dx||, optimal when first layer is fixed."""
dy1_dx_f = jax.grad(two_linear_model_y1_mean, argnums=2)
dy1_dx = dy1_dx_f(w0, w1, x)
loss = two_linear_model_loss(w... | 75af79d7669e6d2b24a001d973bb463fb6c72ddf | 3,622,597 |
def mask_elon(aia_cumul8, hmi_dat):
"""
Masking for elongation algorithm.
Parameters
----------
aia_cumul8 : list
Cumulative ribbon masks, c=8.
hmi_dat : list
SDO/HMI image data for flare.
Returns
-------
aia8_pos_2 : list
Contains only the positive cumulati... | e37b4bd190f37b5dfd129fadec49466578dbfbf9 | 3,622,598 |
def _validate_pad(padtype, padlen, x, axis, ntaps):
"""Helper to validate padding for filtfilt"""
if padtype not in ['even', 'odd', 'constant', None]:
raise ValueError(("Unknown value '%s' given to padtype. padtype "
"must be 'even', 'odd', 'constant', or None.") %
... | 3daa31203401cf9e67a65768c80c05da4b2d9446 | 3,622,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.