content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def openTypeNameVersionFallback(info):
"""
Fallback to *versionMajor.versionMinor* in the form 0.000.
"""
versionMajor = getAttrWithFallback(info, "versionMajor")
versionMinor = getAttrWithFallback(info, "versionMinor")
return "%d.%s" % (versionMajor, str(versionMinor).zfill(3)) | 370ab06aedd9909cc1b5d0e7f2211a554695c268 | 3,641,900 |
def get_quoted_text(text):
"""Method used to get quoted text.
If body/title text contains a quote, the first quote is considered as the text.
:param text: The replyable text
:return: The first quote in the text. If no quotes are found, then the entire text is returned
"""
lines = text.split('\n... | 3ac1801edcaf16af45d118918cb548f41d9a08fb | 3,641,901 |
def pad_sequences(sequences, pad_tok):
"""
Args:
sequences: a generator of list or tuple
pad_tok: the char to pad with
Returns:
a list of list where each sublist has same length
"""
max_length = max(map(lambda x: len(x), sequences))
sequence_padded... | 077d80424607864d6e0fa63d3843f80b9c822d1e | 3,641,902 |
def get_username_for_os(os):
"""Return username for a given os."""
usernames = {"alinux2": "ec2-user", "centos7": "centos", "ubuntu1804": "ubuntu", "ubuntu2004": "ubuntu"}
return usernames.get(os) | 579ebfa4e76b6660d28afcc010419f32d74aa98c | 3,641,903 |
import copy
def stats_getter(context, core_plugin, ignore_list=None):
"""Update Octavia statistics for each listener (virtual server)"""
stat_list = []
lb_service_client = core_plugin.nsxlib.load_balancer.service
# Go over all the loadbalancers & services
lb_bindings = nsx_db.get_nsx_lbaas_loadbal... | 65ebac76b6543683103584c18a7c06d2ea453e0a | 3,641,904 |
from typing import List
def track_to_note_string_list(
track: Track,
) -> List[str]:
"""Convert a mingus.containers.Track to a list of note strings"""
final_note_list = []
for element in track.get_notes():
for note in element[-1]:
final_note_list.append(note_to_string(note))
r... | 71b4fab66d18242e67a4ea59998e94341531f77a | 3,641,905 |
def group_sums_dummy(x, group_dummy):
"""sum by groups given group dummy variable
group_dummy can be either ndarray or sparse matrix
"""
if data_util._is_using_ndarray_type(group_dummy, None):
return np.dot(x.T, group_dummy)
else: # check for sparse
return x.T * group_dummy | 2cfb448130b9c48b41dd491a4fe01ab11a38478b | 3,641,906 |
def fixture_multi_check_schema() -> DataFrameSchema:
"""Schema with multiple positivity checks on column `a`"""
return _multi_check_schema() | f2b95cda9d6cd3e5bf0055d22c4b8505370a9867 | 3,641,907 |
def get_featurizer(featurizer_key: str) -> ReactionFeaturizer:
"""
:param: featurizer_key: key of a ReactionFeaturizer
:return: a ReactionFeaturizer for a specified key
"""
if featurizer_key not in FEATURIZER_INITIALIZERS:
raise ValueError(f"No featurizer for key {featurizer_key}")
retu... | 15583e90a0691ce10df9d789f6decef5443efed2 | 3,641,908 |
from typing import List
def is_negative_spec(*specs: List[List[str]]) -> bool:
""" Checks for negative values in a variable number of spec lists
Each spec list can have multiple strings. Each string within each
list will be searched for a '-' sign.
"""
for specset in specs:
if spe... | 216e6db2e63a657ac95a31896b9b61329a10a3db | 3,641,909 |
def is_np_timedelta_like(dtype: DTypeLike) -> bool:
"""Check whether dtype is of the timedelta64 dtype."""
return np.issubdtype(dtype, np.timedelta64) | b68d244d2d2c4d3029a93cbd8b3affca8c55f680 | 3,641,910 |
def pp2mr(pv,p):
""" Calculates mixing ratio from the partial and total pressure
assuming both have same unitsa nd no condensate is present. Returns value
in units of kg/kg. Checked 20.03.20
"""
pv, scalar_input1 = flatten_input(pv) # don't specify pascal as this will wrongly corrected
p , sc... | 97bd35658a54a53d7541aa0ee71f1b25cf8c2dbf | 3,641,911 |
def initialize_database(app):
""" Takes an initalized flask application and binds a database context to allow query execution
"""
# see https://github.com/mitsuhiko/flask-sqlalchemy/issues/82
db.app = app
db.init_app(app)
return db | 11a9f6046f51239c071d3a61780d1edf775baa51 | 3,641,912 |
from typing import TextIO
def decrypt(input_file: TextIO, wordlist_filename: str) -> str:
"""
Using wordlist_filename, decrypt input_file according to the handout
instructions, and return the plaintext.
"""
encrypt = []
result = ''
ans = ''
plaintext = ''
# store English wordlist ... | 87fae6e252b57f9903cd4b46d18a625455761d62 | 3,641,913 |
def loadEvents(fname):
"""
Reads a file that consists of first column of unix timestamps
followed by arbitrary string, one per line. Outputs as dictionary.
Also keeps track of min and max time seen in global mint,maxt
"""
events = []
ws = open(fname, 'r').read().splitlines()
events = []
for w in ws:
... | 495dbd5d47892b953c139b27b1f20dd9854ea29a | 3,641,914 |
def compute_relative_target_raw(current_pose, target_pose):
"""
Computes the relative target pose which has to be fed to the network as an input.
Both target pose and current_pose have to be in the same coordinate frame (gloabl map).
"""
# Compute the relative goal position
goal_position_difference = [targ... | efee9b6ef48bda67dfd42526c20e7d1de6a164da | 3,641,915 |
import httpx
def get_tokeninfo_remote(token_info_url, token):
"""
Retrieve oauth token_info remotely using HTTP
:param token_info_url: Url to get information about the token
:type token_info_url: str
:param token: oauth token from authorization header
:type token: str
:rtype: dict
"""
... | c0f72b47b97d2d9c57b8b7fe30a3cba9f29c2005 | 3,641,916 |
from datetime import datetime
def make_site_object(config, seen):
"""Make object with site values for evaluation."""
now = datetime.today().strftime("%Y-%m-%d")
subtitle = (
f'<h2 class="subtitle">{config.subtitle}</h2>'
if config.subtitle
else ""
)
site = SN(
autho... | 762382446736a1815deae275db0d7485c0718a4e | 3,641,917 |
from datetime import datetime
import os
def get_filename():
"""
Build the output filename
"""
now_date = datetime.now()
out_date = now_date.strftime("%Y-%m-%d_%H-%M")
outfile_name = "node_ip_cfg_info_" + out_date + '.txt'
if os.path.exists(outfile_name):
os.remove(outfile_name)
... | f3cf65c2ceb71388fc026d3dd603d3878a9a4650 | 3,641,918 |
from datetime import datetime
import json
import hashlib
def map_aircraft_to_record(aircrafts, message_now, device_id):
"""
Maps the `aircraft` entity to a BigQuery record and its unique id.
Returns `(unique_ids, records)`
"""
def copy_data(aircraft):
result = {
'hex': aircraft.get('hex'),
'... | d423b87e2018486de076cc94a719038c53c54602 | 3,641,919 |
def add_gaussian_noise(image, mean=0, std=0.001):
"""
添加高斯噪声
mean : 均值
var : 方差
"""
image = np.array(image / 255, dtype=float)
noise = np.random.normal(mean, std ** 0.5, image.shape)
print(np.mean(noise ** 2) - np.mean(noise) ** 2)
out = image + noise
if image.min() <... | 1683ae5815e28ab0c3354be1623ec56e6058b449 | 3,641,920 |
import os
import datasets
def imagenet_get_datasets(data_dir, arch, load_train=True, load_test=True):
"""
Load the ImageNet dataset.
"""
# Inception Network accepts image of size 3, 299, 299
if distiller.models.is_inception(arch):
resize, crop = 336, 299
else:
resize, crop = 25... | 1008dabb1e7da9f5cff82847e06b44992413a34d | 3,641,921 |
def sub(xs, ys):
"""
Computes xs - ys, such that elements in xs that occur in ys are removed.
@param xs: list
@param ys: list
@return: xs - ys
"""
return [x for x in xs if x not in ys] | 8911bb2c79919cae88463a95521cf051828038e8 | 3,641,922 |
def create_folio_skill(request, folio_id):
"""
Creates a new folio skill
"""
if request.method == "POST":
form = FolioSkillForm(request.POST)
if form.is_valid():
skill = form.save(commit=False)
skill.author_id = request.user
skill.save()
... | 7c1966f7a6b3c98e972da90abb5eb984a4af85a2 | 3,641,923 |
def lambda_handler(event, context):
"""AWS Lambda Function entrypoint to cancel booking
Parameters
----------
event: dict, required
Step Functions State Machine event
chargeId: string
pre-authorization charge ID
context: object, required
Lambda Context runtime ... | e29b8eb3fe2ab38aab91d97d0c63bfb19a9b9363 | 3,641,924 |
def reduce_tags(tags):
"""Filter a set of tags to return only those that aren't descendents from others in the list."""
reduced_tags = []
for tag_a in tags:
include = True
for tag_b in tags:
if tag_a == tag_b:
continue
if not tag_before(tag_a, tag_b):
... | fa76e1cc5bd10ecd58bdc8f5277fa32d41484c17 | 3,641,925 |
def default_param_noise_filter(var):
"""
check whether or not a variable is perturbable or not
:param var: (TensorFlow Tensor) the variable
:return: (bool) can be perturb
"""
if var not in tf.trainable_variables():
# We never perturb non-trainable vars.
return False
if "full... | 12817bf2c2b726d91d9d3cc838b52499e5382d80 | 3,641,926 |
def input_fn(request_body, request_content_type):
"""
An input_fn that loads the pickled tensor by the inference server of SageMaker.
The function deserialize the inference request, then the predict_fn get invoked.
Does preprocessing and returns a tensor representation of the source sentence
ready t... | 62d45e188d5537eaa566bd4b90bdb8abc7626621 | 3,641,927 |
def get_colors(k):
"""
Return k colors in a list. We choose from 7 different colors.
If k > 7 we choose colors more than once.
"""
base_colors = ['b', 'r', 'g', 'c', 'm', 'y', 'k']
colors = []
index = 1
for i in range(0, k):
if index % (len(base_colors) + 1) == 0:
in... | 6c4a38eb394254f57d8be9fca47e0b44f51f5f04 | 3,641,928 |
import logging
def test_significance(stat, A, b, eta, mu, cov, z, alpha):
"""
Compute an p-value by testing a one-tail.
Look at right tail or left tail?
Returns "h_0 Reject
"""
ppf, params = psi_inf(A, b, eta, mu, cov, z)
if np.isnan(params['scale']) or not np.isreal(params['sc... | f723a75c59a23d7110a41036d6873f6023b42333 | 3,641,929 |
def _get_cluster_group_idx(clusters: np.ndarray) -> nb.typed.List:
"""
Get start and stop indexes for unique cluster labels.
Parameters
----------
clusters : np.ndarray
The ordered cluster labels (noise points are -1).
Returns
-------
nb.typed.List[Tuple[int, int]]
Tupl... | 5bdae0228367868c201b8a399ca959bc50c715b2 | 3,641,930 |
from typing import Union
from typing import Optional
def genes_flyaltas2(
genes: Union[str, list] = None,
gene_nametype: Optional[str] = "symbol",
stage: Optional[str] = "male_adult",
enrich_threshold: Optional[float] = 1.0,
fbgn_path: Optional[str] = "deml_fbgn.tsv.gz",
) -> pd.DataFrame:
"""... | 651e3eb2ce58ae19d1785df1217b5434737b8bda | 3,641,931 |
import torch
import tqdm
def _batch_embed(args, net, vecs: StringDataset, device, char_alphabet=None):
"""
char_alphabet[dict]: id to char
"""
# convert it into a raw string dataset
if char_alphabet != None:
vecs.to_bert_dataset(char_alphabet)
test_loader = torch.utils.data.DataLoader... | 43224296330e4516c530d65217edf6a4b12dc5d3 | 3,641,932 |
def get_adjacency_matrix(distance_df, sensor_ids, normalized_k=0.1):
"""
:param distance_df: data frame with three columns: [from, to, distance].
:param sensor_ids: list of sensor ids.
:param normalized_k: entries that become lower than normalized_k after normalization are set to zero for sparsity.
... | b8acd5401dbf743294d52d71ddc97a0b0c74780b | 3,641,933 |
def map_ids_to_strs(ids, vocab, join=True, strip_pad='<PAD>',
strip_bos='<BOS>', strip_eos='<EOS>', compat=True):
"""Transforms `int` indexes to strings by mapping ids to tokens,
concatenating tokens into sentences, and stripping special tokens, etc.
Args:
ids: An n-D numpy arra... | 6e702d8c0d658bd822f0db6c4094ab093207b78e | 3,641,934 |
import argparse
def _parse_args() -> argparse.Namespace:
"""Parses and returns the command line arguments."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('in_json',
type=argparse.FileType('r'),
help='The JSON file containing a ... | 108f2ab7d962fa31a99158997f832f46b8b8d6f8 | 3,641,935 |
import random
def rand_ascii_str(length):
"""Generates a random string of specified length, composed of ascii letters
and digits.
Args:
length: The number of characters in the string.
Returns:
The random string generated.
"""
letters = [random.choice(ascii_letters_and_digits) for _ in range(leng... | 130e8dbe1eb8e60813b01cf08dc7e9fd388638cf | 3,641,936 |
def set_achievement_disabled(aid, disabled):
"""
Updates a achievement's availability.
Args:
aid: the achievement's aid
disabled: whether or not the achievement should be disabled.
Returns:
The updated achievement object.
"""
return update_achievement(aid, {"disabled": ... | 2793e3576904f5b1498361f02e32fdf2642b734c | 3,641,937 |
from datetime import datetime
def get_block(in_dt: datetime):
"""Get the BlockNumber instance at or before the datetime timestamp."""
return BlockNumber.from_timestamp(in_dt.replace(tzinfo=timezone.utc).timestamp()) | a77ca6c4021ebc0e5ef2e2c0294246415ccd9811 | 3,641,938 |
def get_channels(posts):
"""
<summary> Returns post channel (twitter/facebook)</summary>
<param name="posts" type="list"> List of posts </param>
<returns> String "twitter" or "facebook" </returns>
"""
channel = []
for i in range(0, len(posts['post_id'])):
if len(posts['post_text'][i... | 2bd67d13079ce115263ac46856d8a708f461cb7e | 3,641,939 |
from bs4 import BeautifulSoup
def clean_text(text):
"""
text: a string
return: modified initial string
"""
text = BeautifulSoup(text, "lxml").text # HTML decoding
text = text.lower() # lowercase text
text = REPLACE_BY_SPACE_RE.sub(' ', text) # replace REPLACE_BY_SPACE_RE s... | b29f4b388bac55d04c824ad014a6b85e1c9c8ede | 3,641,940 |
def ConvertToTypeEnum(type_enum, airflow_executor_type):
"""Converts airflow executor type string to enum.
Args:
type_enum: AirflowExecutorTypeValueValuesEnum, executor type enum value.
airflow_executor_type: string, executor type string value.
Returns:
AirflowExecutorTypeValueValuesEnum: the execut... | 04162b04719031ba6b96d981a7ffe8a82691bc31 | 3,641,941 |
import numpy
def image2array(image):
"""PIL Image to NumPy array"""
assert image.mode in ('L', 'RGB', 'CMYK')
arr = numpy.fromstring(image.tostring(), numpy.uint8)
arr.shape = (image.size[1], image.size[0], len(image.getbands()))
return arr.swapaxes(0, 2).swapaxes(1, 2).astype(numpy.float32) | bb1ba38f2d27acb63ea7ccfb600720eee3d683a3 | 3,641,942 |
from typing import Type
def enum_name_callback(ctx: 'mypy.plugin.AttributeContext') -> Type:
"""This plugin refines the 'name' attribute in enums to act as if
they were declared to be final.
For example, the expression 'MyEnum.FOO.name' normally is inferred
to be of type 'str'.
This plugin will ... | e7b34490625ad2c8cf55ed002592ed1194f96e2f | 3,641,943 |
def is_forward_angle(n, theta):
"""
if a wave is traveling at angle theta from normal in a medium with index n,
calculate whether or not this is the forward-traveling wave (i.e., the one
going from front to back of the stack, like the incoming or outgoing waves,
but unlike the reflected wave). For r... | 9d90a84be42968eebb1dd89285019ddc10a2b140 | 3,641,944 |
import os
import pkgutil
def get_data(cfg, working_dir, global_parameters, res_incl=None, res_excl=None):
"""Reads experimental measurements"""
exp_type = global_parameters['experiment_type']
path = os.path.dirname(__file__)
pkgs = [
modname
for _, modname, ispkg in pkgutil.iter_modu... | 826314fe99b6ba6dc408c7b0109536ae5fdc0acb | 3,641,945 |
import math
def fit_cubic1(points,rotate,properties=None):
"""This function attempts to fit a given set of points to a cubic polynomial line: y = a3*x^3 + a2*x^2 + a1*x + a0"""
r=mathutils.Matrix.Rotation(math.radians(rotate),4,'Z')
rr=mathutils.Matrix.Rotation(math.radians(-rotate),4,'Z')
S... | dea26481743546600bef54c58523746a638b63a5 | 3,641,946 |
import glob
import os
def tile_from_slippy_map(root, x, y, z):
"""Retrieve a single tile from a slippy map dir."""
path = glob.glob(os.path.join(os.path.expanduser(root), z, x, y + ".*"))
if not path:
return None
return mercantile.Tile(x, y, z), path[0] | 5af475d01591a9f3170adecbc34d53ab26ffb1db | 3,641,947 |
def get_labelstats_df_list(fimage_list, flabel_list):
"""loop over lists of image and label files and
extract label statisics as pandas.DataFrame
"""
if np.ndim(fimage_list) == 0:
fimage_list = [fimage_list]
if np.ndim(flabel_list) == 0:
flabel_list = [flabel_list]
columns = ['i... | e494212975641e8c9f9b2d786077e320d9096c02 | 3,641,948 |
def index(web):
"""The web.request.params is a dictionary,
pointing to falcon.Request directly."""
name = web.request.params["name"]
return f"Hello {name}!\n" | b717ac60d42b8161ed27f7e4156d8a5a03aea803 | 3,641,949 |
def process_object(obj):
""" Recursively process object loaded from json
When the dict in appropriate(*) format is found,
make object from it.
(*) appropriate is defined in create_object function docstring.
"""
if isinstance(obj, list):
result_obj = []
for elem in obj:
... | f5410c6168d96eb153f08c824a98cf58fd80e1a0 | 3,641,950 |
def remove_role(principal, role):
"""Removes role from passed principal.
**Parameters:**
principal
The principal (actor or group) from which the role is removed.
role
The role which is removed.
"""
try:
if isinstance(principal, Actor):
ppr = PrincipalRoleRe... | 78b27631ee80b42a2ee8759315ef00f490c0e86c | 3,641,951 |
def set_var_input_validation(
prompt="",
predicate=lambda _: True,
failure_description="Value is illegal",
):
"""Validating user input by predicate.
Vars:
- prompt: message displayed when prompting for user input.
- predicate: lambda function to verify a condition.
- failure... | 40cad55c5d07a405f946e9583c69029eb2ee4e65 | 3,641,952 |
def mad(data, axis=None):
"""Mean absolute deviation"""
return np.mean(np.abs(data - np.mean(data, axis)), axis) | 955763e5ee5d29e2b2b735d584d7a84b98affc23 | 3,641,953 |
from re import T
def spatial_2d_padding(x, padding=((1, 1), (1, 1)), data_format=None):
"""Pad the 2nd and 3rd dimensions of a 4D tensor
with "padding[0]" and "padding[1]" (resp.) zeros left and right.
"""
assert len(padding) == 2
assert len(padding[0]) == 2
assert len(padding[1]) == 2
top... | ba57f1f8462d7c3212379b9678364c5e2e2e6a5b | 3,641,954 |
def doms_hit_pass_threshold(mc_hits, threshold, pass_k40):
""" checks if there a at least <<threshold>> doms
hit by monte carlo hits. retuns true or false"""
if threshold == 0: return True
if len(mc_hits) == 0: return bool(pass_k40)
dom_id_set = set()
for hit in mc_hits:
dom_id = pm... | 9f4157d202e2587232b13cfc9873400ab6ee6e5b | 3,641,955 |
import os
import difflib
def differ_filelist_with_two_dirs(s_p_dir, d_p_dir, filelist, mode='0'):
"""
使用 difflib 库对两个文件夹下的文件列表进行比较,输出原始结果
"""
output = ''
for f_path in filelist:
s_file_path = os.path.join(s_p_dir, f_path) if mode != '1' else None
d_file_path = os.path.join(d_p_dir,... | bb3b39a894c465ea9df78bb7e6e10016deaaf727 | 3,641,956 |
def _parseLocalVariables(line):
"""Accepts a single line in Emacs local variable declaration format and
returns a dict of all the variables {name: value}.
Raises ValueError if 'line' is in the wrong format.
See http://www.gnu.org/software/emacs/manual/html_node/File-Variables.html
"""
paren = '... | 39dc5130f47589e111e4b894cf293d446ac0eac0 | 3,641,957 |
from re import T
def NLL(mu, sigma, mixing, y):
"""Computes the mean of negative log likelihood for P(y|x)
y = T.matrix('y') # (minibatch_size, output_size)
mu = T.tensor3('mu') # (minibatch_size, output_size, n_components)
sigma = T.matrix('sigma') # (minibatch_size, n_components)
mixing = T... | 60a27f48d404af860cdbeac9e017a3df5ebca450 | 3,641,958 |
from typing import Optional
import sqlite3
def get_non_subscribed_trainers(user) -> Optional[str]:
"""
returns all trainers the user is not subscrbed to
"""
conn = get_db()
error = None
try:
trainers = conn.execute("""SELECT distinct u_name FROM user, trainer
... | 6c728e1bd805047e20224c45fab81f546e291d27 | 3,641,959 |
def __clean_datetime_value(datetime_string):
"""Given"""
if datetime_string is None:
return datetime_string
if isinstance(datetime_string, str):
x = datetime_string.replace("T", " ")
return x.replace("Z", "")
raise TypeError("Expected datetime_string to be of type string (or No... | 77afef31056365a47ea821de7a4979cb061920dc | 3,641,960 |
def get_metric_by_name(metric: str, *args, **kwargs) -> Metric:
"""Returns metric using given `metric`, `args` and `kwargs`
Args:
metric (str): name of the metric
Returns:
Metric: requested metric as Metric
"""
assert metric in __metric_mapper__, "given metric {} is not found".form... | b1ecb1fe1fad330570abcf9abd3f12abd2a18193 | 3,641,961 |
def Square(inputs, **kwargs):
"""Calculate the square of input.
Parameters
----------
inputs : Tensor
The input tensor.
Returns
-------
Tensor
The square result.
"""
CheckInputs(inputs, 1)
arguments = ParseArguments(locals())
output = Tensor.CreateOperator... | 5869ab81460b0a3b56194ec9829bf6ec36716b9a | 3,641,962 |
def make_call(rpc_name, request, retries=None, timeout=None):
"""Make a call to the Datastore API.
Args:
rpc_name (str): Name of the remote procedure to call on Datastore.
request (Any): An appropriate request object for the call, eg,
`entity_pb2.LookupRequest` for calling ``Lookup`... | f360aebb119b8f6e05207f5a7add1a6a16059d41 | 3,641,963 |
def render_table(data, col_width=3.0, row_height=0.625, font_size=14,
header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',
bbox=[0, 0, 1, 1], header_columns=0,
ax=None, **kwargs):
"""[Taken from ref: https://stackoverflow.com/questions/... | 597d8732ca86896d02d0df30d2a0808b88f02873 | 3,641,964 |
def segment_image(class_colours, pixel_classes, height, width, bg_alpha=0, fg_alpha=255):
"""visualise pixel classes"""
segment_colours = np.reshape(class_colours[pixel_classes], (height, width, 3))
segment_colours = segment_colours.astype("uint8")
img = Image.fromarray(segment_colours)
# set backgr... | 2dd1f70342cc101d3cf37d706ede8c55ded91629 | 3,641,965 |
def cross_replica_average(inputs,
num_shards=None,
num_shards_per_group=None,
physical_shape=None,
tile_shape=None,
use_spatial_partitioning=False):
"""Customized cross replica sum op."""
... | 5486eae34e2e25966343a5e115541de7c734ec98 | 3,641,966 |
def run_length_to_bitstream(rl: np.ndarray, values: np.ndarray, v_high: int, v_low: int) -> np.ndarray:
"""Do run length DECODING and map low/high signal to logic 0/1.
Supposed to leave middle values untouched.
[1,2,1,1,1] [7,1,7,1,5] -->
[1 0 0 1 0 5]
:param rl: Array of run lengths
:param val... | 3b9ed2ce753f6adfcf8197886b38595b2eac9978 | 3,641,967 |
def edge_naming(col_list, split_collections=True):
""" This function normalize the naming of edges collections
If split_collections is True an edge collection name will be
generated between each listed collection in order.
So if col_list = [A, B, C]
result will be [A__B, B__C]
... | 47e0c7253a5a9f1c0df9488c54cca38b2264539f | 3,641,968 |
def interactive_visual_difference_from_threshold_by_day(ds_ext):
"""
Returns: 1) xarray DataArray, with three variables, for each day in the dataset
i) Highest value difference from the threshold, across the area
ii) Lowest value difference from the threshold, across the area
... | 2386f3564a105a44ff3cd12979f52e296e8293ac | 3,641,969 |
def _parse_compression_method(data):
"""Parses the value of "method" extension parameter."""
return common.parse_extensions(data) | 71901780aec98d8818a5296aa7b186c79b0f0e7b | 3,641,970 |
def my_distance(drij):
"""
Compute length of displacement vector drij
assume drij already accounts for PBC
Args:
drij (np.array) : vector(s) of length 3
Returns:
float: length (distance) of vector(s)
"""
return np.linalg.norm(drij, axis=0) | 45a29d7335e72dac68ddefcbf32b55b57e87b980 | 3,641,971 |
from typing import List
def show(list_id):
"""Get single list via id."""
data = db_session.query(List).filter(List.id == list_id).first()
if '/json' in request.path:
return jsonify(data.as_dict())
else:
return render_template('list/show.html', list=data) | 9ed8de0dfc5621546dafe447fa83d33c00fa6b7e | 3,641,972 |
import os
def create_folder(path):
"""
Creates a folder if not already exists
Args:
:param path: The folder to be created
Returns
:return: True if folder was newly created, false if folder already exists
"""
if not os.path.exists(path):
os.makedirs(path)
return... | 9b6cfaed256001aa15c15cb535fce54ddcf20bc8 | 3,641,973 |
def extract_smaps(kspace, low_freq_percentage=8, background_thresh=4e-6):
"""Extract raw sensitivity maps for kspaces
This function will first select a low frequency region in all the kspaces,
then Fourier invert it, and finally perform a normalisation by the root
sum-of-square.
kspace has to be of... | e40ec21c8e353e6352b65f35710d83857cc6c124 | 3,641,974 |
import io
def tiff_to_mat_conversion(ms_path, pan_path, save_path, ms_initial_point=(0, 0), ms_final_point=(0, 0), ratio=4):
"""
Generation of *.mat file, starting from the native GeoTiFF extension.
Also, a crop tool is provided to analyze only small parts of the image.
Parameters
... | c0e1a03f82b97ecc8a3e33a1b84624b53c3efae7 | 3,641,975 |
def is_member(musicians, musician_name):
"""Return true if named musician is in musician list;
otherwise return false.
Parameters:
musicians (list): list of musicians and their instruments
musician_name (str): musician name
Returns:
bool: True if match is made; otherwise False.... | 6ef5b9bbccb17d9b97a85e3af7789e059829184b | 3,641,976 |
from typing import Tuple
def _parse_client_dict(dataset: tf.data.Dataset,
string_max_length: int) -> Tuple[tf.Tensor, tf.Tensor]:
"""Parses the dictionary in the input `dataset` to key and value lists.
Args:
dataset: A `tf.data.Dataset` that yields `OrderedDict`. In each
`Ordered... | bd5761396ee661d91898859aa23858da7f674c76 | 3,641,977 |
def init(command):
"""
We assume the first command from NASA is the rover
position. Assumetions are bad. We know that the
command conists of two numbers seperated by a space.
Parse the number so it matches D D
"""
if re.match('^[0-9]\s[0-9]\s[a-zA-Z]$', command):
pos = command.split... | 282bb4bababeb24e0fe8cb1f6f4a57d36b2339dd | 3,641,978 |
def add_small_gap_multiply(original_wf, gap_cutoff, density_multiplier, fw_name_constraint=None):
"""
In all FWs with specified name constraints, add a 'small_gap_multiply' parameter that
multiplies the k-mesh density of compounds with gap < gap_cutoff by density multiplier.
Useful for increasing the k-... | 4573ee33b1be21adfcca1e8be3337b1df51ab737 | 3,641,979 |
def _get_backend(config_backend):
"""Extract the backend class from the command line arguments."""
if config_backend == 'gatttool':
backend = GatttoolBackend
elif config_backend == 'bluepy':
backend = BluepyBackend
elif config_backend == 'pygatt':
backend = PygattBackend
else... | 86374b3c19cbb3fa26434c18720288edf1c4fbe8 | 3,641,980 |
from time import time
def kern_CUDA_sparse(nsteps,
dX,
rho_inv,
context,
phi,
grid_idcs,
mu_egrid=None,
mu_dEdX=None,
mu_lidx_nsp=None,
... | 74b8d93f867fed536b3ba1f1f4f0fc6e33e3efe8 | 3,641,981 |
def _to_sequence(x):
"""shape batch of images for input into GPT2 model"""
x = x.view(x.shape[0], -1) # flatten images into sequences
x = x.transpose(0, 1).contiguous() # to shape [seq len, batch]
return x | bb3b0bb478c924b520bf7bf991a028cf8aaea25f | 3,641,982 |
def read_wav_kaldi(wav_file_path: str) -> WaveData:
"""Read a given wave file to a Kaldi readable format.
Args:
wav_file_path: Path to a .wav file.
Returns:
wd: A Kaldi-readable WaveData object.
"""
# Read in as np array not memmap.
fs, wav = wavfile.read(wav_file_path, False)
... | 50b2f5a848d387d4b1ca2764b7d30178d7ec5e28 | 3,641,983 |
def _testCheckSums(tableDirectory):
"""
>>> data = "0" * 44
>>> checkSum = calcTableChecksum("test", data)
>>> test = [
... dict(data=data, checkSum=checkSum, tag="test")
... ]
>>> bool(_testCheckSums(test))
False
>>> test = [
... dict(data=data, checkSum=checkSum+1, tag=... | 192785ca352eec4686e07f2f103283f6499b656f | 3,641,984 |
def read_img(path):
"""
读取图片,并将其转换为邻接矩阵
"""
# 对于彩色照片,只使用其中一个维度的色彩
im = sp.misc.imread(path)[:, :, 2]
im = im / 255.
# 若运算速度太慢,可使用如下的语句来缩减图片的大小
# im = sp.misc.imresize(im, 0.10) / 255.
# 计算图片的梯度,既相邻像素点之差
graph = image.img_to_graph(im)
beta = 20
# 计算邻接矩阵
graph.data = np... | 41e4d000f9a70a6b6e787c08bcced4083178da11 | 3,641,985 |
def createmarker(name=None, source='default', mtype=None,
size=None, color=None, priority=None,
viewport=None, worldcoordinate=None,
x=None, y=None, projection=None):
"""%s
:param name: Name of created object
:type name: `str`_
:param source: A marker... | 7afaec1d24aad89b85974c509cf7c0ed165f733b | 3,641,986 |
from typing import List
from typing import Optional
from typing import Set
from typing import Callable
def get_parser(disable: List[str] = None ,
lang: str = 'en',
merge_terms: Optional[Set] = None,
max_sent_len: Optional[int] = None) -> Callable:
"""spaCy clinical tex... | 175c4ea51417dc02b4a7f6f5a0c512464bd252c2 | 3,641,987 |
def block_device_mapping_get_all_by_instance(context, instance_uuid,
use_slave=False):
"""Get all block device mapping belonging to an instance."""
return IMPL.block_device_mapping_get_all_by_instance(context,
... | 16fc00068ad87d76831044d626a88960a0278817 | 3,641,988 |
def add_rain(img, slant, drop_length, drop_width, drop_color, blur_value, brightness_coefficient, rain_drops):
"""
From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
Args:
img (np.uint8):
slant (int):
drop_length:
drop_width:
drop_color:
... | f864a46fc13e955baade855ae454249e3a514a03 | 3,641,989 |
def vrctst_tml(file_name):
""" adds vrctst_tml extension, if missing
:param file_name: name of file
:type file_name: str
:returns: file with extension added
:rtype: str
"""
return _add_extension(file_name, Extension.VRC_TML) | 92a084fc19c39c0797d573e01c90da28c0e1c11c | 3,641,990 |
def get_pixel_coords(x, y, xres, yres, xmin, ymax):
"""
Translate x, y coordinates to cols, rows.
Example:
col, row = map_pixel(x, y, geotransform[1],
geotransform[-1], geotransform[0], geotransform[3])
Parameters
----------
x : float, numpy.ndarray
X coordinates.
... | ccf38618de9d24279ab4df6ba016804c6da926f7 | 3,641,991 |
import re
def _boundary_of_alternatives_indices(pattern):
"""
Determines the location of a set of alternatives in a glob pattern.
Alternatives are defined by a matching set of non-bracketed parentheses.
:param pattern: Glob pattern with wildcards.
:return: Indices of the innermost set of m... | 707a4a02a362019db63277b01955bb54d31e51e7 | 3,641,992 |
def plot(model, featnames=None, num_trees=None, plottype='horizontal', figsize=(25,25), verbose=3):
"""Make tree plot for the input model.
Parameters
----------
model : model
xgboost or randomforest model.
featnames : list, optional
list of feature names. The default is None.
nu... | 29b6f242ba6f794440b27fff573d976f9e06a228 | 3,641,993 |
import logging
import tempfile
import os
import shutil
def post_images(*, image_path: str,) -> dict:
"""
Convert Image to PDF
"""
logging.debug('image_path: ' + image_path)
try:
if(image_path.startswith(NEXTCLOUD_USERNAME+"/files")):
image_path = image_path[len(NEXTCLOUD_USERNA... | 2f8d4855b189b55aeb2ba76b957cccf1adf7a935 | 3,641,994 |
def sim_DA_from_timestamps2_p2_2states(timestamps, dt_ref, k_D, R0, R_mean,
R_sigma, tau_relax, k_s, rg,
chunk_size=1000, alpha=0.05, ndt=10):
"""
2-states recoloring using CDF in dt and with random number caching
"""
dt = np.... | c268e49d7fc960c3f684d77fcbb4880be446a5b0 | 3,641,995 |
def get_cross_track_error(data, rate, velocity):
"""Returns the final cross-track position (in nautical miles)
The algorithm simulates an aircraft traveling on a straight trajectory who
turns according to the data provided. The aircraft instantaneously updates
its heading at each timestep by Ω * Δt.
... | 88fa42408090c94c9e3212517d89ba47afeedccb | 3,641,996 |
async def get_list_address():
"""Get list of address
"""
return await service.address_s.all() | 4d0304e23243d7f151c0f09fc5e1896413daee1b | 3,641,997 |
import pathlib
from typing import Optional
def load_xml_stream(
file_path: pathlib.Path, progress_message: Optional[str] = None
) -> progress.ItemProgressStream:
"""Load an iterable xml file with a progress bar."""
all_posts = ElementTree.parse(file_path).getroot()
return progress.ItemProgressStream(
... | 26d6bd350dbe913855479c557c8881b03f90b266 | 3,641,998 |
def SNR_band(cp, ccont, cb, iband, itime=10.):
"""
Calc the exposure time necessary to get a given S/N on a molecular band
following Eqn 7 from Robinson et al. 2016.
Parameters
----------
cp :
Planet count rate
ccont :
Continuum count rate
cb :
Background count r... | ffec688d6e760ace0fc1e38217ec91dc674ee83f | 3,641,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.