content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def parse_identification_method(tag, type):
"""
parses id_marc_tag tag attrib for proper handling in pymarc obj
args:
tag str (marc tag)
type str (standard, control field)
return:
(tag, subfield) tuple
"""
if type == 'standard':
tag_to_check = tag[:3]
subf... | 0b7dca44196ccfabdca102e7a966d4bd7987eef0 | 46,800 |
from typing import List
def entropy_from_indexes(indexes: List[int], lang: str) -> Entropy:
"""Return the entropy from a list of word-list indexes.
Return the entropy from a list of integer indexes into
a given language word-list.
"""
n = _wordlists.language_length(lang)
entropy = 0
... | 4f996eaa49a1719195ed866da3ab6e56aaaa2bae | 46,801 |
def decompress_G2(p: G2Compressed) -> G2Uncompressed:
"""
Recovers x and y coordinates from the compressed point (z1, z2).
"""
z1, z2 = p
c_flag1, b_flag1, a_flag1 = get_flags(z1)
# c_flag == 1 indicates the compressed form
# MSB should be 1
if not c_flag1:
raise ValueError("c_f... | 77d5bb816fdf8a1a5c9bbce7b9fb3da65c29b7f8 | 46,802 |
def lnprob(lnparams, *args):
""" The ln-probability function.
Calculates the logarithmic posterior probability (likelihood times prior)
of the model given the data.
Args:
lnparams (array): The parameter array containing Equivalent
Evolutionary Point (EEP), age in log10(yrs), metall... | bf369647abce998ff9ec7d74f933b4bf221b5c5b | 46,803 |
def VerifyCbiEepromWpStatus(dut, cbi_eeprom_wp_status,
ec_bypass_cbi_eeprom_wp_check):
"""Verify CBI EEPROM status.
If cbi_eeprom_wp_status is Absent, CBI EEPROM must be absent. If
cbi_eeprom_wp_status is Locked, write protection must be on. Otherwise, write
protection must be off.
... | 34aad3d8c73174d2b1f5ef20d3925a59ca9f4227 | 46,804 |
def coding_strand_to_rna(strand):
"""returns the coding strand to the rna strand (T --> U)"""
strand = strand.upper().replace("T","U")
return strand | 5c3420e921c10376b33b17dfc34e7301414bc6ef | 46,805 |
import os
def make_2d(
x_seq, y_seq, alphabet, file_name, out_dir, labels, matplot, pil, array_flag
):
"""
fun plots 2D metrics of watson-crick binding
rules of sequence x and y as heatmap
parameters
x_seq=sequecne on x axis
y_seq=sequence on y axis
alphabet=2D matrix
file_name=im... | 59db0f7b6275574ce6a245e270ad07553c2806c6 | 46,806 |
def _process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (Dictionary of Lists) raw structured data to process
Returns:
List of Dictionaries. Structured data to conform to the schema.
"""
for entry in proc_data:
# add timestamps
... | 7ba6283bf8aaf89f144d3584c8c260ce4a70bc73 | 46,807 |
def load_rsa_key(filename):
"""
Function to get an RSA key from the specified file for Paramiko.
"""
return paramiko.RSAKey.from_private_key_file(prepend_home_dir(filename)) | 291df80fe2623d801dce9ffe71472a09a93ad303 | 46,808 |
import os
def merge_grid(proj_path):
"""This function concatinates the shapefiles which contains the keyword '33kV' and '66kV'
:param proj_path:
:return:
"""
current = os.getcwd()
os.chdir(proj_path)
files = os.listdir(proj_path)
shapefiles = []
for file in files:
if file.e... | a83c1025bee278399111043c8c6b44d9af0373a9 | 46,809 |
def F_score(xs, ys, beta=0.01):
"""
Returns the F score described here: http://en.wikipedia.org/wiki/F1_score
for list `xs` against to the list `ys`.
Make beta smaller to give more weight to the precision.
"""
p = precision(xs, ys)
r = recall(xs, ys)
if (p + r) == 0:
return 0, 0... | 7e4a7267b793449490103fef509a9324940d592d | 46,810 |
def get_db_len(session_id):
"""
Args:
session_id (int): id of a user's session
Returns:
int: how many songs the user has rated in a specific session
"""
cursor, connection = open_db_connection()
try:
cursor.execute(
f"""select count(*)
fro... | f072bfd4d62e388e0630428de4fdf6dcd76bbc38 | 46,811 |
from pathlib import Path
def create_addr_record(addr_file: Path) -> clusterlib.AddressRecord:
"""Return a `clusterlib.AddressRecord`."""
f_name = addr_file.name.replace(".addr", "")
basedir = addr_file.parent
vkey_file = basedir / f"{f_name}.vkey"
skey_file = basedir / f"{f_name}.skey"
if not... | d61667b57c15c8df3688e934251cc2e83d9f0449 | 46,812 |
def graph_to_entities_json(g):
"""
Converts the given graph to entities JSON.
:param g: a graph
:return: an array of JSON
"""
entities = []
for u, v in g.edges():
entity = {
"Device": "",
"IP": "",
"Identity": "",
"Location": "",
... | ef790764c9e6ff4f652c41a5af1d5da3e4d98733 | 46,813 |
def create_annotation_ce_target(creator: str, field: str = None, fragment: str = None):
"""Return a mutation for making an AnnotationCETarget.
An AnnotationCETarget is a node that can be used for a
web Annotation (https://www.w3.org/TR/annotation-model)
as the target field, when the target refers to a n... | dc7219cc02f22dcb8e230c7e376becf8712f71bc | 46,814 |
def sg_put(gid, chid, value):
"""perform a `put` within a synchronous group.
This `put` cannot wait for completion or for a a callback to complete.
"""
if not isinstance(chid, dbr.chid_t):
raise ChannelAccessException("not a valid chid!")
ftype = field_type(chid)
count = element_count(... | 479f5750871a76b676c3868fe9ae094c8b7eb748 | 46,815 |
def do0(*items):
"""Like do, but return the value of the first item.
Examples::
y = do0(17,
assign(x=42),
lambda e: print(e.x),
print("hello from 'do0'"))
assert y == 17
y = do0(assign(x=17), # the first item can be an assignment, too
... | 7491eae056ecb9f32d0dfc5f7cac6a4b13074917 | 46,816 |
def TransformScope(r, *args):
"""Gets the /args/ suffix from a URI.
Args:
r: A URI.
*args: Optional URI segment names. If not specified then 'regions', 'zones'
is assumed.
Returns:
The URI segment after the first /*args/ in r, the last /-separated
component in r if none found.
Example... | f3521519d8beb4863e843799a468e1a339b7a947 | 46,817 |
def variational_mfvi_sample(n_sample, qf_mean, qf_sdev,
mfvi_mixture=False, mixture_par_list=None,
**kwargs):
"""Generates f samples from GPR mean-field variational family.
Args:
n_sample: (int) number of samples to draw
qf_mean: (tf.Tenso... | c643f737541654c200dda2ba784a4168bd3f8e0e | 46,818 |
def recode_mark(mark, mark_shouldbe, no_mark="XX"):
"""A little helper function to remap clips to standard values that can
then be parsed.
Replaces BP with LPRP so ADBP becomes ADLPRP.
Arguments:
- `mark`: A mark string returned by the glfc database.
- `mark_shouldbe`: a dictionary mapping va... | ea31126d8b3d6e519a1f376f4ef58bfdbc24914a | 46,819 |
import os
def parse_rxn_class_file(job_path):
""" Read the class dictionary
"""
if os.path.exists(os.path.join(job_path, CLA_INP)):
print(' class.dat found. Reading contents...')
cla_str = ptt.read_inp_str(job_path, CLA_INP, remove_comments='#')
cla_dct = _build_cla_dct(cla_str)
... | 21104de5f77b87616601e3798a7aa0b8a6906b15 | 46,820 |
def select_copy_number(query, query_id):
"""
Execute copy-number query and return results
"""
cur = connection.cursor()
cur.execute(query, (query_id,))
rows = cur.fetchall()
values = []
for row in rows:
value = CopyNumberValue(entrez_gene_id=row[0], depmap_id=row[1], value=r... | 57049e1bccbd8685fca2a8ac488337b7fb47c9ea | 46,821 |
import os
def remove_extension_from_filename(filename: str) -> str:
"""
Return a filename without its extension
"""
return os.path.splitext(filename)[0] | 3aecca5e188c2a029f3e419070b55e5654fdb49c | 46,822 |
def read_single_camera_description(filename, camera_name):
"""
Read a specific camera description from a DL1 file
Parameters
----------
filename: str
camera_name: str
Returns
-------
`ctapipe.instrument.camera.description.CameraDescription`
"""
geom = read_single_camera_geo... | ecf0b89bd2f9815af4b695d9dea1d059746c1fa5 | 46,823 |
def _get_remains(courses):
""":param courses: list of (id, num) pair"""
return map(int, [i[u'课余量'] for i in val]) | 83a1c7596ff9594e3615bd7e7ffada6a675d3b4d | 46,824 |
from textwrap import wrap
def _update_doc(doc):
"""Add a list of plugins to the module docstring, formatted as
a ReStructuredText table.
"""
info = [(p, plugin_info(p)) for p in plugins() if not p == 'test']
col_1_len = max([len(n) for (n, _) in info])
wrap_len = 73
col_2_len = wrap_len... | ccba1a92ed5c7e0a62f31f020ccb3d2f2ef2f157 | 46,825 |
import sys
import os
import re
def preprocess(infile, outfile=sys.stdout, defines=None,
force=0, keepLines=0, includePath=None, substitute=0,
contentType=None, contentTypesRegistry=None,
__preprocessedFiles=None):
"""Preprocess the given file.
"infile" is the inpu... | 3bec5110e393375b8468de2506e53b775b00e494 | 46,826 |
def IDO(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2017-11-03", **kwargs
) -> Graph:
"""Ret... | 58c2f1886290390a3895de4fc946d5bf97bf9001 | 46,827 |
def scrape_detail(url):
"""
scrape detail page and return its html
:param page: page of detail page
:return: html of detail page
"""
return scrape_page(url) | 65a5bf44eef3da76b09f8b69f1d20fa59e31d569 | 46,828 |
import argparse
import os
def parse_command_line():
"""Parse the command-line options."""
formatter_class = argparse.ArgumentDefaultsHelpFormatter
description = 'Clang-format: Allow CHKERRQ to be on same line.'
parser = argparse.ArgumentParser(description=description,
... | 9f49b12e49bfe21caa7e179fadfb35cee7be35c5 | 46,829 |
def build_phone_encoder(features, speaker_labels, feature_length, params, endpoints, reuse_variables, is_training=False):
"""Build encoder for phone latent variable.
Use the tdnn and share the same structure in the lower layers.
Args:
features: the input features.
speaker_labels: the speake... | 950ed3fdb25531f8fd9542235cd2d18279c5d70a | 46,830 |
def from_probit(func):
"""
Evaluate a function that samples points in probit space and return these points after transforming them to natural space
"""
def f_transf(ref, *args, **kwargs):
y = func(ref, *args)
return transform_from_probit(y, ref.bounds)
return f_transf | 30c6b28829369b67869b91536dda356cb37c7cdd | 46,831 |
def token_is_valid(token):
"""Validate a checkout token."""
if token is None:
return False
if isinstance(token, UUID):
return True
try:
UUID(token)
except ValueError:
return False
return True | deceee5b33eddec2f80bff5de73bf13864b61e4b | 46,832 |
def shortest_path(map, dest, default_value = 0, block_value = 1):
""" Find shortest-path field
:param map: the proposed map (2-d)
:param dest: the goal, a point
:param default_value: the identifier for default cell
:param block_value: the identifier for block cell
:return: floor field and a dis... | fadcddd9cbccc88e21939515e8d31fe0755b8854 | 46,833 |
import ast
def _ast_eval(node):
"""
Performs an algebraic syntax tree evaluation of a unit.
"""
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
ast.USub: op.neg}
if isinstance(node, ast.Num): # <number>
... | b0eb1763aa17bca01350f5a6f65bc52894533682 | 46,834 |
from typing import Iterable
from typing import Any
def getWriteOutColour(
colour: Iterable[Any], convertType: type = int, multiplier: int = 255
) -> list[Any]:
"""getWriteOutColour"""
return [convertType(col * multiplier) for col in colour] | b81784b8e6fcce6a1479b710bc59b0db9c94241c | 46,835 |
from typing import Optional
from typing import Type
from typing import Callable
from typing import Awaitable
from typing import List
from typing import Any
from typing import Dict
import json
import logging
import inspect
def cache(
backend: "redis_helper.RedisHelper",
expire: Optional[int] = None,
namesp... | 579e05b4563aa403e7653ec2111bfe950ca07e10 | 46,836 |
from typing import Dict
from typing import Any
def create_tsmp_placeholders(
name: str,
model_start_time: pd.Timestamp,
end_time: pd.Timestamp,
run_dir: str,
tsmp_config: Dict[str, Any],
cycle_config: Dict[str, Any]
) -> Dict[str, Any]:
"""
This function creates... | 4e0920228bbae25f3c81e0433e8352962b7a180e | 46,837 |
import re
import json
def getIdsOfCities(session, all=False):
"""Gets the user's cities
Parameters
----------
session : ikabot.web.session.Session
Session object
all : bool
boolean indicating whether all cities should be returned, or only those that belong to the current user
... | 30dde3974095cd4ef037371dc06194c6bc9ffb46 | 46,838 |
def tx_collector():
"""A helper to deduplicate transactions"""
def snowflake():
txids = set()
txs = []
while True:
tx = yield txs
if tx:
if tx.id not in txids:
txids.add(tx.id)
txs.append(tx)
... | d164db9f30c8458a17d3e9d929f2e76d3b19154d | 46,839 |
def initialize_model_from_run(run_id):
"""
Initialized a model based on a run_id (i.e., using the exact
same parameter settings)
Parameters
----------
run_id : int
The Openml run_id
Returns
-------
model : sklearn model
the scikitlearn mo... | 1b766d94e1db90cb35717aed433e113b116b044b | 46,840 |
import os
import inspect
def make_cost_function(file_name='cubic.dat', minimizers=None,
max_runtime=None):
"""
Helper function that returns a simple fitting problem
"""
options = Options()
if minimizers:
options.minimizers = minimizers
if max_runtime:
opt... | 6e20d310afb8fcd7fe8c396b63dcfa5fee5645fe | 46,841 |
def get_block_header_by_hash(block_hash, db):
"""
Returns the header for the parent block.
"""
return db.get_block_header_by_hash(block_hash) | 96b5ec740e6286baa55140dd6467bfcc6a8e035b | 46,842 |
def extract_meta_lang(html):
"""
Returns the meta_lang of the HTML provided or None if unsuccessful
:param html:
:return: meta_lang | None
"""
meta_lang = None
try:
goose_config = {'enable_image_fetching': False}
goose = Goose(goose_config)
article = goose.extract(r... | aa0aa7454394107abb9ce52c16219969b06179a3 | 46,843 |
from imp import load_source
from importlib.machinery import SourceFileLoader
from importlib.util import spec_from_file_location, module_from_spec
import sys
def import_file(name, location):
"""
Imports the specified python file as a module, without explicitly
registering it to `sys.modules`.
While pu... | c87093f3304264b83f673caddccf76126fc9311b | 46,844 |
import time
import requests
def collect_data(post_id, duration):
"""
Collects data every 30 secs for {duration} hours on post with {post_id}.
Stores data as a list of objects. Each object contains the number of likes
the post has and the time in secs.
Args:
post_id: String -- id of the post t... | e08376cb710ff8f0e050e992ebdf84a47ce05da5 | 46,845 |
def filter_tags(tags: dict, tag_filter: dict) -> bool:
"""filter tags based on a tag filter"""
including = False
includes = tag_filter['includes']
if 'tag-keys' in includes:
including = any(key in tags for key in includes['tag-keys'])
if not including:
if 'tag-key-values' in include... | 74141ec75ab5551765589411f8746bd448038262 | 46,846 |
def load_ls(ls_path,px_size=1.):
"""Loads a linescan file
Args:
ls_path (str): path of the average linescan file to be loaded
px_size (float): pixel size in microns
Returns:
x (numpy array): the positions (in microns)
i (numpy array): the intensities
"""
ls_data =... | b9c984d020741c373f89c3cb0236fe5a8c2029f6 | 46,847 |
def add_frame_div_parent(cell_info):
"""
Adds the frame a cells parent divides on to cell info.
Args:
cell_info (dict): dict that maps cells to cell info
Returns:
dict: cell info with added frame_div_parent
"""
new_info = cell_info.copy()
for info in new_info.values():
... | 585feeaaf2a353ea2481cda41d547a004ecb8adc | 46,848 |
def _binary_search(alloc, p, d):
"""Compute step length using the binary search long step from BGKL.
Parameters
----------
alloc: AllocationProblem
Allocation problem instance
p: np.ndarray
Price vector.
d: np.ndarray
direction vector s.t. d in {0,1}^n.
Retu... | a1a43651f799f0734296b3ef4fc065a684f5efad | 46,849 |
def feature_engg(df: pd.DataFrame) -> pd.DataFrame:
"""Feature engineering function"""
numeric_feats = df.dtypes[df.dtypes != "object"].index
skewed_feats = df[numeric_feats].apply(
lambda x: skew(x.dropna())
) # compute skewness
skewed_feats = skewed_feats[skewed_feats > 0.75]
skewed_f... | 685c8ba7f6a72ab4912caa19a1024d77b29290c8 | 46,850 |
def upsample(layer, k, s, layer_name):
""" Return the output of transpose convolution given kernel_size k and strides s """
return tf.layers.conv2d_transpose(inputs = layer,
filters = NUMBER_OF_CLASSES,
kernel_size = (k, k),
... | 4f30af47b7665f353bfbd40b2a577f708081eac9 | 46,851 |
def get_data_size_recursively(data) -> int:
"""
Deprecated (Only for revision 2 and below).
Returns size of data(input data or deploying content) by recursive traversal
:param data: input data or deploying content
:return: size of data
"""
size = 0
if data:
if isinstance(data, d... | 0717fcae7377f56da069696e5b6b73ff5ba518eb | 46,852 |
def _to_array_1d(scalar_or_array, arrlen, dtype=float):
"""
A helper function for writing forces that can accept either a single parameter,
or an array of per-particle parameters.
If passed a scalar, it converts it to an array of the length arrlen.
If passed an iterable, it verifies that its leng... | 1107af19f882778a179d9ce40d6bab15d618f0f8 | 46,853 |
import os
def generate_entropy(strength: int = 128) -> str:
"""
Generate entropy hex string.
:param strength: Entropy strength, default to 128.
:type strength: int
:returns: str -- Entropy hex string.
>>> from pybytom.utils import generate_entropy
>>> generate_entropy(strength=128)
... | 270a0d55eaef42e4372bc1115b58f76caad4f796 | 46,854 |
def add_datafile2session(db_session, date_obs, data_provider, data_type, fname_raw,
fname_hdf="", flag=0):
"""
:param db_session: sqlalchemy.orm.session.Session
SQLAlchemy session object
:param date_obs: datetime.datetime
The observation ... | 72bbfabd870eeb015f2f5ad166f7def5fadbd062 | 46,855 |
import numba
def gingerbreadman(n_points: int = 10**6, x_0: float = 1.5, y_0: float = 2.6) -> PlotData:
"""
Calculates a list of (x, y) points according to the Gingerbreadman Map
https://en.wikipedia.org/wiki/Gingerbreadman_map
:param n_points: The number of (x, y) plot points to calculate
:param... | bbbdac680975c88fe3d054f0ab2de002d36c51b8 | 46,856 |
def focal_starting_points(
recording_meta: dict,
seizure_types: list = None):
"""Return a list of dictionaries which contain the focal events.
Here the interest is only on the starting points.
Args:
recording_meta: a dictionary which contains the metadata
of the recording.
... | 5fe79d5be10bfb65f32e1c2305f4b228f752ca61 | 46,857 |
import torch
def nanmean(arr, dim=None, keepdim=False):
"""
Compute the mean of an array ignoring any NaNs.
RH 2021
"""
if dim is None:
kwargs = {}
else:
kwargs = {
'dim': dim,
'keepdim': keepdim,
}
nan_mask = torch.isnan(arr)
arr_no... | b7ca5d59b1f3a43893511433acc7fd5611584beb | 46,858 |
def max_area_index(labels, num=None):
"""
Return index of maxmum labeled area
"""
mx = 0
mxi = -1
un = np.unique(labels)
# kick out zero
un = un[un != 0]
for l in un:
mxtmp = np.sum(labels == l)
if mxtmp > mx:
mx = mxtmp
mxi = l
return mxi | 8bdd3309604689c7a4102b92530b0e4595673f77 | 46,859 |
def basic_cell(args, i, unit_mul):
""" Construct the basic cell. """
c = tf.contrib.rnn.LSTMCell(
args['num_units']*unit_mul,
# dropout_keep_prob=args['dropout']
)
c = tf.contrib.rnn.DropoutWrapper(
cell=c, input_keep_prob=(1.0 - args['dropout']))
if i > 1:
c = ... | b7cb3cfe3ca4531ec5ae61a1dbe4353cb64c9184 | 46,860 |
import os
def pathToApp(location, app):
"""Return path to the app in the given location/repository."""
return os.path.join(repositoryRoot(), location, 'apps', app) | 0368cedb671d1838cbacc5e2b254c9f5c01be654 | 46,861 |
def get_msg_time(msg, zerotime):
""" Переводит бортовое время сообщения в текущее
С учетом того, что когда на борту было 0, на земле было (какбудто) zerotime
и с учетом того, что настоящее время тикает в дробных секундах
"""
if hasattr(msg, "time_boot_ms"):
return msg.time_boot_ms /... | 94d0a9ca50fd9303723577caeec896712fb1517a | 46,862 |
import json
def getAuditLogsWithDecision(decisionUuid, user):
"""
expected: decisionUuid(string), user(object)
result: all audit logs objects that attached to a decision \
would be returned in a json.
"""
data = dict()
if decisionUuid == '' or not user:
msg = "checklistUuid or user... | 01a9d5584702d965ff3a65de6c5217e107c8a816 | 46,863 |
import sqlite3
def db_create(db_path="main.db"): # noqa: D205, D400
"""Check that the database doesn't exist, create the database, create the
tables, finally connect to the database.
Use os.path.isfile() on the database path to check if the file exists.
Connect to the database. Set the conn.isol... | 2d96696d3589e4c438a80070164126274bc5c8ba | 46,864 |
import functools
import traceback
def signal_wrapper(func):
"""
Signal fail-safe wrapper
:param func: original signal
:return: fail-safe signal function
"""
@functools.wraps(func)
def _signal_wrapper(*args, **kwargs):
"""
Wraps original signal wrapper with try
"""
... | cef6369828636ba704b4c3675c33f5242019baaa | 46,865 |
def kml_to_dict(kml_file):
"""
Reads the supplied KML file and returns a dictionary with datetime
keys and descriptions/coordinates (lists of (lon,lat,ele) tuples) as
values. Can contain one level of subfolders as subdictionaries.
"""
print(f"Reading KML from \"{kml_file}\"...")
def placema... | 6d4e735732e8b8fdea87248b1e1b3aecf6fbc9ad | 46,866 |
import sys
import stat
from datetime import datetime
def _harvest_files(prospectors, logger):
"""Traverse all specified prospector paths and determine uncataloged files."""
discovered_files = []
# List of files specified explicitly in the prospectors
absolute_file_paths = [path for x in prospectors f... | b3b3ed4b36c368428262c07b4704ca7cd0711c99 | 46,867 |
import os
from re import VERBOSE
def parse_result_file(result_file: str) -> float:
"""Load mIoU from .txt result file."""
if not os.path.isfile(result_file):
if VERBOSE:
print(result_file + " does not exist!")
return 100000
with open(result_file, "r") as f:
tmp = f.rea... | 3c92c6f8ac7d26f7a2627554b699c4a5c0ee1130 | 46,868 |
def load_intron_vector(table, session):
"""
load intron vector entries for this gene. Wrapper for generic_gene_query.
:param table: One of the intron vector tables
:param session: Active sqlalchemy session.
:return: DataFrame
"""
assert any(table == cls for cls in (TmIntronSupport, AugCgpInt... | 4034002b2c3d9cd42a250adaf6f8beff5042cef1 | 46,869 |
import os
def load_class_info(splits_dir):
"""
Load list of class names
Returns
-------
Numpy array of shape (N) containing strs with class names
"""
print("Loading class info...")
class_info = np.genfromtxt(os.path.join(splits_dir, 'info.txt'), dtype='str', delimiter='/n')
return ... | eeb423f5ce9d03dc8ea495cc94112ae12aed7e17 | 46,870 |
def polar_err(r, phi, r_e, phi_e):
"""polar errors for r and phi"""
# print(r, phi, r_e, phi_e)
dxdr = np.cos(phi)
dxdphi = r * np.sin(phi)
dydr = np.sin(phi)
dydphi = -r * np.cos(phi)
x_e = np.sqrt((dxdr * r_e) ** 2 + (dxdphi * phi_e) ** 2)
y_e = np.sqrt((dydr * r_e) ** 2 + (dydphi * ph... | 2cf7f68bcd5d3a09dd8442a23f904bba9828cc06 | 46,871 |
async def get_textchannel_chatlog(text_channel: discord.TextChannel, limit: int = None):
"""
Returns a TextChannel chatlog
:param text_channel: The text channel for the data to be gathered from
:param limit: An integer to limit the amount of messages retrieved.
:return: String
"""
all_messa... | dfde857bca4d5ba086c194423e65f9a57f0f3bb4 | 46,872 |
import string
def clean_sort(words):
"""A function for cleaning and prepping words for techniques.
Args:
words (list): The list of words
Returns:
list: An updated word list with words cleaned and sorted.
"""
if isinstance(words, basestring):
return words
chars = '!"#$... | 353c1b9ec0b6a29c627dee33b0833e83e4318f59 | 46,873 |
import functools
import os
import time
def add_request_logger(logger):
"""
Add logging functionality to a request function.
Only shows logs for `JINA_LOG_LEVEL` > info.
You can set this as an env variable before starting your `Jina` application.
Example usages:
>>> from jina import Executor, ... | fe78228dc6e0c7b1078c38a5d80860b5d1109397 | 46,874 |
def source_to_neutrino_direction(azimuth, zenith, radian=True):
"""Flip the direction.
Parameters
----------
zenith : float
neutrino origin
azimuth: float
neutrino origin
radian: bool [default=True]
receive + return angles in radian? (if false, use degree)
"""
a... | fca46e24e93ee996542c8ca5c3b6f553daa8068a | 46,875 |
def __virtual__():
"""
Only return if all the modules are available
"""
log.debug("rapyutaio proxy __virtual__() called...")
return True | 27a57bbcba0d311097d202def05d20b3bee4258b | 46,876 |
import os
import tempfile
import subprocess
import sys
def update(
cipd,
package_files,
root_install_dir,
cache_dir,
env_vars=None,
):
"""Grab the tools listed in ensure_files."""
if not check_auth(cipd):
return False
# TODO(mohrr) use os.makedirs(..., exist_ok=True).
if ... | cc227778be77159ff31e93caa8412c8f61937701 | 46,877 |
from typing import Optional
from typing import Tuple
def preprocess(
x: np.ndarray, y: np.ndarray, nb_classes: int = 10, clip_values: Optional["CLIP_VALUES_TYPE"] = None,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Scales `x` to [0, 1] and converts `y` to class categorical confidences.
:param x: Data ins... | 541c3d27b48c017aa23ca7ca08522b8371ad42ee | 46,878 |
from typing import Optional
def partition_softmax(logits: ArrayTree,
partitions: jnp.ndarray,
sum_partitions: Optional[int] = None):
"""Compute a softmax within partitions of an array.
For example::
logits = jnp.ndarray([1.0, 2.0, 3.0, 1.0, 2.0])
partitio... | 89704d75fb147129364b1d555857c1bb1bb2355c | 46,879 |
def split_pem_chain(pem_text):
"""
splits a PEM chain into multiple certs
"""
_certs = CERT_PEM_REGEX.findall(pem_text.encode())
certs = [cleanup_pem_text(i.decode("utf8")) for i in _certs]
return certs | 95a96aa569bc0d768d0dada85d913f593cd732f4 | 46,880 |
def logser_ll(x, p, upper_trunc = False, upper_bound = None):
"""Log-likelihood of a logseries distribution
x - quantiles
p - lower or upper tail probability
upper_trunc - whether the distribution is upper truncated
upper_bound - the upper bound of the distribution, if upper_trunc is True
... | 02238c0206b16511ecd71b5f70feaab902207c21 | 46,881 |
import os
import json
def ecm_list_market_update(ecm_folder, active_list, inactive_list,
filters, market_cat):
"""Update the active and inactive lists based on the user-selected filters
Based on the filters identified by the user for a given baseline
market parameter, this func... | 3192faa6b1bb96b6083c706805529f0db4895a71 | 46,882 |
import inspect
def get_instances_of(cls, context):
"""从 context 中获取所有类型为 cls 的实例"""
if type(context) is not dict:
names = dir(context)
context = {k: getattr(context, k) for k in names}
objects = []
for name, value in context.items():
value_type = type(value)
if inspect... | f95eae2039f2b8b2bcfb09adbd09e24abb6dba48 | 46,883 |
import os
def find_all_files_in_directory(AFileClass, root_dir, excluded_directories, search_extensions, gauge_update_function=None):
"""Recursively searches a directory for files. search_extensions is a dictionary of extension lists"""
global TEXT_FILE_SIZE_LIMIT
all_extensions = [ext for ext_list ... | 8b0a75d72056dfc57d0b7ae937f9c27140c1f6e0 | 46,884 |
def parse_edges_graphml(fin):
""" Turns a GraphML (.graphml) file into a list of edges
Args:
filename (str): Full path to the *.insts file
Returns:
list[Graph]: Graph objects parsed from the *.insts file
Note: This only expects the file format generated from a specific script
See:... | 4a867a133b7f06f5a22bbb15e70167e2fa71ccd6 | 46,885 |
def GetEffectiveEndpoint(version, region, is_prediction=False):
"""Returns regional AI Platform endpoint, or raise an error if the region not set."""
endpoint = apis.GetEffectiveApiEndpoint(
constants.AI_PLATFORM_API_NAME,
constants.AI_PLATFORM_API_VERSION[version])
return DeriveAiplatformRegionalEndp... | a2924e05584905cf1647338e6d42aa759e8d0b92 | 46,886 |
def global_avg_pool2d(attrs, args):
"""Check if the external ACL codegen for global_avgpool2d should be used."""
typ = args[0].checked_type
if typ.dtype not in ["float32"]:
return False
if attrs.layout != "NHWC":
return False
return True | 0f06f0dfaa7409af3bd37708b74e68fa02164b4d | 46,887 |
import string
import os
def modifyPathsForEnvVar(action, env_var_name, path, should_set_env_var=False):
""" Modify the set of paths for the given environment variable
and returns a string to be used to set the environment variable.
"""
logger.debug("Modifying path for '%s' with action '%s' (%s)...... | babab40d65ad400f29b739d4343da0e190ca3fd2 | 46,888 |
def purpleair_us_corr(df, param):
"""US-Wide Correction equation of Barkjohn et al. 2021 for PurpleAir PA-II
sensors.
Publication Link:
https://amt.copernicus.org/articles/14/4617/2021/
Args:
df (pandas dataframe):
Dataframe with PurpleAir PA-II concentration values for PM2... | 9a61af20cc6178de099a31f38215044da0eb0bc2 | 46,889 |
import logging
def _validate(address, userid, password, device_type, ssh_key=None):
""" Validate the password, address and userid information
Args:
address: ip v4 address for the device to validate
userid: userid of the device to validate
password: password for the device
d... | 04f1a75468b68263e89a0e8865dc46d27ec1c6c3 | 46,890 |
def generate_querystring(params):
"""
Generate a querystring suitable for use in the v2 api.
The Requests library doesn't know how to generate querystrings that encode dictionaries using square brackets:
https://api.mollie.com/v2/methods?amount[value]=100.00&amount[currency]=USD
Note: we use `sort... | 93139f54d809d02fcc36deec6ac00f381d16e5bd | 46,891 |
def mobilenet(images, depth_multiplier=1.0):
"""
Arguments:
images: a float tensor with shape [batch_size, height, width, 3],
a batch of RGB images with pixel values in the range [0, 1].
depth_multiplier: a float number, multiplier for the number of filters in a layer.
Returns:
... | abd908c809aebfb01c275c55165c48a0f8f03575 | 46,892 |
def PIsA (inFitRegion):
"""
Tells if input really a Python Obit FitRegion
return True, False
* inFitRegion = Python FitRegion object
"""
################################################################
if not isinstance(inFitRegion, FitRegion):
print("Actually is",inFitRegion.... | 9edc91a531e28c051ff9b5457d8d71a4a3681177 | 46,893 |
from qt_style_sheet_inspector import StyleSheetInspector
def GetStyleSheetInspectorClass():
"""
Indirection mostly to simplify tests.
"""
try:
except ImportError as error:
msg = 'You need to Install qt_style_sheet_inspector.'
raise RuntimeError(msg)
return StyleSheetInspector | 842092916b76dee8f74a491da20d8bb0565aa029 | 46,894 |
def densenet_100_24(**kwargs):
"""
Constructs a DenseNet {L = 100, k = 24} model.
"""
return DenseNet(BasicBlock, 100, [[16, 16], [32]], 24, 1, **kwargs) | a103685307c19284885660c0f34bdde341c1b417 | 46,895 |
def arrow_3d(arrow_length=10, x_label="x", y_label="y", z_label="z"):
"""
Create 3d arrow with labels
:param arrow_length: specify arrow length
:param x_label: label for x axis
:param y_label: label for y axis
:param z_label: label for z axis
:return: return 3d arrow as an actor. Can be tran... | bfe6e43b20ada548f1a7fd50a90f06adf33af605 | 46,896 |
def apply_phases(params, input_pairs, model_vis=1.0):
"""Apply relevant antenna phases to model visibility to estimate measurements.
This corrupts the ideal model visibilities by adding a set of per-antenna
phases to them.
Parameters
----------
params : array of float, shape (N - 1,)
A... | 4ff9d63f8a2314238c69a11ad24e4023c3b4fb5e | 46,897 |
def point_face_distance_truncated(meshes: Meshes, pcls: Pointclouds):
"""
`point_face_distance_truncated(mesh, pcl)`:
Computes the squared distance of each point p in pcl
to the closest triangular face in mesh and averages across all points in pcl
The above distance function is applied for all ... | aea6624f000609266e221ca2cbdeb49ba26cfd81 | 46,898 |
import glob
import os
def read_data(item):
"""reads data """
mesh_filename = glob.glob(os.path.join(item, '*.obj'))[0] # assumes one .obj file
mesh = trimesh.load(mesh_filename)
return mesh | c3be106809528356e88a4d2c9550990a773ba193 | 46,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.