content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def is_mismatch_before_n_flank_of_read(md, n):
"""
Returns True if there is a mismatch before the first n nucleotides
of a read, or if there is a mismatch before the last n nucleotides
of a read.
:param md: string
:param n: int
:return is_mismatch: boolean
"""
is_mismatc... | 1e41c67e29687d93855ed212e2d9f683ef8a88d7 | 3,644,836 |
from typing import Dict
def get_county() -> Dict:
"""Main method for populating county data"""
api = SocrataApi('https://data.marincounty.org/')
notes = ('This data only accounts for Marin residents and does not '
'include inmates at San Quentin State Prison. '
'The tests timeser... | 62fd267141e3cdcb3f5b81b78be2aafb1322335b | 3,644,837 |
import traceback
def address_book(request):
"""
This Endpoint is for getting contact
details of all people at a time.
We will paginate this for 10 items at a time.
"""
try:
paginator = PageNumberPagination()
paginator.page_size = 10
persons = Person.objects.all()
... | 88ec5613a7433128a2d06665319a6e3fd83f870f | 3,644,839 |
def decrement_items (inventory, items):
"""
:param inventory: dict - inventory dictionary.
:param items: list - list of items to decrement from the inventory.
:return: dict - updated inventory dictionary with items decremented.
"""
return add_or_decrement_items (inventory, items, 'minus') | 253339e3a8f9ff49e69372dc99d8b8f626a3b98b | 3,644,840 |
def global_ave_pool(x):
"""Global Average pooling of convolutional layers over the spatioal dimensions.
Results in 2D tensor with dimension: (batch_size, number of channels) """
return th.mean(x, dim=[2, 3]) | 3f681e39041762ee2ca8bc52c542952eebd9b97c | 3,644,841 |
import operator
def get_output(interpreter, top_k=1, score_threshold=0.0):
"""Returns no more than top_k classes with score >= score_threshold."""
scores = output_tensor(interpreter)
classes = [
Class(i, scores[i])
for i in np.argpartition(scores, -top_k)[-top_k:]
if scores[i] >= score_thresho... | 69c4e956cee796384fa74d12338f3fb2cc90ba31 | 3,644,843 |
def bag_of_words_features(data, binary=False):
"""Return features using bag of words"""
vectorizer = CountVectorizer(
ngram_range=(1, 3), min_df=3, stop_words="english", binary=binary
)
return vectorizer.fit_transform(data["joined_lemmas"]) | 55ed963df31c2db79eaab58b585ad264a257c241 | 3,644,844 |
import time
def duration(func):
"""
计时装饰器
"""
def wrapper(*args, **kwargs):
print('2')
start = time.time()
f = func(*args, **kwargs)
print(str("扫描完成, 用时 ") + str(int(time.time()-start)) + "秒!")
return f
return wrapper | c55a941574a92cbe70c9b265eaa39563b91ab45a | 3,644,845 |
def enumerate_assignments(max_context_number):
"""
enumerate all possible assignments of contexts to clusters for a fixed
number of contexts. Has the hard assumption that the first context belongs
to cluster #1, to remove redundant assignments that differ in labeling.
:param max_context_number:... | 881723e2ca6a663821979a9029e03bb4f35195dc | 3,644,846 |
def KL_monte_carlo(z, mean, sigma=None, log_sigma=None):
"""Computes the KL divergence at a point, given by z.
Implemented based on https://www.tensorflow.org/tutorials/generative/cvae
This is the part "log(p(z)) - log(q(z|x)) where z is sampled from
q(z|x).
Parameters
----------
z : (B, N... | 6d509607b3d4d6c248544330af06f2ef92fc3739 | 3,644,847 |
def get_order_discrete(p, x, x_val, n_full=None):
""" Calculate the order of the discrete features according to the alt/null ratio
Args:
p ((n,) ndarray): The p-values.
x ((n,) ndarray): The covaraites. The data is assumed to have been preprocessed.
x_val ((n_val,) ndarray): All possible... | de8f05d7a882c2917e618bf315a45969f55dbd16 | 3,644,848 |
def _read_txt(file_path: str) -> str:
"""
Read specified file path's text.
Parameters
----------
file_path : str
Target file path to read.
Returns
-------
txt : str
Read txt.
"""
with open(file_path) as f:
txt: str = f.read()
return txt | 5f0657ee223ca9f8d96bb612e35304a405d2339e | 3,644,849 |
def dedupe(entries):
"""
Uses fuzzy matching to remove duplicate entries.
"""
return thefuzz.process.dedupe(entries, THRESHOLD, fuzz.token_set_ratio) | d5d56f2acc25a107b5f78eefc4adc71676712f98 | 3,644,851 |
import binascii
def generate_openssl_rsa_refkey(key_pub_raw, # pylint: disable=too-many-locals, too-many-branches, too-many-arguments, too-many-statements
keyid_int, refkey_file,
key_size, encode_format="", password="nxp",
... | ca3acdcf4fe615378f2f7088d015a7acbc58b7ff | 3,644,852 |
import select
async def fetch_ongoing_alerts(
requester=Security(get_current_access, scopes=[AccessType.admin, AccessType.user]),
session=Depends(get_session)
):
"""
Retrieves the list of ongoing alerts and their information
"""
if await is_admin_access(requester.id):
query = (
... | 721deaac7cca5f6589417f07d66a83111a062134 | 3,644,853 |
def breweryBeers(id):
"""Finds the beers that belong to the brewery with the id provided
id: string
return: json object list or empty json list
"""
try:
# [:-1:] this is because the id has a - added to the end to indicate
# that it is for this method, removes the last charact... | f2d8824ad49ffeeec68077cb5e0ed143f4603d4e | 3,644,854 |
def min_max_date(rdb, patient):
""" Returns min and max date for selected patient """
sql = """SELECT min_date,max_date FROM patient WHERE "Name"='{}'""".format(patient)
try:
df = pd.read_sql(sql, rdb)
min_date, max_date = df['min_date'].iloc[0].date(), df['max_date'].iloc[0].date()
ex... | 7f08f42bd7dd9742bef300f5f7009807e47b7f23 | 3,644,855 |
def integrate(f, a, b, N, method):
"""
@param f: function to integrate
@param a: initial point
@param b: end point
@param N: number of intervals for precision
@param method: trapeze, rectangle, Simpson, Gauss2
@return: integral from a to b of f(x)
"""
h = (b-a)/(N)
if method == "... | e716733160fd46943de3518e573215b3cf058113 | 3,644,856 |
def sum_naturals(n):
"""Sum the first N natural numbers.
>>> sum_naturals(5)
15
"""
total, k = 0, 1
while k <= n:
total, k = total + k, k + 1
return total | 0ef1ff7e8f0f2df522c73d6d4affc890ba4ad2fa | 3,644,857 |
def load_data(data_map,config,log):
"""Collect data locally and write to CSV.
:param data_map: transform DataFrame map
:param config: configurations
:param log: logger object
:return: None
"""
for key,df in data_map.items():
(df
.coalesce(1)
.write
.csv(f'{co... | 2b690c4f5970df7f9e98ce22970ce3eb892f15bc | 3,644,858 |
import logging
def _filter_credential_warning(record) -> bool:
"""Rewrite out credential not found message."""
if (
not record.name.startswith("azure.identity")
or record.levelno != logging.WARNING
):
return True
message = record.getMessage()
if ".get_token" in message:
... | bc9d2a96ccadfbdb297af86bbdf0f80ab8d2dafa | 3,644,860 |
import importlib
def import_module_from_path(mod_name, mod_path):
"""Import module with name `mod_name` from file path `mod_path`"""
spec = importlib.util.spec_from_file_location(mod_name, mod_path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod | 18891db514b4f1e41bce6de69f5b66fbf51d06e5 | 3,644,861 |
def preprocessing(text, checkpoint_dir, minocc):
"""
This time, we cannot leave the file as it is. We have to modify it first.
- replace "\n" by " \n " -> newline is a word
- insert space between punctuation and last word of sentence
- create vocab, but only for those words that occur more than once... | f3dd597ac144d1c52ca2a65852ef59f2cee63d8b | 3,644,862 |
def dwave_chimera_graph(
m,
n=None,
t=4,
draw_inter_weight=draw_inter_weight,
draw_intra_weight=draw_intra_weight,
draw_other_weight=draw_inter_weight,
seed=0,
):
"""
Generate DWave Chimera graph as described in [1] using dwave_networkx.
Parameters
----------
m: int
... | cec6232d1f3413b6cedd74d909e8d9fa03d9b43f | 3,644,863 |
def extract_first_value_in_quotes(line, quote_mark):
"""
Extracts first value in quotes (single or double) from a string.
Line is left-stripped from whitespaces before extraction.
:param line: string
:param quote_mark: type of quotation mark: ' or "
:return: Dict: 'value': extracted value;
... | 4f614cbbb3a1a04ece0b4da63ea18afb32c1c86b | 3,644,864 |
def dynamic(graph):
"""Returns shortest tour using dynamic programming approach.
The idea is to store lengths of smaller sub-paths and re-use them
to compute larger sub-paths.
"""
adjacency_M = graph.adjacency_matrix()
tour = _dynamic(adjacency_M, start_node=0)
return tour | 06d1adcadc6456aa29a7c0d176329f9d1569bf58 | 3,644,865 |
import yaml
def read_login_file():
"""
Parse the credentials file into username and password.
Returns
-------
dict
"""
with open('.robinhood_login', 'r') as login_file:
credentials = yaml.safe_load(login_file)
return credentials | 16ef8a74c9523ac0809e80995069c3bbc0e8f8c0 | 3,644,866 |
def flatten(ls):
"""
Flatten list of list
"""
return list(chain.from_iterable(ls)) | afab4515644ce340a73f5a5cf9f97e59fa8c4d7e | 3,644,867 |
def gaussian_kernel(size, size_y=None):
""" Gaussian kernel.
"""
size = int(size)
if not size_y:
size_y = size
else:
size_y = int(size_y)
x, y = np.mgrid[-size:size+1, -size_y:size_y+1]
g = np.exp(-(x**2/float(size)+y**2/float(size_y)))
fwhm = size
fwhm_aper = photut... | 6752c4fc9355507d3b411515b8c687dc02b81d2b | 3,644,868 |
from typing import Any
def parse_property_value(prop_tag: int, raw_values: list, mem_id: int = 0) -> Any:
"""
Parse property raw values
:param prop_tag: The property tag, see 'PropertyTag' enum
:param raw_values: The property values
:param mem_id: External memory ID (default: 0)
"""
if pr... | fc8d54a3f8b8ca762acdc5f6123749236e4eaeb3 | 3,644,869 |
from typing import Optional
from typing import Iterator
from typing import List
from typing import Tuple
def scan_stanzas_string(
s: str,
*,
separator_regex: Optional[RgxType] = None,
skip_leading_newlines: bool = False,
) -> Iterator[List[Tuple[str, str]]]:
"""
.. versionadded:: 0.4.0
Sc... | f68694ce344b738f23b689b74d92f7ab4c20b237 | 3,644,870 |
def format_dependency(dependency: str) -> str:
"""Format the dependency for the table."""
return "[coverage]" if dependency == "coverage" else f"[{dependency}]" | 981a38074dbfb1f332cc49bce2c6d408aad3e9e2 | 3,644,871 |
def _addSuffixToFilename(suffix, fname):
"""Add suffix to filename, whilst preserving original extension, eg:
'file.ext1.ext2' + '_suffix' -> 'file_suffix.ext1.ext2'
"""
head = op.split(fname)[0]
fname, ext = _splitExts(fname)
return op.join(head, fname + suffix + ext) | 2fc0a16f6f8b8be1f27fd7ff32673ed79f84fccb | 3,644,872 |
import re
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'([\+>... | 8bb0ecaa9b2a2e9ce41882b8f140442f28f3c922 | 3,644,873 |
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 ... | 54777fe767075561cbb20c3e7ab88ca209fa8c87 | 3,644,875 |
import tqdm
import operator
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 sorte... | 57d9c5012341acf89e92ffd6df29688af5d6965f | 3,644,876 |
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):... | 48b62b2814f67b66823fc1c35024eaab6cde7591 | 3,644,877 |
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(... | 5d5697ce9a7916920c938a3cff17fdeda8b5f81b | 3,644,878 |
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... | 80e01568cc5fe2ab2c7d11bdd642906374992985 | 3,644,879 |
from datetime import datetime
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... | 4ffa01c2d6682a6320870ac158f564c37aa5a32e | 3,644,880 |
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... | 544aaa734858209c36c84d87bb6beb05761a5194 | 3,644,881 |
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 | 6ed5e4ca426cc61d25dd272f92ba9220186bfd8e | 3,644,882 |
def plot(ax, x, y):
"""Plot """
return ax._plot(x, y) | 90cc2616d21e3c1239524437f653f85602c1984b | 3,644,883 |
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... | 3e138e84db9650af3afbbab4d904dc3a4cb581c9 | 3,644,884 |
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 ... | 09e0775213e4a32f1ea786ad9d1184e7f4dbd7cf | 3,644,885 |
from typing import Sequence
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 th... | b1c4040b216162777e33bbbab0f7774b8b02af91 | 3,644,886 |
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) | 19bc51a648ac558f524f29744e1574a245e50cf2 | 3,644,887 |
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... | c3cac75de48e2c2a9af30ce427bc57d86a56dbc4 | 3,644,889 |
import cupy
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 resamp... | 34a949250239b5334650b89d6566b81460079591 | 3,644,890 |
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) | ae16aff476842c8e0fc2fa2506b68ad60dc603f0 | 3,644,891 |
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... | 1fe73425cb30f0f6fbce6caa740f118ee9591347 | 3,644,892 |
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]) | edf4605c1dd9ad45d3a2508122b85213657f56cb | 3,644,893 |
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... | dae13aa0a10db2133f87c399ec90113ef157a210 | 3,644,894 |
import select
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... | 7fbf296377fb1e4e59b7c9884c6191ff2b0a273b | 3,644,895 |
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) !=... | 827506de7e572b1df1b210ccfb990db5839b5273 | 3,644,896 |
import json
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))
ret... | 686f9298302d30e89ad0d34ed4c0c96d22fd455d | 3,644,898 |
import json
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... | 7164d7f19b14ef601480484d6182f4b62cc250bf | 3,644,899 |
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))
# http:... | 6b364a74c86337108d21539c4a5678af2e6ea48a | 3,644,900 |
import json
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((... | b31128db57ca99a840d4adce6f3116f629d8a0b8 | 3,644,901 |
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... | 74e1e619cc8c4a3201e41820f5f641c651a5f283 | 3,644,903 |
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 | bc44118e871e977a7ecb6a877f7232b837d1bf0e | 3,644,904 |
import typing
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... | ccfc64e54fae868877c6852ebeeadae11bb1221b | 3,644,906 |
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... | 2a3c0c42ee5c541d19bbe695c12f977fd29dfeaf | 3,644,907 |
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 | 4544a0ee292cb4e323c31545009c4d1e17ca98e1 | 3,644,908 |
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... | 1821509506ad31dcdb21f07a2b83c544ff3c3eb3 | 3,644,909 |
from pathlib import Path
import re
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"))... | 3587b849132e4b2eeb6ad184bf58755340473bd9 | 3,644,910 |
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... | d6602078a458fa3f36de3558c8044749caf7f4d5 | 3,644,912 |
from datetime import datetime
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 algo... | ea416fcdc09c71aef56250a8e0b7f558e8e8a884 | 3,644,913 |
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... | a7a1383708c1b6e69c975488b03704698f9b1066 | 3,644,914 |
import colorsys
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... | 4417ce8468e71b7139b57fe270809c7030b2c3df | 3,644,915 |
import itertools
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(itertool... | 59fd932f3906eb411e21207d920f752f7f78df44 | 3,644,917 |
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... | 291f091d06aa768ceb28f2738823f5eeb336c47e | 3,644,918 |
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... | de63af1b649e450214907dd704bde782820d393d | 3,644,919 |
import six
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:
... | 893986e69f6d64167f45daf30dacb72f4b7f2bff | 3,644,920 |
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... | 07c01610f800202ccbdebf834648840b77d47fb7 | 3,644,922 |
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) + \
n... | 6fa53b3f1a0472f45fa59c11b5d869786b5a9f4f | 3,644,923 |
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 % ... | 139b9328190f61a1cd649826bfde806e565d4201 | 3,644,924 |
from typing import Tuple
from typing import Iterable
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.
... | c3d93d459c9b004d199725b11e1b92340e6154b9 | 3,644,925 |
import math
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 - ... | ebef7d773eeb400ef87553fc5838ee2cb97d0669 | 3,644,926 |
from typing import Optional
import this
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:... | d2e539c97a4946f819616d0f596e68e190a68c78 | 3,644,927 |
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... | bddc8da985c7e252effe566c640bca25acd01d6a | 3,644,928 |
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. ... | ca54dc948923826bb81af94e41be42caadfe6004 | 3,644,929 |
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) | c7a8cc806b552b1853eba1d8223aa00225d5539e | 3,644,930 |
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... | a5ee460f57912bb885ae0cb534f6195c92983aad | 3,644,931 |
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 ... | d93d319b84c02b8156c5bad0998f5943a5bbe8ae | 3,644,932 |
from typing import Mapping
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 | 87c8b82bceab0252204ababf842ca0b00ab6a059 | 3,644,933 |
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)) | 9946b8929211df4624ecc201ce026b981ffb3d0c | 3,644,934 |
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... | f132eaa4077dd197faed72d6805f15255b7dd680 | 3,644,935 |
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... | 3e8224a3f48eade9ee01a43819b4c6aa88ef308e | 3,644,936 |
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... | 67827220cdbdd41250a8a40f140c8c21e0625df7 | 3,644,937 |
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... | 99ee42abf95bd338714e42beee42610e3ac2f09d | 3,644,938 |
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... | d4693e41c755dd1067c371bfa740ce1436dfc85a | 3,644,939 |
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:
... | 6f00c8df9e5fb42f4e3fb01744215214e732f441 | 3,644,940 |
def get_piesocket_api_key():
"""
Retrieves user's Piesocket API key.
Returns:
(str) Piesocket API key.
Raises:
(ImproperlyConfigured) if the Piesocket API key isn't specified in settings.
"""
return get_setting_or_raise(
setting="PIESOCKET_API_KEY", setting_str="PieSoc... | 657bba650a914ed1a15d54b9d0000f37b99568d0 | 3,644,942 |
def downsample(myarr,factor,estimator=np.mean):
"""
Downsample a 2D array by averaging over *factor* pixels in each axis.
Crops upper edge if the shape is not a multiple of factor.
This code is pure numpy and should be fast.
keywords:
estimator - default to mean. You can downsample by sum... | 45b6422cb7f9b01512bc4860229164b043201675 | 3,644,943 |
def getActiveWindow():
"""Returns a Window object of the currently active Window."""
# Source: https://stackoverflow.com/questions/5286274/front-most-window-using-cgwindowlistcopywindowinfo
windows = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListExcludeDesktopElements | Quartz.kCGWindowListOptionOn... | ca1c810525f0a49cd9f4b53d0d621cb39b3b733e | 3,644,944 |
def _derivative_log(x):
"""Chain rule on natural log = (1/x)*(dx/dr)"""
return _protected_inverse(x[0])[:, :, np.newaxis, np.newaxis]*x[1] | 5f4bf5416575126cd93adaee6ccfca942ad6218f | 3,644,945 |
def svn_wc_merge_props(*args):
"""
svn_wc_merge_props(svn_wc_notify_state_t state, char path, svn_wc_adm_access_t adm_access,
apr_hash_t baseprops, apr_array_header_t propchanges,
svn_boolean_t base_merge,
svn_boolean_t dry_run, apr_pool_t pool) -> svn_error_t
"""
return _wc.svn_w... | 54187e010f71798bee90eb179a10da11bf410fce | 3,644,946 |
def is_paused():
"""
Return True if is_paused is set in the global settings table of the database.
"""
try:
is_paused_val = Settings.objects.get().is_paused
except ObjectDoesNotExist:
is_paused_val = False
return is_paused_val | 59b99d4a4842e14205376d7923d3e5c8b52c30a6 | 3,644,947 |
import itertools
def get_accurate(clustering_res_df, cluster_number, error=False):
"""
:param clustering_res_df: a pandas DataFrame about clustering result
:param cluster_number: the number of the cluster
(the first column is the index,
the second column is the right information,
the third col... | 7ba71bcd82e70d9344994f9b6a2133676d58f683 | 3,644,949 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.