content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def bwdist(
img,
method=cv2.DIST_L2,
dist_mask=cv2.DIST_MASK_5,
label_type=cv2.DIST_LABEL_CCOMP,
ravel=True,
):
"""Mimics Matlab's bwdist function, similar to OpenCV's distanceTransform()
but with different output.
https://www.mathworks.com/help/images/ref/bwdist.html
Available met... | 39,400 |
def groups(_):
"""
Query or count groups.
"""
pass | 39,401 |
def calculate_cumulative_conf(areaP90: float=1., areaP10: float=10., pdP90: float=10., pdP10: float=24):
"""Calculate cumulative confidence level for expected development size in MW
Args:
areaP90 (float): pessimistic area in sqkm
areaP10 (float): optimistic area in sqkm
pdP90 (float): p... | 39,402 |
def validate_gift_cards(checkout: Checkout):
"""Check if all gift cards assigned to checkout are available."""
if (
not checkout.gift_cards.count()
== checkout.gift_cards.active(date=date.today()).count()
):
msg = "Gift card has expired. Order placement cancelled."
raise NotA... | 39,403 |
def get_admins_timeseries_chart_data():
"""
Return admins timeseries data to frontend
:return: dict
"""
chart_data = {}
try:
pipe = [
{'$match': {VAX_AREA_KEY: {'$ne': 'ITA'}}},
{'$sort': {VAX_DATE_KEY: 1}}
]
cursor = vax_admins_summary_coll.aggreg... | 39,404 |
def get_all_keys(data):
"""Get all keys from json data file"""
all_keys = set(data[0].keys())
for row in data:
all_keys = set.union(all_keys, set(row.keys()))
return list(all_keys) | 39,405 |
def submitmq(request):
"""Message queue submit page"""
context = {
"type": "mq",
"choices": FRUIT_CHOICES,
}
if request.method == 'POST': # If the form has been submitted...
p = None
try:
# save preference
p = Preference()
p.nam... | 39,406 |
def clean_up(files: list):
"""delete unnecessary files
files -- the file paths to remove
"""
for f in files:
remove(f) | 39,407 |
def plot_projections(img: np.ndarray, spacing: int = 5, zoom: float = None) -> np.ndarray:
"""
Plot three maximum intensity projections of the given image side-by-side.
Parameters
----------
img : np.ndarray
Input 3D image.
spacing : int
Number of pixels to separate the projecti... | 39,408 |
def _ngl_write_atom(
num,
species,
x,
y,
z,
group=None,
num2=None,
occupancy=1.0,
temperature_factor=0.0,
):
"""
Writes a PDB-formatted line to represent an atom.
Args:
num (int): Atomic index.
species (str): Elemental species.
x, y, z (float): Ca... | 39,409 |
def docs_setup():
"""
Set some environment variables and ignore some warnings for the docs.
From https://github.com/exoplanet-dev/exoplanet/blob/main/src/exoplanet/utils.py
"""
import logging
import warnings
import matplotlib.pyplot as plt
# Remove when Theano is updated
warnings.f... | 39,410 |
def get_insert_components(options):
""" Takes a list of 2-tuple in the form (option, value) and returns a
triplet (colnames, placeholders, values) that permits making a database
query as follows: c.execute('INSERT INTO Table ({colnames}) VALUES
{placeholders}', values). """
col_names = ','.join(opt[0] for opt in o... | 39,411 |
async def test_update_version_file(readonly):
"""update version for a version file"""
old_version = "0.76.54"
new_version = "0.99.99"
with TemporaryDirectory() as working_dir:
version_file_path = Path(working_dir) / "VERSION"
with open(version_file_path, "w", encoding="utf-8") as f:
... | 39,412 |
def send_recording_to_gist(table: str, results: List['FormattedResult'], assignment: str):
"""Publish a table/result pair to a private gist"""
# the "-" at the front is so that github sees it first and names the gist
# after the homework
table_filename = '-stograde report {} table.txt'.format(assignmen... | 39,413 |
def append_composite_importance(composite_terms, ebm, X, composite_name=None, global_exp=None, global_exp_name=None, contributions=None):
"""Computes the importance of the composite_terms and appends it to a global explanation.
In case a global explanation is provided, the composite importance will be appended... | 39,414 |
def drive_predict(cp, ds):
""" This function performs the out-of-sample one-step forecast:
-checks existing models ( in repository);
-loads models;
-predicts on given numbe periods for foreast;
-logs the predict results.
:param cp: ControlPlane object
:param ds: data... | 39,415 |
def apply_pair(main, other, *, fn):
"""`Apply` optimized for use with paired structured containers."""
# special sequence types must precede generic `Sequence` check
if isinstance(main, (str, bytes)):
return fn(main, other)
# delegate other types to the function (int, float, etc.)
elif not ... | 39,416 |
def run_12():
"""Test 12
run_09 with 2 parallel deciders
"""
result = test_12()
result = get_activity_result(result, 'activity4', 'v2')
print('Result: ' + json.dumps(result) + '\n')
assert [r for r in result.keys() if 'activity1' in r]
assert [r for r in result.keys() if 'activity2' in ... | 39,417 |
def get_info(connector, host, key, datasetid):
"""Get basic dataset information from UUID.
Keyword arguments:
connector -- connector information, used to get missing parameters and send status updates
host -- the clowder host, including http and port, should end with a /
key -- the secret key to lo... | 39,418 |
def solve_network(
NWN: nx.Graph,
source_node: Union[Tuple, List[Tuple]],
drain_node: Union[Tuple, List[Tuple]],
input: float,
type: str = "voltage",
solver: str = "spsolve",
**kwargs
) -> np.ndarray:
"""
Solve for the voltages of each node in a given NWN. Each drain node will
... | 39,419 |
def d2s_func(va, vb, ka, wa, wb, pa):
"""
Create a function that requires only frequency as an argurment, and used to
calculate intensities across array of frequencies in the DNMR
spectrum for two uncoupled spin-half nuclei.
The idea is to calculate expressions
that are independant of frequency... | 39,420 |
def no_email_confirm(request):
""" overrides email confirm feature """
pass | 39,421 |
def network_allocations_get_for_share_server(context, share_server_id,
session=None):
"""Get network allocation for share server."""
return IMPL.network_allocations_get_for_share_server(context,
share_server_id... | 39,422 |
def round_corner(radius, fill):
"""Draw a round corner"""
corner = Image.new('L', (radius, radius), 0) # (0, 0, 0, 0))
draw = ImageDraw.Draw(corner)
draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=fill)
return corner | 39,423 |
def AppendNetworkAndSubnetArgs(args, builder_args):
"""Extracts network/subnet out of CLI args and append for importer.
Args:
args: list of str, CLI args that might contain network/subnet args.
builder_args: list of str, args for builder.
"""
if args.subnet:
AppendArg(builder_args, 'subnet', args.s... | 39,424 |
async def test_set_direction(hass, calls):
"""Test set valid direction."""
await _register_components(hass)
# Turn on fan
await common.async_turn_on(hass, _TEST_FAN)
# Set fan's direction to forward
await common.async_set_direction(hass, _TEST_FAN, DIRECTION_FORWARD)
# verify
assert h... | 39,425 |
def hindcasts(hcsts, obsvs=None, hists=None, shade=False, ax=None, figsize=(15, 4)):
"""
Plot sets of hindcasts. Where multiple variables are provided, it is
assumed that all inputs contain the same variables.
Parameters
----------
hcsts : dict
Dictionary of hindcasts to plot with the f... | 39,426 |
def Main(block_index):
"""
:param block_index:
:return:
"""
header = GetHeader(block_index)
print("got block!")
ts = header.Timestamp
print("got timestamp")
block = GetBlock(block_index)
txlist = block.Transactions
# @TODO this does not work
# for tx in block.Transa... | 39,427 |
def _create_integration_test_executable(
orig_target_name,
target_suffix,
executable):
"""Create _integration_test_executable rule and return its names.
Args:
orig_target_name: The name given to the sut_component or the
integration_test.
target_suffix: A suffix to append to the orig_targe... | 39,428 |
def pgd(model, inp, label,
epsilon=0.3,
step_size=0.01,
num_steps=40,
random_start=True,
pixel_range=(-0.5, 0.5)):
"""Short summary.
Parameters
----------
model : nn.Module
Model to attack
inp : tensor
Input to perturb adversarially.
label... | 39,429 |
def test_grouping_optional_argument():
"""Tests that grouping occurs correctly"""
soup = TexSoup(r"\begin{Theorem}[The argopt contains {$]\int_\infty$} the square bracket]\end{Theorem}")
assert len(soup.Theorem.args) == 1 | 39,430 |
def tourneAleatoire(c):
"""
faire tourner la carte d'un nombre de tours aléatoire
paramètres: c une carte
Cette fonction modifie la carte mais ne retourne rien
"""
r = None
for key, elem in dicType.items():
if c['carte'] in elem:
v = random.randint(0, len(elem) - 1)
... | 39,431 |
def save(discourses, file, encoding="utf-8"):
"""
将一组篇章结构序列化存储到XML格式文档
:param discourses: List[structure.tree.Discourse]
:param file: 保存路径
:param encoding: 文档编码
:return:
"""
CDTB.save_xml(discourses, file, encoding=encoding) | 39,432 |
def enumerate_trials(perievents):
"""
adds an index to perievents_2D that counts the number of trials per session and event
starting with 1, removes FrameCounter index
:param perievents: perievents df, non-column based format
:return: perievents df with additional index Trial
"""
# unstack i... | 39,433 |
def add_dims_right(tensor, ndims, right_indent=0):
""" Add empty dimensions to the right of tensor shape
"""
assert right_indent >= 0
for i in range(ndims):
tensor = torch.unsqueeze(tensor, -1-right_indent)
return tensor | 39,434 |
def test_compact_binary():
""" Test representation on domain with some binary dimensions """
mapDir = os.path.join(__rlpy_location__, "domains", "SystemAdministratorMaps")
mapname = os.path.join(mapDir, "20MachTutorial.txt") # expect 20+1 = 21 states
domain = SystemAdministrator(networkmapname=mapname)... | 39,435 |
def ciClim( imData, sigma = 2.5 ):
"""
Confidence interval color limits, for images. Most useful for highly spikey data.
"""
meanData = np.mean( imData )
stdData = np.std( imData )
return np.array( [meanData - sigma*stdData, meanData + sigma*stdData] ) | 39,436 |
def parse_data(
data, dialect=None, delimiter=None, quotechar=None, escapechar=None
):
"""Parse the data given a dialect using the C parser
Parameters
----------
data : iterable
The data of the CSV file as an iterable
dialect : SimpleDialect
The dialect to use for the parsing. ... | 39,437 |
def get_submodel_name(history = 60, lag = 365, num_neighbors = 20, margin_in_days = None, metric = "cos"):
"""Returns submodel name for a given setting of model parameters
"""
submodel_name = '{}-autoknn-hist{}-nbrs{}-margin{}-lag{}'.format(metric,
... | 39,438 |
def test_inventory_pass_build(request, monkeypatch, netcfgbu_envars):
"""
Test the use-case where the configuraiton contains an inventory build
script. The script exists, it runs without error.
"""
files_dir = request.fspath.dirname + "/files"
monkeypatch.setenv("SCRIPT_DIR", files_dir)
con... | 39,439 |
def create_db_scoped_session(connection_string=None):
"""Create scoped session."""
# we use NullPool, so that SQLAlchemy doesn't pool local connections
# and only really uses connections while writing results
return scoped_session(
sessionmaker(bind=create_engine(
connection_string ... | 39,440 |
def sens_reduce_precise(x: torch.Tensor, sens_maps: torch.Tensor) -> torch.Tensor:
"""
Combine num_coils individual coil images into a single image using estimates of the sensitivity maps.
Then replace the magnitude with the RSS estimate to reduce inaccuracies caused by the sensitivity map estimates.
... | 39,441 |
def dict_to_object(item, callback: Callable = None):
"""This function convert a Python Dict into a Python object:
>>> data = {"name": "John Smith", "hometown": {"name": "New York", "id": 123}}type >>> c = json_to_object(data)
type>> c
<class 'automatic'>
>>> c.name
"John Smith"
>>> c.hometo... | 39,442 |
def show_vm(vm_id):
"""
Executes the onevm show command and returns the xml output.
:param int vm_id: vm id number
:return: XML output from onevm show command
"""
return _get_subp_out(["onevm", "show", "-x", str(vm_id)]) | 39,443 |
def isragged(arr):
"""Test if an array is ragged (i.e. unequal-length records).
Parameters
----------
arr : array
Returns
-------
ragged : bool
Returns True of not all entries in arr are of same length
(i.e. arr is indeed ragged). False otherwise.
"""
ragged ... | 39,444 |
def write_info(text):
"""
Write a message to stderr, but only if permitted
Args:
text (str): The line to be written.
"""
if verbose is True: write_to_stderr(text) | 39,445 |
def tuning_CNN_region_size():
"""
This function works for tuning the CNN model in region (window) sizes.
"""
df = pd.read_csv('Queen.csv')
df = df.drop(columns = ['Unnamed: 0'])
X = df['text']
from sklearn.preprocessing import LabelEncoder
labelEncoder = LabelEncoder()
y = labelEnc... | 39,446 |
def plot_seaice_predict(anomlous = False, temporal_resolution = 'monthly', spatial_resolution = 1, detrend = False, imagefolder = 'images/timeseries/prediction/',seaice_source='nsidc'):
"""Plots a timeseries for Antarctic SIC.
Args:
anomlous (bool, optional): If the data is anomalous.
tempo... | 39,447 |
def compress_public_key(public_key):
"""Compresses a given uncompressed public key.
:param public_key: the key to compress, as bytes
:return: the compressed key, as bytes
"""
if public_key[0] != 0x04 or len(public_key) != 65:
raise ValueError('invalid uncompressed public key')
# We take... | 39,448 |
def sphinx_doc_parser(doc: str) -> DocParserRetType:
"""A doc parser handling Sphinx-style and epydoc-style docstrings
Args:
doc: The function doc string
Returns:
The parsed doc string and parsed parameter list
"""
main_doc, param_docs = plain_doc_parser(doc)
parts = re.spli... | 39,449 |
def GetProfilesDirectory(*args, **kwargs): # real signature unknown
""" Retrieves directory where user profiles are stored """
pass | 39,450 |
def bilinear_interpolate(X, x, y):
"""
Estimates of the pixel values at the coordinates (x, y) in `X` via bilinear
interpolation.
Notes
-----
Assumes the current entries in X reflect equally-spaced
samples from a 2D integer grid.
Modified from https://bit.ly/2NMb1Dr
Parameters
... | 39,451 |
def do_prediction(intbl, pbms, gene_names,
filteropt="p-value", filterval=0.0001, spec_ecutoff=0.4, nonspec_ecutoff=0.35):
"""
intbl: preprocessed table
filteropt: p-value or z-score
filterval: # TFs for opt z-score and p-val cutoff for p-value
"""
# intbl: #rowidx,seq,val,dif... | 39,452 |
def fetch_res(n, k, dim, ampl_noise, type_mat, scaled, norm_laplacian, n_avrg,
save_res_dir, embedding_method):
"""
Get the results from a given experiment when they were saved to a file,
in order to use them for plotting in plot_from_res, or not to redo the same
computation twice in run_s... | 39,453 |
def load_gramar_from_SYGUS_spec(spec):
"""Creates Grammar from the given SYGUS grammar specification (http://sygus.seas.upenn.edu/files/SyGuS-IF.pdf, last access 3.08.2016).
:param spec: SYGUS grammar specification.
:return: New grammar object.
"""
grammar = Grammar()
spec = spec.replace('(', ... | 39,454 |
def test_ascii_ket_elements():
"""Test the ascii representation of "atomic" kets"""
hs1 = LocalSpace('q1', basis=('g', 'e'))
hs2 = LocalSpace('q2', basis=('g', 'e'))
alpha, beta = symbols('alpha, beta')
assert ascii(KetSymbol('Psi', hs=hs1)) == '|Psi>^(q1)'
psi = KetSymbol('Psi', hs=1)
asser... | 39,455 |
def im_entropy(im):
"""
Calculate entropy of one single image
:param im: a greyscale image in numpy format
:return: entropy of the image
"""
h, w = im.shape
hist = np.histogram(im.reshape(-1), bins=256)[0]
probs = hist / (h * w)
probs = probs[probs > 0]
ent = np.sum(-probs * np.... | 39,456 |
def model_save(model, path):
"""Save model."""
torch.save(model.state_dict(), path) | 39,457 |
def main(
ctx: click.Context,
filepaths: tuple[str, ...],
check: bool,
display_diff: bool,
in_place: bool,
no_fix_main_to_bottom: bool,
reverse: bool,
no_aggressive: bool,
encoding: str,
comment_strategy: CommentStrategy,
py_version: PyVersion,
quiet: bool,
verbose: b... | 39,458 |
def forward(layers, x):
"""
function for performing forward propagation in all the layers
Parameters:
layers : list
x : numpy array
Returns:
list : (contains output of all layers in the form of numpy arrays)
"""
conv = layers[0]
pool = layers[1]
de... | 39,459 |
def prepare_upgrade_save_namespace(hdfs_binary):
"""
During a NonRolling (aka Express Upgrade), preparing the NameNode requires saving the namespace.
:param hdfs_binary: name/path of the HDFS binary to use
"""
import params
dfsadmin_base_command = get_dfsadmin_base_command(hdfs_binary)
save_namespace_cmd... | 39,460 |
def gen_word_vec_matrix(doc, nrows=100, stop_min=4, return_df=False):
"""
"""
# filter stop words and non-alpha tokens
vecs = [token.vector for token in doc if token.is_alpha and
((not token.is_stop) or (token.is_stop and len(token)>stop_min))]
vec_df = pd.DataFrame(vecs)
#... | 39,461 |
def __same_axes(x_axis, y_axis, xlim, ylim):
"""Check if two axes are the same, used to determine squared plots"""
axes_same_and_not_none = (x_axis == y_axis) and (x_axis is not None)
axes_same_lim = xlim == ylim
return axes_same_and_not_none and axes_same_lim | 39,462 |
def create_column_dicts(path_to_input):
"""Creates dictionaries: {column_index, column_name} and
{column_name, column_index}"""
cols = {}
with open(path_to_input, newline="") as csvfile:
inputreader = csv.reader(csvfile, delimiter=",")
row = next(inputreader)
for i, col in enumer... | 39,463 |
def check_dependencies():
"""Ensure required tools for installation are present.
"""
print("Checking required dependencies")
try:
subprocess.check_call(["git", "--version"])
except OSError:
raise OSError("bcbio-nextgen installer requires Git (http://git-scm.com/)") | 39,464 |
def autocommit(session_cls: Type[Any], do_commit_at_outermost: bool = True) -> Any:
"""
自动提交装饰器
:param session_cls: Sqlalchemy Session Class, 且该类可以被inject获取到
:param do_commit_at_outermost: 上下文结束后是否提交
:return:
"""
def decorator(func: FunctionType):
@wraps(func)
def wrap(*args... | 39,465 |
def multiply(multiplicand, multiplier):
"""Multiplies the multiplicand by the multiplier
This function multiplies the multiplicand by the multiplier only
when they are either integers or floats
Args:
multiplicand(int/float): The quantity that is to be multiplied
by another
... | 39,466 |
def rolling_enveloped_dashboard(
channel_df_dict: dict, desired_num_points: int = 250, num_rows: Optional[int] = None,
num_cols: Optional[int] = 3, width_for_subplot_row: int = 400, height_for_subplot_row: int = 400,
subplot_colors: Optional[Container] = None, min_points_to_plot: int = 1, plot_as_bars: bool... | 39,467 |
def compare_clusterers(clusterer_1, clusterer_2, ground_truth, reduction,
figsize=(15, 5), **kwargs):
"""Utility function for comparing two clustering approaches on a problem
for which we have a ground truth.
Args:
- clusterer_1: a dictionary where key is the name of ... | 39,468 |
def generate_and_write_ed25519_keypair(password, filepath=None):
"""Generates ed25519 key pair and writes custom JSON-formatted keys to disk.
The private key is encrypted using AES-256 in CTR mode, with the passed
password strengthened in PBKDF2-HMAC-SHA256.
NOTE: The custom key format includes 'ed25519' as s... | 39,469 |
def scale_bicubic(data, scale=(1., 1., 1.)):
"""
returns a interpolated, scaled version of data
the output shape is scaled too.
Parameters
----------
data: ndarray
3d input array
scale: float, tuple
scaling factor along each axis (x,y,z)
interpolation: str
eith... | 39,470 |
def test_calc_functions_multiple_arguments():
"""Tests parse/eval handling functions with multiple arguments correctly"""
def h1(x): return x
def h2(x, y): return x * y
def h3(x, y, z): return x * y * z
assert evaluator("h(2)", {}, {"h": h1}, {})[0] == 2.0
assert evaluator("h(2, 3)", {}, {"h"... | 39,471 |
def get_sentiment(text, word_map):
"""
Identifies the overall sentiment of the text by taking the average
of each word.
Note: Words not found in the word_map dict are give zero value.
"""
# remove all punctuation
text = text.translate(str.maketrans("", "", string.punctuation))
# split... | 39,472 |
def point_line_seg_distance(p1: tuple, p2: tuple, p: tuple, extend_line: bool = False):
"""
Find shortest distance between a line segment (p1, p2) and a given point p.
"""
assert isinstance(p1, tuple) and len(p1) == 2
assert isinstance(p2, tuple) and len(p2) == 2
assert isinstance(p, tuple) and ... | 39,473 |
def train(args: argparse.Namespace):
"""The main training logic."""
if 'AIP_MODEL_DIR' not in os.environ:
raise KeyError(
'The `AIP_MODEL_DIR` environment variable has not been set. '
'See https://cloud.google.com/ai-platform-unified/docs/tutorials/'
'image-recognition-custom/training'
... | 39,474 |
def download_splits():
"""Downloads and extracts splits to ${DATASETS_DIR}/hmdb51/splits."""
print('download_splits() running ...')
common.utils.download(SPLITS_URL, DS_DIR, SPLITS_FILENAME, extract='auto')
print(f'Splits saved to {SPLITS_DIR}') | 39,475 |
def Tanh_Derivative(x):
"""
这是Tanh激活函数的导数计算公式
:param x: 需要进行计算的数据
:return: Tanh激活函数的导数的函数值
"""
f = Tanh(x)
derivative = 1.0-f*f
return derivative | 39,476 |
async def api_update_donation(
data: CreateDonation, donation_id=None, g: WalletTypeInfo = Depends(get_key_type)
):
"""Update a donation with the data given in the request"""
if donation_id:
donation = await get_donation(donation_id)
if not donation:
raise HTTPException(
... | 39,477 |
def random_monoalpha_cipher(pool=None):
"""Generate a Monoalphabetic Cipher"""
if pool is None:
pool = letters + digits
original_pool = list(pool)
shuffled_pool = list(pool)
shuffle(shuffled_pool)
return dict(zip(original_pool, shuffled_pool)) | 39,478 |
def mrf_slice_example(slice):
"""convert mrf slice data to tensorflow
Args:
slice: Dict. Contains keys:
immrf/data, immrf/path,
tmap/data, tmap/path,
mask/data, mask/path
Returns: TODO
"""
immrf = slice["immrf/data"]
tmap = slice["tmap/d... | 39,479 |
def get_comment(entity: Union[Table, TableProtocol, Column, Constraint]) -> str:
"""Get comment on entity"""
if isinstance(entity, TableProtocol):
return to_table(entity).comment or ""
elif isinstance(entity, Table):
return entity.comment or ""
elif isinstance(entity, Column):
re... | 39,480 |
def merge_neighbor_spans(spans: List[Span], distance) -> List[Span]:
"""Merge neighboring spans in a list of un-overlapped spans:
when the gaps between neighboring spans is not larger than the
specified distance, they are considered as the neighbors.
Args:
spans (List[Span]): The input list of ... | 39,481 |
def handle_all_serials(oid, *args):
"""Return dict of oid to serialno from store() and tpc_vote().
Raises an exception if one of the calls raised an exception.
The storage interface got complicated when ZEO was introduced.
Any individual store() call can return None or a sequence of
2-tuples where... | 39,482 |
def remove_null_fields(data):
"""Remove all keys with 'None' values"""
for k, v in data.items():
if isinstance(v, dict):
remove_null_fields(v)
if isinstance(v, list):
for element in v:
remove_null_fields(element)
if not data[k]:
del dat... | 39,483 |
def epsautoconfeval(epsilon, plotTitle):
"""
investigate distance properties for clustering autoconfiguration
plots of k-nearest-neighbor distance histogram and "knee"
See SegmentedMessages#autoconfigureDBSCAN
:param plotTitle: Part of plot's filename and header
:param epsilon The manually det... | 39,484 |
def equal_value_solution(par_dict1=params ,par_dict2=params1 , mean=-0.4, variance=0.35,N=1000):
""" This function sets average tax revenue equal under different sets of parameters by changing the base tax rate.
This is done by minizing the squared difference between old and new average revenue using the ... | 39,485 |
def dist_l2(v, w):
"""
Euclidean (L2) distance between
two vectors.
"""
s = 0
for i in range(len(v)):
s = s + (v[i] - w[i]) ** 2
s = np.sqrt(s)
return s | 39,486 |
def convert_single_example_dual(ex_index, example, max_seq_length, tokenizer,
label_list):
"""Converts a single `InputExample` into one or more `DualInputFeatures`.
Args:
ex_index: index of the example
example: InputExample
max_seq_length: maximal sequence length of quer... | 39,487 |
def find_recipes(rounds):
"""
Calculate the last ten recipes in the sequence.
:param rounds: the number of rounds
:return: a list of the last 10 recipes in the sequence
>>> find_recipes(5)
[0, 1, 2, 4, 5, 1, 5, 8, 9, 1]
>>> find_recipes(18)
[9, 2, 5, 1, 0, 7, 1, 0, 8, 5]
>>> find_re... | 39,488 |
def query_abs_over_wiki(abstract):
"""
query from es with the document is wiki_entity
"""
return {
"track_total_hits": "true",
"version": "true",
"size": 1000,
"sort": [{
"_score": {
"order": "desc"
}
}],
"_source": ... | 39,489 |
def mitm_digest_preimage(tshash_params, digest, except_bitstrings=(), max_length=_MITM_DEFAULT_MAX_LENGTH):
""" Performs a meet-in-the-middle attack to find a preimage whose hash arrives at a certain digest. """
# We currently don't discard bits from the state to get a digest
# possible_truncations = ('0b01... | 39,490 |
def similarityWithResult(Address_1: Address, Address_2: Address):
"""
地址相似度计算
:param Address_1: 地址1, 由 Geocoding.normalizing 方法返回的 Address 类
:param Address_2: 地址2, 由 Geocoding.normalizing 方法返回的 Address 类
:return:
"""
geocoding = jpype.JClass('io.patamon.geocoding.Geocoding')
pattern = r... | 39,491 |
def longitudinal_summary(ds, lat_dim='lat', lon_dim='lon', lon_res=5):
"""Compute longitudinal (bin) statistics, averaging over latitude."""
# Check lat_dim and lon_dim
# Check lon_res < 180
# TODO: lon between -180 and 180 , lat between -90 and 90
aggregating_dims = list(ds[lon_dim].dims)
bi... | 39,492 |
def validFilename(string):
""" return a valid filename from the input string
stripping characters that are not allowed
"""
out = ''
allowed = _allowedfilenamechars()
for s in string:
if s in allowed:
out += s
return out | 39,493 |
def contains_source_code(http_response):
"""
:param http_response: The HTTP response object
:return: A tuple with:
- re.match object if the file_content matches a source code file
- A tuple containing the programming language names
"""
body = http_response.get_body()
... | 39,494 |
async def test_form_cannot_retrieve_device_info(hass, aioclient_mock):
"""Test we handle cannot retrieve device info error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
with patch("pysma.SMA.new_session", return_value=True), patch(
"py... | 39,495 |
def test_invalid_include_path(tmpdir):
"""Ensure non existing paths are not loaded."""
settings_file = tmpdir.join("settings.toml")
settings_file.write(TOML)
settings = LazySettings(
ENV_FOR_DYNACONF="DEFAULT",
silent=False,
LOADERS_FOR_DYNACONF=False,
SETTINGS_MODULE_F... | 39,496 |
def wht(at1,at2,ints):
"""
Assign weights for Hessian matrix given 1-2,1-3,1-4 interactions
:param at1: first atom
:param at2: second atom
:param ints: tuples of 1-2,1-3,1-4 interacting pair
:return: 0 for diagonal, assigned weight constant for all other
"""
apair = [at1,at2]
int2, ... | 39,497 |
def _get_users_with_perms(obj, attach_perms=False, with_group_users=None):
"""
Returns a list of users with their permissions on an object obj.
"""
user_obj_perms = get_user_perms(obj)
if user_obj_perms is None:
return get_users_with_perms(
obj, attach_perms=attach_perms, with_gr... | 39,498 |
def get_file_data(request, oid, version=None, status=None):
"""Get document data"""
document = get_document(request, oid, version, status)
if request.content_type.startswith('text/xml'):
data = Binary(document.data.data)
else:
data = base64.b64encode(document.data.data).decode()
retu... | 39,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.