content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import numpy
def undiskify(z):
"""Maps SL(2)/U(1) poincare disk coord to Lie algebra generator-factor."""
# Conventions match (2.13) in https://arxiv.org/abs/1909.10969
return 2* numpy.arctanh(abs(z)) * numpy.exp(1j * numpy.angle(z)) | 9ac4cd521ca64decd082a34e35e0d080d3190e13 | 20,000 |
def mean_vertex_normals(vertex_count,
faces,
face_normals,
**kwargs):
"""
Find vertex normals from the mean of the faces that contain
that vertex.
Parameters
-----------
vertex_count : int
The number of vertices faces... | 767214b5c2ba701de5288009ee4ebfb90378446c | 20,001 |
def get_beam_jobs():
"""Returns the list of all registered Apache Beam jobs.
Returns:
list(BeamJob). The list of registered Apache Beam jobs.
"""
return [beam_job_domain.BeamJob(j) for j in jobs_registry.get_all_jobs()] | 24e22d487fdbdb02917011e94a6d5b985de67640 | 20,002 |
def z_norm(dataset, max_seq_len=50):
"""Normalize data in the dataset."""
processed = {}
text = dataset['text'][:, :max_seq_len, :]
vision = dataset['vision'][:, :max_seq_len, :]
audio = dataset['audio'][:, :max_seq_len, :]
for ind in range(dataset["text"].shape[0]):
vision[ind] = np.nan... | 8cf40069b2a8c042d357fab3b1e3aaf13c15c69e | 20,003 |
def days_upto(year):
"""
Return the number of days from the beginning of the test period to the
beginning of the year specified
"""
return sum([days_in_year(y) for y in range(2000,year)]) | f87295a53d839e2ce895ef5fe5490b77377d28eb | 20,004 |
def read_DEM(fn=None, fjord=None):
"""
Reads in the DEM (only accepts GeoTiffs right now) into an XArray Dataarray with the desired format.
"""
# intake.open_rasterio accepts a list of input files and may effectively do what this function does!
# try using cropped versions of the input files. Doesn'... | 23abd9bfe9a9c498bee43138245e3b38107eef6c | 20,005 |
def choose_field_size():
"""a function that crafts a field"""
while True:
print('Пожалуйста, задайте размер поля (число от 3 до 5):')
try:
field_size = int(input())
except ValueError:
continue
if field_size == 3:
print('\nПоле для игры:\n')
... | ed370aca1f13a9f93bb96e483885c67e1bd30317 | 20,006 |
def delete_submission_change(id):
"""Delete a post.
Ensures that the post exists and that the logged in user is the
author of the post.
"""
db = get_db()
db.execute('DELETE FROM submission_change WHERE id = ?', (id,))
db.commit()
return jsonify(status='ok') | a886dfd89939ca10d95877bd16bda313ccb9353d | 20,007 |
from datetime import datetime
def get_search_response(db, search_term):
"""Method to get search result from db or google api.
Args:
db: The database object.
search_term: The search term.
Returns:
String: List of relevant links separated by line break.
"""
# Find if the s... | 11180ad1ee57d2a778439fd260d5201d3723cfe7 | 20,008 |
def lattice_2d_rescale_wave_profile(kfit, X, dT, Z_C, Y_C, v, dx=1.):
"""
Fit the wave profile (X, dT) to the ODE solution (X_C, dT_C)
"""
# recenter the profile around 0
k0 = np.argmax(dT)
x0 = X[k0]
Z = kfit*(X.copy()-x0)
# retain a window corresponding to the input ODE solution
z... | 8caea59a092efd9632e4b705400f40aa0ebbec44 | 20,009 |
def extent_switch_ijk_kji(
extent_in: npt.NDArray[np.int_]) -> npt.NDArray[np.int_]: # reverse order of elements in extent
"""Returns equivalent grid extent switched either way between simulator and python protocols."""
dims = extent_in.size
result = np.zeros(dims, dtype = 'int')
for d in range... | c960591fa1f3b31bd0877fd75845a17fff8eff50 | 20,010 |
def create_data(f, x_vals):
"""Assumes f is a function of one argument
x_vals is an array of suitable arguments for f
Returns array containing results of applying f to the
elements of x_vals"""
y_vals = []
for i in x_vals:
y_vals.append(f(x_vals[i]))
return ... | 5f74402586c3f7d02c8d6146d5256dbccdf49e81 | 20,011 |
def register():
"""注册"""
req_dict = request.get_json()
phone = req_dict.get("phone")
password = req_dict.get("password")
password2 = req_dict.get("password2")
sms_code = req_dict.get("sms_code")
phone = str(phone)
sms_code = str(sms_code)
# 校验参数
if not all([phone, password, pass... | f9e6bc8dc30cb967843d0f47fada1b4b62c6b130 | 20,012 |
def cpp_flag(compiler):
"""Return the -std=c++[11/14/17] compiler flag.
The newer version is prefered over c++11 (when it is available).
"""
flags = ["-std=c++17", "-std=c++14", "-std=c++11"]
for flag in flags:
if has_flag(compiler, flag):
return flag
raise RuntimeError(
... | a21a0a8efcad62cc26ff033877c366d7d6acf09d | 20,013 |
def to_null(string):
"""
Usage::
{{ string|to_null}}
"""
return 'null' if string is None else string | 1868ca2c7474a8134f2dbb0b0e542ca659bf4940 | 20,014 |
import warnings
def get_mtime(path, mustExist=True):
"""
Get mtime of a path, even if it is inside a zipfile
"""
warnings.warn("Don't use this function", DeprecationWarning)
try:
return zipio.getmtime(path)
except IOError:
if not mustExist:
return -1
raise | 6c661fb5d7a874a8173ec509b07401e2120da95b | 20,015 |
def get_table_8():
"""表 8 主たる居室の照明区画݅に設置された照明設備の調光による補正係数
Args:
Returns:
list: 表 8 主たる居室の照明区画݅に設置された照明設備の調光による補正係数
"""
table_8 = [
(0.9, 1.0),
(0.9, 1.0),
(1.0, 1.0)
]
return table_8 | 89470f0242982755104dbb2afe0198e2f5afa5f4 | 20,016 |
import requests
import warnings
def query_epmc(query):
"""
Parameters
----------
query :
Returns
-------
"""
url = "https://www.ebi.ac.uk/europepmc/webservices/rest/search?query="
page_term = "&pageSize=999" ## Usual limit is 25
request_url = url + query + page_term
r =... | a8da1ee3253d51738f1d556548f6bccf17b32b53 | 20,017 |
def is_default_array_type(f, type_map=TYPE_MAP):
"""
Check whether the field is an array and is made up of default types, e.g. u8 or s16.
"""
return f.type_id == 'array' and type_map.get(f.options['fill'].value, None) | ec0e7a26261cc72e473d2c365bc452b2eeab396f | 20,018 |
def delete_police_station_collection():
"""
Helper function to delete station collection in db.
"""
result = PoliceStation.objects().delete()
return result | 7b3cc89269695fa494eb12a7b904fabd1974f3d8 | 20,019 |
def compute_asvspoof_tDCF(
asv_target_scores,
asv_nontarget_scores,
asv_spoof_scores,
cm_bonafide_scores,
cm_spoof_scores,
cost_model,
):
"""
Compute t-DCF curve as in ASVSpoof2019 competition:
Fix ASV threshold to EER point and compute t-DCF curve over thresholds in CM.
... | 27819737d7a1a84db10d78cce4c5edd16548e774 | 20,020 |
def all_divisor(n, includeN=True):
"""
>>> all_divisor(28)
[1, 2, 4, 7, 14, 28]
>>> all_divisor(28, includeN=False)
[1, 2, 4, 7, 14]
Derived from https://qiita.com/LorseKudos/items/9eb560494862c8b4eb56
"""
lower_divisors, upper_divisors = [], []
i = 1
while i * i <= n:
i... | 2fa0eb58eac30030cfbbfdcce62bc91cb36f218e | 20,021 |
def isTrue(value, noneIsFalse=True):
"""
Returns True if <value> is one of the valid string representations for True.
By default, None is considered False.
"""
if not value:
if noneIsFalse:
return False
else:
return None
else:
return value.lower() in TRUE_STRINGS | 16e69dc43ef2034d210803e8cc3ebf2ae13e13b2 | 20,022 |
import pickle
def read_doc_labels(input_dir):
"""
:param input_dir:
:return: doc labels
"""
with open(input_dir + "doc_labels.pkl", 'rb') as fin:
labels = pickle.load(fin)
return labels | c0246f8e09441782a7437177877cc1e4d83ecb40 | 20,023 |
import os
def which(bin_dir, program):
"""
rough equivalent of the 'which' command to find external programs
(current script path is tested first, then PATH envvar)
"""
def is_executable(fpath):
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(pro... | 4c7ecc9e43574d95591b4de5df92c5693eda70a3 | 20,024 |
def search(catalog_number):
"""
A top level `catalog_number` search that returns a list of result dicts.
Usually catalog numbers are unique but not always hence the returned list.
"""
results = query(catalog_number)
result_list = []
for result in results:
dict_result = vars(result)["... | 2a8ce325250cbaa5a9f307ef707c74c5101d84d3 | 20,025 |
import requests
import urllib
from io import StringIO
def fetch_csv_for_date(dt, session=None):
"""
Fetches the whole month of the give datetime
returns the data as a DataFrame
throws an exception data is not available
"""
if not session:
session = requests.session()
# bui... | 6e65a9941390beb826eace939d03af4427133029 | 20,026 |
def calculate_mean_probas(time_ser, model):
"""Calculate the metric to evaluate based on average probabilities
Args:
time_ser (np.ndarray): dynophore time series
model (HMM): Fitted HMM
Returns:
np.float: Probability of prediting the given time series based on the fitted model
... | b8320a24c01e56c89b5d706630190a118d803ffa | 20,027 |
def compute_t(i, automata_list, target_events):
"""
Compute alphabet needed for processing L{automata_list}[i-1] in the
sequential abstraction procedure.
@param i: Number of the automaton in the L{automata_list}
@type i: C{int} in range(1, len(automata_list)+1)
@param automata_list: List of a... | 88fc64aaf917d23a29e9400cf29705e6b20665c3 | 20,028 |
def cal_min_sim(y):
"""Calculate the minimal value given multiple trajectories from different isomers"""
y = y.copy()
if len(y.shape) == 2: # add one more dimension if only two provided
y = y[np.newaxis, :]
n_sim, nT, nP = y.shape
y_min_sim = np.min(y, axis = 0)
return y_min_... | efbee1f3d8a88ac447609019a431d3ac6469f2cf | 20,029 |
async def create_rsa_key(
hub,
ctx,
name,
vault_url,
key_ops=None,
enabled=None,
expires_on=None,
not_before=None,
tags=None,
**kwargs,
):
"""
.. versionadded:: 2.0.0
Create a new RSA key or, if name is already in use, create a new version of the key. Requires the ke... | f22a520bc82bed0447440a80639a1f6ef575e718 | 20,030 |
import re
def _parse_size_string(size):
"""
Parse a capacity string.
Takes a string representing a capacity and returns the size in bytes, as an
integer. Accepts strings such as "5", "5B", "5g", "5GB", " 5 GiB ", etc.
Case insensitive. See `man virsh` for more details.
:param size: The size... | 6ad10ba10380eaa7a8acd6bbeb52b537fdcf3864 | 20,031 |
import os
def connect(cfg=None, jar=None):
""" Connect to MF using a token with authority to access the data collection
:return: A new :py:class:`Session`
Example::
>>> from MFQuery.MF import MF
>>> cfg = "$HOME/aterm.cfg"
>>> jar = "$HOME/aterm.jar"
>>> wath = MF.connect(cfg,jar) # d... | f05e959ca7cf9c83d1d8e81eebadf9e8c6244774 | 20,032 |
def get_exp_lr(base_lr, xs, power=4e-10):
"""Get learning rates for each step."""
ys = []
for x in xs:
ys.append(base_lr / np.exp(power*x**2))
return ys | 58486de08742d2467a4178d1ac0544c0d1f2055c | 20,033 |
import time
def dashboard():
""" Main dashboard function. Run stats across all accounts. """
start = time.time()
instance_count = 0
user_count = 0
sg_count = 0
elb_count = 0
aws_accounts = AwsAccounts()
accounts = aws_accounts.all()
pool = Pool(10)
results = pool.map(get_acco... | e5138d8527ecb5712db6205757432d31efde8f2b | 20,034 |
def strip_new_line(str_json):
"""
Strip \n new line
:param str_json: string
:return: string
"""
str_json = str_json.replace('\n', '') # kill new line breaks caused by triple quoted raw strings
return str_json | f2faaa80dca000586a32a37cdf3dff793c0a2d9b | 20,035 |
def fromAtoB(x1, y1, x2, y2, color='k', connectionstyle="arc3,rad=-0.4",
shrinkA=10, shrinkB=10, arrowstyle="fancy", ax=None):
"""
Draws an arrow from point A=(x1,y1) to point B=(x2,y2) on the (optional)
axis ``ax``.
.. note::
See matplotlib documentation.
"""
if ax is No... | a7b14ae62d26f203da0fb3f26c7aa7652fb9a345 | 20,036 |
import torch
def exp(input_):
"""Wrapper of `torch.exp`.
Parameters
----------
input_ : DTensor
Input dense tensor.
"""
return torch.exp(input_._data) | 01449c87486a7145b26d313de7254cb784d94a7b | 20,037 |
import torch
def capsule_sdf(mesh_verts, mesh_normals, query_points, query_normals, caps_rad, caps_top, caps_bot, foreach_on_mesh):
"""
Find the SDF of query points to mesh verts
Capsule SDF formulation from https://iquilezles.org/www/articles/distfunctions/distfunctions.htm
:param mesh_verts: (batch... | f34a734496738464ba601caab8985efc59809e54 | 20,038 |
from datetime import datetime
def get_lat_lon(fp, fs=FS):
"""
get lat lon values for concat dataset
"""
logger.info(f"{str(datetime.datetime.now())} : Retrieving lat lon")
with xr.open_dataset(fs.open(fp)) as ds:
lat, lon = ds["latitude"].values, ds["longitude"].values
logger.info(f"{s... | a99614463121edb99c290ddea8d6bb7b298498f1 | 20,039 |
def one_hot_encode(vec, vals=10):
"""
For use to one-hot encode the 10- possible labels
"""
n = len(vec)
out = np.zeros((n, vals))
out[range(n), vec] = 1
return out | 079c4c505464659248631b3e5c3d1345557d922b | 20,040 |
def COUNTA(*args) -> Function:
"""
Returns a count of the number of values in a dataset.
Learn more: https//support.google.com/docs/answer/3093991
"""
return Function("COUNTA", args) | c8e876e80a0414eab915b6eb0efc9917b12edb19 | 20,041 |
import json
def decode_url_json_string(json_string):
"""
Load a string representing serialised json into
:param json_string:
:return:
"""
strings = json.loads(h.unescape(json_string),
object_pairs_hook=parse_json_pairs)
return strings | 6f616e5e6037024ebdab6e63aa90c13c60fca40c | 20,042 |
import argparse
def init_argparser():
"""
Define and parse commandline arguments.
"""
# training settings
parser = argparse.ArgumentParser(description="PyTorch MNIST Example")
parser.add_argument("--experiment", type=str, help="Choose the experiment.")
parser.add_argument(
"--batch... | 1d435b4d2b714e94c5d4c1fc575ee93db98d93e4 | 20,043 |
def svn_wc_merge2(*args):
"""
svn_wc_merge2(enum svn_wc_merge_outcome_t merge_outcome, char left,
char right, char merge_target, svn_wc_adm_access_t adm_access,
char left_label, char right_label,
char target_label, svn_boolean_t dry_run,
char diff3_cmd, apr_array_header_t merge... | 271e596810b7ee604532f34612e349ae30b108c5 | 20,044 |
import torch
def test_finetuning_callback_warning(tmpdir):
"""Test finetuning callbacks works as expected."""
seed_everything(42)
class FinetuningBoringModel(BoringModel):
def __init__(self):
super().__init__()
self.backbone = nn.Linear(32, 2, bias=False)
self... | c7bec2c256ece471b0f3d9f56a74dcb2c7ad186a | 20,045 |
from contextlib import suppress
def idempotent(function):
"""Shallows 304 errors, making actions repeatable."""
@wraps(function)
def decorator(*args, **kwargs):
with suppress(GitlabCreateError):
return function(*args, **kwargs)
return decorator | 4012ce715a8344a7a9eb7e27a7d96f0e3b9c8f6d | 20,046 |
def newline_formatter(func):
"""
Wrap a formatter function so a newline is appended if needed to the output
"""
def __wrapped_func(*args, **kwargs):
"""
Wrapper function that appends a newline to result of original function
"""
result = func(*args, **kwargs)
# Th... | 71af6af25aa93e0e8f80958b5caf5266f598c878 | 20,047 |
from typing import List
from typing import Tuple
def sigma_splitter(float_arr: List[float]) -> Tuple[List[List[int]], List[List[int]], List[List[int]]]:
"""
separates the NCOF score into the 1-3 sigma outliers for the NCOF input
@param float_arr: List[float]
@return: inliers , pos_outliers , neg_outli... | 824c3d11ffa1fb81763cdf815de3e37a7b8aa335 | 20,048 |
import torch
def cosine_beta_schedule(timesteps, s = 0.008, thres = 0.999):
"""
cosine schedule
as proposed in https://openreview.net/forum?id=-NEXDKk8gZ
"""
steps = timesteps + 1
x = torch.linspace(0, timesteps, steps, dtype = torch.float64)
alphas_cumprod = torch.cos(((x / timesteps) + s... | a1969deafdb282955a53b15978a055d15f0678a0 | 20,049 |
from typing import Callable
from re import T
from typing import Optional
from typing import Dict
from typing import Any
import yaml
def construct_from_yaml(
constructor: Callable[..., T],
yaml_dict: Optional[Dict[str, Any]] = None,
) -> T:
"""Build ``constructor`` from ``yaml_dict``
Args:
con... | 5cb92f8af0b0ab49069e88b74b7b10fdf2cc797d | 20,050 |
import tokenize
def text_to_document(text, language="en"):
""" Returns string text as list of Sentences """
splitter = _sentence_splitters[language]
utext = unicode(text, 'utf-8') if isinstance(text, str) else text
sentences = splitter.tokenize(utext)
return [tokenize(text, language) for text in s... | 2f196c51a979a2f9a849ebd6f89203c907406789 | 20,051 |
def get_top_playlists_route(type):
"""
An endpoint to retrieve the "top" of a certain demographic of playlists or albums.
This endpoint is useful in generating views like:
- Top playlists
- Top Albums
- Top playlists of a certain mood
- Top playlists of a certain mood from pe... | 2012e95073291669a6bb881afa853961922160c5 | 20,052 |
import urllib
def parse_host(incomplete_uri: str) -> str:
"""Get netloc/host from incomplete uri."""
# without // it is interpreted as relative
return urllib.parse.urlparse(f"//{incomplete_uri}").netloc | 099284e970756055f2616d484014db210cb04a76 | 20,053 |
import functools
import operator
def inner_by_delta(vec1: Vec, vec2: Vec):
"""Compute the inner product of two vectors by delta.
The two vectors are assumed to be from the same base and have the same
number of indices, or ValueError will be raised.
"""
indices1 = vec1.indices
indices2 = vec2... | 660f7d73e6d73cd4dfdf73d532e90e5a29f38481 | 20,054 |
def remove_mapping(rxn_smi: str, keep_reagents: bool = False) -> str:
"""
Removes all atom mapping from the reaction SMILES string
Parameters
----------
rxn_smi : str
The reaction SMILES string whose atom mapping is to be removed
keep_reagents : bool (Default = False)
whether to... | fb16648fee136359bc8ef96684824319221a3359 | 20,055 |
def generate_bot_master_get_results_message(message_id, receiving_host, receiving_port):
"""
:rtype : fortrace.net.proto.genericmessage_pb2.GenericMessage
:type receiving_port: int
:type receiving_host: str
:type message_id: long
:param message_id: the id of this message
:param receiving_ho... | 4c46a9c1bf69022092b7df4b48e302a87d2d7b90 | 20,056 |
import fileinput
from datetime import datetime
def readLogData(username,level,root='.'):
"""
Extracts key events from a log
"""
filename = getFilename(username,level,extension='log',root=root)
log = []
start = None
for line in fileinput.input(filename):
elements = line.split()
... | f94c3e715d021b206ef46766fdc0e6051784615e | 20,057 |
def get_type1(pkmn):
"""get_type1(pkmn) returns Type 1 of the Pokémon with the name 'pkmn' """
return __pokemon__[pkmn]['Type 1'] | c4290f695160f2f1962f1dca158359e250a4803a | 20,058 |
def load_json(fname):
"""
Load a JSON file containing a riptide object (or list/dict/composition thereof)
"""
with open(fname, 'r') as f:
return from_json(f.read()) | 93f771ae0ba31974b564e1520412fab5719b08be | 20,059 |
def get_stock_data(symbol, start_date, end_date, source="phisix", format="c"):
"""Returns pricing data for a specified stock and source.
Parameters
----------
symbol : str
Symbol of the stock in the PSE or Yahoo.
You can refer to these links:
PHISIX: https://www.pesobility.com/... | 94171c950198f0975c4232f232ec9be93bd3f2a3 | 20,060 |
def extract_borderless(result) -> list:
"""
extracts borderless masks from result
Args:
result:
Returns: a list of the borderless tables. Each array describes a borderless table bounding box.
the two coordinates in the array are the top right and bottom left coordinates of the bounding box.
... | e81844a5deb553bf8d7380ebec8a76fec219ee72 | 20,061 |
import itertools
def get_frequent_length_k_itemsets(transactions, min_support=0.2, k=1, frequent_sub_itemsets=None):
"""Returns all the length-k itemsets, from the transactions, that satisfy
min_support.
Parameters
----------
transactions : list of list
min_support : float, optional
F... | a293b48c62ebbafda7fa89abb6792f04c4ff1371 | 20,062 |
import types
def create_news_markup():
"""
Метод, создающий клавиатуру для новостей кино
:return: telebot.types.ReplyKeyboardMarkup
"""
news_markup = types.ReplyKeyboardMarkup()
news_markup.row(Commands.GET_BACK_COMMAND)
return news_markup | 654ec227d07fe914c795931f48ce634e0a4a6fc3 | 20,063 |
from datetime import datetime
def get_bibtex_query_set(params):
"""Returns bibtex objects which match the search parameters.
Args:
params: dict which is maded by `parse_GET_params`
Returns:
QuerySet
request_dict
"""
bibtex_queryset = Bibtex.objects.all()
# Book_styl... | 0f19b4cccf3a44ca3fd5e907a2cd07a24208badf | 20,064 |
def _generate_description_from(command, name, description):
"""
Generates description from the command and it's optionally given description. If both `description` and
`command.__doc__` is missing, defaults to `name`.
Parameters
----------
command : `None` or `callable`
The command's fu... | e2f782f7e74635b3c50273b36b837e48d7999f4f | 20,065 |
def uses_na_format(station: str) -> bool:
"""
Returns True if the station uses the North American format,
False if the International format
"""
if station[0] in NA_REGIONS:
return True
elif station[0] in IN_REGIONS:
return False
elif station[:2] in M_NA_REGIONS:
retur... | b3158a85ae9b1ba45ebeb3de27491650d7f4c4c8 | 20,066 |
def openFile(prompt,key = "r",defaulttype = None, defaultname = None):
"""
Method to open a text file with sanity checking, optional defaults and reprompt on failure.
This is the main used callable function to open files.
:param prompt: the prompt to be displayed
:type prompt: str
:param key: ... | e9985872c0beb15eaa5bafa543eefb01f5fd8413 | 20,067 |
def dsphere(n=100, d=2, r=1, noise=None, ambient=None):
"""
Sample `n` data points on a d-sphere.
Parameters
-----------
n : int
Number of data points in shape.
r : float
Radius of sphere.
ambient : int, default=None
Embed the sphere into a space with ambient dimensi... | 8957a328c2025fbdb3741b004f2fb3825f19e4d9 | 20,068 |
def topological_sort_by_down(start_nodes=None, all_nodes=None):
"""
Topological sort method by down stream direction.
'start_nodes' and 'all_nodes' only one needs to be given.
Args:
start_nodes (list[NodeGraphQt.BaseNode]):
(Optional) the start update nodes of the graph.
all... | 22a36d4f8225ae2978459796f115059e2bbb8d62 | 20,069 |
import os
def check_directories(directories):
"""Checks if all given directories are really directories and on the same
device.
Parameters:
directories (list of strings) - The directories to check.
Returns:
The tuple (ok, ok_dirs) where ok is a boolean and ok_dirs a list o... | 779195d7509beb4b13ed237fec654514c6226586 | 20,070 |
import os
def download_accessions(force_download=False):
"""Downloads the compound accessions
:param bool force_download: If true, overwrites a previously cached file
:rtype: str
"""
if os.path.exists(ACCESSION_DATA_PATH) and not force_download:
log.info('using cached data at %s', ACCESSI... | 6a8871acd1b2d171ffd654718bc7e75f87627df7 | 20,071 |
from datetime import datetime
def parseYear(year, patterns):
""""This function returns a string representing a year based on the input and a list of possible patterns.
>>> parseYear('2021', ['%Y'])
'2021'
>>> parseYear('2021', ['(%Y)', '%Y'])
'2021'
>>> parseYear('(2021)', ['%Y', '(%Y)'])
'2021'
"""
... | 743378c868a2439f721e428f676092f9da0a2e7a | 20,072 |
def fit_oxy_nii(target_row,
velocity_column = None,
data_column = None,
IP = "center",
**kwargs):
"""
Fits oxygen bright line to spectrum for future subtraction
Parameters
----------
target_row: `SkySurvey` row
... | 1251bf102abaec690fc97117c2409e2f5e89f35b | 20,073 |
import urllib
import json
import logging
def get(url, accept=None, headers=None):
"""
Make a basic HTTP call to CMR using the POST action
Parameters:
url (string): resource to get
body (dictionary): parameters to send, or string if raw text to be sent
accept (string): encoding of t... | c956a6d7f434b686263f0b179b2e6cd060cd35b0 | 20,074 |
def image_reproject_from_healpix_to_file(source_image_hdu, target_image_hdu_header, filepath=None):
""" reproject from healpix image to normal wcs image
:param source_image_hdu: the HDU object of source image (healpix)
:param target_image_hdu_header: the HDU object of target image (wcs)
:param f... | b261663f18ccdf095c0b6e20c02d2ebc0282b713 | 20,075 |
def flux_reddening_wl(wl, flux_wl, ebv, Rv=None, law=LawFitz, mode=ReddeningLaw.MW):
"""
Apply extinction curves to flux(lambda) values
:param wl: [A]
:param flux_wl: [ergs s^-1 cm^-2 A^-1]
:param ebv: E(B-V)
:param Rv: R_V
:param law: the variant of extinction curves
:param mode: type... | 668d1824d988989a3411c798614aeb1bc6a63cb6 | 20,076 |
import string
def genRandomString( size: int = 5, upper: bool = False, lower: bool = False, mix: bool = False, numbers: bool = True) -> str:
"""
Generates a random string of the given size and content.
:param numbers: Numbers are included in the string. Default True.
:param upper: Uppercase only. Default False.
... | a63a2be76675bbb42da2a4cd0ae20db8be723ee3 | 20,077 |
def process_whole_image(model, images, num_crops=4, receptive_field=61, padding=None):
"""Slice images into num_crops * num_crops pieces, and use the model to
process each small image.
Args:
model: model that will process each small image
images: numpy array that is too big for model.predic... | 3e9ab9485662f9bae40217c60837d8d8cba020d3 | 20,078 |
def compute_covariance(model, xy, XY=None):
"""Returns the covariance matrix for a given set of data"""
if xy.size == 1:
dist = 0
elif XY is None:
dist = squareform(pdist(xy))
else:
dist = cdist(xy, XY)
C = model(dist)
return C | b898ef57155898c75797033e057c6cab4e2487bc | 20,079 |
import sqlite3
def prob1(cur: sqlite3.Cursor) -> pd.DataFrame:
"""List how many stops are in the database.
Parameters
----------
cur (sqlite3.Cursor) : The cursor for the database we're accessing.
Returns
-------
(pd.DataFrame) : Table with the solution.
"""
cur.execu... | ed6a3a316e89177a6224fd7513ca5c098940e312 | 20,080 |
def q_fn(x):
"""
The Q-function assesses all possible actions that can be taken, given a state.
Two layer feed forward neural network. All layers are fully connected, biases initialized with 0.
The constants above define the layer sizes.
:param x: Batch input tensor to the network.
:return: Acti... | 4c4fece48773d020c321fd433aa75caa7bc258ee | 20,081 |
def getPlayer(env, name, decoder):
"""Get user's player data"""
players = getPlayers(env, decoder)
if name in players.keys():
return players[name]
else:
return False | fd98e481abab6e7f53bf66d0285f506d06f5e6ea | 20,082 |
import re
def get_config_errors(conf, filename="<no name>"):
"""
Validate a configuration object and return the list of errors found.
"""
rv = []
# Give a clearer error message than what jsonschema would give
# Something like: None is not of type 'object'
if not isinstance(conf, dict):
... | 4020d5dd33f840dc6c0e3c24be77acf80a606d57 | 20,083 |
def process_vcf( info ):
"""
pass izip object of line object and other needed vars
info[0] = list of vcf lines from VCF object iterator.
info[1] = clf object
info[2] = dataset dictionary
info[3] = filter arg supplied by user
info[4] = min classification frequency supplied by user (defaults to None)
"""
... | 389146cd88804935ee2aae85a9e5d84684f81b7e | 20,084 |
def createLayerOnFrameDepend(job, layer, onjob, onlayer, onframe):
"""Creates a layer on frame dependency
@type job: string
@param job: the name of the dependant job
@type layer: string
@param layer: the name of the dependant layer
@type onjob: string
@param onjob: the name of the job to dep... | 45b49c1406e678213f6d2d93d0cba4dae5d2a824 | 20,085 |
def compute_task1_f1_score(truth, solutions):
""" compute f1 score for task 1
:param truth: list of ground truth values for all problem-ids
:param solutions: list of solutions for all problem-ids
:return: f1 score
"""
task1_truth, task1_solution = extract_task_results(truth, solutions, 'multi-au... | 2e44603c547062d85023fb405d3ab511d3ca40d3 | 20,086 |
def multiply(t1,t2):
"""
Multiplies (expands) two binary expressions t1 and t2 based on the distributive rule
Args:
t1 (str): first binary expression
t2 (str): second binary expression
Returns:
A string representing the expansion of the boolean algebraic... | 0078ee94420722600be31edc74a86b1932c4d2f2 | 20,087 |
def source_remove_all(obj_type, obj_id, name, analyst=None):
"""
Remove a source from a top-level object.
:param obj_type: The CRITs type of the top-level object.
:type obj_type: str
:param obj_id: The ObjectId to search for.
:type obj_id: str
:param name: The name of the source.
:type ... | c9c7860f27b230ea9834c4a58324da70ebee9e30 | 20,088 |
def driver(dbname):
"""
Determine driver module
:Parameters:
`dbname` : ``str``
DB name (section token in db.conf)
:Return: Driver module
:Rtype: ``module``
:Exceptions:
- `DBConfigurationError` : DB not configured
- `KeyError` : DB name not found
- `ImportErro... | 01a2b0e10975879f944bbaf51b44d8eef6b97996 | 20,089 |
from typing import Union
def d1tile_x_d2(d1: Union[float, np.ndarray],
d2: np.ndarray) -> np.ndarray:
"""
Create array of repeated values with dimensions that match those of energy array
Useful to multiply frequency-dependent values to frequency-time matrices
:param d1: 1D input vecto... | 68721f7f9ab1b60f77e8199ad917dd47b19aaa95 | 20,090 |
def get_all_gradients_for_Q4( theta, X, Y ):
"""
Do the same thing as Q(iv) but it is actually only for storing and
observing the sample gradient and whole gradient for the Q(iv) step
Output the sample grdient and whole grdient data
"""
# Get difference of uclidean distance
def get_differen... | d508b826f552d844cf95f9d5515c5eb1512dfbcb | 20,091 |
def findSubsetIndices(min_lat,max_lat,min_lon,max_lon,lats,lons):
"""Array to store the results returned from the function"""
res=np.zeros((4),dtype=np.float64)
minLon=min_lon; maxLon=max_lon
distances1 = []; distances2 = []
indices=[]; index=1
for point in lats:
s1 = max_lat-point # ... | 7d41b33fd492fa8b5cd62c368210bcbea2c7bc89 | 20,092 |
def call(stoptime, seconds, method=None):
"""
Returns a dict with route, direction, stop, call time and source.
Call time is in UTC.
"""
result = dict(stoptime._asdict(), call_time=toutc(seconds), source=method or "I")
result["deviation"] = result["call_time"] - stoptime.datetime
return resu... | bfa78ec89b60bf1140b8b24bc91fd1a2dd9c2a63 | 20,093 |
import re
def sanitize_value(val):
"""Remove crap from val string and then convert it into float"""
val = re.sub(u"(\xa0|\s)", '', val)
val = val.replace(',', '.')
# positive or negative multiplier
mult = 1
if '-' in val and len(val) > 1:
mult = -1
val = val.replace('-', '')
... | 0fc67bf519674575451f4fc029bee658ea2bd2da | 20,094 |
def getObjectInfo(fluiddb, about):
"""
Gets object info for an object with the given about tag.
"""
return fluiddb.about[about].get() | 8614edaf44944fcc11882ac2fcaa31ba31d48d30 | 20,095 |
import warnings
def __getattr__(name):
"""Get attribute."""
deprecated = __deprecated__.get(name)
if deprecated:
warnings.warn(
"'{}' is deprecated. Use '{}' instead.".format(name, deprecated[0]),
category=DeprecationWarning,
stacklevel=(3 if PY37 else 4)
... | c904f1221492e8f08786918dd496d3d6861fd35e | 20,096 |
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
return common.read_model('finger.xml'), common.ASSETS | cacb53de08eef5695a5464fbb72a1706ff489276 | 20,097 |
async def process_logout():
"""
Purge the login information from the users session/cookie data
:return: Redirect to main body
"""
# Simply destroy the cookies in this session and get rid of the creds, redirect to landing
response = RedirectResponse("/") # Process the destruction from main app... | 98d9c8c40e0a1fe224538b353a2a803fdd7fce76 | 20,098 |
from typing import Optional
def _lex_label(label: str) -> _LexedLabel:
"""Splits the label into packages and target."""
match = _LABEL_LEXER.match(label)
if match is None:
raise ValueError(f'{label} is not an absolute Bazel label')
groups = match.groupdict()
packages: Optional[str] = groups['packages']
... | f067d5e81b02a4242d8459b41d49c302459f416b | 20,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.