content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_instance_characteristics(instance):
"""
Returns a tuple of the node & edge model classes and the instance_type
for the provided instance
"""
try:
# Assume a queryset of nodes was provided
_NodeModel = instance._meta.model
_EdgeModel = instance._meta.model._meta.get_fi... | e0df14a4c68a595493a697ac3807281e54184cf3 | 58,709 |
def zebra_puzzle():
"""Return a tuple (WATER, ZEBRA) indicating their house numbers."""
houses = first, _, middle, _, _ = [1, 2, 3, 4, 5]#Replace string with number in a list
print houses
orderings = list(itertools.permutations(houses)) #make a list of unordered houses
#print list(orderings)
ret... | 017e64d91f8cd1a6b0ece56dd1b15c9d020e1b9a | 58,711 |
def main( argv ):
""" Script execution entry point """
# initialize and start the user interface
#ui = timecalc()
#ui.mainloop()
if len( argv ) > 1:
if len( argv ) == 5:
arg = ' '.join( argv[ 1 : ] )
else:
arg = argv[ 1 ]
num = number( arg )
... | 119d5247f1f57b7fcb7a793665c36442066d23e6 | 58,714 |
from bs4 import BeautifulSoup
from pathlib import Path
def clean_html(html: str) -> str:
"""Removes script tags and their contents"""
soup = BeautifulSoup(html, "html.parser")
for script in soup(FORBIDDEN_TAGS):
script.decompose()
for img in soup.find_all("img"):
img.name = "span"
... | b21db67976ee6b4c35701a0c26408920fff497d7 | 58,715 |
import time
def internalKey(key = None):
"""Internal Key
Generates or validates an internal key so services can communicate with
each other
Arguments:
key (str): Passed to validate a key
Returns:
bool
"""
# Pull in salt
global __msSalt
# Generate a timestamp
iTime = int(time())
# If no key was pa... | 3f9d0a92710417701f56c22b58e90fe9b517cc56 | 58,717 |
def squint2(t, r, orbit, attitude, side, sin_az=0.0, h=0.0):
"""Find squint angle given imaging time and range to target.
"""
p, v = orbit.interpolate(t)
R = attitude.rotmat(t)
axis = R[:,0]
angle = np.arcsin(sin_az)
dem = ie.pyDEMInterpolator(height=h)
xyz = rdr2geo_cone(axis=axis, angl... | 62033e43c5e76e9a46d682cbca9d5efe5333f671 | 58,718 |
def generate_action_dict():
""" Generate a list of all possible uci moves and their action number lookup
Return:
actions: lookup dictionary for converting uci into actions(number)
inverse_actions: lookup dictionary for converting actions to uni
"""
# normal uci moves
standard_uci = []
... | 267d80bcf64d76e7742b48de2d6c49507c6710bd | 58,720 |
import time
def check_update(from_currency, to_currency):
""" check if last update is over 30 mins ago. if so return True to update, else False """
if from_currency not in ccache: # if currency never get converted before
ccache[from_currency] = {}
if ccache[from_currency].get(to_currency) is None:
ccache[from_... | be6561d9a94595499196b15b9a2eb1461bef18c5 | 58,721 |
import math
def facto(mult):
""" Product of factorials of multiplicities in the multiset """
if not is_natural_multiset(mult):
raise Exception("Coefficient only works for natural multisets")
result = 1
for a in mult.sp.iter_all():
result *= math.factorial(mult(*a))
return result | 2ac95f97f65fd4c73da6ccfb53dd4055fea6b728 | 58,722 |
def export(cfg, args):
"""
Modifies program config variables.
"""
if args[1] == 'color':
color_triple = export_color(args)
cfg['color'] = color_triple
changed = tuple(color_triple)
elif args[1] == 'time':
time_period = export_time(args)
cfg['time'] = time_pe... | d8f9b8f4a5ca22ad6f1ffa10807e73b5078ea65c | 58,723 |
def build_sampler(tokenizer, device=None):
"""Build the appropriate sampler according to the configs."""
if FLAGS.model_type == 'text':
model_fn = lambda prompts: text_model_fn(tokenizer.vocab_size)( # pylint: disable=g-long-lambda
prompts, is_training=False, cache_steps=FLAGS.sample_memory_size)
s... | 03bb0162ee076516cf35be96182e925e3606e688 | 58,724 |
from typing import Sequence
from typing import Iterator
def apply(masks: Sequence[int], value: int) -> Iterator[int]:
"""Apply each bit mask to the given value using bitwise AND.
Args:
masks: Bit masks to apply.
value: Value to mask.
Returns:
Iterator with each mask independentl... | 6eafc88977eea0d50173a4c37c12b43f5c80a870 | 58,726 |
from scipy.optimize import fmin_cobyla
def _fit_dipoles(fun, min_dist_to_inner_skull, data, times, guess_rrs,
guess_data, fwd_data, whitener, ori, n_jobs, rank):
"""Fit a single dipole to the given whitened, projected data."""
parallel, p_fun, _ = parallel_func(fun, n_jobs)
# parallel ove... | 251a9f38ca7f8545ca2da5e2b9f70da479a23a58 | 58,727 |
import threading
def thread_get_album(update: Update, context: CallbackContext) -> int:
"""Creates a thread to get the album"""
language = context.user_data["bot_lang"]
text = context.bot_data["texts"][language]["get_album"]
chat_id = update.effective_user.id
update.callback_query.answer()
_,... | 0ced06d7175717697c4aebddfceb2b8d946f72c2 | 58,729 |
import random
def _compute_loss_and_metrics(
params, batch, rng,
model, is_experts_model,
auxiliary_loss_factor,
router_z_loss_factor):
"""Computes cross-entropy loss and metrics for classification tasks.
Args:
params: Model state (parameters).
batch: Current batch of examples.
rng: R... | 553356a3c51d66809a6352947410ffb036465aa8 | 58,730 |
def filter_df_for_pred_a(df, list_freq_outliers):
"""
Exclude frequency outliers according to list and drop all hex bin / time window combinations with 0 RTA's
"""
df_pred_a = df.loc[~df["h3_zone_6"].isin(list_freq_outliers)]
df_pred_a = df_pred_a.reset_index()
df_pred_a = df_pred_a.drop(["uid",... | 1115c845593ec2aabf55f6c5d52f4ef8b23fc121 | 58,731 |
def create_modules(module_defs):
"""
Constructs module list of layer blocks from module configuration in module_defs
"""
hyperparams = module_defs.pop(0)
output_filters = [int(hyperparams['channels'])]
module_list = nn.ModuleList()
for i, module_def in enumerate(module_defs):
modules... | 5ecebd8260f6926ed63396b19adc099129d2946c | 58,732 |
def jinja_plugin_factory(options):
"""
Basic implementation of the `GeneralTemplateInterface`.
Supports ``loader_func`` and ``getmtime_func``, as well as
string and file loading but ignores ``mode`` since it's a
text based template engine.
All options passed to this function are forwarded to t... | 16d353ccfcbad598a92cb17767e6eca0075e5e98 | 58,733 |
import cdms2, cdutil, numpy
def join_scalar_data(*args ):
""" This function joins the results of several reduced variables into a
single derived variable. It is used to produce a line plot of months
versus zonal mean.
"""
#pdb.set_trace()
nargs = len(args)
M = []
for arg in args:
... | 20a69cd2559c146c31a72817c79db8d0510103fe | 58,736 |
def group(seq, groupSize, noneFill=True):
"""Groups a given sequence into sublists of length groupSize."""
ret = []
L = []
i = groupSize
for elt in seq:
if i > 0:
L.append(elt)
else:
ret.append(L)
i = groupSize
L = []
L.appe... | a7314803cb3b26c9bd69a2dbc2c0594181085c2c | 58,737 |
def client_response_factory():
"""Custom response factory for client."""
return ResponseFactory() | 99838198b2004d531c147141b62890ef8d29e0f3 | 58,738 |
import torch
def membrane(field, voxel_size=1, bound='dct2', dim=None, weight=None):
"""Precision matrix for the Membrane energy
Note
----
.. This is exactly equivalent to SPM's membrane energy
Parameters
----------
field : (..., *spatial) tensor
voxel_size : float or sequence[float]... | 9ac91c6b79ce10977ba51c13fcc929aa352744e2 | 58,740 |
def get_dataset(config, attack_ds_config, add_x_train=None, add_y_train=None):
"""
@param config:
@param attack_ds_config:
@param add_x_train: x_train samples to add to training set
@param add_y_train: y_train samples to add to training set
@return:
"""
dataset = config.dataset.dataset
... | 55b1561e513de6705dfdbb43fee2aa5eb592392a | 58,742 |
def attrdict_setup(attrdict=milc.attrdict.AttrDict):
"""Setup a simple AttrDict object for testing.
"""
simple_dict = attrdict()
simple_dict['a'] = True
simple_dict['b'] = False
return simple_dict | a66613df54baa1e04a435184e488dbf1b7b46123 | 58,743 |
from typing import List
from typing import Any
def find_duplicates(list_: List[Any]) -> List[Any]:
"""
Find the elements duplicated in a list.
"""
dbg.dassert_isinstance(list_, list)
# Count the occurrences of each element of the seq.
set_l = set(list_)
v_to_num = [(v, list_.count(v)) for ... | 5f97f384395b530527df801239340cac7fde740d | 58,744 |
def create_response_payload_with_status(command_request, method_name, create_user_response=None):
"""
Helper method to create the payload for responding to a command request.
This method is used for all method responses unless the user provides another
method to construct responses to specific command r... | fab9c14046bbbad71f78c2671abf6786bb0a42c8 | 58,745 |
def splitdrive(p):
"""Split a pathname into drive and path. On Posix, drive is always
empty."""
return p[:0], p | 14524196f9f2018fed85081f1825592d244ac50f | 58,746 |
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return PartialConv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False) | 917ded11178349308c46a3ee1187dcb6624c409d | 58,747 |
def namespace_embedded(db_ns: str) -> bool:
"""Return true if this namespace requires IDs to have namespace embedded.
This function first maps the given namespace to an identifiers.org
namespace and then checks the registry to see if namespaces need
to be embedded in IDs. If yes, it returns True. If no... | 283e4436df750d6846fd549fb2aa227e3ae72c90 | 58,748 |
def NoisyNode(num_centroids=2, **kwargs):
"""
Returns a function that takes a graph and adds noise to the
node features except for the centroids.
"""
def inner(data):
graph, labels = data
features = graph[0][:, num_centroids:]
features += np.random.randn(*features.shape) * ... | 44a9bad800a19ddd5abc83876f0925a974fc1cfd | 58,749 |
def train_model_multi_output_w_tmt(x, y, param_grid=None, n_jobs=-1, cv=5):
"""Trains and does gridsearch on a keras nnet. Response can be multi output
Args:
x (np array): explanatory variables
y (np array): response variables. could be more than 1
n_jobs (int): number of cores to run on... | 4d12c393ce032c7dccb5a61b9acc06ccf180d66b | 58,750 |
import torch
def to_numpy(t: torch.Tensor):
"""Convert model output from Torch Tensor to numpy array."""
assert t.ndim == 4
# Inverse normalize [-1, 1] -> [0, 1], rescale [0, 1] -> [0, 255]
out = (torch.clamp(t * 0.5 + 0.5, 0, 1) * 255) \
.permute(0, 2, 3, 1) \
.detach() \
.c... | bbf142eb7c696aa11e2c1d476cc3a7b11eeae600 | 58,751 |
import operator
def decimate(x, q, n=None, ftype='iir', axis=-1, zero_phase=True):
"""
Downsample the signal after applying an anti-aliasing filter.
By default, an order 8 Chebyshev type I filter is used. A 30 point FIR
filter with Hamming window is used if `ftype` is 'fir'.
Parameters
-----... | e2b8258153284d943981975acc642e39cbaf9382 | 58,752 |
import hashlib
def get_interface_name(name, prefix='', max_len=constants.DEVICE_NAME_MAX_LEN):
"""Construct an interface name based on the prefix and name.
The interface name can not exceed the maximum length passed in. Longer
names are hashed to help ensure uniqueness.
"""
requested_name = prefi... | 0309fe509496393ac64d1dc61373d0a8e3c0a64e | 58,753 |
def differentiable_cumsum_capper(x, threshold, width):
"""Starts out 1 and decays to 0 so that (result * x).cumsum() <= threshold."""
cumsum = x.cumsum()
capped_cumsum = threshold - width * nn.softplus((threshold - cumsum) / width)
capped_x = jnp.concatenate([x[:1], jnp.diff(capped_cumsum)])
# The "double whe... | 166983a1ad7aab3b5070535f66cf28fdb82661f6 | 58,754 |
def angle_energy(angle_numbers, uint_crd_f, scalar_f, atom_a, atom_b, atom_c, angle_k, angle_theta0):
"""
Calculate the energy caused by 3-atoms angle term. Assume the number of angles is M and the
number of atoms is N.
.. math::
dr_{ab} = (x_b-x_a, y_b-y_a, z_b-z_a)
.. math::
dr_{c... | 1b34ae109dfe90c4c33a63298344d5806c896d1b | 58,755 |
def sub_mask_1d_indexes_for_mask_1d_index_via_mask_2d(mask_2d, sub_size):
""""For pixels on a 2D array of shape (rows, colums), compute a 1D array which, for every unmasked pixel on \
this 2D array, maps the 1D sub-pixel indexes to their 1D pixel indexes.
For example, for a sub-grid size of 2, the followin... | 4fedf5876127da4ed3b92422ce4da422e7d391a7 | 58,756 |
def plot_mc_value(observation_space: gym.spaces.Box, feature_map: FeatureMap, weights: np.ndarray, fig=None):
"""
Plot MountainCar value function
"""
xs = np.linspace(observation_space.low[0], observation_space.high[0])
ys = np.linspace(observation_space.low[1], observation_space.high[1])
gridx,... | c0481b606d9a84325bc9fece8c4b61fad02e8637 | 58,757 |
import math
def currin_exp_function(X):
"""
Compute the CurrinExp function.
The value is computed as defined in https://www.sfu.ca/~ssurjano/curretal88exp.html
:param X: dictionary containing the input points.
:return: the value of the CurrinExp function.
"""
x1 = X['x1']
x2 = X['x2']
... | 8cbcd384bcc49511a93e517c0b22c9c8d2837826 | 58,758 |
import gettext
def change_email_address():
"""Request a change of the current user's email address."""
current_user = g.user
form = ChangeEmailAddressForm(request.form)
if not form.validate():
return change_email_address_form(form)
new_email_address = form.new_email_address.data.strip()
... | abf3944e25880d543f0adca884d91ecd3917126d | 58,759 |
def run_single_with_display(wf, display):
"""Adds a display to the single runner. Everything still runs in a single
thread. Every time a job is pulled by the worker, a message goes to the
display routine; when the job is finished the result is sent to the display
routine."""
S = Scheduler(error_hand... | ca22f5c7fde36ceb7cd5c69a020a77ca4a47766b | 58,760 |
def solution(n):
"""Returns the largest palindrome made from the product of two 3-digit
numbers which is less than n.
>>> solution(20000)
19591
>>> solution(30000)
29992
>>> solution(40000)
39893
"""
# fetchs the next number
for number in range(n - 1, 10000, -1):
# ... | baccd41bdab7eed9dd7069caecc650834846e0d4 | 58,761 |
import math
def pressure_to_altitude(pres):
"""Convert a pressure (Pascals) to altitude (meters)"""
for i in range(len(_heights)-1,0,-1):
P0 = _basepress[i]
T0 = _basetemps[i]
if pres < P0:
if _isotherm[i]:
dh = _R * T0 / _g * math.log(P0 / pres)
... | fa46e0b438c4cf56355ecaa17f838a152f6680e5 | 58,762 |
def read(filename):
"""
Read a nmrglue table file.
Parameters
----------
filename : str
Filename of nmrglue table file to read.
Returns
-------
comments : list
List of comments (strings terminated with newline)
rec : recarray
Records array with named fields.... | f4d9b0dc040a3d38337783281c38cd471a7b4be7 | 58,763 |
import requests
import json
def get_decomposition(profile_counts, signatures='COSMIC30'):
"""
Decomposition of mutational profiles into a combination of signatures.
It is highly recommended to use profile_counts instead of profile in order to use Maximum Likelihood method
*signatures* should be one of... | be4f5a7777443c44004ae349c5fc437ffd56ed0b | 58,764 |
from django.utils import timezone
from sentry.app import tsdb
from sentry.models import Organization
import click
from typing import OrderedDict
import six
def organizations(metrics, since, until):
"""
Fetch metrics for organizations.
"""
stdout = click.get_text_stream("stdout")
stderr = click.ge... | 5d7659d124e12470515c4421a67c410f2c97849b | 58,765 |
import dbm
from datetime import datetime
import json
def export(start_date: str = Form(...), end_date: str = Form(...),
db: Session = Depends(dbm.get_db), user: UserModel = Depends(auth.get_user)):
"""Export pomodoros"""
start_date = datetime.strptime(start_date, "%Y-%m-%d")
end_date = datetim... | 3e05075c68f8103db759270e1ca610606eea4427 | 58,766 |
def get_bin_counts(array_in: NpArray,
num_bins_per_dim: int) -> NpArray:
"""Divide two dimensional input space into a grid and count points in each.
Point on the upper edge, which does happen in the data, go into the lower bin.
The occurrence of these points is an artefact of the rescaling don... | 3879310d554a61fc8d9e4c675d8e62a6be82d758 | 58,767 |
def parse_comments_from_back(line):
"""
Scan for tokens back to front in line.
Any token that does not start with a valid dice spec or a literal is a comment.
Return separately the line substring without comments and the comments.
Returns:
(line, comment):
line: Remainder of the... | 75f9acc697e18fdb0beb9decb1b383a43d1e5264 | 58,768 |
import numpy
import math
def f_internal(x, h, core_data):
"""
Creates an O(1) dummy function with unit bounds.
So, (I hope) the gradient and stencil are reasonably scaled.
I encode scale and noise awareness in this function, too. If your
function is not noise aware, I pass a zero noise back to imfil_core... | 0384bc7f4c7af5cd42738f467ddff45cbf2618f0 | 58,769 |
def radius_of_curvature(line, method="osculating"):
""" Compute curvature radius of LineString
:param line:
:param method: method for computing radius of curvature {'circumscribe', 'osculating'}
:return:
"""
def norm(xx, yy):
return np.sqrt(xx ** 2 + yy ** 2)
def tangent_vector(xi,... | 6d378bfb366d8f3592ef3f85174239f10a980086 | 58,770 |
def create():
"""Create a new post.
For a post to be created, details are submitted in the form. These details
are then inserted into the posts table in the database.
Returns:
Success JSON response if the operation succeeded.
Else a failed JSON response is returned with the correct err... | da3a657375796dc9f031ed355d0620ef0e55fd2a | 58,771 |
def decode(ids, encoder):
"""
Decode a list of IDs.
"""
ids = list(ids)
if text_encoder.EOS_ID in ids:
ids = ids[:ids.index(text_encoder.EOS_ID)]
return encoder.decode(ids) | 200d113e7ce9ab387b83cd926b8a0d7a4762fff6 | 58,772 |
import io
def _load_image_obj(fileobj):
"""
Turn a byte file object into an image
"""
return Image.open(io.BytesIO(fileobj)).convert("RGB") | 8ac45f3c8dee39d1f6d4181ca78bcabc26de5c28 | 58,773 |
def vround(v):
"""Convert a numpy 1d array to a tuple for hashing.
"""
return tuple(np.round(v, 8)) | c196a465d07793fb0b68a9055741a8d40655b404 | 58,775 |
def LSTM_triggerNG(tx, num_channels, num_outputs, kernel_init='normal', bias_init='zeros') -> Model:
"""Modified from Andrew Ng's Deeplearning.ai Sequence Modeling course on Coursera.
Originally used for trigger word detection.
Notes:
- Switched GRU cells to LSTM cells
- BiDirectional???
... | 877a6fce737f278bb95e6a4109c40ed5cf564d6b | 58,777 |
import random
def load_data(ticker, n_steps=60, scale=True, split=True, balance=False, shuffle=True,
lookup_step=1, test_size=0.15, price_column='Price', feature_columns=['Price'],
target_column="future", buy_sell=False):
"""Loads data from yahoo finance, if the ticker is a pd Data... | 566692d3f493f58981e9b7fdd04b887a8aa257fe | 58,778 |
import numpy as np
def BestDividing(dataSet, bestFeat):
"""
选出连续性特征最优划分点+返回其信息熵
Parameters
----------
dataSet:数据集
bestFeat:对哪个连续特征进行判断
Returns:最优划分点+其信息熵
-------
"""
bestEntropy = 1000.0 # 初始设一个不可能的超大熵
bestValue = 0.0
features = np.sort(dataSet[bestFeat].values)
... | 075834bfa205153411b49c3d431402bb93a316d6 | 58,779 |
import functools
def freezeargs(func):
"""
Transform all mutable objects into immutables using freeze
For the sake of lru_cache
"""
@functools.wraps(func)
def wrapped(*args, **kwargs):
args = tuple(freeze(arg) for arg in args)
kwargs = {k: freeze(v) for k, v in kwargs.items()}... | fe7760698e816b4f7c3599581a8d3d5b60dcb904 | 58,780 |
def classify_name(name):
"""Classify filename `name` as "crds", "oldcdbs", or "newcdbs".
>>> classify_name("jwst_miri_dark_0057.fits")
'crds'
>>> classify_name("s7g1700gl_dead.fits")
'oldcdbs'
>>> classify_name("07g1700gl_dead.fits")
'newcdbs'
>>> classify_name("bbbbbb.fits")
Tra... | 2599e44cabc2fdac8d09ec820acfc101a1129b1e | 58,781 |
import asyncio
def cli(ffmpeg, source, format_img, output, extra):
"""FFMPEG capture frame as image."""
async def capture_image():
stream = ImageFrame(ffmpeg_bin=ffmpeg)
return await stream.get_image(
input_source=source, output_format=format_img, extra_cmd=extra
)
im... | 3b6125ff5d23dd90c83c2a4011e4e71975575cc7 | 58,782 |
def template_modify(id, attrs):
"""
Modifies a template, configuring it with the given attributes.
Parameter *tech*:
The parameter *tech* must be a string identifying one of the supported
template techs.
Parameter *name*:
The parameter *name* must be a string giving a name for the template.
Parameter *... | f40a811e1bf756561895e097a2c83ed3392e69ea | 58,783 |
def parse_args(args):
"""
Parse command line argument and return parsed Namespace object.
Args:
args (list): List of arguments.
Returns:
argparse.Namespace: Parsed arguments Namespace object.
"""
parser = ArgumentParser()
group = parser.add_mutually_exclusive_group(required... | 6d00210c961898bb9f268353be4ce417551cdc01 | 58,784 |
def get_lldp_neighbors(device):
"""Get current LLDP neighbor information.
Return a two-level dictionary with the LLDP neighbor information..
The first-level key is the local port (aka interface) name.
The second-level keys are 'system' for the remote system name
and 'port' for the remote port ID. O... | 7719e3de069bf39533ee0c9fadbc2f94be69bb61 | 58,786 |
def WLS_fit(x_data=None, y_data=None, errors=None, weight_data=None,
xaxis_name=None, yaxis_name=None, f_name=None, data_lines=None,
data_name=None, quiet=True):
"""
Takes a filename string or x and y data as input. We are fitting the
equation A_ij*x_j=b_i of the form b=C+Dx.... | 672f552a2e6ff5e941418b98f0d837b48b97d5fb | 58,788 |
from django.conf import settings
def get_default_cachefile_backend():
"""
Get the default file backend.
"""
return get_singleton(settings.IMAGEKIT_DEFAULT_CACHEFILE_BACKEND,
'file backend') | 2a4d8bd03057a303c26b525ef087587b99a96baf | 58,789 |
def _make_ipy(nets):
"""Given a list of 2-tuples of (address, netmask), returns a list of
IP address objects"""
return [IP(addr) for addr, mask in nets] | 42e92d0b3bde9a0a4d46dcdf9ab093290b17c9b1 | 58,790 |
def Uleb128Encode(value: int) -> bytes:
"""Encodes the argument int to ULEB128 format.
Argument:
value: Unsigned integer.
Returns:
The values encoded as ULEB128 bytes.
"""
if value < 0:
raise ValueError(f'Cannot uleb128 encode negative value ({value}).')
uleb128_bytes = []
done = False
wh... | 68e3d4fb12ce82d9fcb44b634bc8570eddde9078 | 58,791 |
def ex2d_subbundle(image, imageivar, patches, spots, corners, pixpad_frac, regularize, model, psferr):
"""Extract an entire subbundle of patches. The patches' output shape (nspec, nwave) must be aligned.
Args:
image: full image (not trimmed to a particular xy range)
imageivar: image inverse var... | 9930d383aa3eefb01cdaafb0fda9c1ff2e277e7c | 58,792 |
def batch_norm(x, name, _ops, is_train=True):
"""Batch normalization."""
with tf.variable_scope(name):
params_shape = [x.get_shape()[-1]]
beta = tf.get_variable('beta', params_shape, tf.float32,
initializer=tf.constant_initializer(0.0, tf.float32))
gamma =... | dbbd42dd6e290a9c2a970e39e03397946016105e | 58,793 |
import itertools
def unique_slug(model, slug, instance=None, reserved_slugs=[]):
"""
Return unique slug for passed django model class.
:param model: Django model class
:param slug: String. Slug for make unique
:param instance: Django model instance
:return: String
"""
orig, apdx = spli... | 7db45470673316ab01552a936ce8b07cb9d27346 | 58,794 |
def apply_transform(x,
transform_matrix,
channel_axis=0,
fill_mode='nearest',
cval=0.):
"""Apply the image transformation specified by a matrix.
# Arguments
x: 2D numpy array, single image.
transform_matrix: Numpy arra... | 209f614dd2ad751a3b9e5b67024398ce62871385 | 58,795 |
def process_results(results, l1_idxes, l2_idxes):
"""Expands the None elements in l2 and substitutes the real l1 indexes"""
return set(process_result(result, l1_idxes, l2_idxes) for result in results) - set() | 4c01b7f161dd866d4acf74c2fd3f953963bbc758 | 58,796 |
def _graph_minus(graph, nodeset):
"""
"""
newgraph = nx.DiGraph()
for (n1, n2) in graph.edges():
if n1 not in nodeset and n2 not in nodeset:
newgraph.add_edge(n1, n2)
for n in graph.nodes():
if n not in nodeset:
newgraph.add_node(n)
return newgraph | 30e994eb143855afcd5be9d4c0052fd60a9d4a21 | 58,797 |
def create_worker(*, db_session: Session = Depends(get_db), worker_in: WorkerCreate):
"""
Create a new worker contact.
"""
worker = get_by_code(db_session=db_session, code=worker_in.code)
if worker:
raise HTTPException(status_code=400, detail="The worker with this code already exists.")
... | e3f680b81e2b5180929250fd6820fc78b5978b38 | 58,799 |
def strip_comments(contents):
"""Strips the comments from coq code in contents.
The strings in contents are only preserved if there are no
comment-like tokens inside of strings. Stripping should be
successful and correct, regardless of whether or not there are
comment-like tokens in strings.
... | 2c7ddc9fb3e2981cf297ff37a4bb0b7019247a3a | 58,801 |
def get_P_l(mol, configs, weights, epos_rot, l_list, e, at):
"""
Returns a nconf x naip x nl array, which is the legendre function values for each l channel.
The factor (2l+1) and the quadrature weights are included.
Parameters:
l_list: [-1,0,1,...] list of given angular momenta
weights: int... | 51f82d9394e94790b93dde24f03ced5e71122850 | 58,802 |
async def async_rpc_set_tmux_window_visible(connection, tmux_connection_id, window_id, visible):
"""Hides/shows a tmux window (which is an iTerm2 tab)"""
_assert_not_in_transaction()
request = _alloc_request()
request.tmux_request.SetInParent()
request.tmux_request.set_window_visible.SetInParent()
... | 69f8d7aa7a91dcf3daa0db8f772948b920739ac4 | 58,803 |
def localize_timestamp(timestamp, tz=None):
"""
Localizes timestamp to a given timezone
If none of those have worked, localizes to settings.TIME_ZONE.
"""
if isinstance(timestamp, str):
timestamp = get_parsed_datetime(timestamp)
time_zone = get_tz(tz)
try:
local_time = timezo... | 12d5cd68a68b3f40fed06874066d6461de2a4687 | 58,804 |
import yaml
import textwrap
def get_validated_configs(config_text: str, config_path: str, preset_target_definitions_text: str) -> "PlotmanConfig":
"""Return a validated instance of PlotmanConfig with data from plotman.yaml
:raises ConfigurationException: Raised when plotman.yaml is either missing or malforme... | 830c69aa24addde96876871eef55f99ffcf03296 | 58,806 |
def wrapsync(func):
"""Turns synchronous function into asynchronous."""
if iscoroutinefunction(func):
return func
async def inner(*args, **kwargs):
return func(*args, **kwargs)
return update_wrapper(inner, func) | 4b8b490facf00f5f632b71f9c440dd90b96dbd70 | 58,807 |
def softmax(x):
"""Calculates the softmax for x(numpy array, matrix, vector, of any shape)"""
return np.exp(x) / np.sum(np.exp(x), axis=1, keepdims=True) | 059ccba8b3fb69e7d76814778469b457440bb3c4 | 58,808 |
def diff(x):
"""
Computes the approximate local derivative of `x` via finite differencing assuming unit spacing.
Can be viewed as the opposite of trapz().
Args:
x: The vector-like object (1D np.ndarray, cas.MX) to be integrated.
Returns: A vector of length N-1 with each piece corresponding... | e7e21447f2c745ab8d05f05a9c6c50e24a9aec55 | 58,809 |
import random
def random_sentence_swap(sentences, p):
"""Swaps sentences with probability p."""
def swap_sentence(s):
idx_1 = random.randint(0, len(s) - 1)
idx_2 = idx_1
counter = 0
while idx_2 == idx_1:
idx_2 = random.randint(0, len(s) - 1)
counter += 1
if counter > 3:
... | 5a2fa1a7303dc6fe924803fe6fad2ef5da998733 | 58,810 |
import torch
def multiclass_dice_threshold(logits, targets, threshold=0.5, iou=False, eps=1e-8):
"""
Dice coefficient metric for multiclass binary target.
If iou=True, returns iou metric, classic for segmentation problems.
"""
n = targets.shape[0] #Batch size of 4
#Flatten logits ... | e6c1565532accde1debfbf2cf92939797d30b020 | 58,811 |
def process_not_implemented(**kwargs):
""" default process function - return not implemented """
ret_dict = { 'function_return': 'not-implemented',
'slack_response': {} }
return ret_dict | c78b7cda6e52471a5839d1231f45ba45d077888b | 58,812 |
def Eval_point(state, data):
""" External validity, where data is a multiset of
points, to be used as point predicates"""
vals = [state(*a) ** data(*a) for a in data.sp.iter_all()]
val = _prod(vals)
return val | 0dc29e2c1d668e4b077efe55e2c3ec3243f77abc | 58,813 |
import collections
import itertools
def WrapTypeDeclUnit(name, items):
"""Given a list (classes, functions, etc.), wrap a pytd around them.
Args:
name: The name attribute of the resulting TypeDeclUnit.
items: A list of items. Can contain pytd.Class, pytd.Function and
pytd.Constant.
Returns:
A... | 49e5e1e8e962b8c9add3ec99fc63b9f5f3442022 | 58,814 |
def plot_decision_boundary(ax, clf, xx, yy, **params):
"""Plot the decision boundaries for a classifier.
Parameters
----------
ax: matplotlib axes object
clf: a classifier
xx: meshgrid ndarray
yy: meshgrid ndarray
params: dictionary of params to pass to contourf, optional
"""
Z ... | 99f8d9f42b8e9fba9ab6b5936ed5f3c24ab18789 | 58,815 |
def reassign_assignment(worker_id, assignment_id,
staffing_request_inquiry=None):
"""
Return a given assignment after reassigning it to the specified
worker.
Args:
worker_id (int):
The ID of the worker to be assigned.
assignment_id (int):
... | 8be2e860203249ab4001170062db56edb2212806 | 58,816 |
from typing import Tuple
import torch
def draw_img_preds(
img: Tensor,
bboxes: Tensor,
bbox_labels: LongTensor,
img_size: Tuple[int],
color: Tuple[int] = (0, 0, 255)
) -> np.ndarray:
"""
Args:
img:
bboxes: xyxy order, normalized
img_size: (h, w)
"""
img = TF... | b576e151eb6641c76bf1cfb1ae6d1d8afd5537e0 | 58,817 |
def read_depot(df):
"""
reads the instance with the data, return the clietns data only
:param dataframe:
:return: a list of clients with their locations, demand
"""
#clients = df.loc[]
depot = df.loc[df.demand.isna(), ["x_loc", "y_loc"]]
return [depot.values[-1]] | baece330e54db024915f5ab6fd1ec724b687b5a0 | 58,818 |
def parse_human_activity_recog_data(
data_path='https://raw.githubusercontent.com/ChicagoBoothML/MLClassData/master/HumanActivityRecognitionUsingSmartphones',
X_names_file_name='features.txt',
train_subfolder_name='train', X_train_file_name='X_train.txt', y_train_file_name='y_train.txt',
... | 6ecb076308e5121262a07f836562791b7bf6c05e | 58,819 |
def quaternions_to_euler_angles(quats, rotmode=EulerOrder.ZXY):
"""
See https://www.geometrictools.com/Documentation/EulerAngles.pdf
"""
if rotmode == EulerOrder.ZXY:
return quaternions_to_ZXY_euler_angles(quats)
elif rotmode == EulerOrder.YXZ:
return quaternions_to_YXZ_euler_angles(... | 92a0a17180fe451bb7d7968b01b9694e6ca6b7fa | 58,820 |
def _expand_mock_imports(*mock_imports):
"""Returns an expanded set of mock imports.
mock_imports is expected to be a dict which looks like:
{
"absolute.module.name": SomeObject,
}
The objects in this dictionary will be the ones returned in the
eval-compatible env dict. Think of it as a fake sys... | 78941ddde22dc750fac3904a5a0b3d0578f8b91e | 58,821 |
def insert_perform_labeling_job_metadata(
parent_batch_id,
batch_id,
batch_status,
batch_metadata_type,
num_children_batches,
):
"""Creates a new record in the batch execution metadata table.
Parameters
----------
batch_id: id to retrieve the associated batch_execution_metadata
... | e01d5c8b4fcea732ce1e9eec00fc352a8e2c5d18 | 58,823 |
def read_rosbag(bagfile, state_topic='/state_output'):
""" Read states from a rosbag file """
states = []
time = []
with Bag(bagfile) as bag:
start = bag.get_start_time()
for topic, msg, t in bag:
if topic == state_topic:
states.append([
ms... | c0eccba042b24fbe6dccbcd7495dc4b316a861f9 | 58,824 |
def lazy_npgettext(context, singular, plural, num, **variables):
"""Like :func:`npgettext` but the string returned is lazy. The translation
happens when it is used as an actual string.
"""
return _lazy_translate('npgettext',
context, singular, plural, num, **variables) | 94991ca1fc2a5050027d9120cb7b6429f4078b45 | 58,825 |
def is_complete_sentence(root_node):
"""
We'll use "complete sentence" to mean we've found a node tagged 'S'
directly below a node tagged 'ROOT', i.e.: (ROOT (S ...))
"""
return root_node.label() == 'ROOT' and \
len(root_node) == 1 and \
root_node[0].label() == 'S' | 4bac130f2264b7dfabd66371031b5caa472017a7 | 58,826 |
from re import T
def clamp(v: T, min_v: T, max_v: T) -> T:
"""
clamp関数
入力値を`[min_v, max_v]`の範囲に収める
:param T v: 入力値
:param T min_v: 最小値
:param T max_v: 最大値
:return: `[min_v, max_v]`内に収めた値
"""
return min(max_v, max(v, min_v)) | 4d90a11e7201cf449e82befa1a05d7a3cfb9ba3c | 58,827 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.