content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_training_patches(images, patch_size, patches_per_image=1, patch_stride=None):
"""
Returns a batch of image patches, given a batch of images.
Args:
images (list, numpy.array): Batch of images.
patch_size (tuple, list): The (width, height) of the patch to
return.
... | 5fce19d2d13f790500e0cbd42934dd6e83c6b084 | 12,573 |
import time
def get_prover_options(prover_round_tag='manual',
prover_round=-1) -> deephol_pb2.ProverOptions:
"""Returns a ProverOptions proto based on FLAGS."""
if not FLAGS.prover_options:
tf.logging.fatal('Mandatory flag --prover_options is not specified.')
if not tf.gfile.Exists(FL... | ee1ee9fb7ce573c543f0750d6b8fd1eed98deec9 | 12,574 |
def bracketpy(pystring):
"""Find CEDICT-style pinyin in square brackets and correct pinyin.
Looks for square brackets in the string and tries to convert its
contents to correct pinyin. It is assumed anything in square
brackets is CC-CEDICT-format pinyin.
e.g.: "拼音[pin1 yin1]" will be converted int... | 0499047ec45e6b9c66c27dd89663667b13ddbfb1 | 12,575 |
import psutil
def get_ram_usage_bytes(size_format: str = 'M'):
"""
Size formats include K = Kilobyte, M = Megabyte, G = Gigabyte
"""
total = psutil.virtual_memory().total
available = psutil.virtual_memory().available
used = total - available
# Apply size
if size_format == 'K':
... | 990987078b0ad3c2ac2ee76dcf96b7cdf01f0354 | 12,576 |
def weighted_crossentropy(weights, name='anonymous'):
"""A weighted version of tensorflow.keras.objectives.categorical_crossentropy
Arguments:
weights = np.array([0.5,2,10]) # Class one at 0.5, class 2 twice the normal weights, class 3 10x.
name: string identifying the loss to differentiate whe... | 071ab00a723d54194b4b27c889c638debe82f10a | 12,577 |
def _get_package_type(id):
"""
Given the id of a package this method will return the type of the
package, or 'dataset' if no type is currently set
"""
pkg = model.Package.get(id)
if pkg:
return pkg.type or u'dataset'
return None | c84e137e2b0adaf8719d757f178aa47d4a63c46a | 12,578 |
def _find_protruding_dimensions(f, care, fol):
"""Return variables along which `f` violates `care`."""
vrs = joint_support([f, care], fol)
dims = set()
for var in vrs:
other_vars = vrs - {var}
f_proj = fol.exist(other_vars, f)
care_proj = fol.exist(other_vars, care)
if (c... | 02da5718645652288c9fa6fcedc07198afe49a58 | 12,579 |
import random
def simulate_relatedness(genotypes, relatedness=.5, n_iter=1000, copy=True):
"""
Simulate relatedness by randomly copying genotypes between individuals.
Parameters
----------
genotypes : array_like
An array of shape (n_variants, n_samples, ploidy) where each
element... | e319f4e15c4c08eb90260b77efc25ea330aac4c9 | 12,581 |
def pages_substitute(content):
"""
Substitute tags in pages source.
"""
if TAG_USERGROUPS in content:
usergroups = UserGroup.objects.filter(is_active=True).order_by('name')
replacement = ", ".join(f"[{u.name}]({u.webpage_url})" for u in usergroups)
content = content.replace(TAG_U... | 13c2138256a0e1afa0ad376994849f2716020540 | 12,582 |
def vcfanno(vcf, out_file, conf_fns, data, basepath=None, lua_fns=None):
"""
annotate a VCF file using vcfanno (https://github.com/brentp/vcfanno)
"""
if utils.file_exists(out_file):
return out_file
if lua_fns is None:
lua_fns = []
vcfanno = config_utils.get_program("vcfanno", da... | 808488bd07c56b541694715193df4ae1cb51869c | 12,583 |
def clean(params: dict) -> str:
"""
Build clean rules for Makefile
"""
clean = "\t@$(RM) -rf $(BUILDDIR)\n"
if params["library_libft"]:
clean += "\t@make $@ -C " + params["folder_libft"] + "\n"
if params["library_mlx"] and params["compile_mlx"]:
clean += "\t@make $@ -C " + params["folder_mlx"] + "\n"
retur... | fb7dd0e7a2fbb080dd8b0d5d4489e9c5ef1367ec | 12,584 |
import re
def mathematica(quero: str, meta: str = '') -> bool:
"""mathematica
Rudimentar mathematical operations (boolean result)
Args:
quero (_type_, optional): _description_. Defaults to str.
Returns:
bool: True if evaluate to True.
"""
# neo_quero = quero.replace(' ', '')... | b05777e880688d8f3fc90ba9d54098f341054bd7 | 12,585 |
def time_pet(power,energy):
"""Usage: time_pet(power,energy)"""
return energy/power | 11e9c82b8c1be84995f9517e04ed5e1270801e27 | 12,587 |
def compute_sigma0(
T,
S,
**kwargs,
):
"""
compute the density anomaly referenced to the surface
"""
return compute_rho(T, S, 0, **kwargs) - 1000 | 300d5552c70e6fd6d8708345aa3eed53795309cf | 12,588 |
def get_neighbors_radius(nelx, nely, coord, connect, radius):
""" Check neighboring elements that have the centroid within the predetermined radius.
Args:
nelx (:obj:`int`): Number of elements on the x axis.
nely (:obj:`int`): Number of elements on the x axis
coord (:obj:`numpy.array`):... | 669e11d3a2890f1485e33e021b2671ff6f197c03 | 12,589 |
import copy
def merge_with(obj, *sources, **kwargs):
"""
This method is like :func:`merge` except that it accepts customizer which is invoked to produce
the merged values of the destination and source properties. If customizer returns ``None``,
merging is handled by this method instead. The customizer... | 94a16ae7d3f3e73ef8e27b32cd38a09c61ad1b2b | 12,590 |
def count_class_nbr_patent_cnt(base_data_list, calculate_type):
"""
统计在所有数据中不同分类号对应的专利数量
:param base_data_list:
:return:
"""
class_number_patent_cnt_dict = dict()
for base_data in base_data_list:
class_number_value = base_data[const.CLASS_NBR]
calculate_class_number_patent_co... | 6dfe06c2233fbfafc8083dc968d32520564319f8 | 12,591 |
def plot_pta_L(df):
"""
INPUTS
-df: pandas dataframe containing the data to plot
OUTPUTS
-saves pta graphs in .html
"""
title = generate_title_run_PTA(df, "Left Ear", df.index[0])
labels = {"title": title,
"x": "Frequency (Hz)",
"y": "Hearing Threshold (dB HL... | ec82b58a6a476bee5e864b8678bb90d2998d4a02 | 12,592 |
def create_graph(edge_num: int, edge_list: list) -> dict:
"""
Create a graph expressed with adjacency list
:dict_key : int (a vertex)
:dict_value : set (consisted of vertices adjacent to key vertex)
"""
a_graph = {i: set() for i in range(edge_num)}
for a, b in edge_list:
a_graph... | 6ec1a71cf82a3a669090df42ac7d53e1286fda2d | 12,593 |
def get_current_version() -> str:
"""Read the version of the package.
See https://packaging.python.org/guides/single-sourcing-package-version
"""
version_exports = {}
with open(VERSION_FILE) as file:
exec(file.read(), version_exports) # pylint: disable=exec-used
return version_exports["... | c283d58881aa381503bb3500bd7d745f25df0f7e | 12,595 |
import random
def seed_story(text_dict):
"""Generate random seed for story."""
story_seed = random.choice(list(text_dict.keys()))
return story_seed | 0c0f41186f6eaab84a1d197e9335b4c28fd83785 | 12,596 |
def _get_rel_att_inputs(d_model, n_heads): # pylint: disable=invalid-name
"""Global relative attentions bias initialization shared across the layers."""
assert d_model % n_heads == 0 and d_model % 2 == 0
d_head = d_model // n_heads
bias_initializer = init.RandomNormalInitializer(1e-6)
context_bias_layer = c... | 57f58f29a586571f1cc8fa1fc69956a4168cbf16 | 12,598 |
def two_time_pad():
"""A one-time pad simply involves the xor of a message with a key to produce a ciphertext: c = m ^ k.
It is essential that the key be as long as the message, or in other words that the key not be repeated for two distinct message blocks.
Your task:
In this problem you will b... | d4c45312f32b372a065365c78a991969e2bc53be | 12,599 |
def same_datatypes(lst):
"""
Überprüft für eine Liste, ob sie nur Daten vom selben Typ enthält. Dabei spielen Keys, Länge der Objekte etc. eine Rolle
:param lst: Liste, die überprüft werden soll
:type lst: list
:return: Boolean, je nach Ausgang der Überprüfung
"""
datatype = type(lst[0]).__... | 9c49376ec34ed0970171597f77de4c4c224350b4 | 12,600 |
def _show_stat_wrapper_Progress(count, last_count, start_time, max_count, speed_calc_cycles,
width, q, last_speed, prepend, show_stat_function, add_args,
i, lock):
"""
calculate
"""
count_value, max_count_value, speed, tet, ttg, = Pro... | 3c98f44acc8de94573ba37a7785df18fc8e72966 | 12,601 |
def _to_base58_string(prefixed_key: bytes):
"""
Convert prefixed_key bytes into Es/EC strings with a checksum
:param prefixed_key: the EC private key or EC address prefixed with the appropriate bytes
:return: a EC private key string or EC address
"""
prefix = prefixed_key[:PREFIX_LENGTH]
as... | 326580e714d6489a193347498c68ef9d90f6f651 | 12,602 |
def round_int(n, d):
"""Round a number (float/int) to the closest multiple of a divisor (int)."""
return round(n / float(d)) * d | 372c0f8845994aaa03f99ebb2f65243e6490b341 | 12,603 |
def merge_array_list(arg):
"""
Merge multiple arrays into a single array
:param arg: lists
:type arg: list
:return: The final array
:rtype: list
"""
# Check if arg is a list
if type(arg) != list:
raise errors.AnsibleFilterError('Invalid value type, should... | 649412488655542f27a1e7d377252c060107b57e | 12,604 |
def load_callbacks(boot, bootstrap, jacknife,
out, keras_verbose, patience):
"""
Specifies Keras callbacks, including checkpoints, early stopping,
and reducing learning rate.
Parameters
----------
boot
bootstrap
jacknife
out
keras_verbose
patience
batc... | 0ca09ccaca4424c1a546caade3d809b7f69cbb5e | 12,605 |
def build_sentence_model(cls, vocab_size, seq_length, tokens, transitions,
num_classes, training_mode, ground_truth_transitions_visible, vs,
initial_embeddings=None, project_embeddings=False, ss_mask_gen=None, ss_prob=0.0):
"""
Construct a classifier which makes... | 085d6a0538bfa06a34c543c27efd651c4c46168a | 12,606 |
def read_xls_as_dict(filename, header="top"):
"""
Read a xls file as dictionary.
@param filename File name (*.xls or *.xlsx)
@param header Header position. Options: "top", "left"
@return Dictionary with header as key
"""
table = read_xls(filename)
if (header == "top... | 9ed410e42a11ee898466bb2f36b6d02e051b21ec | 12,607 |
def check_hostgroup(zapi, region_name, cluster_id):
"""check hostgroup from region name if exists
:region_name: region name of hostgroup
:returns: true or false
"""
return zapi.hostgroup.exists(name="Region [%s %s]" % (region_name, cluster_id)) | b237b544ac59331ce94dd1ac471187a60d527a1b | 12,608 |
import tempfile
def matlab_to_tt(ttemps, eng, is_orth=True, backend="numpy", mode="l"):
"""Load matlab.object representing TTeMPS into Python as TT"""
_, f = tempfile.mkstemp(suffix=".mat")
eng.TTeMPS_to_Py(f, ttemps, nargout=0)
tt = load_matlab_tt(f, is_orth=is_orth, mode=mode, backend=backend)
... | e21087e2587368a55ece7a50f576573c5284373a | 12,609 |
def encode_mecab(tagger, string):
"""
string을 mecab을 이용해서 형태소 분석
:param tagger: 형태소 분석기 객체
:param string: input text
:return tokens: 형태소 분석 결과
:return indexs: 띄어쓰기 위치
"""
string = string.strip()
if len(string) == 0:
return [], []
words = string.split()
nodes = tagger.... | 847278728ebe7790d8aef2a125a420d5779adc6b | 12,610 |
def nutrient_limited_growth(X,idx_A,idx_B,growth_rate,half_saturation):
""" non-linear response with respect to *destination/predator* compartment
Similar to holling_type_II and is a reparameterization of holling II.
The response with respect to the origin compartment 'B' is approximately
linear for s... | 05e66a0e426a404a5356f04f8568ab23548b6dbe | 12,611 |
def aes128_decrypt(AES_KEY, _data):
"""
AES 128 位解密
:param requestData:
:return:
"""
# 秘钥实例
newAes = getAesByKey(AES_KEY)
# 解密
data = newAes.decrypt(_data)
rawDataLength = len(data)
# 剔除掉数据后面的补齐位
paddingNum = ord(data[rawDataLength - 1])
if paddingNum > 0 and paddin... | 520c03a509f63807a62ccb0385e99bc9b674fd67 | 12,612 |
def human_readable_size(size, decimals=1):
"""Transform size in bytes into human readable text."""
for unit in ["B", "KB", "MB", "GB", "TB"]:
if size < 1000:
break
size /= 1000
return f"{size:.{decimals}f} {unit}" | 5fb0dc79162d0bc0a945061aa0889735b24fff7b | 12,613 |
def generichash_blake2b_final(statebuf, digest_size):
"""Finalize the blake2b hash state and return the digest.
:param statebuf:
:type statebuf: bytes
:param digest_size:
:type digest_size: int
:return: the blake2 digest of the passed-in data stream
:rtype: bytes
"""
_digest = ffi.... | a81da8346bafb2f7d8fd40b0d9ff204689d002f8 | 12,614 |
def walker_input_formatter(t, obs):
"""
This function formats the data to give as input to the controller
:param t:
:param obs:
:return: None
"""
return obs | 651038cd4dc0e8c8ccb89a10a5b20f6031e17ba8 | 12,615 |
def build_url_base(url):
"""Normalize and build the final url
:param url: The given url
:type url: str
:return: The final url
:rtype: str
"""
normalize = normalize_url(url=url)
final_url = "{url}/api".format(url=normalize)
return final_url | a500a6d96ab637182abab966817209324ddc670a | 12,616 |
from typing import Tuple
from typing import List
def build_decoder(
latent_dim: int,
input_shape: Tuple,
encoder_shape: Tuple,
filters: List[int],
kernels: List[Tuple[int, int]],
strides: List[int]
) -> Model:
"""Return decoder model.
Parameters
----------
latent_dim:int,
... | efdac0fa9df81249e531b2568cd8f91816c209a6 | 12,617 |
def execute_with_python_values(executable, arguments=(), backend=None):
"""Execute on one replica with Python values as arguments and output."""
backend = backend or get_local_backend()
def put(arg):
return Buffer.from_pyval(
arg, device=executable.DeviceOrdinals()[0], backend=backend)
arguments ... | 26c9352feb2e5c7e6fb46702105245f582218e91 | 12,618 |
def _get_label_members(X, labels, cluster):
"""
Helper function to get samples of a specified cluster.
Args:
X (np.ndarray): ndarray with dimensions [n_samples, n_features]
data to check validity of clustering
labels (np.array): clustering assignments for data X
cluster (... | 18c213f88816108f93ddd38cdd2c934f431ea35a | 12,620 |
from typing import Tuple
def get_spectrum_by_close_values(
mz: list,
it: list,
left_border: float,
right_border: float,
*,
eps: float = 0.0
) -> Tuple[list, list, int, int]:
"""int
Function to get segment of spectrum by left and right
border
:param mz: m/z array
:param it: ... | 0ec34b044b9105fe1c232baa9b51760cbb96b9d9 | 12,621 |
def refresh_wrapper(trynum, maxtries, *args, **kwargs):
"""A @retry argmod_func to refresh a Wrapper, which must be the first arg.
When using @retry to decorate a method which modifies a Wrapper, a common
cause of retry is etag mismatch. In this case, the retry should refresh
the wrapper before attemp... | 089b859964e89d54def0058abc9cc7536f5d8877 | 12,623 |
def compute_frames_per_animation(
attacks_per_second: float,
base_animation_length: int,
speed_coefficient: float = 1.0,
engine_tick_rate: int = 60,
is_channeling: bool = False) -> int:
"""Calculates frames per animation needed to resolve a certain ability at attacks_per_seco... | 44427cf28152de21de42f0220e75f87717235275 | 12,624 |
def pad_rect(rect, move):
"""Returns padded rectangles given specified padding"""
if rect['dx'] > 2:
rect['x'] += move[0]
rect['dx'] -= 1*move[0]
if rect['dy'] > 2:
rect['y'] += move[1]
rect['dy'] -= 1*move[1]
return rect | 48bdbdc9d4736e372afc983ab5966fc80a221d4d | 12,625 |
import asyncio
async def yes_no(ctx: commands.Context,
message: str="Are you sure? Type **yes** within 10 seconds to confirm. o.o"):
"""Yes no helper. Ask a confirmation message with a timeout of 10 seconds.
ctx - The context in which the question is being asked.
message - Optional messs... | 2b8ab0bfc51d4be68a42507bad6dbb945465d2e4 | 12,626 |
def __validation(size: int, it1: int, it2: int, it3: int, it4: int) -> bool:
""" Проверка на корректность тура
size: размер маршрута
it1, it2, it3, it4: индексы городов: t1, t2i, t2i+1, t2i+2
return: корректен или нет
"""
return between(size, it1, it3, it4) and between(size, it4, it2, it1) | 5fcb29f45c456115e8b87f0313e05f327c702849 | 12,627 |
def get_type_associations(base_type, generic_base_type): # type: (t.Type[TType], t.Type[TValue]) -> t.List[t.Tuple[t.Type[TValue], t.Type[TType]]]
"""Create and return a list of tuples associating generic_base_type derived types with a corresponding base_type derived type."""
return [item for item in [(get_gen... | fe18bf72a96d6dfa8fad2c625732e781d54cae4d | 12,628 |
import rpy2.robjects as robj
from rpy2.robjects.packages import importr
import anndata2ri
def identify_empty_droplets(data, min_cells=3, **kw):
"""Detect empty droplets using DropletUtils
"""
importr("DropletUtils")
adata = data.copy()
col_sum = adata.X.sum(0)
if hasattr(col_sum, 'A'):
... | 9c2d532d75afb6044836249eb525e86c60511c9b | 12,629 |
def catalog_category_RSS(category_id):
"""
Return an RSS feed containing all items in the specified category_id
"""
items = session.query(Item).filter_by(
category_id=category_id).all()
doc = jaxml.XML_document()
doc.category(str(category_id))
for item in items:
doc._push()
... | 13554cf1eba3a83c0fb23a6f848751721579dfea | 12,630 |
def get_caller_name(N=0, allow_genexpr=True):
"""
get the name of the function that called you
Args:
N (int): (defaults to 0) number of levels up in the stack
allow_genexpr (bool): (default = True)
Returns:
str: a function name
CommandLine:
python -m utool.util_dbg... | 6c6ce7690d1bc4bd51037056e27f5dbd73085e29 | 12,631 |
from typing import Any
def create_user(
*,
db: Session = Depends(deps.get_db),
user_in: schema_in.UserCreateIn,
) -> Any:
"""
Create new user.
"""
new_user = User(**{k: v for k, v in user_in.dict().items() if k != 'password'})
new_user.hashed_password = get_password_hash(user_in.passwo... | cd8c3036026639d3e29e6dc030335f328d11c144 | 12,634 |
import math
def number_format(interp, num_args, number, decimals=0, dec_point='.',
thousands_sep=','):
"""Format a number with grouped thousands."""
if num_args == 3:
return interp.space.w_False
ino = int(number)
dec = abs(number - ino)
rest = ""
if decimals == 0 and ... | 9d5ab0b9ed5dd6054ce4f356e6811c1b155e2062 | 12,635 |
from typing import Optional
def _serialization_expr(value_expr: str, a_type: mapry.Type,
py: mapry.Py) -> Optional[str]:
"""
Generate the expression of the serialization of the given value.
If no serialization expression can be generated (e.g., in case of nested
structures suc... | 5920a4c10dabe2ff061a1f141cd9c9f10faebafa | 12,636 |
def get_init_hash():
""" 获得一个初始、空哈希值 """
return imagehash.ImageHash(np.zeros([8, 8]).astype(bool)) | cd4665e6b5cdf232883093dab660aafcc2109a44 | 12,637 |
def get_vertex_between_points(point1, point2, at_distance):
"""Returns vertex between point1 and point2 at a distance from point1.
Args:
point1: First vertex having tuple (x,y) co-ordinates.
point2: Second vertex having tuple (x,y) co-ordinates.
at_distance: A distance at which to locate... | acb5cd76ef7dd3a16592c5fbaf74d6d777ab338c | 12,638 |
def disable_cache(response: Response) -> Response:
"""Prevents cached responses"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, public, max-age=0"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response | 6f63c7e93a7c354c85171652dca51162e15b7137 | 12,639 |
def get_dir(src_point, rot_rad):
"""Rotate the point by `rot_rad` degree."""
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
src_result = [0, 0]
src_result[0] = src_point[0] * cs - src_point[1] * sn
src_result[1] = src_point[0] * sn + src_point[1] * cs
return src_result | 40b36671c50a6b6b8905eca9915901cd613c2aaa | 12,640 |
def sparse_gauss_seidel(A,b,maxiters=100,tol=1e-8):
"""Returns the solution to the system Ax = b using the Gauss-Seidel method.
Inputs:
A (array) - 2D scipy.sparse matrix
b (array) - 1D NumPy array
maxiters (int, optional) - maximum iterations for algorithm to perform.
tol (floa... | 139fefa8e45d14f32ea9bb4dd25df03762737090 | 12,641 |
def delete_user(user_id):
"""Delete user from Users database and their permissions
from SurveyPermissions and ReportPermissions.
:Route: /api/user/<int:user_id>
:Methods: DELETE
:Roles: s
:param user_id: user id
:return dict: {"delete": user_id}
"""
user = database.get_user(user_id... | c8f86dc20db67a5e3511e082f6308903b1acdaa2 | 12,642 |
def selectTopFive(sortedList):
"""
从sortedList中选出前五,返回对应的名字与commit数量列成的列表
:param sortedList:按值从大到小进行排序的authorDict
:return:size -- [commit数量]
labels -- [名字]
"""
size = []
labels = []
for i in range(5):
labels.append(sortedList[i][0])
size.append(sortedList[i][1... | 747ad379ed73aeb6ccb48487b48dc6150350204e | 12,643 |
def get_license(file):
"""Returns the license from the input file.
"""
# Collect the license
lic = ''
for line in file:
if line.startswith('#include') or line.startswith('#ifndef'):
break
else:
lic += line
return lic | 126fff2dd0464ef1987f3ab672f6b36b8fa962f7 | 12,644 |
def quote_query_string(chars):
"""
Multibyte charactor string is quoted by double quote.
Because english analyzer of Elasticsearch decomposes
multibyte character strings with OR expression.
e.g. 神保町 -> 神 OR 保 OR 町
"神保町"-> 神保町
"""
if not isinstance(chars, unicode):
chars = c... | 8d1888df17a617d42e6a0d1b909e08e4f84fa4c9 | 12,645 |
def copy_params(params: ParamsDict) -> ParamsDict:
"""copy a parameter dictionary
Args:
params: the parameter dictionary to copy
Returns:
the copied parameter dictionary
Note:
this copy function works recursively on all subdictionaries of the params
dictionary but does... | 8248b31698f6b51103dc34bad7b13373591b10cd | 12,646 |
def watch_list(request):
"""
Get watchlist or create a watchlist, or delete from watchlist
:param request:
:return:
"""
if request.method == 'GET':
watchlist = WatchList.objects.filter(user=request.user)
serializer = WatchListSerializer(watchlist, many=True)
return Respon... | c92d39da05546fea9330ffe44cea5dd0c30f6427 | 12,647 |
async def user_has_pl(api, room_id, mxid, pl=100):
"""
Determine if a user is admin in a given room.
"""
pls = await api.get_power_levels(room_id)
users = pls["users"]
user_pl = users.get(mxid, 0)
return user_pl == pl | 5678af17469202e0b0a0232e066e7ed5c8212ee6 | 12,648 |
import cgi
from typing import Optional
def get_cgi_parameter_bool_or_default(form: cgi.FieldStorage,
key: str,
default: bool = None) -> Optional[bool]:
"""
Extracts a boolean parameter from a CGI form (``"1"`` = ``True``,
other st... | 905dfa96628414e3b076fd3345113588f3f6ef08 | 12,649 |
def loss_function_1(y_true, y_pred):
""" Probabilistic output loss """
a = tf.clip_by_value(y_pred, 1e-20, 1)
b = tf.clip_by_value(tf.subtract(1.0, y_pred), 1e-20, 1)
cross_entropy = - tf.multiply(y_true, tf.log(a)) - tf.multiply(tf.subtract(1.0, y_true), tf.log(b))
cross_entropy = tf.reduce_mean(cr... | 8426ef13bd56fa3ff11226556d37bf738333a165 | 12,650 |
def sanitize_for_json(tag):
"""eugh the tags text is in comment strings"""
return tag.text.replace('<!--', '').replace('-->', '') | 211c07864af825ad29dfc806844927db977e6ce0 | 12,651 |
def load_data_and_labels(dataset_name):
"""
Loads MR polarity data from files, splits the data into words and generates labels.
Returns split sentences and labels.
"""
for i in [1]:
# Load data from files
positive_examples = list(open('data/'+str(dataset_name)+'/'+str(dataset_name)+'... | d753494f3a614850c07f40230c3373eab13b0c6b | 12,652 |
def tileswrap(ihtORsize, numtilings, floats, wrapwidths, ints=[], readonly=False):
"""Returns num-tilings tile indices corresponding to the floats and ints, wrapping some floats"""
qfloats = [floor(f * numtilings) for f in floats]
Tiles = []
for tiling in range(numtilings):
tilingX2 = tiling * 2... | e9a9dc439307fc114c9abc939f642ea411acd26e | 12,653 |
def coerce(data, egdata):
"""Coerce a python object to another type using the AE coercers"""
pdata = pack(data)
pegdata = pack(egdata)
pdata = pdata.AECoerceDesc(pegdata.type)
return unpack(pdata) | dc7499530b77a25c8b51537e2e21115d3ce3ccee | 12,654 |
from typing import Union
from typing import List
def _write_mkaero1(model: Union[BDF, OP2Geom], name: str,
mkaero1s: List[MKAERO1], ncards: int,
op2_file, op2_ascii, endian: bytes, nastran_format: str='nx') -> int:
"""writes the MKAERO1
data = (1.3, -1, -1, -1, -1, -1, -... | ad45ec25989714685a6a2b2e61d6833a9ab56a6d | 12,656 |
def _mesh_obj_large():
"""build a large, random mesh model/dataset"""
n_tri, n_pts = 400, 1000
node = np.random.randn(n_pts, 2)
element = np.array([np.random.permutation(n_pts)[:3] for _ in range(n_tri)])
perm = np.random.randn(n_tri)
np.random.seed(0)
el_pos = np.random.permutation(n_pts)[:... | c2db6a3484dc4923d92519488d0b10d7a7cd75bb | 12,657 |
def cursor():
"""Return a database cursor."""
return util.get_dbconn("mesosite").cursor() | 516cf2a1716204487dd4cff4f063397365b21fa1 | 12,658 |
def custom_field_check(issue_in, attrib, name=None):
""" This method allows the user to get in the comments customfiled that are not common
to all the project, in case the customfiled does not existe the method returns an
empty string.
"""
if hasattr(issue_in.fields, attrib):
value = str(eval('iss... | d9c051fa922f34242d3b5e94e8534b4dc8038f19 | 12,659 |
def header(text, color='black', gen_text=None):
"""Create an HTML header"""
if gen_text:
raw_html = f'<h1 style="margin-top:16px;color: {color};font-size:54px"><center>' + str(
text) + '<span style="color: red">' + str(gen_text) + '</center></h1>'
else:
raw_html = f'<h1 style="m... | 646b0a16b35cd4350feadd75674eea6ab6da6404 | 12,660 |
def block_pose(detection, block_size=0.05):
# type: (AprilTagDetection, float) -> PoseStamped
"""Given a tag detection (id == 0), return the block's pose. The block pose
has the same orientation as the tag detection, but it's position is
translated to be at the cube's center.
Args:
detectio... | da6ee3bb1bf8a071ea5859d17dcad07ecd8781a3 | 12,661 |
async def batch_omim_similarity(
data: models.POST_OMIM_Batch,
method: str = 'graphic',
combine: str = 'funSimAvg',
kind: str = 'omim'
) -> dict:
"""
Similarity score between one HPOSet and several OMIM Diseases
"""
other_sets = []
for other in data.omim_diseases:
try:
... | 2da8dc25d867f132ec0f571b4d9dff3d7de38c21 | 12,662 |
def vector(*,
unit: _Union[_cpp.Unit, str, None] = default_unit,
value: _Union[_np.ndarray, list]):
"""Constructs a zero dimensional :class:`Variable` holding a single length-3
vector.
:param value: Initial value, a list or 1-D numpy array.
:param unit: Optional, unit. Default=di... | dda09f89ba00ffab789c7ed9f6f6713a45c9bd03 | 12,663 |
import laspy
def read_lidar(filename, **kwargs):
"""Read a LAS file.
Args:
filename (str): Path to a LAS file.
Returns:
LasData: The LasData object return by laspy.read.
"""
try:
except ImportError:
print(
"The laspy package is required for this function. ... | 5336c34223216d4a1857cc5c858ccca704508e22 | 12,664 |
def get_gene_starting_with(gene_symbol: str, verbose: bool = True):
""" get the genes that start with the symbol given
Args:
- gene_symbol: str
- verbose: bool
Returns:
- list of str
- None
"""
gene_symbol = gene_symbol.strip().upper()
ext = "search/symbol/{}*".format(gene_sy... | c0f092a93d44dd264f6b251ff3eba565b29abda0 | 12,665 |
import time
def gen_timestamp():
"""
Generates a unique (let's hope!), whole-number, unix-time timestamp.
"""
return int(time() * 1e6) | cb044e7428c062660eb998856245d4cd2c692a7e | 12,666 |
def learningCurve(X, y, Xval, yval, Lambda):
"""returns the train and
cross validation set errors for a learning curve. In particular,
it returns two vectors of the same length - error_train and
error_val. Then, error_train(i) contains the training error for
i examples (and similarly for error_val(i... | 8cdfdec694cbfadef92375c7cf8eba4da012be59 | 12,667 |
def decode_xml(text):
"""Parse an XML document into a dictionary. This assume that the
document is only 1 level, i.e.:
<top>
<child1>content</child1>
<child2>content</child2>
</top>
will be parsed as: child1=content, child2=content"""
xmldoc = minidom.parseString(text)
retur... | 826bdc1ff0c4df503fdbc6f7e76b013d907b208b | 12,668 |
def _qcheminputfile(ccdata, templatefile, inpfile):
"""
Generate input file from geometry (list of lines) depending on job type
:ccdata: ccData object
:templatefile: templatefile - tells us which template file to use
:inpfile: OUTPUT - expects a path/to/inputfile to write inpfile
""... | 3ca565c4c599bccfd3916a0003126b3085cc7254 | 12,669 |
def arrangements(ns):
"""
prime factors of 19208 lead to the "tribonacci" dict;
only needed up to trib(4)
"""
trib = {0: 1, 1: 1, 2: 2, 3: 4, 4: 7}
count = 1
one_seq = 0
for n in ns:
if n == 1:
one_seq += 1
if n == 3:
count *= trib[one_seq]
one_seq = 0
return count
# # one-liner...
# return r... | 01f3defb25624d7a801be87c7336ddf72479e489 | 12,670 |
def vtpnt(x, y, z=0):
"""坐标点转化为浮点数"""
return win32com.client.VARIANT (pythoncom.VT_ARRAY | pythoncom.VT_R8, (x, y, z)) | 1e7c79353d010d4dd8daa4b7fa7c39b841ff8ffe | 12,671 |
from datetime import datetime
def get_time_delta(pre_date: datetime):
"""
获取给定时间与当前时间的差值
Args:
pre_date:
Returns:
"""
date_delta = datetime.datetime.now() - pre_date
return date_delta.days | 4f8894b06dc667b166ab0ee6d86b484e967501ac | 12,672 |
from bs4 import BeautifulSoup
def render_checkbox_list(soup_body: object) -> object:
"""As the chosen markdown processor does not support task lists (lists with checkboxes), this function post-processes
a bs4 object created from outputted HTML, replacing instances of '[ ]' (or '[]') at the beginning of a list... | 640f00d726a1268eb71134e29dbde53ef0ec44f5 | 12,673 |
def slowness_to_velocity(slowness):
"""
Convert a slowness log in µs per unit depth, to velocity in unit depth
per second.
Args:
slowness (ndarray): A value or sequence of values.
Returns:
ndarray: The velocity.
"""
return 1e6 / np.array(slowness) | dbfc3b4206ddf615da634e328328c4b8588e5c7a | 12,674 |
def SingleDetectorLogLikelihoodModelViaArray(lookupNKDict,ctUArrayDict,ctVArrayDict, tref, RA,DEC, thS,phiS,psi, dist,det):
"""
DOCUMENT ME!!!
"""
global distMpcRef
# N.B.: The Ylms are a function of - phiref b/c we are passively rotating
# the source frame, rather than actively rotating the b... | 35c27e53833cb54f856adde6815bf51c3feca019 | 12,675 |
import numpy as np
def manualcropping(I, pointsfile):
"""This function crops a copy of image I according to points stored
in a text file (pointsfile) and corresponding to aponeuroses (see
Args section).
Args:
I (array): 3-canal image
pointsfile (text file): contains points' coordina... | eb3f49b5b46d1966946fc3d00bcae113f51c60d1 | 12,676 |
from datetime import datetime
def prepare_time_micros(data, schema):
"""Convert datetime.time to int timestamp with microseconds"""
if isinstance(data, datetime.time):
return int(data.hour * MCS_PER_HOUR + data.minute * MCS_PER_MINUTE
+ data.second * MCS_PER_SECOND + data.microsecon... | bfdfe40065db66417bf2b641a24b195f4114687e | 12,677 |
def get_configs_path_mapping():
"""
Gets a dictionary mapping directories to back up to their destination path.
"""
return {
"Library/Application Support/Sublime Text 2/Packages/User/": "sublime_2",
"Library/Application Support/Sublime Text 3/Packages/User/": "sublime_3",
"Library/Preferences/IntelliJIdea2018... | d7617139a36ca2e1d4df57379d6af73e3b075c84 | 12,678 |
def num_from_bins(bins, cls, reg):
"""
:param bins: list
The bins
:param cls: int
Classification result
:param reg:
Regression result
:return: computed value
"""
bin_width = bins[0][1] - bins[0][0]
bin_center = float(bins[cls][0] + bins[cls][1]) / 2
return bin... | 468e56075cf214f88d87298b259f7253d013a3f3 | 12,680 |
def rotate90(matrix: list) -> tuple:
"""return the matrix rotated by 90"""
return tuple(''.join(column)[::-1] for column in zip(*matrix)) | 770a8a69513c4f88c185778ad9203976d5ee6147 | 12,681 |
def get_aspect(jdate, body1, body2):
"""
Return the aspect and orb between two bodies for a certain date
Return None if there's no aspect
"""
if body1 > body2:
body1, body2 = body2, body1
dist = distance(long(jdate, body1),
long(jdate, body2))
for i_asp, aspect in... | 11a9b05fbc924290e390329395361da0c856541e | 12,682 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.