content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def atan2(y, x) -> Expression[float]:
"""
Calculates the arc tangent of a given coordinate.
"""
return _binary_op("atan2", y, x) | b3ef45926fd63487c9b4cc5df3ab3a938ed87598 | 3,610,700 |
def parse_header(header):
"""Read header information from 2 bytes:
- 1 byte for model id
- 4 bits for metric
- 4 bits for quality param
"""
model_id, code = header
quality = (code & 0x0F) + 1
metric = code >> 4
return (
"YUV",
inverse_dict(metric_ids)[metric],
... | e0d85ef9424f253ba18139003e421f58562aa96a | 3,610,701 |
import os
def upload_generate_report():
"""Upload a txt file and display a query report"""
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
... | 6d22fab885202bab1fe7ee6aceb183104135efa6 | 3,610,702 |
def piece_size(file_size):
"""
Based on the size of the file, we decide the size of the pieces.
:param file_size: represents size of the file in MB.
"""
# print 'Size {0} MB'.format(file_size)
if file_size >= 1000: # more than 1 gb
return 2 ** 19
elif file_size >= 500 and file_size ... | 8b48e98a22035f594c2582401cf4145acbf4d680 | 3,610,703 |
import subprocess
def execute(command):
"""
Run local image in a container
Arguments
---------
command: string of command to execute
"""
command = f'"{command}"'
process = subprocess.run(
f"docker exec --workdir $maple_target $maple_container bash -c {command}",
shell=... | 9e4a871447e0c109d14f6e30f6ec2a26d9034416 | 3,610,704 |
import random
def create_mock_datapath(num_ports):
"""Mock a datapath by creating mocked datapath ports."""
dp_id = random.randint(1, 5000)
dp_name = mock.PropertyMock(return_value='datapath')
def table_by_id(i):
table = mock.Mock()
table_name = mock.PropertyMock(return_value='table'... | f9c1821d02e91f5fdfcc3b6b45f71df3da8c7746 | 3,610,705 |
import curses
def get_gold():
"""
Return the gilded symbol.
"""
symbol = u'\u272A' if config.unicode else '*'
attr = curses.A_BOLD | Color.YELLOW
return symbol, attr | 1d0ebde3347e4dc48b83386482b22be63864a025 | 3,610,706 |
def _CharTraits_get_hdf5_memory_type():
"""_CharTraits_get_hdf5_memory_type() -> hid_t"""
return _RMF_HDF5._CharTraits_get_hdf5_memory_type() | c7467ff63725ad8e1f276abb1bf6356bbcb1d5d1 | 3,610,707 |
def operator_unassigned_ticket(request, structure_slug,
structure, office_employee):
"""
Returns all unassigned tickets managed by operator
:type structure_slug: String
:type structure: OrganizationalStructure (from @is_operator)
:type office_employee: OrganizationalS... | d272b2f81629ab8aa6b9d6671cf2cf238b1873fc | 3,610,708 |
def raw_resolution(splitter=False):
"""
Round a (width, height) tuple up to the nearest multiple of 32 horizontally
and 16 vertically (as this is what the Pi's camera module does for
unencoded output).
Originally Written by Dave Jones as part of PiCamera
"""
width, height = RESOLUTION
i... | 4579ee31fafe643ac1a6e8a8ac072bd50932c8b8 | 3,610,709 |
import math
def odd_improvement(lst):
"""Calculates the improvement of odds compared to their base values. The higher above 0, the more the odds
improved from base-value. The lower under 0, the more the odds deteriorated. Used
https://en.wikipedia.org/wiki/Logit as a source for this formula. """
base... | 4f8607d452fc96b57c9573ed0b07bd5a38791876 | 3,610,710 |
def next_named_type(*args):
"""
next_named_type(ti, name, ntf_flags) -> char const *
Enumerate types. Returns mangled names. Never returns anonymous types.
To include it, enumerate types by ordinals.
@param ti (C++: const til_t *)
@param name (C++: const char *)
@param ntf_flags (C++: int)
"""
... | 5fbd4b059c4dbe57e86011f68ea587ff4bff0151 | 3,610,711 |
async def read_role_by_id(
role_id: UUID,
*,
uow: IUnitOfWork = Depends(get_uow),
current_user: models.User = Depends(get_current_active_admin),
) -> models.Role:
"""Gets a specific role by their unique ID."""
role = uow.role.get(role_id)
if not role:
raise HTTPException(
... | e2b82c240bbe5e34b1393d807e7d41884bc44c41 | 3,610,712 |
import socket
def my_name():
"""Returns the name of this BiBli"""
# start with the database
name = get_kv("name")
# fall back to the hostname
if not name:
name = socket.gethostname()
if "." in name:
name = name[:name.index(".")]
return name | a1f9ebb80ea250ecbc08fda38b27c51f5366fe78 | 3,610,713 |
def balanced_bst(sorted_list):
"""Return balanced BST constructed from sorted list."""
return balanced_bst_rec(sorted_list, 0, len(sorted_list)) | f87c4402abbaf9f01cb8b2a340cfe21fa6e66820 | 3,610,714 |
def sql_query_tbr_create_table_dummy() -> TableDummySQL:
"""
returns table tbr create statement, dummy data insertion, and dummy data.
The dummy data is not constructed correctly, all are equal to -1 for
clarity. Message_id = -1 also ensures that first message_id will be set to 0.
Example where the... | 04e25404ada5b6e83e1e706387eb240403280418 | 3,610,715 |
from pixell import curvedsky
import healpy as hp
def enmap_from_healpix(hp_map, shape, wcs, ncomp=1, unit=1, lmax=0,
rot="gal,equ", first=0, is_alm=False, return_alm=False, f_ell=None):
"""Convert a healpix map to an ndmap using harmonic space reprojection.
The resulting map will be band-limited. Bright sou... | 6bbc24db343de6ea843e3b183041a95fc4839f8c | 3,610,716 |
def nearest(items, pivot):
"""Find nearest value in array, including datetimes
Args
----
items: iterable
List of values from which to find nearest value to `pivot`
pivot: int or float
Value to find nearest of in `items`
Returns
-------
nearest: int or float
Valu... | 0f8766e5680b3b271876a80055b99312bde8366f | 3,610,717 |
def exclusively(f):
"""
Decorate a function to make it thread-safe by serializing invocations
using a per-instance lock.
"""
@wraps(f)
def exclusively_f(self, *a, **kw):
with self._lock:
return f(self, *a, **kw)
return exclusively_f | 58da6cd8822375f992ee33352310a01cf2def0e5 | 3,610,718 |
def _read_header(file_object):
"""Get the entire header from a file, and return as dictionary"""
file_object.seek(0)
if _header_read_one_parameter(file_object) != "HEADER_START":
file_object.seek(0)
raise ValueError("Missing HEADER_START")
expecting = None
header = {}
while True:... | c2596c7a09bc5c9c1a4e2e7ffe6767951166f297 | 3,610,719 |
def _create_data_table(
source: ColumnDataSource, schema: ProcSchema, legend_col: str = None
):
"""Return DataTable widget for source."""
column_names = [
schema.user_name,
schema.user_id,
schema.logon_id,
schema.process_id,
schema.process_name,
schema.cmd_lin... | 2c84211ed6d4ad3fb6c64bb7c6aeccb0e4d85695 | 3,610,720 |
def x_integral(a, b, c, x):
"""
function involved in computing the a_matrix (Rayleigh Ritz approx of the spectrum)
@param a:
@param b:
@param c:
@param x:
@return: x_integral
"""
a_conj = np.conj(a)
# helper variables to tidy up function
k_0 = a * a_conj
k_1 = np.sqrt((k... | e224188c62ad708b4afcd38e2fabde44d75f4a9b | 3,610,721 |
def test() -> int:
"""
Testing that connection can be established
:return: int
"""
try:
connection = setup_connection()
setup.test()
cursor = connection.cursor()
# Print PostgreSQL Connection properties
print(connection.get_dsn_parameters(), "\n")
# P... | 65354917692311bfabe5822dd971be09c249c77d | 3,610,722 |
def next_line_same_block(line, *args):
""":type line: FrekiLine"""
next_line = line.doc.get_line(line.lineno+1)
return same_block(line, next_line) | 1febf16717e1244d8cb293652645a7b7f238d782 | 3,610,723 |
import functools
def inspur_driver_debug_trace(f):
"""Log the method entrance and exit including active backend name.
This should only be used on Share_Driver class methods. It depends on
having a 'self' argument that is a AS13000_Driver.
"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
... | b51a7bc38821712f2fe10917fddedcbe00299391 | 3,610,724 |
def make_hash(hash_type="hashids") -> Hashids:
"""Factory function, can make different encoders in the future if needed"""
def make_hashid() -> Hashids:
"""Build a Hashid instance based on Django's settings.py configuration"""
try:
config = settings.PROXYID["hashids"]
sa... | 7c58cc502c24bea3a7674b34f2baeeb0ec2e9846 | 3,610,725 |
def graph_from_polygon(polygon, network_type='all_private', simplify=True,
retain_all=False, truncate_by_edge=False, name='unnamed',
timeout=180, memory=None, date="",
max_query_area_size=50*1000*50*1000,
clean_periphery=True, infrastructure='way["highway"]'):
"""
Create a networkx gra... | cec8734c979e29cd5f98aebc3b30b2de686841a5 | 3,610,726 |
def cast_op(x, dtype):
"""The operation takes input tensor `x` and casts it to the output with `dtype`
Args:
x (oneflow.Tensor): A Tensor
dtype (flow.dtype): Data type of the output tensor
Returns:
oneflow.Tensor: A Tensor with specific dtype.
For example:
.. code-block::... | 16f72392d88953a7a192591dbbb815688c756681 | 3,610,727 |
def decode(model_output: np.ndarray, labels: dict) -> str:
"""Decodes the integer encoded results from inference into a string.
Args:
model_output: Results from running inference.
labels: Dictionary of labels keyed on the classification index.
Returns:
Decoded string.
"""
t... | 009df297ab525ce02ec03e67e1ce30ca7e88b9cf | 3,610,728 |
def CODE(string):
"""
Returns the numeric Unicode map value of the first character in the string provided.
Same as `ord(string[0])`.
>>> CODE("A")
65
>>> CODE("!")
33
>>> CODE("!A")
33
"""
return ord(string[0]) | 0f680fe1e45156c00d0a5839e24f1619a456773f | 3,610,729 |
import os
import sys
def lookupExeFolder():
"""Returns executable folder path"""
if frozen:
exeFolder = (
# targetdir/Bitmessage.app/Contents/MacOS/Bitmessage
os.path.dirname(sys.executable).split(os.path.sep)[0] + os.path.sep
if frozen == "macosx_app" else
... | 9de03777522434ef95f23bcee335d9f1c833b58c | 3,610,730 |
def expected_weighted(da, weights, dim, skipna, operation):
"""
Generate expected result using ``*`` and ``sum``. This is checked against
the result of da.weighted which uses ``dot``
"""
weighted_sum = (da * weights).sum(dim=dim, skipna=skipna)
if operation == "sum":
return weighted_su... | 5d3518de9bd52407cdcf140bd1c43dd5d78f9c37 | 3,610,731 |
def matching(strategies):
"""Returns the number of strategy1's result.
Parameters
----------
strategies : list of str
Names of used strategies.
matching_number : int
Number of matches.
Returns
----------
count_win, count_lose, count_draw : int
result of matches... | 4a86867a7f477c24bbff357442ca997486224a08 | 3,610,732 |
from .fs import mkdir_p
import os
import shutil
def set_logger_dir(dirname, action=None):
"""
Set the directory for global logging.
Args:
dirname(str): log directory
action(str): an action of ["k","d","q"] to be performed
when the directory exists. Will ask user by default.
... | ccc524bf8a2886019ac1ddc8a429fb6ea2875580 | 3,610,733 |
import os
def is_ec2_linux():
"""Detect if we are running on an EC2 Linux Instance
See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/identify_ec2_instances.html
"""
if os.path.isfile("/sys/hypervisor/uuid"):
with open("/sys/hypervisor/uuid") as f:
uuid = f.read()
... | 2a3d453cf520e5c9b3b8acb410e629e6e183391d | 3,610,734 |
def flask_apis():
""" List of Flask RESTful APIs """
apilist = ["Geolocate by IP Address", "Geolocate by Lat/Long", "Phone Number Location", "Street Address Validation",
"Email Address Deliverablity", "IP Address to Consumer Profile"]
return render_template(
"flask.html",
c... | f19909e38e42273c0a8e41161e2e32ef8f75f118 | 3,610,735 |
def train_model(
X, y, df, model, num_epochs, skip_epochs, learning_rate,
plot_frames_dir, predictions_plot_mesh_size):
"""
Train the model by iterating `num_epochs` number of times and updating
the model weights through backpropagation.
Parameters
----------
model: Pytorch model
... | 88b1f27b68c645702fb4d40b3bba7249f2624fb0 | 3,610,736 |
def filter_get_project_samples_response(response, json_response):
"""Filter list project samples sensitive data from response."""
if "results" in json_response:
for result in json_response["results"]:
if "id" in result:
result["id"] = MOCK_UUID
if "client_id" in r... | e4102c9fe0b87d08c5906d3b9041e0d04d556758 | 3,610,737 |
def extract_dictionary(dataframe, column, key_list=None, prefix=None, separator='.'):
"""
Extract values of keys in ``key_list`` into separate columns.
.. code-block:: python
>>> df = DataFrame({
... 'trial_num': [1, 2, 1, 2],
... 'subject': [1, 1, 2, 2],
... | b7e2c1db034b158e545fb6d81444c561a294bc23 | 3,610,738 |
def BetaPrime(alpha, beta, tag=None):
"""
A BetaPrime random variate
Parameters
----------
alpha : scalar
The first shape parameter
beta : scalar
The second shape parameter
"""
assert (
alpha > 0 and beta > 0
), 'BetaPrime "alpha" and "beta" paramete... | d3fccb98cf03445fa85d8d2e8f2c201561b5a5fd | 3,610,739 |
def get_sweep_parameters(parameters, env_config, index):
"""
Gets the parameters for the hyperparameter sweep defined by the index.
Each hyperparameter setting has a specific index number, and this function
will get the appropriate parameters for the argument index. In addition,
this the indices wi... | 4fe3ce005cc5a90694e6386737c6df2d18d41f49 | 3,610,740 |
import numpy
def load_values(files):
"""
Loads the sasa values from the files in the files dictionary. Returns the maximum and minimum values.
Values are loaded into the "files" structure.
"""
min_val = float("inf")
max_val = 0.0
for filename in files:
files[filename]["values"] = ... | a03ff0e928c192f57b911445b216f4baf0d88d7d | 3,610,741 |
import os
def install(path, restart=False):
"""
Install a KB from a .msu file.
Args:
path (str):
The full path to the msu file to install
restart (bool):
``True`` to force a restart if required by the installation. Adds
the ``/forcerestart`` switch to... | c04c9db56d106b852ff4e8566899a2130efe2354 | 3,610,742 |
def reproject_helper(args, raster_tuple, procnum, return_dict, resolution):
"""
Helper function for reprojection
"""
(pre_post, src_crs, raster_file) = raster_tuple
basename = raster_file.stem
dest_file = args.staging_directory.joinpath('pre').joinpath(f'{basename}.tif')
try:
return_... | 36f053946f4747ec8e4df95b948882c1eed18d5b | 3,610,743 |
def create_board(user, **params):
"""Helper function to create a new board"""
defaults = {
'title': 'Test Board',
'code': 'tb'
}
defaults.update(**params)
return Board.objects.create(
user=user, **defaults
) | cdd3fd076480e44e4a5ff14a5e98fedf2d77461f | 3,610,744 |
def transform(resp_type):
"""A decorator to take a RundeckResponse and pass it through one of the is_transform marked
functions above
"""
def inner(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
results = func(self, *args, **kwargs)
try:
... | 60d94e3448aa1bd199fbb835f86e1005106daab0 | 3,610,745 |
def create_attributes_filter_rules_list(raw_attributes_filter_rules_list):
"""Validate and parse a list of attributes filter rules
:param raw_attributes_filter_rules_list: A list of filter rules of type
`attribute`, formatted as strings.
:return The list of filter rules that matches the provided... | f5cf78bb6067b5cbb3616ea99048ef599298034c | 3,610,746 |
import tqdm
def glue_example_to_feature(
task,
examples,
tokenizer,
max_seq_len,
label_list,
pad_token=0,
pad_token_segment_id=0,
):
"""
task: the name of one of the glue tasks, e.g., mrpc.
examples: raw examples, e.g., common.SentenceExamples.
tokenizer: BERT/ROBERTA token... | e2b16a9c04818c82d5e4bd1af1832abefdb2cdec | 3,610,747 |
def mount(
storage=None, name="", storage_parameters=None, unsecure=None, extra_root=None
):
"""
Mount a new storage.
.. versionadded:: 1.0.0
Args:
storage (str): Storage name.
name (str): File URL. If storage is not specified, it will be infered from this
name.
... | fa446f40958b50828e1a9142cdb46f35d9ec0243 | 3,610,748 |
import numpy
def labeled_comprehension(input,
labels,
index,
func,
out_dtype,
default,
pass_positions=False):
"""
Compute a function over an image at spec... | 3475b331c7ba522bf71be264725e247687c7cf39 | 3,610,749 |
from typing import Optional
def get_resub(db: Session, *, name: str) -> Optional[Resub]:
"""Get the resub with the given name."""
return db.query(Resub).filter(Resub.name == name).first() | 15418f7f594f696cb04d33b9a5a332f447405265 | 3,610,750 |
def smooth_control_inputs_gaussian(log, sigma):
"""
Bind smoothed control inputs to the driving log using a Gaussian filter.
This more closely preserves the mean than the exponential smoothing (but
the outputs have so far been not that different).
"""
for control_column in CONTROL_COLUMNS:
... | a6baa03b5ad70537a68ba6581c56f005f0e3d0af | 3,610,751 |
import argparse
def load_batcher(dictionary: dict, args: argparse.Namespace) -> Batcher:
"""Loads batcher into CACHE and on subsequent calls, retrieves batcher
from cache.
Arguments:
dictionary {dict} -- Batcher dictionary
args {argparse.Namespace} -- Parsed commandline options
Retur... | 9b6340b36b25ae50f9849b7d645e2ed5be3fd4ca | 3,610,752 |
from typing import Optional
from typing import Dict
from re import A
def get_scaled_sum_aggregations(field_to_sum: str, pagination: Optional[Pagination] = None) -> Dict[str, A]:
"""
Creates a sum and bucket_sort aggregation that can be used for many different aggregations.
The sum aggregation scaled the v... | 4210903774db8f746eabd48748f0d1016b3d59fe | 3,610,753 |
def _get_versions(client, bucket, key):
"""
Returns all the version IDs for a key ordered by last modified timestamp.
"""
resp_iterator = client.get_paginator("list_object_versions").paginate(
Bucket=bucket, Prefix=key
)
try:
versions = [version for page in resp_iterator for vers... | 32ab35529997c97c3a83e54f9c3a59bbc82d1498 | 3,610,754 |
def associate_new_data(dataframe, df_studies_by_funder):
"""Merge two dataframes based on Case Study ID.
Takes a dataframe with the case study information and merges it with another
dataframe that contains case study IDs and some other data (e.g. funders, disciplines)
:params: a dataframe with case st... | ae86739dae8699865d407e8fedfa97c26902578d | 3,610,755 |
def infer_feature_schema(features, graph, session=None):
"""Given a dict of tensors, creates a `Schema`.
Infers a schema, in the format of a tf.Transform `Schema`, for the given
dictionary of tensors.
If there is an override specified, we override the inferred schema for the
given feature's tensor. An over... | dda42e6e76cf628fc7dac10afa0e169f677d35c5 | 3,610,756 |
def _parse_timestamp(exit_or_boot_timestamp):
"""
Parse boot_timestamp or exit_timestamp and return datetime object or None.
"""
timestamp = exit_or_boot_timestamp.strip(':')
if timestamp:
return datetime_parse(timestamp).replace(tzinfo=utc)
else:
return None | 790e7fb94a93c3dcc0121f19dede7090563afd78 | 3,610,757 |
def authorization(auth, preserve_user=None, white_list=None):
"""
MW для авторизации.
:param auth: сервис авторизации
:param white_list: Список контроллеров без проверки
:return: вызов следующей по списку MW
"""
bypass = set(white_list or []).__contains__
def wrapper(nxt, controller, a... | ec459ea7f1581449561cd1079bec3b5caab1d44b | 3,610,758 |
def format_call(__fn, *args, **kw_args):
"""
Formats a function call, with arguments, as a string.
>>> format_call(open, "data.csv", mode="r")
"open('data.csv', mode='r')"
@param __fn
The function to call, or its name.
@rtype
`str`
"""
try:
name = __fn.__name__... | 0dce4bf0166f59f810063596f872b9f641f84234 | 3,610,759 |
import torch
def rgb_to_yuv(image: Tensor) -> Tensor:
"""Convert an RGB image to YUV. Image data is assumed to be in the
range of [0.0, 1.0].
Args:
image (Tensor[B, 3, H, W]):
RGB Image to be converted to YUV.
Returns:
yuv (Tensor[B, 3, H, W]):
YUV version of... | a891ac3564f8bec2a40163b86e2bab0753749fc2 | 3,610,760 |
import copy
def _get_preprocessor_settings(variables, profile, config_user):
"""Get preprocessor settings for a set of datasets."""
all_settings = {}
profile = copy.deepcopy(profile)
_update_multi_model_statistics(variables, profile,
config_user['preproc_dir'])
... | 87426865a14d975d55ff998018f485d0fe1e78a0 | 3,610,761 |
def method(obj, method, **kwargs):
"""
Call an object method. {% method object method **kwargs %}
"""
try:
return getattr(obj, method)(**kwargs)
except Exception as exception:
raise TemplateSyntaxError(
'Error calling object method; {}'.format(exception)
) | bdc034fcc1e865bd15ff4064a5b64d8f37c3d0a7 | 3,610,762 |
def make_layout() -> Layout:
"""Define the layout."""
layout = Layout(name="root")
layout.split(
Layout(name="header", size=3),
Layout(name="main", ratio=1),
Layout(name="footer", size=7),
)
layout["main"].split_row(
Layout(name="side"),
Layout(name="body", r... | 30839d6c5d4a3b2ea33e737d9967071437cce7fd | 3,610,763 |
import math
def _get_precursor_mz_splits(precursor_mzs: np.ndarray,
precursor_tol_mass: float,
precursor_tol_mode: str,
batch_size: int) -> nb.typed.List:
"""
Find contiguous blocks of precursor m/z's, relative to the precu... | 1b0f0cf9cdfadabac750a44e0ba599ee49f6fdc9 | 3,610,764 |
def generate_fieldnames(value, prefix=''):
"""
"""
fieldnames = []
if isinstance(value, dict):
prefix = prefix + '.' if prefix != '' else ''
for key in sorted(value.keys()):
subnames = generate_fieldnames(value[key], prefix='{}{}'.format(prefix, key))
fieldnames.e... | e5ba2a4bc8786aa37542535e6c2bf2dd11b76648 | 3,610,765 |
def treebank_to_short_name(treebank):
""" Convert treebank name to short code. """
if treebank in treebank_special_cases:
return treebank_special_cases.get(treebank)
if treebank.startswith('UD_'):
treebank = treebank[3:]
splits = treebank.split('-')
assert len(splits) == 2, "Unable ... | c6eca6d1a8e5b5c9fb73ac75716421cee630484b | 3,610,766 |
def solve_chroma_sub(upper_rgb, lower_rgb, xyz_t, l, h, l_val, h_val, c):
"""
与えられた条件下での Chroma の限界値を算出する。
"""
upper_rgb = [
upper_rgb[idx].subs({l: l_val, h: h_val}) for idx in range(3)]
lower_rgb = [
lower_rgb[idx].subs({l: l_val, h: h_val}) for idx in range(3)]
xyz_t = [
... | 54905abf0639ab4067e251cf05337017c8d12dfd | 3,610,767 |
import os
def get_data_dir(file=''):
"""Return the full path to the directory used to store the API data
"""
data_dir = os.getenv('TRAPI_DATA_DIR')
if not data_dir:
# Output data folder in current dir if not provided via environment variable
data_dir = os.getcwd() + '/output/'
else... | febef61b3f22942d087e9d2472b6a99da7bf2a4c | 3,610,768 |
def ProcrustesCompare(mat1,mat2):
"""
Compares similarity of two matrices according to weighted R^2 among their individual components.
R^2 of inidividual components weighted by their magnitude to generate composite score.
Matrcies aligned prior to comparison using orthogonal procrustes (rotation only).
... | d010b0156f0f9e2b0ae1c44205c75167700f91d4 | 3,610,769 |
def _get_value_pos(line, delim):
"""
Finds the first non-whitespace character after the delimiter
Parameters:
line: (string) Input string
delim: (string) The data delimiter
"""
fields = line.split(delim, 1)
if not len(fields) == 2:
raise Exception(f"Expected a '{delim}' ... | 8337c92045f2d3ccb91479502b30c7d191e53f34 | 3,610,770 |
def norm(data):
"""Normaliza una serie de datos"""
return (data - data.min(axis=0))/(data.max(axis=0)-data.min(axis=0)) | 9e2a23d8d734a4e77ec99c0dcb0ae4d85f971ede | 3,610,771 |
def area(ds, Nmax=None, label_name='labels', cell_dim_name='CellID', dims='STCZYX'):
"""
Compute the area of each labelled region in each frame.
"""
if isinstance(dims, str):
S, T, C, Z, Y, X = list(dims)
elif isinstance(dims, list):
S, T, C, Z, Y, X = dims
def padded_area(int... | 24b342b1abc0248171da82925d49bbd89e4f59bf | 3,610,772 |
from pathlib import Path
def create_default_compiler_error_handler(
experiment_handle: 'ExperimentHandle',
project: Project,
report_type: tp.Type[BaseReport],
output_folder: tp.Optional[Path] = None,
binary: tp.Optional[ProjectBinaryWrapper] = None
) -> PEErrorHandler:
"""
Create a default... | 7a3948b7d8eb88c094cea8bdf7d711fe65cbc170 | 3,610,773 |
def format_size(size):
"""格式化大小
>>> format_size(10240)
'10.00K'
>>> format_size(1429365116108)
'1.3T'
>>> format_size(1429365116108000)
'1.3P'
"""
if size < 1024:
return '%sB' % size
elif size < 1024 **2:
return '%.2fK' % (float(size) / 1024)
elif size < 1024... | 66aa2301350def395e32bae87dabccc18a126786 | 3,610,774 |
import argparse
import os
import uuid
def _new(args: argparse.Namespace) -> int:
"""
Begin a new hive! Create initial scafolding for the project, nodes,
etc.
:param args: The namespace that we're given with our settings
:return: int
"""
if args.dir:
os.chdir(args.dir)
config =... | 662fa3d6dbe89f9dacbb6b903a723254018a37e4 | 3,610,775 |
from typing import Counter
def vectorize(tokens_list, feature_fns, min_freq, vocab=None):
"""
Given the tokens for a set of documents, create a sparse
feature matrix, where each row represents a document, and
each column represents a feature.
Params:
tokens_list...a list of lists; each subl... | a6b5addc84c052a48d7bcca98919d4760d5afde7 | 3,610,776 |
def convert_category_to_continuous(df: pd.DataFrame):
"""Convert category to continuous value started from the
trial. 5 sec and 9 sec is flushing time.
See "makeDataFrame" in basicChara for reference code.
Args:
df: cleaned dataframe. Ex., pL.merged_structured_df.
"""
df = df.cop... | 2c98594cf8dd44b74c1e07e76a764616dbe81694 | 3,610,777 |
def closest_contour_center(depth_image, contours):
"""
Takes a depth_image and list of contours.
Finds the center of each contour, then finds which center is closest.
Returns the coordinates for that center in y, x format.
"""
depth_image = cv.GaussianBlur(depth_image, (3, 3), 0)
contour_centers = []
for con... | 297c537e9e0664b2143f333c326ad798213e89ed | 3,610,778 |
def get_download_url_for_platform(url_templates, platform_info_dict):
"""
Compare the dict returned by get_platform_info() with the values specified in the url_template element. Return
true if and only if all defined attributes match the corresponding dict entries. If an entry is not
defined in the url_... | a5eb81ff5aec82b24dc6128e908519dbee4e13e3 | 3,610,779 |
from typing import Union
from typing import List
from typing import Dict
def determine_boundaries(df: pd.DataFrame, bucket_mapping: BucketMapping) -> Union[List, Dict]:
"""
Determine mapping boundaries.
Given a dataframe with pre_bucket and bucket column, determine the boundaries
that can be passed t... | c057decf7a0ff05a830aa29e47adcd44f3d120a6 | 3,610,780 |
def load(filepath):
"""
Load in metadata from filepath.
Args:
filepath (string/path): path to file.
Returns:
pd.DataFrame: dataframe containing metadata.
"""
tracks = pd.read_csv(filepath, index_col=0, header=[0])
# Format the data.
# Remove "tabs" from strings etc.
... | 58f111c95fa85b22b920931bd6af60a330d3fe5a | 3,610,781 |
def compute(
applied_voltages, resistances, r_i=None,
r_i_word_line=None, r_i_bit_line=None, **kwargs):
"""Computes branch currents and node voltages of a crossbar.
Parameters
----------
applied_voltages : array_like
Applied voltages. Voltages must be supplied in an array of sha... | 76f5c80bc1f0cf248d63bac4a3564d64c64facfb | 3,610,782 |
def TypeNameToLogModel(type_name):
"""Return log model associated with type_name."""
if type_name == BitLockerVolume.ESCROW_TYPE_NAME:
return BitLockerAccessLog
elif type_name == DuplicityKeyPair.ESCROW_TYPE_NAME:
return DuplicityAccessLog
elif type_name == FileVaultVolume.ESCROW_TYPE_NAME:
return F... | fcfc65a2c6a534bc73e2e9a59001d93ed8a3bb46 | 3,610,783 |
def grad_logdet(inv_metric: np.ndarray, jac_metric: np.ndarray, num_dims: int) -> np.ndarray:
"""Computes the gradient of the log-determinant of the Riemannian metric.
Args:
inv_metric: The inverse of the Riemannian metric.
jac_metric: The Jacobian of the metric tensor.
num_dims: The nu... | 8d56cb3be084fa8c7030bf86c7e068167ea9263e | 3,610,784 |
def get_code():
""" return code from codes.txt and """
codes = []
with open(codes_file, "r") as cf:
for num, line in enumerate(cf.readlines()):
if num == 1:
if line.startswith("Need"):
raise Exception(line)
codes.append(line)
code = cod... | 1e3343e245e3c2ba627feb6364f3bf3dba487141 | 3,610,785 |
def get_unicode_category(prop):
"""
Retrieve the unicode category from the table
"""
p1, p2 = (prop[0], prop[1]) if len(prop) > 1 else (prop[0], None)
return ''.join([x for x in _unicode_properties[p1].values()]) if p2 is None else _unicode_properties[p1][p2] | 790a6bc54ea7e0839735d681e074b3de7a044123 | 3,610,786 |
def pink_noise(nstep_out, pow_spec=None, f=None, fmin=None, alpha=-1, **kwargs):
""" Generate random pink noise
Parameters
==========
nstep_out : int
Desired size of the output noise array. If smaller than `pow_spec`
then it just truncates the results to the appropriate size.
If... | e4261a5c78cdd68df04a0437c517fe97d1d54ff1 | 3,610,787 |
import getpass
def get_username() -> str:
"""
Returns username lowercase
>>> username = get_username()
>>> assert len(username) > 1
"""
_username = getpass.getuser().lower()
return _username | aa7c5d2974502bd411cd1a77218ca74171d3dc71 | 3,610,788 |
def fetch_ALL_standings():
"""
This returns the complete set of all the standings in the league, namely IGnobels and general/points. It is used
by other functions
"""
dic_stand = {
'Caduti': 'infortunati',
'Cartellino Facile': 'cartellini',
'Porta Violata': 'goal_subit... | f586cbc0a917cc0c23a0ead083b669deba61b458 | 3,610,789 |
def extract_id(source):
"""
Attempts to extract an ID from the argument, first by looking for an
attribute and then by using dictionary access. If both fail, the argument
is returned.
"""
try:
return source.id
except AttributeError:
pass
try:
return source["id"]
... | 7ec169cfd6edf70c9d414ec61edc3bf514a80e02 | 3,610,790 |
import shutil
def pytest_report_header(config):
"""Add header information for pytest execution."""
return [
"LAMMPS Executable: {}".format(
shutil.which(config.getoption("lammps_exec") or "lammps")
),
"LAMMPS Work Directory: {}".format(
config.getoption("lammps_... | dc07ae457cc49a1fc1ac43643a193bb3b6a84399 | 3,610,791 |
def transform_score(data, score_card):
"""
特征映射回分值
Args:
data: 特征表
score_card: 评分卡
Returns:
返回转化后的得分
"""
base_score = score_card[score_card['Bins'] == '-']['Score'].values[0]
data['Score'] = base_score
for i in range(len(data)):
score_i = base_score
... | d3afafeca40f0bcf97e522cb32b4f139d1c0321e | 3,610,792 |
def load_query(asset):
"""Helper to load test asset and parse as Query, returning."""
yaml_query1 = load_test_asset(asset)
parser1 = mql.QueryParser()
return parser1.parse_ystr_query(yaml_query1) | 79cf824066dda4862bd59d8d6ddb94a465d62e3f | 3,610,793 |
def FKinBody(M, Blist, thetalist):
"""Computes forward kinematics in the body frame for an open chain robot
:param M: The home configuration (position and orientation) of the end-
effector
:param Blist: The joint screw axes in the end-effector frame when the
manipulator is at... | 580307d9c2fcc756d943324c044610286df8e82d | 3,610,794 |
def l2_regularization(cg, rate=0.01):
"""compute L2 regularization decay.
Parameters
----------
cg : ComputationGraph
computation graph for a network
rate : float
L2 regularization rate
Returns
-------
L2_cost : expression
L2 cost for a network
"""
W = V... | 8c17ae527831c0c2f781f20e0b9cf7ee5b966af1 | 3,610,795 |
def convertcsv(inputfile, outputfile, templatefile, charset=None,
columnorder=None):
"""reads in inputfile using csvl10n, converts using csv2tbx, writes to
outputfile"""
inputstore = csvl10n.csvfile(inputfile, fieldnames=columnorder)
convertor = csv2tbx(charset=charset)
outputstore = ... | 920163dc1e21a709a84b120ee895a153e5d00eff | 3,610,796 |
import json
def supported_disabled(responses, derived):
""" Return the parsed array of supporting_disabled """
try:
return json.loads(responses.get('supporting_disabled', '[]'))
except ValueError:
return [] | 02e60b525ca8a7cd9cf9f0c053ba9d26d7c9f133 | 3,610,797 |
def mathreco():
"""API function
All model-specific logic to be defined in the get_model_api()
function
"""
input_data = request.json
app.logger.debug("api_input: " + str(input_data))
output_data = model_api(input_data)
app.logger.debug("api_output: " + str(output_data))
response = j... | f0cebde917bc48e20b9fd3b3c81178f6db377569 | 3,610,798 |
def metrics_binary(ytest, predict_y_score):
"""Evaluation metrics for binary classification (including auc, ap, f1)"""
predict_y_label = np.array(predict_y_score >= 0.5).astype(np.int)
pos_num = np.sum(predict_y_label)
frac = np.sum(predict_y_label) * 100 / len(ytest)
try:
auc = metrics.roc_... | f72bedd564c4007b985cb21c4bad471fa2cb8c71 | 3,610,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.