content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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... | ca7a9f8baa433a2ed1828d1f0c8c3dd791d6ea12 | 3,646,600 |
import os
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):
... | b5a8e95e45adfbb1621762a9654aa237b0325d15 | 3,646,601 |
import seaborn as sns
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 lengt... | f03b3701334adcfc12f078b36a75498b2bd1914b | 3,646,602 |
import os
import re
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\.\',\+\-&]+?) - ([\(\)\... | b8e364e2bd299641396ed30659ad2720048cb4c5 | 3,646,603 |
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... | 4da61a899097812fc22bae1f93addbbcd861f786 | 3,646,604 |
import os
import unittest
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') | 68733f14ec7427705698c36ae411caaaff1c0e02 | 3,646,605 |
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[... | d14516edadd60bf5ba56d0ea77a8c6582a847e8e | 3,646,606 |
from numpy import zeros, sqrt, where, pi, mean, arange, histogram
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 t... | cec343757af93b6a49b6ecc856e31f311518a109 | 3,646,607 |
import os
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 | a568db7a6294a7e5d340cf64c23012f8f2809ba9 | 3,646,608 |
import numpy
import copy
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 ... | d6ea3aac54c95e658753f7e8a2a40762ffc32706 | 3,646,609 |
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 | 8fab2ad826c89b66acb083a1a1f07d340cf3ed9b | 3,646,610 |
import copy
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 m... | a64fd8a0ae8d0c8c6c6402741b6080a17e86c19f | 3,646,611 |
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.... | f2fdadcf06d47e55edaab44ca9e040cf8e116ae0 | 3,646,612 |
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)
... | 530d65644647efe4dc0f499cfc60869d412cfdf2 | 3,646,613 |
import warnings
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
... | 998de5b58e93832499f33852fc4fb3970491de4f | 3,646,614 |
from typing import Dict
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 "... | cb43f13e47ab825e1376a3421063fe0a21ff9345 | 3,646,615 |
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... | 4526ad1316ef823615bb41f80e09f7f0f256ba07 | 3,646,616 |
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... | 18ded7340bf8786a531faf76c702e682bb44e0f3 | 3,646,617 |
import subprocess
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... | 1e59126a2ba1a2755eb646d6279b3a320d5c0c5f | 3,646,618 |
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 | 162682ba9e45d2caad532d04e70cdeb9d6c02901 | 3,646,619 |
from sys import version
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_c... | 953cafbabf3a14f11a5b3b79e2b6a0301c845117 | 3,646,620 |
def in_yelling(channel):
"""
checks that channel is #yelling
exists for test mocking
"""
chan = bot.channels.get(channel)
return chan and chan.name == "yelling" | 3fafb60d81944badfd27136820569a25b2d0b7b9 | 3,646,621 |
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:
-----------------------------------------------------------------... | 95c02ad974f2d964596cf770708ed11aa061ea49 | 3,646,622 |
import os
import uuid
def some_path(directory) -> str:
"""Generate unique path in the directory."""
return os.path.join(directory, str(uuid())) | efaa5075942e8359a4ba9d7d6e231a7ecab96b5f | 3,646,623 |
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))... | fcc4ce90233771bb149120bc898ed52a12e46888 | 3,646,624 |
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
------... | 9d18b027a0458ca6e769a932f00705a32edcb3e7 | 3,646,625 |
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... | a55bb95bf152e144b7260716c60262f90f1650f4 | 3,646,626 |
from pathlib import Path
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():
... | 1c86e565987a9fe76fad938c1d763e29e49b0f84 | 3,646,627 |
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 | 292e04bd8dceb2dcc8b2c58dc24142158848c221 | 3,646,628 |
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 ... | 3f5ed060bacfa6feeb25dce02a3829d2b7496ee9 | 3,646,629 |
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... | 7b5106dca604d6c1c18e6f4c3d913a78c37577bb | 3,646,630 |
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... | 02985b75bd24b2a18b07f7f3e158f3c6217fdf18 | 3,646,631 |
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... | 260ae3e32d6c56b63d801e75e22622b9356cb44a | 3,646,632 |
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
"... | 8d0a3c12b16cd4984e9e49d66a459947d5f1315f | 3,646,633 |
import json
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 | a40d6fa93909a2c4bc2a09fada5411c80455dc4c | 3,646,634 |
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):... | df162a9cfc95417ba684caadba776243c2eb867d | 3,646,635 |
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... | 7e91014fbbc57c5a0e96a306865d1ff13dd1ddbe | 3,646,636 |
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 | 334dfb79c1d7ea39ed2b89ebb0592dbaf166144a | 3,646,637 |
import subprocess
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_filepa... | ceb2f78bcd4a688eb17c88915ebfde3f5a142e49 | 3,646,638 |
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... | c0e34d63532688827050d427479dd79f43cda48f | 3,646,639 |
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, ... | caa28cef38a7ac827b67100fe17479a48dfb72fd | 3,646,640 |
from ._sample import sample_
from typing import Union
import typing
from typing import Any
from typing import Optional
import abc
from typing import Callable
def sample(
sampler: Union[typing.RelativeTime, Observable[Any]],
scheduler: Optional[abc.SchedulerBase] = None,
) -> Callable[[Observable[_T]], Observa... | a127926dbffa7035f0da67edf138403a5df66d59 | 3,646,641 |
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... | ab033772575ae30ae346f96aed840c48fb01c556 | 3,646,642 |
from typing import Callable
from typing import Any
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('/')
... | ebfe2fc660fb68803ddc0517a3a5708748fe88ea | 3,646,643 |
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 ... | 0b6f3efab0c04a52af2667a461b9f2db7a256a1b | 3,646,644 |
def get_line_pixels(start, end):
"""Bresenham's Line Algorithm
Produces a list of tuples from start and end
>>> points1 = get_line((0, 0), (3, 4))
>>> points2 = get_line((3, 4), (0, 0))
>>> assert(set(points1) == set(points2))
>>> debuginfo(points1)
[(0, 0), (1, 1), (1, 2), (2, 3), (3, 4)]
... | 67cba479f156119348d7c0db6de4cbf676d45f50 | 3,646,645 |
import signal
def extrema(x):
"""
Gets the local extrema points from a time series. This includes endpoints if necessary.
Note that the indices will start counting from 1 to match MatLab.
Args:
x: time series vector
Returns:
imin: indices of XMIN
"""
x = np.asarray(x)
... | b4464398acb502741a48fe713438b2ebdc3d3063 | 3,646,646 |
import array
def d2X_dt2_Vanderpol(X, t=0):
""" Return the Jacobian matrix evaluated in X. """
return array([[0, 1 ],
[-2*r*X[1]*X[0]-w**2 , r*(1-X[0]**2)]]) | 47fff4981e130ac0140884553ff083fef501e479 | 3,646,647 |
def domain(domain):
"""Locate the given domain in our database and
render an info page for it.
"""
current_app.logger.info('domain [%s]' % domain)
g.domain = current_app.iwn.domain(domain)
if g.domain is None:
return Response('', 404)
else:
return render_template('domain.jinj... | 0f987c538835aa2b7eb6bb95643465a990246b39 | 3,646,648 |
def gaussian_filter(img, kernel_size, sigma=0):
"""take value weighted by pixel distance in the neighbourhood of center pixel.
"""
return cv2.GaussianBlur(img, ksize=kernel_size, sigmaX=sigma, sigmaY=sigma) | ef2c22528f88ccfa1bdae28dd1b814a01cae0261 | 3,646,649 |
def extractBillAdoptedLinks(soup):
"""Extract list of links for Adopted Bill Texts (HTML & PDF Versions)
"""
tables = soup.find_all("table")
content_table = [t for t in tables if t.text.strip().startswith("View Available Bill Summaries")][-1]
adopted_links = {}
for row in content_table.find_all(... | 58089f525beece643a617bd9a208a653e2b7e5b8 | 3,646,650 |
def uniq(string):
"""Removes duplicate words from a string (only the second duplicates).
The sequence of the words will not be changed.
"""
words = string.split()
return ' '.join(sorted(set(words), key=words.index)) | 2e5b6c51bc90f3a2bd7a4c3e845f7ae330390a76 | 3,646,651 |
def l2_regularizer(
params: kfac_jax.utils.Params,
haiku_exclude_batch_norm: bool,
haiku_exclude_biases: bool,
) -> chex.Array:
"""Computes an L2 regularizer."""
if haiku_exclude_batch_norm:
params = hk.data_structures.filter(
lambda m, n, p: "batchnorm" not in m, params)
if haiku_exclude_... | a13966229968aa40f27a1c5c1eb3bc8d3f578aca | 3,646,652 |
def _normalize(log_weights):
"""Normalize log-weights into weights and return resulting weights and log-likelihood increment."""
n = log_weights.shape[0]
max_logw = jnp.max(log_weights)
w = jnp.exp(log_weights - max_logw)
w_mean = w.mean()
log_likelihood_increment = jnp.log(w_mean) + max_logw
... | 1abaf1dd818e5012db8ec8ad5de1e718f934af54 | 3,646,653 |
import multiprocessing
def pq_compute_multi_core(matched_annotations_list,
gt_folder,
pred_folder,
categories,
file_client=None,
nproc=32):
"""Evaluate the metrics of Panoptic Segmenta... | 354a4c6133d8d2030694e71716e7beb487f845a0 | 3,646,654 |
def logout():
"""
Function that handles logout of user
---
POST:
description: remove curent user in the session
responses:
200:
description:
Successfuly log out user from the session.
"""
logout_user() # flask logout library
return redirect("/... | 86fc7d43f2ec13bcf966f2ddc592dacd86f0d158 | 3,646,655 |
import ctypes
def header(data):
"""Create class based on decode of a PCI configuration space header from raw data."""
buf = ctypes.create_string_buffer(data, len(data))
addr = ctypes.addressof(buf)
field_list = header_field_list(addr)
return header_factory(field_list).from_buffer_copy(data) | ca3c4ee8f4f52e2f3b62ee183c858ae64a24e4d5 | 3,646,656 |
def FilterByKeyUsingSideInput(pcoll, lookup_entries, filter_key):
"""Filters a single collection by a single lookup collection, using a common key.
Given:
- a `PCollection` (lookup_entries) of `(V)`, as a lookup collection
- a `PCollection` (pcoll) of `(V)`, as values to be filtered
- a commo... | 6318c46bf8725e3bcc65329af5dd2feceae208c0 | 3,646,657 |
def sw_maxent_irl(x, xtr, phi, phi_bar, max_path_length, nll_only=False):
"""Maximum Entropy IRL using our exact algorithm
Returns NLL and NLL gradient of the demonstration data under the proposed reward
parameters x.
N.b. the computed NLL here doesn't include the contribution from the MDP dynamics
... | fd52750ac8cff60cdce3a6bce09b8bd0b900e08f | 3,646,658 |
def __multiprocess_point_in_poly(df: pd.DataFrame,
x: str,
y: str,
poly: Polygon):
"""
Return rows in dataframe who's values for x and y are contained in some polygon coordinate shape
Parameters
---------... | dc89af19f17c79fd4b5c74d183e6fb6d89d14bec | 3,646,659 |
import time
def print_runtime(func, create_global_dict=True):
"""
A timer decorator that creates a global dict for reporting times across multiple runs
"""
def function_timer(*args, **kwargs):
"""
A nested function for timing other functions
"""
start = time.time()
... | 066b57281efad3fe672ba0737b783233dce9bef0 | 3,646,660 |
def generate_astrometry(kop, time_list):
"""
Simulates observational data.
:param kop: Keplerian orbit parameters
:param time_list: List of observation times
:return: astrometry
"""
trajectory = generate_complete_trajectory(kop, time_list)
return {'t':time_list,
'x':traje... | 9fc52b7cf4fa8b74e19bf3b0e416895fa40f8fee | 3,646,661 |
import io
def _open_remote(file_ref):
"""Retrieve an open handle to a file.
"""
return io.StringIO(_run_gsutil(["cat", file_ref]).decode()) | ea7571ed04b98e2aca72177a9c980aedf1647d1e | 3,646,662 |
def fit(image, labels, featurizer="../model/saved_model/UNet_hpa_4c_mean_8.pth"):
"""Train a pixel classifier.
Parameters
----------
image: np.ndarray
Image data to be classified.
labels: np.ndarray
Sparse classification, where 0 pixels are ingored, and other integer
values ... | dbd6e40b0d6ef363a55ad8f15ec2859d16c676e4 | 3,646,663 |
import json
import threading
def himydata_client(args):
"""Returns an instance of Himydata Client or DryRunClient"""
if args.dry_run:
return DryRunClient()
else:
with open(args.config) as input:
config = json.load(input)
if not config.get('disable_collection', True):
... | 21f704868c583d85c4d095da88654e729f28ef28 | 3,646,664 |
def KeywordString():
"""Returns the specified Keyword String
@note: not used by most modules
"""
return ST_KEYWORDS[1] | f43b32c32c16998d91c2dbf0cf6173f402c89333 | 3,646,665 |
def coo_index_to_data(index):
"""
Converts data index (row, col) to 1-based pixel-centerd (x,y) coordinates of the center ot the pixel
index: (int, int) or int
(row,col) index of the pixel in dtatabel or single row or col index
"""
return (index[1] + 1.0, index[0] + 1.0) | 5cf3ee2cc4ea234aaeb2d9de97e92b41c5daf149 | 3,646,666 |
def prepare_output_well(df, plates, output, rawdata, identifier_features, location_features):
""" Prepare the output file with plate, row and column information
Calculate penetrance and p-value
Args:
df: Existing combined dictionary
plates: ... | 907c4523ca15b52a66947864f12e4375816d047a | 3,646,667 |
def main(input_file):
"""Solve puzzle and connect part 1 with part 2 if needed."""
inp = read_input(input_file)
p1, p2 = part_1_and_2(inp)
print(f"Solution to part 1: {p1}")
print(f"Solution to part 2: {p2}")
return p1, p2 | 6edd09292e6ba0bccfcb1923e2f3011f47dfb331 | 3,646,668 |
def generateListPermutations(elements, level=0):
"""Generate all possible permutations of the list 'elements'."""
#print(" " * level, "gP(", elements, ")")
if len(elements) == 0:
return [[]]
permutations = []
for e in elements:
reduced = elements[:]
reduced.remove(e)
... | 1894b6726bedaaf634e8c7ac56fc1abd9e204eef | 3,646,669 |
import os
from datetime import datetime
def run_tfa(tfalclist_path, trendlisttfa_paths, datestfa_path, lcdirectory,
statsdir,
nworkers=16, do_bls_ls_killharm=True, npixexclude=10,
blsqmin=0.002, blsqmax=0.1, blsminper=0.2, blsmaxper=30.0,
blsnfreq=20000, blsnbins=1000, ... | 10626920a9cf01b7a53d6c4baa0d782b410341ba | 3,646,670 |
def has_security_updates(update_list):
"""
Returns true if there are security updates available.
"""
return filter_updates(update_list, 'category', lambda x: x == 'security') | 57fe7b66b3e678e50a2b44593ea29c26bdee12ac | 3,646,671 |
def lobby():
"""Return an unchecked place named lobby."""
return UncheckedPlace("Lobby") | 18bab877773086b9a29f4184c6948629e2162e4f | 3,646,672 |
import torch
def get_random_sample_indices(
seq_len, num_samples=100, device=torch.device("cpu")):
"""
Args:
seq_len: int, the sampled indices will be in the range [0, seq_len-1]
num_samples: sample size
device: torch.device
Returns:
1D torch.LongTensor consisting ... | e63eeb3a06687bcdbd9b1b9947db83caa5080b62 | 3,646,673 |
import hashlib
import re
def render_mesh_as_dot(mesh, template=DOT_TEMPLATE):
"""Renders the given mesh in the Graphviz dot format.
:param Mesh mesh: the mesh to be rendered
:param str template: alternative template to use
:returns: textual dot representation of the mesh
"""
custom_filters =... | 34826db4a1ab16cc07913b0381881876620551de | 3,646,674 |
def snrest(noisy: np.ndarray, noise: np.ndarray, axis=None):
"""
Computes SNR [in dB] when you have:
"noisy" signal+noise time series
"noise": noise only without signal
"""
Psig = ssq(noisy, axis)
Pnoise = ssq(noise)
return 10 * np.log10(Psig / Pnoise) | f7fb5c00324dfe81d225cb52d0a937c568222824 | 3,646,675 |
from pathlib import Path
def load(spect_path, spect_format=None):
"""load spectrogram and related arrays from a file,
return as an object that provides Python dictionary-like
access
Parameters
----------
spect_path : str, Path
to an array file.
spect_format : str
Valid for... | 2999c8745f7feecb0174f5a230194c6b098c606c | 3,646,676 |
def PSNR(a, b, max_val=255.0, name=None):
"""Returns the Peak Signal-to-Noise Ratio between a and b.
Arguments:
a: first set of images.
b: second set of images.
max_val: the dynamic range of the images (i.e., the difference between the
maximum the and minimum allowed values).
name: namespace ... | 0a140abc081b5faf0cbd1a9e4c67b4db62794f5d | 3,646,677 |
import functools
def command(f):
""" indicate it's a command of naviseccli
:param f: function that returns the command in list
:return: command execution result
"""
@functools.wraps(f)
def func_wrapper(self, *argv, **kwargs):
if 'ip' in kwargs:
ip = kwargs['ip']
... | 71160e4af7d4d64ca2a7ecd059d0c53f9e339308 | 3,646,678 |
def clean_data(file_name):
"""
file_name: file to be cleaned
This function converts the data types in the original dataframe into more suitable type.
The good news is that the orginal dataframe is already in good shape so there's less to do.
"""
df_input = pd.read_excel(file_name,sh... | cd283c97004f013622e4d2022a9c63424248a7f0 | 3,646,679 |
def get_contact_pages(buffer, domain):
"""
Returns links to all possible contact pages found on the site index page
"""
usual_contact_titles = [u'Contact', u'Contacts', u'About', u'Контакты', u'Связаться с нами']
usual_contact_urls = ['/contact', '/contacts', '/info']
result = list()
html =... | ed8f164fe7f85181df011067acb098f771ccc9fa | 3,646,680 |
def _hydrate_active_votes(vote_csv):
"""Convert minimal CSV representation into steemd-style object."""
if not vote_csv:
return []
votes = []
for line in vote_csv.split("\n"):
voter, rshares, percent, reputation = line.split(',')
votes.append(dict(voter=voter,
... | a1903578b1a0a0b3ab1e1f5c60982cfcc2d766a9 | 3,646,681 |
import random
def skew(width, height, magnitude, mode='random'):
"""
Skew the ChArUco in 4 different modes.
:param width:
:param height:
:param magnitude:
:param mode: 0: top narrow, 1: bottom narrow, 2: left skew, 3 right skew
:return:
"""
# Randomize skew
if mode == 'random... | 5212b5597dcf3052c73fe8321771386a3470f9a0 | 3,646,682 |
def aws_ec2_pricing():
"""---
get:
tags:
- aws
produces:
- application/json
description: &desc Get EC2 pricing per gibabyte in all regions and storage types
summary: *desc
responses:
200:
description: List of instance ty... | 3f785a5ea3ca5a18a1e8e4e2c8a7651cafbe3c2c | 3,646,683 |
import logging
def create_app():
"""
Create the application and return it to the user
:return: flask.Flask application
"""
app = Flask(__name__, static_folder=None)
app.url_map.strict_slashes = False
# Load config and logging
load_config(app)
logging.config.dictConfig(
ap... | 1a4dbade0d3ce61c458c0e24e093cfd3d7020cdb | 3,646,684 |
def _get_graph_cls(name):
"""Get scaffoldgraph class from name string."""
if name == 'network':
return ScaffoldNetwork
elif name == 'tree':
return ScaffoldTree
elif name == 'hiers':
return HierS
else:
msg = f'scaffold graph type: {name} not known'
raise ValueE... | 5279cf2518a0a5c3c89766caf41fa9e29d694ae3 | 3,646,685 |
import requests
def getgrayim(ra, dec, size=240, output_size=None, filter="g", format="jpg"):
"""Get grayscale image at a sky position
ra, dec = position in degrees
size = extracted image size in pixels (0.25 arcsec/pixel)
output_size = output (display) image size in pixels (default = size).
... | ca5e92580e428f586800419f1ef7e444fa432a25 | 3,646,686 |
import logging
import sys
def get_logger(base_name, file_name=None):
"""
get a logger that write logs to both stdout and a file. Default logging level is info so remember to
:param base_name:
:param file_name:
:param logging_level:
:return:
"""
if (file_name is None):
file_name... | 6ac5b8d78610179118605c6918998f9314a23ec4 | 3,646,687 |
import time
def elastic_transform(x, alpha, sigma, mode="constant", cval=0, is_random=False):
"""Elastic transformation for image as described in `[Simard2003] <http://deeplearning.cs.cmu.edu/pdfs/Simard.pdf>`__.
Parameters
-----------
x : numpy.array
A greyscale image.
alpha : float
... | 50af01bf47b5273cfc37b136f546f4e0fd6f24bb | 3,646,688 |
def create_markdown(
escape=True,
renderer=None,
plugins=None,
acronyms=None,
bibliography="",
chapters=False,
toc=False,
):
"""Create a Markdown instance based on the given condition.
:param escape: Boolean. If using html renderer, escape html.
:param renderer: renderer instanc... | 7db137aacc35a9a4171ef8f7ac8a50adc4e94e79 | 3,646,689 |
from typing import Optional
def make_game_from_level(level: int, options: Optional[GameOptions] = None) -> textworld.Game:
""" Make a Cooking game of the desired difficulty level.
Arguments:
level: Difficulty level (see notes).
options:
For customizing the game generation (see
... | 35d0764959f8e96549617ebbac21cabf009b1816 | 3,646,690 |
def _split(num):
"""split the num to a list of every bits of it"""
# xxxx.xx => xxxxxx
num = num * 100
result = []
for i in range(16):
tmp = num // 10 ** i
if tmp == 0:
return result
result.append(tmp % 10)
return result | 575068b9b52fdff08522a75d8357db1d0ab86546 | 3,646,691 |
def getHitmask(image):
"""returns a hitmask using an image's alpha."""
mask = []
for x in xrange(image.get_width()):
mask.append([])
for y in xrange(image.get_height()):
mask[x].append(bool(image.get_at((x,y))[3]))
return mask | 6bc38cc7d92f9b8d11241c5559c852d1ac204a60 | 3,646,692 |
def get_args_kwargs_param_names(fparams) -> (str, str):
"""fparams is inspect.signature(f).parameters
for some function f.
Doctests:
>>> import inspect
>>> def f(): pass
>>> get_args_kwargs_param_names(inspect.signature(f).parameters)
(None, None)
>>> def f(*args): pass
>>> get_args... | 948688ca6ba9908dd8bccc0c5232ebbe6fdb071f | 3,646,693 |
def clean_up_tokenization_spaces(out_string):
"""Converts an output string (de-BPE-ed) using de-tokenization algorithm from OpenAI GPT."""
out_string = out_string.replace('<unk>', '')
out_string = out_string.replace(' .', '.').replace(' ?', '?').replace(' !', '!').replace(' ,', ','
).replace(" '... | 0bd51ca7dbaa36569c0d2f18d510f1c6a92e1822 | 3,646,694 |
def upload_pkg(go_workspace, pkg_file, service_url, tags, service_account):
"""Uploads existing *.cipd file to the storage and tags it.
Args:
go_workspace: path to 'infra/go' or 'infra_internal/go'.
pkg_file: path to *.cipd file to upload.
service_url: URL of a package repository service.
tags: a l... | edc290546f14d53bd1b5b725519be0510f25e60b | 3,646,695 |
def make_rgg(n: int, kbar: float) -> ig.Graph:
"""Make Random Geometric Graph with given number of nodes
and average degree.
"""
radius = np.sqrt(kbar/(np.pi*(n-1)))
return ig.Graph.GRG(n, radius=radius, torus=True) | d44cc49284196234bbc2c46c93516e6dea182f4d | 3,646,696 |
def list_directory(bucket, prefix, s3=None, request_pays=False):
"""AWS s3 list directory."""
if not s3:
session = boto3_session(region_name=region)
s3 = session.client('s3')
pag = s3.get_paginator('list_objects_v2')
params = {
'Bucket': bucket,
'Prefix': prefix,
... | a008e6508dc000959c08b5f736951f9c664f0c91 | 3,646,697 |
from datetime import datetime
def manual_overrides():
"""Read the overrides file.
Read the overrides from cache, if available. Otherwise, an attempt is made
to read the file as it currently stands on GitHub, and then only if that
fails is the included file used. The result is cached for one day.
... | 35f64fea6a8a7923e1c94d88604798d3b014b69f | 3,646,698 |
def _ExtractCLPath(output_of_where):
"""Gets the path to cl.exe based on the output of calling the environment
setup batch file, followed by the equivalent of `where`."""
# Take the first line, as that's the first found in the PATH.
for line in output_of_where.strip().splitlines():
if line.startswith('LOC:'... | 6a0c0d4aa74b4e84de69de023e2721edd95c36bd | 3,646,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.