content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def extract_and_resize_frames(path, resize_to=None):
"""
Iterate the GIF, extracting each frame and resizing them
Returns:
An array of all frames
"""
mode = analyseImage(path)["mode"]
im = PImage.open(path)
if not resize_to:
resize_to = (im.size[0] // 2, im.size[1] // 2)
... | 5,334,400 |
def create(self, node=None):
"""Test the RBAC functionality of the `CREATE VIEW` command.
"""
Scenario(run=create_without_create_view_privilege)
Scenario(run=create_with_create_view_privilege_granted_directly_or_via_role)
Scenario(run=create_with_revoked_create_view_privilege_revoked_directly_or_fro... | 5,334,401 |
def voter_star_off_save_doc_view(request):
"""
Show documentation about voterStarOffSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_star_off_save_doc.voter_star_off_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api_device_id(request)
... | 5,334,402 |
def generate_offsets(size_map, flow_map=None, kernel_shape=(3, 3, 3), dilation=(1, 1, 1)):
"""
Generates offsets for deformable convolutions from scalar maps.
Maps should be of shape NxCxDxHxW, i.e. one set of parameters for every
pixel. ``size_map`` and ``orientation_map`` expect a single channel,
and flow_m... | 5,334,403 |
def lighten_color(color, amount=0.5):
""" Lightens the given color by multiplying (1-luminosity) by the given amount.
Input can be matplotlib color string, hex string, or RGB tuple.
Examples:
>> lighten_color("g", 0.3)
>> lighten_color("#F034A3", 0.6)
>> lighten_color((.3,.55,.1), 0... | 5,334,404 |
def unf_gas_density_kgm3(t_K, p_MPaa, gamma_gas, z):
"""
Equation for gas density
:param t_K: temperature
:param p_MPaa: pressure
:param gamma_gas: specific gas density by air
:param z: z-factor
:return: gas density
"""
m = gamma_gas * 0.029
p_Pa = 10 ** 6 * p_MPaa
rho_gas =... | 5,334,405 |
def main() -> None:
"""Read hexadecimal string and converted to binary string."""
with open(INPUT_FILE, encoding='utf-8') as input_file:
packet = hex2ba(input_file.readline().strip())
program = []
parse_packet(program, packet)
print(f'Part One: Sum of all versions parsed: {sum_versions(progr... | 5,334,406 |
def poll():
"""Get Modbus agent data.
Performance data from Modbus enabled targets.
Args:
None
Returns:
agentdata: AgentPolledData object for all data gathered by the agent
"""
# Initialize key variables.
config = Config()
_pi = config.polling_interval()
# Initia... | 5,334,407 |
def dot_product_timer(x_shape=(5000, 5000),
y_shape=(5000, 5000),
mean=0,
std=10,
seed=8053):
"""
A timer for the formula array1.dot(array2).
Inputs:
x_shape: Tuple of 2 Int
Shape of array1;
y_shape: Tupl... | 5,334,408 |
def run_migrations(app=None):
"""
Run the migrations to the database
Usage: fab run_migrations:app_name
"""
with virtualenv(env.virtualenv):
with cd(env.code_dir):
if getattr(env, 'initial_deploy', False):
run_venv("./manage.py syncdb --all")
run_v... | 5,334,409 |
def ref_icrs_fk5(fnout='icrs_fk5.csv'):
"""
Accuracy tests for the ICRS (with no E-terms of aberration) to/from FK5
conversion, with arbitrary equinoxes and epoch of observation.
"""
import starlink.Ast as Ast
np.random.seed(12345)
N = 200
# Sample uniformly on the unit sphere. These... | 5,334,410 |
def availible_files(path:str, contains:str='') -> list:
"""Returns the availible files in directory
Args:
path(str): Path to directory
contains(str, optional): (Default value = '')
Returns:
Raises:
"""
return [f for f in os.listdir(path) if contains in f] | 5,334,411 |
def init_pretraining_params(exe,
pretraining_params_path,
main_program):
"""init pretraining params"""
assert os.path.exists(pretraining_params_path
), "[%s] cann't be found." % pretraining_params_path
def existed_params(var)... | 5,334,412 |
def npareatotal(values, areaclass):
"""
numpy area total procedure
:param values:
:param areaclass:
:return:
"""
return np.take(np.bincount(areaclass,weights=values),areaclass) | 5,334,413 |
def create_aerocode_wrapper(aerocode_params, output_params, options):
""" create wind code wrapper"""
solver = 'FAST'
# solver = 'HAWC2'
if solver=='FAST':
## TODO, changed when we have a real turbine
# aero code stuff: for constructors
from AeroelasticSE.FusedFAST import openF... | 5,334,414 |
def register_todo_update(callback):
"""
Register a callback to be called when the number of tutorials changes
"""
dbus.SessionBus().add_signal_receiver(
callback, "update_tuto_num", LIBTUTO_DBUS_INTERFACE, None, None) | 5,334,415 |
def lqr_ofb_cost(K, R, Q, X, ss_o):
# type: (np.array, np.array, np.array, np.array, control.ss) -> np.array
"""
Cost for LQR output feedback optimization.
@K gain matrix
@Q process noise covariance matrix
@X initial state covariance matrix
@ss_o open loop state space system
@return cost... | 5,334,416 |
def test_stack_str_format_on_empty(empty_stack):
""" Do we get the expected str return on empty stack
"""
expected = 'Top: None | Length: 0'
actual = str(empty_stack)
assert expected == actual | 5,334,417 |
def steadystate_floquet(H_0, c_ops, Op_t, w_d=1.0, n_it=3, sparse=False):
"""
Calculates the effective steady state for a driven
system with a time-dependent cosinusoidal term:
.. math::
\\mathcal{\\hat{H}}(t) = \\hat{H}_0 +
\\mathcal{\\hat{O}} \\cos(\\omega_d t)
Parameters
... | 5,334,418 |
def gsl_blas_dtrmm(*args, **kwargs):
"""
gsl_blas_dtrmm(CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag, double alpha,
gsl_matrix A, gsl_matrix B) -> int
"""
return _gslwrap.gsl_blas_dtrmm(*args, **kwargs) | 5,334,419 |
def scale(value, upper, lower, min_, max_):
"""Scales value between upper and lower values, depending on the given
minimun and maximum value.
"""
numerator = ((lower - upper) * float((value - min_)))
denominator = float((max_ - min_))
return numerator / denominator + upper | 5,334,420 |
def conditional_response(view, video=None, **kwargs):
"""
Redirect to login page if user is anonymous and video is private.
Raise a permission denied error if user is logged in but doesn't have permission.
Otherwise, return standard template response.
Args:
view(TemplateView): a video-speci... | 5,334,421 |
def Flatten(nmap_list):
"""Flattens every `.NestedMap` in nmap_list and concatenate them."""
ret = []
for x in nmap_list:
ret += x.Flatten()
return ret | 5,334,422 |
def get_data_schema() -> T.StructType:
"""
Return the kafka data schema
"""
return T.StructType(
[T.StructField('key', T.StringType()),
T.StructField('message', T.StringType())]
) | 5,334,423 |
def build_graph(num: int = 0) -> (int, List[int]):
"""Build a graph of num nodes."""
if num < 3:
raise app.UsageError('Must request graph of at least 3 nodes.')
weight = 5.0
nodes = [(0, 1, 1.0), (1, 2, 2.0), (0, 2, 3.0)]
for i in range(num-3):
l = random.sample(range(0, 3 + i - 1),... | 5,334,424 |
async def test_locator_run_exception(config, mocker):
"""Test an error doesn't kill the Locator."""
logger_mock = mocker.MagicMock()
p = Locator(config, logger_mock)
p.last_work_end_timestamp = None
p._do_work = AsyncMock()
p._do_work.side_effect = [Exception("bad thing happen!")]
await p.ru... | 5,334,425 |
def concatenate(boxes_list:List[Boxes], fields:Collection[str]=None) -> Boxes:
"""Merge multiple boxes to a single instance
B = A[:10]
C = A[10:]
D = concatenate([A, B])
D should be equal to A
"""
if not boxes_list:
if fields is None:
fields = []
return empty(*fie... | 5,334,426 |
def detect_peaks(array, freq=0, cthr=0.2, unprocessed_array=False, fs=44100):
"""
Function detects the peaks in array, based from the mirpeaks algorithm.
:param array: Array in which to detect peaks
:param freq: Scale representing the x axis (sample length as array)
:p... | 5,334,427 |
def left_index_iter(shape):
"""Iterator for the left boundary indices of a structured grid."""
return range(0, shape[0] * shape[1], shape[1]) | 5,334,428 |
def calculate_precision_recall(df_merged):
"""Calculates precision and recall arrays going through df_merged row-wise."""
all_positives = get_all_positives(df_merged)
# Populates each row with 1 if this row is a true positive
# (at its score level).
df_merged["is_tp"] = np.where(
(df_merged... | 5,334,429 |
def combine(shards, judo_file):
"""combine
this class is passed the
"""
# Recombine the shards to create the kek
combined_shares = Shamir.combine(shards)
combined_shares_string = "{}".format(combined_shares)
# decrypt the dek uysing the recombined kek
decrypted_dek = decrypt(
j... | 5,334,430 |
def shiftRightUnsigned(e, numBits):
"""
:rtype: Column
>>> from pysparkling import Context
>>> from pysparkling.sql.session import SparkSession
>>> from pysparkling.sql.functions import shiftLeft, shiftRight, shiftRightUnsigned
>>> spark = SparkSession(Context())
>>> df = spark.range(-5, 4)... | 5,334,431 |
def test_jenkinslts_home_exists(host):
"""
Tests if jenkins home directory exists.
"""
assert host.file(PACKAGE_HOME).exists | 5,334,432 |
def change_wallpaper_job(profile, force=False):
"""Centralized wallpaper method that calls setter algorithm based on input prof settings.
When force, skip the profile name check
"""
with G_WALLPAPER_CHANGE_LOCK:
if profile.spanmode.startswith("single") and profile.ppimode is False:
t... | 5,334,433 |
def transact():
"""Sends an API request to the VCC exchange"""
# Sets a quantity range to sell. Example: (10,15) randomly selects a number between 10 and 15
quantity = round(random.uniform(10, 15), 2)
# Coin to trade (FCT, ADA, BTC etc...)
coin = 'fct'
# Base currency coin is denominated in (B... | 5,334,434 |
def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
"""Return type hints for an object.
This is often the same as obj.__annotations__, but it handles
forward references encoded as string literals, adds Optional[t] if a
default value equal to None is set and recursively replaces ... | 5,334,435 |
def sheets_from_excel(xlspath):
"""
Reads in an xls(x) file,
returns an array of arrays, like:
Xijk, i = sheet, j = row, k = column
(but it's not a np ndarray, just nested arrays)
"""
wb = xlrd.open_workbook(xlspath)
n_sheets = wb.nsheets
sheet_data = []
for sn in xrange(n_sheets... | 5,334,436 |
def metadata(ctx, drafts, path):
"""List metadata for [PROJECT] [VERSION]"""
_rws = partial(rws_call, ctx)
if len(path) == 0:
_rws(MetadataStudiesRequest(), default_attr='oid')
elif len(path) == 1:
if drafts:
_rws(StudyDraftsRequest(path[0]), default_attr='oid')
else:... | 5,334,437 |
def fitStatmechPseudoRotors(Tlist, Cvlist, Nvib, Nrot, molecule=None):
"""
Fit `Nvib` harmonic oscillator and `Nrot` hindered internal rotor modes to
the provided dimensionless heat capacities `Cvlist` at temperatures `Tlist`
in K. This method assumes that there are enough heat capacity points
provi... | 5,334,438 |
def send_notification(to,
subject,
body,
username=None,
password=None,
smtp_server=None,
port=None):
"""
Send an email or text notification to the given recipient.
email accou... | 5,334,439 |
def plot_summary(labels,
label2array,
xlim=100,
ylim=None,
logscale=True,
ylabel='Regret',
xlabel='BO Iters',
method='mean',
title=None,
violin_trials=None,
... | 5,334,440 |
def add_numbers(a, b):
"""Sums the given numbers.
:param int a: The first number.
:param int b: The second number.
:return: The sum of the given numbers.
>>> add_numbers(1, 2)
3
>>> add_numbers(50, -8)
42
"""
return a + b | 5,334,441 |
def get_version(table_name):
"""Get the most recent version number held in a given table."""
db = get_db()
cur = db.cursor()
cur.execute("select * from {} order by entered_on desc".format(table_name))
return cur.fetchone()["version"] | 5,334,442 |
def area(a, indices=(0, 1, 2, 3)):
"""
:param a:
:param indices:
:return:
"""
x0, y0, x1, y1 = indices
return (a[..., x1] - a[..., x0]) * (a[..., y1] - a[..., y0]) | 5,334,443 |
def latest_file(path_name, keyword='', ext='', **kwargs) -> str:
"""
Latest modified file in folder
Args:
path_name: full path name
keyword: keyword to search
ext: file extension
Returns:
str: latest file name
"""
files = sort_by_modified(
all_files(path... | 5,334,444 |
def like_bp_gauss_mix_loop_nbin(grid_dir, n_bps, n_zbin, lmax_like, lmin_like, lmax_in, lmin_in, fid_pos_pos_dir,
fid_she_she_dir, fid_pos_she_dir, pos_nl_path, she_nl_path, mixmats_path,
bp_cov_filemask, binmixmat_save_dir, obs_bp_save_dir, varied_params,... | 5,334,445 |
def infer_tf_dtypes(image_array):
"""
Choosing a suitable tf dtype based on the dtype of input numpy array.
"""
return dtype_casting(
image_array.dtype[0], image_array.interp_order[0], as_tf=True) | 5,334,446 |
def write_unique_genera():
"""Writes unique genera to the output file
Output:
- written file
"""
with open(argv[1]) as inf:
all_lines = inf.readlines()
all_genera = []
for line in all_lines:
genus = line.strip().split()[0]
if genus not in all_genera:
... | 5,334,447 |
def test_thread_crew(count):
"""
thread_crew() creates multiple worker threads, reading from one Channel
and writing to another.
"""
def worker(value, check, out_chnl):
out_chnl.put((value, threading.get_ident()))
if value == count - 1:
out_chnl.end()
# Now sleep ... | 5,334,448 |
def get_cifar10_datasets(n_devices, batch_size=256, normalize=False):
"""Get CIFAR-10 dataset splits."""
if batch_size % n_devices:
raise ValueError("Batch size %d isn't divided evenly by n_devices %d" %
(batch_size, n_devices))
train_dataset = tfds.load('cifar10', split='train[:90%]')
... | 5,334,449 |
def predict(dataset, fitmodel_url, save_results=True, show=False):
"""
Function starts a job that makes predictions to input data with a given model
Parameters
----------
input - dataset object with input urls and other parameters
fitmodel_url - model created in fit phase
save_results - sav... | 5,334,450 |
def test_multiple_config_to_csv(log_basic_config_reader):
"""
Assert that multiple reads and writes are supported by config_to_csv.
"""
config, config_reader = log_basic_config_reader
log_dir = os.path.dirname(config_reader.data["log_dir"])
for _ in range(5):
config_to_csv(config_reader... | 5,334,451 |
def format_string_to_json(balance_info):
"""
Format string to json.
e.g: '''Working Account|KES|481000.00|481000.00|0.00|0.00'''
=> {'Working Account': {'current_balance': '481000.00',
'available_balance': '481000.00',
'reserved_balance': '0.00',
'uncleared_balance': '0.00'}}
"""
balance_dict = frappe._dic... | 5,334,452 |
def get_relevant_texts(subject: Synset, doc_threshold: float) -> Tuple[List[str], List[int], int, int]:
"""Get all lines from all relevant articles. Also return the number of retrieved documents and retained ones."""
article_dir = get_article_dir(subject)
rel_path = get_relevant_scores_path(subject)
s... | 5,334,453 |
def plot_mae(X, y, model):
"""
Il est aussi pertinent de logger les graphiques sous forme d'artifacts.
"""
fig = plt.figure()
plt.scatter(y, model.predict(X))
plt.xlabel("Durée réelle du trajet")
plt.ylabel("Durée estimée du trajet")
image = fig
fig.savefig("MAE.png")
plt.cl... | 5,334,454 |
def test_precision_epoch():
"""
Check that input via epoch also has full precision, i.e., against
regression on https://github.com/astropy/astropy/pull/366
"""
t_utc = Time(range(1980, 2001), format='jyear', scale='utc')
t_tai = Time(range(1980, 2001), format='jyear', scale='tai')
dt = t_utc... | 5,334,455 |
def compile_options(
rst_roles: Optional[List[str]],
rst_directives: Optional[List[str]],
*,
allow_autodoc: bool = False,
allow_toolbox: bool = False,
):
"""
Compile the list of allowed roles and directives.
:param rst_roles:
:param rst_directives:
:param allow_autodoc:
:param allow_toolbox:
"""
d... | 5,334,456 |
def get_pure_function(method):
"""
Retreive pure function, for a method.
Depends on features specific to CPython
"""
assert(isinstance(method, types.MethodType))
assert(hasattr(method, 'im_func'))
return method.im_func | 5,334,457 |
def test_failure_of_just_reload():
"""
Test that really_reload is _actually_ needed in this test case
This test exists to check that the test before it is
actually testing what needs to be tested
"""
from importlib import reload, invalidate_caches
setup_old_math_lib()
invalidate_caches... | 5,334,458 |
def _agg_samples_2d(sample_df: pd.DataFrame) -> pd.DataFrame:
"""Aggregate ENN samples for plotting."""
def pct_95(x):
return np.percentile(x, 95)
def pct_5(x):
return np.percentile(x, 5)
enn_df = (sample_df.groupby(['x0', 'x1'])['y']
.agg([np.mean, np.std, pct_5, pct_95]).reset_index())
e... | 5,334,459 |
def get_np_num_array_str(data_frame_rows):
"""
Get a complete code str that creates a np array with random values
"""
test_code = cleandoc("""
from sklearn.preprocessing import StandardScaler
import pandas as pd
from numpy.random import randint
series = randint(0,100,siz... | 5,334,460 |
def get_config(name: str = None, default: Any = _MISSING) -> Any:
"""Gets the global configuration.
Parameters
----------
name : str, optional
The name of the setting to get the value for. If no name is
given then the whole :obj:`Configuration` object is returned.
default : optiona... | 5,334,461 |
def domain_domain_distance(ptg1, ptg2, pdb_struct, domain_distance_dict):
"""
Return the distance between two domains, which will be defined as
the distance between their two closest SSEs
(using SSE distnace defined in ptdistmatrix.py)
Parameters:
ptg1 - PTGraph2 object for one domain
... | 5,334,462 |
def rip_subtitles():
"""
%prog <dvd_source>
"""
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(usage=trim(encode_dvd.__doc__))
parser.add_argument(
'-t', '--title', help='enter the dvd title number to process', default=''
)
parser.add_argument('-s', '--... | 5,334,463 |
def main():
"""
generate a sales example with tables for customers,
sales, products
"""
s = content.DataFiles()
date_list = generate.get_list_dates(2016, 2016, 500)
prod_list = list(s.get_collist_by_name(os.path.join(content.data_fldr,'food','garden_produce.csv'), 'name')[0])
t... | 5,334,464 |
def pred_error(f_pred, prepare_data, data, iterator, max_len, n_words, filter_h):
""" compute the prediction error.
"""
valid_err = 0
for _, valid_index in iterator:
x = [data[0][t] for t in valid_index]
x = prepare_data(x,max_len,n_words,filter_h... | 5,334,465 |
def standardize_10msample(frac: float=0.01):
"""Runs each data processing function in series to save a new .csv data file.
Intended for Pandas DataFrame. For Dask DataFrames, use standardize_10msample_dask
Args:
frac (float, optional): Fraction of data file rows to sample. Defaults to 0.01.
Re... | 5,334,466 |
def test_assign_resolution_bins(data_fmodel, bins, inplace, return_labels):
"""Test DataSet.assign_resolution_bins"""
result = data_fmodel.assign_resolution_bins(bins=bins,
inplace=inplace,
return_labels=return_... | 5,334,467 |
def put(bucket, key, val):
"""
Writes key-value pair to storage.
:param bucket: (string) A bucket name.
:param key: (string) A key name.
:param val: (bytes) Value to write.
"""
_check_bucket(bucket)
if not isinstance(val, bytes):
raise TypeError("value should be of type bytes")
... | 5,334,468 |
def smatrix_backward_kernel_S(z, phase_factors, mean_probe_intensities, r, r_min, out, tau):
"""
S-matrix has beam tilts included, pre-calculated scanning phase factors.
Fastest to compute
:param z: D x K x MY x MX x 2
:param phase_factors: B x D x K x 2
:param r... | 5,334,469 |
def is_ansible_managed(file_path):
"""
Gets whether the fail2ban configuration file at the given path is managed by Ansible.
:param file_path: the file to check if managed by Ansible
:return: whether the file is managed by Ansible
"""
with open(file_path, "r") as file:
return file.readli... | 5,334,470 |
def delete_samples_generic_database(exec_tag, testcase_name=None):
""" delete existing samples of given testcase """
db_path = os.getenv("WAR_TOOLS_DIR") + "/generic_samples.db"
con = sqlite3.connect(db_path)
statement = "SELECT name FROM sqlite_master WHERE type='table';"
if ('GEN_RESULTS_TABLE',) ... | 5,334,471 |
def sumai(array):
"""
Return the sum of the elements of an integer array.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sumai_c.html
:param array: Input Array.
:type array: Array of ints
:return: The sum of the array.
:rtype: int
"""
n = ctypes.c_int(len(array))
array... | 5,334,472 |
def _get_connection_dir(app):
"""Gets the connection dir to use for the IPKernelApp"""
connection_dir = None
# Check the pyxll config first
cfg = get_config()
if cfg.has_option("JUPYTER", "runtime_dir"):
connection_dir = cfg.get("JUPYTER", "runtime_dir")
if not os.path.abspath(conne... | 5,334,473 |
def download(accession):
"""Downloads GEO file based on accession number. Returns a SOFTFile or ANNOTFile
instance.
For reading and unzipping binary chunks, see:
http://stackoverflow.com/a/27053335/1830334
http://stackoverflow.com/a/2424549/1830334
"""
import os
if 'GPL' not in accession: # soft file
geo_... | 5,334,474 |
def invoke(
node: Union[DAG, Task],
params: Optional[Mapping[str, Any]] = None,
) -> Mapping[str, NodeOutput]:
"""
Invoke a node with a series of parameters.
Parameters
----------
node
Node to execute
params
Inputs to the task, indexed by input/parameter name.
Ret... | 5,334,475 |
def test_adder1_config():
"""Test adder1_offset kwarg from config
"""
configfy.set_active_config_file('./tests/test_config.ini')
assert adder1(1, 1) == 3, 'Offset not read from config!' | 5,334,476 |
def convert_acl_to_iam_policy(acl):
"""Converts the legacy ACL format to an IAM Policy proto."""
owners = acl.get('owners', [])
readers = acl.get('readers', [])
if acl.get('all_users_can_read', False):
readers.append('allUsers')
writers = acl.get('writers', [])
bindings = []
if owners:
bindings.ap... | 5,334,477 |
def fix_module_doctest(module):
"""
Extract docstrings from cython functions, that would be skipped by doctest
otherwise.
"""
module.__test__ = {}
for name in dir(module):
value = getattr(module, name)
if (isinstance(value, numbawrapper.NumbaWrapper) and
from_modu... | 5,334,478 |
def get_valid_start_end(mask):
"""
Args:
mask (ndarray of bool): invalid mask
Returns:
"""
ns = mask.shape[0]
nt = mask.shape[1]
start_idx = np.full(ns, -1, dtype=np.int32)
end_idx = np.full(ns, -1, dtype=np.int32)
for s in range(ns):
# scan from start to the end
... | 5,334,479 |
def put_network_object(session, key, data):
# type: (Session, Text, Any) -> None
"""Put data as extended object with given key for the current network."""
url_tail = "/{}/{}/{}".format(
CoordConstsV2.RSC_NETWORKS, session.network, CoordConstsV2.RSC_OBJECTS
)
_put_stream(session, url_tail, da... | 5,334,480 |
def pahrametahrize(*args, **kwargs) -> t.Callable:
"""Pass arguments straight through to `pytest.mark.parametrize`."""
return pytest.mark.parametrize(*args, **kwargs) | 5,334,481 |
def utcnow():
"""Return the current time in UTC with a UTC timezone set."""
return datetime.utcnow().replace(microsecond=0, tzinfo=UTC) | 5,334,482 |
def default_to(default, value):
"""
Ramda implementation of default_to
:param default:
:param value:
:return:
"""
return value or default | 5,334,483 |
def copy_one_class_images_labels(path_to_images, path_to_labels, target_path,
image_type='.png', label_suffix='-labels'):
"""
copy images which contain only one class label
Args:
path_to_images: path to the images
path_to_labels: path to the labels
... | 5,334,484 |
def dummy():
"""
>>> import gym
>>> env = gym.make("FetchReachCSL-v1")
>>> _ = env.seed(0)
>>> _ = env.reset()
>>> for _ in range(5):
... obs, rew, _, info = env.step(env.action_space.sample())
... rew2 = env.compute_reward(obs['achieved_goal'], obs['desired_goal'], dict())
.... | 5,334,485 |
def main(page_size: int = 10000, period: str = "daily", adjust: str = ""):
"""
下载入口程序
:param page_size: a市场46多只,这里默认10000,即下载全部
:param period: 日线:daily; 周线:weekly; 月线: monthly
:param adjust: 复权类型,前复权:"qfq";后复权:"hfq";"不复权":"", 默认不复权
:return:
"""
res = json.loads(requests_get(a_detail_url(... | 5,334,486 |
def insertGraph():
"""
Create a new graph
"""
root = Xref.getroot().elem
ref = getNewRef()
elem = etree.Element(etree.QName(root, sgraph), reference=ref)
name = makeNewName(sgraph, elem)
root.append(elem)
Xref.setDirty()
return name, (elem, newDotGraph(name, ref, elem)) | 5,334,487 |
def get_line_notif(line_data: str):
"""
Извлечь запись из таблицы.
:param line_data: запрашиваемая строка
"""
try:
connection = psycopg2.connect(
user=USER,
password=PASSWORD,
host="127.0.0.1",
port="5432",
database=DATABASE)
... | 5,334,488 |
def apply_user(username: str, password: str =None,
extra_smb_groups: List[str] =None, no_default_smb_group: bool =False, **kwargs):
"""Add user or modify user
Args:
username: username
password: password
extra_smb_groups: extra groups besides default samba group to add
... | 5,334,489 |
def load_alloc_model(matfilepath, prefix):
""" Load allocmodel stored to disk in bnpy .mat format.
Parameters
------
matfilepath : str
String file system path to folder where .mat files are stored.
Usually this path is a "taskoutpath" like where bnpy.run
saves its output.
pr... | 5,334,490 |
def bouts_per_minute(boutlist):
"""Takes list of times of bouts in seconds, returns bpm = total_bouts / total_time."""
bpm = (total_bouts(boutlist) / total_time(boutlist)) * 60
return bpm | 5,334,491 |
def test_registration(windows):
"""Test that the manifest is properly regsistered.
"""
w = Workbench()
w.register(CoreManifest())
w.register(ErrorsManifest())
w.register(PackagesManifest())
with signal_error_raise():
w.get_plugin('exopy.app.packages').collect_and_register()
# ... | 5,334,492 |
def convert_to_snake_case(string: str) -> str:
"""Helper function to convert column names into snake case. Takes a string
of any sort and makes conversions to snake case, replacing double-
underscores with single underscores."""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', string)
draft = re.sub('([a-... | 5,334,493 |
def test_ttl_action_first_encrypt():
"""Test that when _last_updated has never been set, ttl_action returns TtlActions.EXPIRED."""
store = MagicMock(__class__=ProviderStore)
provider = CachingMostRecentProvider(provider_store=store, material_name="my material", version_ttl=10.0)
assert provider._last_u... | 5,334,494 |
def list_keys(client, keys):
"""
:param client: string
:param keys: list of candidate keys
:return: True if all keys exist, None otherwise
"""
objects = client.get_multi(keys)
if bool(objects):
return objects
else:
return None | 5,334,495 |
def write_fasta(df,out_file,seq_column="sequence",seq_name="pretty",
write_only_keepers=True,empty_char="X-?",clean_sequence=False):
"""
df: data frame to write out
out_file: output file
seq_column: column in data frame to use as sequence
seq_name: column in data frame to use as >NAM... | 5,334,496 |
def load_config(config_name):
"""
Load a configuration object from a file and return the object. The given configuration name
must be a valid saved configuration.
:param config_name: The name of the configuration file to load from.
:return: The configuration object saved in that file.
"""
if... | 5,334,497 |
def estimate_variance(ip_image: np.ndarray, x: int, y: int, nbr_size: int) -> float:
"""Estimates local variances as described in pg. 6, eqn. 20"""
nbrs = get_neighborhood(x, y, nbr_size, ip_image.shape[0], ip_image.shape[1])
vars = list()
for channel in range(3):
pixel_avg = 0
for i, j ... | 5,334,498 |
def api_key_regenerate():
"""
Generate a new API key for the currently logged-in user.
"""
try:
return flask.jsonify({
constants.api.RESULT: constants.api.RESULT_SUCCESS,
constants.api.MESSAGE: None,
'api_key': database.user.generate_new_api_key(current_user.u... | 5,334,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.