content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def cross_entropy_sequence_loss(logits, targets, sequence_length):
"""Calculates the per-example cross-entropy loss for a sequence of logits and
masks out all losses passed the sequence length.
Args:
logits: Logits of shape `[T, B, vocab_size]`
targets: Target classes of shape `[T, B]`
sequence_len... | 78ee272b2e6fe7b7f02579fdd0e9f90aab936e76 | 3,631,847 |
def get_common_interior_polygons(polygon, list_of_polygons):
"""Check if polygon resides inside any polygon
in the list_of_polygons.
Parameters
----------
polygon: matplotlib.Polygon
Returns
-------
list_of_common_polygons: list
A filtered list of ids
... | 489cd8afd61ce8431f253c445266c14b3f8b50f6 | 3,631,848 |
def handle_image_size(input_image: np.ndarray, dimension: tuple):
"""
:param input_image:
:param dimension:
:return:
"""
assert input_image.ndim == 3, (
"Image should have 3 dimension '[HxWxC]'" "got %s",
(input_image.shape,),
)
assert len(dimension) == 2, (
"'di... | d4327548130c86e7ffdfa34ad3ed3e72bb510eb4 | 3,631,849 |
def netconvecs_to_listoflists(t_vec, id_vec, minmax=None):
"""
Convert data from NetCon.record(tvec, idvec) vectors into a dict
where the keys of the dict are the ids and the value is a list of
timestamps associated with that id.
:param tvec: Timestamp vector.
:param idvec: Associated ids o... | e3ed2752c963de97379ce5fac7e7adb4bec2e334 | 3,631,850 |
import random
def log_roulette_selection_method(fx_input, optimization_type_input, n_individuals_input, seed_input):
"""Roulette selection method with a twist. Here the evaluation value is processed with a log function. It reduces the difference between individuals, which increases population diversity."""
r... | 72a440402b0af2b1a6dcec8aba1116094bc87ecd | 3,631,851 |
import torch
def evaluate(attention_model,x_test,y_test):
"""
cv results
Args:
attention_model : {object} model
x_test : {nplist} x_test
y_test : {nplist} y_test
Returns:
cv-accuracy
"""
attent... | 3216f6092c61f35bb74140ac51ef635f53691e19 | 3,631,852 |
def reorder_cols_df(df, cols):
"""Reorder the columns of a DataFrame to start with the provided list of columns"""
cols2 = [c for c in cols if c in df.columns.tolist()]
cols_without = df.columns.tolist()
for col in cols2:
cols_without.remove(col)
return df[cols2 + cols_without] | 917b0084ba34f8e1b1fc697c4838ff8404a2fc90 | 3,631,853 |
from typing import Union
from pathlib import Path
from typing import Optional
def uri_resolve(base: Union[str, Path], path: Optional[str]) -> str:
"""
Backport of datacube.utils.uris.uri_resolve()
"""
if path:
p = Path(path)
if p.is_absolute():
return p.as_uri()
if isi... | d280456a0071edd1cfce60a8d3b17c193c9ba446 | 3,631,854 |
def preprocess_report(rep, rep2):
""" Processes lists containing report grades """
rv = np.asarray([rep], dtype="float32")
rv2 = np.asarray([rep2], dtype="float32")
return rv, rv2 | 628659ba90af516497b005986854b86dde3c6edb | 3,631,855 |
from typing import Any
async def async_check_srv_record(hass: HomeAssistant, host: str) -> dict[str, Any]:
"""Check if the given host is a valid Minecraft SRV record."""
# Check if 'host' is a valid SRV record.
return_value = None
srv_records = None
try:
srv_records = await aiodns.DNSResol... | 40aef8e2446669040975a5d15c4be2c28e08b6e1 | 3,631,856 |
def add_923_heat_rate(df):
"""
Small function to calculate the heat rate of records with fuel consumption and net
generation.
Parameters
----------
df : dataframe
Must contain the columns net_generation_mwh and
fuel_consumed_for_electricity_mmbtu
Returns
-------
dat... | 907ac6ba469a65dfe25a84f7498e66b1e0535d19 | 3,631,857 |
def get_local_bounding_box_min_max():
"""Gets an Axis-Aligned Bounding Box for the canonical die model, in local coordinate space."""
return np.array([[-0.49946,-0.48874,-0.52908],
[0.50094,0.51166,0.47132]]).T | be707edf6e1d92726a55f355bbe0052323b9c27b | 3,631,858 |
def get_inception_features(inputs, inception_graph, layer_name="pool_3:0"):
"""Compose the preprocess_for_inception function with TFGAN run_inception."""
preprocessed = preprocess_for_inception(inputs)
return tfgan_eval.run_inception(
preprocessed,
graph_def=inception_graph,
output_tensor=layer... | ea6d8772291bb3e6b156f4905e2f22bb1539870c | 3,631,859 |
def v4_multimax(iterable):
"""Return a list of all maximum values.
Bonus 1 - on short solution.
"""
try:
max_item = max(iterable)
except ValueError:
return []
return [
item
for item in iterable
if item == max_item
] | fddeae328993fa77a0b73ab55c4e53a88b42b39c | 3,631,860 |
def sig_beg_to_adj_ground_ht(ds):
"""
Height in meters from GLAS signal beginning to whichever of the two lowest peaks has greater amplitude.
"""
return get_heights_from_distance(
ds, top_metric='sig_begin_dist', bottom_metric='adj_ground_peak_dist'
) | d83aeb47ac7df081f310dc2e445d232326b099b2 | 3,631,861 |
from typing import List
def tree_to_formula(tree: DecisionTreeClassifier, concept_names: List[str], target_class: int) -> str:
"""
Translate a decision tree into a set of decision rules.
:param tree: sklearn decision tree
:param concept_names: concept names
:param target_class: target class
:... | dc0c1d03aab3f5ef458f74665a5a203a53db87ee | 3,631,862 |
from datetime import datetime
def datefix(datestr):
""" transform string into a python datetime object
handle mm/dd/yy or mm/dd/yyyy or dashes instead of slashes """
fix = datestr.replace('-','/')
if len(fix) > 4:
try:
return datetime.strptime(fix, "%m/%d/%y")
except V... | 2cb728dfcec24b350d63a79fc3964d3325780b6a | 3,631,864 |
import math
def vector_angle(v1: Vector3D, v2: Vector3D) -> float:
"""
Calculate the angle between two given vectors.
Keyword arguments:
v1 -- First vector
v2 -- Second vector
"""
v1_n = normalize_vector(v1)
v2_n = normalize_vector(v2)
return math.acos(dot_product(v1_n, v2_n) / (v... | 694b5d49140ae409166bc55c7ecf6c19db8fe5bf | 3,631,865 |
from typing import Counter
def removed_mirrored_association(left_assoc, right_assoc):
"""
Remove the mirrored association (associations like (a, b) and (b, a)) that occurs in the intra-night associations.
The column id used to detect mirrored association are candid.
We keep the associations with the s... | 1f3bcd16c0f8321ba43d2f47163f59d7c0b12f26 | 3,631,866 |
import re
def valgrind_supports_exit_early():
"""Checks if we support early exit from valgrind"""
version = helpers.run_subprocess(['valgrind', '--version'])
match = re.match(r'valgrind-(\d)\.(\d+).*', version)
if match:
return int(match.group(2)) >= 14
return False | a33d9795587b2f678c88d58ec058aead215b36fb | 3,631,868 |
from typing import List
import hashlib
def document_etag(value: dict, ignore_fields: List[str] = None) -> str:
"""Computes and returns a valid ETag for the input value."""
h = hashlib.sha1()
h.update(dumps(value, sort_keys=True).encode("utf-8"))
return h.hexdigest() | 5415ee356f610728d764139eb1813f987f1bcce3 | 3,631,870 |
def answer(request):
"""
Save the answer.
GET parameters:
html:
turn on the HTML version of the API
BODY
json in following format:
{
"answer": #answer, -- for one answer
"answers": [#answer, #answer, #answer ...] -- for multiple ans... | 61ed14331bd682cdf85b428dfb89695c35237087 | 3,631,871 |
def valid_client_model(initialize_db):
"""
A fixture for creating a valid client model.
Args:
initialize_db (None): initializes the database and drops tables when
test function finishes.
"""
return Client(username='Leroy Jenkins', avatar_url='').save() | cc9a7d3bea9f50a5250d1fe98781af5441fba492 | 3,631,872 |
def merge_features(df: pd.DataFrame)-> pd.DataFrame:
"""
Merges features that estimate the same thing
"""
# kelvin conversions
df['station_max_temp_c'] += 273.15
df['station_min_temp_c'] += 273.15
df['station_avg_temp_c'] += 273.15
df = (df
.fillna(method = 'backfill')
... | 33c085a0b4defddcfc3310644ce371a9532dea1b | 3,631,873 |
def threatActorSTIX(adversaries):
"""
Parse the adversaries key to convert it to STIX
"""
adversariesList = []
for adv in adversaries: adversariesList.append(ThreatActor(name="%s"%(adv))) if len(adversaries) >= 1 else adversariesList.append(ThreatActor(name="%s"%(adversaries[0])))
return adversariesList | 723224b0c271ea0c7b9cedb99cfd27557cd9a5f1 | 3,631,874 |
import scipy
def merge_channels(data, sampling_rate, filter_data: bool = True):
"""Merge channels based on a running maximum.
Args:
data (ndarray): [samples, channels]
sampling_rate (num): in Hz
Returns:
ndarray: merged across
"""
data = np.array(data) # ensure data is a... | 6d6df0ef40ee350786b6ef19396b889f08e945cc | 3,631,875 |
def maximalEigenvector(A):
""" using the eig function to compute eigenvectors """
n = A.shape[1]
_,v = np.linalg.eig(A)
return abs(np.real(v[:n,0])/np.linalg.norm(v[:n,0],1)) | b45b9a1b7b44b98575c9ca282cdb3e4ef1cb58f2 | 3,631,876 |
from operator import sub
def remove_hyperlinks(text):
"""Remove hyperlinks from text."""
# If text is empty, return None.
if not text: return None
# If is tokenized, merge tokens.
if is_tokenized(text):
was_tokenized = True
normalized_text = merge_tokens(text)
else:
wa... | 5b1ee46644cb12365b4f4939cfb0ac6d00eebcea | 3,631,877 |
def _check_nx(path):
"""NX - This mitigation technique attempts to mark
as the binary as non-executable memory. E.g. An attacker
can't as easily fill a buffer with shellcode and jump
to the start address. It is common for this to be disabled
for things like JIT interpreters.
"""
headers = _e... | 1dfd1c14e7b49e211c7a6a42e10bd3201dc5262b | 3,631,879 |
def verify_auth(username, password):
""" Verify the HTTP Basic Auth credentials """
config = app.config
return username == config['USERNAME'] and password == config['PASSWORD'] | 18960b0355f158b601e4097694eb1b417715227c | 3,631,880 |
def mat_list_to_rf_array(mats_list: list) -> (np.ndarray, dict):
"""Make an RF array from a list of mats"""
rf_array = np.array(
[open_rf(x) for x in mats_list]
)
parameters = open_parameters(mats_list[0])
return rf_array, parameters | 3b6a84b76a096eabe0c14183d23a795da8c742f1 | 3,631,881 |
def show_options(last_row):
"""
Show the options. The user can choose what to do.
last_row: the last row in the worksheet (list).
"""
while True:
choose = input('What to do? (Q)uit/(L)ist/(N)ew [N]: ')
if choose is '' or choose.lower()[0] is 'n':
return True
eli... | 1d20d5de02f6011cfe4d4f635d43ee097cfc6568 | 3,631,882 |
def is_pilot_snipe(sortie):
"""
A pilot snipe is when a plane goes down because the pilot gets killed, and not because the aircraft is crtically
damaged. Currently, in the logs, a pilot snipe looks rather similar to a normal death. Even in a pilot snipe,
the logs think the aircraft gets shotdown before ... | 112770e8dceb339af7f67bb074739c4066b8121d | 3,631,883 |
def change_lang(request):
"""
Change current documentation language.
"""
lang = request.GET.get('lang_code', 'en')
response = redirect('/')
portal_helper.set_preferred_language(request, response, lang)
return response | 8b9ffce5b15159d3dad0c565d3caac8ed2a4fd71 | 3,631,886 |
import re
def cleanHtml(sentence):
"""
remove all Html canvas from the sentence
:param sentence {str} sentence
:return:
{str}: sentence without html canvas
"""
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, ' ', str(sentence))
return cleantext | 1a3edcd7227468f8f3102525538a728a9bc93fc0 | 3,631,887 |
def simple_decoder_fn_train(encoder_state, name=None):
""" Simple decoder function for a sequence-to-sequence model used in the
`dynamic_rnn_decoder`.
The `simple_decoder_fn_train` is a simple training function for a
sequence-to-sequence model. It should be used when `dynamic_rnn_decoder` is
in the training ... | e23c0d47096b2234e670ce7720f1936c4ee7b7b7 | 3,631,888 |
def explain_point_local(data_row, neighbors, oversampled_data, model_features, categorical_features, numeric_features, budget=999, show_pos_neg = False):
"""
Provides explanations on each point in the selected subset for local explanations.
Parameters:
-----------------
data_row: integer, the i... | dd4ef3aafbe7ac97d4bead509e7f746554b4f015 | 3,631,889 |
def pots_scan(n_src, ele_lims, true_csd_xlims,
total_ele, ele_pos, R_init=0.23):
"""
Investigates kCSD reconstructions for unitary potential on different
electrodes
Parameters
----------
n_src: int
Number of basis sources.
ele_lims: list
Boundaries for electrod... | 442b093422907801858efeba6e493ebf0c8e82c6 | 3,631,890 |
from typing import Any
def add_nav_entry(mkdocs_settings, nav_entry: NavEntry) -> Any:
"""
Add an additional entry to the Nav in mkdocs.yml
Args:
mkdocs_settings (): The mkdocs settings to update.
nav_entry (NavEntry): The NavEntry to add
Returns:
The updated mkdocs_settings
... | 06899c76b1788096b88237f3f12f6ef7cd786191 | 3,631,891 |
import re
def is_guid(value):
"""
проверяет на наличие только [a-zA-z/-]
"""
if re.match("^[A-Za-z0-9_-]*$", value):
return value
return None | ca9c84ebfe271d93bd7c8d3043f8dd1849fb3239 | 3,631,892 |
def load_scikit_learn_model(model_uri):
"""
Load a scikit-learn model from a local file.
:param model_uri: The location, in URI format, of the aiflow model, for example:
- ``/Users/aiflow/path/to/local/model``
- ``relative/path/to/local/model``
... | d10d22ec1f5eb659a18c4720860e72aa1a03a387 | 3,631,893 |
def epimorphism_in_laurent(tri, angle, cycles, ZH):
"""
The argument cycles specifies a group epimorphism from the
manifold to the filled manifold. This function returns the image
of the generators of the group ring under the induced epimorphism.
"""
n = tri.countTetrahedra()
S,U,V = faces_... | 8563c400ecc9420682144300be1a990df531b861 | 3,631,894 |
def merge_config(a, b):
"""Merges config b in a."""
for key, b_value in b.items():
if not isinstance(b_value, dict):
a[key] = b_value
else:
a_value = a.get(key)
if a_value is not None and isinstance(a_value, dict):
merge_config(a_value, b_value... | 2e194d9b19c2270968cd205062b4d3ec992cfced | 3,631,895 |
def tsi_moving_average(df, periods=7):
"""Function calculating Moving Average (MA) for TSI
Args:
df (pandas.DataFrame): Quotes with TSI values
periods (int, optional): The number of periods from which MA is calculated. Defaults to 7.
Returns:
pandas.DataFrame: Quotes extended by th... | 5491dc1a82b26d152baaa7d9a53048d63a658f69 | 3,631,896 |
def fit_index(dataset, list_variables):
""" Mapping between index and category, for categorical variables
For each (categorical) variable, create 2 dictionaries:
- index_to_categorical: from the index to the category
- categorical_to_index: from the category to the index
Parameters
---... | 7b8c73a5d23de2e537c1f28078d2e032095d6b1c | 3,631,897 |
def theoretical_motion(input, g):
"""
Compute the theoretical projectile motion.
Args:
input: ndarray with shape (num_samples, 3) for t, v0_x, v0_z
g: gravity acceleration
Returns:
theoretical motion of x, z.
"""
t, v0_x, v0_z = np.split(input, 3, axis=-1)
x = v0_x ... | 200a2430a79239f21e22db07feaf315d8919f21b | 3,631,898 |
from typing import List
import requests
def list_analyses() -> List[str]:
"""Get a list of all supported analyses."""
response = requests.get(_url("/info/analyses"))
assays = response.json()
return assays | 8f14ed36d572ca222df53dfa2fe8605b2975db48 | 3,631,899 |
def applyAlign(mrt,al):
"""
Takes meaning representation triples (mrt) and combines with alignments
"""
for alignment in al.split():
# Alignment: x9:arg0:sell:x11-39
fromNode,rest = alignment.split(":",1)
rest,toAlign = rest.rsplit("-",1)
edgeLabel,toNode ... | 098f7a42e2661938138c703d9e0c337816c1dcd4 | 3,631,900 |
def get_unverified_jwt_claims(encoded_token):
"""
Returns the Headers of an encoded JWT without verifying the actual signature of JWT.
Note: The signature is not verified so the header parameters
should not be fully trusted until signature verification is complete
:param encoded_token: The encode... | b041ab4579c6907c229bf3dd590e8ea559de24c5 | 3,631,901 |
def dos_orbitals(
folder,
orbitals,
output='dos_orbitals.png',
fill=True,
alpha=0.3,
linewidth=1.5,
sigma=0.05,
energyaxis='x',
color_list=None,
legend=True,
total=True,
figsize=(4, 3),
erange=[-6, 6],
spin='up',
soc_axis=None,
combination_method='add',
... | 85fa9e17eaaf62e801e6439b135ff1c1ed86150d | 3,631,902 |
from .ginzburg_landau import GinzburgLandau2Components
from .flory_huggins import FloryHuggins2Components
from .general import FreeEnergy
from typing import Union
def get_free_energy_single(
free_energy: Union[str, FreeEnergyBase] = "ginzburg-landau"
) -> FreeEnergyBase:
"""get free energy for systems with a ... | d40d29543a943eb5fc7a9122627d1635aaa8fe43 | 3,631,903 |
def convert_bin_to_text(bin_str: str) -> str:
"""Convert a string of binary to text.
Parameters:
-----------
bin_str:
string: A string of binary, terminating with 00000000.
Returns:
--------
text:
string: A plaintext representation of the binary string.
"""
# get nu... | 8890ff192ae4b6e01401dd7f018bf8906c3c37ce | 3,631,905 |
import select
def _retrieve_transaction_type(t_type: str, connection) -> RowProxy:
""" Retrieves Transaction Type
Args:
ttype (str): The transaction type that represents the trasaction being recorded 'archive' or 'compress'.
Returns:
RowProxy: The transaction_type
"""
tr... | f6b883b7e524f3dff5757f46de11e6fb10af66f2 | 3,631,906 |
def myDijkstra(graph, source, start, end):
"""
Implements Dijkstra's single source shortest path algorithm
for a directed graph
Parameters:
graph: the graph we are working on
source (int): the vertex choose as source
start (strin... | 3296b510dafe4e3b08550ae771e137f7139f4eea | 3,631,907 |
def scale_on_x_list(x_list, scaler):
"""Scale list of ndarray.
"""
return [scaler.transform(e) for e in x_list] | 2fbe36cb23e99ca6eaf277fb5509e2e997ec4a52 | 3,631,908 |
def calc_distance(origin, destination):
"""
title::
calc_distance
description::
Great-circle distance between two points on a sphere from their longitudes
and latitudes.
author::
Stackoverflow User: user2514381
https://stackoverflow.com/questions/1727312... | 02f9e63970e9e2f561cea095c045e08618e5e444 | 3,631,910 |
import tokenizers
def tokenize(string,tokenizer = tokenizers.keras):
"""
Tokenizes a string using the selected tokenizer.
:param string: the string to tokenize
:param tokenizer: which tokenizer to use (nltk or keras)
:return: the list of tokens
"""
if tokenizer == tokenizers.nltk:
... | 8d158f3bb97356724a1f1438bc8e5d91314af367 | 3,631,911 |
import math
def move_point(pt: XY, distance: float, degrees: float) -> XY:
"""
Create a new point that is the original point moved by distance (m) in direction degrees.
"""
x = pt.x + distance * math.cos(math.radians(degrees))
y = pt.y + distance * math.sin(math.radians(degrees))
return XY(x, ... | 51fa927ca06525b91985af652ed7579ed72903a9 | 3,631,912 |
import jinja2
from datetime import datetime
def _generate_follow_up(the_date, vms, template='delete_followup.html'):
"""Create the HTML email body stating what VMs were randomly deleted.
:Returns: String
:param the_date: The specific time when vLab randomly deleted a user's VM(s).
:type the_date: In... | 8a72a21dd653c86fc4e6fb4bd5246b84b88300cd | 3,631,913 |
def find_empty_node(grid):
"""There should be one and only one empty node. Find it
and return its location as a tuple."""
for x in range(len(grid)):
row = grid[x]
for y in range(len(row)):
if row[y][USED] == 0:
return (x, y)
# else:
# p... | 778b4424f4bcb45db093a40e879628b13f3d9a4f | 3,631,914 |
import hashlib
def md5(ori_str):
""" MD5加密算法
:param ori_str: 原始字符串
:return: 加密后的字符串
"""
md5_obj = hashlib.md5()
md5_obj.update(ori_str.encode("utf8"))
return md5_obj.hexdigest() | 75efc3226c2f0355ce4b988acd6dcd1a95ea8294 | 3,631,915 |
import getpass
def getuser() -> str:
"""
Get the username of the current user.
Will leverage the ``getpass`` package.
Returns:
str: The username of the current user
"""
return getpass.getuser() | 3f6053e9aba37f7eafcd7735d7509af290fd3940 | 3,631,916 |
import requests
def order_depth(type_id: int, region_id: int = 10000002, system_id: int = None, order_type: str = 'sell'):
"""
Pulls the orders for a specified typeid in a region
Args:
type_id: typeid to pull the market orders for
region_id: the region the orders should be pulled from. th... | da369f5732e642bf352be85541f52dd1531d0512 | 3,631,917 |
import ctypes
def get_normal_amps():
"""This parameter will deliver the normal ampere rating for the active PDElement."""
return dsslib.CktElementF(ctypes.c_int32(0), ctypes.c_double(0)) | 16a97d32658a5e6e19d99b952724116d5c729857 | 3,631,918 |
def cal_pipe_equivalent_length(tot_bui_height_m, panel_prop, total_area_module):
"""
To calculate the equivalent length of pipings in buildings
:param tot_bui_height_m: total heights of buildings
:type tot_bui_height_m: float
:param panel_prop: properties of the solar panels
:type panel_prop: di... | 60c95cc1c5a38876095a77f4e68ab3b0df6280a3 | 3,631,919 |
def embedding_to_padding(maxlen, sequence_length):
""" Calculates the padding mask based on `sequence_length`.
Args:
maxlen: The maximum sequence length.
sequence_length: Length of each sequence in `emb`,
a Tensor with shape [batch_size, ]
Returns: A float Tensor with shape [bat... | fdd0660e7e9edbaa6523ac266dcd44873b8efccf | 3,631,920 |
from typing import List
import tqdm
import csv
def csv_fat_cross_time(arrival_enum: ArrivalEnum,
list_number_servers: List[int],
perform_param: PerformParameter, opt_method: OptMethod,
mc_dist: MonteCarloDist, target_util: float) -> dict:
"""Cho... | 5929ab69781ef979255f79f01d840fca336f19cd | 3,631,921 |
def service_status() -> Response:
"""
Service status endpoint.
Returns ``200 OK`` if the service is up and ready to handle requests.
"""
data, code, headers = controllers.service_status(request.params)
response: Response = jsonify(data)
response.status_code = code
response.headers.exten... | dbdb33253cc2a74d4c02a91e711eba7731be60de | 3,631,922 |
def gromov_wasserstein2(C1, C2, p, q, loss_fun, epsilon,
max_iter=1000, tol=1e-9, verbose=False, log=False):
"""
Returns the gromov-wasserstein discrepancy between the two measured similarity matrices
(C1,p) and (C2,q)
The function solves the following optimization problem:
... | 5a30cc1ea70bfc6c0310d791f6bb61d37df59b83 | 3,631,924 |
import copy
def parseOptions(json_options):
"""Parse the raw son options.
Parses the parameter values into ranges and adds missing information
that can be inferred from other values.
Returns parsed options as dictionary"""
parsed = dict(json_options)
if "algorithms" in json_options:
... | d254c1fd36245119bca67f19935e4a76dcb8e592 | 3,631,925 |
def numeric_type(num):
""" Verify that a value is given as a numeric data type.
Return the number if the type is sensible or raise ValueError
if not.
"""
if num is None:
num = 0
elif not (isinstance(num, int) or \
isinstance(num, long) or \
isinstance... | 3ef13db9477c0278e69bb7c2293083e00d01d48a | 3,631,926 |
from typing import Union
async def load(payload: None, context: EventContext, *,
item_id: str, update_status: bool = False) -> Union[Something, SomethingNotFound]:
"""
Loads json file from redis as `Something` instance
:param payload: unused
:param context: EventContext
:param item... | c56fcd15e9c7151c2b58c34c4cf32a36c9488a3a | 3,631,927 |
def format_parameters(section):
"""Format the "Parameters" section."""
def format_item(item):
item = map(lambda x: x.strip(), item)
return ' - **{0}**: *{1}*\n {2}'.format(*item)
return '**Parameters**\n\n{0}'.format('\n\n'.join(
map(format_item, section))) | 8f1393b843b6ea46d69d5644f932f7f0e62160ab | 3,631,928 |
def get_kinds(cell, mf, kpts, tol=1e-6):
"""Given a list of kpts, return inds such that mf.kpts[inds] is a list of kpts equivalent to the input list"""
kdiffs = mf.kpts[np.newaxis] - kpts[:, np.newaxis]
frac_kdiffs = np.dot(kdiffs, cell.lattice_vectors().T) / (2 * np.pi)
kdiffs = np.mod(frac_kdiffs + 0.... | f187a01eef1349db1fb47582d409070f7362ecc5 | 3,631,929 |
from typing import List
def restore_checkpoints(
models: List[tf.keras.Model], ckpt_dir: str) -> tf.keras.Model:
"""Restores weights from the checkpoint."""
attr_names = list(ATTRIBUTES.keys())
for i in range(2):
attr_name = attr_names[i]
print("Restoring weights for attribute %s" % at... | 25d7e9c5e6fbb27119e3be4888d9f7c3c5ec2391 | 3,631,930 |
def get_schema_piece(content_piece, uniprot_to_dcid):
"""Generate each
Args:
content_piece example:
AAC ABCD_AU181
BIT Nanobody
AID anti-SARS-CoV-2 Nb
TTY Protein
TGP UniProt:P0DTC2
TDE S, Spike protein, Spike glycoprotein
TPE Receptor-bindi... | ad7e3a8f47624602057c1ffac6e772b721722488 | 3,631,931 |
import copy
def editViewData(uniqueValue):
"""Edit the source service data for the current unique value"""
# Create a copy from the source service data
uniqueValueData = copy.deepcopy(_sourceServiceData)
# Change service data to use current unique value information (assumes a string value )
uniq... | 5a67a269e94d6906f7e1bbab757be75a875cbbd9 | 3,631,932 |
import functools
def _borg_pod_set_with_safe_self_access(wrapped_method):
"""
Wrapper for __setattr__ methods in @assimilate decorated classes to apply self.queen injection wrapper on any
relevant instance methods set during runtime.
:param Function wrapped_method: A @assimilate decorated class's... | b0dcfa6869a866794c088ac3c51eb682ca823206 | 3,631,934 |
from typing import Union
from typing import Iterable
from typing import Any
def prepend(catch: Union[type, tuple[type]], *values: Iterable[Union[Any, Iterable[Any]]]):
"""
Return a context manager that catches exception(s), prepends value(s) to the exception's
message (first argument) and reraises the exc... | 9a6a1e4e1061cc6fde92b45bdc18e367d19504ec | 3,631,935 |
import hashlib
def sha256(message):
"""
Returns the hexadecimal representation of the SHA256 hash digest.
"""
return hashlib.sha256(to_bytes(message)).hexdigest() | 1f57e10c59f896424f79dce274c153c036d4f85a | 3,631,936 |
def _grouprule_aggs_filter(having, columns):
"""
Given (having) conditions, return what to filter on as a string, to be used
after groupbys as grouped.query(string returned by this function).
:param having:
:type having: list
:param columns: Columns on which the group by is made.
:type colu... | 86243383bc3bd6f66751effe275ffaa0c34edf5e | 3,631,937 |
def _trim(s):
""" Trim long string to LOG_ENTRY_MAX_STRING(+3) length """
return s if not isinstance(s, str) or len(s) < LOG_ENTRY_MAX_STRING else s[:LOG_ENTRY_MAX_STRING] + '...' | 2e7a74796edcd63ffb5ab63254ae64989e3ad4bd | 3,631,938 |
def get_id_or_name(value, model):
"""Returns the id or name of a model instance from value. If a number or a
string is supplied, a check will be made to make sure it exists in the
data store.
"""
if not issubclass(model, db.Model):
raise TypeError('Invalid type (model); expected subclass of ... | 169643c95443a51d87bab87efc9a80ff9f98eca7 | 3,631,939 |
def validate_query_handler(query_string):
"""Verify the input query is some level of valid, right now it does not
check the value sent, just the key.
Currently only support one key, value pair -- but does verify this is
supplied."""
# likely throws an exception on parse error.
query_dict = p... | c342ef1aee9d8cf022848b2cfa9c3c43b47c5c4a | 3,631,940 |
from datetime import datetime
import time
def makevalue(t, value):
"""Get value of ctypes-compatible value in XDWAPI-compatible type."""
t = XDW_ATTRIBUTE_TYPE.normalize(t)
if t == XDW_ATYPE_INT:
return int(value)
elif t == XDW_ATYPE_STRING:
return str(value)
elif t == XDW_ATYPE_DA... | 176b4f86f7dde0a21f304cc6205792e8cdc9e6f2 | 3,631,941 |
from typing import Optional
def parse_directive_definition(
directive_definition_node: "DirectiveDefinitionNode",
schema: "GraphQLSchema",
) -> Optional["GraphQLDirective"]:
"""
Computes an AST directive definition node into a GraphQLDirective instance.
:param directive_definition_node: AST direct... | 47cfdae0387373c1ed37627ec3194cf72070e3a9 | 3,631,942 |
def _find_literal(s, start, level, parts, exprs):
"""Roughly Python/ast.c:fstring_find_literal"""
i = start
parse_expr = True
while i < len(s):
ch = s[i]
if ch in ("{", "}"):
if level == 0:
if i + 1 < len(s) and s[i + 1] == ch:
i += 2
... | 39e7d97f8aa4bfcd79af00359395605c5910985c | 3,631,943 |
import collections
def evaluate(ref_intervals, ref_labels, est_intervals, est_labels, **kwargs):
"""Compute all metrics for the given reference and estimated annotations.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab')
>>> (est_intervals,... | 62dc19f4f8e5341db53ff59d89d0cda26b14e7fc | 3,631,944 |
import re
def amex(value):
"""
Return whether or not given value is a valid American Express card number.
Examples::
>>> amex('378282246310005')
True
>>> amex('4242424242424242')
ValidationFailure(func=amex, args={'value': '4242424242424242'})
.. versionadded:: 0.15... | fa17a2631607d7e22b5b6cb5f0e85689e403c4d1 | 3,631,946 |
def rel_multihead_attn(q, k, v, pos_enc, seg_mat, attn_mask, d_model, n_head,
d_head, dropout, dropatt, is_training, initializer,
attn_bias=None, func_mask=None, scope="rel_attn",
reuse=None, rel_attn_type="factorized",
name='rel_attn'):
"""Multi-head attention with rel... | bc6fc963dee32c20f4dc54b25b7a615f39dc0ec2 | 3,631,947 |
def incident_created_modal_payload(pd_api_response):
"""Return the Slack Block Kit payload for the "Incident created" modal"""
safe_summary = slack_escape(pd_api_response["summary"])
return {
"response_action": "update",
"view": {
"type": "modal",
"title": {"type": "p... | 1e1e44c564aae6861099810f86de5051372a461e | 3,631,949 |
import re
def split_name(package: str):
""" Use regex to properly split the string into name and version spec """
version_tuple = re.search('(-\d{1,10}\.\d{1,10}\.\d{1,10}-?.{0,50})', package)
version_string = version_tuple.groups()[0]
version = version_string.split("-", 1)[1]
name = re.split('(-... | 57923f6d1af86c2b6f1b4afeded92c7af1dfca30 | 3,631,950 |
def buchdahl_find_alpha(wv, indices, wv_center, n_center, order=3, gtol=1.0e-9):
"""
Find the Buchdahl alpha parameter which gives a refractive index versus omega curve that is closest to a straight line.
Parameters
----------
wv : array of float
Wavelengths at which the refractive index da... | fd8f5d16bf721f8b0385ad3c5af79ebe7cea3df2 | 3,631,951 |
from re import T
def shn_pentity_represent(id, default_label="[No ID Tag]"):
""" Represent a Person Entity in option fields or list views """
pe_str = T("None (no such record)")
pe_table = db.pr_pentity
pe = db(pe_table.pe_id == id).select(pe_table.instance_type,
... | d48ce7d28f48d57f7386a34bacecc0f6a42bf21a | 3,631,953 |
def calculate_mean_SD_CV(df, ranking, mean_col_name):
"""calculate the mean coefficient of variation of the tFs binding to a promoter"""
# group by promoter and calculate mean for each promoter
means = df.groupby("promoter_AGI")[ranking].mean()
# turn into a dataframe
means_df = pd.DataFrame(means)
... | 8fbefc305ea3ada337cf929e19953c3e56549b64 | 3,631,954 |
def normalize_trinucleotide(trinucleotide):
"""Return the normalized representation of the input trinucleotide sequence
Notes
-----
Each trinucleotide sequence has two possible representations (the sequence
and its reverse complement). For example, 5'-ACG-3' and 5'-CGT-3' are two
representation... | fe04ba6fad28285eac9becbbd6e5324ec7734850 | 3,631,955 |
def r2z(data):
"""
Fischer's r-to-z transform on a matrix (elementwise).
"""
return(0.5 * np.log((1+data) / (1-data))) | 8874829837c2b47d019325835b73080cd524c0ac | 3,631,957 |
def loader_shift(loader, frame, relative=True):
"""Shift global in time by i preserving duration
This moves the loader by i frames preserving global duration. When relative
is False it will shift the global in to the start frame.
Args:
loader (tool): The fusion loader tool.
frame (int)... | 2593473b58aad8e073aaf7d4adc978e12df20762 | 3,631,958 |
import time
def get_current_timestamp(): # pylint: disable=unused-variable
"""
Retrieves the current local time in a custom timestamp format
"""
return time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime()) | 839ef3e2bc434355d5b077ef4e2a1cb138fab2d1 | 3,631,959 |
from datetime import datetime
def get_fight_updates(game_ids=None, before=None, after=None, order=None, count=None, page_size=1000, lazy=False, cache_time=5):
"""
Return a list of boss fight event updates
Args:
game_ids: list or comma-separated string of fight IDs.
before: return elements... | 69b32e224cd2651de850b03fd3ba2fef05e327cc | 3,631,960 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.