content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def fire_nozzles(firing_column):
"""Return the G-CODE describing the printing sequence. If there
is nothing to be printed, return an empty string.
"""
out = ''
if np.all(firing_column == 0):
return out
else:
while np.any(firing_column != 0):
firing_pattern, firing_c... | 912a1768626d1ccd2062950a37e713da274372f6 | 58,200 |
import os
def get_git_diff(filepath, git_hash):
"""Get a git diff of filepath from git_hash"""
filepath = os.path.expanduser(filepath)
try:
git_toplevel_dir = run_git(
["rev-parse", "--show-toplevel"], git_directory=os.path.dirname(filepath)
).rstrip("\n")
except GitError:
... | 709f076aa8b94f5fcc6f070f744794b55153c2bb | 58,201 |
import json
import random
def get_product_information(row, product_attributes):
"""Cleans event details and product information."""
category_code = row.category_code
details = category_code.split('.')
row = row.asDict()
row['category_code'] = dict(zip(product_attributes, details))
row['categ... | a16f7f0f06e9f2ad7f1262384aa1fedcfd72e0a3 | 58,202 |
import random
def make_block_trials(ntrials_block):
"""Creates a matrix of pseudo-random balanced trial parameters for a block of trials.
Parameters
----------
ntrials_block : int
Number of trials in the block
Returns
-------
block : 2d array
Matrix of trial parameters (t... | 8622657850c04f7ca3ab2f53e806d8709ecc1cd3 | 58,203 |
import time
import base64
import json
def create_custom_token(uid, valid_minutes=60):
"""Create a secure token for the given id.
This method is used to create secure custom JWT tokens to be passed to
clients. It takes a unique id (uid) that will be used by Firebase's
security rules to prevent unautho... | 93ce08439f35d82ae46043c8ab219e49bc2959ef | 58,204 |
def parseData(filename):
""" Parse a data file
Args:
filename (str): input file name of the data file
Returns:
RDD: a RDD of parsed lines
"""
return (sc
.textFile(filename, 4, 0)
.map(parseDatafileLine)
.cache()) | 73f959420ffa71a0c75612e519e6c2c6d7595546 | 58,205 |
def annotate_face(face_img):
"""
annotate_face: Annotate face image with its eyes, nose and mouth.
標記出 雙眼 鼻子 嘴巴 位置
"""
# Get mouth coordinates
mouth, _ = mouth_position(face_img) # Try finding the eyes in ref_img
mouth_x, mouth_y, w_mouth, h_mouth = mouth
mouth_coor... | 8d4f80e98aad2b9aab2510a39333353f795ca45f | 58,206 |
def get_user_alerts_request(username):
"""Retrieves a collection of Alerts related to a given user ID.
Args:
username (str): The user ID
Returns:
dict. Alerts entities
"""
cmd_url = '/users/{}/alerts'.format(username)
response = http_request('GET', cmd_url)
return response | f9c7dca23d170c87e181b16d466b2db73ec86daf | 58,207 |
import math
def re_sampling(px, pw):
"""
Robot generates a set of new particles, with most of them generated around the previous particles with more weight.
Argument:
px -- The state of all particles befor resampling.
pw -- The weight of all particles befor resampling.
Return:
px -- The ... | d83ba54905619f20cda950a24bd62471666e8eed | 58,208 |
def opt_in_argv_tail(argv_tail, concise, mnemonic):
"""Say if an optional argument is plainly present"""
# Give me a concise "-" dash opt, or a "--" double-dash opt, or both
assert concise or mnemonic
if concise:
assert concise.startswith("-") and not concise.startswith("--")
if mnemonic:
... | 17333a2a526799d6db5e78746d3ecb7111cd8cd6 | 58,209 |
def text(data: str) -> HTTPHandler:
"""Respond client with passed `str`.
Also sets "Content-Type: text/plain" response header.
Args:
data (str): response body.
"""
return set_text(data) >> start >> respond | 2c859fda17e364881151440a5d84c2b30acceda3 | 58,210 |
def render_solvation_math(solvation, user=None):
"""
Return a math representation of the given `solvation` using MathJax. If a
`user` is specified, the user's preferred units will be used; otherwise
default units will be used.
"""
# The string that will be returned to the template
result = '... | d2d94d52ed5f6b5a482c17eed6baa9a9b4644b17 | 58,211 |
import os
def load_data(cache_dir=None):
"""Loads the federated Stackoverflow dataset.
Downloads and caches the dataset locally. If previously downloaded, tries to
load the dataset from cache.
This dataset is derived from the Stack Overflow Data hosted by kaggle.com and
available to query through Kernels ... | 13786deb2b52d6a5cac64211eb5bb07d0d0daed3 | 58,212 |
import urllib3
import six
import os
def create_session(cred_dict, hmccreds_filename):
"""
To create a context, a session must be created first.
Parameters:
cred_dict (dict): 'metric' object from the HMC credentials file,
specifying items: hmc, userid, password, verify_cert.
hmccreds_f... | 651da86f9f785b8510c18a1f8b22bf708917e5be | 58,213 |
import os
def MODIS_shptoNC(dpath, fnames, force, client, ymin, ymax, dsn = "esacci"):
"""
Function to open the shape file and get the values into a raster at a workable
resolu
"""
# ========== Open the Raster dataset ==========
fname = dpath + "/masks/landwater/%s_landwater.nc" % dsn
ds_in = xr.open_dataset... | 30f07ee49ce026235a1542c9752d2974721b7c9a | 58,214 |
def find_shufflenet_layer(arch, target_layer_name):
"""Find mobilenet layer to calculate GradCAM and GradCAM++
Args:
- **arch - **: default torchvision googlenet models
- **target_layer_name (str) - **: the name of layer with its hierarchical information. please refer to usages belo... | becbfbe8aa2d59c0a56fcb82831e67da3b3f8f40 | 58,215 |
def compute_moment(name="rough_example",
outname="ufault",
results_dir=None):
"""
computes seismic moment for a given problem
"""
datadir = join(results_dir, "data")
U = fdfault.analysis.output(name, outname, datadir)
U.load()
return simps(U.U, U.x) | 3075109becfe23e83f2203119b252155dd7f16be | 58,216 |
from datetime import datetime
def calendar_data_current() -> CalendarEvent:
"""Representation of a Demo Calendar for a current event."""
middle_of_event = dt_util.now() - datetime.timedelta(minutes=30)
return CalendarEvent(
start=middle_of_event,
end=middle_of_event + datetime.timedelta(mi... | 623979f5233a0e5a8632d1a68997929d2470307c | 58,217 |
from typing import Type
def create_type(*args, dry=False, **kwargs):
""" @orm: (:class:ORM)
@name: (#str) name of the type
@*opt: (#str or :class:Clause) type options
* |PASSEDBYVALUE|
@attrs: (#tuple(#tuple)) #tuple pairs of |(attr_name, data_type, *opt)|
- creates... | bce0f5e3a4d934e17d2a82ab8dc732a312c8d5c0 | 58,218 |
def fraction_of_symptomatic():
"""
Real Name: b'fraction of symptomatic'
Original Eqn: b'ZIDZ(Infected symptomatic, total infected)'
Units: b'dmnl'
Limits: (None, None)
Type: component
b''
"""
return functions.zidz(infected_symptomatic(), total_infected()) | 6203845247e6b90bed79fb27d39c970b0dfd87df | 58,219 |
def add_side_effect_wrapper(session_mock):
"""Side effect for the add function, used to add an id to the input table."""
def add_side_effect(table):
tablename = table.__tablename__
if tablename in session_mock.tables and len(session_mock.tables[tablename]) > 0:
max_id = 0
... | b85052f962c6437934fa9cd310eec7c559d5222d | 58,220 |
def AuthVerifyInfo(result):
""" result
{
'options': {
'a': 'b',
...
'auth_type': 'google_oauth2'
}
"""
result['options'] = change_struct_type(result['options'])
return auth_pb2.AuthVerifyInfo(**result) | c93d51297be82c293e00cfdf3306f624bc5ef42c | 58,221 |
def expand(posterior, vocabulary, m=10):
"""
>>> vocabulary = "a b c".split()
>>> posterior = [0.9, 0.1, 0.42]
>>> expand(posterior, vocabulary, 0)
[]
>>> expand(posterior, vocabulary, 1)
['a']
>>> expand(posterior, vocabulary, 2)
['a', 'c']
"""
if m <= 0:
return []
... | c79d5bfb3f8f0ee750cc6514ba7c9142553357e2 | 58,222 |
from pathlib import Path
from typing import Tuple
from typing import List
from datetime import datetime
import csv
def read_account(account_csv: Path) -> Tuple[List[List[str]], datetime.date]:
"""Opens a DeGiro 'Account.csv' file and returns the contents as well as the first date"""
csv_data = list(csv.reader... | 996e295f3249ff077d44618a31ef78d9ef9a28c3 | 58,223 |
def random_rotation(x, rg, row_axis=0, col_axis=1, channel_axis=2,
fill_mode='nearest', cval=0., interpolation_order=1):
"""Performs a random rotation of a Numpy image tensor.
# Arguments
x: Input tensor. Must be 3D.
rg: Rotation range, in degrees.
row_axis: Index of ... | ad8958f20214725a4c0111569506ae7f1298c99c | 58,224 |
def addY_label(IoT_df1,df2):
"""
This function is to add Y_label from df2 to IoT_df1
:param IoT_df1: dataset x_val
:param df2: dataset for y_val
:return: y_val
"""
y_label = []
macADD_list = df2["MAC_address"].tolist()
macADD_list = [x.strip(' ') for x in macADD_list]
for r in r... | b039dfad641309d7673954b2a81787d6e1b6ad9c | 58,225 |
def line_plot(x, y, title=None, xlabel=None, ylabel=None, ax=None):
"""Helper function to draw a line graph.
.. moduleauthor:: Jin Soo Ihm <jinihm@umich.edu>
Args:
x (list): x values of the line graph.
y (list): y values corresponding to :code:`x`.
title (str): Title of the graph. ... | 39103997db0c5fcdcdd4633a5d1147524a9dbebd | 58,226 |
def authenticate(**credentials):
"""
If the given credentials are valid, return a User object.
"""
for backend in get_backends():
try:
user = backend.authenticate(**credentials)
except TypeError:
# This backend doesn't accept these credentials as arguments. Try th... | e4e6e7ee037172bc6bb3280f1d90205e5a2b797d | 58,227 |
from normalizr import Normalizr
def remove_acentos(tokens=list()):
"""
Remove acentos dos tokens
Return: lista de tokens
"""
normalizr = Normalizr(language='pt')
normalizations = [ 'remove_accent_marks' ]
l = list()
for token in tokens:
l.append(normalizr.normalize(token, norma... | df7d6cce0fc16e4d03d18a2bbc74135894a1038b | 58,228 |
def tie_amps_FIR_to_SIL1(model):
"""
function to tie the FIR amplitude to the SIL1 amplitude
"""
return (0.012 / 0.002) * model.SIL1_amp_0 | 13ae408cc618c118a7ad1059422fabad0036dff2 | 58,229 |
import json
import time
def scan(browser, token, node=None, group=None, environment=None, wait=False, label=""):
"""
Scan a node, group, or environment. If `wait` is True, then this function will wait for the scan job to complete before returning.
"""
job = {}
found_obj = False
if node:
... | f69ba1561ea1bc2f3172f706dfcd2427c32e3a25 | 58,230 |
import math
def apply_forces_cpu(number_agents, jkr_force, motility_force, locations, radii, stokes, size, move_dt):
""" This just-in-time compiled method performs the actual
calculations for the apply_forces() method.
"""
for index in prange(number_agents):
# stokes law for velocity based... | 6ae7f370589d534e804005a7738a9358a4af7fa0 | 58,231 |
def calcPionMassSq_1gen(CA, CG, CW, CZ, eQ, gs, sQsq, lamW, fpi, mD, kappa, DEBUG=True):
"""
"""
fsq = fpi**2
pi3 = np.pi**3
pi2 = np.pi**2
eQsq = eQ**2
gssq = gs**2
# NOTE: The \ continues the expression onto the next line for readability
# https://stackoverflow.co... | ac4dcb100350825434e2ede64959b11b2b2315b4 | 58,232 |
import os
def hurst_exp(resonance: list,
OUT_PATH: str):
"""
resonance: list of resonance values
OUT_PATH: path for where the output is saved to
Returns hurst exponent hurst_r
"""
nolds.hurst_rs(resonance, nvals=None, fit='poly', debug_plot=True, plot_file=None, corrected=True... | fe8e106aeb63a1234b41288a272b2c6bf398a619 | 58,233 |
def split_by_unicode_char(input_strs):
"""
Split utf-8 strings to unicode characters
"""
out = []
for s in input_strs:
out.append([c for c in s])
return out | 290bb5ec82c78e9ec23ee1269fe9227c5198405e | 58,234 |
import google
def login():
"""
Login view. Redirects to google authorization
"""
return google.authorize(callback=url_for('authorized', _external=True)) | 951f0aae2b7549133a05e3892aaebfdaafc73518 | 58,235 |
from typing import List
import re
def get_e2e_suite_names_from_protractor_file() -> List[str]:
"""Extracts the test suites section from the protractor.conf.js file.
Returns:
list(str). An alphabetically-sorted list of names of test suites
from the protractor.conf.js file.
"""
protract... | 0b8ed9b1f4bbf37b7b3f21c6e60b5d0f0c3b6141 | 58,236 |
import re
def convert_string(string: str, wrap_blocks: bool = False) -> str:
"""Converts Markdown like expression to html.
See :data:`PATTERNS` for available substitutions.
Arguments:
string: The string to convert to html.
wrap_blocks: If True wrap string in `<p>` blocks. Delimi
"""... | 4c2a2e12dba2a59b192a95100a336eee363ac837 | 58,237 |
async def is_superuser(current_user: User = Depends(login_required)) -> User:
"""Check if the user is superuser.
Args:
current_user: depends function.
Returns:
user model
Raises:
HTTPException: If user is not superuser return 404 status.
"""
if current_user.is_superuse... | 83cdc96def476db521b7cd79a7ae1e944df85e0e | 58,238 |
from datetime import datetime
def profile(request):
"""
Add a person to the database with all of the fields specified.
"""
curr_user_id = request.user.id
if request.method == 'POST':
form = PersonForm(request.POST)
if form.is_valid():
input = req... | 605ea4cd2319f72d01c7437051342a76b77c9a6e | 58,239 |
def filter(lst):
"""
Method that filters list
:param lst: list to be filtered
:return: new filtered list
"""
if lst is None:
return []
if not isinstance(lst, set):
lst = set(lst) # Remove duplicates.
new_lst = []
for item in lst:
item = str(item)
if (... | 06c96962910b77a78615861822c76bbc9cfb52ce | 58,240 |
def b64decode_url(istr):
""" JWT Tokens may be truncated without the usual trailing padding '='
symbols. Compensate by padding to the nearest 4 bytes.
"""
istr = encode_safe(istr)
try:
return urlsafe_b64decode(istr + '=' * (4 - (len(istr) % 4)))
except TypeError as e:
raise E... | fc7425adc14e1adf094d1711023f4ff45a01df20 | 58,241 |
def convert_calibre_to_mendeley_ref(calibre_ref: CalibreReference) \
-> MendeleyReference:
"""Convert a MendeleyReference to the corresponding CalibreReference
instance.
.. todo:: Unittest this - Have a sample reference - convert it to the
Calibre format
.. todo:: Implement this
... | da0c94ab543db03c747303bdbfe3409cf9a60ff4 | 58,242 |
def mirror_p3d(seq):
"""
:param seq: {n_frames x 14*3}
:return:
"""
assert len(seq.shape) == 2, str(seq.shape)
n_frames = len(seq)
LS = [0, 1, 2, 6, 7, 8]
RS = [3, 4, 5, 9, 10, 11]
lr = np.array(LS + RS)
rl = np.array(RS + LS)
x = seq.reshape((n_frames, -1, 3))
x_copy = x... | bdec2fd59e8bc53c119850c8f31542138c2e508f | 58,243 |
import os
def upload_facettes_file(project_id):
"""
uploads the test data and saves it as test_data.csv in the working directory
:param project_id: the ID of the current project
:return: returns 204 if the file was saved successfully
"""
with app.app_context():
location = app.config.ge... | 30dd7a75ceb9db30e18e29dd19b8b9709d62872c | 58,244 |
import torch
from typing import Tuple
def get_point_covariances(
points_padded: torch.Tensor,
num_points_per_cloud: torch.Tensor,
neighborhood_size: int,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Computes the per-point covariance matrices by of the 3D locations of
K-nearest neighbors of each... | c4a303477e096a2a1253cc10a4a78e248b7f7005 | 58,245 |
def get_dir(abs_src_path: str, abs_dest_path: str) -> None:
"""Allows the server pulling a directory from the client and saving it at the server. The directory is pulled
with all its files and inner directories."""
return gen_file_exchanges.get_dir(abs_src_path, abs_dest_path, net_interface.server.pull_file... | 1cafdf317472534a961b5bd4cbe58d68a9f75691 | 58,246 |
def runLineageProfiler(species,array_type,exp_input,exp_output,codingtype,compendium_platform,modelSize=None,customMarkers=False,geneModels=False,permute=False,useMulti=False):
""" This code differs from LineageProfiler.py in that it is able to iterate through the LineageProfiler functions with distinct geneModels
... | 4a9155da428bf5a70abc1181163e91156cf0d982 | 58,247 |
import itertools
from typing import OrderedDict
import operator
from datetime import datetime
def parse_cdrs(cdr_list, config_settings):
"""Parse list of CDRInstance to generate & return list of CDRException for CDRInstances where termination
cause code isn't in the list of exclusions or MoS/CCR is worse than... | ab2acdaa779d7ba7b5878a2e6cd85ed20cc68ec5 | 58,248 |
def calculate_angle_difference(alpha, beta):
"""
Return min angle in rad between two give angles in range <-pi, pi>
"""
diff = alpha - beta
diff = clip_angle(diff)
return diff | c073cf88402c84ab59ad9e739bd775483650cc5f | 58,249 |
import requests
def make_ecobee_request(request_type, url, **kwargs):
"""
Wrapper around making arbitrary GET and POST requests to remote Ecobee API
:return: Ecobee API response using provided request content
"""
# Generate appropriate grequests object
if request_type.lower() in ["get", "post"... | d1af35212fba25a3e27b205dba6bc631e2989e27 | 58,250 |
import warnings
import copy
def combine_ins(ins1, ins2, inplace=False):
"""
This utility function combines INS for the same obs that have been averaged
over different baselines.
Args:
ins1: The first spectrum for the combination
ins2: The second spectrum for the combination
in... | 18e8e3f208642eef1c66c03dab653ff5c76b45df | 58,251 |
import http
def ope_titre_detail(request, pk):
"""
view, une seule operation mais pour les comptes titres
@param request:
@param pk: id de l'ope
"""
ope = get_object_or_404(Ope_titre.objects.select_related(), pk=pk)
if request.method == 'POST':
# date_initial = ope.date#inutile
... | 650c5c812c1ec044fbcdbed2b74d38945f6104d6 | 58,252 |
def get_coordinate(title):
"""
Extract coordinates from ocrx coordinates string
:param title: ocrx coordinate string
:return: dictionary contains ``xmin``, ``ymin``, ``xmax``, ``ymax``
"""
match = BBOX_COORDINATES_PATTERN.search(title)
return {
'xmin': int(match.group(1)),
'y... | e2363040fd6ac5f44b5e24cb65b529f2e5c9dc05 | 58,253 |
import pandas
def asks(orders: pandas.DataFrame) -> pandas.DataFrame:
"""
Get orders of type "ask".
Args:
orders: dataFrame of orders
"""
return orders[orders.side == 'ask'] | e5a2799e35cab1888403ee8480f0535db5e1c73d | 58,254 |
def bm_group_load(name, path):
"""a wrapper to download, process and load benchmark group
Args:
name (str): the rough benchmark group name
path (str): the benchmark group path to save/retrieve
Returns:
str: exact benchmark group name
"""
name = bm_download_wrapper(name, path)
return name | bf9d116db8b10eca296b21c33465941232ae72df | 58,255 |
def GetAssetCreationTime(primStack, assetIdentifier):
"""Finds the weakest layer in which assetInfo.identifier is set to
'assetIdentifier', and considers that an "asset-defining layer". We then
retrieve the creation time for the asset by stat'ing the layer's
real path.
Returns a triple of strings:... | c6a0585128815ad6f9938ede3fc9cbc1dded1b8d | 58,256 |
def redact(text, classification_segmenter: Segmenter, detection_segmenter: Segmenter,
redactor: Redactor, comprehend: ComprehendClient, redaction_config: RedactionConfig, language_code) -> Document:
"""
Redact pii data from given text. Logic for redacting:- .
1. Segment text into subsegments of ... | 8f36ddbcb8419b988fd3ddd09fbb18c79ede9ee2 | 58,257 |
def calc_hvac_energy(surface_area, building_type, Tin, Tout):
"""
Heat Transfer Equation
Notes
-----
Q = U x SA x (Tin - Tout)
Q - Heat lost or gained due to outside temperature (kJ·h−1)
U - Overall heat transfer coefficient (kJ·h−1·m−2·°C... | 1616196b36f6c512763362292ceb296ad4acbf96 | 58,258 |
import types
def goes_flare_class(gcls):
"""Convert GOES classes into a number to aid size comparison. Units are
watts per meter squared."""
def calc(gcls):
powers_of_ten = {'A':1e-08, 'B':1e-07, 'C':1e-06, 'M':1e-05, 'X':1e-04}
power = gcls[0].upper()
if power in powers_of_ten:
... | b98d09154dafc0bdd4b67df8477110acece1ad92 | 58,259 |
def helpMe():
"""
Render the help page
"""
return render_template('home/help.html', title="Help") | 4659534574ddcbd05c34c8cb0d9b479701aa3f91 | 58,260 |
import shlex, subprocess
def RunShellCommand(command):
""" Run a shell command in subprocess.
params: command with arguments to run
returns: (exit_code, stdout, stderr)
"""
cmd_args = shlex.split(command)
output_str = ""
exit_code = 0
try:
output_str = subprocess.check_... | 4a3534491ceed74f2371550d2b0748f0af31e7f0 | 58,261 |
import requests
import io
import time
def download_data(url):
"""
Args:
url:
Returns:
pandas dataframe
"""
attempt = 0
while attempt < MAX_ATTEMPTS:
try:
response = requests.get(url)
if response.status_code == 200:
print("\tReq... | ff1d4cb787abb49209d2b5d87fc847968921c184 | 58,262 |
def measure_total_snapshot_creation_time(snap_name, start_time):
"""
Measure Snapshot creation time based on logs
Args:
snap_name (str): Name of the snapshot for creation time measurement
start_time (str): start time, starting from which the logs are searched
Returns:
float: Cr... | 57e5c407db2aaec17954438789fc45abb810da6c | 58,263 |
def filter_records_for_filetypes(records: dict, return_types: list):
""" Find the records that have all the requested filetypes. e.g. get all subdirectories with labels """
valid_records = {}
for k, v in records.items():
# k is the key for this record, e.g. experiment00_mouse00
# v is the di... | 4c79d8646534875c4b64e0e851fc6e4b6676746b | 58,264 |
def mass_ks_test(x, y):
"""mass-univariate two-sample kolmogorov-smirnov test
Args:
x ([type]): 1D numpy array
y ([type]): 1D numpy array
"""
pvals = []
num_dims = x.shape[1]
for dim in range(num_dims):
_, p_val = ks_2samp(x[:, dim], y[:, dim])
pvals.append(... | 480aa574e9a1fd719453d1c792244fd3f3a62862 | 58,265 |
import base64
import os
def handler_local(base64_encoded_path):
"""Serving local files."""
fullpath = base64.urlsafe_b64decode(base64_encoded_path).decode('utf-8')
fullpath = unquote(fullpath)
basename = os.path.basename(fullpath)
dirname = os.path.dirname(fullpath)
return static_file(basename... | cfef30e37987ccd293fb7ead68cc5f99bac04783 | 58,266 |
import torch
def cmn(data, axis=1, is_tensor=False):
"""Apply mean normalization on input sequences for every dimensions.
axis is the dimension in which we perform normalization. """
if is_tensor:
data2 = data - torch.mean(data, dim=axis, keepdim=True)
else:
data2 = data - np.mean(data... | d9dd3ba9d43a56a48ed06e3be5ef041be3ad1cea | 58,267 |
def getValidData(filelist=[]):
"""过滤集合中空的元素."""
valifile = []
for fp in filelist:
if fp != None:
valifile.append(fp)
return valifile | 57bccc440a056deee3bd16a4785823ab4f0845c2 | 58,268 |
from typing import Tuple
from typing import Union
import torch
def odeint_hybrid(f, x, t_span, j_span, solver, callbacks, atol=1e-3, rtol=1e-3, event_tol=1e-4, priority='jump',
seminorm:Tuple[bool, Union[int, None]]=(False, None)):
"""Solve an initial value problem (IVP) determined by function `f` and initial ... | cb00770d93d185763d0f11ff1e2246597c530946 | 58,269 |
import functools
import six
def wrap_wsme_controller_exception(func):
"""This decorator wraps controllers method to manage wsme exceptions:
In case of expected error it aborts the request with specific status code.
"""
@functools.wraps(func)
def wrapped(*args, **kwargs):
try:
r... | 71e4c5f6bdd963bb2180db576144a14f40ff04b2 | 58,270 |
import typing
def _init_ctz_db_and_table(n: int) -> typing.Tuple[int, typing.List[int]]:
"""Setup for fast ctz of ints with up to 2**n bits.
This code initializes the De Bruijn sequence (as an integer) and
the lookup table needed to do constant time (1 multiply and some
bit twiddling) ctz, as describ... | b9bbd5dfa085ade0fb8a8369ab683016ce3d0418 | 58,271 |
def _plot_dendrogram(dendrogram_list, active_sites, cluster_indicies_dict):
"""
Plots a dendrogram from the hierarchical clustering
Parameters
----------
dendrogram_list
active_sites
cluster_indicies_dict
Returns
-------
"""
sns.set_style("white")
fig, ax = plt.subplots... | 2af3ef55f91a50ba6381a84d387357fb7574453c | 58,272 |
def xrdataset(filenames,aggdims,no_mf=True):
""" filenames: shape 2 list [dim y [dim x]] ; aggdims = [dimy,dimx] """
ncs = []
for names in filenames:
#tmes, tmeb = time.clock(), time.time()
if no_mf:
ncc = [xr.open_dataset(name) for name in names]
ncs.append( \
... | eb788aa0dfdf7b91f7509dc1df7aaad0427ca9c8 | 58,273 |
from typing import TextIO
from typing import Tuple
def _read_table(f06_file: TextIO, line: str, i: int,
log: SimpleLogger) -> Tuple[str, np.ndarray, str, int]:
"""
'0 TABLE MKLIST LINES CONTAINING BINARY ZERO HAVE BEEN DELETED.\n'
''
''
'0RECORD NO. 0'... | 893265cf4790a275cf6226d2fe31aace54143dc6 | 58,274 |
def sorted_dict(d : dict) -> dict:
"""
Sort a dictionary's keys and values and return a new dictionary
"""
try:
return {key: value for key, value in sorted(d.items(), key=lambda item: item[1])}
except Exception as e:
return d | ec8b38805ee26f2d2e2fe0d876c8cbda88098026 | 58,275 |
def getWordsUnder(wordList, targetLength):
""" return list of words of a specified length in the list """
return [word for word in wordList if len(word) < targetLength] | ba49461ab90d32a97cdd9db3a8785cdc95579463 | 58,276 |
import os
def prepare_input_data():
"""
Loads data from description_template.txt file, which contains labels for the images, and the associated images described in the file.
:return: List of dictionaries[name=name of file,image_type==category(0 for clean, 1 for dirty),data==data]
"""
output = []
... | fd8ea3948029de441aee6f89bc03c86f21ce8d22 | 58,277 |
def helpers(request):
"""return a dict of app helpers"""
return dict(
app_url=request.app.url,
app_menu=request.app.menu,
app_name=request.app.name,
app_class=zoom.utils.id_for(request.app.name.strip()),
app_description=request.app.description,
app_keywords=reques... | 6411bf8eb508daf2417dfdae67a46a6c724f9572 | 58,278 |
import configparser
def export_story_as_config(from_slide, with_fields):
""" Returns the story items for a story slide in the config format
Each slide contains placeholder with a text frame which in turn contains
paragraphs with text. Only ASCII characters are allowed in the story text
files to overc... | 529893dc5b238e86a9480d983afe5a229d762dd0 | 58,279 |
def mean_value_2d(f, psi, x_range, y_range, M):
"""
Short summary.
Parameters
----------
f : type
Description of parameter `f`.
psi : type
Description of parameter `psi`.
x_range : type
Description of parameter `x_range`.
y_range : type
Description of par... | 030518250a18cc61974b4615c4d2f80b0bd032f7 | 58,280 |
import sys
import glob
import os
import logging
def set_gcc(use_openmp):
"""
try to find and use GCC on OSX for OpenMP support.
Reference
---------
https://github.com/maciejkula/glove-python/blob/master/setup.py
"""
# For macports and homebrew
patterns = ['/opt/local/bin/gcc-mp-[0... | 6e56f2ff46233f90eca3df274cafecd1cfde2774 | 58,281 |
def get_percentage(new, last):
"""
:param new: float
New value
:param last: float
Last value
:return: float in [0, 100]
Percentage increase (or decrease) since last value
"""
ratio = abs(get_ratio(new, last))
percentage = min(ratio * 100.0, 100.0) # in bounds
pe... | 374d8f51bda7a9152b33674749b2b499480f00e8 | 58,282 |
def get_info(city, route):
"""取得該城市符合條件的所有路線基本資料"""
return jsonify(info.main(city, route)) | 5dce8e5e9cdad4b8e7a56c0370722de39171abb1 | 58,283 |
from datetime import datetime
def get_payouts(num_days=None, payout_status=None,
start_date=None, end_date=None, sandbox=False, **kwargs):
"""Get payout using the Sell Finances API.
Arguments
num_days: Only return payouts from the last num_days
payout_status: Only return payou... | 8b46a0760eb03db2cc18035b6d80b1ef7a4e04ed | 58,284 |
def get_base_deck_nodes(bridge: Bridge, ctx: BuildContext) -> DeckNodes:
"""Deck nodes without refinement."""
deck_grid = get_deck_grid(bridge=bridge, ctx=ctx)
nodes = []
for z in deck_grid[1]:
nodes.append([])
for x in deck_grid[0]:
nodes[-1].append(ctx.get_node(x=x, y=0, z=... | d0c0050ca9a570189e4cf660b2f2be1d3e5b2795 | 58,285 |
from operator import inv
def fim_for_single_t(xpdot1, Vold, sigma, nx, ntheta,A):
"""
:param xpdot:
:param sigma:
:return: FIM1
"""
xpdot = xpdot1
FIM1 = Vold#np.zeros([2, 2])
for i in range(1):
xp_r = reshape(xpdot, (nx, ntheta))
# vv = np.zeros([ntheta[0], ntheta[0], 1 + ... | 0a0a364e935781a99def0864aa42986ee5f8694a | 58,286 |
def get_project_image_count(project, with_all_subfolders=False):
"""Returns number of images in the project.
:param project: project name or folder path (e.g., "project1/folder1")
:type project: str
:param with_all_subfolders: enables recursive folder counting
:type with_all_subfolders: bool
:... | db3806bc4e74aedf4feef686bdf63259e98b9067 | 58,287 |
def compute_short_chain(number):
"""Compute a short chain
Arguments:
number {int} -- Requested number for which to compute the square
Returns:
int -- Value of the square/short chain for the given number
"""
return number * number | 7ce09da632cdc19a1b785121ff60b60c0dd719a9 | 58,288 |
def generate_default_ok_responses():
"""
Generate default ok responses for http requests
"""
default_ok_responses = generate_default_response()
default_ok_responses["200"] = {
"$ref": "#/components/responses/Ok"
}
return default_ok_responses | 2089319050027e1c3dfe62917dc5249924021f58 | 58,289 |
def sort_by_type_and_size(layer_nodes):
"""
对关键路径中的叶子节点按照资源类型和大小进行排序
Args:
leaf_nodes: 叶子节点列表
Returns:
排好序的叶子节点列表
"""
document_list = []
stylesheet_list = []
font_list = []
script_list = []
for node in layer_nodes:
if node['mime_type'] == 'text/html':
... | 02026778cfe0ff1481e24a9b2f9304fb2a5a4fc3 | 58,290 |
import os
def get_tox21_filepath(dataset_type, download_if_not_exist=True):
"""Returns a file path in which the tox21 dataset is cached.
This function returns a file path in which `dataset_type`
of the tox21 dataset is or will be cached.
If the dataset is not cached and if ``download_if_not_exist``
... | 9ad604ed628ff954e30d72834486abb6e7279abf | 58,291 |
def delete_sms(overrides=None):
"""
Delete Sms
Args
overrides (dict):
msg_id: ';' (empty), 'X;' (one) 'X;Y;Z;' (many)
"""
defaults = {
'goformId': 'DELETE_SMS',
'msg_id': '',
}
data = _update_params(defaults, overrides)
return post(data) | 56464a4c7d8852977a16dff26de6596557078559 | 58,292 |
def unescape_html(html):
"""
*Unescape a string previously escaped with cgi.escape()*
**Key Arguments:**
- ``dbConn`` -- mysql database connection
- ``log`` -- logger
- ``html`` -- the string to be unescaped
**Return:**
- ``html`` -- the unescaped string
"""
###... | cafa4eb7ecc68b6221250947173c579e125ede07 | 58,293 |
def get_lth_sparsity(save_round, n_rounds, target_sparsity, end_epoch):
"""
save_round: when to save the weight; 1 onwards
n_rounds: number of pruning cycles to do
target_sparsity: the sparsity percentage to achieve by the end of the iteration
end_epoch: total number of epochs to train for where pruning is el... | b4bae2bbd53858f1daa177bbf242c72c3a243e33 | 58,294 |
def is_connected_to_prev(res1, res2) -> bool:
"""
Return the bond distance between two residues using Numpy array math.
:param res1: Bio.PDB.Residue.Residue
:param res2: Bio.PDB.Residue.Residue
:rtype: float
"""
distance = atomic_distance(res1, res2, 'N', 'C')
if distance <= float(1.8):
... | f181bd84cb509b069c4b66d492ac11fce2921517 | 58,295 |
def get_lr(optimizer):
"""get learning rate from optimizer
Args:
optimizer (torch.optim.Optimizer): the optimizer
Returns:
float: the learning rate
"""
for param_group in optimizer.param_groups:
return param_group['lr'] | fc8293cc29c2aff01ca98e568515b6943e93ea50 | 58,296 |
import os
import json
def get_saved_token(client_id: str):
"""
Checks a local directory for a file containing an auth token
If present, check the token hasn't expired, otherwise return it
Raises exceptions if the token directory is missing,
or if there is no token file,
or if the token has ex... | b24d6035405e8f1023aa7fc31bf4c84146e29619 | 58,297 |
def autodetect_format(content: str) -> str:
"""Return format identifier for given fragment or raise FormatAutodetectionError."""
formats = set()
for impl in FORMAT_IDENTIFIER_TO_FORMAT_CLASS.values():
guess = impl.guess_format(content)
if guess is not None:
formats.add(guess)
... | b4bac8830b23c1b048bfdd90686f8891ce10cb4a | 58,298 |
import json
def create_index(es, indexname, mapping=None):
"""
Create a index based upon the configured base indexname. It will increment an appendend 5 digit number to version the different index instances.
Args:
es : elasticsearch instance
indexname (str): configured base indexname
... | 28eec9c0c81a8735e3308d414165e77b3f2f4534 | 58,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.