content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def emg_filter_highpass(x, order = 4, sRate = 200., lowcut = 10.):
""" Forward-backward high-pass filtering (IIR butterworth filter) """
nyq = 0.5 * sRate
low = lowcut/nyq
b, a = butter(order, low, btype = 'high', analog=False)
return filtfilt(b=b, a=a, x=x, axis=0, method = 'pad', padtype = 'od... | 2d5d89941765d52ad4cbcc76be016b6340525c9c | 3,601,155 |
import random
def process_image(path, steering_angle, augment, shape=(100,100)):
"""Process and augment an image."""
image = load_img(path, target_size=shape)
if augment and random.random() < 0.5:
image = random_darken(image) # before numpy'd
image = img_to_array(image)
if ... | 3c0e8896f92d9c4d0966412f3785b6762d1c66aa | 3,601,156 |
import html
def create_deck(df: pd.DataFrame, city: str) -> html.Div:
"""
Create a deck of tweets
:param df: dataframe to get tweets of
:param city: string of city to filter on
:return: list of child elements
"""
if city is not None:
df = df[df['city'] == city]
list_items = []... | c913edb138f638bf3bdb9bd9acc48ebd93c1784b | 3,601,157 |
import string
def readSurface( name ):
"""Read the files 'name'.vertices and 'name'.triangles and returns
lists of 6-floats for vertices x,y,z,nx,ny,nz and a list of 3-ints
for triangles"""
f = open( name+'.vertices' )
vdata = f.readlines()
f.close()
vdata = map( string.split, vdata ... | 360cc8c6a61acdab44ac15ffb21979600441c1ca | 3,601,158 |
import json
def get_labels_and_manifest(schema_content, args):
"""Get schema content and labels from cli argument or automated creation."""
if args.schema_path:
labels = json.loads(schema_content)['schemas']['named_entity']['tags']
else:
labels = DEFAULT_LABELS if not args.entity_types els... | d0928ad07cedc0658d623cd66c60436bfc17266f | 3,601,159 |
from typing import List
def create_outputfiles(payload: List[DojoSchema.ModelOutputFile]):
"""
Create an `outputfile` for a model. Each `outputfile` represents a single file that is created upon each model
execution. Here we store key metadata about the `outputfile` which enables us to find it within the ... | 25ba09a197e7613a9bcd8289e0b8f76f7cafbf5a | 3,601,160 |
from typing import Any
def check_value_base_type(t: BaseType, value: Any):
"""Validate that value conforms with the BaseType and return the canonicalized value if so
Raises InvalidValueError if the value is invalid
"""
t = canonicalize_base_type(t)
if isinstance(t, type):
if isinstance(va... | 3f1a17e13aecac7719ca3bd1bb8eba2ca7f05047 | 3,601,161 |
import torch
def load_data(path="./cora/", dataset="cora"):
"""读取引文网络数据cora"""
print('Loading {} dataset...'.format(dataset))
idx_features_labels = np.genfromtxt("{}{}.content".format(path, dataset),
dtype=np.dtype(str)) # 使用numpy读取.txt文件
features = sp.csr_matri... | 86cfb27406d8dbed33c10e461606c191fee48aa0 | 3,601,162 |
def t_statistic(mean1, mean2, n1, n2, svar1, svar2):
"""
Compute the t-statistic for the given estimates
"""
# Complete this funtion
a=svar1
b=svar2
c=a/n1
d=b/n2
e= 1/sqrt(c+d)
t_stat = e*(mean1-mean2)
return t_stat | 92435680aee41d5a6973ba6edc240bc808aecda9 | 3,601,163 |
def move_left(place: Coord) -> Coord:
"""Move left from place."""
x_place, y_place = place
return (x_place - 1, y_place) | b07939e7d9bcb77a2020eb862c65a7359731e9b2 | 3,601,164 |
def find_closest_star(root, star, depth=0):
"""
For one star, recursively finds closest match in entire k-d tree-ized catalog.
Returns element of kd tree
Parameters
----------
Root: element of kd tree
Star: element of kd tree
"""
if root is None:
return None
coord = dep... | dd9ee9c361c9e1a4b2d196097616f30836ac65aa | 3,601,165 |
def is_possible_move(direction, you, snake_heads, occupied, height, width, spacing=1):
"""
:param direction: up down left or right
:type direction: str
:param you: all blocks our body is occupying
:type you: list of dict
:param occupied: all blocks all snakes are occupying
:type occupied:... | 01909f9daecd01fd21b13c5a24bc0081ce50b7c9 | 3,601,166 |
def make_dot(x, model):
"""Produces Graphviz representation of PyTorch autograd graph.
Notes:
* Blue nodes are the Variables that require grad.
* Orange nodes are input tensors.
* Green nodes are output tensors.
* Darkpink nodes are backward operations.
Args:
x (tor... | 51c4139645d5f00bd814d356f1c763ace3250712 | 3,601,167 |
def get_intervals(xi,yi,grid):
""" This function computes the length of intersection of the line parametrized by the sample
observations X and Y with the grid (i.e. returns all the lengths of the line-segments generated
by passing a line through the grid)
"""
start = grid.start
end = grid.end
... | 2e0b59fe66abd1588536c45a88974f801d98b71d | 3,601,168 |
import sqlite3
def create_subject(subject, metadata=None):
"""Formally adds the given subject into the binder. It will be added into the database and automate
the creation of the template needed for the subject.
:param subject: The subject to be added.
:type subject: str
:param db: The database ... | 05bc970786a01b804ba2ce2728fa1ad4b7825f2e | 3,601,169 |
import time
def corporation_system_oneday(mongohandle, corporation_id, system):
"""find by corp and system - one day"""
allkills = mongohandle.allkills
system = int(system)
timeframe = 24 * 60 * 60
gmtminus = time.mktime(time.gmtime()) - timeframe
cursor = allkills.find({"corporation_id": corp... | fcedbb5853f5f9278450a5a7518c46ad37075136 | 3,601,170 |
from typing import List
def run_lsm_from_final_norm_state(config: Config) -> List[Step]:
"""
Run the LSM over the entire historical period, and retain the state files
for each iteration. Discard the results.
"""
# Set the yearmon in final state from climate norms run to be the first
# forcing... | f9fca4aacfa4f9c70249bcf4f0322ab39083da42 | 3,601,171 |
def gin_ensure_key(token):
"""
Confirms whether the public key 'gin-proc' is installed
on user's GIN account or not.
"""
for key in gin_get_keys(token):
if key['title'] == PRIV_KEY:
return True | 0e7f91ab38d16e49cf1102555a1e58027835dc2f | 3,601,172 |
def MakeModeratedEffect(data,i = 0, j = 1, effect = 0):
"""Summary line.
Extended description of function.
Parameters
----------
arg1 : int
Description of arg1
arg2 : str
Description of arg2
Returns
-------
bool
Description of return value
Examples
... | add8b8490f9df5d235067ba26993885e7762685b | 3,601,173 |
import copy
def copy_trade(trade):
"""
Make a modifiable copy of a Trade object for use in split_trades.
"""
new_trade = Trade(
trade.trade_type,
copy.copy(trade.price),
copy.copy(trade.fee),
copy.copy(trade.volume),
trade.exchange_trade_id,
None,
)
... | 6b127f49904e3eddb440c0aca44d51c3317c3f09 | 3,601,174 |
def valid_permlink(permlink, allow_empty=False):
"""Returns validated permlink or throws Assert."""
assert isinstance(permlink, str), "permlink must be string: %s" % permlink
if not (allow_empty and permlink == ''):
assert permlink and len(permlink) <= 256, "invalid permlink"
return permlink | ec5094ed8ac938b85c423218527d92b89ba3f1f3 | 3,601,175 |
def watershed_ift(input, markers, structure = None, output = None):
"""Apply watershed from markers using a iterative forest transform
algorithm.
Negative markers are considered background markers which are
processed after the other markers. A structuring element defining
the connectivity of the ob... | 713088daa1023744c0a2c249b59d81fcf4ac9548 | 3,601,176 |
def get_answer(offer, user):
"""Returns an user answer for the given offer"""
if not user.is_authenticated:
return None
return offer.answers.filter(user=user).first() | e89da7d11e6e8a01deb8177d3af9c693267fe09a | 3,601,177 |
from typing import List
def to_vecs_from_matrices_with_sparsity(
c_sys: CompositeSystem, matrices: List[np.ndarray]
) -> np.ndarray:
"""converts matrices to vecs.
this function uses the scipy.sparse module.
Parameters
----------
c_sys : CompositeSystem
CompositeSystem of this povm.
... | 278f1db6fa16f8575d683ce5027832998ecb3d89 | 3,601,178 |
def folder_navigation_top(request, item_container):
""" Eigenschaften des Ordners aendern """
class dms_itemForm ( forms.Form ) :
name = forms.CharField(max_length=60,
widget=forms.TextInput(attrs={'size':60}) )
navigation = forms.CharField(required=False,
... | 2f2b821a7cb6c0b962d4c9ca6a5b492991928b06 | 3,601,179 |
def simple_cdf(x_vals, num_summed, algorithm=0):
"""Analytic expression for the cdf of a sum of
num_summed random variables distributed according
to an algorithm.
Parameters
----------
x_vals : list
List of x values for which we will return a cdf.
num_summed : type
Number of... | c8ce1da482a04ac1bac9f6cf0bde608a05385ff1 | 3,601,180 |
from typing import Tuple
def distance_filter(contour, point: Tuple[int, int], min_dist: float = 0, max_dist: float = 50):
"""
Filters out contours that their center is not close enough
to the given (x, y) point in the image
:param contour: the contour to be filtered (numpy.ndarray)
:param point: ... | 8788ec042b9a549202ecc7df648e9dd75587c25f | 3,601,181 |
def main():
"""Main routine, when called as a script."""
global _CONN
# Parse command line args
optparser = optparse.OptionParser(
usage='%prog HOSTNAME [-u USER -p PASS] [-n NAMESPACE] [--no-ssl]')
# Username and password
optparser.add_option('-u', '--user', dest='user',
... | 32c515cf543ebe1594705be71527a3bda806e1e7 | 3,601,183 |
def do_tasks(request, uid):
"""Execute tasks of a wizard"""
task = request.session.get('wiz_' + uid + '_class')
if not task:
raise Http404
return
if task not in wizs:
raise Http404
return
if not request.session['wiz_' + uid + '_ctask']:
raise Http404
... | cc06d5750074b6fbe0b145a0c4b6f9a22b668050 | 3,601,184 |
async def oppio_client_supervisor(opp, aiohttp_client, oppio_stubs):
"""Return an authenticated HTTP client."""
access_token = opp.auth.async_create_access_token(oppio_stubs)
return await aiohttp_client(
opp.http.app,
headers={"Authorization": f"Bearer {access_token}"},
) | ccc821b17490e8c9163a813d8b9aab03f1467713 | 3,601,185 |
def get_charts(current_date):
"""
Grabs the charts entries for the given date
:return list of chart entries
"""
print u"{0:s}".format(current_date.strftime("%d.%m.%Y"))
date_in_milliseconds = time.mktime(current_date.timetuple()) * 1000
url = EP % date_in_milliseconds
html = common.re... | f766843347044f45fa427a37137cc8eacedf084a | 3,601,186 |
from ocflib.account.search import user_exists
def email_for_user(username, check_exists=True):
"""Return email for a user.
Currently, just appends @ocf.berkeley.edu, but could eventually do
something more complicated.
"""
if check_exists:
if not user_exists(username):
raise Va... | 8ad77fd07c0f2b8f9f85e6cbe5dbb243dd7053ab | 3,601,188 |
from typing import Tuple
from typing import Iterable
def resize(array: np.ndarray,
shape: Tuple[int, ...],
reflect_axes: Iterable[int] = ()) -> np.ndarray:
"""Resize an array with the local mean / bilinear scaling.
Works for both upsampling and downsampling in a fashion equivalent to
... | 5e6953faf3560783dfd26ac395ef584c6a2e24f1 | 3,601,189 |
from typing import Union
def cmd_concept_list(mixcli: MixCli, **kwargs: Union[str, bool]):
"""
Default function when MixCli concept list command is called.
:param mixcli: a MixCli instance
:param kwargs: keyword arguments from command-line arguments
:return: None
"""
proj_id = kwargs['pro... | dea85ea37172948d9f09927aa27fb7c51cb42bdf | 3,601,190 |
def leiaDinheiro(msg):
"""
-> Função que verifica se um preço digitado é valido
:param msg: recebe a menssagem pedindo um preço
:return: retorna o preço válido
"""
while True:
preco = input(msg).strip().replace(',', '.')
if preco.isalpha() or preco == "":
print(f'\033... | 9712bf74c29f0ac62d6f2326794d0537cc885b5c | 3,601,192 |
from aiida.cmdline.utils.templates import env
import re
import click
def edit_pre_post(pre=None, post=None, summary=None):
"""
use click to call up an editor to write or edit pre / post
execution scripts for both codes and computers
"""
template = env.get_template('prepost.bash.tpl')
summary =... | 5e4ea8e2fa4ea4cda74ae71825e7bfab8c2482ed | 3,601,193 |
def search_port(dvs, portgroupkey):
"""
Find port by port group key
"""
search_portkey = []
criteria = vim.dvs.PortCriteria()
criteria.connected = False
criteria.inside = True
criteria.portgroupKey = portgroupkey
ports = dvs.FetchDVPorts(criteria)
for port in ports:
searc... | de5244d60f77e74a56b40314ba57d0148e3e02ad | 3,601,194 |
def delete_user(user_id):
"""Delete the named user from the system
Mark the given user as deleted. The user isn't actually deleted,
but marked as such to maintain the audit trail. After deletion,
all other operations on said user are prohibited.
---
tags:
- User
operationId: delete... | 45fbc70a60c70f19ce5e2a4de6998b7be740c275 | 3,601,195 |
from typing import OrderedDict
def get_attributes(ncobj, verbose=None, normalise=True):
"""
Copy the global and variable attributes from a netCDF object to an
OrderedDict. This is a little like 'ncdump -h' (without the formatting).
Global attributes are keyed in the OrderedDict by the attribute name.... | 311e76f5f8b675a11fe3b897b2375feb3952636d | 3,601,196 |
def process_dsn(dsn):
"""
Take a standard DSN-dict and return the args and
kwargs that will be passed to the psycopg2 Connection
constructor.
"""
args = ['host=%s dbname=%s user=%s password=%s' % (dsn['host'], dsn['db'], dsn['user'], dsn['passwd'])]
del dsn['host']
del dsn['db']
del dsn['user']
del dsn['passw... | c73b641cd4e28c5824db6d37d3aec2786c7461ff | 3,601,197 |
import collections
def parse_useful_string():
"""Return a changed defaultdict
"""
useful_lines = product_checkout_useful_string().split(sep='\n')
changed_files = collections.defaultdict(list)
for line in useful_lines:
if line == '':
continue
pairs = line.split('\t')
... | a556466141ee0a285fc87fa3e9c100903c2372cd | 3,601,199 |
import pickle
def get_ctf_by_name(database, name):
"""
Fetch a CTF object in the database with a given name.
Return the matching CTF object if found, or None otherwise.
"""
ctfs = pickle.load(open(database, "rb"))
for ctf in ctfs:
if ctf.name == name:
return ctf
return... | 32bf2489da5a01810813715060bdcdd15126b8f7 | 3,601,200 |
def system_storage(required_resource_keys, name=None, is_persistent=True, config_schema=None):
"""Creates a system storage definition.
The decorated function will be passed as the ``system_storage_creation_fn`` to a
:py:class:`SystemStorageDefinition`.
Args:
name (str): The name of the system ... | 7eccc29c3616ef534a2b489cd551bc473488ffed | 3,601,201 |
def run(gens, env, version):
"""
Run the pole balancing task using the Gym environment
Returns the winning genome and the statistics of the run.
"""
winner, stats = run_es(gens, env, 500, CONFIG, params(version), SUBSTRATE)
print(f"es_hyperneat_polebalancing_{VERSION_TEXT} done")
return winn... | e592f0c28e69b16e7498a7aff450fb19bd9f8126 | 3,601,202 |
def flow_to_color(flow_uv, clip_flow=None, convert_to_bgr=False):
"""
Expects a two dimensional flow image of shape [H,W,2]
According to the C++ source code of Daniel Scharstein
According to the Matlab source code of Deqing Sun
:param convert_to_bgr: convert output to BGR in the process
:param f... | da55f830984d05837d1318752525b643550b9d12 | 3,601,203 |
def find_greater(l,cab,year):
"""
Compraing list objects in their years according to their cab type
Parameters:
l(list): list of car
cab(str): type of car
year(int): year
returns:
str: return a
"""
counter_year = 0
temp_km = 0
for i in l:
... | 33dac27085495a7d2f5145216acdc124c111c7bf | 3,601,204 |
def find_dist_max(ar_coorx,ar_coory):
"""
Compute the maximum distance between several points defined by their coordinates ar_coorx and ar_coory
"""
nb_cell=len(ar_coorx)
max_dist=0.
for i in range(nb_cell):
for j in range(nb_cell):
max_dist=max(max_dist,distance(ar_coorx[i],... | 40cad577460cf853f589da16a0fb1efeee5e41f4 | 3,601,205 |
from typing import Optional
def start(
categories: Optional[str] = None,
options: Optional[str] = None,
bufferUsageReportingInterval: Optional[float] = None,
transferMode: Optional[str] = None,
streamFormat: Optional[StreamFormat] = None,
streamCompression: Optional[StreamCompression] = None,
... | 369e64cb444b119a0fce8a7b2638817f89e237b8 | 3,601,206 |
def parse_tree(lines):
"""Parses input lines into a decision tree."""
current_index = [0] # need mutable container because of closure limitations
def parse(current_depth):
"""Helper recursive function."""
node_feature = None
children = []
while current_index[0] < len(lines):
... | 2e2b9a408f4682b5a5e61b5830ccad0409646573 | 3,601,207 |
import random
def _random_level():
"""Returns a random level for the new skiplist node
The return value of this function is between 1 and ZSKIPLIST_MAXLEVEL
(both inclusive), with a powerlaw-alike distribution where higher
levels are less likely to be returned.
"""
level = 1
while random.... | 3f5f13defae1140836fedf29c257ed6fc9b68384 | 3,601,208 |
def mobilenet_v2_factory(image_size, pretrained=True):
"""
Args:
image_size:
pretrained:
Returns:
"""
model = MobileNetV2(image_size)
if pretrained:
model.load_state_dict(
load_state_dict_from_url(
"https://download.pytorch.org/models/mobilenet_... | b6bd8f3dc20a68a57bc0b4d268d7b9f4429c04a7 | 3,601,209 |
def make_3d_plots(canonical_field, live_field):
"""
Makes a 3D plot of the live sdf, with the SDF value plotted along the (vertical) Z axis
:param canonical_field: canonical (source) SDF field
:param live_field: warped/transformed live (target) SDF field
:return: image (numpy array) of the 3D plot
... | 10ee05a2a4be346dd869699713ccb831dae463db | 3,601,210 |
def run_analysis(GM_dt, GM_npts, TS_List, EDP_specs, model_params):
"""
Run dynamic analysis for a time history and return a dictionary of envelope EDPs.
Assumes that length is measured in inches and acceleration in in/s2
Parameters
----------
GM_dt: float
Time step of time series
... | 7deae3f1ddedba4d32eb31298e4b161e38226ce0 | 3,601,211 |
def num_rep_2d(xvec, yvec, rCut):
"""
Find the number of replications necessary such that the
2D-circle of radius r_cut at the center of the primitive-cell
lies completely inside the super-cell.
Parameters
-----------------
xvec : numpy array
The basis vector in x direction in x-z p... | f26239c39b0209bb23b532128c7c7aa817411b17 | 3,601,212 |
import json
def get_results(response):
"""This helper method consumes the response of an ElasticSearch Query and
adds the hits to an array then returns a dictionary representing the
results"""
hit_arr = []
agg_dict = response.aggregations.to_dict()
for hit in response:
hit_dic... | 8bd7ae3d88b57b2af75aedd9b64778832da5f1c8 | 3,601,214 |
def logout():
"""Logout process."""
logout_user()
flash('Вы успешно разлогинились')
return redirect(url_for('landing.index')) | f06f8650ce2b06d8c7ae9329edb7446b78d576cd | 3,601,215 |
def get_minifig_sets(minifig_id, page=None, page_size=None, ordering=None, api_key=None):
"""
Gets details about available sets containing specific minifig.
Args:
minifig_id: str or int
Rebrickable minifig ID.
page: int or None
A page number within the p... | de0a853ff7886585194b1f7cad371806b8f7aa15 | 3,601,216 |
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: ConfigEntry
) -> dict:
"""Return diagnostics for a config entry."""
trackables = hass.data[DOMAIN][config_entry.entry_id][TRACKABLES]
diagnostics_data = async_redact_data(
{
"config_entry": config_entry... | f7a5a84a6cb93c0aacc377cc66bc122f8f9efc3b | 3,601,217 |
def ucm_retrieval(retrieval_conf, vectors, targets, mode='test'):
"""
Perform retrieval on the smaller datasets. Difficulty thresholds should
be modified is not using the standard (0.6, 0.4, 0.2) values.
:param retrieval_conf: Retrieval configuration.
:param vectors: Matrix of image embeddings.
... | d7749e90563386ff26041bc988af71050f0f2f0a | 3,601,218 |
import requests
import json
def address(lat, lng, *, raw=False):
"""
DVB Map Address
(GET https://www.dvb.de/apps/map/address)
:param lat: Latitude
:param lng: Longitude
:param raw: Return raw response
:return: Dict of address
"""
try:
lat, lng = wgs_to_gk4(lat, lng)
... | 6b09c12330491fc23cfe3ca7e168f9916614de83 | 3,601,221 |
def twoTauOU_gaussianSpikes(theta, deltaT, binSize, T, numTrials, data_mean, data_var, disp):
"""Generate a two-timescales process with spike counts sampled from a Guassion distribution.
Assuming that disperssion parameter (fano factor) of spike generation function is known.
Parameters
-----------
... | b567ee3a36337ef17fedf6bf370fd2e91c57b14d | 3,601,222 |
def get_py_param_value(context):
"""Extract the value of a parameter.
Dedicated to parameters under dynamic reconfigure
Args:
context (dict): context (related to an param description)
Returns:
str: The value of the parameter as a string
Examples:
>>> context = {desc="an in... | ffeb1044674799b8bb92f90eba963281061a55d3 | 3,601,224 |
def makeBleMessage(header, payload):
"""Factory method for identifying incoming BLE messages and creating the
correct message subclass instance.
"""
# All the supported messages are listed here. Keep ABC-sorted for neatness.
lookup = {
AttClientAttributePrepareWriteResponse().header : A... | 2cb10dbb03cd9b6060242ef40f5ebeccac0cd0f2 | 3,601,225 |
def message(username=None):
"""
Get and send messages
"""
if request.method == 'GET':
messages = current_user.get_messages()
message_data = Message.get_message_data(messages)
users = set()
for u in message_data:
users.add(u['from'])
users.add(... | 3ef1e12952eb9393a2d7ed547d10ea67845a22b2 | 3,601,226 |
def add_contig_to_header(line, ref_file):
"""Streaming target to add contigs to a VCF file header.
"""
if line.startswith("##fileformat=VCF"):
out = [line]
for region in ref.file_contigs(ref_file):
out.append("##contig=<ID=%s,length=%s>" % (region.name, region.size))
retu... | 06135e7b87d33479cb04b9e22173249c4ed7567c | 3,601,228 |
import re
def quac_qasm_transpiler(qiskit_qasm: str) -> str:
"""Converts Qiskit-generated QASM instructions into QuaC-supported instructions
:param qiskit_qasm: a string with a QASM program
:return: a string with a modified QuaC-supported QASM program
"""
quac_qasm = ""
for line in qiskit_qas... | 1db5932053e00756e80db49b555ee70d3f4d881c | 3,601,229 |
def calculate_kinetic_energy(mass, velocity):
"""Returns kinetic energy of mass [kg] with velocity level."""
return 0.5 * mass * velocity ** 2 | 3e92aec7f7fd86b06c8c3ac5671e8908d9a175dd | 3,601,230 |
def moftype(cimtype, refclass):
"""Converts a CIM type name to MOF syntax."""
if cimtype == 'reference':
_moftype = refclass + " REF"
else:
_moftype = cimtype
return _moftype | c09697b9a1fabea1f1529de8ab7ee7eeed4da846 | 3,601,232 |
def add_cumulative_samples(df: pd.DataFrame) -> pd.DataFrame:
"""
Add cumulative samples to data table
This is useful for multi file recordings and helping to decide which files
to read to get a certain time range
Parameters
----------
df : pd.DataFrame
Data table with an n_samples... | df0c84d8e41ebfb57b7d3660d9400f25c2625655 | 3,601,233 |
def user_model():
"""Returns the User model object as a test fixture."""
return User | 882c2d886d9c2808e1ce44788b2ec4eb826b11cc | 3,601,234 |
def is_resource_sufficient(order_ingredients):
"""
Returns True when order can be made, False if ingredients are insufficient.
"""
for item in order_ingredients:
if order_ingredients[item] > resources[item]:
print(f"Sorry!! there is not enough {item}.😢")
return False
... | 42b6d324e9bd506e3b4d75514fc9ffa001c3c593 | 3,601,235 |
from typing import Any
from typing import Type
from typing import Optional
from typing import get_args
from typing import Mapping
from typing import get_origin
def is_instance_of_type(_object: Any, required_type: Type) -> Optional[bool]:
"""
Check if `object` is of type `required_type`.
Works same as `is... | f100ab818b3ee3cbd7ef00487d5156db7b1f2f9c | 3,601,237 |
def es_healthcheck(*args, **kwargs):
"""Elasticsearch healthcheck."""
verbose = kwargs['verbose']
return _run_healthcheck_command([
"curl",
"-f",
"localhost:9200/_cluster/health?wait_for_status=green"
], verbose) | 2979a2b2ff6860d2079864f66bd39a8767237752 | 3,601,238 |
def rleToMask(rleString, height, width):
"""
This function is an rle to mask converter.
You supply the rle string for one mask, along with it's height and width
from the solutions for stage1 and it will return the mask.
Source: https://www.kaggle.com/robertkag/rle-to-mask-converter
"""
row... | 2fa8fa7e9c8a608347509ab0cd910a405ea11526 | 3,601,239 |
def trolls():
"""pull all entries from trolls table"""
trolls_query = Troll.query.all()
troll = [troll.serialize_troll() for troll in trolls_query]
return jsonify(troll) | d7ae72bbf69773e7dcc2312ca85e7fb37261efe0 | 3,601,240 |
from typing import Optional
import types
def _should_dither(in_bits: int,
out_bits: int,
in_range: Optional[types.Range] = None,
out_range: Optional[types.Range] = None,
in_sample_type: Optional[vs.SampleType] = None,
out_s... | 11c9d22800b44ed5a8ab8a1a3ff95e1b88426c24 | 3,601,241 |
def remove_artefacts(data, ch_labels, Fs, data_ref, ch_labels_ref, params=None):
"""
remove_artefacts: simple procedure to remove artefacts
Syntax: data = remove_artefacts(data, ch_labels, Fs, data_ref, ch_refs)
Inputs:
data - EEG data, in bipolar montage; size: N_channels x N (pandas dat... | 0454c5f83ee07d0258400939bb07fcd2d3951e86 | 3,601,242 |
def bd_wgs(lon, lat, check_china=True):
"""Convert BD09 coordinates to WGS84 (fast estimation)."""
result = lib.prcoords_bd_wgs({'lon': lon, 'lat': lat}, check_china)
return (result.lon, result.lat) | 713b6103156a6307ca66c8f347526165f8268476 | 3,601,243 |
def shift(arr: list):
"""
方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度
从数组中删除的元素; 如果数组为空则返回 undefined(None)
"""
if len(arr):
return arr.pop(0)
return None | ff7ea2320c6b9f846b8d047e6a6a76d0cd7ab645 | 3,601,246 |
def rel_diff_cube(cube_0, cube_1, in_threshold=None, out_threshold=None, percentage=False):
"""rel_diff(cube_0, cube_1, in_threshold=None, out_threshold=None, percentage=False) ->
cube of relative difference
| a - b |
_________
|a|
'in_threshold': if passed, this absolute threshold is applied... | 6dd3da914c271f403a58c5d5408d73e98eb2ddb7 | 3,601,247 |
def train(ca, x, target, steps, optimizer, scheduler):
"""Runs cellular automata (nCA), backpropagates and updates the weights
Args:
ca ([type]): cellular automata model
x ([type]): image to update with nCA
target ([type]): target image
steps ([type]): how many times we update w... | 996e13434711fed4132f16cf93534b86dd10b022 | 3,601,248 |
def handle_status_update(loan_id, new_status):
"""Handles a status update for an order."""
# lookup order in your system using loan_id
# set order status to new_status
return '' | d75f6c145346d7fe9c6fd124dc0590fd66b64da6 | 3,601,249 |
import operator
def format_sensors(ant_sensors, band, full_report):
"""Returns a 2D list of antennae sensor values with text-marked anormalies"""
data = []
exclude = []
revised_data = []
# add warning text
for sensor in ant_sensors:
row = []
row.append(sensor["name"])
... | 789c2f0b2b8bb9f82c1988904599185d8385ee52 | 3,601,250 |
def unconfirmed():
"""User is unconfirmed."""
if current_user.is_anonymous or current_user.confirmed:
return redirect(url_for('web.home_page'))
return render_template('auth/unconfirmed.html') | 1c01d770b14056b68dbfe089e41a50d9cacec64a | 3,601,251 |
def make_sinks_api(client):
"""Create an instance of the Sinks API adapter.
Args:
client (~logging_v2.client.Client): The client
that holds configuration details.
Returns:
_SinksAPI: A metrics API instance with the proper credentials.
"""
generated = ConfigServiceV2Clie... | 7e792fb057b29b277101f189abd4b8ca03972ddf | 3,601,253 |
def pretty_string(dict, indent=0):
""" Returns string containing all keys and values in a dict. Makes it 'Pretty'. """
result = []
for key, value in dict.items():
if isinstance(value, str):
result.append('\t' * indent + ('%s:\t "%s"' % (key, value)).encode('ascii', 'ignore'))
elif isinstance(value, list):
... | a5e5aa17b29bb31bd9122dc878f0a511c2dcafd9 | 3,601,254 |
def search_for_currency():
""" display a currency by currency slug """
users_currencies = get_users_currency()
slug = request.args.get('slug')
currency_data = get_by_slug(slug)
return render_template('single_currency.html', currency=currency_data, user_currencies=users_currencies) | bb8e4d3cc6d3e03d49a26d42009b168e90633965 | 3,601,255 |
import json
def search(request):
"""
JSON-based search api for external calls into the discovery app
"""
query = request.POST.get('q')
type_of = request.POST.get('q_type')
if len(query) > 0:
if type_of == 'kw':
search_results = {
'works': whoosh_helpers.keyw... | 5c661a5b21f084e3a321896ac7b56158eeace0c5 | 3,601,256 |
def std(data: np.ndarray, ddof: int = 1) -> float:
""" 计算修正的样本标准差
:param data: 要求标准差的数据
:param ddof: 修正值,除法分母为n - ddof,默认为1
:return: 标准差
>>> std(np.array([0.2,0.2,0.2,0.2]))
0.0
"""
return data.std(ddof=ddof) | c8dc4ec832a33b0bf194f85b01124d638999123d | 3,601,257 |
def get_unigram_dist(sentences):
"""
Returns a dictionary with unigrams and thier corresponding probability, given a list of sentences as input
"""
# sentences = random.sample(sentences, sample_count)
# sentences = [s[:-1] for s in sentences]
tokens = nltk.tokenize.word_tokenize(' '.join(sentenc... | 2e4034190edfe30c534be47bf4a49192ef5589de | 3,601,258 |
def eval_instance_segmentation_soma(
flag, pred_mask_path, gt_mask_path, img_names, iou_thresh, use_07_metric=False):
"""Calculate average precisions based on evaluation code of PASCAL VOC.
This function evaluates predicted masks obtained from a dataset
which has :math:`N` images by using average pr... | c0758049b121a579ba81f59ecb34c0cc8da5f58c | 3,601,259 |
def _reverse_reaction_rates(ktp_dct, thermo_dct, rxn, temps):
""" use the equilibrium constant to reverse the reaction rates
"""
[rct_idxs, prd_idxs] = rxn
k_equils = _calculate_equilibrium_constant(
thermo_dct, rct_idxs, prd_idxs, temps)
rev_ktp_dct = {}
for pressure, rates in ktp_dct... | 62aa585ce4ac4cd4397a2e1a83f47ed8d4cdd3e0 | 3,601,260 |
def get_entity(endpoint):
"""
Return the entity of a kernel endpoint
Example param: /journals/8767-8766-12-32-2
Return: journals
"""
_entity, _id = parser_endpoint(endpoint)
return _entity | 5682e262ba9bdefc798fc2e3cb3f70e1b7fbc3ec | 3,601,261 |
def x_y_to_zeta_eta(x, y):
"""Same as def x_y_to_zeta_eta, but for ndarrays."""
x = np.abs(x)
y = np.abs(y)
zeta = np.sqrt(x ** 2 + y ** 2) # + offset
eta = np.ones(zeta.shape)
index = np.where(x > y)
zeta[index] = -zeta[index]
eta[index] = (4.0 / np.pi) * np.arctan(y[index] / x[index])... | 11bf993d3b9c0751a04f1a9870d064c1d414e447 | 3,601,262 |
def config_ldap_server_map_override_attribute_value(dut, **kwargs):
"""
Author: Chandra.vedanaparthi@broadcom.com
config_ldap_server_map_override_attribute_value(dut=data.dut1,key_list=[userShell], \
value_list=["/bin/rbash"],config='yes')
config_ldap_server_map_override_attribute_value(dut=data.du... | baac770b00f24a3dc69dfe38dc4640440fa53db2 | 3,601,263 |
def bisection_search(f, low:float, high:float):
"""
A root finding method that does not rely on derivatives
:param f: a function f: X -> R
:param low: the lower bracket
:param high: the upper limit bracket
:return: the location of the root, e.g. f(mid) ~ 0
"""
# flip high and low if out... | 297f4fb80f0837d28573199ca05b90821155cd52 | 3,601,265 |
def clustering(edge_list):
"""ノードパスによってクラスタリング"""
clustered_edge_in_list = []
for edge in edge_list:
clustering_edge = ClusteredDirectiveEdgeV15.clustering(edge)
clustered_edge_in_list.append(clustering_edge)
return clustered_edge_in_list | b0998f1d84d6bbc667031a0cfd78771e943686d2 | 3,601,266 |
def name_fun(n):
"""
input: stopping rule
output: finish nodes
"""
output = []
temp = ['']
for i in range(2*n - 1):
temp_cur = []
for j in temp:
candidate_pos = j + '+'
candidate_neg = j + '-'
if str.count(candidate_pos, '+') >= n:
... | 74111c9a31475a764ed98ab5e2cfae6ec894b10c | 3,601,267 |
import torch
from typing import Any
def add_embeddings(df: pd.DataFrame, bert: Any,
overlap: int = 32, non_overlap: int = 64) -> pd.DataFrame:
"""
Add BERT embeddings to a DataFrame of BERT tokens.
:param df: DataFrame containing BERT tokens, as returned by
:func:`make_bert_token... | 3ac1944dc00a407aa1f16201df780f7c1f107461 | 3,601,268 |
def data_from_game(pm: Pymem, module_offset: int):
"""Return x,z,confirmation, sin and cos values read from game memory"""
plahka = pm.read_bool(module_offset+0x54C2F9)
x = pm.read_float(pm.base_address+0x10493C)
z = pm.read_float(pm.base_address+0x104944)
view_sin = pm.read_float(pm.base_address+0x... | ef16df240f937d8edd0b4a4d44edaa3fd7c2d04f | 3,601,269 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.