content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from datetime import datetime
def iso8601(dt=None, aware=False):
"""
Returns string datetime stamp in iso 8601 format from datetime object dt
If dt is missing and aware then use now(timezone.utc) else utcnow() naive
YYYY-MM-DDTHH:MM:SS.mmmmmm which is strftime '%Y-%m-%dT%H:%M:%S.%f'
Only TZ aware ... | 181d2f38b39792cc0331ee7bd9a34f76691b5128 | 3,637,200 |
import re
import string
def parse_text(infile, xpath=None, filter_words=None, attributes=None):
"""Filter text using XPath, regex keywords, and tag attributes.
Keyword arguments:
infile -- HTML or text content to parse (list)
xpath -- an XPath expression (str)
filter_words -- regex keywords (list... | 7d2b04c477624db322721b785d95bffa16af1576 | 3,637,201 |
def _check_blacklist_members(rule_members=None, policy_members=None):
"""Blacklist: Check that policy members ARE NOT in rule members.
If a policy member is found in the rule members, add it to the
violating members.
Args:
rule_members (list): IamPolicyMembers allowed in the rule.
poli... | 2fc41f4ff6c401de0976b04dd6a8cb858cef96e7 | 3,637,202 |
def create_variable_weather(weather_data, original_epw_file, columns: list = ['drybulb'], variation: tuple = None):
"""
Create a new weather file adding gaussian noise to the original one.
Parameters
----------
weather_data : opyplus.WeatherData
Opyplus object with the weather for the simul... | 13674db675cb5c03c77047e78d0cf57b3bfab1ac | 3,637,203 |
def transform(func, geom):
"""Applies `func` to all coordinates of `geom` and returns a new
geometry of the same type from the transformed coordinates.
`func` maps x, y, and optionally z to output xp, yp, zp. The input
parameters may iterable types like lists or arrays or single values.
The output ... | 71bde1500ec8370a7718542ee26181d2aad6591f | 3,637,204 |
def get_jit(policy_name, asc_location, resource_group_name):
"""Building query
Args:
policy_name: Policy name
asc_location: Machine location
resource_group_name: Resource name group
Returns:
dict: response body
"""
cmd_url = (
"/resourceGroups/{}/providers/M... | 9e50eaf91fb2b2318f6b5334b848a6dce70ddf61 | 3,637,205 |
def rank_by_yield(df):
"""
Rank phenotypes by yield only.
Parameters
----------
df : pd.DataFrame
MAIZSIM yield output dataframe.
df_sims or df_mature
"""
# Prep data
groups = ['cvar', 'site']
how = 'mean'
sim = 'dm_ear'
mx_mean = agg_sims(df, groups, how, ... | 10dd1c9a8e3ffc94cf4580bc789d7cc19353d748 | 3,637,206 |
def k2lc(epic):
"""
load k2 light curve
"""
prefix = epic[:4]
id = epic[4:]
c = "01"
path = "data/c01/{0}00000/{1}".format(prefix, id)
end = "kepler_v1.0_lc.fits"
file = "{0}/hlsp_everest_k2_llc_{1}-c{2}_{3}".format(path, epic, c, end)
x, y = process_data(file)
return x, y | 6cd5ffa387fa3d666c2f6561c06b458c7556509f | 3,637,207 |
def multi_leave_topics(multileaver, user_id, time):
"""Multileaves a number of suggested topics for a user and returns
the results."""
topics = get_user_suggested_topics(user_id)
if not topics:
return None
ranking, credit = multileaver.team_draft_multileave(topics)
topic_recommendations... | 0b845a7a16419e4592ffd4f75d988728cef70727 | 3,637,208 |
def generate_age(sex):
"""Generate the age of a person depending on its sex
Parameters
----------
sex : int
Sex should be either 0 (men) or 1 (women).
Raises
------
ValueError
If sex is not 0 or 1.
Returns
-------
age : int
Generated age of a perso... | 8f0ba4f215417035760fd1bbe1db5cc0974ed629 | 3,637,209 |
def _extract_text_Wikilink(node: mwparserfromhell.nodes.wikilink.Wikilink) -> str:
"""
Wikilinks come in 2 formats, thumbnails and actual links.
In the case of thumbnails, if posible pull out the nested caption.
"""
if node.title.startswith('File:') or node.title.startswith('Image:'):
if nod... | bc6c16aff602cfeac9756d0c357e054731dc7ff8 | 3,637,210 |
def dict_zip(*dicts):
"""
Take a series of dicts that share the same keys, and reduce the values
for each key as if folding an iterator.
"""
keyset = set(dicts[0])
for d in dicts:
if set(d) != keyset:
raise KeyError(f"Mismatched keysets in fold_dicts: {sorted(keyset)}, {sorte... | 47416641a6451828b78ae6dfd81a48676fcea71f | 3,637,211 |
import argparse
def process_command_line():
"""
Parse command line arguments
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
Return a Namespace representing the argument list.
"""
# Create the parser
parser = argparse.ArgumentParser(prog='obflow_6_output',
... | 5563be1fa3e122222fccd9ca1edfce25907dcc58 | 3,637,212 |
def Ustagger_to_mass(U):
"""
U are the data on the left and right of a grid box
A simple conversion of the U stagger grid to the mass points.
Calculates the average of the left and right value of a grid box. Looping
over all columns it reduces the staggered grid to the same dimensions as the
mas... | d3dbae52d74aff40b83b0437eed9f0aafb5e37ee | 3,637,213 |
def _linear(args,
output_size,
bias,
bias_initializer=tf.zeros_initializer(),
kernel_initializer=initializer(),
scope=None,
reuse=None):
"""Linear map: sum_i(args[i] * W[i]), where W[i] is a variable.
Args:
args: a 2D Tensor or a l... | 3d11e74e4e28aeb737f63046fc4e53b4e68aeb9b | 3,637,214 |
def build_fpn_mask_graph(rois, feature_maps, image_size, num_classes,
pool_size, train_bn=True):
"""Builds the computation graph of the mask head of Feature Pyramid Network.
rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
coordinates.
feature_maps: L... | c6286955fb07d3feb20801a409d44e20382133ef | 3,637,215 |
def calculate_perf_counter_counter(previous, current, property_name):
"""
PERF_COUNTER_COUNTER
https://technet.microsoft.com/en-us/library/cc740048(v=ws.10).aspx
"""
n0 = previous[property_name]
n1 = current[property_name]
d0 = previous["Timestamp_Sys100NS"]
d1 = current["Timestamp_Sys1... | f517f39ef20af5a4d23f1fd74a14fab93be4037b | 3,637,216 |
import http
from datetime import datetime
def event_edit(request, id):
"""Edit form for a particular event."""
event = get_object_or_404(Event, id=id)
result = can_edit_event(event, request.user)
if isinstance(result, http.HttpResponse):
return result
if request.user.has_perm('main.change_... | 0ea47e7b1772c3fa0529f6cc7675a83108ad0018 | 3,637,217 |
from typing import Callable
def migrator(from_: str, to_: str) -> Callable[[MigratorF], MigratorF]:
"""Decorate function as migrating settings from v `from_` to v `to_`.
A migrator should mutate a `NapariSettings` model from schema version
`from_` to schema version `to_` (in place).
Parameters
-... | 20bf5c7c8e693fc880ed9d31e610b2d939f8c020 | 3,637,218 |
import json
def rawChipByLocation_query():
"""
Get chips images by parcel id.
Generates a series of extracted Sentinel-2 LEVEL2A segments of 128x128 (10m
resolution bands) or 64x64 (20 m) pixels as list of full resolution GeoTIFFs
---
tags:
- rawChipByLocation
responses:
200:
... | bfb2b32a17d5b1b8a05efcf710d70fc4179996c5 | 3,637,219 |
import os
from datetime import datetime
def load_adni_longitudinal_av45_pet():
"""Returns paths of longitudinal ADNI AV45-PET
"""
# get file paths and description
(subjects,
subject_paths,
description) = _get_subjects_and_description(base_dir='ADNI_av45_pet',
... | 7ccffff0f945a214088d2c14567cf34f2fb3d063 | 3,637,220 |
from pathlib import Path
from typing import Optional
from typing import List
import json
def build_settings(
tmp_path: Path,
template: str,
*,
oidc_clients: Optional[List[OIDCClient]] = None,
**settings: str,
) -> Path:
"""Generate a test Gafaelfawr settings file with secrets.
Parameters
... | aaba1048c96cd07b42492d11ca34a87365350a20 | 3,637,221 |
import os
import struct
def load_mnist(path, data_type='train'):
"""Load MNIST data from `path`"""
labels_path = os.path.join(path,
'%s-labels.idx1-ubyte'
% data_type)
images_path = os.path.join(path,
'%s-images.i... | 5443a355c78bfb34b5f219e8205265f46e9619f2 | 3,637,222 |
def get_actions_matching_arn(arn):
"""
Given a user-supplied ARN, get a list of all actions that correspond to that ARN.
Arguments:
arn: A user-supplied arn
Returns:
List: A list of all actions that can match it.
"""
raw_arns = get_matching_raw_arns(arn)
results = []
for... | 595e985829df5035c81928a4441c64b136818e8d | 3,637,223 |
import os
def path_splitter(path):
"""
Split a path into its constituent parts.
Might be better written as a recursive function.
:param path: The path to split.
:return: A list of the path's constituent parts.
"""
res = []
while True:
p = os.path.split(path)
if p[0] == ... | cf9ec119eb302ff45b7835a00e235215110c8dc5 | 3,637,224 |
import logging
import time
def _run_defp(mode,code,time_steps,error_model,decoder,error_probability,perm_rates,code_name,layout,measurement_error_probability,
max_runs=None,max_failures=None,random_seed=None):
"""Implements run and run_ftp functions"""
# assumptions
assert (mode == 'ideal' and ti... | dff7f10f32f4cbad4286207d6caf9039898cfedc | 3,637,225 |
import time
def api_retry(func, task_id):
"""
添加api重试机制
:param func: 调用的api函数
:param task_id: 任务id
:return: 重试结果
"""
retry_flag, status_result = False, ""
for i in range(TRANSPORT_RETRY_TIMES):
time.sleep(TRANSPORT_RETRY_INTERVAL)
retry_flag, status_result = func(task_... | 8f3ad5d6c9865ec8405c7504e9a6af851f5e4916 | 3,637,226 |
def test_bound_callables():
"""Test that we can use a callable as a bound value."""
@magicgui(x={"bind": lambda x: 10})
def f(x: int = 5):
return x
assert f() == 10
f.x.unbind()
assert f() == 5 | baf0cafcef7160e23c1b66be9734245adbe9d219 | 3,637,227 |
def delete_role(user_id: str, role_id: str):
""" Removes a role from a user """
print(user_id)
print(role_id)
return jsonify(), HTTPStatus.NO_CONTENT | aa97868d54f0f3b887d80a7f4f8ef258fb050001 | 3,637,228 |
import multiprocessing as mp
from functools import partial
from jinfo.utils.percentage_identity import percentage_identity
def remove_degenerate_seqs(
alignment_obj: BaseAlignment, identity_limit: int, show_id_array: bool = False
) -> BaseAlignment:
"""
Filter high similarity sequences from a list of Seq ... | fcada477a01290fb54a83d074c31de31c9be17e1 | 3,637,229 |
def get_domain(url):
""" Get the domain from a URL.
Parameters
----------
url : string
HTTP URL
Returns
-------
domain : string
domain of the URL
"""
o = urlparse(url)
scheme = o.scheme
if not o.scheme:
scheme = "http"
link = scheme + "://" + o... | e47d2fdedab66d356887a94db5c22770f5e21823 | 3,637,230 |
def push_activations(activations, from_layer, to_layer):
"""Push activations from one model to another using prerecorded correlations"""
inverse_covariance_matrix = layer_inverse_covariance(from_layer)
activations_decorrelated = np.dot(inverse_covariance_matrix, activations.T).T
covariance_matrix = laye... | ddbacdbbfb30156204df27b00c79a28a4895810e | 3,637,231 |
def cross_val_score(estimator, X, y=None, groups=None, scoring=None, cv=None,
n_jobs=1, verbose=0, fit_params=None, pre_dispatch='2*n_jobs'):
"""Evaluate a score using cross-validation
Parameters
----------
estimator : estimator object implementing 'fit'
The object to use to... | 8c4fe69cb2043adf5541b188d99da23beb4d9874 | 3,637,232 |
def load_graph(N, M):
"""
Builds an adjacency list representation of a graph with N vertices. Each
graph[i][j] is the minimum length of an edge between vertice i and j.
:rtype List[int, Dict[int, int]]
"""
graph = [dict() for i in range(0, N)]
for i in range(0, M):
(x, y, r) = read... | acee5cb79eb5bbc04eada9d54344700bff3ffaa4 | 3,637,233 |
def quartile_range(arr):
"""
Find out the Interquartile Range
"""
#if it is odd
if len(arr)%2 != 0:
left=median(arr[:len(arr)/2])
right=median(arr[len(arr)/2 + 1:])
else:
#if array is even
left = median(arr[:len(arr)/2])
right = median(arr[len(arr)/2:])
... | c6fafd63e3e64b893a4632bfb2027e330e8a3c32 | 3,637,234 |
def check_syntax(filename, raise_error=False):
"""Return True if syntax is okay."""
with autopep8.open_with_encoding(filename) as input_file:
try:
compile(input_file.read(), '<string>', 'exec', dont_inherit=True)
return True
except (SyntaxError, TypeError, UnicodeDecodeEr... | d401e292ddb20d66c65a7ffa8988ddab4a7962ec | 3,637,235 |
from astropy.convolution import convolve as astropy_convolve
from ..utils import process_image_pixels
def test_process_image_pixels():
"""Check the example how to implement convolution given in the docstring"""
def convolve(image, kernel):
'''Convolve image with kernel'''
images = dict(image=... | 439e45a7fd403de4df8dd9dfc662be6405d69dc0 | 3,637,236 |
import math
def im2vec(im, bsize, padsize=0):
"""
Converts image to vector.
Args:
im: Input image to be converted to a vector.
bsize: Size of block of im to be converted to vec. Must be 1x2 non-negative int array.
padsize (optional, default=0): Must be non-negative integers in a 1... | 0a88cf02e37fdaeb24103cc0a7027067ea703c82 | 3,637,237 |
def mobilenetV2_block(
input_layer,
filters: int = 32,
dropout_ratio: float = DEFAULT_DROPOUT_RATIO,
use_batchnorm: bool = False,
prefix: str = "mobilenetV2_",
initializer=DEFAULT_KERNEL_INITIALIZER,
regularizer=DEFAULT_KERNEL_REGULARIZER,
channels_index: ... | 0fd2e38d32d192412de4928c7ef92b577235581f | 3,637,238 |
def _grid_archive():
"""Deterministically created GridArchive."""
# The archive must be low-res enough that we can tell if the number of cells
# is correct, yet high-res enough that we can see different colors.
archive = GridArchive([10, 10], [(-1, 1), (-1, 1)], seed=42)
archive.initialize(solution_... | 540ea0270bbe06830ab096c79590c6ffcad487a2 | 3,637,239 |
def check_flush(hand):
"""Check whether the hand has a flush; returns a boolean."""
if len(hand) == len(hand.by_suit(hand[0].suit)):
return True
return False | de11f50f11b477e61f284063c7f0da0dda2dd87e | 3,637,240 |
import torch
def binary_accuracy(preds, y):
"""
Returns accuracy per batch
:param preds: prediction logits
:param y: target labels
:return: accuracy = percentage of correct predictions
"""
# round predictions to the closest integer
rounded_predictions = torch.round(torch.sigmoid(preds... | 2a321bb9e60a937a879619c2fa3baf1cbe968a33 | 3,637,241 |
import csv
def load_taxondump(idpath):
"""Importing the Acidobacteria taxon IDs"""
taxons = {}
with open(idpath) as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
taxons[row[1]] = row[0]
return taxons | b20c973f97d609b646e5c15be7cc320019f21236 | 3,637,242 |
import re
def _to_numeric_range(cell):
"""
Translate an Excel cell (eg 'A1') into a (col, row) tuple indexed from zero.
e.g. 'A1' returns (0, 0)
"""
match = re.match("^\$?([A-Z]+)\$?(\d+)$", cell.upper())
if not match:
raise RuntimeError("'%s' is not a valid excel cell address" % cell)... | 468f452a7e4d4b045ecbb1a1fc261712fb25f3fc | 3,637,243 |
def LUCroutDecompose(A):
"""
Implementação do método de Crout para decomposição LU.
"""
assert A.shape[0] == A.shape[1] and type(A) is matrix, "'A' deve ser NxN."
L = zeros(A.shape)
n = A.shape[0]
U = L.copy()
lib.LUDec(n, byref(ctypeslib.as_ctypes(A)),
byref(ctypeslib.as_c... | cb201e00c8727a6fc005779ca315f61d811d38c1 | 3,637,244 |
def protocol(recarr, design_type, *hrfs):
""" Create an object that can evaluate the FIAC
Subclass of formulae.Formula, but not necessary.
Parameters
----------
recarr : (N,) structured array
with fields 'time' and 'event'
design_type : str
one of ['event', 'block']. Handles how... | d2ce4b35614ca692226133ec72b4f1d46baf065c | 3,637,245 |
def iter_children(param,childlist=[]):
"""
| Iterator over all sub children of a given parameters.
| Returns all childrens names.
=============== ================================= ====================================
**Parameters** **Type** **Description*... | 2edbdccc5957cbe6131da70d6dfc24ea67a19e69 | 3,637,246 |
from typing import Callable
from typing import Optional
from typing import Union
import sys
import atexit
def shell__shell_hook(callback: Callable[[int, WPARAM, LPARAM], Optional[str]]) -> Union[HHOOK, WindowsErrorMessage]:
"""
Adds a global shell hook, called when any key is pressed in any
context. The ... | 6209c800a8e5153f3de8d7f5dfa4793104b51085 | 3,637,247 |
def depth_first_graph_search(problem):
"""
[Figure 3.7]
Search the deepest nodes in the search tree first.
Search through the successors of a problem to find a goal.
The argument frontier should be an empty queue.
Does not get trapped by loops.
If two paths reach a state, only use the first ... | d610752a99a8c4e7f1b5eee2d520d88f868279eb | 3,637,248 |
def check_matrix_equality(A, B, tol=None):
"""
Checks the equality of two matrices.
:param A: The first matrix
:param B: The second matrix
:param tol: The decimal place tolerance of the check
:return: The boolean result of the equality check
"""
if len(A) != len(B) or len... | afc89de848597c6325b6eceb109f7f2311c9be7d | 3,637,249 |
def about(topic):
"""Return a select function that returns whether
a paragraph contains one of the words in TOPIC.
Arguments:
topic: a list of words related to a subject
>>> about_dogs = about(['dog', 'dogs', 'pup', 'puppy'])
>>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup!'], about_d... | b73512058675ac9a17a8d5cd36ab544080a2acbe | 3,637,250 |
def calcBarycentricCoords(pt, verts):
"""calculate the Barycentric coordinates"""
verts = np.array(verts) # vertices formed by N+1 nearest voxels
pt = np.array(pt) # voxel of interest
A = np.transpose(np.column_stack((verts, np.ones(verts.shape[0]))))
b = np.append(pt, 1)
retur... | 5869c40d9b95280d3db77dd7eb3a42fab46c45a8 | 3,637,251 |
import os
def get_masked_fastas(bed):
"""create the masked fasta files per chromosome. needed to run bl2seq.
and puts it into a dictionary seqid to path to genomic masked fasta"""
f = bed.fasta.fasta_name
fname = op.splitext(op.basename(f))[0]
d = op.dirname(f) + "/%s_split" % fname
try: os.mk... | 2eb0eb7c9604563463ec7dd2d1e231804396edeb | 3,637,252 |
import re
def parse_regex(ctx, param, values):
"""Compile a regex if given.
:param click.Context ctx: click command context.
:param click.Parameter param: click command parameter (in this case,
``ignore_regex`` from ``-r|--ignore-regiex``).
:param list(str) values: list of regular expressions... | b920d5a406ac3b7a8f28bb9125313c90eec5e212 | 3,637,253 |
import os
def FileJustRoot(fileName):
""" Gets just the root of the file name """
try:
return os.path.splitext(fileName)[0]
except:
return "" | 18fed9fbbaa0d5f3f08c89ff36a1f752605c52d2 | 3,637,254 |
import sys
import os
def generate_command(pbs_script, pbs_config, pbs_vars=None, python_exe=None):
"""Prepare a correct PBS command string"""
pbs_env_init()
# Initialisation
if pbs_vars is None:
pbs_vars = {}
# Necessary for testing
if python_exe is None:
python_exe = sys.ex... | 069d86b9e91ef65339e1ebaf99e9833af43df863 | 3,637,255 |
def get_query_string(**kwargs):
"""
Concatenates the non-None keyword arguments to create a query string for ElasticSearch.
:return: concatenated query string or None if not arguments were given
"""
q = ['%s:%s' % (key, value) for key, value in kwargs.items() if value not in (None, '')]
return ... | cc73c157a8975e5df9c98efcd5b10396e5175486 | 3,637,256 |
def check_bin(img):
"""Checks whether image has been properly binarized. NB: works on the assumption that there should be more
background pixels than element pixels.
Parameters
----------
img : np.ndarray
Description of parameter `img`.
Returns
-------
np.ndarray
A bina... | 808e4635befa5848d7683e6e12ead5b5ee297339 | 3,637,257 |
def add_quotes(path):
"""Return quotes if needed for spaces on path."""
quotes = '"' if ' ' in path and '"' not in path else ''
return '{quotes}{path}{quotes}'.format(quotes=quotes, path=path) | 6e65da4512183ef62a0ac22b4c3c74f9e5273fbd | 3,637,258 |
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
if len(actions(board)) == 0:
return True
if winner(board) is not None:
return True
return False
#raise NotImplementedError | 6776ad6a261dd8dd90abbb6abb5fa428f8149bba | 3,637,259 |
def login():
"""LogIn Page"""
if request.method == "GET":
return render_template("login.html")
email = request.form.get("email")
password = request.form.get("password")
remember = bool(request.form.get("remember"))
user = User.query.filter_by(email=email).first()
if not user or not... | 3db9447298ca149037cdac89e850e893d5f9ac37 | 3,637,260 |
from typing import List
from operator import not_
def apply_modifiers(membership: npt.ArrayLike, modifiers: List[str]) -> npt.ArrayLike:
"""
Apply a list of modifiers or hedges to a numpy array.
:param membership: Membership values to be modified.
:param modifiers: List of modifiers or hedges.
... | 6140646bc5943ba7c7b6ce597e033c9797ba5ab4 | 3,637,261 |
def unitY(m=1.0):
"""Return an unit vector on Y"""
return np.array((0, m, 0)) | fda046e085e9ab00d263ec7f5569bcd719113c5d | 3,637,262 |
def create_suction_model(radius):
"""Create a suction model"""
hm = np.zeros((2 * radius + 1, 2 * radius + 1))
hm1 = np.tile(np.arange(-radius, radius + 1), (2 * radius + 1, 1))
hm2 = hm1.T
d = np.sqrt(hm1**2 + hm2**2)
return np.where(d < radius, 1, 0).astype(np.float64) | df8e34b0b8957169099740dc74d07c813056dfc4 | 3,637,263 |
def model_entrypoint(model_name):
"""Fetch a model entrypoint for specified model name
"""
return _model_entrypoints[model_name] | 8c1658f07db87e99ffbde428bc55281b6b185639 | 3,637,264 |
def encrypt(data, password):
"""Enrcrypt data and return content in binary"""
try:
cipher = AES.new(password.encode(), AES.MODE_CBC)
cypher_text_bytes = cipher.encrypt(pad(data.encode(), AES.block_size))
return b'' + cipher.iv + b':' + cypher_text_bytes
except ValueError:
p... | 2e4719cc48ded4f8c5400bfb5ab583a229034261 | 3,637,265 |
from datetime import datetime
def change_datetime_to_str(input_time=None, str_format="%Y-%m-%d"):
"""
:param input_time: 指定需要转换的时间, 默认当前时间
:param str_format: 字符时间的格式, 默认%Y-%m-%d
:return:
"""
spec_time = input_time or datetime.datetime.now()
return spec_time.strftime(str_format) | f0f3a72ee05b41dbeec12b05a89a26542fcefb21 | 3,637,266 |
def find_possible_words(word: str, dictionary: list) -> list:
"""Return all possible words from word."""
possible_words = []
first_character = word[0]
last_character = word[len(word) - 1]
for dictionary_entry in dictionary:
if (dictionary_entry.startswith(first_character) and
... | a3e63e6b6b9d8de3ca718cfc8e031bbc34630d50 | 3,637,267 |
def diag_multidim_gaussian_log_likelihood(z_u, mean_u, logvar_u, varmin):
"""Log-likelhood under a multidimensional Gaussian distribution with diagonal covariance.
Returns the log-likelihood for the multidim distribution.
"""
return np.sum(diag_gaussian_log_likelihood(z_u, mean_u, logvar_u, varmin), axis=0) | 010b1f510a74b2af29fe0cc94a2c36bc9c980778 | 3,637,268 |
import os
def _shared_galaxy_properties(config_directory, kwds, for_tests):
"""Setup properties useful for local and Docker Galaxy instances.
Most things related to paths, etc... are very different between Galaxy
modalities and many taken care of internally to the container in that mode.
But this met... | 2ebda019b8752eadfe25bdc212a7ad64d8f6989c | 3,637,269 |
def get_method(java_object, method_name):
"""Retrieves a reference to the method of an object.
This function is useful when `auto_field=true` and an instance field has
the same name as a method. The full signature of the method is not
required: it is determined when the method is called.
:param ja... | 9678cf38bfcf8dd34d6ccbad9b689709e9ab3dc5 | 3,637,270 |
import os
def createRegionLabeledSet(setname, entity, label, mesh, format="Exodus II"):
"""Create a labeled set region.
setname | string, name of the region
entity | string, entity (see mesh_entity.py)
label | string, label id in mesh file (note this is usually a string containing an i... | e32ba65bdc08f88128d62b36348c899e7e3ebfdd | 3,637,271 |
def set_up_cube(
zero_point_indices=((0, 0, 7, 7),),
num_time_points=1,
num_grid_points=16,
num_realization_points=1,
):
"""Set up a cube with equal intervals along the x and y axis."""
zero_point_indices = list(zero_point_indices)
for index, indices in enumerate(zero_point_indices):
... | d19380e0cc7471178887ea006fa4f367461dac4d | 3,637,272 |
def messageBox(self, title, text, icon=QMessageBox.Information):
"""
Working on generic message box
"""
m = QMessageBox(self)
m.setWindowTitle(title)
m.setText(text)
m.setIcon(icon)
# yesButton = m.addButton('Yes', QMessageBox.ButtonRole.YesRole)
# noButton = m.addButton('No', QMess... | 7bec2d2f0ca1366382d5bfc800c23af424d9a3d3 | 3,637,273 |
def binary_seg_loss(loss):
"""
Chooses the binary segmentation loss to use depending on the loss name in parameter
:param loss: the type of loss to use
"""
if loss == 'focal':
return BinaryFocalLoss()
else:
return tf.keras.losses.BinaryCrossentropy() | 9d94a7e406a2fa1a12ba970731c7ce25b2408b21 | 3,637,274 |
def get_config_file():
""" Return the loaded config file if one exists. """
# config will be created here if we can't find one
new_config_path = os.path.expanduser('~/dagobahd.yml')
config_dirs = ['/etc',
os.path.expanduser('~/dagobah/dagobah/daemon/')]
config_filenames = ['dago... | 4a5009d5d6f5a4be6d953d7bc9150c033a56f187 | 3,637,275 |
def bostock_cat_colors(color_sets = ["set3"]):
"""
Get almost as many categorical colors as you please.
Get more than one of the color brewer sets with ['set1' , 'set2']
Parameters
----------
sets : list
list of color sets to return valid options are
(set1, set2, set3, paste... | d01a2c833c3ee4ab1a196184ec4aecdb6cfc97a0 | 3,637,276 |
def bbpssw_gates_and_measurement_bob(q1, q2):
"""
Performs the gates and measurements for Bob's side of the BBPSSW protocol
:param q1: Bob's qubit from the first entangled pair
:param q2: Bob's qubit from the second entangled pair
:return: Integer 0/1 indicating Bob's measurement outcome
"""
... | 71e981a99065ea2b0d76a2ebaacebdf04b53488a | 3,637,277 |
from typing import Tuple
def fiber_array(
n: int = 8,
pitch: float = 127.0,
core_diameter: float = 10,
cladding_diameter: float = 125,
layer_core: Tuple[int, int] = gf.LAYER.WG,
layer_cladding: Tuple[int, int] = gf.LAYER.WGCLAD,
) -> Component:
"""Returns a fiber array
.. code::
... | 88bf1536788313c99f6b3c56ce8633db8cc30b8b | 3,637,278 |
def delete(movie_id):
"""
deletes the movie from the database
:param movie_id: id to delete
:return: index file
"""
movie_to_delete_id = Movie.query.get(movie_id)
db_session.delete(movie_to_delete_id)
db_session.commit()
return redirect(url_for('home')) | cfaade7b63e4d4413b7593a667fe62d5de90eaad | 3,637,279 |
import torch
def one_vector_block_diagonal(num_blocks: int, vector_length: int) -> Tensor:
"""Computes a block diagonal matrix with column vectors of ones as blocks.
Associated with the mathematical symbol :math:`E`.
Example:
::
one_vector_block_diagonal(3, 2) == tensor([
... | babe3e8178f3d9cde9150909fbf890ae17830730 | 3,637,280 |
def get_cli_args():
"""
:return: argparse.Namespace with command-line arguments from user
"""
args = get_main_pipeline_arg_names().difference({
'output', 'ses', 'subject', 'task', WRAPPER_LOC[2:].replace('-', '_')
})
tasks = ('SST', 'MID', 'nback')
parser = get_pipeline_cli_argparser... | d728c1254ffcfdeb2ba883681dd997d578084e72 | 3,637,281 |
from google.cloud import securitycenter
def list_all_assets(organization_id):
"""Demonstrate listing and printing all assets."""
i = 0
# [START securitycenter_list_all_assets]
client = securitycenter.SecurityCenterClient()
# organization_id is the numeric ID of the organization.
# organizatio... | 882672c91e8a698730532e1e7801aba0d5ec7d05 | 3,637,282 |
def _0_to_empty_str(dataframe: pd.DataFrame, column_data_type: dict):
"""
데이터가 str인 column에 들어있는 0을 '' 로 바꾸어 준다.
column_data_type 에서 value가 'str' 인 column 만 바꾸어 준다.
"""
for column, datatype in column_data_type.items():
if datatype == "str":
dataframe[column].replace("0", "", inpl... | 2453b53c0e7a0067772f37d9d8c370b8accb933c | 3,637,283 |
def _predict(rel):
"""
Predicts the betrayal probabilities and returns them as an inference.Output object.
"""
return inference.predict(rel) | c3b0489bef0723012f1de336dad5f61c40d77c7e | 3,637,284 |
from datetime import datetime
def evaluate_exams(request, exam_id):
"""
Request-Methods :POST
Request-Headers : Authorization Token
Request-Body: Student-Solution -> JSON
Response: "student_name" -> str,
"teacher_name" -> str,
"batch" -> str,
"mark... | 688cf2cd43991c98475fb7921ad64fccd0ea2b36 | 3,637,285 |
def _accumulated_penalty_energy_fw(energy_to_track, penalty_matrix, parallel):
"""Calculates acummulated penalty in forward direction (t=0...end).
`energy_to_track`: squared abs time-frequency transform
`penalty_matrix`: pre-calculated penalty for all potential jumps between
two frequ... | cc05de06ab53a9dcf7937df8bc6c5613a649b01c | 3,637,286 |
def rot90(m, k=1, axis=2):
"""Rotate an array k*90 degrees in the counter-clockwise direction
around the given axis
This differs from np's rot90 because it's 3D
"""
m = np.swapaxes(m, 2, axis)
m = np.rot90(m, k)
m = np.swapaxes(m, 2, axis)
return m | 40bb5c4406e8f7a1f4f6019c56d1a734bee0eac6 | 3,637,287 |
def get_pads(onnx_node): # type: (NodeWrapper) -> Tuple[int, int, int]
"""
Get padding values for the operation described by an ONNX node.
If `auto_pad` attribute is specified as SAME_UPPER or SAME_LOWER, or VALID values are
calculated. Otherwise values are taken from the `pads` attribute.
`pads`... | 9199129f59c3f459dfbad209427f4dcb8b5863e7 | 3,637,288 |
from typing import Optional
import os
import re
def get_changelog_version() -> Optional[str]:
"""
Return latest version from changelog.txt file.
"""
version: Optional[str] = None
root_dir = hgit.get_client_root(super_module=False)
changelog_file = os.path.join(root_dir, "changelog.txt")
hd... | 83eff9412d13e33bb9c8ff0cc0f62dd34aa06c0f | 3,637,289 |
def from_dict(transforms):
"""Deserializes the transformations stored in a dict.
Supports deserialization of Streams only.
Parameters
----------
transforms : dict
Transforms
Returns
-------
out : solt.core.Stream
An instance of solt.core.Stream.
"""
if not... | bf09deac48819306a7fef9b98cd68775f3d9bcbd | 3,637,290 |
def create_mp_pool(nproc=None):
"""Creates a multiprocessing pool of processes.
Arguments
---------
nproc : int, optional
number of processors to use. Defaults to number of available CPUs
minus 2.
"""
n_cpu = pathos.multiprocessing.cpu_count()
if nproc is None:
... | 37b750fb961535eada1924f524a4ec851ad7d613 | 3,637,291 |
def subpixel_edges(img, threshold, iters, order):
"""
Detects subpixel features for each pixel belonging to an edge in `img`.
The subpixel edge detection used the method published in the following paper:
"Accurate Subpixel Edge Location Based on Partial Area Effect"
http://www.sciencedirect.com/sci... | 546a8d1aedd1c53a329ce7a6e600307cf85b70a4 | 3,637,292 |
import numbers
import numpy
def arrays(hyperchunks, array_count):
"""Iterate over the arrays in a set of hyperchunks."""
class Attribute(object):
def __init__(self, expression, hyperslices):
self._expression = expression
self._hyperslices = hyperslices
@property
def expression(self):
... | 0b4e8833b1dd0f7cf90ed1fc97dbc77d76e29e17 | 3,637,293 |
from typing import Union
import torch
import types
def ne(x: Union[DNDarray, float, int], y: Union[DNDarray, float, int]) -> DNDarray:
"""
Returns a :class:`~heat.core.dndarray.DNDarray` containing the results of element-wise rich comparison of non-equality between values from two operands, commutative.
T... | f948f586781fb6c841a576b19defe2dff388469b | 3,637,294 |
def _quote_embedded_quotes(text):
"""
Replace any embedded quotes with two quotes.
:param text: the text to quote
:return: the quoted text
"""
result = text
if '\'' in text:
result = result.replace('\'', '\'\'')
if '"' in text:
result = result.replace('"', '""')
ret... | 71231e590e025c2ceb7b2dd4fde4465a9ff61a4c | 3,637,295 |
def exp2(x):
"""Calculate 2**x"""
return 2 ** x | d76d1e344e79ebb05d38a2e7e6ef36b6f367e85b | 3,637,296 |
import json
from typing import Generator
def play():
"""Play page."""
ticket_name = request.cookies.get('ticket_name')
ticket = None
game = get_game()
new_ticket = True
if ticket_name:
ticket = Ticket.get_by_name(ticket_name)
new_ticket = ticket and ticket.game != game.id
... | 75dd74a843c60d7eea2f1f2ffd08febbabbf5d41 | 3,637,297 |
def count_search_results(idx, typ, query, date_range, exclude_distributions,
exclude_article_types):
"""Count the number of results for a query
"""
q = create_query(query, date_range, exclude_distributions,
exclude_article_types)
#print q
return _es().... | b53742010645fc363abca8ddad5a15c7268ff49b | 3,637,298 |
def ifft(data: np.ndarray) -> np.ndarray:
"""
Perform inverse discrete Fast Fourier transform of data by conjugating signal.
Arguments:
data: frequency data to be transformed (np.array, shape=(n,), dtype='float64')
Return:
result: Inverse transformed data
"""
n = len(data)
result =... | 540ed47b2c7c4085609a9f94dba469c2b3a32d7a | 3,637,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.