content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_input(calc_params_crystal, elements, bs_repo, label):
"""
Generates a test input
"""
calc_params_crystal['title'] = label
return write_input(calc_params_crystal, [bs_repo[el] for el in elements]) | 64,900 |
def ocr_loader(json_path):
"""Helper function to load ocr data from json file
Args:
json_path (string):
Path to the json file with OCR output data
Returns:
string:
OCR text output
"""
json_path = json_path.replace('\\', '/')
with open(json_path, "r") as ... | 64,901 |
def precision_posterior_prior(samples, mean, variance,
a_prior=5, b_prior=6):
""" This using the solution of Question 3 from Exercise 3
Parameters
----------
samples : array [n_samples,]
the samples from data distribution (i.e. X ~ Normal(mu, sigma^2))
mean : a scalar
th... | 64,902 |
def export_onnx(model, dummy_input, file, input_names, output_names,
num_inputs):
"""
Converts a Pytorch model to the ONNX format and saves the .onnx model file.
The first dimension of the input nodes are of size N, where N is the
minibatch size. This dimensions is here replaced by an ar... | 64,903 |
def tokenize_only(text):
"""
first tokenize by sentence, then by word to ensure that punctuation is caught as it's own token
filter out any tokens not containing letters (e.g., numeric tokens, raw punctuation)
Args:
text:
Returns:
"""
tokens = [
word.lower()
for se... | 64,904 |
def locations_list():
"""Returns a dictionary of ASNs as keys, list of associated locations, router hostnames, and \
router display names as keys. Used by Flask to populate the /routers/<asn> route, which is \
ingested by a JS Ajax call to populate the list of locations associated with the selected \
ne... | 64,905 |
def _spend_skills_on_level_up(player, race, amount):
"""
Callback for the race_level_up event to handle menu sending,
bot auto-upgrades and level up effects.
"""
if (race.level > sum(skill.max_level for skill in race.skills) or
race.level > race.max_level):
return
spend_skil... | 64,906 |
def restore_db(db: LuhSql, dump_path: Text):
"""
Restores the specified file into DB, using the wp config and remote
location to connect the DB.
"""
try:
with open(dump_path, "r", encoding="utf-8") as f:
db.restore_dump(f)
except OSError as e:
raise LuhError(f"Could ... | 64,907 |
def check_min_area( prob_mask, frame, min_area = p.min_area, type = 2,
check_area = p.check_area, **kwargs):
"""Finds contours in image and optinally checks if area bigger than `min_area`
Parameters
------------
prob_mask : ndarray
2D probability map output of `prob_mas... | 64,908 |
def delete_podcast_episode(podcast_episode_obj):
"""
Runs a task to delete an ES PodcastEpisode document
Args:
podcast_episode_obj (course_catalog.models.PodcastEpisode): A PodcastEpisode object
"""
delete_document.delay(
gen_podcast_episode_id(podcast_episode_obj), PODCAST_EPISODE_... | 64,909 |
def generate_images(session, input_name, n_images, image_size, nz, nc, input_seed, output_dir):
"""
Generates images
Args:
session (onnxruntime.capi.onnxruntime_inference_collection.InferenceSession): ONNX session
input_name (str): ONNX session input name
n_images (int): number of im... | 64,910 |
def video(request, id=None):
"""
*/entry/videos/<id>*, */entry/videos/new*
The entry interface's edit/add/delete video view. This view creates
the edit page for a given video, or the "new video" page if it
is not passed an ID. It also accepts POST requests to create or edit
videos.
If call... | 64,911 |
def country(get_response):
"""Detect the user's country and assign it to `request.country`."""
def _country_middleware(request):
client_ip = get_client_ip(request)
if client_ip:
request.country = get_country_by_ip(client_ip)
if not request.country:
request.countr... | 64,912 |
def multipart(sources, rectype="multipart"):
"""Migrate multiparts from xml dump file."""
click.echo("Migrating {}s...".format(rectype))
import_series_from_dump(
sources, rectype=rectype, loader_class=CDSMultipartDumpLoader,
) | 64,913 |
def extract_clips_with_consecutive_frames(path, num_clips, num_frames_per_clip):
"""
Args:
path: path of a video
num_clips: expected numbers of splitted clips
num_frames_per_clip: number of frames in a single clip, pretrained model only supports 16 frames
Returns:
A list of r... | 64,914 |
def solve_classical(args):
""" Classical Model Solver """
t_init = time()
# Create the model and load the spectra.
data = map(oracle.specutils.Spectrum.load, args.spectra_filenames)
model = oracle.models.StellarSpectrum(args.config_filename, data)
# Sort the spectra from blue to red
data.... | 64,915 |
def test_zero_literal() -> None:
"""Verify that the same object is returned."""
zero = IntLiteral(0)
assert simplifyExpression(zero) is zero | 64,916 |
def layer_modelformset(extra=0):
""" Form set for film layers """
return forms.modelformset_factory(ReflectivityLayer, form=LayerForm, extra=extra,
fields=('name', 'thickness', 'sld', 'i_sld', 'roughness', 'remove', 'layer_number',
... | 64,917 |
def setup(hass, config):
"""Set up the MQTT export component."""
pub_topic = config[DOMAIN].get("publish_topic", DEFAULT_TOPIC)
global PAYLOAD
PAYLOAD = dict(states=None, details=None)
# Add the configuration
PAYLOAD["details"] = hass.config.as_dict()
def mqtt_event_listener(event):
... | 64,918 |
def two_broadcastable_shapes(draw, shapes=shapes):
"""
This will produce two shapes (shape1, shape2) such that shape2 can be
broadcast to shape1.
"""
from .test_broadcasting import broadcast_shapes
shape1, shape2 = draw(two_mutually_broadcastable_shapes)
if broadcast_shapes(shape1, shape2)... | 64,919 |
def get_data_path(file_name=None):
"""Return the path to a file in the test data directory."""
if file_name is None:
file_name = ""
return os.path.join(DATA_DIR, file_name) | 64,920 |
def execute_application(arguments):
""" Execute the requested building block.
Args:
arguments (Namespace): System arguments.
"""
# Application related arguments
app_name = arguments.name
app_parameters = arguments.parameters
workflow_manager = arguments.workflow_manager
workflow... | 64,921 |
def observed(data):
"""Computes the observed agreement, Pr(a), between annotators."""
total = float(np.sum(data))
agreed = np.sum(data.diagonal())
percent_agreement = agreed / total
return percent_agreement | 64,922 |
def number_name(item):
"""The English name for that number
>>> assert number_name(5) == 'five'
"""
return _inlection.number_to_words(item) | 64,923 |
def create_nmt_model(session, forward_only, model_path=None, use_best=False, FLAGS=None, buckets=None, translate=False):
"""Create translation model and initialize or load parameters in session."""
assert FLAGS is not None
assert buckets is not None
decode_input = FLAGS.decode_input
decode_file = ... | 64,924 |
def pay_cash(amount, *args):
"""This exists so we can update the global cash counter.
:param amount: Amount to pay
:type args: bool[]
"""
paid = app_character.statblock.pay_cash(amount, *args)
return paid | 64,925 |
def degeneracyOrientation(G):
"""Directed version of G with <= degeneracy out-neighbors per vertex."""
D = {}
for v,d in degeneracySequence(G):
D[v] = {w for w in G[v] if w not in D}
return D | 64,926 |
async def get_tec_status() -> TecStatus:
"""Analyze the current TEC subsystem status.
side effect
This will initialize all temp. ramps on units that are active but have
an undefined ramp state.
:raises TecError: Couldn't get ambient temperatures.
"""
# pylint: disable=too-many-retu... | 64,927 |
def update_job_by_id(user, job_id):
"""Update a job
"""
# get If-Match header
if_match_etag = utils.check_and_get_etag(flask.request.headers)
values = clean_json_with_schema(update_job_schema, flask.request.json)
job = v1_utils.verify_existence_and_get(job_id, _TABLE)
job = dict(job)
... | 64,928 |
def _kalman_info_sample(J_ini, h_ini, log_Z_ini,
J_dyn_11, J_dyn_21, J_dyn_22, h_dyn_1, h_dyn_2, log_Z_dyn,
J_obs, h_obs, log_Z_obs):
"""
Information form Kalman sampling for time-varying linear dynamical system with inputs.
"""
T, D = h_obs.shape
# Run... | 64,929 |
def filechunkiter(f, size=131072, limit=None):
"""Create a generator that produces the data in the file size
(default 131072) bytes at a time, up to optional limit (default is
to read all data). Chunks may be less than size bytes if the
chunk is the last chunk in the file, or the file is a socket or
... | 64,930 |
def testbuild(cxn):
"""
Configure the build droplet, but do not clean up or shut down
"""
install_pkgs(cxn)
install_files(cxn)
run_scripts(cxn)
print('Build complete. This droplet is NOT ready for use. ' +
'Use build instead of testbuild for your final build') | 64,931 |
def generate_pdf(layout: LabelLayout, api: str = DEFAULT_LABEL_API) -> bytes:
"""
Generate a PDF from the given *layout* using the `Lab Labels
<https://github.com/MullinsLab/Lab-Labels>`_ web service *api*.
Returns a byte string.
"""
spec = json.dumps(layout.spec())
LOG.info(f"Generating P... | 64,932 |
def assert_allclose(
actual: numpy.float64,
desired: numpy.float64,
rtol: float,
atol: float,
err_msg: Literal["randint - kurtosis"],
):
"""
usage.scipy: 1
"""
... | 64,933 |
def test_get_level_valueerror(mocked_profile_constructor, init_statick):
"""Test the behavior when Profile throws a ValueError."""
mocked_profile_constructor.side_effect = ValueError("error")
args = Args("Statick tool")
args.parser.add_argument(
"--profile", dest="profile", type=str, default="pr... | 64,934 |
def get_term_start_end_from_date_for_actual_working_time(
start_date: Optional[str], end_date: Optional[str], tzinfo: Optional[datetime.tzinfo] = None
) -> tuple[Optional[str], Optional[str]]:
"""開始日と終了日から、実績作業時間を取得するAPIに渡すクエリパラメタterm_startとterm_endを返します。
Args:
start_date: 開始日
end_date: 終了日... | 64,935 |
def cwipc_source_netclient(address, verbose=False):
"""Return cwipc_source-like object that reads individual compressed pointclouds from a TCP-based server specified as host:port"""
source = _NetClientSource(address, verbose=verbose)
return source | 64,936 |
def create_msa_matrix(chimerics, msa):
"""
Convert a msa from chimerics to a matrix.
Each cell has the subexon number (Index) or nan for gaps and padding.
"""
if not chimerics:
return np.empty((0, 0), dtype=object)
n_seq = len(msa)
n_col = msa.get_alignment_length()
msa_matrix =... | 64,937 |
def number_of_objectives(obj_instance: Union[_ScalarObjective, VectorObjective]) -> int:
"""Return the number of objectives in the given obj_instance.
Args:
obj_instance (Union[_ScalarObjective, VectorObjective]): An instance of one of
the objective classes
Raises:
ProblemError... | 64,938 |
def to_ps(obj, parlen=False):
"""Converts object into postscript literal
>>> to_ps(None)
'null'
>>> to_ps(123)
'123'
>>> to_ps(456.78)
'456.78'
>>> to_ps(True), to_ps(False)
('true', 'false')
>>> to_ps('foo bar baz')
'foo bar baz'
>>> to_ps('foo bar baz', parlen=True)
... | 64,939 |
def run(*args, cwd=None,
input=None, capture_stdout=False, capture_stderr=False,
shell=False, env=None, check=True, quiet=False):
"""Runs a subprocess.
Args:
*args: The subprocess arguments.
cwd: The working directory. If None, specifies the current directory.
input: The... | 64,940 |
def undistort_image(img, mtx, dist, newcameramtx=None):
"""
Use camera intrinsics to undistort raw image
:param img: Raw Image
:param mtx: Camera Intrinsics matrix
:param dist: Distortion Coefficient
:param newcameramtx: Camera Intrinsics matrix after correction
:return: Undistorted image
... | 64,941 |
def voigt_tau(wave, par):
""" Find the optical depth at input wavelengths
Taken from linetools.analysis.voigt
This is a stripped down routine for calculating a tau array for an
input line. Built for speed, not utility nor with much error
checking. Use wisely. And take careful note of the expected... | 64,942 |
def add_hidden_method():
"""
>>> path.Path('.').is_hidden()
False
"""
path.Path.is_hidden = jaraco.path.is_hidden | 64,943 |
def reset_neopixels(pixels):
"""
Red and green color wipe then
turn off all the pixels
"""
for i in range(20):
pixels[i] = (255, 0, 0)
time.sleep(0.05)
for i in range(20):
i = 19 - i
pixels[i] = (0, 255, 0)
time.sleep(0.05)
for i in range(20):
... | 64,944 |
def enum_member_name(state):
"""
All enum member names have the form <EnumClassName>.<EnumMemberName>. For
our rendering we only want the member name, so we take their representation
and split it.
"""
return str(state).split('.', 1)[1] | 64,945 |
def combine_datasets(lma_data):
""" lma_data is a list of xarray datasets of the type returned by
pyxlma.lmalib.io.cf_netcdf.new_dataset or
pyxlma.lmalib.io.read.to_dataset
"""
# Get a list of all the global attributes from each dataset
attrs = [d.attrs for d in lma_data]
# Create a ... | 64,946 |
def gene_pvalue_burden_nb(df_model):
""" Calculate burden P-values based on the transfered NB model params
"""
# PVAL_SYN, PVAL_MIS, PVAL_NONS, PVAL_SPL, PVAL_TRUNC, PVAL_NONSYN = [], [], [], [], [], []
# for i, row in df_model.iterrows():
# PVAL_SYN.append(nb_model.nb_pvalue_greater_midp(row.O... | 64,947 |
def seq2polyA(seq):
""" input seq
output polyA report
(1) pass or not
(2) Left or Right
(3) most common character
(4) length of polyA
(5) length of isoseq
"""
lst = []
L = seq[0:10]
R = seq[-10:]
end = L + R
most_common_char = Counter(end).most... | 64,948 |
def multiscale_entropy(timeseries, stat_name, scales, **kwds):
"""
Calculates multi-scale entropy for any of the entropies defined above.
Idea from Costa, Goldberger and Peng, "Multiscale Entropy Analysis of
Complex Physiologic Time Series", Phys. Rev. Lett. 89, No.6, July 2002
timeseries: pd.Series... | 64,949 |
def setbit(target, bit):
"""
Устанавливает бит bit в 1 в байте target
"""
return target | (1 << bit) | 64,950 |
def write_to_file(array, filename):
""" Write tuples from 'array' into a file named 'filename'
Parameters:
array (list): list to read from
filename (string): file to write. Will create a new 'filename' if doesn't
exist or overwrite an existing one
"""
try:
# creates a fil... | 64,951 |
def get_footprint(request):
"""Generates and render png"""
template = loader.get_template('dashboard/fits_to_png.html')
start = request.GET.get('start')
end = request.GET.get('end')
program = request.GET.get('program')
if not program:
processed_exposures = []
elif not start or not en... | 64,952 |
def download_decompress(url: str, download_path: [Path, str], extract_paths=None):
"""Download and extract .tar.gz or .gz file to one or several target locations.
The archive is deleted if extraction was successful.
Args:
url: URL for file downloading
download_path: path to the directory wh... | 64,953 |
def test_game(env, agent, n_eval_episodes):
"""
Test the agent to measure rewards.
It evlautes the agent with the environment for some epidoses,
and record totol rewards.
:param env: environment to intereact with
:param agent: agent
:param n_eval_episodes: number of episodes
"""
all... | 64,954 |
def write_parcel_output(filename=None, format=None, parcel=None,
parcel_df=None, aerosol_dfs=None, other_dfs=None):
""" Write model output to disk.
Wrapper for methods to write parcel model output to disk.
Parameters
----------
filename : str
Full filename to writ... | 64,955 |
def dict_union_combine(dict1, dict2, combine_op=op.add,
default=util_const.NoParam,
default2=util_const.NoParam):
"""
Combine of dict keys and uses dfault value when key does not exist
CAREFUL WHEN USING THIS WITH REDUCE. Use dict_stack2 instead
"""
key... | 64,956 |
def _get_order_book(base_asset, quote_asset,
bid_book_min_pct_fee_provided=None, bid_book_min_pct_fee_required=None, bid_book_max_pct_fee_required=None,
ask_book_min_pct_fee_provided=None, ask_book_min_pct_fee_required=None, ask_book_max_pct_fee_required=None):
"""Gets the cu... | 64,957 |
def _cron_job_status(cron: CronTab, vrb: bool) -> None:
"""
Check tman cron job status.
:param CronTab cron: users cron
:param bool vrb: verbose output
:return: None
"""
msg.Prints.verbose("Cron job status selected", vrb)
msg.Prints.verbose("Looking for cron job", vrb)
# Find cron ... | 64,958 |
def mixed_treatment_intervention():
"""Apply mixed strategy on all controls starting at time 0."""
return zika.Intervention(
time=0,
treated_bednet_use=0.5,
condom_use=0.5,
treatment_of_infected=0.5,
indoor_spray_use=0.5,
) | 64,959 |
def expand_agent(agent, ontology, ns_filter=None):
"""Return children agents of a given parent agent.
Parameters
----------
agent : indra.statements.Agent
An INDRA Agent whose children in the given ontology should
be returned as Agents.
ontology : indra.ontology.IndraOntology
... | 64,960 |
def delete_msg(msg) -> None:
"""Remove the msg from all state databases."""
entities = [msg.src]
if hasattr(msg.src, "_evo"):
entities.append(msg.src._evo)
if msg.src._evo._dhw:
entities.append(msg.src._evo._dhw)
entities.extend(msg.src._evo.zones)
# remove the msg f... | 64,961 |
def sphericalize_density_matrix(mol, dm):
"""Sphericalize the density matrix in the sense of an integral over all possible rotations.
Args:
mol (pyscf Mole): pyscf Mole object used for the computation of the density matrix.
dm (numpy ndarray): density matrix in AO-basis.
Returns:
n... | 64,962 |
def has_specific_team_access(user, team):
"""
To have access to a team a user must:
- Be course staff
OR
- be in the correct bubble
- be in the team if it is private
"""
return has_course_staff_privileges(user, team.course_id) or (
user_protection_status_matches_t... | 64,963 |
def check_queue(queue_name):
"""
Args:
queue_name : queue_name of the queue
Checks queue for messages, logs queue status of messages left on que and hidden messages
returns only when queue is empty
"""
region = get_config()['provider']['region']
client = boto3.client('sqs', region... | 64,964 |
def plot_trap(radius= default_radius, height= default_height, slope= default_slope, delta= default_delta, constant_population= True):
"""Generates a plot for the fish trap operating over 1 week
Args:
radius: the radius of the semi-circular trap created
height: the height of the trap
slo... | 64,965 |
def nc1_to_gtiff(file_path, var, save_dir_path):
"""
Description: This script accepts a netcdf file in a geographic coordinate system, specifically the NASA GLDAS
netcdfs, and extracts the data from one variable and the lat/lon steps to create a geotiff of that information.
Dependencies: netCDF4, nu... | 64,966 |
def systematic_sample(n, prob):
""" systematic re-sampling algorithm.
Note: objects with > 1/n probability (better than average) are guaranteed to occur atleast once.
see section 2.4 of 'Comparison of Resampling Schemes for Particle Filtering' by Douc et. al for more info.
"""
assert(n == len(prob))... | 64,967 |
def add_organization(authn):
"""Add organization."""
try:
post_data = request.get_json()
org_name = post_data['name']
primary_admin = User.from_uuid(authn.sub)
is_public = post_data.get('is_public', True)
except NoResultFound:
raise NotFound('User does not exist')
... | 64,968 |
def _f_integrand(z, cosmo):
"""
Calculate the integrand for a given redshift and cosmology. This
the integrand for integral that appears in Zhang2018, Inoue2004
and Ioka2003.
Parameters
----------
z : float
The input redshift.
cosmo : An instance of :obj:`astropy.cosmology`
... | 64,969 |
def link_to_ticket_from_redmine():
"""API to link the ticket with the repostiory data."""
import jwt
import datetime
from result_linker.utils.rest_utilities import load_request_data
if request.method == "POST":
data = load_request_data(request)
logger.info(data)
issue_id = da... | 64,970 |
def populate_example_meetings(
config: RecurringMeetingTestConfig, mock_now: datetime = None
):
"""Test helper that populates mock data for meetings
Creates 60 minute meetings between 1/1/2018 - 1/15/2018 that occur:
* Monday + Friday
* Each meeting lasts 60 minutes
* Each matching Weekda... | 64,971 |
def generate_type_handlers(model):
"""
Generates msg handlers for all messages except for dumps and requests (handled by vpp, not client).
:param model: meta-model of VPP API used for jVPP generation.
"""
type_handlers = []
for t in model.types:
if not isinstance(t, Class):
c... | 64,972 |
def ex9():
"""
Example 9
Breakable Activity
file name: Example9.py
Copyright Log Opt Co., Ltd.
Consider the same scenario as in Example 6.
Here, Activities can interrupt their processing and re-start after one unit of break time.
Find the optimal schedule (minimum tardiness solution) un... | 64,973 |
def plot_pair_ransac(outputdir, pairstring, p, full_im1, full_im2,
kp_im1, kp_im2, matches, inliers):
"""Create plots of orb keypoints vs. ransac inliers."""
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(2, 1)
plot_matches(ax1, full_im1, full_im2, kp_im1, kp_im2,
... | 64,974 |
def _applySpecial_ColourMapOpts_negativeCmap(
args, overlayList, displayCtx, target):
"""Handles the :attr:`.ColourMapOpts.negativeCmap` option. See
:func:`_applyColourMap`.
"""
args.negativeCmap = _applyColourMap(
args.negativeCmap, overlayList, displayCtx)
return True | 64,975 |
def collate2iters(riter1, riter2):
"""
Collate two iterators.
The elements yielded by each iterator must be have an index
variable, and this function returns pairs (elem1, elem2), (elem1,
None), or (None, elem2) two elements in a pair will have the same
index, and earlier indicies are yielded l... | 64,976 |
def GetPixelScriptCode():
""" """
pass | 64,977 |
def assert_array_equal(x: xarray.core.variable.IndexVariable, y: numpy.int64):
"""
usage.xarray: 2
"""
... | 64,978 |
def train(model):
"""Train the model."""
# Training dataset.
dataset_train = KITTIDataset()
dataset_train.load_KITTI(args.dataset, "train")
dataset_train.prepare()
# Validation dataset
dataset_val = KITTIDataset()
dataset_val.load_KITTI(args.dataset, "val")
dataset_val.prepare()
... | 64,979 |
def process_directories(model_dirs, out_dir, gpu_idx=0):
"""Load the latest snapshot in each of the given model directories, and
render a video for each test variant corresponding to the train variants in
the model. Note that the video will show all models in sequence."""
set_seeds(DEFAULT_SEED)
reg... | 64,980 |
def test_short_log_diff(mock_repo, fake_commits):
"""
GIVEN GitRepo initialized with a path and repo
WHEN short_log_diff is called with two valid hashes
THEN a list of log entries is returned
"""
mock_repo.iter_commits.return_value = fake_commits
repo = GitRepo('./', mock_repo)
with pat... | 64,981 |
def handler(event, context):
"""
Handler for all Lambda events
"""
logging.info('AWS Event was: {}'.format(event))
if 'source' in event and event['source'] == 'aws.events':
# This is a scheduled event. See
# https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html... | 64,982 |
def concrete_head(expr, n=10):
""" Return head of computed expression """
if not expr._resources():
raise ValueError("Expression does not contain data resources")
if iscollection(expr.dshape):
head = expr.head(n + 1)
result = compute(head)
if not len(result):
ret... | 64,983 |
def list():
"""Seznam cvičení"""
usr = getUser()
if request.params.get("activate"):
lec = Lecture.get( request.params.get("activate") )
lec.activate()
msg("Cvičení %s bylo zapnuto" % lec.name,"success")
redirect(request.path)
if request.params.get... | 64,984 |
def load_snapshot(snapshot_file):
"""Load a training snapshot"""
print("--- Loading model from snapshot")
# Create network
norm_act = partial(InPlaceABN, activation="leaky_relu", slope=.01)
body = models.__dict__["net_wider_resnet38_a2"](norm_act=norm_act, dilation=(1, 2, 4, 4))
head = DeeplabV... | 64,985 |
def squash(x, axis=-1):
"""The Squashing Function.
The nonlinear activation function used in Capsule Network
# Arguments
x: Input Tensor.
axis: Integer axis along which the squashing function is to be applied.
# Returns
Tensor with scaled value of the input tensor
"""
s_... | 64,986 |
def payment_method(ctx):
"""
Get your payment method.
"""
gigalixir_payment_method.get(ctx.obj['host']) | 64,987 |
def move_file(source: str, destination: str):
"""Checks if the destination folder exists,
creates it if it doesn't,
then moves a file into it
Parameters
----------
file : Path
the path to a file
dest_path : Path
the path to the destination folder
"""
if os.path.isdi... | 64,988 |
def update_user_chosen(request):
"""This view updates the team member: this is needed to see the ground truth of a specific user"""
request_body_json = json.loads(request.body)
user = request_body_json['user_chosen']
if user is not None:
request.session['team_member'] = user
json_resp ... | 64,989 |
async def slowlog(request: SubRequest, r: RedisCluster) -> None:
"""
Set the slowlog threshold to 0, and the
max length to 128. This will force every
command into the slowlog and allow us
to test it
"""
# Save old values
current_config = await r.config_get(target_nodes=r.get_primaries()[... | 64,990 |
def read_all(resourceTypes):
"""Load all data to the FHIR server."""
_config = config()
for resourceType in resourceTypes:
url = f"{_config.base_url}{resourceType}"
entity = get(_config.connection, url)
assert entity, f"{url} should return entity" | 64,991 |
def encode(ds, is_implicit_vr, is_little_endian):
"""Encode a pydicom Dataset `ds` to bytes.
Parameters
----------
ds : pydicom.dataset.Dataset
The dataset to encode
is_implicit_vr : bool
The element encoding scheme the dataset will be encoded with.
is_little_endian : bool
... | 64,992 |
def process_alignment(data, alt_input=None):
"""Do an alignment of fastq files, preparing a sorted BAM output file.
"""
data = cwlutils.normalize_missing(utils.to_single_data(data))
data = cwlutils.unpack_tarballs(data, data)
fastq1, fastq2 = dd.get_input_sequence_files(data)
if alt_input:
... | 64,993 |
def listen_print_loop(responses):
# print(responses)
"""Iterates through server responses and prints them.
The responses passed is a generator that will block until a response
is provided by the server.
Each response may contain multiple results, and each result may contain
multi... | 64,994 |
def tryJSON(response: Response) -> dict:
"""
Try to convert response data to JSON
"""
try:
response_data = response.json()
except json.decoder.JSONDecodeError:
raise PluginException(
cause="Received an unexpected response from Deep Security",
assistance="(non... | 64,995 |
def path_to_coords(svg_path: str, xtype: str = None) -> np.array:
"""From SVG path to numpy array of coordinates, each row being a (row, col) point"""
indices_str = [
pt.replace("M", "").replace("Z", "").replace("_", " ").split(",") for pt in svg_path.split("L")
]
if xtype == "datetime":
... | 64,996 |
def insert(*data):
"""
Create an insert clause, e.g. `INSERT INTO ...`
Each value in *data* should be dictionary with key/values representing
columns/values. The format of this should be the same as in
:py:func:`.update`.
"""
return QueryBuilder().insert(*data) | 64,997 |
def get_default_gl_major_version():
""" Default GL major version """
return __gl_major_version__ | 64,998 |
def expandf(m, format): # noqa B002
"""Expand the string using the format replace pattern or function."""
if isinstance(format, (Replace, ReplaceTemplate)):
if not format.use_format:
raise ValueError("Replace not compiled as a format replace")
elif not isinstance(format, (compat.string... | 64,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.