content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from cache_requests import Memoize
def test_bust_cache_reevaluates_function(redis_mock):
""":type redis_mock: mock.MagicMock"""
# LOCAL TEST HELPER
# ------------------------------------------------------------------------
def call_count():
try:
return redis_mock.get.call_count, ... | 7d61180ea48be9985f9f861777d33e95640795e6 | 35,147 |
from scipy.sparse import csc_matrix
def read_ccs(fname):
"""
Read a CCS matrix from file into a scipy csc matrix.
This routine uses the CCS matrix files that CheSS generates.
Args:
fname (str): name of the file.
Result:
scipy.sparse.csc_matrix: the matrix in the file.
"""
da... | 74d893eeb7176b5dfa967fe1ad009cc64e7e9a4e | 35,149 |
def demo__google_result_open_in_new_tab(raw_text, content_mime):
"""Force google search's result to open in new tab. to avoid iframe problem
在新标签页中打开google搜索结果
"""
def hexlify_to_json(ascii_str):
_buff = ''
for char in ascii_str:
if char in '\'\"<>&=':
_buff ... | 9e11f59ab66d037887c60fa0e5b636af2c5fc0c8 | 35,150 |
def to_location_via_telescope_name(self):
"""Calculate the observatory location via the telescope name.
Returns
-------
loc : `astropy.coordinates.EarthLocation`
Location of the observatory.
"""
return EarthLocation.of_site(self.to_telescope()) | 928fa0afa141dc4a974eb29ad4302b751ab4793b | 35,151 |
def mailmangle_linked(email):
"""
Weakly obfuscates an email address using JavaScript and displays it
with a mailto link. If JS not present (i.e. what's in ``<noscript>``),
displays a link to a reCAPTCHA.
"""
encoded = _encoder(
'<a href="mailto:{0}" class="email">'
'{0}'
... | b6b7a3edfd8e3f714ec3de70e428b1551f3635ac | 35,152 |
def hamiltonian(ncomp, freq, controls):
"""Assemble hf for one spin, given a detuning freq, the control amplitudes
controls, and ncomp components of the control pulse."""
nc = 2 * ncomp + 1 # number of components in hf
hf = np.zeros((nc, 2, 2), dtype=np.complex128)
for k in range(ncomp):
# ... | 50d2c938319d7f817f7272761e3c29799f7b686b | 35,153 |
def delete_database_cluster(rds_client, db_identifier):
"""Function to delete RDS instance.
Args:
rds_client (Client): AWS RDS Client object.
db_instance_identifier (str): RDS instance to delete
Returns:
bool: True if instance was deleted successfully or does not exist,
... | 6469dbb722cb5f546dedbae0a228719e068b668a | 35,154 |
def get_nbow_vecotr(word_string, label_dict):
"""
Calc nBOW vector
:param word_string:
:param label_dict:
:return:
"""
n_bow = label_dict.transform([word_string]) # nBOW vector
n_bow = n_bow.toarray().ravel()
n_bow = n_bow.astype(np.double)
n_bow /= n_bow.sum()
return n_bow | 453a0b9754aef2742aba29f1680bc9d4b99200b6 | 35,155 |
import base64
def google_audio_settings_to_mod9(google_audio_settings):
"""
Map from Google-style audio input to Mod9 TCP server-style audio
input.
Args:
google_audio_settings (dict):
Google-style audio.
Returns:
Union[str, Iterable[bytes]]:
Mod9-style aud... | 65e81e26316201e0032db68ad4cad161e93fc69b | 35,156 |
def get_sequence_lengths(sequence_batch: Array, eos_id: int) -> Array:
"""Returns the length of each one-hot sequence, including the EOS token."""
# sequence_batch.shape = (batch_size, seq_length, vocab_size)
eos_row = sequence_batch[:, :, eos_id]
eos_idx = jnp.argmax(eos_row, axis=-1) # returns first occurren... | 7db2c66c19ad08033126773d8575bac2ee62654d | 35,157 |
def Shift(parent, shift, da_mode="nearest", constant=0.0, name=""):
"""\
Shift the input image.
:param parent: parent layer
:param shift: list of maximum absolute fraction for the horizontal and
vertical translations
:param da_mode: one of "nearest", "constant"
:param constant: fill value... | 8b7d4aa4909bab9dd937d2df03e937c87dcfcf21 | 35,159 |
def iterations_for_terms(terms):
"""
Parameters
----------
terms : int
Number of terms in the singular value expansion.
Returns
-------
Int
The number of iterations of the power method needed to produce
reasonably good image qualit for the given number of terms in th... | 4142d8325f132e16e0525c36d114dd989873870f | 35,160 |
def explained_variance(y_pred, y):
"""
Returns 1 - Var[y - y_pred] / Var[y]
"""
assert y.ndim == 1 and y_pred.ndim == 1
variance = np.var(y)
return np.nan if variance == 0 else 1 - np.var(y - y_pred) / variance | 80ea05c9d83f3d48cfe49a038b81f9712a04df16 | 35,161 |
import itertools
def get_3d_points_from_multiple_observation(candidate_sets, camera_matrixs, fundamental_matrixs, threshold_sv = 15.0):
"""
param candidate_sets : [[np.array{2}, ...], ...] list of candidate sets(list) in cameras
param camera_matrixs : np.array{ v x 3 x 4 }
return : [np.array{3}, ...] ... | 3e1171c798c0ab7f0a587d94ff262d9fafda4b8a | 35,162 |
def get_macro(macro_name):
"""
Get the configured macro
:param macro_name: The name of the macro to add
:return: The macro itself in string form
"""
return MACROS[macro_name] | 624bc6912ce1d32d68ffd11c029b6c84e2bf563f | 35,163 |
def part_1(input_data: str) -> int:
"""What do you get if you multiply your final horizontal position by your final depth?
Returns:
int: [final horizontal position * final depth]
"""
h_pos, depth = 0, 0 # Your horizontal position and depth both start at 0.
commands = parse_input(input_data)... | 4ae988405c568d8f409935dee1eb6413fc68e8a5 | 35,164 |
def preprocess_image(img, cam_values):
"""
Function to prepare image for lane extraction:
1. undistort image
2. crop a region of interest
3. convert image to hsv
4. Get binary gradient image using sobel
5. transfer binary image using the roi
Args:
img ([type]): [description]
... | b4d132144629de64c4556c9f16fa16ce9a54a23d | 35,165 |
import struct
import tqdm
def init_compress_eigerdata(
images,
mask,
md,
filename,
bad_pixel_threshold=1e15,
hot_pixel_threshold=2 ** 30,
bad_pixel_low_threshold=0,
nobytes=4,
bins=1,
with_pickle=True,
reverse=True,
rot90=False,
direct_load_data=False,
data_path... | 71d60adabb48e1b6566e7888dbeca06d54647d88 | 35,166 |
import re
def parseTomEval(inFile, strand):
"""parse the tomtotm.txt file and return a dict of e-values between motifs """
#dict between query and target Ids
matchDict = {}
#read the tomtom.txt file and see if any known are found
with open(inFile, 'rb') as handler:
for line in handler:
line = line.strip()
... | d9394111d35444199f93bf97e7de606d919b9bb3 | 35,167 |
from typing import Dict
from typing import Union
from pathlib import Path
import tqdm
import warnings
def prepare_peoples_speech(
corpus_dir: Pathlike,
output_dir: Pathlike,
) -> Dict[str, Union[RecordingSet, SupervisionSet]]:
"""
Prepare :class:`~lhotse.RecordingSet` and :class:`~lhotse.SupervisionSe... | 48605c9511824a5fbe0e130fa4df0368228a8d0a | 35,168 |
def process_edit_distances(mx, reference_counter, reference_values, search_values):
"""Extract search values that has minimum edit distance from reference values. Multiple hits are enabled."""
min_distances = mx.min(axis=1)
matches = []
for i in range(mx.shape[0]):
min_dist = min_distances[i]
... | 87ea6d8adfd6810c8aa56eb248bb3126acf25022 | 35,169 |
def get_jobs():
"""Get a list of jobs"""
query = "SELECT * FROM urls"
result = db.execute(query)
return jsonify(result) | 03b2987a8a11c88b493c6e6e435434b96e0741db | 35,170 |
def get_leaf_nodes(struct):
""" Get the list of leaf nodes.
"""
leaf_list = []
for idx, node in enumerate(struct):
if node['is_leaf']:
leaf_list.append(idx)
return leaf_list | 90c66e49bac0c49ef5d2c75b4c1cbe6f4fdd4b83 | 35,171 |
def cg_build_w_env(A, B, i):
""" Build the environment for constructing the ith HOTRG isometry
for A and B.
"""
A_indices1 = [1,2,3,4,5,-11]
A_indices2 = [1,2,3,4,5,-12]
A_indices1[i] = -1
A_indices2[i] = -2
A2 = ncon((A, A.conjugate()), (A_indices1, A_indices2))
B_indices1 = [1,2,3... | 4ea4e660dc1dc95cebcb2612c1d9a46d0d7d85ac | 35,172 |
def get_node_edge(docs, w2d_score, d2d_score):
"""
:param docs:
:param w2d_score:
:param d2d_score:
:return:
"""
wid2wnid = {}
w_id, d_idx = [], []
w_d_wnid, w_d_dnid = [], []
w_d_feat = {"score": [], 'dtype': []}
d_d_dnid1, d_d_dnid2 = [], []
d_d_feat = {"score": [], '... | 40e4d0a11fdd671971319ae8d463ad94a7e3ca9a | 35,173 |
def get_elixier_org_by_id_local(id_local):
""" ..liefert den zu id_local passenden Datensatz """
items = DmsElixierOrg.objects.filter(id_local=id_local)
if len(items) > 0:
return items[0]
else:
return None | fdecff1dbc8cda34da994b87fb197b1c88515a75 | 35,174 |
def nearest_approach_to_any_vehicle(traj, vehicles):
"""
Calculates the closest distance to any vehicle during a trajectory.
"""
closest = 999999
for v in vehicles.values():
d = nearest_approach(traj, v)
if d < closest:
closest = d
return closest | de09f23d0886f48ce34c455a41f12c0bb435d216 | 35,175 |
def getAllQuery():
""" This will get all the records in the userQuery table
"""
rows = []
with engine.begin() as conn:
sel = userQuery.select()
rows = conn.execute(sel).fetchall()
return rows | d7800ea523877e930f7e0e0d4c4d70e70ad608ca | 35,176 |
def testingParameters(cal_file = None):
"""
Create a Spliner parameters object.
"""
params = parameters.ParametersSpliner()
params.setAttr("max_frame", "int", -1)
params.setAttr("start_frame", "int", -1)
params.setAttr("background_sigma", "float", 8.0)
if cal_file is not None:... | fbd5c4a20ce036274bf221d4fb9e16933b94d332 | 35,177 |
def fetch_labels(k, kmeans_history, offset=-1):
"""This fetches the original edges of a hierarchical mean.
"""
labels = kmeans_history[1]
passes = labels.shape[0]
indices = np.array([k])
for i in range(offset, -(passes + 1), -1):
try:
indices = np.array([np.nonzero(labels[i]... | b6752505be9cd6b2c849a79ef9e7f9ef6528651f | 35,178 |
def _reshape(t: 'Tensor', shape) -> 'Tensor':
"""
Also see
---------
:param t:
:param shape:
:return:
"""
data = t.data.reshape(shape)
requires_grad = t.requires_grad
if requires_grad:
def grad_f(grad: 'np.ndarray') -> 'np.ndarray':
return grad.reshape(t.s... | 46677d4bbe6fb384fa1759b8c7e08ae481bba5e7 | 35,179 |
from datetime import datetime
def get_target_month(month_count, utc_now=None):
"""
Return datetime object for number of *full* months older than
`month_count` from now, or `utc_now`, if provided.
:arg month_count: Number of *full* months
:arg utc_now: Used for testing. Overrides current time wit... | c2a8f79add91cb176d537cf7a523f70d8c3ec2c2 | 35,180 |
from datetime import datetime
def mark_notifications_read(db: orm.Session = Depends(get_db)):
"""Mark all the notifications as read
Returns:
List of schema.Notification: A list of all the notifications updated to read
"""
notifications = db.query(model.Notification).all()
for notifi... | bb659f1d5676c9442aba4a0bc00c810f51493bad | 35,181 |
import copy
def created_task(result, status=202, mimetype='application/vnd.task-v1+json',
headers={}):
"""
Created response for celery result by creating a task representation and
adding a link header.
:param result:
:type result: AsyncResult
:param status: Http status code. ... | ef56fdb129585e5b078bc20a0a449204c75705d7 | 35,182 |
def _get_dir_list(names):
"""This function obtains a list of all "named"-directory [name1-yes_name2-no, name1-no_name2-yes, etc]
The list's building occurs dynamically, depending on your list of names (and its order) in config.yaml.
The entire algorithm is described in "img" in the root directory and in th... | 284c328878c2c8d0e0ae273c140798e2884ef13f | 35,183 |
def mapCardToImagePath(card):
"""
Given a card, return the relative path to its image
"""
if card == "01c":
return 'src/imgs/2C.png'
if card == "02c":
return 'src/imgs/3C.png'
if card == "03c":
return 'src/imgs/4C.png'
if card == "04c":
return 'src/imgs/5C.png... | f2a8d4918b26617335a274a536a0569c845cb526 | 35,184 |
from typing import Optional
def update_partition(chain_parent_in: list, job_id: str, partition_name: str) -> Optional[dict]:
"""
NOTE: This task is part of a chain(). At very first, it is evaluated if the previous tasks contain any errors.
:param chain_parent_in: Output of parent task.
:param job_id:
... | 72aa1ba409cb83d179cc178daad7677db6f17504 | 35,185 |
def consolidate_gauge(df):
""" takes in gauge columns and normalizes them all to stiches per inch """
try:
df['gauge_per_inch'] = df.loc[:,'gauge']/df.loc[:,'gauge_divisor']
except:
print("Error occured when consolidating gauge")
return df | a3a1eecec97b521c19bc50f2d1496f1aba9fbce6 | 35,187 |
import time
def parse_data(driver):
"""Return a float of the current price given the driver open to the TMX page of the specific symbol."""
# The driver needs time to load the page before it can be parsed.
time.sleep(5)
content_obj = driver.find_element(by="id", value="root")
content_text = conten... | 289a71909753278336c414a0b3c3854aeb60b05f | 35,188 |
def grab_images_and_videos(adir):
"""Grabs image and video files
Args:
adir: directory with images
Returns:
files: image and video files
"""
return grab_images(adir) + grab_videos(adir) | 6acf0559c8e26dde8b179e170693210bc72b43de | 35,189 |
def _get_default_siaf(instrument, aper_name):
"""
Create instance of pysiaf for the input instrument and aperture
to be used later to pull SIAF values like distortion polynomial
coefficients and rotation.
Parameters
----------
instrument : str
The name of the instrument
aper_nam... | d0b4d72d8bd1323521552452a8531a5339c26f56 | 35,191 |
def add_shift_steps_unbalanced(
im_label_list_all, shift_step=0):
"""
Appends a fixed shift step to each large image (ROI)
Args:
im_label_list_all - list of tuples of [(impath, lblpath),]
Returns:
im_label_list_all but with an added element to each tuple (shift step)
"""
... | 63fc45bc14e54ec5af473ec955bd45602f3c7041 | 35,192 |
def load_img_embeddings(source_file):
""" Load image embeddings saved as pickle file
:param source_file: The pickle file where the embeddings are stored
:return: a list of image embeddings
"""
img_embeddings = load_pickle_file(source_file)
img_embed = list(img_embeddings.values())
img_embed... | 775b965d9b90a4aed4e5d68658d9877ca3a24c81 | 35,193 |
def are_aabb_colliding(a, b):
"""
Return True if given AABB are colliding.
:param AABBCollider a: AABB a
:param AABBCollider b: AABB b
:return: True if AABB are colliding
:rtype bool:
"""
a_min = [a.center[i] - a.size3[i] / 2 for i in range(3)]
a_max = [a.center[i] + a.size3[i] / 2 for i in range(3)]
b_min ... | e4d3174cbde1bcffb8e43a710ad2434fb9e4e783 | 35,194 |
def edit_distance(str1, str2):
"""
Given two sequences, return the edit distance normalized by the max length.
"""
matrix = [[i + j for j in range(len(str2) + 1)] for i in range(len(str1) + 1)]
for i in range(1, len(str1) + 1):
for j in range(1, len(str2) + 1):
if (str1[i - 1] ==... | df8f2b5cd6ef2b20c9f8440fe2f65cc0a6185fcf | 35,195 |
import logging
def scoped_logger(module_name: str, config_name: str = "maestral") -> logging.Logger:
"""
Returns a logger for the module ``module_name``, scoped to the given config.
:param module_name: Module name.
:param config_name: Config name.
:returns: Logger instances scoped to the config.
... | 30bf30f1502ad4b89ed2ef0dc006aa12f1db0bff | 35,196 |
def parse (line):
"""Parse line into an array of numbers (`EMPTY`, `OCCUPIED`, or `FLOOR`)
for each spot in the seatring area.
"""
return [ CharToInt[c] for c in line.strip() ] | 708a446fb24e595fb4d8fd7b096543f3a56af1e0 | 35,197 |
def aic(X, k, likelihood_func):
"""Akaike information criterion.
Args:
X (np.ndarray): Data to fit on.
k (int): Free parameters.
likelihood_func (function): Log likelihood function that takes X as input.
"""
return 2 * k - 2 * likelihood_func(X) | 18ec376d15bdb8190818730b4676febdc01bd476 | 35,198 |
from typing import Callable
from typing import Any
def lazy_formatter_gettext(
string: str, lazy_formatter: Callable[[str], str], **variables: Any
) -> LazyString:
"""Formats a lazy_gettext string with a custom function
Example::
def custom_formatter(string: str) -> str:
if current_a... | d9a1a88a146443ba7b4d8b2dc114a4f613128573 | 35,199 |
def render_color_palette(color: tuple) -> Image.Image:
"""
Assembles the entire color palette preview from all the render pieces.
:param color: the color to lookup
:return: the preview image
"""
pixel, ratio = get_cast_color_info(color)
reticle_preview = render_reticle(CAST_COLOR_IMAGE, pix... | c4eb383262f66650f5240b4a52fd92fbb8527acb | 35,200 |
def heightmap_get_interpolated_value(hm: np.ndarray,
x: float, y: float) -> float:
"""Return the interpolated height at non integer coordinates.
Args:
hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions.
x (float): A floating point x coordi... | 7319edf4f3adb08bd6e382612c917f579e7ff0b5 | 35,201 |
def construct_policy(
bucket_name: str,
home_directory: str,
):
"""
Create the user-specific IAM policy.
Docs: https://docs.aws.amazon.com/transfer/latest/userguide/
custom-identity-provider-users.html#authentication-api-method
"""
return {
'Version': '2012-10-17',
'Stat... | 650459810d01b28cc82d320a3b42592d3bb51170 | 35,202 |
def read_b2fgmtry(fileloc):
"""
Modified from omfit_solps.py
"""
with open(fileloc, 'r') as f:
tmp = f.read()
tmp = tmp.replace('\n', ' ')
tmp = tmp.split("*c")
tmp = [[f for f in x.split(' ') if f] for x in tmp]
m = {'int': int, 'real': float, 'char': str}
b2fgmtry = {}
... | 5a198ed94442f40af7a0f823ac5a4b1ac43488a1 | 35,203 |
def random_rotation_matrix(rand=None, key=None):
"""Return uniform random rotation matrix.
rand: array like
Three independent random variables that are uniformly distributed
between 0 and 1 for each returned quaternion.
"""
return quaternion_matrix(random_quaternion(rand, key)) | 7e25403afbe758029fa9773cf8bdbeecb54c076f | 35,204 |
def vea_create(context, values, session=None):
"""Creates a new VEA instance in the Database"""
# If we weren't given a session, then we need to create a new one
if not session:
session = nova_db_sa_api.get_session()
# Create a Transaction around the insert in the Database
with session.begin... | d3d6ea7a6a26df8f0de5d630cadf33e668523ca2 | 35,205 |
from orphics import stats
def binned_power(imap,bin_edges=None,binner=None,fc=None,modlmap=None,imap2=None,mask=1):
"""Get the binned power spectrum of a map in one line of code.
(At the cost of flexibility and reusability of expensive parts)"""
shape,wcs = imap.shape,imap.wcs
modlmap = enmap.mod... | 2731935a1acbacea0f5a776ae72ef56f631df043 | 35,206 |
import logging
def batch_to_dict(batch):
"""
Batch file contains two columns:
FULL/PATH/TO/SAMPLE_bin.13.fa SAMPLE_bin.13
Create a dict with [sample_bin_name] = ["Tigname1", "Tigname2"]
:param batch: full path to batch file
:return batch_dict: dict described above
:return bin_list: list o... | eabfff643ceb0afeee8825863a52d9d740fd97af | 35,207 |
def md_link(name: str, url: str) -> str:
"""Makes strings easier to read when defining markdown links."""
return f"[{name}]({url})" | 7fcef4e75e8fd77f81ddca23957fe326db869a01 | 35,208 |
def extract_uhs(dstore, what):
"""
Extracts uniform hazard spectra. Use it as /extract/uhs/mean or
/extract/uhs/rlz-0, etc
"""
oq = dstore['oqparam']
mesh = get_mesh(dstore['sitecol'])
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
dic = {}
for kind, hcurves in getters.PmapGetter(d... | 97209cbe923e1e237bfcacabcb9f5611866cb82c | 35,209 |
def geocode_presidents(town):
"""
Returns a list of all intersections where a numbered street crosses a street
named after the corresponding president ("1st and Washington", etc.)
Each item in the resulting list is a tuple, with item[0] holding the name
of the intersection ("1st and Washington"... | b1b257f02b1f78b1af509d30e78a003bb0d71e6a | 35,210 |
def _check_numeric(*, check_func, obj, name, base, func, positive, minimum,
maximum, allow_none, default):
"""Helper function for check_float and check_int."""
obj = check_type(obj, name=name, base=base, func=func,
allow_none=allow_none, default=default)
if obj is No... | c3a62c5c95efe44dfb5a7dcd2f36a875f3dcdda1 | 35,212 |
import sh
def cli(args, cook_url=None, flags=None, stdin=None, env=None, wait_for_exit=True):
"""Runs a CLI command with the given URL, flags, and stdin"""
url_flag = f'--url {cook_url} ' if cook_url else ''
other_flags = f'{flags} ' if flags else ''
cp = sh(f'{command()} {url_flag}{other_flags}{args}... | 0159cc37314c3804dd616e6a8e3068a1bcc90520 | 35,213 |
def cleanup(sender=None, dictionary=None):
"""Perform a platform-specific cleanup after the test."""
return True | 655a4f7192d36aa9b73eca40e587eefd3e37f65d | 35,214 |
def dB2(N,s,ρ=0.5,seed=0):
"""
Get random numbers for two correlated rBergomi processes, each having
N paths and s steps.
"""
np.random.seed(0)
# Following assumes orthogonal variance components equivalent
rn = np.random.normal(size=(N,6*s))
# In what follows the 3 indices correspond to ... | 2dfe2172bb50fd9b566860f263778f237affcfe9 | 35,215 |
def karaoke_perceptual_metric(reference_timestamps, estimated_timestamps):
"""Metric based on human synchronicity perception as measured in the paper
"User-centered evaluation of lyrics to audio alignment" [#lizemasclef2021]
The parameters of this function were tuned on data collected through a user Karaok... | 830e6ae8cde5dd96aa53beabe0ffabca1e2bfa15 | 35,216 |
def buildTraceback(frames, modules):
"""
Build a chain of mock traceback objects from a serialized Error (or other
exception) object, and return the head of the chain.
"""
last = None
first = None
for func, fname, ln in frames:
fname = modules.get(fname.split('/')[-1], fname)
... | e6fa610265af765f23588cbb1cae66830007d4a5 | 35,217 |
def deployment_update(uuid, values):
"""Update a deployment by values.
:param uuid: UUID of the deployment.
:param values: dict with items to update.
:raises DeploymentNotFound: if the deployment does not exist.
:returns: a dict with data on the deployment.
"""
return get_impl().deployment_... | 0589a453cdd6d6503b973a0571c58ec8fd476dad | 35,218 |
from typing import List
from typing import Tuple
def navigate_part_two(commands: List[Tuple[str, int]]) -> Tuple[int, int]:
"""Navigate and return the horizontal position and depth."""
horizontal: int = 0
depth: int = 0
aim: int = 0
for command, units in commands:
if command == 'forward':... | 379c31e668ba63fb8bc3b98c28c2cd3087f66c51 | 35,219 |
import time
from faker import Faker
import random
def _generate_events_for_day(date):
"""Generates events for a given day."""
# Use date as seed.
seed = int(time.mktime(date.timetuple()))
Faker.seed(seed)
random_state = random.RandomState(seed)
# Determine how many users and how many events... | 0ebf0d524460d010fbbf29957276fbf81729cc6e | 35,220 |
def _hessian_vector_product(fun, argnum=0):
"""Builds a function that returns the exact Hessian-vector product.
The returned function has arguments (*args, vector, **kwargs). Note,
this function will be incorporated into autograd, with name
hessian_vector_product. Once it has been this function can be
... | 0b4506645b8b5ae1572006f6b64873bf8fa129b2 | 35,221 |
def check_for_tags(*tag_args, msg="Inkluderar inte någon av de givna taggarna"):
"""
Compares the user tags and the test_case tags to see which tests
should be be ran.
"""
def skip_function():
"""
replaces test_cases so they are skipped
"""
raise SkipTest(msg)
de... | 5ddf41d0eb1ce3f8ee5b9c08db027af8e896fce6 | 35,222 |
def find_n_max_vals(list_, num):
"""Function searches the num-biggest values of a given list of numbers.
Returns the num maximas list and the index list wrapped up in a list.
"""
li_ = list_.copy()
max_vals = [] #the values
max_ind = []# the index of the value, can be used to get the param
w... | 48e274a2e2feac04b285b883ce5948c8f39caff3 | 35,223 |
def color_burn(im1, im2):
"""Darkens the backdrop color to reflect the source color.
The color burn formula is defined as:
if(Cb == 1)
B(Cb, Cs) = 1
else if(Cs == 0)
B(Cb, Cs) = 0
else
B(Cb, Cs) = 1 - min(1, (1 - Cb) / Cs)
See the W3C document:
... | 04dd7510d14fb88643fd512fc5020924c5163387 | 35,224 |
def G_2_by_2(a, b, c, d, williams=1, directional=1):
"""G test for independence in a 2 x 2 table.
Usage: G, prob = G_2_by_2(a, b, c, d, willliams, directional)
Cells are in the order:
a b
c d
a, b, c, and d can be int, float, or long.
williams is a boolean stating whether to do t... | 57150b32a0c5b6416dc3c0a1ef8ee0dc7b357b14 | 35,226 |
def test_elapsed_duration(monkeypatch):
"""
.
"""
@counter_wrapper
def duration(interval: float):
"""
.
"""
return interval
monkeypatch.setattr(print_utils, "current_unix_timestamp", lambda: 123)
monkeypatch.setattr(print_utils, "readable_duration", duration... | 0ac8491ff88e09a09b952273413c51855621e3f8 | 35,227 |
def solve(y1,y2) :
""" solve SIS lens equation with
y1,y2 : relative source position with respect to the lens
return : phi,x image position in polar coordinate as arrays of length 2 or 4
"""
eq = lambda phi : eq2(phi,y1,y2)
step = 0.1
phiTest = np.arange(0,2*np.pi+step,step)
test = eq... | e24bd5935f5c8be3700f00cd4a51d122a0b43215 | 35,228 |
def makeNme(segID: int, N, CA, C, O, geo: NmeGeo) -> Residue:
"""Creates a NME capping residue"""
res = makeGly(segID, N, CA, C, O, geo)
res.resname = "NME"
return res | 9335b22a7c578a7eb026d04ba0980d239995ffb7 | 35,229 |
import resource
def sobjects_metadata_resource(client: Client):
"""Return resource representing SObject metadata."""
path = f"{client.resources['sobjects']}"
@resource
class SObjectMetadataResource:
"""..."""
def __init__(self, name):
self.name = name
@query
... | 3c7cd711e0fb01692d43c3b726a8d9e01357b680 | 35,232 |
def makeDrinkInfo(rec_id):
""" Permet de dresser les infos de la boissons passees en argument
:param arg1: id de la boissons (recette)
:type arg1: int
:return: le nom, prix et les informations utiles (alcool, chaud ou froid) de la boissons
:rtype: Json
"""
price = calculePriceRec(rec_id)
nom = recupNameRec... | b428c55b71ab2045b8d660f6cb1e587da4723b13 | 35,233 |
def get_vars(host):
"""
parse ansible variables
- defaults/main.yml
- vars/main.yml
- molecule/${MOLECULE_SCENARIO_NAME}/group_vars/all/vars.yml
"""
base_dir, molecule_dir = base_directory()
file_defaults = "file={}/defaults/main.yml name=role_defaults".format(base_dir)
file... | e2498edda87bc879b7fe571a6c21674ebf3a9164 | 35,234 |
def get_smem_args(smem_args, params):
""" return a dict with kernel instance specific size """
result = smem_args.copy()
if 'size' in result:
size = result['size']
if callable(size):
size = size(params)
elif isinstance(size, str):
size = replace_param_occurren... | 52a77346798a7bd8cf417eb729a2a1a2d5b1059e | 35,235 |
from typing import Optional
from typing import Iterable
from re import T
from typing import Sequence
from typing import Callable
def fork_procs(variant_arg: Optional[Iterable[T]] = None,
variant_args: Optional[Iterable[Sequence]] = None) \
-> Callable[[Callable], process.Handle]:
""" A decorate ... | 149055123de138388b62e52244e9bbab9f13ebe3 | 35,237 |
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3):
"""
Compute c_v coherence for various number of topics
Parameters:
----------
dictionary : Gensim dictionary
corpus : Gensim corpus
texts : List of input texts
limit : Max num of topics
Returns:ocs
... | 3b2391aecc67353f6d60bb68f027713ad7e4ea52 | 35,238 |
def set_mosflm_beam_centre(detector, beam, mosflm_beam_centre):
"""detector and beam are dxtbx objects,
mosflm_beam_centre is a tuple of mm coordinates.
supports 2-theta offset detectors, assumes correct centre provided
for 2-theta=0
"""
return set_slow_fast_beam_centre_mm(detector, beam, mosflm... | a7b0ed140a4beb05766734fe838351f5cfa0c255 | 35,239 |
def getNumColors(path):
"""
Detect the number of colors in the supplied image
(Only up to 8 colors not including the background)
NOTE: This feature is experimental and may not work
well for ALL images
"""
im = Image.open(path)
# Resize to reduce processing time
w, h = im.size
wS... | 7b49dbb48c25910220bcf8ec7b9c267c9d0934b0 | 35,241 |
def reduce_precision_np(x, npp):
"""
Reduce the precision of image, the numpy version.
:param x: a float tensor, which has been scaled to [0, 1].
:param npp: number of possible values per pixel. E.g. it's 256 for 8-bit gray-scale image, and 2 for binarized image.
:return: a tensor representing image... | eb322b81976ea3a2b56c408ce0b9f5eb11580f04 | 35,242 |
from typing import Callable
from typing import Union
from typing import Optional
from typing import Tuple
import functools
def multi_dut_argument(func) -> Callable[..., Union[Optional[str], Tuple[Optional[str]]]]:
"""
Used for parse the multi-dut argument according to the `count` amount.
"""
@functoo... | ce7523c9e63cdc076dc4ec326ce3bc4572042a54 | 35,243 |
def ts2wws(C):
"""
Convert a stiffness tensor into a skew notation stiffness matrix
"""
Cv = zeros(3,6)
for i in range(3):
for j in range(6):
ma = skew_mults[i]
mb = mandel_mults[j]
Cv[i,j] = C[skew_inds[i] + mandel[j]] * ma * mb
return Cv | 55fb55d32af033c6eeb082ffd2740c40376de1ee | 35,244 |
def _get_oauth2_client_id_and_secret(settings_instance):
"""Initializes client id and client secret based on the settings"""
secret_json = getattr(django.conf.settings,
'GOOGLE_OAUTH2_CLIENT_SECRETS_JSON', None)
if secret_json is not None:
return _load_client_secrets(secret... | 1cdb02999af3ab289f262de316bc4afc17add8ac | 35,246 |
def lpp_transform(X, V, ncomp=2):
"""
Args:
--------------
X: n x d. Data matrix
V: d x m. Each column of V is a LPP direction.
ncomp (<= m <= d): The dimension of transformed data
Returns:
--------------
tr_X: n x ncomp
"""
_, m... | 44b362932e420252689fb87e845665a3bdfe332e | 35,248 |
def U_net(optimizer, activation, metrics):
"""
Parameters:
- optimizer (String): Keras optimizer to use
- activation (String): Keras layer activation function to use in hidden
layers
- metrics to use for model evaluation
Returns: (Model)
a compiled U-net designed for binary segmentatio... | 009eea82f105d6b5975a83739f52e43855274481 | 35,249 |
def create_environment(env_name='',
stacked=False,
representation='extracted',
rewards='scoring',
enable_goal_videos=False,
enable_full_episode_videos=False,
render=False,
... | 548449ddcb9dd35161ebb7ab65f564b9644fa438 | 35,250 |
def self_biosample_id():
"""本人的样品编号"""
return SELF_BIOSAMPLE_ID | d2fdf081de5248284b0317051d9d2dcc63e4913b | 35,251 |
def exp_process_image_20(img):
"""Get multiprocess experiment."""
return process_image(
img, imgclf.ImageClassifier(), segments_no=20,
sample_size=100, random_seed=42) | 4cd686fee485106a6004abb4f04fddda7aa722f4 | 35,252 |
import json
import requests
def get_lol_version():
""" Get current League of Legends version """
versions = json.loads(requests.get(
"https://ddragon.leagueoflegends.com/api/versions.json").text)
# reformats from 10.14.5 to 10.14
latest = ".".join(versions[0].split(".")[:2])
return latest | 2702b3375cee503cea561f2965bbafdb17a3f232 | 35,253 |
def retrieve_domain_name(module, client, name):
"""
Retrieve domain name by provided name
:return: Result matching the provided domain name or an empty hash
"""
resp = None
try:
resp = backoff_get_domain_name(client, name)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'... | e88959843c9973c9ac8071316cef9dcaec8ccf91 | 35,254 |
def create_BIP122_uri(chain_id, resource_type, resource_identifier):
"""
See: https://github.com/bitcoin/bips/blob/master/bip-0122.mediawiki
"""
if resource_type not in {BLOCK, TRANSACTION}:
raise ValueError("Invalid resource_type. Must be one of 'block' or 'transaction'")
elif not is_block... | fc6ca06c094082f748c14250cf67da416aaf5fb9 | 35,255 |
import time
def draw_down(x, y, threshold, timeout):
"""
Draws the line down.
:param x: X coordinate of click
:param y: Y coordinate of click
:param threshold: pixel gradient threshold
:param timeout: timeout (sec)
:return: Y coordinate where pixel gradient is hit
"""
y_position = ... | 2bfa7a7fbdeea2c5e4b974cf69b473c44273ab61 | 35,256 |
def read_read_basis(input_string):
"""
"""
pattern = ('ReadBasis' +
one_or_more(SPACE) + capturing(LOGICAL))
block = _get_functional_form_section(input_string)
keyword = first_capture(pattern, block)
assert keyword is not None
return keyword | 6e2f0a59bdddb2ac34ec8cf730f9a778a67e8d59 | 35,257 |
def _Ipr7ConfigRead(config):
"""Extracts DPA and grants from IPR7 config JSON.
Args:
config: A JSON dictionary.
Returns:
A tuple (dpas, grants) where:
dpas: a list of objects of type |dpa_mgr.Dpa|.
grants: a list of |data.CbsdGrantInfo|.
"""
if 'portalDpa' in config:
dpa_tag = 'port... | 78f9288be544c6a66845eadb42bef30fcf84632c | 35,258 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.