content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _strategies(min_difficulty=None, max_difficulty=None):
"""DOCUMENT ME!!!"""
return draw(one_of(
_global_strategy_lookup.items()[min_difficulty : max_difficulty]
)) | a447a63d9739897e9a3e9d2987542bb4ccf485f4 | 3,635,100 |
def imag(z):
"""
Returns the imaginary part of z.
>>> imag(2+3j)
3.0
If the input is a number, a number is returned:
>>> isinstance(imag(2+3j), float)
True
Can be used with arrays, too:
>>> imag(np.array([1+10j, 2+20j, 3+30j]))
array([ 10., 20., 30.])
"""
return conte... | 82385e71479e09b4676daedb26c6a82d2d51d9fd | 3,635,101 |
from typing import Callable
from typing import Sequence
def apply(f: Callable[[str], B_monoid], description: str) -> Parser[B_monoid]:
"""
A shortcut for ``item(description).apply(f)``.
In contrast to :py:meth:`Parser.apply`, this function spares ``f``
the trouble of outputting a :py:class:`Result<do... | 0de89f6b9db794ace5244e03d37e3b233bcfe385 | 3,635,102 |
def fit_normalized_gaussian_process(X, y, nu=1.5):
"""
We fit a gaussian process but first subtract the mean and divide by stddev.
To undo at prediction tim, call y_pred = gp.predict(X) * y_stddev + y_mean
"""
gp = gaussian.GaussianProcessRegressor(
kernel=gaussian.kernels.Matern(nu=... | 7a2a17fcaaf79f8395d697cf8cf91a883da125be | 3,635,103 |
def choices_on_ballots(L, printing_wanted=False):
"""
Return a dict of the choices shown on ballot list L, with counts.
Args:
L (list): list of ballots
Returns:
C (dict): dict of distinct strings appearing in ballots in L,
each with count of number of occurren... | e489eef70ee0efd0f40f5163c2135a5549c8893e | 3,635,104 |
def prime_mask(n: int) -> np.ndarray:
"""Generate boolean array of length N, where prime indices are True."""
primes = np.ones(n, dtype=bool)
primes[:2] = False
for i in range(2, n):
if primes[i]:
# Mark all multiples of i as composite
composite = 2 * i
while ... | cd8d64e35b440e92727a76508f52e1b6540bc461 | 3,635,105 |
from django_pg_returning import ReturningQuerySet
def _bulk_update_no_validation(model, values, conn, key_fds, upd_fds, ret_fds, where):
# type: (Type[Model], TUpdateValuesValid, TDatabase, Tuple[FieldDescriptor], Tuple[FieldDescriptor], Optional[Tuple[FieldDescriptor]], Tuple[str, tuple]) -> Union[int, 'Returnin... | 424613c09a9b3a7697bce01ae1e576bfe6c01f39 | 3,635,106 |
def dmm_exitcell(subidxs_ds, subuparea, subshape, shape, cellsize, mv=_mv):
"""Returns exit highres cell indices of lowres cells according to the
double maximum method (DMM).
Parameters
----------
subidxs_ds : 1D-array of int
highres linear indices of downstream cells
subuparea : 1D-arr... | e8c10e39c07cdcdd245653c05ed456f049b58e89 | 3,635,107 |
import re
def cast_to_decimal(amount: str):
"""Cast the amount to either an instance of Decimal or None.
Args:
amount: A string of amount. The format may be '¥1,000.00', '5.20', '200'
Returns:
The corresponding Decimal of amount.
"""
if amount is None:
return None
amou... | c043f7449b42154e7dcfba1b2ed9b64feb9ffece | 3,635,108 |
import json
def test_csrf_exempt(csrf_app, csrf):
"""Test before CSRF protect decorator."""
# Test `exempt` as a function passing the name of the view as string
csrf.exempt('conftest.csrf_test')
with csrf_app.test_client() as client:
res = client.post(
'/csrf-protected',
... | fcc7bd34add8da223b5a89d644949d5fe930718f | 3,635,109 |
def ITERATIVETEST_Variation_Of_Input_Parameter_inUseSecondPlane():
"""Tests variation of input value at field "inUseSecondPlane"."""
Logging.infoHTML( "<b>ToDo: Add more \"TestData\" objects to maximize variations!</b>" )
testDataVariations = {
"Variation_1" : __getTestDataVariation1_inUseSecondPlane(),
}
... | 5d53797367154cc0315c6b5ded3fab8cc22cea5d | 3,635,110 |
def wave_energy(F, df, rhow=1000, g=9.8):
"""Returns total wave energy."""
return rhow * g * np.sum(F * df) | 663299aa6732c034fe494cc7353d05f673329ec5 | 3,635,111 |
def get_x_vector(N, K):
"""
Return x from given order of WH matrix and K
:param N: Order of WH matrix
:param K: Number of ones
:return: numpy.ndarray
"""
x = np.zeros(N)
random_pos = np.random.choice(
np.arange(0, N), K, replace=False
)
x[random_pos] = 1
return x | 90f90f09d6d2516c9558938514bd965d719f65dc | 3,635,112 |
import random
def person_split(whole_data, train_names, valid_names, test_names):
"""Split data by person."""
random.seed(30)
random.shuffle(whole_data)
train_data = []
valid_data = []
test_data = []
for idx, data in enumerate(whole_data): # pylint: disable=unused-variable
if da... | ef0475fbc515af1352401c576be27351cda81a35 | 3,635,113 |
def budget_delete(request, slug):
"""
Delete a budget object.
"""
budget = get_object_or_404(Budget.active.all(), slug=slug)
if request.POST:
if request.POST.get('confirmed'):
budget.delete()
return HttpResponseRedirect(reverse('budget:budget_budget_list'))
context = ... | 706e578bba7d33049188f2c9f62a87f39d528c1b | 3,635,114 |
def get_connection_name(db_connection_id):
"""
To give data base connection name if data base exist.
Args:
db_connection_id(int):data base connection id.
Returns:
Returns data base name if exist or return message saying that db not
exist.
"""
if db_connection_id == APIM... | 8617d83012548daa7f8691899c1b8ec208dce101 | 3,635,115 |
import torch
def cal_area(group_xyz):
"""
Calculate Area of Triangle
:param group_xyz: [B, N, K, 3] / [B, N, G, K, 3]; K = 3
:return: [B, N, 1] / [B, N, G, 1]
"""
pad_shape = group_xyz[..., 0, None].shape
det_xy = torch.det(torch.cat([group_xyz[..., 0, None], group_xyz[..., 1, None], torc... | bbafa626c1833b5bde81303b4038081dae7bc965 | 3,635,116 |
import copy
def detect_edges_better(img: Image, threshold: int) -> Image:
"""
Returns a copy of an image with the pixels changed to either black
or white based on the contrast of the pixel above, below, or to the right
based on the inputed threshold.
Author: Anita Ntomchukwu
>>>dete... | 97ed5a1404599586ac427a6e54a6d1f9f91ff53b | 3,635,117 |
import functools
def lru_cache(timeout=10, maxsize=128, typed=False):
"""Least Recently Used Cache- cache the result of a function.
Args:
timeout
How many seconds to cache results for.
maxsize
The maximum size of the cache in bytes
typed
When `Tr... | 82fb0732583707064d773e6264d612ee4cd61b76 | 3,635,118 |
def _mutator_plugins_bucket_name():
"""Mutator plugins bucket name."""
return environment.get_value('MUTATOR_PLUGINS_BUCKET') | 1d5aabc949947a8b5ca5c89a9c709f8575ecd063 | 3,635,119 |
def densenet_imagenet_169(inputs, is_training=True, num_classes=1001):
"""DenseNet 121."""
depths = [6, 12, 32, 32]
growth_rate = 32
return densenet_imagenet_model(inputs, growth_rate, depths, num_classes,
is_training) | 1fdb578b09d6ad54301cce67beccaf22e1e221e7 | 3,635,120 |
import logging
import os
def delete_todo(request, todo_id):
"""Delete one to_do task"""
logging.info(f'{os.getenv("ID_LOG", "")} Deleting the element with id={todo_id}')
TodoItem.objects.get(id=todo_id).delete()
logging.info(f'{os.getenv("ID_LOG", "")} Todo task with id={todo_id} successfully deleted'... | d772610e1d30120b21ba1ba7b724d24eb2736391 | 3,635,121 |
def get_jquery_min_js():
"""
Return the location of jquery.min.js. It's an entry point to adapt the path
when it changes in Django.
"""
return 'admin/js/vendor/jquery/jquery.min.js' | 86315a0992dc181435f6899b24eb93abc0a47941 | 3,635,122 |
def getLines_from_file(path, clean=False):
""" returns the table of lines from text file """
text = getText_from_file(path)
if not text:
return None
text = text.split("\n")
if clean:
text = [t.strip(' \t') for t in text]
return text | 26bc682c58c09cc875a071b735304bdba320e4db | 3,635,123 |
def channel_shift(img, random_state):
"""
Adds random brightness to image.
Parameters
------
img: np.array
Image array [CWH].
random_state: np.random
Randomized state.
Returns
------
img: np.array
Image array [CWH].
"""
shift_val = int(random_state.u... | d490d3cdd49ba0e918e5cbef76ed14b13cb9f4a4 | 3,635,124 |
def quicksort(inputArray):
"""input: array
output: new sorted array
features: stable
efficiency O(n^2) (worst case), O(n log(n)) (avg case), O(n) (best case):
space complexity: O(n)
method:
Pick the last element in the array as the pivot.
Separate values into arrays based on whether they... | 2a8036ba038f4f7a8e817175d9a810184911ce4b | 3,635,125 |
def get_paypal_currency_code(iso_currency_code):
"""
Function will map the currency code to paypal currency code
"""
if iso_currency_code == 124:
return 'CAD'
if iso_currency_code == 840:
return 'USD'
if iso_currency_code == 484:
return 'MXN'
return 'CAD' | af9579a6d12e44dd3263956eb41ece9eadeacaee | 3,635,126 |
def get_num_audio_tracks(mpeg4_file, in_fh):
""" Returns the number of audio track in the input mpeg4 file. """
num_audio_tracks = 0
for element in mpeg4_file.moov_box.contents:
if (element.name == mpeg.constants.TAG_TRAK):
for sub_element in element.contents:
if (sub_ele... | fcd650290bc041d9db61912ec654d88dbcdd6955 | 3,635,127 |
import logging
def pandas_pivot(filename):
"""Used to import a csv file to a pandas data frame,
so the data can be pivoted and aggregated by date"""
if filename == None:
raise FileNotFoundError("File is not found.")
else:
logging.info("Reading .csv and writing to .xlsx file...")
... | c9d2d4b738ee57b7e7b3689c884c004e21eaebd5 | 3,635,128 |
def add_user_session(username):
"""Generates a token for a user and adds that token and username to the sesssions."""
token = b64encode(uuid4().bytes).decode()
con, cur = create_con()
cur.execute('INSERT INTO sessions(username, token) VALUES (?, ?);', (username, token))
con.commit()
cur.close()
... | bd4c57a06a1a2da500e43266bf3b96a0833f6070 | 3,635,129 |
def array_input(f):
""" decorator to provide the __call__ methods with an array """
@wraps(f)
def wrapped(self, t):
t = np.atleast_1d(t)
r = f(self, t)
return r
return wrapped | 58cb8c3fb1ef5b50c6f983646efea2410a0e84a7 | 3,635,130 |
import socket
def get_own_ip():
"""
returns own ip
original from:
https://stackoverflow.com/a/25850698/3990615
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 1)) # connect() for UDP doesn't send packets
local_ip_address = s.getsockname()[0]
return l... | 53195ee3880a9025ba525c120f2e4ccc0e676a93 | 3,635,131 |
def get_sle_after_datetime(self):
"""get Stock Ledger Entries after a particular datetime, for reposting"""
return get_stock_ledger_entries(self.previous_sle or frappe._dict({
"item_code": self.args.get("item_code"), "warehouse": self.args.get("warehouse")}),
">", "asc", for_update=True, check_s... | 29c813507eab3c1f76df0acab49b374681f95f01 | 3,635,132 |
import time
def chaperone(method):
"""
Wraps all write, read and query methods of the adapters; monitors and handles communication issues
:param method: (callable) method to be wrapped
:return: (callable) wrapped method
"""
def wrapped_method(self, *args, validator=None, **kwargs):
... | ec224565208428c9daacdb2e3d15ae0dbb4ee9b1 | 3,635,133 |
def mc_wheeny_purification(p,s):
""" The McWheeny Prurification for an idempotent matrix p in a basis with
overlaps S
"""
return (3 * np.dot(np.dot(p, s), p) - np.dot(np.dot(np.dot(np.dot(p, s), p), s), p)) / 2 | 10e95ca413340262b2209a28da4e29032f0ae722 | 3,635,134 |
def shutdown():
"""
Shuts down the Pi
"""
auth = auth_active()
if auth["status"] and "username" not in session:
flash(auth["msg"], "error")
return redirect(url_for("index"))
shutdown_pi()
return redirect(url_for("index")) | d8f4ecf7a7ac23e012ab02d35b418bc203b387a4 | 3,635,135 |
import os
def _set_up_model_thermo_rxns(base_df: pd.DataFrame, rxns_order: list, rxn_list: list, use_equilibrator:bool,
file_bigg_kegg_ids: str = None, pH: float = 7.0, ionic_strength: float = 0.1) \
-> pd.DataFrame:
"""
Fills in the thermoRxns sheet on the excel GRASP in... | 587376614ea7dc5f0a2a033814e8ea53700878ca | 3,635,136 |
def load_ref_system():
""" Returns cyclopentane as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
C -0.8201 -1.0104 -0.1068
C -1.2133 0.4696 0.0650
C 0.0767 1.2934 -0... | 3691043f20a9313d2db67881d75d9558ba68370f | 3,635,137 |
def load_audio_channel(delay, attenuation, pytorch=True):
"""
Return an art LFilter object for a simple delay (multipath) channel
If attenuation == 0 or delay == 0, return an identity channel
Otherwise, return a channel with length equal to delay + 1
NOTE: lfilter truncates the end of the echo... | 684490c3fe7416f6059263eb64934b7473efe364 | 3,635,138 |
def slices(img, shape=[3, 4]):
"""
create tiled image with multiple slices
:param img:
:param shape:
:return:
"""
sh = np.asarray(shape)
i_max = np.prod(sh)
allimg = np.zeros(img.shape[-2:] * sh)
for i in range(0, i_max):
# i = 0
islice = round((img.shape[0] / fl... | d2223a2f7a6b1a704288b682b878c189d6538262 | 3,635,139 |
def getRawInput(display):
"""
Wrapper around raw_input; put into separate function so that it
can be easily mocked for tests.
"""
return raw_input(display) | 9eaf45446caa8794b79b908ef8e9eec50cbb646a | 3,635,140 |
import os
def path_completer(text, state):
"""
Completer method for system paths.
"""
return [x if os.path.isfile(x) else (x + os.sep)
for x in sorted_glob(text + '*')][state] | 873a7ff489c9004fc9ae03b129b4c60aceabf34d | 3,635,141 |
import PIL
def prepare_input_image(img_fpath):
"""Read and prepare input image as AlexNet input."""
# Read input image as 3-channel 8-bit values
pil_img = PIL.Image.open(img_fpath)
# Resize to AlexNet input size
res_img = pil_img.resize((IMG_SIZE, IMG_SIZE), PIL.Image.LANCZOS)
# Convert to ... | 1e177ddd17a3858a6f6c063728037c0b641e693f | 3,635,142 |
def sparse_spectral_matrix(c, ell, em, ess=-2):
"""
Combine functions to create the sparse matrix to be solved.
Inputs:
c (float): a * omega
ell (int): swsh mode number
em (int): mode number
ess (int) [-2]: spin number
Returns:
band_matrix (sparse<float>): spars... | cb2708c2a95a11e0f7d0129d6343886b202fb9ed | 3,635,143 |
import re
def preprocess_text(text, lower=True):
""" Prepsocess text.
"""
text = text.replace("ä", "äe").replace("ö", "oe").replace("ü", "ue").replace("ß", "ss")
# Remove punctuations and numbers
text = re.sub("[^a-zA-Z]+", " ", text)
# Single character removal
text = re.sub(r"\b[a-zA-Z]\b... | fb0c982b8ce3dce2d78918dd8a6ce469a33c93eb | 3,635,144 |
def decode_aes256_base64_auto(data, encryption_key):
"""Guesses AES cipher (EBC or CBD) from the length of the base64 encoded data."""
assert isinstance(data, bytes)
length = len(data)
if length == 0:
return b''
if data[0] == b'!'[0]:
return decode_aes256_cbc_base64(data, encryption... | 71292d967cce08fc344ac787dc2bbcc7fbbd72a2 | 3,635,145 |
def get_TS(
norm_sh,
mass,
# Msh,
# csh,
bsh,
vsh,
spec_sh_interp,
# bsh_range,
N_samples,
n_nu,
nthetas,
ext_bool,
ext_unc,
# N_track_bins,
spec_halo_interp,
spec_1a,
spec_neutrons,
spec_nu,
indep_index,
wimp_masses,
Gaussian_likelihoo... | 0f5d90b92412d75550c5bc6936dbdfc27f7e3951 | 3,635,146 |
import collections
def rotate(start):
"""Rotate the orientation clockwise one increment from the starting
orientation.
Args:
start: The starting orientation.
Returns:
The orientation one increment clockwise from the start.
"""
orientations = collections.deque([NE, NW, W, SW, S... | 70a7bdc6fc28355d9bdc0462bd089d52b08d9453 | 3,635,147 |
def make_wcs(shape, galactic=False):
"""
Create a simple celestial `~astropy.wcs.WCS` object in either the
ICRS or Galactic coordinate frame.
Parameters
----------
shape : 2-tuple of int
The shape of the 2D array to be used with the output
`~astropy.wcs.WCS` object.
galacti... | fec4b247875f6bbecc61f8db9973da3f88fc6ff3 | 3,635,148 |
def _is_shape(expected_shape, actual_tensor, actual_shape=None):
"""Returns whether actual_tensor's shape is expected_shape.
Note that -1 in `expected_shape` is recognized as unknown dimension.
Args:
expected_shape: Integer list defining the expected shape, or tensor of same.
actual_tensor: Tensor to te... | e3ae49991e3f224ef58b3f41cc5d520fd04449cf | 3,635,149 |
def separate_last_day(df_):
"""
takes a dataset which has the target and features built
and separates it into the last day
"""
# take the last period
last_period = df_.iloc[-1]
# the last period is now a series, so it's name will be the timestamp
training_data = df_.loc[df_.i... | 0e7e7ea31a55c6f648e218b44845290689e344ab | 3,635,150 |
from sklearn.neighbors import KernelDensity
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import LeaveOneOut
def KDEbounded(x_d,x,bandwidth=np.nan,lowbnd=np.nan,uppbnd=np.nan,kernel = 'gaussian'):
"""Estimate the probability by Kernel Density Estimation
If bandwidth is np.nan,... | 5970a59ee7c38b56e86d44a684baf660b36dba3c | 3,635,151 |
def update(movie_id, **options):
"""
updates the info of given movie.
it returns a value indicating that update is done.
:param uuid.UUID movie_id: movie id.
:keyword bool content_rate: update content rate.
defaults to True if not provided.
:keyword bool count... | f7efffac6ca0cbd8d49d65135ae284b78d6b5dd6 | 3,635,152 |
from typing import Tuple
def validate_sig_integrity(signer_info: cms.SignedData,
cert: x509.Certificate,
expected_content_type: str,
actual_digest: bytes) -> Tuple[bool, bool]:
"""
Validate the integrity of a signature for a part... | 9cf3164ffb9b1c4952d15537e22313e82fe797ba | 3,635,153 |
def get_c_header_path(*args):
"""get_c_header_path(char buf) -> ssize_t"""
return _idaapi.get_c_header_path(*args) | d9cca8050dac372953ef59f4df54787e7c2e3591 | 3,635,154 |
from datetime import datetime
def str_to_datetime(str_datetime: str) -> datetime.datetime:
"""
WebAPIがサポートしているISO8601の文字列をdatetime objectに変換します。
datetime objectはawareです。
Args:
str_datetime (str): ISO8601の文字列(例: ``2021-04-01T01:23:45.678Z`` )
Returns:
datetime object
"""
#... | aa1324beb7889dc5a390e46678cdac1515091805 | 3,635,155 |
def uncertainty_separation_variance(predicted_distribution, true_labels):
"""Total, epistemic and aleatoric uncertainty based on a variance measure
B = batch size, N = num predictions
Note: if a batch with B samples is given,
then the output is a tensor with B values
The true targets argument is si... | 16dfb2260b972e1615e0e9b62ddd11edf3ff4e52 | 3,635,156 |
def cubic_spline_breaksToknots(bvec):
"""
Given breakpoints generated from _cubic_spline_breaks,
[x0, x0, x0, x0, x1, x2, ..., xN-2, xf, xf, xf, xf],
return the spline knots [x0, x1, ..., xN-1=xf].
This function ``undoes" _cubic_spline_breaks:
knot_vec = _cubic_spline_breaks2knots(_cubic_spline_breaks(knot_vec))
... | 15a73dea4b001e05bd67075ec21e15247db1f031 | 3,635,157 |
from datetime import datetime
def as_iso_date(wx_date):
""" Convert a QDate object into and iso date string.
"""
day = wx_date.GetDay()
month = wx_date.GetMonth() + 1 # wx peculiarity!
year = wx_date.GetYear()
return datetime.date(year, month, day).isoformat() | 2c74aa2a16ff46089d1dfab30abfef6396c304e9 | 3,635,158 |
from datetime import datetime
def should_certificate_be_visible(
certificates_display_behavior,
certificates_show_before_end,
has_ended,
certificate_available_date,
self_paced
):
"""
Returns whether it is acceptable to show the student a certificate download
link for a course, based on... | 76ebaa5f924d5c4209859a6047f5866c7eb4e6a6 | 3,635,159 |
def svn_repos_invoke_freeze_func(*args):
"""svn_repos_invoke_freeze_func(svn_repos_freeze_func_t _obj, void * baton, apr_pool_t pool) -> svn_error_t"""
return _repos.svn_repos_invoke_freeze_func(*args) | 5145309e8ab7c1d8c7ab22ebe9b463f6f7c1f5b2 | 3,635,160 |
from typing import Union
from pathlib import Path
def load_results(
files_or_dir: Union[str, list, Path],
scoring_key: str = "balanced_accuracy",
average_results: bool = True,
) -> pd.DataFrame:
"""Load prediction results from *results.csv"""
# Create Dataframes from Files
files_or_dir = _hand... | e4668b0e2881a5acff8156f1e1d65687105dc840 | 3,635,161 |
def _tflite_convert_verify_op(tflite_convert_function, *args, **kwargs):
"""Verifies that the result of the conversion contains Gelu op."""
result = tflite_convert_function(*args, **kwargs)
tflite_model_binary = result[0]
if not result[0]:
tf.compat.v1.logging.error(result[1]) # stderr from running tflite_... | 430cf0068f3c144fc26a09f56b0c90bcd1c8fd35 | 3,635,162 |
def tamper_nt_response(data, vars):
"""The connection is sometimes terminated if NTLM is successful, this prevents that"""
print("Tamper with NTLM response")
nt_response = vars["nt_response"]
fake_response = bytes([(nt_response[0] + 1 ) % 0xFF]) + nt_response[1:]
return data.replace(nt_response, fak... | cf2acad343f457b5ea5529d91653169d2093d500 | 3,635,163 |
def get_banned_per_category(cat: int, w_id: int) -> bool:
"""
Determine if a weapon is banned.
:param cat: Category of the weapon.
:param w_id: Id of the weapon.
:return: True if the weapon is banned, False if not.
"""
d = dict()
# Edit this function to change the ruleset:
# To ban ... | e55ec72e1b672f6f31f296df749b179614f08a42 | 3,635,164 |
def pascal_classes():
"""Get Pascal VOC classes
:return: mapping from class name to an integer
"""
return {
'aeroplane': 1, 'bicycle' : 2, 'bird' : 3, 'boat' : 4,
'bottle' : 5, 'bus' : 6, 'car' : 7, 'cat' : 8,
'chair' : 9, 'cow' ... | e6f488df00075ed6977024466e0eebb995b98605 | 3,635,165 |
def get_duty_cate_score(chosen_duty_list: list) -> pmag.MagicDict:
"""
Get duty score of each category.
We don't calculate each post score, we think what a man like can be
described on category level.
Parameters
----------
chosen_duty_list: list
Duty list chosen by user, each word w... | 0b4fe97499be40f6058465aa3454a2e2654e9549 | 3,635,166 |
from typing import Optional
def offset(xs: Optional[ColumnSize] = None,
sm: Optional[ColumnSize] = None,
md: Optional[ColumnSize] = None,
lg: Optional[ColumnSize] = None,
xl: Optional[ColumnSize] = None) -> Optional[str]:
"""
Arguments:
xs: Offset (in column... | 7b2cc1c96deda1cdbea02e44415c98ef3ba1a34d | 3,635,167 |
def play_sound(data):
"""
Parameters
----------
data: dict
Returns
-------
"""
if 'sound_name' in data:
clientUtils.sound(data.get('sound_name'))
return ""
return "Je ne trouve pas le son demandé" | 3206d44682581458d62ebda2c90597d10aff9fab | 3,635,168 |
async def async_setup(hass, config):
"""Start the Fortigate component."""
conf = config[DOMAIN]
host = conf[CONF_HOST]
user = conf[CONF_USERNAME]
api_key = conf[CONF_API_KEY]
devices = conf[CONF_DEVICES]
is_success = await async_setup_fortigate(hass, config, host, user, api_key, devices)
... | 0ed909bc2e18a242131bee458a4d7b0082576fb4 | 3,635,169 |
import select
from operator import and_
def get_snapshot_usages_project(meta, project_id):
"""Return the snapshot resource usages of a project"""
snapshots_t = Table('snapshots', meta, autoload=True)
snapshots_q = select(columns=[snapshots_t.c.id,
snapshots_t.c.volume_s... | 8185cd670d595f07d739d9c9e9e52b23eace432c | 3,635,170 |
import contextlib
def compute_patch_embeddings(
samples,
model,
patches_field,
embeddings_field=None,
force_square=False,
alpha=None,
handle_missing="skip",
batch_size=None,
num_workers=None,
skip_failures=True,
):
"""Computes embeddings for the image patches defined by ``p... | 371d4ae24e1e451b0e9970b78d43c4b8791d0e3c | 3,635,171 |
import os
import logging
def get_exact_file_name(file_name, file_path):
"""
:param file_name:
:param file_path:
:return:
"""
for root, dirs, files in os.walk(file_path):
for name in files:
logging.debug("Checking {0}".format(name))
if str(name).startswith(file_... | 7b7e72a5d2d5001f7452347f4bebcff9a9a9d0c3 | 3,635,172 |
def getRetRange( rets, naLower, naUpper, naExpected = "False", s_type = "long"):
"""
@summary Returns the range of possible returns with upper and lower bounds on the portfolio participation
@param rets: Expected returns
@param naLower: List of lower percentages by stock
@param naUpper: List of uppe... | 7e51851ab82d9da6ff670ef52b09464190e8ee3c | 3,635,173 |
def landing():
"""
Landing page - either shows login/sign-up or redirects to dashboard
"""
if g.uid:
return redirect("/dashboard")
else:
return render_template("landing.html", menu_item="login") | 4ca27c76ca76bd762dc24ba2fa6a64cc06b355d3 | 3,635,174 |
def pi_estimator(iterations: int):
"""An implementation of the Monte Carlo method used to find pi.
1. Draw a 2x2 square centred at (0,0).
2. Inscribe a circle within the square.
3. For each iteration, place a dot anywhere in the square.
3.1 Record the number of dots within the circle.
4. After a... | 65475038c3655ea9e093b82b64eb1086f81a1ba8 | 3,635,175 |
from typing import Optional
from typing import Sequence
def get_projects(filters: Optional[Sequence[pulumi.InputType['GetProjectsFilterArgs']]] = None,
sorts: Optional[Sequence[pulumi.InputType['GetProjectsSortArgs']]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> Awaitable... | fa282a9420eb30633c4f354963343d46d77d4c2f | 3,635,176 |
def get_market_impact(
portfolio_name,
start_date,
end_date,
denominator="reference_equity",
model_id=DEFAULT_MODEL_ID,
):
"""Get market impact for each daily change of a portfolio in terms of dollars and percent of a denominator, either reference_equity or gmv.
Note that this ignores change... | fa74d8aad26bd4bb759a115cfc51a8fbc21b9353 | 3,635,177 |
def importH5(name, df):
"""
"""
f = h5py.File(name,'r')
data = f.get(df)
data = np.array(data)
oldShape = data.shape
data = np.swapaxes(data, 1, 2)
print 'convert shape %s to %s' % (oldShape, data.shape)
return data | 4c6f14fec8497f965c2b14a153bd2f6f21f429c7 | 3,635,178 |
def svc_longi_u_polar(vr,vpsi,vz,gamma_l=-1,R=1,m=0,ntheta=180,polar_out=False):
""" Raw function, not intended to be exported.
Induced velocity from a skewed semi infinite cylinder of longitudinal vorticity.
Takes polar coordinates as inputs, returns velocity either in Cartesian (default) or polar.
Th... | c4d1713ef08c4672bfefba0e11d2daca121032f4 | 3,635,179 |
import requests
import json
import logging
def _unremediate_email_o365_EWS(emails):
"""Remediates the given emails specified by a list of tuples of (message-id, recipient email address)."""
assert emails
assert all([len(e) == 2 for e in emails])
result = [] # tuple(message_id, recipient, result_code,... | 15c4b07b0f45d0792f9632cdf3312f8ab6025e44 | 3,635,180 |
def compute_feedback_score(user_search, result):
"""
Compute the feedback score
Input: user_search: keyword entered by the user
result: proposed result to the user
Output: Feedback score, default value to 0.4 if no feedbacks available
"""
# This old version take into account when ... | 33e9e70111824e6eff60214cc0b55778a0cc5108 | 3,635,181 |
def filenames_per_batch (gen):
""" arg = name of the data generator (datagen.flow_from_dataframe) """
img_paths_per_batch=[]
batches_per_epoch = gen.samples // gen.batch_size + (gen.samples % gen.batch_size > 0)
for i in range(batches_per_epoch):
batch = next(gen)
current_inde... | 23ea9dfbbfe64fc51796af22c83a470847c9f698 | 3,635,182 |
def coarsemask_head_generator(params):
"""Generator function for ShapeMask coarse mask head architecture."""
head_params = params.shapemask_head
return heads.ShapemaskCoarsemaskHead(
head_params.num_classes,
head_params.num_downsample_channels,
head_params.mask_crop_size,
head_params.use_c... | 6dea83780e2b0169f71401ca3577d9c4383280f0 | 3,635,183 |
def ethtype_to_int_priv_pubv(priv, pubv):
"""
将 priv 和 pubv 转换为 weidentity 支持的格式(十进制)
:param priv: type: bytes
:param pubv: type: hex
:return: priv int, pubv int
"""
private_key = int.from_bytes(priv, byteorder='big', signed=False)
public_key = eval(pubv)
return {"priv": str(private... | 763a284015029a43257061818634b50d69417de5 | 3,635,184 |
import argparse
def build_arg_parse() -> argparse.ArgumentParser:
"""Builds the arguments parser."""
parser = argparse.ArgumentParser(
description="This script updates the python extension micro version based on the release or pre-release channel."
)
parser.add_argument(
"--release",
... | 8151e3366c7a2acecb7f40cb05684af368dc9e1f | 3,635,185 |
import time
def solver(I, a, L, Nx, F, T, theta=0.5, u_L=0, u_R=0,
user_action=None):
"""
Solve the diffusion equation u_t = a*u_xx on (0,L) with
boundary conditions u(0,t) = u_L and u(L,t) = u_R,
for t in (0,T]. Initial condition: u(x,0) = I(x).
Method: (implicit) theta-rule in time.
... | 99da0c06fcbbc36515b6b4aee23b4b3b4eff0032 | 3,635,186 |
def create_clean_df_from_cloud_json(js):
""" Given a json downloaded on the cloud from get_datasource_data or get_location_data, returns a corrected df"""
df = json_to_df(js)
df_data = set_timestamp_df_index(df)
for col in df_data.columns:
if col[:6] == 'values':
df_data[col] = __pd.... | cdad4f51dd3014a05e9c1e5f5068d344220bccd5 | 3,635,187 |
def tfidf_corpus(docs=CORPUS):
""" Count the words in a corpus and return a TfidfVectorizer() as well as all the TFIDF vecgtors for the corpus
Args:
docs (iterable of strs): a sequence of documents (strings)
Returns:
(TfidfVectorizer, tfidf_vectors)
"""
vectorizer = TfidfVectorizer()
... | 401b9e0ed9321e7a20f9efeb303b5c8f51b70a75 | 3,635,188 |
def svn_utf_cstring_from_utf8_string(*args):
"""svn_utf_cstring_from_utf8_string(svn_string_t const * src, apr_pool_t pool) -> svn_error_t"""
return _core.svn_utf_cstring_from_utf8_string(*args) | 63be2c2624a66d7221845e8c0546f58c5f2f952a | 3,635,189 |
def squint(t, r, orbit, attitude, side, angle=0.0, dem=None, **kw):
"""Find squint angle given imaging time and range to target.
"""
assert orbit.reference_epoch == attitude.reference_epoch
p, v = orbit.interpolate(t)
R = attitude.interpolate(t).to_rotation_matrix()
axis = R[:,1]
# In NISAR ... | 0172b4f525e5738740eb0c948b650bf3c1abbb11 | 3,635,190 |
def get_cmfgenNoRot_atmosphere(metallicity=0, temperature=30000, gravity=4.14):
"""
metallicity = [M/H] (def = 0)
temperature = Kelvin (def = 30000)
gravity = log gravity (def = 4.14)
"""
sp = pysynphot.Icat('cmfgenF15_noRot', temperature, metallicity, gravity)
# Do some error checking
... | a188661f24083b4ab29f83559dac6011eee4d7aa | 3,635,191 |
def _SanitizeDoc(doc, leader):
"""Cleanup the doc string in several ways:
* Convert None to empty string
* Replace new line chars with doxygen comments
* Strip leading white space per line
"""
if doc is None:
return ''
return leader.join([line.lstrip() for line in doc.spli... | 7ca6f17296c9b23c05239092e28c8d6b4df7c725 | 3,635,192 |
import json
import yaml
def load_file(file_path: str):
"""Loads a file using a serializer which guesses based on the file extension"""
if file_path.lower().endswith('.json'):
with open(file_path) as input_file:
return json.load(input_file)
elif file_path.lower().endswith('.yaml') or fi... | 1b9c3278bd40a23e142590952d95876401c5f99b | 3,635,193 |
import json
def list_assets(event, context):
"""
Get a list of assets of the given type.
Query string parameters
-----------------------
asset_type (required):
The type of asset to get. Allowed values are found in the
``asset_map`` dict.
"""
query_params = event.get('query... | e0cf59d2ee275dc9c6610f30daacc91a9042723a | 3,635,194 |
def pop_execute_query_kwargs(keyword_arguments):
""" pop the optional execute query arguments from arbitrary kwargs;
return non-None query kwargs in a dict
"""
query_kwargs = {}
for key in ('transaction', 'isolate', 'pool'):
val = keyword_arguments.pop(key, None)
if val is not No... | d4ae2df3158660f62e21153d943922692f633b76 | 3,635,195 |
import time
import json
def decompress(target_file):
"""This is the decompression section"""
# extract binary string from a file
start_decompress = float(time.process_time()) # start measure time in this line to check processing time
binary_file_name = target_file
filename = target_file
wit... | 0491bdcb3b4555b42705b2a3a02fe3bf98ca6bb6 | 3,635,196 |
def resize(img, new_shape, interpolation=1):
"""
img: [H, W, D, C] or [H, W, D]
new_shape: [H, W, D]
"""
type = 1
if type == 0:
new_img = skt.resize(img, new_shape, order=interpolation, mode='constant', cval=0, clip=True, anti_aliasing=False)
else:
shp = tuple(np.array(new_s... | 5754f8e61cca50927fc7ad65d4f3122c1718bcc1 | 3,635,197 |
import logging
def get_oneview_client(session_id=None, is_service_root=False):
"""Establishes a OneView connection to be used in the module
Establishes a OV connection if one does not exists.
If one exists, do a single OV access to check if its sill
valid. If not tries to establish a new ... | eeb5c80bbced6deb6188878ff646ef0a7a54a184 | 3,635,198 |
def SegmentByPeaks(data, peaks, weights=None):
"""Average the values of the probes within each segment.
Parameters
----------
data : array
the probe array values
peaks : array
Positions of copy number breakpoints in the original array
Source: SegmentByPeaks.R
"""
segs =... | 97acb45c320d4da9a3094188239a6442cafe48b1 | 3,635,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.