content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def GenerateMLNetWrapper(function, output_name):
"""
The starting to create the C# Files.
It takes in a function from the function list and builds all the output based on that.
"""
# should be fine to have constant
required_namespaces = ["Microsoft.ML", "Microsoft.ML.Data",
"Microsoft.... | d5d1e80e6ef778996ecc1913abf65396ef43bcf9 | 71,588 |
def check_flacs(flacs):
"""
Check if the given flacs are suitable for transcoding.
:param flacs: A `list` of `mutagen.flac.FLAC` objects.
:returns: A string containing a description of the problem if there was
one, or `None` if no problems were detected.
"""
if any(flac.info.chan... | 3004ef891fb6d7b1b20ba40009448b99e08c3784 | 71,589 |
def cov_eig_kl(m, y, k=None):
"""computes similarity of x, y covariance matrices"""
s1, s2 = get_svd(m, y)
if k is not None: s1, s2 = s1[:k] - s2[:k]
d = F.kl_div(F.softmax(s1) - F.softmax(s2))
return d | 8a465043b6173ab337eabe119f55023cdbe2bab2 | 71,590 |
def generic_sum(algorithm):
"""compute digest based on algorithm passed in parameter
:param algorithm: hashlib algorithm to use
:return: digest returned by the algorithm
"""
def hash_sum(fileobj):
"""compute digest by chunks multiple of the block_size
:param fileobj: Open file(-l... | 5f3f3e00b9a1878d416491a06453cfeed4e0884c | 71,591 |
def load_as_dataset(relative_path, version=iati.version.STANDARD_VERSION_ANY):
"""Load a specified test data file as a Dataset.
Args:
relative_path (str): The path of the file, relative to the root test data folder. Folders should be separated by a forward-slash (`/`).
version (str): The versio... | 31f97575a2ebd50a4b3cf9583ea238dea7293840 | 71,592 |
def solid_angle(ra_lim, dec_lim):
"""
Calculate solid angle with given ra & dec range.
All angles in degrees.
Parameters
----------
ra_lim : list-like, optional
ra limits.
dec_lim : list-like, optional
dec limits.
Returns
-------
area : float
Solid angle ... | 477ed7fac6ce65e45cba5b6f1334f9554ac5064c | 71,593 |
def plot_lor_fit(data, skew=1, full=1, plt=plt):
"""Fits a Lorentzian function to a dataset and plot the result.
'data' is a data array with elements [x-axis data,y-axis data];
'skew' is 1 (default) to subtract a linear background,
and 0 to use no slope;
'full' is 1 (default) to fit the whole datas... | 55d6f9688f5c8b9cf3bcd85db6e762e0e196a5cb | 71,594 |
def jacobian(x, *args):
"""Calculates jacobian of log-linear model."""
data, n_features, lambda_, datapath, verbose, store_intermediate, weights_fname = args
empirical_counts = np.zeros(shape=n_features)
expected_counts = np.zeros(shape=n_features)
transformed = data
for feat_dict in transfo... | 382500f421eca01b64b6e5d7fb71158e5cd7a42a | 71,595 |
def parse(data, raw=False, quiet=False):
"""
Main text parsing function
Parameters:
data: (string) text data to parse
raw: (boolean) output preprocessed JSON if True
quiet: (boolean) suppress warning messages if True
Returns:
List of Dictionaries... | e4d980ac8ecd147bf530651cf9ef08f5af7aecd5 | 71,596 |
def index():
"""
Student index
* list available activities (GET)
- along with information about them (also how many spaces available)
"""
chosen_activity = student_chosen_activity()
activities = []
for activity in dict_sql_query("SELECT * FROM activities"):
activities.appe... | fda2591ce06e653ce19d68a4f56fdbadd78dee55 | 71,597 |
def Phi_batch(X, theta, MSE_reduction, W_1, W_2):
"""
Computes MSE-loss for batch X containing N samples (rows) by averaging or summing
the individual sample losses.
"""
N = X.shape[0]
# Accumulate loss over all batches
loss_batch = 0.0
for n in range(N):
x = X[n, :].reshape(1,... | 19045d73507f06ac2ecbb3f206f3b8d17a222638 | 71,598 |
def get_input(question: str, validation: str):
"""
ask a question and validate the input
Parameters
----------
question : str
question string to display.
validation : str
regex string used to validate input.
Returns
-------
str
the value inserted.
"""
... | 79b01a67deeef7213bdde622d7997a5c27474055 | 71,600 |
import torch
def pre_process_datasets(encoded_datasets, input_len, cap_length, start_token, delimiter_token, clf_token):
""" Pre-process datasets containing lists of tuples(story, 1st continuation, 2nd continuation, label)
To Transformer inputs of shape (n_batch, n_alternative, length) comprising for each batch, ... | 737a9513a3ff9ef74a0ba985f6e6d4b17f6ce669 | 71,601 |
from typing import _type_convert
def _type_checking_for_xspace(start, stop, num, endpoint, dtype, axis):
"""utility parameter checking function for linspace, logspace, geomspace."""
if not isinstance(start, ARRAY_TYPES):
_raise_type_error("start should be int, float, bool, list, tuple, Tensor, but got... | 3b3fcfc4d67d378bb47d1ccff87e806c46b88374 | 71,602 |
def prime(n):
"""
return true si n est premier
"""
if n % 2 == 0:
return (n == 2)
# règle dxd < n
# on peut cesser la recherche d'un diviseur dès que d2 > n.
# En effet, si n est composite, c'est-à-dire produit de deux facteurs (différents de 1),
# le plus petit d'entre eux es... | 4031355bb38b1f347f800932ed27fb8dadf8b7f3 | 71,603 |
import sh
def setup_remote(ind):
""" setup any state specific to the execution of the given module."""
sh(f"""
# docker kill pyfra_test_remote_{ind}
# docker container rm pyfra_test_remote_{ind}
cd tests
cp ~/.ssh/id_rsa.pub .
docker build -t pyfra_test_remote .
docker run --rm --name ... | e9ac71e007d1387780831f62fee447d27ca5b171 | 71,604 |
def get_voltage_metrics(results: PyDssResults, job_info: JobInfo):
"""Return the voltage metrics for all scenarios."""
voltage_metrics_table = []
data = _read_file(results, "Reports/voltage_metrics.json")
if not data:
return voltage_metrics_table
for scenario in data["scenarios"]:
... | 9e9dc340a00fafc6c5c402c09ce65f524bb295c2 | 71,605 |
import numba
def _reorganise_product(vis, cp_argsort, out_vis):
""" Reorganise correlation product dim of vis so that
correlations are grouped as given in cp_argsort.
Parameters
----------
vis : np.ndarray
Input array of visibilities and weights.
Shape: (nt... | 4893592915a925edb51079e4e6db6040dbc505a7 | 71,606 |
def timegap(x, y, timedelta='D'):
"""
Calculate the number of ``timedelta``'s between date x and y. Order of
the dates is unimportant.
Parameters
----------
x : str, date-like, or Series-like
First date, or series of dates.
y : str, date-like, or Series-like
Second date, or ... | 939a402c77b78e11e5a4004212e05f692c57681a | 71,607 |
def saveall(filename='NLSdata'):
""" save all data in a compressed file .npz """
np.savez_compressed(filename,
nx=nx,
ny=ny,
nt=nt,
xmin=xmin,
xmax=xmax,
ymin=ymin,
... | dc8f1bb3908516c853de7ad551baad036a394454 | 71,608 |
from typing import Any
def encode_voltage(value: Any) -> bytes:
"""Encode voltage value to raw (2 bytes) payload"""
return int.to_bytes(int(value * 10), length=2, byteorder="big", signed=True) | f970783eb7d84b61d9db8c230a6a5622b571635d | 71,609 |
def merge_dict(x,y):
"""
将字典x合并入字典y
"""
for k,v in x.items():
if k in y.keys():
y[k]=str(y[k])+";"+str(v)
else:
y[k] = v
return y | 2251af1fe611ba7c2bf9978094ad0f649bd4d4d7 | 71,611 |
import random
def roll_damage(dice_stacks, modifiers, critical=False):
"""
:param dice_stacks: Stacks of Dice to apply
:param modifiers: Total of modifiers affecting the roll
:param critical: If is a critical damage roll
:return: Total damage to apply.
"""
if critical:
for dice_sta... | 2627f1de0fe0754a4bfc802378ea1950b2b078a2 | 71,612 |
def complet_csv(human_csv, delta, triplet_id):
"""Complete the human csv file with the new delta values"""
df = pd.read_csv(human_csv)
df = df[
[
"subject_id",
"triplet_id",
"language_TGT",
"language_OTH",
"phone_TGT",
"phone_... | 8b63e3cfd5ed373e2db026a2c1888cd2f9359a0d | 71,613 |
def solve_puzzles(puzzles, boxsize, model = 'CP'):
"""Solve every puzzle in iterable 'puzzles'."""
return [solve_puzzle(puzzle, boxsize, model) for puzzle in puzzles] | 994f4b1b15e0893833d07bac536efe79357f5762 | 71,614 |
from unittest.mock import patch
def test_get_last_state_changes(opp_recorder):
"""Test number of state changes."""
opp = opp_recorder()
entity_id = "sensor.test"
def set_state(state):
"""Set the state."""
opp.states.set(entity_id, state)
wait_recording_done(opp)
return... | c49f24291983dc13503cf9031106eb09551a40ab | 71,615 |
def get_audio_bitrate(bitrate):
"""
Get audio bitrate from bits to human easy readable format in kbits.
Arguments:
:param bitrate: integer -- audio bitrate in bits per seconds
:return: string
"""
return "%s kbps" %(bitrate/1000) | 847d74e08e8f75b24be1fc144fb3896f5e141daf | 71,616 |
def _mesh_to_mat_cards(mesh, divs, frac_type):
"""Prepares the material cards for mesh_to_geom."""
mat_cards = ""
idx = mesh.iter_structured_idx('xyz')
for i in idx:
mesh.mats[i].metadata['mat_number'] = int(i + 1)
mat_cards += mesh.mats[i].mcnp(frac_type=frac_type)
return mat_cards | 2d3cbd8d4a371244938ce1b9aa1e2532801e705d | 71,617 |
def frame(frame_id):
"""
Retrieve metadata for an id that points to a Frame.
:param frame_id: the key of a Frame in H2O.
:returns: dict containing the frame meta-information.
:examples:
>>> training_data = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/junit/cars_20... | 799435951d1e69a613c9f8fdcf5a1ded301c6f86 | 71,618 |
def norm_one_constraint(x):
"""
This function defines an 1-norm equality constraint on the a vector.
The value returned by the function is 0 if the equality constraints is satisfied.
Parameters
----------
:param x: vector
Returns
-------
:return: difference between the norm of x an... | 72baa3c70db819a0f3c5f47c68156213eef275fd | 71,619 |
def wrap360_to180(ds, lon='lon'):
"""
wrap longitude coordinates from 0..360 to -180..180
Parameters
----------
ds : Dataset
object with longitude coordinates
lon : string
name of the longitude ('lon', 'longitude', ...)
Returns
-------
wrapped : Dataset
Anot... | 4c37efb575fb0ed29630da71410467455bfdec04 | 71,620 |
from datetime import datetime
def filter_jobs_by_start_date(client=None, project_key=None, start_date=None):
"""List jobs that were started after a specific date.
Args:
client: A handle on the target DSS instance
project_key: A string representing the target project key
start_date: A ... | 9bcad881eb5d09878b445de45d3f5f2d88cb0ddb | 71,621 |
from typing import Dict
from typing import Any
import torch
import datasets
def evaluate_config(cfg: DictConfig) -> Dict[str, Any]:
"""Evaluates with the given hydra configuration.
Args:
cfg: Hydra-format configuration given in a dict.
Returns:
Evaluation result given in a dict, containi... | 340188dd920cba94aaf1a6fba50838d3da17623d | 71,624 |
def get_welcome_response():
""" If we wanted to initialize the session to have some attributes we could
add those here
"""
session_attributes = {}
card_title = "Welcome"
speech_output = "Hello ! I am your AWS Case Status Bot! You can get the status of a case by saying. " \
"... | 3582b5ff940289d93c1ac7009b0bdcadd31d1c71 | 71,626 |
def output_prefix(prefix):
"""Decorate a function to add a prefix on its output.
:param str prefix: the prefix to add (must include trailing whitespace if
desired; Sopel does not assume it should add anything)
Prefix will be added to text sent through:
* :meth:`bot.say <sopel.b... | 8f7e333b3fd40725b3d9681cfdf432d01cb8d24e | 71,627 |
import typing
def main(args: typing.List[str]) -> int:
"""Main entry point, return exit code."""
parsed_args = parse_arguments(args)
protocol = parsed_args['protocol']
output_folder = parsed_args['output']
scribble_file = parsed_args['filename']
sing_file = not parsed_args['single']
err_... | 866441dfec7b147b1884453daaa6e248a614897c | 71,629 |
from typing import Any
from typing import List
def apply_env_wrapper_preprocessors(
environment: Any,
env_preprocess_wrappers: List,
) -> Any:
"""Apply env preprocessors to env.
Args:
environment : env.
env_preprocess_wrappers : env preprocessors.
Returns:
env after the p... | 9f56bc5a38b46d8f5f1bd3fa462b2bf27b9ca02f | 71,630 |
import array
def maxs(p, lengths=None):
"""Return ordered array of max distances from a point to the edges of
a hypercuboid.
"""
if lengths is None:
lengths = [1.] * len(p)
a = array([max([p[i],lengths[i]-p[i]]) for i in range(len(p))])
a.sort()
return a | d27f1af51f52871c44dada133255dcecd7c6fe41 | 71,631 |
def mock_keyboard():
"""Fixture to provide a mock hardware keyboard for tests to simulate keyboard events."""
return MockKeyboard() | 1e1b281d86b1f006eef68aae63e69f053d57e311 | 71,632 |
def spat_ave_rmsd_vs_time(Cout, Cref):
""" Spatially averaged root mean square deviation versus time"""
if not Cout.shape == Cref.shape:
raise ValueError("Incompatible shapes: {}, {}".format(
Cout.shape, Cref.shape))
N = Cout.shape[1]
err = Cout - Cref
return np.sqrt(np.sum(err**... | b13f4c04835efd3fe466e703d28f7cc0150ed7bc | 71,633 |
async def async_setup_entry(hass, config_entry):
"""Set up Mikrotik Router as config entry."""
controller = MikrotikControllerData(hass, config_entry)
await controller.async_hwinfo_update()
await controller.async_update()
if not controller.data:
raise ConfigEntryNotReady()
await contr... | 8f92852520a8c767375ed776e7d0c0e4587a978a | 71,634 |
from typing import Dict
import configparser
def get_config_xrandr_args() -> Dict[str, str]:
"""Read xrandr argument configurations from CONFIG_PATH.
Returns
-------
xrandr_args
A mapping from screen layout names to xrandr arguments that apply
specific screen layouts.
"""
confi... | 006816afa683c567f8fe6534283593554fc9585d | 71,635 |
import torch
from typing import Optional
import warnings
def affine_image_transform(image_batch: torch.Tensor,
matrix_batch: torch.Tensor,
output_size: Optional[tuple] = None,
adjust_size: bool = False,
interpo... | 51741b1bf655d2dfd8fb3455f40d18fdc0eec33b | 71,636 |
from typing import Any
import websockets
import json
async def userinfo(code: str, timeout: int = config.TIMEOUT) -> Any:
"""
返回最近游玩成绩
"""
async with websockets.connect(config.ESTERTION_URI, timeout=timeout) as ws:
await ws.send(f"{code} 1 5")
pstring = await ws.recv()
if pstri... | 4acf557d66c9039f8db60aecb9d508f25fa1f963 | 71,637 |
import torch
def torch_from_pandas(df: pd.DataFrame, cols=None, types=None):
"""
Transform pandas.DataFrame into torch.Tensors based on columns
If columns is None, new Tensor will be created for each column in df
"""
_tensors = []
if cols is None:
for col in df.columns:
cu... | c4fbcc578966420031fb574618cfdd6b1ceb9c58 | 71,639 |
from unittest.mock import patch
def test_query_balances_asset_balance(mock_bitfinex, inquirer): # pylint: disable=unused-argument
"""Test the balances of the assets are returned as expected.
Also test the following logic:
- An asset balance is the result of aggregating its balances per wallet
ty... | 45461df772faa0e1db30fbb171f88accbc6e2d5c | 71,640 |
import numpy
def fftfreq(n=None, d=1.0):
"""
Compute the one-dimensional discrete Fourier Transform sample frequencies.
Limitations
-----------
Parameter ``d`` is unsupported.
For full documentation refer to :obj:`numpy.fft.fftfreq`.
"""
return call_origin(numpy.fft.fftfreq, n, d) | 8ca61b7dceca8ad1b250b1d6c95c1222a0332def | 71,641 |
import collections
def load_manifest(manifest_path):
"""Extract sample information from a manifest file.
"""
# pylint: disable=I0011,C0103
Sample = collections.namedtuple("Sample", "id status path")
samples = []
with open(manifest_path, "r") as manifest_file:
for line in manifest_fi... | 21e15fa8de75d963f8d35c4b5f939d3fcee45c99 | 71,642 |
def get_post_like_info(post, author):
"""
Returns a boolean indicating whether the author parameter
liked the post parameter and an integer representing the
number of likes on the post parameter
If an error occurs, it returns None and 0
"""
try:
if type(post) is LocalPost:
... | 6a9bd9ea98098db587119f5d7d8caba409bb7fc8 | 71,643 |
def gtsrb_decoder(codes,
height,
width,
channels,
batch_norm_params=None,
weight_decay=0.0):
"""Decodes the codes to a fixed output size. This decoder is specific to GTSRB
Args:
codes: a tensor of size [batch_size, ... | 3392f3f8169c708ee3d22687d147e8802eb75845 | 71,644 |
from typing import Sequence
def _get_predicted_output(
batch_predicted_kinds: dt.NDArrayIntBO,
batch_predicted_indices: dt.NDArrayIntBO,
output_token_encoder,
input_eval_data: dt.BatchedEvalTocopoData,
decode_utf8: bool = True) -> Sequence[Sequence[str]]:
"""Get the predicted output generated by... | 7f4079cd6980940a223790923658822b09fe430c | 71,645 |
def subplot_fixed(n_rows, n_cols, ax_size,
x_margin=(200, 200),
y_margin=(200, 300),
ax_spacing=125):
"""Create figure with subplots of a fixed size.
"""
# Convert lists to arrays. This makes working with them easier.
ax_size = np.array(ax_size)
... | 03e3e661f6cfe182186a8f13de4471d0ef194f3a | 71,646 |
def _get_ascii_token(token):
"""Removes non-ASCII characters in the token."""
chars = []
for char in token:
# Try to encode the character with ASCII encoding. If there is an encoding
# error, it's not an ASCII character and can be skipped.
try:
char.encode('ascii')
except UnicodeEncodeError:... | e77f9fe9d59cbcee8cd1893e56a988b70a15542a | 71,647 |
def parse_env_var(value):
"""
Split a env var text like
ENV_VAR_NAME=env_var_value
into a tuple ('ENV_VAR_NAME', 'env_var_value')
"""
k, _, v = value.partition('=')
# Remove any leading and trailing spaces in key, value
k, v = k.strip(), v.strip().encode('unicode-escape').decode('asci... | 129151ba1f6f1f953761db900f8a87fda0895932 | 71,648 |
def sample_a2c_params(trial):
"""
Sampler for A2C hyperparams.
:param trial: (optuna.trial)
:return: (dict)
"""
gamma = trial.suggest_categorical('gamma', [0.9, 0.95, 0.98, 0.99, 0.995, 0.999, 0.9999])
normalize_advantage = trial.suggest_categorical('normalize_advantage', [False, True])
... | 54c7aa216df4617a1093bf1cc9d7cd3b65f18739 | 71,649 |
def get_child_pages(context, parent):
"""
Return all children of parent.
"""
paginator = get_paginator(context, parent)
page = context['request'].GET.get('page', 1)
return paginator.page(page) | 0c21843c3d984f248fd124ed80704392251cee15 | 71,650 |
import inspect
def oneOrMany(answer, *, forceTuple = False, forceContainer = True,
consumeFunction = True, isDict = False, returnForNone = None):
"""Returns the the first element of the list if it is one item long.
Otherwise, returns the list.
Example Input: oneOrMany(answer)
Example Input: oneOrMany(yieldAnsw... | 2cd167558682da9bacc708f7fd32050dbf27cbd4 | 71,651 |
def string_at(ptr, size=-1):
"""string_at(addr[, size]) -> string
Return the string at addr."""
return _string_at(ptr, size) | 454b9f8ca7af39fd59099841f1cc14121055ee2a | 71,652 |
from typing import Any
def parse_record_field(registry: Any, *, type, **kwargs: Any) -> AvroField:
"""Helper function to parse the type of a record field."""
return AvroField(type=parse(registry, type), **kwargs) | 6275908497baf616a1fd43cb0393ea7a9fa34863 | 71,653 |
def _rabbitmq_helper():
"""
Helper method that establishes a connection with rabbitmq and returns
a channel to work with
"""
rabbitmq_connection = pika.BlockingConnection(parameters=params)
return rabbitmq_connection.channel() | 4966ff9e0b9819c3ba7b1fa1a24cad8db1949c7f | 71,654 |
import pickle
def loadFromFile(filePath):
"""
从本地文件中加载序列化的内容
param filePath: 文件路径
return content: 序列化保存的内容(e.g. list, dict, tuple, ...)
"""
with open(filePath) as f:
content = pickle.load(f)
return content | ab183b5e5f31c9fd0b7b6ba2c9687401617dd7e4 | 71,655 |
import json
def list_response():
"""JSON:API list pytest fixture."""
return json.load(open('tests/responses/example_list.json')) | f4e815f452ae3e0eb806bbd816c429ad0a63c413 | 71,656 |
def _cosine_drift(high_pass, frame_times):
"""Create a cosine drift matrix with frequencies or equal to
high_pass.
Parameters
----------
high_pass : float
Cut frequency of the high-pass filter in Hz
frame_times : array of shape (n_scans,)
The sampling times in seconds
Ret... | 1529f2a744fdeb977741c52f70e9d9c5bac73910 | 71,658 |
def fcport_to_dict(db_fcport):
"""
Convenience method to take a FC Port entry DTO and return a dict
representation of the DTO. When FCPorts are created and looked up by
their own DOM above, then this logic can move to the DOM's to_dict().
"""
fcport_dict = {'id': db_fcport.id,
... | d3d1f2f4a42c02d09fc2a9c7abc2e7a0f0a3ef0f | 71,659 |
def getRowCharBounds(rows):
"""
Gets the segment image of chars in a text row image
For every row segment gets a list of char segments
Parameters
----------
rows(list[numpy.ndarray,...]) : The list of segmented text row images
Returns
-------
list : List of segment chars images... | c199b0954ff626f0f2f01b809bc25064d591d3a5 | 71,660 |
import numpy
def fix_nans(picklename):
"""Marshall has a few NaNs, replace these with Drimmel"""
with h5py.File(picklename.replace('.sav','.h5'),'r') as combdata:
pix_info= combdata['/pixel_info'][:]
best_fit= combdata['/best_fit'][:]
nanIndx= numpy.isnan(best_fit[:,0])
print("Found %i... | 8b07d1b172227395eefa7a8a2144621030aed8a5 | 71,661 |
def unpack_run(shape, dtype, tensor_format, num, axis, attrs):
"""run function for unpack"""
mod = utils.op_build_test(unpack.unpack, [shape], [dtype],
op_attrs=[tensor_format, num, axis],
kernel_name="unpack", attrs=attrs)
data, expects, out_bufs ... | 1fd33224945b881b049c0a67302191bf3aa7e90f | 71,663 |
import re
def fix_vba_code(vba_code):
"""
Fix up some substrings that ViperMonkey has problems parsing.
"""
# Clear out lines broken up on multiple lines.
vba_code = re.sub(r" _ *\r?\n", "", vba_code)
vba_code = re.sub(r"\(_ *\r?\n", "(", vba_code)
vba_code = re.sub(r":\s*[Ee]nd\s+[Ss]ub"... | 13dfef692ccfdbf544f48f8912ac98c01e2186da | 71,665 |
def get_filename(fd):
"""
Helper function to get to file name from a file descriptor or filename.
:param fd: file descriptor or filename.
:returns: the filename.
"""
if hasattr(fd, 'name'):
# fd object
return fd.name
# fd is a filename
return fd | d2b3e51969c0f445037cbf099bda3c499ae66b0e | 71,666 |
def _get_all_osc(centers, osc_low, osc_high):
"""Returns all the oscillations in a specified frequency band.
Parameters
----------
centers : 1d array
Vector of oscillation centers.
osc_low : int
Lower bound for frequency range.
osc_high : int
Upper bound for frequency ra... | 9199283080bd0111d8ca3cb74f4c0865de162027 | 71,667 |
def xerob2tauR(z,xe): #xe:ionization rate of the Universe ; z = list in descending order (from 30 to 0 for instance)
"""
computes tau(z) integrated from xe(z)
"""
dz = abs(z[1]-z[0])
csurH = 0.925e28 / hz.h #cm
Hdezsurc = (hz.Om*(1+z)**3.+hz.Ol)**(0.5) /csurH
eta=1 #eta=1 for now
int... | 161327b24fea284c4cdb22ad9332ceb3ffce77ae | 71,668 |
def make_color_wheel():
"""
Generate color wheel according Middlebury color code
relative lengths of color transitions:
these are chosen based on perceptual similarity
(e.g. one can distinguish more shades between red and yellow
than between yellow and green)
:return: Color wheel
"""
... | 6b2d479d2f5dfbd6aecaaa7ad95f925ab18c512d | 71,670 |
def CanViewGroupMembers(perms, effective_ids, group_settings, member_ids,
owner_ids, user_project_ids):
"""Return True if the given user may view a user group's members.
Args:
perms: Permissionset for the current user.
effective_ids: set of user IDs for the logged in user.
group... | c5bcedf86f3e227f67fc96a25c342f1f988e6dc1 | 71,671 |
def purity(y_true, y_pred):
"""Calculate purity for given true and predicted cluster labels.
Parameters
----------
y_true: array, shape: (n_samples, 1)
True cluster labels
y_pred: array, shape: (n_samples, 1)
Cluster assingment.
Returns
-------
purity: float
Calculate... | 162427c1cc70e9369a6e0699d571fcf20c9feea0 | 71,672 |
def keras_decay(step, decay=0.0001):
"""Learning rate decay in Keras-style"""
return 1.0 / (1.0 + decay * step) | b922e999ff678127535988eaf04b35e2be2a9117 | 71,674 |
def PublicAPI(obj):
"""Annotation for documenting public APIs.
Public APIs are classes and methods exposed to end users of RLlib. You
can expect these APIs to remain stable across RLlib releases.
Subclasses that inherit from a ``@PublicAPI`` base class can be
assumed part of the RLlib public API a... | 62f5567fe67e6a7048ae9c6fc11ae58bcec49fb5 | 71,675 |
def _inverse_gaussian_cdf(p: float, mean: float, stddev: float) -> float:
""" CDF is monotonically increasing so using binsearch to find correct value
:param p float: Value P(X < x) for which we want to find x
:param mean float: Mean of distribution we calculate
:param stddev float: Stddev o... | 890786e8e03d8340018aecd96f240c73f810a181 | 71,676 |
def create_tag_and_add_to_item(request, app, object_type, object_id):
"""adds tag with name=request.POST['tag'] to the tag list, and tags the given object with it
****
Currently not used anywhere, sine we don't want to allow users to add
more tags for now.
"""
if request.method == 'POST' and 'ta... | dcc6da590a740204b93f2860fc831ef87c3e2bba | 71,677 |
def address_capability():
"""Storage `user_capability` will update. Useful to assert over in tests."""
return {} | de8a75beed5de5b9ee06e34e7d702f563a93cf65 | 71,678 |
def to_xml_string(item: BibliographicItem, **kwargs) -> bytes:
"""
Passes given item and any kwargs through to :func:`.to_xml()`,
and renders the obtained XML element as a string with pretty print.
"""
return serialize(item, **kwargs) | 8bdbb026a9319b63f5cfcdd64ff3f73db897c787 | 71,679 |
def get_dtd_menu_texts(has_dtd):
"""determine text to update dtd menu with
"""
# how to use in gui.<xx>.py:
# def adjust_dtd_nemu(self):
# label, helpstr = shared.get_dtd_menu_texts(self.dtdmenu.has_dtd)
textdict = {'label': '{} &DTD', 'help': '{} the Document Type Declaration'}
re... | 359a91ec3b0bfe5cc28f1b3cf0ec44e9f34bd210 | 71,680 |
from typing import OrderedDict
def load_section(cp, section, ordered=True):
"""
Returns a dict of the key/value pairs in a specified section of a configparser instance.
:param cp: the configparser instance.
:param section: the name of the INI section.
:param ordered: if True, will return a <colle... | 9b819efb75082138eb9e13405ac256908112c744 | 71,681 |
def metadata2json(meta, force=False):
# type: (Union[ANY_Metadata_Type, Any], bool) -> Union[JSON, Any]
"""
Retrieve metadata information and generate its JSON representation.
Obtains the JSON representation of a :class:`OWS_Metadata` or :class:`pywps.app.Common.Metadata`.
Otherwise, simply return ... | 8c2d992396190b2810463e0e89360d37ae3c0270 | 71,682 |
def _get_permissions_in_policy(policy_dict, warn_unknown_perms=False):
"""
Given a set of policies for a role, return a set of all allowed permissions
Args:
policy_dict
warn_unknown_perms
Returns
tuple
set - all permissions allowed by the policies
set - all perm... | 83ec8f3ffa8103780efaebdaa5706c006b8b7e3d | 71,683 |
def get_psnr(real, generated):
"""Calculate PSNR values for the given samples of images.
Args:
real: batch of tensors representing real images.
generated : batch of tensors representing generated images.
Returns:
PSNR value for the given batch of real and generated images.
"""
psnr_value =... | ee818963e889d48e90c805fd4181abeb9cfb4c7e | 71,684 |
from typing import Iterable
from typing import Optional
from typing import Set
def fetch_all_used_taxons_map(
company_id: str,
request_formula: Iterable[str],
data_sources: Optional[Iterable[str]] = None,
include_aggregation_definition_taxons: bool = True,
) -> TaxonMap:
"""
Get taxons map bas... | 3246725777ebc073ffe20b1460c07ecac9f2b194 | 71,685 |
def im_detect(net, im, gt_boxes):
"""Detect classes in an image given object proposals.
"""
blobs, unused_im_scale_factors = _get_blobs(im, gt_boxes)
base_shape = blobs['data'].shape
blobs_rois = blobs['rois'].astype(np.float32, copy=False)
blobs_rois = blobs_rois[:, :, np.newaxis, np.newaxis]... | 57d7d41a427037fccaf301ccb1ee2d74c85b6227 | 71,687 |
def match_task(question: str, keywords: list):
"""Match question words with the keywords.
Return True and the matched word if at least one word is matched.
"""
for word in question.split(" "):
for kw in keywords:
if word == kw:
return word
return "" | 52b5f3188cd4d3faffcebf66572c3d3a40a43de8 | 71,689 |
def convert_to_millisecond(duration):
"""
Converts a ISO 8601 duration str to milliseconds.
:param duration: The ISO 8601 duration str
:return: int milliseconds
"""
duration_string = duration.replace('PT', '').upper()
seconds = 0
number_string = ''
for char in duration_string:
... | 89ca142d1d87ecc819dde83c80bc678aee662417 | 71,690 |
def smallLevenshteinBetweenLists(wordList1, wordList2):
"""This function checks the levenshtein distances between the two word lists.
It considers a match if the words of the smaller list all match with distance 0 or 1 with
a word of the longer list.
>>> smallLevenshteinBetweenLists(['bauwens', 'noella'], ['no... | c07ff75285d62cb777c32b512f016efc91020ca8 | 71,691 |
def getEnvVar(var_name):
"""
fetches an environment variable or raises an exception if not found
"""
val = getenv(var_name)
if not val:
raise Exception(f"can't find envvar {var_name}")
return val | 32679e28731d178db91317ae1fefce3d539c2333 | 71,692 |
import json
def open_json(path):
"""Open the db from JSON file previously saved at given path."""
fd = open(path, 'r')
return json.load(fd) | c0c0c4857b4582091a145a71767bc0168808593a | 71,693 |
import torch
def prep_fft_channel(x):
""" Rotates complex image dimension from channel to last position. """
x = torch.reshape(x, x.shape[:-3] + (x.shape[-3] // 2, 2) + x.shape[-2:])
return x.permute(*range(x.ndim - 3), -2, -1, -3) | ad6be1660239a87b60cf6be838caf37988ef19ca | 71,694 |
def consolidate_events(ev_list):
"""
Consolidates the busy times of multiple calenders so there is no overlap in busy events
"""
consolidated = []
for i in range(len(ev_list)-1):
ev = ev_list[i]
next = ev_list[i+1]
#If the next busy event starts before the current ev... | 612015c2200eb29c3f2303807e449da465354927 | 71,695 |
import random
def point_on_triangle(pt1, pt2, pt3):
"""
Random point on the triangle with vertices pt1, pt2 and pt3.
"""
s, t = sorted([random.random(), random.random()])
return (s * pt1[0] + (t-s)*pt2[0] + (1-t)*pt3[0],
s * pt1[1] + (t-s)*pt2[1] + (1-t)*pt3[1],
s * pt1[2] ... | 1963c2792a0a2a2fdcaa7fcbdc4a5edf22af7101 | 71,696 |
def right(m):
"""Select the right side of a mobile."""
assert is_mobile(m), "must call right on a mobile"
return m[2] | a39c254f6de39603b49a821b7df6cb3f5f6c1460 | 71,697 |
from typing import Optional
from typing import Any
def build_get_odata_multiple_pages_request(
*,
client_request_id: Optional[str] = None,
maxresults: Optional[int] = None,
timeout: Optional[int] = 30,
**kwargs: Any
) -> HttpRequest:
"""A paging operation that includes a nextLink in odata form... | af87ba898a1ef572d1025de963d9eb4be78c629f | 71,698 |
def compute_weights(trajectories_cost, weight_fonction=None):
"""
Compute normalized weights associated with each trajectory.
Inputs:
- trajectories_cost: ndarray
Array containing the cost of the trajectories
- weight_fonction: function, default=None
Function used to... | c0262ba6894ba845d17d12eb2c19be54515b334a | 71,699 |
def yaml_dump(doc, target=None, transform=None):
"""Dump to the target file. If target is None, return the
dumped yaml as a String. Otherwise return the path to the file."""
yaml = _StringYAML()
yaml.indent(mapping=2, sequence=4, offset=2)
if target is None:
return yaml.dump(doc, transform=t... | eb7c56741f40f45ee9376e0701c1375cb493fea5 | 71,700 |
from .common import CONFIG_TO_CLASS
def create_instance(config, asdict=False):
"""create machine learing model by config"""
class_name = CONFIG_TO_CLASS[config.__class__.__name__]
if asdict:
return class_name(**config.asdict())
else:
return class_name(config) | badd7e1f6edb6fbdbd2dd7a195552036335b5b4e | 71,701 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.