content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def load_deputati(legislatura):
"""
Carica lista dei deputati
NOTA: Include anche i deputati che si sono dimessi e quindi raggiunge
un numero totale maggiore di 630.
:param legislatura: url identificativo della legislatura.
:return: lista di deputati con nome e cognome, ordinata per cogn... | e9a2b6b5104e9b85a78c1d8cbf6bd96f21b7e751 | 45,800 |
def create_connection(graph, node1, node2, linktype, propertydict=None, allow_dup=False):
"""
:param graph:
:param node1:
:param node2:
:param linktype:
:param propertydict:
:return:
"""
graph = graphs[graph]
anode = node1
bnode = node2
if isinstance(node1, dict):
... | d2224abe6be71c938358bb49dc4c00a179f8277a | 45,801 |
def download_log(request, log_id):
"""
"""
user = request.user
# Check that the user is allowed to download the log
if not (user.is_authenticated and (user.has_perm("jobs.view_joblog"))):
return HttpResponse("Not authorized to view logs", status=401)
try:
log = JobLog.objects.g... | e9f4087df32b039f46a763c886e2d65a87cd3386 | 45,802 |
def build_keras_network(model_file: str) -> Network:
"""
Wrapper for the more low-level KerasNetwork classes. Figures out the backend and
returns an istance of the appropriate class.
Parameters
----------
model_file
Path to the .h5 model file.
Returns
-------
"""
curren... | da804e83654d4214f040edd41e976207d382a73c | 45,803 |
def get_parser(identifier):
"""
:param identifier:
:return:
"""
ret_parser = None
for parser in BINSON_VALUES:
if identifier in parser.identifiers():
ret_parser = parser.from_bytes
break
if not ret_parser:
error_msg = 'Value 0x%02x' % identifier
... | 7defa94bbc3e4d419bfe0faa0b05e6e47046eced | 45,804 |
import numpy
def approximate_quantum_error(error, *,
operator_string=None,
operator_dict=None,
operator_list=None):
"""
Return an approximate QuantumError bases on the Hilbert-Schmidt metric.
Currently this is only ... | c5989a313ba39a84b3b91f1c01debb3510eec2eb | 45,805 |
def demo(sess, net, im_file, icdar_dir, oriented=False, ltrb=False):
"""Detect object classes in an image using pre-computed object proposals."""
# Load the demo image
im = helper.read_rgb_img(im_file)
# Detect all object classes and regress object bounds
timer = Timer()
timer.tic()
scores... | 80ee1a5fa88c71144940d650340bbbb1a1d0c9b1 | 45,806 |
def load_cam_ext(file):
""" read camera txt file """
cam = np.empty((3, 4))
data = file.read().split()
for i in range(3):
for j in range(4):
cam[i, j] = data[4 * i + j + 1]
return cam | 225ac897b3f47cf8efc22c46671e12ffc6a34ff6 | 45,807 |
def error_propagation(
func: sp.Function,
syms: tp.List[sp.Symbol],
vals: np.ndarray,
covar: np.ndarray = None,
stds: np.ndarray = None) -> tp.Tuple[sp.Expr, sp.Expr]:
"""Error propagation for an arbitrary function"""
if (covar is None) == (stds is None):
raise Va... | 8f9a8ad5a76c815d4cb8f90bf855da12cd442c4c | 45,808 |
def get_db_config():
"""
获取服务器链接
:return: host, user, password, database, port, charset
"""
db_config = get_config()
if "mysql" in db_config:
host = db_config['mysql']['host']
user = db_config['mysql']['user']
password = db_config['mysql']['password']
database = ... | 2307b5abbbc9a0fba194d97bb1b5533c71990553 | 45,809 |
from datetime import datetime
from typing import List
def phase_dates(base_sunday: datetime.date) -> List[datetime.datetime]:
"""
Test dates and times for the entire week of base_sunday. These are the times we
will use as our message times for updating bell prices.
"""
sunday = relative_message_ti... | 9a7975299d0e19888a2c926ff939313fd4736c81 | 45,810 |
def rejection_sampling(X, e, bn, N):
"""Estimar a distribuição de probabilidade da variável X dada
Evidência e em BayesNet bn, usando N amostras. [Figura 14.14]
Gera um ZeroDivisionError se todas as N amostras são rejeitadas,
I.e., inconsistente com e."""
counts = {x: 0 for x in bn.variable_values(X... | 1a66a9807ab2dcc47a9ac997583e8f9a9b5247a7 | 45,811 |
def get_valid_pbc(inputpbc):
"""
Return a list of three booleans for the periodic boundary conditions,
in a valid format from a generic input.
:raise ValueError: if the format is not valid.
"""
if isinstance(inputpbc, bool):
the_pbc = (inputpbc, inputpbc, inputpbc)
elif (hasattr(inp... | 75ef8175debe6cca03d73fa7430a7bcd44a651ec | 45,812 |
def test_negate_of_neg():
"""Check functionality of unary neg operator."""
return """
fn main() {
var a := -1;
{dest} = -a;
}
""" | 7e66a38e74df011e19705821c1e33efea31b8eb5 | 45,813 |
def get_user_for_token(token, scope, max_age=None):
"""
Given a selfcontained token and a scope try to parse and
unsign it.
If max_age is specified it checks token expiration.
If token passes a validation, returns
a user instance corresponding with user_id stored
in the incoming token.
... | 2e0bd487cf0cf49ba88a55b56437c313468a8f87 | 45,814 |
import os
def _generate_bytes(size_bytes: int, times: int = 1):
"""
Generates a list of <times> random bytes objects,
each the size of <size_bytes>.
"""
return [os.urandom(size_bytes) for _ in range(times)] | 789f912354cd02d836f9ca1caa177cb8c8a1da37 | 45,815 |
import typing
def redirect(url: str) -> typing.Callable:
"""
This function returns a decorator that redirects the request to the given url.
"""
html = f"""
<!DOCTYPE html>
<html>
<p>Redirecting...</p>
<p><a href="{url}">Click here if you are not redirected</... | 5ead24898fba9e98fdb3a31c2bafb87f951f2479 | 45,816 |
import torch
def bi_tempered_binary_logistic_loss(activations,
labels,
t1,
t2,
label_smoothing = 0.0,
num_iters=5,
reduction='mean'):
"""Bi-Tempered binary logistic loss.
Args:
activations: A tensor containing activations for class 1.
labels: A tens... | 1b1b7f6e738839eb2527f17d9765734f313fdb17 | 45,817 |
import os
def get_paths(param, targetdir=None, smbconf=None):
"""Get paths to important provision objects (smb.conf, ldb files, ...)
:param param: Param object
:param targetdir: Directory where the provision is (or will be) stored
:param smbconf: Path to the smb.conf file
:return: A list with the... | f51e977a2e02198c600b803cf4c0123d8942e3ff | 45,818 |
import torch
def bucketize(tensor, bucket_boundaries):
"""Equivalent to numpy.digitize
Notes
-----
Torch does not have a built in equivalent yet. I found this snippet here:
https://github.com/pytorch/pytorch/issues/7284
"""
result = torch.zeros_like(tensor, dtype=torch.int32)
for boun... | ee48e11de50e52278ddf940e32c04e330dceed97 | 45,819 |
import re
import inspect
def _get_task_path(wrapped, instance) -> str:
"""Get the synthetic URL path for a task, based on the `wrapt` parameters."""
funcname = wrapped.__name__
if funcname.startswith("_") and not funcname.endswith("_"):
funcname = re.sub(r"^_+", repl="", string=funcname, count=1)
... | 16ca96d29abddfa104afc5a0ec466e0bd1d202dc | 45,820 |
def location_from_dictionary(d):
"""
Builds a *Location* object out of a data dictionary. Only certain
properties of the dictionary are used: if these properties are not
found or cannot be read, an error is issued.
:param d: a data dictionary
:type d: dict
:returns: a *Location* instance
... | 5bb064993a02e1368484a9a9e53e3a106b86f2ea | 45,821 |
from typing import Mapping
import inspect
from typing import Tuple
from typing import Any
def assert_args_correct_typing(
params: Mapping[str, inspect.Parameter],
args: Tuple[Any],
kwargs: Mapping[str, Any],
join: bool = True,
context: str = "",
) -> None:
"""
Applies :func:`output_if_args... | 7955406cd44716094a0fbbb07002db30e92d0901 | 45,822 |
import sys
def about():
"""Render About page. Only when is run independent from ComPath"""
metadata = [
('Python Version', sys.version),
('Deployed', time_instantiated),
('KEGG Version', current_app.pathme_manager.get_pathway_by_id('hsa00010', 'kegg').created),
('Reactome Versi... | 5ec0ddc80052a6b58a357dacb80095d037d2db5c | 45,823 |
def get_task(username, m_wf_id, wf_id, task_id):
"""
Returns task identified by m_wf_id, wf_id, task_id.
:query boolean pretty-print: Return formatted JSON response
:statuscode 200: OK
:statuscode 401: Authentication failure
:statuscode 403: Authorization failure
:statuscode 404: Not found... | e24e79ecc8fa18c90e8dd2cdc21ef39f1e796ff1 | 45,824 |
import os
import codecs
def check_all(doc_root):
""" check_all iteratively checks docs link. return True on error occurs,
broken links will be outputed to stderr """
has_error = False
for root, dirs, files in os.walk(doc_root):
for name in files:
if name.endswith(".md"):
... | de630a6e7306e82e7c71a84a644d2072a5339e9c | 45,825 |
def requires_internet(func):
""" Decorator for functions that require internet
Parameters
----------
func: func
Function that requires an active internet connection
Returns
-------
"""
def inner(*args, **kwargs):
if internet():
return func(*args, **kwargs)
... | 97b84059361d2ca102c199c28ba33a053f5ac806 | 45,826 |
from emoji_data_python import emoji_short_names, EmojiChar
from typing import cast
import re
def replace_colons(text: str, strip: bool = False) -> str:
"""Parses a string with colon encoded emoji and renders found emoji.
Unknown emoji are left as is unless `strip` is set to `True`
:param text: String of ... | 08488e31bf93478ee0cb6f52ea8e544c2c2480f5 | 45,827 |
def check_feature_names(num_features, feature_names, active_features):
"""Check feature names for consistency and supply defaults if necessary.
:param num_features: positive integer; number of features
:param feature_names: list of strings or None; if not None, must have num_features elements
:param ac... | d8b53139af08053dee24ae762b283fadb0709f78 | 45,828 |
import uuid
def autoslugWithFieldAndUUID(fieldname):
"""[Generates auto slug integrating model's field value and UUID]
Args:
fieldname ([str]): [Model field name to use to generate slug]
"""
def decorator(model):
# some sanity checks first
assert hasattr(model, fieldname), f"... | bd1a96f865a2389deb596ab15680bedef8de75c5 | 45,829 |
def create_sequence_diagram_x(eye_x, eye_valid, height, width, offset=0, step=0.5, should_skip=True):
"""
A Function that returns a 2D numpy array representing the sequence diagram on it
:param eye_x: an indexable datastructure with the x eye coordinates
:param eye_valid: an indexable d... | c2c5b415287b359558937b3d42a37e9966450528 | 45,830 |
import os
def compute_hashes(paths, path_only=lambda p: False):
"""Computes strong hashes of the contents of all the files paths, and returns them as a list.
:param path_only: Optional lambda function which takes in a path, and returns true if that path
should be hashed using only its pathname, rather than it... | 239e37b17173fa8d4f98ba10db3f30e8ae49fd94 | 45,831 |
def status(channel_id):
"""From Hub fetch Status"""
channel = Channel.query.get_or_404(channel_id)
response = channel.refresh()
return jsonify(response) | 8f5e0d12ebd13d4de032f2bc71cc4118dc719321 | 45,832 |
import os
def collect_dmripreproc_output(dmriprep_dir, subject_id, session_id = None):
"""
Collect the dmripreproc output files for a specific subject and session.
"""
dmri_output = dict()
dmri_files = os.listdir(dmriprep_dir)
# Get path for this subject
subject_name = "sub-" + subject_id
... | e792cb21245bacc88d0a939a728208ae77126007 | 45,833 |
from . import routes
def init_app():
"""Construct core Flask application with possible Dash app."""
fapp = Flask(__name__, instance_relative_config=False)
fapp.config.from_object('config.Config')
with fapp.app_context():
# Import parts of our core Flask app
# # Import Dash applicatio... | 95b6e82135f272f0a99bc81b261343701b9f1806 | 45,834 |
def get_lidar_image_message(lidar_image):
"""Convert an opencv image (image) to an imgmsg."""
try:
return bridge.cv2_to_imgmsg(lidar_image, encoding="mono8")
except CvBridgeError:
rospy.loginfo("Error converting lidar image to imgmsg")
raise | c398dd2354ecf9e8b4df0fdfc72b41c59a044b27 | 45,835 |
import argparse
def get_argument_parser():
"""
List of arguments supported by the script
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-i",
"--input",
type=str,
help="Path to the folder containing the 'jpg', 'imagelabels.mat' and 'setid.mat' files",
... | 9a89ddeb58869296b037a318ebaeb8ea320f30d0 | 45,836 |
def make_email(slug):
"""Get the email address for the given slug"""
return '{}@djangogirls.org'.format(slug) | f07dc679d4ee2d3e13939e5b13897b98766f5037 | 45,837 |
import os
import glob
def list_files_of_extensions(folder, extensions):
"""
List files in the specified folder which have the specified extensions.
Do not traverse subfolders.
folder: string path to folder containing files
extensions: only files with these extensions will be returned
Return ... | 2f8d5aeada3799d9171c83c241f8896fe6d7786c | 45,838 |
def count_related(model, field):
"""
Returns a `Subquery` suitable for annotating a child object count.
"""
subquery = Subquery(
model.objects.filter(**{field: OuterRef("pk")})
.order_by()
.values(field)
.annotate(c=Count("*"))
.values("c")
)
return Coales... | 119dc9d4da6b447e195128a86312a7e0386d2782 | 45,839 |
def get_not_registered_tests(conf_json_tests: list, content_item_id: str, file_type: str, test_playbooks: list) -> list:
"""
Return all test playbooks that are not configured in conf.json file
Args:
conf_json_tests: the 'tests' value of 'conf.json file
content_item_id: A content item ID, cou... | 1c1482866e594b6e318999a927cb38576fa4ee37 | 45,840 |
import pandas as pd
def _dataarray_unstack(da, sources, targets, roi_tot, fill_value, order,
rm_missing):
"""Unstack a 1d to 2d DataArray."""
da['roi'] = pd.MultiIndex.from_arrays(
[sources + targets, targets + sources], names=['sources', 'targets'])
da = da.unstack(fill_va... | a5938dfd1ecfd156351103b60f5aab64ba184926 | 45,841 |
import zoneinfo
def to_internal_dt(date_time):
"""
Convert input datetime to internal timezone
and removes microsecond component.
"""
return date_time.astimezone(zoneinfo.ZoneInfo(settings.internal_tz)).replace(microsecond=0) | 56b0972c6483b763c59644a7e1327b8a90c1fc20 | 45,842 |
import sys
import io
import csv
def construct_csv(cursor):
""" transforms the db cursor rows into a csv file string
"""
header, data = construct_list(cursor)
# python 2 and 3 handle writing files differently
if sys.version_info[0] <= 2:
output = io.BytesIO()
else:
output =... | 39dbdd5373c69dd5503813d12e6f1350b38ed7f1 | 45,843 |
def _get_queue_properties():
"""Function used to return a list of queue properties."""
properties = []
properties.append(QueuePropHeader(
queue_property=QueueProperties.OFPQT_MIN_RATE, length=12))
return properties | 3e1fd49c92fe1f553315172a4a239bfb1e5a13b4 | 45,844 |
def _dump_privatekey(key, filetype=FILETYPE_PEM):
"""Dumps obj private key object to string."""
return crypto.dump_privatekey(filetype, key) | 718496e94d71b3f5c7d2820fe85ee81a44093b34 | 45,845 |
def pool3d(layer, ksize, strides, padding, pooling_type):
"""Convenience function to perform pooling in 3D
Parameters
----------
layer : tf.Tensor
Input tensor.
ksize : list of int
Size of pooling kernel in each dimension:
[size_batch, size_x, size_y, size_z, size_channe... | 62efba712e39b2a16b971cd93cc9455eb91c4fb0 | 45,846 |
def generateUniformMesh(domain: Domain, offset=0):
"""
[i][]: i source index
[][k]: k = 0,1, where 0 is X data and 1 is t data
"""
if domain.spatial_dimension == 1:
grid = np.meshgrid(
np.linspace(domain.Xbounds[0][0], domain.Xbounds[1][0], domain.nX[0]),
... | 9815ba3b8fb1ca38b7fdee3bd94ccd15711106f6 | 45,847 |
def flipTurn(piece):
"""手番反転
Returns
-------
str
piece
"""
if piece == PC_X_LABEL:
return PC_O_LABEL
elif piece == PC_O_LABEL:
return PC_X_LABEL
return piece | f038bd1c1efd01a75ebd42988c2c30844abcc85f | 45,848 |
import asyncio
async def startPrediction(sid, data):
"""
data: dict of
- champion id
- lane
"""
log(sid, "startPrediction", data)
runeproposers[sid] = RuneProposer(models, preprocessing);
if not "champion_id" in data or not "lane" in data:
return False, "Mis... | d189e4462dd2d0e2614c3175db739f7d42925fc1 | 45,849 |
import _ctypes
def IMG_isCUR(src):
"""Tests whether a file object contains a CUR (Windows cursor) image.
Args:
src (:obj:`SDL_RWops`): The file object to check.
Returns:
int: 1 if BMPs are supported and file is a valid CUR, otherwise 0.
"""
return _ctypes["IMG_isCUR"](src) | fc6ba3d4bb8f51c3ce4f6af19fd5219f21d89eb0 | 45,850 |
def compute_kid_from_feature(fake_features,
real_features,
num_subsets=100,
max_subset_size=1000):
"""Computes Kernel Inception Distance (KID) based on the extracted features.
KID metric is introduced in https://arxiv.org/pd... | 8708e7faabd3807437bb30b623003328eeee0c55 | 45,851 |
def blockmodel(g, k, iterations=20, corrected=True, indices=[]):
""" Takes a graph and a number of clusters, returns group assignments.
g is the graph, a 2- or 3-d binary (NOT boolean) numpy array
Right now, treats the network as 1-mode, so there's only 1 k.
"""
# The indices of the people whose n... | fd6ce3d416965bf712c9f482760d4ed012a96aca | 45,852 |
def _get_otsu_threshold(gray_img) -> int:
"""大津の二値化によるしきい値を返します。
Arguments:
gray_img {numpy.ndarray} -- グレー画像(1ch)
Returns:
int -- しきい値
"""
opt_threshold = 0
max_sb2 = 0
# w0 * w1 * (M0 - M1) ^2 が最大になるような t が最適なしきい値
for threshold in range(1, 256):
sb2 = _get_sb... | ffb3719fbd05d9cff68235351ddc20060eb916a6 | 45,853 |
def create_dropout_layer(dropout,
num_gpus,
default_gpu_id,
random_seed):
"""create dropout layer"""
dropout_layer = Dropout(rate=dropout, num_gpus=num_gpus, default_gpu_id=default_gpu_id, random_seed=random_seed)
return dropout_laye... | fc8fff4f7ec700ed7946f2983fbdd0b47c15b39c | 45,854 |
def r2_op(predictions, targets, inputs):
""" r2_op.
An op that calculates the standard error.
Examples:
```python
input_data = placeholder(shape=[None, 784])
y_pred = my_network(input_data) # Apply some ops
y_true = placeholder(shape=[None, 10]) # Labels
stderr_op =... | d3f52ec28c0a03fd8fc23b401d2c618266970e36 | 45,855 |
def dday_to_datetime64(dday: np.ndarray, yearbase: int) -> tp.Tuple[NDArray, NDArray]:
"""Convert time recorded time to pandas time (np.datetime64[s]).
Replace time coordinates with datetime64 in strftime='%Y-%m-%d %H:%M:%S'
Add `time_string` variables to dataset (strftime='%Y-%m-%d %H:%M:%S')
Paramet... | 356400b5565eca50341175fb953a8cdc98b87df7 | 45,856 |
def quant(bins, bins_density, interval=0.95):
"""
Get the indexes defining range of equal tail density (for one interval) given binned density values.
:param bin_density:
:return: indexLower, indexUpper: the indexes corresponding to the edge of the interval
:type list of one tuple... | 260cb30cfd2078c7cbae179a0b2c92da64e03174 | 45,857 |
def evaluate_field_nodeset_mean(field: Field, nodeset: Nodeset):
"""
:return: Mean of field over nodeset.
"""
fieldmodule = nodeset.getFieldmodule()
components_count = field.getNumberOfComponents()
with ChangeManager(fieldmodule):
mean_field = fieldmodule.createFieldNodesetMean(field, no... | cbeb56d6e1301b27a38a0ef632ef8f91f60ed99d | 45,858 |
import glob
def open_generic_product(inpath):
"""Open a satellite product.
Open a satellite product based on satpy functions without specifying a
reader.
:param inpath: Path to the folder containing the satellite images
:type inpath: pathlib.PosixPath
:return: Satpy scene containing the open... | 7a77793fecfa2cc84ae49f0b8111fef99160ab59 | 45,859 |
import math
def _get_best_sol2(x_0, y_0, x_1, y_1, x_ca, y_ca, x_prev, y_prev, r_a, r_b, sols, i_center=1):
"""Gets the solution with the the solution with the shortest arclength
"""
arc_lengths = []
for i, sol in enumerate(sols):
# Look for NaNs in tan point and center point
if ... | 580ce3f6538a37f49d47ba2a0cc4a7bc54a8b1ff | 45,860 |
import os
def generate_one_year(year, path_features="./../data/wikipedia_italy/new_data"):
"""
Generate a dataframe containing the data of only one influenza season.
The dataframe contains, for each week, the pageview of a each Wikipedia's page
of the dataset.
:param year: the year we want to gen... | 7cb79cd81664f12fc6d2aff929a5f2eeed1e1412 | 45,861 |
def s_input(prompt : str = ">", accepted_inputs : list = ["break"], case_sensitive : bool = False, fail_message : str = "") -> str:
"""Keeps asking for user input until the answer is acceptable.
Args:
prompt (str, optional): User is prompted with this each time. Defaults to ">".
accepted_inpu... | 8adda3fefe9111167af387e569d080e88e239e4e | 45,862 |
def set_vmem_rt(args, run_dir, conf, run_hours, nslots=1,
pool_jobs=False, test_run=False, request_vmem=True):
"""Set vmem and runtime per time step based on settings in config file."""
skip = False
resource_search_paths = [args["run_path"], *conf.resource_search_paths]
# get runtime ... | 33b586d5d38ba0e5fdba05b4d0cf6ad91eadf635 | 45,863 |
def hadamard(normalized=False, dtype=jnp.float32):
"""We need the numpy to use it as initializer"""
def init(key, shape, dtype=dtype):
n = shape[0]
# Input validation
if n < 1:
lg2 = 0
else:
lg2 = np.log2(n)
assert 2 ** lg2 == n, "shape must be a ... | eeb32d66b033370c03e49b4ff9f0b72b52c03ef3 | 45,864 |
def _gen_ntluf_capture_chain_fo(nt_names, ii):
"""
Given a list of OP_NAME_NT_NAME strings(nt_names), generate a function
object (function_object_t)
that calls corresponding xed3 NT capturing functions.
Each such function captures everything that xed2 decode graph would
capture for a given patt... | 78d3576ee6d55d5f31f4327d1e84184cefcb78a8 | 45,865 |
def silhouette_loss(input_img, prob, z, vh=128, vw=128, num_kp=10):
"""
Args:
prob, z: Output of keypoint network for a single image
(batch_size, 128, 128, 10)
"""
mask = input_img[..., 3]
mask = tf.cast(tf.greater(mask, tf.zeros_like(mask)), dtype=tf.float32)
prob = ge... | 7226a023947ff3c6eaa5c555a855d296c7556b0d | 45,866 |
import torch
def get_ctrl_vec(exs, history, control_settings):
"""
Given a batch of examples with given history, return the bucketed CT control values.
This is used both when training and evaluating CT systems.
Inputs:
exs: list length batch_size of message dictionaries. Each dictionary contain... | 523e6fd68c3a82f2c3aec04e53e13e7ab78af7e4 | 45,867 |
import os
import sqlite3
def get_ports(db_name):
"""Extract all local_port that are being used.
Args:
db_name: Database name used to read.
Return:
ports: local_port from all users.
"""
# CHECK IF DB EXISTS OR NOT
if os.path.isfile(db_name):
try:
# CONNECT T... | fc980d76bf4d0144ed272432dceb9aabbbd94c32 | 45,868 |
def stationary_fixed_points(history):
"""Take the decision if the point is stationary. It runs for different
orders.
Parameters
----------
sequence: np.ndarray
the sequence information.
Returns
-------
stationary: boolean
if the sequence is in a stationary point.
fi... | c0a9692880147b3c6ce083fe5612b1f2a04aea8a | 45,869 |
def WRAP(r, Hr, wrapname):
"""Wrapping
(macro)
e.g. WRAP(r, ['D', 'E', 'F'], 'X') (or r.wrap(['D', 'E', 'F'], 'X')
(Tutorial D equivalent: r WRAP { D, E, .., F } AS X
"""
return r.extend([wrapname], lambda t:{wrapname:t.project(Hr)}).remove(Hr) | 4b981704a85a289fb0d16e653a851a99298cd793 | 45,870 |
def is_empty(iterable):
"""
This filter checks whether the given iterable is empty.
:param iterable: The requested iterable
:type iterable: ~collections.abc.Iterable
:return: Whether or not the given iterable is empty
:rtype: bool
"""
return not bool(iterable) | 0163a8ff1c2e38fbe3f343b852a5dce39fb76536 | 45,871 |
import os
async def delete_snapshot(request):
"""delete a snapshot
:Example:
curl -X DELETE http://localhost:8081/fledge/snapshot/plugins/1554204238
When auth is mandatory:
curl -X DELETE http://localhost:8081/fledge/snapshot/plugins/1554204238 -H "authorization: <token>"
"""
... | aba633d34d1dadd4d4da1ddab9a69ec4e57db0ef | 45,872 |
def order_flag_field(key, value):
"""Return the fields key value pairs in the correct order (name (str), bit (int)).
Args:
key (int/str): Bit int or name.
value (str/int): Name or bit int.
Returns:
field (tuple): (name (str), bit (int))
"""
bit, name = order_flag_options(ke... | 7c69ed9edd12fe6dfcf643bdddf05b2e8099ceed | 45,873 |
import requests
from bs4 import BeautifulSoup
def priprav_bs(url, params):
"""BeautifulSoup z celé stránky
url: str
params: dict
Vrátí: bs4.BeautifulSoup
"""
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:80.0) Gecko/20100101 Firefox/80.0'}
r = requests.get(url,... | 30775e56960829413211524d615ca0dea6bc8b0c | 45,874 |
import time
def evaporation():
"""
Real Name: b'Evaporation'
Original Eqn: b'Max(0,"monthly evaporation -1 Finesk" (Time)*"normal evaporation -1 Finesk"*"surface -1 Finesk"\\\\ )'
Units: b'MCM/Month'
Limits: (None, None)
Type: component
b''
"""
return np.maximum(
0,
... | 73b9677963784b4a6af8e7f50f96a9445dec91eb | 45,875 |
def calcAnisousFromModel(model, ):
"""Returns a Nx6 matrix containing anisotropic B factors (ANISOU lines)
from a covariance matrix calculated from **model**.
:arg model: 3D model from which to calculate covariance matrix
:type model: :class:`.ANM`, :class:`.PCA`
.. ipython:: python
from p... | ae55e08a3b35ed9c7d5cb52d2fb8d859cd4f0f67 | 45,876 |
def local_opchains_to_MPO(qd, L, lopchains):
"""
Construct Hamiltonian as MPO based on local operator chains,
which are shifted along a 1D lattice.
Args:
qd: physical quantum numbers at each site
L: number of lattice sites
lopchains: local operator chains
Returns:
... | 0951289db729db3cd1805dee6298b45f90ae2ebc | 45,877 |
from functools import reduce
def solve(ar):
"""
Given an array of 5 integers, return the minimal and maximal sum of 4 out of
5 of the integers.
"""
# Just sort the list of integers in place and take the sum of the first 4
# then the last 4.
ar.sort()
minSum = reduce((lambda x, y: x + y... | 68d650c51cbe611c51c0b5754c61b541cb1838f8 | 45,878 |
from typing import Optional
def landmark_elastic_registration_warping(
fd: FData,
landmarks: ArrayLike,
*,
location: Optional[ArrayLike] = None,
grid_points: Optional[GridPointsLike] = None,
) -> FDataGrid:
"""Calculate the transformation used in landmark registration.
Let :math:`t_{i... | c270080e0c85106d469ca0179746d6a366f094b2 | 45,879 |
def composite(ifrom, ito, values, comp_length=1.0, min_comp_length=-1.0):
"""
cfrom,cto,clen,cvar,cacum= composite(ifrom, ito, values,
comp_length = 1, min_comp_length=-1)
Composite intervals in a single drillhole. The From-To
intervals may be sorted.
Parame... | 876a4347b288aa0c78a40e6988aba22bef9c008a | 45,880 |
def search_by_stop_id(stop_id):
""" Search for a stop by its stop_id
returns a list that should contain only one stop
"""
return [Stop.from_json(_query("stops/bystop/" + stop_id))] | 8ae67f041494a73c29c9f7051aca842d706fe25a | 45,881 |
import os
def frontend(args):
"""Generate the LLVM bitcode file."""
bitcodes = []
libs = set()
noreturning_frontend = False
def add_libs(lang):
if lang in extra_libs():
libs.add(extra_libs()[lang])
if args.language:
lang = languages()[args.language]
if lang in ['boogie', 'svcomp', 'j... | 4e8ea1ce7a832b0e4f47a29e838e14c36a78b55f | 45,882 |
from pathlib import Path
def run_tiempo(input_dictionary, prefix_atm_data, sourcefolder, save_name_data, savefolder = None, save_P=True, save_T=True, n_jobs = 30, n_batches = 8,\
obs_time = 3600., grid = .2, x_length_strip = 65536., separation = 1.1326,\
galaxy_on = True, luminos... | 91949083c52a8f84a4d013d9517c109ccf669489 | 45,883 |
def poly_regression(sequence, seq_range):
"""Return (x0,y0,x1,y1) of a poly_line fit to a segment of a sequence using polynomial regression"""
y = sequence.values[seq_range[0]:seq_range[1]]
x = np.arange(seq_range[0], seq_range[1])
if len(x) != len(y):
x = np.arange(seq_range[0], seq_range[1])[:... | e13cb1acc7c59626b28776a7679a766d3bc965bd | 45,884 |
async def api_get_donations(g: WalletTypeInfo = Depends(get_key_type)):
"""Return list of all donations assigned to wallet with given invoice
key
"""
wallet_ids = (await get_user(g.wallet.user)).wallet_ids
donations = []
for wallet_id in wallet_ids:
new_donations = await get_donations(wa... | 9eb6ac02bf5a52c2d7823d108d6881a79257c7a8 | 45,885 |
import tqdm
import os
def get_coverage_data(genes, degnorm_dir, save_dir=None):
"""
Access raw and DegNorm-estimated coverage matrices of a set of genes run through the DegNorm pipeline.
By default, returns two lists:
- raw coverage pandas.DataFrames
- DegNorm-estimated coverage pandas.Da... | 92a5e9bc5ffb534c7fdac55498ba5c458702313c | 45,886 |
def yolo_eval(yolo_outputs,
anchors,
num_classes,
origin_image_shape,
max_boxes=20,
score_threshold=.6,
iou_threshold=.5, return_xy=True, lite_return=False):
"""Evaluate YOLO model on given input and return filtered boxes.
只适用于一... | f8e95dff3e70ec58909f95d17b3fdb8cc832b224 | 45,887 |
def combine_matrix_4_128_1_64(input1, input2):
"""
Combine diag matrix.
Args:
input1:tvm.Tensor of type float32 with shape [4,128,128].
input2:tvm.Tensor of type float32 with shape [1,64,64].
Returns:
akg.tvm.Tensor of type float32 with shape [576,576]
"""
batch_dim_1 =... | e9655d39caa0348a5d57e38e54eac8a4bb9c49c9 | 45,888 |
import torch
def global_order_idxs_to_local(
global_indices: torch.Tensor, x_possible_actions: torch.Tensor, *, ignore_missing=False
) -> torch.Tensor:
"""Convert global order indices to local order indices.
Args:
global_indices: Long tensor [B, 7, S] of indices in ORDER_VOCABULARY
x_poss... | 3de8065d77cad46ccb441207e35598769786db68 | 45,889 |
import resource
def read(address, args={}):
"""
Read pool by address
"""
return resource.read(**{**{
'type': 'pool',
'key': address,
}, **args}) | c29f1643b74866c8c0879947d720526494083834 | 45,890 |
import logging
import sys
import argparse
import tempfile
import shutil
def main():
""" See collect_task.collect_task for more on the merge script API. """
logging.info(sys.argv)
parser = argparse.ArgumentParser()
# configuration-name (previously perf-id) is the name of bot the tests run on
# For example, b... | 3b22294e4220a1e4319841df540014b037bde80b | 45,891 |
def force_auth_user(app, admin=False):
"""EditFlask-Login's request loader to force a logged in user."""
user = User.query.filter(User.email == str(ADM if admin else USR)).first()
@app.login_manager.request_loader
def load_user_from_request(_request):
return user | 723137bb6f0aca52324caa8fcbe1321ae4d82e55 | 45,892 |
def get_config_data():
"""
Get config data object.
"""
return Config().__data__ | db57c44df739e18c7af176c31679637fd9ed98e1 | 45,893 |
import sys
def chain_bed_intersect(chain, bed):
"""Entry point."""
# get list of chrom: ranges for both
skipped = []
chain_data = parse_chain(chain)
bed_data = parse_bed(bed)
chroms = list(set(bed_data.keys()).intersection(chain_data.keys()))
# to save beds that are skipped at this stage:... | 33fc162160331dbf19e436bb1612dcaa62f9c17d | 45,894 |
def verify_package(ns, package):
"""
Returns the instances of ``LMI_SoftwareIdentityFileCheck`` representing
files, that did not pass the verification.
:param package: Instance or instance name of
``LMI_SoftwareIdentity`` representing package to verify.
:type package: :py:class:`lmi.shell.L... | f8174a85a9fd154d3849c28cd11e04ad5b4db132 | 45,895 |
def parse_time(ev_time, datetime_format="%Y%m%d %H%M%S%f", unix=False):
"""Convert EV datetime to a numpy datetime64 object
Parameters
----------
ev_time : str, list
EV datetime string or list of these
datetime_format : str
Format of datestring to be used with datetime strptime
... | c9d7b673be43e8eca55d40baafd0448ee627ca23 | 45,896 |
import json
import base64
def aes_encrypt(key, data):
"""
AES ECB模式 Pkcs7补全 加密
:param key: 密钥
:param data: 待加密表单
:return:
"""
data = json.dumps(data).replace(' ', '')
# 初始化 AES 加密, ECB模式
encrypter = AES.new(key.encode('utf-8'), AES.MODE_ECB)
# Pkcs7 补全
pad_pkcs7 = pad(data.... | 07eec765a91b6c7d28ec142b282642da889f8811 | 45,897 |
def class_to_xy(poly, grid_size):
"""
NOTE: Numpy function
poly: [bs, time_steps] or [time_steps]
Returns: [bs, time_steps, 2] or [time_steps, 2]
"""
x = (poly % grid_size).astype(np.int32)
y = (poly / grid_size).astype(np.int32)
out_poly = np.stack([x, y], axis=-1)
return out_pol... | ad0ee423fe4aa5b89de56bcf74cf6e47f3df7dc6 | 45,898 |
def fit_polynomial(leftx, lefty, rightx, righty, fit, visualize=False,
img=np.array([], [])):
"""
Fits a 2nd order polynomial to the detected pixels on the lane lines
"""
# Fit a poltnomial x = A*y**2 + B*y + C to the detected lane line pixels
try:
left_fit = np.polyfit(le... | 92871cb0a5a765ad35b047582589eae48c9e223f | 45,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.