content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def encode_circuits(circuits, model):
"""
Encode a list of circuits generated from a given model. Each circuit will be encoded using 4 integers:
1. The index of the gate sequence before the germ, i.e. preparation fiducials
2. The index of the gate sequence after the germ, i.e. measurement fiduci... | 90e4c10a31968b93177e100a9f225833658b3544 | 3,616,700 |
def domain_match(A, B):
"""Return True if domain A domain-matches domain B, according to RFC 2965.
A and B may be host domain names or IP addresses.
RFC 2965, section 1:
Host names can be specified either as an IP address or a HDN string.
Sometimes we compare one host name with another. (Such co... | 4f930b92f3b869d8ac4f499ef817f4bb2ed44360 | 3,616,701 |
def _build_timetables(schedules, events=None, partner=None):
"""
Dati un elenco di schedule ids/eventi e partner program ritorna una lista
di TimeTable relative ai dati passati.
_build_timetables([1,2])
Restituisce due TimeTable relative agli schedule 1 e 2 (gli eventi
vengono recupera... | 31b431b224273649ce63e9f9419e2d28043bf24d | 3,616,702 |
import os
def readSeeingFromASDM_minidom(asdm):
"""
Reads information from CalSeeing.xml into a dictionary
Returns a dictionary with the following keys:
atmPhaseCorrection: AP_UNCORRECTED or AP_CORRECTED
baselineLengths: typically 3 values (in meters)
startValidTime: MJD nano seconds
endVa... | d1132a409b30d5ec7162d152240b577a31b20934 | 3,616,703 |
from typing import Optional
from typing import Iterator
def get_tags(owner: str, repo: str, n: int = 100, filter: Optional[str] = None) -> Iterator[str]:
"""Get the tags on a repository in descending commit tag date order."""
ref_query = ""
if filter is not None:
ref_query = f', query: "{filter}"... | b5e5b79a03e5bf8dea13fade121a6b81bd762512 | 3,616,704 |
def Function(from_types, to_type):
"""A binary type constructor which builds function types"""
return TypeOperator('fun', list(from_types) + [to_type]) | 6f16c0f885c16186592ac1661adae29f13bfd77a | 3,616,705 |
def _threshold_binary(image, thresholds):
"""
Apply binary thresholding to an image
Inputs
----------
image: numpy.ndarray
A single image, grayscale or RGB
thresholds: numpy.ndarray
A list containing a min and max value for thresholding
Outputs
-------
binary_ou... | dac47dbbdcfcbc9a5c55bfc4447ecf2a0bceb803 | 3,616,706 |
def is_field_remote(model, field_name):
"""Check whether a given model field is a remote field.
"""
if not hasattr(model, '_meta'):
# ephemeral model with no metaclass
return False
model_field = get_model_field(model, field_name)
return isinstance(model_field, (ManyToManyField, Rela... | f000422278aa934a9400f1b31ddde9d5b7a5728d | 3,616,707 |
def dist_bool_output(dist, dist1, dist2=0, mode='lim'):
"""
This function takes an input distance and the upper and lower limits or the central value and the tolerance and outputs
if it satisfies or not the given criteria.
modes:
lim -> limit mode, it requires a max and a min value
tol ... | bf3df055331ddfc608ad0c97fe9602c65082c582 | 3,616,708 |
def rollaxis(a, axis, start=0):
"""
Roll the specified axis backwards, until it lies in a given position.
Parameters
----------
a : ndarray
Input array.
axis : int
The axis to roll backwards. The positions of the other axes do not
change relative to one another.
sta... | 0a386ae86096be232b7ed83f4f7497ddf51ddb64 | 3,616,709 |
def consistency_check(args, alphabet, key):
"""Checks the alphabet and the key for consistency and normalizes both to lower case
:param object args: object containing the converted arguments
:param str alphabet: the untrusted alphabet to check
:param str key: the untrusted key to check
:return: a t... | 44c650d5a6db285b6d2df9bb25699860dd24ca8e | 3,616,710 |
def func(arg1, arg2):
"""magic function
"""
return arg2, arg1 | eb5841ce5765d44ede5162aa8bf51ec370c35b00 | 3,616,711 |
import os
def make_summary_table(indir,aggregation_rules,aggregation_rules_twiki, hashing_flag, standalone_flag):
"""Create a table, with as rows the directories and as columns the samples.
Each box in the table will contain a pie chart linking to the directory.
"""
#aggregation_rules={}
#aggregation_rule... | 61e7ec3aee7f6cb9290f8e513b837a33b5b86264 | 3,616,712 |
def network_exists(network: str):
"""True if a network exists in docker, else False"""
try:
get_client().networks.get(network)
return True
except NotFound:
return False | 78b0ddae2deeeac2150c7283ec294f25f68a2ade | 3,616,713 |
def calc_theta(t,p):
"""
Calculate potential temperature.
**Inputs/Outputs**
Variable I/O Description Units
-------- --- ----------- -----
t I Air pressure Pa
p I Air temperature K
theta O Potential temp. K
"""
re... | 597f56ddb0a48e8b10c7c4d155d9fc772966741e | 3,616,714 |
def louvain(adj_mat: np.ndarray,
verbose: bool = False,
shuffle_nodes: bool = False,
tol_optimization: float = 0.0001,
tol_aggregation: float = 0.001,
return_adj: bool = False,
**kwargs):
""" Performs louvain partiti... | 19241490e19a73ed8ed40aca963ad9a94aa03950 | 3,616,715 |
def _init_search_param(search_idx, x, y0):
"""Initialize search_param
"""
if len(search_idx[0]) != len(set(search_idx[0])):
raise ValueError('Duplicate param name.')
elif len(search_idx[1]) != len(set(search_idx[1])):
raise ValueError('Duplicate var name.')
else:
pass
se... | d1308614a4ddc65c73dc766d9864b1b833794200 | 3,616,716 |
def create_timelength(
seconds: spec.TimelengthSecondsRaw,
to_representation: spec.TimelengthRepresentation = None,
) -> spec.Timelength:
"""create Timelength
## Inputs
- seconds: int or float seconds
- to_reprsentation: str name of Timelength representation
## Returns
- Timelength wit... | f7143b484f19e360eb582ca93a11bc9be71b910a | 3,616,717 |
import collections
def _load_vocabulary(filename):
"""Loads a vocabulary file.
Args:
filename: Path to text file containing newline-separated words.
Returns:
vocab: A dictionary mapping word to word id.
"""
tf.logging.info("Reading vocabulary from %s", filename)
vocab = collections.OrderedDict()... | b13648d603c8876cc6acc74c36bc106b75d3f804 | 3,616,718 |
def get_instance_type_by_flavor_id(flavor_id):
"""Retrieve instance type by flavor_id."""
ctxt = context.get_admin_context()
try:
return db.instance_type_get_by_flavor_id(ctxt, flavor_id)
except ValueError:
raise exception.FlavorNotFound(flavor_id=flavor_id) | afa709da2bfa98d1396946b3733d2becb1ae5eb9 | 3,616,719 |
def create_job(system, args:Args) -> str:
""" Create a job file template """
return f"""#!/usr/bin/bash
# --------------------------------------------------
# Request resources here
# --------------------------------------------------
#{system} --job-name={args.name}
#{system} --output={args.name}.out
#{system... | 7a91030310ba8c9185ebc6e07de8a08b9f78dd6c | 3,616,720 |
def standardize_features(df_train, df_test, cols=[]):
"""Scale continuous features to unit variance and zero mean.
Parameters
----------
df_train : pandas.core.frame.DataFrame
A subset of data intended for training.
df_test : pandas.core.frame.DataFrame
A subset of data intended for... | c1ff27d1c339cb155e04d5322bf848bd7694451e | 3,616,721 |
def tile_ref_enc_to_elements(ref_enc, elements_mask):
"""Utility to tile the ref_enc to the same shape as the elements."""
with tf.variable_scope('tile_ref_enc_to_elements'):
orig_shape = tf.shape(ref_enc)
orig_shape_static = ref_enc.get_shape().as_list()
ref_enc = tf.tile(
tf.reshape(ref_enc, [... | 3af995b296228802128a759e113ba9a12579631e | 3,616,722 |
async def get_level(request: web.Request) -> web.Response:
"""GET /api/level/{id}
Description:
Fetch a level by given ID.
Example:
link: /api/level/30029017
Returns:
200: JSON with level info;
400: Invalid type;
404: Level was not found.
Return Type:
a... | 1684a89f3d3dae170b8e93ab5e58189af5487f66 | 3,616,723 |
def sanity_fit(model: nn.Module, train_loader, val_loader,
device: str, num_batches: int = None,
log_interval: int = 100, fp16: bool = False,):
"""
Performs Sanity fit over train loader and valid loader.
Use this to dummy check your fit function. It does not calculate metrics,... | 220d720573d4967dda9ccd77ea1304b53b7d6a55 | 3,616,724 |
from typing import Tuple
import ctypes
def spkezp(
targ: int, et: float, ref: str, abcorr: str, obs: int
) -> Tuple[ndarray, float]:
"""
Return the position of a target body relative to an observing
body, optionally corrected for light time (planetary aberration)
and stellar aberration.
https... | 07de45de30a7364375e5cdba4b7e927468da4b80 | 3,616,725 |
def make_birefringent(theta, eta=pi, phi=0):
"""
:param theta: Angle fast axis makes with horizontal
:param eta: retardance
:param phi: "circularity"?
:return: Jones matrix for the given parameters
"""
a = exp(1j * eta/2)*cos(theta)**2 + exp(-1j * eta/2)*sin(theta)**2
b = (exp(1j * eta... | bac26af439c7aaf670fe286a2f6729f90d50e37c | 3,616,726 |
import json
import logging
def news_API_request(covid_terms:str=json.loads(
open("config.json").read())["news_terms"]) -> list:
"""news_API_request function
This function takes in covid_terms and returns a list of dictionaries of news articles with those terms.
Args:
covid_terms (string)... | 51cfd0bcece47b6e99f64cc5b05311318f31ed65 | 3,616,727 |
def gt(value, other):
"""Greater than"""
return value > other | 943d50ded0dfcb248eefb060d28850154693956b | 3,616,728 |
def user_label(i):
""" Generate the user lable. Lables are 1 indexed.
"""
i = i - 1
if i < 0 or i > len(users):
return "User" + str(int(i))
return users[i] | 736ea251ada086ab1314d8d7b9f3320925bfbaeb | 3,616,729 |
import numpy
def doweight(theta, lam, p, v):
"""Re-weight visibilities
Note that as is usual, convolution kernels are not taken into account
"""
N = int(round(theta * lam))
assert N > 1
gw = numpy.zeros([N, N])
x, xf, y, yf = frac_coords(gw.shape, 1, p / lam)
for i in range(len(x)):
... | f8a397318c43326221e0b4c75d3281b021b27628 | 3,616,730 |
from typing import List
def build_import_command_line(input_path: str, tfs: TempFileSaver,
options: ImportOptions) -> List[str]:
"""Builds a command line for invoking the import stage.
Args:
input_path: The input path.
tfs: TempFileSaver.
options: Import options.
Retur... | 6d3c229274ace20c9375871d3111f4a22f95d448 | 3,616,731 |
def ecg_rsa(rpeaks, rsp, sampling_rate=1000):
"""
Returns Respiratory Sinus Arrhythmia (RSA) features. Only the Peak-to-trough (P2T) algorithm is currently implemented (see details).
Parameters
----------
rpeaks : list or ndarray
List of R peaks indices.
rsp : list or ndarray
Fi... | 999a1a8f3208df113c61af08e4499e6e57ac5cf4 | 3,616,732 |
import jsonschema
import ipaddress
def ipam_release_address():
"""Deallocates the IP address in the given request.
This function takes the following JSON data and remove the given IP address
from the allocation_pool attribute of the subnet. ::
{
"PoolID": string
"Address"... | bb4334f8f62e4151208ed752754313f37c2fd80d | 3,616,733 |
import inspect
from typing import OrderedDict
def data_io_decorator(func):
"""
Decorator to standardize docstrings for data I/O functions.
"""
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
# Parse the docstrings of the base df_to_time_series function & decorated function.
... | 177400dc57bb5a0fa571790a148cf2ebfb176074 | 3,616,734 |
def similar(amazonID, googleURL):
""" Return similarity value
Args:
amazonID: amazon ID
googleURL: google URL
Returns:
similar: cosine similarity value
"""
return (similarities
.filter(lambda record: (record[0] == googleURL and record[1] == amazonID))
... | 3edb4e3a07150fd1da2c09c95ba6d828fc73ba14 | 3,616,735 |
def atos(data, separator=' ', fmt='02X'):
""" Convert array of bytes to string
:param data: Data in bytes or bytearray type
:param separator: String separator
:param fmt: String format
:return string
"""
ret = ''
for x in data:
if fmt == 'c' and x not in printable.encode():
... | 362f2cac329abaa91ebba8b35f72fea27f908bc0 | 3,616,736 |
def get_fc_block(n_in: int, n_out: int):
"""
Fully connected block of SimpleCNN model
:param n_in: number of input channels
:param n_out: number of output channels
:return: fully connected block
"""
block = nn.Sequential(
nn.Linear(n_in, n_out),
nn.ReLU()
)
return bl... | d68a6fba3c1e5413b96e530217a603413ddaff60 | 3,616,737 |
def get_instance_from_str(matrix, format):
"""This function returns the string representation of the given matrix instance according to the indicated format."""
# Parsing format
format_list = format.split('.')
if len(format_list) == 1:
format_primary = format_list[0]
format_secondary = '... | 0bce3af9d6e988a125847a1e3ba29746824cb34f | 3,616,738 |
import stat
def find_duplicates( rootdir ):
"""Find duplicate files in directory tree."""
filesizes = {}
# Build up dict with key as filesize and value is list of filenames.
for path, dirs, files in walk( rootdir ):
for filename in files:
filepath = joinpath( path, filename )
... | a1ce6a15872d50a4447e5d03daae07cd78dfb34c | 3,616,739 |
def get_oiio_info_for_input(filepath, logger=None):
"""Call oiiotool to get information about input and return stdout.
Stdout should contain xml format string.
"""
args = [
get_oiio_tools_path(), "--info", "-v", "-i:infoformat=xml", filepath
]
output = run_subprocess(args, logger=logger... | 00e2bbb28e9e37a294510c54b1127a7ebf928faf | 3,616,740 |
def _tsnr(imgdata, t_axis):
"""Calculate median of temporal signal to noise ratio.
This is consistent with MRIQC
"""
meanimg = np.mean(imgdata, axis=t_axis)
stddevimg = np.std(imgdata, axis=t_axis)
tsnr = np.zeros_like(meanimg)
stddevimg_nonzero = stddevimg > 1.0e-3
tsnr[stddevimg_nonzer... | c31f11d08cc437c1227f5d4cc02d0a0401b5a10c | 3,616,741 |
def point_dist(a, b):
""" Distance between two points. """
return ((a[0]-b[0]) ** 2 + (a[1]-b[1]) ** 2) ** 0.5 | ad3490e25fb21a555ee2d12bead5fa476f682566 | 3,616,742 |
def checking(Y, V_map, S_map, I0_pq, n_buses, n_time, n_scale):
"""
:param Y: data file name
:param V_map: outer iterations
:param S_map: intermediate iterations
:param I0_pq: inner iterations
:param n_buses: number of buses
:param n_scale: number of discretized points, arbitrary
:param... | 69dee0de6b918eca3e4e69de30863b872458d5ea | 3,616,743 |
def parse_xml(path):
"""Return ([analysts], service number, document text, document title).
"""
with open(path) as f:
doc = etree.parse(f)
analysts = [x.text.encode('utf-8', 'ignore')
for x in doc.xpath('//authors/author/author-name')]
title = ''
els = doc.... | 424174d5e8c98503b4d05c7194ddfbce60f9f482 | 3,616,744 |
def task(*, name, waiter=None, exception_handler=None):
"""Returns a decorator that creates a `Task` with the given options."""
def decorator(func):
return Task(name, func, waiter, exception_handler, instance=None)
return decorator | db32e8c7b3013a32be47b58985fe932c4f849bc5 | 3,616,745 |
def quote(s: str) -> str:
"""
Quotes the identifier.
This ensures that the identifier is valid to use in SQL statements even if it
contains special characters or is a SQL keyword.
It DOES NOT protect against malicious input. DO NOT use this function with untrusted
input.
"""
if not (s.... | b4530f7570384beedbb7aafd02e642862a484bb8 | 3,616,746 |
def cluster_tweets_external(texts: PreprocessedText, top=3):
"""
Clusters Tweets, from preprocessed texts in db.
:param texts: PreprocessedText objects representing the texts.
:param top: The number of keywords to assign to each clusters.
:return: The ClusterResult representing the result.
"""
... | d76ae7d2b8c9dcfc8da3943e6c262141571cbe03 | 3,616,747 |
import warnings
def dicom2narray(path, voi_lut = False, fix_monochrome = True):
"""
Converts a DICOM into a NUMPY array and returns this array and
its corresponding dataset.
"""
dicom = pydicom.read_file(path)
# VOI LUT (if available by DICOM device) is used to transform raw DICOM data
#... | 0a02bcf7f4a2e48c7c4476a13d9cfba75bb7d525 | 3,616,748 |
import torch
import os
def evaluate_kantorovich_v2(device, args, model, growth_model=None):
""" Eval the model via kantorovich distance on leftout timepoint
v2 computes samples from subsequent timepoint instead of base distribution.
this is arguably a fairer comparison to other methods such as WOT which ... | 47618c6003a9739ef60ec5df9e55866cdc02d7ed | 3,616,749 |
def make_activity_context(context,
splits, strava_activity,
race,
stravaSessionExists,
isStrava,
trackFit,
laps, lap_index=-1
):
"""
... | e1d0319d7cf71cd2df6b7969e6ab87b740d043cc | 3,616,750 |
def extract_bigrams_as_list(text):
"""Extract bigrams from text and return as list
:param text: source text
:type text: str
:return: bigram tokens list
:rtype: list
"""
tokens = text.split(" ")
bigram_tokens = create_bigrams(tokens)
return bigram_tokens | 3d5dc0c406a084c129ac7edd931fa22a42674977 | 3,616,751 |
import time
import warnings
def find_best_polynomial(data_x, data_y, max_poly_order, rsq_threshold,
max_dim_n=32,
alpha_sweep=None,
max_iter=1000, cv=2):
"""Find minimal polynomial expansion that is sufficient to explain data using Lasso reg... | 6a1b9b9a034acf08710222541c2c1c630e401835 | 3,616,752 |
import decimal
def create_decimal128_context():
"""Returns an instance of :class:`decimal.Context` appropriate
for working with IEEE-754 128-bit decimal floating point values.
"""
opts = _CTX_OPTIONS.copy()
opts['traps'] = []
return decimal.Context(**opts) | 3d6832212e5af5a4eb41c63759ba6f599f0ff7d2 | 3,616,753 |
def decipher(ciphered_text: str, key: str, charset: str = DEFAULT_CHARSET) -> str:
""" Decipher given text using substitution method.
Note you should use the same charset that ciphering end did.
:param ciphered_text: Text to be deciphered.
:param key: Secret key. In substitution method it corresponds ... | 608606abff29bd0b81a96f8ddafbd8f13d389240 | 3,616,754 |
def manifold_polar(x,y,lamda,A,s,p,m,k,mu):
"""
Returns "Omega", the orthogonal basis for the manifold evaluated at x[-1]
and "gamma" the radial equation evaluated at x[-1].
Input "x" is the interval on which the manifold is solved, "y" is the
initializing vector, "lambda" is the point in the c... | fe60dfe0584e9ad6ca4f55ced3ffe504f6c3d40a | 3,616,755 |
def shrink(filename):
"""
:param filename: str, original image.
:return img: SimpleImage, 0.5x size of original image.
"""
original = SimpleImage("images/poppy.png")
blank_img = SimpleImage.blank(original.width//2, original.height//2)
for x in range(0, original.width, 2):
for y in r... | 36f1f1b9942d08206f9706bd282e2b4c7cb21743 | 3,616,756 |
def sendBind(to):
"""绑定手机"""
code = str(randint(1000, 999999))
param = "%s,3" % (code)
return _sendSms(to, config.SMS_BIND, param) and code | 4443d481836673ac52743ae4bd8f03a6e67a89b7 | 3,616,757 |
def WMTNewsCrawl(tokenizer=None, root='.data', vocab=None, split=('train'), year=2010, language='en'):
""" Defines WMTNewsCrawl datasets.
Create language modeling dataset: WMTNewsCrawl
returns the train set
Args:
tokenizer: the tokenizer used to preprocess raw text data.
The defaul... | c4d3ef56ad3373b0663ae4952d3a66518b5b021a | 3,616,758 |
def c2s_stereographic(z):
"""
Stereographic projection from the plane to the sphere.
"""
x = z.real
y = z.imag
u = 2*x
v = 2*y
w = 1 - x**2 - y**2
return np.stack([u,v,w], axis=-1)/(1+x**2+y**2)[..., np.newaxis] | 706f7dc5fb91a3b162a6e3d5def55077c723304a | 3,616,759 |
def get_dtype(nbits):
"""For a given number of bits per sample return
a numpy-recognized dtype.
Input:
nbits: Number of bits per sample, as recorded in the filterbank
file's header.
Output:
dtype: A numpy-recognized dtype string.
"""
check_nb... | d3aa6f32c517d7ebf4fa4a8b2e226f65972a7d0f | 3,616,760 |
def feature_exposed_pop(df):
"""
Adds the total population of the countries to which an individual can travel
from the initial country. Is the population most exposed to the disease
apart from the initial country.
Parameters
----------
df : pandas.DataFrame
Returns
-------
df ... | 47d533b2fa52338d2a2c6414387b744ddf916eac | 3,616,761 |
import select
def add_new_location(project):
"""
Add a new location object to the database
POST data MUST be in JSON format.
POST data MUST contain:
name: location name
POST data SHOULD also contain:
description: location description
POST data CAN also contain:
legacy_id: legac... | d9e44aa11583644970300dfe159f3f6ff67589a0 | 3,616,762 |
def red_highlight(val) -> str:
"""Red highlight
Parameters
----------
val
dataframe values to color
Returns
----------
str
colored dataframes values
"""
return f"{Fore.RED}{val}{Style.RESET_ALL}" | 023c4ca8ee9cec8661cb8a3c1549a71734c51c74 | 3,616,763 |
import math
def animal_ears(image, ear_image, face_landmarks):
"""attach animal_ears like nekomimi
args:
image: base image
ear_image: one animal ear image
face_landmarks: face_landmarks list
"""
for landmark in face_landmarks:
# position of ear_image center
left... | 77f3a629d3d9fa733a2596db6352876befa3067c | 3,616,764 |
def covariance_matrix(data, fb=False, spsmooth=0, method='scm'):
"""
Parameters
----------
data : np.ndarray
The data used to create the covariance matrix. Is of shape (n_samples, n_snapshots)
fb : bool
If true, uses forward-backward averaging
spsmooth : int
Number of ... | 47ec9e531938e6310738737df9a8139c9549e86d | 3,616,765 |
import torch
def replicate_layers(layer: torch.nn.Module, num_copies: int):
"""
# Parameters
layer (torch.nn.Module) - The torch layer that needs to be replicated.
num_copies (int) - Number of copies to create.
# Returns
A ModuleList that contains `num_copies` of the `... | a6e88d2d9d37f2f0cc4acdbdc3da21c19ace1eba | 3,616,766 |
def get_stocks_urls(db_name) -> list:
"""
# This function gets the basic url for each stock. It reads the stocks and url from the database
:return: list for the stocks name and urls [(stock1, stock1_url), (stock1, stock1_url), ...]
"""
con = connect_to_mysql(db_name)
cursor = con.cursor()
cu... | cf7c5309034b34f5e9fa07d079551b7c65065304 | 3,616,767 |
def substBuiltInVarsInParam(val, svars, splitListOfStrs = True, notHandled = None):
"""
Return value with handled substitutions from a param of 'str',
'list-of-strs' types or from a param of 'dict' with params of such types.
"""
if not val:
return val
if isinstance(val, stringtype):
... | 59162fefb02f9f80d167cd1078d409a5ca672688 | 3,616,768 |
def _mangle_dimension_name(name):
"""Return a dimension name from a mixpanel property name."""
fixed_name = name.replace("$", "_")
fixed_name = fixed_name.replace(" ", "_")
return fixed_name | b18738f4c27fcebe7a93f724bfd45414e075f0a6 | 3,616,769 |
def all_variants(protein_id, sequence, position=None):
"""Position is 0-based"""
positions = [(position, sequence[position])] \
if position else enumerate(sequence)
return pd.DataFrame([
[protein_id, sequence, i+1, wt, mt]
for i, wt in positions
for mt in AMINO_A... | 008a31ffbb701d745f39c7d1a9ae18b45b69bf80 | 3,616,770 |
def strftime(time, include_date=True, include_tz=False):
"""
This function converts a time value to a string.
Parameters
----------
time : numeric, pandas.Timestamp with tz
The time value to convert.
include_date : bool (Default: True)
If time is a pandas.Timestamp, include the ... | 41207b31cdc4fa1c87a16d89ca9b8e9ebefe5241 | 3,616,771 |
def update_dict(old_data, new_data):
"""
Overwrites old usa_ids, descriptions, and abbreviation with data from
the USA contacts API
"""
old_data['usa_id'] = new_data.get('usa_id')
if new_data.get('description') and not old_data.get('description'):
old_data['description'] = new_data.get(... | bec860144de28f5e3097e92216d94e6025223d2e | 3,616,772 |
def read(f, normalized=False):
"""MP3 to numpy array"""
a = pydub.AudioSegment.from_mp3(f)
y = np.array(a.get_array_of_samples())
# if a.channels == 2:
# y = y.reshape((-1, 2))
if normalized:
return a.frame_rate, np.float32(y) / 2**15
else:
return a.frame_rate, y | 21c7ce0018f458b35828ca8e82f77ea6facaf608 | 3,616,773 |
from pathlib import Path
import json
def read_fgdb_fc(path, simplify=True, geom_attrs=True, strict=True):
"""Generates a networkx.DiGraph from an Esri File Geodatabase Feature
Class. Point geometries are translated into nodes, and lines into edges.
Coordinate tuples are used as keys. Attributes are pres... | d3215420c8436ad8a930698d5fcc9b61676d9382 | 3,616,774 |
def min_box(box1, box2):
"""
return the minimum of two bounding boxes
"""
ext = lambda values: max(values) if sum(values) <= 0 else min(values)
return tuple(tuple(ext(offs) for offs in zip(dim[0], dim[1])) for dim in zip(box1, box2)) | 58c8a0fa75c66f1327df13a4e7b5a0f7385c805e | 3,616,775 |
def trapezoid(t, params):
"""Trapezoidal pulse. Width of linear slope.
Parameters
----------
params : dict
t_final : float
Total length of pulse.
risefall : float
Length of the slope
"""
risefall = tf.cast(params["risefall"].get_value(), tf.float64)
t... | 107de257dd6072503e5e7cb175e2dd0f2a3e7730 | 3,616,776 |
import logging
import os
def get_maya_logger(path):
"""
Returns a logger object that writes a log file to disk ( provided path )
and to the stderr output.
:param str path:
:return: Logger
:rtype: logging.RootLogger
"""
# get logger
global logger
logger = logging.getLogger()
... | df7ab4a156a0bd2afc018b19f7eb91eb336d6b5c | 3,616,777 |
import sys
def yn_prompt(query):
"""Generic Y/N Prompt"""
sys.stdout.write('%s [y/n]: ' % query)
val = raw_input()
try:
ret = strtobool(val)
except ValueError:
sys.stdout.write('Please answer with a y/n\n')
return yn_prompt(query)
return ret | cf798193438a20565a570ce0afc18871710364ed | 3,616,778 |
import math
def exempt_milliwatts_sar(cm: float, ghz: float) -> float:
"""Calculate power threshold for exemption from routine radio frequency exposure evaluation. Note: narrow range
of applicable frequencies. FCC formula is "based on localized specific absorption rate (SAR) limits." Source: FCC
19-126 p.... | d705c3fd2388204d188e95d9013fe0c574f9e82a | 3,616,779 |
def estimate_fdr_stats(res_real, res_perm, delta):
"""
Helper function for get_fdr_stats_across_deltas.
It computes the FDR and tval_s0 thresholds for a specified delta.
The function returns a list of the following values:
t_cut, n_pos, n_false_pos, pi0, n_false_pos_corr, fdr
"""
perm_avg = ... | 1bfc1b506907ce5b1d42a30916ffe5161b845e21 | 3,616,780 |
def generate_base_anchors(cfg):
"""
Generating top left anchors for given anchor_ratios, anchor_scales and image size values.
:param cfg: dictionary with configuration parameters
:returns: base_anchors = (anchor_count, [y1, x1, y2, x2])
"""
img_size = cfg.IMG_SIZE_WIDTH
anchor_ratios = c... | 474dbdd34a1994dd6de9b24c17991525791f0953 | 3,616,781 |
def spaghetti_annual_hydrograph(file):
"""
spaghetti_annual_hydrograph
INPUTS:
file -- Raven output file containing simulated streamflows of one model
Create a spaghetti plot of the mean hydrological cycle for one model
simulations. The mean simulation is also displayed.
"""
# Tim... | f92637a6794dde26142f1afdddddc0e37c981884 | 3,616,782 |
def divinity_univariate_factory(y:Y_TYPE, s, k:K_TYPE, a=None, t=None, e=None,
max_buffer_len=1000,
n_warm = 101,
model_params:dict=None):
""" A partial wrapping of the divinity library with notable limitations:
... | ec372a70902069635f9c453dce72a620f2638930 | 3,616,783 |
import logging
def fill_categories(array,fill,coord=None):
"""
Replace categorical labels and interpolate missing categories depending on a custom dictionary
:param array: array of a categorical variable
:param fill: dictionary with category replacements and missing categories
:param coord: o... | cb5ad614b85357b2b288b83474410fc9ebc6f2ad | 3,616,784 |
def get_u(r_div_R, z_div_L, k, Ap, Am, lam1):
""" Using Eq. (31) (the second expression) in [1]
"""
# uR_HP = (1. - r_div_R**2.0)*lam1/2.
uR_HP = (1. - r_div_R**2.0)
uZ_PS = -k*(exp( k*z_div_L)*Ap - exp(-k*z_div_L)*Am)
return uZ_PS*uR_HP | cc0a959291186abed0a429fd3933b5d79ddce567 | 3,616,785 |
from stalker import Budget
from stalker import BudgetEntry
import json
import openpyxl
from stalker_pyramid.views.project import get_project_user
import tempfile
from functools import reduce
def generate_report(budget, output_path=''):
"""generates report for the given client and budget
:param stalker.Budget... | 7a80d372fe09d031dd71307255716b052325cc80 | 3,616,786 |
def is_zero(pauli_string):
"""
Checks if a PauliString is zero.
Parameters
----------
pauli_string : (PauliString object) a PauliString object which is to be checked
Returns
-------
True if PauliString is zero, False otherwise
"""
if isinstance(pauli_string, PauliString):
... | aa0a8c0565fd61cf2a767ab081cbfee5f9d2dbd4 | 3,616,787 |
def evalAllocater(task, metrics, reshapeDims, n_classes):
"""Returns an evaluator based on the specified task.
# Arguments
task: integer value denoting the task
metrics: evaluation metrics related to that task
reshapeDims: reshape dimensions of the image
n_classes: integer value denoting the number of classe... | 2a2b15493168c14196d6035e2b3b10a2260c07fe | 3,616,788 |
def checkCrash(player, upperPipes, lowerPipes):
"""returns True if player collders with base or pipes."""
pi = player['index']
player['w'] = IMAGES['player'][0].get_width()
player['h'] = IMAGES['player'][0].get_height()
# if player crashes into ground or above screen
if (player['y'] + player['h... | 85e093c0455e85cae838a0ddce9d5df37a3783ba | 3,616,789 |
def login_required(func):
"""Decorator for enforcing a logged in user.
Also pulls the token out of the request and passes a user instance into the decorated function.
"""
@wraps(func)
def check_log_in(*args, **kwargs):
current_user.ping()
database_session.commit()
return f... | 40a44b5022d3a71f2428b961e81cf493cac4f75d | 3,616,790 |
def gdx(request, year=None, gdx_path=None, array_results=False):
"""
Look up the request in a gdx file.
A request uses Gekko syntax, e.g. "qBNP", "qY[tje]", or "qY[#s]".
If no year is specified, an array is returned with values for all available years.
If no gdx_path is specified, use the global path set usin... | 527e475f42e26efa8810fa6249f8f1b6539a71c6 | 3,616,791 |
def KernelDisorderSC(kx, ky, px, py, params):
"""
This subroutine defines the kernel between self energy and free Feynman propagator.
In case of phase-disordered superconductivity,
this corresponds to the fourier transformation of space correlation of Cooper gap.
E.g. In two dimens... | 4dbc85bb1800d066e1e86edf7f2cbe1840f7d4c0 | 3,616,792 |
def DOV(ATcur, A, Gcur, a):
"""
| LAT | ----------+---------- Astr.
| LON | | Azimuth
| H |AT | (A)
|
|
+-----------------> Deflection of , Geoid
... | b18b26f2985fec536dfda029a1f3803e076d0f5c | 3,616,793 |
import typing
import re
def replace_cif_reference(refs: typing.Iterable[str], new_sub_str: str) -> typing.List:
"""Replace the "cif-reference-0" to bec new names with increasing index."""
ans = []
source = r"@article{.*,"
for i, ref in enumerate(refs):
ref2 = re.sub(source, "@article{{{}{},".f... | 014f633c8eef43093944ec8f63690b59c446c2c1 | 3,616,794 |
import uuid
def random_string() -> str:
"""
Create a 36-character random string.
Returns
-------
str
"""
return str(uuid.uuid4()) | f01e291f6d36a8468a256af0fad83e2d468b471d | 3,616,795 |
def get_points_raytracing(count, side, other_side, building_data, road_part, points_classified):
"""
Get all the point created by the raytracing for the given road segment.
Returns a dictionary with the distances and heights on the left and right side.
"""
bld_dist_heights = {}
i = count
fo... | 30902b1c43d36c37bc13fbb0b88da1465c38012b | 3,616,796 |
import torch
def forward(sample, G, imgs_size, indices, device):
"""
This function takes the whole input, prepares it for the forward pass,
creates the patches of given size and with two loops pass these adiacent
patches through the generator. Then, the simulated patches are concatenaed
together t... | 7fa360e56f27f94090b0f88c42659fdcbb5040f3 | 3,616,797 |
def _extent(x, y):
"""Get data extent for pyplot imshow.
Parameters
----------
x: list
Data array on X-axis.
y: list
Data array on Y-axis.
Returns
-------
[float, float, float, float]
X and Y extent.
"""
dx, dy = .5 * (x[1] - x[0]), .5 * (y[1] - y[0])
... | 1b8a062e2060dc99d3fcdc32fe6fd1952f468a6a | 3,616,798 |
import copy
def OverrideConfigForTrybot(build_config, options):
"""Apply trybot-specific configuration settings.
Args:
build_config: The build configuration dictionary to override.
The dictionary is not modified.
options: The options passed on the commandline.
Returns:
A build configuration ... | 920c1f472893085aca686186e0894421db9d6d20 | 3,616,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.