content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def load_image(folder, test):
"""Load the data for a single letter label."""
image_files = glob.glob(folder + "*[0-9].tif")
dataset = np.ndarray(shape=(len(image_files), FLAGS.image_size, FLAGS.image_size),
dtype=np.float32)
mask_train = []
print(folder)
num_images = 0
for image_f... | 83b824d7127cd2e0751578aadbde8ab4936ff909 | 3,628,700 |
def get_log_p_k_given_omega_int_analytic(k_train, k_bnn, interim_pdf_func):
"""Evaluate the log likelihood, log p(k|Omega_int),
using kernel density estimation (KDE) on training kappa,
on the BNN kappa samples of test sightlines
Parameters
----------
k_train : np.array of shape `[n_train]`
... | 83b4c43d86eddc6fd0a4f51deaec570889054d3f | 3,628,701 |
import theano.tensor as T
def LeakyReLU(a=0.33):
"""
Leaky rectified linear unit with different scale
:param a: scale
:return: max(x, a*x)
"""
def inner(x):
return T.switch(x < a*x, a*x, x)
return inner | 5b9227f9e013fff14fbd49be77230dd1e9069525 | 3,628,702 |
def get_top_element_count(mol, top):
"""
Returns the element count for the molecule considering only the atom indices in ``top``.
Args:
mol (Molecule): The molecule to consider.
top (list): The atom indices to consider.
Returns:
dict: The element count, keys are tuples of (elem... | f7293c1d154346c955052ceff0ee59483538bdc3 | 3,628,703 |
def load_data(filename, start=0.0, end=1.0, include_profiles=False):
"""
Wrapper function to load data from a file.
Args:
filename: The path of the file to load the data from.
start: Fractional position from which to start reading the data.
end: Fractional position up to which to re... | e234e037260ef31292f939cd39f20bc394197d31 | 3,628,704 |
def query_spf(domain: str) -> str:
"""
takes in a domain as a string and trys to find a spf with a query, if it finds one it returns the spf record if not returns an empty string.
"""
q = query(domain,'TXT')
if not q:
return ""
for txtd in q.rrset:
if txtd.strings[0].decode('utf-... | 0c3bd664930445372cff2c9ffcd88ae1224ef6f8 | 3,628,705 |
def str_wire(obj):
"""Returns a string listing the edges of a wire."""
s = []
edges = obj.Edges()
edge_count = len(edges)
if edge_count == 1:
s.append("Wire (1x Edge)\n")
else:
s.append("Wire (%dx Edges) " % (edge_count))
s.append("length:")
s.append(_str_value(wi... | 8434b804178e0e480b1804a2186f360c93c9fd4a | 3,628,706 |
from environmental import EFM
from performance import calculate_performance
import os
def run_model(model_input, resmap, ID, full_output=False):
""" run model
Parameters
----------
'model_inputs' (dictionary): contains inputdata, interference flag,
logit flag, candidate model pa... | 9e05369bddd4d5290eae3362caf8b28cd385b176 | 3,628,707 |
from typing import Tuple
def calculate_approximate_ci(
xs: np.ndarray, ratios: np.ndarray, confidence_ratio: float
) -> Tuple[float, float]:
"""
Calculate approximate confidence interval based on profile. Interval
bounds are linerly interpolated.
Parameters
----------
xs:
The ... | d48133a5017e3e121c918ef1efc44d1bef2c21cd | 3,628,708 |
import logging
def get_logger(level=logging.INFO, quite=False, debug=False, to_file=''):
"""
This function initialises a logger to stdout.
:param level: logging level (DEBUG / INFO / WARNING / CRITICAL)
:param quite: if mute logging
:param debug: if debug mode
:param to_file: log file path
... | 13e60d08055639fcad9389b1ee49b2c7113f38c3 | 3,628,709 |
import torch
def transform_means(means, size, method='sigmoid'):
"""
Transforms raw parameters for the index tuples (with values in (-inf, inf)) into parameters within the bound of the
dimensions of the tensor.
In the case of a templated sparse layer, these parameters and the corresponding size tuple... | 86bd46f2a10f01dc3a39e5b3e7c3003bb95641bb | 3,628,710 |
def pull_if_not_exist(region: str=None, registry_prefix: str=None, repo: str=None, tag: str=None):
"""
Pull the image from the registry if it doesn't exist locally
:param region:
:param registry_prefix:
:param repo:
:param tag:
:return:
"""
output = get_stdout('''{docker} images {re... | 4826a31f41db9cac92b70f1b568dd5351ff2d0bd | 3,628,711 |
import re
def _remove_junk(plaintext, language):
"""
"""
if language in {"zh", "ja", "fa", "iw", "ar"}:
return plaintext
lines = plaintext.splitlines()
lines = [l for l in lines if re.findall(MEANINGFUL, l) or not l.strip() or l.startswith("<meta")]
out = "\n".join(lines).strip() + "\n... | 0d88d55021aa4b81eeb39f1ca21540b3112c6a08 | 3,628,712 |
def model_parallel_is_initialized():
"""Check if model and data parallel groups are initialized."""
if _TENSOR_MODEL_PARALLEL_GROUP is None or _PIPELINE_MODEL_PARALLEL_GROUP is None or _DATA_PARALLEL_GROUP is None:
return False
return True | f60560130cbde971e340987064f58e66cd1b6855 | 3,628,713 |
def CV_IS_IMAGE(*args):
"""CV_IS_IMAGE(CvArr img) -> int"""
return _cv.CV_IS_IMAGE(*args) | ca00c5f9614a59e037fbe1bd06d97f38f6c27b57 | 3,628,714 |
def fingerprint(samp):
"""A memory-efficient algorithm for computing fingerprint when wid is
large, e.g., wid = 100
"""
wid = samp.shape[1]
d = np.r_[
np.full((1, wid), True, dtype=bool),
np.diff(np.sort(samp, axis=0), 1, 0) != 0,
np.full((1, wid), True, dtype=bool)
]
... | 3b372b4480da2fc5fdfd89755b0dc7ec1408fbf3 | 3,628,715 |
def ldns_rr_list_compare(*args):
"""LDNS buffer."""
return _ldns.ldns_rr_list_compare(*args) | 7a4414931578ec475bae6b1cf112e6eb8b8d564f | 3,628,716 |
def at_least_one_shift_each(cur_individual):
""" checks if there is at least one of each shift: 01, 10, 11 """
num_entrega = 0
num_recogida = 0
num_dual = 0
while cur_individual:
shift = cur_individual[:2]
cur_individual = cur_individual[2:]
if shift == '01':
num_... | 070fe16e779ab30bcee7873ec01876962f30ec91 | 3,628,717 |
def generate_validate_yaml_for_python(
artifact_name,
top_level_imports,
allowed=None,
exclude_files=None,
verbose=0,
):
"""Generate a validation YAML file from an artifact that is a python package.
This function works in two stages.
1. It uses a default set of globs for python install... | 074df24576fecabdd4d7d53faeacb09791556441 | 3,628,718 |
def near_points(px, qx, r, pxtree=None, qxtree=None):
"""
Finds points in qx that are within a distance r of any point in px
Parameters:
px, required, float(np, dim), coordinates of px
qx, required, float(nq, dim), coordinates of py
r, required, float, radius of closeness
... | d9ee596d0b3dc02247f8df31ea521a978b79a1f2 | 3,628,719 |
def batch_dtype(observation_space, action_space):
"""Returns a batch dtype for the provided observation and action spaces.
Args:
observation_space -- the observation space
action_space -- the action space
Returns a complex numpy dtype for the batch
"""
states_dtype = np.dtype((obse... | 1525d9a2817a97b748ffd06c20b88b2e7d25a538 | 3,628,720 |
def runQuery(tStart, tStop):
"""
Get all the rows from all the events within the time period of _tStart_ and _tStop_.
:param tStart: start of the time period
:param tStop: stop of the time period
:return: an array of all the events between _tStart_ and _tStop_
"""
mariadb_connection = mariad... | b3dd62cc41a8a5da331190303b4008a135c07dbb | 3,628,721 |
from datetime import datetime
import pytz
def get_aware_utc_now():
"""Create a timezone aware UTC datetime object from the system time.
:returns: an aware UTC datetime object
:rtype: datetime
"""
utcnow = datetime.utcnow()
utcnow = pytz.UTC.localize(utcnow)
return utcnow | b0b102b8d7d49e0d7d4041a476502cdd683dc8af | 3,628,722 |
from typing import Optional
from typing import Callable
from typing import Iterator
from typing import Any
import inspect
def iterpoints(resp: dict, parser: Optional[Callable] = None) -> Iterator[Any]:
"""Iterates a response JSON yielding data point by point.
Can be used with both regular and chunked respons... | 000c2c873ab38378bb42945ed3304213b254061a | 3,628,723 |
def evaluation(board: chess.Board, deciding_agent):
"""
Basic heuristic.
:param board: The current state of the game The current state of the game
:param deciding_agent: The identity of the "good" agent.
:return: Heuristic value for the state
"""
# Define 1 for myself and -1 for rival:
... | 95bbc6c7b3dfd20b7c88b172f5b42adbada64247 | 3,628,724 |
import time
def calculate_temperature(T0, setpoint, K, omega, Tvar):
"""
Calculate temperature according to the following formula:
:math:`T_{output} = T_{var} exp^{-(t - t_0)/K} sin(ω t) + T_{setpoint}`
"""
t = time.monotonic()
return ((Tvar *
np.exp(-(t - T0) / K) *
... | 3c56efe329e7f393b0bf1d6829fdcd0b0b32a557 | 3,628,725 |
def nodes_visited_for_seq_ref(distance, max_array, min_array, list_parent_node):
"""
"""
boolean_grp = np_logical_and(np_less_equal(distance, max_array),
np_greater(distance, min_array))
count_visited_nodes = np_sum(boolean_grp)
not_boolean_grp = np_logical_not(boo... | a85b86a28993d25f9c3b0a3b1f6ff0d8db5edab6 | 3,628,726 |
from typing import Type
import subprocess
from typing import Any
import importlib
def get_config_class() -> Type[BaseSettings]:
"""
Dynamically imports and returns the Config class from the current service.
This makes the script service repo agnostic.
"""
# get the name of the microservice package... | 5e64bc3735593b576dd516adfb49564429f18ee4 | 3,628,727 |
def bdc_plot_datasets(datasets, zoom = 4, layout=Layout(width='600px', height='600px')):
"""Plot Dataset tiles
"""
bbox = get_bounds(datasets, datasets[0].crs)
bbox_pol = shapely.wkt.loads(bbox.wkt)
project = partial(
pyproj.transform,
pyproj.Proj(datasets[0].crs.crs_str),
... | 6c05b84571dbef30116debb3605f14e56acb176c | 3,628,728 |
from typing import Tuple
from typing import List
import csv
def read_xnli(dir_path, lang, split, spm_path=None) -> Tuple[List[List[str]], List[str]]:
"""
Reads XNLI data.
:param dir_path: the path to the xnli folder
:param lang: the language
:param split: the split of the data that should be read ... | bdfe3a1d938fb39573e604e97ce8bd27512b3f34 | 3,628,729 |
def indexation(obj, key):
""":yaql:operator indexer
Returns value of attribute/property key of the object.
:signature: obj[key]
:arg obj: yaqlized object
:argType obj: yaqlized object, initialized with
yaqlize_indexer equal to True
:arg key: index name
:argType key: keyword
:re... | 3848641447a50e0059c7ce4d68318ff832d2f5f1 | 3,628,730 |
def convert_output_key(name):
""" Convert output name into IE-like name
:param name: output name to convert
:return: IE-like output name
"""
if not isinstance(name, tuple):
return name
if len(name) != 2:
raise Exception('stats name should be a string name or 2 elements tuple '
... | d5c59766c615e0e7b45f173948692050a7b890e3 | 3,628,731 |
def collection(identifier: str):
"""Get a collection.
---
tags:
- collection
parameters:
- name: prefix
in: path
description: The identifier of the collection
required: true
type: string
example: 0000001
- name: format
description: The file type
in:... | 1f37d74617d6e92fa4f955214b1f613856a8dadf | 3,628,732 |
def tensor_shape_proto(output_size):
"""
The shape of this tensor.
"""
return TensorShapeProto(dim=[TensorShapeProto.Dim(size=d) for d in output_size]) | f5b89370c62259349c27c0da1558b2abb5160173 | 3,628,733 |
def check_raises(physical_line, filename):
"""Check raises usage
N354
"""
ignored_files = ["./tests/unit/test_hacking.py",
"./tests/hacking/checks.py"]
if filename not in ignored_files:
if re_raises.search(physical_line):
return (0, "N354 ':Please use ':rai... | 9c735f485fdf73d0914abd105ddb6ff39140fda2 | 3,628,734 |
def eval_expr(src, env=None, **kwargs):
"""
Similar to eval_ast, but receives expression as a string and variables as
keyword arguments.
"""
env = {} if env is None else env
env.update(kwargs)
return eval_ast(parser(src), env) | 752e7198476f528916e2252a0d78b0586f7a88b8 | 3,628,735 |
def tasksInView(): # pragma: no cover
"""Iterate over all the tasks in view."""
return filter(isTask, itemsInView()) | b46b9c75590bc36aac015470e1d04183752a7855 | 3,628,736 |
def in_polygon(point, polygon):
"""Simple wrapper on the within method of shapely points
Params: point (POINT) a shapely point object
polygon (POLYGON) a shapely polygon object (the target overlap area)
Returns: (bool) whether or not the point is within polygon expressed as a boolean
"... | 0a26d023672162a53affddfe23a89361d900d9a0 | 3,628,737 |
def sort_points(points:list) -> list:
"""
Returns a list of point tuples equivalent to points, but sorted in order
by ascending x coordinate.
>>> sort_points([(5,4),(2,3)])
[(2,3),(5,4)]
>>> sort_points([(1,1),(3,2),(2,3)])
[(1,1),(2,3),(3,2)]
>>> sort_points([(99,120),(0,10),(200,... | 007b20889ad7b474b891196da1ee9ed6e3286812 | 3,628,738 |
from sys import path
def validate_overwrite_different_input_output(opts):
"""
Make sure that if overwrite is set to False, the input and output folders
are not set to the same location.
:param opts: a namespace containing the attributes 'overwrite', 'input',
and 'output'
:raises Validatio... | 06427ee7782533979740f465f79a03aa3054bc1f | 3,628,739 |
def NASNetMobile(input_shape=None,
include_top=True,
weights='imagenet',
input_tensor=None,
pooling=None,
classes=1000):
"""Instantiates a Mobile NASNet model in ImageNet mode.
Optionally loads weights pre-trained on ImageNet.
N... | 5cbfb237566dab72376fb14b167e48e2cb69b219 | 3,628,740 |
def dcn_resnet152(pretrained=False, **kwargs):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
if pretrained:
pretrained_model = model_zoo.load_url(model_urls['resnet1... | edf6ab41af211cc37f04bf6614497be9e7a77293 | 3,628,741 |
import string
def preprocessing(text):
"""Exclude punctuations and digits from text."""
text = process_tweets(text)
text = text.lower()
exclude = string.punctuation + string.digits
for i in exclude:
text = text.replace(i, "")
return text | f390ce2b0c1a1ff831b5a7c7b2491b9c860ad4e4 | 3,628,742 |
import typing
def parse_patter(pats: typing.List[str]) -> typing.Tuple[typing.List[str], typing.List[str]]:
"""
分析匹配项
========
/xx/ # 只匹配根目录下文件夹
xx/ # 匹配所有的文件夹
/xx # 只匹配根目录下文件
xx # 匹配所有的文件
!xx # 除xx之外
=========
/xx/ => xx + xx/**
xx/ => xx + xx/... | 17eca544b157fe2ad406e1c4385c49acc53ff0d7 | 3,628,743 |
def index():
"""Job Status Index."""
return render_template('fts_index.html') | bd382655aea46c910ef66c6563a094186d5b2a51 | 3,628,744 |
def createNiftiTestFiles(shouldValidate: bool = True):
"""
Create base 3D NIfTI1 file all others are created from
"""
convertDicomFileToNifti(test_dicomPath, test_3DNifti1Path)
nifti1_3D = nib.load(test_3DNifti1Path)
# Extract the TR time, then eliminate pixel dimension data past 3rd
# dime... | 8d7f3ce200ef4b2a6e1438f8949c2541c264b292 | 3,628,745 |
import os
def is_downloaded(folder,path_):
"""[check if the .html file exists]
Args:
folder ([folder in which is placed the book]): [description]
path_ ([type]): [path of the .html page]
Returns:
[type]: [description]
"""
if not os.path.exists(folder):
os.maked... | 1d480fedb13429baa4bc3234f7a42cafe8dba93c | 3,628,746 |
def calc_brownian_displacement(dt, viscosity, particle_diameter, temperature):
"""
Calculate brownian motion characteristic displacement per dt
"""
kb = 1.3806e-23 # (J/K) Boltzmann constant
dx = np.sqrt(2*kb*temperature*dt/(3*np.pi*viscosity*particle_diameter))
return dx | 1bfdba75d0ad30b1f0dca790c47e004afa39b1b1 | 3,628,747 |
def manhattan_distance(v1, v2, norm=False):
"""
return ||v1 - v2||_1
"""
v1, v2 = check_pairwise_vector(v1, v2, norm)
diff = v1 - v2
K = np.abs(diff).sum()
return K | c41f6c529bb7604a4ca0aa6487d8a2cc5225bf04 | 3,628,748 |
def read_data_submit(ftdi, buf, size):
"""
read_data_submit(context ftdi, unsigned char * buf, int size) -> transfer_control
Reads data from the chip. Does not wait for completion of the transfer
nor does it make sure that the transfer was successful.
Use libusb 1.0 asynchronous API.
Parame... | a70652e72d9a425e052b723fc12102742eab6121 | 3,628,749 |
def set_spines(ax, plot_params):
"""
Sets spines of the shift graph to be invisible if chosen by the user
Parameters
----------
ax: Matplotlib ax
Current ax of the shift graph
plot_parms: dict
Dictionary of plotting parameters. Here `invisible_spines` is used
"""
spines ... | 4e74ce30f52d465e9470f608cd8c909dfae4d0a5 | 3,628,750 |
def update_user(id):
"""Method to handle update a user"""
try:
data = request.get_json() or {}
user = Authentication()
response = user.update_user(id, data)
return response
except KeyError:
return ({"Error": "An error occured"}) | 398e28b6fb03f505512738ad28824e0c885693b4 | 3,628,751 |
import types
def _normalize_resources(resources):
""" Exclude any resources that have `/facebook` in the path as these
are internal and require internal FB infra. Only applies to resources
specified in the `dict` format
Will also go ahead an invert the dictionary using `_invert_dict`
"""
if r... | 16a0bd8cd1d4e4ec5ad8e929d8be969d95a1924e | 3,628,752 |
import sys
def process_file(fn, coverage, percentage, multiple, debug):
"""
Determine whether there was adequate coverage of bases in this file.
NOTE: Returns True if the run was OK.
:param fn:
:param coverage:
:param percentage:
:param multiple:
:param debug:
:return:
"""
... | cd7465a0e175138ae73f2a0d46ae729673bf0ec5 | 3,628,753 |
def parse_targets(target):
"""
Parse provided targets
:param target: Targets
:return: List of IP addresses
"""
if '-' in target:
ip_range = target.split('-')
try:
t = IPRange(ip_range[0], ip_range[1])
except AddrFormatError:
try:
st... | 94e9a5784f0fa18bf7677e08fed62ee542a429d0 | 3,628,754 |
def lgam(x):
"""Natural log of the gamma fuction: see Cephes docs for details"""
if x < -34:
q = -x
w = lgam(q)
p = floor(q)
if p == q:
raise OverflowError("lgam returned infinity.")
z = q - p
if z > 0.5:
p += 1
z = p - q
... | e165ee0f53aef367350ed964ae2d31374b847d59 | 3,628,755 |
def matches(G, queue):
"""
If the sequence in 'queue' correspond to a
node in 'G', return the sequence id,
otherwise return False
"""
if not queue:
return False
seq = 0
for a in queue:
try:
seq = G[seq][a]
except KeyError:
return False
... | 859f43f6457b4add4cda88495a8dc6c4a559e5d5 | 3,628,756 |
def get_mu_sigma(prices, returns_model='mean_historical_return', risk_model='ledoit_wolf',
frequency=252, span=500):
"""Get mu (returns) and sigma (asset risk) given a expected returns model and risk model
prices (pd.DataFrame) – adjusted closing prices of the asset,
each row i... | 272196b663e43696166fa7134b6dd5d9c6a9c49c | 3,628,757 |
def getPortList(chute):
"""
Get a list of ports to expose in the format expected by create_container.
Uses the port binding dictionary from the chute host_config section.
The keys are expected to be integers or strings in one of the
following formats: "port" or "port/protocol".
Example:
po... | eb97568befca72f6d9cb6c455d8d9ad03b13eebf | 3,628,758 |
from typing import Union
from typing import Tuple
from typing import Any
from typing import Sequence
def _apply_kraus_single_qubit(
kraus: Union[Tuple[Any], Sequence[Any]], args: 'ApplyChannelArgs'
) -> np.ndarray:
"""Use slicing to apply single qubit channel. Only for two-level qubits."""
zero_left = li... | 89b4d1ee99aafc01b8727c7a2c88337fac8e1273 | 3,628,759 |
def get_itk_array(path_or_image):
""" Get an image array given a path or itk image.
Parameters
----------
path_or_image : str or itk image
Path pointing to an image file with extension among
*TIFF, JPEG, PNG, BMP, DICOM, GIPL, Bio-Rad, LSM, Nifti (.nii and .nii.gz),
Analyze, SD... | c8d16f5fb4bc55695183c1cb8b9dd20b57a9909f | 3,628,760 |
def get_datasets_dbpedia(subset, limit):
"""
Loads dbpedia data from files, split the data into words and generates labels.
Returns split sentences and labels.
"""
datasets = dict()
data = []
target = []
target_int =[]
target_names = []
filename = 'data/dbpedia/'+subset+'.cs... | 03f567e814b3ca0227b558177feb8a2165256cfc | 3,628,761 |
def cv_read(path):
"""Read an image using opencv.
Args:
path: path to image
Returns:
numpy array containing the RGB image
"""
image = cv2.imread(path)
image = bgr_to_rgb(image)
return image | 3a3fff8edc5d533c394f611c020cc70986844608 | 3,628,762 |
def get_git_log_raw_output_for_two_commits(commit1, commit2):
"""
Get the git log raw output for a git commit.
:param commit1: the first commit, which occurs earlier than commit2
:param commit2: the second commit, which occurs later than commit1
returns the git command output
"""
if not comm... | 0acf4c81b38968e376de2294be1c6f6c1a47a53e | 3,628,763 |
def get_info_from_service(service, zconf):
""" Resolve service_info from service. """
service_info = None
try:
service_info = zconf.get_service_info("_googlecast._tcp.local.", service)
if service_info:
_LOGGER.debug(
"get_info_from_service resolved service %s to s... | 0d19b5cbe5f8c07fc429f1bcaca3dbcce6978331 | 3,628,764 |
import glob
import sys
import os
def recursive_glob(path):
"""Version-agnostic recursive glob.
Implements the Python 3.5+ glob module's recursive glob for Python 2.7+.
Recursive glob emulates the bash shell's globstar feature, which is enabled
with `shopt -s globstar`.
Args:
path: A path that may cont... | 6a738db431a0230c186f14f6739f1beb20e1ff97 | 3,628,765 |
def _ragged_tile_axis(rt_input, axis, repeats):
"""Tile a dimension of a RaggedTensor to match a ragged shape."""
assert axis > 0 # Outermost dimension may not be ragged.
if not ragged_tensor.is_ragged(rt_input):
rt_input = ragged_conversion_ops.from_tensor(rt_input, ragged_rank=1)
if axis > 1:
retur... | 1bed0ee8f239be0e370a5a853829699c4cfac511 | 3,628,766 |
import re
def camelcase_to_snakecase(value: str) -> str:
"""
Convert a string from snake_case to camelCase.
>>> camelcase_to_snakecase('')
''
>>> camelcase_to_snakecase('foo')
'foo'
>>> camelcase_to_snakecase('fooBarBaz')
'foo_bar_baz'
>>> camelcase_to_snakecase('foo_bar_baz')
... | 05fe02739e8152bc64ab35bd842162b5d7c3ab4c | 3,628,767 |
from deephaven.TableTools import emptyTable
def colorTable():
"""
Returns a table which visualizes all of the named colors.
:return: table which visualizes all of the named colors.
"""
return emptyTable(1) \
.updateView("Colors = colorNames()") \
.ungroup() \
... | 4a359979d9f44b8f6174f4a7939fd98da942cb2d | 3,628,768 |
def not_found(error):
"""Custom error handler for bad requests"""
return jsonify(dict(error = 'Not Found, resource not found')), 404 | 89e125144637258a4b663c489967f6187ce50744 | 3,628,769 |
def string_distance(str1, str2):
"""
计算两个字符串之间的编辑距离
@author: 仰起脸笑的像满月
@date: 2019/05/15
:param str1:
:param str2:
:return:
"""
m = str1.__len__()
n = str2.__len__()
distance = np.zeros((m + 1, n + 1))
for i in range(0, m + 1):
distance[i, 0] = i
for i in rang... | 1dbdcddd13f7a7f5d62e6028a045f224d10984a1 | 3,628,770 |
def best_archiver(random, population, archive, args):
"""Archive only the best individual(s).
This function archives the best solutions and removes inferior ones.
If the comparison operators have been overloaded to define Pareto
preference (as in the ``Pareto`` class), then this archiver will form ... | 20d606f5ea4d76b1c6bd2acfd6bf1017e694f026 | 3,628,771 |
import dotenv
import os
import requests
def elections():
"""Download raw election data from the Election Guide API.
Refer to Election Guide API specifications to understand the data structure
and the meaning of specfic fields.
.. note:: This function requires a ``.env`` file in the project root with... | effa7356346ec69ff48d07d473ef3ffe86267ed4 | 3,628,772 |
import time
import logging
def google_subdomains(name):
"""
This method uses google dorks to get as many subdomains from google as possible
Returns a dictionary with key=str(subdomain), value=GoogleDomainResult object
"""
google_results = {}
results_in_last_iteration = -1
while len(googl... | a2152b5878b85e2db45f9586ea6f7473defda34e | 3,628,773 |
def contacts_per_person_normal_self_30():
"""
Real Name: b'contacts per person normal self 30'
Original Eqn: b'30'
Units: b'contact/Day'
Limits: (None, None)
Type: constant
b''
"""
return 30 | cbb35d2d87ed961a7295615598294d231de032dd | 3,628,774 |
import re
def process_text2phrases(text, clinical_ner_model):
"""
用于从文本中提取Clinical Text Segments
:param text:自由文本
:param clinical_ner_model: Stanza提供的预训练NER模型
:return: List[PhraseItem]
"""
tokenizer = SpanTokenizer()
spliters = getSpliters()
stopwords = getStopWords()
# 将文本处理成正... | c92e3bc458ee75b472cf4766b7d6111004589a62 | 3,628,775 |
def get_all(isamAppliance, check_mode=False, force=False):
"""
Receives all services
"""
return isamAppliance.invoke_get("Receiving all Services", module_uri) | 67f6939c1b7b30898064c1b196bff852424e90e7 | 3,628,776 |
from scipy.stats import norm
def numeric_outlier(feature, keep_rate=0.9545, mode='right', feature_scale=None):
"""feature clip outlier.
Args:
feature: pd.Series, sample feature.
keep_rate: default 0.9545,
method: default 'right', one of ['left', 'right', 'both'], statistical dist... | 6d675cad7694fa6481e979f19dc35b9e99cdff38 | 3,628,777 |
def elk_index(hashDict):
""" Index setup for ELK Stack bulk install """
index_tag_full = {}
index_tag_inner = {}
index_tag_inner['_index'] = "hash-data"
index_tag_inner['_id'] = hashDict['hashvalue']
index_tag_full['index'] = index_tag_inner
return index_tag_full | 9adcc529b88b319180e223ba9e47bda51e628478 | 3,628,778 |
def build_2d_gauss_data(mu_1, mu_2, sig_1, sig_2, samples, changes={},
w=50, alpha=0.1, lags=0):
"""Build a bivarite dataset following a Gaussian distribution.
Parameters
----------
mu_1 : float
Mean of x_1.
mu_2 : float
Mean of x_2.
sig_1 : float
... | 4b523e4c417fc223a19a1630004d0479fbe02b42 | 3,628,779 |
def parse_between_expression(var_dict, variable, expression_dict):
"""
Takes an integer variable and a string:string expression_dict. The key string is a semicolon-separated expression
denoting the lower and upper bounds of the value it can match, while the value string is a simple arithmetic
expression... | 221c1d6d5da3f079fb9bad6f9a6908a036720d7c | 3,628,780 |
def get_tag(el):
""" :returns: `geographic_msgs/KeyValue`_ message for `<tag>` *el* if any, None otherwise. """
pair = None
key = el.get('k')
if key != None:
pair = KeyValue()
pair.key = key
pair.value = get_required_attribute(el, 'v')
return pair | 2650603e5b88a51cef3dce3ef29478c3ccda79ca | 3,628,781 |
from typing import Dict
from typing import Any
from typing import Tuple
def json_to_transactions(json_data: Dict[Any, Any]) -> Tuple[Transaction, ...]:
"""
Convert json data to tuple of transaction objects.
Parameters
----------
json_data :
The transactions data where the values are hexad... | 2444e778331874eff4b2b385b0b9aab113a436c2 | 3,628,782 |
def textureLightingCost(texParam, img, vertexCoord, sh, model, renderObj, w = (1, 1), option = 'tl', constCoef = None):
"""
Energy formulation for fitting texture and spherical harmonic lighting coefficients
"""
if option is 'tl':
texCoef = texParam[:model.numTex]
shCoef = texParam[model... | 95a54db4eba8ac799cde237805999ee47078d2ab | 3,628,783 |
def find_reaction_by_index(rxn:list,num:int)-> object:
"""
find reactions by chemkin reaction index
:param rxn: (list) rmg reaction list
:param num: (int) chemkin reaction index
:return: rmg reaction
"""
#x1 = []
for react in rxn:
if react.index==num:
#x1.append(react... | 99e98bd29fbce92d538e41f6dda124be2c861dc1 | 3,628,784 |
def map_contributor(contributor_dict, role_idx=0):
"""Map the DMP's contributor(s) to the record's contributor(s)."""
cid = contributor_dict["contributor_id"]
identifiers = (
{cid["type"]: cid["identifier"]}
if is_identifier_type_allowed(cid["type"], contributor_dict)
else {}
)
... | d2e55613bc17e3154d557c7e9104b9f0b3eec0a7 | 3,628,785 |
def timeIntegration(params):
"""
TIMEINTEGRATION : Simulate a network of aLN modules
Return:
rates_exc: N*L array : containing the exc. neuron rates in kHz time series of the N nodes
rates_inh: N*L array : containing the inh. neuron rates in kHz time series of the N nodes
... | 8f97380549d58e6b20a6df4ede3e16fd84b19d57 | 3,628,786 |
def string_similarity(s1, s2):
"""
Get a float representation of the difference between 2 strings.
Args:
s1: string
s2: string
Returns: float
"""
return SequenceMatcher(None, s1, s2).ratio() | 42faeb337edade5290d58a9f712d8de9a51118f5 | 3,628,787 |
from re import T
import torch
def pinv(mat: T.FloatTensor) -> T.FloatTensor:
"""
Compute matrix pseudoinverse.
Args:
mat: A square matrix.
Returns:
tensor: The matrix pseudoinverse.
"""
U, s, V = torch.svd(mat)
S = unsqueeze(s.reciprocal(), axis=0)
return multiply(V,... | 0727e4b980cf1284920e431ed90e2fa5922083d2 | 3,628,788 |
from typing import Mapping
def get_remappings_full() -> Mapping[str, str]:
"""Get the remappings for xrefs based on the entire xref database."""
return _get_curated_registry()["remappings"]["full"] | 89dbf2f65a628ec7b5df010df0af5863ad4433ae | 3,628,789 |
def attention(img, att_map):
"""
Inputs:
img -- original image
att_map -- attention map, in this case shape (7,7) or (7,7,1,1) else.
To visualize just imshow new_img
"""
att_map = np.reshape(att_map, [7,7])
att_map = att_map.repeat(32, axis=0).repeat(32, axis=1)
att_map = n... | 262e33d7ec2d4ed0c97acccebc9e98ce8d35babe | 3,628,790 |
import scipy
def _winsorize_wrapper(x, limits):
"""
Wraps scipy winsorize function to drop na's
"""
if hasattr(x, 'dropna'):
if len(x.dropna()) == 0:
return x
x[~np.isnan(x)] = scipy.stats.mstats.winsorize(x[~np.isnan(x)],
... | 49cade19f486d596241ef5eaf18c2a8c3c7a078f | 3,628,791 |
def haversine(lon1, lat1, lon2, lat2, unit = 'km'):
"""Calculate the great circle distance between two lat/lons.
Adapted from https://stackoverflow.com/questions/4913349
Parameters
----------
lon1 : :obj:`float` or vector of :obj:`float`
Longitude of 1st point
lat1 : :obj:`float` or ve... | 09aabd13b60b863d38199a9e156f4d2240e0903e | 3,628,792 |
def get_datatype() -> str:
"""Returns a user specified datatype to be used elsewhere.
Returns
-------
desired_datatype: str
User specified datatype from list.
"""
data_func, data_args = get_inquirer("choices")
data_args["choices"] = DATATYPE_NAMES
datatype_call = data_func(**dat... | 3b0a2d187dc61336b3d23e9c2ae88347a2859b5f | 3,628,793 |
def stereonet2xyz(lon, lat):
"""
Converts a sequence of longitudes and latitudes from a lower-hemisphere
stereonet into _world_ x,y,z coordinates.
Parameters
----------
lon, lat : array-likes
Sequences of longitudes and latitudes (in radians) from a
lower-hemisphere stereonet
... | 3ecb65cf60bed31199745df50199a6e666f9e3fd | 3,628,794 |
def sky_to_cartesian(rdd, degree=True, dtype=None):
"""
Transform distance, RA, Dec into cartesian coordinates.
Parameters
----------
rdd : array of shape (3, N), list of 3 arrays
Right ascension, declination and distance.
degree : default=True
Whether RA, Dec are in degrees (`... | 9e70245ccb2c6c0c97a4be4e2e5c00398d119564 | 3,628,795 |
def delete(id):
"""Delete post function"""
data = Post.query.get(id)
db.session.delete(data)
db.session.commit()
flash("Post successfully deleted")
return redirect(url_for(".index2")) | 4988c197429208e8e54a52370706aa211067cc5d | 3,628,796 |
import six
def repeat_n_times(n, fn, *args, **kwargs):
""" Repeat apply fn n times.
Args:
n: n times.
fn: a function or a list of n functions.
*args: additional args. Each arg should either be not a list, or a list
of length n.
**kwargs: additional keyword args. Ea... | f08437f560f1ec6eb967c4236e017a6b123df8e0 | 3,628,797 |
def get_submissions(request, domain_id=0):
""" Takes a POST containing a tar of all MD5's
and returns a tar of all missing submissions
Heh, this is explicitly against good REST methodology
We leave this inside the django-rest 'Resource' so we can
use their authentication tools
"""
try:... | c689f429665867e1b74f8ca8d11bdcfc3e89930f | 3,628,798 |
import uuid
def generate_unique_str(allow_dashes=True):
"""
Generate unique string using uuid package
Args:
allow_dashes (bool, optional): If true use uuid4() otherwise use hex that will skip dash in names. Defaults to True.
"""
if allow_dashes:
unique_str = str(uuid.uuid4())
... | 9a08364837ea719454b885fcb344631005e7a610 | 3,628,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.