content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def prepare_vcf_table(varfile, sample, variants):
"""Prepare vcf table."""
header = [
"CHROM",
"POS",
"REF",
"ALT",
"AF",
"DP",
"DP4",
"GEN[0].AD",
"SB",
"FS",
"EFF[*].GENE",
"ID",
"EFF[*].AA",
]
head... | 396eb3966196352dbbbe0ff6c9386aba7fcc032b | 69,836 |
def counts_from_confusion(confusion):
"""
Obtain TP, FN FP, and TN for each class in the confusion matrix
"""
counts_list = []
# Iterate through classes and store the counts
for i in range(confusion.shape[0]):
tp = confusion[i, i]
fn_mask = np.zeros(confusion.shape)
fn... | 7c9b1f8309ef7a0304aa218e75f90d0c6a09bd66 | 69,837 |
def vaccination_view():
"""
App route to display India level vaccination data
:return:
"""
dates, cumulative_data, daily_data, fully_vaccinated, daily_fully_vaccinated, sources = service.vaccination_data()
context = {
'dates': dates.tolist(),
'cumulative_data': cumulative_data.to... | 0f4fb72c72abf31d65c2b541fc891d6c574c6252 | 69,838 |
def im_to_torch(img):
"""Transform ndarray image to torch tensor.
Parameters
----------
img: numpy.ndarray
An ndarray with shape: `(H, W, 3)`.
Returns
-------
torch.Tensor
A tensor with shape: `(3, H, W)`.
"""
img = np.transpose(img, (2, 0, 1)) # C*H*W
img = to_t... | fcda6a9e65d87b09ff5d1340dcf958fb1f14089e | 69,839 |
def get_f1sc(y_true, y_pred, threshold = 0.5):
"""
- Description
y_true: should be one-hot encoded tensor
y_pred: should be logit tensor
threshold: thres to claim it is 1
- Reutrn
f1-score under threshold
"""
y_true = tf.argmax(y_true, axis = 1)
y_pred = y_pred[:,1] >= threshold
... | c21436263fcfa938ee70c2c90bf2ed4375edceec | 69,841 |
def rules(supvisors):
""" Return the instance to test. """
return ProcessRules(supvisors) | 68fd580498e590a320cfb8ba25e177fdfbe7f512 | 69,843 |
def _parse_build(encoded_data, pointer=0, spec=None, spec_params=None, strict=False):
"""
Parses a byte string generically, or using a spec with optional params
:param encoded_data:
A byte string that contains BER-encoded data
:param pointer:
The index in the byte string to parse from
... | 3824e87b120b63cbbc18a140b8b2c0cca95d5405 | 69,844 |
def cache_basic_crud_update_row_view(request, id):
"""
Renders the Django edit form page and execute the update statement.
But, with invalidating the cache to clear the previous cached results.
"""
if request.method == "GET":
# Check if the row id existed or not.
if is_contact_us_id... | 83d90a5fe70715dd6e8e0aff8b342a193c77ac19 | 69,845 |
def interpolate_at_times(df_or_series, new_times) -> ndarray:
"""
Parameters
-----------
df_or_series: Pandas DataFrame or Series
new_times: iterable, numpy array
can be a n-d array, list.
"""
assert df_or_series.index.is_monotonic_increasing, "df_or_series must be a increasing ... | f9dd3dbb780331f40d38d505bceac609ed88df86 | 69,846 |
def PFullInstantiate (inOTF, access, err):
""" Fully instantiate an OTF by opening and closing
return 0 on success, else failure
inOTF = Python OTF object
access = access code 1=READONLY, 2=WRITEONLY, 3=READWRITE
err = Python Obit Error/message stack
"""
#######################... | fa5691292e27153afeebe6ef42fe91b974c2b933 | 69,847 |
from typing import Any
async def get_user_info_by_id_async(client: Any, user_id: str):
"""Gets profile information about a user by id."""
return (await make_call_async(client, "users.info", user=user_id))["user"] | 262dc6afa0f17a3f2debd0d05738b20441f4f2d9 | 69,848 |
def getStep(raw, config):
"""
Detect the type of the build step and generate a model from it
"""
if exists(raw, "partitiontable"):
ptable = partitiontable()
ptable.reference = raw["partitiontable"]
return ptable
if exists(raw, "format"):
form = format()
form.r... | 54518f813709b5b578cf87504343024a9306450c | 69,849 |
def _compute_background_amplitude(image_spot):
"""Compute amplitude of a spot and background minimum value.
Parameters
----------
image_spot : np.ndarray, np.uint
A 3-d image with detected spot and shape (z, y, x).
Returns
-------
psf_amplitude : float or int
Amplitude of t... | 84a5138d2757459f8e0a61c12222cb32fa24662d | 69,850 |
def strip_comments(string, comment_symbols=frozenset(('#', '//'))):
"""
:param string: A string containing json with comments started by comment_symbols.
:param comment_symbols: Iterable of symbols that start a line comment (default # or //).
:return: The string with the comments removed.
"""
lines = string.split... | 4dfc1b0e627d8559db61f00b10fa5cb807ba2d01 | 69,851 |
def return_user_best_video(username):
"""
In GET request
- Returns video ID of the video uploaded by the user with the highest view count.
"""
if request.method == 'GET':
return str(db.get_best_video_ID(username)) | 9751f36a0cd45c54ca38f4e2f19a6be43df8fed3 | 69,852 |
def get_unique_tasks(*task_groups):
"""
Compare input JSON objects containing tasks and return a unique set
:param json_objects: lists of task objects
:type json_objects: list
:rtype: list
"""
# Combine all sub-json objects into a single group
unique_tasks = []
# Get a list of ta... | c9eb32ea0a953e797ea28021c3a434941f7b05ff | 69,853 |
def get_srl16_init(site, srl):
"""
Decodes SRL16 INIT parameter. Returns two initialization strings, each one
for one of two SRL16s.
"""
lut_init = get_lut_init(site, srl)
bits = lut_init.replace("64'b", "")
assert bits[1::2] == bits[::2]
srl_init = bits[::2]
return "16'b{}".forma... | 651cef9d266fe2edd896f17018cda1455d2d54a8 | 69,854 |
def problema(n):
"""
Input
n - maxim number of digits that can produce this result
"""
suma = 0
b = {}
for i in product(range(10), repeat=n):
aux = reduce(lambda x, y: 10*x + y, i)
b[aux] = sum(map(lambda x: x**5, i))
if aux == b[aux]:
suma += aux
... | f6c5d0436b8d41f82c56c996f9e26fb53887abd8 | 69,855 |
def news_detail(news_id):
"""
新闻详情
:param news_id:
:return:
"""
# 显示用户是否登录的逻辑
print('test')
user = g.user
print(user)
# 右侧新闻排行的逻辑
news_list = []
try:
news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
except Exception as e... | abf8f3d3542ca80eb0fbd907dfcc4cb7a668c4dd | 69,857 |
def directorio_imagen(instance, filename):
"""Obtiene el directorio para guardar las imagenes de los platillos"""
# Obtenemos la extension del archivo para guardar la imagen solo con el id y nombre del platillo
extension = filename.rsplit('.', 1)[1]
return f"platillo/imagen/{instance.id}_{instance.nomb... | 90db760562327a16858e1bf6419fb1ed6e9eeefa | 69,858 |
import json
def output_fn(prediction, accept):
"""Format prediction output
The default accept/content-type between containers for serial inference is JSON.
We also want to set the ContentType or mimetype as the same value as accept so the next
container can read the response payload correctly.
""... | 47ad5dcb528c8fbaca9b0de22f6745dd1c058da2 | 69,859 |
def stack_error_improvement_matrix(result_list, model_names, error='mae'):
"""Computes the stacked error improvement matrix, which for each element (i,j) contains the pairwise stacked error improvement of model_list i and j. Returns as pd.DataFrame.
Arguments:
result_list: a list of SPSbBandwidthOptimi... | 540d01a8764643ccec3db68fb8bd5a95ddb423ae | 69,860 |
from typing import Union
def gen_batch_vectors(
n_batches: int,
n_features: int,
batch_scale: float,
bio_batch_angle: Union[float, None] = None,
projection_to_bio: Union[np.ndarray, None] = None,
) -> np.ndarray:
"""Generates a batch-effect vector for each batch, optionally with some
relat... | 744ffced9013686b14a6c4100a24f8df81b70093 | 69,861 |
def main():
"""
Main procedure; accept the file name as a command-line parameter and run the solver.
"""
if len(sys.argv) < 2:
print 'Specify the file name corresponding to the Brick Pop screenshot as the first ' \
'positional argument.'
return sys.exit(1)
return solve... | 9db3fc1fd77a07e1a58c2eafe513edf357a08167 | 69,862 |
def is_multiple_folder(schema_map):
"""
Return True if the schema map identifies a multiple folder.
:param schema_map: the schema map to be examined
:return: True if the map identifies a multiple folder
"""
property_type = get_type(schema_map)
if property_type == "array":
return get_... | c18d6a7557e458998a4d2c008f7b1f3b74fff2c7 | 69,863 |
def cicle_move(A):
"""
move first to last and move elements between first and last 1 element back
:param A: list to execute cicle move
:return:
"""
tmp = A[0]
for i in range(len(A) - 1):
A[i] = A[i + 1]
A[len(A) - 1] = tmp
return A | 4948b863829d77a879ad0ec9745bb3a35e580026 | 69,864 |
import torch
def test_is_index_valid() -> None:
"""
Test if checks for valid sequence positions work.
"""
def _create(pos: int) -> ScalarDataSource:
z = torch.empty(0)
return ScalarDataSource(metadata=GeneralSampleMetadata(id="", sequence_position=pos),
... | cb3210c2fd59ceb013b8bc909fa9f08cf03e1af1 | 69,865 |
def load_keras_model(dataset, model_name):
"""
Loads pretrained model from disk for a given dataset type.
"""
folder_path = '../Models/'
model_path = folder_path + dataset + '/' + model_name + '_model.json'
try:
json_file = open(model_path, 'r')
except IOError:
print('\nE... | 70f2670d414466a675646e6689dff7ac4f609c08 | 69,866 |
def _is_float_or_nan(val):
"""Check whether a given item is a float or np.nan"""
try:
float(val)
except ValueError:
if val is np.nan:
return True
return False
else:
if not isinstance(val, bool):
return True
else:
return False | 9eadced4492fd052173b4a6d953df7862df2c370 | 69,867 |
import collections
def resize(img, size, interpolation=Image.BILINEAR):
"""Resize the input PIL.Image to the given size.
Args:
img (PIL.Image): Image to be resized.
size (sequence or int): Desired output size. If size is a sequence like
(h, w), the output size will be matched to th... | 829bbdeea7cb99dbc2f935330b5180319e17da9e | 69,868 |
from operator import concat
def scriptGen(step, config):
"""
Generate a script command from a parser.executor.script
"""
if not step.model.command == None:
return concat(["\n# Executing custom script"], script.script(shell="", payload=step.model.command).exec())
with open(step.model.file, ... | bc1bd50e05c8514d32483d3c5aaf9951494d15f6 | 69,869 |
def read_binary_file(bf: str):
"""
to read binary file
:param bf:
:type bf:
:return:
:rtype:
"""
# example: f'./local_data/MSG+0415.3km.lon'
data = np.fromfile(bf, '<f4') # little-endian float32
# data = np.fromfile(bf, '>f4') # big-endian float32
return data | 4ecf7fb3098339b5ea0e77e738bb59f863cf641c | 69,870 |
def get_bounding_boxes(start_path = '.'):
""" Extracts a bounding box file and returns a dictionary
"""
return GetBoundingBoxes(start_path).unpack_all() | a0d80d6d6a77555e4bdbecaf7bd52e8403270965 | 69,871 |
def get_VAE_os(X):
"""
takes in only data 'X', in samples as rows format
returns only list of outlier scores for each sample
higher score = more outlier
gives reconstruciton error from AE, should be largest for outliers
"""
losses = get_vae_losses(X)
return losses | 1c1a078409b29d2e7306b72ddbe670f56cf9f538 | 69,872 |
def get_activation_gradients(label):
"""Gets the sample gradient w.r.t activation according to the model_fn."""
# The sample loss is (label - logits)**2, where
# logits = \sum_j^HIDDEN_LAYER_SIZE (
# \sum_i^EMBEDDING_DIM w_i * kernel + bias)
#
# Note kernel and bias are both constant initializer... | 6714795be6893106ecbfacecd368854b377ae75c | 69,873 |
import gzip
import tqdm
import json
def read_examples(input_file):
"""Read a SQuAD-like json file into a list of Examples."""
def is_whitespace(c):
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
return True
return False
reader = tf.gfile.Open(input_file, "rb")
if input... | f0ea238c4313ec6a0779452014c7875feeefbb4e | 69,875 |
async def record(request):
"""Renders the video recording and upload view."""
return templates.TemplateResponse("record.html", {"request": request}) | fa3d6633a68f9cf1f01aab8d45b3198024a4d219 | 69,877 |
import ctypes
import readline
def rl_get_point() -> int: # pragma: no cover
"""
Returns the offset of the current cursor position in rl_line_buffer
"""
if rl_type == RlType.GNU:
return ctypes.c_int.in_dll(readline_lib, "rl_point").value
elif rl_type == RlType.PYREADLINE:
return i... | 257dd29b23869b6e6245773f86e64ef58f9e763b | 69,878 |
def plot_averages(
fig: go.Figure,
data: pd.DataFrame,
value_col: str,
aggregate: dict,
color: str,
line_shape: str = "spline",
color_discrete_sequence: list = px.colors.qualitative.G10,
category_orders: dict = default_category_orders(),
mode: str = "polar",
):
"""Add traces for ... | b3f99ee216fc8375ea071ca7483c9c003fe38bff | 69,879 |
import typing
def rating(apikey: str, symbol: str) -> typing.List[typing.Dict]:
"""
Query FMP /rating/ API.
:param apikey: Your API key.
:param symbol: Company ticker.
:return: A list of dictionaries.
"""
path = f"rating/{symbol}"
query_vars = {"apikey": apikey}
return __return_js... | fddc609276e0f63e2f6523337c47a95c9f651a94 | 69,880 |
import tokenize
def tokenize_code(text):
"""Tokenize code strings.
This simply considers whitespaces as token delimiters.
Args:
text: A code string to be tokenized.
Returns:
A list of strings representing the tokens in the code.
"""
return tokenize.RegexpTokenizer(r'\w+').tokenize(text) | 692eec16363f4d6816482025942aac7e149f3910 | 69,881 |
def getScriptClass(scriptVersion, script):
"""
getScriptClass returns the class of the script from the known standard
types. NonStandardTy will be returned when the script does not parse.
NOTE: All scripts that are not version 0 are currently considered
non standard.
"""
if scriptVersion !... | ead86ca55a820bf0f93aa31f70c74c733a61f253 | 69,882 |
def print_compare(x, y):
"""
Helper method used in
:meth:`Sets.ParentMethods._test_elements_eq_symmetric`,
:meth:`Sets.ParentMethods._test_elements_eq_tranisitive`.
INPUT:
- ``x`` -- an element
- ``y`` -- an element
EXAMPLES::
sage: from sage.categories.sets_cat import print... | 7a591b52fb20bc2bf0ec8ea029e4f10b3e1fee26 | 69,884 |
def Words_Before_and_after(words, item, nbr):
"""
:param words: list of words
:param item: word of interest
:param nbr: number of words wanted before and after the word of interest
:return: list of words before and after the word of interest
"""
liste = [[words[item], item]]
for n in ran... | 6dc874565a308cc642bf0510a3be56264c6d89e9 | 69,885 |
async def get_mocked_redis_client(*args, **kwargs) -> RedisCluster:
"""
Return a stable RedisCluster object that have deterministic
nodes and slots setup to remove the problem of different IP addresses
on different installations and machines.
"""
cluster_slots = kwargs.pop("cluster_slots", defau... | 5fb6e3b70971a27ceaef2676741b2a36f4168039 | 69,886 |
import yaml
def df_to_yaml(df):
""" conert DataFrame to yaml string """
d = df.to_dict(orient='records')
return yaml.dump(d) | 285b4cad92e73fbaec19e631664bb474ecaf309f | 69,887 |
from datetime import datetime
def naturaltime(text, now=None):
"""Convert a naturaltime string to a datetime object."""
text = text.lower().strip()
if not now:
now = datetime.now()
if text == 'now':
return now
if text == 'yesterday':
return now - timedelta(days=1)
if t... | 25f56b5afd11cd5e4b6dd4a94a1de3c47476bd1e | 69,889 |
def get_polar(d, Re=6371.):
""" Convert to polar coordinates """
th = d.grange / Re
r = d.height + Re
dop, sth, dth = d.dop, d.sth, d.dth
return th, r, dop, sth, dth | 1d4710152b5dbbbfd09cdc5cbf934f3adb94deeb | 69,890 |
def _corr_vectors(A, B, axis=0):
"""Compute pairwise correlation of multiple pairs of vectors.
Fast way to compute correlation of multiple pairs of vectors without
computing all pairs as would with corr(A,B). Borrowed from Oli at Stack
overflow. Note the resulting coefficients vary slightly from the on... | 51df38f9e1703c98718d3f15b481975ce82f47a2 | 69,891 |
def getGenomesInHal(halFile):
"""Get a set of all genomes in the hal file."""
spaceSeparatedGenomes = popenCatch("halStats --genomes %s" % halFile).strip()
return set(spaceSeparatedGenomes.split(" ")) | fad81779e8a8e8788117099d96526083e8d635b1 | 69,892 |
def diagflat(d, k=0):
"""
Create a two-dimensional array with the flattened input as a diagonal.
Parameters
----------
d : array_like
Input data, which is flattened and set as the `k`-th
diagonal of the output.
k : int, optional
Diagonal to set; 0, the default, correspon... | 6dbf5f72eda5771bd0a7080a353de69a65ebeca3 | 69,893 |
import re
def hasNoProcessExtension(file_name: str):
""" Determine if the file should not be processed, just copied directly """
m = re.search(r'(?<=\.)[^.]+', file_name)
return m.group() in CONFIG['ignoredExtensions'] if m else False | cc67d7e8633454a852f87a7a41aa7d85624cbf21 | 69,894 |
def get_patchy_N0s(qekey_in, npatches, pixivmap_t, pixivmap_p, cls_unl, cls_cmb_dat, cls_cmb_filt, cls_weight, lmin_ivf, lmax_ivf, lmax_qlm, transf,
rvmap_uKamin_t_data=None, rvmap_uKamin_p_data=None, joint_TP=False,
nlevt_fid=None, nlevp_fid=None, cacher=cachers.cacher_mem(), source... | 3e504133ea53409bff3475468843dbf3ae183b87 | 69,895 |
def generate_sphere(radius):
"""Generates a centered boolean mask of a 3D sphere"""
rint = np.ceil(radius).astype('int')
t = np.arange(-rint, rint+1, 1)
x,y,z = np.meshgrid(t, t, t, indexing='ij')
r = np.sqrt(x*x + y*y + z*z)
sphere = r < radius
return sphere | 56b3e45397464701ecd472e90ffc863785646200 | 69,896 |
def find_percentile_coordinate(cube: Cube) -> Coord:
"""Find percentile coord in cube.
Args:
cube:
Cube contain one or more percentiles.
Returns:
Percentile coordinate.
Raises:
TypeError: If cube is not of type iris.cube.Cube.
CoordinateNotFoundError: If no... | 718f4ef482a317784c46c397bf68e8630631e857 | 69,897 |
def get_user_plants(user_id):
"""Returns a list of plants a user has added."""
user_plants = User.query.get(user_id).plants
unpacked_user_plants = {}
for plant in user_plants:
unpacked_user_plants[plant.plant_id] = plant.__dict__
if '_sa_instance_state' in unpacked_user_plants[plant.p... | f2fdd16bc535eab5fcfe28d65f2ebe74dfaeceb5 | 69,898 |
import six
import sh
def apply_sh(actions):
"""Add the shell function to any actions that are strings"""
return [ a if six.callable(a) else sh(a, log_command=False) for a in actions ] | dd2d24fccb0e8d02752a3f5bd86bc0b41161b87d | 69,899 |
def _is_new_prototype(caller):
"""Check if prototype is marked as new or was loaded from a saved one."""
return hasattr(caller.ndb._menutree, "olc_new") | 1282db1ce6ae2e5f0bb570b036d7166a53287229 | 69,900 |
def rotate_from(points, rotation_transform):
"""Rotate an ndarray of given points(x,y) from a given rotation"""
if type(points) != np.ndarray:
raise TypeError("rotate_from: takes an numpy.ndarray")
new_points = []
for point in points:
point_mat = np.mat([[point[0]],[point[1]],[0]], dtype... | 42f04a44a527a74b8a447d284a7484823c57b17f | 69,901 |
from typing import Union
def pix_rad_to_physical(im_prod: Union[Image, RateMap, ExpMap], pix_rad: Quantity, out_unit: Union[UnitBase, str],
coord: Quantity, z: Union[float, int] = None, cosmo=None) -> Quantity:
"""
Pure convenience function to convert a list of pixel radii to whatever ... | fdac0d35890acee58ab786d0c5fad953cc8c2721 | 69,902 |
def _ms_dalt_ind(item):
"""
Sorts elements in a sign-alternating descending order and returns a list
of their previous indices compared to their current ones.
\> Parameters:
`item` : *array-like*
"""
if type(item) == np.ndarray:
raise TypeError('numpy.ndarray not yet supported for... | 31d6836227300415c2b59679150966bcb49e4ded | 69,904 |
def wmt_affine_base_trueadam_longer():
"""Set of hyperparameters."""
hparams = wmt_affine_base_trueadam()
hparams.learning_rate_constant = 4.0
hparams.learning_rate_warmup_steps = 20000
return hparams | a57f749c73288ffd6c397d555844574b63f508a5 | 69,905 |
def leave(playerName):
""" Permet de supprimer un joueur dans la partie en cours
...
"""
plId = func.recupIdFromName(playerName)
# Je le passe a 'false' dans la table Participate
db.execute("""UPDATE Participate par SET present = 'false' WHERE par.pl_id = '"""+ str(plId) +"""';""")
return "",200 | 920bc31cb3bfcd9fc6828b65ed930fa2b94ccd72 | 69,907 |
def get_route_map_entry_by_search(search=dict()):
"""Return a list of RouteMapEntry's by dict."""
try:
objects = RouteMapEntry.objects.filter()
object_map = build_query_to_datatable_v3(objects, search)
except FieldError as e:
raise ValidationAPIException(str(e))
except Exception... | a144abaee91ce3a564a9e6fb25e1d3c62867d76b | 69,909 |
def generate_slug(obj, slug_length):
""" A function to generate a slug with a given length and make sure it's unique. """
slug = get_random_string(slug_length)
slug_is_not_unique = True
while slug_is_not_unique:
slug_is_not_unique = False
other_objs_with_slug = type(obj).objects.filter(id=slug)
if... | 1913d7e888a2ffa3be02faa88db03f0544ae6991 | 69,910 |
from typing import List
import math
def diversity(individuals:List[Individual]) -> float:
"""Computes the diversity of a population. Higher diversity value the better.
Citations:
J. Hu, J. Zeng, and Y. Tan, ‘‘A diversity-guided particle swarm optimizer for dynamic environments,’’ in Bio-Inspired Com... | 339d00261961a1458faea1e412170b8c2ee21020 | 69,911 |
import uuid
def submit_job(function_name, kwargs, queue_name='default'):
"""
Parameters
----------
function_name: string
Name of the function that will be expected
by the waiting process.
kwargs: dict
Keyword arguments to pass to the function.
queue_name: string ['defau... | e1455a62ec699c1b293149bd4727a682cf7a1b1a | 69,913 |
def read_md_file(filepath):
"""Reads an md file and returns the string."""
with open(filepath, "r", encoding="utf-8") as md_file:
md_file_str = md_file.read()
return md_file_str | 35ad658f850be903b6b183e8970c86c894530c62 | 69,914 |
def regression_loss(pred_boxes, gt_boxes, weights):
"""
Regression loss (Smooth L1 loss: also known as huber loss)
Args:
pred_boxes: [# anchors, 4]
gt_boxes: [# anchors, 4]
weights: Tensor of weights multiplied by loss with shape [# anchors]
"""
loss = tf.losses.huber_loss(pr... | e380c9b91269ac6583c1a89b85d2deea3c2db5aa | 69,915 |
def countObjectTypes(objects):
"""Given a list of objects, returns a count of how many of each type there are."""
results = {"rootgroup": 0, "group": 0, "job": 0}
for obj in objects:
if isJob(obj):
results["job"] += 1
elif isGroup(obj):
results["group"] += 1
e... | ab44060e6581d8cbfc8e83d9bb16e308789c6e13 | 69,916 |
def input_fn(split, mode, data_dir, batch_size, cutout_size, num_epochs=1):
"""Input_fn using the tf.data input pipeline for CIFAR-10 dataset.
Args:
mode: train, valid or test.
data_dir: The directory containing the input data.
batch_size: The number of samples per batch.
num_epochs: The number of ... | 6937c6613868f8b852c0c29b17837dac493b9c31 | 69,917 |
import array
from pathlib import Path
def get(java, name):
"""Returns the value of a Java node property as a Python data type."""
datatype = java.getValueType(name)
if datatype == 'Boolean':
return java.getBoolean(name)
elif datatype == 'BooleanArray':
return array(java.getBooleanArray... | aa70914ffe3180de22d7edea0f3c06c9482cdd4c | 69,918 |
def grid(gdf):
"""
sampling the GNSS data by grids
Parameters
----------
gdf: geodataframe
geodataframe of all gnss data(population)
Returns
-------
list:
list of each grid which contains all related gnss data
"""
#create new column to... | f613359a0061fd2975607044ffcaa8b25b53dcfc | 69,919 |
def convertColorTable(table):
"""Converts a Kaitai Struct-parsed color table to a list of matplotlib color maps"""
cdict = {
"red": [],
"green": [],
"blue": []
}
countOfColors = len(table.colors)
maxColorIndex = countOfColors - 1
for i, col in enumerate(table.colors):
for compName in cdict:
comp = geta... | 2a513a4ecaf60a81c7bf650ba524af29ff51e96f | 69,920 |
def _filter_label_set_to_most_specific(
label_set,
reversed_normalizer):
"""Filters label set to most specific.
Args:
label_set: set of all labels given to protein.
reversed_normalizer: output of reverse_map(label_normalizer). Helps this
function run fast.
Returns:
Filtered set of labe... | 84397b8a6c208b88c13456805be592d9f2e9a505 | 69,921 |
def get_tasks_for_weekly_report(model_obj, company, date_from, date_to):
"""Отдает отфильтрованный кверисет с уникальными датой и описанием"""
return model_obj.objects.select_related(
'tag', 'employees').filter(
date__gte=date_from).filter(
date__lte=date_to).filter(
... | 3b46205d3c1bb5b5d472b350371561167aa2fb5b | 69,922 |
def detectFallingSeq(points_list):
"""Find falling temperatures sequences in given list and stores beginnings and ends of them in list.
Always with format [seq1 start index, seq1 end index, seq2 start index, seq2 end index, ...]
:param points_list: list of pipe temperatures
:return: list of indexes
... | e940497b72745af1669062373a6aca025ac0626c | 69,924 |
async def find_app(hass: HomeAssistantType, api):
"""Find an existing SmartApp for this installation of hass."""
apps = await api.apps()
for app in [app for app in apps if app.app_name.startswith(APP_NAME_PREFIX)]:
# Load settings to compare instance id
settings = await app.settings()
... | 57787205e3fd9ea94607d2c4cc62e60d8bd48257 | 69,925 |
def count_symbols(atoms, exclude=()):
"""Count symbols in atoms object, excluding a set of indices
Parameters:
atoms: Atoms object to be grouped
exclude: List of indices to be excluded from the counting
Returns:
Tuple of (symbols, symbolcount)
symbols: The unique symbols in... | 31f7c116f07788171828f0e116ef28a43eb0e313 | 69,926 |
def extract_bboxes(mask):
"""Compute bounding boxes from masks.
Args:
mask [height, width, num_instances]:
Mask pixels are either 1 or 0.
Returns:
bounding box array [num_instances, (y1, x1, y2, x2)].
"""
boxes = np.zeros([mask.shape[-1], 4], dtype=np.int32)
for i i... | f303ba362be567d8b981630201ba913c4b987bf0 | 69,927 |
import functools
def ignore_transport(transport):
"""
If test function is wrapped into this decorator then
it should not be tested if test is performed for
specified transport
"""
def wrapper(func):
@functools.wraps(func)
def test_method(*args, **kwargs):
if GRAB_T... | b39d1b7db2b82722e39159cdf7b529d5f88caa65 | 69,928 |
import ntpath
def lookup_folder(event, filesystem):
"""Lookup the parent folder in the filesystem content."""
for dirent in filesystem[event.parent_inode]:
if dirent.type == 'd' and dirent.allocated:
return ntpath.join(dirent.path, event.name) | e18df4610bba9cf71e85fe0038a5daf798822bd3 | 69,929 |
import json
def parse_response(func):
"""Parse receive response to json format."""
def wrapper(*args, **kwargs):
response = func(*args, **kwargs)
try:
return response.json()
except json.JSONDecodeError:
return {
"success": False
}
... | 7ad55e524c52cf151e2de8c29d6c2ea786b21a9a | 69,930 |
def ret (numerator,denominator,code):
"""
Divides two dataframes by transposing and using linear algebra rules
"""
df_tradingret = numerator.T / denominator -1
df_tradingret = df_tradingret.T
df_tradingret = pd.concat ([df_tradingret, code], axis=1)
return df_tradingret | 243ab30c44cda82ff7bbf8174a3644efbc22811b | 69,931 |
def read_xyz(filedesc):
"""Takes a xyz-style file and creates an Atoms object.
Args:
filedesc: An open readable file object from a xyz formatted file.
Returns:
An Atoms object with the appropriate atom labels, masses and positions.
"""
natoms = filedesc.readline()
if natoms == "":
... | 44444a452bc364ac9df76674ed60e0482666a34d | 69,932 |
import hashlib
def create_unique_shape_id(line_string: LineString):
"""
Creates a unique hash id using the coordinates of the geomtery
Args:
line_string: Line Geometry as a LineString
Returns: string
"""
x1, y1 = list(line_string.coords)[0] # first co-ordinate (A node)
x2, y2 = lis... | afb57e4bef7baab401467e073d484a4131a1d32e | 69,933 |
def p27():
""" a and b s.t n*n + a*n + b produces the longest sequence of primes """
maxLen, res = 0, 0
for a in xrange(-999, 1000):
for b in xrange(-999, 1000):
seqLen = getLen(a, b)
if seqLen > maxLen:
maxLen = seqLen
res = a*b
return res | 1db5ad6cc2d8484f5494aab5234d3b88e7c97f2f | 69,935 |
def gate_expand_2toN(U, N, control, target):
"""
Create a Qobj representing a two-qubit gate that act on a system with N
qubits.
Parameters
----------
U : Qobj
The two-qubit gate
N : integer
The number of qubits in the target space.
control : integer
The index ... | 3501a6b785092b95ce9f95d8b1b617a78c5d8863 | 69,936 |
import html
def test_cdcb003_dict_callback_strict_true(dash_duo):
""" Test if strict is True an extra output keys in output dictionary causes a KeyError
At this point I don't know how to write an assertion for this
"""
lock = Lock()
app = dash.Dash(__name__, plugins=[DashCallbackPlugin()])
ap... | 044b8ee80d8eebcd32d67aae8494aacfdf532c14 | 69,937 |
def extract_user(ops, json_data):
""" Extract user from JSON data.
"""
if json_data is None:
return None
if 'required_posting_auths' not in ops or 'required_auths' not in ops:
return None
if ops['required_posting_auths'] is None or ops['required_auths'] is None:
return None
... | 0722afa2f174628670658fbbc0f1a0ab80cd36fe | 69,938 |
from itertools import izip
def _slow_pivot(index, columns, values):
"""
Produce 'pivot' table based on 3 columns of this DataFrame.
Uses unique values from index / columns and fills with values.
Parameters
----------
index : string or object
Column name to use to make new frame's inde... | f5eab1b016424c0cd4922b537aa573b66f0a663d | 69,939 |
def calculate_adjusted_elo_rating(player_one_rating: int, player_two_rating: int, player_one_win: bool, k_factor=32) -> (int, int):
"""
Calculates new elo scores for two players
:param player_one_rating: first player's original rating
:param player_two_rating: second player's origin rating
:param player_one_... | 2792981c6b50836897c5c2396e35bcce7026a716 | 69,940 |
import io
def usgs_lead_call(*, resp, year, **_):
"""
Convert response for calling url to pandas dataframe, begin parsing
df into FBA format
:param url: string, url
:param resp: df, response from url call
:param year: year
:return: pandas dataframe of original source data
"""
df_ra... | 500e8a61c287b4311f6abd8fe32362b55ac5b544 | 69,941 |
def ParseDeviceBlocked(blocked, enable_device):
"""Returns the correct enabled state enum based on args."""
if enable_device is None and blocked is None:
return None
elif enable_device is None or blocked is None:
# In this case there are no default arguments so we should use or.
return blocked is True... | 4554ca5e33194fea77516e910516f3937cd61f3a | 69,942 |
import random
def blobs(
width=8,
height=8,
k=3,
min_extend=0,
max_extend=1,
random_seed=None):
"""Generates a 1 to k number of blobs on a 2D grid
Args:
width: width of grid generated
height: height of grid generated
k: number of random ... | 44fa440913dbf5ecfc16e03972a48c6713d47406 | 69,943 |
def load_env() -> Environ:
"""Load environment variables and expand hierarchy as namespace."""
return Environ(prefix='PLOT').expand() | abda28d07ac2205f9bbf45b8dea8c2c6b03ec697 | 69,945 |
def squared_pearson_correlation_r2(results, labels, pos=1, neg=0):
"""
Citation: MITTLBÖCK, M. and SCHEMPER, M. (1996), EXPLAINED VARIATION FOR LOGISTIC REGRESSION. Statist. Med., 15: 1987-1997.
doi:10.1002/(SICI)1097-0258(19961015)15:19<1987::AID-SIM318>3.0.CO;2-9.
https://pdfs.semanticscholar.org/39f1... | b12de91d6c2e781fe5681f3ac58b07d32bfbe493 | 69,946 |
from typing import Dict
from typing import Any
def grains_filter_by(
salt_mock: SaltMock,
lookup_dict: Dict[str, Any],
grain: str = "os_family",
**kwargs: Any,
) -> Any:
"""Read grains from a SaltMock instance to implement grains.filter_by.
See https://github.com/saltstack/salt/blob/v3002.5/s... | bcbf632adf2b5397f67c2b5d223f8cb215884b81 | 69,947 |
def exists(reader_name: str) -> bool:
"""Check whether the given reader exists
Args:
reader_name: Name of reader.
Returns:
True if reader exists, False otherwise.
"""
return plugins.exists(package_name=__name__, plugin_name=reader_name) | 99ff673a4110a601500ae4c3e3367c64c21b4d0d | 69,948 |
def is_broken_link(url):
"""Determine whether the link returns a 404 error."""
try:
request = urllib_request.Request(
url, headers={'User-Agent': 'Mozilla/5.0'})
urllib_request.urlopen(request).read()
return False
except urllib_request.URLError:
return True
ex... | 12afac7aec8b8465a968e6bb7a2df9e9bdb0de8d | 69,950 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.