content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def getChanprofIndex(chanprof, profile, chanList):
""" List of indices into the RTTOV chanprof(:) array corresponding to the chanlist.
NB This assumes you've checked the chanlist against chanprof already.
"""
ilo = sum(map(len, chanprof[:profile-1]))
ichanprof = []
for c in chanList:
... | e61e210e8b05fdfbf3a769f4b5b388d765d436b9 | 33,168 |
def _get_blob_size_string(blob_key):
"""Return blob size string."""
blob_size = blobs.get_blob_size(blob_key)
if blob_size is None:
return None
return utils.get_size_string(blob_size) | 5f223101c71d641540aef97bda1b59f3bc7dfa7c | 33,169 |
def masked_softmax_full(input_layer, n_nodes, batch_size):
"""
A Lambda layer to compute a lower-triangular version of the full adjacency.
Each row must sum up to one. We apply a lower triangular mask of ones
and then add an upper triangular mask of a large negative number.
After that we return the... | d48d48a90cb8ac80614ea54ee3a3f2e56def3a69 | 33,171 |
import collections
import socket
def match_backends_and_tasks(backends, tasks):
"""Returns tuples of matching (backend, task) pairs, as matched by IP and port. Each backend will be listed exactly
once, and each task will be listed once per port. If a backend does not match with a task, (backend, None) will
... | 9fab7e8b8f1a3c7a3cdbfb271fc5a4aac4807b03 | 33,172 |
def _drop_path(x, keep_prob):
"""
Drops out a whole example hiddenstate with
the specified probability.
"""
batch_size = tf.shape(x)[0]
noise_shape = [batch_size, 1, 1, 1]
random_tensor = keep_prob
random_tensor += tf.random_uniform(noise_shape, dtype=tf.float32)
binary_tensor = tf.f... | a91d308a91fbf328c472c2758dd080bab1b3ee4c | 33,173 |
import yaml
def read_pipeline_definition(file_path):
"""Function reads the yaml pipeline definitions.
Function reads the yaml pipeline definitions. We also remove the variables
key as that was only used for yaml placeholders.
Args:
file_path (str): Path to the pipeline definition.
Returns... | ea6ee7e8fcd14ffb30bca48b5f9505bc49657d0c | 33,174 |
import io
def detect_text(path):
"""Detects text in the file."""
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision.types.Image(content=content)
response = client.text_detection(image=image)
texts = response.text... | 22993db37ca8d858a9c4e1fbf866da9deca67528 | 33,175 |
import bisect
def find_dataset_ind(windows_ds, win_ind):
"""Taken from torch.utils.data.dataset.ConcatDataset.
"""
return bisect.bisect_right(windows_ds.cumulative_sizes, win_ind) | 76abcbdf9718cc59f1d2b7ca8daacc062970b253 | 33,176 |
def from_moment(w):
"""Converts a moment representation w to a 3D rotation matrix."""
length = vectorops.norm(w)
if length < 1e-7: return identity()
return rotation(vectorops.mul(w,1.0/length),length) | 3a5adf11665cd32dbebde158fbee5939e5654f18 | 33,177 |
def add_menu(data):
"""
新增
:param data:
:return:
"""
i = SysMenu.insert(data).execute()
return i | 07173c3648bbb3ed957f549420e80bcb1c539f48 | 33,178 |
def compute_distance_matrix(m1: np.ndarray, m2: np.ndarray,
dist_func: np.ndarray, row_wise: bool = False) \
-> np.ndarray:
"""
Function for computing the pair-wise distance matrix between two arrays of
vectors. Both matrices must have the same number ... | d044daaca81e9dc0ec186195493f1182a8209a1a | 33,179 |
from typing import List
from typing import Iterator
from typing import Any
def term_table(
strings: List[str], row_wise: bool = False, filler: str = "~"
) -> Iterator[Any]:
"""
:param strings:
:param row_wise:
:param filler:
:return:
"""
max_str_len = max(len(str) for str in strings) ... | 47fe2d7fc63490b99f03acb57b08eabbe9e1b20c | 33,180 |
def create_pipelines_lingspam():
"""Reproduces the pipelines evaluated in the LingSpam paper.
I. Androutsopoulos, J. Koutsias, K.V. Chandrinos, George Paliouras,
and C.D. Spyropoulos, "An Evaluation of Naive Bayesian Anti-Spam
Filtering". In Potamias, G., Moustakis, V. and van Someren, M. (Eds.),
... | 3d691c869e1b92f16d892e7d87cc59bad055d2a0 | 33,181 |
def band_dos_plain_spin_polarized(
band_folder,
dos_folder,
output='band_dos_plain_sp.png',
up_color='black',
down_color='red',
linewidth=1.25,
up_linestyle='-',
down_linestyle=':',
figsize=(6, 3),
width_ratios=[7, 3],
erange=[-6, 6],
kpath=None,
custom_kpath=None,
... | 8a00300828a0a9672edf025fcf4ca2a7c3264c96 | 33,182 |
def _unsigned16(data, littleEndian=False):
"""return a 16-bit unsigned integer with selectable Endian"""
assert len(data) >= 2
if littleEndian:
b0 = data[1]
b1 = data[0]
else:
b0 = data[0]
b1 = data[1]
val = (b0 << 8) + b1
return val | 22feb074aca7f4ab7d489eacb573c3653cad9272 | 33,183 |
def calculate_term_frequencies(tokens):
"""Given a series of `tokens`, produces a sorted list of tuples in the
format of (term frequency, token).
"""
frequency_dict = {}
for token in tokens:
frequency_dict.setdefault(token, 0)
frequency_dict[token] += 1
tf = []
for token... | b764175cd59fe25c4a87576faee2a76273097c5e | 33,184 |
def max(*l):
"""
Element-wise max of each of the input tensors (with Numpy-style broadcasting support).
Args:
*x (a list of Tensor): List of tensors for max.
Returns:
Tensor, the output
"""
return Max()(*l)[0] | 9467af70178c17d8bfa6404ca4969f6aae22ef2f | 33,185 |
def _edr_peak_trough_mean(ecg: pd.Series, peaks: np.array, troughs: np.array) -> np.array:
"""Estimate respiration signal from ECG based on `peak-trough-mean` method.
The `peak-trough-mean` method is based on computing the mean amplitude between R peaks (`peaks`) and
minima before R peaks (`troughs`).
... | 9f2a5fdbe9d27d0461133757157ef034fe46e2af | 33,186 |
import joblib
def feature_stacking(n_splits=CV, random_state=None, use_proba=False, verbose=False, drop_words=0.):
"""
Args:
n_splits: n_splits for KFold
random_state: random_state for KFlod
use_proba: True to predict probabilities of labels instead of labels
verbose: True to ... | 7af6d07dabd39ff27dcf66dc0d9d41cc30eefb70 | 33,187 |
import traceback
import json
def data(request):
"""
[メソッド概要]
アクション履歴画面の一覧表示
"""
logger.logic_log('LOSI00001', 'none', request=request)
msg = ''
lang = request.user.get_lang_mode()
ita_flg = False
mail_flg = False
servicenow_flg = False
filter_info = {
'tblname' : ... | e5292200699d169693d55e3032a47260258db5bc | 33,188 |
def get_default():
"""Get the configuration from the source code"""
return {name: dict(block()._asdict()) for name, _, block in triples} | 00279671d46b95dd85c307d2d690f5215d9e0a99 | 33,189 |
def npulses(image_number,passno=0):
"""How many X-ray bursts to send to the sample as function of image
number. image_number is 1-based, passno is 0-based.
"""
# When using sample translation the exposure may be boken up
# into several passes.
if passno != None: npulses = npulses_of_pass(image_n... | 485c2b27979a0b25ca4449b538f12554d2f12938 | 33,190 |
import torch
from typing import Optional
def topk__dynamic(ctx,
input: torch.Tensor,
k: int,
dim: Optional[int] = None,
largest: bool = True,
sorted: bool = True):
"""Rewrite `topk` for default backend.
Cast k to tensor... | f01ac53e2b7b5a1cef4ff55b0066bff7e9846f7f | 33,191 |
def GetLocalNodeId() -> int:
"""Returns the current local node id. If none has been set, a default is set and
used."""
global _local_node_id
if _local_node_id is None:
SetLocalNodeId(DEFAULT_LOCAL_NODE_ID)
return _local_node_id | 500c2795eade3e0854f23fbfb99e82796b98c7ef | 33,192 |
def get_dlons_from_case(case: dict):
"""pull list of latitudes from test case"""
dlons = [geo[1] for geo in case["destinations"]]
return dlons | 666ab789761e99749b4852a51f5d38c35c66bd2a | 33,193 |
def account_info(info):
"""Extract user information from IdP response"""
return dict(
user=dict(
email=info['User.email'][0],
profile=dict(
username=info['User.FirstName'][0],
full_name=info['User.FirstName'][0])),
external_id=info['User.em... | 1e3141e4ca84b935af67078d36e035c6c94bcefc | 33,194 |
from typing import Concatenate
def MangoYOLO(inputs, num_anchors, num_classes, **kwargs):
"""Create Tiny YOLO_v3 model CNN body in keras."""
x1 = compose(
DarknetConv2D_BN_Leaky(16, (3,3), **kwargs),
DarknetConv2D_BN_Leaky(16, (3, 3), strides=2, **kwargs),
DarknetConv2D_BN_Leaky(32, (3,3), **kwargs),
Darkne... | b9d1eba1407e5cd5e0037bd968e0d897153e31c0 | 33,195 |
def zone_max_matching(plan_a, plan_b):
"""
Determines the optimal bipartite matching of
districts in plan_a to districts in plan_b
to maximize the total population overlap.
Both plans should have districts indexed from 1 to k,
where k is some positive integer.
Based on the concept of "... | a710b27540ddff5c352374c62e074a2eed9ce39e | 33,196 |
def dyn_sim_feedback_discrete_time(A, Bu, Bd, x0, u, d, t_series, K):
"""
Simulate discrete-time ODE
Args:
A: discrete-time A
Bu: discrete-time B for control
Bd: discrete-time B for disturbance
x0: Initial condition in numpy array nx*1
u: Control signal in numpy array... | 9e77bdd04f03e8b2f20d204188d1d83ca325932c | 33,197 |
import logging
def get_recordings(mysql, symbol_id):
"""
Parameters
----------
mysql : dict
Connection information
symbol_id : int
ID of a symbol on write-math.com
Returns
-------
list :
A list of HandwrittenData objects
"""
connection = pymysql.connect... | c6e64b51353ae210c67adffd372b45a01847342d | 33,199 |
def horiLine(lineLength, lineWidth=None, lineCharacter=None, printOut=None):
"""Generate a horizontal line.
Args:
lineLength (int): The length of the line or how many characters the line will have.
lineWidth (int, optional): The width of the line or how many lines of text the line will take spa... | 64a4e9e22b480cbe3e038464fe6e0061e023d2c2 | 33,200 |
import struct
import functools
def decrypt(content, salt=None, key=None,
private_key=None, dh=None, auth_secret=None,
keyid=None, keylabel="P-256",
rs=4096, version="aes128gcm"):
"""
Decrypt a data block
:param content: Data to be decrypted
:type content: str
:... | e9a993f1a94bac294d14f21b993b9e59d26ae9e7 | 33,201 |
import math
def _rescale_read_counts_if_necessary(n_ref_reads, n_total_reads,
max_allowed_reads):
"""Ensures that n_total_reads <= max_allowed_reads, rescaling if necessary.
This function ensures that n_total_reads <= max_allowed_reads. If
n_total_reads is <= max_allowed_r... | d09b343cee12f77fa06ab467335a194cf69cccb4 | 33,202 |
def encode_log_entry_to_json(logEntry):
""" Transform the log entry to jason format dict to store into MongoDB """
if logEntry.action == "Query_Success" or "Commit_Success":
# Common fileds for query and commit log entry
json_dict= {"date": logEntry.utcTimestamp,
... | 4185074194459bb9ba78677a9383d29f92b2b12f | 33,203 |
def run_backward_rnn(sess, test_idx, test_feat, num_lstm_units):
""" Run backward RNN given a query."""
res_set = []
lstm_state = np.zeros([1, 2 * num_lstm_units])
for test_id in reversed(test_idx):
input_feed = np.reshape(test_feat[test_id], [1, -1])
[lstm_state, lstm_output] = rnn_one_step(
... | f6c113aed718b23778b75d592ccdcee9210a46bd | 33,205 |
import functools
def preprocess_xarray(func):
"""Decorate a function to convert all DataArray arguments to pint.Quantities.
This uses the metpy xarray accessors to do the actual conversion.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
args = tuple(a.metpy.unit_array if isinsta... | dc59d7c4b84cff76584c859354c25a77df6ab9b2 | 33,206 |
def _get_verticalalignment(angle, location, side, is_vertical, is_flipped_x,
is_flipped_y):
"""Return vertical alignment along the y axis.
Parameters
----------
angle : {0, 90, -90}
location : {'first', 'last', 'inner', 'outer'}
side : {'first', 'last'}
is_vertica... | 6dfceb74bea740f70f0958192b316c43eb9a2ef7 | 33,207 |
def load_dict(path):
""" Load a dictionary and a corresponding reverse dictionary from the given file
where line number (0-indexed) is key and line string is value. """
retdict = list()
rev_retdict = dict()
with open(path) as fin:
for idx, line in enumerate(fin):
text = line.stri... | 31a67c2a28518a3632a47ced2889150c2ce98a78 | 33,210 |
import numpy
def hsplit(ary, indices_or_sections):
"""
Split an array into multiple sub-arrays horizontally (column-wise).
Please refer to the `split` documentation. `hsplit` is equivalent to
`split` with ``axis=1``, the array is always split along the second axis
regardless of the array dimensi... | cd04cbeb3ac89910289d6f1ddc1809373f896ac6 | 33,211 |
def is_valid_ipv6_addr(input=""):
"""Check if this is a valid IPv6 string.
Returns
-------
bool
A boolean indicating whether this is a valid IPv6 string
"""
assert input != ""
if _RGX_IPV6ADDR.search(input):
return True
return False | f866aa5e8e005823ec78edcc9c7dedd923c28c4f | 33,212 |
def calc_TEC(
maindir,
window=4096,
incoh_int=100,
sfactor=4,
offset=0.0,
timewin=[0, 0],
snrmin=0.0,
):
"""
Estimation of phase curve using coherent and incoherent integration.
Args:
maindir (:obj:`str`): Path for data.
window (:obj:'int'): Window length in samp... | f2af0a58d866b79de320e076e3ecc5ae3e704cad | 33,215 |
def solve(A, b):
"""solve a sparse system Ax = b
Args:
A (torch.sparse.Tensor[b, m, m]): the sparse matrix defining the system.
b (torch.Tensor[b, m, n]): the target matrix b
Returns:
x (torch.Tensor[b, m, n]): the initially unknown matrix x
Note:
'A' should be 'dense'... | 64a51eb8b1bd52ea3c47b80363b68ec346260ac9 | 33,216 |
def smiles_to_fp(smiles):
"""
Convert smiles to Daylight FP and MACCSkeys.
Parameters
----------
smiles : str, smiles representation of a molecule
Returns
-------
fp : np.ndarray zero and one representation of the fingerprints
"""
try:
mol = Chem.MolFromSmiles(smiles)
... | e64b3b94ccf950af41473800e992720b7dd6b155 | 33,218 |
import re
def _networkinfo(interface):
"""Given an interface name, returns dict containing network and
broadcast address as IPv4Interface objects
If an interface has no IP, returns None
"""
ipcmds = "ip -o -4 address show dev {}".format(interface).split()
out = check_output(ipcmds).decode('ut... | 51ab39e2f05f1dad8d02272c425a357750781414 | 33,219 |
def score_decorator(f):
"""Decorator for sklearn's _score function.
Special `hack` for sklearn.model_selection._validation._score
in order to score pipelines that drop samples during transforming.
"""
def wrapper(*args, **kwargs):
args = list(args) # Convert to list for item assignment
... | ee3464cb596846f3047fa04a6d40f5bec9634077 | 33,222 |
def trait(name, notify=True, optional=False):
""" Create a new expression for observing a trait with the exact
name given.
Events emitted (if any) will be instances of
:class:`~traits.observation.events.TraitChangeEvent`.
Parameters
----------
name : str
Name of the trait to match.... | ecd6b0525efadea6e0a7bc2b57ebaf99f2463cca | 33,223 |
def get_splits(space,
data,
props,
max_specs=None,
seed=None,
fp_type="morgan"):
"""
Get representations and values of the data given a certain
set of Morgan hyperparameters.
Args:
space (dict): hyperopt` space of hyperpara... | 9ff20a62b7615d3f7b1b3a8ede1c1d4f6ff5bccf | 33,224 |
def amortized_loan(principal, apr, periods, m=12):
"""
"""
return principal / pvifa(apr, periods, m) | f7d67683cd625179012a24e6cd62c0c552009a48 | 33,226 |
from typing import Optional
from typing import Iterable
def horizontal_legend(
fig: Figure,
handles: Optional[Iterable[Artist]] = None,
labels: Optional[Iterable[str]] = None,
*,
ncol: int = 1,
**kwargs,
) -> Legend:
"""
Place a legend on the figure, with the items arranged to read right to left rathe... | ea229c4deee241c37b3c26a5ab2fab4d2233b8dd | 33,228 |
def _create_lock_inventory(session, rp_uuid, inventories):
"""Return a function that will lock inventory for this rp."""
def _lock_inventory():
rp_url = '/resource_providers/%s' % rp_uuid
inv_url = rp_url + '/' + 'inventories'
resp = session.get(rp_url)
if resp:
data ... | e9988b989cc22f82110923466906aa64a515c41f | 33,229 |
def strip(string, p=" \t\n\r"):
"""
strip(string, p=" \t\n\r")
"""
return string.strip(p) | 1be2a256394455ea235b675d51d2023e8142415d | 33,230 |
def correlation_matrix_plot(
df, function=pearsonr, significance_level=0.05, cbar_levels=8, figsize=(6, 6)
):
"""Plot corrmat considering p-vals."""
corr, pvals = correlation_matrix(df, function=function)
# create triangular mask for heatmap
mask = np.zeros_like(corr)
mask[np.triu_indices_from(... | 343aa7c0240be34da037ea45bd0020d6eed83770 | 33,232 |
def _unvec(vecA, m=None):
"""inverse of _vec() operator"""
N = vecA.shape[0]
if m is None:
m = np.sqrt(vecA.shape[1] + 0.25).astype(np.int64)
return vecA.reshape((N, m, -1), order='F') | 766dd244016691cc2f29d0af383034116e067401 | 33,233 |
import logging
def one_hot_encode(sequences):
"""One hot encoding of a list of DNA sequences
Args:
sequences (list):: python list of strings of equal length
Returns:
numpy.ndarray: 3-dimension numpy array with shape
(len(sequences), len(list_i... | 3ccb69c433872968510065e2ce86b69558767cf8 | 33,234 |
def binary_cross_entropy(labels, logits, linear_input=True, eps=1.e-5, name='binary_cross_entropy_loss'):
"""
Same as cross_entropy_loss for the binary classification problem. the model should have a one dimensional output,
the targets should be given in form of a matrix of dimensions batch_size x 1 with va... | 60c29e67144e91ac384016642322eafe34d70984 | 33,235 |
def get_number_from_user():
""" None -> (int)
Get a symbol by index from the user's input.
"""
movers = ApiWrapper.get_movers()
while True:
print("To choose a company, enter a responding integer from the list below")
print_movers(movers)
y = input("Enter the number of compan... | f04d312ba115bd601e9d0d6bfde7f614359ba13d | 33,236 |
def read_refseqscan_results(fn):
"""Read RefSeqScan output file"""
ret = dict()
for line in open(fn):
line = line.strip()
if line == '' or line.startswith('#'):
continue
cols = line.split()
ret[cols[0]] = cols[2]
return ret | 4450e4113d47e72c5332dd1ca79b37a6847a296f | 33,238 |
import array
def discretize_categories(iterable):
"""
:param iterable:
:return:
"""
uniques = sorted(set(iterable))
discretize = False
for v in uniques:
if isinstance(v, str):
discretize = True
if discretize: # Discretize and return an array
str_to_int_... | a55bb0cc8632274d15f00478783e3def3f4ebd49 | 33,239 |
def multhist(hists, asone=1):
"""Takes a set of histograms and combines them.
If asone is true, then returns one histogram of key->[val1, val2, ...].
Otherwise, returns one histogram per input"""
ret = {}
num = len(hists)
for i, h in enumerate(hists):
for k in sorted(h):
if k... | 0bb6b0af90e75fcfb4c2bee698a123c897bcb64c | 33,240 |
def to_dict(obj, table=None, scrub=None, fields=None):
"""
Takes a single or list of sqlalchemy objects and serializes to
JSON-compatible base python objects. If scrub is set to True, then
this function will also remove all keys that match the specified list
"""
data = None
serialize_obj = ... | 270c22f8a096d65024f0ddc5699ba21155b7c2ef | 33,241 |
import torch
def CWLoss(output, target, confidence=0):
"""
CW loss (Marging loss).
"""
num_classes = output.shape[-1]
target = target.data
target_onehot = torch.zeros(target.size() + (num_classes,))
target_onehot = target_onehot.cuda()
target_onehot.scatter_(1, target.unsqueeze(1), 1.)... | 6f9a61dcb1b2377e4e76fa71d0de86ee12647f17 | 33,242 |
def get_square(array, size, y, x, position=False, force=False, verbose=True):
"""
Return an square subframe from a 2d array or image.
Parameters
----------
array : 2d array_like
Input frame.
size : int
Size of the subframe.
y : int
Y coordinate of the center of the s... | 8d83d4d16241e118bbb65593c14f9f9d5ae0834c | 33,243 |
def iou_with_anchors(anchors_min, anchors_max, box_min, box_max):
"""Compute jaccard score between a box and the anchors.
"""
len_anchors = anchors_max - anchors_min
int_xmin = np.maximum(anchors_min, box_min)
int_xmax = np.minimum(anchors_max, box_max)
inter_len = np.maximum(int_xmax - int_xmi... | f3c3a10b8d86bb25ca851998de275a7c5fb8fbec | 33,244 |
def load_from_np(filename, arr_idx_der):
"""
arr_idx_der 1 for rho and 2 for p
"""
# load npy data of 3D tube
arr = np.load(filename)
arr_t = arr[:, 0]
arr_der = arr[:, arr_idx_der]
return arr_t, arr_der | 77b64fdf067cf70a6861d75b60c7ca63bbf21de0 | 33,245 |
def rxzero_vel_amp_eval(parm, t_idx):
"""
siglognormal velocity amplitude evaluation
"""
if len(parm) == 6:
D, t0, mu, sigma, theta_s, theta_e = parm
elif len(parm) == 4:
D, t0, mu, sigma = parm
else:
print 'Invalid length of parm...'
return None
#argument for... | acc1c102723d276db6603104ad8ad3848f72b7f8 | 33,246 |
import json
def read_json(json_file):
""" Read input JSON file and return the dict. """
json_data = None
with open(json_file, 'rt') as json_fh:
json_data = json.load(json_fh)
return json_data | 4e1ea153d040ec0c3478c2d1d3136eb3c48bfe1c | 33,248 |
def mixnet_xl(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
"""Creates a MixNet Extra-Large model.
Not a paper spec, experimental def by RW w/ depth scaling.
"""
default_cfg = default_cfgs['mixnet_xl']
#kwargs['drop_connect_rate'] = 0.2
model = _gen_mixnet_m(
channel_multipl... | e03c12abb4bb2cb43553cecd6b175cf6724cc8c0 | 33,249 |
def accuracy(results):
"""
Evaluate the accuracy of results, considering victories and defeats.
Args:
results: List of 2 elements representing the number of victories and defeats
Returns:
results accuracy
"""
return results[1] / (results[0] + results[1]) * 100 | 911e38741b7c02772c23dd6a347db36b96a0e7e0 | 33,250 |
def sub_sellos_agregar():
"""
Agregar nuevo registro a 'sub_sellos'
"""
form = SQLFORM(db.sub_sellos, submit_button='Aceptar')
if form.accepts(request.vars, session):
response.flash = 'Registro ingresado'
return dict(form=form) | 8c9ad3c3648bda12f5259b164886a0e6ce822d11 | 33,251 |
async def ensure_valid_path(current_path: str) -> bool:
""" ensures the path is configured to allow auto refresh """
paths_to_check = settings.NO_AUTO_REFRESH
for path in paths_to_check:
if path in current_path:
return False
return True | a39c46e0df1db2ac93afbb063e16a3c52cb378eb | 33,252 |
from typing import List
def part_1_original_approach(lines: List[str]) -> int:
"""
This was my original approach. I missed a few critical details that really bit me in
the ass.
1. Operator precedence for modulo.
"""
ans = 0
seq = [[int(c) for c in x] for x in lines]
for _ in range(10... | b8fbf734c0a476244cb8f999afa961c8ec0ff737 | 33,254 |
def get_distances(username,location,dist):
"""
The purpose of this function is the calculation of distances between user and created rooms
"""
distances=[]
keys = ['_id','dist']
base=list(nego.find({},{'location':0})) ## Retrieves every user in the base except location
for d in base:
... | 41c3caf26c46d227367da813fb8e2a0d059e6500 | 33,256 |
import pickle
def AcProgEgrep(context, grep, selection=None):
"""Corresponds to AC_PROG_EGREP_ autoconf macro
:Parameters:
context
SCons configuration context.
grep
Path to ``grep`` program as found by `AcProgGrep`.
selection
If ``None`` (default), ... | d8f8ed373950ef4a9b6aaa2790a988f5aacd9730 | 33,257 |
def is_number(s):
"""Is string a number."""
try:
float(s)
return True
except ValueError:
return False | 22eb560c2723f6551d1a445ba777208a75139a7c | 33,258 |
import numpy
def calc_motif_dist(motifList):
"""Given a list of motifs, returns a dictionary of the distances
for each motif pair, e.g. {Motif1:Motif2:(dist, offset, sense/antisense)}
"""
ret = {}
for m1 in motifList:
for m2 in motifList:
if m1.id != m2.id:
#che... | 1610d2213afc28a810077949c4a763e742f364ab | 33,259 |
def step(name=None):
"""
Decorates functions that will register
a step.
"""
def decorator(func):
add_step(get_name(name, func), func)
return func
return decorator | 64a69b5c0f31bef4e5126c869417a9215adc9221 | 33,260 |
def prepare_subimg(image5d, size, offset):
"""Extracts a subimage from a larger image.
Args:
image5d: Image array as a 5D array (t, z, y, x, c), or 4D if
no separate channel dimension exists as with most one channel
images.
size: Size of the region of interest as ... | c8c14333ed862fc3acec4347d0462e5dcb644ab8 | 33,261 |
def filter_plants_by_region_id(region_id, year, host='switch-db2.erg.berkeley.edu', area=0.5):
"""
Filters generation plant data by NERC Region, according to the provided id.
Generation plants w/o Region get assigned to the NERC Region with which more
than a certain percentage of its County area interse... | e9eaa363a4ec2293b97a7a7ffacf82bc0ae49702 | 33,262 |
def _get_image_blob(roidb, scale_ind):
"""Builds an input blob from the images in the roidb at the specified
scales.
"""
num_images = len(roidb)
processed_ims = []
# processed_ims_depth = []
# processed_ims_normal = []
im_scales = []
for i in xrange(num_images):
# rgba
... | 69200c535818d159b10f80d9c967546cbbd33a75 | 33,263 |
def translate_month(month):
"""
Translates the month string into an integer value
Args:
month (unicode): month string parsed from the website listings.
Returns:
int: month index starting from 1
Examples:
>>> translate_month('jan')
1
"""
for key, values ... | 5ff0e3506e37e4b9b5cdd2cd3bf5b322622172ab | 33,264 |
def gencpppxd(desc, exception_type='+'):
"""Generates a cpp_*.pxd Cython header file for exposing C/C++ data from to
other Cython wrappers based off of a dictionary description.
Parameters
----------
desc : dict
Class description dictonary.
exception_type : str, optional
Cython... | a2e7cc486589ee301483b8a76b65313eb754221d | 33,265 |
def no_results_to_show():
"""Produce an error message when there are no results to show."""
return format_html('<p class="expenses-empty">{}</p>', _("No results to show.")) | 492c1c19d4daf159a495c001bfc6671fdf6ed593 | 33,267 |
def enhance_shadows(Shw, method, **kwargs):
""" Given a specific method, employ shadow transform
Parameters
----------
Shw : np.array, size=(m,n), dtype={float,integer}
array with intensities of shading and shadowing
method : {‘mean’,’kuwahara’,’median’,’otsu’,'anistropic'}
method n... | daddde00889be9eb6a1bb57fc140363d85ede32a | 33,269 |
from typing import Optional
from typing import Set
import collections
def _to_real_set(
number_or_sequence: Optional[ScalarOrSequence]
) -> Set[chex.Scalar]:
"""Converts the optional number or sequence to a set."""
if number_or_sequence is None:
return set()
elif isinstance(number_or_sequence, (float, i... | c0f380a9a179634da04447198ad6553c3c684f7c | 33,270 |
def alt_or_ref(record, samples: list):
"""
takes in a single record in a vcf file and returns the sample names divided into two lists:
ones that have the reference snp state and ones that have the alternative snp state
Parameters
----------
record
the record supplied by the vcf reader
... | abaccfeef02ee625d103da88b23fce82a40bc04c | 33,271 |
def plot_loss(ctx, tests, rulers=[], sfx="", **kwargs):
"""Loss plot (1 row per test, val on left, train on right)."""
vh = len(tests)
fig, axs = plt.subplots(vh, 2, figsize=(16, 4 * vh))
for base, row in zip(tests, axs.reshape(vh, 2)):
ctx.plot_loss(
base, row[0], baselines=["adam"]... | d215ec0bc20520380bf0625f27abbad383981cd3 | 33,272 |
def mpi_rank():
"""
Returns the rank of the calling process.
"""
comm = mpi4py.MPI.COMM_WORLD
rank = comm.Get_rank()
return rank | 63fba63118edbced080b5077931c0d63d2c672b2 | 33,273 |
def db(app):
"""
Setup our database, this only gets executed once per session.
:param app: Pytest fixture
:return: SQLAlchemy database session
"""
_db.drop_all()
_db.create_all()
# Create a single user because a lot of tests do not mutate this user.
# It will result in faster tests... | 0176de576b1f217ce56e61cdba5b2deb287d7430 | 33,274 |
def is_const_component(record_component):
"""Determines whether a group or dataset in the HDF5 file is constant.
Parameters
----------
record_component : h5py.Group or h5py.Dataset
Returns
-------
bool
True if constant, False otherwise
References
----------
.. https://... | 4adb2ff7f6fb04086b70186a32a4589ae9161bb5 | 33,275 |
def centernet_resnet101b_voc(pretrained_backbone=False, classes=20, **kwargs):
"""
CenterNet model on the base of ResNet-101b for VOC Detection from 'Objects as Points,'
https://arxiv.org/abs/1904.07850.
Parameters:
----------
pretrained_backbone : bool, default False
Whether to load th... | 39b6ed4aa1d5c1143ef3b35f12f6be71160ec5cf | 33,276 |
import pytz
def isodate(dt):
"""Formats a datetime to ISO format."""
tz = pytz.timezone('Europe/Zagreb')
return dt.astimezone(tz).isoformat() | d07118e188772ec6a87d554c6883530164eeb550 | 33,278 |
def _ncells_after_subdiv(ms_inf, divisor):
"""Calculates total number of vtu cells in partition after subdivision
:param ms_inf: Mesh/solninformation. ('ele_type', [npts, nele, ndims])
:type ms_inf: tuple: (str, list)
:rtype: integer
"""
# Catch all for cases where cell subdivision is not perf... | 981db31a7729c0cac88575b1cb12505a30cf0abb | 33,279 |
def match_santa_pairs(participants: list):
""" This function returns a list of tuples of (Santa, Target) pairings """
shuffle(participants)
return list(make_circular_pairs(participants)) | dc002f82d25df89ee70392ff48fdd401a960ccc5 | 33,280 |
def conv_relu_forward(x, w, b, conv_param):
"""
A convenience layer that performs a convolution followed by a ReLU.
Inputs:
- x: Input to the convolutional layer
- w, b, conv_param: Weights and parameters for the convolutional layer
Returns a tuple of:
- out: Output from the ReLU
- cache: Object to give to t... | 52ee4941c7cf48179652a0f0e26a4d271579047f | 33,281 |
def top_rank(df, target, n=None, ascending=False, method='spearman'):
"""
Calculate first / last N correlation with target
This method is measuring single-feature relevance importance and works well for independent features
But suffers in the presence of codependent features.
pearson : standard corr... | f8e2b0b9888af00c6c75acac4f5063580bbada07 | 33,282 |
def sample_points_on_sphere(center, distance_from_center, hemisphere=False):
"""just use the polar coordinates to do this, this can be sped up do that
"""
EPS = 1e-6
thetas = np.linspace(0+EPS, 2*np.pi, 64)
phis = np.linspace(0+EPS, np.pi/2, 64) if hemisphere else np.linspace(0+EPS, np.pi, 64)
p... | 0441a58da5e9bd6cccd8aeae29c022ffd6e6eae8 | 33,283 |
from pathlib import Path
def get_package_path() -> Path:
"""
Get local install path of the package.
"""
return to_path(__file__).parent.absolute() | 7976606ad2731b408dd6a44d72e27f6307c2fa8b | 33,284 |
import inspect
import types
def parameterized_class(cls):
"""A class decorator for running parameterized test cases.
Mark your class with @parameterized_class.
Mark your test cases with @parameterized.
"""
test_functions = inspect.getmembers(cls, predicate=inspect.ismethod)
for (name, f) in t... | 084ec02b2c9427ffb9ddd41ef9857390477d9d6f | 33,285 |
def isStringLike(s):
""" Returns True if s acts "like" a string, i.e. is str or unicode.
Args:
s (string): instance to inspect
Returns:
True if s acts like a string
"""
try:
s + ''
except:
return False
else:
return True | 73fc002843735536c159eed91cf54886f52e78e7 | 33,286 |
def velocity_to_wavelength(velocities, input_units, center_wavelength=None,
center_wavelength_units=None, wavelength_units='meters',
convention='optical'):
"""
Conventions defined here:
http://www.gb.nrao.edu/~fghigo/gbtdoc/doppler.html
* Radio V = c (c/l0 - c/l)/(c/l0) f(V) = (c/l0)... | aff040967297848253e49272eb6b5ba4e687433b | 33,287 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.