content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def initializeANEOS(in_filename = "std::string",
out_filename = "std::string",
izetl = "std::vector<int>"):
"""Initialize ANEOS with some rather arcane input.
in_filename : The name of the ANEOS input file, initializes the Fortran ANEOS library
out_filename : An optional fi... | eedb4227c13e78a52916f64f7589b9a694f3b28f | 3,614,269 |
def verify_already_exists(username):
""" verify if user already exists """
if User.by_name(username):
return "User already exists" | 57cde28a6fbba6d486d0edaec0eb637570f51398 | 3,614,270 |
from bs4 import BeautifulSoup
def parse(fp_or_str):
"""parse TA98 english web pages into a Python dictionary"""
soup = BeautifulSoup(fp_or_str, "html.parser")
res = soup.find_all(class_=('SectionTitle', 'SectionContent'))
sections = {}
found_current_in_hierarchy = False
ta_hierarchy = []
... | 5f52df040ffbe10c7603ff5a3ad0413c591a3819 | 3,614,271 |
from typing import Any
import torch
def infer_device(x: Any):
"""Infer the device of any object (CPU for any non-torch object)"""
if isinstance(x, torch.Tensor):
return x.device
return torch.device("cpu") | a566c267897ca602e13710a30d928fdc49f856a5 | 3,614,272 |
def test_ps_info():
""" log information for manual testing """
return SkipTest("only used in manual testing")
zones, ps_zones = init_env()
realm = get_realm()
zonegroup = realm.master_zonegroup()
bucket_name = gen_bucket_name()
# create bucket on the first of the rados zones
bucket = zon... | a46619a457663d5281d3a4b74ee8d19561e867b5 | 3,614,273 |
def fertl(rw, rt, phi, a, m, vsh, alpha):
"""Estimate water saturation from Fertl [1]_ equation.
Parameters
----------
rw : int, float
Water resistivity.
rt : array_like
True resistivity.
phi : array_like
Porosity (must be effective).
a : int, float
... | a1bcc19d93d6da56bee35f2e917308d0697ab11a | 3,614,274 |
def mean_agg_func(samples: np.ndarray, num_resamples: int=25_000):
"""
Computes mean.
"""
# Point estimation.
point_estimate = np.mean(samples)
# Confidence interval estimation.
resampled = np.random.choice(samples,
size=(len(samples), num_resamples),
... | d0c8d865a6e314f6a7214160b5d79b96a68722bb | 3,614,275 |
def factory_membership_model(user_id, org_id, member_type='OWNER'):
"""Produce a Membership model."""
membership = Membership(user_id=user_id,
org_id=org_id,
membership_type_code=member_type)
membership.save()
return membership | 010bde5588acda75a337a529befcacdcf063820e | 3,614,277 |
def from_arrays(x,y,u,v,mask):
"""
from_arrays(x,y,u,v,mask,frame=0)
creates an xArray Dataset from 5 two-dimensional Numpy arrays of x,y,u,v and mask
Input:
x,y,u,v,mask = Numpy floating arrays, all the same size
Output:
data is a xAarray Dataset, see xarray... | c494f421b5cc7e04f69221f3050917dfe969b8f2 | 3,614,278 |
def dup_gf_factor(f, K):
"""Factor univariate polynomials over finite fields. """
f = dup_convert(f, K, K.dom)
coeff, factors = gf_factor(f, K.mod, K.dom)
for i, (f, k) in enumerate(factors):
factors[i] = (dup_convert(f, K.dom, K), k)
return K.convert(coeff, K.dom), factors | 3795623a33998d29285a6fe454049cd6e908a922 | 3,614,279 |
def turns_remaining(turns):
"""returns the number of turns remaining"""
if turns == 0:
return "You ran out of turns."
else:
return "You have {} turns remaining.".format(turns) | 7315f5522c0da660ba37526005c53ba9986d8aa8 | 3,614,280 |
def cross_ratio(A, B, C, D):
"""The cross ration of four _colinear_ points is invariant under projective
transformation. That means that, for any homography H,
cross_ratio(A, B, C, D) == cross_ratio(HA, HB, HC, HD)
which can be useful."""
# (u, v, w) is the line orthogonal to (A-D), that... | 4095d6c448f0d43824ab5b6a05b1921de98388f1 | 3,614,281 |
import random
def find_optimal_route(start_time,
expected_time,
favorite_route='SBS1K',
favorite_option='bus'):
""" Find optimal route for me to go from home to office.
First two inputs should be datetime instances.
"""
# C... | beb64a91e1b5eae4059048c6bf916b8b15dd0be5 | 3,614,282 |
def load_fasta_file(filename, name=None, feature='fasta', unique=True):
"""
Load a fasta file given the filename.
Args:
filename (str): name of the fasta file.
name (str): name for the sequence set
(default: None means use 'filename' as 'name')
feature (str): name for th... | 5071b2c9f625f4cc5e325bdf87a9d92b19ad0285 | 3,614,283 |
from typing import List
from typing import Tuple
def collect_info_masters(
designspace: designspaceLib.DesignSpaceDocument, axis_bounds: AxisBounds
) -> List[Tuple[Location, FontMathObject]]:
"""Return master Info objects wrapped by MathInfo."""
locations_and_masters = []
for source in designspace.sou... | 80fed01b20d59f32493c8fbf7628e5b922d90cdd | 3,614,284 |
def lines_intersect(line1, line2):
""" Returns intersection point between line1 and line2, or None if they dont intersect """
(x1, y1), (x2, y2) = line1
(x3, y3), (x4, y4) = line2
# Compute coeficients for line1
# where a1 x + b1 y + c1 = 0
a1 = y2 - y1
b1 = x1 - x2
c1 = x2 * y1 - x... | 01630c4e056d9c6cca0fd174b71c86ade0ac91c7 | 3,614,285 |
def _get_project_id():
"""Get project ID from default GCP connection."""
extras = BaseHook.get_connection("google_cloud_default").extra_dejson
key = "extra__google_cloud_platform__project"
if key in extras:
project_id = extras[key]
else:
raise ("Must configure project_id in google_cloud_default "
... | 5dca0b4a9c1e331390e2fa87f891ae63b619ce91 | 3,614,287 |
def get_old_groups():
"""
Get all projects from Firebase which have been created
before we switched to v2.
"""
fb_db = auth.firebaseDB()
ref = fb_db.reference("groups")
projects = ref.get(shallow=True)
logger.info("got old projects from firebase")
return projects | 791a993bfe0b533e3e9826cdfecc05209e234e92 | 3,614,288 |
import json
def get_orders():
"""Return all orders"""
return json.dumps(orders, indent = 4) | f7f72ab387e10a375e86af92fcd0a60470381c6d | 3,614,289 |
def transform_geom(proj, geom):
"""Transform geometry"""
projected_geom = transform(proj, geom)
return projected_geom | fc1f1db121f3925dbc0ce5f062e630ba386868ec | 3,614,290 |
def get_rotation_matrix(init, target):
"""Get rotation matrix that rotates the unit vector init to unit vector target
https://en.wikipedia.org/wiki/Rotation_matrix
Parameters
----------
init : list or numpy array
Initial unit vector
target : list or numpy array
Target unit vecto... | e8dd0f553e96872e5c44b8c1e9150e64c85f5047 | 3,614,291 |
import requests
def make_dcos_request(host_address, relative_url, params=None):
"""Makes a requests that is capable of traversing DCOS EE Strict boundary
:param master: The address for the Mesos master
:type master: `util.host.HostAddress`
:param relative_url: URL path relative to the base address
... | 6075bfc5f5eb935aee835596fc2e6ce4ae530190 | 3,614,292 |
def compute_log_phi(data_intervals, qs, eps, swap):
"""Computes multi-dimensional array log_phi.
Args:
data_intervals: Array of intervals of adjacent points from
compute_intervals.
qs: Increasing array of quantiles in [0,1].
eps: Privacy parameter epsilon.
swap: If true, uses swap dp sensitiv... | a31ba93d85e29f9afb6bf7f005dd0cee25ddcc46 | 3,614,293 |
def get_referencing_foreign_keys(mixed):
"""
Returns referencing foreign keys for given Table object or declarative
class.
:param mixed:
SA Table object or SA declarative class
::
get_referencing_foreign_keys(User) # set([ForeignKey('user.id')])
get_referencing_foreign_k... | 400395d9f8cce763cabdfc74f3c3b9daa6f90966 | 3,614,294 |
def G1DListMergeEdges(eda, edb):
""" Get the merge between the two individual edges
:param eda: the edges of the first G1DList genome
:param edb: the edges of the second G1DList genome
:rtype: the merged dictionary
"""
edges = {}
for value, near in eda.items():
for adj in near:
if (... | 4393e1d9260a02b20d49afe53e86393f16a4d879 | 3,614,296 |
import operator
def find_corners_of_largest_polygon(img):
"""Finds the 4 extreme corners of the largest contour in the image."""
opencv_version = cv2.__version__.split('.')[0]
if opencv_version == '3':
_, contours, h = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Find contours
els... | 3d21c2bfb830b492e3659637640c3a09237eba68 | 3,614,297 |
import tempfile
def hist_k(*args, **kwargs) -> str:
"""Returns the contents of the file created by ISIS hist as a string.
If there is a TO= parameter in the arguments, ``hist_k()`` will
create the file, and return its contents as a string
"""
to_pathlike = None
for (k, v) in kwargs.items():
... | 9154284b6754a74a300b27eaf75d00235efd0442 | 3,614,298 |
def make_rpc_batch_request_entry(rpc_name, params):
"""
Construct an entry for the list of commands that will be passed as a batch
(for `_batch`).
"""
return {
"id": "50",
"version": "1.1",
"method": rpc_name,
"params": params,
} | 603bc7d063f638849a94820af591331f3993c496 | 3,614,299 |
def iterm2hex(root):
"""Get hex codes from iterm xml
Args:
root (xmlroot): xmlroot
Returns:
dict: iterm keys to hex
"""
keys = root.findall("./dict/key")
dicts = root.findall("./dict/dict")
iterm = {}
for i, _key in enumerate(keys):
keyName = keys[i].text
r = g = b = None
for index, item in enumerat... | db499fc5d648727974bc449e5a801eeaa1f5ae46 | 3,614,300 |
def __increaseCombinationCounter(root):
""" increase the combination-counter,
which is located in the provided root-node """
if root['type']=='graphroot':
root['combination'] += 1
return root | c2f7c88ef2eca4f8c4bf6532cc76ed5a1833dfe6 | 3,614,301 |
async def get_complaints(request: Request):
"""Get complains
Get complaints for User.
- If user has role complainer, returns complaints created by this user.
- If user has role aprover, returns complains in status pending
The user have been authenticate!!!.
Args:
request (Request): ... | aabb8eff59a79f8f8d6a3965914634f1a9c40da0 | 3,614,302 |
import winreg
def supports_color():
"""
Return True if the running system's terminal supports color,
and False otherwise.
"""
def vt_codes_enabled_in_windows_registry():
"""
Check the Windows Registry to see if VT code handling has been enabled
by default, see https://super... | 5b3460d0c4da46de1c707a34c471c8278128830c | 3,614,303 |
def make_list_of_model_filenames(model,fc_dates,lt):
"""
returns: flst - list of model files to be opened
dlst - list of dates to be chosen within each file
"""
#fn = make_model_filename_wrapper('mwam4',datetime(2021,1,1,1),1)
flst = []
for d in fc_dates:
fn = make_model_fil... | 0961d7f7c6a6ed952d3ec93013e6c411ecfb765e | 3,614,304 |
def mask_to_lbl(mask, label):
"""Convert mask to label image."""
lbl = np.empty(mask.shape, dtype=np.int32)
lbl[mask] = label
lbl[~mask] = -1
return lbl | 590109ed73d06737551875da4e44117cb8546ff7 | 3,614,305 |
from . import support
def setup_resources(resources=None):
"""
Call either with a list of resources or a resource string.
If ``None`` is given, get the resource string from the environment.
"""
if isinstance(resources, str) or resources is None:
resources = parse_resources(resources)
... | ea9a736e071a3f9f8525c68776e026bd3be6c966 | 3,614,306 |
def approx_average_is_average(hand):
"""
:param hand: list - cards in hand.
:return: bool - is approximate average the same as true average?
"""
median = hand[len(hand)//2]
approx_average = (hand[0] + hand[-1])/2
avg = card_average(hand)
return median == avg or approx_average == avg | 49b6373858a28e7bc9420f1ff561cf0cb0909822 | 3,614,307 |
def test_runner_names():
"""Get iterable of test-runner plugin names."""
return ExtensionManager('cosmic_ray.test_runners').names() | 1d0af25928c1224ebafc9801fc5e1c05877b3060 | 3,614,308 |
def get_options():
"""Create user interface options."""
user_options = {}
user_options['chassis'] = {'label': 'Chassis',
'type': 'stringList',
'default': 'benzene',
'values': chassis_list}
user_options['center-... | dce5c29735b2a0d20dd60cf2df165c4ce2fd4d99 | 3,614,309 |
def compute_dissymmetries(diffables_a, diffables_b):
"""Return a list of dissymmetry from two given diffable lists."""
if not diffables_a and not diffables_b:
return []
dissymmetries = []
for a, b in _outer_join_diffables(diffables_a, diffables_b):
if not a:
dissymmetry = b.... | f8e66a23fbeaf44f9942bf8eea3db009d63a3a55 | 3,614,310 |
def getInterestHistory(asset="", isolatedSymbol="", startTime="", endTime="", current="", size="", archived="", recvWindow=""):
"""# Get Interest History (USER_DATA)
#### `GET /sapi/v1/margin/interestHistory (HMAC SHA256)`
### Weight:
1
### Parameters:
Name |Type |Mandatory |Description
--------|--------|--------... | 2f9abb185241386dd6b072c8c73210112a71332e | 3,614,311 |
def orthonormalize(A):
"""Return an orthonormal basis in which `A` has a sparse representation.
`A` will have support only on the first three elements. The first element
is guaranteed to be proportional to the identity. This basis is
constructed using Gram-Schmidt orthogonalization.
Parameters
... | 6e5a0aecf1f3036bdaccf1ab8e3e39846185e69b | 3,614,312 |
import time
def get_time_human_readable():
"""
returns well formated time string.
for example: Donnerstag, 21:00
"""
return time.strftime("%A, %H:%M") | 2dfc67ba6eec8b830a9bacb5f4d9c6baaab17943 | 3,614,314 |
def proc_annotation(file_path, ann_dict, split, trimmed, class_to_id_map):
"""Process the annotations and return list of file_paths and corresponding
annotations
Arguments:
file_path (str): File path for the corresponding annotation
ann_dict (dict): The annotation dictionary
spl... | 182fa2f8bb168c7d91f0669ff4c2066db6b34869 | 3,614,315 |
def get_csv_filename(name: str) -> str:
"""
Returns the name of a CSV file corresponding to the input file `name`. If `name` is a CSV
file already (that is: does not have an .xls ending or some extension of this suffix) the
`name` is returned unchanged. If on the other hand `name` is the name of a
s... | eb4e61fb926d5295571146aba343e0ee00c1261e | 3,614,316 |
def findpeaks(data, spacing=1, limit=None):
"""Finds peaks in `data` which are of `spacing` width and >=`limit`.
:param data: values
:param spacing: minimum spacing to the next peak (should be 1 or more)
:param limit: peaks should have value greater or equal
:return:
"""
len = data.size
... | a47b5e0767fff2541906160ab358d4dc35c80979 | 3,614,317 |
import numpy
def gaussian_kernel(x1, x2, sigma):
"""
Computes the radial basis function
Returns a radial basis function kernel between x1 and x2.
Parameters
----------
x1 : numpy ndarray
A vector of size (n, ), representing the first datapoint.
x2 : numpy ndarray
A vecto... | 09305fe216a1994e597b9c44c83e7f0fc5283575 | 3,614,319 |
def _extractSpecCAP(config, tab, kernelDict, method = 'CAP', diskRadiusArcmin = 4.0, highPassFilter = False,
estimateErrors = True):
"""See extractSpec.
"""
# Define apertures like Schaan et al. style compensated aperture photometry filter
innerRadiusArcmin=diskRadiusA... | 46cf8a477f3ef3b74e8f5b6af5431fedc618d85c | 3,614,320 |
def freq_title_format(freq):
"""
e.g. Frequency: 440 Hz
e.g. Frequency: 15.0 kHz
"""
if freq < 10000:
title = f"Frequency: {round(freq, 1)} Hz"
elif freq >= 10000:
freq = round(freq * 1e-3, 1)
title = f"Frequency: {freq} kHz"
return title | f2235efcb8d25c33741923ca44962e0ef6bb0899 | 3,614,322 |
def mat_toeplitz(h, g):
"""
Constructs a Toeplitz matrix from the given sequences
Parameters
----------
h: list[]
A sequence defining the matrix for non-negative indices.
This will define the number of rows.
g: list[]
A sequence defining the matrix for negative indices. ... | b9c3cacccd8c230180c1c28ac4e9f2cf2b991a2a | 3,614,323 |
def validateShot(msg):
"""Valida tiro dado e retorna uma resposta formatada.
Parameters
----------
msg : str
Mensagem do client.
Returns
-------
response : str
Resposta formatada.
"""
# Pegar linha e coluna do tabuleiro
line = msg[3] # linha
column = msg[4... | 1652af53ed35d17f59289e4cd6135b708a9cd288 | 3,614,324 |
from typing import Tuple
from typing import List
def _normalize_einsum_in_subscript(subscript: str,
in_operand_shape: ShapeT,
index_to_descr: PMapT[str,
EinsumAxisAccess],
... | 32feadca7092805e27b1d1fb763b4d50327e781e | 3,614,326 |
def poincareSeedsLine(POT, nPoints = 500, start=-1, stop=1, center = [0,0,0]):
"""
returns an array of the positions to seed the stream tracing
the positions lie on a line from going from center through the degenerate
torus. start should be negative for the points to start before the degenerate
to... | e3fdedf82351bd6e4159af53a723bfc9c25bd541 | 3,614,327 |
from typing import Dict
from typing import Any
def modify_openapi() -> Dict[str, Any]:
"""modify_openapi."""
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="MySQL-AutoXtrabackup",
version=f"{VERSION}",
description="Rest API doc for MySQ... | 8f0422ad65734ba4807de67b084ab2ede7b12d64 | 3,614,330 |
def bootstrap(values, nIter, alpha):
"""
bootstrapping to create error bounds, uses resmapling with replacement of sample size n-4
:param values: n-by-m matrix, n = number of runs to resmaple from, m = observations per run
:param nIter: int, number of resamples
:param alpha: float, percentile bounds... | 02b2dbf9ba170ebf2e931100fb63d365395d8f1a | 3,614,333 |
def resolve_required_interfaces():
"""Helper function to build a map of required interfaces based on the
OpenStack release being deployed.
@returns dict - a dictionary keyed by high-level type of interfaces names
"""
required_ints = deepcopy(REQUIRED_INTERFACES)
if CompareOpenStackReleases(os_r... | f7c2a85b99817e3fc32b56d49a841e02a73815da | 3,614,334 |
from typing import Optional
from typing import Union
from pathlib import Path
from typing import List
from typing import Dict
def create_run(
logger: Optional[HasuraLogger] = None,
config: Optional[Union[Path, str]] = None,
charts: Optional[List[dict]] = None,
metadata: Optional[Dict] = None,
swee... | e08222ae1ed5369a9d1118b6c96168aa5ce6aa80 | 3,614,335 |
from typing import List
from textwrap import dedent
def generate_bootstrap_sql_bal_erg(header: Header, outputs: List[Output]) -> str:
"""
Bootstrap sql for erg balance tables
Watcher checks latest height in bal.erg_diffs to determine if bootstrapping
is needed and if so, from which height. Here, we s... | 88cb1510570f78c75fcf5c3f30db0da34821c0a0 | 3,614,336 |
def _gen_id(prefix, suffix=None):
"""
Generates the id
"""
suffix = "-{}".format(suffix) if suffix else ""
return "{prefix}-{uid}{suffix}".format(prefix=prefix, uid=uuid4(), suffix=suffix) | 31fc98e3325a7794e34cd929365df219be840038 | 3,614,337 |
def _add(set, item):
"""Adds an item to the set and returns the set"""
set[item] = _EMPTY
return set | 0bc459c267fc2b88116f74e3fb597004241f7153 | 3,614,338 |
import math
from datetime import datetime
def suntime(date_time,latitude,longitude):
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 21 10:36:23 2017
@author: Roland Proud
"""
T = date_time.timetuple() ### time (today)
## (year, month, day, hour, minutes, seconds)
## lat lon for hobart, tasmania
#lat1 =... | 353a678bc20fe0e991fe69edf158cf586a33f7b6 | 3,614,340 |
def _get_batch(data, i, seq_len):
"""バッチ毎にデータを取得する
"""
slen = min(seq_len, data.shape[0] - i)
inputs = data[i:i + slen]
target = inputs.copy()
# tensorflowのopに変換
# dataは変数ではないのでconstantとする
return tf.constant(inputs), tf.constant(target) | 68ed3536cf720446c1f5523c65efd386b9fc77c8 | 3,614,341 |
from typing import List
def calibrate_universal(observations: List, detector, num_radial=2, tangential=True, zero_skew=True,
mirror_offset=None):
"""
Calibrate a fisheye camera using Universal Omni model.
:param observations: List of {"points":(boofcv detections),"width":(image wi... | 46cc216e2072a70afa55f34d105056ac720f4e40 | 3,614,342 |
def first_pass(text):
"""
Find links, comments, escaped (or non wiki-formatted text), templates and template arguments
:param text:
:return: list containing 2 lists
(first one gives the locations of links, templates and template arguments,
second ... | fabe9a121070c6b91e43701d3545df046e38b2ff | 3,614,344 |
def map_url_out(request, env, application, controller,
function, args, other, scheme, host, port, language=None):
"""
Supply /a/c/f (or /a/lang/c/f) portion of outgoing url
The basic rule is that we can only make transformations
that map_url_in can reverse.
Suppose that the incomin... | 179aba72008865250b3b1f36b92192ce9338e560 | 3,614,345 |
import re
def remove_numbers(s):
"""Removes numbers, including times."""
return re.sub('\d+(:\d*)*(\.\d*)?', ' ', s) | b234b914cc84b04cd183ba086674df0775f3b098 | 3,614,347 |
def process_lightcurve_into_numpy_array(hdulist, row, replace_outliers=True):
"""The function is to get the time series and the flux series from the original light curve file."""
## get planetary and stellar parameters
quality = hdulist[1].data['QUALITY']
tess_mag = hdulist[0].header['TESSMAG']
sta... | cfa5cbdfd0a2beff706f33ab1b6cf707d834df7a | 3,614,348 |
import collections
def char_ngram_count_normalised(text, n, number_of_terms = 0):
"""Returns a list of ngram frequencies given a text
text -- the text from which the word frequencies are to be extracted
n - the number of grams (2 indicates bigram)
number_of_terms -- number of terms to extr... | 952e2366f91ca6d43204276922ad2a179e95e946 | 3,614,350 |
def entropy_difference_timeseries(usage_distribution, absolute=True, intervals=None):
"""
:param usage_distribution: a CxT diachronic usage distribution matrix
:return: array of entropy differences between contiguous usage distributions
"""
if absolute:
return np.array([abs(d) for d in np.di... | ae63ee91ad0712da4d04a1f00904c091ea7fd85e | 3,614,351 |
import logging
def merge_files(left_file: str, right_file: str, columns: list, keep: str = 'none', keep_missing: str = 'none') -> pd.DataFrame:
"""
Merges two csv files
Parameters:
left_file (str): Path to first file
right_file (str): Path to second file
column (str): Name of column to merge ... | feca64766f5505ed95e4717a1d8e1ece94bc9157 | 3,614,352 |
def transformMeshPosOri(vertices, normals, pos=(0., 0., 0.), ori=(0., 0., 0., 1.)):
"""Transform a mesh.
Transform mesh vertices and normals to a new position and orientation using
a position coordinate and rotation quaternion. Values `vertices` and
`normals` must be the same shape. This is intended to... | 281bc002555ef30980d9c382557a7dddbdfa1210 | 3,614,353 |
def rmse_over_time(pred_time_series, meas_time_series, normalization=None):
""" Calculates the NRMSE over time,
Args:
pred_time_series (np.ndarray): predicted/simulated data, shape (T, d)
meas_time_series (np.ndarray): observed/measured/real data, shape (T, d)
normalization (str_or_None... | d560e319847df7ef7a06c9b72840e05fd0621edb | 3,614,354 |
def planFree(world,hand,qtarget):
"""Plans a free-space motion for the robot's arm from the current
configuration to the destination qtarget"""
globals = Globals(world)
cspace = TransitCSpace(globals,hand)
robot = world.robot(0)
qmin,qmax = robot.getJointLimits()
#get the start/goal con... | 4281f2cd1ffa759d2fceec927a11c04c99f52605 | 3,614,356 |
import torch
def squash_tensor(x, min_val, max_val):
"""Normalize a tensor to a specific range."""
x_np = x.clone().numpy()
sq = np.interp(x_np, (x_np.min(), x_np.max()), (min_val, max_val))
return torch.from_numpy(sq) | d64326d15b06bc0e9be11e66655bfff158645fe2 | 3,614,357 |
def test_downstream_message_sending_via_recipewrapper_with_unnamed_output():
"""Test sending messages via the RecipeWrapper when the current step
does not have named outputs, or any output at all.
"""
def downstream_message(dest, payload, path=()):
"""Helper function to generate expected messag... | ebf070c63e72a749321e210f7a40d0093af78251 | 3,614,358 |
from werkzeug.exceptions import SecurityError
def get_host(environ, trusted_hosts=None):
"""Return the host for the given WSGI environment. This first checks
the ``Host`` header. If it's not present, then ``SERVER_NAME`` and
``SERVER_PORT`` are used. The host will only contain the port if it
is differ... | 292b949a5ab2b5f1eb52d06c1a785a61935b6f54 | 3,614,359 |
import copy
def feature_engineering(df, ft_requests, idcol):
"""
The Feature Engineering module needs FeatureTools installed to work.
So please do "pip install featuretools" before trying out this module.
It takes a given data set, df and adds features based on the requet types in
ft_requests whic... | d43bdb0895162922e9c927181f906244cb2175bd | 3,614,360 |
def rss(type: RSSType):
"""Get the RSS feed url for the entire site depending on which feed type you want
Parameters
-----------
type : RSSType
The type of feed you desire to get
Returns
--------
str
URL for the feed type
"""
return f"https://rss.moddb.com/{type.nam... | f12b35057e15bcd8aea31007a9441e641eefcc38 | 3,614,361 |
def explode_df(df, schema):
"""
Transform ouroborous DR1/DR2 extracts into unified vote table
Designed for Ouroborous raw data extract, after removing rare answers.
Args:
df (pd.DataFrame): rows by classification, columns by question (e.g. 'decals-0'), values by answer (e.g. 'a-0')
schem... | ea997a0920e8b2919f659901fd5629ca146da95f | 3,614,362 |
def fold(ts, period, bins, subints=None):
"""
Fold TimeSeries at given period
Parameters
----------
ts : TimeSeries
Input time series to fold
period : float
Period in seconds
bins : int
Number of phase bins
subints : int or None, optional
Number of desire... | 9d53355bcdc0cf073f030886962de8daba0090bc | 3,614,363 |
def is_image(im, cv2_ok=True, pil_ok=True):
""" Check if the input is a valid image or not
Args:
im: image
cv2_ok (bool, optional): check cv2. Defaults to True.
pil_ok (bool, optional): check pil. Defaults to True.
"""
assert cv2_ok or pil_ok
if cv2_ok:
flag_cv2 = is... | d96d99c2e7a93a4389239dfccc3013fd87cebd40 | 3,614,364 |
def get_ois_using_template(template,
type_ois: TypeOis, rp: Qcf.RecPay, notional: float, start_date: Qcf.QCDate,
tenor: Qcf.Tenor, fixed_rate_value: float, spread: float, gearing: float):
"""
"""
template_dict = template[type_ois]
meses = tenor.get_y... | 0898b8c9f5c5d1c03318f2b31a2507e5cec6988c | 3,614,365 |
from typing import Iterable
from pathlib import Path
def get_versions(
dependency: str,
granularity: str = "minor",
# ascending: bool = False, limit: Optional[int] = None,
# allow_prerelease: bool = False,
) -> Iterable[str]:
"""Yield all versions of `dependency` considering version constraints
... | 82853c6728de30aa55368d3230ccfc285a9e34eb | 3,614,366 |
import numpy
def insert_dummy_atom(zma, x_key, x_key_mat, x_name_mat, x_val_dct):
""" insert a dummy atom at a given position in the z-matrix
"""
syms = symbols(zma)
key_mat = numpy.array(key_matrix(zma))
name_mat = numpy.array(name_matrix(zma))
# check whether x_name_mat overlaps with name_m... | 82115070c618bae5ed01995fdcea2c9b90e20897 | 3,614,367 |
def prepare_plane_to_curved_flat_arbitrary(k, rs_support, num_pointss, z, xo, yo, qs_center=(0, 0), kz_mode='local_xy'):
"""Prepare propagator from uniformly sampled plane to arbitrarily sampled curved surface.
The zero-th order component (k_z) is included (arbitrarily) in Px.
Args:
k (scalar): Wav... | 620601d45384c0942d02fc047c06fd627300b8c3 | 3,614,368 |
def deprecated_alias(**aliases):
"""
A deprecation decorator constructor.
Parameters
----------
aliases: str
The key-value pairs of mapping old --> new argument names of a
function.
Returns
-------
callable
A decorator for the specific mapping of deprecated argu... | f9b71682a55a298c4626e51f3b53864ff8adf44c | 3,614,369 |
from typing import Optional
def get_asset_encryption_key(account_name: Optional[str] = None,
asset_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetA... | 6c794a2347a4a939857342ef7f6558d11c6b10bb | 3,614,370 |
def _escapeWildCard(klassContent):
"""
>>> _escapeWildCard('')
''
>>> _escapeWildCard(':*')
''
>>> _escapeWildCard(':Object')
':Object'
"""
return klassContent.replace(':*', '') | 537b3969dabb46c3a093dacc3ba49a58833f8c18 | 3,614,371 |
def convert_xyz_to_rgb(x, y, z, *, space, reference, clip=True):
"""
Converts give XYZ values to RGB (0-1).
Note: For general purpose use, directly use conversion functions like
`xyz_to_srgb`, `xyz_to_adobe_rgb` etc. instead using this function.
:param x: X
:param y: Y
:param z: Z
:par... | da909f979013e47806e3ea364db3022d439b5868 | 3,614,372 |
def _show_graph() -> None:
"""Function that sets the plt configuration then calls matplotlib.show().
plt configuration is set from _GLOBAL_GRAPH_CONFIGS
"""
_configure_plot(_GLOBAL_GRAPH_CONFIGS)
plt.show()
return None | f9cb085828e414c0fc306d2ecd2dd6d7275d74d9 | 3,614,373 |
import logging
import tqdm
def pr3_search(bursts, obs_mjds, obs_durations, pmin=1.57, pmax=62.8, nbins=8, pres = None, nopbar=False):
"""
Periodicity search using Pearson chi square method used in The CHIME/FRB Collaboration et al 2020
:param bursts: List or array of burst MJDs
:param obs_mjds: Start... | a1e8014d0e3f52352ea5cdd75da308adaeb21773 | 3,614,374 |
import gzip
import tqdm
import json
def get_df(path):
""" Apply raw data to pandas DataFrame. """
idx = 0
df = {}
length = len(gzip.open(path, 'rb').readlines())
g = gzip.open(path, 'rb')
# progress = g
progress = tqdm(g, desc='transforming', total=length, leave=False, unit_scale=True)
... | 9c22ae55c4a95b8a891d923541cba79d967263bf | 3,614,375 |
def width_required_for_column(header, values):
"""
Spaced needed to display column in a single line, accounts for the two
extra characters that the tabulate package adds to the header when the
content is too short
"""
values_max = -1 if not values else max(len(str(v)) for v in values)
return... | 1ec812af0da623f4b52edc6708f265a5c14fb03a | 3,614,376 |
def token_to_tuple(token: Token) -> tuple:
"""Convert token to tuple."""
return (token['txn_hash'],
token['owner'],
token['value'],
token['signature']) | 43429d0995d5f45c78fc80326ca3e7d718bb0137 | 3,614,378 |
def _setup_entities(hass, dev_ids, platform):
"""Set up Tuya Climate device."""
tuya = hass.data[DOMAIN][TUYA_DATA]
entities = []
for dev_id in dev_ids:
device = tuya.get_device_by_id(dev_id)
if device is None:
continue
entities.append(TuyaClimateEntity(device, platfo... | e50189e52c1495028b2fd1a3432eaa8f80ad2a64 | 3,614,380 |
import torch
import re
import collections
def imed_collate(batch):
"""Collates data to create batches
Args:
batch (dict): Contains input and gt data with their corresponding metadata.
Returns:
list or dict or str or tensor: Collated data.
"""
error_msg = "batch must contain tenso... | 553e27cedc2767270ae2d70490af0af19e1da16f | 3,614,381 |
import time
def throttle(s):
"""Decorator ensures function that can only be called once every `s` seconds.
"""
def decorate(f):
t = None
def wrapped(*args, **kwargs):
nonlocal t
t_ = time()
if t is None or t_ - t >= s:
result = f(*args, ... | 5095b9477958099798d1a00740e313d007e346e4 | 3,614,382 |
import numpy
def _tot_recovery_op(habitat_arr, num_arr, denom, max_rating):
"""Calculate and reclassify habitat recovery scores to 1 to 3.
The equation for calculating reclassified recovery score is:
score = 3 * (1 - num/denom/max_rating)
If 0 < score <= 1, reclassify it to 1.
If 1 < score <=... | 7f538374e62884a355b2976707125505fd93550d | 3,614,383 |
import posixpath
def rdsamp(record_name, sampfrom=0, sampto=None, channels=None, pn_dir=None,
channel_names=None, warn_empty=False, return_res=64):
"""
Read a WFDB record, and return the physical signals and a few important
descriptor fields.
Parameters
----------
record_name : str... | d2271ff273b34d7871b944aab9c925e771b33dad | 3,614,384 |
import tkinter
def create_puzzle_frame(parent_frame, n, current_puzzle_frame=None, read_only=False):
"""
Creates a new puzzle frame inside a parent frame and if the puzzle frame already exists, first destroys it.
This is done because when the n changes we have to change the puzzle frame's grid row and col... | 9017d288c2ae33a789af3a1197d09375282e3fdf | 3,614,385 |
async def tag_info_command(ctx: utils.PrefixContext) -> None:
"""Get info about a tag
Args:
<name|alias>: The tag name or alias to get info about.
"""
name = ctx.options.name.lower()
query = (
"SELECT t.tagname, t.tagowner, t.uses "
"FROM tags t FULL OUTER JOIN tag_aliases a... | 0dc13ef6f7e484fb96146625afff687a7adf2dec | 3,614,386 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.