content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def affine_jac_obs_element(prep, error, observable):
"""
Computes the Jacobian matrix element for a Affine error: how the
expectation value of `observable` changes with respect to the rate of
`error` when preparing state `prep`.
Note: Affine error maps leave qubits corresponging to I's in
`erro... | 3c07be3eb88dbc93c303949370e4baa1628aaf37 | 65,513 |
def encode_genotype(nucleotides):
"""Parses a string representing a set of nucleotides observed at a loci,
and returns the corresponding IUPAC code. Commas are allowed, but are
simply ignored if found in the string. Does not handle lower-case
nucleotides, due to lack of clear criteria for mixed case inp... | 3236a3d3ac858d6f10c7a38e82b91c44893928b8 | 65,514 |
from typing import Tuple
def spatial_transformation(inputs: tf.Tensor,
theta: tf.Tensor,
output_size: Tuple[int, int] = None
) -> tf.Tensor:
"""Transform input images according to theta. If `output_size` is provided, also rescales im... | fc02cf4e8afb1d93d4893405b206cb5493a7cfe7 | 65,515 |
def _create_dummy_archive(hs):
"""Create empty archive so that GHC has some input files to work on during
linking.
See: https://github.com/facebook/buck/blob/126d576d5c07ce382e447533b57794ae1a358cc2/src/com/facebook/buck/haskell/HaskellDescriptionUtils.java#L295
Args:
hs: Haskell context.
Returns:
... | a686398fc621050400895a2d541f0c41ba65ee98 | 65,516 |
import torch
def load_robust_model(model_name, device):
"""loads robust model specified by modelname"""
model = models.resnet50(pretrained=True)
model_paths = {
'ANT+SIN': './Models/ANT_SIN_Model.pth',
'ANT': './Models/ANT_Model.pth',
'Speckle': './Models/Speckle_Model.pth',
... | 3971c0236bdbb09e7258d3f6895779453f38fc78 | 65,517 |
def render_html_from_fields(fields, template_url):
"""Returns html rendering of timeline item with custom fields data."""
template = jinja_environment.get_template(template_url)
return template.render(fields) | eff3a5c33a961c3b2ea939b877de4bdf7a00a3f5 | 65,518 |
from typing import Optional
def greater_sum_bst(root_node: Node) -> Node:
"""
time complexity: O(n)
space complexity: O(n)
"""
def construct(node: Optional[Node]) -> Optional[Node]:
"""
Reverse inorder traversal
"""
nonlocal total
if node:
const... | d4a4039397f5f41a9723ca7d51e0665d91dcb2dc | 65,519 |
def flatten_df(df):
"""Flatten the df to an array
Args:
df(pd.DataFrame): a dataframe
Returns:
an array
"""
return df.values.flatten() | 4faedf1059fa60c2ee3af95cd6f01e7d3cadd97e | 65,520 |
from typing import List
from typing import Dict
from typing import OrderedDict
def build_bluff_data_year_month_dict(database_connection: mysql.connector.connect
) -> List[Dict]:
"""Returns an OrderedDict that will be used to populate
Bluff the Listener data for all years an... | 9fa6131ff57f8ea29fd628a31e7de2c267e0d1ea | 65,521 |
def aes_ecb(key: bytes, b: bytes, decrypt: bool=False) -> bytes:
"""AES ECB mode.
:param key: The cipher key.
:param b: The buffer to be encrypted/decrypted.
:param decrypt: Whether we should encrypt or decrypt.
:returns: The encrypted/decrypted buffer.
"""
assert len(b) % 16 == 0
asse... | 6ca780353ceec49149fffcaa286b4654f2ee243f | 65,522 |
import random
def get_random_num(number):
""" xxx """
maxnum = int(number)
return random.randint(1, maxnum) | 9ad5a62ed510f4153b91f2a5c982ef83373dfca3 | 65,523 |
def get_auc(labels, preds, n_bins=10000):
"""ROC_AUC"""
postive_len = sum(labels)
negative_len = len(labels) - postive_len
total_case = postive_len * negative_len
if total_case == 0:
return 0
pos_histogram = [0 for _ in range(n_bins+1)]
neg_histogram = [0 for _ in range(n_bins+1)]
... | 4a216bb6b6ce8a992163fe92c2fb3b8642995dfb | 65,524 |
def fastdance(progs, compiled_moves):
"""Dance faster using parsed moves."""
for (func, args) in compiled_moves:
progs = func(progs, *args)
return progs | a3d0f68b3a75c79cc489d17aa8eefaf64a351d2b | 65,525 |
from typing import Counter
def duplicated(v):
"""Returns a generator expression of values within v that appear more than
once
"""
return (x for x, y in Counter(v).items() if y > 1) | bf854dfde83c9d998f3f0b5f5553254be6347a4c | 65,526 |
def _readonly_array_copy(x):
"""Return a copy of x with flag writeable set to False."""
y = x.copy()
y.flags["WRITEABLE"] = False
return y | ffd973bb354a642362a7382934f879c9dfa95c3b | 65,527 |
def filter_in(values, vmin=None, vmax=None):
"""
Handles 'in' filters
op: ['in', 'not in']
values: iterable of values
vmin, vmax: the range to compare within
Returns
-------
True or False
"""
if len(values) == 0:
return True
if vmax == vmin and vmax is not None and ... | e64a5f05216786c618c616e61c562ca1aad78b59 | 65,528 |
def _variable_to_parameter(param_list, variable=None, variable_name=""):
"""
Takes either a Variable object or a the name of a Variable object and
returns the corresponding Parameter object. If variable is specified,
and it has a value, the parameter's expr is accordingly specified.
Args:
p... | b720dbcdf6e436f306d4cb0ecc87e810dd569e49 | 65,530 |
def parse_na(txt: str) -> (MetarData, Units): # type: ignore
"""
Parser for the North American METAR variant
"""
units = Units(**NA_UNITS) # type: ignore
clean = core.sanitize_report_string(txt)
wxresp = {'raw': txt, 'sanitized': clean}
wxdata, wxresp['remarks'] = core.get_remarks(clean)
... | 7cad2889d5ddf82368c799c0e9c0cacae30fed23 | 65,532 |
import re
def str_list_to_list_str(str_list, regex_pattern='[A-Z]\d+'):
"""
Turn a string of a list into a list of string tokens.
Tokens determined by regex_pattern
"""
p = re.compile(regex_pattern)
return p.findall(str_list) | 99d3bbccadc0676dac6854ee717f8aef3bb878a6 | 65,533 |
import re
def parse_readme_unicode_version(readme_content):
# type: (str) -> UnicodeVersion
"""
Parse the Unicode version contained in their `ReadMe.txt` file.
"""
# "Raw string" is necessary for \d not being treated as escape char
# (for the sake of compat with future Python versions).
# ... | cae4710a6e8d3ec82dc9398509bdd09f3aeccc8c | 65,534 |
import inspect
import logging
import functools
def _instantiable_base_dists():
"""Computes the table of mechanically instantiable base Distributions.
A Distribution is mechanically instantiable if
- The class appears as a symbol binding in `tfp.distributions`;
- The class defines a `_params_event_ndims` met... | 1f37f8aafbd079a1a071ec6d2db931f1723a1c14 | 65,535 |
def ask(string, **default):
"""Ask the user a question providing the option to choose "yes", "no", or "cancel".
If any of the options are specified as a boolean, then it is
assumed that this option will be the default. If the user
chooses "cancel", then this value will be returned instead of
the va... | a54118950dc893601087db99a72e973e3b263a58 | 65,536 |
from typing import List
def get_trace_events(trace_directory: str) -> List[DictEvent]:
"""
Get the events of a trace.
:param trace_directory: the path to the main/top trace directory
:return: events
"""
events: List[DictEvent] = [
_event_to_dict(event) for event in _get_trace_ctf_even... | 7e2d9037ac0653fba2d7884dbc3a0b367047c603 | 65,539 |
def zero_pad(x, n):
"""
Pad an array to length `n` with zeros.
If the original array length is greater than `n`,
a copy of the original array is returned with it's length unchanged.
"""
nx = len(x)
if n < nx:
n = nx
new = np.zeros((n, *x.shape[1:]), dtype = x.dtype)
new[:nx] ... | 961b436be4b13fa21099ad4c99d91ec02da071dd | 65,540 |
from typing import Iterator
import tqdm
def get_statistics(samples: Iterator):
"""
Input:
samples: [{
"text":
"summary":
}]
Output:dict:
usage:
you can test it with following code:
from datalabs import load_dataset
from aggregate.summariz... | ba653de272c8207ec7ebc4afd43cdcb659653054 | 65,541 |
def isin(collection) -> InUnit:
"""
Overview:
Containment check, the same as ``in_(keep(), collection)``.
:param collection: Collection to be checked.
:return: Unit for checking containment.
Examples::
>>> from argsloader.units import isin, add, mul
>>> u = add.by(2) >> mul... | 82f1d3a14b6ed691b3fc9e214195b2521c1e2564 | 65,544 |
def delete_user_id(activation_id, user_id):
"""
makes request to ->
/api/v4/activations/{activation_id}/
users/{user_id}
Revoke access of a user from activation
Parameters
----------
activation_id : int, required
unique id of activation/system
user_id : int, required
... | 8dcce8a3fd52958d446df504eebac41a0e9ca5a4 | 65,546 |
def intrinsic_char(args):
"""Return the UTF-8 character value for the ordinal number or numbers
given in the argument list."""
return MUMPSExpression(
lambda a=args: _char(a)
) | ae2a3c622908fa73d1df400680e5cc0bb1728df7 | 65,547 |
import yaml
def get_configuration(config: str) -> dict:
"""
Open Config YAML file
"""
with open(config) as f:
configuration = yaml.load(f, Loader=yaml.FullLoader)
return configuration | c275b80363bca4a8587b7f09ead17a85f9b8dfda | 65,549 |
def flagger(value):
"""
Conversion routine for flags. Accepts ints or comma-separated
strings.
:param str value: The value to convert.
:returns: A value of an appropriate type.
"""
try:
# Convert as an integer
return int(value)
except ValueError:
# Convert as ... | cdc3fab338fd7f25499e25593302fb209f9be2a4 | 65,551 |
import progressbar
def compare_methods(im1,im2, ntests=100, noise=np.std,
usfac=201, **kwargs):
"""
Perform tests with noise added to determine the errors on the
'best-fit' offset
Parameters
----------
usfac : int
upsampling factor; governs accuracy of fit (1/usfac is best acc... | 1606ed610827968f862681df5c0aad60715faa06 | 65,552 |
def method_comparison_boxplot(*,
title="Accuracy of models created with each method\n",
data, # pd.DataFrame with the results,
figsize=(10,4),
# ...
col_with_results, # df colname with values to display, eg: test_accuracy ...
col_with_group_names, # df colname with values t... | 9dc6d10487f202b8eeb284e0120fa2f6970db847 | 65,553 |
def is_present(input: Input) -> bool:
"""Returns true if the stream for this input is indeed found.
If we can't probe this input type, assume it is present."""
return bool(_probe(input, 'stream=index') or
input.input_type in TYPES_WE_CANT_PROBE) | 90e470dbf5088d19cbb93a5218bbcc6ccc478bdb | 65,554 |
def get_accuracy(testSet, predictions):
"""Calculate accuracy."""
correct = 0
for x in range(len(testSet)):
if testSet[x][-1] in predictions[x]:
correct = correct + 1
return correct / float(len(testSet)) * 100 | afb8b781fff25373c764d49457422fd3d676019d | 65,555 |
def extract_positive_gfc(c: np.ndarray) -> np.ndarray:
"""
Extract global functional connectivity from connectivity matrix.
The GFC is compute as the mean FC of each time series with all the others.
Args:
c:
2-dimensional numpy array where each entry is the correlation
... | 18acdb5a4d5c801ac4aa2b8704ac615dab003eed | 65,556 |
import time
def time_func(func, kwargs):
"""
Time a function. Return the time it took to finish and subsequent result.
"""
start = time.time()
res = func(**kwargs)
finish = time.time() - start
return finish, res | 78f73058a90048f8de24915f1f8ba56bda79cc6a | 65,557 |
def remove_common_path(path1, path2):
"""
Removes path that is common in both given paths
:param path1: str
:param path2: str
:return: str, path without the path shared by both given paths
"""
path1 = clean_path(path1)
path2 = clean_path(path2)
split_path1 = path1.split('/')
sp... | d61c0069c7ed2bf47215a13510d6b2df8263dc7a | 65,558 |
def verify_election_partial_key_challenge(
verifier_id: GUARDIAN_ID, challenge: ElectionPartialKeyChallenge
) -> ElectionPartialKeyVerification:
"""
Verify a challenge to a previous verification of a partial key backup
:param verifier_id: Verifier of the challenge
:param challenge: Election partial ... | a33c4c1c43122f99d0fd6d4baa65bbc4708dfe0e | 65,559 |
def number_days(year,month,day):
"""
return the number of days between the date and 0 BC
"""
monthdays = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
return year * 365 + monthdays[month-1] + day | 8858d8d19b50970aff4b831e62f4335e29722877 | 65,560 |
def evaluation(logits, labels):
"""Evaluate the quality of the logits at predicting the label.
Args:
logits: Logits tensor, float - [batch_size, NUM_CLASSES].
labels: Labels tensor, int32 - [batch_size], with values in the
range [0, NUM_CLASSES).
Returns:
A scalar int32 tensor with the number of... | 7aa6d71ce4d3d222fa0df47e6611dd0e5d222716 | 65,561 |
def delete_gif_route(gif_id: int):
"""DELETE /gifs/<gif_id>
Deletes a gif with specified gif id. Token's "sub" must match
owner's username of the gif, unless an admin.
Args:
gif_id (:obj:`int`): The gif id to modify.
"""
gif = Gif.get_by_id(gif_id)
if not gif:
return {"erro... | 39885946dc34fa6d85b3d03b7fa061ebbbb312d9 | 65,562 |
from typing import Tuple
def _run_ilp(dataset: str, name: str) -> Tuple[int, float, str]:
"""Run ILP on all datasets.
Parameters
----------
dataset : str
Dataset name.
name : str
FCL name.
Returns
-------
Tuple[int, float, str]
Solution size, time, and certifi... | 76b957b762a3661efcb9ac17903d5a05a081edde | 65,563 |
def obtain_combined_clusters(data_a, data_b, label_a = 'Sim A', label_b = 'Sim B', start_frame = 0,
algorithm='kmeans', num_clusters=2, min_dist=12, max_iter=100,
plot=True, saveas=None):
"""
Clusters a combination of two data sets.
Parameters
... | aabd3fe236927a7a64097c17a49725649816cd76 | 65,564 |
def dRELU(x):
"""if x <= 0:
return 0
else:
return 1"""
#return x * (1 - x)
return 1 | ade7095133b44f61c3ce6350abdf5b2251e2c6fb | 65,565 |
import torch
def flatten_tensors(tensors):
"""
Flatten dense tensors into a contiguous 1D buffer. Assume tensors are of
same dense type.
Since inputs are dense, the resulting tensor will be a concatenated 1D
buffer. Element-wise operation on this buffer will be equivalent to
operating individu... | 27ecbb26cf3bb084a0216248f2314519fb735bde | 65,566 |
def gen_end(first_instruction_address):
""" Generate an end record. """
# specify the size of each column
col2_size = 6
# content for each column
col1 = "E"
col2 = hex(first_instruction_address)[2:].zfill(col2_size).upper()
return col1 + col2 | d5df69b33cfb4f99aa9dbc5e003b713637fa1eff | 65,568 |
def zScale(df):
"""
x= np.linspace(0,50)
y, z= np.linspace(0, 50, 50, False, True)
T= np.linspace(0, 200, 50, False)
b= np.arange(0, 200, 200/50) #same as T 200/50 - gives the increment to create same array as T - 1 to 200, with 50 elements
print(b)
b.size
df = pd.Dat... | f9261d3b7089496068562b8085df5bbfad94e68b | 65,569 |
def fit_func_tree(infix,vals):
"""Passing infix string to posfix notation"""
stack = []
stackSize = 0
buff = []
n_vals = len(vals)
for ch in infix:
if is_operand(ch):
if (not stack) or (level_ops[ch] > level_ops[stack[stackSize-1]]):
stack.append(ch)
stackSize += 1
else:
... | 29b1e34a0a1d6757d523805a8025e5c6d48ef21c | 65,571 |
def dashboard():
"""Admin dashboard route."""
return render_template('dashboard.html',
title='Flask-Blueprint Tutorial | Admin Dashboard',
template='dashboard-template account',
body="Account") | e90c9f8f7745ac470bec1c798d2183412e340ed9 | 65,572 |
def is_equal_2_refactorings_list(a, b):
"""
This method implement is_equal method which should return True if two instances of Individual class are equal.
Otherwise it return False.
The duplicate instances are removed from population at each generation.
Only one instance is held to speed up the sear... | 155248bb60ac560af03edd533d4573c9a5801b78 | 65,573 |
import re
def split(combined_unit):
"""
Splits a unit string into magnitude prefix, the base unit, and the power.
:param combined_unit: The unit string.
:returns: A tuple of prefix, base unit, and power.
:rtype: tuple
"""
prefix_re = "(?P<prefix>{})".format(PREFIXES)
unit_re = "(?P<u... | 975d9ad2f05583839bad2a3f7dfa0848de83a0fe | 65,574 |
import tqdm
def sample_magnetization_average(graph, T, Glauber_Runs , beta,positions=None , T_Burn=0, Initial_State=None,control_field=None) :
"""
Average magnetization at the end of the chain
for a specified number of Glauber runs.
For each glauber run we take the average magnetization
for the period after ... | e9eeb5a5d929abae44e0e6928cd9d197463829cb | 65,575 |
from typing import Dict
from typing import Any
def nom_comps(
srs: dd.Series,
first_rows: pd.Series,
ngroups: int,
largest: bool,
bins: int,
top_words: int,
stopword: bool,
lemmatize: bool,
stem: bool,
) -> Dict[str, Any]:
"""
This function aggregates all of the computation... | 1ae2ef8a3f7105518b170419cf413f9c28b35676 | 65,576 |
import re
def filter_subject(subj, cfg):
"""Function: filter_subject
Description: Filter out strings from the message subject line.
Arguments:
(input) subj -> Message subject line.
(input) cfg -> Configuration settings module for the program.
(output) subj -> Filtered message ... | db3e2dcff95ef91b0190e4a3c9a0c9c72113403a | 65,577 |
def name_fmt(name, fmt=NameFormat(0)):
"""Format name for output.
Parameters
----------
name : `ged4py.model.Name`
Person name.
fmt : `NameFormat`, optional
Bitmask combination of `NameFormat` flags.
Returns
-------
name : `str`
Formatted name representation.
... | 0d2173c62a36c3fe35e8946dc9ac115b0a342a57 | 65,578 |
def filter_remove_background(rgb, red_lower_thresh=235, green_lower_thresh=210, blue_lower_thresh=235, output_type="bool"):
"""
Create a mask to filter out pixels which are pre-defined as background
Args:
np_img: RGB image as a NumPy array.
red_lower_thresh: Red channel lower threshold value... | 0320af3ce1a20501e772a2feec4a4268b5a6d059 | 65,579 |
def batch_ispecgram(spec,
n_fft=512,
hop_length=None,
mask=True,
log_mag=True,
re_im=False,
dphase=True,
mag_only=False,
num_iters=1000):
"""Computes inverse ... | 8e6219385ab9d09743e19501c0f3c642ed02138a | 65,580 |
def makeTable(lid,es,TOTAL,TDIR,FDIR,tag,offset=0):
"""Overall textual analysis with rendering of tables"""
#TDIR="/home/r/repos/artigoTextoNasRedes/tables/"
#TDIRf="/home/r/repos/artigoTextoNasRedes/figs/"
ds=es.structs[1]
timest=es.structs[2]
pr=es.structs[-1]
nm=es.structs[4]
B.LANG=[... | a6024aa699376e576552cfc1fd377f57464be7d0 | 65,581 |
def topography_dam(x,y):
"""Complex topography defined by a function of vectors x and y."""
z = -x/100
N = len(x)
for i in range(N):
# Step
if 2 < x[i] < 4:
z[i] += 0.4 - 0.05*y[i]
# Permanent pole
if (x[i] - 8)**2 + (y[i] - 2)**2 < 0.4**2:
z[i]... | 1ac128fe8ab0852ca42df9e54168617f47a79bee | 65,582 |
import math
def extraterrestrial_irrad(utc_datetime, latitude_deg, longitude_deg, SC=SC_default):
"""Equation calculates Extratrestrial radiation. Solar radiation incident outside the earth's
atmosphere is called extraterrestrial radiation. On average the extraterrestrial irradiance
is 1367 Watts/meter2 (... | 1f872404b6e3f289a90c05ac8e985c1a37f8512a | 65,583 |
def get_json(item):
"""nasty hack to get round requests api change"""
if callable(item):
return item()
else:
return item | 13b549063503fc1bf8857a23af38d905735c901e | 65,585 |
def variantMetadata_object(processed_request):
"""
Builds the variantAnnotation object.
Since we only have one model for this object we keep it simple.
"""
beacon_variant_metadata_v1_0 = {
"default": {
"version": "beacon-variant-metadata-v1.0",
... | 4bf6dc519fcca02ea63d0f94af55adffe29ad9f8 | 65,586 |
import requests
def get_file_from_net(url):
"""
Gets any file from the net and prints it if possible (i.e if Content-Type is text.
:param url: Address of resource to be read
:return: Text of possible, otherwise throw exception.
"""
try:
response = requests.get(url)
if 200 <= ... | 47aa4d3ca8a439c4bbbe90da654193d40ad1a6b5 | 65,587 |
def _is_filtering_only_by_id(options):
"""
Funcao que checa se a query tem como unico filtro o ID de uma entidade.
Args:
options (str): As opções da query.
Returns:
(bool): Verdadeiro, se o unico filtro é na propriedade ID. False, do contrário.
"""
if "$select" in options:
... | 984074de92f3dc2fd9b300cdaf7f500c77e96269 | 65,588 |
def BetaBinomial(data, name, shape=1, ranges=(1, np.inf)):
"""
Constructs a BetaBinomial distributions with RV = X ~ BetaBinomial(n, a, ß)
Returns: Tuple[Pymc3.distributions.BetaBinomial, Tuple[String, int, float, float]]
----------
- Returns a tuple with distributions paired with the [name, nu... | de04b84244fbd67377242d549bb668ca46d39fc8 | 65,590 |
def to_unicode_repr( _letters ):
""" helpful in situations where browser/app may recognize Unicode encoding
in the \u0b8e type syntax but not actual unicode glyph/code-point"""
return repr(_letters) | 379331356ea4f4b3763a16c3d0e531e984ec7a85 | 65,591 |
def getExperimentalDataPaths():
"""
getExperimentalDataPaths()
"""
print("------------------------------------------------------------")
print("PLEASE ENTER PATHS OF EXPERIMENTAL DATA")
print("")
print("IF THERE ARE MULTIPLE DATA FILE YOU WANT TO TOMOGRAPHY,")
print("ENTER ALL PATHS SE... | f9a63ca89de6c636fc8d6d7499c9eaf9933c9b4c | 65,592 |
import torch
def load_pytorch_weights_and_quant(path, config):
"""
Load the weights from the pytorch checkpoint
"""
state_dict = torch.load(path, map_location='cpu')["model"]
tensor_dict = {onnx_to_trt_name(name):val.numpy() for name, val in state_dict.items()}
return get_onnx_weight_dict(tens... | ef7defde0c20eccdc37bf0b13259257f6da26707 | 65,593 |
import uuid
def correct_captcha(sub):
"""When a correct control challenge is submitted, the unknown map tile result is recorded"""
print("correct captcha")
tile = CaptchaTilesTable()
tile.year = sub['year']
tile.x_coord = sub['x']
tile.y_coord = sub['y']
tile.uuid = uuid.uuid4().hex
t... | 1763e866a4a22713b48f0028e090dfcf5e9f3e13 | 65,594 |
def find_closest_stores(friends, stores):
"""
Finds the closest store to each friend based
on absolute distance from the store.
Parameters:
friends: Dictionary with friend names as keys
and point location as values.
stores: Dictionary with store names as keys
and point l... | ca879f6f442a4d734bf9e3c7b0313cd31ea2a026 | 65,595 |
def sum_nth_i(seq, n):
""" takes a list seq and a number n that is
bigger then 0 and takes the sum of the n number """
if n > 0:
res = 0
for i in range(n-1, len(seq), n):
print(i)
res += seq[i]
return res
else:
print("n needs to be bigger then 0 \n... | 3ee7eec74b73449038d735355f29b3b57c9402b5 | 65,596 |
def levenshtein(s1, s2):
"""
Given two strings s1 and s2, returns the levenshtein
distance between the two strings.
Credit: http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance
"""
if len(s1) < len(s2):
return levenshtein(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:... | 9fa02d9c0bc43291e8de44ff9101e4afbbef49a5 | 65,597 |
def prepare_removepoints_log(mod, target_member, case):
"""Prepares log for point removal
Parameters
----------
mod : discord.Member
"Mod who removed the points"
target_member : discord.Member
"Member whose points were removed"
case
"Case object"
"""
... | 31d576acc4349c049dffad99acd6ccf6fcb77c00 | 65,598 |
def solve_market_side_with_exogenous_price(
bids, price,
fees):
"""
Clears the market based on an external price.
First it removes all biders that are not willing
to trade at the given price, and then it fits
the best allocation.
Fees are calculated based on users that were
willing b... | 408a9e2f1362fa11eb4e85394600aafcf4223936 | 65,599 |
def _func_and(current, checks):
"""Implementation of And."""
return all(check(current) for check in checks) | a778d9193c958729f40e09feb3903350b2d3054b | 65,600 |
def add_eo3_parts(doc, tol=None):
"""Add spatial keys the DB requires to eo3 metadata
"""
return dict(**doc,
**eo3_grid_spatial(doc, tol=tol)) | 5340d2134568e2836bb368acd6a48228d95ffa45 | 65,601 |
from typing import Dict
def get_potential_fields(attrs: Dict) -> Dict:
"""
Gets all the fields in current class namespace that are Fields.
:param attrs: current class namespace
:type attrs: Dict
:return: extracted fields that are ormar Fields
:rtype: Dict
"""
return {k: v for k, v in ... | 8594286f7331ef36b9d77d9e0fcfb7e57d1b3331 | 65,602 |
def _hilbert_integer_to_transpose(p, h):
"""Store a hilbert integer (`h`) as its transpose (`x`).
Args:
p (int): iterations to use in the hilbert curve
h (int): integer distance along hilbert curve
Returns:
x (list): transpose of h
(n components with values between... | aa2166cdde6ebf978a1514c370f9c0dcdc2d703a | 65,603 |
def plot_sphere(ax=None, radius=1.0, p=np.zeros(3), ax_s=1, wireframe=True,
n_steps=20, alpha=1.0, color="k"):
"""Plot sphere.
Parameters
----------
ax : Matplotlib 3d axis, optional (default: None)
If the axis is None, a new 3d axis will be created
radius : float, optional... | 56c75eb6547c51d85a04a85ef50be804f1a28eb0 | 65,605 |
def __parse_num_den(num: ndarray, den: ndarray):
"""
Reduce the two linears objects as a single item
The reduction follows the matrix_rn_representation protocol:
=======================
INTER-LINEARS REDUCTION
=======================
-> checks for possible reductions between numerator... | 0cc010b4590dfebc1a4eaf6ce37793a7f498fcb9 | 65,606 |
def get_auc_score(result_dataframe, # result dataframe for a certain run
key): # the name of the result to get the curve for
""" Get the Area Under the Curve for the indicated key in the dataframe.
Args:
result_dataframe: Result dataframe for a certain run
key: The name of t... | f1609fae173a498a2f38214010068d52bd0758a0 | 65,607 |
from typing import Optional
from typing import Sequence
def method_def(
name: BaseOperatorName,
module: Optional[str],
overloads: Sequence[PythonSignatureNativeFunctionPair],
*,
method: bool
) -> str:
"""
Generate method def entry.
"""
pycname = get_pycname(name)
if is_noarg(o... | 309943490d5268b50e72aca9e330624450747682 | 65,608 |
import torch
def normalize_quaternion(quaternion, eps=1e-12):
"""Normalizes a quaternion.
The quaternion should be in (w, x, y, z) format.
Parameters
----------
quaternion: torch.FloatTensor (B4)
Input quaternion to normalize.
eps: float, default: 1e-12
Epsilon value to avoid... | 8e1de3b25753b982f0a06b0c6aa9fb98d5360e86 | 65,610 |
def get_user_id(email):
"""Fetches user's id.
Args:
email: user's email address.
Returns:
User ID of user with given email address.
"""
try:
user = User.query.filter_by(email=email).one()
return user.id
except:
return None | 31204d23e38c6bb55e7d4e70144a10e87e64203a | 65,612 |
from meerschaum.utils.misc import choose_subaction
from typing import Optional
from typing import List
from typing import Any
def install(
action : Optional[List[str]] = None,
**kw : Any
) -> SuccessTuple:
"""
Install Meerschaum plugins or Python packages.
"""
options = {
'... | 2d7ece9237843f96b776bb0f1161bec1a40d157a | 65,614 |
def eval_py(distmat, q_pids, g_pids, q_camids, g_camids, max_rank=50):
"""Evaluation with market1501 metric
Key: for each query identity, its gallery images from the same camera view are discarded.
"""
num_q, num_g = distmat.shape
if num_g < max_rank:
max_rank = num_g
print("... | 81f248829b9c357eae72bc26441ca09ae55d8124 | 65,615 |
def compare_events(a: EnterEvent, b: EnterEvent) -> int:
"""Compares 2 Enter events based on the timestamp of the first human event
:param a: The first enter event
:param b: The second enter event
:return: Returns -1 if `a` is before `b`, 1 if `b` is before `a`, and 0 if `a` and `b` occur at the same t... | e5d7a3f2d48b13ee5773ca3d9590453eb603b795 | 65,616 |
def _extra_gas_dndfeh(s, feh, p, M):
""" Not normalized! """
z = (10**feh)/p
return z * (1 + s*(1-1/M)) / (1/(1-s/M) - 2*z*(1-1/M)) | 485880edfc10be58716a31f25edd4d1c1188867e | 65,617 |
def bash_quote(*args):
"""Quote the arguments appropriately so that bash will understand
each argument as a single word.
"""
def quote_word(word):
for c in word:
if not (c.isalpha() or c.isdigit() or c in '@%_-+=:,./'):
break
else:
if not word:
... | cb25adb60ea98cb6887e89a6a4f5097bb8f4843f | 65,618 |
def count_change(amount):
"""Return the number of ways to make change for amount.
>>> count_change(7)
6
>>> count_change(10)
14
>>> count_change(20)
60
>>> count_change(100)
9828
>>> from construct_check import check
>>> # ban iteration
>>> check(HW_SOURCE_FILE, 'count_c... | 8926533e846f67474ebe0ea8983089010af28ed0 | 65,619 |
from datetime import datetime
def datetime_ceil(dateval: datetime) -> datetime:
"""Round the given datetime object upwards."""
if dateval.microsecond > 0:
return dateval + timedelta(seconds=1, microseconds=-dateval.microsecond)
return dateval | d77531000d8fbda01d4631193e4e09a5e13611a7 | 65,621 |
import numpy
def asind(slope: ArrayLike) -> ArrayLike:
"""Return the arcsine of an angle specified in degrees.
Returns
-------
float
An angle, in degrees.
"""
return numpy.degrees(numpy.arcsin(slope)) | f6d87036f5d1ae3c5879f54f457e34818e6b478b | 65,622 |
def on_status():
"""
command /status: show bot status
"""
return bot.send_message("Listening Motion run") \
if bot.is_listen else bot.send_message("Listen Motion doesn't run") | c22315512c3727430c363b8877480393f0def52e | 65,623 |
def XfmrCode(*args):
"""Name of an XfrmCode that supplies electircal parameters for this Transformer."""
# Getter
if len(args) == 0:
return get_string(lib.Transformers_Get_XfmrCode())
# Setter
Value, = args
if type(Value) is not bytes:
Value = Value.encode(codec)
lib.Transf... | f11b4d43ec6c1d4a4b5cb36b8fbb466dc8a4cd73 | 65,624 |
def move(rel_src_path: str, rel_dest_path: str) -> None:
"""paths are relative to users root folder (ROOT/user_X/).
Folders that don't exist are created"""
client_logger_sync().info(f"Move file: rel_src_path={rel_src_path}, rel_dest_path={rel_dest_path}")
abs_src_path = path_utils.rel_user_path_to_abs(r... | fe44b5223d29520a8d698ba6f47b0cd580a5c016 | 65,626 |
def blackholes(data_in,
filter_spec_samples=None,
filter_spec_variables=None,
label_rows_with=None,
label_cols_with=None,
group_rows_by=None,
group_cols_by=None,
missing_color='black',
backkground_col... | 633b39914929dc40525de9411a362a3adc0733dd | 65,627 |
def get_area(root):
"""Extracts the ash cloud total area
Values returned are in this order"
1. Total ash area
2. Total ash area unit"""
area = root.alert.total_area.attrib.get('value')
area_unit = root.alert.total_area.attrib.get('units')
return area, area_unit | ea5a908e4226359aeb962f66c4ed4691d8d93a1b | 65,628 |
from typing import Iterable
from typing import Any
def replace_na(
data: Iterable[Any],
data_or_replace: Any = None,
replace: Any = None,
) -> Any:
"""Replace NA with a value
This function can be also used not as a verb. As a function called as
an argument in a verb, data is passed implicitly... | ffebb0d26b58766e3d4c7c6780e92d31e95f5f98 | 65,629 |
def mid_point(p1, p2):
"""
计算中点
"""
x = (p1[0] + p2[0]) // 2
y = (p1[1] + p2[1]) // 2
return [x, y] | 2630e4158ea6414242b05ada987f2cf020442339 | 65,630 |
def extract_task(tsk, tsk_lst):
""" Searches for a task in the task lst and if found:
the corresponding keywords and values will be returned
Function only works if task is present in the list one time.
:param tsk: task to extract information for
:type tsk: str
:param tsk_ls... | b8c3e68ca5d00227e51cbd0b869cbe09ddd3123f | 65,631 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.