content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Union
import re
def import_maxquant_data(
file: str,
sample: Union[str, list, None] = None
) -> pd.DataFrame:
"""Import peptide level data from MaxQuant.
Args:
file (str): The name of a file.
sample (Union[str, list, None]): The unique raw file name(s) to filter the... | 28238068b0703388909a5f90ca651ce5ebc74e06 | 37,200 |
def get_z_from_freq(obs_freq):
""" Convert observed frequency to (measured) redshift
Parameters
==========
obs_freq: float
Observation (central) frequency in units of Hz !
Return
======
z: float
Measured redshift
"""
z = ( _HI_RESTFREQ / obs_freq ) - 1.
return ... | ad7f7d24a8dd1e8aa858563ba27be5c7f829378d | 37,201 |
import array
def R_to_orientstring(R):
#************************
"""
Purpose: Convert transformation matrix to 3-character string
defining orientation (e.g., RAI, LPI etc)
Arguments:
R: 4x4 transformation matrix
Returns:
orientation: A 3-character string.
"""
#LPI ... | 4687919dac1dd743d2aa096fa8a569263577211d | 37,202 |
def get_executor():
"""
Gets executor from the current event thread if applicable. If not, starts a new one.
Returns
-------
executor : ``ExecutorThread`` or ``ClaimedExecutor``
"""
loop = current_thread()
if isinstance(loop, EventThread):
executor = loop.claim_executor()
... | 3d0e60f159896ff5c94d9c01d75e7c4101045cbd | 37,203 |
def shape4(tik_instance, input_x, res, dtype):
"""input shape (32, 8, 28, 28, 16)"""
zero = tik_instance.Scalar(dtype="float16", init_value=0)
with tik_instance.for_range(0, 32, block_num=32) as block_idx, tik_instance.for_range(0, 2) as cc1_db, \
tik_instance.for_range(0, 2, thread_num=2) as db... | 5150f7637e495d74f7a858eca4a59b25b425e219 | 37,204 |
def parse_person(elt):
"""Parse a person type response element into nested dictionaries
http://developer.healthvault.com/sdk/docs/urn.com.microsoft.wc.thing.types.person.1.html
"""
return dict(
name = elt.find('name').text,
organization = text_or_none(elt, 'organization'),
profe... | 2429102554e09e2b5fc8297c6f86e903db366826 | 37,205 |
def to_absolute_coordinates(keypoints, height, width,
check_range=True, scope=None):
"""Converts normalized keypoint coordinates to absolute pixel coordinates.
This function raises an assertion failed error when the maximum keypoint
coordinate value is larger than 1.01 (in which case ... | c337fd7b332b2c9a5ef9ca0a6dd59b9c937bbbef | 37,206 |
def get_zygosity(call):
"""Check if a variant position qualifies as a variant
0,1,2,3==HOM_REF, HET, UNKNOWN, HOM_ALT"""
zygdict = dict([(0, "nocall"), (1, "het"), (2, "nocall"), (3, "hom")])
return zygdict[call] | aff88ed481beeb6406261822eca482430494b6f6 | 37,207 |
def discrete_mutual_info(mus, ys):
"""Compute discrete mutual information."""
num_codes = mus.shape[0]
num_factors = ys.shape[0]
print(mus.shape,ys.shape)
m = np.zeros([num_codes, num_factors])
for i in range(num_codes):
for j in range(num_factors):
m[i, j] = sklearn.metrics.mutual_info_score(ys[j... | dcc81d137bcce2f358bb5e796ba034641aed7e56 | 37,208 |
import os
def get_stderr(self, uid, iwd, out, err, job_id, job_name=None, instance_id=-1):
"""
Return the stdout from the specified job
"""
if instance_id > -1:
if os.path.isfile('%s/job.%d.err' % (iwd, instance_id)):
with open('%s/job.%d.err' % (iwd, instance_id), 'rb') as fd:
... | 1b918b93550d425d4a55e430ad81259ee872933f | 37,209 |
import torch
def create_batch(sentences, params, dico):
""" Convert a list of tokenized sentences into a Pytorch batch
args:
sentences: list of sentences
params: attribute params of the loaded model
dico: dictionary
returns:
word_ids: indices of the tokens
lengths... | c08430651ea20f633169187f62f7b22e09bbd17e | 37,210 |
def path_label_squeeze(paths):
"""Returns a weights sum of paths solutions, for visualization."""
v_range = tf.range(1, tf.shape(paths)[-1] + 1, dtype=paths.dtype)
return tf.einsum('ijkn,n->ijk', paths, v_range) | cd2300b83abd8294cb78800142c1616ae918df7a | 37,211 |
def _Hz2Semitone(freq):
"""_Hz2Semitone."""
A4 = 440
C0 = A4 * pow(2, -4.75)
name = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
if freq == 0:
return "Sil" # silence
else:
h = round(12 * log2(freq / C0))
octave = h // 12
n = h % 12
r... | 9ca4fe4cad8e01971756d5c09c9cefd6ad62b69f | 37,212 |
def uCSIsCatLt(code):
"""Check whether the character is part of Lt UCS Category """
ret = libxml2mod.xmlUCSIsCatLt(code)
return ret | a4c95edf37dd9d9a462ce3176d8cfd5ed152b878 | 37,213 |
def export_file(isamAppliance, path, name, filename, check_mode=False, force=False):
"""
Exporting a file from the runtime template files directory
:param isamAppliance:
:param path:
:param name:
:param check_mode:
:param force:
:return:
"""
warnings = []
check_file = _check... | c7b71462b3aab32b34fa24153bad502764f155c4 | 37,214 |
from typing import List
def make_pos_array_and_diff(trials: List[dict]) -> List[dict]:
"""
Parameters
----------
trials : Non-filtered refinement trials
Returns
-------
A list of dictionaries with updated position and difference of neighbours
"""
_trials = trials[:]
for i, c... | ebdb0a63d9399985d11b06ec28d4032a54b22f89 | 37,215 |
import collections
import itertools
import torch
def test_log_works_in_train_callback(tmpdir):
"""
Tests that log can be called within callback
"""
class TestCallback(callbacks.Callback):
# helpers
count = 1
choices = [False, True]
# used to compute expected values
... | a20e619abd567144e9f3e30c459c7aa4ceccda36 | 37,216 |
def a(O, R_r, E, aggregator='sum', include_v=True):
""" Applies and returns the aggregating function of the Interaction Network
Parameters
----------
O : numpy.ndarray
Object matrix
R_r : numpy.ndarray
Binary matrix that indexes the receiver objects
E : numpy.ndarray
Predict... | d54caf23ec9090edbacab012a494798fa3875f79 | 37,217 |
def coords_json_to_api_pan(ang_clockwise):
"""converts from robot coordinates to API coordinates."""
return ang_clockwise | 6511b7cf196a171095b184d48281f25f97fc6792 | 37,218 |
import copy
import six
import warnings
from typing import Iterable
def polnum2str(num, x_orientation=None):
"""
Convert polarization number to str according to AIPS Memo 117.
Uses 'pI', 'pQ', 'pU' and 'pV' to make it clear that these are pseudo-Stokes,
not true Stokes
Parameters
----------
... | 5d6fab5d1e2c66db6d9dedd966a826090791c954 | 37,219 |
async def delete_me(twofa: Code2FA, user: UserPass = Depends(is_connected_pass)) -> User:
"""Delete your user."""
if user.totp is not None:
if twofa.code is None or not twofa.verify(user):
raise HTTPException(
status.HTTP_401_UNAUTHORIZED,
"Un code de double a... | c17a4eec312d9e6ad4a2ec8ef936d26d5a60b853 | 37,220 |
from typing import Type
def should_unwrap(obj: Type[ObjectT]) -> bool:
"""Test whether we should use the __args__ attr for resolving the type.
This is useful for determining what type to use at run-time for coercion.
"""
return (not isliteral(obj)) and any(x(obj) for x in _UNWRAPPABLE) | 9a8c391b692c22fd836f01cf6f186ccdcaa16ae2 | 37,221 |
def normalize(net,nodesToIndices=None,layersToIndices=None,nodeStart=0,layerStart=0):
"""Returns a copy of the network with layer and node indices as integers.
In network with n nodes the nodes are renamed so that they run from 0 to n-1.
In network has b_a elementary layers in aspect a, the layers are rena... | 37e494ded554b5a6dbbb366066bedf6b8ec033e8 | 37,222 |
def dict_other_json(imagePath, imageData, shapes, fillColor=None, lineColor=None):
"""
:param lineColor: list
:param fillColor: list
:param imageData: str
:param imagePath: str
:return: dict""
"""
# return {"shapes": shapes, "lineColor": lineColor, "fillColor": fillColor, "imageData": im... | 3742664276d70ce5f037ba99994c8c2e61114107 | 37,223 |
import numpy
def draw_dot_singlearrows(fname, epsilon, invepsilon, morph_by_state, axs, ays, L_max, all_digits = False, save_dot = True):
"""
This function draws the .dot file associated with the
epsilon-transducer stored in epsilon+invepsilon.
This version works with *memoryful* transducers,
where we assume ... | 3d915f855ae2bd1050553b1f75d95d1ed8eacb82 | 37,224 |
import requests
def get_post(post_id):
""" Get the post. """
# Returns: (post_title, post_body, user_tuple)
route = '{}/api/v2.0/posts/' +\
'{}?key={}&filter=MLLKIHJMHIHKKFMJLLHGMKIMMGOKFFN'
response = requests.get(route.format(ms_config["ms_host"], post_id, ms_config["api_key"]))
tr... | a3a0027d6f83da7ef343a4e87b45cb6c3e9dd6c4 | 37,225 |
def track_from_filename(filename, filetype = None, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False):
"""
Create a track object from a filename.
NOTE: Does not create the detailed analysis for the Track. Call
Track.get_analysis() for that.
Args:
filename: A string containing the path to t... | 929ba302f05b975fd0ee42988a8835aa13ac6f4b | 37,226 |
from typing import List
def create_sectors_from_entities(
entities: List[Entity], created_by: Identity
) -> List[Identity]:
"""Create sectors from entities."""
sectors = []
for entity in entities:
sector = create_sector_from_entity(entity, created_by)
if sector is None:
co... | 256b3296420454514d938882f577b0a5bd005686 | 37,227 |
def minor1d(array1d, i):
"""Accept 1D array and return a new array with element i removed."""
range1 = list(range(i)) + list(range(i+1, array1d.shape[0]))
return array1d[np.array(range1)] | 63ef3f3093e9619d09079af71e0fb1ce769dea23 | 37,228 |
def get_ast_field_name(ast):
"""Return the normalized field name for the given AST node."""
replacements = {
# We always rewrite the following field names into their proper underlying counterparts.
'__typename': '@class'
}
base_field_name = ast.name.value
normalized_name = replacemen... | c5cf0acbca963e7dc0d853064a2599b732d6b0d1 | 37,229 |
def public_api(host_uri):
"""
Note: unlike the authenticated variant, this helper might get called even
if the API isn't going to be used, so it's important that it doesn't try to
actually connect to the API host or something.
"""
conf = fatcat_openapi_client.Configuration()
conf.host = host... | e35e4528e06d817f89ef6950590518745e06c76d | 37,230 |
import argparse
def main(observation=None, mask=None, outName=None, velStart=None, velEnd=None, velPixel=None, normDepth=None, normLande=None, normWave=None):
"""Run the LSD code.
Arguments are:
observation -- name of a spectrum file
mask -- name of the LSD mask file
outName -- name ... | 1c0f7992d0e1b64ea24eca814d9aa28f4ebd771b | 37,231 |
import os
import copy
from typing import OrderedDict
def draw_heatmap_fingerprints(
fluor_df, results_dir, scale, class_order=None, prefix='', test=False
):
"""
Draws a heatmap for each analyte representing the median reading for each
peptide
Input
----------
- fluor_df: Dataframe of fluo... | f41624a9f8bed2fb6a45db312580830c4e5b3d6a | 37,232 |
def convex_hull_3d(input, inputmsk=None, outhull=None, inhull=None, copy=False, copyoutside=True):
"""
Calculates 3D convex hull of non-masked voxels of an image.
By default, returns an image where inside-hull-voxels have value :samp:`inhull`
and outside-hull-voxels have value :samp:`outhull`.
:typ... | d7a6a9adb15b258ba737518a187db546a735a945 | 37,233 |
from typing import Any
def liquid_filter(_filter: FilterT) -> FilterT:
"""A filter function decorator that wraps `TypeError` in `FilterArgumentError`."""
@wraps(_filter)
def wrapper(val: object, *args: Any, **kwargs: Any) -> Any:
try:
return _filter(val, *args, **kwargs)
excep... | 1b6ed4bb26013af1cfe638e3e5cd36cce20c822a | 37,234 |
def end():
"""
Terminates a PyNGL script, flushes all buffers, and closes all
internal files.
Ngl.end()
"""
NhlClose()
return None | 072f8c4757492407d93a2eec6ce6607a2c823b00 | 37,235 |
import time
import os
import logging
from re import T
def unseven(nzo, workdir, workdir_complete, delete, one_folder, sevens):
""" Unpack multiple sets '7z' of 7Zip files from 'workdir' to 'workdir_complete.
When 'delete' is set, originals will be deleted.
"""
i = 0
unseven_failed = False
... | ff448cbd35eda0784137c4f70c279390a6134ce0 | 37,236 |
def check_home():
"""
Checks the button that is clicked from the home screen and returns the corrseponding values.Returns
1 if Play button is clicked, 3 if Instructions button is clicked, and 4 if About button is clicked
"""
global value, right_click
value = 0
mouse = pygame.mouse.get_pos()
if 370 <= mouse[... | fe10c9fbd15775c43fa2fafe87cef518b4db4a3a | 37,237 |
def olivine(piezometer=None):
""" Data base for calcite piezometers. It returns the material parameter,
the exponent parameter and a warn with the "average" grain size measure to be use.
Parameter
---------
piezometer : string or None
the piezometric relation
References
----------
... | 387ea9413acdf551abe108ba5ba7dda51e162c51 | 37,238 |
def serialize(value):
"""If the value is an BSON ObjectId, cast it to a string."""
if isinstance(value, bson.objectid.ObjectId):
return str(value)
else:
return value | 1fd0e01ebb46e4501b3a82744fcd3b2cdeaaf35b | 37,239 |
def stash_node_versions(node_id):
"""Gets all version of a node.
stash currently only keeps upto 10 versions.
"""
return stash_invoke('node-versions', node_id) | 5b0c32c6f3d45e18233d65255267652eca416d59 | 37,240 |
def ReEncode(outFileName):
"""\
Prefab.
Takes in audio and video frames and encodes them to a compressed video file
using ffmpeg to do the compression.
Inboxes:
- "inbox" -- NOT USED
- "control" -- Shutdown signalling
- "video" -- Video frames to be saved
- "aud... | 1a9208322843ac9090ce8a1c6ee217a0a4945609 | 37,241 |
from desiutil.log import get_logger, DEBUG
from desispec.io.util import header2wave
import multiprocessing
import os
def read_basis_templates(objtype, subtype='', outwave=None, nspec=None,
infile=None, onlymeta=False, verbose=False):
"""Return the basis (continuum) templates for a given o... | 3f815617f4088e0985259c0ce62ce943110ec153 | 37,242 |
import logging
import json
def readConfig(configFile):
# returns list of parameters
# with key 'name'
"""
reads the config file to dictionary
"""
logging.debug("Loading config")
with open(configFile) as json_file:
try:
d = json.load(json_file)
except:
... | 6cc0f1e631d8c1c6425bfefe080c5300c3e2acd4 | 37,243 |
from datetime import datetime
def predict_one_epoch(sess, ops, train_writer):
""" ops: dict mapping from string to tf ops """
is_training = True
# Shuffle train samples
# train_idxs = np.arange(0, len(TRAIN_DATASET))
# 预测不需要打乱
# np.random.shuffle(train_idxs)
# num_batches = len(TRAIN_DATA... | a48c7a309702f2e9db5a59d6ba50d3d1579d33f9 | 37,244 |
from typing import Tuple
import re
import typing
def hex_to_rgb(hex: str, hsl: bool = False) -> Tuple[int, int, int]:
"""Converts a HEX code into RGB or HSL.
Taken from https://stackoverflow.com/a/62083599/7853533
Args:
hex (str): Takes both short as well as long HEX codes.
hsl (bool): C... | 2c912dacfcf6c52c21c94c5d7bb9b9763279245d | 37,245 |
def connect(ctx, timeout=None):
"""
Returns a connection to the database. Does some initial-setup
too, though that's probably a bad design somehow.
The optional timeout parameter is an integer expressing the number of seconds
to set the underlying connection object to timeout after.
NOTE: Timeo... | d2fc5eaccb24907c72a0bed29cfb057a957514d3 | 37,246 |
def load_burn_data(url) -> xr.Dataset:
"""Open a GeoTIFF into an in memory DataArray
with DataArray labelled as given name"""
geotiff_burn = xr.open_rasterio(url)
burn_dataset = geotiff_burn.to_dataset('band')
return burn_dataset | 195ba329ba5e3d07a737a93e73403d76caa8ca61 | 37,247 |
def strip_org(name):
""" Returns the name with ORG_PREFIX stripped from it.
"""
if name.startswith(ORG_PREFIX):
return name[len(ORG_PREFIX):]
else:
return name | 855e1bf886c3a3335901e03eab4bb8d1e0e86ebc | 37,248 |
import json
def _ios_format_data(cmd_outputs: json) -> json:
"""
This function will retrieve data from differents
commands outputs and gegroup them in a structured data format.
Three command are executed on devices
-> show ip ospf neighbor detail
-> show ip ospf interface
-> sh... | cf8cd150b0cdb19f80a962d7c13956347d32f665 | 37,249 |
def get_mode_C_array(mode_C):
"""冷房の運転モードを取得する
Args:
mode_C(str): 冷房方式
Returns:
tuple: 冷房の運転モード
"""
# 運転モード(冷房)
if mode_C == '住戸全体を連続的に冷房する方式':
return tuple(["全館連続"] * 12)
else:
return ('居室間歇', '居室間歇', '居室間歇', '居室間歇', '居室間歇', None, None, None, None, None, None,... | 6b9bce2eccab7698ec78ef3b843b17f3c3c9200d | 37,250 |
def launch_and_move(prog_array, workspace,
get_wid=get_wid_by_pid, new_name=None):
"""Launch application and move the created window to `workspace`.
Returns the window id as used by wmcrtl.
`prog_array` : list forwarded to subprocess.Popen. This should
include the co... | db55e33bc6d9f6c9118e04ed0b1c153f5f66e525 | 37,251 |
def construct_label_array(video_labels):
"""Construction label array."""
label_arr = np.zeros((cfg.MODEL.NUM_CLASSES, ))
# AVA label index starts from 1.
for lbl in video_labels:
if lbl == -1:
continue
assert lbl >= 1 and lbl <= 80
label_arr[lbl - 1] = 1
return l... | 0a49f915324311d24888bfa03be186a16f61cdcf | 37,252 |
from typing import Optional
def any(x: _cpp.Variable,
dim: Optional[str] = None,
*,
out: Optional[_cpp.Variable] = None) -> _cpp.Variable:
"""Element-wise OR over the specified dimension or all dimensions if not
provided.
:param x: Input data.
:param dim: Optional dimension al... | fbe911d588adabe9d1f2dbe885a830dedf73e86d | 37,253 |
from datetime import datetime
def get_date():
""" gets current date """
return datetime.now() | dccf420bc6eb216bf76ee153504696ec1c390b5d | 37,254 |
def singular(plural):
"""
Take a plural English word and turn it into singular
Obviously, this doesn't work in general. It know just enough words to
generate XML tag names for list items. For example, if we have an element
called 'tracks' in the response, it will be serialized as a list without
... | 92ab7e074387d943d5593d759a10b3fafa67deca | 37,255 |
def create_simple_keras_model(learning_rate=0.1):
"""Returns an instance of `tf.Keras.Model` with just one dense layer.
Args:
learning_rate: The learning rate to use with the SGD optimizer.
Returns:
An instance of `tf.Keras.Model`.
"""
model = tf.keras.models.Sequential([
tf.keras.layers.Flatt... | a1c777004fe253da5b9f1689284ab99cd6d98cd9 | 37,256 |
def elli(x, rot=0, xoffset=0, cond=1e6, actuator_noise=0.0, both=False):
"""Ellipsoid test objective function"""
x = np.asarray(x)
if not isscalar(x[0]): # parallel evaluation
return [elli(xi, rot) for xi in x] # could save 20% overall
if rot:
x = rotate(x)
N = len(x)
if actuat... | 8768114827746e1b45ec98aa373201d0e4f8c5bc | 37,257 |
def plot_coauthor_network(docs: DocumentSet, *, max_authors=None, **kwargs):
"""Plot a co-author network.
This is a shorthand for `plot_network(build_coauthor_network(docs))`."""
b, p = split_kwargs(**kwargs)
return plot_network(
build_coauthor_network(docs, max_authors=max_authors, **b), *... | b98e7ec214b92dd413fac7f27ace9423af9e0921 | 37,258 |
def read_gene_list(fname, id_type):
"""Return references for genes from a file with the given ID type.
Parameters
----------
fname : str
The name of the file containing the list of genes. Each line of the
file corresponds to a single gene.
id_type : str
The type of identifie... | 612e5254c47f3ec189a18c989abd89b8a414d3da | 37,259 |
from datetime import datetime
from typing import Dict
def backtest(
start_date: datetime = None,
end_date: datetime = None,
interval=1,
yield_interval=100,
start_balances: Dict[str, float] = None,
starting_coin: str = None,
config: Config = None,
):
"""
:param config: Configuratio... | 9aa527f6fa11a00ccdbc2c39e3cd0f79fb322e8e | 37,260 |
def define_vgg_pre_processing(tf_input):
"""
This function defines the vgg_pre_processing network using the tensorflow nn
api.
Parameters
----------
tf_input: tensorflow.Tensor
The input tensor to the network. The image is expected to be in RGB
format.
Returns
-------
... | e74f686da3f6ec068c4ee69a0a20f63015bec569 | 37,261 |
import torch
def subreservoir(weight: Tensor, k=3):
"""
size of weight must devide by k
"""
subres_size = weight.size(0) // k
mask = np.zeros_like(weight)
for i in range(k):
mask[i * subres_size: (i + 1) * subres_size, i * subres_size: (i + 1) * subres_size] = torch.ones(subres_size,
... | ede0db464956bbf825b57650ae9198c656b850bc | 37,262 |
def buy_tickets(request):
""" Provides the event form data and passes it to the frontend as json """
form_html = ""
message_html = ""
success = True
# Ensure all required data has been sent
if 'event' not in request.GET or not request.GET['event']:
messages.error(request, 'No event infor... | aa5a2791688c9696d462b5efc33ab7f79a83dc93 | 37,263 |
def crop_and_revenue_to_df(financial_annual_overview, waste_adjusted_yields, total_sales, vadded_sales, education_rev, tourism_rev, hospitality_rev, grants_rev):
"""Adding yields and sales information to financial overview
Notes:
Adds waste-adjusted yields for crops 1, 2, 3 and 4 with t... | 6be32e6f4ff3ae0ed6434313b8bcc2f44192231b | 37,264 |
def cr_notification_dispatcher(r, **attr):
"""
Send a notification.
"""
if r.representation == "html" and \
r.name == "shelter" and r.id and not r.component:
T = current.T
msg = current.msg
record = r.record
message = ""
text = ""
s_id = re... | 38dc726e9e136348548e0003f303520d75c9a539 | 37,265 |
def download_blob(bucket_name, source_blob_name):
"""Downloads a blob from the bucket."""
client = storage.Client()
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(source_blob_name)
return blob.download_as_string() | 1251b9f1675237306e5f0057fecd136da6d4cad7 | 37,266 |
def val_epoch(state: train_state.TrainState):
"""
perform a validation epoch
:param state:
:return:
"""
val_config = deepcopy(config)
val_config['data']['val_fns'] = "path_to_tvqa/val{:03d}of008.tfrecord"
val_config['data']['num_val_files'] = 8
val_config['data']['do_random_scale'] =... | 023a2b9ec1da79cb7d3b604dcf9ff2b23cb99a2d | 37,267 |
import torch
def getBERTFeatures(model, text, attn_head_idx=-1): # attn_head_idx - index o[]
"""
Get BERT features for the `text`
Args:
model: BERT model of type `BertForPreTrainingCustom`
text: required, get features for this text
attn_head_idx: optional, defaults to last layer
... | 63a05f9457bbe8e7178c931321d48dc60243bfab | 37,268 |
def filter_rows_via_column_matching(data, column, index=0):
"""
Filter data, by keeping rows whose particular field index matches the
column criteria
It takes parameters:
data (data in the form of a list of lists)
column (used as the match criteria for a particular field of the data)
and op... | fcd5548677290a34d94c2eb8d5fefcb2bb50f0b4 | 37,269 |
def get_td_at_index(tr, index):
"""
When calculating the rowspan for a given cell it is required to find all
table cells 'below' the initial cell with a v_merge. This function will
return the td element at the passed in index, taking into account colspans.
"""
current = 0
for td in tr.xpath(... | f9b72d5597714273c527187738b99a69580c0576 | 37,270 |
import re
def _normalize_name(name: str) -> str:
"""
Normalizes the given name.
"""
return re.sub(r"[^a-zA-Z0-9.\-_]", "_", name) | b38a90c05b0a6ec5a26db6d0da85bed2ae802cea | 37,271 |
def time_step(las, historic_las, max_t, transport, data_df,
transport_threshold, transport_time, transport_severity,
transport_release, beta_threshold, beta_time, beta_severity,
lockdown_release, nat=False):
"""
Enacts all actions of the day such as the morning commute,... | 4a95d47304616288dbf8e5ea6f1a9abf63700bec | 37,272 |
import os
def generate_geneset():
"""
Populates the GeneSet class with atoms and fragments to be used
by the engine. As it stands these are hardcoded into the engine
but will probably be adapted in future versions
Parameters
----------
None
Returns
----------
GeneSet : object... | ba0982e1eaa032be84684bb781df7a04e725bfe4 | 37,273 |
def filter_claims_by_date(claims_data, from_date, to_date):
"""Return claims falling in the specified date range."""
return [
claim for claim in claims_data
if (from_date <= claim.clm_from_dt <= to_date)
] | d1568d0fd52382bdb3f1f02414f591d5f4da3596 | 37,274 |
import json
def get_policies_in_category(jamf_url, object_type, object_name, enc_creds, verbosity):
"""return all policies in a category"""
url = "{}/JSSResource/{}/{}".format(
jamf_url, object_types(object_type), object_name
)
r = curl.request("GET", url, enc_creds, verbosity)
if r.stat... | c0621a10c922d6a6cbcaad4d3a1ba68bb70a79b4 | 37,275 |
from userbot.modules.sql_helper.notes_sql import add_note
async def add_note(fltr):
""" .save """
try:
except AttributeError:
await fltr.edit("`Bot Non-SQL modunda işləyir!!`")
return
keyword = fltr.pattern_match.group(1)
string = fltr.text.partition(keyword)[2]
msg = await fl... | 276290fc376671adc8694c6f0e9869e344c12309 | 37,276 |
import tqdm
def get_sorted_nodelist(nodelist, timeout):
"""
check all nodes and poll for latency,
eliminate nodes with no response, then sort
nodes by increasing latency and return as a list
"""
pool_size = mp.cpu_count()*2
n = len(nodelist)
with mp.Pool(processes=pool_size... | c903f8b5bae1aaf5557b4ed60b32aebdf34fc0d7 | 37,277 |
def featurise_mols(smiles_list, representation, bond_radius=3, nBits=2048):
"""
Featurise molecules according to representation
:param smiles_list: list of molecule SMILES
:param representation: str giving the representation. Can be 'fingerprints' or 'fragments'.
:param bond_radius: int giving the b... | bb2a3f1eb50b52beabd2da013ee50cf668f02354 | 37,278 |
def clear_inactive_structural_variant_sets(_self):
"""Task to cleanup variant sets and their variants that are stuck in a non-active status for a long time."""
return models.cleanup_variant_sets() | cbcefe13b6cbadc9cf6636ba6dbe17b6db944a80 | 37,279 |
def unicode2str(content):
"""Convert the unicode element of the content to str recursively."""
if isinstance(content, dict):
result = {}
for key in content.keys():
result[unicode2str(key)] = unicode2str(content[key])
return result
elif isinstance(content, list):
r... | 30618f0305d28646af36bcff488af971643fd142 | 37,280 |
def cell_test(U,count,max_kpd_=None):
"""Tests the ability of the niggli basis to preserve the symmetry of
the parent cell under action of the HNF.
Args:
U (numpy array): The parent lattice as columns of vector.
count (dict): A dictionary to count how many times each niggli
cel... | e9e488470f19275a42101f1e3224f59acc0f841c | 37,281 |
def get_engine(path: str) -> create_engine:
"""
Function for connecting to the database-file
:param path: path to the file
:return: sqlmodel's engine
"""
return create_engine(path, echo=False) | 0a7eb924934ed9b0ea276daa46943ae626ed3073 | 37,282 |
def mri_signal_inversion_recovery_function(input_data: dict) -> np.ndarray:
""" Function that calculates the inversion recovery signal """
t1: np.ndarray = input_data["t1"].image
t2: np.ndarray = input_data["t2"].image
m0: np.ndarray = input_data["m0"].image
mag_enc: np.ndarray = input_data["mag_en... | ef0819be79a1d575caf4defdedcf2e1d6bb32d49 | 37,283 |
def clip_grads(grad_tree, max_norm):
"""Clip gradients stored as a pytree of arrays to maximum norm `max_norm`."""
norm = l2_norm(grad_tree)
normalize = lambda g: np.where(norm < max_norm, g, g * (max_norm / norm))
return layers.nested_map(grad_tree, normalize) | 0f6790f92716939263c61a732121e67579916162 | 37,284 |
def get_all_facility_users(admin: Client, facility_id: int) -> dict: # noqa: unused client
"""Query for users related to the given facility."""
disallow_parameters(request)
return {
'user': [
user.to_json()
for user in Facility.from_id(facility_id).users()
]
} | 1d72d1e506d052ca67c204035d3d32078833cded | 37,285 |
def rpkm(count, length, nb_read):
""" Return the rpkm value """
length /= 10**3
return rpm(count, length, nb_read) / length | 8e0c8a557b8bd6a10eead706e5176811d7706dec | 37,286 |
import copy
def usm_make(sequence, A=None, seed='centroid'):
"""
Calculates USM coordinates of a categorical sequence of arbitrary alphabet size.
Parameters
----------
sequence : LIST OR ARRAY TYPE;
CATEGORICAL SEQUENCE OF DATA
d : LIST, optional;
LIST CONTAINING ALL POSSIBLE ... | c689a3fba96b0bc995103b9d2c16ef6ab98030aa | 37,287 |
def single_dataset_variableselect(c=cmdc.Client()):
"""
This example loads a subset of the demographic data by selecting
a few variables and a few fips codes
"""
c.demographics(
variable=[
"Total population",
"Fraction of population over 65",
"Median age",... | 4a64844a434e06d188a142f2a5658112104f4caa | 37,288 |
import sys
def validate_min_python_version(major, minor, error_msg=None, exit_on_fail=True):
"""If python version does not match AT LEAST requested values, will throw non 0 exit code."""
version = sys.version_info
result = False
if version.major > major:
return True
if major == version.maj... | 49f078af83d956b3e099d792b5a364c359991df0 | 37,289 |
from operator import gt
def _get_total_sizes(graph_tensor: gt.GraphTensor) -> SizeConstraints:
"""Returns the total number of items in the `graph_tensor`."""
return SizeConstraints(
total_num_components=graph_tensor.total_num_components,
total_num_nodes={
name: node_set.total_size
... | a9c802f5d2b1280132f0016c2b30cfede2692e5e | 37,290 |
def _lookup_credentials_data_workspace_access(access_key_id):
"""
Raises HawkFail if the access key ID is not of Data workspace
"""
if access_key_id != settings.HAWK_LITE_DATA_WORKSPACE_CREDENTIALS:
raise HawkFail(f"Incorrect Hawk ID ({access_key_id}) for Data workspace")
return _lookup_cre... | 7f2adcd5576d03a5d41ab7af2aa273fb8a2e13e7 | 37,291 |
import os
import argparse
def get_arg_parser():
"""Allows arguments to be passed into this program through the terminal.
Returns:
argparse.Namespace: Object containing selected options
"""
def dir_path(string):
if os.path.isfile(string):
return string
else:
... | 035bb8df1743aca4ba78c17d60836b9f485e769d | 37,292 |
def generate_2d_data(func, size=100, data_range=(-2., 2.),
validation=False, visualize=False, seed=100):
"""Generates 2d data according to function.
Args:
func: (function) function that takes (x, y) and return a scalar
size: (int) size of training sample to generate
... | a78116489d151624a997fb1b464b86b068cd1df6 | 37,293 |
def sphere_line_intercept(l, o, r):
"""Calculate intercept point between line y = l.x + o
and a sphere around the center of origin of the
coordinate system: c=0
Parameters:
------------
l ... vector of line of sight
o ... observer position
r ... vector of dis... | 83f3d22a0af6f2a7b9042622525dde7d1984842d | 37,294 |
from typing import List
def compress_pulses(schedules: List[Schedule]) -> List[Schedule]:
"""Optimization pass to replace identical pulses.
Args:
schedules: Schedules to compress.
Returns:
Compressed schedules.
"""
existing_pulses = []
new_schedules = []
for schedule in... | 5782b725fa08b26125722a9b695ca4ff92e229d3 | 37,295 |
def get_localhost_info() -> dict:
"""Get information about the specifications of localhost.
Returns:
dict: Current dict keys: 'os', 'cpu_cores', 'memory', 'python_version', 'workspace_version', 'gpus'.
"""
info = {
"os": _get_os_on_localhost(),
"cpu_cores": _get_cpu_count_on_loc... | ce6959f9a5cc95d643c99c0180da53e661226c4f | 37,296 |
import os
def locations(db, instance_path):
"""File system location."""
default = Location(
name='default',
uri=instance_path,
default=True
)
archive = Location(
name='archive',
uri=os.path.join(instance_path, 'archive'),
default=False
)
db.sessi... | 63e4d61f91d45b12c8708e8383ce63c898bcff2d | 37,297 |
from pydantic import BaseModel # noqa: E0611
import os
import re
import torch
def load(ckpt: int, exp_name: str) -> BaseModel:
"""Load pre-trained language model instance by checkpoint and experiment name.
Load pre-trained language model from path ``project_root/exp/exp_name``.
Parameters
----------
ckpt... | 563c4d8ecea6d0a28d1f5f94c2a8db9ea8ad4c13 | 37,298 |
def predictions(logits):
"""Class prediction from logits."""
inner_dim = logits.get_shape().as_list()[-1]
with tf.name_scope('predictions'):
# For binary classification
if inner_dim == 1:
pred = tf.cast(tf.greater(tf.squeeze(logits, -1), 0.), tf.int64)
# For multi-class classification
else:
... | 11b08eca2c8f7a65bb778651374bdee605968a30 | 37,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.