content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def bold_viewed(val, viewed_pages):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
weight = 'bold' if val in viewed_pages else 'normal'
return 'font-weight: %s' % weight | f7cbe6b3d3736926841941dfbc8cc4595a1eda62 | 3,615,900 |
def cut_map_chunks(c):
"""
Cut a map into many chunks based on the chunk_size variable (note_group_size).
"""
r = [];
for i in range(0, (c.shape[0] - chunk_size) // step_size):
chunk = c[i * step_size:i * step_size + chunk_size];
r.append(chunk);
return tf.stack(r); | 471b8287c076a3994a6e8f61f9d1f2c2870f3aad | 3,615,901 |
def get_state_cmds(cmds):
"""Get the state-changing commands need to create LOAD_EVENT OBS commands.
:param cmds: CommandTable of input commands.
:returns: CommandTable of state-changing commands.
"""
state_tlmsids = [
'AOSTRCAT',
'COAOSQID',
'AOMANUVR',
'AONMMODE',
... | e79c74bff735304e0d6c856ec6f0be310fc9b8d5 | 3,615,902 |
def get_grid_search(X, y):
"""
Perform Grid Search on dataset with SVM classifier.
:param X:
:param y:
:return: the C_range and gamma_range of the search, then the GridSearch obj itself
"""
C_range = np.logspace(-1, 5, 7)
gamma_range = np.logspace(-6, 2, 9)
param_grid = dict(gamma=... | 3f60553e1c65e41c6ef4df326c0df30d9c01234f | 3,615,903 |
def get_can_reach_set(n, reach_dic, max_trip_duration=150):
"""Return the set of all nodes whose trip to node n takes
less than "max_trip_duration" seconds.
Arguments:
n {int} -- target node id
reach_dic {dict[int][dict[int][set]]} -- Stores the node ids whose distance to n
is w... | f422db246ac926c8d0e2144ef42c09ba06b8a488 | 3,615,904 |
def n4_bias_field_correction(img, mask=None, shrink_factor=4,
convergence={'iters':[50,50,50,50], 'tol':1e-07},
spline_param=200, verbose=False, weight_mask=None):
"""
N4 Bias Field Correction
"""
iters = convergence['iters']
tol = convergenc... | 4a9481b0844f7ca3fe7c74375158d2359d901a4a | 3,615,905 |
def normaliseContinuum(spec):
"""
Based on example.py
normalize_whole_spectrum_strategy1_ignoring_prefixed_strong_lines function
"""
model = 'Splines'
degree = 2
nknots = None
from_resolution = INSTRUMENT['RESOLUTION']
# continuum fit
order = 'median+max'
median_wave_range =... | 6912e3f0ae405d257bef2b337389632d54cf937d | 3,615,906 |
def buildOCSPRequest(*reqs, **kwargs):
"""
reqs
(cert, serial), ...
kwargs
'nonce'
True to generate a nonce
:return:
OCSPRequest object
"""
ocspBuilder = OCSPRequestBuilder()
for c, serial in reqs:
ocspBuilder.addRequest(c, int(serial))
if 'non... | e1e09c8b6345b1afeedd5fe099452d527b275b00 | 3,615,907 |
def get_functional_model(config):
"""Construct keras functional model from Galaxy tool parameters
Parameters
-----------
config : dictionary, galaxy tool parameters loaded by JSON
"""
layers = config['layers']
all_layers = []
for layer in layers:
options = layer['layer_selection... | 61ccfb09163806bd400e7af13339f6a29e1287ad | 3,615,908 |
import math
def get_carpet(parameterized_line, distance, step):
"""
Return M x N x 2 numpy array.
It contains the centers of the ParameterizedLine, but perpendicularly
repeated by step along the normals to the segments of the
ParameterizedLine, until distance is reached.
"""
# length must... | 9968206598e878319b613864797a8e74dbc2d523 | 3,615,909 |
def freq_to_band(freq):
"""converts a Frequency [kHz] into the band and mode according to the IARU bandplan
Args:
frequency (float): Frequency in kHz
Returns:
dict: Dictionary containing the band (int) and mode (str)
Raises:
KeyError: Wrong frequency or... | ddc34dd2f418e47d8a7b8ec5842d0b34a6f420be | 3,615,910 |
from kkpmx_core import from_vertices_get_faces
from sympy import Plane
def __find_sign_against_plane(pmx, old_vert, new_vert, mat_idx, moreinfo):
"""
Find all faces that contain [old_vert] and look if [new_vert] is in front of at least one of them.
"""
new_point = pmx.verts[new_vert].pos
if moreinfo: print("Find... | d295cfabcfa374b1d3768b6b91fc9a22ce0991ab | 3,615,911 |
def create_empty_gid_matrix(width, height):
"""Creates a matrix of the given size initialized with all zeroes."""
return [[0] * width for row_index in range(height)] | 8f1a0adf9e45bb6fc267a5cec3079657dbace51d | 3,615,912 |
def random_noise_levels() -> tuple:
""" Generates random noise levels from a log-log
linear distribution.
"""
log_min_shot_noise = np.log(0.0001)
log_max_shot_noise = np.log(0.012)
log_shot_noise = np.random.uniform(log_min_shot_noise, log_max_shot_noise)
shot_noise = np.exp(log_shot_no... | 28524817cb507967d797201f6ef4361b6abb12c3 | 3,615,913 |
def _read_signing_keys(key_filename):
"""Reads the given file as a WIF formatted key.
Args:
key_filename: The filename where the key is stored.
Returns:
tuple (str, str): the public and private key pair
Raises:
CliException: If unable to read the file.
"""
filename = ... | ae45f8928b137b7a040451d1b0bc88d6e02e3cda | 3,615,914 |
import random
def load_mosaic(self, index):
"""
concatenate four images into one mosaic image
:param self:
:param index: the index of requied images
:return:
"""
# loads images in a mosaic
labels4 = [] # concatenate the labels
s = self.img_size
# choose a random center point ... | 926820114fd393faa8436798e2e8b85e0386c073 | 3,615,915 |
from typing import List
from typing import Any
def placeholder_imputer(df: pd.DataFrame,
columns_to_impute: List[str],
placeholder_value: Any = -999) -> LearnerReturnType:
"""
Fills missing values with a fixed value.
Parameters
----------
df : pand... | de4280f4c8d292440a70f3c238bd3c7e12dcd6af | 3,615,916 |
from datetime import datetime
def query_token(token, session=None):
"""
Validate an authentication token using the database. This method will only be called
if no entry could be found in the according cache.
:param token: Authentication token as a variable-length string.
:param session: The datab... | 366058f59f2ad0142a60bce567efa881eb3ac5e8 | 3,615,917 |
def value_to_none_low_medium_high(confidence_value):
"""
This method will transform an integer value into the None / Low / Med /
High scale string representation.
The scale for this confidence representation is the following:
.. list-table:: STIX Confidence to None, Low, Med, High
:header-... | ac3b39ae12591408fca2f8b4e844b535e7b1aaa3 | 3,615,918 |
def _decrypted_todolist_protobuf(pb):
"""Args: pb: bytes; Returns the serialized bytes of a pyatdl_pb2.ChecksumAndData."""
# We should never see InvalidToken. If we see it, let it become a 500.
try:
return _protobuf_fernet().decrypt(pb)
except InvalidToken:
_debug_log('Invalid encrypted pb')
raise | fb2f285566411a7398b76ebd74583fae196dd352 | 3,615,919 |
from datetime import datetime
import re
def get_disc_df(date, filepath, offset=60):
"""[summary]
Returns:
dataframe:
"""
def fix_timestamp(x):
if ".500" in str(x):
return datetime.strptime(str(x)[0:19], "%Y-%m-%d %H:%M:%S")
else:
return x
disc_df ... | f85d30d48b2b874b84866a89561eefb95a0e8185 | 3,615,920 |
def ping() -> models.Pong:
"""A simple ping/pong endpoint for aliveness checks."""
return models.Pong() | 10a06a20867883df14b131acfbdddf5c67825298 | 3,615,921 |
def split_srf_by_mult_crv(srf,crvs):
""" Split a surface with multiple curves. """
srfb = srf.ToBrep()
faces_ = srfb.Faces[0]
splits = faces_.Split(crvs,TOLER).Faces
split_return = []
for s in splits:
split_return.append(s.DuplicateFace(False))
return split_return | 5e9039e6b7a85042959621c828cd6c21c59da8d1 | 3,615,922 |
def process_detail(hvr_client, hub_name, channel, source, target):
"""
Get all process details
"""
rt = {}
jobs = hvr_client.get_hubs_jobs(hub=hub_name)
for job_name in jobs:
if (
job_name == f"{channel}-activate"
or job_name == f"{channel}-refr-{source}-{targ... | 0a8e2f1bc0f45c1e4854421497bb809c7d8ef457 | 3,615,923 |
def mixed_canonical_full_ret_sv(data_tensor, max_bond_dimension, batch_size_position):
"""
Performs a full mixed canonical MPS decomposition of a pre-partitioned data tensor.
See "The density matrix renormalization group in the age of Matrix Product States" (https://arxiv.org/abs/1008.3477)
pages 43-55... | 4e68172ba61ebbf91d68a11a7548e082d9eef012 | 3,615,924 |
import os
import tarfile
def download_model(url, dest, verbose=True):
"""
Downloads a model from tfhub and unzips it.
The function assumes the format is `.tar.gz`.
"""
if not os.path.exists(dest):
os.makedirs(dest)
fpath = os.path.join(dest, "model.tar.gz")
if not os.path.exists(fp... | ea774b6ee5487a82f2e32c59d32395463d3d0aff | 3,615,925 |
import os
def doclist():
"""List all the documents."""
docs = Document.query.all()
docsd = {d.slug: d for d in docs}
fs = os.listdir(app.config['DOCPATH'])
fs.remove('__ARCHIVE')
docs = []
for d in docsd:
if d not in fs:
_ = docsd[d]
_.status = 0b10
... | d016dcecc714a505347c6402a596f6ef330373a5 | 3,615,926 |
def _get_process_task_request_test_cases():
"""Returns a lit of
targets, send_order, request_client_idx
"""
num_clients = 3
clients = [create_client(name=f"__test_client{i}") for i in range(num_clients)]
return [
[clients, SendOrder.ANY, 0],
[clients, SendOrder.ANY, 1],
... | a22501a241e7a1cf2d62e4f7f11e6e147958ddd7 | 3,615,927 |
def parsebody(body):
"""Parse a message from the server returning a dict."""
data = dict()
lines = body.splitlines()
for line in lines:
equal_ix = line.find('=')
if equal_ix > 0:
key = line[:equal_ix]
data[key] = unquote(line[equal_ix + 1:])
return data | aa35fc7867a9643f00319fb51ebcad124ed94578 | 3,615,928 |
import re
def get_sudoers(machine_name):
"""
This function returns a list of usernames that are sudoers on the machine
passed as a parameter.
"""
machine_name = _unicode_to_str(machine_name)
con = get_binded_connection()
sudoers = con.search_s("%s,%s" % (settings.ADMINS_OU, settings.DC),
... | 16d6d56c8cb497c1d3a9e0686039818f8f272a23 | 3,615,929 |
def get_speakers(data: list, num=3):
"""获取差异大的说话人,说话人之间相互的embed的余弦相似度最大。"""
sim_mat = pairwise_distances(data, metric='cosine')
sim_vec = np.mean(sim_mat, axis=0)
targets = list(range(len(sim_vec)))
idx = np.argmax(sim_vec)
outs = [idx]
targets.remove(idx)
while 1:
sim_vec = np.m... | feee0e648e49f73402889bd4c621c7db08df5344 | 3,615,930 |
import os
def preprocess_documents(tmp_dir, tag_name, url):
"""
Prepares the data to be used by the document generation
:param docs: pandasdataframe
:return:
"""
URL = url
compressed_filename = os.path.basename(URL)
download_path = generator_utils.maybe_download(tmp_dir, compressed_fil... | dda6f93ffa0d54333db23b3b25a89de847497475 | 3,615,931 |
from typing import Iterable
def iterify(x):
"""Return an iterable form of a given value."""
if isinstance(x, Iterable):
return x
else:
return (x,) | 85373e5ac0e03caf2115096088ce92ca27b65b4a | 3,615,932 |
def get_regression_estimate(X, neuron_idx):
"""
Estimates the connectivity matrix using lasso regression.
Args:
X (np.ndarray): our simulated system of shape (n_neurons, timesteps)
neuron_idx (int): a neuron index to compute connectivity for
Returns:
V (np.ndarray): estimated ... | 2e03096d2a5ec59e2c84ab1d7503335e12a7d538 | 3,615,933 |
import numpy
def read_messpf_temps(pf_path):
""" Obtain the temperatures from the MESSPF file
"""
# Obtain the temperatures, remove the 298.2 value
temps, _, _, _ = read_messpf(pf_path)
temps = [temp for temp in temps if not numpy.isclose(temp, 298.2)]
return temps | 71017cb2faa0deca4852e5405297a6d8fc6f819b | 3,615,934 |
def fitsin(fits):
"""Read in a fits file and retun the data
Parameters
----------
fits : str
fits file name to read
Returns
----------
data : np.array
data arry of input fits file
"""
data = pyfits.getdata(fits)
return data | 9a7952986c8fa1aa23f9585b0412ba7a157d7d96 | 3,615,935 |
import os
def get_subfolder(path, subfolder, init=True):
"""
Check if subfolder already exists in given directory, if not, create one.
:param path: Path in which subfolder should be located (String)
:param subfolder: Name of the subfolder that must be created (String)
:param init: Initialize ... | 2109aa0c8e8d402f6ced8437e5399b754d9cbfa9 | 3,615,936 |
def _destination_sample(
primary_purpose,
trips,
alternatives,
model_settings,
size_term_matrix,
skims,
alt_dest_col_name,
estimator,
chunk_size,
trace_label):
"""
Note: trips with no viable destination receive no sample rows
(... | 71eed715bb5a42379656c38ba32486cace21e48c | 3,615,937 |
def zeros(axes=None, dims=None, shape=None, dtype=float):
""" Initialize an array filled with zeros. See empty for doc.
>>> zeros(dims=('time','items'), shape=(2, 3))
dimarray: 6 non-null elements (0 null)
0 / time (2): 0 to 1
1 / items (3): 0 to 2
array([[0., 0., 0.],
[0., 0., 0.]])... | da394c9e25cc1ea10d8b28f83f867ce88ab04ab7 | 3,615,938 |
def get_textcellfont(size, face, color, bold, italic,
uline, vertical, antialiased):
"""テキストセル用のフォントを生成し、
(font, lineheight)を返す。
"""
font = cw.imageretouch.Font(face, -size, bold, italic)
if uline:
font.set_underline(True)
return font, font.get_linesize() | 2dbd45417fc8db17987df78e7b3bf3a84b961568 | 3,615,939 |
import binascii
import os
def choose_boundary() -> str:
"""Random boundary name."""
return binascii.hexlify(os.urandom(16)).decode("ascii") | 6335e14abc34652141e7c77989d60fcb40ec3d17 | 3,615,940 |
def center(E, out=None):
"""
Adjusts the ensemble to zero mean.
"""
u = np.mean(E, axis=1).reshape(E.shape[0], 1)
return np.subtract(E, u, out=out) | 66f8c9f12fb8ab0cb8d8750e18038d7a249b2338 | 3,615,941 |
def load_ignore(fname):
"""Loads patterns signalling lines to ignore
Args:
fname: File name containing patterns
Returns:
A list of patterns
"""
values = []
with open(fname, 'r') as f:
lines = f.readlines()
for line in lines:
values.append(line.rstrip('\n'))
return values | 6a2b4aad3bb4f2747e91a0b1a9a58b70187d1d1e | 3,615,942 |
import sys
def check_path(filename, reporter=modReporter.Default, settings_path=None, **setting_overrides):
"""Check the given path, printing out any warnings detected."""
try:
with open(filename, 'U') as f:
codestr = f.read() + '\n'
except UnicodeError:
reporter.unexpected_err... | b2a5e191146aee3bb6b80a2e926c19f4e87bba52 | 3,615,943 |
import torch
def line_to_tensor(line):
"""
Convert a line to a tensor (line_len x 1 x 57)
:param line: line in string format
:return: tensor in one hot vector
>>> line
>>> 'ツバサ'
>>> tensor
>>> (0 ,.,.) =
>>> Columns 0 to 18
>>> 1 0 0 0 ..
>>> (1 ,.,.) =
>>> Co... | af4f46d142c4267d4e819a8b948990293667d5c2 | 3,615,944 |
def load_output(variable, scenario='p16a_F_Hist_2000', season='annual', apply_sf=True):
"""
Load annual/seasonal data for a specific variable and scenario.
Args:
variable: string of variable name to load (e.g. 'SWCF_d1', or 'FSNTOA+LWCF')
scenario: string scenario (default 'p16a_F_Hist_2000... | d60a9abf893f958dbebc58444086ef9bddcdc455 | 3,615,945 |
import string
def bind(binding, name, mixin_modules=None):
"""Generates a client binding for the resource identified by ``name``, using the resource
definition specified by ``binding``.
:param binding: The resource bundle to bind, specified as either (a) a binding module, either
pre-generated or ... | cfc3c82e7ae1c0869cd8e94c3399b1bf5aef3e7e | 3,615,946 |
import warnings
import collections
import tokenize
import pickle
def build_dictionary(training_datasets, dict_path, params):
"""
Extract vocabulary and build dictionary.
"""
warnings.warn('Start building a new dictionary.')
word_counter = collections.Counter()
for i, dataset in enumerate(tra... | b35d1c646c5d536def2eacaba81dc62f6bd70db2 | 3,615,947 |
def format_status(report_status):
"""
For readability purposes, both failed and
erroneous tests will be displayed as failed.
"""
if report_status in (Status.FAILED, Status.ERROR):
return Status.FAILED.title()
return report_status.title() | ce92f4103853048f63d78461fe228c881135ce8e | 3,615,948 |
def compose_email(in_dict):
"""Composes email to send to attending if tachycardic
If the patient is exhibiting symptoms of tachycardia,
ie an increased heart rate, further action from the
physician might be necessary. As such, the physician
must be notified.
Args:
in_dict (dict): input... | 321e81a3d5e0c8c2f77da3cb5c2667ea68293c88 | 3,615,949 |
def _parse_xtekct_file(file_path):
"""Parse a X-tec-CT file into a dictionary
Only = is considered valid separators
Parameters
----------
file_path : string
The path to the file to be parsed
Returns
-------
string
A dictionary containing ... | 744f67638c50573cfa7d568238b488f12e59217b | 3,615,950 |
def get_on_demand_price(instance_type, region_name):
"""
Get on demand price at current instant of an instance in a
given region
:param instance_type: EC2 instance type
:param region_name: AWS regions name
:return: a floating point number - on demand price
"""
price = ON_DEMAND_PRICES.lo... | 8aafab3df7286b9dcd303f41a673a75011b1df02 | 3,615,951 |
def reportsActionMissingImagesDeactivateProduct(objectId: str):
"""
Deactivate a product with missing images and then redirect back to
the missing images report.
:param objectId: The master product object id.
"""
ok = thk.products.setProductActive(objectId=objectId, active=False)
if ok:
... | 33c963e703bbf58f8926ee3da1d781e4b180f6f5 | 3,615,952 |
def store_math(raw='', html=''):
""" MathFields must be stored in the database as a string containing both
the raw math and html.
Arguments:
* raw: this is your raw math as either LaTeX or just regular text
* html: if you already know the html, there's no sense in calculating it
... | 7cd571f672501274018496c697afc82050ecb05c | 3,615,953 |
from QtExt import QtGui, QtCore
def processAndWriteThumbnailQImage(qImage, options):
"""
Takes a Qimage processes it, and writes it to a file based on the supplied
options (from Manager.thumbnailSpecification), returns the path or an empty
string if the write failed.
"""
## @todo This isn't a good meth... | 03d132f7f4dc1a9ac78b5cb3e9e5db6112b89157 | 3,615,954 |
from typing import Union
def slerp(
t: Union[float, np.ndarray],
v0: Union[float, list, tuple, np.ndarray],
v1: Union[float, list, tuple, np.ndarray],
dot_threshold: float = 0.9995) -> np.ndarray:
"""
Spherical linear interpolation between v0 (starting) and v1 (final) vectors; ... | 00cac708c2cd6f0f8ec7c7540e0da2498b33035b | 3,615,955 |
def removeObstacle(numRows, numColumns, lot):
"""
See shortestMazePath for more info. This is similar to shortestMazePath with
slightly different conditions.
1 <= numRows, numColumns <= 1000
"""
possible_paths = {
'left': [-1, 0],
'right': [1, 0],
'up': [0, 1],
'd... | 2a1d541742b478f1132b01e018a7aed1b9e7493c | 3,615,956 |
def get_defaults(*, local: Namespace = Namespace()) -> Configuration:
"""Constructs arguments from local and system defaults."""
logger.debug(f'core -- Prepairing to build arguments.')
return harvest(local=local, **prepare({'system': DEFAULTS}, MAPPING)) | 20be5ff66268f98f7b3d9bc4f1e6f36359d2d709 | 3,615,957 |
def cmd_ok(cmd) -> bool:
"""Returns True if cmd can be run."""
try:
sp.check_call(cmd, stderr=sp.PIPE, stdout=sp.PIPE)
except sp.CalledProcessError:
# bwa gives return code of 1 with no argument
pass
except FileNotFoundError:
logger.error(f"{cmd} not found, skipping")
... | 27825a996ee6afbbb8f8774997974d0334ac68db | 3,615,958 |
def states():
"""Returns different possible states a VM can have."""
return defer.maybeDeferred( _getController().states ) | c55af0687238934f78a79a69814e592a48cde964 | 3,615,959 |
def validate_email(value):
"""
Validate an email input.
Parameters:
value (any): Input value
Returns:
boolean: True if value has email format or is empty string
"""
return isinstance(value, str) and (email_regex.match(value) or value == "") | e14015361516dbe421ce9f89cb7a5481e71072ab | 3,615,960 |
def random_box_jitter(box, landmarks, ratio=0.05):
"""Randomly jitter bounding box.
Arguments:
box: a float tensor with shape [4].
landmarks: a float tensor with shape [num_landmarks, 2].
ratio: a float number.
The ratio of the box width and height that the corners can jitte... | f39f8157b2ab7b1a911c209435d0057f55e7a89f | 3,615,961 |
def net_revenue(gross_revenue, tax_rate=0.2):
"""Returns total net revenue based on gross revenue and tax rate.
Args:
gross_revenue (float): Gross revenue.
tax_rate (float, optional): Product tax as decimal, i.e. 0.2 for 20% tax. Default is 0.2.
Returns:
net_revenue (float): Total ... | a5f8826fdf71b8c041edb7895fa7e14d1583fcfc | 3,615,962 |
def _read_stimtime_AFNI(stimtime_files, n_C, n_S, scan_onoff):
""" Utility called by gen_design. It reads in one or more stimulus timing
file comforming to AFNI style, and return a list
(size of ``[number of runs \\* number of conditions]``)
of dictionary including onsets, durations and weig... | 5fcda88f9d29606ee2e13e005d9523d58ef88e9c | 3,615,963 |
import itertools
def run_constrained_prim(experiments, y, issignificant=True,
**kwargs):
""" Run PRIM repeatedly while constraining the maximum number of dimensions
available in x
Improved usage of PRIM as described in `Kwakkel (2019) <https://onlinelibrary.wiley.com/doi/full/10.... | 0606189a5d7e175962e750456d66b7e980c3180d | 3,615,964 |
def process_data(data_path='../input/train.csv',
output_name='train'):
"""
"""
spark = SparkSession.builder.getOrCreate()
min_word_TF = 10
min_word_DF = 2
vocabulary_size = 30000
start_time = time.time()
df = spark.read.csv(data_path,
header=True)
df = df.withColumn('new_relevance',df['relevance'].cast... | 983c398c22ac089a8d5ae68a2f0654f93cd83578 | 3,615,965 |
from typing import Union
from typing import List
def _write_caero3(model: Union[BDF, OP2Geom], name: str,
caero_ids: List[int], ncards: int,
op2_file, op2_ascii, endian: bytes, nastran_format: str='nx') -> int:
"""
Aerodynamic panel element configuration.
Word Name Typ... | 0b148589dfcf6665bf1ba7783b8ca4d104a66961 | 3,615,966 |
def isok(num: int):
"""주어진 인수가 0과 1로만 이루어져 있을 경우 참 반환"""
cnv = set(int(n) for n in str(num))
return all(e in {0, 1} for e in cnv) | bb47608695029ef9450b29b7c69c16a00f1032f5 | 3,615,967 |
def ConvertHexadecimalToDecimal (hexadecimal: str) -> int:
"""
Convert hexadecimal string to integer
:type hexadecimal: str
:rtype: int
"""
if not isinstance(hexadecimal, str):
raise Exceptions.IncorrectTypeException(hexadecimal, "hexadecimal", (str,))
return int(hexadecimal, 16) | 63039427df1af6fce4e35c8f7d81ba2acab5bea5 | 3,615,968 |
def from_fig_to_array(fig: plt.Figure) -> np.ndarray:
"""
:param fig: a matplotlib figure that we want to convert to an array
:return: 3D array of the figure
"""
fig.canvas.draw()
image_from_plot = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
image_from_plot = image_from_plot.re... | c74902e029bcc9d5c7a6e8a4827f1c66ddcc596d | 3,615,969 |
import html
def hfDistPlots(update=False):
"""
div for heat flux distribution plots
if update is False, just return an empty div, so that nothing happens on
page load. If update=True, get qDivs and update the plot.
This is called at the end of a HEAT run (runHEAT callback) button click
"""
... | 8701cb0b87982f4fe1b2818ad5587d2f4c5e860c | 3,615,970 |
from typing import Tuple
def get_total_evaluation(pred: np.ndarray, mask: np.ndarray, require_edge:bool=True) -> Tuple:
"""
Get whole evaluation of all metrics
Return Tuple, (value_list, name_list)
"""
gala = get_vi(pred, mask)
if require_edge:
metric_values = [get_pixel_accu... | 9b2a65b3da9669a575b5da3904d6edfabd676b1c | 3,615,971 |
def get_uniques(constraints):
"""Get unique key(s) given constraint list"""
uniques = {}
if constraints:
for name, constraint in constraints.items():
if constraint["type"] == UNIQUE and len(constraint['columns']) == 1:
column = constraint['columns'][0]
uni... | 78125ecadc3989030e900b78c7277d238e9e6b36 | 3,615,972 |
import regex
def query_volumes(entry_link) -> list:
"""
Query volume list from @entry_link
"""
url = f'{BASE_URL}{entry_link}'
page = httpclient.get_page(url)
volumes = regex.multi_match(VOLUME_PATTERN, page)
return [(volume, link) for link, volume in volumes] | f26c71e0da69a773bd7d6fc96415b02c589b5882 | 3,615,973 |
def _compute_R(order, factor):
"""
computes the R matrix with entries
given by the first equation on page 8 of [1]
This is used to update the differences matrix when step size h is varied according
to factor = h_{n+1} / h_n
Note that the U matrix also defined in the same section can be also be... | bb27d63c46a92015dbaf98d078e34588994d60c5 | 3,615,974 |
def _complement_CS_CS(m1, m2, dtype, name):
"""CS-CS"""
return pair(one(m1.parent).new() | one(m2.parent).new()).new(dtype, name=name) | bdd2b22c2cc311274cc03973ac79768cf3ad2780 | 3,615,975 |
import math
def imeanstd_plusStats( iterable ):
"""Return the mean and stddev of an iterable, as well as
counts of values (total and the non-nan values on which
this is based),
or (nan,nan) if there are no values. If iterable yields
sequence values, then return (mean,std) for each column
of t... | d53a762699141ed38c6baf16aa049d8cf56c318c | 3,615,976 |
def heapsort(values):
"""Heapsorts a list of values in nondecreasing order."""
length = len(values)
def pick_child(parent):
left = parent * 2 + 1
if left >= length:
return None
right = left + 1
if right == length or values[left] >= values[right]:
ret... | 74e1afaf33e474611e842e97032a60a28fe5664d | 3,615,977 |
def pd_remove_no_mol2smiles( pdr, smiles_id = 'SMILES'):
"""
Find not working smiles codes
"""
s = pdr[ smiles_id].tolist()
fail_list = get_mol2smiles( s)
pdr = jutil.pd_remove_faillist_ID( pdr, fail_list)
return pdr | 1d2e9bdf3fbe2bbdd849681f004f90f59686e880 | 3,615,978 |
def MarkerPairSet_getClassName():
"""MarkerPairSet_getClassName() -> std::string const &"""
return _tools.MarkerPairSet_getClassName() | 562a299a88758c686ea5c7b08c7e4348d961f6a9 | 3,615,979 |
def anaSi(spc, det, digits=2, display=True):
"""anaSi
Strip continuum and analyze a spectrum for Si
Parameters
----------
spc: A DTSA-II scriptable spectrum
The spectrum to process
det: The detector
Returns
-------
A dictionary of tuples for C and Si where each tuple is the
peak integral (in counts/nA-se... | 0019057eb9ade2eaa26c1c2127093cbed6d5c8b9 | 3,615,980 |
import itertools
def batch_pairwise_dot(arr, batch_size=1024):
"""
Computes dot product between all pairs in arr, returned as a vector-form distance matrix as returned by scipy's
squareform (i.e. overall, very similar to pdist). Computation is performed in batches to avoid "RuntimeError: nnz
of the re... | 82d776b333b17469e279054ef90913bda6f77130 | 3,615,981 |
import yaml
from typing import Any
import os
import json
def construct_include(loader: Loader, node: yaml.Node) -> Any:
"""Include file referenced at node."""
filename = os.path.abspath(
os.path.join(loader._root, loader.construct_scalar(node)))
extension = os.path.splitext(filename)[1].lstrip('.'... | 988151225c907b2202ac073086682bbe29359d1f | 3,615,982 |
from pathlib import Path
import pathlib
def merge_test_metadata(
gdspath: Path = CONFIG["mask_gds"], labels_prefix: str = "opt"
) -> DictConfig:
"""Returns a test metadata dict config of labeled cells
Args:
gdspath
labels_prefix
"""
gdspath = pathlib.Path(gdspath)
mask_metada... | 29d2e089be3a80d34bbf1f4671447f4019fb8a8c | 3,615,983 |
def clear_system_log(ip, login_account, login_password, system_id, type):
"""Clear system log
:params ip: BMC IP address
:type ip: string
:params login_account: BMC user name
:type login_account: string
:params login_password: BMC user password
:type login_password: string
:params sy... | e97f16a73b5b4491e6bde03edd0b4cd9667daf01 | 3,615,984 |
def load_caffe_graph(prototxt_path: str, caffemodel_path: str) -> BaseGraph:
"""
从一个指定位置加载 caffe 计算图,注意该加载的计算图尚未经过调度,此时所有算子被认为是可量化的
load caffe graph from the specified location
Args:
prototxt_path (str): caffe prototxt的保存位置 the specified location of caffe prototxt
caffemodel_path... | 157186ec6af822af2d94d0158c9f20bdeade4294 | 3,615,985 |
import pytz
import copy
from datetime import datetime
def to_timezone(tz):
"""Parse the timezone.
Strings are parsed by `pytz` and `dateparser`, while integers and floats are treated as hour offsets.
If the timezone object can't be checked for equality based on its properties,
it's automatically con... | 831f6bb12116bb5b53a168c43224a016364121f0 | 3,615,986 |
def get_array_info(subs, dictofsubs):
"""
Returns information needed to create and access members of the numpy array
based upon the string names given to them in the model file.
Parameters
----------
subs : Array of strings of subscripts
These should be all of the subscript names that a... | ad97545278eddd12e8098dc623024beb797baebc | 3,615,987 |
def get_mean_stderr_annots_in_nested_dict(nested_dict,
as_string=True,
dict_level: int = 2) -> dict:
"""
Returns means and standard errors of the values inside a nested dictionary.
Parameters
----------
nested_dict... | 38ea17c996ff3b863f5990e46dc0cb31ce4e6bb6 | 3,615,988 |
def extractHeroicNovels(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [
('id', 'ID – The Greatest Fusion Fantasy', 'translated'),
('Magician City',... | 32cedc22548b8c140b73d45bc066256f0f4848cc | 3,615,989 |
def box_iou_xywh(box1: np.ndarray, box2: np.ndarray) -> float:
"""Calculate iou by xywh"""
assert box1.shape[-1] == 4, "Box1 shape[-1] should be 4."
assert box2.shape[-1] == 4, "Box2 shape[-1] should be 4."
b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2
b1_y1, b1_y2 = box1... | 96eb0a8a849253c49d87f79d02bbf40d8d93ac16 | 3,615,990 |
import io
def _encode_selected_predictions_recordio_protobuf(predictions):
"""Encode predictions in recordio-protobuf format.
For each prediction, a new record is created. The content is populated under the "label" field
of a record where the keys are derived from the selected content keys. Every value i... | 335bad49c4facf4a23648f2de38831179ebf404b | 3,615,991 |
from typing import Any
from typing import Optional
def async_check_significant_change(
hass: HomeAssistant,
old_state: str,
old_attrs: dict,
new_state: str,
new_attrs: dict,
**kwargs: Any,
) -> Optional[bool]:
"""Test if state significantly changed."""
if new_state != old_state:
... | b2648dbc6b7a4ddc02cd9f965d58517dddf60d29 | 3,615,992 |
def _format_truncated_traceback(traceback, max_num_chars=2000):
"""Truncate the traceback to the given character length."""
n = 0
for i, line in enumerate(reversed(traceback)):
n += len(_strip_ansi_codes(line)) + 2 # add 2 for newline control characters
if n > max_num_chars:
bre... | 146e18c2012f8f26afbbf09c0c66dc8dd8520b91 | 3,615,993 |
import click
def validate_nonempty(ctx, param, value):
"""Validate parameter is not an empty string."""
if not value.strip():
raise click.BadParameter('value cannot be empty')
return value | a8dd9a81c7fc7b0d0064fe34e849d35c0ce52a04 | 3,615,994 |
import re
def get_genres_from_soup(soup):
"""Get the genres of a book.
Parameters
----------
soup : BeautifulSoup
BeautifulSoup object created from a book page.
Returns
-------
list
Book genres.
"""
genres_elements = soup.find_all('a', {'href': re.compile('/genres... | 16db0fc8cb58cdcf19aa89ea8fef27078d33a390 | 3,615,995 |
import re
def escape_str(input) :
"""Just makes it so the string won't be evaluated oddly in eval_str."""
return re.sub(r"\[|\]|\$|{|}", _escape_str, input) | 714d6d5e3764bae28b5398b5b530e59603c727cb | 3,615,996 |
def truncate(string, length, extra=0, add_whitespace=True):
"""
Add whitespace to strings shorter than the length, truncate strings
longer than the length, replace the last few characters with ellipsis
"""
# Strip whitespace
base = string.strip()
difference = length-(len(base))
if diffe... | 228612cc4591122085ca358513eac7d025b19e77 | 3,615,997 |
def edit_get(u_id):
"""Render an edit form for the logged in user.
Login required.
Argument:
u_id (int): the id of the desired user.
"""
return render_template('edit_user.html') | 1edb87ee9ff69f6b8eb26bfc0144260de61a8731 | 3,615,998 |
def ModelCheckpoint(filepath='model.{epoch:02d}-{val_loss:.2f}.pt', save_model_params_only=False,
monitor='val_loss', save_best_only=False, mode='auto', period=1, min_delta=0):
"""Save the model after every epoch. `filepath` can contain named formatting options, which will be filled any
values from stat... | 993507420532bf02e38a48d3ddda025588f9cb3d | 3,615,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.