content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 vsan_enable(
host, username, password, protocol=None, port=None, host_names=None, verify_ssl=True
):
"""
Enable VSAN for a given host or list of host_names.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
T... | 21bcd4d639d411d85f1d622aca81244be9cb3f0e | 3,599,907 |
import logging
def project_engine(project, default=False) -> ("Engine", sessionmaker):
"""Creates and register a SQLAlchemy engine for a Meltano project instance."""
existing_engine = _engines.get(project)
if existing_engine:
return existing_engine
settings = ProjectSettingsService(project)
... | e9c7e6d33c079674709187c0439bb4a8ed63cabe | 3,599,908 |
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 argparse
def parsing():
"""
Parse arguments
"""
descr = "Superimpose all .pdb conformations onto the provided template"
descr_pdbDir = "Directory containing conformation ensemble"
descr_templatePath = "Template onto which superimpose the conformation " \
"ensemble"
parser =... | 45e96831e82adf04fd974631a303418db42fc09a | 3,599,910 |
from typing import Tuple
import logging
def hash_genomes(
args: Namespace, dlstatus: download.DLStatus, filestem: str, uid_class
) -> Tuple[str, str]:
"""Hash genome files in passed dlstatus.
:param args: Namespace of command-line arguments
:param dlstatus:
:param filestem: str, filestem for ou... | aa0afb125b2fdd4b5d712231954f632394426a8d | 3,599,911 |
import zipfile
import os
def zip_file(dir, filename):
"""
Add the contents of dir to zipfile.
:param dir: str
:param filename: str (the name of the zip file)
:return: None
"""
zp = zipfile.ZipFile(filename, "w")
for i in os.walk(dir, followlinks=True):
for fp in i[2]:
... | 23fa15682bd1e0917830139ef0848fddee36dbd0 | 3,599,912 |
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 print_tensor_process_values(trigger_tensor, tensor_list, tensor_name_list):
"""
Prints all listed tensor shapes and values with the listed names, every time the trigger_tensor is executed. This
printed information gives insight in the model during usages, training or testing. This insight can be used fo... | ee3cc7e07b85a303275fecd787e308973ff2a96c | 3,599,915 |
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 make_state():
"""For debugging purposes"""
return s.State(f.own_team, f.opponent_team, f.own_mon_out,
f.opponent_mon_out, True, True) | 6343d475ad56c817b7cf8eef6d0fc5188d8dc5a2 | 3,599,921 |
from typing import Counter
import logging
def generate_molecule_ZMW_map( mols, chunk_id ):
"""
Map zmw_id <--> mol_id. This will also remove any double-loaded molecules.
"""
zmw_mol_map = {}
zmw_mol_counts = Counter()
for mol in mols.values():
zmw_mol_map[mol.mol_id] = mol.zmw_id
zmw_mol_counts[mol.zmw_id... | d86b437dcf698799cfdabe6d795a3a4c1b1c979d | 3,599,922 |
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 |
import os
def read_link(link_file):
"""
Reads the properties of a Shell Link File (``.lnk``).
Args:
link_file (str): The path of the ``.lnk`` file.
Returns:
dict: A dict containing the properties:
::
{'target': "The resolved target file; path is already expanded",... | ef3109b28f6d02e91a85bb5cea804a8654452c9f | 3,599,924 |
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 |
import os
import json
import textwrap
import sys
def GetCredentialFromStore(desired_scopes,
ask_user=True,
force_reauth=False,
credentials_file=None,
authorization_uri_base=None,
clie... | edab6724af79dad89d37149a65ab39c74b44ceef | 3,599,927 |
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 load_zicontrol_zibin(filename, column_names=ZICONTROL_NAMES):
"""
Load a ziBin file containing demodulator samples as saved by the ziControl
User Interface into a numpy structured array. This is for data saved by
ziControl in binary format.
Arguments:
filename (str): The filename of the ... | 7bb827ac7a38fbd3c044c23bd85b8e3d778b90d4 | 3,599,935 |
import os
def GetEnvInt(variable):
"""Returns the environment variable value as an integer."""
return int(os.getenv(variable) or 0) | dc87a87318efe816fdb1f0a96b4e14ea226d7a5d | 3,599,936 |
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 |
import os
def get_default_terminal(environ=None, fallback=_UNSPECIFIED):
"""Get the user's default terminal program."""
if environ is None:
environ = os.environ
# If the option is specified in the environment, respect it.
if "PIAS_OPT_TERMINAL" in environ:
return environ["PIAS_OPT_TERM... | 02e8c01ae98c5b07bb66e1c56b9c1d9cb4c17bbd | 3,599,953 |
import os
def load_text(data_path, text):
"""
Load the non-imaging information from data downloaded.
The official file Phenotypic_V1_0b_preprocessed1.csv contains some redundant information.
:param data_path: path of the downloaded data.
:return: non-imaging information for all the samples downloa... | b9c9050a02f3a108fdeb1dbe04ffd12d1a114210 | 3,599,954 |
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 |
import torch
import os
def init_model(net, restore):
"""Init models with cuda and weights."""
# init weights of model
# net.apply(init_weights)
# restore model weights
if restore is not None:
net.load_state_dict(torch.load(restore))
net.restored = True
print("Restore model... | 5e58286fd72dac8b2fc66cc437e1d4f5d714734d | 3,599,962 |
from math import gcd
import torch
import os
def create_nerf(args, autodecoder_variables=None, ignore_optimizer=False):
"""Instantiate NeRF's MLP model."""
grad_vars = []
if autodecoder_variables is not None:
grad_vars += autodecoder_variables
embed_fn, input_ch = get_embedder(args.multires,... | 1dc64c9cfad4413f980233d749ef0e949ded7059 | 3,599,963 |
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 os
def main(argv):
"""This is the main function."""
if len(argv) >= 1:
dir = argv[0]
else:
dir = '.'
file = open(os.path.join(dir, 'gles2_conform_test_autogen.cc'), 'wb')
GenerateTests(file)
file.close()
return 0 | 49b006bec43283f541a6ff683ecb964105d52adb | 3,599,969 |
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 |
import os
def _add_travis_info(capabilities):
"""
"""
capabilities['tunnel-identifier'] = os.getenv('TRAVIS_JOB_NUMBER')
capabilities['build'] = os.getenv('TRAVIS_BUILD_NUMBER')
capabilities['tags'] = [os.getenv('TRAVIS_PYTHON_VERSION'), 'CI']
return capabilities | c47d4c6f4524b7e1e6c01c0b5186ef1f4dd5fb88 | 3,599,976 |
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 |
from typing import Any
from pathlib import Path
import os
def test_make_docs_rm_cache(
main: Any, monkeypatch: Any, call_status: Any, make_tree: Any
) -> None:
"""Test ``make_docs`` removes all builds before starting a new one.
:param main: Patch package entry point.
:param monkeypatch: ... | 12ddab37ab2c19782b1886a37b21726691edc7e5 | 3,599,985 |
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 |
import json
def get_v1_sessiontemplates(): # noqa: E501
"""
GET /v1/sessiontemplates
List all sessiontemplates
"""
LOGGER.debug("get_v1_sessiontemplates: Fetching sessions.")
with BosEtcdClient() as bec:
results = []
for st, _meta in bec.get_prefix('{}/'.format(BASEKEY)):
... | 803d360419929c53af6c1c1cc3d9cfd09481429c | 3,599,997 |
import os
from pathlib import Path
import pickle
def gather_nse_metrics(run_dir: str, exp_name: str) -> pd.DataFrame:
"""Gathers NSE metrics for all runs that are related to a certain experiment.
Parameters
----------
run_dir: str
Parent directory that contains several run directories
exp... | d750814d270a4cfe7079e970c7f13419016843a5 | 3,599,998 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.