content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import ast
def get_import_stmt_str(alias_list, import_src=None, max_linechars=88):
"""
Construct an import statement by building an AST, convert it to source using
astor.to_source, and then return the string.
alias_list: List of strings to use as ast.alias `name`, and optionally also
... | f4c7dad79b7c949bd7e9045b9c9ae474a09303d2 | 34,217 |
def convert_into_decimal(non_binary_number: str, base: int) -> int:
"""
Converts a non binary string number into a decimal number
:param non_binary_number:
:param base:
:return: a decimal number
"""
decimal_number = 0
for digit in range(len(non_binary_number)):
decimal_number += int(n... | fecdd152000399fbc33a259a647118b0607daac9 | 34,218 |
from typing import Sequence
def sgld_sweep() -> Sequence[SGMCMCConfig]:
"""sweep for vanilla sgld."""
sweep = []
for learning_rate in [
1e-5, 5e-5, 1e-4, 5e-4, 1e-3, 5e-3, 1e-2
]:
for prior_variance in [0.01, 0.1, 0.5]:
sweep.append(SGMCMCConfig(learning_rate, prior_variance))
return tuple(s... | 9f64505c8aa7efb33f2fbc4a7e0756ef896ee9c3 | 34,219 |
def stringify(num):
"""
Takes a number and returns a string putting a zero in front if it's
single digit.
"""
num_string = str(num)
if len(num_string) == 1:
num_string = '0' + num_string
return num_string | 7cf37776bc774d02bce0b2016d41b26b8ab94cf7 | 34,220 |
def euc_distance(vertex, circle_obstacle):
"""
Finds the distance between the point and center of the circle.
vertex: Vertex in question.
circle_obstacle: Circle obstacle in question.
return: Distance between the vertex and the center of the circle.
"""
x = vertex[0] - circle_obstacle.posi... | 60ed338eb7a81fc282196c38d41cecda8f28efb7 | 34,222 |
def less(x, y):
"""
Returns the truth value of (x < y) element-wise.
Parameters
----------
x : tensor
Must be one of the following types: float32, float64, int32, uint8,
int16, int8, int64, bfloat16, uint16, half, uint32, uint64.
y : tensor
A Tensor. Must have the same t... | 6db5cf54e7f23e174050676f7f1e319e8dd6982d | 34,223 |
def decision_tree_learning(examples: list, attributes: list, parent_examples,
importance_function: callable):
"""
Decision tree learning algorithm as given in figure 18.5 in Artificial
Intelligence A Modern Approach.
:param examples: list of dictionaries containing examples t... | df9dd631b5df38451e03cfab65d8a8c0f6a218eb | 34,225 |
def modified_bessel(times, bes_A, bes_Omega, bes_s, res_begin, bes_Delta):
""" Not Tested. """
b = np.where(times > res_begin + bes_Delta / 2.,
special.j0(bes_s * bes_Omega *
(- res_begin + times - bes_Delta / 2.) ),
(np.where(times < res_begin - bes_Delta / 2.,
spe... | 1afcb27b53b364199289dff2bd7850fe6e5027fa | 34,226 |
def predict_csr_val(csr_op, rs1_val, csr_val, csr_mask):
"""
Predicts the CSR reference value, based on the current CSR operation.
Args:
csr_op: A string of the CSR operation being performed.
rs1_val: A bitarray containing the value to be written to the CSR.
csr_val: A bitarray containing the current... | 1e8be22540b89db9719ea078dbb4e1d11e53bdcc | 34,227 |
def request(url: str, args: dict = None, method: str = 'GET'):
"""
Custom Method that requests data from requests_session
and confirms it has a valid JSON return
"""
response = request_session(url, method, args)
try:
# you only come here if we can understand the API response
retu... | 603712a7aa2978fc00e664eaebf18929108064e3 | 34,228 |
def create_se3(ori, trans=None):
"""
Args:
ori (np.ndarray): orientation in any following form:
rotation matrix (shape: :math:`[3, 3]`)
quaternion (shape: :math:`[4]`)
euler angles (shape: :math:`[3]`).
trans (np.ndarray): translational vector (shape: :math:`[... | c564b8e3761b737bfc95c94e5134c57cec05805e | 34,230 |
def build_negative_log_likelihood(
image,
telescope_description,
oversampling,
min_lambda,
max_lambda,
spe_width,
pedestal,
hole_radius=0 * u.m,
):
"""Create an efficient negative log_likelihood function that does
not rely on astropy units internally by defining needed values as ... | 10c481448b1b2eb2e09eb4d76dda228bc6ed894d | 34,231 |
import collections
def _ParseParameterType(type_string):
"""Parse a parameter type string into a JSON dict for the DF SQL launcher."""
type_dict = {'type': type_string.upper()}
if type_string.upper().startswith('ARRAY<') and type_string.endswith('>'):
type_dict = collections.OrderedDict([
('arrayTyp... | 213a6d6e119c76da7fc6193493e11b57e260f200 | 34,233 |
import time
def get_now_utc_epoch():
"""
Returns the epoch
:return:
"""
return int(time.time()) | 7e9836908aed9598bab1f01365fe255aa43a94e0 | 34,234 |
from typing import List
def get_top_words(text: str, blacktrie: dict, top_n: int) -> List[str]:
"""Get top words in a string, excluding a predefined list of words.
Args:
text (str): Text to parse
blacktrie (dict): Trie built from a blacklist of words to ignore
top_n (int): Number of top words to return
Ret... | 20839162d06447f7651c1051ed88feef9d62db72 | 34,235 |
def get_fluid_colors(fXs, fVs, normalize=False):
## I realized that with limited data, this coloring does not make much sense
"""
Given the velocity field (Ux, Uy) at positions (X,Y), compute for every x in (X,Y) if the position is contributing to the inflow or the outflow. This can be obtained by u*x (scal... | cda836658f30c7f8cfd96d774f2654e2a056de51 | 34,236 |
def getitem(x, item):
"""returns specific item of a tensor (Functional).
# Arguments
item: Item list.
# Returns
A new functional object.
"""
validate_functional(x)
res = x.copy()
ys = []
lmbd = [Lambda(lambda xx: xx.__getitem__(item)) for xx in x.outputs]
for l, y ... | 7854bad7ff67aa3d04be7e26b25785832ce04522 | 34,237 |
import torch
from typing import Optional
def norm_range(
data: torch.Tensor, min: float, max: float, per_channel: bool = True, out: Optional[torch.Tensor] = None
) -> torch.Tensor:
"""
Scale range of tensor
Args:
data: input data. Per channel option supports [C,H,W] and [C,H,W,D].
min... | 52f36f0b9a74d8813ee72bc7a773620e92c4923b | 34,238 |
def get_mvarg(size_pos, position="full"):
"""Take xrandrs size&pos and prepare it for wmctrl (MVARG) format
MVARG: <G>,<X>,<Y>,<W>,<H>
* <G> - gravity, 0 is default
"""
allowed = ["left", "right", "top", "bottom", "full"]
if position not in allowed:
raise ValueError(f"Position has... | 0b8a9c3f5ca7e24212502a3f2c76b18167deef6e | 34,239 |
def fr2date(edate, **kwargs):
"""
Wrapper function for :func:`date2date` with French input and
standard output date formats
That means `date2date(edate, fr=True, **kwargs)`;
but *fr* given in call will overwrite *fr=True*.
Examples
--------
>>> edate = ['12/11/2014 12:00', '01/03/2015 ... | 4bdf32e344585caa159d64bcdaa3e870b41f8633 | 34,240 |
def convert_species_tuple2chianti_str(species):
"""
Convert a species tuple to the ion name format used in `chiantipy`.
Parameters
-----------
species: tuple (atomic_number, ion_number)
Returns
--------
str
ion name in the chiantipy format
Examples
---------
>>> co... | d37aa9c9a9e186febc4ef6df2f3b53f9110ace7a | 34,241 |
import hashlib
def vote(request, village_no, day_no):
"""投票処理"""
vote_id = request.POST['vote']
login_id = request.session.get('login_id', False)
participant = VillageParticipant.objects.get(village_no=village_no, pl=login_id, cancel_flg=False)
ability = VillageParticipantExeAbility.objects.get(vi... | 4935ee87645d037e9455e61c588168f3f276f8ce | 34,243 |
def read_header_offsets(file, block_size):
"""Reads the PBDF header (not checking the included file size) and returns the list of offsets adjusted to match
decrypted data positions.
Args:
file: The decrypted input file.
block_size (int): The block size in bytes at which end a checksum is pla... | cf2d5c89083bebf3dff1b92bd2365e1a62b2f97e | 34,244 |
def level_2_win_play(x):
"""
Probability that a deck with x SSGs will win on the play using level two reasoning
:param int x: SSGs in deck
:return float:
"""
return sum([
level_2_hand_odds_play(i, x) * mull_to_play(i, x) for i in range(0, 8)
]) | 94834ad0cc603b2923c0f5c441def95196197c25 | 34,245 |
def getfullargspec(func):
"""Get the names and default values of a function's arguments.
A tuple of seven things is returned:
(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** argumen... | d239d6d9b7399689157d6a5f025148e287f06b68 | 34,246 |
import json
def get_json(file_path):
"""
Faz a leitura de um arquivo Json com codificacao utf-8,
apenas para arquivos dentro do diretorio folhacerta_settings
:param file_path: (string) nome do arquivo json com extensao
:return: Dicionario com os dados do json
"""
with open... | bd475d7427705026ad17d32d25a1a016d6c6f93d | 34,247 |
def color_array(arr, alpha=1):
""" take an array of colors and convert to
an RGBA image that can be displayed
with imshow
"""
img = np.zeros(arr.shape + (4,))
for row in range(arr.shape[0]):
for col in range(arr.shape[1]):
c = mpl.colors.to_rgb(arr[row, col])
img[... | dbfdf7e78788365f6bc0bb61b7c7607aec79e250 | 34,248 |
def showturtle():
"""Makes the turtle visible.
Aliases: showturtle | st
No argument.
Example (for a Turtle instance named turtle):
>>> turtle.hideturtle()
>>> turtle.showturtle()
"""
return __SingletonTurtle().showturtle() | 011edcca34c25d42831826c73f8a823d992448b7 | 34,249 |
def get_setting(db, name):
"""
Get a specific setting
@param db The database connection
@param name The setting's name
@return The setting's value
"""
result = _query(db, "SELECT value FROM settings WHERE name=%(name)s;", { "name" : name })
if len(result) > 0:
return getattr(res... | 1a82faf9e2f222328d9deb9c0beb19a8a7b22862 | 34,250 |
def check_table_exists(client: AitoClient, table_name: str) -> bool:
"""check if a table exists in the instance
:param client: the AitoClient instance
:type client: AitoClient
:param table_name: the name of the table
:type table_name: str
:return: True if the table exists
:rtype: bool
"... | b45a7cbe8a896040903af6f5ece177d53773d098 | 34,252 |
def bytes_to_str(s, encoding='latin-1'):
"""Extract null-terminated string from bytes."""
if b'\0' in s:
s, _ = s.split(b'\0', 1)
return s.decode(encoding, errors='replace') | 7d98d91443ab16478f1b8ecba39311110e92009c | 34,253 |
from typing import Pattern
import re
from typing import Optional
from typing import Match
from typing import AnyStr
from typing import Dict
def get_time_delta(time_string: str) -> timedelta:
"""
Takes a time string (1 hours, 10 days, etc.) and returns
a python timedelta object
:param time_string: the... | 8a1df45286f0994e1f9aab4f4209ea14f639e8b9 | 34,254 |
def lens_of(data):
"""Apply len(x) to elemnts in data."""
return len(data) | e10cba2bd801afd8f41dd0b15bfc23b7849c06ba | 34,255 |
from typing import Any
def _format_phone(
phone: Any, output_format: str, fix_missing: str, split: bool, errors: str
) -> Any:
"""
Function to transform a phone number instance into the desired format.
The last component of the returned tuple contains a code indicating how the
input value was cha... | 97341088f03f5d276339c83d0061bbfec28933b9 | 34,256 |
def mvg_all_joints(jLs, face_keypoints=True, upper_sternum=True, upper_body=True, lower_body=True, wsize=6):
"""
:param jLs: list of lists with length 54 derived from text file
including x,y,z coordinates for each joint as separately list.
:type jLs: list
:param face_keypoints... | cf6b2d5092cbbf902fe33902efbb4ca9dbe32d74 | 34,257 |
def check_in_all_models(models_per_expt):
"""
Check intersection of which models are in all experiments
:param models_per_expt: an ordered dictionary of expts as keys with a list of valid models
:return: list of models that appear in all experiments
"""
in_all = None
for key, items in mod... | 75e17b8558a592471dda8a855959f60c40b06759 | 34,258 |
import torch
def _translate_x(video: torch.Tensor, factor: float, **kwargs):
"""
Translate the video along the vertical axis.
Args:
video (torch.Tensor): Video tensor with shape (T, C, H, W).
factor (float): How much (relative to the image size) to translate along the
vertical... | 925a9dc0b67b70330937b38cc1694c8cebd93e1c | 34,259 |
import numpy
def get_volume_pixeldata(sorted_slices):
"""
the slice and intercept calculation can cause the slices to have different dtypes
we should get the correct dtype that can cover all of them
:type sorted_slices: list of slices
:param sorted_slices: sliced sored in the correct order to cre... | f935a3b820211fe1535a95d24f021cc2e8d48fbe | 34,260 |
import logging
def read_val_dataframe_from_hdf5(input_pattern, val_fold=0):
"""Reads the hdf5 tables for the validation fold only.
Args:
input_pattern: String with the path for the hdf5 with a '%d' for the fold.
val_fold: Integer. The zero-based validation fold num.
Returns:
A pandas dataframe cont... | 894e59c893b6e2eb7beaa7bd2dd67ac2eeca7a99 | 34,261 |
from pathlib import Path
def hash_file(hash_obj, fout: Path):
"""Create a hash of the file.
Parameters
hash_obj () The hash object
fout (Path) : Path to file to be written.
Return
str : If fout was found.
None : If fout was not found.
"""
try:
with fout.open('r... | b57b87b192dbd63a3cd3136ffd7a6b98fd8ed7dd | 34,262 |
import scipy
def Get_Wav_EMA_PerFile(EMA_file, Wav_file, F, EmaDir, MFCCpath, BeginEnd, XvectorPath, cfg):
"""Return mean and variance normalised ema, mfcc, and x-vectors if required (of the cross-corpus).
Parameters
----------
EMA_file: str
path to ema file
Wav_file: str
path ... | 91d77fb4dd2a3202f7c94db2fa7a029c9562b63a | 34,263 |
def is_class_name(class_name):
"""
Check if the given string is a python class.
The criteria to use is the convention that Python classes start with uppercase
:param class_name: The name of class candidate
:type class_name: str
:return: True whether the class_name is a python class otherwise Fa... | 2b4b6a09f2a112f7e8163f3caf97fdfca0c93e12 | 34,264 |
def is_pesummary_json_file_deprecated(path):
"""Determine if the results file is a deprecated pesummary json file
Parameters
----------
path: str
path to results file
"""
return _is_pesummary_json_file(path, _check_pesummary_file_deprecated) | 49ddd8f84e259cf26955220013bcfe7003bcca5d | 34,265 |
def popart(image_array):
"""
Applique la fonction popart 4 fois avec des paramètres un peu différents
:return: une image avec moins de couleurs.
"""
h = get_image_height(image_array)
w = get_image_width(image_array)
small_height = h // 2
small_width = w // 2
small_image = image_array... | 77b8af2bc5db976289a94118d8e01789c535b2b0 | 34,266 |
from AugSeg.get_instance_group import extract
from AugSeg.affine_transform import transform_image, transform_annotation
from datasetsAug.roidb import combined_roidb_for_training
def _get_image_blob(roidb, coco):
"""Builds an input blob from the images in the roidb at the specified
scales.
"""
num_imag... | 637983405303c304bdf480feca7ea29f1a06d6a6 | 34,267 |
def solve_lu(A, P, B, options=MATPROP.NONE):
"""
Solve a system of linear equations, using LU decomposition.
Parameters
----------
A: af.Array
- A 2 dimensional arrayfire array representing the coefficients of the system.
- This matrix should be decomposed previously using `lu_inplac... | 96eb1f222618c5b17db48a69535204b6246b873f | 34,268 |
import mimetypes
def guess_type(filename, strict=False, default="application/octet-stream"):
""" Wrap std mimetypes.guess_type to assign a default type """
content_type, encoding = mimetypes.guess_type(filename, strict=strict)
if content_type is None:
content_type = default
return content_type, encoding | ae3dae1d005797b2dc96cd893f4a79d20922e6a2 | 34,269 |
def _lookup_alias(aliases, value):
"""
Translate to a common name if our value is an alias.
:type aliases: dict of (str, [str])
:type value: str
:rtype: str
>>> _lookup_alias({'name1': ['alias1']}, 'name1')
'name1'
>>> _lookup_alias({'name1': ['alias1', 'alias2']}, 'alias1')
'name1... | df0641b1f8aca964f76afd2a83fb91a587d52e1d | 34,270 |
def triplet_loss(anchor, positive, negative, alpha):
"""Calculate the triplet loss according to the FaceNet paper
Args:
anchor: the embeddings for the anchor images.
positive: the embeddings for the positive images.
negative: the embeddings for the negative images.
Returns:
t... | 7c3d218833e86f62a0de493ff8dc1045fd3a7788 | 34,271 |
import json
def loadConfig() -> list:
"""Loads configuration from CONFIG_PATH
Returns:
[list] -- the CONFIG_VARS as loaded from CONFIG_PATH
"""
configData = json.load(open(CONFIG_PATH, 'r', encoding='utf-8'))
returnValue = []
# make sure we're not missing anything
for configItem i... | f115cd8896ca5d52086f4054cc7fb5a05c230d0e | 34,272 |
import httpx
async def get_corrected_name_api(keyphrase: str) -> str:
"""
Get corrected artist name via Last.fm API method
artist.getCorrection. See: https://last.fm/api/show/artist.getCorrection
:param keyphrase: Name of an artist or a band.
:return: Corrected artist name.
"""
async with ... | befe2f89b233bf0453873d710531483e61832786 | 34,273 |
def missing_columns(df, missing_threshold=0.6):
"""Find missing features
Parameters
----------
df : pd.DataFrame, shape (n_samples, n_features)
Training data, where n_samples is the number of samples and n_features is the number of features.
missing_threshold : float, default=0.6... | 4d31673670d894556b6571a0233ec36c8452570a | 34,274 |
import re
import yaml
def read_message(raw_data: bytes):
"""Reads a UDP raw message, split the metadata, and decode data.
:param raw_data: Raw UDP packet
:type raw_data: bytes
:return: Metadata and decoded data required for packet reassembly.
:rtype: tuple
"""
header, data = read_raw_mess... | bd039b55f579971be6750519bcc79f5ac6670ea4 | 34,276 |
def is_ordered(treap):
""" Utility to check that every node in the given Treap satisfies the following:
Rules:
- if v is a child of u, then v.priority <= u.priority
- if v is a left child of u, then v.key < u.key
- if v is a right child of u, then v.key > u.key
"""
# iterate through all n... | 38b7fd7690931e017e9ece52b6cba09dbb708400 | 34,278 |
def log_prob(x, df, loc, scale):
"""Compute log probability of Student T distribution.
Note that scale can be negative.
Args:
x: Floating-point `Tensor`. Where to compute the log probabilities.
df: Floating-point `Tensor`. The degrees of freedom of the
distribution(s). `df` must contain only posit... | 6714c53e1be59aaa8c9194ea30b6e51d665caba9 | 34,279 |
def get_cleaned_query_data_http_error(handler, *args):
"""
同上
:param handler:
:param args:
:return:
"""
data = {}
for k in args:
try:
data[k] = clean_data(handler.get_query_argument(k))
except MissingArgumentError:
raise HTTPError(400)
return d... | f5513034be8cd9082a3ad632c77ed4d364644819 | 34,281 |
import http
from datetime import datetime
def CreateOrUpdateActivity(request, program, activity=None):
"""Creates or updates an activity.
Caller must provide the program. Activity is optional when creating a new one.
Args:
request: A request.
program: A models.Program under which we are either creatin... | 15ddb2a423a82f4a3ebfda43b20a697be54d0d1d | 34,282 |
import json
def dowork(lon, lat):
""" Actually do stuff"""
pgconn = get_dbconn('postgis')
cursor = pgconn.cursor()
res = dict(mcds=[])
cursor.execute("""
SELECT issue at time zone 'UTC' as i,
expire at time zone 'UTC' as e,
product_num,
product_id
from text_products WHERE pil... | 4acc671cd3701562866c237b06267f7b5038413b | 34,283 |
from scdali.models.gp import SparseGP
def run_interpolation(
A, D,
cell_state,
kernel='Linear',
num_inducing=800,
maxiter=2000,
return_prior_mean=False,
n_cores=1):
"""Run scDALI interpolation of allelic rates for each region.
A, D are assumed to be n-b... | ccc07014ebae18a37e878f34c968b84b23995a5f | 34,284 |
def extended_knapsack_dp(value_set, weight_set, total_allowed_weight, max_number_of_elements):
"""Knapsack with limited number of elements allowed.
Notes
-----
The rows are the number of elements in value_set
Columns are the number of weights, ranging from 0 to weight_set.
The third dimension ... | 85527b28706a92eeb822594a0a98e90e4e6f6257 | 34,285 |
def get_matrix_rbf(X, var, have_var=True):
"""e^-||(x_i - x_j)||/ 2*var^2 RBF"""
(rows, _) = X.shape
K = np.empty((rows, rows))
for i in range(rows):
c = np.sum(np.abs(X - X[i]) ** 2, axis=-1) ** (1. / 2) # norm
if (have_var):
c = c / (2 * (var ** 2))
K[i] = c
w ... | b5260a44a1abca1ddbf9703a68e9a562feb22dc6 | 34,287 |
import time
import logging
def buildDict(filterKeys=None, mapColumns=False, targetDatasets=None):
""" Maps the dataset names, contained tables, and contained
columns in the projects BigQuery.
Args:
filterKeys (LIST of STRING): A list of substrings,
one of which must be included in
the table n... | 882ab375eacd946f8d3751055076566d30a1af46 | 34,289 |
from functools import reduce
def build_gaussian_pyramid(im, max_levels, filter_size):
"""
Construct a Gaussian pyramid for a given image
:param im: a grayscale image with double values in [0,1]
:param max_levels: the maximal number of levels in the resulting pyramid.
:param filter_size: the size o... | 9e7975695a3ba435644595ea6c2ce1e876d022b1 | 34,290 |
def broadcast_weeks(start, end):
"""return broadcast weeks with start, end for date range"""
starts = broadcast_week_starts(start, end)
return [(start, start+timedelta(days=6)) for start in starts] | 1a19fb8128104c480d2c2bd2ccd2b3c4e7a2d428 | 34,292 |
def _aix_iqn():
"""
Return iSCSI IQN from an AIX host.
"""
ret = []
aix_cmd = "lsattr -E -l iscsi0 | grep initiator_name"
aix_ret = salt.modules.cmdmod.run(aix_cmd)
if aix_ret[0].isalpha():
try:
ret.append(aix_ret.split()[1].rstrip())
except IndexError:
... | f51a1f95bb42db9f8bc42ae26f8409074d3c81f7 | 34,293 |
def generate_token(user):
""" Currently this is workaround
since the latest version that already has this function
is not published on PyPI yet and we don't want
to install the package directly from GitHub.
See: https://github.com/mattupstate/flask-jwt/blob/9f4f3bc8dce9da5dd8a567dfada0854e0cf656ae/f... | e357d33f0ba8ee5a80f1d45d3576e0676ca6660d | 34,294 |
from typing import Counter
def calculate_lines_per_gloss(lines):
"""
Calculates lines per gloss of lines
Parameters
----------
lines : list
lines in the corpus
Returns
-------
number : int
the count of lines per gloss
"""
line_counts = [len(x[1]) for x in lin... | 5e7a3ab4b819f4a7dd0cc7053eb09a5572e5f448 | 34,296 |
def random_selection(population: np.ndarray, mut_p: float) -> np.ndarray:
"""Randomly select genes to mutate
Args:
population (np.ndarray): Population of chromosomes
chromosome_size (int): Number of genes per chromosome
mut_p (float): Mutation probability
Returns:
np.ndarra... | b498bf816d085aa1cd4a2f68d144e4b4df051d77 | 34,297 |
def _combo_runner(fn, combos, constants, split=False, parallel=False,
num_workers=None, executor=None, verbosity=1, pool=None):
"""Core combo runner, i.e. no parsing of arguments.
"""
executor = _choose_executor_depr_pool(executor, pool)
n = prod(len(x) for _, x in combos)
ndim = ... | 86a57d1800457166395ae2baa4e04ca8ea4c0cdf | 34,298 |
from typing import Sequence
import fnmatch
def _should_ignore(fd_name: str, patterns: Sequence[str]) -> bool:
"""Return whether `fd_name` should be ignored according to `patterns`.
Examples
--------
>>> fd_name = "google/protobuf/empty.proto"
>>> pattern = "google/protobuf/*"
>>> _should_igno... | 8bf698afddbda869e26ebcaa98e1f4e950117c08 | 34,300 |
def unc_inertia_eval(awg, afg, bout, bi, mw, ed, out_xml):
""" Unconventional aircraft Moment of Inertia analysis main function.
It dvides the cases defined and evaluates them calling the
function in the with_fuse_geom subfolder.
Source: An introduction to mechanics, 2nd ed., D. Kleppner
... | cff3ebe8f0e613c5742c3d16bae29dfcc0998d2a | 34,301 |
import json
def str2body(v):
"""
convert str to json data or keep original string
:param v:
:return:
"""
try:
return json.loads(v)
except:
return v | 5785d9dca1d1120a4827feb93382d1d0bf68519a | 34,302 |
from datetime import datetime
def get_default_law_key():
""" Default key needs to be unique timestamp until changed """
x = str(datetime.now())
key = x[5:25]
return key | 569d1ff7cc9c6d0e95dded80c1e068ff885e95c7 | 34,303 |
def _evaluate_Delaunay_component(
subgraph_RE_comp: nx.Graph,
subgraph_R_comp: nx.Graph,
subgraph_E_comp: nx.Graph,
num_R: int,
):
"""
Phase 3
Evaluates given graph-connected component.
:param subgraph_RE_comp: Delaunay graph of the component containing R and E points..
:param subgra... | 98f12800201cf89f3a92c07d93d9b446e019ec60 | 34,304 |
def abcd_normalize(A=None, B=None, C=None, D=None):
"""Check state-space matrices and ensure they are two-dimensional.
If enough information on the system is provided, that is, enough
properly-shaped arrays are passed to the function, the missing ones
are built from this information, ensuring the corre... | 2292347708f93570d96062d6e94058e55c96b112 | 34,307 |
def extract_full_symbol(full_symbol: str):
"""
:return: (symbol, exchange)
"""
tmp = full_symbol.split(' ')
if len(tmp) < 4:
return "unknwonsymbol", Exchange.SHFE
symbol = tmp[2] + tmp[3]
exchange_str = tmp[0]
ex = Exchange(exchange_str)
if ex in [Exchange.SHFE, Exchange.DCE,... | 7e031bfb969215092765a33cdb93377a6c98d922 | 34,309 |
def remove(user_id):
"""User removing"""
user = User.query.get(user_id)
db.session.delete(user)
db.session.commit()
flash('User "%s" successfully remove' % user.name, 'success')
return redirect(url_for('backend.index')) | 33ced3d0e54a3edcc04e89440faca6778dd65944 | 34,310 |
from typing import Dict
from typing import List
from typing import Tuple
def phonemes_to_sentences(
arpabet: Dict[str, List[List[str]]],
data: Tuple[List[list], ...],
print_every: int,
of: int,
) -> Tuple[str, ...]:
"""Convert list of phoneme lists to sentences."""
data = [
(
... | 25f21e79f5029a80adeb4bd277c273db1e0caf31 | 34,311 |
def butter_bandpass_filter(flux, lowcut, fs, order=3):
"""
Apply a Butterworth high-pass filter.
Args:
flux (array): The flux array.
lowcut (float): The frequency cut off.
fs (array): The frequency array.
order (Optional[int]): The order of the Butterworth filter. Default
... | aed17a9f43292a5c7274e3ad0d708aabf14e4404 | 34,313 |
def main(filepath=None):
"""execution starts here"""
# print("main():")
if filepath==None:
filepath = r"C:\Program Files\7-Zip\7z.exe"
print("Getting Metadata From File: " + filepath)
parser = hachoir.parser.createParser(str(filepath))
metadata = hachoir.metadata.extractMetadata(parser)... | eb6f8d3086cd3e527be7a7d2f4c79453fed2f21c | 34,314 |
def calculate_background_gradient(u, v, w, weights, u_back, v_back, Cb=0.01):
"""
Calculates the gradient of the background cost function. For each u, v
this is given as 2*coefficent*(analysis wind - background wind).
Parameters
----------
u: Float array
Float array with u component of ... | bab0558148faf3694c7b5c4db174af69c70fd526 | 34,315 |
def read_embedding_vocabularies(filenames):
"""
Reads every vector embedding file in the given collection of
filenames, and returns the union of their vocabularies. (The
files are assumed to be hdf5 files containing dataframes, and
the vocabularies are their indices.
"""
result = pd.Inde... | 17c72725cc8fe06ac000a00eb76fc19bb98e6dc5 | 34,316 |
def sorted_keys(lut: dict) -> list:
"""returns sorted lut keys if env_flags[sorted] is set to True"""
if env_flags['sorted'] is True or str(env_flags['sorted']).lower() == 'true':
return sorted(lut.keys(), key=lambda x: x)
return lut.keys() | db801d14096af85de679ccf26c7ef3045b992a69 | 34,317 |
def sigmax(dim=2):
"""Qiskit wrapper of sigma-X operator.
"""
if dim == 2:
return ops.sigmax()
else:
raise Exception('Invalid level specification of the qubit subspace') | a27ec81ad0396167c6207120a031375816b463ec | 34,318 |
def is_relative_path(p):
""" Return True if path is relative """
p = p.replace('\\', '/')
if p and p[0] == '/':
return False
if sabnzbd.WIN32 and p and len(p) > 2:
if p[0].isalpha() and p[1] == ':' and p[2] == '/':
return False
return True | 0368ea2588344f90eb915f7144f0b60145b13b74 | 34,319 |
import types
def setting_keybord(
is_admin: bool, language: str, session_timeout: int
) -> types.InlineKeyboardMarkup:
"""انشاء كيبورد الاعدادات
المعطيات:
is_admin (bool): هل الكيبورد مرسل لادمن
language (str): لغة االكيبورد
session_timeout (int): وقت الجلسة
المخرجات:
... | c53f2dd95dae6bb972789ab81d1d15ba6ddb5be4 | 34,320 |
def IoU(bbox1, bbox2):
"""Compute IoU of two bounding boxes
Args:
bbox1 - 4-tuple (x, y, w, h) where (x, y) is the top left corner of
the bounding box, and (w, h) are width and height of the box.
bbox2 - 4-tuple (x, y, w, h) where (x, y) is the top left corner of
the bou... | dfb7aabac557a4ca71fe989da94e3775233d734b | 34,321 |
def filter_red_pen(rgb, output_type="bool"):
"""
Create a mask to filter out red pen marks from a slide.
Args:
rgb: RGB image as a NumPy array.
output_type: Type of array to return (bool, float, or uint8).
Returns:
NumPy array representing the mask.
"""
result = (
... | 33f78f9048754e306fbd1a9a783eff79a7442ed8 | 34,323 |
import shutil
def project_delete(request, project_slug):
"""
Make a project as deleted on POST, otherwise show a form asking for
confirmation of delete.
"""
project = get_object_or_404(request.user.projects.live(),
slug=project_slug)
if request.method == 'POST'... | 0bd8bd63a51892438fb321487d8538630fe21854 | 34,324 |
def compose_left(*funcs):
"""Compose sync and async functions to operate in series.
Returns a function that applies other functions in sequence. The returned
function will be an async function iff at least one of the functions in the
sequence is async.
Functions are applied from left to right so t... | ea02215c46b369cea993dc5565937807e76b584f | 34,325 |
def squarefree_part(x, timeout_duration=20, use_ecm=True):
"""return the squarefree part of x or 'NO DATA (timed out)'"""
F = squarefree_and_factorization(
x=x, timeout_duration=timeout_duration, use_ecm=use_ecm
)
if isinstance(F, str):
return F
else:
return F[0] | 3143aa9032b65f22631488a7f8dd96b0ae71cb4c | 34,326 |
def unix_time_to_id(unix_time):
"""
Converts the given unix time to id.
Parameters
----------
unix_time : `int`, `float`
The unix time to convert to id.
Returns
-------
id_ : `int`
"""
return (floor(unix_time*1000.)-DISCORD_EPOCH)<<22 | 50b40ab1e23971b8ba44cfdd6546158b42415d66 | 34,327 |
def method_withBadName_with_bad_params_on_single_line(myBadlyNamedParam, my_other_Bad_name):
"""Provide parameters with bad names on single line."""
return myBadlyNamedParam + my_other_Bad_name | 10857c53fb36ef96ebfc4cd10b52b412b600836a | 34,328 |
async def async_setup_platform(
hass, config, async_add_devices, discovery_info: object = {}
):
"""Set up Loxone Sensor from yaml"""
value_template = config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
value_template.hass = hass
# Devices from yaml
if config != {}:
# ... | 36a896270e448b50121d685aa3048006b7246abe | 34,329 |
from datetime import datetime
def build_cal_args(args):
"""Determine the year/month. Return list [year] or [year, month]"""
t = datetime.date.today()
m, y = t.month, t.year
x = None
if len(args) == 0:
# no args - print default calendar
x = [y, m]
elif len(args) == 1:
... | 241630f6a15f1a8c2ac195740aba8a7307b763ba | 34,330 |
def _dice(array):
"""Given an array containing true/false positive/negative columns for the
'shadow' class, calculates the dice coefficient."""
v = {'TP': 0, 'TN': 0, 'FP': 0, 'FN': 0}
for val in v:
v[val] = float(np.sum(array['Shadow ' + val]))
dice = v['TP'] / ((v['FP'] + v['TP']) + (v[... | 644f1e5d982b9d5239f2b339ae4bdd14c10ebc73 | 34,335 |
import math
def euclidian_dist(p1, p2):
""" p1 and p2 must both be of len 2 where p1 = (x1,y1); p2 = (x2,y2)"""
return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) | 3bceb46cf311e418cac83370c673772f885587be | 34,336 |
def colorify_by_name(image, cmap_name, flip_map=False, rescale_type='min_max', limits=None, num_colors=256):
"""
Return 2D image as 3D RGB stack colored with a given colormap.
Parameters
----------
image: 2d array
image to convert to RGB
cmap_name: str
Matplotlib colormap or... | 68a034150e327c3fbef2603f422d18e935dec590 | 34,337 |
import numpy
def lazy_matrix_mul(m_a, m_b):
"""
multiply 2 matrix that is given
Args:
m_a: input first matrix
m_b: input second matrix
Returns:
return m_a * m_b
"""
return numpy.matmul(m_a, m_b) | 3e58214d944d1962260b747af53dc8c82cc79b40 | 34,338 |
def denormalize_tags(df: pd.DataFrame) -> pd.DataFrame:
""" For a DataFrame with a column 'tags' that contains comma-space-separated
tags, denormalize the 'tags' column. """
if df.empty:
return add_missing_columns(df, required_columns=['tag'])
df = df.copy()
df['tags'] = df['tags'].str.spli... | ce61cd49041a6238fc91bb1256ee0357944dc71e | 34,339 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.