content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def get_installation_path():
"""
Returns 3ds Max installation folder
NOTE: This function is added here to avoid some errors related with 3ds Max PATH env var setup
This functionality is available in dcclib for each specific DCC
:return: str
"""
version_id = MaxPlus.Application... | d86a3aa38c5e96e1174a33300654aa829238cdcd | 55,556 |
import sympy
def collect(expr,lst):
"""
Wrapper for sympy.collect.
"""
lst = MV.scalar_to_symbol(lst)
return(sympy.collect(expr,lst)) | 00097d0eab616fb302d15fdafd8afb62486aab01 | 55,557 |
def decrement(name, num_shards, delta=-1, do_transaction=True, use_memcache=True ):
"""
Decrement the value for a given sharded counter.
This will create the counter if it does not exist.
Args:
name: The name of the counter.
num_shards: the number of shards in the counter
"""
retu... | 1b4d88a6409cf11209d965ba7fe7fc2f917cb7eb | 55,558 |
import functools
import types
def memoize_method(func):
"""
A decorator to remember the result of the method call
"""
@functools.wraps(func)
def wrapped(self, *args, **kwargs):
name = '_memoize_{}'.format(func.__name__)
try:
return getattr(self, name)
except Att... | f3a43d03e9b34c7a623452868ff2d33fed299dd9 | 55,559 |
def get_random_data(data, n=10, seed=1):
"""
:param data: np.ndarray
:param n: int
:param seed: int
:return: np.ndarray
"""
np.random.seed(seed)
ind = np.random.choice(data.shape[0], n)
return data[ind] | 7b9951d2bae537062d1ef7ada7622ece13b6a9e9 | 55,560 |
import sqlite3
def get_groups_per_sweep(sweep, include, query, db_path):
"""pulls out all the data in a sweep and structures it as a dict.
String of integers (`peaks`) is transformed into a list of ints or empty list."""
con = db.persistent_connection_to_db(db_path)
con.row_factory = sqlite3.Row
d... | b936534df39183c05418b1c4afc4b146f9d75e94 | 55,561 |
import time
def searchForCamptown(rhyming_dict, attempts=MAX_ATTEMPTS, backoff=BACKOFF):
"""Loop MAX_ATTEMPT times, searching for a Camptown meter wikipedia title.
Args:
Integer: attempts, retries remaining.
Integer: backoff, seconds to wait between each loop.
Returns:
String or F... | 5c8e85c4712f1b18be31f248f9b4706612e9d65e | 55,562 |
def example_boxplot():
"""Generate an example box plot."""
non_symmetric = _non_symmetric_data()
# find the quartiles and iqr
q1_y, median_y, q3_y = non_symmetric.quantile([0.25, 0.5, 0.75])
iqr = q3_y - q1_y
# make the boxplot
ax = non_symmetric.plot(kind='box', figsize=(6, 6), title='Box... | 63d558439323464234122478fcdb9ebf0845bf6b | 55,563 |
def dfs(graph, start):
"""Depth first search
Args:
graph (dict): graph
start (node): some key of the graph
"""
seen = set()
path = []
stack = [start]
while stack:
current = stack.pop()
if current not in seen:
seen.add(current)
path.appe... | ca4a8260e3e27d73852c27b3d07b0cf248b25be8 | 55,564 |
def get_reverse(rna_sequence):
"""Reverse orientation of `sequence`.
Returns a string with `sequence` in the reverse order.
If `sequence` is empty, an empty string is returned.
"""
sequence = rna_sequence.upper()
rev_seq = sequence[::-1]
if len(sequence) == 0:
return ""
else:
... | 497ad7c4d16fddb6f7d9f657f0a63632e1d8ebdb | 55,565 |
def beautify_latex(expr):
"""convert string to latex-compatible expression"""
return substr_replace(expr, [
('**', '^'),
('plus', '+'),
('minus', '-'),
('comma', ','),
('LEFT', '\\left ('),
('RIGHT', '\\right )'),
('integral', '\\int'),
('rvert', '... | 876364a2b41d147fe6d98954359b7a8fe71e2eaf | 55,566 |
def a(P, T):
"""Isobaric cubic expansion coefficient [1 / K]"""
pi = P / Ps
tau = Ts / T
return ((1 + pi * gammaR_pi(pi, tau) - tau * pi* gammaR_pitau(pi, tau)) / (1 + pi * gammaR_pi(pi, tau))) / T | faa27a987a474aeadd03212c4f29e0e603cdbe25 | 55,567 |
def added_fields():
"""Return list of col. names that should be added to csv
"""
return [cn for rgcn,cn in COLUMNS_MAPPING] | af16b8d18d60c9e190b3ced6eaf48bb50d456a8e | 55,568 |
def one_hot(length, index):
"""Return an nd array of given `length` filled with 0s and a 1 at `index`."""
result = np.zeros(length)
result[index] = 1
return result | 07f23d4e17df78e3e607326e15f9fefbd1bcd168 | 55,569 |
def optimize_lsq(
mesh_conductor, bfield_specification, reg=1e3, objective="minimum_inductive_energy"
):
"""
Optimization of coil stream function according to a specified objective using least-squares.
Parameters
----------
mesh_conductor: MeshConductor object
Contains Trimesh mesh as w... | 531eaf8d569e4460089142706487941b1c8e4d37 | 55,570 |
import json
def getHesitationAndTypingTimeFromResponseChanges(json_data):
"""
get hesitation and typing time from response changes(i.e list of time stamps)
"""
if json_data != None:
changes = json.loads(json_data)
else:
changes = []
if len(changes) >= 2:
hesitation_tim... | 0f6df94fee9c1bff602dfbdf7000628d9edc2dde | 55,571 |
import functools
def translate_server_exception(method):
"""Transforms the exception for the instance.
Note: keeps its traceback intact.
"""
@functools.wraps(method)
def wrapper(self, ctx, instance_id, *args, **kwargs):
try:
res = method(self, ctx, instance_id, *args, **kwarg... | 45fdcdec2d3be7ef2ee21f0017c8e8f3e09a1b28 | 55,572 |
from pathlib import Path
import io
from unittest.mock import patch
async def test_upload_view(hass, hass_client, temp_dir, hass_admin_user):
"""Allow uploading media."""
img = (Path(__file__).parent.parent / "image/logo.png").read_bytes()
def get_file(name):
pic = io.BytesIO(img)
pic.nam... | 6bdc05a17a44c4ae016ae8c8fc40bfceb2072c7f | 55,573 |
def calculate_COM(offsets):
"""
Determine the centre of mass (COM) in a collection of offsets.
The COM is a basis to span the vectors in ``offsets``.
Also return the distance of each element E in ``offsets`` from the COM (i.e.,
the coefficients that when multiplied by the COM give exactly E).
... | b789c45ff6ba84ef170df881b0936879fd9d3781 | 55,575 |
def datapoints_to_datalist(datapoints, avoid=[], verbose=True):
"""Removes the outer layer of the datapoints dictionary, i.e.
sample. The second organizational level (i.e., molecule) becomes the
outermost level. Lists and arrays are appended.
In other words, it just lumps all samples together.
"""
... | 3a5f4d4caa434b91e76f2d15a1b79b9686f9ee92 | 55,577 |
def fastq(
draw,
size=0,
min_score: int = 0,
max_score: int = 62,
offset: int = 64,
add_comment: bool = True,
additional_description: bool = True,
) -> str:
"""Generate strings representing sequences in FASTQ format.
Arguments:
- `size`: Size of the sequence and quality string.
... | 4de1e651192b1e17b3809135bbc51e1e8f7477ff | 55,578 |
import torch
def mixup(data, targets, alpha):
"""
original mixup.
"""
indices = torch.randperm(data.size(0))
shuffled_data = data[indices]
shuffled_targets = targets[indices]
lam = np.random.beta(alpha, alpha)
data = data * lam + shuffled_data * (1 - lam)
results = {
'tar... | 69153f3fc5d0565a96ded7671bbe737600504a86 | 55,579 |
def euclidean_dist_ttr(c1, c2):
"""
Computes Euclidean distance between two cities
"""
x1, y1 = vertex_coordinates[c1]
x2, y2 = vertex_coordinates[c2]
return ((x1 - x2)**2 + (y1 - y2)**2)**0.5 | 0fac4c1a822aa1a065087ca791839874704eb9ea | 55,580 |
def scatter_data(file):
"""
return the data for the scatter plot for both debits and credits. It would
be a visual method to see the values of debits and credits. One can find out
what is the highest dollar entry or around what value it lies.
"""
df = pd.DataFrame(
file.groupby(["Date", ... | c2729de0898df497573bfc56dc80e7da964d9ae2 | 55,581 |
def viterbi(state_matrix,pointers):
"""Get viterbi path from state_matrix and pointers output of make_dynamic
Args:
state_matrix : :class:`~numpy:numpy.array`
matrix where each column gives the prob of max prob path to that state, where each row is IBD 0,1,2
pointers : :class:`~numpy... | e38f3569838167520d10fbdf527bd2fa89275f9d | 55,583 |
def add_global_mean_vars(xr_ds_: xr.Dataset,
variable_list,
prefix='glmean_', weighting_var='area_p', averaging_dims=('ncol')
) -> xr.Dataset:
""" For each variable in the input list, we add an accompanying variable that represents a global ... | 345c9453914fbaa396214445f0e49274c99d2655 | 55,585 |
def find_center_of_rotation(projection, background_internsity=0.9, method="center_of_gravity"):
""" Find the axis of rotation of the object in the projection
Parameters
----------
projection : ndarray
The projection, normalized between 0 and 1
background_internsity : flo... | b21ee3f308fff8f1b21056b68989433de953336b | 55,586 |
def _is_valid_rng(rng: Array):
"""Checks whether rng is a valid JAX PRNGKey, also handling custom prngs."""
# New-style JAX KeyArrays have a base type.
if jax_config.jax_enable_custom_prng:
if not isinstance(rng, jax.random.KeyArray):
return False
# Old-style JAX PRNGKeys are plain uint32 arrays.
el... | 7bb77578d9aa74528b2d5f25b1d0bbe6ea57f1da | 55,587 |
import re
import itertools
def extract_and_update_methylation_index_from_single_end_read(read, AlignmentFile, methylation_m_tuples, m, all_combinations, methylation_type, methylation_pattern, ignore_read_1_pos, min_qual, phred_offset, ob_strand_offset):
"""Extracts m-tuples of methylation loci from a single-end r... | 34d103fd24dfcd72c058d847f59adf8b9c3addc8 | 55,588 |
def mask_above_key(ccd_in, bmp_meta=None, key=None, margin=0.1, **kwargs):
"""CorMultiPipe post-processing routine to mask pixels > input key
"""
if key is None:
raise ValueError('key must be specified')
masklevel = ccd_in.meta.get(key.lower())
if masklevel is None:
return ccd
cc... | 49df5541f605b532bfa6364709c593609ce36ad5 | 55,589 |
def list_services():
"""
GET /system/services
:param request_inputs:
:return:
"""
request_inputs = anchore_engine.services.common.do_request_prep(request, default_params={})
user_auth = request_inputs['auth']
params = request_inputs['params']
return_object = []
httpcode = 500
... | 1d9f5160fc926c6920daa7038573835d32786578 | 55,590 |
def users_list():
"""
JSON {"key":str}
username, password, text - строки
:return: {'users':list}
"""
key = request.json['key']
username = get_by_value(key, key_stor)
if not username:
return {
'ok': False,
'message': 'Сначала пройдите регистрацию или автори... | d02618306828322212bf224435cc76e3a822d4f8 | 55,591 |
def findRoot(value, x_low, x_high, function):
"""Use the bisection method to find root such that function(root) == value."""
guess = (x_high + x_low) / 2.0
v = function(guess)
difference = v - value
i = 0
while abs(difference) > ACCURACY and i < MAX_ITERATIONS:
i += 1
if differe... | 2113077eb5439a014b4fa2406a7d0ebfb7c5a795 | 55,592 |
def iss():
"""
Return the token issuer (``USER_API``).
"""
return USER_API | c601488aa87d0b72415de2c95c6483d91c9c2c01 | 55,593 |
def scan_buildings():
"""
Creates a list of lists of buildings in current village and returns it. Each
tile element is a string. Must be on building view.
Returns
-------
[[buildingSlot, a#, g#, aid#, roman, buildingLVL]]
All strings in list. g# is building ID.
"""
result = []
... | f39ca8a8cfb5aeeee0f00de644a620be22b28029 | 55,594 |
def password_success(request):
""" redirect to the registraion successful page """
return render(request, 'registration/password_success.html', {}) | 54b34f9a71ce13fc5f0d61db1b7a4db79f41b2dd | 55,595 |
def officer_confirm_view(request, pk):
"""Officer views and confirms a challenge request after clicking email link.
Only the officer who gave the challenge can review it."""
challenge = OffChallenge.objects.get(id=pk)
if request.user.id != challenge.officer.id:
raise PermissionDenied # not the ... | d6276f03507d0aa9b597aead5eab47e814a08109 | 55,596 |
def process_stn_activation(df, side):
"""
Calculates STN activation percentage
:param df: dictionary containing STN volume and active STN volume for patients
:param side: side of the brain 'L' or 'R'
:return: STN activation percentage for each side for all patients
"""
#print(list(df))
... | 6ed2a21e547a0ed9f35a77fed02e6f4fbf59cb6a | 55,597 |
import string
def GetTestWrapper(func_name):
"""Return a C preprocessor token to test in order to wrap code.
This handles extensions.
Example: GetTestWrapper("glActiveTextureARB") = "CR_multitexture"
Example: GetTestWrapper("glBegin") = ""
"""
cat = apiutil.Category(func_name)
if (cat == "1.0" or
cat == "1.1... | 4e7f0f6dc9c656229fd92aa2673a71606d20a556 | 55,598 |
import logging
def plot(f):
"""
Plot function decorator. Calls the function, does several generic tasks,
and saves the figure as the function name.
"""
def wrapper(*args, **kwargs):
logging.info('generating plot: %s', f.__name__)
f(*args, **kwargs)
fig = plt.gcf()
... | 0e98ad95a7578490558f2c104ac732b7b11beb71 | 55,599 |
def build_dataset(cfg, args=None):
"""
Build the module with cfg.
Args:
cfg (dict): the config of the modules
registry(Registry): A registry the module belongs to.
Returns:
The built module.
"""
args = cfg
name = args.pop("name")
dataset = DATASET_REGISTRY.ge... | c5657ca553ae268a17f5e3ac084b72cf0e0c1535 | 55,600 |
def plot_damped_oscillator(m=1.0, k=1.0, b=1.0):
"""
m = 1.0 # mass [kg]
k = 1.0 # spring constant [N/m]
b = 1.0 # friction constant [Ns/m = kgm/s^2*s/m = kg/s]
"""
two_gamma = b/m
omega_squared = k/m
gamma = two_gamma/2
omega = np.sqrt(omega_squared)
if gamma == 0.0:
... | f226a3d227383b0c59af5355d4a70ed719ac8bc2 | 55,601 |
def combine_dictionaries(dict1,dict2):
"""append lists that share the same key, and add new keys
WARNING: this only works if the dictionaries have values that are lists"""
outdict = dict1
for key in dict2:
if key in outdict:
assert(isinstance(dict2[key],list))... | bc291bd8b31870ee8d04f4cb13c94c88bb97fea9 | 55,602 |
def greatest_common_divisor(larger_num, smaller_num):
"""This function uses Euclid's algorithm to calculate the Greatest Common Divisor
of two non-negative integers
pre: larger_num & smaller_num are both non-negative integers, and larger_num > smaller_num
post: returns the greatest common d... | 70db69b222f1a4a0d395e9bb1ff87ef031dbbbd6 | 55,603 |
def randomColor(image):
"""
对图像进行颜色抖动
:param image: PIL的图像image
:return: 有颜色色差的图像image
"""
random_factor = np.random.randint(0, 31) / 10. # 随机因子
color_image = ImageEnhance.Color(image).enhance(random_factor) # 调整图像的饱和度
random_factor = np.random.randint(1... | 71825e6d4c6e0feac26f5b292210f54db79447d4 | 55,608 |
def tj_max_volume():
"""
Real Name: b'Tj max Volume'
Original Eqn: b'162.4'
Units: b'MCM'
Limits: (None, None)
Type: constant
b''
"""
return 162.4 | c921033f825ed719d41f7663fd7c83cc46227f57 | 55,610 |
def cca(features_x, features_y):
"""Compute the mean squared CCA correlation (R^2_{CCA}).
Args:
features_x: A num_examples x num_features matrix of features.
features_y: A num_examples x num_features matrix of features.
Returns:
The mean squared CCA correlations between X and Y.
"""
qx, _ = np.l... | ff7d0fa7c8e0fe71ef72d0716af2a2f331ed1db8 | 55,611 |
def get_stats_value(value_considered,ad_or_ped,ind_clusters,demographics_coll,logger):
"""get the Kruskal Wallis U index and p-value for a type of demographics
Parameters: value_considered (str): type of demographics we want the KW U index and p-value
ad_or_ped (str): "adult" or "pediatric", to ... | fc2f3bcdbc98bb55ceaf1db63acab176bb3919b1 | 55,612 |
def overlap_ellipse_polygon(ellipse, polygon):
"""Get ratio of how much of ``ellipse`` that is contained in ``polygon``.
Current implementation:
Convert ellipse to polygon and use :py:meth:`overlap_polygon_polygon`
:param ellipse: The ellipse.
:type ellipse: :py:class:`b2ac.geometry.ellipse.B2ACEl... | 21c5619bbc6e9316b7f7478f31ccc234f931293c | 55,613 |
def percent_median(data: pd.DataFrame) -> pd.DataFrame:
"""
Calculate the points expected as a percentage of the median player in the position
Args:
data (pd.DataFrame): the dataframe that has the players and a single scoring scheme
Returns:
pd.DataFrame: updated dataframe with a colum... | 6e9e19ddd3936a770516e3693e15cbbbe24d47e3 | 55,615 |
def _build_g_gradient(x, classifier, pred_class, target_class):
"""
Build tensors of gradient `g`.
:param x: One input sample
:type x: `np.ndarray`
:param classifier: A trained model
:type classifier: :class:`Classifier`
:param pred_class: Predicted class
:type pred_class: `int`
:pa... | 780da740cbf0d29a3d3fb7f8205855c4b156178f | 55,616 |
import time
import requests
def reboot_and_wait(username, password, check_func=None, timeout=100):
"""
重启光猫并等待光猫重启完成,这需要一个检查函数来确定光猫是否重启完成,如果检查光猫重启状态时间超时,则将抛出TimeoutError异常
:param username: 终端配置账户用户名
:param password: 终端配置账户密码
:param check_func: 光猫重启完成检查函数,它不接受任何参数,由返回值来决定光猫是否重启成功 (默认值是 None,即使用内置的检... | 72ff57c61c3e6a1585a897050ee5ca9f41cf0d39 | 55,617 |
def _percent_match(date_classes, tokens):
"""
For each date class, return the percentage of tokens that the class matched (floating point [0.0 - 1.0]). The
returned value is a tuple of length patterns. Tokens should be a list.
"""
match_count = [0] * len(date_classes)
for i, date_class in enume... | fb90ab7d1d6cf0b0d5024d2834175a0d068ac8e0 | 55,618 |
def convert_ATvalue(byte_string, is_little_endian, struct_format=None):
"""Read and return AT (tag) data_element value(s)"""
length = len(byte_string)
if length == 4:
return convert_tag(byte_string, is_little_endian)
# length > 4
if length % 4 != 0:
logger.warn("Expected length to be... | c1ff908a413d27d29e4fc378259027eb12075c1f | 55,619 |
def find_idx_in_list(lst, target_value, start=0):
"""Find the max idx in the list such that lst[idx] < target_value.
If list is empty or the first value is larger than the target value, return -1
"""
if len(lst) == 0 or lst[0] > target_value:
return -1
for idx in range(start, len(lst)):
... | e87258a00c98a02ca4fe94e7cab67dbc1b07a34f | 55,621 |
from typing import Iterable
from typing import List
def tishka_flatten(data: Iterable) -> List:
"""
Non recursive algorithm
Based on append/extend elements to new list
"""
nested = True
while nested:
new = []
nested = False
for i in data:
if isinstance(i, l... | ca9d6eb4507e95ba94b6c1859aa30b81dd6f7a32 | 55,622 |
def server_create_snapshot_respect_max(request, server_id):
"""
View for creating a new snapshot on a server
Dialog asks for confirmation then runs synchronous creation of new
snapshot, then potentially starts a job to delete old ones asynchronously
if there is a maximum set and it has been exceede... | 5d1c67476812d63267942024a72519577379b386 | 55,623 |
import collections
def api_calls(function: Function) -> collections.Counter:
"""
Returns counter containing API calls and the number of times they were called.
e.g.
with dragodis.open_program("input.exe") as dis:
func = dis.get_function(0x40000)
api_calls = functions.api_c... | 907e72ecd3a3d152443a7ad6e926c49d8051f074 | 55,624 |
def _preprocess(features, wires, weights):
"""Validate and pre-process inputs as follows:
* Check that the features tensor is one-dimensional.
* Check that the first dimension of the features tensor
has length :math:`n` or less, where :math:`n` is the number of qubits.
* Check that the shape of t... | 716de91ef381f1cd9f1c1e255094e0821be98c2f | 55,625 |
def apply_xtalk(vis, xtalk):
"""
Apply to a (NTIMES,NFREQS) visibility waterfall a crosstalk signal
Args:
vis (array-like): shape=(NTIMES,NFREQS)
the visibility waterfall to which gains will be applied
xtalk (array-like): shape=(NTIMES,NFREQS) or (NFREQS,)
the crosst... | 01712c18166889011a03627e07c79c71404cc2cd | 55,626 |
import requests
def get_vcdr_sddc_details_json(strVCDRProdURL, sddc_id, session_token):
"""Get Recovery SDDC Details - Get details of a specific Recovery SDDC. """
myHeader = {'x-da-access-token': session_token}
myURL = f'{strVCDRProdURL}/api/vcdr/v1alpha/recovery-sddcs/{sddc_id}'
response = requests.... | 8852683fe2d62f152559070643a4b9e13cfece4a | 55,627 |
from re import T
import torch
def estimate(
signal: T.Union[T.List, np.ndarray, torch.Tensor],
sample_rate: float,
pitch_min: float = 20,
pitch_max: float = 20000,
frame_stride: float = 0.01,
threshold: float = 0.1,
) -> torch.Tensor:
"""estimate the pitch (fundamental frequency) of a sign... | 81d94cfcdceba4518b56d64e9002b61a60608a4e | 55,628 |
def _residual_maker(A, b):
"""
Returns a matrix which can be used to make residuals from b
"""
n = A.shape[0]
I = eye(n)
return I - _hat(A) | 7d649d295faa8553a82d65c4ea2708d0a64b26ed | 55,629 |
def highway_ramps_example(render=None):
"""
Perform a simulation of vehicles on a highway section with ramps.
Parameters
----------
render: bool, optional
Specifies whether or not to use the GUI during the simulation.
Returns
-------
exp: flow.core.experiment.Experiment
... | 66c4fa17af6a09b0ba52245638fb054fdfeca0e6 | 55,630 |
import typing
def count(*items: typing.Any) -> int:
"""Count the number of items that are provided that are `UNDEFINED`."""
return sum(1 for item in items if item is UNDEFINED) | bc8f3465d685401ed108bcdcec69e4c27867ffff | 55,631 |
def _urlescape(name):
"""Escape the given name for inclusion in a URL.
Escaping is done in the manner in which AutoDuck(?) seems to be doing
it.
"""
name = name.replace(' ', '_')\
.replace('(', '.28')\
.replace(')', '.29')
return name | ec94492778ccdefdde7d657f8fffd953915949ae | 55,632 |
def threshold_voltage(logId, print_error = True):
"""
기울기가 커야 전압을 조금만 조절해도 전류 변화가 크고,
누설 전류가 작음.
"""
sample = np.array(logId)
sample = sample.astype(np.float)
rowsize = sample.shape[0]
columsize = sample.shape[1]
for i in range(0, rowsize) :
for j in range(0,columsize) :
... | 8df1ebeeac7a278278cff567c06b099edceef6d8 | 55,633 |
def not_started_timeout():
"""
Fixture that yields a :class:`~adbtp.timeouts.Timeout` that has not been started.
"""
return timeouts.Timeout(1) | 4336427e0c47c63d8d2f2e9b247e7a274e1815b9 | 55,634 |
import operator
def 数组_是否全部相同(iterable, eq=operator.eq):
"""
#allsame([1, 1, 1, 1])
# True
#allsame([])
# True
#allsame([0, 1])
# False
#iterable = iter([0, 1, 1, 1])
#next(iterable)
#allsame(iterable)
# True
#allsame(range(10))
# False
#allsame(range(10), lambd... | 36250c46043888e8df27315ae45f151a1e4494e9 | 55,635 |
def normalize(data):
"""
Normalize data set to have zero mean and unit variance.
Args
data: A numpy array of arrays containing input or target data.
Returns
A normalized numpy array of arrays.
"""
return (data - data.mean(axis=0)) / data.var(axis=0) | d09f7bc81c5f6c5e1c593836bd758a3553f243ca | 55,636 |
from typing import TextIO
import csv
def load_chords(fhandle: TextIO) -> annotations.ChordData:
"""Load Queen format chord data from a file
Args:
fhandle (str or file-like): path or file-like object pointing to a chord file
Returns:
(ChordData): loaded chord data
"""
start_times... | 80be5d91989b89d6ecf6f164d3cebe8573b564c3 | 55,637 |
import re
def try_repat(s, default=None):
""" Try compiling a regex pattern.
If `s` is Falsey, `default` is returned.
On errors, InvalidArg is raised.
On success, a compiled regex pattern is returned.
"""
if not s:
return default
try:
p = re.compile(s, flags=re.... | 871549a3fb43418053bd2b1a2bab68d96ab49da6 | 55,638 |
import statistics
def mean_median_diff(district_plan, party_to_analyze, competing_party):
"""
:param district_plan: an iterable of Districts
:param party_to_analyze: the key specifying which party to analyze
:param competing_party: the competing party
:return: median - mean party share across all ... | 82bbf5fa9b5af2ec8f572d743dc7f2f92b6970da | 55,639 |
def get_airfares():
"""Requests user's input information at the root --> /, and gets the cheapest airfares based on users input.
"""
departure = (request.form.get("departure")).upper()
arrival = (request.form.get("arrival")).upper()
departure_date = request.form.get("departure_date")
return_dat... | 3aadec31895b78e05653a419731e67e38e871e69 | 55,640 |
from typing import List
def our_istft(z: nparr) -> List[nparr]:
"""
:param z: matrix of size [stft_freq,stft_time,len(signals)] of transformed spectrograms
:return: signals: list of numpy arrays
"""
stft_n = 512
return [ss.istft(cur_z, nperseg=stft_n)[1] for cur_z in np.transpose(z, (2, 0, 1))... | 9583d252e8400b0fa57f6a69679d5479ebe4c85c | 55,641 |
def run_to_ball_bottom_left(obs, player_x, player_y):
""" run to the ball if it is to the bottom left from player's position """
def environment_fits(obs, player_x, player_y):
""" environment fits constraints """
# ball is to the bottom left from player's position
if (obs["memory_pattern... | 482d4ae53c105efd087e2c6325e2427507500cb2 | 55,642 |
def other(
player_id # type: int
):
# type: () -> int
"""
Returns the index of the opposite player to the one given: ie. 1 if the argument is 2 and 2 if the argument is 1.
:param player:
:return:
"""
return 1 if player_id == 2 else 2 | 0216b42f821a3dfb8ece1702ca28cf56070eaa7a | 55,643 |
def is_chi(item):
"""
:param item: array of tile 34 indices
:return: boolean
"""
if len(item) != 3:
return False
return item[0] == item[1] - 1 == item[2] - 2 | e2c1b915ed7a8c841a436e3dfe88d7bae1a38e5a | 55,644 |
from typing import Dict
def make_dict_for_graph_data(db: Session, user_id: int) -> Dict[str, int]:
"""create a dict with number of events per day for current week"""
events_this_week, events_for_graph = get_events_for_the_week(db, user_id)
for event_obj in events_this_week:
event_date = event_obj... | e417d129f5262c42747ce0b4f7bf81e598f1e683 | 55,645 |
def coord(x_coordinate = 0, y_coordinate = 0):
"""function to form a coordinate string from x and y integers"""
return '(' + str(x_coordinate) + ',' + str(y_coordinate) + ')' | 65bb18ffefdaaa13b30d5237b9061b053a9e8a9d | 55,646 |
def to_camera_coordinate(joints, T, R):
"""
Args:
joints: 3x24xT
T: 3x1
R: 3x3
Returns:
"""
new_joints = np.zeros_like(joints)
for t in range(joints.shape[2]):
new_joints[:, :, t] = (R @ joints[:, :, t]) + T
return new_joints | 6ce9b73ecbbe9617c8fd0938a021094caec97273 | 55,647 |
def XML_file_to_parameter(file_name):
"""
Convert a xml file into pyqtgraph parameter object.
=============== =========== ================================================
**Parameters** **Type** **Description**
*file_name* string the file name of the XML file to be co... | 194a9b715fc331b9106a14f5db351985dc5d3e5d | 55,648 |
def CopyTraceDataFromHTMLFilePath(html_path, trace_path, gzipped_output=False):
"""Copies trace data from an existing HTML file into new trace file(s).
If |html_path| doesn't contain any trace data blocks, this function throws an
exception. If |html_path| contains more than one trace data block, the first
bloc... | 5fdab909aec29104aed3e5ed41df96dc6a7c3fb1 | 55,649 |
def public(*objects):
"""add objects to `__all__`. deprecated"""
return _add(_caller_modules()[1], objects) | 7c397333883ffb447f970b92fa1baa6b69527456 | 55,650 |
from typing import List
def equal_camera_params(camera_params_a: List[float], camera_params_b: List[float]) -> bool:
"""
Checks if the camera parameters are equals.
:param camera_params_a: first camera parameters
:param camera_params_b: second camera parameters
:return: True if they are equal, Fa... | 1b97163baca39d332536a1c3a77cbafd28021008 | 55,652 |
from datetime import datetime
def series():
"""Make mocked series as fixture."""
arr = np.random.randn(100)
locs = np.arange(20, 40)
arr[locs] = np.NaN
series = Series(arr, index=bdate_range(datetime(2009, 1, 1), periods=100))
return series | e743055a74b9aebfd24b28f09cc6249f2f17ae97 | 55,653 |
from typing import Tuple
from typing import Any
from typing import Callable
from typing import Optional
def get_arg_by_name(name: str, args: Tuple[Any], func: Callable) -> Optional[Any]:
"""Get the index of the argument in the function signature that matches the name provided"""
sig = signature(func)
for ... | 1b8e8e72e0d4db249c32669c656591d940ac1fa3 | 55,654 |
from typing import List
def create_fyle_projects_payload(projects: List[DestinationAttribute], existing_project_names: list):
"""
Create Fyle Projects Payload from Xero Projects and Customers
:param projects: Xero Projects
:return: Fyle Projects Payload
"""
payload = []
for project in pro... | b35fe6a9a02c591a544609a448e59ea0c5a0cf03 | 55,655 |
import re
def get_s3_key_as_string(s3_url):
""" Returns a file from S3 as string. Machine should have access to S3
Args:
s3_url (str): in form of 'https://s3-eu-west-1.amazonaws.com/x/y/file.yaml'
or 'https://s3.eu-central-1.amazonaws.com/x/y/file.yaml'
Returns:
str: content of gi... | 77a7ec756ed534c05ea7d7630f0f948f1ec5062a | 55,656 |
from typing import Optional
from typing import Generator
def set_virtual_time_policy(
policy: VirtualTimePolicy,
budget: Optional[float] = None,
maxVirtualTimeTaskStarvationCount: Optional[int] = None,
waitForNavigation: Optional[bool] = None,
initialVirtualTime: Optional[network.TimeSinceEpoch] =... | 36b67a3d51a0186d127ace9c0357d812edf594b6 | 55,657 |
def write_txt(w_path, val):
"""Write a text file from the string input.
"""
with open(w_path, "w") as output:
output.write(val + '\n')
return None | 964f92cd63c0c448ef96577fa506051a3a89c08b | 55,658 |
def sendEmail():
"""
"""
if request.method == 'POST':
user_email = request.form.get('user_email')
firstName = request.form.get('firstName')
lastName = request.form.get('lastName')
subject = request.form.get('subject')
user_massage = request.form.get('userMessage')
... | c18610f08b123c2e6308ebd9ac99c2eb2c827682 | 55,659 |
def add_node(store, node_list, lb_id, current_timestamp):
"""
Returns the canned response for add nodes
"""
if lb_id in store.lbs:
_verify_and_update_lb_state(store, lb_id, False, current_timestamp)
if store.lbs[lb_id]["status"] != "ACTIVE":
resource = invalid_resource(
... | 170e8fddf65f3968705baa706c2dccc56129cf1d | 55,660 |
from typing import List
def create_vulnerability(
name: str,
author: Identity,
external_references: List[ExternalReference],
object_marking_refs: List[MarkingDefinition],
) -> Vulnerability:
"""Create a vulnerability."""
return Vulnerability(
created_by_ref=author,
name=name,
... | 7fbbadb0488fd06ba75b487347667cfa0058a598 | 55,661 |
def histtrends2():
"""
Reads in future LENS 1970-2005 SI-x data
Returns
----------
lstfrz_trendh2 : array of last freeze trends
leaf_trendh2 : array of leaf trends
"""
directory = '/volumes/eas-shared/ault/ecrl/spring-indices/LENS_springonset/data/cesmclimo/'
name2 = 'Leaftren... | ca92bedf3459089eb7cda0698899638d6c6c5c8b | 55,662 |
def load_manifest(path: Pathlike) -> Manifest:
"""Generic utility for reading an arbitrary manifest."""
raw_data = load_yaml(path)
data_set = None
for manifest_type in [RecordingSet, SupervisionSet, FeatureSet, CutSet]:
try:
data_set = manifest_type.from_dicts(raw_data)
excep... | bcbf4848768b6c66ec5a5f6fac929cd818a1a7aa | 55,663 |
def ListToDict(args):
"""
change a list to dict
:param args: a list
:type args: list
:return: dict
.. code-block:: python
>>> a = [1,2,3,4]
>>> print(ListToDict(a))
{1: {2: {3: 4}}}
"""
if not isinstance(args, list):
return None
if len(... | 23f3ed1f47adbc842906a06d704150962b3f5a76 | 55,664 |
def compare_maps(map1: Nifti1Image, map2: Nifti1Image):
"""
Compare two maps, given as Nifti1Image objects.
This function exploits that nibabel's get_fdata() caches the numerical arrays,
so we can use the object id to cache extraction of the nonzero coordinates.
Repeated calls involving the same map... | 333b8676408d42c2aa25311997e8002ed04f5a66 | 55,665 |
def blockingCallOnMainThread(func, *args, **kwargs):
"""
Modified version of twisted.internet.threads.blockingCallFromThread
which waits 30s for results and otherwise assumes the system to be shut down.
This is an ugly workaround for a twisted-internal deadlock.
Please keep the look intact in case someone ... | 80549226fc26d69c4740110817f37435e33ba956 | 55,666 |
from typing import Optional
def get_region_commitment(commitment: Optional[str] = None,
project: Optional[str] = None,
region: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRegionCommitmentResult:
"""... | 31fbf797b0e4bc637027784bb99887f8b18c67a1 | 55,667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.