content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def ismanacostlist(s, name, val, valkwargs):
"""Validation for the scryfall.com mana cost string."""
mc = parse_manacost(s)
return isvalidseq(mc, name, val, valkwargs) | 9ac549ce36b3de030b75548c367cd20bc180b371 | 3,595,221 |
def splitext_plus(fname):
"""Split on file extensions, allowing for zipped extensions.
"""
base, ext = splitext(fname)
if ext in [".gz", ".bz2", ".zip"]:
base, ext2 = splitext(base)
ext = ext2 + ext
return base, ext | 5a95ad85a67b75cc2ae99fdde6514bd804c9d6b2 | 3,595,223 |
def potential(state, incentive=None, G=None, mu=None):
"""Compute the potential function for a given state"""
if not incentive:
incentive = incentives.DEFAULT_INCENTIVE
if not G:
G = geometries.DEFAULT_METRIC
if mu is None:
mu = np.eye(len(state))
ones = np.ones(len(state))
... | 69a260560b05bf096c0b3810fb6129882a7664d1 | 3,595,224 |
def add_missing_columns(df1, df2, fill_value=0):
"""
Updates df1 to have all the columns of df2
"""
# Things that are in df2 but not df1
for c in set(df2.columns) - set(df1.columns):
df1[str(c)] = [fill_value] * len(df1)
# Sort the columns to be the same for bo... | 1d038aecb8df1149467d98a6816b42e0e3bae12f | 3,595,225 |
def cho_solve(A, y):
""" Solves [A x = y] for x using a Cholesky decomposition
via calls to LAPACK dpotrf and dpotrs in the F2PY module.
Arguments:
==============
A -- the A-matrix (symmetric and positive definite).
y -- the right-hand side of the equation (vector).
... | 3a8960d9da2d35160b6601d8d1f9cd859271161e | 3,595,226 |
from typing import Tuple
import torch
def sample_local_feat(img_feats, screen_meshes: Meshes, visible_verts,
interp_mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = False,
vis: bool = True,
... | 34b491a7b43bcc599b4e3945dbf10b81919d0ba6 | 3,595,227 |
def prepare_features(spectrogram):
"""
Calculates useful features for the vocalization detection
:param spectrogram: the spectrogram for the vocalization detection, only the frequency range of interest
:return
1) spectral_energy
2) means: mean spectral energy of a range of 60 kHz around... | ca497f2a56654524968b74c2dfb0a9fda9dc5d65 | 3,595,228 |
from datetime import datetime
async def create_timer(expires_at: datetime.datetime, event_type: str, *args, **kwargs):
"""Creates a new timer object.
Args:
expires_at (datetime.datetime): when the timer expires
event_type (str): The timer event type
*args: Any additional arguments
... | ce4ae728801586d6b044c1a9f319658982271e70 | 3,595,229 |
def CallPoolStatsPy(inp_d):
"""
Args:
inp_d: (dict) contains
output_fp (str) (pool_fp) finished pool file
genes_table_fp (str) genes table file path
nMapped (int)
tmp_dir (str) Path to tmp_dir
Returns:
res_d (dict): If succesful, also contain... | be619a40d2a51fe1a6e33dd22c0c62b68facf674 | 3,595,230 |
from scipy.spatial import cKDTree
def join_by_cell_location(df_cells, df_ph, max_distance=4):
"""Join together dataframes representing in situ sequencing data and phenotypic data on a
per-cell basis. Datasets must already be spatially aligned; cells are matched within
max_distance` (typically less than ... | b86b3cc8100b07fa11e5989525b85532bc9f6bcb | 3,595,231 |
def Rmrs(top=None, index=None, xarg=None,
eps=None, args=None, hcons=None, icons=None,
lnk=None, surface=None, identifier=None, vars=None):
"""
Construct an [Xmrs] from RMRS components.
Robust Minimal Recursion Semantics (RMRS) are like MRS, but all
predications have a nodeid ("anchor... | 9648d58369ec23fd06fcc6ccea9cdd0627d56147 | 3,595,232 |
import math
def rotz(angle_rad):
"""
Rotation.RotX, Y, Z returns None object in PyKDL library. Cannot be indexed.
Use self-defined function instead.
"""
rotz = np.eye(3)
rotz = np.array([[math.cos(angle_rad), -math.sin(angle_rad), 0],
[math.sin(angle_rad), math.cos(angl... | c9ecc07b1ddbdbea8e78994fba182bc72b7c5c1c | 3,595,233 |
def _warping_envelope(X, region):
"""Compute the warping envelope.
Parameters
----------
X : array
Input data. It must be two- or three-dimensional.
region : array, shape = (2, n_timestamps)
Constraint region. The first row consists of the starting indices
(included) and th... | 4f6be6cc44d2c4e88a9e1181eb5d83c324493fb7 | 3,595,234 |
def _serial_from_status(status):
"""Find the best serialvalue from the status."""
serial = status.get("device.serial") or status.get("ups.serial")
if serial and (serial.lower() == "unknown" or serial.count("0") == len(serial)):
return None
return serial | 5075493926a946878d2263dc79879809a2af4fca | 3,595,235 |
from pygotham.forms import TalkSubmissionForm
def proposal(pk=None):
"""Return the talk proposal form."""
if not (current_user.name and current_user.bio):
message = 'Please fill out your speaker profile before continuing.'
flash(message, 'warning')
return redirect(url_for('profile.set... | 88e51416a5a95362eec836f4a92e424508beb3cc | 3,595,236 |
def load(team_size,
time_limit=45.,
random_state=None,
disable_walker_contacts=False,
enable_field_box=False,
keep_aspect_ratio=False,
terminate_on_goal=True,
walker_type=WalkerType.BOXHEAD):
"""Construct `team_size`-vs-`team_size` soccer environment.
... | 257a953b2fcb49eb62e92a96f3473fe67f7170d8 | 3,595,237 |
def colorspace_conversion(raster, conversion_type="rgb_to_hsv"):
"""
The ColorspaceConversion function converts the color model of a three-band
unsigned 8-bit image from either the hue, saturation, and value (HSV)
to red, green, and blue (RGB) or vice versa. An ExtractBand function and/or
a Stretch ... | ebf5cb2f93580232fe2418c2230b671d5ffa2f72 | 3,595,238 |
def KA(feat1, feat2, remove_mean=True):
"""
feat1, feat2: n x d
"""
if remove_mean:
feat1 -= np.mean(feat1, axis=0, keepdims=1)
feat2 -= np.mean(feat2, axis=0, keepdims=1)
norm12 = norm(feat1.T.dot(feat2))**2
norm11 = norm(feat1.T.dot(feat1))
norm22 = norm(feat2.T.dot(fea... | 002bcf615df4b5677759d6a9ef50d633fd96da6f | 3,595,239 |
def reconstruction_loss(x, x_recon, distribution='gaussian'):
"""
from https://github.com/1Konny/Beta-VAE/blob/master/solver.py
"""
batch_size = x.size(0)
assert batch_size != 0
n_frames = x.size(1)
if distribution == 'bernoulli':
recon_loss = nn.functional.binary_cr... | ee6cdaa4dd5b731219ea9b54f65c3e309bd952e6 | 3,595,242 |
def point(surface, string=None):
"""Return ``(x, y, trailing_text)`` from ``string``."""
if not string:
return (0, 0, "")
try:
x, y, string = (string.strip() + " ").split(" ", 2)
except ValueError:
raise PointError("The point cannot be found in string %s" % string)
return s... | de82aa531c47d8703784c98a176147e53e68a7ee | 3,595,244 |
def compute_metrics(dataset, gamma=1.):
"""
Compute the metrics of each complete episode in the dataset.
Args:
dataset (list): the dataset to consider;
gamma (float, 1.): the discount factor.
Returns:
The minimum score reached in an episode,
the maximum score reached in... | a79598a0ddfc503a8dbbbdfb43bf09230ea245e2 | 3,595,247 |
def calc_angular_travelled(xyt):
"""Takes in the list of positions, uses calc_vector to turn the positions into vectors. the vectors are then
passed to angle_between, which returns the angles between the vectors (change in direction). This is then
summed and returned, representing the total angular distance... | 5949c2342bf2640b6030abd3c397dabcd5b10511 | 3,595,248 |
def craft_sms(machine, check, message, time_check):
"""Create a valuable alert with less text."""
# keep just the hour, i.e. strip year/month/day
time_check = time_check[-5:]
# remove the domain
machine = machine.split('.')[0]
alert = f'{time_check} {machine}!{check} {message}'
return alert[... | 3e926b44fdfca29ba731bd29c15790c53f395c85 | 3,595,249 |
from typing import List
import torch
def decode(loc, priors, variances: List[float]):
"""Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_priors,4]
... | 19f5c72555f01364cf8817a3904f0df4c09ecd65 | 3,595,250 |
import scipy
def helmert_basis(D: int, full=False, **kwargs):
"""
Generate a set of orthogonal basis vectors in the form of a helmert matrix.
Parameters
---------------
D : :class:`int`
Dimension of compositional vectors.
Returns
--------
:class:`numpy.ndarray`
(D-1, ... | fb1b9e3c3f8afcc05097b9c996ed4db330addaaa | 3,595,251 |
def longest_orf(sequence, clean=False, full=False, all=False, code=1, mini=1):
"""
Finds the longest open reading frame in the sequence. By default,
the longest sequence without stop codon (except for the trailing
stop codon) is returned, therefore the returned ORF doesn't
necessarily start by ... | d889a8316ab7adbb5ba5352b44e77790ee0f870c | 3,595,253 |
import json
def query_collection_mycollections_id(id):
"""
Query Content API Collection with access token.
"""
access_token = request.args.get("access_token", None)
collection_id = id
if access_token is not None and access_token != '':
# Construct an Authorization header with th... | 717b57273af1aa094cbf21b594b30fcc838aed23 | 3,595,254 |
import hashlib
def get_text_hash(text):
"""
Returns the hash of the given text.
"""
h = hashlib.sha512()
if not isinstance(text, text_type):
text = text_type(text, encoding='utf-8', errors='replace')
h.update(text.encode('utf-8', 'replace'))
return h.hexdigest() | 5c0ccfeb2b8c1a8f429f44a696d7248efb81a57b | 3,595,255 |
from typing import Callable
from re import A
def curry2(f: Callable[[A, B], C]) -> Callable[[A], Callable[[B], C]]:
"""Curry a two argument function."""
return lambda a: lambda b: f(a, b) | 755bac6e2a5955733432951c3506be4511122675 | 3,595,256 |
import math
def almost_equal(a, b, significant=7):
"""determine if two numbers are nearly equal to significant figures
copied from numpy.testing.assert_approx_equal
"""
if a is None or b is None:
return False
a, b = float(a), float(b)
# Normalized the numbers to be in range (-10.0,10... | c41098a142d681bf6d428abc36cee6f3676bd6d3 | 3,595,257 |
from typing import Sequence
from typing import Union
import numpy
def apply_expression(
blocks: Sequence[str],
bands: Sequence[Union[str, int]],
data: numpy.ndarray,
) -> numpy.ndarray:
"""Apply rio-tiler expression.
Args:
blocks (sequence): expression for a specific layer.
bands... | f5a67966054b5f37a409d5d2af153f8359c390b1 | 3,595,258 |
def sample_markov_network(MN, sampler=None, fixed_variables=None,
return_sampleset=False,
**sampler_args):
"""Samples from a markov network using the provided sampler.
Parameters
----------
G : NetworkX graph
A Markov Network as returned by :f... | 6f6c14df6e3c31c3bdffab3567dfbca8a9181cbc | 3,595,259 |
def get_label(buf: str, prefix: str = None) -> str:
"""
Returns a label
For example, the string 'TEAM - Core Engineering' should return 'team:core_engineering'
Args:
buf: the original string
prefix: a label prefix if the label should have one
Returns:
str
"""
lower... | e043d929b328f65787a50e95f4dff9b6b84492c7 | 3,595,260 |
def vector_cross(x,y):
"""
Does cross product of two 3x1 np arrays.
Normal numpy cross product only takes vectors.
"""
assert x.shape[0] == 3
assert y.shape[0] == 3
return np.expand_dims(np.cross(x[:,0],y[:,0]), axis=-1) | bd0e09eff00ed67aae90cf7ac9a4b0f2fe440717 | 3,595,261 |
def fourier_matrix_c2r(N, fsel=None):
"""Generate a Fourier matrix to represent a complex to real FFT.
Parameters
----------
N : integer
Length of timestream that we are transforming to. Must be even.
fsel : array_like, optional
Indexes of the frequency channels to include in the tr... | 286f2e88012912eeeb42fe2797a1038b2e89acf6 | 3,595,262 |
def filter_activation_fn():
"""Returns a activation if actv is an string name, otherwise input."""
filter_actv = lambda actv: (
get_activation(actv) if isinstance(actv, str) else actv)
return filter_actv | 60f9994ba58c59c65f37ef283723cc71d3b1cb6a | 3,595,263 |
def rotate(pt, theta):
""" Rotates points theta radians. Looks like it rotates clockwise for
raster coordinates.
args:
pt = 2x1 numpy array representing point
theta = rotation angle in radians
returns 2x1 numpy array of point after rotation
"""
r_matrix = np... | dbe45b3852dce3737287ecf39b246ac6a6186d1c | 3,595,264 |
from typing import Dict
from typing import Any
from typing import Tuple
def business_create(task: Dict[str, Any], job_id: JobId) -> Tuple[Content, HttpStatusCode]:
""" Creates new Task db record under the given parent job
and new db records for given command segments of that task.
"""
try:
new... | 826d3086e2f3a7907fc51dd45c62031cb6169fba | 3,595,265 |
from typing import Dict
from typing import OrderedDict
def replaceDictODict(obj):
"""
Function for/to <short description of `netpyne.sim.utils.replaceDictODict`>
Parameters
----------
obj : <type>
<Short description of obj>
**Default:** *required*
"""
if type(obj) == l... | a44d4ae6525033469af54373f82d72b2244a7cda | 3,595,267 |
def sparseArray(dataFrame, frac=0.95):
""" reduce data rows to `frac` ratio (sparse data)
dataFrame Pandas dataFrame
frac fraction cut down. For example, frac=0.95 remove 95%, only keep 5% leftover
Equivalent Function df = df.sample(frac= (1-frac) )
"""
drop_indices = np.random.choice(data... | 93d66683dd924340f8d896aebbfed14c78036b84 | 3,595,268 |
def makeWriteable(array):
"""Updates the given ``numpy.array`` so that it is writeable. If this
is not possible, a copy is created and returned.
"""
try:
# Versions of numpy prior to 1.16 will
# happily mutate a bytes array, whcih
# is supposed to be immutable. So if
# is... | acdcd4ff9b050cb1bb41261581659e74389a9eda | 3,595,269 |
import random
def _extract_patches_worker(tuples, max_per_frame=1, trials_per_tuple=100, flow_threshold=0.0,
jumpcut_threshold=np.inf):
"""
Extracts small patches from the original frames. The patches are selected to maximize
their contribution to the training.
:param tuple... | 2b31a1e691bfdd9d29eebb99fe13d7576d6aa96b | 3,595,270 |
import torch
def to_one_hot(y, n_dims=None):
""" Take integer y (tensor or V) with n dims and convert it to 1-hot representation with n+1 dims. """
y_tensor = y.data if isinstance(y, V) else y
y_tensor = y_tensor.type(torch.LongTensor).view(-1, 1)
n_dims = n_dims if n_dims is not None else int(torch.m... | 63ad01e5a4311eac441cdb672662b1b1aec7e9a9 | 3,595,271 |
import unittest
def skip_unless_symlink(test):
"""Skip decorator for tests that require functional symlink"""
ok = can_symlink()
msg = "Requires functional symlink implementation"
return test if ok else unittest.skip(msg)(test) | 7bf0de8ec573c5e3680d1355205b200d20fede87 | 3,595,272 |
import re
def test_unescaped_dots(tree, rulename, from_attrib, to):
# Rules containing unescaped dots outside of brackets and before slash.
# Note: this is meant to require example\.com instead of example.com,
# but it also forbids things like .* which usually ought to be replaced
# with something lik... | b767a4255d99b054f8b1dd5e1ee5a74ee68a07b3 | 3,595,273 |
from typing import Optional
from typing import List
import warnings
def command(
name: str,
label: Optional[str] = None,
caption: Optional[str] = None,
icon: Optional[str] = None,
items: Optional[List[Command]] = None,
value: Optional[str] = None,
data: Optional... | 15cd296061bb3ab3461a2397e033da919526c894 | 3,595,274 |
def decode_base64(data):
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
missing_padding = len(data) % 4
if missing_padding != 0:
data += '='* (4 - missing_padding)
return data | d52cc95795ca0167233b934086305acb01a71ecf | 3,595,275 |
def populate_headers(headers):
"""
Concatenate headers with subheaders
"""
result = [''] * len(headers[0])
values = [''] * len(headers)
for k_index in range(0, len(headers)):
for i_index in range(0, len(headers[k_index])):
if headers[k_index][i_index]:
values[... | 3b4bff30aac9e0b300cee12fa1bc9a26570dc762 | 3,595,276 |
def prepare_2q_correlation_matrix(
result: dict, s_obs_name: str, t: float, n_qubits: int
) -> (np.ndarray, str):
"""
Prepare the data used for plotting the matrix of connected correlation values of one type for all.
qubits. The connected correlation is defined as a 2Q observable from which the product ... | 334a2e726989d7ab6c17acf24e01903dd4f3edd8 | 3,595,277 |
def get_net(appliance, architecture):
"""
Parameters
----------
appliance : string
architecture : {'rnn', 'ae', 'rectangles'}
"""
NET_DICTS = {
'rnn': net_dict_rnn,
'ae': net_dict_ae,
'rectangles': net_dict_rectangles
}
net_dict_func = NET_DICTS[architecture]
... | 55c9e073d45f52a1e5d521a3eddbc1c704e53e08 | 3,595,278 |
def define_linear_regression_model(learning_rate):
""" Defines a linear regression model of one feature to predict the target.
Args:
learning_rate: A `float`, the learning rate
Returns:
A linear regressor created with the given parameters
"""
linear_regressor = tf.contrib.learn.LinearRegressor... | f278519a61aca354c747da1e5243718e02f2df6c | 3,595,280 |
def _generate_centralities_parallel(model_list):
"""
This function takes a list of null models or networks,
where each item in the list is a tuple.
The tuple contains the network name and the NetworkX object.
This function adds centrality rankings to the tuple.
:param model_list: List of list o... | 4c3ab49ba092700cafe8b5be8f190457842e46b7 | 3,595,281 |
from datetime import datetime
import calendar
import warnings
import re
import time
def futures_spot_price(date="20200401", vars_list=cons.contract_symbols):
"""
获取某个交易日大宗商品现货价格及相应基差
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品
:r... | bca47fde387c95cacacda568c5eb4444425f1b6e | 3,595,282 |
import re
def getPattern():
"""
Gets or builds a pre-compiled regex for cleaning text.
Returns:
compiled regex
"""
global PATTERN
if not PATTERN:
# List of patterns
patterns = []
# Remove emails
patterns.append(r"\w+@\w+(\.[a-z]{2,})+")
# Re... | 14fec59b7be5b268df6fb4473d87ec479c91b32c | 3,595,283 |
def find_dft_max_structure(method):
"""
Once an xtb path has been calculated the xTB guess is refined with an
interpolation around the xtb max using the method specified in 'method'.
The maximum of this path is used in the search for a TS.
"""
files_list = ['max_structure-1.xyz', 'max_structure.... | 4a460c51bf343b0126d293dd0b54e9b2ba2b948c | 3,595,284 |
def spike_encode(d, random_gen, n_dt_per_step, n_input_code, dt):
"""
Assumes input is binary or rate between 0 and 1. Does rate coding between min and max rate. (200Hz and 2Hz resp.)
:param d: d['input']:
:param random_gen:
:param n_dt_per_step:
:param n_input_code:
:param dt:
:return: ... | 1ad5c298edc0d1bc1664f01104c54f7e33c39570 | 3,595,285 |
from typing import List
from typing import Tuple
from typing import Optional
from typing import Callable
def get_rule(words: List[str], words_eol: List[str],
prefixless: bool) -> Tuple[Optional[Callable], tuple]:
"""
Attempt to find a rule in the given dict of patterns and rules.
Args:
... | 25c4a3597753d2ec829474981033a427cf3db115 | 3,595,286 |
def cube_info(connection, cube_id):
"""Get information for specific cubes in a specific project. The cubes can
be either Intelligent cubes or Direct Data Access (DDA)/MDX cubes. This
request returns the cube name, ID, size, status, path, last modification
date, and owner name and ID.
Args:
... | 30d4944e3878f686b8e80ddf630b9e9fa4f05912 | 3,595,288 |
def get_number_of_events_and_mw(dataset, mw_monomer=None):
"""
Calculate number of events and monomers
"""
data = get_data(dataset)
# determine the number of events of the data
mw_monomer = 1 if mw_monomer is None else mw_monomer
number_of_events = []
number_of_monomers = []
for d in... | 32f1521b2bc6a78525d1fd57b1137a1121c87700 | 3,595,289 |
def unimodularize(d):
"""Give d a conventional phase factor so that d[0][0] == conj(d[1][1])."""
d00, d11 = d[0][0], d[1][1]
phase_d00, phase_d11 = angle(d00), angle(d11)
phase_append = -(phase_d00 + phase_d11) / 2
d = d * exp(1j * phase_append)
return d | b82013c78c0edc15be79359cd2afe11c021b1dc5 | 3,595,290 |
def outside(chart,psg,start_beta=1.,start='S'):
"""
Calculates the outside probabilities of the CKY entries and adds them into the chart
I have the starting prob for the top right equal to the proportion of the sentence probability that the parse contributes. We might not need this: We might be able to mul... | 48c1a3c2695dae639e0b19baac2937c849aff438 | 3,595,291 |
import array
def F(x, xold, pthold):
""" Cost function for implicit midpoint rule in axisymmetric field """
global pth
ret = zeros(3)
# evaluate at midpoint
[H, pth, vpar, dHdx, dHdpph, dpthdx,
dpthdpph, dvpardx, dvpardpph] = get_der(
array([x[2], 0.5*(x[1] + xold[1]), 0.0, p... | 18bcf0b28601cf884a8f174e237b76f04f506d8f | 3,595,292 |
def linear_normalization(arr):
"""
Converting an RGB image into normalized RGB removes the effect
of any intensity variations.
Linear normalization
http://en.wikipedia.org/wiki/Normalization_%28image_processing%29
"""
arr = arr.astype('float')
# Do not touch the alpha channel
for i ... | de2297574ae9c794fde89ec7d7f22779528eb8c2 | 3,595,293 |
def fista(mode, beta, step, delta, slack, orig_img):
"""
Fast Iterative Shrinkage-Thresholding Algorithm.
Input:
- mode : mode for analysis
- beta : regularization coefficient (hyperparameter)
- step : k
- delta : last perturbation
- slack : last sla... | 8f9dd58a5bd0d53e651aa03074d6359a973d6436 | 3,595,294 |
def head(your_list, default=None):
"""Simple head function implementation."""
return next(iter(your_list or []), default) | 382e6f069b7aa15c710b41007bbd03be23d63bde | 3,595,295 |
def workdps(n, normalize_output=False):
"""
This function is analogous to workprec (see documentation)
but changes the decimal precision instead of the number of bits.
"""
return PrecisionManager(None, lambda d: n, normalize_output) | 0704f19885068cf2ca450551c7da633b01c79027 | 3,595,296 |
def get_user_sheet(sheet_id):
"""Fetch the storage object given an id.
If not existent, return None.
"""
WebStorage.auto_expire()
if sheet_id is None:
return None
storage = WebStorage.q.get(sheet_id)
if storage is None:
return None
return b64decode(storage.data) | fd70aba02ed101229c2489fcd2b93ee7250828d7 | 3,595,297 |
def get_train_transform(input_size):
"""
:return:
"""
return transforms.Compose([
transforms.Resize(input_size),
transforms.RandomHorizontalFlip(),
transforms.RandomVerticalFlip(),
transforms.RandomChoice([transforms.RandomAffine(180,
... | 1933cf9bbc7977c5535e89900626d85803666daf | 3,595,298 |
import collections
def dict_merge(xs):
"""
>>> dict_merge([{1: 2}, {3: 4}, {3: 5}])
{1: 2, 3: 4}
"""
return dict(collections.ChainMap(*xs)) | fff3a615c44df45b83b6bb8c9368c4f12ecd94bc | 3,595,299 |
def add_service(protocol=None, service_address=None, scheduler="wlc"):
"""
Add a virtual service.
protocol
The service protocol(only support tcp, udp and fwmark service).
service_address
The LVS service address.
scheduler
Algorithm for allocating TCP connections and UDP da... | fdd4595448bedba5d38bf73da56d9ad2e522cd4d | 3,595,300 |
from typing import Dict
from typing import Any
def get_standard_context_domain(record: Dict[str, Any]) -> Common.Domain:
"""
Prepare standard context for Domain
:param record: The record for which context is to be prepared
:return: Common.Domain
"""
return Common.Domain(
domain=record.... | ce65398ff9512b6faf0c58efc3dd8979179e088e | 3,595,301 |
def jitter(x, sigma=0.05):
"""jittering
Parameters
----------
x:
sigma:
Returns
-------
"""
noise = np.random.normal(loc=0, scale=sigma, size=x.shape)
return x + noise | 665cf65ef48d6a0b1788b3a46d6b9e18ba41aef3 | 3,595,302 |
from typing import List
def network_spec_to_net_label(network_spec: List[str], styled: bool = False) -> str:
"""Returns a converted network_spec to net_label as in gwbench's network.py.
Args:
network_spec: Network specification, e.g. ['A+_H', 'A+_L', 'V+_V', 'K+_K', 'A+_I'].
styled: Whether t... | ab3a483f58fe3ea28a3bb2cab302f592274d0c8b | 3,595,303 |
def snapshot(uri, generate_section=date_path_string, fetcher=Fetcher):
""" snapshot? Use this function to further; [snapshot]; a web resource into an
Archival space on the disk. An already [fetched] resource will be moved
into the archival directory under a generated name. Here the [dir] is
... | 1c9b8a53962e3842702cd5c7611606f9b87e847b | 3,595,304 |
from typing import Iterable
from typing import Any
def is_empty(iterable: Iterable[Any]) -> bool:
"""
Check whether provided iterable is empty.
:param iterable: iterable whose emptiness is to be checked.
:return: flag indicating if the provided iterable is empty.
"""
return not any(map(lambda... | cef865deec6a7fd4241e15abaac7fced9ac114b0 | 3,595,305 |
def device_queue_search(request):
"""
Returns a queryset that can be used as a base for searching the device
specific queue.
"""
filters = {
'status': amo.STATUS_PENDING,
'disabled_by_user': False,
}
sig = request.GET.get('pro')
if sig:
profile = FeatureProfile.fr... | 1b46beac4ed16bba878fbbcc2618f8e1ef9069c4 | 3,595,306 |
from pathlib import Path
def readCapture(capturePath):
"""Read capture folder (e.g. 'hs') and return Capture
Keyword arguments:
noprune -- A page must a) have a tag, b) be a zone homepage,
c) be in noprune, or
d) have an ancestor with one of these properties
... | 4252b4b0e116e328e43cd741c8a71a6dc2988661 | 3,595,307 |
def people_uuid_get(uuid, as_self=None): # noqa: E501
"""Person details by UUID
Person details by UUID # noqa: E501
:param uuid: universally unique identifier
:type uuid: str
:param as_self: GET object as Self
:type as_self: bool
:rtype: PeopleDetails
"""
return rc.people_uuid_ge... | c4bad98a08f4add8ae663ae01d34a59ba2031285 | 3,595,309 |
def run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs):
"""Patched of subprocess.run to fix blocking io making timeout=innefective"""
if input is not None:
if 'stdin' in kwargs:
raise ValueError('stdin and input arguments may not both be used.')
k... | f40bd610870f98c1ae3de5de0be6f427963da9e8 | 3,595,310 |
import logging
def rule_query(session, query_object: dict) -> dict:
"""
Purpose:
Construct the rule graql query
Args:
session: The Grakn session
query_object: The details of the query
Returns:
rules_map: info on the rule
"""
logging.info(query_object)
cond1 ... | 2aa742ef9a00613896d9b64025fdc8f77ce6b6e1 | 3,595,311 |
def nb_matrix(graph, aux=False, ordering='blocks', return_ordering=False):
"""Return NB-matrix of a graph.
If aux=False, return the true non-backtracking matrix, defined as the
unnormalized transition matrix of a random walker that does not
backtrack. If the graph has m edges, the NB-matrix is 2m x 2m.... | e1b95f9d389543fcebfad05fde38e34f4514fc7b | 3,595,312 |
def select_join_dummy(conn: Connection):
"""
Select first 5000 records containing employee's first name, last name and their job title on specified date
"""
return do_single_query(conn, queries.make_query_on_dummy(queries.QUERY_SELECT_JOIN)) | a6d6e37ca7a5021da57f32e57e02efba22c91743 | 3,595,313 |
def gen_xacro_macro(name, links, joints):
"""
Generates (as a string) the complete urdf element sequence for a simple
ROS-Industrial xacro macro that defines geometry (links, joints). It takes
a single argument ``prefix`` that should be used when instantiating the
macro in a composite parent scene.
... | 4be7f3353a9fba1f7127e81e29e3536150ed834e | 3,595,314 |
def solution(A): # O(N)
"""
Given an integer array nums, find the contiguous subarray
(containing at least one number) which has the largest sum and
return its sum.
>>> solution([-2, 1, -3, 4, -1, 2, 1, -5, 4])
6
>>> solution([-2, -1, -3, 1... | 9c41707940d563ba10c97af53e72f8bbf30fd071 | 3,595,315 |
import re
def re_comp_num_pos_name():
"""
Compiles the regex pattern that extracts the pattern (num) (position) (last), (first)
Example:
s = '21 C Stepan, Derek'
reg = re_comp_num_pos_name()
num, pos, last, first = reg.findall(s)[0]
:return: compiled regex
"""
... | 5994efcca453cef7201b92ca53863fc34791c0f1 | 3,595,316 |
def print_binary_tree(node, node_info=None, inverted=False, is_top=True):
"""
Print binary tree
from https://stackoverflow.com/questions/48850446/how-to-print-a-binary-tree-in-as-a-structure-of-nodes-in-python
:param node: root node
:type node: TreeNode
:param node_info: function to extract no... | 5db2529c66c22f13e4583ee27eefb731f9b5597e | 3,595,317 |
def get_object(object_id):
"""
Gets the record of the object with the given ID.
Returns:
(GamObject/None): The object with the given ID, None if not found.
"""
return GamObject.get_or_none(GamObject.ob_id == object_id) | 4b03e77c3e6ae540f231f0606e35529e6521613b | 3,595,320 |
def get_blendshape_delta(orig_mesh, source_meshes, corrective_mesh, replace = True):
"""
Create a delta following the equation:
delta = orig_mesh + corrective_mesh - source_meshes
Args:
orig_mesh (str): The unchanged base mesh.
source_meshes (list): Name of the mesh that represents ... | 156443fe36418b7418a9efceeddd081e3288a9e8 | 3,595,322 |
def synthesize ( utry ):
"""
Synthesis function with SearchCompiler.
Args:
utry (np.ndarray): The unitary matrix to synthesize.
Returns
qasm (str): The synthesized QASM output.
"""
if not isinstance( utry, np.ndarray ):
raise TypeError( "utry must be a np.ndarray." )
... | a196520f8f44878d57e5782f82e5414e34e2c320 | 3,595,323 |
import logging
def log_out(request):
"""
注销登录
:param request:
:return:
"""
if request.method == 'GET':
logger.info('{username}退出'.format(username=request.session['now_account']))
try:
del request.session['now_account']
del request.session['login_status']... | 85fd7f219a2dbd0196470a3dbd69327584b3709b | 3,595,324 |
def fetch_dataframe(variables=None, include_dependent_var=True):
"""Build the dataframe from sql result.
:param variables: independent or depedent variables from `fetch_data`. If None, fetch data implicitly
:param include_dependent_var: include dependent variable, only works when `inputs` is None
:retur... | abfeebbcf386deeb461e5d8d61d6e93e560bf90c | 3,595,325 |
def _index(key, sequence, testfn=None, keyfn=None):
"""Return the index of key within sequence, using testfn for
comparison and transforming items of sequence by keyfn first.
>>> _index('e', 'hello')
1
>>> _index('E', 'hello', testfn=_equalsIgnoreCase)
1
>>> _index('x', 'hello')
"""... | 0595726f9e14e8f4a3fd4b925de04c801be317a3 | 3,595,326 |
def sub(A,B):
"""Subtracts two fuzzy membership functions/sets"""
return np.maximum(A-B,0) | 8b8952e5a3ae5f3462a06f1eb0218895cbd3add3 | 3,595,327 |
def optimize(w , b , X , Y , num_iterations , learning_rate , print_cost = False):
"""
此函数通过运行梯度下降算法来优化w和b
参数:
w - 权重,大小不等的数组(num_px * num_px * 3,1)
b - 偏差,一个标量
X - 维度为(num_px * num_px * 3,训练数据的数量)的数组。
Y - 真正的“标签”矢量(如果非猫则为0,如果是猫则为1),矩阵维度为(1,训练数据的数量)
num_iteration... | 8e6e413c9df7ec5fb93f27f26295ab8d17b5a33b | 3,595,328 |
import inspect
from pathlib import Path
def _is_in_my_project(item) -> bool:
"""UNUSED"""
in_my_project = False
try:
path = inspect.getfile(item)
except TypeError:
pass # raised for builtins e.g.`sys`
else:
try:
Path(path).relative_to(_my_project_dir)
... | 4f187c8be3ec87dc401c12788a6f9fe8d3d75fbc | 3,595,329 |
def bundledir(sourcedir):
"""Get build dir for projects."""
return join(sourcedir, 'bundle') | 8df96b888ef964be74c01acaea5f0d95ff12940a | 3,595,330 |
def plot_segments(x, y, z=None, labels=None, width=0.0, compact=True, add_breaks=True,
monotonic_axis='auto', color=None, clim=None, ax=None, **kwargs):
"""Plot segmented lines, bars or images.
This plots a sequence of lines, bars or images consisting of one or more
*segments*. These segm... | e19dc220d66350e35b5cb9f36901fc3ead7b8f8a | 3,595,331 |
from typing import List
def fix_column_names(df: pd.DataFrame, info: dict) -> pd.DataFrame:
"""Format all column names as strings."""
new_columns: List[str] = []
for column_idx, column in enumerate(df.columns):
if isinstance(column, (list, tuple)):
new_column = ''
for col i... | 9692901b0f08d23d4a9d812fb2358991143db1da | 3,595,332 |
from datetime import datetime
def make_time_window_and_lights_on_off_ratio_dfs(complete_df):
""" Make time window features from 3-minute resolution level data.
These features include:
- Averages per 4 hour time bin
- Ratio of averages of 4 hour bins before / after lights on / off
"""
... | 00088757af060abf1e0dbd23490b1bb986563dfb | 3,595,333 |
def path_to_href_abs(target, base_dir):
""" Generate absolute href (/root/a/b/c.md)
- target: Path to target
- base_dir_abs: The Path to base directory, used to generate absolute hrefs
- Output: href if successful, or None.
"""
href = util.path_to_href(target, base_dir)
if href:
re... | 5b7527ad4688ddab527ee924bd707066093fa47b | 3,595,334 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.