content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def readProtectedRegistry(protectedRegistryFile):
"""
Reads records from a protected registry and divides into two dictionaries
that map record->(recordId, siteId).
@return: (exactMatchDict, partialMatchDict)
"""
exactMatch, partialMatch = {}, {}
# Iterate the protected registry file one li... | 5,322,000 |
def get_graph_feature(x, xyz=None, idx=None, k_hat=20):
"""
Get graph features by minus the k_hat nearest neighbors' feature.
:param x: (B,C,N)
input features
:param xyz: (B,3,N) or None
xyz coordinate
:param idx: (B,N,k_hat)
kNN graph index
:param k_hat: (int)
th... | 5,322,001 |
def get_poly(time, npoly=3):
"""Returns a matrix of polynomial """
# Time polynomial
t = (time - time.mean())
t /= (t.max() - t.min())
poly = np.vstack([t**idx for idx in np.arange(0, npoly + 1)]).T
return poly | 5,322,002 |
def match(first_name, last_name, province, date_of_birth, record_id):
"""Find the Type of Match, if there is any and create Match object"""
def update_match(notice, match_type):
"""Create Match object"""
try:
record = Record.objects.get(id=record_id)
Match.objects.create... | 5,322,003 |
def rmse(adata):
"""Calculate the root mean squared error.
Computes (RMSE) between the full (or processed) data matrix and a list of
dimensionally-reduced matrices.
"""
(
adata.obsp["kruskel_matrix"],
adata.uns["kruskel_score"],
adata.uns["rmse_score"],
) = calculate_rm... | 5,322,004 |
def p_skip_template_args_extra(p):
"""
skip_template_args : LESS_THAN skip_template_args GREATER_THAN skip_template_args
| LEFT_PARENTHESIS skip_parameters RIGHT_PARENTHESIS skip_template_args
| DOXYGEN_BEGIN skip_doxy DOXYGEN_END skip_template_args
... | 5,322,005 |
def blackened_vim():
"""Currently the main entrypoint."""
start = time.time()
new_buffer_str = _robust_black()
if new_buffer_str is None:
return
vim.current.buffer[:] = new_buffer_str.split("\n")[:-1]
print(f"Reformatted in {time.time() - start:.4f}s.") | 5,322,006 |
def test_history_serialize():
"""
GIVEN a StatusHistory object
WHEN the 'serialize' method is called
THEN a json object representing the history is returned
"""
# Setup history
today = datetime.now()
history = StatusHistory(stand_id=99, status=Status.full.value, status_date=today)
... | 5,322,007 |
def format_dic(dic):
"""将 dic 格式化为 JSON,处理日期等特殊格式"""
for key, value in dic.iteritems():
dic[key] = format_value(value)
return dic | 5,322,008 |
def validate_task(task, tasks=None):
"""
Validate the jsonschema configuration of a task
"""
name = task['name']
config = task.get('config', {})
schema = getattr(TaskRegistry.get(name)[0], 'SCHEMA', {})
format_checker = getattr(TaskRegistry.get(name)[0], 'FORMAT_CHECKER', None)
try:
... | 5,322,009 |
def pred_data_2D_per_sample(model, x_dir, y_dir, fnames, pad_shape = (256, 320), batch_size = 2, \
mean_patient_shape = (115, 320, 232), ct = False):
"""
Loads raw data, preprocesses it, predicts 3D volumes slicewise (2D) one sample at a time, and pads to the original shape.
Assu... | 5,322,010 |
def test_get_error_with_normal_dict_syntax(config):
"""Test that the config can behave like a normal dict."""
with pytest.raises(KeyError):
config["does_not_exist"] | 5,322,011 |
def cogve(COP, freq, mass, height, show=False, ax=None):
"""COGv estimation using COP data based on the inverted pendulum model.
This function estimates the center of gravity vertical projection (COGv)
displacement from the center of pressure (COP) displacement at the
anterior-posterior direction durin... | 5,322,012 |
def locked_view_with_exception(request):
"""View, locked by the decorator with url exceptions."""
return HttpResponse('A locked view.') | 5,322,013 |
def galaxy(ctx, spectral_index):
"""Generate a Milky way only foreground map.
Use Haslam (extrapolated with a spatially varying spectral index) as a base,
and then generate random spatial, spectral and polarisation fluctuations for
unconstrained modes.
"""
from cora.foreground import galaxy
... | 5,322,014 |
def generate_api_queries(input_container_sas_url,file_list_sas_urls,request_name_base,caller):
"""
Generate .json-formatted API input from input parameters. file_list_sas_urls is
a list of SAS URLs to individual file lists (all relative to the same container).
request_name_base is a request name f... | 5,322,015 |
def estimate_H_unbiased_parallel(X, Y, n_jobs, freq_dict = None):
"""Parallelised estimation of H with unbiased HSIC-estimator"""
assert Y.shape[0] == X.shape[0]
p = X.shape[1]
x_bw = util.meddistance(X, subsample = 1000)**2
kx = kernel.KGauss(x_bw)
if freq_dict is not None:
ky = KDiscre... | 5,322,016 |
def histogram(sample, column_name):
"""Create a histogram"""
column = sample[[column_name]]
values = column[column_name].unique()
values.sort()
#print(values)
table = column.groupby([column_name]).size()
table = table.sort_index(level=column_name)
#print(table)
result = table.as_matr... | 5,322,017 |
def logsumexp_across_rois(roi_inputs, rois):
"""
Args:
roi_inputs (torch.Tensor): shape (bn, chn, rh, rw)
rois (torch.Tensor): shape (bn, 5)
Returns:
Tensor, shape (bn, chn, rh, rw)
"""
bn, kn, rh, rw = roi_inputs.size()
# allocate memory, (bn, chn, rh, rw)
rois_logsu... | 5,322,018 |
def add_symbol_and_color(df: pd.DataFrame, colormap: dict):
"""
Color logic happens here. Use nowcast's precipitation, when it is available and
otherwise forecast's weather symbol (defined by YR).
:param df: DataFrame containing weather data
:param colormap: color definitions to use
:return: en... | 5,322,019 |
def ignore_troublesome_polymer(polymer):
"""
See what the possible shortest string is by ignoring one of the polymers and its polymer of inverse polarity.
:param polymer: the string representing the polymer
:return: the simplified polymore
>>> ignore_troublesome_polymer('dabAcCaCBAcCcaDA')
'daD... | 5,322,020 |
def add_version(match):
"""return a dict from the version number"""
return {'VERSION': match.group(1).replace(" ", "").replace(",", ".")} | 5,322,021 |
def replace_cryptomatte_hashes_by_asset_index(
segmentation_ids: ArrayLike,
assets: Sequence[core.assets.Asset]):
"""Replace (inplace) the cryptomatte hash (from Blender) by the index of each asset + 1.
(the +1 is to ensure that the 0 for background does not interfere with asset index 0)
Args:
segmen... | 5,322,022 |
def getValueBetweenKey1AndKey2(str, key1, key2):
"""得到关键字1和关键字2之间的值
Args:
str: 包括key1、key2的字符串
key1: 关键字1
key2: 关键字2
Return:
key1 ... key2 内的值(去除了2端的空格)
"""
offset = len(key1)
start = str.find(key1) + offset
end = str.find(key2)
value = ... | 5,322,023 |
def sample_function_parameter(parameter_name, return_variable_name=None):
""" Returns sample function that extracts a parameter from current state
Args:
parameter_name (string): atrribute in sampler.parameters
(e.g. A, C, LRinv, R)
return_variable_name (string, optional): name of re... | 5,322,024 |
def generate_linear_probe(num_elec=16, ypitch=20,
contact_shapes='circle', contact_shape_params={'radius': 6}):
"""
Generate a one-column linear probe
"""
probe = generate_multi_columns_probe(num_columns=1, num_contact_per_column=num_elec,
... | 5,322,025 |
def subview(request, subid):
"""present an overview page about the substance in sciflow"""
substance = Substances.objects.get(id=subid)
ids = substance.identifiers_set.values_list('type', 'value', 'source')
descs = substance.descriptors_set.values_list('type', 'value', 'source')
srcs = substance.sou... | 5,322,026 |
def debug(msg, suffix='', *args, **argd):
"""Print a debug message to the screen"""
logging.getLogger(_console_name + suffix).debug(msg, *args, **argd) | 5,322,027 |
def convert_to_attributes(
raw: Union[Dict[str, Any], types.Attributes]
) -> types.Attributes:
"""Convert dict to mapping of attributes (deep copy values).
Values that aren't str/bool/int/float (or homogeneous
"Optional" tuples/lists of these) are swapped for
their `repr()` strings, wholesale.
... | 5,322,028 |
def check_row(args, f, ps, idx, row):
"""
Check a row for the presence of any of the patterns in ps
"""
for col_idx, col in enumerate(row):
if args['-c'] and col_idx not in args['-c']:
continue
to_check = str(col)
for p in ps:
s = p.search(to_check)
... | 5,322,029 |
def shouldpoll(name, curtime):
""" check whether a new poll is needed. """
global lastpoll
try: lp = lastpoll.data[name]
except KeyError: lp = lastpoll.data[name] = time.time() ; lastpoll.sync()
global sleeptime
try: st = sleeptime.data[name]
except KeyError: st = sleeptime.data[name] = 900 ... | 5,322,030 |
def submit_task(pipeline_name, accession, rest_api_key, priority="MEDIUM", starting_index=0):
"""
Submits a Conan task. Sending post request to ``api/submissions`` with data similar to the following JSON
{
"priority": `priority`,
"pipelineName": `pipeline_name`,
"startingProcessIndex": `starting... | 5,322,031 |
def puissance(poly, n):
"""Renvoie le polynôme _poly_ à la puissance _n_"""
if n == 0: return [1]
poly = clear_poly(poly)
result = poly.copy()
for i in range(n-1):
result = mult_poly(result,poly)
return result | 5,322,032 |
def getGridSample(lat, lon, n):
"""
Get a random sampling of n locations within k km from (lat, lon)
param: lat latitude of grid center point
param: lon longitude of grid center point
param: n number of locations to sample
return: array of length n of latitude, longitude... | 5,322,033 |
def remotews_fixture():
"""Patch the samsungtvws SamsungTVWS."""
with patch(
"openpeerpower.components.samsungtv.bridge.SamsungTVWS"
) as remotews_class, patch(
"openpeerpower.components.samsungtv.config_flow.socket.gethostbyname",
return_value="fake_host",
):
remotews = ... | 5,322,034 |
def multiplication(integer_one, integer_two):
"""
It multiplies two numbers
Args:
integer_one: The original integer
integer_two: The integer which needs to be multiplied with integer_one
Returns:
an integer with the value: integer_one*integer_two
"""
mul... | 5,322,035 |
def verify_secret_section_values(cm, secret_section_arr):
"""
Verify that values in DB_CLIENT and DB_CLIENT_2 still have assigned values
"""
config = cm.get_config()
for secret_section in secret_section_arr:
assert config.get(secret_section, 'user') == 'datashark'
assert config.get(s... | 5,322,036 |
def group_obs_table(obs_table, offset_range=[0, 2.5], n_off_bin=5,
eff_range=[0, 100], n_eff_bin=4, zen_range=[0., 70.],
n_zen_bin=7):
"""Helper function to provide an observation grouping in offset,
muon_efficiency, and zenith.
Parameters
----------
obs_tabl... | 5,322,037 |
def dist_matrix(n, cx=None, cy=None):
"""
Create matrix with euclidian distances from a reference point (cx, cy).
Parameters
----------
n : int
output image shape is (n, n)
cx,cy : float
reference point. Defaults to the center.
Returns
-------
im : ndarray with shap... | 5,322,038 |
def by_srid(
srid: int,
authority: Union[Authorities, str] = Authorities.EPSG.name,
validate: bool = True
) -> Sr:
"""
Get a spatial reference (`Sr`) by its SRID and, optionally, the authority
(if it isn't an `EPSG <http://www.epsg.org/>`_ spatial reference).
:param srid: the SR... | 5,322,039 |
def prune_network(network):
"""
Removes stub reactions (in- or out-degree of 1 and 0 respectively) and
assures that all other reactions consume and produce something.
Parameters
----------
network: MetabolicNetwork
A MetabolicNetwork instance.
"""
rand_int = numpy.random.random_... | 5,322,040 |
def play(ctx):
"""Starts/resumes playback on a player group."""
with ctx.obj["group"] as group:
group.play() | 5,322,041 |
def admin_cli(request, rancher_cli) -> RancherCli:
"""
Login occurs at a global scope, so need to ensure we log back in as the
user in a finalizer so that future tests have no issues.
"""
rancher_cli.login(CATTLE_TEST_URL, ADMIN_TOKEN)
def fin():
rancher_cli.login(CATTLE_TEST_URL,... | 5,322,042 |
def crop_image(image, crop_box):
"""Crop image.
# Arguments
image: Numpy array.
crop_box: List of four ints.
# Returns
Numpy array.
"""
cropped_image = image[crop_box[0]:crop_box[2], crop_box[1]:crop_box[3], :]
return cropped_image | 5,322,043 |
def fig_uo_coverage_oa_diff(
lad20cd: str,
uo_coverage: dict,
theta: float,
all_groups: dict,
networks: dict,
save_dir: Path,
):
"""Show the coverage difference of each outupt area between the Urban Observatory
network and networks optimised for the coverage of single objectives (single
... | 5,322,044 |
def reorder(names, faname):
"""Format the string of author names and return a string.
Adapated from one of the `customization` functions in
`bibtexparser`.
INPUT:
names -- string of names to be formatted. The names from BibTeX are
formatted in the style "Last, First Middle and Last, Fi... | 5,322,045 |
def test_d_traversal_from_deep_node_gets_full_depth_node_list(full_weight_graph_tree):
"""Test that depth traversal of deep weight graph gets full depth of nodes, no repeat."""
assert full_weight_graph_tree.depth_first_traversal(1) == [1, 2, 4, 5, 3, 6, 7] | 5,322,046 |
def train_model(rank, world_size, args):
""" 모델 학습 """
if 1 < args.n_gpu:
init_process_group(rank, world_size)
master = (world_size == 0 or rank % world_size == 0)
if master and args.wandb:
wandb.init(project=args.project)
vocab = load_vocab(args.vocab)
config = Config.load(arg... | 5,322,047 |
def smoter(
## main arguments / inputs
data, ## training set (pandas dataframe)
y, ## response variable y by name (string)
k = 5, ## num of neighs for over-sampling (pos int)
pert = 0.02, ## perturbation / noise percenta... | 5,322,048 |
def _compute_descriptive_stats(lst: list):
"""Basic descriptive statistics and a (parametric) seven-number summary.
Calculates descriptive statistics for a list of numerical values, including
count, min, max, mean, and a parametric seven-number-summary. This summary
includes values for the lower quarti... | 5,322,049 |
def prepareNewHTTPDConfig(inputDict, currentHttpdConf):
"""Check if needed start end tags are available.
If not consistent or was modified, file will append new config between tags"""
start, end = -1, -1
# Get the start and the end. In the automatic preparation it will 3 lines defined:
# # PROXYR... | 5,322,050 |
def array_xy_offsets(test_geo, test_xy):
"""Return upper left array coordinates of test_xy in test_geo
Args:
test_geo (): GDAL Geotransform used to calcululate the offset
test_xy (): x/y coordinates in the same projection as test_geo
passed as a list or tuple
Returns:
x... | 5,322,051 |
def test_retraining_threshold():
"""
Test that retraining happens at right threshold
"""
emulator = Learner(constant, Emulator)
training_threshold = emulator.init_train_thresh
# The emulator should be untrained until the threshold is reached
for i, x in enumerate(
[np.random.unifor... | 5,322,052 |
def log_density_normal(x, mean=0, var=1, average=False, reduce_dim=None):
"""
:param x:
:param mean:
:param var:
:param average:
:param reduce_dim:
:return:
"""
if isinstance(var, Number):
var = torch.tensor(var).float()
if x.is_cuda:
var = var.to(x.get_... | 5,322,053 |
def get_group_policies(group_names):
"""
returns groups attached policies
"""
# TODO optimize algorithm
group_list = group_names.split(" ")
all_group_policies = ""
for group in group_list:
group_policies_response = iam.list_attached_group_policies(GroupName=group)
group_polic... | 5,322,054 |
def generate_episodes(
tag_reader: Any,
episode_metadata_fn: Callable[[Dict[str, Any]],
Optional[Dict[str, Any]]] = lambda x: x,
step_fn: Callable[[Dict[str, Any]], Dict[str, Any]] = lambda x: x
) -> Generator[Dict[str, Any], None, None]:
"""Generates episodes by reading ... | 5,322,055 |
def _sort2D(signal):
"""Revert the operation of _sort.
Args:
signal an instance of numpy.ndarray of one dimention
Returns:
An instance of numpy.ndarray
"""
to = signal.shape[1]
for i in range(1, to // 2 + 1, 1):
temp = signal[:, i].copy()
signal[:, i:to - 1] = ... | 5,322,056 |
def test_message_glue_sd(diagram):
"""Test gluing message on sequence diagram."""
msg = diagram.create(MessageItem)
ll1 = diagram.create(LifelineItem)
ll2 = diagram.create(LifelineItem)
# 1st lifeline - communication diagram
# 2nd lifeline - sequence diagram
ll2.lifetime.visible = True
... | 5,322,057 |
def get_organizations_by_types(types, allowed_keys=None):
"""Get organization by list of types."""
session = get_session()
items = (
session.query(models.Organization)
.filter(models.Organization.type.in_(types))
.order_by(models.Organization.created_at.desc()).all())
return _to_... | 5,322,058 |
def use(payment_method=None, wallet=None):
"""Set the payment method to be used in the request."""
global _current_method
global _current_wallet
if payment_method:
if payment_method not in [OFF_CHAIN, ON_CHAIN, CHANNEL]:
raise ValueError('Method not supported.')
_current_met... | 5,322,059 |
def demo(args):
"""
Interactive command line demo.
Specify a target database from the Spider dataset and query the database using natural language.
The output includes:
1. if the input question is translated to the SQL query, return the SQL query
2. otherwise, return a confusion span in... | 5,322,060 |
def hiscale(trange=['2003-01-01', '2003-01-02'],
datatype='lmde_m1',
suffix='',
get_support_data=False,
varformat=None,
downloadonly=False,
notplot=False,
no_update=False,
time_clip=False):
"""
This function loads data from the HI-SCALE experim... | 5,322,061 |
def order_stats(X):
"""Compute order statistics on sample `X`.
Follows convention that order statistic 1 is minimum and statistic n is maximum. Therefore, array elements ``0``
and ``n+1`` are ``-inf`` and ``+inf``.
Parameters
----------
X : :class:`numpy:numpy.ndarray` of shape (n,)
Da... | 5,322,062 |
def get_npr(treedata, idx):
"""
Returns number of progenitors of a given idx
"""
ind = np.where(treedata['id'] == idx)[0]
return treedata['nprog'][ind][0] | 5,322,063 |
def PlotOneDimension(data_list, ax, args):
""" Plot one dimensional data.
Args:
data_list: a list of Data objects.
ax: a matplotlib axis object.
args: an argparse arguments object.
"""
if args.mode == 'bar' or args.mode == 'column':
PlotColumns(data_list, ax, args)
elif args.mode == 'hist':
... | 5,322,064 |
def run_gramtools_build(outdir, vcf_file, ref_file, kmer_size=10):
"""Runs gramtools build. Makes new directory called 'outdir' for
the output"""
if os.path.exists(outdir):
raise FileExistsError(
f"Gramtools build output directory '{outdir}' already exists. Cannot continue"
)
... | 5,322,065 |
def cuda_sell_rd_spmv(slice_ptr, slice_col, colidx,
val, x, slice_height, row_th, y):
"""
CUDA Sliced ELLPACK SpMV with reduction.
Parameters
----------
slice_ptr : ndarrays
Slice pointer
slice_col : ndarrays
Column length of each slice
colidx : ndarray... | 5,322,066 |
def dispatch_single_datapoints(timestamp, datapoints, target):
"""
Dispatch data points to given target one at a time based on target's slice sizes
@param timestamp: the time slot for retrieved data points from SQS queue
@param datapoints: a dictionary of data points to be dispatched to given targets
... | 5,322,067 |
def parse_args():
"""Parse arguments from the command line."""
parser = argparse.ArgumentParser("Generate trace files.")
parser.add_argument('--save-dir', type=str, required=True,
help="direcotry to save the model.")
# parser.add_argument('--trace-file', type=str, required=True,
... | 5,322,068 |
def main():
"""
The program finds anagrams of word we type in by using recursion and dictionary of data structure.
"""
# To test how fast all anagrams are found
####################
print(f"Welcome to stanCode \"Anagram Generator\" (or -1 to quit)")
word = input("Find anagrams for: ")
r... | 5,322,069 |
def dir_xtrack_to_geo(xtrack_dir, ground_heading):
"""
Convert image direction relative to antenna to geographical direction
Parameters
----------
xtrack_dir: geographical direction in degrees north
ground_heading: azimuth at position, in degrees north
Returns
-------
np.float64
... | 5,322,070 |
def log(lvl, msg, *args, **kwargs):
""" Logs a message with integer level lvl """
return get_outer_logger().log(lvl, msg, *args, **kwargs) | 5,322,071 |
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path, scheduler, patience=9):
"""returns trained model"""
early_stopping = EarlyStopping(save_path=save_path, patience=patience, )
# initialize tracker for minimum validation loss
valid_loss_min = np.Inf
for epoch in rang... | 5,322,072 |
def micro_jy_to_luminosity(mjy, msun, d):
"""Convert an SED in µJy to log solar luminosities.
Parameters
----------
mjy : ndarray
Flux in microjankies.
msun : float
Absolute magnitude of the Sun. 4.74 is the bolometric absolute
magnitude of the Sun.
d : ndarray
D... | 5,322,073 |
def _MakeRE(regex_str):
"""Return a regular expression object, expanding our shorthand as needed."""
return re.compile(regex_str.format(**SHORTHAND)) | 5,322,074 |
def generate_rand_num(n):
"""
Create n 3-digits random numbers
:param n:
:return:
"""
nums = []
for i in range(n):
r = random.randint(100, 999)
nums.append(r)
return nums | 5,322,075 |
def add_protocols(session, verbose):
"""Adds protocols"""
# 1. DEFINITIONS
enroll_session = [1, 2]
client_probe_session = [3, 4]
protocols = ['A']
# 2. ADDITIONS TO THE SQL DATABASE
protocolPurpose_list = [('world', 'train'), ('dev', 'enrol'), ('dev', 'probe'), ('eval', 'enrol'), ('eval', 'probe')]
fo... | 5,322,076 |
def preprocess_for_eval(image_bytes,
image_size=IMAGE_SIZE,
resize_method=tf.image.ResizeMethod.BILINEAR):
"""Preprocesses the given image for evaluation.
Args:
image_bytes: `Tensor` representing an image binary of arbitrary size.
image_size: image size.
... | 5,322,077 |
def draw_sun():
"""Draw the sun on the canvas"""
c.create_oval(20,20,100,100,fill='yellow') | 5,322,078 |
def _time_to_seconds_nanos(t):
"""
Convert a time.time()-style timestamp to a tuple containing
seconds and nanoseconds.
"""
seconds = int(t)
nanos = int((t - seconds) * constants.SECONDS_TO_NANOS)
return (seconds, nanos) | 5,322,079 |
def _extract_impl(ctx, name = "", image = None, commands = None, docker_run_flags = None, extract_file = "", output_file = "", script_file = ""):
"""Implementation for the container_run_and_extract rule.
This rule runs a set of commands in a given image, waits for the commands
to finish, and then extracts ... | 5,322,080 |
def conforming_delaunay_triangulation(boundary, polylines=None, polygons=None, angle=None, area=None):
"""Construct a Conforming Delaunay triangulation of set of vertices, constrained to the specified segments.
Parameters
----------
boundary : list
Ordered points on the boundary.
polylines ... | 5,322,081 |
def init_db_from_scratch():
"""Build the necessary stuff in the db to run."""
call_command('flush', interactive=False, verbosity=0)
call_command('syncdb', interactive=False, verbosity=0)
filler_data() | 5,322,082 |
def nlopt_newuoa(
criterion_and_derivative,
x,
lower_bounds,
upper_bounds,
*,
convergence_relative_params_tolerance=CONVERGENCE_RELATIVE_PARAMS_TOLERANCE,
convergence_absolute_params_tolerance=CONVERGENCE_ABSOLUTE_PARAMS_TOLERANCE,
convergence_relative_criterion_tolerance=CONVERGENCE_REL... | 5,322,083 |
def ExistsOnPath(cmd):
"""Returns whether the given executable exists on PATH."""
paths = os.getenv('PATH').split(os.pathsep)
return any(os.path.exists(os.path.join(d, cmd)) for d in paths) | 5,322,084 |
def mean_velocity_error(predicted, target):
"""
Mean per-joint velocity error (i.e. mean Euclidean distance of the 1st derivative)
"""
assert predicted.shape == target.shape
velocity_predicted = np.diff(predicted, axis=0)
velocity_target = np.diff(target, axis=0)
return np.mean(np.linalg.nor... | 5,322,085 |
def getObjectFormat(repo, sha):
"""Returns the object format of the object represented by hash"""
"""NOTE: hash has to be a full sha"""
path = repo_file(repo, "objects", sha[0:2], sha[2:])
with open(path, "rb") as f:
raw = zlib.decompress(f.read())
# computing the starting positi... | 5,322,086 |
def wrangle_fast_instances(obj, now):
"""Output instanced geoemtry defined by fast instancing"""
# We need hou.Node handles so we can resolve relative paths
# since soho does not do this.
# NOTE: the above isn't true, some cleverness from RIBsettings shows
# if len(shop_path) > 0:
# if not po... | 5,322,087 |
def v(a, b, th, nu, dimh, k):
"""Function used in **analytic_solution_slope()**
:param a:
:type a:
:param b:
:type b:
:param th:
:type th:
:param nu:
:type nu:
:param dimh:
:type dimh:
:param k:
:type k:
:return:
:rtype:
"""
# real,... | 5,322,088 |
def image_filenames(image_numbers):
"""List of image file names with directory
image_numbers: list or array of 1-based indices
"""
return [filename(i) for i in image_numbers] | 5,322,089 |
def test_discounts(load_data):
"""Test discounting scheme."""
am = AM()
for discount, points in load_data.items():
discount /= 100
for point in points:
assert discount == am.get_discount(point) | 5,322,090 |
def _send_instant_emails(
recipient_list, feedback_message_reference, exploration_id,
has_suggestion):
"""Adds the given FeedbackMessageReference to each of the recipient's email
buffers. The collected messages will be sent out immediately.
Args:
recipient_list: list(str). A list of... | 5,322,091 |
def p_datatype(p):
""" datatype : INT
| INTEGER
| TINYINT
| SMALLINT
| MEDIUMINT
| BIGINT
| FLOAT
| DOUBLE
| DECIMAL
| CHAR "(" NUMBER ")"
| VARCH... | 5,322,092 |
def _load_from_mongo(mongo_uri: str):
"""
Load API Test information from a MongoDB.
Collection used to store API Test information will be named: **apitest**
>>> load_from_mongo("mongodb://127.0.0.1:27017")
<type 'APITest'>
>>> _load_from_mongo("mongodb://user:pass@mongo.example.com:27017/data... | 5,322,093 |
def string_as_datetime(time_str):
"""Expects timestamps inline with '2017-06-05T22:45:24.423+0000'"""
# split the utc offset part
naive_time_str, offset_str = time_str[:-5], time_str[-5:]
# parse the naive date/time part
naive_dt = datetime.strptime(naive_time_str, '%Y-%m-%dT%H:%M:%S.%f')
# pars... | 5,322,094 |
async def test_debug_info_filter_same(hass, mqtt_mock):
"""Test debug info removes messages with same timestamp."""
config = {
"device": {"identifiers": ["helloworld"]},
"platform": "mqtt",
"name": "test",
"state_topic": "sensor/#",
"unique_id": "veryunique",
}
r... | 5,322,095 |
def __find_regexp_in_pdf(extra_data, patterns, forbidden_patterns=None, accept_even_if_not_found=False):
"""
Finds all matches for given patterns with surrounding characters in all filetypes.
Fails only if there are no matches at all or there is a match for a forbidden pattern.
:param patterns: iterable... | 5,322,096 |
def truncated_normal(mean, std, num_samples, min, max):
"""
Return samples with normal distribution inside the given region
"""
return np.random.multivariate_normal(mean=mean, cov=std, size=num_samples * 2) % (max - min) + min | 5,322,097 |
def post_required(func):
"""Decorator that returns an error unless request.method == 'POST'."""
def post_wrapper(request, *args, **kwds):
if request.method != 'POST':
return HttpResponse('This requires a POST request.', status=405)
return func(request, *args, **kwds)
return post_wrapper | 5,322,098 |
def gen_incar(incar_dict=None, dirname='.'):
"""
write a INCAR directly
"""
filename = os.path.join(dirname, INCAR_STRING)
with open(filename, 'w') as _fd:
_fd.write(output_incar(incar_dict)) | 5,322,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.