content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def preprocess(inputs,
output_keys=None,
is_training=False,
input_field_mapping_fn=None,
image_preprocess_fn_dic=None,
images_points_correspondence_fn=None,
points_pad_or_clip_size=None,
voxels_pad_or_clip_size=None... | f41b93fa10aaaeca081d9af25e16e52b8d4655f6 | 3,599,882 |
def _get_dataset_from_files(file_name_pattern: str, label: int, test_set_pct: int, shuffle: bool):
"""Create train and test sets from the images in the directory, given the pattern.
Args:
file_name_pattern (str): The file name pattern that identifies one set of images.
label (int): The label to... | 99072b210f62646db45968adbcc537748455c8ae | 3,599,884 |
def BD_BldGag(BD):
""" Returns the radial position of BeamDyn blade gages
INPUTS:
- BD: either:
- a filename of a BeamDyn input file
- an instance of FileCl, as returned by reading the file, BD = weio.read(BD_filename)
OUTPUTS:
- r_gag: The radial positions of the gages,... | ef5d721186319bc3c9800645e7245bae78578cb2 | 3,599,885 |
def multiply(matrix1, matrix2):
"""
Multiply 2 matrices by first filling them up with zeros to become of size
2^n x 2^n matrices and then multiplying them recursively
Complexity (n = matrix rows/cols)
Time complexity: O(n^3)
"""
m1 = matrix1
m1.fillToSquare()
m2 = matrix2
m2.fil... | 5f589d0b8a2bd602a3f9ff0a8376ddfefd6bc1b8 | 3,599,886 |
from typing import Union
from typing import cast
def check_task_existence(
task_type: TaskType, dataset_id: int, target_name: str, **kwargs
) -> Union[int, None]:
"""Checks if any task with exists on test server that matches the meta data.
Parameter
---------
task_type : openml.tasks.TaskType
... | 449f7a422fcc2999d0c550f20faba50fb9775c38 | 3,599,887 |
def clean_data(df):
""" This functions cleans the data by
a. converting categories into columns and their values into binary
b. duplicates removal
Arguments:
df (pandas dataframe): Merged categories and messages dataframe
Returns:
df (pandas dataframe): Cleaned data... | bffe90ea03931f64f28c68d67b27ffda02098387 | 3,599,888 |
def product_detail(request, pk):
"""商品详情"""
prod_obj = get_object_or_404(Product, uid=pk, is_valid=True)
# 用户的默认地址
user = request.user
default_addr = None
if user.is_authenticated:
default_addr = user.default_addr
return render(request, 'product_detail.html', {
'prod_obj': pr... | 1362d36ec100a8b0af7aa5b558a56fe403f9c63b | 3,599,889 |
def dynamic_unroll(cell, inputs, begin_state, drop_inputs=0, drop_outputs=0,
layout='TNC', valid_length=None):
"""Unrolls an RNN cell across time steps.
Currently, 'TNC' is a preferred layout. unroll on the input of this layout
runs much faster.
Parameters
----------
cell : ... | 391a9fa4cb80a90d298f71ca10f5fa5c06461561 | 3,599,890 |
def ldap_auth_login(user):
"""" Authenticate as a test LDAP user and create a new entry in
auth RethinkDB table.
Args:
user:
dict: User table entry for imported LDAP user
Returns:
token:
str: Bearer token upon user's successful authentication
"""
env = E... | 891e8b1c96065f7e74804b2c03264b76ff9444a8 | 3,599,891 |
def BGR2Gray(set_x):
"""
This method takes input in cv2 BGR format and converts it to grayscale
Parameters:
-------------
set_x: is expected to be a 4D tensor of shape (#sampels, #rows, #cols, 3)
or
an image (a 3D tensor) of shape (#rows, #cols, 3)
... | 5bcdc9c6fc99539fe84808de6cf70ca815bf5ba2 | 3,599,892 |
def index_names_from_symbol(symbol):
"""
Return the domain names of a GAMS symbol,
except ['*'] cases are replaced by the name of the symbol
and ['*',..,'*'] cases are replaced with ['index_0',..'index_n']
"""
index_names = list(symbol.domains_as_strings)
if index_names == ["*"]:
return [symbol.name]
... | dc4acc473eaf13d18f553abd722384bf4fe3115a | 3,599,893 |
def _getsortargs(x):
"""Parse sort options into (set, [(key, reverse)], opts)"""
args = getargsdict(x, b'sort', b'set keys topo.firstbranch')
if b'set' not in args:
# i18n: "sort" is a keyword
raise error.ParseError(_(b'sort requires one or two arguments'))
keys = b"rev"
if b'keys' i... | 8f22b3735b786fb6efc0dff107617ac41386f910 | 3,599,894 |
def flights_as_json(flights_qs, limit):
"""
Given a queryset of flights, return it as JSON with the from/to airports
grafted onto it since Django's serializer can't follow relationships.
We also need to call values() on both the airports and flights since
simplejson doesn't understand models.
... | c6ad0673743c190ec7ca37ab58e07791a182ef27 | 3,599,896 |
import numpy
def _get_vil_colour_scheme():
"""Returns colour scheme for VIL (vertically integrated liquid).
:return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`.
:return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`.
"""
colour_list = [
[16, 71, ... | 6547d071fe8a441db78c052684db35e381642804 | 3,599,897 |
def _extract(printer, archives, output_dir):
"""Implementation of the extract function"""
if not output_dir.is_dir():
printer("creating output dir {}...".format(output_dir))
output_dir.mkdir()
printer("reading archives from {}...".format(__file__))
archive_paths = {}
archive_path = N... | ce2ece3f315075ec77f33a0f265042c20daeb9d7 | 3,599,898 |
def softmax_accuracy(logits, ids):
"""Computes accuracy of class logits and ids marginalizing over samples."""
softmax_probs = np.mean(softmax(logits, axis=2), axis=1)
correct = np.argmax(softmax_probs, axis=1) == ids
acc = np.sum(correct) / float(len(ids))
return (acc, softmax_probs) | 2a54e9a5786cacd516bdfae8ab0816d06d870600 | 3,599,899 |
from pathlib import Path
import json
def read_description(filename):
"""Read the description from .zenodo.json file."""
with Path(filename).open() as file:
info = json.load(file)
return info['description'] | 0568aa956f3b0c3f5be4ba75ea8e6b98e08c469e | 3,599,900 |
def select_session(sessions):
"""Select one session out of a list of sessions.
Parameters
----------
sessions : list
list of integers
Returns
-------
None or int
index of the session being chosen
"""
question = QMessageBox(QMessageBox.Question, 'Open Dataset',
... | 24e7f3c3b2233cfe2337419d614d7627bab9eec4 | 3,599,901 |
def timestamp_to_seconds(timestamp):
"""
Convert a timestamp to seconds
"""
parts = timestamp.split(":")
return std_float(
float(parts[0]) * 3600 + float(parts[1]) * 60 + float(parts[2]), 3) | 9469909e9b36d088a00fffb9a1d7ecdfe042adb9 | 3,599,902 |
import re
def parse_xml_file_with_version(_text, nodev=False):
"""parse f"https://pypi.org/rss/project/{package_name}/releases.xml to get list of package releases"""
root = ET.fromstring(_text)
versions = {}
for channel in root:
for item in channel:
version = None
date_... | 2b080358d79e25928f9b8270f6ba222c4f2bd77f | 3,599,903 |
def isLeft(*args):
"""
isLeft(Position2D pA, Position2D pB, Position2D pC, float const & pEps=0.00001) -> int
isLeft(Position2D pA, Position2D pB, Position2D pC) -> int
isLeft(Position3D pDirection, Position3D pA, Position3D pB, Position3D pC, float const & pEps=0.00001) -> int
isLeft(Position3D pDire... | be5c911c9eb80ffbb60f790ea3b2ee7949a283eb | 3,599,904 |
def square(x: ndarray) -> ndarray:
"""
Return the element-wise square of the input.
"""
return x * x | 4df34ce105c0c4dc672228ecf1c0ce0eb1013a80 | 3,599,905 |
def color_text(text, color):
"""
Returns given text string with appropriate color tag. Allowed values
for color parameter are 'red', 'blue', 'green' and 'yellow'.
"""
return '%s%s%s' % (COLORS[color], text, COLORS['nocolor']) | d86a8d053d95c692b8789f221557965f6580a165 | 3,599,906 |
def smallest_qnode_number(df):
"""
Args:
df: input dataframe with columns [column, row, label, kg_id, kg_labels, method, retrieval_score, GT_kg_id, GT_kg_label, evaluation_label]
Returns:
a dataframe with 'smallest_qnode_number' column
"""
res = pd.DataFrame()
for ((col, row), g... | 56bf483b1858500d1c49766d81840f35f1baedf9 | 3,599,909 |
import inspect
def get_plot_commands():
"""
Get a sorted list of all of the plotting commands.
"""
# This works by searching for all functions in this module and removing
# a few hard-coded exclusions, as well as all of the colormap-setting
# functions, and anything marked as private with a pr... | 811f58f1dd08e3c5e10fc1b6a78b67e81df7fe0c | 3,599,913 |
def exec_sedml_docs_in_combine_archive(archive_filename, out_dir, config=None):
""" Execute the SED tasks defined in a COMBINE/OMEX archive and save the outputs
Args:
archive_filename (:obj:`str`): path to COMBINE/OMEX archive
out_dir (:obj:`str`): path to store the outputs of the archive
... | e25197764d0d99c4cc9e153403ec1a83fae3eeb2 | 3,599,914 |
def get_list(isamAppliance, id, trace_id, check_mode=False, force=False):
"""
List trace files for a trace component
"""
return isamAppliance.invoke_get("List trace files for a trace component",
"{0}/{1}/tracing/{2}/trace_files/v1".format(uri, id, trace_id),
... | ce13ef105dcebc67fa4af78e2f16261ab806ba9d | 3,599,916 |
def joukovski_qs_segment(zetaA, zetaB, v_mid, gamma=1.0, fact=0.5):
"""
Joukovski force over vetices A and B produced by the segment A->B.
The factor fact allows to compute directly the contribution over the
vertices A and B (e.g. 0.5) or include DENSITY.
"""
rab = zetaB - zetaA
fs = algebr... | 758e8eac9b2208536427af96abd99981b3828319 | 3,599,917 |
def make_char_array(text, space_token='<space>'):
"""
Make text as char array. Replace spaces with space token.
Args:
text: string.
Given text.
space_token: string.
Text which represents space char.
Returns:
string array.
Split text.
"""
... | 4533398f8e9b865b219214785d3d92171c108a68 | 3,599,918 |
import sqlite3
from typing import Dict
def student_summary() -> str:
""" Query for Student Course Grade """
db_path: str = "G:/Stevens/Courses/Sem4/Assignment/SSW810_Python/StudentRepository_SSW810/input_12/810_startup.db"
try:
db: sqlite3.Connection = sqlite3.connect(db_path)
except sqlite3.... | 7b0d07727a62a9d35f63984c377fe66313204015 | 3,599,919 |
def minimize_donors_and_biosamples(report_df, report_df_index, fields_conversion):
"""
This function generically converts the report tsvs into submittable objects,
at least for biosamples and donors. Empty (NaN) fields are generally not included
in the output objects. However, documents, references, ch... | 8e01245284a68d6b3f66324ebf402f53e93187d6 | 3,599,920 |
def check_collision_agents(agents: list):
"""
:param agents: List of agents with ego_lines property containing 4 points
representing corners of hit box
"""
pair_indexes = get_pair_indexes(len(agents))
collisions = []
for i, j in pair_indexes:
if check_collision(agents[i].ego_line... | be7dab446b49a776b78538524f5aba5fc9d3d7a8 | 3,599,923 |
def fill(courses, dictionary):
"""Fill a DataFrame for all the courses
Args:
courses (list): The list of courses
dictionary (dict): The requirements dictionary
Returns:
DataFrame: The dataframe for the courses
"""
# Add the requirements matching
df = pd.concat([lookup(... | 3fdc61864a124e431d1be781024444df897c1ed3 | 3,599,925 |
def LogNorm():
"""Custom LogNorm.
Returns
-------
ImageNormalize
"""
return ImageNormalize(stretch=LogStretch()) | 204387b101547a9fa816c79399abea52b3a45c86 | 3,599,926 |
def as_block_diag_linear_operator(matrices):
"""Block diag of SciPy sparse matrices or linear operators."""
linear_operators = [as_linear_operator(op) for op in matrices]
nrows = [op.shape[0] for op in linear_operators]
ncols = [op.shape[1] for op in linear_operators]
m, n = sum(nrows), sum(ncols)
... | cfd8d138f8c78f6fad71967009aa5666cb98c4f4 | 3,599,928 |
def cocktail_shaker_sort(list_: list) -> list:
"""Returns a sorted list, by cocktail shaker sort method
:param list_: The list to be sorted
:type list_: list
:rtype: list
:return: Sorted list, by cocktail shaker sort method
"""
higher = len(list_) - 1
lower = 0
Flag = False
wh... | 5a5214100859f95a34fd6f89786f5b93dad426ce | 3,599,929 |
import collections
def summarize_episodes(episodes, new_episodes, num_dropped):
"""Summarizes a set of episode metrics tuples.
Arguments:
episodes: smoothed set of episodes including historical ones
new_episodes: just the new episodes in this iteration
num_dropped: number of workers h... | 7c616b31c2fc4b45642dfd78e566f6e389e73d5d | 3,599,930 |
from bs4 import BeautifulSoup
import requests
import re
def getProductInfo(link):
"""
gets a random item link and looks for item_name,
item_price and item_main_image
returns all three infos as string
"""
req = requests.get(link)
soup = BeautifulSoup(req.text, 'html.parser')
# get im... | b1d1a2fc28db46fbc506865a9c5a470408680ba0 | 3,599,931 |
def downloadCompoundsAjax(user, source_id, ids, output_format):
"""AJAX version of downloadCompounds(). Given a list of compound IDs
(i.e. ChEMBL, PubChem, workbench ID, tags...), download the associated
compound data (i.e. SDF, SMILES)."""
if len(ids) == 0:
raise Exception('Empty list of "ids"... | acda7fb5e002dd7806f44e645cd8bf5b7ee5b714 | 3,599,932 |
def iou(bbox, gt):
"""
:param bbox: (n, 4)
:param gt: (m, 4)
:return: (n, m)
"""
if len(bbox) == 0 or len(gt) == 0:
return np.array(0)
lt = np.maximum(bbox[:, None, :2], gt[:, :2]) # left_top (x, y)
rb = np.minimum(bbox[:, None, 2:], gt[:, 2:]) # right_bottom (x, y)
wh = np... | 51e34aa134c636470593f2de10a17b7ec1bef5ff | 3,599,933 |
from libs.sites.sites import get_curr_img, get_full_doc
from libs.files.files import get_nf
def list_filters(request, cls, filters):
""" если чтото выбрали для фильтров
"""
db = request.db; clss = []
parent_id = db.doc.find_one({'doc_type':'des:ware_class', 'doc.alias':cls})
for doc in db.doc.find({'doc_type':'d... | 9fc7b48e5bd66d9514493fb5e54378fdd12a4f63 | 3,599,934 |
def convert_params_to_image_manifest(params):
"""Converts params to an ImageManifest for ingestion."""
return _convert_dict(
params, {
'id': ('name', convert_asset_id_to_asset_name),
'tilesets': ('tilesets', convert_tilesets_to_one_platform_tilesets)
},
retain_keys=True) | 66fbfb4f6332962e33b1484743782850eb3c142b | 3,599,937 |
def convertBoolean(value: bool):
"""Convert Python bool to JS boolean.
Args:
value (bool): True/False
"""
if value:
jvalue = "true"
else:
jvalue = "false"
return jvalue | d9f3f58eed31f960050df25b5a8ec69fad5f8754 | 3,599,938 |
def get_functions():
"""
Get all current functions
@return: a tuple of (function_name, function_ea)
"""
return {get_function_name(func_ea): func_ea for func_ea in idautils.Functions()} | cce05e571d6f209d5747bf38b9503adbca87198a | 3,599,939 |
from typing import Any
def transform_onehot(input_df: pd.DataFrame, model: Any):
"""
Perform One-hot encoding to the given DataFrame using previously fitted encoder
Previously unseen value, NaN values, and Special value specified under `na_value` in the DataFrame
will be encoded as unseen value.
A... | 9b6705cffbdc5f94c30a3e4c082d57858b442a8a | 3,599,940 |
def LSTM_Prepare(fname):
"""Prepare data for LSTM model
Args:
fname (string): Raw data csv path
Returns:
[tuple]: Train data, Test Data and Data Scaler
"""
# load dataset
dataset = read_csv(fname, header=0, index_col=0)
values = dataset.values
idx = list(dataset.index)
... | 5cb18ee45cdd62a84eafed763d85038b9626c512 | 3,599,941 |
def data_fun(times):
"""Generate time-staggered sinusoids at harmonics of 10Hz"""
global n
n_samp = len(times)
window = np.zeros(n_samp)
start, stop = [int(ii * float(n_samp) / (2 * n_dipoles))
for ii in (2 * n, 2 * n + 1)]
window[start:stop] = 1.
n += 1
data = 25e-9 *... | f6b0e168e734c6751d170e3317055f500d1c46c4 | 3,599,942 |
import copy
def mdlhist(mdlhist, fault='', time=0, fxnflows=[], returnfigs=False, legend=True, timelabel='Time', units=[]):
"""
Plots the states of a model over time given a history.
Parameters
----------
mdlhist : dict
History of states over time. Can be just the scenario states or a dic... | 7e383bb5eca32562a15eabb29bd5fd964314867c | 3,599,943 |
def canny(img, low_threshold, high_threshold):
"""Applies the Canny transform"""
return cv2.Canny(img, low_threshold, high_threshold) | 72c9615628aa96d2aacd91d66331727679f98a3d | 3,599,944 |
import random
def square_img(im: Image.Image) -> Image:
"""
:param im:
:return:
"""
w, h = im.size
if w == h:
return im
crop_shift = random.randrange(abs(h-w)) # crops only in the dimension that is bigger!
if w > h:
# left-upper, right-lower
# box dimension mu... | 442d730db4881db827aaeb3ac5263afdd4f48f2f | 3,599,945 |
def merge(left, right):
"""Merge sort merging function."""
result = []
while left and right:
if left[0] < right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
return result + left + right | c05ae1848d9d7c3b635144b68be269f35408e39b | 3,599,946 |
import torch
def prep_image(img, inp_dim):
"""
Prepare image for inputting to the neural network.
Returns a Variable
"""
orig_im = img
dim = orig_im.shape[1], orig_im.shape[0]
img = (letterbox_image(orig_im, (inp_dim, inp_dim)))
img_ = img[:,:,::-1].transpose((2,0,1)).copy() ... | bdb4803bc237ae4386e824fd8688c28b5cfe112f | 3,599,947 |
import functools
import operator
def get(dic, path, seps=PATH_SEPS, idx_reg=_JSNP_GET_ARRAY_IDX_REG):
"""getter for nested dicts.
:param dic: a dict[-like] object
:param path: Path expression to point object wanted
:param seps: Separator char candidates
:return: A tuple of (result_object, error_m... | 76184ad032dc8109521d6e3ce414bf9634687adc | 3,599,948 |
def make_password(raw_password):
"""
Make a password compatible with metin2 database
if raw_password is none then generate a password
"""
if raw_password is None:
return UNUSABLE_PASSWORD_PREFIX + get_random_string(
UNUSABLE_PASSWORD_SUFFIX_LENGTH
)
mysql_hash = "*"... | c36806eaa43db9928bc1b3272642eb7731a92615 | 3,599,949 |
def top_skills(title: hug.types.text):
"""Get skills by a job title"""
skills = get_top_skills_for_job_title(title)
return {'skills': [
{'name': s.name,
'score': s.score} for s in skills
]} | 3d4b9dbad244940f0c32ccb0dafa183273d0bc74 | 3,599,950 |
def predict_search_extent(obj1_extent, shift, params, grid_size):
""" Predicts search extent/region for the object in image2 given
the image shift. """
shifted_center = obj1_extent['obj_center'] + shift
search_radius_r = params['SEARCH_MARGIN'] / grid_size[1]
search_radius_c = params['SEARCH_MARGIN'... | 588356ce6d4068ef931e34d64deb85b25e58513b | 3,599,951 |
from typing import Union
from typing import List
def _load_splits(
split_infos: Union[type_utils.PathLike, List[split_lib.SplitInfo]],
file_infos: List[naming.FilenameInfo],
builder: dataset_builder.DatasetBuilder,
) -> split_lib.SplitDict:
"""Load the SplitDict which can be passed to DatasetInfo."""
... | 7652ef1a81aedaf540a564b429724f3b25955d0e | 3,599,952 |
def resize_vocoder(data, ratio):
"""
Speeds up a WAV file by phase vocoding its spectrogram
:param data: 1D ndarray of dtype float64 representing the original sample points,
:param ratio: positive float64 representing the duration change
:return: data rescaled according to ratio with the same data t... | fc028e6edfec52d08ebccbae5ffe1bf73939726b | 3,599,955 |
def get_user_for_request(request):
"""
Function checks for an existing session, and creates one if necessary
then checks for existing tutorialUser, and creates one if necessary
returns this tutorialUser
"""
session_key = request.session._get_or_create_session_key()
return _get_or_create_user... | 76bb42285f75a367d6ff03a6cc3625dd141bbd7b | 3,599,956 |
def a_or_an(word):
"""Naively returns "a word" or "an word" depending on the word."""
if len(word) > 0:
if word[0] in 'aeiouAEIOU':
return 'an'
else:
return 'a'
else:
return 'a' | 45f53fbc100511364d56c06b4030055f7671ff3e | 3,599,957 |
def cosh(x):
"""Take cosh of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.cosh", x) | 22949755977a6eb3cbeb9286ab93d15a9b46a1a5 | 3,599,958 |
def execute(isamAppliance, operation='restart', check_mode=False, force=False):
"""
Execute an operation on runtime component
:param isamAppliance:
:param operation:
:return:
"""
check_value, warnings = _check(isamAppliance)
if (force is False):
if warnings == []:
r... | 500988d2c361ff95a78182555e8bcef6a35c23ca | 3,599,959 |
from typing import Set
def top_tipsters(response: Response, top100_limit: int = 50) -> Set[AsianBookieUser]:
"""
Returns a list of top 50 tipsters and top 10 tipsters in leagues
:param top100_limit: a limit for top 100 tipsters
:param response: request response
:return: a list of top tipster
... | c90ce433a6732bbc4970ea9d51de1a7227f38fb0 | 3,599,960 |
import torch
def VAE_loss(X, forward_output):
"""
Loss function of a VAE using mean squared error for reconstruction loss.
This is the criterion for VAE training loop.
:param X: Original input batch.
:param forward_output: Return value of a VAE.forward() call.
Triplet consisting o... | 15c4f4ca6887ed022d31b8df6aa445d77163ed48 | 3,599,961 |
def get_router():
""" returns all routes as nested router in the auth package """
router = APIRouter()
router.include_router(ping.router, prefix='/ping', tags=['Health Check'])
return router | 2347dac05546764ba4700f5704a1fa1369a4f974 | 3,599,964 |
from typing import List
from typing import Tuple
import numpy
def draw_nodes_on_empty_canvas(nodes: List[Node], margin: int = 10) -> Tuple[
numpy.ndarray, Tuple[int, int]]:
"""Draws all the given Nodes onto a zero background.
The size of the canvas adapts to the Nodes, with the given margin.
Also ... | 4c9e652f55943de48632bf1d4570e55229e6c1db | 3,599,965 |
def find_earliest_start(t_goal, deltas):
"""Find the earliest start time with an active range reaching t_goal.
Example
-------
t_goal == 5
delta[t_goal - 1] == 3
We first take a guess...
|√-2|√-1| √ |
<------3
* ... Case 1 (e.g. deltas = [4, 4, 3, 3, 3]): guess DO... | f2716df58b8986a016dd79943b43959554a1786b | 3,599,966 |
def to_numbers(line, dictionary):
"""
Turn a nature language sentence string to a list of numbers.
:param line:
:param dictionary:
:return:
"""
return [dictionary[string] for string in line.split()] | 754cd8e10fda44a53e06a57cabb8f4663548c5e1 | 3,599,967 |
def glm(*args, **kwargs):
"""Create GLM after Patsy model specification string.
Parameters
----------
formula : str
Patsy linear model descriptor.
data : array
Labeled array (e.g. pandas DataFrame, recarray).
priors : dict
Mapping prior name to prior distribution.
... | 74d8d594a9e176af863fff34288a5d12492484ce | 3,599,968 |
import importlib
def get_func(func_name):
"""Helper to return a function object by name. func_name must identify a
function in this module or the path to a function relative to the base
'modeling' module.
"""
if func_name == '':
return None
try:
parts = func_name.split('.')
... | da95b0933ce60cd55049c13ef198eba4d9d0b0ee | 3,599,970 |
import html
import re
import unicodedata
def normalize_text(text):
"""Normalize text"""
if text is None:
return ""
# Convert to lower case
text = text.lower()
# Unescape HTML entities
text = html.unescape(text)
# Remove HTML tags
text = re.sub(r"<[^.]*>", " ", text)
# ... | e14b945496d0a2cc957b067a8701f334885b39f8 | 3,599,971 |
def full_url_resolver(url_name, **kwargs):
"""Add domain and protocol to the to-be-reversed ``url_name``."""
url = sites.get_current_site().domain
if not url.startswith("http"):
url = "https://" + url
if url.endswith("/"):
url = url.rstrip("/")
path = reverse(url_name, kwargs=kwarg... | 04f42258ec9554c0da005dbbabd1e4a599d9414e | 3,599,972 |
def anomaly_correlation(y_true, y_pred, mean=0., regularize_mean='mse', reverse=True):
"""
Calculate the anomaly correlation. FOR NOW, ASSUMES THAT THE CLIMATOLOGICAL MEAN IS 0, AND THEREFORE REQUIRES DATA
TO BE SCALED TO REMOVE SPATIALLY-DEPENDENT MEAN.
:param y_true: Tensor: target values
:param ... | a5e75285126b98bd96f8e6b6062706b12a7eeba3 | 3,599,973 |
def data_attribute(
types=(),
subtypes=False,
checked=None,
module=None,
factory=None,
serialized=True,
serializer=None,
deserializer=None,
represented=True,
compared=True,
default=MISSING,
default_factory=None,
required=True,
changeable=True,
deletable=False,... | a9785cc50f82a2997264e8b89b8d99577ddf0eb8 | 3,599,974 |
import re
import regex
def transliterate_pick_best(characters):
"""
transliterate_pick_best: Picks the best choice for transliteration from tags created from kytea
- Returns the original if it isn't in kanji to begin with, because the hiragana
- ... | 5040848042ef12692eea4bb504aeea6e62bbbb07 | 3,599,975 |
def prep_dataset(config):
"""
Expand dataset configuration to match split length
Parameters
----------
config : CfgNode
Dataset configuration
Returns
-------
config : CfgNode
Updated dataset configuration
"""
# If there is no dataset, do nothing
if len(confi... | 673c8fb722a52af1640c20d426b7eb50b6056783 | 3,599,977 |
def cica_const_ratio(ambient_co2, const):
"""ci/ca is constant."""
"""Return ci = intercellular CO2 concentration, kg/m^3."""
return const * ambient_co2 | 418f5172def68cede271767943a3af5817ccfe62 | 3,599,978 |
def MTFfreq(MTFpos, MTF, modulation=0.2):
""" Return the frequency for the requested modulation height. """
mtf_freq = 0
for f in range(len(MTFpos)):
if MTF[f] < modulation:
if f > 0:
# Linear interpolation:
x0 = MTFpos[f-1]
x1 = MTFpos[f]... | fadec075afaffa405ef4135f714be6e2bceb71c7 | 3,599,979 |
from hashlib import algorithms
from hashlib import algorithms_available as algorithms
def get_algorithms():
"""Returns an organized list of this machine's hashing algorithms
(Ideally organized by strength, but I am not a cryptography expert)
"""
try:
except ImportError:
sorted_algs = [
... | 970662c51c0c59947eac72966c78704dfbe27437 | 3,599,980 |
def get_checkpoint(device):
"""Get a local base checkpoint file to work with.
No file is saved on remote device.
"""
filename = 'temp_cp_file_from_pycsco'
set_checkpoint(device, filename)
cp_out_dict = xmltodict.parse(device.show(
'show file {0}'.format(
filename), text=Tr... | 5f2b970a9826291fcb1ad0391c3bf0b6833a1d6b | 3,599,981 |
from .image.image import _smooth_array
def _apply_mask_fmri(imgs, mask_img, dtype='f',
smoothing_fwhm=None, ensure_finite=True):
"""Same as apply_mask().
The only difference with apply_mask is that some costly checks on mask_img
are not performed: mask_img is assumed to contain only ... | 17e08efa7bab24f61c1f159c2b08d75bf5605147 | 3,599,982 |
from typing import Callable
from typing import List
def list_cabins(
park_filter: Callable[[Park], bool] = lambda p: True,
cabin_filter: Callable[[Cabin], bool] = lambda c: True,
) -> List[Cabin]:
"""List cabins matching criteria.
Parameters
----------
park_filter:
A callback function... | 5adea2892f83b702ebabed9e74d25cfdd49638cd | 3,599,983 |
import time
def vote_on_assay(request, conflict_id, assay_id):
"""
Commit changes specified in html form to database and return the next
conflict view, or start page, if n/a.
"""
if not request.user.is_authenticated():
return render_to_response('pfam_maps/user_portal.html',context_instance... | c5ee8fbf4d09d7997ff87e9f08b3c5cb6da61f4e | 3,599,984 |
def parse_token_or_quoted_string(s, start=0, allow_quoted=True, allow_token=True):
"""Parses a token or a quoted-string.
's' is the string to parse, while start is the position within the
string where parsing should begin. It will returns a tuple
(token, chars_consumed), with all \-escapes and quotati... | 2ffd54e4ebd1125134874ba4350005ee9b3fb08c | 3,599,986 |
from typing import Union
from typing import List
from typing import SupportsFloat
def parade(p: dict, x: Union[List[SupportsFloat], None], y: Union[SupportsFloat, None], rho=0.01):
"""
A 'parade' holds previous predictions and truths, and can be used to determine a running
estimate of the empi... | 6b6c38a6a016740212698668d8a7610bfb4adada | 3,599,987 |
def group_objects(objects):
"""
Group objects as Nodes
:param objects: list(str)
:return: dict
"""
results = dict()
for name in objects:
node = Node(name)
results.setdefault(node.namespace(), list())
results[node.namespace()].append(name)
return results | d6a67a3679de252f7b8893771f6fa136a1d10045 | 3,599,988 |
def make_kvs_two(A, B):
"""
compute the Kronecer-Vector stack of the matrices A and B
"""
shape = tf.stack([tf.shape(A)[0], tf.shape(A)[1] * tf.shape(B)[1]])
return tf.reshape(tf.matmul(tf.expand_dims(A, 2), tf.expand_dims(B, 1)), shape) | efaccd791adb8cdf91652321f4a2784a47051424 | 3,599,989 |
def yolo3_decode(predictions, anchors, num_classes, input_dims, elim_grid_sense=False):
"""
YOLOv3 Head to process predictions from YOLOv3 models
:param num_classes: Total number of classes
:param anchors: YOLO style anchor list for bounding box assignment
:param input_dims: Input dimensions of the... | cce34e56369e1864084fcc448e9766b40d4a9f0d | 3,599,990 |
def eluniversocom_story(soup):
"""
Function to pull the information we want from Eluniverso.com stories
:param soup: BeautifulSoup object, ready to parse
"""
hold_dict = {}
#text
try:
article_body = soup.find('div', attrs={"id": "content", "class": "column"})
body = article_b... | db4cddcb1bf014e117fc7c51553410814a19ba8f | 3,599,991 |
import codecs
def countsyll(instring):
"""This function counts the number of characters in a tamil string
This is done by ignoring the vowel additions. If one uses the len
function, the sample string has a length of 17 - but there are actually
only 11 characters"""
s = codecs.utf_8_enc... | 3340eb844014c2c53661f9ea278dd38eff8e8a33 | 3,599,992 |
def aggregate_confidence_colwise(aggregate, significance=0.05):
"""Calculate the colwise confidence of a ResponseAggregate."""
confidence = []
n_likert = 4 # agree or disagree with experts
B = stats.chi2.ppf(1 - significance / n_likert, 2)
for col in aggregate:
n = sum(col)
n_total ... | eec6d514950b097e380e39549029bc5cb67d2caa | 3,599,993 |
from typing import Tuple
from typing import Dict
import array
def _eq_nodes_setup_node(model: BDF, renumber_nodes: bool=False,
) -> Tuple[NDArrayNint, NDArrayNint, Dict[int, int]]:
"""helper function for ``_eq_nodes_setup``"""
inode = 0
nid_map = {}
if renumber_nodes:
... | 01ec449a2380d5ab9acbd33bf9f448361dd0f6f2 | 3,599,994 |
async def get_one_sample(dataset_id, sample_id, db_session: Session = Depends(get_db)):
"""Get a single sample"""
db_sample = (
db_session.query(sample.Sample)
.filter_by(sample_id=sample_id, dataset_id=dataset_id)
.first()
)
if db_sample is None:
raise HTTPException(
... | fe66e76a5797b8a131a8b308611f46399cb402a8 | 3,599,995 |
def infer_relationship(coeff: float, ibs0: float, ibs2: float) -> str:
"""
Inferres relashionship labels based on the kin coefficient
and ibs0 and ibs2 values.
"""
result = 'ambiguous'
if coeff < 0.1:
result = 'unrelated'
elif 0.1 <= coeff < 0.38:
result = 'below_first_degree... | c24ab30a4a9d06ef552abe728f78d8081f40e87f | 3,599,996 |
def allStudentsMajoringIn(thisMajor,listOfStudents):
"""
return a list of the students with the major, thisMajor
>>> majorToLNames("MATH",[Student("MARY","KAY","MATH"), Student("FRED","CRUZ","HISTORY"), Student("CHRIS","GAUCHO","UNDEC")])
[Student(fName='MARY',lName='KAY',major="MATH")]
>>>
""... | ad32dfd68b2daa4aa3e46ff8563e4575bd940336 | 3,599,999 |
def lemmatize(docs, docs_meta, language=None, lemmatizer_fn=None):
"""
Lemmatize documents according to `language` or use a custom lemmatizer function `lemmatizer_fn`.
:param docs: list of tokenized documents
:param docs_meta: list of meta data for each document in `docs` or list of POS tags per docume... | 1bcf3b8ad5c5ce1a840d60c211300d8dadccd7fb | 3,600,000 |
def float_to_string(f):
""" this prints a number with a certain number of digits after the point,
while removing trailing zeros.
"""
num_digits = 6 # we want to print 6 digits after the zero
g = f
while abs(g) > 1.0:
g *= 0.1
num_digits += 1
format_str = '%.{0}g'.format(num_... | 41ad07eb610044ae54a201ebc77c20e2b647da3a | 3,600,001 |
def edr3_propermotion_to_ICRF(pmra, pmdec, ra, dec, G):
"""
Cantat-Gaudin & Brandt 2021 correction of EDR3 to ICRF proper motions.
This applies only to bright sources (G<13). Correction is of order ~0.1
mas/yr, depending on the source brightness and on-sky location.
Input: source position, coordin... | 970901bd29cfb6f7912f89e3265db816040ea9ad | 3,600,002 |
def AP_BICC(G, k, K, l):
"""an efficient algorithm for structural hole spanners detection.
Returns top k nodes as structural hole spanners,
Algorithm 3 of [1]_
Parameters
----------
G : easygraph.Graph
An unweighted and undirected graph.
k : int
top - k structural hole spa... | 81bbabdc3e643327acbd29d797841db3c3d670f5 | 3,600,003 |
def connect_rps(cur_RP, wire_RPs, via_wire = False, wire_via = False, mid_RP = None):
"""
Desc:
* Having a routing point found between two routing points
break the old connection and add the new routing point as a steiner node
* If the connection is a via to a wire:
- The V... | b56ddd632fd4001a533fefbfde9eb42e43e74cdb | 3,600,004 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.