content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def receives(func):
""" Decorate a method to enable method mocking
"""
def call_receiver(*kargs, **kwargs):
receiver = Receiver()
kwargs['receive'] = receiver
result = func(*kargs, **kwargs)
receiver.finalize()
return result
return call_receiver | 1505b82e3cdb2d3a2a74fc8b295ee39acc65c33b | 36,766 |
def left_hash(msg, func="HS256"):
""" Calculate left hash as described in
https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
for at_hash and in
for c_hash
:param msg: The message over which the hash should be calculated
:param func: Which hash function that was used for the ID to... | 6e9732bd511173770e9bfbb81d77607e8b1be32c | 36,769 |
def xbin_ybwt(x, y, xbins, Nmin=1):
"""
Take x,y pairs. Bin in x, find biweight location and scale
Input: x and y, xbins
Nmin : default 1
minimum number of points per bin to be used (otherwise nan)
Return: xbins centers, yloc, yscale
"""
assert len(x) == len(y)
... | af6938bd58c1cc2a0852e52fa9f5137b73b48f7d | 36,770 |
def render_body_keypoints(img: np.array,
body_keypoints: np.array) -> np.array:
"""
Render OpenPose body keypoints on input image.
Args:
img (np.array): Input image of shape (H, W, 3) with pixel values in the [0,255] range.
body_keypoints (np.array): Keypoint array ... | d52d79bb316647a538a8225a38498d0160cf29c1 | 36,772 |
import asyncio
def create_app():
"""
建立web应用
url: http://flask.pocoo.org/docs/1.0/quickstart/
:return:
"""
flask_app = Flask(__name__)
with flask_app.app_context():
# 项目内部配置
mongodb_base = MongodbManager.get_mongo_base(
mongodb_config=Config.MONGODB_CONFIG
... | 6a2f995254d23dc41422282c204e8e435cdbd9ed | 36,773 |
import json
def update_status_config(milestones_content):
"""Convert the JSON milestones from GitHub to a simple dict."""
milestones = json.loads(milestones_content)
# Test that GitHub milestones and local definitions are equivalent
status_names = sorted(STATUSES.keys())
milestone_names = sorted([... | d0c8a4b1591735970bcab9c76fdc22135171b41d | 36,774 |
def getNjuClassesUrl(date=date.today()):
"""url of classes information"""
return 'https://wx.nju.edu.cn/njukb/wap/default/classes?date={}'.format(str(date)) | 535cf2e7ad176464d5db07c5bf32812abfd3e6ec | 36,775 |
def sg_to_brix(sg):
"""
Specific Gravity to Degrees Brix
:param float sg: Specific Gravity
:return: Degrees Brix
:rtype: float
Source:
* http://en.wikipedia.org/wiki/Brix
* http://www.brewersfriend.com/brix-converter/
"""
if sg > 1.17874:
raise SugarException(u"Above 4... | 4a097fd7898368a7608ae0a76181f6d090b2cf17 | 36,776 |
def detect_peaks(x, mph=None, mpd=1, threshold=0, edge='rising',
kpsh=False, valley=False, show=False, ax=None):
"""Detect peaks in data based on their amplitude and other features.
Parameters
----------
x : array-like
1D vector with data
mph : {None, number}, optional (def... | e6a73fc30b1973f921195e676b43cc0d82b3ab5c | 36,778 |
import numpy
def HarmonicOscillatorsSample(N_k=[100, 100, 100], O_k = [0, 1, 2], K_k = [1, 1, 1], seed=None):
"""
Generate samples from 1D harmonic oscillators with specified relative spacing (in units of std devs).
OPTIONAL ARGUMENTS
N_k (list or numpy.array of nstates) - number of samples per state
O... | b83a28f22703113908910c84655f2a8ed2321af5 | 36,779 |
def genkeys(e, bit):
"""
Generates keys for rsa.
Parameters:
e (int): public key
bit (int): bit length of primes
Outputs:
n (int): modulus
e (int): public key
d (int): private key
"""
lam=0
while np.gcd(e, lam) != 1:
p=genprime(bit)
q=genprime(bit)
... | 788f0f51cea7c72a0715565e04b3f59677d62db8 | 36,780 |
def get_xml_subelement(xml_elem, subelement, attribute=None, multi=False, convert=None, default=None, quiet=False):
"""
Return the text or attribute of the specified subelement
=== PARAMETERS ===
xml_elem : search the children nodes of this element
subelement: name of the subelement whose text wil... | 574880a2bfb7a6203b5079ec38ebc0d9af41cb07 | 36,781 |
def sub_env_var(uri, envvars):
"""Substitute any environment variables found"""
match = ENVVAR_RE.search(uri)
if not match: # no environment variable in uri
return uri
old = match.group(1)
envvar = match.group(2)
if not envvar in envvars:
print(f'Undefined environment variable {... | 273244d13662f6f5bc6ceeef181b9f044020f81b | 36,782 |
def filter_intensity_jumps(i0,winsz=20,num_quantiles=2,quantile=0.5):
"""
Identify locations in the trajectory where the intensity jumps significantly
Parameters
----------
i0 : numpy.ndarray
Dot intensity time series.
winsz : int
Window size for creating the trendl... | 1cd0d69cd88fe78b6ba6e171c84c5dccb50d0074 | 36,783 |
def str_to_tn(str_):
"""Fully parses str_.
A full parse might not be necessary. Both blocks and the nodes can be (and
probably should be) parsed lazily.
"""
lines = str_.split(NODE_BREAK)
return get_blocks(lines) | 7e8a23a4a3010f5eef3b5226456d42f19078acfc | 36,784 |
from typing import List
def parse_with_semantics(text: str, semantics: type=None) -> List[base.StatementObject]:
"""Parse a file with given semantics."""
return lang.parse(text, semantics=semantics()) | 10c3b93df0b501733bbae5208c2a46ef4fa5217e | 36,786 |
def get_object_expiry_time(storage_url, auth_token, container, name):
"""Return in seconds the header x-expiry-at for the given object."""
cont = client.head_object(storage_url, auth_token, container, name)
return cont.get('x-delete-at', '') | 0a5a3f3ba2f14cb6737d52907f08e26e98b83935 | 36,787 |
def file(input_file):
"""Import colorscheme from json file."""
data = util.read_file_json(input_file)
if "wallpaper" not in data:
data["wallpaper"] = "None"
if "alpha" not in data:
data["alpha"] = "100"
return data | 053bc45f11f3995e8b07c85febd1aeb1d9f20686 | 36,788 |
import requests
import html
def find_artists(artist):
"""
Searches and returns the first page results of AZLyrics artists.
:param artist: string with the name of the artist
:return: list of dicts with artist and url strings
"""
r = requests.get("https://search.azlyrics.com/search.php",
... | d691eec62807c9201f05ccdda6b7f5b78960adee | 36,789 |
def l_model_forward(x, parameters):
"""
Forward propagation of deep learning.
@param x: input x, numpy arrays
@param parameters:
@return: output aL and caches for following calculations, numpy arrays and indexes
"""
caches = []
a = x
l_total = len(parameters) // 2 # number of layer... | bb689ff9dc7488215311f8ef97c6cc89503035ff | 36,790 |
def get_work_value(block_hash, work, as_hex=False):
"""
Get the proof-of-work value. The work value must be equal to or higher than
the work difficulty to be considered valid.
"""
validate_block_hash(block_hash)
parse_work(work)
reversed_work = bytearray(unhexlify(work))
reversed_wor... | b818623f9a00d4a9ff52dfd24d822e7a0414bfdb | 36,791 |
def total_loss(output, target, loss='mse', only_nodes=False, only_graph=False):
""" returns the average of the average losses of each task """
assert not (only_nodes and only_graph)
if only_nodes:
nodes_loss = get_loss(loss, output[0], target[0])
return nodes_loss
elif only_graph:
... | f39efeba4fae9dd397c2c9ea36d1ece865721e67 | 36,792 |
def parse_mem_str_to_gbsize(strmem):
"""
String like 845 MB 677.8 MB to GB size
:param strtime:
:return:
"""
strmem = strmem.strip()
if strmem.endswith('MB'):
memgb = float(strmem[:-2]) / 1024
elif strmem.endswith('GB'):
memgb = float(strmem[:-2])
elif strmem.endswit... | fd7d96c25b446a1c5ff94694908a9c355e340780 | 36,793 |
def Emonet_extend(num_classes):
"""
This model is optional and bigger than the previous one. Practically, this model is less useful than the first one
therefore is not called by the application. Use only for experimental purposes
"""
emonet = Sequential()
"""
Convolution and Maxpool layers:... | 7a22fe1f1107d0b27545a3046c35f5a661930227 | 36,794 |
def isListController(obj):
"""
Evaluates if the supplied object is a list controller.
:type obj: pymxs.runtime.MXSWrapperBase
:rtype: bool
"""
return pymxs.runtime.classOf(obj) in LIST_TYPES | 7d2285cb07744fd31aedd857c1691cda8b3e1f2a | 36,796 |
def genomic_del1():
"""Create test fixture containing params for genomic del VD."""
params = {
"id": "normalize.variation:NC_000003.12%3Ag.10149811del",
"type": "VariationDescriptor",
"variation_id": "",
"variation": dict(),
"molecule_context": "genomic",
"structu... | 12083300ee1115bc65ef0a9c4494b9918ac16ad9 | 36,797 |
def civic_vid258():
"""Create a test fixture for CIViC VID258."""
return {
"id": "civic.vid:258",
"type": "VariationDescriptor",
"label": "A222V",
"value_id": "ga4gh:VA.V5IUMLhaM8Oo-oAClUZqb-gDPaIzIi-A",
"value": {
"location": {
"interval": {
... | ee725d2c4601ce400abf1cf9da3d5eaaa7ba5bda | 36,798 |
def get_continuous_ts(finger, max_nans=30):
""" Split TS where n consecutive nans bigger than max_nans. 1D only"""
gaps = np.isnan(finger)
assert(np.all(gaps[0,:] == gaps[1,:])), "Finger x, y dim not equal. Check!"
# Use one axis (x,y)
gaps = gaps[0,:]
seg, n_seg = label(gaps)
for s in ran... | 7f1e05ab8757078b28b9b74abc6337f821a50b3c | 36,799 |
def find_rising_edge(x, y, *, threshold=None, interp=False):
"""Find the first `x` where `y` exceeds `threshold` (along the last axis).
`x` and `y` must have the same shape.
If `threshold` is None, it will be inferred as half the rise from min(y) to max(y).
If `interp` is True, linearly interpolate b... | 69c8601987cac8e44dc89d52499d907f58dc225c | 36,800 |
def normalize_os_name(os_name):
"""
:API: public
"""
if os_name not in OS_ALIASES:
for proper_name, aliases in OS_ALIASES.items():
if os_name in aliases:
return proper_name
logger.warning('Unknown operating system name: {bad}, known names are: {known}'
.format(bad=os_nam... | ca7e921580ae72d77d4d16158f45edefac2cd8b6 | 36,801 |
def make_prediction(*, path_to_images) -> float:
"""Make a prediction using the saved model pipeline."""
# Load data
# create a dataframe with columns = ['image', 'target']
# column "image" contains path to image
# columns target can contain all zeros, it doesn't matter
dataframe = path_to_ima... | 80d30707ecbacdae50c0f986bb3c66a504cc3740 | 36,802 |
def vmanage_login(host: str, username: str, password: str):
"""
"""
return Authentication(
host=host,
user=username,
password=password
).login() | f127072880035b30e652d87f4af1b8bcd5110ffd | 36,803 |
def load_image():
"""Load image from file, then scale and rotate.
Returns CV2 object."""
if display_histogram == 1:
image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
else:
image = cv2.imread(filename, cv2.IMREAD_COLOR)
image_resized = cv2.resize(image, None, fx=scale, fy=scale,... | edaea5b59d6e87c8315bbc556d460b7cbefa2737 | 36,804 |
def handle_odd_pad_bwd(dx, odd_padding):
"""
handle odd padding mode backward
Args:
dx, the backward tensor
odd_padding, the odd_padding
Returns:
tensor, the output
"""
# (axis, left padding if True else right padding)
flags = [(2, True), (2, False), (3, True), (3, F... | fbf75299db943be3930db77abd21b0dd59c263bf | 36,805 |
import logging
def gwas_snp_to_precluster(gwas_snp, populations):
"""
Extract neighbourhood of GWAS snp
Args:
* [ GWAS_SNP ]
* [ string ] (populations)
Returntype: GWAS_Cluster
"""
mapped_ld_snps = postgap.LD.calculate_window(gwas_snp.snp)
logging.info("Found ... | aaa3ac23e0797cfda134f7a105c0e0c33ff8c7a6 | 36,806 |
def cleanup_ud(ds):
"""More cleaning and calculation of derived variables."""
# remove spikes in temperature
for v in ["t1", "t2"]:
ds[v] = despike(ds[v], ds.attrs["spike_thresh_t"])
# despike T, C
ibefore = 1
iafter = 1
for v in ["c1", "c2", "t1", "t2"]:
ds[v].data = helpe... | ff97f13667f07fd79aa3400ffea65d4b958d3163 | 36,809 |
import collections
def ParseIoStatsLine(line):
"""Parses a line of io stats into a IoStats named tuple."""
# Field definitions: http://www.kernel.org/doc/Documentation/iostats.txt
IoStats = collections.namedtuple('IoStats',
['device',
'num_r... | 2764dc96f0720359f906f1b27763738331f63e19 | 36,810 |
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool
def sql_readaspd(db_dets, query):
"""
Pull a SQL query output and read it into a Pandas DataFrame
Parameters
----------
db_dets: str
URL of a postgreSQL database that will be connected to.
query: str
... | 73d936aa8a9658a35efdb8e4ac451aca9c68abea | 36,811 |
def grid2spec(gfield):
"""Transform a field on physical grid to spectral space
Args:
gfield: numpy array with shape (time(optional), y, x, z(optional))
"""
if _is_single_layer(gfield):
y_loc = -2
else:
y_loc = -3
ny, nx = gfield.shape[y_loc], gfield.shape[y_loc+1]
... | 224d3e5e739b5b08dc380a161f9bba14e6915771 | 36,812 |
def parse_bits_transmission(
bits: list[str], pos: int = 0, indent: int = 0
) -> tuple[int, int]:
"""Parse a message accoring to the Buoyancy Interchange Transmission System (BITS)
Args:
bits (list[str]): message in binary representation
pos (int): current position in the bit stream
... | 30c05c10b3529b70db61dde81b11f44eeec43e4c | 36,813 |
def get_pixel_neighbors(height, width):
"""
Estimate the 4 neighbors of every pixel in an image
:param height: image height
:param width: image width
:return: pixel index - neighbor index lists
"""
pix_id = []
neighbor_id = []
for i in range(height):
for j in range(width):
... | 3e49081fdc59ff2b0df54b84e0cf8c5983ec7b2c | 36,814 |
def parse_copy_running_config_startup_config(raw_result):
"""
Parse the 'copy running-config startup-config' command raw output.
:param str raw_result: copy running-config startup-config
raw result string.
:rtype: dict
:return: The parsed result of the copy running-config startup-config:
... | 01bba91527d64e32dc4eabe08de791e45b1c2040 | 36,815 |
def make_bson(obj):
"""Given a Python (JSON compatible) dictionary, returns a BSON string.
(This hijacks the Python -> BSON conversion code from pymongo, which is needed for
converting queries. Perhaps this dependency can be removed in a later version.)
:param obj: object to be encoded as BS... | 1b8e862280b3287377fe1cc95d7e28f618fc90a9 | 36,816 |
from typing import Optional
from typing import Union
import json
def plot_hail_file_metadata(
t_path: str,
) -> Optional[Union[Grid, Tabs, bokeh.plotting.Figure]]:
"""
Takes path to hail Table or MatrixTable (gs://bucket/path/hail.mt), outputs Grid or Tabs, respectively.
Or if an unordered Table is pr... | e3158b525a9f632efa2c592ec4ae802c075bad52 | 36,817 |
def get_user_details(request):
"""
DataHub account registration form for social accounts.
Gives new users a chance to choose a DataHub username and set their email
address.
Called by the Python Social Auth pipeline's get_user_details step. For
more details, look for pipeline.py and the SOCIAL_... | 297fa9a15bd9671c827261157118f5fc6d722a96 | 36,819 |
from typing import Optional
def _cqv(
data: NumArrayLike,
ndigits: Optional[int] = 4,
interpolation: Optional[str] = "linear",
multiplier: Optional[int] = 1,
) -> float:
"""Internal function to calculate cqv."""
# ------------------- convert data to pandas.core.series.Series ------------------... | 179b9060152851c9a898aa70ce4d8a68f13b11a2 | 36,821 |
def GetCulpritsForFailures(failures):
"""Gets culprits for the requested failures.
Args:
failures (list of AtomicFailures)
Returns:
(list of findit_result.Culprit)
"""
culprit_keys = set([
failure.culprit_commit_key
for failure in failures
if failure and failure.culprit_commit_key
... | 7fc5270c687a0056f6a61d5fea09efdc529ef2d5 | 36,822 |
from typing import Optional
from typing import Dict
def get_object_perms(obj: models.Model, user: Optional[User] = None) -> Dict:
"""Return permissions for given object in Resolwe specific format.
Function returns permissions for given object ``obj`` in following
format::
{
"type": "gr... | 3aca9eacb250086dc449fad41d570f958ad71655 | 36,823 |
def fixed_from_old_hindu_lunar(l_date):
"""Return fixed date corresponding to Old Hindu lunar date l_date."""
year = old_hindu_lunar_year(l_date)
month = old_hindu_lunar_month(l_date)
leap = old_hindu_lunar_leap(l_date)
day = old_hindu_lunar_day(l_date)
mina = ((12 * year) - 1) * ARYA_SOLAR... | b9dc05384d1e92ba55bec1b6b4e373122bf76fcc | 36,824 |
def get_zrand_mask(zrand, percentile=95):
"""
Calculates stable regions of `zrand` based on `percentile`
Parameters
----------
zrand : (C, K, M) array_like
Local similarity of clustering solutions in SNF parameter space
percentile : [0, 100] float, optional
Percentile of `zrand`... | 6e41367c27d4159497d57089c1feee01b45b20ca | 36,825 |
def remove_small_areas(img, min_area):
"""
Segmenta uma imagem em várias regiões com propriedades em comum e gera
uma imagem resultado, deixando de fora todas as regiões que possuam
areas menores do que o limiar passado. Esse processo é realizado para
remover áreas pequenas (no geral... | 4cc7d7120e35317e6b077c4500c1eb3580887b6d | 36,826 |
def show_pages(parser, token):
"""
Show page links.
Usage::
{% show_pages %}
It is only a shortcut for::
{% get_pages %}
{{ pages }}
You can set *ENDLESS_PAGINATION_PAGE_LIST_CALLABLE* in your settings.py
as a callable used to customize the pages that are displayed.
... | b412602108544c4560b757807317f043c36619e7 | 36,827 |
from image import is_b64
import logging
def check_file(file, direction):
""" Validate a user input
This function ensures that the user enters a valid file list
where the list contains a non-empty filename, b64 image, and a valid
processing steps array.
Args:
direction (str): either "uplo... | a22ded240f771a98efc0d613b851dcc84bd95c03 | 36,828 |
from typing import Counter
def check_valid_solution(solution, graph):
"""Check that the solution is valid: every path is visited exactly once."""
expected = Counter(
i for (i, _) in graph.iter_starts_with_index()
if i < graph.get_disjoint(i)
)
actual = Counter(
min(i, graph.get... | ec22134973153605b3a9b7a2ac7f180ffe55f97e | 36,829 |
import copy
def filter_props(props):
"""Filter props from the Component arguments to exclude:
- Those without a "type" or a "flowType" field
- Those with arg.type.name in {'func', 'symbol', 'instanceOf'}
Parameters
----------
props: dict
Dictionary with {propName: propMetadata}... | df2dad9d174702e40d2410fba2cc2b21b05ddfd3 | 36,830 |
import numpy
def sqr_ts(timeseries, nodata=-9999):
"""sqr - Interquaritle range (IQR)
It computes the interquaritle range of the time series.
:param timeseries: Your time series.
:type timeseries: numpy.ndarray
:param nodata: nodata of the time series. Default is -9999.
:type nodata: int
... | 21e98734dfa95036cc6194ac253c1cb2eb275d25 | 36,831 |
from typing import Union
from typing import Collection
def to_shape(data: Union[Collection, Tensor], add_batch=False, exact_shape=True) -> Union[Collection, Tensor]:
"""Compute the shape of tensors within a collection of `data`recursively.
This method can be used with Numpy data:
```python
data = {"x... | 00693cd854252805dcbef7ee9ba85c804a896166 | 36,833 |
def Color(colorname):
"""pygame.color.Color(colorname) -> RGBA
Get RGB values from common color names
The color name can be the name of a common english color,
or a "web" style color in the form of 0xFF00FF. The english
color names are defined by the standard 'rgb' colors for X11.
... | ef553c482014d9e2275d5ae64016cbb27e34272b | 36,834 |
import multiprocessing
def from_image_files(
images_dir: str,
extensions: str | tuple[str, ...] = '.jpg',
selection: set[str] = set(),
) -> Statistics:
"""From a directory path with images, will generate the stats of all
images. The statistics generated are: mean, std, max, and min.
Parameter... | bc2e07891646c7bf5e49c22f7022a2f44df215e5 | 36,836 |
def _memoized_fibonacci_aux(n: int, memo: dict) -> int:
"""Auxiliary function of memoized_fibonacci."""
if n == 0 or n == 1:
return n
if n not in memo:
memo[n] = _memoized_fibonacci_aux(n - 1, memo) + \
_memoized_fibonacci_aux(n - 2, memo)
return memo[n] | 9a6d8646139d6ae9f6f63d2e990545fd088407eb | 36,837 |
import logging
def make_app(table_size, update_size, update_rate):
"""Create a Tornado application for the webserver."""
MANAGER.host_table("table", TABLE)
MANAGER.host_view("view", VIEW)
if table_size is not None and TABLE.size() < table_size:
current_size = TABLE.size()
while curre... | f4670831d6a8dfc8afa232b6198988a2babad2e3 | 36,838 |
import nibabel as nib
def get_scan_info(in_file):
""" Get useful scan-parameters.
Function to extract some useful scan-parameters.
Parameters
----------
in_file : str
Path to (functional!) nifti-image
Returns
-------
TR : float
Time-to-repetition of file
"""
... | dde7b2bfcbeee7bccddef8678f717b2f40b5c4df | 36,839 |
def merge_sort(array_of_numbers):
"""
This should split the array into single numbers and then recombine
the list into a single sorted list in a recursive way.
:param array_of_numbers:
:return:
"""
length = len(array_of_numbers)
split = int(length/2)
if length <= 1:
return ... | 4fb90843689bb213b5dfa0460e99126c9aa16778 | 36,840 |
import socket
def select_random_ports(n):
"""Selects and return n random ports that are available."""
ports = []
for i in xrange(n):
sock = socket.socket()
sock.bind(('', 0))
while sock.getsockname()[1] in _random_ports:
sock.close()
sock = socket.socket()
... | 93145b58e6ecce60da9ae96527ca8e61c794f7ed | 36,841 |
def choose_targets(label_dic_set, m, label_dic, source_label):
"""
This differs from random.sample which can return repeated
elements if seq holds repeated elements.
"""
#global count1
#global count2
targets = set()
if len(label_dic_set[source_label]) > m:
#print(1)
whil... | e350ab8c504d59f3a1db8a9977924c4ad3ba96af | 36,843 |
def sinkhorn(C, log_w_p, log_w_q, key, alpha=0.01):
"""Uses sinkhorn iterations to solve an optimal transport problem.
Computes the optimal cost and transport plan for moving mass from an
atomic measure p to another atomic measure q.
Args:
C: The cost matrix, C_ij contains the cost of moving mass from the... | f1796ce1c2fe347cf24e81bf121a0ad4d9e6193d | 36,844 |
def string_count_words(string: str) -> dict:
"""Count occurrences of individual words in a given string
This function counts occurrences of each separate words. It returns
a dictionary, in wich keys correspond to words and values
to the number of occurrences.
Args:
string (str): String for the countin... | cd51101a33fb4fd4c8488718549362fa25ebb360 | 36,845 |
import torch
def compute_class_freqs(labels):
"""
https://www.kaggle.com/eugennekhai/chest-x-ray-pytorch-lightning-densnet121
Compute positive and negative frequences for each class.
Args:
labels (np.array): matrix of labels, size (num_examples, num_classes)
Returns:
positive_freq... | 94915525c138038c20093e3f5c6499383e293369 | 36,846 |
def cayley_menger_analysis(vertices, d = 2):
"""
Determines volume and circumradius for a tetrahedron given the vertices
https://westy31.home.xs4all.nl/Circumsphere/ncircumsphere.htm#Coxeter
"""
if d == 3:
cm_matrix = np.array([[0, 1, 1, 1, 1], [1, 0, distance.sqeuclidean(vertices[0], vertic... | 794d387adf8bafdba0e4b81aa9635069335da62a | 36,847 |
async def async_setup_entry(hass, entry):
"""Set up a bridge for a config entry."""
await async_setup_bridge(hass, entry.data['host'],
username=entry.data['username'])
return True | de649b60ec38c85807860c9e64c46c6f9019d25f | 36,849 |
def make_non_parallel_copy(model):
"""Make a non-data-parallel copy of the provided model.
torch.nn.DataParallel instances are removed.
"""
def replace_data_parallel(container):
for name, module in container.named_children():
if isinstance(module, nn.DataParallel):
... | 2a82494a6b6ef3ac8ca08bd210d3ae2c95a9b9e4 | 36,851 |
from re import T
from typing import Callable
def from_dependent_matroid(matroid: tuple[set[T], list[set[T]]]) -> Callable[[set[T]], int]:
"""Construct a nulity function from a matroid defined by dependent sets.
Args:
matroid (tuple[set[T], list[set[T]]]): A matroid defined by dependent sets.
Ret... | b449d8d260fe4ec3dd684266c8f990cdc9872309 | 36,852 |
def convolve(image, psf, return_Fourier=False):
""" Convolves given image by psf.
Args:
image: a JAX array of size [nx, ny], either in real or Fourier space.
psf: a JAX array, must have same shape as image.
return_Fourier: whether to return the real or Fourier image.
Returns:
The resampled kimage... | 02010e1f0a39a412ac11ff62c5990218334a93ec | 36,853 |
def read_csv(file: PATH_TYPE) -> pd.DataFrame:
"""A wrapper for ``pd.read_csv`` which tries to handle errors gracefully.
Args:
file: The CSV file to read.
Returns:
A ``DataFrame`` containing the contents of the file.
"""
try:
return pd.read_csv(file, encoding="utf-8")
e... | 0cb4a2840d0f1718759356705149aa0025db6baa | 36,854 |
def tfm_shear(x_angle=0.0, y_angle=0.0, shape=(0, 0)):
"""
Generate a shear transformation matrix.
:param x_angle: The angle to shear the image in horizontal direction
:param y_angle: The angle to shear the image in vertical direction
:param shape: The shape of the image to be transformed
:retu... | 28614a617791142a9955495827a76f957b08ff46 | 36,855 |
def _load(handler_obj):
"""
Load an :class:`.IHandler` handler object. The
handler_obj.load_type() defines whether
:func:`._load_module_function` or :func:`._load_module_class` is
to be used.
"""
if handler_obj.load_type() == "function":
return _load_module_function(handler_obj)
... | 57b207125c7be45b979f0c9a84722382b8078782 | 36,857 |
def comp_ac_fft_middlepad(data):
"""Compute auto-correlations from binned data (without normalization).
Uses FFT after zero-padding the time-series in the middle.
Parameters
-----------
data : nd array
time-series from binned data (numTrials * numBin).
Returns
-------
a... | 6bef88dd15e24e9d74654b8c407888066dd7efe5 | 36,858 |
def get_mod_for_key(keycode):
"""
Finds the modifier that is mapped to the given keycode.
This may be useful when analyzing key press events.
:type keycode: int
:return: A modifier identifier.
:rtype: xcb.xproto.ModMask
"""
return __keysmods.get(keycode, 0) | b65e81d2ace36547b799b680e7756f61fcc3118c | 36,860 |
from typing import List
from typing import Dict
from typing import Any
def remove_delay_fault(virtual_service_name: str,
routes: List[Dict[str, str]],
ns: str = "default",
version: str = "networking.istio.io/v1alpha3",
configu... | da0a10d6b2316cb1c2aa2fa777e87f3dc592cb8a | 36,861 |
def set_lm_labels(dataset, vocab, stm_lex, stm_win=3):
"""
set labels of bi-directional language modeling and sentiment-aware language modeling
:param dataset: dataset
:param vocab: vocabulary
:param stm_lex: sentiment lexicon
:param stm_win: window size (i.e., length) of sentiment context
:... | ec87003f9f427c5de5ea969f7040f7f10d49c3ea | 36,862 |
def pad_sequences(sequences, pad_func, maxlen = None):
"""
Similar to keras.preprocessing.sequence.pad_sequence but using Sample as higher level
abstraction.
pad_func is a pad class generator.
"""
ret = []
# Determine the maxlen
max_value = max(map(len, sequences))
if maxlen is None... | 5879ab8f8df7477b9d73c87b6c8065fcc43a66df | 36,863 |
def update(event, context):
"""
Runs on Stack Update
"""
physical_resource_id = event['PhysicalResourceId']
if event.get('ResourceType') == 'Custom::CWEventPermissions':
cwe = CWEventPermissions(event, logger)
logger.info("Updating CW Event Bus Policy - CR Router")
response =... | afca288f444ebd7acd2442d0178496b144528c8f | 36,864 |
def measure_arbitrary_sequence(qubits, sequence=None, sequence_function=None,
sequence_args=None, drive='timedomain', label=None,
detector_function=None, df_kwargs=None,
sweep_function=awg_swf.SegmentHardSweep,
... | b03a12875c070dbfb16e987307cf89444b57ea19 | 36,865 |
def LoadAnnotation(
seg_path,
prefix=None,
label_map=None,
reduce_zero_label=False,
imdecode_backend='pillow',
file_client: FileClient = FileClient(backend='disk'),
):
"""Load annotations for semantic segmentation.
**Args**:
- reduce_zero_label (bool): Wh... | 7dffe11c98a60ab10e7786cdb1be36e3b830b0d8 | 36,866 |
def random_translate(img, streering_angle, range_x, range_y):
"""
Randomly shift the image virtially and horizontally (translation).
"""
trans_x = range_x * (np.random.rand() - 0.5)
trans_y = range_y * (np.random.rand() - 0.5)
streering_angle += trans_x * 0.002
trans_m = np.float32([[1, 0, ... | 1ca533617da950657e4d8b1dbd6c681e381d2e1a | 36,867 |
def read_input_data(filename, arguments):
"""
Reads single input data
:param filename: relative path to file
:param arguments: image resize
:return: left image, right image
"""
cv_image = cv2.imread(filename)
if cv_image is None:
raise RuntimeError(f"Unable to open {filename}"... | 4857314f6b5ad682ef09a09aa5b567987d2d1aec | 36,868 |
import uuid
def get_uuid4():
""" make a random UUID
"""
s = uuid.uuid4()
return str(s) | 9643fb712c2181fbba4fabc36b61eecfa42a3dfd | 36,869 |
from typing import Union
def black76_vega(F: float,
K: Union[float, np.ndarray],
vol: Union[float, np.ndarray],
disc: float,
T: float) -> Union[float, np.ndarray]:
"""
Vega(s) for strike(s)
:param F: float, forward price
:param K: flo... | 61d10ce1adcdd8478ea789e1e7e2291d900fafba | 36,870 |
def replace_greek_uni(s):
"""Replace Greek spelled out letters with their unicode character."""
for greek_uni, greek_spelled_out in greek_alphabet.items():
s = s.replace(greek_spelled_out, greek_uni)
return s | 998d97421d3503de890cdccf60e32ae5e3ddba92 | 36,871 |
import torch
def load_GG2_images(images):
"""
Normalizes images and upscales them
"""
images = [fits.open(file, memmap=False)[0].data for file in images]
images = [torch.from_numpy(x.byteswap().newbyteorder()) for x in images]
#Normailze
normalize = [3.5239e+10, 1.5327e+09, 1.8903e+09, ... | eb50450c64748afcb043d7e0a779b5be03f9c4d4 | 36,872 |
def index():
"""Main page"""
return render_template('landing.html') | de60270e90eea3f42435a9c16ff0326545964b83 | 36,873 |
def has_computed_fields(context, obj):
"""
Return a boolean value indicating if an object's content type has associated computed fields.
"""
content_type = ContentType.objects.get_for_model(obj)
return ComputedField.objects.filter(content_type=content_type).exists() | a820f164ba021a3b61fdb200c941cfbb1cb9aa42 | 36,874 |
from typing import Optional
from typing import List
from typing import Tuple
def _prepare_dataframes(
forecast_df: DataFrame,
truth_df: DataFrame,
percentiles: Optional[List[float]] = None,
experiment: Optional[str] = None,
) -> Tuple[DataFrame, DataFrame]:
"""Prepare dataframes for conversion to ... | 56b9c024e9b87f22be31d33ba0151545534e4901 | 36,875 |
def contour_and_point_distance(point):
"""
A reusable function that preloads a point and then
calculates the distance to a given contour.
:param point: an (x,y) tuple point
:return:
"""
return partial(geometry.distance_between_points, point) | da821b2c704e5aeb65719fce95a77e890c8e7f07 | 36,876 |
def replace_codepoints(text: str) -> str:
"""
Replaces Unicode codepoints in a string with the corresponding glyphs.
Multiple codepoints can be specified in the same string. Characters
which are not part of codepoint annotation are kept.
@param text: The text with codepoint annotations to be repla... | d55a608153e8873ef472403110d6534d919e6853 | 36,877 |
def grid2grid1D(f1, boxsize, ngridout, origin=0., originout=0., boxsizeout=None):
"""Remaps a dataset defined on 2D cartesian grid onto a new 2D cartesian grid.
Parameters
----------
f1 : array
The values of the 2D grid pixels.
boxsize : float
Box size.
ngridout : int
Gr... | 51ba20f50f689703043d1eb05761c1b6d07de95e | 36,878 |
def get_all_user_feedback(request):
"""
Returns a list of all the feedbacks for a given user
:param request:
:return: 200 successful
"""
feedbacks = Feedback.objects.filter(user=request.user).order_by('-created')
serializer = FeedbackSerializer(feedbacks, many=True)
return Response(seria... | 853dd1a29ade3b0874815be9074471aadda6c86f | 36,879 |
from re import T
def atom(env, args):
"""Atom has the value of 't' or 'f' according to
whether its argument is an atomic symbol. Thus:
(atom t) = t
(atom (quote (t f))) = f
"""
arg = args.car().eval(env)
if isinstance(arg, Symbol) or arg == F:
return T
return F | 671ff8c71ac17bfd443523205b95e4e9f5de8694 | 36,880 |
def ad_get_user_dn_by_mail(user_mail_addr):
"""
通过mail查询某个用户的完整DN
:param user_mail_addr:
:return: DN
"""
conn = __ad_connect()
conn.search(BASE_DN,
'(&(objectclass=person)(mail=' + user_mail_addr + '))', attributes=['distinguishedName'])
user_dn = conn.entries[0]['disting... | a826929a8f3106a823279462ec1f8a2b30693b00 | 36,881 |
import collections
def get_interface_config_ipv6(ip_address, ip_subnet, ip_gateway):
"""
Return the interface configuration parameters for all IPv6 static
addressing.
"""
parameters = collections.OrderedDict()
parameters['IPV6INIT'] = 'yes'
parameters['IPV6ADDR'] = netaddr.IPNetwork('%s/%u... | deb75b75e5e806965db30717dda902efa4d07263 | 36,883 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.