content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 |
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 |
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 |
def make_email(slug):
"""Get the email address for the given slug"""
return '{}@djangogirls.org'.format(slug) | f07dc679d4ee2d3e13939e5b13897b98766f5037 | 45,837 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
import re
def file_to_subtitles(filename):
""" Converts a srt file into subtitles.
The returned list is of the form ``[((ta,tb),'some text'),...]``
and can be fed to SubtitlesClip.
Only works for '.srt' format for the moment.
"""
with open(filename,'r') as f:
lines = f.readlines()
... | 007c4360c0b8168c8a1ff4f609a02316f7374690 | 45,900 |
def all_layers():
"""Sample layer elevation grid where some layers
are completely pinched out (no botm elevation specified) and
others partially pinched out (botms specified locally).
Returns
-------
"""
nlay, nrow, ncol = 9, 10, 10
all_layers = np.zeros((nlay + 1, nrow, ncol), dtype=f... | fc9f43cf0f7a44512b3c21e3c0ac86a0ff881dd9 | 45,901 |
def calculate_border(grid_dims, width, height):
"""Calculate each line in all borders.
Args:
grid_dims: tuple of the number of tiles in grid. In format `(row, column)`
width: float width in pixels
height: float height in pixels
Returns:
list: containing dictionaries keys `(... | b4ec0e063034547783e871abf1a46d943648df67 | 45,903 |
import pandas
def df_fe2num_frames(fn_instance):
"""
create a df in which each row contains the number of frames that a FE is a part of
:param instance of nltk.corpus.reader.framenet.FramenetCorpusReader fn_instance: instace of fn version
:rtype: pandas.core.frame.DataFrame
:return: df with for... | 69393f8097a0a705a193a3015bcb725dda6dbb8d | 45,904 |
def check_y_pos(act: Act, acts: list) -> bool:
"""Checks if the y position of Activities overlaps any other given Activities.
Args:
act: Activity of which to check the overlap.
acts: List of Activities to check against.
Returns:
True if Activity does not... | c63e9335a4357b5a4f091f2ad5b2758fd846f2ac | 45,905 |
def dijkstra_heap(siten):
"""
1-indexed
疎グラフの時に有効 O(E log(V))
:return:
"""
dist = [INF] * (n + 1)
dist[siten] = 0
que = []
heappush(que, (dist[siten], siten))
while len(que):
d, v = heappop(que)
if d > dist[v]:
continue
for e in G[v]:
... | a7c5d770a7df6ca888e4df42146f327c95eca612 | 45,907 |
def _parse_face(face_row):
"""Parses a line in a PLY file which encodes a face of the mesh."""
face = [int(index) for index in face_row.strip().split()]
# Assert that number of vertices in a face is 3, i.e. it is a triangle
if len(face) != 4 or face[0] != 3:
raise ValueError(
'Only supports face repre... | c0cf7472705544c3089a6c1c82190bcb8bd5f463 | 45,908 |
def include_keys(include, d):
"""
Pick out the `include` keys from a dict
Args:
include: list or set of keys to be included
d: raw dict that might have irrelevant keys
"""
assert is_sequence(include)
return {k: v for k, v in d.items() if k in set(include)} | 83dde8334819fd1be825707172219eb8505956f1 | 45,910 |
import torch
def spherical_interpolate(p1, p2, n_steps=8):
"""Spherical interpolation between two vectors."""
assert p1.dim() == p2.dim() == 1, "Only 1d vectors are currently supported."
def _spherical_interpolate_pytorch():
ratios = torch.linspace(0, 1, steps=n_steps)
vectors = [slerp(ra... | c30aca403ee6f4a96311c6b95a8fe81a515b3ff9 | 45,911 |
def override_serializer(format_output, dimension, base_serializer_class):
"""
Override Serializer switch output format and dimension data
"""
if format_output == 'geojson':
if dimension == '3':
class GeneratedGeo3DSerializer(BaseGeoJSONSerializer,
... | f02c3d6144cb152c40040a37a73f649c011c8ea4 | 45,912 |
def _get_config():
"""Return a config dictionary."""
return {
DYSON_DOMAIN: {
CONF_USERNAME: "email",
CONF_PASSWORD: "password",
CONF_LANGUAGE: "GB",
CONF_DEVICES: [
{"device_id": "XX-XXXXX-XX", "device_ip": "192.168.0.1"},
... | b69094088f1dda94540e8e5f6f89a108ceb93396 | 45,914 |
def test_parallel_pathos_pp_task ( ) :
"""Test parallel processnig with parallel_pathos (task interface)
"""
logger = getLogger ("ostap.test_parallel_pathos_pp_task")
if not WorkManager :
logger.error ("Failure to import WorkManager")
return
logger.info ('Test job submission w... | 8b027b496f52e26a8ee64d6c56882acda4cc4f13 | 45,915 |
def create_r2_script_content(sample_file_path, decoded_strings, stack_strings):
"""
Create r2script contents for r2 session annotations.
:param sample_file_path: input file path
:param decoded_strings: list of decoded strings ([DecodedString])
:param stack_strings: list of stack strings ([StackStrin... | edb91bc3489560cb5b3a9445ae35ffc5bb7d0dad | 45,916 |
import pandas
def ReadData(filename='PEP_2012_PEPANNRES_with_ann.csv'):
"""Reads filename and returns populations in thousands
filename: string
returns: pandas Series of populations in thousands
"""
df = pandas.read_csv(filename, header=None, skiprows=2,
encoding='iso-88... | 931256a3a22f64ee698bb4116728494473230bb4 | 45,917 |
import json
def get_new_username():
"""提示用户输入用户名"""
username = input('请输入用户名:\n')
filename = 'username.json'
with open(filename, 'w') as f:
json.dump(username, f)
return username | 3b6023dd950e689995af472005809d6ca97033c1 | 45,918 |
def bezier3_split_batch(batch):
"""Split N bezier3 curves in 2xN bezier3 curves at t=0.5"""
return np.moveaxis(np.dot(BEZIER3_SPLIT, batch), 0, -2).reshape((-1, 4, 2)) | daaae323b8e91ea40d1425b8a088f8f6eed616cf | 45,919 |
def create_indices(ordering_1: SortedList, ordering_2: SortedList):
"""
Creates indices np.array which represents how agents from ordering_1 have to be rearranged
in order to fit agents from ordering_2. If such relation is not possible, return False.
:param ordering_1: first agents ordering
:param ... | f58d59b997449a248673671375377fb623bdcd38 | 45,920 |
def extend_conv_spec(convolutions):
"""
添加默认配置(残差)
Extends convolutional spec that is a list of tuples of 2 or 3 parameters
(kernel size, dim size and optionally how many layers behind to look for residual)
to default the residual propagation param if it is not specified
"""
extended = []
... | 4e6639342b19db18939991c7bc681d7e23a855f4 | 45,921 |
def bin_spectra(filename, start=None, end=None, save=True, dec=3, function=None):
"""
Sums spectra from raw file and outputs to excel file
:param filename: raw or mzML filename
:param start: start scan (None will default to 1)
:param end: end scan (None will default to the last scan)
:param sav... | ef0a25d4b55dcef198b5e7a2a7d87411f2a144b1 | 45,922 |
def internal_manifest_from_external(
manifest: ImportManifest, content_records: list
) -> InternalImportManifest:
"""
Construct an internal manifest from an external one plus the db records for the content
:param manifest: ImportManifest object
:param content_records: list of ImageImportContent rec... | ba20c97a80879d038f596603ebe8853e34634b87 | 45,923 |
def hello():
"""Return a friendly HTTP greeting."""
if request.method == 'POST':
return "Yes {}".format(request.form.get("myname"))
return "<form id='myform' method='POST'><input name='myname'/></form>" | e05a9d20ac8626a70af8aa8cd377e79f4209099e | 45,924 |
def prepare(topic_model, docs, **kargs):
"""Transforms the GraphLab TopicModel and related corpus data into
the data structures needed for the visualization.
Parameters
----------
topic_model : graphlab.toolkits.topic_model.topic_model.TopicModel
An already trained GraphLab topic model.
... | ff18e1784d13a5e089a74f6ccab400ae7303c7d6 | 45,925 |
def fit_gaussians(data, height, width, savedir='./', overplot=False,
savename='./Data-With-Gaussians.csv'):
"""
Fits gaussians to the data peaks.
Parameters
----------
data: string or Pandas DataFrame
This should be a string that points to the csv DataFrame file
or... | de223ce309bf40dd13bff4e6166da777255a5e1f | 45,926 |
import json
import re
import requests
def aci_app_proxy():
""" this function is a workaround to current ACI app api restriction that
only allows for post/get requests and static one-level urls. Instead
of doing get/post/delete to dynamic url as provided by this app,
the request will be p... | 32fcb0c8cce1142b522e42ad7517c5378eb9aef4 | 45,928 |
def f(x):
"""return x*x"""
return x * x | f6f06aa4c83d4dfbdfe6d0d8cec93f4a0fef3d4d | 45,929 |
def divideURL(url, queryDelim="&"):
"""Divides a URL into a dict with the following keys,
whose values are an empty str if optional and not set:
- scheme (str)
- authority (dict. Keys: username, password, host, port)
- path (str)
- query (dict. Keys are query keys = list of their values)
- ... | d8bca62a0c99fa1a1c93b07eb8e9a92d8e9c0ac8 | 45,930 |
import torch
def permutation_kronecker(perm1: FixedPermutation, perm2: FixedPermutation) -> FixedPermutation:
"""Combine two permutations of size n1 and n2 into their Kronecker product of size n1 * n2.
"""
n1, n2 = perm1.permutation.shape[-1], perm2.permutation.shape[-1]
x = torch.arange(n2 * n1, devi... | 09538e042794f2c2ebba1743c13e3de04d0144f3 | 45,931 |
import pdb
def get_palate_line_segments(speaker_tensor, name, mt_hull, plot_bool):
"""
data: unordered x,y coordinates from tongue coils T1/TT, T2/TB, T3/TD
and data from T1/TT in the case of 'faet0', 'mjjn0', 'fsew0' are used
to create a convex hull estimate as to where the palate is
in order to... | d1bf5d4c8e87fa805b8d9e758940e00567a45193 | 45,932 |
import copy
def third_round_phase(tableau, phase_stabilizer, phase_destabilizer):
"""Adds a diagonal matrix to the Z destabilizer matrix such that Zd + D = M*M' for some invertible M"""
num_qubits = int(len(tableau[0, :]) / 2)
x_destab = tableau[0:num_qubits, 0:num_qubits]
z_destab = tableau[0:num_qub... | 8fcc4842abd9046e353d489d0591fb55f867ff69 | 45,933 |
def conv_en2ko(string):
"""
conv_en2ko(string)
Convert English characters to Korean characters.
:return: String (Korean)
"""
char_groups = split_en(string)
converted_string = ''
for char_group in char_groups:
top_idx = 0
mid_idx = 0
bot_idx = 0
for char_... | ffc3236a7a2c2773d5ed5e318461ac87d296e534 | 45,934 |
def _check_to_numpy(plugin, tensor):
"""Check the tensor and return a numpy.ndarray."""
np_value = tensor.asnumpy()
if plugin == 'scalar':
if np_value.size == 1:
return np_value
raise ValueError('The tensor holds more than one value, but the scalar plugin expects on value.')
... | 919ff69a7eebf2d32d72f343ff51c9e41c915c5b | 45,935 |
import json
def get_f1_score(labels, pre_file, gold_file):
"""
Get F1 scores for each label.
Args:
labels: list of labels.
pre_file: prediction file.
gold_file: ground truth file.
Returns:
average F1 score on all labels.
"""
pre_lines = [json.loads(line.strip(... | cd473db2abd4c504293557e2c2be84f603083910 | 45,936 |
def calendar_date(year, doy):
"""
Calendar date from day of year
@param year : int
@param doy : int
day of year
@return: tuple of ints
(year, month, day)
"""
if doy < 32:
month = 1
day = doy
elif doy < 60 + leap_year(year):
month = 2
day = doy - 31
else:
if leap_year(yea... | 5c88ed2003d520cd83aba0e822f9ba9ffc9d12ff | 45,937 |
def get_vulnerabilities():
"""Return a paginated list of available vulnerabilities
For vulnerability details see
:http:get:`/api/1.0/vulnerabilities/(int:vuln_id)`
**Example request**:
.. sourcecode:: http
GET /api/1.0/vulnerabilities HTTP/1.1
Host: cp.cert.europa.eu
Accep... | edf3ea064aa51257ca04423316357c423dc414d3 | 45,938 |
def change_referential(
self,
rotation_speed,
is_waveform,
atol=1e-9,
axes_list_change=list(),
arg_list=list(),
freqs_new=np.array([]),
I1=np.array([]),
Irf_un=np.array([]),
sym_t_new=dict(),
ta_in=tuple(),
ta_out=tuple(),
atol_freq=1e-6,
):
"""Change referential ... | 801493ecb2e1ed9c497b6f54bbd661fa18143f65 | 45,940 |
def get_model(tree_type='lgb', objective='regression', n_tree=100,
max_depth=5, random_state=1, max_bins=255, learning_rate=0.3):
"""
Return the ensemble object from the specified framework and objective.
"""
if tree_type == 'cb':
class_fn = CatBoostRegressor if objective == 'regr... | 4643440fad70c7e42b823d14456abb799dade9d3 | 45,941 |
import secrets
import traceback
def alert_gwg_owners(team, subject=None, body=None):
"""Direct messages the owners of the GWG challenge that there isn't a form available
for todays game and that their players are angry!!!
"""
owners = secrets.get_team_contacts(team)
if not subject:
subjec... | b6fa01ef7516fd80ee46d7eceaed8be0af13d314 | 45,942 |
def make_client(args, password='BadKangaroo'):
"""Make an app3 client that talks to an olinapp3 server."""
if 'local' in args:
client = App3Client('localhost:8080', password)
else:
client = App3Client('olinapp3.appspot.com', password)
return client | 957ecda68dc0e8203f561e07b88c11d28ab54802 | 45,944 |
import json
def app(args): # pragma: no cover
"""
Dumps Concepticon's contents for English, German, Chinese, and French.
Notes
-----
Data are by default dumped into a structured JSON file in html/data.js.
Examples
--------
$ concepticon html
"""
data = defaultdict(list)
... | 3d3ee3e0fede9f5d77bd322797795ddadfd36274 | 45,945 |
def get_current_user_info(token):
"""Returns information about the authenticated user."""
return _fetch_api(token, GITHUB_API_ROOT + '/user', bust_cache=True) | 726971e21fd1428ebd543b30bdb9b3cd921e984e | 45,948 |
def remove_no_include(wikicode: mwparserfromhell.wikicode.Wikicode) -> mwparserfromhell.wikicode.Wikicode:
"""Removes the noinclude tags"""
for tag in wikicode.filter_tags():
if tag.tag.matches('noinclude'):
try:
wikicode.remove(tag)
except ValueError:
... | d7c59ce6275a5b287f3f4b8828e890acddb6da1f | 45,950 |
from typing import Dict
from typing import Any
from typing import cast
from typing import Union
from functools import reduce
def parse_query_params(connection: HTTPConnection) -> Dict[str, Any]:
"""
Parses and normalize a given connection's query parameters into a regular dictionary
"""
qs = cast(Unio... | 86f834b58030d065b1364d408c75df7b8d721e2a | 45,951 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.