content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def pad_image(immy,down_factor = 256,dynamic=False):
"""
pad image with a proper number of 0 to prevent problem when concatenating after upconv
Args:
immy: metaop that produces an image
down_factor: downgrade resolution that should be respected before feeding the image to the network
... | fca01d0bf8cc8c036f1d54d7cde253ffba8f6877 | 3,608,257 |
from typing import Sequence
def remote_cpp_executor_factory(
channels: Sequence[executor_bindings.GRPCChannel],
default_num_clients: int = 0) -> executor_factory.ExecutorFactory:
"""ExecutorFactory backed by C++ Executor bindings."""
py_typecheck.check_type(default_num_clients, int)
def _executor_fn(
... | 05d848cbe1375c9a2a89fb6f31c9aef7daa0fdad | 3,608,258 |
import logging
def remove_extr_freq(corpus, high=0.999, low=5):
"""Removes words with very high and very low frequency
Args:
corpus: tokenised documents
high: high-cile in the token frequency distribution
low: minimum number of occurrences in the corpus
Returns:
A filtered ... | 05c7282a9312575bccd4f76420cb7b3aa5c89c56 | 3,608,260 |
def parse_file(filepath: str) -> list:
"""Parsing content of specified file
:param filepath: Path to file with content for parsing
:type filepath: str
:rtype: list
:raises: ParseException
"""
parsed = create_grammar().parseFile(filepath, parseAll=True)
return parse_tokens(parsed) | 8b8d77caca637db7cfd84e550999ce2ec03fc2f6 | 3,608,261 |
def publication_email_article_do_not_send_list():
"""
Return list of do not send article DOI id
"""
do_not_send_list = [
"00003", "00005", "00007", "00011", "00012", "00013", "00031", "00036", "00047", "00048",
"00049", "00051", "00065", "00067", "00068", "00070", "00078", "00090", "000... | 30b813490c3ccd076fc59dd2090c9861f3ab495f | 3,608,262 |
import types
import numpy
def hpat_pandas_series_count(self, level=None):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.Series.count
Limitations
-----------
Parameter ``level`` is currently unsupported.
Examples
... | 5768f63b7dbfaaeeef5b583cbdf0dcb0dd77ab34 | 3,608,263 |
import urllib
import json
def get_list_of_titled_players(title):
"""
Downloads a list of players with specified title on Chess.com
:param title: The desired title to use for getting player list
:return list_of_users: Returns the list of all users with this title on Chess.com
"""
try... | 70bd5cde6c5cefb923662e10f147adff1d7d39a0 | 3,608,264 |
def disconnect_handler(event):
""" Handle disconnections from WS"""
print("Handling disconnection")
connection_id = event['requestContext']['connectionId']
print(f"From {connection_id}")
murd.delete([MurdMemory(ROW="ws_connections",
COL=connection_id)],
id... | eb82061b1ea485319c5e62f4354860e918f7e94d | 3,608,266 |
def sanity_check_model():
"""
Bare Bones model with one no hidden layer i.e flattened input features
directly connected to output node.
This model is suppose to be used when building pipeline with minimum focus on model
performance.
Returns
---------
keras model
"""
# Initial... | 30522cdd5a33dde523ccd40eb6e9bf47dc44547f | 3,608,267 |
import urllib
def _make_hostport(conn, default_host, default_port, default_user='', default_password=None):
"""Convert a '[user[:pass]@]host:port' string to a Connection tuple.
If the given connection is empty, use defaults.
If no port is given, use the default.
Args:
conn (str): the string ... | b4c99d41435298bdb8badd2294585d073b9a1db4 | 3,608,268 |
import urllib
def getChipForYearByTargetDay(lng, lat, year, day, vis):
"""
get image chip for specified year for plot coordinate.
"""
values = {}
try:
values = getLandsatChipForYearByTargetDay(
(float(lng), float(lat)), year, day, vis)
fp = urllib.request.urlopen(value... | 7268fd5bfbfb04cd43b4eb02050bd8903ce1739d | 3,608,272 |
def make_uniform(dim=2,depth=6,Data=None,xmin=None,xmax=None,**kargs):
"""
Helper function to construct a full tree.
Parameters
----------
nleaves : int
Number of leaves to add to the tree
dim : int
Number of dimensions of the tree
depth : int
The depth of the tree
... | 0047a4d711b4d532831b3f38ddf4025485116f67 | 3,608,273 |
def get_latest_applied_migrations_qs(
connection_obj=None,
) -> "QuerySet[MigrationRecorder.Migration]":
"""Return latest applied migration in all django apps in project"""
if connection_obj is None:
connection_obj = connection
recorder = MigrationRecorder(connection_obj)
migration_qs = reco... | 5723a043416128ec5463d1bbefc881869d7a5c07 | 3,608,274 |
def get_filter(image_file):
""" Read in the filter used on the instrument and get its simple
name.
"""
with fits.open(image_file) as hdu:
prime_header = hdu['PRIMARY'].header
sci_header = hdu['SCI'].header
filter2 = prime_header['FILTER2']
if 'i' in filter2:... | 988273b4f110430ceb2c1d1eb6b861fb79595436 | 3,608,275 |
def compute_score(model, query):
"""Compute and return activity likeness for given query molecule.
"""
fingerprint = compute_representation(query)
return max([similarity_tannimoto(fingerprint, ligand)
for ligand in model]) | 12713c7d84452a302ce4ae8daabf3a014260341e | 3,608,276 |
def _bookmark_name(bookmark):
"""
Given a bookmark dictionary, return back the name of that bookmark. If the
bookmark has no defined name, one will be returned.
"""
if bookmark is None:
return "No bookmark"
if "name" in bookmark:
return bookmark["name"]
pkg_info = help_inde... | b7b3c7aea19740424d121360dc4aef533beabf80 | 3,608,277 |
import base64
import json
def encode_transaction(value):
"""Encode a transaction (dict) to Base64."""
return base64.b64encode(json.dumps(value).encode('utf8')).decode('utf8') | 066fa737b9c2d474be500bf2006ce43adea8d4f8 | 3,608,278 |
def getRawSegments(music21Part, segmentBreaks=SEGMENT_SEGMENTBREAKS):
"""
Takes in a :class:`~music21.stream.Part` and a segmentBreaks list which
contains (measureNumber, offsetStart) tuples. These tuples determine how
the Part is divided up into segments (i.e. instances of
:class:`~music21.braille... | 2a64bb74d41e02fb6262fe0dbbefe011b41b3b07 | 3,608,279 |
def calcAutoArea(img, imn, colourrange, hmatrix=None, threshold=None,
invprojvars=None):
"""Detects areas of interest from a given image, and returns pixel and xyz
areas along with polygon coordinates. Detection is performed from the image
using a predefined RBG colour range. The colour ... | 7b0fea6ddd26ca33c12205a65788beb754416f25 | 3,608,280 |
def _transitive_closure_dense_numpy(A, kind='metric', verbose=False):
"""
Calculates Transitive Closure using numpy dense matrix traversing.
"""
C = A.copy()
n,m = A.shape
# Check if diagonal is all zero
if sum( np.diagonal(A) ) > 0:
raise ValueError("Diagonal has to be zero for matrix computation to be corr... | 41c237ae9d702d69e0e96ea3e812882afab0cfc1 | 3,608,282 |
from typing import Union
import logging
def get_azure_auth(azure_config: AzureConfig) -> Union[DefaultAzureCredential, ClientSecretCredential]:
"""
Returns the authentication object for the azure.identity library,
based on either the chosen Service Principal (if set, and if the password was found), or the... | f2e39c8250622c17f47319fa9aa0e417ffe181f1 | 3,608,283 |
def residual_transformation(
model,
blob_in,
dim_in,
dim_out,
stride,
prefix,
dim_inner,
dilation=1,
group=1,
):
"""Add a bottleneck transformation to the model."""
# weight_init = None
# weight_init = ('XavierFill', {})
weight_ini... | 2fc21653e4787b7732910d466005ff67c6c61622 | 3,608,286 |
def tfConfigSetup():
"""
:return: Returns tensorflow configuration.
"""
tf_config = tf.ConfigProto(allow_soft_placement=False)
tf_config.gpu_options.allow_growth = True
tf_config.gpu_options.polling_inactive_delay_msecs = 50
return tf_config | 4592291aee5c0d3edb36b899623c7cccffdbee3b | 3,608,287 |
def toposort(dependencies):
"""Returns a tuple of the dependencies dictionary keys sorted by entries
in the dependency lists. Given circular dependencies, sort will impose
an order. Raises MissingDependency if a key is not found.
"""
s = Sorter(dependencies)
return s.sort() | 78c7ba3f56b4ba9e8c03aa953a8ab3ce3eed223a | 3,608,288 |
import random
def shuffle_sequence(sequence):
"""Shuffle sequence.
Parameters
----------
sequence : str
Sequence to shuffle.
Returns
-------
str
Shuffled sequence.
"""
shuffled_sequence = list(sequence)
random.shuffle(shuffled_sequence)
return "".j... | 1acb94516a6ed491359538f2016a22fc6d613499 | 3,608,289 |
def createBorder(image=None,color=(255,255,255),lineThickness=3):
"""
Creates border on the canvas
Arguments:
image = 3D Numpy array; image on which the border has to be added
color = (B,G,R); color of the border
lineThickness = integer; thickness of the border
"""
# If image... | 5f03ce8abf455b5b0d6d97a47fd57fec20d4d745 | 3,608,290 |
def barcode_reader():
"""Barcode code obtained from 'brechmos'
https://www.raspberrypi.org/forums/viewtopic.php?f=45&t=55100"""
hid = {4: 'a', 5: 'b', 6: 'c', 7: 'd', 8: 'e', 9: 'f', 10: 'g', 11: 'h', 12: 'i', 13: 'j', 14: 'k', 15: 'l', 16: 'm',
17: 'n', 18: 'o', 19: 'p', 20: 'q', 21: 'r', 22: '... | a25c83491cbdce81f4f353f23ed808c30d5f8117 | 3,608,291 |
def enable_cloud_admin_access(session, confirm, return_type=None, **kwargs):
"""
Enables the ability of a storage cloud administrator to access the VPSA
GUI of this VPSA to assist in troubleshooting. This does not grant access
to any volume data. Enabled by default.
:type session: zadarapy.sessio... | 5444ba9f4c917a72c666908bcd4db3b8527d596c | 3,608,292 |
import hashlib
def get_icon_hash(fp, fp_name):
"""Returns a file's hashed, fp is passed as a string"""
sha1 = hashlib.sha1(fp)
return sha1.hexdigest() | 89ecd2292384cf255ecd41bd80006eafbbd13bd9 | 3,608,294 |
def delete_like_feed(id_feed:int, user:User):
"""
Method to dislik feed
:param id_feed: id feed
:type id_feed: int
:param user: user who dislike
:type user: User
"""
try:
like_feed = likes_models.LikeFeed.objects.get(feed__id=id_feed, user=user)
like... | 46805967e5044e7b7652ffa478ee3dfffd8ede18 | 3,608,295 |
def get_collapsed_file_name(psl_point: TPslPoint) -> str:
"""
Create unique file name for collapsed PSL points
"""
file_name = dut_top + psl_point["name"].split(dut_top)[-1]
file_name = file_name.replace(".", "_")
file_name = file_name.replace(" ", "_")
file_name = file_name.replace(")", "_"... | f86345e9b462d1d63f9688f1b54237994d605bc4 | 3,608,296 |
def affine_stddev(sr: pd.Series):
"""function for calculating standard deviations of affine values"""
d = sr - affine_mean(sr)
u = d / np.array(1, dtype=d.dtype)
s = np.sqrt(np.sum(u**2))
return s * np.array(1, dtype=d.dtype) | 4dcf756e15e518e345e024dd1e6ef73132a3f088 | 3,608,299 |
import math
def get_angle(p1, a1, p2) -> float:
"""
Izračunaj kot, za katerega se mora zavrteti robot, da bo obrnjen proti točki p2.
Robot se nahaja v točki p1 in ima smer (kot) a1.
"""
a = math.degrees(math.atan2(p2.y-p1.y, p2.x - p1.x))
a_rel = a - a1
if abs(a_rel) > 180:
if a_re... | 93ad2d8b1a8a98e1669f2b9c1553e507850f0384 | 3,608,300 |
def get_mnist_loader(batch_size, classes=[9, 4], n_items=5000, proportion=0.9, n_val=5, mode='train'):
"""Build and return data loader."""
dataset = MNISTImbalanced(classes=classes, n_items=n_items, proportion=proportion, n_val=n_val,mode=mode)
shuffle = False
if mode == 'train':
shuffle = Tru... | eb49de9693f9a2fc1c8a9681353c897bab259935 | 3,608,301 |
from typing import Iterable
from typing import Mapping
from typing import Set
def is_ordered_sequence(caster):
"""Caster can be ordered sequence of another casters."""
return (isinstance(caster, Iterable)
and not isinstance(caster, (Mapping, Set))) | cbefae7359f112b5ab13f377b3c9552d286d14d0 | 3,608,302 |
def entityRegister(name, type="business", subtype=0, ipfsData=None):
"""
Build an entity registration.
Arguments:
name (str): entity name
type (str): entity type. Possible values are `business`, `product`,
`plugin`, `module` and `delegate`. Default to `business`.
subtype... | 37c0926f14839b6e9d97f839d07585d3e10cbdac | 3,608,303 |
def isiterable(obj: any) -> bool:
"""Check if the input is iterable.
Note that this function does not capture all possible cases
and is subject to change in the future if issues arise.
Parameters
----------
obj
The object to check.
Returns
-------
bool
True if the o... | 840ddab4fc1d50fa7de40c6dccd2d6dc9bffc4cb | 3,608,304 |
def get_ipv4_network(cidrs):
"""Get the IPv4 network from the given CIDRs or None"""
return {net.version: net for net in get_networks(cidrs)}.get(4) | d1cedc434419f845bdd59d880c651c0580995f7b | 3,608,305 |
def get_case_for_doc(doc):
"""Retrieves case for a document.
"""
s = """SELECT * FROM cases WHERE id=?"""
db.cursor.execute(s, (doc['case_id'],))
rows = db.cursor.fetchone()
if not rows:
return None
else:
return db._convert_to_cases_dict([rows])[0] | be5e36900348217cb12e765b6d8f45eefdd85eb4 | 3,608,306 |
def read_data(path, actuals=False):
"""
Read fcst and actuals arrays from disc
"""
with Resource(path) as f:
fcst = f['fcst']
if actuals:
acts = f['actuals']
if actuals:
return fcst, acts
else:
return fcst | e22df659915d962e57bfb26bcfce4a11fe4ed7b7 | 3,608,307 |
import unicodedata
def clean_for_search(text_html):
""" Clean up for searching """
text_html = to_unicode(text_html)
text = remove_html(text_html).replace('\n',' ').lower() # Remove html, line breaks, and make lower case
text = unicodedata.normalize('NFKD', text).encode('ascii','ignore') # https://www... | 84ff49fffa92859f65d2296ea8c556a9a4268e4e | 3,608,308 |
def broken_track():
"""Mark a track as broken for later investigation."""
youtube_id = request.form['youtube_id']
name = request.form['name']
Track.save_broken_track(youtube_id, name)
return Response() | 186606417c89d3dddefa21f559f152ee460f22f9 | 3,608,309 |
def _height_metrics(box_center_z, box_height, boxes_center_z, boxes_height):
"""Compute 3D height intersection and union between a box and a list of boxes.
Args:
box_center_z: A scalar.
box_height: A scalar.
boxes_center_z: A Numpy array of size [N].
boxes_height: A Numpy array of size [N].
Retu... | ec18243b9da72b82f4c8f8075b9c17ea2f73eff9 | 3,608,310 |
def _inv_QR(M, iszerofunc=_iszero):
"""Calculates the inverse using QR decomposition.
See Also
========
inv
inverse_ADJ
inverse_GE
inverse_CH
inverse_LDL
"""
_verify_invertible(M, iszerofunc=iszerofunc)
return M.QRsolve(M.eye(M.rows)) | 84fa6910bebe0bb598bd0acb899ed8e281dec132 | 3,608,311 |
import re
def parseQuestion(sentence, translate_language='Translate Here...'):
"""
parse sentence and return correct answer for each gap
"""
sentence = sentence.replace("{", "[").replace("}", "]")
gaps = re.findall(r"[^[]*\[([^]]*)\]", sentence)
first_option = gaps[0].split('|')[0]
# text... | 982a560bd15c00f49322242e970a8c366f0ec3fd | 3,608,312 |
from datetime import datetime
def _purge_legacy_format(
instance: Recorder, session: Session, purge_before: datetime, using_sqlite: bool
) -> bool:
"""Purge rows that are still linked by the event_ids."""
(
event_ids,
state_ids,
attributes_ids,
data_ids,
) = _select_leg... | ec0e5337dd43cc41882237b9b3fedd775e7aef38 | 3,608,313 |
def summary(value_dict, global_step, writer):
"""Make tf.Summary for tensorboard"""
summary = tf.Summary(value=[tf.Summary.Value(tag=k, simple_value=v) for k, v in value_dict.items()])
writer.add_summary(summary, global_step)
return None | 4f435aaf8277e22ac8fa6d7b320a73c42335367d | 3,608,314 |
def inference_network(x, latent_dim, hidden_size):
"""Construct an inference network parametrizing a Gaussian.
Args:
x: A batch of MNIST digits.
latent_dim: The latent dimensionality.
hidden_size: The size of the neural net hidden layers.
Returns:
mu: Mean parameters for the variational family N... | a2c2d5f461a9bd0787309fe838a5da05fae057f5 | 3,608,315 |
import torch
def align(src_tokens, tgt_tokens):
"""
Given two sequences of tokens, return
a mask of where there is overlap.
Returns:
mask: src_len x tgt_len
"""
mask = torch.ByteTensor(len(src_tokens), len(tgt_tokens)).fill_(0)
for i in range(len(src_tokens)):
for j in ra... | 0408ae7148c4bed9e3c24b71acdbd1a182dd6e69 | 3,608,316 |
import logging
def apply_change_list(question_id, change_list):
"""Applies a changelist to a pristine question and returns the result.
Args:
question_id: str. ID of the given question.
change_list: list(QuestionChange). A change list to be applied to the
given question. Each entry... | 16df354a6096b96c915e167b0c4b8e059b77de57 | 3,608,317 |
def set_identity_pool_roles(
IdentityPoolId,
AuthenticatedRole=None,
UnauthenticatedRole=None,
region=None,
key=None,
keyid=None,
profile=None,
):
"""
Given an identity pool id, set the given AuthenticatedRole and UnauthenticatedRole (the Role
can be an iam arn, or a role name) ... | 6ebcd259d901094474bcf867cd018487b318ac56 | 3,608,318 |
from typing import Any
def is_listy(x: Any) -> bool:
"""
Grabbed this from fast.ai
"""
return isinstance(x, (tuple, list)) | 331791b4d1e1f4047ab99b54a58441805bc71311 | 3,608,319 |
def ResolveApiInfoFromFlags():
"""Determine an api and api_version."""
api_version = FLAGS.api_version
api = FLAGS.api
return {'api': api, 'api_version': api_version} | 0978fd96017ce1e8870407f0e5eb1e706c7a7a72 | 3,608,320 |
import psutil
def get_disk_space(path: str) -> tuple:
"""_summary_
Args:
path (str): _description_
Returns:
tuple: _description_
"""
usage = psutil.disk_usage(path)
space_total = bytes2human(usage.total)
space_used = bytes2human(usage.used)
space_free = bytes2human(us... | 77c9b16441703d6a1644e28fb5dd5a4c9f91790d | 3,608,321 |
def lnglat_to_meters(longitude, latitude):
"""
Projects the given (longitude, latitude) values into Web Mercator
coordinates (meters East of Greenwich and meters North of the
Equator).
Longitude and latitude can be provided as scalars, Pandas columns,
or Numpy arrays, and will be returned in th... | 20540a5c2cf74ee0b8a2c01f3daa2cd32dcdd369 | 3,608,322 |
def _scrub_parameters(parameters):
"""Returns a scrubbed list of RayParameters."""
return [
RayParameter(
name=param.name,
kind_int=_convert_from_parameter_kind(param.kind),
default=param.default,
annotation=param.annotation,
partial_kwarg=para... | 19029bf360c8061e56a0287527e4d90779be1da7 | 3,608,323 |
def get_parsers(klass, key):
"""Return tuple of 2 parsers related to current key and class"""
fulltext_parser = get_fulltext_parsed_value(klass, key)
if fulltext_parser:
if isinstance(fulltext_parser, DatetimeValue):
return (fulltext_parser, None)
else:
return (None, fulltext_parser)
columns... | 69c68d9cdf1ed03abe829884c9a0511a73cc906c | 3,608,324 |
def create_alert():
"""
Create an alert. Must be an advocate.
"""
form = AlertForm()
if not form.validate_on_submit():
return api_error(form.errors)
send_out_alert(form)
return '', 201 | 35770137480d27b0e91c1abd2f354980cd873b5c | 3,608,325 |
def register_env(name):
"""Registers a env by name for instantiation in plaidrl."""
def register_env_fn(fn):
if name in ENVS:
raise ValueError("Cannot register duplicate env {}".format(name))
if not callable(fn):
raise TypeError("env {} must be callable".format(name))
... | 0efde537098dfdb92d67ae6d77615c79998c12a0 | 3,608,326 |
from re import T
def acl():
"""
Preliminary controller for ACLs
for testing purposes, not for production use!
"""
table = auth.permission.table
tablename = table._tablename
table.group_id.requires = IS_ONE_OF(db, "auth_group.id", "%(role)s")
table.group_id.represent = lambda o... | fd23fbae798f34bd9a5652d87d5c33025d8cef77 | 3,608,327 |
import torch
def real(a: torch.Tensor):
"""Real part."""
if is_real(a):
raise ValueError('Last dimension must have length 2.')
return a[..., 0] | 19f81a29a404c232de9a837509a96f84a80fc07b | 3,608,328 |
from pathlib import Path
from typing import Dict
import yaml
def _load_yaml_doc(path: Path) -> Dict:
"""Load a yaml document."""
with open(path, "r") as src:
doc = yaml.load(src, Loader=yaml.FullLoader)
return doc | 4b049909c5e6eac6e7772b3311f928ccd6cf528c | 3,608,329 |
def welcome():
"""List all available api routes."""
return (
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/datesearch/<start><br/>"
f"/api/v1.0/datesearch/<start>/<end>"
) | b9d63139680f5bd41349c34642ca4d1608542978 | 3,608,330 |
import binascii
def encrypt(bdata, encr_key):
"""
Encrypt some data.
"""
# Enhance user password with PBKDF2
pwd = PBKDF2(password=encr_key, salt='^0Twister-Salt9$', dkLen=32, count=100)
crypt = AES.new(pwd)
pad_len = 16 - (len(bdata) % 16)
padding = (chr(pad_len) * pad_len)
# Encr... | 167b5e1e72466a5a02f491dda1bd6e116a70d1a9 | 3,608,331 |
from typing import Iterable
from typing import List
def get_all_dangling(nodes: Iterable[AbstractNode]) -> List[Edge]:
"""Return the set of all dangling edges."""
edges = []
for node in nodes:
edges += node.get_all_dangling()
return edges | 64624655a4f53a673e437fc08f4cc781931aeb56 | 3,608,332 |
def parse_reroute_domain_query(project_id, dataset_id, dest_table):
"""
This function generates a query that reroutes the records from all domain tables for the given dest_table.
It uses _mapping_alignment_table to determine in which domain table the records should land.
:param project_id: the project_... | bc7379b2eae3fb31ba8a3157220ff8e0baa35f21 | 3,608,333 |
def getFloat (Float):
"""
Float input verification
usage: x = getFloat ('mensage to display ')
"""
while True:
try:
user_input = float(input(Float))
return user_input
except ValueError:
print('Use only numbers and separete decimals with point') | 27d9128441cadd00627d88bbfdb45144bf5a55f3 | 3,608,334 |
def histogram_of_pixel_projection(img):
"""
This method is responsible for licence plate segmentation with histogram of pixel projection approach
:param img: input image
:return: list of image, each one contain a digit
"""
# list that will contains all digits
character_list_image = list()
... | 8f3c528557ca44b76f4b534fa1c42912ebb06a12 | 3,608,335 |
def head_status(request, persistence):
"""Respond with OK."""
return web.Response() | c19fbd1ba01ecc855ffd9e0106e005430b6a679c | 3,608,337 |
def Cl_flat_plate(alpha, Re_c):
"""
Returns the approximate lift coefficient of a flat plate, following thin airfoil theory.
:param alpha: Angle of attack [deg]
:param Re_c: Reynolds number, normalized to the length of the flat plate.
:return: Approximate lift coefficient.
"""
Re_c = cas.fab... | fd7e976819a50cfd951e9df90ebf11adbd63aae9 | 3,608,338 |
import warnings
def weight_list(spam, weights, warn=True):
""" Returns weighted list
Args:
spam(list): list to multiply with weights
weights (list): of weights to multiply the respective distance with
warn (bool): if warn, it will warn instead of raising error
Returns:
(l... | 6b2258675a5c346c50ecc8f7d8aba466a7b216ef | 3,608,340 |
import tqdm
def jitter(traces, exp=1):
"""
Simulates jitter using the given rate parameter. Applies it to the supplied traces.
"""
res = np.zeros_like(traces)
for ix in tqdm(range(len(traces)), desc=f"Applying jitter with exp={exp}"):
res[ix] = jitter_trace(traces[ix], exp)
return re... | 1f43057936ca3f9bab0242798b0e4f5961f001c2 | 3,608,341 |
def harvest_index(prof, Soil_zTop, Crop, InitCond, Et0, Tmax, Tmin, GrowingSeason):
"""
Function to simulate build up of harvest index
<a href="../pdfs/ac_ref_man_3.pdf#page=119" target="_blank">Reference Manual: harvest index calculations</a> (pg. 110-126)
*Arguments:*
`Soil`: `SoilClass` : ... | 1406c3416cbdadcdd454397b42fd69e4459ea521 | 3,608,342 |
from astropy.nddata.ccddata import _generate_wcs_and_update_header
from reproject import reproject_interp
def wcs_project(ccd, target_wcs, target_shape=None, order='bilinear'):
"""
Given a CCDData image with WCS, project it onto a target WCS and
return the reprojected data as a new CCDData image.
Any... | 663ef4893de19c51a8a2be0e030db1c237252e91 | 3,608,343 |
from typing import Callable
import click
def test_env_run_option(command: Callable[..., None]) -> Callable[..., None]:
"""
A decorator for choosing whether to run commands in a test environment.
"""
function = click.option(
'--test-env',
'-te',
is_flag=True,
help=(
... | 33de24e435aa258f8bd3474ee2ca3a3358651584 | 3,608,344 |
def get_paged_jobs(rc, url, basic_auth, cafile, tower_job_status_list, last_update_epoch):
"""
get jobs results, returning paged results
:param rc: RequestsCommon
:param url:
:param basic_auth:
:param cafile:
:param tower_job_status_list: list of pending, failed, successful
:param last_u... | 803c902a7cdd90a7b5179c7e8b5bf17289f99663 | 3,608,345 |
import types
def _prepare_schema(
*, schema: types.Schema, schemas: types.Schemas, array_context: bool = False
) -> types.Schema:
"""
Check and transform readOnly schema to consistent format.
Args:
schema: The readOnly schema to operate on.
schemas: Used to resolve any $ref.
a... | ef42166792b23a424ee43a073b51917916ca3443 | 3,608,346 |
def rinex_name(station, year, month, day):
"""
author: kristine larson
given station (4 char), year, month, day, return rinexfile name
and the hatanaka equivalent
"""
doy,cdoy,cyyyy,cyy = ymd2doy(year,month,day)
fnameo = station + cdoy + '0.' + cyy + 'o'
fnamed = station + cdoy + '0.' +... | adf90ae9e05718a910a8f6818590539f73e24ea9 | 3,608,347 |
def threshold_otsu(image, nbins=256):
"""Return threshold value based on Otsu's method.
Parameters
----------
image : (N, M) ndarray
Grayscale input image.
nbins : int, optional
Number of bins used to calculate histogram. This value is ignored for
integer arrays.
Returns
... | 65872502a886d97d2ac999aa767ad749af1832e5 | 3,608,348 |
def create(cart_id: str):
"""
Endpoint. Creates a cart.
:param str cart_id: cart id
:return: dict with message
:rtype: dict
"""
logger.info(f'Request@/create/{cart_id}')
return cart.create_cart(cart_id=cart_id) | 10d8955699b7780fd35020adbb2fc568ce604d30 | 3,608,349 |
def get_speed_soft_current():
"""
for line chart and radar
:return:
"""
soft_speed_list = speed_softgame_current("soft")
if soft_speed_list != "no data":
return jsonify({"softtop5": soft_speed_list[0: 5],
"softtop10": soft_speed_list[5: 10]})
else:
ret... | a942dedc85434e71145837a9c843feb5402c649c | 3,608,350 |
import random
def create_population(size, result):
"""
Creates a population of chromosomes
Args:
size : size of the population
result : the target chromosome
Returns:
a population of chromosomes each having length equal to 'result'
and made up of random character
"""
length = len(result.co... | 2478cdb8e1fb5214cdbc3ff021d7a79aa38a288b | 3,608,352 |
def get_old_ip(security_group_obj, current_ip):
"""
Loop over aws security group ips for current ip or set description
:param security_group_obj: aws security group obj
:param current_ip: current ip
:return: ip from security group that has the set description, or is the current ip if remove_ip is Tr... | 6c4e5e224dd758cd3c5e9ceb608ef204fcf34476 | 3,608,353 |
from typing import Iterable
from typing import Any
from typing import Union
from typing import Dict
def any_in_dict(
values: Iterable[Any], d: Union[Dict[Any, Any], TxData, TxParams]
) -> bool:
"""
Returns a bool based on whether ANY of the provided values exist among the keys of the provided
dict-lik... | ed6a1be6405a534c9a0afce6f1a4ec4975fa096b | 3,608,355 |
def privacy_policy(request):
"""Privacy Policy"""
return render(request, 'dublinbus/privacy_policy.html') | 5a5fba069cf39cb33d65f0e5130c47ad872be241 | 3,608,356 |
import numpy
def compute_features(net, im):
"""
Compute fc7 features for im
"""
fc7 = numpy.array(lasagne.layers.get_output(net['fc7'], im, deterministic=True).eval())
return fc7 | 380a32771ba53d0c9310985d96dc835d8d5480ca | 3,608,357 |
def bout_boundaries_ts(ts, bname):
"""Gets the bout boundaries for a specific behavior from a male within
a FixedCourtshipTrackingSummary.
Parameters
----------
ts : FixedCourtshipTrackingSummary
Should contain ts.male and ts.female attributes.
bname : string
Behavior to calcul... | c9c4351e18ff3e089cc7a925101ad77116b1f571 | 3,608,358 |
import timeit
def mclp_batch_solver(env_path, road_network, demand_point, potential_facility_site, service_distance, list_num_facility, demand_weight_attr):
"""
Solve multiple MCLPs using the given inputs and a list of number of facilities. This function will call the function of mclp_solver
:param env_pa... | 8e21380c1fed383c062cea18092363be00a62538 | 3,608,359 |
import torch
def locations_to_boxes(
*,
locations: torch.Tensor,
priors: torch.Tensor,
center_variance: float,
size_variance: float
) -> torch.tensor:
"""Convert regressional location results of SSD into boxes in the form of (center_x, center_y, h, w).
The conversion:
$$predicted\_center * ... | dbe72b796c38f1705e377d8f6668562bb5b1fc96 | 3,608,360 |
def get_metric_fqdd_mapping(connection: str):
"""get_metric_fqdd_mapping Get Metric-FQDD Mapping
Get metric-fqdd mapping
Args:
connection (str): connection string
"""
engine = db.create_engine(connection)
metadata = db.MetaData()
connect = engine.connect()
mapping = {}
me... | d41dbd051d4f6f3eebab62eeb16fc812bf58fbb9 | 3,608,361 |
def __extract_digits__(string):
"""
Extracts digits from beginning of string up until first non-diget character
Parameters
-----------------
string : string
Measurement string contain some digits and units
Returns
-----------------
digits : int
... | 6613e56dc33c88d9196c2ec95412155ad0aaf382 | 3,608,362 |
def scatterkwargs(kwargs):
"""
Get a subset of keyword arguments to pass to a matplotlib scatter call.
Parameters
-----------
kwargs : :class:`dict`
Dictionary of keyword arguments to subset.
Returns
--------
:class:`dict`
"""
kw = subkwargs(
kwargs,
plt... | ead7da23f7726a9fdd8a7e600b83b01bbfe2f7c7 | 3,608,363 |
def _proxy_user(environ, username):
"""
Load up the correct user information for the user being proxied
in a mapping.
"""
store = environ['tiddlyweb.store']
try:
user = User(username)
user = store.get(user)
return {'name': user.usersign, 'roles': user.list_roles()}
ex... | 8ace13f8c1a6481e6fb4493af90c56ec3f8128c0 | 3,608,364 |
import csv
def class_names_from_csv(class_map_csv):
"""Read the class name definition file and return a list of strings."""
if tf.is_tensor(class_map_csv):
class_map_csv = class_map_csv.numpy()
with open(class_map_csv) as csv_file:
reader = csv.reader(csv_file)
next(reader) # Skip... | f03b85dc412a2f11608cb0c24ae6c1cc0b272316 | 3,608,365 |
def add_attachment(manager, issue, path):
"""
Replace jira's method 'add_attachment' while don't well fixed this issue
https://github.com/shazow/urllib3/issues/303
And we need to set filename limit equaled 252 chars.
:param manager: [jira.JIRA instance]
:param issue: [jira.JIRA.resources.Issue i... | 0bb2b910e1e92f1ebfe9272959ba61b07cc36091 | 3,608,366 |
def is_valid_array_size(x, lower=1e-10, upper=1e10):
"""Checks whether a vector or matrix norm is within lower and upper bounds.
Parameters
----------
x : array-like
The data to be checked
lower : float (default = 1e-10)
The lower bound vector or matrix norm.
upper : float... | 68a257fa63ccd6e0a24e07d06d82a6c8d946a293 | 3,608,367 |
def array_rotation():
"""Solution to exercise R-11.10.
Explain why performing a rotation in an n-node binary tree when using
the array-based representation of Section 8.3.2 takes Ω(n) time.
---------------------------------------------------------------------------
Solution:
------------------... | f448fede21496701509e2399f1ebc1b3fbf50954 | 3,608,368 |
def collisional_model(q, system, ancillae, collision_number=None,
g=1., tau=1., measure=False,
environment_qubits=None, **kwargs):
"""Prepare QuantumCircuit for the collisional model
Args:
q (QuantumRegister): the register
system (i... | 11810909b0c003fca830ceef97d8bdb347533d7c | 3,608,369 |
def update_sulfuras(item):
"""
sulfuras keeps it quality and has not to be sold
"""
return item.sell_in, item.quality | 7ed10720aa7543719383f73923f2f64bf1439021 | 3,608,370 |
def prune_punc(a_toks):
"""Remove tokens representing punctuation from set.
Args:
a_toks (iterable): original tokens
Returns:
frozenset: tokens without punctuation marks
"""
return frozenset([tok for tok in a_toks if not _ispunct(tok[-1])]) | 9be17ba73841aee4d16380b71a2107bc9bbbd16c | 3,608,371 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.