content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def create_app() -> Flask:
"""Create flask app."""
app_settings = os.getenv('APP_SETTINGS')
app.config.from_object(app_settings)
db.init_app(app)
migrate.init_app(app, db)
register_blueprints(app)
app.register_error_handler(400, handle_validation_errors)
app.register_error_... | 53924e1fbb9332cfa940771cd57117c569fa9555 | 25,900 |
def roll(y, z):
"""Estimate angular roll from gravitational acceleration.
Args:
y, z (float, int, array-like): y, and z acceleration
Returns:
(float, int, array-like): roll
"""
return np.arctan2(y, z) * 180/np.pi | ccb0bf948baf7fee9853f4b842139e8a964c25b6 | 25,901 |
def eq_to_az_za(ra, dec, lst, latitude=HERA_LATITUDE):
"""
Convert equatorial (RA/Dec) coordinates to azimuth and zenith angle.
Basic expression from http://star-www.st-and.ac.uk/~fv/webnotes/chapter7.htm
Parameters
----------
ra, dec : array_like, float
RA and Dec in radians.
... | e8c847779cfd440c5df37e4d80cf650a87c0c2c3 | 25,902 |
def log_cc(image, sigma, threshold):
"""Find connected regions above a fixed threshold on a LoG filtered image.
Parameters
----------
image : np.ndarray
Image with shape (z, y, x) or (y, x).
sigma : float or Tuple(float)
Sigma used for the gaussian filter (one for each dimension). I... | 6a0347b846e5bc1c8d9557d66142a8c3b834db9b | 25,903 |
def check_valid_move(grid: np.ndarray, current_position: tuple, move: tuple) -> bool:
"""
Checking if move is valid for the current position in provided grid
:param grid: validated array of a grid
:param current_position: current position
:param move: move in tuple form
:return: True or False
... | 60f58c618a01aad744e1ae7c6d425fc69db20686 | 25,904 |
def check_valid_game(season, game):
"""
Checks if gameid in season schedule.
:param season: int, season
:param game: int, game
:return: bool
"""
try:
get_game_status(season, game)
return True
except IndexError:
return False | 5bc95a2dc397b933c1e5716eb5a7e79641b87968 | 25,905 |
def console(session_console):
"""Return a root console.
Be sure to use this fixture if the GUI needs to be initialized for a test.
"""
console = session_console
assert libtcodpy.console_flush() == 0
libtcodpy.console_set_default_foreground(console, libtcodpy.white)
libtcodpy.console_set_def... | 25c13c549a40c24f7abc90ecb7c303bbc791643b | 25,906 |
def conv(out_channels, kernel_size, stride=2, padding=1, batch_norm=True):
"""Creates a convolutional layer, with optional batch normalization.
"""
layers = []
conv_layer = Conv2D(out_channels, kernel_size, strides = stride, padding = 'same', use_bias = False, data_format = "channels_first")
# bias ... | fe568a8b3cd5092db6751677f1accd3d73e36e77 | 25,907 |
def t90_from_t68(t68):
"""
ITS-90 temperature from IPTS-68 temperature
This conversion should be applied to all in-situ
data collected between 1/1/1968 and 31/12/1989.
"""
return t68 / 1.00024 | a2d8c7ccc0797d47fa8f732bdb61c1ec1e15700e | 25,908 |
def prettify(elem):
"""Return a pretty-printed XML strong for the Element.
"""
rough_string = ElementTree.tostring(elem, "utf-8")
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ") | b7686ca0b6d6def2e86f465fa0eb5726fe29d2ab | 25,909 |
import re
import json
def course_search(search_str, include_inactive=False, debug=False):
""" Parse search string to get institution, discipline, and catalog_number, then find all matching
courses and return an array of catalog entries.
Search strings by example
qns csci * All CSCI courses at Q... | 42468dfc70dfda19cf776aab97fc17c1f5978747 | 25,910 |
def _pad(
s: str,
bs: int,
) -> str:
"""Pads a string so its length is a multiple of a specified block size.
:param s: The string that is to be padded
:type s: str
:param bs: The block size
:type bs: int
:returns: The initial string, padded to have a length that is a multiple of... | 1da441d51c57da688ebcf46b7a30feb36cd007fe | 25,911 |
import json
def get_json(headers) -> str:
"""Construct a str formatted like JSON"""
body: dict = {}
for key, value in headers.items():
body[key] = value
return json.dumps(body, indent=2) | 8471f044ae986acd2173d5e9be26c110ee1b1976 | 25,912 |
from sys import path
def get_targets(units, assembly_basename, outdir, extensions = ['.fasta.dammit.gff3', '.fasta.dammit.fasta'], se_ext = ['se'], pe_ext = ['pe']):
"""
Use the sample info provided in the tsv file
to generate required targets for dammit
"""
dammit_dir = assembly_basename + ".fast... | 8edd84c9012c20d55f0087ae34eb9bf64a91b686 | 25,913 |
from typing import Any
def is_jsonable_object(obj: Any) -> bool:
"""
Return `True` if ``obj`` is a jsonable object
"""
cls = obj if isinstance(obj, type) else type(obj)
return isinstance(getattr(cls, PHERES_ATTR, None), ObjectData) | f0492544c88efc46d135bc913bc7f8dd7a7f7462 | 25,914 |
def Dir(obj):
"""As the standard dir, but also listup fields of COM object
Create COM object with [win32com.client.gencache.EnsureDispatch]
for early-binding to get what methods and params are available.
"""
keys = dir(obj)
try:
## if hasattr(obj, '_prop_map_get_'):
## k... | 8abc62fbe09e953fb171626a888838e21346ad9e | 25,915 |
def image_classify(request):
""" Image classification """
if request.method == 'POST':
# Get upload image
img = request.FILES.get('img', None)
if img:
return JsonResponse(dict(name=img.name, size=img.size))
else:
return JsonResponse(dict(code=401, msg='Ba... | 4f459f7a7afd90b1c6de7f174b4926d0d90b35cb | 25,916 |
def calculate_performance_indicators_V1(df):
"""Compute indicators of performances from df of predictions and GT:
- MAE: absolute distance of predicted value to ground truth
- Accuracy: 1 if predicted value falls within class boundaries
Note: Predicted and ground truths coverage values are ratios betwee... | f5c374ffb558eaf65a4c29894fbcb831162a451d | 25,917 |
def PH2_Calc(KH2, tH2, Kr, I, qH2):
"""
Calculate PH2.
:param KH2: hydrogen valve constant [kmol.s^(-1).atm^(-1)]
:type KH2 : float
:param tH2: hydrogen time constant [s]
:type tH2 : float
:param Kr: modeling constant [kmol.s^(-1).A^(-1)]
:type Kr : float
:param I: cell load current... | fe69353bfdde4f301439b89f9946782457d07645 | 25,918 |
import scipy
def log_transform(image):
"""Renormalize image intensities to log space
Returns a tuple of transformed image and a dictionary to be passed into
inverse_log_transform. The minimum and maximum from the dictionary
can be applied to an image by the inverse_log_transform to
convert i... | 8e8d6779b313c7ff02e7aafa291e4d2abd687ac1 | 25,919 |
from bs4 import BeautifulSoup
from typing import Optional
def parse_cpu(website: BeautifulSoup, product_id: int) -> Optional[CPU]:
"""Parses the given Intel ARK website for a CPU."""
# thanks for making accessing so easy btw.
# a simple string used for identification of the CPU
raw = website.find(att... | 1e7d068caba63947c39ce3a2391009986c5d6ad3 | 25,920 |
from typing import List
def create_result_dict(
begin_date: str,
end_date: str,
total_downloads: int,
downloads_per_country: List[dict],
multi_row_columns: dict,
single_row_columns: dict,
) -> dict:
"""Create one result dictionary with info on downloads for a specific eprint id in a given ... | 59ed6c40e98a8a68e1914f8f14b992b702851ccd | 25,921 |
def getConcentricCell(cellNum, matNum, density, innerSurface, outerSurface, universe, comment):
"""Create a cell which has multiple components inside a cell."""
uCard = ''
if type(universe) is int:
uCard = 'u=' + str(universe)
listType = []
if type(innerSurface) == type(listType):
ne... | f0e8af3210774500eac0fde195896f3b85473e3f | 25,922 |
import os
import glob
def is_downloaded(folder):
""" Returns whether CIFAR has been downloaded """
return os.path.isdir(folder) and len(glob(os.path.join(folder, '*'))) == 8 | ddae821b88eaec059dba66bbfefe4bd2d90707d5 | 25,923 |
from pathlib import Path
import subprocess
def main():
"""Validates individual trigger files within the raidboss Cactbot module.
Current validation only checks that the trigger file successfully compiles.
Returns:
An exit status code of 0 or 1 if the tests passed successfully or failed, respecti... | b67137a115fa88334cd5e44b7715f19d64482045 | 25,924 |
import tqdm
def weight_compression(weights, bits, axis=0, quantizer=None):
"""Creates an in, out table that maps weight values to their codebook values.
Based on the idea presented by https://arxiv.org/pdf/1911.02079.pdf
Arguments:
weights: Numpy array
bits: Number of bits to compress weights to. This ... | f7fd3a1908c51a1781367bfd717d9db6f7740934 | 25,925 |
import multiprocessing
def noncoherent_dedispersion(array, dm_grid, nu_max, d_nu, d_t, threads=1):
"""
Method that de-disperse dynamical spectra with range values of dispersion
measures and average them in frequency to obtain image in (t, DM)-plane.
:param array:
Numpy 2D array (#freq, #t) wi... | 866e129e74ae121c093c70a67c811f6a0bf0d3bc | 25,926 |
import struct
def parse_cstring(stream, offset):
"""
parse_cstring will parse a null-terminated string in a bytestream.
The string will be decoded with UTF-8 decoder, of course since we are
doing this byte-a-byte, it won't really work for all Unicode strings.
TODO: add proper Uni... | 986073f9b473ec36c08e5d041e8a4b8c1ea6bbf1 | 25,927 |
def ParseLabelTensorOrDict(labels):
"""Return a tensor to use for input labels to tensor_forest.
The incoming targets can be a dict where keys are the string names of the
columns, which we turn into a single 1-D tensor for classification or
2-D tensor for regression.
Converts sparse tensors to dense ones.
... | d0f5dcd32fc04418caa9715be2779897703927cb | 25,928 |
def showCallGraph(pyew, doprint=True, addr=None):
""" Show the callgraph of the whole program """
dot = CCallGraphGenerator(pyew)
buf = dot.generateDot()
if doprint:
showDotInXDot(buf)
return buf | 936176e312652536dc4cea8eaf3da531ec519615 | 25,929 |
def make_template(center, data):
"""Make templated data."""
if isinstance(data, dict):
return {key: make_template(center, val) for key, val in data.items()}
if isinstance(data, list):
return [make_template(center, val) for val in data]
env = get_env(center)
return env.from_string(s... | 54763209c2b65604c3c781bdbf7553198048757f | 25,930 |
def get_sequana_adapters(type_, direction):
"""Return path to a list of adapters in FASTA format
:param tag: PCRFree, Rubicon, Nextera
:param type_: fwd, rev, revcomp
:return: path to the adapter filename
"""
# search possible types
registered = _get_registered_adapters()
if type_ not ... | a331f9f0839d1193b9deefb3dbbdc8e31f882843 | 25,931 |
def board_str(board):
"""
String representation of the board. Unicode character for the piece,
1 for threat zone and 0 for empty zone.
"""
mat = ''
for row in board:
for squ in row:
if squ > 1:
mat += '%s ' % chr(squ)
else:
mat +=... | 769d846c5b03c8b75145e3b81cab17ed7331fbbf | 25,932 |
def build_pubmed_url(pubmed_id) -> str:
"""
Generates a Pubmed URL from a Pubmed ID
:param pubmed_id: Pubmed ID to concatenate to Pubmed URL
:return: Pubmed URL
"""
return "https://pubmed.ncbi.nlm.nih.gov/" + str(pubmed_id) | 5794fbec75de0451547d6f0570bb89964026c394 | 25,933 |
def create_build_job_query(user, time_frame, local=False):
"""Create the query to get build jobs from graylog
Args:
user(str): Fed ID
time_frame(int): Graylog search period in hours
local(bool): If True also search string for local builds
Returns:
str: Query string for a gr... | ada2dd0c40ef0de8221e03dbdf5c2410705ff2cf | 25,934 |
def convert_to_json(payload_content):
"""Convert the OPC DA array data to JSON (Dict) and return the aggregated JSON data."""
try:
json_response = {}
for t in payload_content: # tuple in payload_content
temp = {}
key = t[0].replace(".", "-").replace("/", "_")
... | be7aa3a60c9d8ad48e5a48e09bb16e5d456f2cba | 25,935 |
def unites(value=32767):
"""
Restock all resistance messages.
"""
invoker = spellbook.getInvoker()
value = min(value, 32767)
invoker.restockAllResistanceMessages(value)
return 'Restocked %d unites!' % value | 6cb8e977216b0559c1de85c14ff95983b92a11a1 | 25,936 |
def gif_summary(name, tensor, max_outputs, fps, collections=None, family=None):
"""Outputs a `Summary` protocol buffer with gif animations.
Args:
name: Name of the summary.
tensor: A 5-D `uint8` `Tensor` of shape `[batch_size, time, height, width,
channels]` where `channels` is 1 or 3.
... | c0c4fda8e988c6f5a3918ae45531692ef36588e4 | 25,937 |
def fFargIm(k,phi, x):
"""Imaginary part of the argument for the integral in fF()
"""
theta=phi*x
return (1/np.sqrt(1-k*k*np.sin(theta)**2)).imag | ec858c9b81e881e6d91299546904670723300b82 | 25,938 |
import warnings
def deprecated(func):
"""Prints a warning for functions marked as deprecated"""
def new_func(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning) # turn off filter
warnings.warn('Call to deprecated function "{}".'.format(func.__name__),
c... | f92e71f8662d71d3ed5a93f914cf3352282d940c | 25,939 |
def _simulate_dataset(
latent_states,
covs,
log_weights,
pardict,
labels,
dimensions,
n_obs,
update_info,
control_data,
observed_factor_data,
policies,
transition_info,
):
"""Simulate datasets generated by a latent factor model.
Args:
See simulate_data
... | 5f3c046ffea328e01580e607762311a96b9bf66d | 25,940 |
def has_user_data(node: hou.Node, name: str) -> bool:
"""Check if a node has user data under the supplied name.
:param node: The node to check for user data on.
:param name: The user data name.
:return: Whether or not the node has user data of the given name.
"""
return _cpp_methods.hasUserDat... | 5953a24fa369f7d8c1aed7635d5fde3f30324c27 | 25,941 |
def load_ptsrc_catalog(cat_name, freqs, freq0=1.e8, usecols=(10,12,77,-5), sort=False):
"""
Load point sources from the GLEAM catalog.
Parameters
----------
cat_name : str
Filename of piunt source catalogue.
freqs : array_like
Array of frequencies to evaluate point sour... | 54f830e9fef746cdabe8b29cc9a7481b67593476 | 25,942 |
from datetime import datetime
import uuid
def create():
"""
Create a new experiment record and the container associated with it.
"""
# Process form submission
if flask.request.method == 'POST':
experiment_id = flask.request.form['experiment_id']
container = experiment_id
... | 6537372eb7a2345d5cd38954fb69e5fac446d2f1 | 25,943 |
def get_model():
"""
Reference : http://images.nvidia.com/content/tegra/automotive/images/2016/solutions/pdf/end-to-end-dl-using-px.pdf
I have added dropout layers to reduce overfitting
"""
model = Sequential()
# Normalization and zero centering.
model.add(Lambda(lambda x: x / 255.0 - ... | 4591745f43719450f2da579b13ebd45a103bf76e | 25,944 |
def ser_iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed):
"""
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for a single CPU core.
INPUTS:
in1 (no... | 3a0e22ef55b14dfce3eb706800439d55f97bcd19 | 25,945 |
def delete_ref(profile, ref):
"""Delete a ref.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
ref
The ref to ... | 4009c3bb787914ed4130760cf5d3fcfad4032496 | 25,946 |
def mean_ratio_reversion_test(hd1, hd2, n=20, offset=20, hold_time=30, return_index=False):
"""
Tests over the time period offset:offset-hold_time to see if the price ratio of the
price pair reverts to the mean.
"""
#Get initial price ratio
init_pr = hd1.close[offset]/hd2.close[offset]
#Get... | 248987fbbb718303b413fe1eb63384fba42edc07 | 25,947 |
def list_contents(path, root):
"""
@return list of relative paths rooted at "root"
"""
cmd = "svn ls %s/%s" % (root, path)
code, out = util.execute(cmd, return_out=True)
dirs = out.strip().split('\n')
return dirs | 4fd02b8aeb362bdca1d37f4dc3d481b38f1d9059 | 25,948 |
def evaluate_voting():
"""Evaluates the Voting-Results in the instance_dict. Returns Array with the Player-ID(s)"""
poll_dict = {}
for ip in instance_dict.keys():
if 'poll' in instance_dict[ip]:
if instance_dict[ip]['poll'] in poll_dict:
old = poll_dict[instance_dict[ip][... | 4c86e453e24114ad00239a3ad97c23f9b25dd243 | 25,949 |
import torch
def mmd(x1, x2, sigmas):
"""the loss of maximum mean discrepancy."""
x1 = torch.reshape(x1, [x1.shape[0], -1])
x2 = torch.reshape(x2, [x2.shape[0], -1])
# print('x1x2shape:', x1.shape)
diff = torch.mean(gaussian_kernel(x1, x1, sigmas)) # mean_x1x1
diff -= 2 * torch.mean(gaussian_... | 1248de57d5aac658c54c6f67b4ba072f3dcd3978 | 25,950 |
async def api_audio_summaries() -> str:
"""Turn audio summaries on or off."""
assert core is not None
toggle_off = (await request.data).decode().lower() in ["false", "off"]
if toggle_off:
# Disable
core.disable_audio_summaries()
_LOGGER.debug("Audio summaries disabled.")
... | 4091678ed60d2569178d45ba30b25c6580cab601 | 25,951 |
import sys
def get_image():
"""Gets an image file via POST request, feeds the image to the FaceNet model then saves both the original image
and its resulting embedding from the FaceNet model in their designated folders.
'uploads' folder: for image files
'embeddings' folder: for embedding num... | ee9b59c695f11b5797356012a9c7dccfa49a5569 | 25,952 |
def choose(n,r):
"""
number of combinations of n things taken r at a time (order unimportant)
"""
if (n < r):
return 0
if (n == r):
return 1
s = min(r, (n - r))
t = n
a = n-1
b = 2
while b <= s:
t = (t*a)//b
a -= 1
b += 1
return t | 5852054f1a6381278039b0ec2184d0887e2b1d2b | 25,953 |
def _bisearch(ucs, table):
"""
Auxiliary function for binary search in interval table.
:arg int ucs: Ordinal value of unicode character.
:arg list table: List of starting and ending ranges of ordinal values,
in form of ``[(start, end), ...]``.
:rtype: int
:returns: 1 if ordinal value uc... | f9b985771fa94138ae9b0dfbb8fa9ee413c65a48 | 25,954 |
def get_xml_serial_number (root):
"""
Get the serial number from the system global settings XML.
Parameters:
root -- An XML element to the root of the system global settings.
Return:
The serial number.
"""
return get_xml_string_value (root, "serialNumber", "ser... | 5b1dd2ef70f34980cddce442a1c8707c5d81e478 | 25,955 |
def ParseMachineType(resource_parser, machine_type_name, project, location,
scope):
"""Returns the location-specific machine type uri."""
if scope == compute_scopes.ScopeEnum.ZONE:
collection = 'compute.machineTypes'
params = {'project': project, 'zone': location}
elif scope == comput... | 70b5311525569a4981fd0170a62a3f0d53a8a8f1 | 25,956 |
def redirect_to_default():
"""
Redirects users to main page if they make a GET request to /generate
Generate should only be POSTed to
"""
log("Received GET request for /generate, returning to default page")
return redirect(url_for("default")) | 951e610ac3e56ec6e84dbeacb3174fe79a1c6f9c | 25,957 |
def client_credential_grant_session():
"""Create a Session from Client Credential Grant."""
oauth2credential = OAuth2Credential(
client_id=None,
redirect_url=None,
access_token=ACCESS_TOKEN,
expires_in_seconds=EXPIRES_IN_SECONDS,
scopes=SCOPES_SET,
grant_type=auth... | 54b37e3a6ae582982e47e2135058ce6d7bafd6ea | 25,958 |
import requests
def _query(server, method, parameters, timeout=DEFAULT_TIMEOUT, verify_ssl=True, proxies=None):
"""Formats and performs the query against the API.
:param server: The MyGeotab server.
:type server: str
:param method: The method name.
:type method: str
:param parameters: The par... | a7615543dffc7270fddc12bc909488cdd03ad0be | 25,959 |
def volume_update(context, volume_id, values):
"""Set the given properties on an volume and update it.
Raises NotFound if volume does not exist.
"""
return IMPL.volume_update(context, volume_id, values) | 1f696458654daf25767ec2a888a2bfa7a8c1872d | 25,960 |
def get_E_Elc_microwave_d_t(P_Elc_microwave_cook_rtd, t_microwave_cook_d_t):
"""時刻別消費電力量を計算する
Parameters
----------
P_Elc_microwave_cook_rtd : float
調理時の定格待機電力, W
t_microwave_cook_d_t : ndarray(N-dimensional array)
1年間の全時間の調理時間を格納したND配列, h
d日t時の調理時間が年開始時から8760個連... | c49666272e86c8e10b8df15e639056ba8701f88b | 25,961 |
from typing import Tuple
from typing import Any
def set_up_text_location(
image: ImageDraw, img_opened: Image, text: str, font: ImageFont
) -> Tuple[Any, Any]:
"""
Returns coordinates of text location on the image
:param image: ImageDraw object
:param img_opened: opened PIL image
:param text: ... | 26f8a7719e033cd81db66e50ecd638abd67a6846 | 25,962 |
def service_detail(request, service_id):
"""This view shows the details of a service"""
service = get_object_or_404(Service, pk=service_id)
job_statuses = (
enumerations.QUEUED,
enumerations.IN_PROCESS,
enumerations.FAILED,
)
resources_being_harvested = HarvestJob.objects.fil... | 13abb413973428eda57c0c18e9ee71044f9e32ab | 25,963 |
def convolutional_block(X, f, filters, stage, block, s):
"""
Implementation of the convolutional block as defined in Figure 4
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for the main path
... | ab695bd12b7179c02f2cc8696eeeedf3f153bfce | 25,964 |
def process_input(values, puzzle_input, u_input):
"""Takes input from the user and records them in the location specified
by the "value", and returns the resulting puzzle input
"""
puzzle_input[values[0]] = u_input
return puzzle_input | 300c0850afa977d738f5a5ebbcb1b36ccd557b23 | 25,965 |
import json
def init_store():
"""
Function to initialize the store listener.
Parameters
----------
Returns
-------
dict
request response
"""
challenge_id = str(request.form.get('challenge_id'))
flag =... | c7c3c6d9f3b645edfdcf82a4fd9cdbf1abd62b01 | 25,966 |
def PyLong_AsSsize_t(space, w_long):
"""Return a C Py_ssize_t representation of the contents of pylong. If
pylong is greater than PY_SSIZE_T_MAX, an OverflowError is raised
and -1 will be returned.
"""
return space.int_w(w_long) | c0d64c9be4333a0d40133478bcc5fcad221d0efc | 25,967 |
import os
def validate_prmtop(prmtop, target_dir=None, override=False):
"""
Check that file exists and create a symlink if it doesn't have a
prmtop extension (often *.top is used but mdtraj cant't detect type
with ambiguous extensions).
Parameters
----------
prmtop : str
Path to s... | 08763ed68a822069274177bc7ecb27521ec231b0 | 25,968 |
from typing import List
from typing import Tuple
import os
def make_dataset(image_fp: List[str], titles: List[str], im_size: Tuple[int, int], batch_size: int) -> tf.data.Dataset:
"""
Parameters
----------
image_fp: List[str]
List of image filepaths.
titles: List[str]
List of book ... | a6805a9730b4698c3df7506172ba668cac9fd29e | 25,969 |
import requests
def getssa_handler() -> Response:
"""Software Statement Assertion retrieval"""
if request.method == 'POST':
try:
r = requests.get(
'{}/tpp/{}/ssa/{}'.format(
cache.get('tpp_ssa_url'),
cache.get('tpp_id'),
... | ddf9c7538c12073906caf934eba07995dd6ab590 | 25,970 |
import copy
def dataTeapotShallow():
"""
Values set interactively by Dave Hale. Omit deeper samples.
"""
txf = [
30, 69,0.50, 99, 72,0.50,
63, 71,0.90, 128, 72,0.90,
29,172,0.35, 97,173,0.35,
63,173,0.75, 127,174,0.75,
33,272,0.20, 103,270,0.20,
70,271,0.60, 134,268,0.60]
n = len(t... | ef03e417424d975b24e258741c57db319f918ac1 | 25,971 |
from pathlib import Path
def count_labels(l_path, selected_class,num_workers=4):
"""Calculate anchor size.
Args:
l_path: path to labels.
selected_class: class to be calculated.
Returns:
(w, l, h)
"""
def count_single_label(label_file):
size = []
z_axis = []
... | e027ace155e6b7ca83dc98b7b0191109ca12420d | 25,972 |
def sorted_chromosome(all_samples):
"""
sorted_chromosome(AllSamples) -> list
:return: list of chromosome found in all samples
"""
sorted_chromosome_list = sorted(all_samples.chr_list.keys())
print(sorted_chromosome_list)
return sorted_chromosome_list | c1e49ac974e16c7f9b69581442186c3efc23ef70 | 25,973 |
def adjust_bb_size(bounding_box, factor, resample=False):
"""Modifies the bounding box dimensions according to a given factor.
Args:
bounding_box (list or tuple): Coordinates of bounding box (x_min, x_max, y_min, y_max, z_min, z_max).
factor (list or tuple): Multiplicative factor for each dimen... | 93a3c5947cb7c3335421084092dbae8840f8164b | 25,974 |
def round_dt64(t,dt,t0=np.datetime64("1970-01-01 00:00:00")):
"""
Round the given t to the nearest integer number of dt
from a reference time (defaults to unix epoch)
"""
return clamp_dt64_helper(np.round,t,dt,t0) | 5e3695993110f875cc62402a770c9cb56ff9e544 | 25,975 |
def distill_base():
"""Set of hyperparameters."""
# Base
hparams = common_hparams.basic_params1()
# teacher/student parameters
hparams.add_hparam("teacher_model", "")
hparams.add_hparam("teacher_hparams", "")
hparams.add_hparam("student_model", "")
hparams.add_hparam("student_hparams", "")
# Distill... | 7bbf85971e0323282a801c7db4e646f7b745d453 | 25,976 |
def authorize(*args, **kwargs):
"""Handle for authorization of login information."""
next_url = url_for('oauth.authorize', **{
'response_type': request.args.get('response_type'),
'client_id': request.args.get('client_id'),
'redirect_uri': request.args.get('redirect_uri'),
'scope'... | e38b958567b9fa7427c2b3dd7b04cabadbbf4a8c | 25,977 |
def summary_stats(r, riskfree_rate=0.027):
"""
Return a DataFrame that contains aggregated summary stats for the returns in the columns of r
"""
ann_r = np.round(r.aggregate(annualize_rets, periods_per_year=4), 2)
ann_vol = np.round(r.aggregate(annualize_vol, periods_per_year=4), 2)
ann_sr = np.... | 230534298d907d0bff9dd843d14e3a6c5481ddbf | 25,978 |
def mid_longitude(geom: Geometry) -> float:
"""Return longitude of the middle point of the geomtry."""
((lon,), _) = geom.centroid.to_crs("epsg:4326").xy
return lon | ada60c2b72fc36af7d37cd3e063d0154484727d0 | 25,979 |
def unique_count_weight(feature):
"""Normalize count number of unique values relative to length of feature.
Args:
feature: feature/column of pandas dataset
Returns:
Normalized Number of unique values relative to length of feature.
"""
return len(feature.value_counts()) / len(featu... | 0345208cd7d9d4bc2303db377206e5362db6cdde | 25,980 |
def mode_glass(frame_bg, frame_fg, args_glass):
"""
Description: In glass mode, your eyes will be located with a pair of glass.
Params:
frame_bg: The background layer.
frame_fg: The canvas layer.
args_glass: The arguments used in glass mode.
"""
frame_bg = wear_glasses.wear_g... | 4f2957a1aed66383fe2f8ea394fb4fca0f2ba550 | 25,981 |
def line_meshes(verts, edges, colors=None, poses=None):
"""Create pyrender Mesh instance for lines.
Args:
verts: np.array floats of shape [#v, 3]
edges: np.array ints of shape [#e, 3]
colors: np.array floats of shape [#v, 3]
poses: poses : (x,4,4)
Array of 4x4 transform... | 22b5fa7aaa475e56bcb120427437881f4fa28209 | 25,982 |
import math
def isPrime(n):
"""
check if the input number n is a prime number or not
"""
if n <= 3:
return n > 1
if n % 6 != 1 and n % 6 != 5:
return False
sqrt = math.sqrt(n)
for i in range(5, int(sqrt)+1, 6):
if n % i == 0 or n % (i+2) == 0:
return Fa... | 91da5b13840181d039902e2db3efb8cc09609465 | 25,983 |
def seqprob_forward(alpha):
"""
Total probability of observing the whole sequence using the forward algorithm
Inputs:
- alpha: A numpy array alpha[j, t] = P(Z_t = s_j, x_1:x_t)
Returns:
- prob: A float number of P(x_1:x_T)
"""
prob = 0
##########################################... | edc24df276db1e4d0ffcdd51231036f1dc1eadaa | 25,984 |
def center_filter(gt_boxes, rect):
"""
过滤边框中心点不在矩形框内的边框
:param gt_boxes: [N,(y1,x1,y2,x2)]
:param rect: [y1,x1,y2,x2]
:return keep: 保留的边框索引号
"""
# gt boxes中心点坐标
ctr_x = np.sum(gt_boxes[:, [1, 3]], axis=1) / 2. # [N]
ctr_y = np.sum(gt_boxes[:, [0, 2]], axis=1) / 2. # [N]
y1, x1,... | 3a9d946789b1ee2de732f6cc29970d0fdf051e1f | 25,985 |
def named_entities(s, package="spacy"):
"""
Return named-entities.
Use Spacy named-entity-recognition.
PERSON: People, including fictional.
NORP: Nationalities or religious or political groups.
FAC: Buildings, airports, highways, bridges, etc.
ORG: Companies, agencies, inst... | 239f7f4887ee72ac5f698b2b32098019ccde3965 | 25,986 |
def get_premium_client():
"""Get a connection to the premium Minio tenant"""
return __get_minio_client__("premium") | f6c28453e7f04835c2dd2c91458712c7c80f3ded | 25,987 |
from typing import List
from typing import Tuple
import os
def get_all_versions(lang: str) -> List[Tuple[int, int, int]]:
"""Return the list of version available for a given lang"""
versions = []
for filename in os.listdir(GRAMMAR_PACKAGE):
match = VERSION_REGEX.match(filename)
if match:
... | 5ae335241ec8d364f6e7a3898aa08bbf5f0d6ff1 | 25,988 |
def chunk_sample_text(path: str) -> list:
"""Function to chunk down a given vrt file into pieces sepparated by <> </> boundaries.
Assumes that there is one layer (no nested <> </> statements) of text elements to be separated."""
# list for data chunks
data = []
# index to refer to current chunk
... | 6e6c36db38383283bd6076f0b6b346dcfd608243 | 25,989 |
from typing import Dict
def describe_dag_diffs(x, y):
"""Returns a list of strings describing differences between x and y."""
diffs = []
# A pair of dictionaries mapping id(x_val) or id(y_val) to the first path at
# which that value was reached. These are used to check that the sharing
# stucture of `x` a... | 4e3a767af9dd64b119111860a039a99b2b210a0f | 25,990 |
def ec_cert(cert_dir):
"""Pass."""
return cert_dir / "eccert.pem" | 71cf6d98b05e4fc80515936d7aedc6f184fbe0a6 | 25,991 |
from datetime import datetime
def get_expiries(body):
"""
:type body: BeautifulSoup
"""
_ex = body.find_all('select', {'id': 'date', 'name': 'date'})
ex = []
for ch in _ex:
for _e in ch:
try:
ex.append(datetime.strptime(_e.text, '%d%b%Y').date())
... | 09d7f067aa283ff930151b129378785dcbc17b09 | 25,992 |
def _add_experimental_function_notice_to_docstring(doc):
"""Adds an experimental notice to a docstring for experimental functions."""
return decorator_utils.add_notice_to_docstring(
doc, '',
'EXPERIMENTAL FUNCTION',
'(experimental)', ['THIS FUNCTION IS EXPERIMENTAL. It may change or '
... | 449ab32b4ddae2d383776d0c90dbc56dc6041da6 | 25,993 |
def format_args(args):
"""Formats the command line arguments so that they can be logged.
Args:
The args returned from the `config` file.
Returns:
A formatted human readable string representation of the arguments.
"""
formatted_args = "Training Arguments: \n"
args = args.__dict_... | 22d4334daba7cdfd77329f5a6de93a2411f0594d | 25,994 |
import uuid
def generate_id() -> str:
"""Generates random string with length of `ID_LENGTH`"""
return int_to_base36(uuid.uuid4().int)[:LENGTH_OF_ID] | 8cf317741edf02ca79ef72bf51c7958877a98d98 | 25,995 |
def getHG37PositionsInRange(chromosome, startPos, endPos):
"""Return a DataFrame containing hg37 positions for all rsids in a range.
args:
chromosome (int or str): the chromosome number
startPos (int or str): the start position on the chromosome
endPos (int or str): the ... | 64107a375588737e6fedcd336fe5d1a648a93efc | 25,996 |
def spherical_from_cart_np(xyz_vector):
"""
Convert a vector from cart to spherical.
cart_vector is [idx][x, y, z]
"""
if len(xyz_vector.shape) != 2:
xyz_vector = np.expand_dims(xyz_vector, axis=0)
expanded = True
else:
expanded = False
sph_vector = np.zeros(xyz_vect... | 86da4d3426b6327c5fd00f431e36655b9213a027 | 25,997 |
def _execute_query(connection, query):
"""Executes the query and returns the result."""
with connection.cursor() as cursor:
cursor.execute(query)
return cursor.fetchall() | 9f71eb650d323f7a5ead3451810a7b9f9d77b4b0 | 25,998 |
def mediaValues(x):
"""
return the media of a list
"""
return sum(x)/len(x) | ab4a436d3383e5df7d8d891c9661eabb0af81ef8 | 25,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.