content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Literal
def DataClass(name, columns, constraint=None):
"""
Use the DataClass to define a class, but with some extra features:
1. restrict the datatype of property
2. restrict if `required`, or if `nulls` are allowed
3. generic constraints on object properties
It is expected... | 4305c5f85ead063b0bf4e71235333cbc43a3cef1 | 40,600 |
def _run_prop_dos(
frequencies, mode_prop, ir_grid_map, ir_grid_points, num_sampling_points, bz_grid
):
"""Run DOS-like calculation."""
kappa_dos = KappaDOS(
mode_prop,
frequencies,
bz_grid,
ir_grid_points,
ir_grid_map=ir_grid_map,
num_sampling_points=num_samp... | ec031e31eb752cbe4cfd7219255382f4be325bb2 | 40,601 |
def load_data(database_filepath):
"""
Read the input database to create and return separate numpy arrays for
messages, category values, and names of categories respectively
"""
# creating sqlite engine to interact with database
engine = create_engine('sqlite:///'+database_filepath)
df =... | 115f9a72534aa8a528b15decf9373ee73e05dc10 | 40,602 |
import warnings
def Client(**kwargs):
"""Get a SoftLayer API Client using environmental settings.
Deprecated in favor of create_client_from_env()
"""
warnings.warn("use SoftLayer.create_client_from_env() instead",
DeprecationWarning)
return create_client_from_env(**kwargs) | 8d59c34ffba44de2254cf63297553c49240dd7f0 | 40,603 |
def _merge_candidate_name(src, dest):
"""Returns the formatted name of a merge candidate branch."""
return f"xxx-merge-candidate--{src}--{dest}" | a08b6d4b57385bc390e649448ce264cffd5a1ffa | 40,604 |
def feature(enabled=True, default_rule=True, conditions=True, operator=None):
"""Generates feature structure like parsed JSON from server"""
return {
'key': fake.word(),
'variantSalt': fake.word(),
'enabled': enabled,
'offVariantKey': fake.word(),
'rules': [rule(default_... | 4f7f76304e1dadbb75107beb246359b64f3d800f | 40,605 |
import pandas
def to_datetime(
arg,
errors="raise",
dayfirst=False,
yearfirst=False,
utc=None,
box=True,
format=None,
exact=True,
unit=None,
infer_datetime_format=False,
origin="unix",
):
"""Convert the arg to datetime format. If not Ray DataFrame, this falls
bac... | a14bfea0c0e60fe7094cffb3482101ddabeb1c02 | 40,606 |
def cv_process(data=None, current_column=1, potential_column=0, area=5, reference='she', thermo_potential=0, export_data=False, save_dir='processed', **kwargs):
"""
Processes cyclic voltammetry data
Can either process pre-loaded data or load and process data files. If called with no arguments, loads and processes a... | 8a2c26fb84d92e45b49072e3ca76e1112625110c | 40,607 |
def OpenNormalFVFile(fv_file, type_str):
"""
Open a normalized frequency vector file and check to make sure it's valid.
The first line of a valid normalized FV file contains the number of vectors
in the file followed by the char ':' and an optional char 'w'.
Subsequent lines contain an optional we... | a0c8ce05adf8b59204a31abf74bc480c4d6eb878 | 40,608 |
import torch
import itertools
import time
def td3(env_fn, actor_critic=core.MLPActorCritic, ac_kwargs=dict(), seed=0,
steps_per_epoch=4000, epochs=100, replay_size=int(1e6), gamma=0.99,
polyak=0.995, pi_lr=1e-3, q_lr=1e-3, batch_size=100, start_steps=10000,
update_after=1000, update_every=50, ... | ea9d322f7180289de34faea66bda5526466d0121 | 40,609 |
def meta(condition):
"""Return a class with a subclassing relation defined by condition.
For example, a dataclass is a subclass of `meta(dataclasses.is_dataclass)`,
and a class which name starts with "X" is a subclass of
`meta(lambda cls: cls.__name__.startswith("X"))`.
Arguments:
conditio... | d10937c24181dc3c259267b469e772dc29ffad7e | 40,610 |
def queue_once_key(name, kwargs, restrict_to=None):
"""
Turns a list the name of the task, the kwargs and allowed keys
into a redis key.
"""
keys = ['qo', name]
# Restrict to only the keys allowed in keys.
if restrict_to is not None:
restrict_kwargs = {key: kwargs[key] for key in res... | 4db9b257716ca7c24b4943bb99e2e7de82a38aff | 40,611 |
def get_outliers(training_data, unlabeled_data, number=10):
"""Get outliers from unlabeled data in training data
Returns number outliers
An outlier is defined as the percent of words in an item in
unlabeled_data that do not exist in training_data
"""
outliers = []
total_feature_count... | 40747dccd40d538cbca87b128db1664b828c08b0 | 40,612 |
def is_cdn_cache_hit(response):
"""Checks the response for evidence of a cache hit on the CDN."""
return is_cloudfront_cache_hit(response) | 9593941226299a2bee129d8fb05210587cc36abd | 40,613 |
def mms_feeps_energy_table(probe, eye, sensor_id):
"""
This function returns the energy table based on
each spacecraft and eye; based on the table from:
FlatFieldResults_V3.xlsx
from Drew Turner, 1/19/2017
Parameters:
probe: str
probe #, e.g., '4' for MMS4
... | 56e88802a553d56aedff92ef0d251d8dc1c98c3c | 40,614 |
def load_jets(hdf5):
"""load_jets(hdf5) -> jets
Loads a list of Gabor jets from the given HDF5 file, which needs to be open for reading.
**Parameters**:
``hdf5`` : :py:class:`bob.io.base.HDF5File`
An HDF5 file open for reading
**Returns**:
``jets`` : [:py:class:`bob.ip.gabor.Jet`]
The l... | a44ae133560ed9e1abc6a2eb29e62dd0b07e8927 | 40,615 |
import math
def build_label_vector(label_dict_list, n_xgrids, n_ygrids, mean_lwh,
xlim=(0.0, 70.0), ylim=(-50.0,50.0), zlim=(-10.0,10.0)):
""" Build the ground-truth label vector
given a set of poses, classes, and
number of grids.
Input:
label_dict_lis... | e5b88aaf2b24fe662ef77bdf2ea1958398023839 | 40,616 |
def get_all_admins_chat_ids():
"""
List all chat ids of admin
"""
session = Session()
admins_chat_ids = [admin.chat_id for admin in session.query(Admin)]
session.close()
return admins_chat_ids | d34b56857da99859da3d38dacc42c4ad8d133001 | 40,617 |
def decorator_with_args(decorator_to_enhance):
"""
This is decorator for decorator. It allows any decorator to get additional arguments
"""
def decorator_maker(*args, **kwargs):
def decorator_wrapper(func):
return decorator_to_enhance(func, *args, **kwargs)
return decorator_... | 1af073daf9e9ac9a8834f3a1484bdfa293b1b2bb | 40,618 |
def get_k_model(Te0, alpha, ni_Al_profile, shot, Ew_fwhm=1300., delta_a=0.06, delta_h=0.01, ne=0.8, num_cores=16):
"""
"""
# Load threshold data from the supplied shot
MST_data = data.load_ME(shot, direction='horizontal')
MST_data = data.load_ME_horiz(MST_data)
Ec_map = MST_data['thresholds'][:,... | 9596a6664df7bd431dd571ad32d0db07b44472da | 40,619 |
def drop_by_activity(df: pd.DataFrame):
"""Drops non-active players from the dataframe. Active players are those
players who have at least one killmail per month that resulted from their
use of a combat-based Frigate-class ship type, for a minimum of 12 months
or more.
Examples
--------
Exa... | 5dd39657553f920736ffdc20edafee34d2a5e159 | 40,620 |
from datetime import datetime
def login(userObj):
"""
If you are using the Auth module and want to track login times as part of the userObj, use this
to set the appropriate state of the user objects last_login field, can be used in conjunction with
``Mojo.Auth.Helpers.login_assistant()`` to round-off ... | a1ce67aee064f3277715724c6a18ea3fd430e7fa | 40,621 |
def generate_intervals(nelements):
"""
Generates all possible permutations of lists that access elements from
boths ends of a list without accessing the middle, and one permutation
that accesses ALL elements of a list.
"""
intervals = list()
for i in range(0, nelements):
interval = l... | 06098fbff3342c369b7334e4447cdf9b3ef1a0ab | 40,622 |
import re
def find_subtype(meta_dict):
"""Find subtype from dictionary of sequence metadata.
Args:
`meta_dict` (dict)
dictionary of metadata downloaded from genbank
Returns:
`subtype` (str)
RSV subtype as one letter string, 'A' or 'B'.
"""
subtype = ''
if '... | 130b8ed61f117a786cf5f5ae49fc75e8b074ef2e | 40,623 |
def multihop_sampling(src_nodes, sample_nums, neighbor_table):
"""根据源节点进行多阶采样
Arguments:
src_nodes {list, np.ndarray} -- 源节点id
sample_nums {list of int} -- 每一阶需要采样的个数
neighbor_table {dict} -- 节点到其邻居节点的映射
Returns:
[list of ndarray] -- 每一阶采样的结果
"""
sampling_re... | 9a6e86ba0daf99ec257ebce3ff2f0609abb42aa6 | 40,624 |
from typing import Union
from typing import Mapping
from typing import Callable
def gen_random_series(
size: int,
dtype: str = "object",
na_ratio: float = 0.0,
str_max_len: int = 100,
random_state: Union[int, np.random.RandomState] = 0,
) -> pd.Series:
"""
Return a randomly generated Panda... | 407945cbaccc2b0b3cc146d3f47d43d64cea1af8 | 40,625 |
def extract_gff3_fields(primer_info):
"""
The gff3 file is a format to annotate locations on a genome.
The gff3 annotations requires locations on the genome, this was not required for creating the primers.
This function computes these locations and prepares the data for the gff3 file
:param primer_i... | 4e8f0fbfc3bff136b3c03d4a2c35648491d42fba | 40,626 |
def flip_label(target, ratio, pattern=0):
"""
Induce label noise by randomly corrupting labels
:param target: list or array of labels
:param ratio: float: noise ratio
:param pattern: flag to choose which type of noise.
0 or mod(pattern, #classes) == 0 = symmetric
int = asymme... | 4c2242b2914c245091a3441082c5887bf840c617 | 40,627 |
def retrieve_stripe_checkout_session(subscription):
"""This function returns a Stripe Checkout Session object or raises an
error when the session does not exist or the API call has failed."""
stripe.api_key = settings.STRIPE_API_SECRET_KEY
return stripe.checkout.Session.retrieve(subscription.stripe_sess... | 306fd92a5f7b0a8be890e7e41bf217aa61facbf6 | 40,628 |
from typing import List
def _create_agents(num_frames: int, num_agents: int, label: int = 1) -> List[List[Box3D]]:
"""
Generate dummy agent trajectories
:param num_frames: length of the trajectory to be generate
:param num_agents: number of agents to generate
:param label: agent type label. Typica... | 44a4ab4fef1ed29a0b3861e354357bbd3d2ff44f | 40,629 |
def get_ℓ_prior(points):
"""Calculates mean and sd for InverseGamma prior on lengthscale"""
distances = pdist(points[:, None])
distinct = distances != 0
ℓ_l = distances[distinct].min() if sum(distinct) > 0 else 0.1
ℓ_u = distances[distinct].max() if sum(distinct) > 0 else 1
ℓ_σ = max(0.1, (ℓ_u -... | 673e71206c08c815543888d045fc2255ef323816 | 40,630 |
from re import DOTALL
def parse_wars(content):
""" Second part of the main parser. Reads all relevant information about wars
from the savegame. Returns a list of all wars, as well as a dictionary about
the participants in each war."""
previous_wars = content.split("previous_war={")[0].split("active_war={")[1:] + ... | 13b6a168d17118d9ac71e41979a31abcc3999d0b | 40,631 |
from typing import Sequence
from typing import Type
from typing import Union
def unique_fast(
seq: Sequence, *, ret_type: Type[Union[list, tuple]] = list
) -> Sequence:
"""Fastest order-preserving method for (hashable) uniques in Python >= 3.6.
Notes
-----
Values of seq must be hashable!
See... | c41c6b298e52bd3069414206cf9ada4766ea8f4d | 40,632 |
import os
import torch
def loadimg_from_id(ID, root_dir=test_dataset.root_dir):
"""load image from pre-defined id.
Args:
ID: List of ids of 5 items.
Return:
imgs: torch.tensor of shape (1, 5, 3, 224, 224)
"""
imgs = []
for id in ID:
if 'mean' in id:
... | 876216222f92d55bce64c8f0ce097706ec3778f6 | 40,633 |
import time
def verify_signed_url(url, salt=None):
"""
Check a signed URL is valid and unexpired.
"""
salt = salt or _DEFAULT_SALT
m = _SIGNED_URL_RE.match(url)
if not m:
return None
url = m.group(1)
signature = m.group(2)
expiry = int(m.group(3))
if expiry <= int(tim... | 347770eef1fdddc70ef7aef754f20b30d554acfb | 40,634 |
def yices_type_is_function(tau):
"""Returns 1 if tau is a function type, 0 otherwise."""
return libyices.yices_type_is_function(tau) | 5078fbe3777b230297df0553d983c8cb7a1df8c3 | 40,635 |
import torch
def kumaraswamy_sample(conc1, conc0, sample_shape):
"""
Sample from the Kumaraswamy distribution given the concentrations
:param conc1: torch tensor: the a concentration of the distribution
:param conc0: torch tensor: the b concentration of the distribution
:param batch_shape: scalar: the batch sha... | 41869f17bdc1e9d439f5277b26d4ed50e4d9f0f1 | 40,636 |
def parse_atom_ids(input_list, mol):
"""
List of the form id,id,isotope,addHs
e.g. 1,2,104,True
:param input_list:
:param mol:
:return:
"""
spl_list = input_list.split(",")
bond_ids = []
atom_ids = []
bond_colours = {}
for i, data in enumerate(spl_list):
list_len ... | 8939aa5ad2ef8d2de73a1c3595426602742aa758 | 40,637 |
def cluster_hierarchically(active_sites):
"""
Cluster the given set of ActiveSite instances using a hierarchical algorithm. #
Calls to agglomerative clustering algorithm housed in another script
Input: a list of ActiveSite instances
O... | feedfaec13387c6f2534c82110fe3e348e106d85 | 40,638 |
def _is_container_running(duthost, container_name):
"""
Checks if the required container is running in DUT.
Args:
duthost (SonicHost): The target device.
container_name: the required container's name.
"""
try:
result = duthost.shell("docker inspect -f \{{\{{.State.Running\}}... | 2653a82f65170a04f5d2a6ddf6137272e27e298d | 40,639 |
def slow_closest_pair(cluster_list):
"""
Compute the distance between the closest pair of clusters in a list (slow)
Input: cluster_list is the list of clusters
Output: tuple of the form (dist, idx1, idx2) where the centers of the clusters
cluster_list[idx1] and cluster_list[idx2] have minimum dist... | 473aaa90b644da69a72db6f88e19f3000641ad9e | 40,640 |
def is_retaincase(bunchdt, data, commdct, idfobject, fieldname):
"""test if case has to be retained for that field"""
thiscommdct = getfieldcomm(bunchdt, data, commdct, idfobject, fieldname)
return "retaincase" in thiscommdct | 1164376ea22ca97238623e65b3081b75900e37ac | 40,641 |
def test_multiple_forks(scheduler: Scheduler) -> None:
"""
Ensure multiple handle forks are recorded.
"""
@task()
def task1(conn):
return conn
@task()
def main():
conn = DbHandle("conn", "data.db")
conn = task1(conn)
conn = task1(conn.fork("a").fork("b").for... | b53c25c1035fc9473d5e75ccebdd9296b2666209 | 40,642 |
def add_run_number(bids_suffix, run_no):
"""
Safely add run number to BIDS suffix
Handle prior existence of run-* in BIDS filename template from protocol translator
:param bids_suffix, str
:param run_no, int
:return: new_bids_suffix, str
"""
if "run-" in bids_suffix:
# Preserve... | 8f8d4cd036c7ba63ec7aaf2562a638e59d842598 | 40,643 |
def logout():
"""Log user out."""
# forget any username
session.clear()
# redirect user to login form
return redirect(url_for("login")) | 0c2ce69eb27291ef15b98ad6e1a6a02d37b00119 | 40,644 |
def complement(clr):
""" Returns the color opposite on the color wheel.
The complementary color contrasts with the given color.
"""
if not isinstance(clr, Color):
clr = Color(clr)
return clr.rotate(180) | c340b3a2cefc22a8d99b04bf58911bf9600ef0b2 | 40,645 |
from re import S
def get_file_info(pipeline_context, filename):
"""Return a dictionary of CRDS information about `filename`."""
return S.get_file_info(pipeline_context, filename) | cfb469bb96049fe0c387ce9a3818c74b4e967098 | 40,646 |
def parse_colors(sequence):
"""Return escape codes from a color sequence."""
return ''.join(ESCAPE_CODES[n] for n in sequence.split(',') if n) | a2c32b861440136afc7a9495ef762206a98984fd | 40,647 |
def intersect(s1, s2):
"""
Returns the intersection of two slices (which must have the same step).
Parameters
----------
s1, s2 : slice
The slices to intersect.
Returns
-------
slice
"""
assert (s1.step is None and s2.step is None) or s1.step == s2.step, \
"Only i... | 13841ceddd3bb5c73a29bd4067a751579bc04e9b | 40,648 |
def apply_hpso_parameters(o, hpso, hpso_pipe):
"""
Applies the parameters for the HPSO pipeline to the parameter container object o.
:param o: The supplied ParameterContainer object, to which the symbolic variables are appended (in-place)
:param hpso: The HPSO whose parameters we are applying
:para... | a859c7598e8b5dc40aee24bafa654a439fff02d4 | 40,649 |
def checkpoint_get_group_command(client: Client, identifier: str) -> CommandResults:
"""
Show existing group object using object name or uid.
Args:
client (Client): CheckPoint client.
identifier(str): uid or name.
"""
result = client.get_group(identifier)
printable_result = buil... | 4a0d6e6696385a5b844ce4070ff55655fa23e830 | 40,650 |
def remove_duplicate_indices(data: pd.DataFrame, keep="first") -> pd.DataFrame:
"""Function that removes duplicate indices
Args:
data: The data frame for which duplicate indices need to be deleted
keep: Determines which duplicates (if any) to mark. See pandas.DataFrame.index.duplicated document... | d5288bfa5e7b7ab34a2b7a3ac58ce43595f825d8 | 40,651 |
def rdkit_molecule(gra):
""" Convert a molecular graph to an RDKit molecule.
This is mainly useful for quick visualization with IPython, which can be
done as follows:
>>> from IPython.display import display
>>> display(rdkit_molecule(gra))
:param gra: the graph
:returns: the RDKit molecule... | dfab20957deffb27f0e05c73d53eb77f213cda48 | 40,652 |
def make_filename_template(**kwargs):
"""Generate a filename template snippet from the schema, based on specific
filters.
Parameters
----------
kwargs : dict
Keyword arguments used to filter the schema.
Example kwargs that may be used include: "suffixes", "datatypes",
"exten... | 6aafb5791d3314a7baa885c080bdbd194a0a9717 | 40,653 |
import torch
def compute_entropy_bernoulli(logit: torch.Tensor):
""" Compute the entropy of the bernoulli distribution, i.e. H= - [p * log(p) + (1-p) * log(1-p)] """
p = torch.sigmoid(logit)
one_m_p = torch.sigmoid(-logit)
log_p = F.logsigmoid(logit)
log_one_m_p = F.logsigmoid(-logit)
entropy ... | e1a01541e3fd6673a1d53f834c16256581b0dd6d | 40,654 |
def domain_from_url(url):
"""Returns the website part of a given url
:param url: str the URL for which the website is needed
:returns: the website extracted from the url value
:rtype: str (or None)
"""
if url is None:
return None
try:
parsed = urlparse(url)
if parsed... | 21e2998052782718e388571642fa3f216bc52806 | 40,655 |
import os
def deDoc_run(dirname, sample_df, cutoff, deDoc_path):
"""
Input:
- dirname: ../Matrix_aligned/Sample_name/100k
- sample_df: chromosome pairs with sorted score
- cutoff: for choose the baseline of the prop in cumsum of the sorted score.
- deDoc_path: the path of deDoc... | 8f07f02d3465f74cb5d74115870d313dc07b9a91 | 40,656 |
def check_event_attr(logpath):
"""
Checks for existence of event attributes, given the path of event log.
Parameters:
logpath (str): Path of event log
Returns:
attr (List of str): List of event attributes
"""
log = importer.apply(logpath)
log_df = log_converter.apply(log, v... | 49291864b387cadc5e2777342ba55d415a97aa08 | 40,657 |
def is_word_guessed(word, guesses):
"""
This function will check if the user has guessed all of the letters in the word.
"""
# Loop through the word.
for letter in word:
# Check if the letter has been guessed.
if letter not in guesses:
# The user has not guessed the letter.
return False
# The user has ... | 7ab3ad07a5588745dc4a9f01dac89c788cc688f5 | 40,658 |
def solve(start, end, min_studios):
"""Solve an instance of the grid, given start and end gate locations.
min_studios is an integer specifying the minimum number of studio squares
that must be visited.
"""
# We may attempt the same gates multiple times. Memoize to improve speed.
memo_key = (start, end, min... | e124340639a8c8a2463c0fd98d6bed9fcf52e688 | 40,659 |
import os
def find_exe(arch='x86'):
"""Get the path to an exe launcher provided by this package.
The options for arch are currently 'x86' and 'x64'.
"""
if arch == 'x86':
return os.path.join(_pkg_dir, 'cli-32.exe')
elif arch == 'x64':
return os.path.join(_pkg_dir, 'cli-64.exe')
... | 939f192c9b8ff867fa35398ed1d97a7e775b8098 | 40,660 |
def unpack_seven(inbytes):
"""
Reconstruct a number from the seven-bit representation used in
the SysEx message data.
Takes a bytes-like object, where each byte is seven bits of the number
(big-endian byte order)
Each byte must have its high bit zero, or else ValueError is raised.
"""
va... | ce3084126b1851015cb0323b6aae2b1acd46b971 | 40,661 |
def h(node1, node2, l1, l2, *, g):
"""If node has 8 neighbors"""
g_n = g(node1)
path = node1.path
parent = next(path)
try:
parent = next(path)
except StopIteration:
pass
g_p = g(parent)
if g_p <= g_n:
w = l1
else:
w = l2
h_n = euclid(node1, node2)
... | d4cb4620147f550424711632f6bdfc43ee8c2cd2 | 40,662 |
import logging
def logout_page():
"""Redirects user to homepage and cleans session"""
flask.session.clear()
clean_cache()
logging.debug(flask.request.remote_addr + ' logged out')
return flask.redirect(flask.url_for('home_page')) | 1ecaa4f44f84ebffa7d503d6063b9a96aa3ce177 | 40,663 |
def nativestr(x):
"""Return the decoded binary string, or a string, depending on type."""
return x.decode("utf-8", "replace") if isinstance(x, bytes) else x | c4474e3c1953331fee46d29e59777494d626f660 | 40,664 |
def seperate(df, column, new_names, sep=".", remove=False):
"""Verb: split strings on a seperator.
Inverse of :func:`unite`
Parameters
----------
column : str or pd.Series
column to split on (Series.name is named in case of a series)
new_names : list
list of new column names
... | 026eeb557d395ffab748fc0a164b20ad3f4ed506 | 40,665 |
def listdetail(filename,
itemtype,
name='',
tablefmt='simple',
header='default'):
"""List nodes and metadata in output file.
Parameters
----------
{filename}
{itemtype}
name : str
Optional specific name to print only that entry... | 70636b05a975b76da17c8f00abafe61b22a136d9 | 40,666 |
def template_match_hashes(template_hashes, source_hashes, match_percent=0.6):
"""
Takes in array of template fingerprint hashes, and an array of hashes to search through. Looks through the search
array for the template, and registers a match so long as the percent of matches exceeds the provided match_perce... | 7bb37c315b62aa3116e5019a5c2d9b22cf65976c | 40,667 |
import io
def unparse(tree: typed_ast.ast3.AST, *args, **kwargs) -> str:
"""Unparse AST based on typed_ast.ast3 with nodes as defined in horast.nodes into code."""
assert isinstance(tree, typed_ast.ast3.AST), type(tree)
stream = io.StringIO()
Unparser(tree, *args, file=stream, **kwargs)
return str... | 2e97e4bd8f79d90651f942ec83c57c3c7fcbbd5f | 40,668 |
import re
def Clean_price(post_price):
"""This function takes out the price range used by the website"""
if re.search('\-.*', post_price):
pos = re.search('\-.*', post_price).start()
return post_price[:pos]
else:
return post_price | a84a4d0bf2c20640f92e7d56ac672316412a30fc | 40,669 |
def remove_duplicates(list1):
"""
Eliminate duplicates in a sorted list.
Returns a new sorted list with the same elements in list1, but
with no duplicates.
This function can be iterative.
"""
uniques = []
for dummy_idx in list1:
if dummy_idx not in uniques:
uniques... | ddb0fb01760ddf58f2d7e178ec7556d6083ff271 | 40,670 |
def extract_single_image(img_path, lab_path,
voxel_picker_class,
patch_picker_class,
cent_picker_class,
patch_size, scales,
n_voxels):
"""Sample and extract feature from an image.
Argume... | 304ab035b3a0ea4c69c8583d2453e59ac7cdc5e9 | 40,671 |
def fitness_function(solution, answer):
"""fitness_function(solution, answer) Returns a fitness score of a solution compaired to the desired answer. This score is the absolute 'ascii' distance between characters."""
score =0
for i in range(len(answer)):
score += (abs(solution[i]-answer[i]))
retu... | 059924beb07d0e0e1892783f515061ffcf714d43 | 40,672 |
import scipy
import itertools
def rr_order_patterns(
signal1: "np.ndarray[np.int32]", signal2: "np.ndarray[np.int32]", m: int, tau: int
) -> float:
"""
Parameters
----------
signal1 :
signal2 :
m : int
Embedding dimension.
tau : int
Time delay parameter.
Not... | ad3219d46563a2cb8c926b295e4cf91bcccc51b6 | 40,673 |
def adjust_cruise_no(cruise):
"""If shipc should be mapped we map cruise_no as well."""
if len(cruise) > 7:
return '_'.join((cruise[:4], cruise[4:8], cruise[8:]))
else:
return cruise | a83a35cb0a1bad17778f3b39756c431237254a51 | 40,674 |
def update_uas_class_admin(class_id=None,
comment=None,
default=None,
public_ip=None,
image_id=None,
priority_class_name=None,
namespace=None,
... | adba5a1027f21dc233abb29c013c0f33bbe85126 | 40,675 |
import argparse
def parse_args():
"""Parse command line arguments.
"""
arg_parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
arg_parser.add_argument('-hca', '--http_cert', default=None,
help='The ca cert of external HTTP Serve... | f2edbc2dbbfdb438198e6f6bb8edba6400982ef0 | 40,676 |
def test_batch_execution_of_gradient_tf(device, shots, mocker):
"""Test that the output of a parallelized execution of batch circuits to evaluate the
gradient is correct in comparison to default.qubit when using the tf interface."""
tf = pytest.importorskip("tensorflow", minversion="2.4")
qubits = 2
... | 385c5dbfebf99f1f7e471d39f394fac53918c859 | 40,677 |
def get_glconfig():
"""Returns a GLConfig to be used for OpenGL widgets initialisation."""
global __old_glconfig
if __old_glconfig == None:
# Query the OpenGL extension version.
# Configure OpenGL framebuffer.
# Try to get a double-buffered framebuffer configuration,
# if no... | c09ebcdca7aca7cb9338b8b79ce6b0e8449c6415 | 40,678 |
import uuid
from typing import Literal
import requests
def newOrder(idProds):
"""
Creates a new order with the idProd
:return:
"""
product_ids = idProds.split(',')
order_id = uuid.uuid4()
order = agn['order_' + str(order_id)]
graph_message = Graph()
graph_message.add((order, RDF.t... | 7d2c4c485862feed495fff0cde5571110f61ac70 | 40,679 |
def Demographic_Parity(pred_labels, true_labels, groups, priv_group=None):
"""
A fair algorithm would have an equal rate of positive outcomes :math:`(\\hat{Y}=1)` in privileged group :math:`(A=0)` and unprivileged groups :math:`(A=1)`.
:math: :math:`P(\\hat{Y} = 1|A=0) = P(\\hat{Y} = 1|A=1)`
:return:... | 7dfecac35b8241404520dba17718716cbbca7cc8 | 40,680 |
def decode(k, key_length):
"""
Decodes a klv message
"""
key = k[:key_length]
val_length, ber_length = decode_ber(k[key_length:])
value = k[key_length + ber_length : key_length + ber_length + val_length]
return key, value | b5be5af3425fbb36958695d0620d4ab489f232ff | 40,681 |
def maybe_copy(arr):
"""Decide if we should make a copy of an array in order to release memory.
NumPy arrays may be views into other array objects, by which a small array can
maintain a persistent pointer to a large block of memory that prevents it from
being garbage collected. This can quickly lead to memory ... | 8d2837fdcfe20a3a735d2a2a630fdc1ea7f719d7 | 40,682 |
from typing import List
def bmeow_to_bio(tags: List[str]) -> List[str]:
"""Convert BMEOW tags to the BIO format.
Args:
tags: The BMEOW tags we are converting
Raises:
ValueError: If there were errors in the BMEOW formatting of the input.
Returns:
Tags that produce the same sp... | 883f93eca51fb83f97daa5a46832d7efb805044a | 40,683 |
def signature(word: str) -> str:
"""Return a word sorted
>>> signature("test")
'estt'
>>> signature("this is a test")
' aehiisssttt'
>>> signature("finaltest")
'aefilnstt'
"""
return "".join(sorted(word)) | a17e006dcd9f55cfc57d7cd0140489c7be518dc7 | 40,684 |
def decision_tree(tree, inputs, method="predict", value_transform=None):
"""
Creates a SKAST expression corresponding to a given SKLearn Tree object.
Kwargs:
inputs: a list of AST nodes to be used as inputs to the model.
method: 'predict' (for classifier and regressor models),
... | 1bdb366edc5550c70ccec711032bfd3e1bb2e0ad | 40,685 |
import itertools
def plot_spark_error(xdat,ydat, error, filename='plot.eps', save=True, show=False, color='#47d147'):
"""Generic plotting function for (multiple) xy datasets.
Based on matplotlib spark_line function defined here:
https://markhneedham.com/blog/2017/09/23/python-3-create-sparklines-using-mat... | 775f2b563d5f8b238d5d20769eaf5ed7161fe1d3 | 40,686 |
def get_object(bucket: str, key: str) -> bytes:
"""Gets the object at key in the passed bucket
Wraps the Acquire get_object function
Args:
bucket: Bucket containing data
key: Key for data in bucket
Returns:
bytes: Object from store
"""
return ObjectStore.get_object(buck... | 073d48c7134c3dce60e57c8d70a8debb91bd58ec | 40,687 |
def get_radius(box, element, dr, n=1, ratio=0.5):
"""Get the radius of a bubble.
Radius is determined to be r with closest value of n_element / n_atoms
to ratio, i.e. within radius, n_element / n_atoms should be as close to
ratio as possible.
n specifies number of radiuses to return, i.e. n radiuses... | 85cb05f81a2ae70f230ec1be385a6f6f0acd480e | 40,688 |
def _get_extra_price_id(items, key_name, hourly, location):
"""Returns a price id attached to item with the given key_name."""
for item in items:
if not utils.lookup(item, 'keyName') == key_name:
continue
for price in item['prices']:
if not _matches_billing(price, hourl... | d9ba4bcdc50b2bb79d2e284a98a733cd6b65adb7 | 40,689 |
from typing import Generator
from typing import Dict
def test_validate_generator():
"""Test that generator replacement for validation in config doesn't
actually replace the returned value."""
@my_registry.schedules("test_schedule.v2")
def test_schedule():
while True:
yield 10
... | c65d67a65420ce2463905b9dc14397f996e5f107 | 40,690 |
def plot_det_label(image, anno, labels):
""" 目标检测类型生成标注图
Args:
image: 图片路径
anno: 图片标注
labels: 图片所属数据集的类别信息
"""
catid2color = {}
img = cv2.imread(image)
img, scale_value = resize_img(img)
tree = ET.parse(anno)
objs = tree.findall('object')
color_map = get_colo... | 99885b7677533c2cb6da4194d68687e28eee28de | 40,691 |
def getHeaders(lst, filterOne, filterTwo):
"""
Find indexes of desired values.
Gets a list and finds index for values which exist either in filter one or filter two.
Parameters:
lst (list): Main list which includes the values.
filterOne (list): A list containing values to find indexes of in the main list... | 0aa3612b15114b0e0dcdf55eb3643df58157239b | 40,692 |
def get_binary_clf_scores(y_true, y_pred, y_score=None,
sample_weight=None, level=1):
"""
Scores a binary classifiers.
Parameters
----------
y_true: array-like, (n_samples, )
The ground truth labels.
y_pred: array-like, (n_samples, )
The predicted labe... | de9a66be676e308894ec9e7e7cb1d6401f37c73f | 40,693 |
def historylog_with_tab(historylog, mocker, monkeypatch):
"""Return a fixture for a history log with one tab.
The base history log is a plugin widget. Within the plugin widget,
the method add_history creates a tab containing a code editor
for each history file. This fixture creates a history log with... | 0da05ee2f7831771984b9eab4a727a6378929256 | 40,694 |
from bs4 import BeautifulSoup
from datetime import datetime
def get_audio_uris(uri):
"""
Fetches HTML of a File page and returns an array of URIs to the audio files on that page
:param uri: URI to a File page full of audio players
:return: A list of dictionaries with the date, index, and ... | 268b2fea021f6a0e6f757194b38ef0c0ae2aa192 | 40,695 |
def overlap_compress(X, n_components, window_size):
"""
Overlap (at 50% of window_size) and compress X.
Parameters
----------
X : ndarray, shape=(n_samples,)
Input signal to compress
n_components : int
number of DCT components to keep
window_size : int
Size of wind... | c449f8f0ec4241aa70d058aed4aeab8e19ae49e0 | 40,696 |
def get_total_count(query):
"""Get count of all objects in the query."""
with benchmark("Apply limit: apply_limit > query_count"):
# Note: using func.count() as query.count() is generating additional
# subquery
# query.count() has a bug and it returns incorrect number of objects
count_q = query.stat... | 82fe88f08e5ecf41203188ab2e5f756102395766 | 40,697 |
import array
def lcsubstrings(seq1, seq2, positions=False):
"""Find the longest common substring(s) in the sequences `seq1` and `seq2`.
If positions evaluates to `True` only their positions will be returned,
together with their length, in a tuple:
(length, [(start pos in seq1, start pos in seq2)..])
Other... | 3241de831be64334cac21c2bc2a3ac8e2a5d5443 | 40,698 |
def n_max_numbers(in_iter, n=2):
"""Get N maximal numbers from iter.
>>> n_max_numbers([])
[]
>>> n_max_numbers([1, 2, 3])
[2, 3]
>>> n_max_numbers([4, 2, 3])
[3, 4]
>>> n_max_numbers([1, 2, -1, 0], 3)
[0, 1, 2]
"""
max_numbers = list()
for number in in_iter:
... | 5cac858891f3c76d51bda473a743ab9700db334c | 40,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.