content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def tau_for_x(x, beta):
"""Rescales tau axis to x -1 ... 1"""
if x.min() < -1 or x.max() > 1:
raise ValueError("domain of x")
return .5 * beta * (x + 1) | 1d7b868dfadb65e6f98654276763fd4bff2c20ff | 3,653,700 |
from typing import Optional
from typing import Dict
def _generate_element(name: str,
text: Optional[str] = None,
attributes: Optional[Dict] = None) -> etree.Element:
"""
generate an ElementTree.Element object
:param name: namespace+tag_name of the element
:... | d7d8f7d174f207d64993aca54803af6600c3ddb6 | 3,653,701 |
def CoA_Cropland_URL_helper(*, build_url, config, **_):
"""
This helper function uses the "build_url" input from flowbyactivity.py,
which is a base url for data imports that requires parts of the url text
string to be replaced with info specific to the data year. This function
does not parse the dat... | 5cd08b8c4198428e45267f33d35d98b63df4fd17 | 3,653,702 |
def _centered_bias(logits_dimension, head_name=None):
"""Returns `logits`, optionally with centered bias applied.
Args:
logits_dimension: Last dimension of `logits`. Must be >= 1.
head_name: Optional name of the head.
Returns:
Centered bias `Variable`.
Raises:
ValueError: if `logits_dimension... | 868fc2681ee1177932b77bdfe9ce9eefc3c5fde1 | 3,653,703 |
from typing import Union
from typing import List
def get_columns(dataframe: pd.DataFrame,
columns: Union[str, List[str]]) -> Union[pd.Series, pd.DataFrame]:
"""Get the column names, and can rename according to list"""
return dataframe[list(columns)].copy(True) | e624233a3aca3f71f203bf7acca700722819b237 | 3,653,704 |
import pandas
import math
def get_vote_activity(session):
"""Create a plot showing the inline usage statistics."""
creation_date = func.date_trunc("day", Vote.created_at).label("creation_date")
votes = (
session.query(creation_date, func.count(Vote.id).label("count"))
.group_by(creation_da... | 9b59ad083147d7e21d8d32e730b235a23b187c0f | 3,653,705 |
def viz_graph(obj):
"""
Generate the visulization of the graph in the JupyterLab
Arguments
-------
obj: list
a list of Python object that defines the nodes
Returns
-----
nx.DiGraph
"""
G = nx.DiGraph()
# instantiate objects
for o in obj:
for i in o['input... | a826438b3e207f88a7bddddcd4fc02a4ad9c753d | 3,653,706 |
def zrand_convolve(labelgrid, neighbors='edges'):
"""
Calculates the avg and std z-Rand index using kernel over `labelgrid`
Kernel is determined by `neighbors`, which can include all entries with
touching edges (i.e., 4 neighbors) or corners (i.e., 8 neighbors).
Parameters
----------
grid ... | 4b3950239886cb7e41fb2a7105c2413234dcdb30 | 3,653,707 |
def msg_receiver():
"""
消息已收界面
:return:
"""
return render_template('sysadmin/sysmsg/sys_msg_received.html', **locals()) | 0902f9eb4ad75802d7f858f4474c5e587082403f | 3,653,708 |
from datetime import datetime
def abs_timedelta(delta):
"""Returns an "absolute" value for a timedelta, always representing a
time distance."""
if delta.days < 0:
now = datetime.datetime.now()
return now - (now + delta)
return delta | 81018ea9c54585a8c24e52cc48c21fcb2d73e9b3 | 3,653,709 |
def make_new_get_user_response(row):
""" Returns an object containing only what needs to be sent back to the user. """
return {
'userName': row['userName'],
'categories': row['categories'],
'imageName': row['imageName'],
'refToImage': row['refToImage'],
... | e13d8d297bd1401752ce07d93a68e765ed1113e8 | 3,653,711 |
def is_feature_enabled():
"""
Helper to check Site Configuration for ENABLE_COURSE_ACCESS_GROUPS.
:return: bool
"""
is_enabled = bool(configuration_helpers.get_value('ENABLE_COURSE_ACCESS_GROUPS', default=False))
if is_enabled:
# Keep the line below in sync with `util.organizations_hel... | 57f0b94409d9332f8846d64a6a30518b6dcc8173 | 3,653,713 |
def solve_disp_eq(betbn, betbt, bet, Znak, c, It, Ia, nb, var):
"""
Решение дисперсионного уравнения.
Znak = -1 при преломлении
Znak = 1 при отражении
"""
betb = sqrt(betbn ** 2. + betbt ** 2.)
gamb = 1. / sqrt(1. - betb ** 2.)
d = c * It / Ia
Ab = 1. + (nb ** 2. - 1.) * gamb ** 2. *... | b67b41cdccf37a14fda103b6f05263c7cbb4514e | 3,653,714 |
import numpy
def phistogram(view, a, bins=10, rng=None, normed=False):
"""Compute the histogram of a remote array a.
Parameters
----------
view
IPython DirectView instance
a : str
String name of the remote array
bins : int
Number of histogra... | 3c4633891b495a5cad867c945a8f8cc1c6b3c14f | 3,653,715 |
from typing import Iterable
from typing import Iterator
def windowed(it: Iterable[_T], size: int) -> Iterator[tuple[_T, ...]]:
"""Retrieve overlapped windows from iterable.
>>> [*windowed(range(5), 3)]
[(0, 1, 2), (1, 2, 3), (2, 3, 4)]
"""
return zip(*(islice(it_, start, None)
fo... | 6e3b29b67f9eb323d00065fa58ccd916c7c49640 | 3,653,716 |
def minmax(data):
"""Solution to exercise R-1.3.
Takes a sequence of one or more numbers, and returns the smallest and
largest numbers, in the form of a tuple of length two. Do not use the
built-in functions min or max in implementing the solution.
"""
min_idx = 0
max_idx = 0
for idx, n... | 9715bef69c120f6d1afb933bd9030240f556eb20 | 3,653,717 |
def sample_discreate(prob, n_samples):
"""根据类先验分布对标签值进行采样
M = sample_discreate(prob, n_samples)
Input:
prob: 类先验分布 shape=(n_classes,)
n_samples: 需要采样的数量 shape = (n_samples,)
Output:
M: 采样得到的样本类别 shape = (n_samples,)
例子:
sample_discreate([0.8,0.2],n_sa... | 34c19c2dcbad652bdae8f2c829f42934c2176e84 | 3,653,718 |
from xml.dom.minidom import parseString # tools for handling XML in python
def get_catalyst_pmids(first, middle, last, email, affiliation=None):
"""
Given an author's identifiers and affiliation information, optional lists of pmids, call the catalyst service
to retrieve PMIDS for the author and return a ... | d0cb5560ec8e6f80627b40c4623683732c84dc7c | 3,653,719 |
from typing import List
from typing import Dict
def upload_categories_to_fyle(workspace_id):
"""
Upload categories to Fyle
"""
try:
fyle_credentials: FyleCredential = FyleCredential.objects.get(workspace_id=workspace_id)
xero_credentials: XeroCredentials = XeroCredentials.objects.get(w... | 0efcdc205a3aaa33acd88a231984ab9407d994ac | 3,653,721 |
def georegister_px_df(df, im_fname=None, affine_obj=None, crs=None,
geom_col='geometry', precision=None):
"""Convert a dataframe of geometries in pixel coordinates to a geo CRS.
Arguments
---------
df : :class:`pandas.DataFrame`
A :class:`pandas.DataFrame` with polygons in... | e310fee04d214186f60965e68fb2b896b8ad0004 | 3,653,722 |
def load_ui_type(ui_file):
"""
Pyside "load_ui_type" command like PyQt4 has one, so we have to convert the
ui file to py code in-memory first and then execute it in a special frame
to retrieve the form_class.
"""
parsed = xml.parse(ui_file)
widget_class = parsed.find('widget').get('class')... | 1f9bfc05d52fd8f25d63104c93f675cc8e978501 | 3,653,723 |
def how_did_I_do(MLP, df, samples, expected):
"""Simple report of expected inputs versus actual outputs."""
predictions = MLP.predict(df[samples].to_list())
_df = pd.DataFrame({"Expected": df[expected], "Predicted": predictions})
_df["Correct"] = _df["Expected"] == _df["Predicted"]
print(f'The netwo... | 5fbebeac01dad933c20b3faf3f8682ae59d173ba | 3,653,724 |
def all_bootstrap_os():
"""Return a list of all the OS that can be used to bootstrap Spack"""
return list(data()['images']) | b7a58aabe17ee28ed783a9d43d1d8db5d0b85db3 | 3,653,725 |
def coords_to_volume(coords: np.ndarray, v_size: int,
noise_treatment: bool = False) -> np.ndarray:
"""Converts coordinates to binary voxels.""" # Input is centered on [0,0,0].
return weights_to_volume(coords=coords, weights=1, v_size=v_size, noise_treatment=noise_treatment) | 62e2ba5549faff51e4da68f6bc9521ff2f9ce9cb | 3,653,726 |
def logo(symbol, external=False, vprint=False):
""":return: Google APIs link to the logo for the requested ticker.
:param symbol: The ticker or symbol of the stock you would like to request.
:type symbol: string, required
"""
instance = iexCommon('stock', symbol, 'logo', external=external)
retu... | 320755632f81686ceb35a75b44c5176893ea37e2 | 3,653,727 |
def get_dependency_node(element):
""" Returns a Maya MFnDependencyNode from the given element
:param element: Maya node to return a dependency node class object
:type element: string
"""
# adds the elements into an maya selection list
m_selectin_list = OpenMaya.MSelectionList()
m_selectin_... | d573b14cf7ba54fd07f135d37c90cfe75e74992a | 3,653,728 |
def create_lineal_data(slope=1, bias=0, spread=0.25, data_size=50):
"""
Helper function to create lineal data.
:param slope: slope of the lineal function.
:param bias: bias of the lineal function.
:param spread: spread of the normal distribution.
:param data_size: number of samples to generate.... | fa735416a1f23a5aa29f66e353d187a5a896df7a | 3,653,729 |
def parse_station_resp(fid):
"""
Gather information from a single station IRIS response file
*fid*. Return the information as a :class:`RespMap`.
"""
resp_map = RespMap()
# sanity check initialization
network = None
stn = None
location = None
# skip initial header comment block
... | 9d61b2c033008fc594b230aad83378a442cb748b | 3,653,730 |
def plot_pol(image, figsize=(8,8), print_stats=True, scaled=True, evpa_ticks=True):
"""Mimics the plot_pol.py script in ipole/scripts"""
fig, ax = plt.subplots(2, 2, figsize=figsize)
# Total intensity
plot_I(ax[0,0], image, xlabel=False)
# Quiver on intensity
if evpa_ticks:
plot_evpa_ti... | dc3741703435bb95b7ea511460d9feda39ea11f3 | 3,653,731 |
def _ensure_dtype_type(value, dtype: DtypeObj):
"""
Ensure that the given value is an instance of the given dtype.
e.g. if out dtype is np.complex64_, we should have an instance of that
as opposed to a python complex object.
Parameters
----------
value : object
dtype : np.dtype or Exte... | 36de4b993e2da0bacf3228d46e13332f89346210 | 3,653,733 |
from typing import List
def format_batch_request_last_fm(listens: List[Listen]) -> Request:
"""
Format a POST request to scrobble the given listens to Last.fm.
"""
assert len(listens) <= 50, 'Last.fm allows at most 50 scrobbles per batch.'
params = {
'method': 'track.scrobble',
's... | 8f7b36b6880ecd91e19282b80975cccc999014b6 | 3,653,734 |
def get_entry_for_file_attachment(item_id, attachment):
"""
Creates a file entry for an attachment
:param item_id: item_id of the attachment
:param attachment: attachment dict
:return: file entry dict for attachment
"""
entry = fileResult(get_attachment_name(attachment.name), attachment.cont... | c3d10402da0ada14289a7807ef1a57f97c6a22ba | 3,653,737 |
def check_all_particles_present(partlist, gambit_pdg_codes):
"""
Checks all particles exist in the particle_database.yaml.
"""
absent = []
for i in range(len(partlist)):
if not partlist[i].pdg() in list(gambit_pdg_codes.values()):
absent.append(partlist[i])
absent_... | eab49388d472934a61900d8e972c0f2ef01ae1fb | 3,653,738 |
def binarize_tree(t):
"""Convert all n-nary nodes into left-branching subtrees
Returns a new tree. The original tree is intact.
"""
def recurs_binarize_tree(t):
if t.height() <= 2:
return t[0]
if len(t) == 1:
return recurs_binarize_tree(t[0])
elif len(t)... | 5f9bc8ab7a0c1ab862b7366b188072006a80ff51 | 3,653,739 |
def calculate_prfs_using_rdd(y_actual, y_predicted, average='macro'):
"""
Determines the precision, recall, fscore, and support of the predictions.
With average of macro, the algorithm Calculate metrics for each label, and find their unweighted mean.
See http://scikit-learn.org/stable/modules/generated/... | 01fadc6a03f6ce24e736da9d1cfd088b490aa482 | 3,653,740 |
def translation_from_matrix(M):
"""Returns the 3 values of translation from the matrix M.
Parameters
----------
M : list[list[float]]
A 4-by-4 transformation matrix.
Returns
-------
[float, float, float]
The translation vector.
"""
return [M[0][3], M[1][3], M[2][3]... | 2b3bddd08772b2480a923a778d962f8e94f4b78a | 3,653,741 |
def saving_filename_boundary(save_location, close_up, beafort, wave_roughness):
""" Setting the filename of the figure """
if close_up is None:
return save_location + 'Boundary_comparison_Bft={}_roughness={}.png'.format(beafort, wave_roughness)
else:
ymax, ymin = close_up
return save... | c0357a211adc95c35873a0f3b0c900f6b5fe42d0 | 3,653,742 |
def get_library() -> CDLL:
"""Return the CDLL instance, loading it if necessary."""
global LIB
if LIB is None:
LIB = _load_library("aries_askar")
_init_logger()
return LIB | 64183953e7ab3f4e617b050fbf985d79aebc9b95 | 3,653,743 |
def childs_page_return_right_login(response_page, smarsy_login):
"""
Receive HTML page from login function and check we've got expected source
"""
if smarsy_login in response_page:
return True
else:
raise ValueError('Invalid Smarsy Login') | e7cb9b8d9df8bd5345f308e78cec28a20919370e | 3,653,744 |
def merge_files(intakes, outcomes):
"""
Merges intakes and outcomes datasets to create unique line for each animal in the shelter to capture full stories for each animal
takes intakes file then outcomes file as arguments
returns merged dataset
"""
# Merge intakes and outcomes on animal id and yea... | c7110cf1b5fe7fad52c3e331c8d6840de83891b3 | 3,653,745 |
def construct_features_MH_1(data):
"""
Processes the provided pandas dataframe object by:
Deleting the original METER_ID, LOCATION_NO, BILLING_CYCLE, COMMENTS, and DAYS_FROM_BILLDT columns
Constructing a time series index out of the year, month, day, hour, minute, second columns
Sorting by the tim... | 32f238ee730e84c0c699759913ffd2f6a2fc6fbf | 3,653,747 |
from functools import cmp_to_key
def sort_observations(observations):
"""
Method to sort observations to make sure that the "winner" is at index 0
"""
return sorted(observations, key=cmp_to_key(cmp_observation), reverse=True) | 183b044a48b4a7ea5093efaa92bd0977b085d949 | 3,653,748 |
def coor_trans(point, theta):
"""
coordinate transformation (坐标转换)
theta方向:以顺时针旋转为正
"""
point = np.transpose(point)
k = np.array([[np.cos(theta), np.sin(theta)],
[-np.sin(theta), np.cos(theta)]])
print(point)
# return np.dot(k, point)
return np.round(np.dot(k, point),6) | aa3b1532c629011e6f0ce72dc80eb1eebfc43765 | 3,653,749 |
import torch
import time
def ppo(
env_fn,
actor_critic=core.MLPActorCritic2Heads,
ac_kwargs=dict(),
seed=0,
steps_per_epoch=4000,
epochs=100,
epochs_rnd_warmup=1,
gamma=0.99,
clip_ratio=0.2,
pi_lr=3e-4,
vf_lr=1e-3,
rnd_lr=1e-3,
train_pi_iters=80,
train_v_iters=8... | 481da1fc7cc0677e02009d983345a15fbca23159 | 3,653,750 |
import heapq
def ltopk(k, seq, key=None):
"""
>>> ltopk(2, [1, 100, 10, 1000])
[1000, 100]
>>> ltopk(2, ['Alice', 'Bob', 'Charlie', 'Dan'], key=len)
['Charlie', 'Alice']
"""
if key is not None and not callable(key):
key = getter(key)
return list(heapq.nlargest(k, seq, key=key)) | 3d41f8576ca6b2741d12ca8b80c8fb220166b85b | 3,653,751 |
def index():
""" Root URL response """
return (
jsonify(
name="Promotion REST API Service",
version="1.0",
),
status.HTTP_200_OK,
) | 7c45e54c3500f638291c85d38d27976952d0a6e3 | 3,653,752 |
def add_cameras_default(scene):
""" Make two camera (main/top) default setup for demo images."""
cam_main = create_camera_perspective(
location=(-33.3056, 24.1123, 26.0909),
rotation_quat=(0.42119, 0.21272, -0.39741, -0.78703),
)
scene.collection.objects.link(cam_main)
cam_top = cre... | 50428d5f3c79c4581e397af1411a5a92055fe695 | 3,653,753 |
def distr_mean_stde(distribution: np.ndarray) -> tuple:
"""
Purpose:
Compute the mean and standard deviation for a distribution.
Args:
distribution (np.ndarray): distribution
Returns:
tuple (ie. distribution mean and standard deviation)
"""
# Compute and print the mean,... | 9232587e2c1e71a8f7c672cb962961cab7ad8d85 | 3,653,754 |
from operator import and_
def release_waiting_requests_grouped_fifo(rse_id, count=None, direction='destination', deadline=1, volume=0, session=None):
"""
Release waiting requests. Transfer requests that were requested first, get released first (FIFO).
Also all requests to DIDs that are attached to the sam... | 9a52a28fe06634de73a0436721aa97e590612e17 | 3,653,755 |
def _get_gap_memory_pool_size_MB():
"""
Return the gap memory pool size suitable for usage on the GAP
command line.
The GAP 4.5.6 command line parser had issues with large numbers, so
we return it in megabytes.
OUTPUT:
String.
EXAMPLES:
sage: from sage.interfaces.gap import ... | 035072ff6fff18859717b131cdd660f252ac6262 | 3,653,756 |
async def order_book_l2(symbol: str) -> dict:
"""オーダーブックを取得"""
async with pybotters.Client(base_url=base_url, apis=apis) as client:
r = await client.get("/orderBook/L2", params={"symbol": symbol,},)
data = await r.json()
return data | 4c9b8e067874871cda8b9a9f113f8ff6e4529c02 | 3,653,757 |
async def create_comment_in_post(*, post: models.Post = Depends(resolve_post), created_comment: CreateComment,
current_user: models.User = Depends(resolve_current_user),
db: Session = Depends(get_db)):
"""Create a comment in a post."""
return cru... | 90e4a8628d631bcb33eb5462e0e8001f90fb5c86 | 3,653,759 |
def sigma_bot(sigma_lc_bot, sigma_hc_bot, x_aver_bot_mass):
"""
Calculates the surface tension at the bottom of column.
Parameters
----------
sigma_lc_bot : float
The surface tension of low-boilling component at the bottom of column, [N / m]
sigma_hc_bot : float
The surface tensi... | 5105e5592556cab14cb62ab61b4f242499b33e1d | 3,653,760 |
def _normalize_zonal_lat_lon(ds: xr.Dataset) -> xr.Dataset:
"""
In case that the dataset only contains lat_centers and is a zonal mean dataset,
the longitude dimension created and filled with the variable value of certain latitude.
:param ds: some xarray dataset
:return: a normalized xarray dataset
... | 0a6021cc22271d6489a1a946e5ff38a6019ae3e8 | 3,653,761 |
def setup_audio(song_filename):
"""Setup audio file
and setup setup the output device.output is a lambda that will send data to
fm process or to the specified ALSA sound card
:param song_filename: path / filename to music file
:type song_filename: str
:return: output, fm_process, fft_calc, mus... | 63ca73faf6511047d273e3b36d3ef450dc073a2f | 3,653,762 |
def _collect_package_prefixes(package_dir, packages):
"""
Collect the list of prefixes for all packages
The list is used to match paths in the install manifest to packages
specified in the setup.py script.
The list is sorted in decreasing order of prefix length so that paths are
matched with t... | 6c497725e8a441f93f55084ef42489f97e35acf8 | 3,653,763 |
def _grae_ymin_ ( graph ) :
"""Get minimal y for the points
>>> graph = ...
>>> ymin = graph.ymin ()
"""
ymn = None
np = len(graph)
for ip in range( np ) :
x , exl , exh , y , eyl , eyh = graph[ip]
y = y - abs( eyl )
if None == ymn or y <= ymn : ymn = y
... | 99efb6f6466e56b350da02963e442ac2b991ecf5 | 3,653,764 |
def vec_sum(a, b):
"""Compute the sum of two vector given in lists."""
return [va + vb for va, vb in zip(a, b)] | d85f55e22a60af66a85eb6c8cd180007351bf5d9 | 3,653,767 |
import time
def one_v_one_classifiers(x,y,lambd,max_iters,eps=.0001):
"""
Function for running a 1v1 classifier on many classes using the linearsvm function.
Inputs:
x: numpy matrix
a matrix of size nxd
y: numpy matrix
a matrix of size nx1
lambd: float
... | 3cf564039c78363021cb65650dd50db9536922bb | 3,653,768 |
def rlsp(mdp, s_current, p_0, horizon, temp=1, epochs=1, learning_rate=0.2,
r_prior=None, r_vec=None, threshold=1e-3, check_grad_flag=False):
"""The RLSP algorithm"""
def compute_grad(r_vec):
# Compute the Boltzmann rational policy \pi_{s,a} = \exp(Q_{s,a} - V_s)
policy = value_iter(mdp... | d389363929f4e7261d72b0d9d83a806fae10b8ab | 3,653,769 |
import numbers
def rotate(img, angle=0, order=1):
"""Rotate image by a certain angle around its center.
Parameters
----------
img : ndarray(uint16 or uint8)
Input image.
angle : integer
Rotation angle in degrees in counter-clockwise direction.
Retu... | 8b55fe060ff6b8eb0c7137dc38a72531c24c7534 | 3,653,770 |
def activate(request, uidb64, token):
"""Function that activates the user account."""
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_... | 8538fc17e37b2743a7145286720ba5e8d653c790 | 3,653,771 |
def dfn(*args, **kwargs):
"""
The HTML Definition Element (<dfn>) represents the defining
instance of a term.
"""
return el('dfn', *args, **kwargs) | 798fb57360aca6f035ad993998c622eb6fff4e82 | 3,653,772 |
def handle_post_runs(project_id, deployment_id):
"""Handles POST requests to /."""
is_experiment_deployment = False
experiment_deployment = request.args.get('experimentDeploy')
if experiment_deployment and experiment_deployment == 'true':
is_experiment_deployment = True
run_id = create_deplo... | 5684a2b1f82981d4a3d5d7b870485b01201fdd2e | 3,653,774 |
def get_in_reply_to_user_id(tweet):
"""
Get the user id of the uesr whose Tweet is being replied to, and None
if this Tweet is not a reply. \n
Note that this is unavailable in activity-streams format
Args:
tweet (Tweet): A Tweet object (or a dictionary)
Returns:
str: the user i... | 74bbfa224f15781f769bf52bb470e23e9c93a95a | 3,653,775 |
def release_definition_show(definition_id=None, name=None, open_browser=False, team_instance=None, project=None,
detect=None):
"""Get the details of a release definition.
:param definition_id: ID of the definition.
:type definition_id: int
:param name: Name of the definition. I... | 3a4f13a1dfb7f1bd95bf8eae52d41f14566eb5fb | 3,653,777 |
def GKtoUTM(ea, no=None, zone=32, gk=None, gkzone=None):
"""Transform any Gauss-Krueger to UTM autodetect GK zone from offset."""
if gk is None and gkzone is None:
if no is None:
rr = ea[0][0]
else:
if isinstance(ea, list) or isinstance(ea, tuple):
rr = ea... | 330804d9bfe4785d867755b58355b0633d1fe7c8 | 3,653,778 |
def robots(req):
"""
.. seealso:: http://www.sitemaps.org/protocol.html#submit_robots
"""
return Response(
"Sitemap: %s\n" % req.route_url('sitemapindex'), content_type="text/plain") | 42e21c5968d7e6d02049a0539d5b115aa596292e | 3,653,779 |
import numpy as np
def bolling(asset:list, samples:int=20, alpha:float=0, width:float=2):
"""
According to MATLAB:
BOLLING(ASSET,SAMPLES,ALPHA,WIDTH) plots Bollinger bands for given ASSET
data vector. SAMPLES specifies the number of samples to use in computing
the moving average. ALPHA is an op... | 90c06bb45f30713a05cde865e23c0f9e317b0887 | 3,653,780 |
def metrics():
"""
Expose metrics for the Prometheus collector
"""
collector = SensorsDataCollector(sensors_data=list(sensors.values()), prefix='airrohr_')
return Response(generate_latest(registry=collector), mimetype='text/plain') | 93a3de3fbddaeeeaafd182824559003701b718bc | 3,653,781 |
def solar_energy_striking_earth_today() -> dict:
"""Get number of solar energy striking earth today."""
return get_metric_of(label='solar_energy_striking_earth_today') | a53c6e45f568d5b4245bbc993547b28f5414ca47 | 3,653,782 |
def write_data_str(geoms, grads, hessians):
""" Writes a string containing the geometry, gradient, and Hessian
for either a single species or points along a reaction path
that is formatted appropriately for the ProjRot input file.
:param geoms: geometries
:type geoms: list
:... | 34c1148f820396bf4619ace2d13fb517e4f6f16d | 3,653,783 |
import types
from typing import Dict
from typing import Any
from typing import List
def gen_chart_name(data: types.ChartAxis,
formatter: Dict[str, Any],
device: device_info.DrawerBackendInfo
) -> List[drawings.TextData]:
"""Generate the name of chart.
... | 032abcb5e6fca1920965fdd20203614dd750c9c0 | 3,653,784 |
from typing import Sequence
def vector_cosine_similarity(docs: Sequence[spacy.tokens.Doc]) -> np.ndarray:
"""
Get the pairwise cosine similarity between each
document in docs.
"""
vectors = np.vstack([doc.vector for doc in docs])
return pairwise.cosine_similarity(vectors) | 14456abcbb038dd2a4c617690d7f68dfc7a7bcb8 | 3,653,786 |
def create_test_validation():
"""
Returns a constructor function for creating a Validation object.
"""
def _create_test_validation(db_session, resource, success=None, started_at=None, secret=None):
create_kwargs = {"resource": resource}
for kwarg in ['success', 'started_at', 'secret']:
... | 7d78ae1c999cb79151e7527fd5bad448946aaccc | 3,653,787 |
def nrmse(img, ref, axes = (0,1)):
""" Compute the normalized root mean squared error (nrmse)
:param img: input image (np.array)
:param ref: reference image (np.array)
:param axes: tuple of axes over which the nrmse is computed
:return: (mean) nrmse
"""
nominator = np.real(np.sum( (img - ref... | ab040a2dd88acb2ce1e7df3b37215c5a40092f8a | 3,653,788 |
def pairwise_comparison(column1,var1,column2,var2):
"""
Arg: column1 --> column name 1 in df
column2 --> column name 2 in df
var1---> 3 cases:
abbreviation in column 1 (seeking better model)
abbreviation in column 1 (seeking lesser value in column1 in co... | a67ef991dcad4816e9b15c1f352079ce14d7d823 | 3,653,789 |
def prep_data_CNN(documents):
"""
Prepare the padded docs and vocab_size for CNN training
"""
t = Tokenizer()
docs = list(filter(None, documents))
print("Size of the documents in prep_data {}".format(len(documents)))
t.fit_on_texts(docs)
vocab_size = len(t.word_counts)
print("Vocab ... | a568942bdedbea99d6abf2bd5b8fc8c7912e4271 | 3,653,790 |
def gc2gd_lat(gc_lat):
"""Convert geocentric latitude to geodetic latitude using WGS84.
Parameters
-----------
gc_lat : (array_like or float)
Geocentric latitude in degrees N
Returns
---------
gd_lat : (same as input)
Geodetic latitude in degrees N
"""
wgs84_e2 = ... | e019a5a122266eb98dba830283091bcbf42f873f | 3,653,791 |
def polynomial_kernel(X, Y, c, p):
"""
Compute the polynomial kernel between two matrices X and Y::
K(x, y) = (<x, y> + c)^p
for each pair of rows x in X and y in Y.
Args:
X - (n, d) NumPy array (n datapoints each with d features)
Y - (m, d) NumPy array (... | 5532692b0a8411560f56033bcf6ad27b3c8e41a1 | 3,653,793 |
def slug_from_iter(it, max_len=128, delim='-'):
"""Produce a slug (short URI-friendly string) from an iterable (list, tuple, dict)
>>> slug_from_iter(['.a.', '=b=', '--alpha--'])
'a-b-alpha'
"""
nonnull_values = [str(v) for v in it if v or ((isinstance(v, (int, float, Decimal)) and str(v)))]
r... | 0da42aa5c56d3012e5caf4a5ead37632d5d21ab0 | 3,653,794 |
def modulusOfRigidity(find="G", printEqs=True, **kwargs):
"""
Defines the slope of the stress-strain curve up to the elastic limit of the material.
For most ductile materials it is the same in compression as in tensions. Not true for cast irons, other brittle materials, or magnesium.
Where:
E =... | cb849755799d85b9d4d0671f6656de748ab38f7c | 3,653,795 |
async def async_unload_entry(hass: HomeAssistantType, entry: ConfigType) -> bool:
"""Unload FRITZ!Box Tools config entry."""
hass.services.async_remove(DOMAIN, SERVICE_RECONNECT)
for domain in SUPPORTED_DOMAINS:
await hass.config_entries.async_forward_entry_unload(entry, domain)
del hass.data[... | e934ec21be451cc1084bd293dbce5495f6b4915c | 3,653,796 |
def queryMaxTransferOutAmount(asset, isolatedSymbol="", recvWindow=""):
"""# Query Max Transfer-Out Amount (USER_DATA)
#### `GET /sapi/v1/margin/maxTransferable (HMAC SHA256)`
### Weight:
5
### Parameters:
Name |Type |Mandatory |Description
--------|--------|--------|--------
asset |STRING |YES |
isolatedSymbol |... | f9e178d18eea969e5aabc0efa3aee938ad730752 | 3,653,797 |
def remove_layer(nn, del_idx, additional_edges, new_strides=None):
""" Deletes the layer indicated in del_idx and adds additional_edges specified
in additional_edges. """
layer_labels, num_units_in_each_layer, conn_mat, mandatory_child_attributes = \
get_copies_from_old_nn(nn)
# First add new edges to c... | 33d4a2e6ba05000f160b0d0cc603c568f68790d7 | 3,653,799 |
import itertools
import random
def brutekeys(pinlength, keys="0123456789", randomorder=False):
"""
Returns a list of all possibilities to try, based on the length of s and buttons given.
Yeah, lots of slow list copying here, but who cares, it's dwarfed by the actual guessing.
"""
allpossible = list(itertools.i... | 42f659e37468073c42117d1f4d6235f08aedde59 | 3,653,800 |
def return_figures():
"""Creates four plotly visualizations
Args:
None
Returns:
list (dict): list containing the four plotly visualizations
"""
df = query_generation('DE', 14)
graph_one = []
x_val = df.index
for energy_source in df.columns:
y_val = df[energ... | c89fe79d12173bc0b167e43e81d3adf19e81eb7b | 3,653,801 |
def create_central_storage_strategy():
"""Create a CentralStorageStrategy, using a GPU if it is available."""
compute_devices = ['cpu:0', 'gpu:0'] if (
tf.config.list_logical_devices('GPU')) else ['cpu:0']
return tf.distribute.experimental.CentralStorageStrategy(
compute_devices, parameter_device='cpu... | 46cc64d6cb888f51513a2b7d5bb4e28af58b5a29 | 3,653,802 |
def ToolStep(step_class, os, **kwargs):
"""Modify build step arguments to run the command with our custom tools."""
if os.startswith('win'):
command = kwargs.get('command')
env = kwargs.get('env')
if isinstance(command, list):
command = [WIN_BUILD_ENV_PATH] + command
else:
command = WIN_... | 30bdf2a1f81135150230b5a894ee0fa3c7be4fa4 | 3,653,803 |
def get_security_groups():
"""
Gets all available AWS security group names and ids associated with an AWS role.
Return:
sg_names (list): list of security group id, name, and description
"""
sg_groups = boto3.client('ec2', region_name='us-west-1').describe_security_groups()['SecurityGroups']... | 48a30454a26ea0b093dff59c830c14d1572d3e11 | 3,653,804 |
def traverseTokens(tokens, lines, callback):
"""Traverses a list of tokens to identify functions. Then uses a callback
to perform some work on the functions. Each function seen gets a new State
object created from the given callback method; there is a single State for
global code which is given None in the co... | 4fcdfc4505a0a3eb1ba10a884cb5fc2a2714d845 | 3,653,805 |
from typing import Any
def publications_by_country(papers: dict[str, Any]) -> dict[Location, int]:
"""returns number of published papers per country"""
countries_publications = {}
for paper in papers:
participant_countries = {Location(city=None, state=None, country=location.country) \
... | 7295fd9491d60956ca45995efc6818687c266446 | 3,653,806 |
def dequote(str):
"""Will remove single or double quotes from the start and end of a string
and return the result."""
quotechars = "'\""
while len(str) and str[0] in quotechars:
str = str[1:]
while len(str) and str[-1] in quotechars:
str = str[0:-1]
return str | e6377f9992ef8119726b788c02af9df32c722c28 | 3,653,807 |
import numpy
def uccsd_singlet_paramsize(n_qubits, n_electrons):
"""Determine number of independent amplitudes for singlet UCCSD
Args:
n_qubits(int): Number of qubits/spin-orbitals in the system
n_electrons(int): Number of electrons in the reference state
Returns:
Number of indep... | 408c9158c76fba5d118cc6603e08260db30cc3df | 3,653,808 |
def variance(timeseries: SummarizerAxisTimeseries, param: dict):
"""
Calculate the variance of the timeseries
"""
v_mean = mean(timeseries)
# Calculate variance
v_variance = 0
for ts, value in timeseries.values():
v_variance = (value - v_mean)**2
# Average
v_variance = len(timeseries.values)
i... | 9b8c0e6a1d1e313a3e3e4a82fe06845f4d996620 | 3,653,809 |
def setup_i2c_sensor(sensor_class, sensor_name, i2c_bus, errors):
""" Initialise one of the I2C connected sensors, returning None on error."""
if i2c_bus is None:
# This sensor uses the multipler and there was an error initialising that.
return None
try:
sensor = sensor_class(i2c_bus... | 62633c09f6e78b43fca625df8fbd0d20d866735b | 3,653,810 |
def argparse_textwrap_unwrap_first_paragraph(doc):
"""Join by single spaces all the leading lines up to the first empty line"""
index = (doc + "\n\n").index("\n\n")
lines = doc[:index].splitlines()
chars = " ".join(_.strip() for _ in lines)
alt_doc = chars + doc[index:]
return alt_doc | f7068c4b463c63d100980b743f8ed2d69b149a97 | 3,653,811 |
import ctypes
def iterator(x, y, z, coeff, repeat, radius=0):
""" compute an array of positions visited by recurrence relation """
c_iterator.restype = ctypes.POINTER(ctypes.c_double * (3 * repeat))
start = to_double_ctype(np.array([x, y, z]))
coeff = to_double_ctype(coeff)
out = to_double_ctype(... | 82c32dddf2c8d0899ace56869679ccc8dbb36d22 | 3,653,812 |
import webbrowser
def open_pep(
search: str, base_url: str = BASE_URL, pr: int | None = None, dry_run: bool = False
) -> str:
"""Open this PEP in the browser"""
url = pep_url(search, base_url, pr)
if not dry_run:
webbrowser.open_new_tab(url)
print(url)
return url | 2f23e16867ccb0e028798ff261c9c64eb1cdeb31 | 3,653,813 |
def random_sparse_matrix(n, n_add_elements_frac=None,
n_add_elements=None,
elements=(-1, 1, -2, 2, 10),
add_elements=(-1, 1)):
"""Get a random matrix where there are n_elements."""
n_total_elements = n * n
n_diag_elements = n
fra... | 41ea01c69bd757f11bbdb8a259ec3aa1baabadc2 | 3,653,814 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.