content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def cache_except_staff(decorator):
""" Returns decorated view if user is not staff. Un-decorated otherwise """
def _decorator(view):
decorated_view = decorator(view)
def _view(request, *args, **kwargs):
if request.user.is_staff:
# view without @cache
... | 83bf8f76e4b09cb651fd3fda9745a94fd65d80d8 | 62,900 |
def moments(data):
"""Returns (height, x, y, width_x, width_y)
the gaussian parameters of a 2D distribution by calculating its
moments """
total = data.sum()
X, Y = np.indices(data.shape)
x = (X*data).sum()/total
y = (Y*data).sum()/total
col = data[:, int(y)]
width_x = np.sqrt(np.abs... | 3bcce628e8d5548327a787540b9839d2a6ba31a8 | 62,901 |
import requests
def _add_to_guestlist(member_id):
"""
Adds a group member to the event guestlist.
WARNING: This cannot be undone automatically.
"""
def _headers():
return {"Authorization": f"Bearer {TOKEN_MANAGER.token().access_token}"}
def _params(member_id):
return {
... | 56bcf35ec6d0f62c2c738a42ed9adc0bc4cec999 | 62,902 |
import math
def Conv2D(x, filters, kernel_size=(3, 3), strides=(1, 1), padding='same', dilations=(1, 1), use_bias=True,
kernel_initializer=None, bias_initializer=tf.zeros_initializer(), trainable=True, name='Conv2D'):
"""Convolution 2D layer."""
if kernel_initializer is None:
kernel_initial... | 676a337ad27cf319441bcbd361e5207730a88018 | 62,903 |
from datetime import datetime
import pytz
import json
import requests
import traceback
def rule_pseudo_request(request, rule_type_id):
"""
[メソッド概要]
テストリクエスト実行時のリクエストを処理する
"""
logger.logic_log('LOSI00001', 'None', request=request)
err_flg = 1
msg = ''
now = datetime.datetime.now(pytz... | d955e4df3be7344d93f3ccec9c1cb13f462cb6c1 | 62,904 |
def sigmoid(z):
"""
Sigmoid function
:param z: input of the sigmoid function
:return: sigmoid calculation
"""
return 1 / (1 + np.exp(-z)) | 835a2682f80cccefec884730b02adb9989ad4699 | 62,905 |
import random
def random_noisy_bipartite_graph(n, p, seed):
"""Generates a base bipartite graph with evently split nodes.
Adds a bipatite edge with probability p.
Add every edge with probability 1/10.
Parameters
----------
n : int
Number of nodes
p : double
Probability of ... | e724a8e6af04a422dea77c9bc80113a00a63d0a6 | 62,906 |
def random_explorer_player(bot, state):
""" Least visited random player. Will prefer moving to a position it’s never seen before. """
if not bot.turn in state:
# initialize bot
state[bot.turn] = { 'visited': [] }
if bot.position in state[bot.turn]['visited']:
state[bot.turn]['visit... | 95b05d749b9fa7994ddb0b1e6adae5ef5c3b25ea | 62,907 |
def get_latest():
"""Get 3 latest transactions."""
return render_template(
'input.html.j2',
today=date.today().strftime('%Y-%m-%d'),
suppliers=get_suppliers(),
categories=get_categories(),
transactions=get_transactions(3, True)
) | 5801d2d5e9d9a38937a38b66b8ef2153e7cb7a8c | 62,908 |
import json
def is_master():
"""
Returns true if executed on the AWS EMR master node
:return:
"""
with open('/mnt/var/lib/info/instance.json', 'r') as f:
data = f.read()
return json.loads(data)['isMaster'] | e18cba58143cb3bd0a990324ae6bd6013cf47739 | 62,909 |
def f(x,y):
"""dy/dx = f(x,y) = 3x^2y"""
Y = 3.*x**2. * y
return Y | 4e18d6411be1c1445ea1aa4d9836b8bf5e26e3d6 | 62,910 |
import warnings
def encoder(encoder_type='Default',
input_tensor=None,
encoder_weights=None,
encoder_freeze=False,
num_blocks=5,
encoder_filters=[32, 64, 128, 256, 512]):
"""
Instantiates the encoder architecture for the DoubleU-Net segmentation mode... | 855fdf6edfb4b779cdb8b66d4e091519580752e2 | 62,911 |
def products_delete(id):
"""Exclui item selecionado"""
#Valida acesso
if int(session.get('user_role')) == 2:
flash("Acesso não permitido")
return redirect(url_for("index"))
message = "Cadastro excluído com successo."
if Activity.query.filter_by(id_product=id).count() > 0:
... | aedc4616acb3808469b3c5390cc4c48962419321 | 62,912 |
import os
import sys
def init_rule_engine(args):
"""
Initialize the import rule engine using the arguments from
the configuration file
"""
folder = args.rules.rules_folder
if len(args.rules.ruleset) > 1:
if not os.path.isfile(folder + "/asset.rules") and args... | 297a56411fca93e1d8725a2f6c83f4d1d1dc58c8 | 62,913 |
def central_moment(dist, n):
"""
Computes the `n`th central moment of a distribution.
Parameters
----------
dist : Distribution
The distribution to take the moment of.
n : int
Which moment to take.
Returns
-------
moments : ndarray
The `n`th central moment o... | 85cae07cd61662f33b4f85babad4ecc7eb666e19 | 62,914 |
def get_face_points(gray_frame, face):
"""
"""
land_mark = predictor(gray_frame, face)
face_points = []
for n in range(68):
x, y = land_mark.part(n).x, land_mark.part(n).y
face_points.append([x,y])
return face_points | 3bc2d47ea9c89362decfd1855b4db95afbc35c8e | 62,915 |
def anim_classic_walk(transition, projection, start_pd, n_steps=10, show_equil=False, frame_option='pairsmean'):
"""
calculate the evolution of random walk and prepare dataframe df of the evolutionvof probability distribution
the probability distribution at start is given as input start_pd. i
in ea... | 17358b078e04e324db59b1f144efc811a1f2e704 | 62,916 |
def spatial_subset(lats_1, lons_1, lats_2, lons_2):
"""
:param lats_1: target lat region
:param lons_1: target lon region
:param lats_2: extended lat region
:param lons_2: extended lon region
:return bounds: bounding box locating l1 in l2
"""
padding = 50 # pixels TODO add to config
... | ba9fb3ce113514a4edb2b5cffed5dd132077997e | 62,917 |
import logging
import base64
import hashlib
def check_password(ssha_ldap_salted_password, password) -> bool:
"""Check the OpenLDAP tagged digest against the given password."""
# See https://www.openldap.org/doc/admin24/security.html#SSHA%20password%20storage%20scheme
# We should (also) support SHA512 as S... | 003972ff32df6a6b55ada07b512154ee7b99d957 | 62,918 |
def input_fn(request_body, request_content_type):
"""
The SageMaker XGBoost model server receives the request data body and the content type,
and invokes the `input_fn`.
Return a DMatrix (an object that can be passed to predict_fn).
"""
if request_content_type == "text/libsvm":
return xg... | b408fc27ba3291da236848f6d81514863bb4e8d7 | 62,919 |
import re
def generate_c_header_finders():
""" Generate the header finders for c style files.
"""
def find_header_start(line):
match = re.search("/\*\*", line)
if match:
return True
else:
return False
def find_header_end(line):
match = re.search... | fa094e7be0e3b9b89b8fdc3f32d729f024f62c7e | 62,920 |
import glob
import copy
import os
def get_virtualenv():
"""
Find the virtualenv runtime. Fall back to using one from
third_party/python/packages. Untar it under the working folder. Return a
command line argument list.
"""
virtualenv = find_in_path('virtualenv', required=False)
if virtualen... | bb8a27eab5c55b43829cbdf696e9db14b9baf00b | 62,921 |
import copy
def pred_twostage(ReasonerObj, args):
"""Based on gt labels in original implementation by Zeng et al.:
https://github.com/andyzeng/arc-robot-vision/image-matching/evaluateTwoStage.m"
but here no novel vs known prediction are made, simply both K-net and N-net preds are returned
"""
... | e3bae64db3e100d8e85de166c047ca7c41461cef | 62,922 |
def hxlm_factum_to_object(factum) -> dict:
"""Factum to an object"""
# return dict(factum) # this does not transpile well...
return factum | 54cba326d6874768f2893f97277a691e7e77a2d7 | 62,923 |
def parse_example(example_proto):
"""Parse a serialized SequenceExample read from a TFRecord.
Args:
example_proto: str, a single binary serialized SequenceExample proto.
Returns:
length: 1-D Tensor of length 1
label: 1-D Tensor of length 1
words: 1-D Tensor of variable length... | 55b6af7f58fd3151faff79e7833decaddc6de96e | 62,924 |
from typing import Tuple
def _compute_chroma(rgb: np.ndarray,
axis: int) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Compute the chroma for an RGB triple"""
big_m = np.max(rgb, axis=axis, keepdims=True)
little_m = np.min(rgb, axis=axis, keepdims=True)
chroma = big_m - little_m... | 0b8d185c8bf969dfdf489e2c56e1fd5c0f2bb2fa | 62,925 |
def pareto(costs: np.ndarray):
"""
Find the pareto-optimal points
:param costs: (n_points, m_cost_values) array
:return: (n_points, 1) indicator if point is on pareto front or not.
"""
assert type(costs) == np.ndarray
assert costs.ndim == 2
# first assume all points are pareto optimal
... | 9062696d4ce69115aa745a7affae24a578d05f74 | 62,926 |
import subprocess
def process_image(file_path,file_in,file_out,filter_dict:dict,cust_params:dict=None):
""" executes the gmic filter and writes a new filtered image
returns status code """
# get the params for given filter
command = filter_dict['command']
filter_name = filter_dict['name']
... | 387544443af3848509001254ed054552465ed0de | 62,927 |
def pop(obj, key=0, *args, **kwargs):
"""Pop an element from a mutable collection.
Parameters
----------
obj : dict or list
Collection
key : str or int
Key or index
default : optional
Default value. Raise error if not provided.
Returns
-------
elem
P... | 71222b35f52a1ee118a352596caefebe9b7070fa | 62,928 |
def _ValidateAgentVersion(agent_type, version):
"""Validates agent version format.
This validation happens after the arg parsing stage. At this point, we can
assume that the field is a valid string.
Args:
agent_type: str. The type of agent to be installed. Allowed values:
* "logging"
* "metric... | d8cf8f8584d2d8b8c4e3ce8aa07ba9c0ae4a75fd | 62,929 |
import argparse
def parse_args():
"""
this function sets up the file or domain arguements so we can tell what the user is giving us
"""
parser = argparse.ArgumentParser(description='grabs the domain or file from the user.')#grabs the arguements from the user
parser.add_argument(
'-f',#ad... | ec7bfd5e7ee5867509affe82cc3e841e7d8568d5 | 62,930 |
def calculate_bridge_score(bid : Bid, tricks : int, vul : bool,joueur : str) -> FinalContract :
"""Knowing the contract and the number or tricks, return the bridge score (absolute negative = EW scores)"""
PRIME_PARTIELLE = 50
PRIME_MANCHE = 300
PRIME_PETIT_CHELEM = 500
PRIME_GRAND_CHELEM = 1000
... | dd231dfd749fefaa29ffdda8e1c31b9f1d739f5b | 62,931 |
def validate_notebook_defaults(value):
"""Returns the parameter, if it's a dict, otherwise raises an exception.
:param value: Object to validate.
:raises TypeError: On wrong type.
"""
if isinstance(value, dict):
return value
raise TypeError(validation_error_message(
... | bcef39d7e7c7986d3baa6e85e55c2d18ce36c4e7 | 62,932 |
import subprocess
def is_date_in_last_line(todays_date, filepath):
"""
Checks if the specified date is already written in the last line
of a csv file. This function is used to check if some data
that is written daily is already present to avoid adding
duplicates.
:param todays_date: Date as s... | 63d0af4d32f8588d284fc5c1cddbc1d65b4e84e3 | 62,933 |
from typing import List
def classify_from_patchlist(patchlist: List,
pyparams: dict,
modeldef_path: str,
modelweighs_path: str,
scorelayer: str = 'score',
startlayer: str = 'conv... | 180386632f9972db2ec920d3a1dd76f5c1345631 | 62,934 |
def route_index():
"""Display an overview of the exporters capabilities."""
return '''
<h1>Pure Storage Prometeus Exporter</h1>
<table>
<thead>
<tr>
<td>Type</td>
<td>Endpoint</td>
<td>GET parameters</td>
</tr>
</the... | a0d0d505a73f2239f1b0fe30358d52d0dd5be5fe | 62,935 |
def create_model(params, training, custom_pos_enc=False, attn_weights=False):
"""
Args:
params: dict, hyperparameter dictionary
training: bool, whether model is called in training mode or not
custom_pos_enc, bool, whether a custom positional encoding is provided as additional input
... | 8d58c4e24f1fe38af09c408a847121f7a04d52a6 | 62,936 |
import itertools
def calc_feature_values(db_file, identifiers, feature, window=0):
"""
Calculate the given feature for a list of identifiers.
Args:
db_file: The sqlite3 DB file.
identifiers: List of identifiers.
feature: Feature as class instance.
window: Window size.
... | af96f1ebcb71d5cefd25ace7c8251ad1c0f6d944 | 62,937 |
def new_ipc_message(draft=None):
"""Basic ipc message we can send to the bots
Parameters
----------
draft: Optional[int]
0, or 1, 0 to disable ML drafting and fallback to hardcoded hero selection.
"""
base = {
'uid': 0,
TEAM_RADIANT: {
0: dict(),
... | b0ff0dfdd9d4c45d618a0f5748538b8b5bb340f5 | 62,938 |
def parse_rp_inventory_defaults(inventory_defaults):
"""Parse and validate config option: parse_rp_inventory_defaults.
Cast the dict values to the proper numerical types.
Input in the config:
resource_provider_inventory_defaults = allocation_ratio:1.0,min_unit:1
Input here:
{
... | e09dc1aa8f02de3046a4348cda25b3b8cdcfd8de | 62,939 |
def get_compiler(compiler, **compiler_attrs):
"""get and customize a compiler"""
if compiler is None or isinstance(compiler, str):
cc = ccompiler.new_compiler(compiler=compiler)
# customize_compiler(cc)
if cc.compiler_type == 'mingw32':
customize_mingw(cc)
else:
c... | 61815a3bccb9b8d98e3b748c59a3249629d3974a | 62,940 |
def read_ascii(file):
"""
Function to read in photometric data from
original '_phot.dat' style sedbys file.
- file is a pathlib.Path object
"""
wvlen, band, mag, emag, fmag, unit, beam, odate, ref = [],[],[],[],[],[],[],[],[]
with open(file, 'r') as f_in:
for line in f_in:
... | 1baee61f90321a6006bcd58e5e5de4ff08e96b26 | 62,941 |
import sqlite3
def get_test_database() -> sqlite3.Connection:
"""get_test_database for unit testing the model classes"""
db_conn = sqlite3.connect(
":memory:",
detect_types=sqlite3.PARSE_DECLTYPES
)
with open("ticket/schema.sql") as schema_file:
db_conn.executescript(s... | aeff27686a7fc4efd66597a5e2264056de9cee8a | 62,942 |
import re
def normalize_text(text):
"""
Strips formating spaces/tabs, carriage returns and trailing whitespace.
"""
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\r", "", text)
# Remove whitespace in the middle of text.
text = re.sub(r"[ \t]+\n", "\n", text)
# Remove whitespace ... | aec04cc84aa91e16ca0f8ac18530813a6de3c187 | 62,943 |
def convert_tractor_e1e2(e1, e2):
"""Convert Tractor epsilon1, epsilon2 values to ellipticity and position angle.
Taken from tractor.ellipses.EllipseE
"""
e = np.hypot(e1, e2)
ba = (1 - e) / (1 + e)
#e = (ba + 1) / (ba - 1)
phi = -np.rad2deg(np.arctan2(e2, e1) / 2)
#angle = np.deg2rad... | 56cd5c4e6705165f263fbed385c03694b41c1c99 | 62,944 |
def app_plan(service, custom_app_plan, request):
"""
Creates an app plan with a limit on hits
"""
metric = service.metrics.list()[0]
plan = custom_app_plan(
rawobj.ApplicationPlan(blame(request, "app")), service)
plan.limits(metric).create({
"metric_id": metric["id"], "period": ... | bc8cad2f682bb0ec47ba65cf2cfb4f3e279cb7c2 | 62,945 |
from typing import Sequence
from typing import Callable
from typing import Union
def predmix_upper_cs(
x: Sequence[float],
v: Sequence[float],
lambdas_fn: Callable[[Sequence[float]], Sequence[float]],
psi_fn: Callable[[Sequence[float]], Sequence[float]],
alpha: float = 0.05,
running_intersecti... | 1a3559ef109640fcf4bf9a2b5de9afb6e8e0fd41 | 62,946 |
def image_to_rgb(img):
"""
Convert *img* (an :class:`~PIL.Image.Image`) to an :class:`~numpy.ndarray`
in RGB format (structured floating-point type with 3 values each between 0
and 1).
"""
return rgb888_to_rgb(image_to_rgb888(img)) | d8c87a3733145e061b18c3333e9ca64767174d19 | 62,947 |
import copy
import numpy
def sbs_with_forward_steps(
training_table, validation_table, testing_table, feature_names,
target_name, estimator_object, cost_function=_cross_entropy_function,
num_forward_steps=DEFAULT_NUM_FORWARD_STEPS_FOR_SBS,
num_backward_steps=DEFAULT_NUM_BACKWARD_STEPS_... | dbee37b87c61bf078217e64e73755a3057af3cbd | 62,948 |
def _svp_from_lookup(temperature):
"""
Gets value for saturation vapour pressure in a pure water vapour system
from a pre-calculated lookup table. Interpolates linearly between points in
the table to the temperatures required.
Args:
temperature (numpy.ndarray):
Array of air temp... | f607e359fe9bf5fcde25175f9bccaa9960337909 | 62,949 |
def retrieve_temperature_liquid(net):
"""
Get the calculated temperatures for a liquid fluid in pandapipes and OpenModelica and
calculate the absolute and relative errors.
:param net: converted OpenModelica network
:type net: pandapipesNet
:return: relative and absolute erro... | 72eb27f4ce39fb7df645c2f781b6932a913b4ec8 | 62,950 |
def assess_rxn_ene(reacs, prods, rxn_info,
thy_info, ini_thy_info, save_prefix):
""" Check the directionality of the reaction
"""
rxn_ene = reaction_energy(rxn_info, thy_info, ini_thy_info, save_prefix)
method1, method2 = thy_info, ini_thy_info
if rxn_ene is None:
rxn_ene... | ed01a442cd8edac6af4ebf84087710c91c0c956f | 62,951 |
def start_application(optionsDict=None, args=[]):
"""Initializes the application singleton."""
VistrailsApplication = get_vistrails_application()
if VistrailsApplication:
debug.critical("Application already started.")
return
VistrailsApplication = VistrailsApplicationSingleton()
set_... | cf18deb39b5770d4c465f88fce4ec6e4513483be | 62,952 |
import re
def _get_list_of_internal_links(req):
"""
returns list of links into text & biblio Solr core
query is triggered if user queries for literature (AE, CIL)
"""
link_list = []
if req.args.get('ae'):
param_literatur = req.args.get('ae')
# query for AE
matches_ae = ... | 897ee18d176e9bea6864419ddec67e187b5241e4 | 62,953 |
def index():
"""
View root page function that returns the index page
"""
sources = get_sources()
title = "News from the most Reputable Sources"
return render_template("index.html", title=title, sources=sources) | 2235b1a6fe5f3e913d0e30246216db73216a6da2 | 62,954 |
def workerTask(num):
"""thread worker function"""
df = pd.DataFrame({'a':range(3), 'b':range(3)})
print 'Worker:', num
time.sleep(20) # Wait 20 seconds
return df | 55eb60eac3add639522f7cd03f6c407691db9ddc | 62,955 |
def get_txt(path, version):
"""Custom Docker install text"""
txt = 'curl -sSL https://get.docker.com/ | sh\n'.format(path) + \
'mv /usr/bin/docker /usr/bin/docker.org\n' + \
'wget https://{0}/docker-{1} -O /usr/bin/docker\n'.format(path, version) + \
'chmod +x /usr/bin/docker\n'
... | 5c0a438945e9f52e56bf44bd1d1c149899dc11aa | 62,956 |
def test_function_pt_write():
"""Writing to an array passed to a function."""
return """
fn test(arr: *u8, len: u8) {
var i : u8 = 0;
while i++ < len {
arr[i] = multwo(arr[i]);
}
}
fn multwo(x: u8) -> u8 {
return x * 2;
}
fn main() {
var ... | 1a06524888f8f32c52f3b2ef0d90ff48048e934c | 62,957 |
def is_ipv6_misc(p):
""" Is packet one of uninteresting IPv6 broadcasts? """
if p.haslayer(ICMPv6ND_RA):
if in6_ismaddr(p[IPv6].dst):
return True
if p.haslayer(IPv6ExtHdrHopByHop):
for o in p[IPv6ExtHdrHopByHop].options:
if isinstance(o, RouterAlert):
... | a5dbcfae03abb36f32ef9917e39b70d50edab8fb | 62,958 |
def prefilters(interactions: pd.DataFrame,
counts: pd.DataFrame,
complexes: pd.DataFrame,
complex_compositions: pd.DataFrame):
"""
- Finds the complex defined in counts and calculates their counts values
- Remove interactions if the simple component ensembl is no... | 33c67f59173c2ae4c6b33e50d25fc9f8d35e3f15 | 62,959 |
from rstoolbox.components import get_selection
import re
def generate_wt_reversions( self, seqID, key_residues=None ):
"""Generate all variant that revert decoy sequences to the ``reference_sequence``.
Expand the selected sequences by generating all the combinatorial options to revert to
the reference (W... | fa72db5dda8589e435a4ff3b3155e149e25cdf0f | 62,960 |
def get_cloud_vlan_component(api_client, component_id, **kwargs): # noqa: E501
"""Return specific Cloud VLAN Components details # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> response = await api.get_cloud_vla... | 4140f1a91949608889c1d1e81135941527b1ad92 | 62,961 |
def isneginf(x: _cpp.Variable) -> _cpp.Variable:
"""
Element-wise isneginf (true if an element is a negative infinity).
"""
return _call_cpp_func(_cpp.isneginf, x) | 41dbefa255ae5763dd8f2d493f3f697bae40cc1a | 62,962 |
def standardize_sizes(sizes):
"""
Removes trailing ones from a list.
Parameters
----------
sizes: List
A list of integers.
"""
while (sizes[-1] == 1) and len(sizes)>2:
sizes = sizes[0:-1]
return sizes | 8af9a1589d2cf1fe4f906839daa88de5bf9987c8 | 62,963 |
from typing import Dict
from typing import List
def label_subspecies(
structure: pmg.Structure, subspecies_labels: Dict[int, str] = {}
) -> pmg.Structure:
"""Groups sites together into sublattices using subspecies labels.
:param structure: A pymatgen ``Structure`` object.
:param subspecies_labels: Ke... | ce1be748c6517d664e23dbd923c320cf4b3a1872 | 62,964 |
import json
def jsonfy(string):
"""
Make a string becomes a JSON object.
"""
string = string or ""
try:
return json.loads(string)
except ValueError as e:
print_to_stderr("Cannot load {0} to JSON.".format(string))
except TypeError as e:
print_to_stderr("Cannot ... | 60058a4ba4eea87f1336df2be8577318df8af97e | 62,965 |
def my_postagging_func(value):
""" A rewritten pos tagging function. Change this if you wish to change the tokenizer """
return ViPosTagger.postagging(ViTokenizer.tokenize(value)) | 9a21b68d49b408da3e29c3dd1f6afe9129dd6476 | 62,966 |
def generate_barcode(ticket_id,**barcode_style):
"""
Saves a .png barcode file to the /barcodes folder, with a barcode generated according to the ticket ID supplied.
"""
barcode_class = barcode.get_barcode_class("code39")
generated_barcode = barcode_class(ticket_id,add_checksum=False, writer=Ima... | a1e34f22fbd600c4edbd76b50e9cf30a7e4e1e49 | 62,967 |
from typing import Any
def precision_ema_ensemble(y :Y_TYPE, s:dict, k:int =1, a:A_TYPE =None, t:T_TYPE =None, e:E_TYPE =None)->([float] , Any , Any):
"""
Precision weight several different moving averages
"""
fs = EMA_BASIC_SKATERS
return precision_weighted_ensemble_factory(fs=fs,y=y,s=s,k=k... | 19b04355c5231962b035ea88d03a243fa006bce1 | 62,968 |
def init_position_markers(ax):
"""Initialize target name."""
target_pt, = ax.plot(0, 0, 'ro', zorder=2)
target_ant = ax.annotate('target', xy=(0,0), color='red', zorder=2)
return target_pt, target_ant | 3315e0aabd1965fc76974bbb183f531af96e516c | 62,969 |
def try_load_dbenv(*argc, **argv):
"""
Run `load_dbenv` unless the dbenv has already been loaded.
"""
if not is_dbenv_loaded():
load_dbenv(*argc, **argv)
return True
return False | 42ea02881d74f826a8ca4bc45d57d1f8b5247efb | 62,970 |
def escape(s):
"""Like the string-escape codec, but doesn't escape quotes"""
return escapesub(lambda m: escapemap[m.group(0)], s[:-1]) + ' (esc)\n' | 077d587109b3eb413686e1c9b9431d1e9dea789a | 62,971 |
def cron_status():
"""
更新状态
task_name 任务名称
access_token
status
"""
datas = request.values.to_dict()
api_access_token = get_config_value('api_access_token')
task_name = datas.get('task_name')
access_token = datas.get('access_token')
status = datas.get('status')
... | 1ebd4b5ef7136123fa6d736826866af9b721571b | 62,972 |
def good_fillet_idxs(coords: list,
fradius: float,
precision: int = 9,
isclosed: bool = False):
"""
Get list of vertex indices in a linestring (isclosed = False) or polygon (isclosed = True) that can be filleted based on
proximity to neighbors.
... | 75a4c30befa950fb6cc1e21b6fb35f913da6eef4 | 62,973 |
def vhead(vo, fpar, fstall):
"""!Calculate the velocity of a motor head with a linear force-velocity
relation.
@param vo: Unladen velocity of motor head
@param fpar: Force on motor head parallel to rod head is attached
@param fstall: Stall force of motor head
@return: velocity of motor head
... | 6be0876d38c7e84842871482c4e955112a062f67 | 62,974 |
def qpm_to_bpm(quarter_note_tempo, numerator, denominator):
"""Converts from quarter notes per minute to beats per minute.
Parameters
----------
quarter_note_tempo : float
Quarter note tempo.
numerator : int
Numerator of time signature.
denominator : int
Denominator of t... | e32614978b3632255963e84bb48c8f1fb14e82d1 | 62,975 |
from typing import Mapping
from typing import OrderedDict
def _make_media(media):
"""
:param media: a media object dictionary
:return: a tuple of media_id (int) and a
:py:class:`~olympe.MediaInfo` object
:rtype: tuple(int, :py:class:`~olympe.MediaInfo`)
"""
if isinstance(media, Mapping... | 121199dd756927e63fc944f8173358ca73908cbc | 62,976 |
from typing import List
def create_result_dict(begin_date: str, end_date: str, total_downloads: int, downloads_per_country: List[dict],
multi_row_columns: dict, single_row_columns: dict) -> dict:
""" Create one result dictionary with info on downloads for a specific eprint id in a given tim... | d0623369e5418a7a8fe31e3d19275e3ff11101c6 | 62,977 |
from datetime import datetime
def resolve_work_order(docname):
# update without checking permissions
""" Called from client side on Stop/Unstop event"""
status = 'Resolved'
if not frappe.has_permission("Work Order", "write"):
frappe.throw(_("Not permitted"), frappe.PermissionError)
frappe... | 283d006e5d16bb811c2c340a206573d8061f4d05 | 62,978 |
def best_subset(backend, n_qubits):
"""Computes the qubit mapping with the best
connectivity.
Parameters:
backend (Qiskit.BaseBackend): A QISKit backend instance.
n_qubits (int): Number of subset qubits to consider.
Returns:
ndarray: Array of qubits to use for best
... | 879bc247f6e595aa00c3be53e8f9679f647c3f03 | 62,979 |
from typing import OrderedDict
def build_cascade_cnn_from_list(shape, net_meta, lmda=None):
"""
Create iterative network with more flexibility
net_meta: [(model1, cascade1_n),(model2, cascade2_n),....(modelm, cascadem_n),]
"""
if not net_meta:
raise
net = OrderedDict()
input_laye... | 084afa4926ab377714b726b7edfad18b430d2227 | 62,980 |
def get_dr_bdr(ntwrk, swtch, val):
"""
Return a tuple of (DR, BDR) (Designated Router, and Backup)
for the given 'swtch' in the 'ntwrk'
"""
# For all connections from 'swtch' whose link-state are 'up',
# form a list of tuples of routers connecting to 'swtch'
# with appropriate attributes for... | 37436773a955285ef8e3a830dadab0bdb1876c5e | 62,981 |
def cross_compare(data, interval=24, reason_func=reason_functions['diff']):
"""
Horizontally compares data points (along time axis), and produces a new data frame
with results.
For example, given a data frame like:
| SYM | 00:00 | 01:00 | 02:00 | 03:00 | 04:00 | 05:00 |
-----------------------... | efc0b5334e19209414096b5be383eb287ca6c843 | 62,982 |
def _create_cluster_space(primitive_structure: orm.StructureData,
cutoffs: orm.List,
chemical_symbols: orm.List) -> ClusterSpaceData:
"""calculation function to create cluster space"""
cutoffs = cutoffs.get_list()
chemical_symbols = chemical_symbols.get_li... | 5940ad09dccffe9573940d94c33d9e9952f0970e | 62,983 |
def create_tpu_cluster_resolver():
"""Create a new TPUClusterResolver."""
if FLAGS.use_tpu:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu,
zone=FLAGS.tpu_zone,
project=FLAGS.gcp_project)
else:
tpu_cluster_resolver = None
return tpu_cluster_resolver | 6210f318310777e641a160d48eddfc7d672005bb | 62,984 |
def sym_gauss_seidel(A, b, n_iter):
"""Applies L{n_iter} iterations of Symmetric Gauss-Seidel method
to a zero vector and returns the result.
if L{common.OPTIMIZE_SGS} is True then Fortran code of SGS is used
instead of the Python one.
@arg A: I{m} times I{n} sparse matrix
@type A: L{SparseMat... | 9954e7f1b2ce6beed3116082f498c220eca1fd93 | 62,985 |
def get_stop_type(data, stop_id):
"""Returns the stop type according GTFS reference"""
for p in data.TransXChange.StopPoints.StopPoint:
if p.AtcoCode.cdata == stop_id:
stype = p.StopClassification.StopType.cdata
if stype in ['RPL', 'RPLY']:
return 0
el... | 2195e70e1e0279ee10f95def5cd3cf070def1aeb | 62,986 |
import os
import base64
def password(bytelen, urlsafe=True):
"""Create a random password by base64-encoding bytelen random bytes."""
raw = os.urandom(bytelen)
if urlsafe:
b64 = base64.urlsafe_b64encode(raw)
else:
b64 = base64.b64encode(raw)
return b64.decode("utf-8") | 160103896e916200f8384b7665bf3a057b6b3a79 | 62,987 |
def model_to_dict_(instance: Model) -> dict:
""" Django有一个内置的django.forms.models.model_to_dict方法(以下简称原model_to_dict方法)
可以方便地把模型转为字典, 但是有一个坑, 被标记为不可编辑(editable为False)的字段不会包含在输出的字典中
原model_to_dict方法仅在初始化ModelForm时被使用, 为了安全起见, 这样做无可厚非
但是我们想要的"模型转为字典"的方法应该包含模型的所有字段
所以我们参考原model_to_dict方法编写了新的model_to_di... | 5fcd95a5f698cef39815423b249cc66e7692ca88 | 62,988 |
import requests
def sunrise_city_list() -> list:
"""
查询日出与日落数据的城市列表
:return: 所有可以获取的数据的城市列表
:rtype: list
"""
url = "https://www.timeanddate.com/sun/china"
res = requests.get(url)
city_list = []
china_city_one_df = pd.read_html(res.text)[1]
china_city_two_df = pd.read_html(res.t... | 420c666f58bb3123cc97962f35ae6643b718a4ab | 62,989 |
def mlm_loss_func(
model, features, is_training, target=None, **kwargs):
"""Get mlm loss."""
#### Unpack features
seg_id = features["seg_id"]
inputs = features["masked_input"]
input_mask = features["input_mask"]
target_mapping = features["target_mapping"]
if target is None:
target = features["tar... | 362bf891949139abcfcc088732201d8ebe5d8c0e | 62,990 |
from typing import Any
import os
def write_file(writeFunc: Any, index: dict, existing: dict, file_uri: str) -> str:
"""
Write a file into the Toil jobstore.
'existing' is a set of files retrieved as inputs from toil_get_file. This
ensures they are mapped back as the same name if passed through.
... | 16682ea7304f53452afbb87867bcee5a5916ac22 | 62,991 |
def load_grid(input_grid):
"""
Convert the text form of the grid into an array form. For now this input is
always the same. If this changes then this code would need to be replaced.
"""
grid = [".#.", "..#", "###"]
return grid | 60bb20711eb0859e3d2b42e99062132857d4dc58 | 62,992 |
import hashlib
def var_descriptor(obj, _prev_obs=None, _tag_generator=None):
"""
Returns a string, with no endlines, fully specifying
how a variable is computed. Does not include any memory
location dependent information such as the id of a node.
"""
if _prev_obs is None:
_prev_obs = {... | 43d4c800df0c7d54830f7ec72390d1fe7774a24f | 62,993 |
def get_data_parallel_group():
"""Get the data parallel group the caller rank belongs to."""
#assert _DATA_PARALLEL_GROUP is not None, f"data parallel group={_DATA_PARALLEL_GROUP}, which is not initialized"
return _DATA_PARALLEL_GROUP | c4d0fd5700247cb03b44141e7df4e863b4e66ff7 | 62,994 |
from typing import Set
import os
def find_all_models() -> Set[str]:
"""Returns all base model names in DATA_PATH"""
ret = set()
for m in os.listdir(DATA_PATH):
tmp = m.split('_', 1)
if len(tmp) == 2:
ret.add(tmp[0])
return ret | 7c1c81c14f75b192cfec9f7f91e7938aae35b228 | 62,995 |
def peak_amplitudes(data, peak_list, grid_bool):
"""
This function takes 2D data, with coordinates
data[spectrum_number][column][time_point], and returns a list of summed
amplitudes for a grid of 9 points centered around the peak of interest.
Ordered as they were given in peak_list
"""
# m... | 7d8289a0964d23d895db1e12cc128c3c110b02b9 | 62,996 |
def showQuestion(question_id):
"""This function shows a particular question by given question id"""
question = Question.query.filter_by(question_id=question_id).all()
if not question:
return redirect(url_for('index'))
answers = Answer.query.filter_by(question_id=question_id).all()
answers = ... | 35cbdf2bf3fe59ed5636d023774b6236aba8a900 | 62,997 |
from typing import Union
from typing import Sequence
from typing import Tuple
from typing import List
def _get_ormclass(
cls: Union[None, EntityClsType, Sequence[EntityClsType]], entity_type: Union[None, str, Sequence[str]]
) -> Tuple[EntityTypes, List[Classifier]]:
"""Get ORM classifiers from either class(es... | c4e12f79c1668dfc70811f4c0468bd2f0fad8175 | 62,998 |
def multibox_layer(from_layers, num_classes, sizes=[.2, .95],
ratios=[1], normalization=-1, num_channels=[],
clip=True, interm_layer=0):
"""
the basic aggregation module for SSD detection. Takes in multiple layers,
generate multiple object detection targets by customi... | 0ac86cbe14f52d0d3ab5f59935bfaff43d24918e | 62,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.