content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_random_crop_and_resize_03():
"""
Test RandomCropAndResize with md5 check: max_attempts is 1, expected to pass
"""
logger.info("test_random_crop_and_resize_03")
original_seed = config_get_set_seed(0)
original_num_parallel_workers = config_get_set_num_parallel_workers(1)
# First data... | 5,296,200 |
def user_label(i):
""" Generate the user lable. Lables are 1 indexed.
"""
i = i - 1
if i < 0 or i > len(users):
return "User" + str(int(i))
return users[i] | 5,296,201 |
def append_reach2yaml(
yaml_path: Union[Path, str],
events_file: Union[Path, str],
leap_sec: float = 18,
) -> None:
"""
Append Reach M2 lat/lon/height into the yamls created by the
create_img_acqi_yamls() function.
Parameters
----------
yaml_path : Path or str
The directory ... | 5,296,202 |
def doweight(theta, lam, p, v):
"""Re-weight visibilities
Note that as is usual, convolution kernels are not taken into account
"""
N = int(round(theta * lam))
assert N > 1
gw = numpy.zeros([N, N])
x, xf, y, yf = frac_coords(gw.shape, 1, p / lam)
for i in range(len(x)):
gw[x[i],... | 5,296,203 |
def connect(args):
"""Connect to Mi Kettle."""
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
last_exception_time = datetime.datetime(1, 1, 1, 0, 0)
sec = 5
try:
kettle = MiKettle(args.mac, args.product_id)
print("Authenticating")
print("Getting data... | 5,296,204 |
def build_import_command_line(input_path: str, tfs: TempFileSaver,
options: ImportOptions) -> List[str]:
"""Builds a command line for invoking the import stage.
Args:
input_path: The input path.
tfs: TempFileSaver.
options: Import options.
Returns:
List of strings of... | 5,296,205 |
def ecg_rsa(rpeaks, rsp, sampling_rate=1000):
"""
Returns Respiratory Sinus Arrhythmia (RSA) features. Only the Peak-to-trough (P2T) algorithm is currently implemented (see details).
Parameters
----------
rpeaks : list or ndarray
List of R peaks indices.
rsp : list or ndarray
Fi... | 5,296,206 |
def ipam_release_address():
"""Deallocates the IP address in the given request.
This function takes the following JSON data and remove the given IP address
from the allocation_pool attribute of the subnet. ::
{
"PoolID": string
"Address": string
}
Then the foll... | 5,296,207 |
def test_http_get(app):
"""Test that the correct Response class is being used"""
assert type(GET('home')) == current_app.response_class == Response | 5,296,208 |
def plot_cv_results(train_loss,
cv_loss,
ind_loss=None,
log_scale_p=False,
plot_title='Mean Square Error Loss',
filepath=None):
"""
Helper function to plot the results of cross-validation.
You can use this wh... | 5,296,209 |
def data_io_decorator(func):
"""
Decorator to standardize docstrings for data I/O functions.
"""
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
# Parse the docstrings of the base df_to_time_series function & decorated function.
prefix, suffix, params = parse_basic_docstring... | 5,296,210 |
def test_offline():
"""
Let's try and see which CMT versions are compatible with this straxen
version
"""
cmt = straxen.CorrectionsManagementServices()
cmt_versions = list(cmt.global_versions)[::-1]
print(cmt_versions)
success_for = []
for global_version in cmt_versions:
try:... | 5,296,211 |
def similar(amazonID, googleURL):
""" Return similarity value
Args:
amazonID: amazon ID
googleURL: google URL
Returns:
similar: cosine similarity value
"""
return (similarities
.filter(lambda record: (record[0] == googleURL and record[1] == amazonID))
... | 5,296,212 |
def send_email(to, subject, template, **kwargs):
"""发送电子邮件"""
msg = Message(current_app.config['NECTAR_MAIL_SUBJECT_PREFIX'] + subject,
sender=current_app.config['NECTAR_MAIL_SENDER'],
recipients=[to])
msg.body = render_template(template + '.txt', **kwargs)
# msg.html... | 5,296,213 |
def main():
""" If you want to resume a job, all you have to do is change ss """
ts = 4000000 # total number of steps in the simulation
js = 2000000 # number of steps per job
ss = 0 # starting step, this number gets changed in the loop ~ incremented by js on each submit
starting_param_filename = 'pa... | 5,296,214 |
def test_update_project_response():
""" TEST update_project_response """
scrndr = Screendoor(SD_KEY)
with patch('screendoor_sdk.screendoor.requests.put') as mock_put:
mock_put.return_value.status_code = 200
mock_put.return_value.json.return_value = json.loads(MOCK_RESPONSES)
response... | 5,296,215 |
def atos(data, separator=' ', fmt='02X'):
""" Convert array of bytes to string
:param data: Data in bytes or bytearray type
:param separator: String separator
:param fmt: String format
:return string
"""
ret = ''
for x in data:
if fmt == 'c' and x not in printable.encode():
... | 5,296,216 |
def get_fc_block(n_in: int, n_out: int):
"""
Fully connected block of SimpleCNN model
:param n_in: number of input channels
:param n_out: number of output channels
:return: fully connected block
"""
block = nn.Sequential(
nn.Linear(n_in, n_out),
nn.ReLU()
)
return bl... | 5,296,217 |
def get_instance_from_str(matrix, format):
"""This function returns the string representation of the given matrix instance according to the indicated format."""
# Parsing format
format_list = format.split('.')
if len(format_list) == 1:
format_primary = format_list[0]
format_secondary = '... | 5,296,218 |
def find_duplicates( rootdir ):
"""Find duplicate files in directory tree."""
filesizes = {}
# Build up dict with key as filesize and value is list of filenames.
for path, dirs, files in walk( rootdir ):
for filename in files:
filepath = joinpath( path, filename )
filesiz... | 5,296,219 |
def get_oiio_info_for_input(filepath, logger=None):
"""Call oiiotool to get information about input and return stdout.
Stdout should contain xml format string.
"""
args = [
get_oiio_tools_path(), "--info", "-v", "-i:infoformat=xml", filepath
]
output = run_subprocess(args, logger=logger... | 5,296,220 |
def parse_extended_tweet(connection_params, depth):
"""Aggregate operation to parse extended tweet and append contents to top level.
Preprocessing Pipeline Stage 6.
Entities include hashtags, user_mentions, urls and media.
http://stackoverflow.com/questions/28827516/using-unwind-twice-with-group-and-su... | 5,296,221 |
def _tsnr(imgdata, t_axis):
"""Calculate median of temporal signal to noise ratio.
This is consistent with MRIQC
"""
meanimg = np.mean(imgdata, axis=t_axis)
stddevimg = np.std(imgdata, axis=t_axis)
tsnr = np.zeros_like(meanimg)
stddevimg_nonzero = stddevimg > 1.0e-3
tsnr[stddevimg_nonzer... | 5,296,222 |
def point_dist(a, b):
""" Distance between two points. """
return ((a[0]-b[0]) ** 2 + (a[1]-b[1]) ** 2) ** 0.5 | 5,296,223 |
def checking(Y, V_map, S_map, I0_pq, n_buses, n_time, n_scale):
"""
:param Y: data file name
:param V_map: outer iterations
:param S_map: intermediate iterations
:param I0_pq: inner iterations
:param n_buses: number of buses
:param n_scale: number of discretized points, arbitrary
:param... | 5,296,224 |
def parse_xml(path):
"""Return ([analysts], service number, document text, document title).
"""
with open(path) as f:
doc = etree.parse(f)
analysts = [x.text.encode('utf-8', 'ignore')
for x in doc.xpath('//authors/author/author-name')]
title = ''
els = doc.... | 5,296,225 |
def task(*, name, waiter=None, exception_handler=None):
"""Returns a decorator that creates a `Task` with the given options."""
def decorator(func):
return Task(name, func, waiter, exception_handler, instance=None)
return decorator | 5,296,226 |
def restore_output():
"""restore_output(): restore the standard output back to the
default (also closes the capture file)"""
global _file_object
sys.stdout = sys.__stdout__
_file_object.close()
print("standard output has been restored back to normal") | 5,296,227 |
def quote(s: str) -> str:
"""
Quotes the identifier.
This ensures that the identifier is valid to use in SQL statements even if it
contains special characters or is a SQL keyword.
It DOES NOT protect against malicious input. DO NOT use this function with untrusted
input.
"""
if not (s.... | 5,296,228 |
def CloseInheritedPipes():
""" Gmake in MAC OS has file descriptor (PIPE) leak. We close those fds
before doing other work."""
if platform.system() != "Darwin":
return
for d in range(3, 1025):
try:
stat = os.fstat(d)
if stat is not None:
pipebit = stat[0] & 0x1000
if pipebit ... | 5,296,229 |
def cluster_tweets_external(texts: PreprocessedText, top=3):
"""
Clusters Tweets, from preprocessed texts in db.
:param texts: PreprocessedText objects representing the texts.
:param top: The number of keywords to assign to each clusters.
:return: The ClusterResult representing the result.
"""
... | 5,296,230 |
def dicom2narray(path, voi_lut = False, fix_monochrome = True):
"""
Converts a DICOM into a NUMPY array and returns this array and
its corresponding dataset.
"""
dicom = pydicom.read_file(path)
# VOI LUT (if available by DICOM device) is used to transform raw DICOM data
# to "human-friendl... | 5,296,231 |
def evaluate_kantorovich_v2(device, args, model, growth_model=None):
""" Eval the model via kantorovich distance on leftout timepoint
v2 computes samples from subsequent timepoint instead of base distribution.
this is arguably a fairer comparison to other methods such as WOT which are
not model based t... | 5,296,232 |
def run_fn(fn_args: tfx.components.FnArgs):
"""Train the model based on given args.
Args:
fn_args: Holds args used to train the model as name/value pairs.
"""
tf_transform_output = tft.TFTransformOutput(fn_args.transform_output)
train_dataset = _input_fn(
fn_args.train_files,
fn_args.data_ac... | 5,296,233 |
def train_nn(sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss, input_image,
correct_label, keep_prob, learning_rate):
"""
Train neural network and print out the loss during training.
:param sess: TF Session
:param epochs: Number of epochs
:param batch_size: Batch s... | 5,296,234 |
def make_activity_context(context,
splits, strava_activity,
race,
stravaSessionExists,
isStrava,
trackFit,
laps, lap_index=-1
):
"""
... | 5,296,235 |
def extract_bigrams_as_list(text):
"""Extract bigrams from text and return as list
:param text: source text
:type text: str
:return: bigram tokens list
:rtype: list
"""
tokens = text.split(" ")
bigram_tokens = create_bigrams(tokens)
return bigram_tokens | 5,296,236 |
def find_best_polynomial(data_x, data_y, max_poly_order, rsq_threshold,
max_dim_n=32,
alpha_sweep=None,
max_iter=1000, cv=2):
"""Find minimal polynomial expansion that is sufficient to explain data using Lasso regression."""
rsq = 0
poly_o... | 5,296,237 |
def test_angular_to_linear():
"""Test conversion between milliarcsecond and meter."""
a_mas = 3.
absolute_parallax_mas = 100.
a_recovered_mas = convert_from_linear_to_angular(convert_from_angular_to_linear(a_mas, absolute_parallax_mas), absolute_parallax_mas)
# print(np.abs(a_mas - a_recovered_mas... | 5,296,238 |
def test_list_date_time_min_length_3_nistxml_sv_iv_list_date_time_min_length_4_3(mode, save_output, output_format):
"""
Type list/dateTime is restricted by facet minLength with value 8.
"""
assert_bindings(
schema="nistData/list/dateTime/Schema+Instance/NISTSchema-SV-IV-list-dateTime-minLength-4... | 5,296,239 |
def create_decimal128_context():
"""Returns an instance of :class:`decimal.Context` appropriate
for working with IEEE-754 128-bit decimal floating point values.
"""
opts = _CTX_OPTIONS.copy()
opts['traps'] = []
return decimal.Context(**opts) | 5,296,240 |
def decipher(ciphered_text: str, key: str, charset: str = DEFAULT_CHARSET) -> str:
""" Decipher given text using substitution method.
Note you should use the same charset that ciphering end did.
:param ciphered_text: Text to be deciphered.
:param key: Secret key. In substitution method it corresponds ... | 5,296,241 |
def assert_allclose(
actual: numpy.float64,
desired: float,
rtol: float,
atol: float,
err_msg: Literal["randint"],
verbose: bool,
):
"""
usage.scipy: 1
"""
... | 5,296,242 |
def manifold_polar(x,y,lamda,A,s,p,m,k,mu):
"""
Returns "Omega", the orthogonal basis for the manifold evaluated at x[-1]
and "gamma" the radial equation evaluated at x[-1].
Input "x" is the interval on which the manifold is solved, "y" is the
initializing vector, "lambda" is the point in the c... | 5,296,243 |
def shrink(filename):
"""
:param filename: str, original image.
:return img: SimpleImage, 0.5x size of original image.
"""
original = SimpleImage("images/poppy.png")
blank_img = SimpleImage.blank(original.width//2, original.height//2)
for x in range(0, original.width, 2):
f... | 5,296,244 |
def sendBind(to):
"""绑定手机"""
code = str(randint(1000, 999999))
param = "%s,3" % (code)
return _sendSms(to, config.SMS_BIND, param) and code | 5,296,245 |
def WMTNewsCrawl(tokenizer=None, root='.data', vocab=None, split=('train'), year=2010, language='en'):
""" Defines WMTNewsCrawl datasets.
Create language modeling dataset: WMTNewsCrawl
returns the train set
Args:
tokenizer: the tokenizer used to preprocess raw text data.
The defaul... | 5,296,246 |
def c2s_stereographic(z):
"""
Stereographic projection from the plane to the sphere.
"""
x = z.real
y = z.imag
u = 2*x
v = 2*y
w = 1 - x**2 - y**2
return np.stack([u,v,w], axis=-1)/(1+x**2+y**2)[..., np.newaxis] | 5,296,247 |
def get_dtype(nbits):
"""For a given number of bits per sample return
a numpy-recognized dtype.
Input:
nbits: Number of bits per sample, as recorded in the filterbank
file's header.
Output:
dtype: A numpy-recognized dtype string.
"""
check_nb... | 5,296,248 |
def feature_exposed_pop(df):
"""
Adds the total population of the countries to which an individual can travel
from the initial country. Is the population most exposed to the disease
apart from the initial country.
Parameters
----------
df : pandas.DataFrame
Returns
-------
df ... | 5,296,249 |
def add_new_location(project):
"""
Add a new location object to the database
POST data MUST be in JSON format.
POST data MUST contain:
name: location name
POST data SHOULD also contain:
description: location description
POST data CAN also contain:
legacy_id: legacy id for locatio... | 5,296,250 |
def red_highlight(val) -> str:
"""Red highlight
Parameters
----------
val
dataframe values to color
Returns
----------
str
colored dataframes values
"""
return f"{Fore.RED}{val}{Style.RESET_ALL}" | 5,296,251 |
def animal_ears(image, ear_image, face_landmarks):
"""attach animal_ears like nekomimi
args:
image: base image
ear_image: one animal ear image
face_landmarks: face_landmarks list
"""
for landmark in face_landmarks:
# position of ear_image center
left = landmark[14... | 5,296,252 |
def covariance_matrix(data, fb=False, spsmooth=0, method='scm'):
"""
Parameters
----------
data : np.ndarray
The data used to create the covariance matrix. Is of shape (n_samples, n_snapshots)
fb : bool
If true, uses forward-backward averaging
spsmooth : int
Number of ... | 5,296,253 |
def replicate_layers(layer: torch.nn.Module, num_copies: int):
"""
# Parameters
layer (torch.nn.Module) - The torch layer that needs to be replicated.
num_copies (int) - Number of copies to create.
# Returns
A ModuleList that contains `num_copies` of the `layer`.
"""... | 5,296,254 |
def prune_volumes():
"""
Prune any volumes not in use
"""
get_docker_client().volumes.prune() | 5,296,255 |
def setup_framework():
"""Set up the testing framework."""
import pathlib
from sel4.conf import settings
paths = settings.PROJECT_PATHS
def _create_last_result_backup():
src: pathlib.Path = dict(paths).get("LAST_EXECUTION")
if src.exists():
import shutil
im... | 5,296,256 |
def list_clusters(
profile=None,
access_key_id=None,
access_key_secret=None):
"""List ECS clusters."""
aws_profile = utils.get_profile(profile, access_key_id, access_key_secret)
try:
records = cluster_jobs.fetch_all(aws_profile)
except PermissionDenied:
msg = "Yo... | 5,296,257 |
def get_stocks_urls(db_name) -> list:
"""
# This function gets the basic url for each stock. It reads the stocks and url from the database
:return: list for the stocks name and urls [(stock1, stock1_url), (stock1, stock1_url), ...]
"""
con = connect_to_mysql(db_name)
cursor = con.cursor()
cu... | 5,296,258 |
def a_test_sample_model():
"""
Tests sampling function
"""
model = ARIMAX(formula="y ~ x1", data=data, ar=2, ma=2, family=Exponential())
x = model.fit('BBVI', iterations=100)
sample = model.sample(nsims=100)
assert(sample.shape[0]==100)
assert(sample.shape[1]==len(data)-2) | 5,296,259 |
def substBuiltInVarsInParam(val, svars, splitListOfStrs = True, notHandled = None):
"""
Return value with handled substitutions from a param of 'str',
'list-of-strs' types or from a param of 'dict' with params of such types.
"""
if not val:
return val
if isinstance(val, stringtype):
... | 5,296,260 |
def _mangle_dimension_name(name):
"""Return a dimension name from a mixpanel property name."""
fixed_name = name.replace("$", "_")
fixed_name = fixed_name.replace(" ", "_")
return fixed_name | 5,296,261 |
def stage_3():
"""Stage 3 initialization for WORKSPACE.
This step includes any initialization which can't take place in stage 2 for
various reasons, including:
* A transitive load statement that references a repository that doesn't
exist until stage 2 completes
"""
python_deps()
grpc_... | 5,296,262 |
def set_lvj_index(df):
"""
Make an lvj index in place from the length, v_gene, and j_gene.
"""
df['length'] = df['amino_acid'].apply(len)
df.set_index(lvj, inplace=True) | 5,296,263 |
def all_variants(protein_id, sequence, position=None):
"""Position is 0-based"""
positions = [(position, sequence[position])] \
if position else enumerate(sequence)
return pd.DataFrame([
[protein_id, sequence, i+1, wt, mt]
for i, wt in positions
for mt in AMINO_A... | 5,296,264 |
def org_organisation_create_onaccept(form):
"""
Create a Reserves Forum for this Organisation with dual hierarchy to main Reserves Forum & this Organisation
"""
db = current.db
s3db = current.s3db
ftable = s3db.pr_forum
# Lookup the Reserves Forum
forum = db(ftable.name == "Reserve... | 5,296,265 |
def strftime(time, include_date=True, include_tz=False):
"""
This function converts a time value to a string.
Parameters
----------
time : numeric, pandas.Timestamp with tz
The time value to convert.
include_date : bool (Default: True)
If time is a pandas.Timestamp, inc... | 5,296,266 |
def update_dict(old_data, new_data):
"""
Overwrites old usa_ids, descriptions, and abbreviation with data from
the USA contacts API
"""
old_data['usa_id'] = new_data.get('usa_id')
if new_data.get('description') and not old_data.get('description'):
old_data['description'] = new_data.get(... | 5,296,267 |
def read(f, normalized=False):
"""MP3 to numpy array"""
a = pydub.AudioSegment.from_mp3(f)
y = np.array(a.get_array_of_samples())
# if a.channels == 2:
# y = y.reshape((-1, 2))
if normalized:
return a.frame_rate, np.float32(y) / 2**15
else:
return a.frame_rate, y | 5,296,268 |
def setup_logging(loglevel):
"""Setup basic logging
Args:
loglevel (int): minimum loglevel for emitting messages
"""
logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
logging.basicConfig(
level=loglevel,
stream=sys.stdout,
format=logformat,
datefmt=... | 5,296,269 |
def read_fgdb_fc(path, simplify=True, geom_attrs=True, strict=True):
"""Generates a networkx.DiGraph from an Esri File Geodatabase Feature
Class. Point geometries are translated into nodes, and lines into edges.
Coordinate tuples are used as keys. Attributes are preserved, line
geometries are sim... | 5,296,270 |
def min_box(box1, box2):
"""
return the minimum of two bounding boxes
"""
ext = lambda values: max(values) if sum(values) <= 0 else min(values)
return tuple(tuple(ext(offs) for offs in zip(dim[0], dim[1])) for dim in zip(box1, box2)) | 5,296,271 |
def import_social_content():
"""
Iterate over all active social accounts and import post data with matching
social service class.
"""
for social_account in SocialAccount.active.all():
try:
service = get_service_class_by_name(social_account.social_content_type)
except Serv... | 5,296,272 |
def trapezoid(t, params):
"""Trapezoidal pulse. Width of linear slope.
Parameters
----------
params : dict
t_final : float
Total length of pulse.
risefall : float
Length of the slope
"""
risefall = tf.cast(params["risefall"].get_value(), tf.float64)
t... | 5,296,273 |
def get_maya_logger(path):
"""
Returns a logger object that writes a log file to disk ( provided path )
and to the stderr output.
:param str path:
:return: Logger
:rtype: logging.RootLogger
"""
# get logger
global logger
logger = logging.getLogger()
# remove existing handle... | 5,296,274 |
def run_pipeline(vars):
"""
Run pipeline for current checked-out branch passing vars
in form VAR1=VALUE VAR2=VALUE.
"""
d = [{'key': a.split('=')[0], 'value': a.split('=')[1]} for a in vars]
for _, v in d:
if any(elem in v for elem in r", "):
# FIXME non working
r... | 5,296,275 |
def yn_prompt(query):
"""Generic Y/N Prompt"""
sys.stdout.write('%s [y/n]: ' % query)
val = raw_input()
try:
ret = strtobool(val)
except ValueError:
sys.stdout.write('Please answer with a y/n\n')
return yn_prompt(query)
return ret | 5,296,276 |
def test_bin_two_col():
"""Basic binning test."""
df = pd.DataFrame([[-3, 9], [4, 2], [5, 1], [9, 5]], columns=['s', 'p'])
bin_stage = Bin({'s': [5], 'p': [5]}, drop=False)
res_df = bin_stage.apply(df, verbose=True)
assert 's_bin' in res_df.columns
assert res_df['s_bin'][0] == '<5'
assert re... | 5,296,277 |
def exempt_milliwatts_sar(cm: float, ghz: float) -> float:
"""Calculate power threshold for exemption from routine radio frequency exposure evaluation. Note: narrow range
of applicable frequencies. FCC formula is "based on localized specific absorption rate (SAR) limits." Source: FCC
19-126 p.23
:param... | 5,296,278 |
def estimate_fdr_stats(res_real, res_perm, delta):
"""
Helper function for get_fdr_stats_across_deltas.
It computes the FDR and tval_s0 thresholds for a specified delta.
The function returns a list of the following values:
t_cut, n_pos, n_false_pos, pi0, n_false_pos_corr, fdr
"""
perm_avg = ... | 5,296,279 |
def generate_base_anchors(cfg):
"""
Generating top left anchors for given anchor_ratios, anchor_scales and image size values.
:param cfg: dictionary with configuration parameters
:returns: base_anchors = (anchor_count, [y1, x1, y2, x2])
"""
img_size = cfg.IMG_SIZE_WIDTH
anchor_ratios = c... | 5,296,280 |
def spaghetti_annual_hydrograph(file):
"""
spaghetti_annual_hydrograph
INPUTS:
file -- Raven output file containing simulated streamflows of one model
Create a spaghetti plot of the mean hydrological cycle for one model
simulations. The mean simulation is also displayed.
"""
# Tim... | 5,296,281 |
def divinity_univariate_factory(y:Y_TYPE, s, k:K_TYPE, a=None, t=None, e=None,
max_buffer_len=1000,
n_warm = 101,
model_params:dict=None):
""" A partial wrapping of the divinity library with notable limitations:
... | 5,296,282 |
def fill_categories(array,fill,coord=None):
"""
Replace categorical labels and interpolate missing categories depending on a custom dictionary
:param array: array of a categorical variable
:param fill: dictionary with category replacements and missing categories
:param coord: optional, coordina... | 5,296,283 |
def get_u(r_div_R, z_div_L, k, Ap, Am, lam1):
""" Using Eq. (31) (the second expression) in [1]
"""
# uR_HP = (1. - r_div_R**2.0)*lam1/2.
uR_HP = (1. - r_div_R**2.0)
uZ_PS = -k*(exp( k*z_div_L)*Ap - exp(-k*z_div_L)*Am)
return uZ_PS*uR_HP | 5,296,284 |
def generate_report(budget, output_path=''):
"""generates report for the given client and budget
:param stalker.Budget budget: The :class:``stalker.Budget`` instance
:param str output_path: The output path of the resultant report
"""
# check the budget argument
from stalker import Budget
if... | 5,296,285 |
def save_env_info(container_command, worktree, commit_id, image_name, slug, result_path):
"""Save reference info about a given container image."""
envinfo_path = result_path / 'env-info'
envinfo_path.mkdir()
with envinfo_path.joinpath('os-release').open('w') as f:
run(
container_comm... | 5,296,286 |
def is_zero(pauli_string):
"""
Checks if a PauliString is zero.
Parameters
----------
pauli_string : (PauliString object) a PauliString object which is to be checked
Returns
-------
True if PauliString is zero, False otherwise
"""
if isinstance(pauli_string, PauliString):
... | 5,296,287 |
def evalAllocater(task, metrics, reshapeDims, n_classes):
"""Returns an evaluator based on the specified task.
# Arguments
task: integer value denoting the task
metrics: evaluation metrics related to that task
reshapeDims: reshape dimensions of the image
n_classes: integer value denoting the number of classe... | 5,296,288 |
def checkCrash(player, upperPipes, lowerPipes):
"""returns True if player collders with base or pipes."""
pi = player['index']
player['w'] = IMAGES['player'][0].get_width()
player['h'] = IMAGES['player'][0].get_height()
# if player crashes into ground or above screen
if (player['y'] + player['h... | 5,296,289 |
def login_required(func):
"""Decorator for enforcing a logged in user.
Also pulls the token out of the request and passes a user instance into the decorated function.
"""
@wraps(func)
def check_log_in(*args, **kwargs):
current_user.ping()
database_session.commit()
return f... | 5,296,290 |
def gdx(request, year=None, gdx_path=None, array_results=False):
"""
Look up the request in a gdx file.
A request uses Gekko syntax, e.g. "qBNP", "qY[tje]", or "qY[#s]".
If no year is specified, an array is returned with values for all available years.
If no gdx_path is specified, use the global path set usin... | 5,296,291 |
def KernelDisorderSC(kx, ky, px, py, params):
"""
This subroutine defines the kernel between self energy and free Feynman propagator.
In case of phase-disordered superconductivity,
this corresponds to the fourier transformation of space correlation of Cooper gap.
E.g. In two dimens... | 5,296,292 |
def build_from_path(package, path, dry_run=False, env='default', outfilename=DEFAULT_BUILDFILE):
"""
Compile a Quilt data package from a build file.
Path can be a directory, in which case the build file will be generated automatically.
"""
team, owner, pkg, subpath = parse_package(package, allow_sub... | 5,296,293 |
def DOV(ATcur, A, Gcur, a):
"""
| LAT | ----------+---------- Astr.
| LON | | Azimuth
| H |AT | (A)
|
|
+-----------------> Deflection of , Geoid
... | 5,296,294 |
def replace_cif_reference(refs: typing.Iterable[str], new_sub_str: str) -> typing.List:
"""Replace the "cif-reference-0" to bec new names with increasing index."""
ans = []
source = r"@article{.*,"
for i, ref in enumerate(refs):
ref2 = re.sub(source, "@article{{{}{},".format(new_sub_str, i), ref... | 5,296,295 |
def random_string() -> str:
"""
Create a 36-character random string.
Returns
-------
str
"""
return str(uuid.uuid4()) | 5,296,296 |
def get_points_raytracing(count, side, other_side, building_data, road_part, points_classified):
"""
Get all the point created by the raytracing for the given road segment.
Returns a dictionary with the distances and heights on the left and right side.
"""
bld_dist_heights = {}
i = count
fo... | 5,296,297 |
def forward(sample, G, imgs_size, indices, device):
"""
This function takes the whole input, prepares it for the forward pass,
creates the patches of given size and with two loops pass these adiacent
patches through the generator. Then, the simulated patches are concatenaed
together to compose ... | 5,296,298 |
def blacklist_notify(recipient_pk, sms_body, keyword):
"""Send email to office when we discover we are blacklisted."""
from apostello.models import Recipient
recipient = Recipient.objects.get(pk=recipient_pk)
if keyword == "start":
return
if keyword == "stop":
async_task(
... | 5,296,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.