content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_bin_values(base_dataset, bin_value):
"""Gets the values to be used when sorting into bins for the given dataset, from the configured options."""
values = None
if bin_value == "results":
values = base_dataset.get_output()
elif bin_value == "all":
# We set all values to 0, assuming... | cf2419066d6e642e65d9a8747081ebfee417ed64 | 3,643,784 |
def get_reviews(revision_range):
"""Returns the list of reviews found in the commits in the revision range.
"""
log = check_output(['git',
'--no-pager',
'log',
'--no-color',
'--reverse',
r... | 0ff81eef45fb123e25dc7662f320e49fac7aa378 | 3,643,785 |
def create_cert_req(keyType=crypto.TYPE_RSA,
bits=1024,
messageDigest="md5"):
"""
Create certificate request.
Returns: certificate request PEM text, private key PEM text
"""
# Create certificate request
req = crypto.X509Req()
# Generate private key
... | 168fd8c7cde30730cdc9e74e5fbf7619783b29c9 | 3,643,786 |
def large_xyz_to_lab_star(large_xyz, white=const_d50_large_xyz):
"""
# 概要
L*a*b* から XYZ値を算出する
# 入力データ
numpy形式。shape = (N, M, 3)
# 参考
https://en.wikipedia.org/wiki/Lab_color_space
"""
if not common.is_img_shape(large_xyz):
raise TypeError('large_xyz shape must be (N, M, 3)')
... | aec3cb423698954aa07a61bf484e1acd8e38d5db | 3,643,787 |
from typing import Any
def return_value(value: Any) -> ObservableBase:
"""Returns an observable sequence that contains a single element,
using the specified scheduler to send out observer messages.
There is an alias called 'just'.
example
res = rx.Observable.return(42)
res = rx.Observable.ret... | e14ac3a08a3f127b77f57b7192a8f362ec3485b2 | 3,643,788 |
def compare_policies(current_policy, new_policy):
""" Compares the existing policy and the updated policy
Returns True if there is a difference between policies.
"""
return set(_hashable_policy(new_policy, [])) != set(_hashable_policy(current_policy, [])) | e69ecaa051602e2d9eab0695f62b391a9aca17ad | 3,643,789 |
def meanPSD(d0,win=np.hanning,dx=1.,axis=0,irregular=False,returnInd=False,minpx=10):
"""Return the 1D PSD averaged over a surface.
Axis indicates the axis over which to FFT
If irregular is True, each slice will be stripped
and then the power spectra
interpolated to common frequency grid
Presume... | 99d6ab3e8ef505f031346db10762a195904b455e | 3,643,790 |
async def get_temperatures(obj):
"""Get temperatures as read by the thermostat."""
return await obj["madoka"].temperatures.query() | b4643d9c40f6aa8953c598dd572d291948ef34a4 | 3,643,791 |
import itertools
def get_zero_to_2pi_input(label, required, placeholder=None, initial=None, validators=()):
"""
Method to get a custom positive float number field
:param label: String label of the field
:param required: Boolean to define whether the field is required or not
:param placeholder: Pla... | d1349088d8b2c29ecc07bdb6900ff335384e3c30 | 3,643,792 |
def compile_math(math):
""" Compile a mathematical expression
Args:
math (:obj:`str`): mathematical expression
Returns:
:obj:`_ast.Expression`: compiled expression
"""
math_node = evalidate.evalidate(math,
addnodes=[
... | 511c281a03591ed5b84e216f3edb1503537cbb86 | 3,643,793 |
from typing import Optional
from typing import Union
from typing import List
import click
def colfilter(
data,
skip: Optional[Union[str, List[str]]] = None,
only: Optional[Union[str, List[str]]] = None,
):
"""
Remove some variables (skip) or keep only certain variables (only)
Parameters
-... | 16c901f514afb1990e43c470c7e089eab5b4eb56 | 3,643,794 |
import math
def acos(x):
"""
"""
return math.acos(x) | 0a8ca8f716f0ea54b558ca27021830480dac662d | 3,643,795 |
def get_callable_from_string(f_name):
"""Takes a string containing a function name (optionally module qualified) and returns a callable object"""
try:
mod_name, func_name = get_mod_func(f_name)
if mod_name == "" and func_name == "":
raise AttributeError("%s couldn't be converted to a... | ef1ae8d4c1da06e38a6029e0caa51b4e3fb5b95c | 3,643,796 |
from typing import List
import bisect
def binary_get_bucket_for_node(buckets: List[KBucket], node: Node) -> KBucket:
"""Given a list of ordered buckets, returns the bucket for a given node."""
bucket_ends = [bucket.end for bucket in buckets]
bucket_position = bisect.bisect_left(bucket_ends, node.id)
#... | ff1fc765c56e67af3c33798b403779f7aafb6bb0 | 3,643,797 |
def darken(color, factor=0.7):
"""Return darkened color as a ReportLab RGB color.
Take a passed color and returns a Reportlab color that is darker by the
factor indicated in the parameter.
"""
newcol = color_to_reportlab(color)
for a in ["red", "green", "blue"]:
setattr(newcol, a, facto... | bcb937409a6790c6ac04a1550654e9b4fc398f9f | 3,643,798 |
def fetch_all_tiles(session):
"""Fetch all tiles."""
return session.query(Tile).all() | 15e21dff372859ad07f76d97944b9a002f44a35e | 3,643,799 |
def transaction_update_spents(txs, address):
"""
Update spent information for list of transactions for a specific address. This method assumes the list of
transaction complete and up-to-date.
This methods loops through all the transaction and update all transaction outputs for given address, checks
... | 6ac33306cafd5c75b37e73c405fff4bcc732226f | 3,643,800 |
def count_tilings(n: int) -> int:
"""Returns the number of unique ways to tile a row of length n >= 1."""
if n < 5:
# handle recursive base case
return 2**(n - 1)
else:
# place each tile at end of row and recurse on remainder
return (count_tilings(n - 1) +
cou... | 70f9caa9a27c65c73862dd8c415d93f5a7122632 | 3,643,801 |
import math
def _meters_per_pixel(zoom, lat=0.0, tilesize=256):
"""
Return the pixel resolution for a given mercator tile zoom and lattitude.
Parameters
----------
zoom: int
Mercator zoom level
lat: float, optional
Latitude in decimal degree (default: 0)
tilesize: int, opt... | 467d23bd437f153345c67c8c1cab1a086fde4995 | 3,643,802 |
import time
import random
def _generate_submit_id():
"""Generates a submit id in form of <timestamp>-##### where ##### are 5 random digits."""
timestamp = int(time())
return "%d-%05d" % (timestamp, random.randint(0, 99999)) | 285c975e626f0ef1ffe9482432c70b981c9bdea7 | 3,643,803 |
def draw_from_simplex(ndim: int, nsample: int = 1) -> np.ndarray:
"""Draw uniformly from an n-dimensional simplex.
Args:
ndim: Dimensionality of simplex to draw from.
nsample: Number of samples to draw from the simplex.
Returns:
A matrix of shape (nsample, ndim) that sums to one al... | 8dac53212a7ccdab7ed9e6cbbffdf437442de393 | 3,643,804 |
def manhattanDistance( xy1, xy2 ):
"""Returns the Manhattan distance between points xy1 and xy2"""
return abs( xy1[0] - xy2[0] ) + abs( xy1[1] - xy2[1] ) | ce0ee21237f253b1af33fbf088292405fd046fe3 | 3,643,805 |
import math
def Linear(in_features, out_features, dropout=0.0, bias=True):
"""Weight-normalized Linear layer (input: B x T x C)"""
m = nn.Linear(in_features, out_features, bias=bias)
m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features))
m.bias.data.zero_()
return nn.utils.weigh... | 38decbeda35ef9a6ab5d1397af224b77d49b3342 | 3,643,806 |
def homogeneous_type(obj):
"""
Checks that the type is "homogeneous" in that all lists are of objects of the same type, etc.
"""
return same_types(obj, obj) | e44a29de0651175f543cb9dc0d64a01e5a495e42 | 3,643,807 |
def crosscorr(f, g):
"""
Takes two vectors of the same size, subtracts the vector elements by their
respective means, and passes one over the other to construct a
cross-correlation vector
"""
N = len(f)
r = np.array([], dtype=np.single)
r1 = np.array([], dtype=np.single)
r2 = np.arr... | 6a4fec358404b7ca4f1df764c38518d39f635ed9 | 3,643,808 |
def nearest_neighbors(point_cloud_A, point_cloud_B, alg='knn'):
"""Find the nearest (Euclidean) neighbor in point_cloud_B (model) for each
point in point_cloud_A (data).
Parameters
----------
point_cloud_A: Nx3 numpy array
data points
point_cloud_B: Mx3 numpy array
model points
... | 0849c372c6358ded16c7907631a3bdd3c53385c6 | 3,643,809 |
def us_1040(form_values, year="latest"):
"""Compute US federal tax return."""
_dispatch = {
"latest": (ots_2020.us_main, data.US_1040_2020),
"2020": (ots_2020.us_main, data.US_1040_2020),
"2019": (ots_2019.us_main, data.US_1040_2019),
"2018": (ots_2018.us_main, data.US_1040_2018)... | 8056ea5dfae8698dd1e695b96680251f1fb45b63 | 3,643,810 |
def resolve_service_deps(services: list) -> dict:
"""loop through services and handle needed_by"""
needed_by = {}
for name in services:
service = services.get(name)
needs = service.get_tasks_needed_by()
for need, provides in needs.items():
needed_by[need] = list(set(neede... | 4979d24aa6105579c3208f2953f8bdc276ad127b | 3,643,811 |
def rolling_window(series, window_size):
"""
Transforms an array of series into an array of sliding window arrays. If
the passed in series is a matrix, each column will be transformed into an
array of sliding windows.
"""
return np.array(
[
series[i : (i + window_size)]
... | dfa95d12f287aeeb2f328919979376c0c890c0eb | 3,643,812 |
def ldns_key_set_inception(*args):
"""LDNS buffer."""
return _ldns.ldns_key_set_inception(*args) | 0411dd40b6d61740d872f1e4ac4f50683540de57 | 3,643,813 |
def verifyIP(ip):
"""Verifies an IP is valid"""
try:
#Split ip and integer-ize it
octets = [int(x) for x in ip.split('.')]
except ValueError:
return False
#First verify length
if len(octets) != 4:
return False
#Then check octet values
for octet in octets:
if octet < 0 or octet > 255:
return ... | 72c373099a75adb2a1e776c863b6a2d1cb2698df | 3,643,814 |
from datetime import datetime
def get_datetime_now(t=None, fmt='%Y_%m%d_%H%M_%S'):
"""Return timestamp as a string; default: current time, format: YYYY_DDMM_hhmm_ss."""
if t is None:
t = datetime.now()
return t.strftime(fmt) | c4fc830b7ede9d6f52ee81c014c03bb2ef5552dc | 3,643,815 |
def is_firstline(text, medicine, disease):
"""Detect if first-line treatment is mentioned with a medicine in a sentence.
Use keyword matching to detect if the keywords "first-line treatment" or "first-or second-line treatment", medicine name, and disease name all appear in the sentence.
Parameters
----------
... | c9f8a31c6089c4f7545780028ccb1a033372c284 | 3,643,816 |
def mac_address(addr):
""" mac_address checks that a given string is in MAC address format """
mac = addr.upper()
if not _mac_address_pattern.fullmatch(mac):
raise TypeError('{} does not match a MAC address pattern'.format(addr))
return mac | 201d32bd73f50c2818feef7c9c9be5371739dfcf | 3,643,817 |
def py3_classifiers():
"""Fetch the Python 3-related trove classifiers."""
url = 'https://pypi.python.org/pypi?%3Aaction=list_classifiers'
response = urllib_request.urlopen(url)
try:
try:
status = response.status
except AttributeError: #pragma: no cover
status = ... | 70e769811758bef05a9e3d8722eca13808acd514 | 3,643,818 |
def match(i, j):
"""
returns (red, white) count,
where red is matches in color and position,
and white is a match in color but not position
"""
red_count = 0
# these are counts only of the items that are not exact matches
i_colors = [0]*6
j_colors = [0]*6
for i_c, j_c in zip(c... | 06ddf17b6de367cd9158a33834431f3bc1c9e821 | 3,643,819 |
def time_delay_runge_kutta_4(fun, t_0, y_0, tau, history=None, steps=1000,
width=1):
"""
apply the classic Runge Kutta method to a time delay differential equation
f: t, y(t), y(t-tau) -> y'(t)
"""
width = float(width)
if not isinstance(y_0, np.ndarray):
y_0... | 02905a447e07857fdacc4c6b3e34ddf15726b141 | 3,643,820 |
def Vstagger_to_mass(V):
"""
V are the data on the top and bottom of a grid box
A simple conversion of the V stagger grid to the mass points.
Calculates the average of the top and bottom value of a grid box. Looping
over all rows reduces the staggered grid to the same dimensions as the
mass poin... | f3dbb75506f05acb9f65ff0fe0335f4fe139127b | 3,643,821 |
import base64
def verify_l4_block_pow(hash_type: SupportedHashes, block: "l4_block_model.L4BlockModel", complexity: int = 8) -> bool:
"""Verify a level 4 block with proof of work scheme
Args:
hash_type: SupportedHashes enum type
block: L4BlockModel with appropriate data to verify
Returns:
... | 301ea1c4e74ae34fb61610a7e614ac1af437a6c3 | 3,643,822 |
def file_reader(file_name):
"""file_reader"""
data = None
with open(file_name, "r") as f:
for line in f.readlines():
data = eval(line)
f.close()
return data | 6d3d63840cc48ccfdd5beefedf0d3a60c0f44cf9 | 3,643,824 |
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
account = model.authenticate(username, password)
if account is None:
return AuthResponse.no_account
if not model.hasAssignedBlock(account):
return AuthRespon... | 5c735f354ed56a5bc3960de96a76eacbc5a3bdd1 | 3,643,826 |
def plot_energy_ratio(
reference_power_baseline,
test_power_baseline,
wind_speed_array_baseline,
wind_direction_array_baseline,
reference_power_controlled,
test_power_controlled,
wind_speed_array_controlled,
wind_direction_array_controlled,
wind_direction_bins,
confidence=95,
... | 2ccdfa20dc8a475ab6c65086ab1f39d6db5e211f | 3,643,827 |
def first_position():
"""Sets up two positions in the
Upper left
.X.Xo.
X.Xoo.
XXX...
......
Lower right
......
..oooo
.oooXX
.oXXX.
(X = black, o = white)
They do not overlap as the Positions are size_limit 9 or greater.
"""
def position_moves(s):
re... | 029e965fe20f550030ece305975e96f7d1cd9115 | 3,643,829 |
def _create_teams(
pool: pd.DataFrame,
n_iterations: int = 500,
n_teams: int = 10,
n_players: int = 10,
probcol: str = 'probs'
) -> np.ndarray:
"""Creates initial set of teams
Returns:
np.ndarray of shape
axis 0 - number of iterations
... | 5889cc356a812c65ca7825e26c835b520cad1680 | 3,643,830 |
def calculate_magnitude(data: np.ndarray) -> np.ndarray:
"""Calculates the magnitude for given (x,y,z) axes stored in numpy array"""
assert data.shape[1] == 3, f"Numpy array should have 3 axes, got {data.shape[1]}"
return np.sqrt(np.square(data).sum(axis=1)) | 6493660467154d3e45c10a7a4350e87fa73c9719 | 3,643,831 |
def clean_str(string: str) -> str:
""" Cleans strings for SQL insertion """
return string.replace('\n', ' ').replace("'", "’") | d3833293163114642b4762ee25ea7c8f850e9d54 | 3,643,832 |
def zeros(shape, name=None):
"""All zeros."""
return tf.get_variable(name=name, shape=shape, dtype=tf.float32,
initializer=tf.zeros_initializer()) | 2c20b960bd17a0dc752883e65f7a18e77a7cde32 | 3,643,833 |
import io
def parseTemplate(bStream):
"""Parse the Template in current byte stream, it terminates when meets an object.
:param bStream: Byte stream
:return: The template.
"""
template = Template()
eof = endPos(bStream)
while True:
currPos = bStream.tell()
if currPos <eof:
... | 716858cde357be4036b62824ac17ba60cf71eea1 | 3,643,834 |
def load_circuit(filename:str):
""" Reads a MNSensitivity cicuit file (.mc) and returns a Circuit list
(format is 1D array of tuples, the first element contains a Component
object, the 2nd a SER/PAL string).
Format of the .mc file is:
* each line contains a Component object init string (See Com... | c77aa31f9a1c1f6803795c19de509ea967f65077 | 3,643,837 |
def get_output_attribute(out, attribute_name, cuda_device, reduction="sum"):
"""
This function handles processing/reduction of output for both
DataParallel or non-DataParallel situations.
For the case of multiple GPUs, This function will
sum all values for a certain output attribute in various batch... | c09ff6a3dd4ae2371b1bbec12d4617e9ed6c6e1e | 3,643,838 |
def get_ref_aidxs(df_fs):
"""Part of the hotfix for redundant FCGs.
I did not record the occurrence id in the graphs, which was stupid.
So now I need to use the df_fs to get the information instead.
Needs to be used with fid col, which is defined in filter_out_fcgs_ffs_all.
"""
return {k: v for ... | 9b57d7297d96f6b711bb9d3c37f85a17c4ccacd5 | 3,643,839 |
def format_info(info):
""" Print info neatly """
sec_width = 64
eq = ' = '
# find key width
key_widths = []
for section, properties in info.items():
for prop_key, prop_val in properties.items():
if type(prop_val) is dict:
key_widths.append(len(max(list(p... | 9dd3a6ef15909230725f2be6eb698e7ca08a2d8b | 3,643,840 |
import itertools
import copy
def server_handle_hallu_message(
msg_output, controller, mi_info, options, curr_iter):
"""
Petridish server handles the return message of a forked
process that watches over a halluciniation job.
"""
log_dir_root = logger.get_logger_dir()
q_child = controlle... | a4dc3da855066d719ca8a798a691864ed9d04e7f | 3,643,841 |
def pBottleneckSparse_model(inputs, train=True, norm=True, **kwargs):
"""
A pooled shallow bottleneck convolutional autoencoder model..
"""
# propagate input targets
outputs = inputs
# dropout = .5 if train else None
input_to_network = inputs['images']
shape = input_to_network.g... | 0a9609b776a9373f28bacf10f9f6aa9dcfbb17d2 | 3,643,842 |
def CoarseDropout(p=0, size_px=None, size_percent=None, per_channel=False, min_size=4, name=None, deterministic=False,
random_state=None, mask=None):
"""
Augmenter that sets rectangular areas within images to zero.
In contrast to Dropout, these areas can have larger sizes.
(E.g. you m... | c60828aa2a81459ef0a84440305f6d73939e2eb5 | 3,643,843 |
def chenneling(x):
"""
This function makes the dataset suitable for training.
Especially, gray scale image does not have channel information.
This function forces one channel to be created for gray scale images.
"""
# if grayscale image
if(len(x.shape) == 3):
C = 1
N, H, W =... | c47c1690affbb52c98343185cae7e0679bfff41a | 3,643,844 |
import collections
def _get_ordered_label_map(label_map):
"""Gets label_map as an OrderedDict instance with ids sorted."""
if not label_map:
return label_map
ordered_label_map = collections.OrderedDict()
for idx in sorted(label_map.keys()):
ordered_label_map[idx] = label_map[idx]
return ordered_labe... | 4c5e56789f57edda61409f0693c3bccb57ddc7cf | 3,643,845 |
def eight_interp(x, a0, a1, a2, a3, a4, a5, a6, a7):
"""``Approximation degree = 8``
"""
return (
a0
+ a1 * x
+ a2 * (x ** 2)
+ a3 * (x ** 3)
+ a4 * (x ** 4)
+ a5 * (x ** 5)
+ a6 * (x ** 6)
+ a7 * (x ** 7)
) | 98be2259c9e0fae214234b635a3ff55608f707d1 | 3,643,846 |
import logging
def create_ec2_instance(image_id, instance_type, keypair_name, user_data):
"""Provision and launch an EC2 instance
The method returns without waiting for the instance to reach
a running state.
:param image_id: ID of AMI to launch, such as 'ami-XXXX'
:param instance_type: string, s... | 4c1edda4b2aed0179026aacb6f5a95a0b550ef66 | 3,643,847 |
def get_pop(state):
"""Returns the population of the passed in state
Args:
- state: state in which to get the population
"""
abbrev = get_abbrev(state)
return int(us_areas[abbrev][1]) if abbrev != '' else -1 | 0d44a033eaff65c1430aab806a93686c68f5c490 | 3,643,848 |
import requests
import json
def GitHub_post(data, url, *, headers):
"""
POST the data ``data`` to GitHub.
Returns the json response from the server, or raises on error status.
"""
r = requests.post(url, headers=headers, data=json.dumps(data))
GitHub_raise_for_status(r)
return r.json() | 7dbdbd3beed6e39ff3e20509114a11761a05ab52 | 3,643,849 |
def subsample(inputs, factor, scope=None):
"""Subsample the input along the spatial dimensions.
Args:
inputs: A `Tensor` of size [batch, height_in, width_in, channels].
factor: The subsampling factor.
scope: Optional variable_scope.
Returns:
output: A `Tensor` of size [batc... | 32df6bccbb016d572bbff227cf42aadeb07c6242 | 3,643,850 |
def password_reset(*args, **kwargs):
"""
Override view to use a custom Form
"""
kwargs['password_reset_form'] = PasswordResetFormAccounts
return password_reset_base(*args, **kwargs) | a2764365118cc0264fbeddf0b79457a0f7bf3c62 | 3,643,851 |
def update_tab_six_two(
var,
time_filter,
month,
hour,
data_filter,
filter_var,
min_val,
max_val,
normalize,
global_local,
df,
):
"""Update the contents of tab size. Passing in the info from the dropdown and the general info."""
df = pd.read_json(df, orient="split")
... | 0ce47fc30c088eae245de1da8bc4392408f16e26 | 3,643,852 |
import json
async def blog_api(request: Request, year: int, month: int, day: int,
title: str) -> json:
"""Handle blog."""
blog_date = {"year": year, "month": month, "day": day}
req_blog = app.blog.get(xxh64(unquote(title)).hexdigest())
if req_blog:
if all(
ma... | 6c497a9280c8c8a1301f407c06065846267743f8 | 3,643,853 |
def coherence_score_umass(X, inv_vocabulary, top_words, normalized=False):
"""
Extrinsic UMass coherence measure
Parameter
----------
X : array-like, shape=(n_samples, n_features)
Document word matrix.
inv_vocabulary: dict
Dictionary of index and vocabulary from vectorizer.
... | 185cfa1e6df64e799ae07116c8f88ef9cd37c94b | 3,643,854 |
def _splitaddr(addr):
"""
splits address into character and decimal
:param addr:
:return:
"""
col='';rown=0
for i in range(len(addr)):
if addr[i].isdigit():
col = addr[:i]
rown = int(addr[i:])
break
elif i==len(addr)-1:
col=addr... | 6f4ef43ed926a468ae5ae22fc062fe2b2701a18a | 3,643,855 |
def checksum(data):
"""
:return: int
"""
assert isinstance(data, bytes)
assert len(data) >= MINIMUM_MESSAGE_SIZE - 2
assert len(data) <= MAXIMUM_MESSAGE_SIZE - 2
__checksum = 0
for data_byte in data:
__checksum += data_byte
__checksum = -(__checksum % 256) + 256
try:
... | 105bb5a9fe748ee352c080939ea33936c661e77b | 3,643,856 |
def as_character(
x,
str_dtype=str,
_na=np.nan,
):
"""Convert an object or elements of an iterable into string
Aliases `as_str` and `as_string`
Args:
x: The object
str_dtype: The string dtype to convert to
_na: How NAs should be casted. Specify np.nan will keep them unc... | ed8653f5c713fd257062580e03d26d48aaac3421 | 3,643,857 |
def test_logger(request: HttpRequest) -> HttpResponse:
"""
Generate a log to test logging setup.
Use a GET parameter to specify level, default to INFO if absent. Value can be INFO, WARNING, ERROR,
EXCEPTION, UNCATCHED_EXCEPTION.
Use a GET parameter to specify message, default to "Test logger"
... | 04ef0d03d85402b5005660d9a06ae6ec775cb712 | 3,643,858 |
def remoteness(N):
"""
Compute the remoteness of N.
Parameters
----------
N : Nimber
The nimber of interest.
Returns
-------
remote : int
The remoteness of N.
"""
if N.n == 0:
return 0
remotes = {remoteness(n) for n in N.left}
if all(remote % 2... | 6ea40df2a79a2188b3d7c9db69ee9038ec2e6462 | 3,643,860 |
def breakfast_analysis_variability(in_path,identifier, date_col, time_col, min_log_num=2, min_separation=4, plot=True):
"""
Description:\n
This function calculates the variability of loggings in good logging day by subtracting 5%,10%,25%,50%,75%,90%,95% quantile of breakfast time from the 50% breakfast t... | e174f57fd146e07d41f0fc21c028711ae581a580 | 3,643,861 |
def _sdss_wcs_to_log_wcs(old_wcs):
"""
The WCS in the SDSS files does not appear to follow the WCS standard - it
claims to be linear, but is logarithmic in base-10.
The wavelength is given by:
λ = 10^(w0 + w1 * i)
with i being the pixel index starting from 0.
The FITS standard uses a natura... | b4b4427d5563e85f80ddc2200e9c323098ad35ae | 3,643,862 |
def request_records(request):
"""show the datacap request records"""
address = request.POST.get('address')
page_index = request.POST.get('page_index', '1')
page_size = request.POST.get('page_size', '5')
page_size = interface.handle_page(page_size, 5)
page_index = interface.handle_page(page_index... | 6eac819ab78afa6e7df00be8e47b87344a129abc | 3,643,863 |
def extendCorrespondingAtomsDictionary(names, str1, str2):
"""
extends the pairs based on list1 & list2
"""
list1 = str1.split()
list2 = str2.split()
for i in range(1, len(list1)):
names[list1[0]][list2[0]].append([list1[i], list2[i]])
names[list2[0]][list1[0]].append([list2[i], list... | cb586be8dcf7a21af556b332cfedbdce0be6882a | 3,643,864 |
def _device_name(data):
"""Return name of device tracker."""
if ATTR_BEACON_ID in data:
return "{}_{}".format(BEACON_DEV_PREFIX, data['name'])
return data['device'] | 7a3dd5765d12c7f1b78c87c6188d3afefd4228ee | 3,643,865 |
def get_share_path(
storage_server: StorageServer, storage_index: bytes, sharenum: int
) -> FilePath:
"""
Get the path to the given storage server's storage for the given share.
"""
return (
FilePath(storage_server.sharedir)
.preauthChild(storage_index_to_dir(storage_index))
... | e37566e0cb09bf6c490e6e0faf024cedf91c4576 | 3,643,866 |
import torch
def focal_loss_with_prob(prob,
target,
weight=None,
gamma=2.0,
alpha=0.25,
reduction='mean',
avg_factor=None):
"""A variant of Focal Loss used in TOOD."""
target_one_hot = prob.new_zeros(len(prob), len(prob[0]) + 1)
target_one_hot = target_one_hot.scatter_(1, ... | 0c730a1eef5487d3ce5b79c06fda5d8a0e8542a7 | 3,643,867 |
def root_key_from_seed(seed):
"""This derives your master key the given seed.
Implemented in ripple-lib as ``Seed.prototype.get_key``, and further
is described here:
https://ripple.com/wiki/Account_Family#Root_Key_.28GenerateRootDeterministicKey.29
"""
seq = 0
while True:
private_ge... | b93cfa8c31ab061f6496f8e12f5c3d7ba5f0d7a7 | 3,643,868 |
def fake_login(request):
"""Contrived version of a login form."""
if getattr(request, 'limited', False):
raise RateLimitError
if request.method == 'POST':
password = request.POST.get('password', 'fail')
if password is not 'correct':
return False
return True | 41b2621b38a302837c9f8ab1fafa0a4f45ca2c26 | 3,643,870 |
def split_to_sentences(data):
"""
Split data by linebreak "\n"
Args:
data: str
Returns:
A list of sentences
"""
sentences = data.split('\n')
# Additional clearning (This part is already implemented)
# - Remove leading and trailing spaces from each sentence... | 56540da88e982615e3874ab9f6fd22229a076565 | 3,643,871 |
def read_config_file(fp: str, mode='r', encoding='utf8', prefix='#') -> dict:
"""
读取文本文件,忽略空行,忽略prefix开头的行,返回字典
:param fp: 配置文件路径
:param mode:
:param encoding:
:param prefix:
:return:
"""
with open(fp, mode, encoding=encoding) as f:
ll = f.readlines()
ll = [i for i in... | 94e6130de22b05ca9dd6855206ec748e63dad8ad | 3,643,872 |
def PrepareForMakeGridData(
allowed_results, starred_iid_set, x_attr,
grid_col_values, y_attr, grid_row_values, users_by_id, all_label_values,
config, related_issues, hotlist_context_dict=None):
"""Return all data needed for EZT to render the body of the grid view."""
def IssueViewFactory(issue):
r... | a8e8a70f56001398e75f1ab2e82c8e995e164203 | 3,643,873 |
def custom_address_validator(value, context):
"""
Address not required at all for this example,
skip default (required) validation.
"""
return value | 06ec3af3b6103c06be5fc9cf30d1af28bd072193 | 3,643,874 |
from typing import Tuple
def get_model(args) -> Tuple:
"""Choose the type of VQC to train. The normal vqc takes the latent space
data produced by a chosen auto-encoder. The hybrid vqc takes the same
data that an auto-encoder would take, since it has an encoder or a full
auto-encoder attached to it.
... | fb50a114efdd1f4f358edf2906aad861688056de | 3,643,876 |
def tail_ratio(returns):
"""
Determines the ratio between the right (95%) and left tail (5%).
For example, a ratio of 0.25 means that losses are four times
as bad as profits.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full... | 620fa7b5f5887f80b3fd56e2fb24077cbc3dcf86 | 3,643,877 |
def get_trajectory_for_weight(simulation_object, weight):
"""
:param weight:
:return:
"""
print(simulation_object.name+" - get trajectory for w=", weight)
controls, features, _ = simulation_object.find_optimal_path(weight)
weight = list(weight)
features = list(features)
return {"w": ... | e68827fc3631d4467ae1eb82b3c319a4e45d6a9b | 3,643,878 |
def UnNT(X, Z, N, T, sampling_type):
"""Computes reshuffled block-wise complete U-statistic."""
return np.mean([UnN(X, Z, N, sampling_type=sampling_type)
for _ in range(T)]) | e250de27fc9bfcd2244269630591ab8f925b29af | 3,643,879 |
def boolean_matrix_of_image(image_mat, cutoff=0.5):
"""
Make a bool matrix from the input image_mat
:param image_mat: a 2d or 3d matrix of ints or floats
:param cutoff: The threshold to use to make the image pure black and white. Is applied to the max-normalized matrix.
:return:
"""
if not i... | 3b23c946709cde552a8c2c2e2bee0a3c91107e85 | 3,643,880 |
import torch
def global_pool_1d(inputs, pooling_type="MAX", mask=None):
"""Pool elements across the last dimension.
Useful to convert a list of vectors into a single vector so as
to get a representation of a set.
Args:
inputs: A tensor of shape [batch_size, sequence_length, input_dims]
c... | a8c7d51c76efaaae64a8725ae9296894fdc9b933 | 3,643,881 |
def _monte_carlo_trajectory_sampler(
time_horizon: int = None,
env: DynamicalSystem = None,
policy: BasePolicy = None,
state: np.ndarray = None,
):
"""Monte-Carlo trajectory sampler.
Args:
env: The system to sample from.
policy: The policy applied to the system during sampling.
... | 9107289e89a37bd29bc96d2d549b74f15d3008e0 | 3,643,882 |
def pi_mult(diff: float) -> int:
"""
Функция, вычисляющая множитель, на который нужно домножить 2 pi, чтобы компенсировать разрыв фазы
:param diff: разность фазы в двух ячейках матрицы
:return : целое число
"""
return int(0.5 * (diff / pi + 1)) if diff > 0 else int(0.5 * (diff / pi - 1)) | 041c4740fba4b9983ec927d3fb3d8f5421e4919c | 3,643,883 |
import warnings
def get_integer(val=None, name="value", min_value=0, default_value=0):
"""Returns integer value from input, with basic validation
Parameters
----------
val : `float` or None, default None
Value to convert to integer.
name : `str`, default "value"
What the value rep... | 9c967a415eaac58a4a4778239859d1f6d0a87820 | 3,643,884 |
def release(cohesin, occupied, args):
"""
AN opposite to capture - releasing cohesins from CTCF
"""
if not cohesin.any("CTCF"):
return cohesin # no CTCF: no release necessary
# attempting to release either side
for side in [-1, 1]:
if (np.random.random() <... | 89d0d1446f1c5ee45a8e190dff76b91ea59a3bcf | 3,643,886 |
def cosine(u, v):
"""
d = cosine(u, v)
Computes the Cosine distance between two n-vectors u and v,
(1-uv^T)/(||u||_2 * ||v||_2).
"""
u = np.asarray(u)
v = np.asarray(v)
return (1.0 - (np.dot(u, v.T) / \
(np.sqrt(np.dot(u, u.T)) * np.sqrt(np.dot(v, v.T))))) | 139b38f674bc19e50bf37714b3593e7f055c5b7f | 3,643,887 |
from typing import Iterator
from typing import Tuple
from typing import Any
def _train_model(
train_iter: Iterator[DataBatch],
test_iter: Iterator[DataBatch],
model_type: str,
num_train_iterations: int = 10000,
learning_rate: float = 1e-5
) -> Tuple[Tuple[Any, Any], Tuple[onp.ndarray, onp.ndarray]... | 46043beaf170f164f13e91fec3a30d024ede6dc8 | 3,643,889 |
def swig_base_TRGBPixel_getMin():
"""swig_base_TRGBPixel_getMin() -> CRGBPixel"""
return _Core.swig_base_TRGBPixel_getMin() | 454de4b9f3014b950ebe609ab80d15f0c71cd175 | 3,643,891 |
def archive_deleted_rows(context, max_rows=None):
"""Move up to max_rows rows from production tables to the corresponding
shadow tables.
:returns: Number of rows archived.
"""
# The context argument is only used for the decorator.
tablenames = []
for model_class in models.__dict__.itervalue... | c2c26191824edfe3d31ed5b0f321022f5bac85a5 | 3,643,892 |
from typing import TextIO
import json
def load_wavefunction(file: TextIO) -> Wavefunction:
"""Load a qubit wavefunction from a file.
Args:
file (str or file-like object): the name of the file, or a file-like object.
Returns:
wavefunction (pyquil.wavefunction.Wavefunction): the wavefuncti... | 23b38e0739f655e5625775c80baa81874b48d45f | 3,643,893 |
import requests
def delete_alias(request, DOMAIN, ID):
"""
Delete Alias based on ID
ENDPOINT : /api/v1/alias/:domain/:id
"""
FORWARD_EMAIL_ENDPOINT = f"https://api.forwardemail.net/v1/domains/{DOMAIN}/aliases/{ID}"
res = requests.delete(FORWARD_EMAIL_ENDPOINT, auth=(USERNAME, ''))
if res.s... | ca59eccef303461b3be562c6167753959ad3eb67 | 3,643,894 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.