content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_into_tree(abbr, doc_type = 'html'):
"""
Преобразует аббревиатуру в дерево элементов
@param abbr: Аббревиатура
@type abbr: str
@param doc_type: Тип документа (xsl, html)
@type doc_type: str
@return: Tag
"""
root = Tag('', 1, doc_type)
parent = root
last = None
token = re.compile(r'([\+>])?([a-z][a-... | 5,337,600 |
def map_pao1_genes(gene_list):
"""Takes a list of PAO1 genes and returns the corresponding PA14 names."""
pa14_pao1_mapping = dict()
mapping_path = os.path.join(os.getcwd(), 'data', 'ortholuge_pa14_to_pao1_20190708.tsv')
with open(mapping_path) as mapping:
reader = csv.reader(mapping, delimiter=... | 5,337,601 |
def test_set_profile_data_empty_last_name(api_client, user):
"""Test profile data cannot be set last name is blank."""
api_client.login(username=user.username, password="test_password")
response = api_client.patch(
"/v1/users/set_profile/", {"first_name": "John", "last_name": ""},
)
assert r... | 5,337,602 |
def banner():
"""Verify banner in HTML file match expected."""
def match(path, expected_url=None, expected_base=None):
"""Assert equals and return file contents.
:param py.path.local path: Path to file to read.
:param str expected_url: Expected URL in <a href="" /> link.
:param ... | 5,337,603 |
def harvester():
"""Harvests remotely mastered metadata.
"""
pass | 5,337,604 |
def terminate_execution(
execution: t.Union[CurrentExecutionId, ExecutionId],
domain: str,
reason: str = None,
details: str = None,
child_execution_policy: ChildExecutionTerminationPolicy = None,
client: "botocore.client.BaseClient" = None,
) -> None:
"""Terminate (immediately close) a workf... | 5,337,605 |
def rerank(x2ys, x2cnt, x2xs, width, n_trans):
"""Re-rank word translations by computing CPE scores.
See paper for details about the CPE method."""
x2ys_cpe = dict()
for x, ys in tqdm(x2ys.items()):
cntx = x2cnt[x]
y_scores = []
for y, cnty in sorted(ys.items(), key=operator.ite... | 5,337,606 |
def ParallelTempering(num_sweeps=10000, num_replicas=10,
max_iter=None, max_time=None, convergence=3):
"""Parallel tempering workflow generator.
Args:
num_sweeps (int, optional):
Number of sweeps in the fixed temperature sampling.
num_replicas (int, optional):... | 5,337,607 |
def get_document_info(file):
"""
Scrape document information using ChemDataExtractor Scrapers
:param file: file path to target article
:type file: str
:return: list of dicts containing the document information
"""
if file.endswith('.html'):
file_type = 'html'
elif file.endswith(... | 5,337,608 |
def qlog(q):
"""
Compute logarithm of a unit quaternion (unit norm is important here).
Let q = [a, qv], where a is the scalar part and qv is the vector part.
qv = sin(phi/2)*nv, where nv is a unit vector. Then
ln(q) = ln(||q||) + qv / ||qv|| * arccos(a / ||q||)
Therefore for a unit quaternion, t... | 5,337,609 |
def trx():
"""Response from ADN about current transaction APPROVED/DECLINED and showing Receipt of transaction"""
trx = web.trxs[-1]
trx.shoppingCartUuid = request.args.get('shoppingCartUuid', default = "", type = str)
trx.mediaType = request.args.get('mediaType', default = "", type = str)
trx.corre... | 5,337,610 |
def test_return_topological_neighbors_hexagonal():
"""Test the topological neighbors of a neuron for hexagonal grid type."""
som = SOM(random_state=RANDOM_STATE, gridtype='hexagonal').fit(X)
assert set(som._return_topological_neighbors(0, 0)).issubset(set([(1, 0), (0, 1)]))
assert set(som._return_topolo... | 5,337,611 |
def get_counts_by_domain(df):
"""
Parameters:
df (pandas.Dataframe) - form of `get_counts_df` output
Returns:
pandas.Dataframe
"""
columns = ['study', 'study_label', 'domain_code', 'domain_label']
df2 = df.groupby(columns, as_index=False)[["count", "subjects"]].max()
retur... | 5,337,612 |
def raise_value_exception(method_name, expected_value_range, val):
"""Utility function for raising value exceptions."""
raise ValueError('Method \'' + method_name + '\' expects a value in range of{' + str(expected_value_range) + '} but got {' + str(val) + '} instead!') | 5,337,613 |
def batch_cosine_similarity(x1, x2):
""" https://en.wikipedia.org/wiki/Cosine_similarity """
mul = np.multiply(x1, x2)
s = np.sum(mul, axis=1)
return s | 5,337,614 |
def plot(ax, x, y):
"""Plot """
return ax._plot(x, y) | 5,337,615 |
def plot_character(character_name, movie_name, character_sentiments):
"""
This functions takes the name of the character, and plot their sentiment in a ring chart
Parameters:
character_name: str: The name of the character who emotions are to be displayed\
movie_name: str: the movie which the char... | 5,337,616 |
async def test_list_photos(
client: _TestClient, mocker: MockFixture, token: MockFixture
) -> None:
"""Should return OK and a valid json body."""
ID = "290e70d5-0933-4af0-bb53-1d705ba7eb95"
mocker.patch(
"photo_service.adapters.photos_adapter.PhotosAdapter.get_all_photos",
return_value=[... | 5,337,617 |
def concatenatePDFs(filelist, pdfname, pdftk='pdftk', gs='gs', cleanup=False,
quiet=False):
"""
Takes a list or a string list of PDF filenames (space-delimited), and an
output name, and concatenates them.
It first tries pdftk (better quality), and if that fails, it tries
ghostscr... | 5,337,618 |
def get_module_offset(
process_id: int,
process_name: str
) -> Address:
"""Returns an Adress with the base offset of the process.
Args:
process_id (int): PID
process_name (str): Name of the process. Case does not matter.
Returns:
Address: Adress with the base offset of the ... | 5,337,619 |
def sequence_to_header(sequence: Sequence[Bytes]) -> Header:
"""
Build a Header object from a sequence of bytes. The sequence should be
containing exactly 15 byte sequences.
Parameters
----------
sequence :
The sequence of bytes which is supposed to form the Header
object.
... | 5,337,620 |
def cache_tree_children(queryset):
"""
For all items in the queryset, set the '_cached_children' attribute to a
list. This attribute is in turn used by the 'get_children' method on the
item, which would otherwise (if '_cached_children' is not set) cause a
database query.
The queryset must be or... | 5,337,621 |
def makeASdef(isd_id, as_id_tail, label, public_ip, is_core=False, is_ap=False):
""" Helper for readable ASdef declaration """
return ASdef(isd_id, _expand_as_id(as_id_tail), label, public_ip, is_core, is_ap) | 5,337,622 |
def _get_fs_subjid(subject_id, subjects_dir=None):
"""
Gets fsaverage version `subject_id`, fetching if required
Parameters
----------
subject_id : str
FreeSurfer subject ID
subjects_dir : str, optional
Path to FreeSurfer subject directory. If not set, will inherit from
... | 5,337,623 |
def EnableTrt(mod, params=None, trt_version=None):
"""Converts the "main" function in the module into one that can be executed using
TensorRT. If any of the operators are not supported by the TensorRT
conversion, the unmodified program will be returned instead.
Parameters
----------
mod: Module... | 5,337,624 |
def _setup_cuda_fft_resample(n_jobs, W, new_len):
"""Set up CUDA FFT resampling.
Parameters
----------
n_jobs : int | str
If n_jobs == 'cuda', the function will attempt to set up for CUDA
FFT resampling.
W : array
The filtering function to be used during resampling.
... | 5,337,625 |
def sentensize(text):
"""Break a text into sentences.
Args:
text (str): A text containing sentence(s).
Returns:
list of str: A list of sentences.
"""
return nltk.tokenize.sent_tokenize(text) | 5,337,626 |
def tokenize(texts, context_length=77):
"""
Returns the tokenized representation of given input string(s)
Parameters
----------
texts : Union[str, List[str]]
An input string or a list of input strings to tokenize
context_length : int
The context length to use; all CLIP models use... | 5,337,627 |
def _int64_feature_list(values):
"""Wrapper for inserting an int64 FeatureList into a SequenceExample proto,
e.g, sentence in list of ints
"""
return tf.train.FeatureList(feature=[_int64_feature(v) for v in values]) | 5,337,628 |
def read_relative_pose(object_frame_data: dict) -> tf.Transform:
"""
Read the pose of an object relative to the camera, from the frame data.
For reasons (known only to the developer), these poses are in OpenCV convention.
So x is right, y is down, z is forward.
Scale is still 1cm, so we divide by 10... | 5,337,629 |
def upsert_task(task_uuid: str, task: Task) -> Task:
"""Upsert a task.
It is used to create a task in the database if it does not already exists,
else it is used to update the existing one.
Args:
task_uuid:
The uuid of the task to upsert.
task:
The task data.
Returns:
... | 5,337,630 |
def shuffle_entries(x, entry_cls, config=None, value_type=sgf2n, reverse=False, perm_size=None):
""" Shuffle a list of ORAM entries.
Randomly permutes the first "perm_size" entries, leaving the rest (empty
entry padding) in the same position. """
n = len(x)
l = len(x[0])
if n & (n-1) !=... | 5,337,631 |
def file(input_file):
"""Import colorscheme from json file."""
theme_name = ".".join((input_file, "json"))
user_theme_file = os.path.join(CONF_DIR, "colorschemes", theme_name)
theme_file = os.path.join(MODULE_DIR, "colorschemes", theme_name)
util.create_dir(os.path.dirname(user_theme_file))
# ... | 5,337,632 |
def entities(request):
"""Get entities for the specified project, locale and paths."""
try:
project = request.GET['project']
locale = request.GET['locale']
paths = json.loads(request.GET['paths'])
except MultiValueDictKeyError as e:
log.error(str(e))
return HttpRespon... | 5,337,633 |
def info(request, token):
"""
Return the HireFire json data needed to scale worker dynos
"""
if not settings.HIREFIRE_TOKEN:
return HttpResponseBadRequest(
"Hirefire not configured. Set the HIREFIRE_TOKEN environment variable on the app to use Hirefire for dyno scaling"
)
... | 5,337,634 |
def get_domain_from_url(url):
"""get domain from url"""
domain=''
# url is http://a.b.com/ads/asds
if re.search(r'://.*?/',url):
try:
domain = url.split('//', 1)[1].split('/', 1)[0]
except IndexError, e:
LOGGER.warn('Get domain error,%s,%s' % (url, e))
... | 5,337,635 |
def render_response(body=None, status=None, headers=None):
"""生成WSGI返回消息"""
headers = [] if headers is None else list(headers)
if body is None:
body = ''
status = status or (204, 'No Content')
else:
body = json.dumps(body, encoding='utf-8')
headers.append(('Content-Type'... | 5,337,636 |
def sanic_client():
"""Fixture for using sanic async HTTP server rather than a asgi async server used by test client"""
env = os.environ.copy()
env["SANIC_PORT"] = str(SERVER_PORT)
args = ["ddtrace-run", "python", RUN_SERVER_PY]
subp = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess... | 5,337,637 |
def tests(request):
"""Print a list of tests."""
test_list = Test.objects.all()
tag_list = Tag.objects.all().order_by(u'name')
# check if we need to filter the test list based on tags
# defaults to empty list because we're always passing the list to the template
tags = request.GET.get(u'tag', [... | 5,337,638 |
def nashpobench_benchmark(params):
"""
The underlying tabulated blackbox does not have an `elapsed_time_attr`,
but only a `time_this_resource_attr`.
"""
config_space = dict(
CONFIGURATION_SPACE,
epochs=params['max_resource_level'],
dataset_name=params['dataset_name'])
re... | 5,337,639 |
def test_application():
"""Test application running"""
app = use_app()
print(app) # __repr__ without app
app.create()
wrong = 'glfw' if app.backend_name.lower() != 'glfw' else 'pyqt5'
assert_raises(RuntimeError, use_app, wrong)
app.process_events()
print(app) # test __repr__
asser... | 5,337,640 |
def horizontal_plate_natual_convection_2(Gr, Pr):
"""hot side downward, or cold side upward """
""" 1e5 < Ra < 1e10 """
Ra = Gr * Pr
return 0.27 * Ra**0.25 | 5,337,641 |
def run_test_case(test_case: TestCase) -> Tuple[Simulation, Scenario, ExtThread, SimulationID]:
"""
This method starts the actual simulation in a separate thread.
Additionally it already calculates and attaches all information that is need by this node and the separate
thread before calling _start_simul... | 5,337,642 |
def test_pre_commit_hook_sync_nbstripout(
tmpdir,
cwd_tmpdir,
tmp_repo,
jupytext_repo_root,
jupytext_repo_rev,
notebook_with_outputs,
):
"""Here we sync the ipynb notebook with a Markdown file and also apply nbstripout."""
pre_commit_config_yaml = f"""
repos:
- repo: {jupytext_repo_root}... | 5,337,643 |
def translate_value_data(
new_values: list,
options: dict,
parent_value: str,
translate_dict: typing.Optional[dict],
values: list,
):
"""Translates value data if necessary and checks if it falls within the Castor optiongroup"""
for value in values:
if pd.isnull(parent_value):
... | 5,337,644 |
def makeVocabFromText(
filelist=None,
max_size=10*10000,
least_freq=2,
trunc_len=100,
filter_len=0,
print_log=None,
vocab_file=None,
encoding_format='utf-8',
lowercase = True):
""" the core of this function... | 5,337,645 |
def elimV(N, a, b, c, p, uu, alpha, beta):
"""
elimV. Called by LPSteps
Double sweep elimination along the vertical direction, i.e. column-wise
Inputs NxN arrays or scalars
"""
"""
/* initial condition, everything is going to be zero at the edge */
"""
alpha[0,:] = 0.0
beta[0,:] ... | 5,337,646 |
def _run_agent(
agent_dir: Union[PathLike, str], stop_event: Event, log_level: Optional[str] = None
) -> None:
"""
Load and run agent in a dedicated process.
:param agent_dir: agent configuration directory
:param stop_event: multithreading Event to stop agent run.
:param log_level: debug level ... | 5,337,647 |
def import_supplemental(file_path):
"""Get data from a supplemental file"""
data = sio.loadmat(file_path)
data['move'] = np.squeeze(data['move'])
data['rep'] = np.squeeze(data['rep'])
data['emg_time'] = np.squeeze(data['emg_time'])
return data | 5,337,648 |
def _unpickle_injected_object(base_class, mixin_class, class_name=None):
"""
Callable for the pickler to unpickle objects of a dynamically created class
based on the InjectableMixin. It creates the base object from the original
base class and re-injects the mixin class when unpickling an object.
:p... | 5,337,649 |
def parse_endfblib(libdir):
"""Parse ENDF/B library
Parametres:
-----------
libdir : str
directory with ENDFB file structure"""
filepaths = []
nuclidnames = []
endf_dir = Path(libdir)
neutron_files = tuple((endf_dir / "neutrons").glob("*endf"))
for n in neutron_files... | 5,337,650 |
def get_parser():
"""Get parser object."""
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
parser = ArgumentParser(
description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter
)
parser.add_argument(
"-f",
"--file",
dest="filename",
h... | 5,337,651 |
def build_val_col_list(tableName):
"""Build and return a schema to use for the sample data."""
statement = "( SELECT column_name, data_type, case when data_type='NUMBER' THEN NVL(DATA_PRECISION,38) + DATA_SCALE ELSE DATA_LENGTH END AS ORACLE_LENGTH FROM dba_tab_columns WHERE table_name = '" + tableName + "' or... | 5,337,652 |
def save_image(user, filename, image_tif, process, latency, size, hist):
"""
Function that saves image to Mongo database
Args:
user: username
filename: desired file name in database
image_tif: tiff image in byte format
process: processing algorithm applied to image
l... | 5,337,653 |
def run_simulation_with_params(
sim_params, replicate, repeats=10, should_perform_gwas=True):
"""Runs simulation with given params and returns result object.
"""
try:
simulation_result = run_simulation(
simulation_params=sim_params)
except Exception as e:
print si... | 5,337,654 |
def hsl_to_rgb(hsl):
"""Convert hsl colorspace values to RGB."""
# Convert hsl to 0-1 ranges.
h = hsl[0] / 359.
s = hsl[1] / 100.
l = hsl[2] / 100.
hsl = (h, s, l)
# returns numbers between 0 and 1
tmp = colorsys.hls_to_rgb(h, s, l)
# convert to 0 to 255
r = int(round(tmp[0] * 25... | 5,337,655 |
def init_celery(app=None):
"""
Initialize celery.
"""
app = app or create_app(os.environ.get('APP_MODE'))
celery.conf.update(app.config.get("CELERY", {}))
class ContextTask(celery.Task):
"""
Make celery tasks work with Flask app context
"""
def __call__(self, *ar... | 5,337,656 |
async def test_filterfalse_matches_itertools_filterfalse(
arange: ty.Type[ty.AsyncIterator[int]], stop: int
):
"""Ensure that our async filterfalse implementation follows the standard
implementation.
"""
async def _pair(x):
return (x % 2) == 0
target = list(itertools.filterfalse(lambd... | 5,337,657 |
def extract_buffer_info(mod, param_dict):
"""
This function is to read the tvm.IRModule that
contains Relay to TIR compiled IRModule. Thereafter,
this will extract the buffer information as the shape
and constant data (if any).
Parameters
----------
mod : tvm.IRModule
The NPU TI... | 5,337,658 |
def reproject_as_needed(src, tilespec, resampling='nearest'):
""" Return a ``rasterio`` dataset, reprojected if needed
Returns src dataset if reprojection unncessary. Otherwise returns an in
memory ``rasterio`` dataset. Reprojection will snap the bounding
coordinates of the source dataset to align with... | 5,337,659 |
def find_external_nodes(digraph):
"""Return a set of external nodes in a directed graph.
External nodes are node that are referenced as a dependency not defined as
a key in the graph dictionary.
"""
external_nodes = set()
for ni in digraph:
for nj in digraph[ni]:
if nj not i... | 5,337,660 |
def strip(val):
"""
Strip val, which may be str or iterable of str.
For str input, returns stripped string, and for iterable input,
returns list of str values without empty str (after strip) values.
"""
if isinstance(val, six.string_types):
return val.strip()
try:
return lis... | 5,337,661 |
def warn_deprecated(obj, msg):
"""
Issue the warning message `msg`.
"""
warnings.warn(msg, category=DeprecationWarning, stacklevel=2) | 5,337,662 |
def test_single_shape_properties(attribute):
"""Test creating single shape with properties"""
shape = (4, 2)
np.random.seed(0)
data = 20 * np.random.random(shape)
layer_kwargs = {f'{attribute}_color': 'red'}
layer = Shapes(data, **layer_kwargs)
layer_color = getattr(layer, f'{attribute}_colo... | 5,337,663 |
def export_gene_exons(adapter, hgnc_id, build="37"):
"""Export all exons from one gene
Args:
adapter(scout.adapter.MongoAdapter)
hgnc_id(int): hgnc ID of a gene
build(str): "37" or "38"
Yields:
printlines(str): formatted like this: Chrom\tStart\tEnd\tExonId\tTranscripts\tHg... | 5,337,664 |
def set_manager_hook(file_manager):
"""Saves a reference to the file_manager.py."""
global FMANAGER
FMANAGER = file_manager | 5,337,665 |
def durations_histo(filename: str, v1_2_1, v1_5_2):
"""Generate all the figures for the histograms.
Returns a dictionary of dict with dict containing the full filename.
"""
from matplotlib.backends.backend_pdf import PdfPages
ensure_path(os.path.dirname(filename))
filenames = dict()
filename... | 5,337,666 |
def construct_area_cube(var_name, area_data, global_atts, dim_coords):
"""Construct the new area cube """
dim_coords_list = []
for i, coord in enumerate(dim_coords):
dim_coords_list.append((coord, i))
if var_name == 'areacello':
long_name = 'Grid-Cell Area for Ocean Variables'
else... | 5,337,667 |
def _switch_obs_2_time_dim(ds):
"""Function to create a single time variable that is the midpoint of the
ObsPack averaging interval, and make it the xarray coordinate. """
# Get the midpoint of the average pulled from the model:
midpoint = pd.to_datetime(ds.averaging_interval_start.data) + \
... | 5,337,668 |
def mqtt_cb_on_message(client, userdata, msg):
"""Do the callback for when a message is received without it own callback."""
print("misc_message_cb: unexpected message:",
msg.topic, str(msg.payload), file=sys.stderr) | 5,337,669 |
def bitfield_v(val, fields, col=15):
"""
return a string of bit field components formatted vertically
val: the value to be split into bit fields
fields: a tuple of (name, output_function, (bit_hi, bit_lo)) tuples
"""
fmt = '%%-%ds: %%s' % col
s = []
for (name, func, field) in fields:
s.append(fmt % ... | 5,337,670 |
def split_housenumber_line(line: str) -> Tuple[str, bool, bool, str, Tuple[int, str], str,
Tuple[int, str], Iterable[str], Tuple[int, str]]:
"""
Augment TSV Overpass house numbers result lines to aid sorting.
It prepends two bools to indicate whether an entry ... | 5,337,671 |
def readAsync(tagPaths, callback):
"""Asynchronously reads the value of the Tags at the given paths.
You must provide a python callback function that can process the
read results.
Args:
tagPaths (list[str]): A List of Tag paths to read from. If no
property is specified in the path,... | 5,337,672 |
def parse_lambda_config(params, name):
"""
Parse the configuration of lambda coefficient (for scheduling).
x = "3" # lambda will be a constant equal to x
x = "0:1,1000:0" # lambda will start from 1 and linearly decrease to 0 during the first 1000 iterations
x = "0:0,1000:0,2... | 5,337,673 |
def tau_polinomyal_coefficients(z):
"""
Coefficients (z-dependent) for the log(tau) formula from
Raiteri C.M., Villata M. & Navarro J.F., 1996, A&A 315, 105-115
"""
log_z = math.log10(z)
log_z_2 = log_z ** 2
a0 = 10.13 + 0.07547 * log_z - 0.008084 * log_z_2
a1 = -4.424 - 0.7939 * log_z... | 5,337,674 |
def test_stop_after_max_trial_reached():
"""Check that all results are registered before exception are raised"""
count = 10
max_trials = 1
workers = 2
runner = new_runner(0.1, n_workers=workers)
runner.max_broken = 2
runner.max_trials_per_worker = max_trials
client = runner.client
... | 5,337,675 |
def register( # lgtm[py/similar-function]
fn: callbacks.ResourceHandlerFn,
*,
id: Optional[str] = None,
errors: Optional[errors_.ErrorsMode] = None,
timeout: Optional[float] = None,
retries: Optional[int] = None,
backoff: Optional[float] = None,
cooldown:... | 5,337,676 |
def release_notes(c, version=None, username=None, password=None, write=False):
"""Generates release notes based on issues in the issue tracker.
Args:
version: Generate release notes for this version. If not given,
generated them for the current version.
username: GitHub usern... | 5,337,677 |
def pd_read_csv_using_metadata(filepath_or_buffer, table_metadata, ignore_partitions=False, *args, **kwargs):
"""
Use pandas to read a csv imposing the datatypes specified in the table_metadata
Passes through kwargs to pandas.read_csv
If ignore_partitions=True, assume that partitions are not columns i... | 5,337,678 |
def read_parfile_dirs_props(filename):
"""Reads BRUKER parfile-dirs.prop file to in order to get correct mapping
of the topspin parameters.
Args:
filename: input Bruker parfile-dirs.prop file
Returns:
A dict mapping parameter classes to the their respective directory.
E.g. ... | 5,337,679 |
def get_all_playlist_items(playlist_id, yt_client):
"""
Get a list of video ids of videos currently in playlist
"""
return yt_client.get_playlist_items(playlist_id) | 5,337,680 |
def test_check_file_many_conflicts(
capsys, tmp_path, shared_datadir, source_pipfile_dirname
): # type: (Any, Path, Path, str) -> None
"""
many conflicts, return code should be one
"""
pipfile_dir = shared_datadir / source_pipfile_dirname
for filename in ("Pipfile", "Pipfile.lock", "setup.py"):... | 5,337,681 |
def generator(samples, is_validation=False, correction=0.15, batch_size=32):
"""Generates batches of training features and labels.
Args
samples: driving log file records
"""
# Fetch corresponding images, and build a generator
num_samples = len(samples)
while 1:
samples = sklearn... | 5,337,682 |
def plot_best_laps(timings):
"""Plot each driver's best lap in as a bar chart and output a file.
`timings` : dict
Return value of `api.get_best_laps`
"""
race, sn = timings['race'], timings['season']
drivers = [x['Driver'] for x in timings['data']]
times = [lap_time_to_seconds(x['Time']... | 5,337,683 |
def patch_callables(callables: List[str], patch_func: PatchFunction) -> None:
"""Patch the given list of callables.
Parameters
----------
callables : List[str]
Patch all of these callables (functions or methods).
patch_func : PatchFunction
Called on every callable to patch it.
... | 5,337,684 |
def test_particles_ja011_particles_ja011_v(mode, save_output, output_format):
"""
TEST :3.9.1 The Particle Schema Component [ check length of element
information items ] : Particle Derivation OK (elt:Any) element R
drived by restriction from wildcard (any) B : B's namespace=##any, R's
targetNamespac... | 5,337,685 |
def _get_last_measurement(object_id: int):
"""
Get the last measurement of object with given ID.
Args:
object_id (int): Object ID whose last measurement to look for.
Returns:
(GamMeasurement): The last measurement of the object, or None if it doesn't exist.
"""
last_mea = (GamM... | 5,337,686 |
def get_library_isotopes(acelib_path):
"""
Returns the isotopes in the cross section library
Parameters
----------
acelib_path : str
Path to the cross section library
(i.e. '/home/luke/xsdata/endfb7/sss_endfb7u.xsdata')
Returns
-------
iso_array: array
array of ... | 5,337,687 |
def read_wires(data: str) -> Mapping[int, Wire]:
"""Read the wiring information from data."""
wires = {}
for line in data.splitlines():
wire_name, wire = get_wire(line)
wires[wire_name] = wire
return wires | 5,337,688 |
def test_disk_dataset_get_shape_single_shard():
"""Test that get_shape works for disk dataset."""
num_datapoints = 100
num_features = 10
num_tasks = 10
# Generate data
X = np.random.rand(num_datapoints, num_features)
y = np.random.randint(2, size=(num_datapoints, num_tasks))
w = np.random.randint(2, siz... | 5,337,689 |
def back_ease_out(p):
"""Modeled after overshooting cubic y = 1-((1-x)^3-(1-x)*sin((1-x)*pi))"""
f = 1 - p
return 1 - (f * f * f - f * sin(f * pi)) | 5,337,690 |
def configure_estimator_params(init_args, train_args):
"""Validates the initialization and training arguments and constructs a
`params` dictionary for creating a TensorFlow Estimator object."""
params = {}
init_val = ArgumentsValidator(init_args, "Initialization arguments")
with init_val:
params["rm_dir... | 5,337,691 |
def bit_lshift(bin_name, bit_offset, bit_size, shift, policy=None):
"""Creates a bit_lshift_operation to be used with operate or operate_ordered.
Server left shifts bitmap starting at bit_offset for bit_size by shift bits.
No value is returned.
Args:
bin_name (str): The name of the bin contain... | 5,337,692 |
def compute_ccas(sigma_xx, sigma_xy, sigma_yx, sigma_yy, epsilon,
verbose=True):
"""Main cca computation function, takes in variances and crossvariances.
This function takes in the covariances and cross covariances of X, Y,
preprocesses them (removing small magnitudes) and outputs the raw results... | 5,337,693 |
def vcf_entry_match(vcf_id, start, stop, target_vcf):
"""Returns whether the requested update entry matches the target VCF entry"""
pass | 5,337,694 |
def generate_samples(
segment_mask: np.ndarray, num_of_samples: int = 64, p: float = 0.5
) -> np.ndarray:
"""Generate samples by randomly selecting a subset of the segments.
Parameters
----------
segment_mask : np.ndarray
The mask generated by `create_segments()`: An array of shape (image_w... | 5,337,695 |
def get_mix_bandpassed(bp_list, comp, param_dict_file=None,bandpass_shifts=None,
ccor_cen_nus=None, ccor_beams=None, ccor_exps = None,
normalize_cib=True,param_dict_override=None,bandpass_exps=None,nus_ghz=None,btrans=None,
dust_beta_para... | 5,337,696 |
def try_again() -> None:
""" Prompts the user to retry some process or exit program """
while True:
value = input("Enter 't' to try again or 'e' to exit. ").lower()
if value == 't': return
if value == 'e': sys.exit(0) | 5,337,697 |
def partition(data, label_name, ratio):
""" Partitions data set according to a provided ratio.
params:
data - The data set in a pandas data frame
label_name - the name of the collumn in the data set that contains the labels
ratio - the training/total data ratio
returns:
... | 5,337,698 |
def find_background2(data, mask, channels, apertureset_lst,
method='poly', scale='linear', scan_step=200,
xorder=2, yorder=2, maxiter=5, upper_clip=3, lower_clip=3,
extend=True, display=True, fig_file=None, reg_file=None):
"""Subtract the background for an input FITS image.
Args:
... | 5,337,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.