content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import copy
def generate_output_descriptors(filename_out_base,
max_block_size_voxels,
overlap_size_voxels,
dim_order,
header,
output_type,
... | ebb7ecbc3f3105ee995033fbccccd8f745a6a12d | 3,635,058 |
def clean_data(df):
"""
The function is to clean the data.
Parameters:
df (pandas dataframe): loaded data from load_data function.
Returns:
df (pandas dataframe): cleaned version of the data.
"""
# Create a dataframe of the 36 individual category columns
cate_df = df['categor... | 12706ed7889482b709f33e085d10dc92f0d1bf9e | 3,635,059 |
import math
def squeezenet1_0_fpn_feature_shape_fn(img_shape):
""" Takes an image_shape as an input to calculate the FPN output sizes
Ensure that img_shape is of the format (..., H, W)
Args
img_shape : image shape as torch.Tensor not torch.Size should have
H, W as last 2 axis
Retu... | d56fe3d834bcd9633727defe3ad9a27ea756ed40 | 3,635,060 |
from pathlib import Path
def temp_paths_2(tmp_path_factory):
"""
Makes temporary directories, for testing bak_to_git_2, and populates them
with test files. Returns pathlib.Path objects for each.
"""
temp_path: Path = tmp_path_factory.mktemp("baktogit2")
bak_path = temp_path / "_0_bak"
bak_... | da3b9ef6af7dc04bbc1aadfb3147223564f71458 | 3,635,061 |
def clip_alpha(aj, H, L):
"""
cLips alpha vaLues tHat are greater
tHan H or Less tHan L
"""
if aj > H:
aj = H
if L > aj:
aj = L
return aj | d272e2703c1b6008fc4840e887ce842005dfad62 | 3,635,062 |
def nextfig():
"""Return one greater than the largest-numbered figure currently
open. If no figures are open, return unity.
No inputs or options."""
# 2010-03-01 14:28 IJC: Created
figlist = getfigs()
if len(figlist)==0:
return 1
else:
return max(figlist)+1
retu... | d8a4ec57880f247d243f80e662e1172456551984 | 3,635,063 |
from pathlib import Path
def load_laurent2016():
"""Model dataset for refolded fold
Returns
-------
tuple
pandas data frame with loopstructural dataset and numpy array for bounding box
"""
module_path = dirname(__file__)
data = pd.read_csv(join(module_path, Path('data/refolded_f... | 01a048b4e8748e9cc4e7ef9ea1c1385bfd0faaed | 3,635,064 |
def get_user_best(key: str, user: int, mode: int = 0, limit: int = 10, type_: str = None, type_return: str = 'dict'):
"""Get the top scores for the specified user."""
params = {
'k': key,
'u': user,
'm': mode,
'limit': limit,
'type': type_}
r = req.get(urls['user_best'], params=params)
return from_json(r.text,... | b42357c0ca3553c2cf01624869931748c2df897c | 3,635,065 |
import types
def _copy_fn(fn):
"""Create a deep copy of fn.
Args:
fn: a callable
Returns:
A `FunctionType`: a deep copy of fn.
Raises:
TypeError: if `fn` is not a callable.
"""
if not callable(fn):
raise TypeError("fn is not callable: %s" % fn)
# The blessed way to copy a function. co... | 37fca64ddaadfc8a6a24dce012af2143038cacd2 | 3,635,066 |
from re import T
def ireport():
""" Incident Reports, RESTful controller """
resource = request.function
tablename = "%s_%s" % (module, resource)
table = db[tablename]
# Don't send the locations list to client (pulled by AJAX instead)
table.location_id.requires = IS_NULL_OR(IS_ONE_OF_EMPTY(... | 02cc630ce76336ff3e94021c0378daf48fe6a3bd | 3,635,067 |
import torch
def makenetbn(dims, softmax=True, single=True):
"""A batch-normalizing version of makenet. Experimental."""
ndims = len(dims)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# the weights must be set explicitly as attributes in the class
# (i.e., we ca... | b9978c610992bbd0566cb8d855613761446a050f | 3,635,068 |
def _ccsd_t_energy(output_str):
""" Reads the CCSD(T)/UCCSD(T) energy from the output file string.
Returns the energy in Hartrees.
:param output_str: string of the program's output file
:type output_str: str
:rtype: float
"""
ene = ar.energy.read(
output_str,
... | 74352ad0f717de6b6c1125508a0556635e6446a3 | 3,635,069 |
from miner_globals import getCurrentScriptPath
def getMyPath():
"""returns path of current script"""
return getCurrentScriptPath() | 7ba447d8a7b34a9e0ada1ae11cdefa81ec5a89e9 | 3,635,070 |
import random
def get_codename():
"""Helper for generating a random codename to represent a voter
in the admin interface. To protect voting privacy of our voters,
we are using hashes to make it slightly more difficult to
reveal/infer who voted for who. On the admin interface, however,
instead of u... | 6baf9cc8dd774f0d5541980d7a48be98cb4c66a0 | 3,635,071 |
def load_paste_config(app_name, options, args):
"""
Looks for a config file to use for an app and returns the
config file path and a configuration mapping from a paste config file.
We search for the paste config file in the following order:
* If --config-file option is used, use that
* If args... | 26524003ac407433eb82b196aed8836aad7ccf92 | 3,635,072 |
import numpy
def get_nearest_to_layers_mean_indicators(layers):
"""
Return indicators of weights in layers nearest
to layer weight mean.
This function, for every given layer, computes weights mean
and returns importance indicators for every weight
based on how close to it's layer mean it is.
... | 5fe27d680566097743b708c07fdeb44b1f68ce0f | 3,635,073 |
def mach_wave_angle(mach: float):
"""Return the angle of the Mach wave given the Mach number after a turn
Notes
-----
Parameters
----------
mach : float
The mach number after a turn
Returns
-------
float
The angle of the mach wave in degrees
Examples
-... | a5dd1d2021dbdf87a4c255a207ad0d8b9627a407 | 3,635,074 |
from ssl import SSLError
def download_to_file(url, file, quiet=False):
"""Downloads a URL to file. Returns the file size.
Returns -1 if the downloaded file size does not match the expected file
size
Returns -2 if the download is skipped due to the file at the URL not
being newer than the local cop... | 723d5e733c623b6b770f71b31085861433d7ad3d | 3,635,075 |
def peakfit(xvals, yvals, yerrors=None, model='Voight', background='slope',
initial_parameters=None, fix_parameters=None, method='leastsq', print_result=False, plot_result=False):
"""
Fit x,y data to a peak model using lmfit
E.G.:
res = peakfit(x, y, model='Gauss')
print(res.fit_repo... | 2f5aab6bb2eff7eb72217924d1487e5a2f87ec43 | 3,635,076 |
import re
def error_027_mnemonic_codes(text):
"""Fix some cases and return (new_text, replacements_count) tuple."""
(text, ignored) = ignore(text, r"https?://\S+")
(text, count1) = re.subn(r"–", "–", text)
(text, count2) = re.subn(r" ", " ", text)
text = deignore(text, ignored)
retu... | 4716e567db007ab49182ccc9fa82f556f56d55b3 | 3,635,077 |
def memodict(f):
"""Memoization decorator for a function taking a single argument
http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/
"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
... | e49da93343320a86d07394c0015589d4d34aab97 | 3,635,079 |
def xval(v):
"""Return the scalar x value of a single vector.
>>> xval(make(1, 2, 3))
1
"""
assert is_vec3(v)
assert v.shape[0] == 1
return v[0, 0] | f4637f54e7350d7c24e40db687cf1ee8b5467a31 | 3,635,080 |
from datetime import datetime
def payload_full():
"""full jwt payload"""
return {
"iss": "https://www.myapplication.com",
"aud": "https://www.myapplication.com",
"exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=10),
"iat": datetime.datetime.utcnow(),
"nbf"... | c459fecc3b6de6960be7b2eabb44388e09153ca4 | 3,635,081 |
def ensure_package(
requirement_str, error_level=None, error_msg=None, log_success=False
):
"""Verifies that the given package is installed.
This function uses ``pkg_resources.get_distribution`` to locate the package
by its pip name and does not actually import the module.
Therefore, unlike :meth:... | 1006358dff21366424d2b4085599956d67542ab5 | 3,635,082 |
def deliver_image_gif(): # type: () -> str
"""Return a minimal GIF image."""
return b64decode("""
R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
""") | 9dadcba602aeae9ae64f789d594ef42ede5562f3 | 3,635,083 |
from re import L
def build_bootstrap_likelihood(lex, sentence, ontology,
alpha=0.25, meaning_prior_smooth=1e-3):
"""
Prepare a likelihood function `p(meaning | syntax, sentence)` based on
syntactic bootstrapping.
Args:
lex:
sentence:
ontology:
alpha: Mixing para... | 19274987b8ef5ace9f31638c81933bcab122d55f | 3,635,084 |
def getTJstr(text, glyphs, simple, ordering):
""" Return a PDF string enclosed in [] brackets, suitable for the PDF TJ
operator.
Notes:
The input string is converted to either 2 or 4 hex digits per character.
Args:
simple: no glyphs: 2-chars, use char codes as the glyph
... | bd5b7abd1b5ceb0b273e99e30ecc248482ed7476 | 3,635,085 |
def datetime_to_jd(date):
"""
Convert a `datetime.datetime` object to Julian Day.
Parameters
----------
date : `datetime.datetime` instance
Returns
-------
jd : float
Julian day.
Examples
--------
>>> d = datetime.datetime(1985,2,17,6)
>>> d
... | 6a149aba3719eaf4e0a81e2372192b9d17676b1f | 3,635,087 |
def parse_channel_mention(part, message):
"""
If the message's given part is a channel mention, returns the respective channel.
Parameters
----------
part : `str`
A part of a message's content.
message : ``Message``
The respective message of the given content part.
... | 38b3bbe5f7a918210a4ddc4005d61c651687ab55 | 3,635,088 |
def keep_alive(headers, version, method):
""" return True if the connection should be kept alive"""
conn = set((v.lower() for v in headers.get_all('connection', ())))
if "close" in conn:
return False
elif 'upgrade' in conn:
headers['connection'] = 'upgrade'
return True
elif "... | da8e9a5908d19a5bdb5ba2915abc5f85e1e3c553 | 3,635,089 |
def apply_dies_factory(have_dies, jones_type):
"""
Factory function returning a function that applies
Direction Independent Effects
"""
# We always "have visibilities", (the output array)
jones_mul = jones_mul_factory(have_dies, True, jones_type, False)
if have_dies:
def apply_dies... | 460477cc5cd6b195f331c8db2dfd0d0ec9080750 | 3,635,090 |
def check_skip(timestamp, filename):
"""
Checks if a timestamp has been given and whether the timestamp corresponds
to the given filename.
Returns True if this condition is met and False Otherwise"
"""
if ((len(timestamp) > 0) and not(timestamp in filename)):
return True
elif ((len(... | 738043fb554f20b79fa3ac8861f9e60d0d697e5e | 3,635,091 |
from typing import Optional
from typing import Union
import re
def extract_emoji(string: str, bot: Bot) -> Optional[Union[str, Emoji]]:
"""
Extracts a single emoji or custom emote from the input string.
:param string: Input string
:param bot: Discord bot object
:return: Either a string containing... | 00d2c3614b8f4e9b8292fec781aefa231d9d4e83 | 3,635,092 |
def get_bridge(driver):
"""Call this method to get a Bridge instead of a standalone accessory."""
bridge = Bridge(driver, 'Bridge')
light_1 = LightBulb(driver, 'Red Light', pin=LedPin1)
light_2 = LightBulb(driver, 'Blue Light', pin=LedPin2)
bridge.add_accessory(light_1)
bridge.add_accessory(ligh... | e3ee071661e4cc19da8ec5f7b7b7b5017c2f76d4 | 3,635,093 |
def compute_gradient_penalty(D, real_samples, fake_samples):
"""Calculates the gradient penalty loss for WGAN GP"""
# Random weight term for interpolation between real and fake samples
alpha = Tensor(np.random.random((real_samples.size(0), 3, 1, 1)))
# Get random interpolation between real and fake samp... | 724da4c0d18996e0813e4cea6cbb33d1f3a316fc | 3,635,094 |
def is_tabledap(url):
"""
Identify a dataset as an ERDDAP TableDAP dataset.
Parameters
----------
url (str) : URL to dataset
Returns
-------
bool
"""
return "tabledap" in url | 9f4650bc3a3bc0794637b042c1779a84d7c02779 | 3,635,095 |
def generate_timestamp(time_to_use, stamp_type="default"):
""" Genrate a text timestamp """
new_stamp = time_to_use.strftime("%Y%m%d-%H%M%S")
return new_stamp | 1b386ed7375b3158867d980796c764a627c68338 | 3,635,097 |
def scr2idb(*args):
"""scr2idb(char name) -> char"""
return _idaapi.scr2idb(*args) | 0ec28ae35176b4f28c755723a063c8ddadb583df | 3,635,098 |
import torch
def compute_local_nre_maps(
source_descriptors: torch.Tensor,
target_features: torch.Tensor,
prior_target_keypoints: torch.Tensor,
norm_coarse: torch.Tensor,
window_size: int,
):
"""Compute dense local correspondence maps.
Args:
* source_descriptors: The interpolated s... | 281eb31981b81e9a9d4053786a22256ee182c7b4 | 3,635,099 |
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 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 |
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 |
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 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 |
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 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.