content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def p_express_arg_8(p):
"""
express_arg : express_arg ARITOP express_arg
"""
p[0] = Expression(p[2], p[1], p[3]) | 5,340,100 |
def xy_to_array_origin(image):
"""Return view of image transformed from Cartesian to array origin."""
return rgb_transpose(image[:, ::-1]) | 5,340,101 |
def test_start_test_program():
"""
>>> write('t.py',
... '''
... import time
... time.sleep(1)
... open('x', 'w').close()
... time.sleep(99)
... ''')
>>> write('conf',
... '''
... <runner>
... program %s t.py
... start-test-program cat x
... </runner>
...... | 5,340,102 |
def read_csv(infile, delimiter=',', encoding='utf-8', named=False):
"""Reads a csv as a list of lists (unnamed) or a list of named tuples (named)
Args:
string infile: the file to read in
OPTIONAL:
string delimiter: the delimiter used (default ',')
encoding encoding: the ... | 5,340,103 |
def publish_ims_legacy(f='ims_legacy'):
""" create public version of data by deletion of all email addresses """
out_dir = global_vars['published_files_directory']
data = {}
dls = []
infile = open(f + '.txt')
instring = infile.read()
##instring = instring.replace(':description',' :citati... | 5,340,104 |
def is_ivy_enabled(ctx):
"""Determine if the ivy compiler should be used to by the ng_module.
Args:
ctx: skylark rule execution context
Returns:
Boolean, Whether the ivy compiler should be used.
"""
# Check the renderer flag to see if Ivy is enabled.
# This is intended to support ... | 5,340,105 |
def get_directions_id(destination):
"""Get place ID for directions, which is place ID for associated destination, if an event"""
if hasattr(destination, 'destination'):
# event with a related destination; use it for directions
if destination.destination:
return destination.destinatio... | 5,340,106 |
def decode_token(params, token_field=None):
"""
This function is used to decode the jwt token into the data that was used
to generate it
Args:
session_obj: sqlalchemy obj used to interact with the db
params: json data received with request
token_field: name of the field that tok... | 5,340,107 |
def gas_arrow(ods, r, z, direction=None, snap_to=numpy.pi / 4.0, ax=None, color=None, pad=1.0, **kw):
"""
Draws an arrow pointing in from the gas valve
:param ods: ODS instance
:param r: float
R position of gas injector (m)
:param z: float
Z position of gas injector (m)
:param... | 5,340,108 |
def get_word_vector(text, model, num):
"""
:param text: list of words
:param model: word2vec model in Gensim format
:param num: number of the word to exclude
:return: average vector of words in text
"""
# Creating list of all words in the document which are present in the... | 5,340,109 |
def find_storage_pool_type(apiclient, storagetype='NetworkFileSystem'):
"""
@name : find_storage_pool_type
@Desc : Returns true if the given storage pool type exists
@Input : type : type of the storage pool[NFS, RBD, etc.,]
@Output : True : if the type of storage is found
False : if th... | 5,340,110 |
def test_feed_from_annotations_item_guid(factories):
"""Feed items should use the annotation's HTML URL as their GUID."""
annotation = factories.Annotation(
created=datetime.datetime(year=2015, month=3, day=11)
)
feed = rss.feed_from_annotations(
[annotation], _annotation_url(), mock.Mo... | 5,340,111 |
def parse_year(candidate: Any) -> int:
"""Parses the given candidate as a year literal. Raises a ValueError
when the candidate is not a valid year."""
if candidate is not None and not isinstance(candidate, int):
raise TypeError("Argument year is expected to be an int, "
"but ... | 5,340,112 |
def dropout2d(tensor: Tensor, p: float = 0.2) -> Tensor:
"""
Method performs 2D channel-wise dropout with a autograd tensor.
:param tensor: (Tensor) Input tensor
:param p: (float) Probability that a activation element is set to zero
:return: (Tensor) Output tensor
"""
# Check argument
as... | 5,340,113 |
def svn_repos_finish_report(*args):
"""svn_repos_finish_report(void * report_baton, apr_pool_t pool) -> svn_error_t"""
return _repos.svn_repos_finish_report(*args) | 5,340,114 |
def step(
read_path: Path,
write_path: Path,
overrides
) -> None:
"""
Read config, apply overrides and write out.
"""
step_config(read_path, write_path, overrides) | 5,340,115 |
def problem451():
"""
Consider the number 15.
There are eight positive numbers less than 15 which are coprime to 15: 1,
2, 4, 7, 8, 11, 13, 14.
The modular inverses of these numbers modulo 15 are: 1, 8, 4, 13, 2, 11,
7, 14
because
1*1 mod 15=1
2*8=16 mod 15=1
... | 5,340,116 |
def collate_molgraphs(data):
"""Batching a list of datapoints for dataloader.
Parameters
----------
data : list of 3-tuples or 4-tuples.
Each tuple is for a single datapoint, consisting of
a SMILES, a DGLGraph, all-task labels and optionally
a binary mask indicating the existenc... | 5,340,117 |
def os_path_abspath():
"""将相对路径转换为绝对路径"""
os.chdir("C:\\")
paths = [
".",
"..",
"/one/two/three",
"./one/two",
]
for path in paths:
print("{!r:>21}: {!r}".format(path, os.path.abspath(path))) | 5,340,118 |
def reshape_practice(x):
"""
Given an input tensor of shape (24,), return a reshaped tensor y of shape
(3, 8) such that
y = [
[x[0], x[1], x[2], x[3], x[12], x[13], x[14], x[15]],
[x[4], x[5], x[6], x[7], x[16], x[17], x[18], x[19]],
[x[8], x[9], x[10], x[11], x[20], x[21], x[22], x[23]],
]
... | 5,340,119 |
def xnnpack_cc_library(
name,
srcs = [],
psimd_srcs = [],
x86_srcs = [],
aarch32_srcs = [],
aarch64_srcs = [],
asmjs_srcs = [],
wasm_srcs = [],
wasmsimd_srcs = [],
copts = [],
gcc_copts = [],
msvc_copts = [],
mingw_c... | 5,340,120 |
def recouvrement_view(request, id):
"""
Fonction Detail
"""
user = request.user
recouvrement = Recouvrement.objects.filter(user=user).get(id=id)
context = {
'recouvrement': recouvrement,
}
template_name = 'pages/recouvrement/recouvrement_view.html'
return render(reque... | 5,340,121 |
def getFileServicesNames(fileServices=None, verbose=True):
"""
Returns the names and description of the fileServices available to the user.
:param fileServices: a list of FileService objects (dictionaries), as returned by Files.getFileServices(). If not set, then an extra internal call to Jobs.getFileServi... | 5,340,122 |
def load_demo_data_from_scratch(*args, **kwargs):
"""Loads demo data for testing purpose. Do not use this in production"""
data_files_1 = os.path.join(BASE_DIR, 'data/data/setup/*.json')
data_files_2 = os.path.join(BASE_DIR, 'data/data/admin_units/*.json')
data_files_3 = os.path.join(BASE_DIR, 'data/da... | 5,340,123 |
def username_in_path(username, path_):
"""Checks if a username is contained in URL"""
if username in path_:
return True
return False | 5,340,124 |
def str_parse_as_utf8(content) -> str:
"""Returns the provided content decoded as utf-8."""
return content.decode('utf-8') | 5,340,125 |
def IGet(InterfaceItemPath):
"""
Returns the current value of a ZBrush or ZScript interface item
Output: The item value
"""
pass | 5,340,126 |
def create_wiki_titles():
""" Read global variable DATA and get all available articles titles.
After update global variable wiki_articles_titles with them.
:return: None
:rtype: None
"""
wiki_articles_titles = []
for article_title, question, answer, article in DATA:
wiki_... | 5,340,127 |
def TypeProviderClient(version):
"""Return a Type Provider client specially suited for listing types.
Listing types requires many API calls, some of which may fail due to bad
user configurations which show up as errors that are retryable. We can
alleviate some of the latency and usability issues this causes by... | 5,340,128 |
def create_indicator(
pattern: str,
pattern_type: str,
created_by: Optional[Identity] = None,
name: Optional[str] = None,
description: Optional[str] = None,
valid_from: Optional[datetime] = None,
kill_chain_phases: Optional[List[KillChainPhase]] = None,
labels: Optional[List[str]] = None... | 5,340,129 |
def write_filtered_mtx(
raw_barcode_filename,
raw_matrix_filename,
filtered_barcode_filename,
filtered_matrix_filename,
):
"""wrapper for filter_mtx that will save the filtered matrix
We read the the raw barcodes, raw matrix, and filtered barcodes
and then yield the rows from the raw matrix... | 5,340,130 |
def import_data(
path_to_csv: str,
response_colname: str,
standards_colname: str,
header: int = 0,
nrows: int = None,
skip_rows: int = None,
) -> pd.DataFrame:
"""Import standard curve data from a csv file.
Args:
path_to_csv: Refer to pd.read_csv docs.
response_colname: ... | 5,340,131 |
def plus(x: np.ndarray, y: np.ndarray) -> np.ndarray:
""" 矩阵相加"""
if x.shape == y.shape:
return x + y | 5,340,132 |
def add_noise(wave, noise, fs, snr, start_time, duration, wave_power):
"""Add a noise to wave.
"""
noise_power = np.dot(noise, noise) / noise.shape[0]
scale_factor = np.sqrt(10**(-snr/10.0) * wave_power / noise_power)
noise = noise * scale_factor
offset = int(start_time * fs)
add_length = mi... | 5,340,133 |
def _sort_factors(factors, **args):
"""Sort low-level factors in increasing 'complexity' order."""
def order_if_multiple_key(factor):
f, n = factor
return len(f), n, default_sort_key(f)
def order_no_multiple_key(f):
return len(f), default_sort_key(f)
if args.get('multiple', Tru... | 5,340,134 |
def get_affix(text):
"""
This method gets the affix information
:param str text: Input text.
"""
return " ".join(
[word[-4:] if len(word) >= 4 else word for word in text.split()]) | 5,340,135 |
async def async_setup_entry(hass, config_entry):
"""Konfigurowanie integracji na podstawie wpisu konfiguracyjnego."""
_LOGGER.info("async_setup_entry " + str(config_entry))
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(config_entry, "sensor")
)
return True | 5,340,136 |
def analyse_branching(geom,ordering_system,conversionFactor,voxelSize):
""" Does a branching analysis on the tree defined by 'geom'
Inputs:
- geom: A geometry structure consisting of element list, node location and radii/lengths
- ordering_system: the ordering system to be used in analysis (e.... | 5,340,137 |
def remove_start(s: str) -> str:
"""
Clear string from start '-' symbol
:param s:
:return:
"""
return s[1:] if s.startswith('-') else s | 5,340,138 |
async def get_user_requests(user, groups):
"""Get requests relevant to a user.
A user sees requests they have made as well as requests where they are a
secondary approver
"""
dynamo_handler = UserDynamoHandler(user)
all_requests = await dynamo_handler.get_all_requests()
query = {
"d... | 5,340,139 |
async def test_import_unknown_exception(opp):
"""Test we handle unknown exceptions from import."""
await setup.async_setup_component(opp, "persistent_notification", {})
with patch(
"openpeerpower.components.foscam.config_flow.FoscamCamera",
) as mock_foscam_camera:
mock_foscam_camera.si... | 5,340,140 |
def list_dirs(path):
"""遍历文件夹下的文件夹,并返回文件夹路径列表
:param path:
:return:
"""
if not os.path.exists(path):
os.mkdir(path)
_path_list = []
for lists in os.listdir(path):
sub_path = os.path.join(path, lists)
# 如果是文件夹
if os.path.isdir(sub_path):
_path_list.... | 5,340,141 |
def main(reddit_client, subreddit):
"""
Execute the logic of the bot. Run after init() is successful.
:param reddit_client: PRAW Reddit Object
:param subreddit: String name of the subreddit to check
:return: Nothing
"""
logging.info('Getting ' + str(config.reddit_commentsPerCheck) +... | 5,340,142 |
def seaborn(data, row_labels=None, col_labels=None, **args):
"""Heatmap based on seaborn.
Parameters
----------
data : numpy array
data array.
row_labels
A list or array of length N with the labels for the rows.
col_labels
A list or array of length M with the labels for ... | 5,340,143 |
def info(context: AnonAPIContext):
"""Show batch in current directory"""
logger.info(context.get_batch().to_string()) | 5,340,144 |
def get_artist_title(path):
""" Return artist & title information from filename """
directory, filename = os.path.split(path)
name, extension = os.path.splitext(filename)
# Splitting out artist & title with regular expression
result = re.search("^([\w\s\.\',\+\-&]+?) - ([\(\)\w\s\.\',\-\!&]+)", nam... | 5,340,145 |
def normalize_column(df_column, center_at_zero=False):
"""Converts an unnormalized dataframe column to a normalized
1D numpy array
Default: normalizes between [0,1]
(center_at_zero == True): normalizes between [-1,1] """
normalized_array = np.array(df_column, dtype="float64")
amax, amin = np.m... | 5,340,146 |
def get_tests():
"""Grab all of the tests to provide them to setup.py"""
start_dir = os.path.dirname(__file__)
return unittest.TestLoader().discover(start_dir, pattern='*.py') | 5,340,147 |
def apply_mask(image, mask):
"""Apply the given mask to the image.
"""
image = image.astype(np.uint8)
image = np.array(image)
for c in range(3):
image[:, :, c] = np.where(mask == 1,
cv2.blur(image[:, :, c],(40,40)),
image[... | 5,340,148 |
def pairCorrelationFunction_3D(x, y, z, S, rMax, dr):
"""Compute the three-dimensional pair correlation function for a set of
spherical particles contained in a cube with side length S. This simple
function finds reference particles such that a sphere of radius rMax drawn
around the particle will fit e... | 5,340,149 |
def handle(req):
"""handle a request to the function
Args:
req (str): request body
"""
dir_contents = os.listdir(SECRETS_DIR)
print(dir_contents)
with open(SECRETS_DIR+"my-new-secret") as fptr:
print(fptr.read())
return dir_contents | 5,340,150 |
def _find_endpoints_of_skeleton(binary_image_matrix):
"""Finds endpoints of skeleton.
:param binary_image_matrix: M-by-N numpy array of integers in 0...1. If
binary_image_matrix[i, j] = 1, grid cell [i, j] is part of the skeleton.
:return: binary_endpoint_matrix: M-by-N numpy array of integers in ... | 5,340,151 |
def set_up():
"""
"""
reset_config()
config['app']['considering_candles'] = [('Sandbox', 'BTC-USD')]
store.reset()
store.trades.init_storage() | 5,340,152 |
def get_today_timestamp():
"""
Get the formatted timestamp for today
"""
today = dt.datetime.today()
stamp = today.strftime("%d") + today.strftime("%b") + today.strftime("%Y")
return stamp | 5,340,153 |
def interpolate_to_mesh(
old_mesh, new_mesh, params_to_interp=["VSV", "VSH", "VPV", "VPH"]
):
"""
Maps both meshes to a sphere and interpolate values
from old mesh to new mesh for params to interp.
Returns the original coordinate system
Values that are not found are given zero
"""
# sto... | 5,340,154 |
def massAvg(massList, method='weighted', weights=None):
"""
Compute the average mass of massList according to method.
If method=weighted but weights were not properly defined,
switch method to harmonic.
If massList contains a zero mass, switch method to mean.
:parameter method: possibl... | 5,340,155 |
def listListenerPortsOnServer(nodeName, serverName):
"""List all of the Listener Ports on the specified Node/Server."""
m = "listListenerPortsOnServer:"
sop(m,"nodeName = %s, serverName = %s" % (nodeName, serverName))
cellName = getCellName() # e.g. 'xxxxCell01'
lPorts = _splitlines(AdminControl.... | 5,340,156 |
def forward_propagation_with_dropout(X, parameters, keep_prob=0.5):
"""
实现具有随机舍弃节点的前向传播。
LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID.
参数:
X - 输入数据集,维度为(2,示例数)
parameters - 包含参数“W1”,“b1”,“W2”,“b2”,“W3”,“b3”的python字典:
W1 - 权重矩阵,维度为(20,2)
... | 5,340,157 |
def getPotInstance(pot_name):
""" Try to get an instance of a give pot_name
Return
----------
pot_module: module object of pot_name, if it is a combined list, return None
pot_instance: module instance, if it is not 3D or not available, return None
"""
pot_module = None
pot_instance=None... | 5,340,158 |
def upload_processed_files(job_context: Dict) -> Dict:
"""Uploads the processed files and removes the temp dir for the job.
If job_context contains a "files_to_upload" key then only those
files will be uploaded. Otherwise all files will be uploaded.
If job_context contains a "job_dir_prefix" key then t... | 5,340,159 |
def update_hook(branch, from_rev, to_rev, installdir):
""" Function to be called from the update hook """
if from_rev == gitinfo.NULL_COMMIT:
from_rev = gitinfo.START_COMMIT
changeset_info = githook.UpdateGitInfo(branch, from_rev, to_rev)
hooks_ok = run_hooks(changeset_info, installdir)
m... | 5,340,160 |
def definition():
"""
Most recent student numbers and fees by set
(i.e. by year, costcentre and set category.),
aggregated by fee, aos code, seesion and fee_category.
"""
sql = """
select s.set_id, s.acad_year, s.costc,
s.set_cat_id,
fsc.description as set_cat_description,
f... | 5,340,161 |
def ssh_connection():
"""Returns the current tmate SSH connection string."""
result = subprocess.run(['tmate', 'display', '-p', "#{tmate_ssh}"],
text=True,
capture_output=True)
if result.returncode != 0:
raise TmateException('Failed to interact... | 5,340,162 |
def get_geo_distance(p1, p2, signed=False):
"""Returns distance (meters) between to lat/lon points"""
d = geopy.distance.vincenty(p1, p2).m # .m for meters
return -d if (p2[0] < p1[0] or p2[1] > p1[1]) else d | 5,340,163 |
def bot_info(sub_bots, cfg):
"""Returns a description for this TweetCredReviewer
:param sub_bots: a list of bot items used by this TweetCredReviewer
:param cfg: config options
:returns: a `TweetCredReviewer` item
:rtype: dict
"""
result = {
'@context': ci_context,
'@type': '... | 5,340,164 |
async def metrics_upload(websocket, client_set: ClientSet, msg, *_):
"""
Save the performance metrics sent by the client to disk.
"""
metrics, route_id = msg['metrics'], msg['metrics']['route_id']
logging.info(f"Received performance metrics for routeID '{route_id}'")
save_json(route_id, metrics,... | 5,340,165 |
def in_yelling(channel):
"""
checks that channel is #yelling
exists for test mocking
"""
chan = bot.channels.get(channel)
return chan and chan.name == "yelling" | 5,340,166 |
def draw_adjacency_list():
"""Solution to exercise R-14.4.
Draw an adjacency list representation of the undirected graph shown in
Figure 14.1.
---------------------------------------------------------------------------
Solution:
-----------------------------------------------------------------... | 5,340,167 |
def some_path(directory) -> str:
"""Generate unique path in the directory."""
return os.path.join(directory, str(uuid())) | 5,340,168 |
def get_user_categories(user_id, public=False):
"""Get a user's categories.
Arguments: user_id as int, Boolean 'public' (optional).
Returns list of Category objects. Either all private or all public.
"""
return db_session.query(Category).filter((Category.user_id==user_id)&(Category.public==public))... | 5,340,169 |
def dict_to_one(dp_dict):
"""Input a dictionary, return a dictionary that all items are set to one.
Used for disable dropout, dropconnect layer and so on.
Parameters
----------
dp_dict : dictionary
The dictionary contains key and number, e.g. keeping probabilities.
Examples
------... | 5,340,170 |
def handle_500(request, response, exception):
"""Default handler for 500 status code"""
logging.exception(exception)
response.set_status(500) | 5,340,171 |
def file_io_read_img_slice(path, slicing, axis, is_label, normalize_spacing=True, normalize_intensities=True, squeeze_image=True,adaptive_padding=4):
"""
:param path: file path
:param slicing: int, the nth slice of the img would be sliced
:param axis: int, the nth axis of the img would be sliced
:p... | 5,340,172 |
def get_document_path(workspace_name: str, document_name: str) -> Path:
"""
TODO docstring
"""
path = (
Path(".")
/ Directory.DATA.value
/ Directory.WORKSPACES.value
/ workspace_name
/ document_name
)
if not path.exists():
raise HTTPException(
... | 5,340,173 |
def upload_lambda_zip(bosslet_config, path):
"""
Upload a multilambda.domain.zip to the S3 bucket. Useful when
developing and small changes need to be made to a lambda function, but a full
rebuild of the entire zip file isn't required.
"""
s3 = bosslet_config.session.client('s3')
with open... | 5,340,174 |
def is_replaced_image(url):
"""
>>> is_replaced_image('https://rss.anyant.com/123.jpg?rssant=1')
True
"""
return url and RSSANT_IMAGE_TAG in url | 5,340,175 |
def version(*args, **kwargs): # real signature unknown
"""
Returns a tuple of major, minor, and patch release numbers of the
underlying DB library.
"""
pass | 5,340,176 |
def notification_server():
"""
Starts a HeyU notifier. The specific notifier is specified as a
subcommand.
"""
pass | 5,340,177 |
def get_raw_segment(fast5_fn, start_base_idx, end_base_idx, basecall_group='Basecall_1D_000',
basecall_subgroup='BaseCalled_template'):
"""
Get the raw signal segment given the start and end snp_id of the sequence.
fast5_fn: input fast5 file name.
start_base_idx: start snp_id of the ... | 5,340,178 |
def center_distance(gt_box: EvalBox, pred_box: EvalBox) -> float:
"""
L2 distance between the box centers (xy only).
:param gt_box: GT annotation sample.
:param pred_box: Predicted sample.
:return: L2 distance.
"""
return np.linalg.norm(np.array(pred_box.translation[:2]) - np.array(gt_box.tr... | 5,340,179 |
def set_specs(override_spec_data):
""" Override Resource Specs """
excludes = []
includes = []
# Extract the exclude list from the override file
if 'ExcludeResourceTypes' in override_spec_data:
excludes = override_spec_data.pop('ExcludeResourceTypes')
if 'IncludeResourceTypes' in overr... | 5,340,180 |
def Dc(z, unit, cosmo):
"""
Input:
z: redshift
unit: distance unit in kpc, Mpc, ...
cosmo: dicitonary of cosmology parameters
Output:
res: comoving distance in unit as defined by variable 'unit'
"""
res = cosmo.comoving_distance(z).to_value(unit) #*cosmo.h
return... | 5,340,181 |
def _get_all_answer_ids(
column_ids,
row_ids,
questions,
):
"""Maps lists of questions with answer coordinates to token indexes."""
answer_ids = [0] * len(column_ids)
found_answers = set()
all_answers = set()
for question in questions:
for answer in question.answer.answer_coordinates:
al... | 5,340,182 |
def transduce(source, transducer) -> ObservableBase:
"""Execute a transducer to transform the observable sequence.
Keyword arguments:
:param Transducer transducer: A transducer to execute.
:returns: An Observable sequence containing the results from the
transducer.
:rtype: Observable
"... | 5,340,183 |
def readfile(filename):
""" Read candidate json trigger file and return dict
TODO: add file lock?
"""
with open(filename, 'r') as fp:
dd = json.load(fp)
return dd | 5,340,184 |
def isoformViewer():
"""
Make a "broken" horizontal bar plot, ie one with gaps
"""
fig = pylab.figure()
ax = fig.add_subplot(111)
ax.broken_barh([ (110, 30), (150, 10) ] , (10, 5), facecolors=('gray','blue')) # (position, length) - top row
ax.broken_barh([ (10, 50), (100, 20), (130, 10)... | 5,340,185 |
def get_phonopy_gibbs(
energies,
volumes,
force_constants,
structure,
t_min,
t_step,
t_max,
mesh,
eos,
pressure=0,
):
"""
Compute QHA gibbs free energy using the phonopy interface.
Args:
energies (list):
volumes (list):
force_constants (list):... | 5,340,186 |
def forgot():
"""
Allows an administrator to state they forgot their password,
triggering a email for further instructions on how to reset their password.
"""
if current_user.is_authenticated:
return redirect(url_for('index'))
form = RequestResetPasswordForm()
if form.validate_on... | 5,340,187 |
def install_enterprise(ansible_client):
"""
Install OpenShift Container Platform from RPMs.
:param ansible_client: Ansible client
"""
install_openshift(ansible_client, 'enterprise') | 5,340,188 |
def test_s3_path_for_public_key():
"""
Should get s3 path for public key
"""
# When: I get S3 path for public key
s3path = provider._s3_path('default')
# Then: Expected path is returned
eq_(s3path, 'totem/keys/default-pub.pem') | 5,340,189 |
def test_tell_total_vaccinated_booster():
"""Tests whether results returned by icl.tell_total_vaccinated with dose="booster" and with ranging for date options make sense (i.e. the number of total vaccinated individuals is equal to the sum of the number of vaccinated individuals in three periods into which the whole... | 5,340,190 |
def diffractionAngle(inc):
"""Return the diffraction angle for the UV yaw system
Input graze angle in degrees
Output diffraction graze angle in degrees"""
alpha0 = np.sin((90.-inc)*np.pi/180)
alpha1 = alpha0 - 266e-9/160e-9
dang = 90 - np.arcsin(np.abs(alpha1))*180/np.pi
return dang | 5,340,191 |
def check_conf(conf_filepath):
"""Wrap haproxy -c -f.
Args:
conf_filepath: Str, path to an haproxy configuration file.
Returns:
valid_config: Bool, true if configuration passed parsing.
"""
try:
subprocess.check_output(['haproxy', '-c', '-f', conf_filepath],
... | 5,340,192 |
def get_subject(email):
"""
Takes an email Message object and returns the Subject as a string,
decoding base64-encoded subject lines as necessary.
"""
subject = email.get('Subject', '')
result = decode_header(subject)
subject = result[0][0]
if isinstance(subject, str):
return sub... | 5,340,193 |
def distort(dist_mat, mat):
"""Apply distortion matrix to lattice vectors or sites.
Coordinates are assumed to be Cartesian."""
array = np.array(mat)
for i in range(len(mat)):
array[i, :] = np.array([np.sum(dist_mat[0, :]*mat[i, :]),
np.sum(dist_mat[1, :]*mat[i, ... | 5,340,194 |
def sample(
sampler: Union[typing.RelativeTime, Observable[Any]],
scheduler: Optional[abc.SchedulerBase] = None,
) -> Callable[[Observable[_T]], Observable[_T]]:
"""Samples the observable sequence at each interval.
.. marble::
:alt: sample
---1-2-3-4------|
[ sample(4) ]
... | 5,340,195 |
def test_positive_judgement(module_headers, observable, observable_type):
"""Perform testing for enrich observe observables endpoint to get
judgement for observable from CyberCrime Tracker
ID: CCTRI-844-4e53f335-d803-4c3e-a582-af02c94cf727
Steps:
1. Send request to enrich deliberate observable... | 5,340,196 |
def get_genome_dir(infra_id, genver=None, annver=None, key=None):
"""Return the genome directory name from infra_id and optional arguments."""
dirname = f"{infra_id}"
if genver is not None:
dirname += f".gnm{genver}"
if annver is not None:
dirname += f".ann{annver}"
if key is not Non... | 5,340,197 |
def stream_with_context(func: Callable) -> Callable:
"""Share the current request context with a generator.
This allows the request context to be accessed within a streaming
generator, for example,
.. code-block:: python
@app.route('/')
def index() -> AsyncGenerator[bytes, None]:
... | 5,340,198 |
def silence_removal(signal, sampling_rate, st_win, st_step, smooth_window=0.5, weight=0.5, plot=False):
"""
Event Detection (silence removal)
ARGUMENTS:
- signal: the input audio signal
- sampling_rate: sampling freq
- st_win, st_step: window size ... | 5,340,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.