content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def concat_chunked_data(jsons, f_src='c', *args, **kwargs):
"""
Takes chunks of data and combines them into a numpy array
of shape trial x cells x time, concatendated over trials, and
clips the trials at shortest frame number and fewest cells. Args and
kwargs are passed to process_data.
Args:
... | 5,332,300 |
def test_apply_phaser(frequency: float, frame_rate: int, kind: str) -> None:
"""Test that `apply_phaser` function runs without failures."""
sound = generate_mono_wave(
'sine', frequency, np.ones(frame_rate), frame_rate
)
sound = np.vstack((sound, sound))
event = Event(
instrument='an... | 5,332,301 |
def hmc_update(context, hmc_uuid, values, session=None):
"""Updates an existing HMC instance in the Database"""
return IMPL.hmc_update(context, hmc_uuid, values, session) | 5,332,302 |
def _dense_difference(fun, x0, f0, h, one_sided, method):
"""
Calculates an approximation of the Jacobian of `fun`at the point `x0` in dense matrix form.
NOTE: Inspired from: https://github.com/scipy/scipy/blob/master/scipy/optimize/_numdiff.py
Parameters
----------
fun : callable
... | 5,332,303 |
def alternate( name, *functions ):
"""Construct a callable that functions as the first implementation found of given set of alternatives
if name is a function then its name will be used....
"""
if not isinstance( name, (bytes,unicode)):
functions = (name,)+functions
name = name.__name__... | 5,332,304 |
def check_messenger(messenger: Optional[Callable]):
"""
Check that `messenger` is a `utipy.Messenger` object or `None`.
In the latter case a `utipy.Messenger` with `verbose=False` is returned.
Parameters
----------
messenger : `utipy.Messenger` or None
A Messenger instance to check.
... | 5,332,305 |
def convert(s):
"""Take an input string s, find all things that look like SGML character
entities, and replace them with the Unicode equivalent.
Function is from:
http://stackoverflow.com/questions/1197981/convert-html-entities-to-ascii-in-python/1582036#1582036
"""
matches = re.findall("&#\d+;", ... | 5,332,306 |
def check_data_selection(race_id=None, category_index=None, racer_id=None):
"""Makes sure that we are trying to show data that is in the database."""
errors = []
if not race_id in Races.get_column('race_id'):
race_id = Races.get_random_id()
errors.append('race')
categories = Races.get_c... | 5,332,307 |
def request_access_ticket(pat: str, permission_endpoint: str,
resources: List[dict],
secure: bool = False) -> str:
"""
As a Resource Server, request permission to the AS to access a resource,
generating a ticket as a result.
- CAN THROW EXCEPTIONS
- M... | 5,332,308 |
def index(request):
"""
Root page view. Just shows a list of liveblogs.
"""
# Get a list of liveblogs, ordered by the date of their most recent
# post, descending (so ones with stuff happening are at the top)
liveblogs = Liveblog.objects.annotate(
max_created=Max("posts__created")
).... | 5,332,309 |
def model_fn_builder(
bert_config,
num_labels,
init_checkpoint,
learning_rate,
num_train_steps,
num_warmup_steps,
use_tpu,
use_one_hot_embeddings
):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
... | 5,332,310 |
def strarray(*args):
"""strarray(strarray_t array, size_t array_size, int code) -> char"""
return _idaapi.strarray(*args) | 5,332,311 |
def _single_value_set(target_list, value):
"""
Return true if this constraint has only one value and it is
this one.
"""
return len(target_list) == 1 and target_list[0] == value | 5,332,312 |
def get_positive_input(message, float_parse=False, allow_zero=False):
""" Obtains and returns a positive int from the user.
Preconditions:
message: non-empty string
float_parse: bool defaulted to False
allow_zero: bool defaulted to False
Parameters:
message: The message that is printed whe... | 5,332,313 |
def hellinger(p, q):
"""Compute Hellinger distance between 2 distributions."""
return np.linalg.norm(np.sqrt(p) - np.sqrt(q)) / np.sqrt(2) | 5,332,314 |
def usd_currency(currency_df: pd.DataFrame, value: int, date: str) -> float:
"""
Compute VALUE/(USD/SYMBOL)
Parameters
----------
currency_df : pd.DataFrame
USD/SYMBOL df
value : int
Value of product
date : str
Currency quote day
Returns
---------
float
... | 5,332,315 |
def svn_wc_adm_probe_retrieve(*args):
"""svn_wc_adm_probe_retrieve(svn_wc_adm_access_t associated, char path, apr_pool_t pool) -> svn_error_t"""
return _wc.svn_wc_adm_probe_retrieve(*args) | 5,332,316 |
def flights_preclean(df):
"""
Input: Raw dataframe of Flights table.
Output: Cleaned flights table:
- Remove cancelled rows, made available in new dataframe "df_can"
- Drop columns ['Unnamed: 0', 'branded_code_share',
'mkt_carrier', 'cancelled', 'cancellation_code', 'flights', 'ai... | 5,332,317 |
def convert_spectral_kernel_quint(sequences, list_seq_to_id):
""" Return a list seq of nb of time the seq in list_seq_to_id appear in sequence"""
final = []
for j in range(len(sequences)):
sequence = sequences[j]
dico_appear = {seq: 0 for seq in list_seq_to_id}
for i in range(len(seq... | 5,332,318 |
def grad_of_marginal_fit(c, h, tau, epsilon):
"""Computes grad of terms linked to marginals in objective.
Computes gradient w.r.t. f ( or g) of terms in
https://arxiv.org/pdf/1910.12958.pdf, left-hand-side of Eq. 15
(terms involving phi_star)
Args:
c: jnp.ndarray, first target marginal (either a or b in... | 5,332,319 |
def SuggestField(**kwargs):
"""
Query 'foo' to get the TextField, or 'foo.raw' to get the KeywordField, or 'foo.suggest' to get the CompletionField.
"""
return fields.TextField(
fields={
'raw': fields.KeywordField(),
'suggest': fields.CompletionField(),
},
... | 5,332,320 |
def pyramid(a, b, c, d, e, depth, vertices, edges, surfaces, config):
"""
Recursive pyramid fractal generation.
ARGUMENTS:
a, b, c, d, e - pyramid vertices
depth - how deep in interations
vertices, edges, surfaces - mesh data lists
config - config tuple to generate from
"""
# if dep... | 5,332,321 |
def distance_on_unit_sphere(FoLat, FoLng, ToLat, ToLng):
""" Convert latitude and longitude to spherical coordinates in radians."""
phi1 = math.radians(90.0 - FoLat)
phi2 = math.radians(90.0 - ToLat)
theta1 = math.radians(FoLng)
theta2 = math.radians(ToLng)
"""Compute spherical distance from s... | 5,332,322 |
def check_pandas_support(caller_name):
"""Raise ImportError with detailed error message if pandsa is not
installed.
Plot utilities like :func:`fetch_openml` should lazily import
pandas and call this helper before any computation.
Parameters
----------
caller_name : str
The name of ... | 5,332,323 |
def multisgmapper(filein, krnfolder, outfolder):
"""Create series of artificial brightness maps from kernels in folder.
filein (str): VIIRS DNB file path
krnfolder (str): path to folder with kernel tifs
outfolder (str): location to save skyglow maps to
"""
# read in VIIRS DNB image
viirsras... | 5,332,324 |
def parse_cmdline():
"""Parse the command line arguments.
Returns:
argparse.Namespace. The parsed arguments or defaults.
"""
parser = argparse.ArgumentParser(
description="Dataplane Automated Testing System, version " + __version__,
epilog='Note: parameters on the command line w... | 5,332,325 |
def summarize_sequence(summary_type, hidden, d_model, n_head, d_head, dropout,
dropatt, input_mask, is_training, initializer,
scope=None, reuse=None):
"""Summarize hidden sequence into a vector."""
tf.logging.info("===== Sequence summary =====")
tf.logging.info(" - ... | 5,332,326 |
def process_submissions(company: Company, filing_data: dict):
"""
Adds all 10-K/10-Q (and amended versions) from the SEC API data
:param company: Company model object
:param filing_data:
:return: None
"""
form_list = filing_data["form"]
report_date_list = filing_data["reportDate"]
f... | 5,332,327 |
def encode_line(line, vocab):
"""Given a string and a vocab dict, encodes the given string"""
line = line.strip()
sequence = [vocab.get(char, vocab['<UNK>']) for char in line]
sequence_length = len(sequence)
return sequence, sequence_length | 5,332,328 |
def get_like_from_mats(ky_mat, l_mat, alpha, name):
""" compute the likelihood from the covariance matrix
:param ky_mat: the covariance matrix
:return: float, likelihood
"""
# catch linear algebra errors
labels = _global_training_labels[name]
# calculate likelihood
like = (-0.5 * np.m... | 5,332,329 |
def cached(*cache_args, **cache_kwargs):
"""General-purpose.
Allows custom filename, with function fallback.
Load/save cached function data. Also handle data types gracefully.
Example:
>>> cached('myfile.json', directory=SOME_DIR)
>>> def my_thing():
>>> return {'foo': 'bar... | 5,332,330 |
def test_python(host, f):
"""Ensure that python2-specific files no longer exist, except on AmazonLinux or Debian 9."""
# Note that r"^9(\.|$)" will match any string starting with "9.",
# or the string "9".
if host.system_info.distribution == "amzn" or (
host.system_info.distribution == "debian"
... | 5,332,331 |
def engulfing(data: pd.DataFrame):
"""
engulfing
Positive numbers are multi-side, negative numbers are short-side
0 is abnormal, meaning that the ratio of the absolute value of the current Candle up or down to the previous one is more than 10 times.
For machine learning convenience, a floating point... | 5,332,332 |
def create_dat_files(ipc_tests, test_results, dst_dir):
"""
Creates .dat files for all the test_results.
@param ipc_tests: list of ipc tests which was used to created the data.
@param test_results: dictionary containing all test results.
@param dst_dir: directory where the .dat-files shall be store... | 5,332,333 |
def filter_matches(kp1, kp2, matches, ratio = 0.75):
"""
This function applies a ratio test
:param kp1: raw keypoint 1
:param kp2: raw keypoint 2
:param matches: raw matches
:param ratio: filtering ratio
:return: filtered keypoint 1, filtered keypoint 2, keypoint pairs
"""
mkp1, mkp2... | 5,332,334 |
def try_different_adaptors():
"""
This method didn't return any positive results but it was work a try. We were
looking to see if using different SSLAdapters with the session object made a
difference. It certainly has different behaviour on different platforms but did
not fix the issue.
"""
... | 5,332,335 |
def logInsideConfInt(value0, unc0, value1, unc1, quantity):
"""Two values are within acceptable statistical limits."""
_notifyWithUncs(debug, quantity, 'Confidence intervals for {} overlap',
value0, unc0, value1, unc1) | 5,332,336 |
def add_derived_columns(
data: pd.DataFrame,
differences: bool = True,
second_differences: bool = True,
multiplications: bool = True,
rolling_means: int | None = 10,
rolling_stds: int | None = 10,
mean_distances: bool = True,
) -> pd.DataFrame:
"""This will create many columns that can b... | 5,332,337 |
def parse_query(
query: List[str],
format,
use_youtube,
generate_m3u,
lyrics_provider,
threads,
path_template,
) -> List[SongObject]:
"""
Parse query and return list containing song object
"""
songs_list = []
# Iterate over all search queries and add them to songs_list
... | 5,332,338 |
def start_db_server():
"""Spin up a test database server"""
log.debug('start_db_server()')
try:
os.mkdir(DATA_DIR)
except FileExistsError:
shutil.rmtree(DATA_DIR)
sp.check_call(['initdb', '-D', DATA_DIR])
db_proc = sp.Popen(['postgres', '-D', DATA_DIR])
time.sleep(0.5) # Ens... | 5,332,339 |
def GFF_bcftools_format(in_handle, out_handle):
"""Convert a bacterial genbank file from NCBI to a GFF3 format that can be used in bcftools csq.
see https://github.com/samtools/bcftools/blob/develop/doc/bcftools.txt#L1066-L1098.
Args:
in_file: genbank file
out_file: name of GFF file
"""
... | 5,332,340 |
def assert_address_book(address_book):
"""Fixture returning an object providing a custom address book asserts."""
return icemac.addressbook.testing.AddressBookAssertions(address_book) | 5,332,341 |
def make_shell_context():
"""Open shell."""
db = get_db()
return {"db": db, "Doi": Doi, "Url": Url, "FBRequest": FBRequest} | 5,332,342 |
def get_version():
"""
Extracts the version number from the version.py file.
"""
VERSION_FILE = 'fleming/version.py'
mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M)
if mo:
return mo.group(1)
else:
raise RuntimeError('Unable to find... | 5,332,343 |
def test_batch_op_async_execute_failure(context):
"""Tests that an AirflowException is raised in case of error event"""
task = BatchOperatorAsync(
task_id="task",
job_name=JOB_NAME,
job_queue="queue",
job_definition="hello-world",
max_retries=MAX_RETRIES,
status_... | 5,332,344 |
def get_cache_path():
""" Return a path suitable to store cached files """
try:
os.mkdir(cache_path)
except FileExistsError:
pass
return cache_path | 5,332,345 |
def distance(s1, s2):
""" Euclidean distance between two sequences. Supports different lengths.
If the two series differ in length, compare the last element of the shortest series
to the remaining elements in the longer series. This is compatible with Euclidean
distance being used as an upper bound for... | 5,332,346 |
def remove_test_set_gender_and_age(nodes):
"""Remove the gender feature from a subset of the nodes for estimation"""
# todo: the 40k random can be adjusted if youre working with a subset
test_profiles = np.random.choice(nodes["user_id"].unique(), 40000, replace=False)
nodes["TRAIN_TEST"] = "TRAIN"
... | 5,332,347 |
def valid_attribute(attr_filter_key, attr_filter_val, hit):
"""Validates the hit according to a filter attribute."""
if (attr_filter_key != "None") and (attr_filter_val != "None"):
try:
# If key for filtering is not correct or doesn't exist-> error
# should be ignored
... | 5,332,348 |
def dek_to_greg(dek_day: int, dek_month: int, dek_year: int) -> tuple:
"""Returns a Gregorian date from a Dekatrian date.
Args:
dek_day (int): Day of the month.
dek_month (int): Month of the year.
dek_year (int): Year.
Return:
tuple: A tuple with the day, month and year.
... | 5,332,349 |
def progress_bar(t):
"""Prints a progress bar that take t seconds to complete loading."""
from time import sleep
for i in range(1, 101):
print("\r{:>6}% |{:<30}|".format(
i, u"\u2588" * round(i // 3.333)), end='', flush=True)
sleep(t/100)
sleep(0.1)
print("\n") | 5,332,350 |
def encrypt_message(kx, ky, message):
"""
Encrypts a message using ECC and AES-256
First generates a random AES key and IV with os.urandom()
Then encrypts the original message with that key
Then encrypts the AES key with the ECC key
NOTE:
This means that plaintext will not have the same cip... | 5,332,351 |
def _create_init_files(original_file_location: FilePath) -> List[str]:
"""Given the original file location of a handler, create the artifact paths for all the __init__.py files that
make the handle a valid python modules
Args:
original_file_location (str): original file path
Returns:
L... | 5,332,352 |
def mirror_notes(key_position: int) -> int:
"""
指定したキーポジションを反転させた値を返します
引数
----
key_position : int
-> キーポジション
戻り値
------
int
-> キーポジションを反転したときのキーポジション
"""
return 512 - key_position | 5,332,353 |
def import_odim_hdf5(filename, **kwargs):
"""Import a precipitation field (and optionally the quality field) from a
HDF5 file conforming to the ODIM specification.
Parameters
----------
filename : str
Name of the file to import.
Other Parameters
----------------
qty : {'RATE', ... | 5,332,354 |
def sugerir(update: Update, _: CallbackContext) -> int:
"""Show new choice of buttons"""
query = update.callback_query
query.answer()
keyboard = [
[
InlineKeyboardButton("\U0001F519 Volver", callback_data=str(NINE)),
InlineKeyboardButton("\U0001F44B Salir", callba... | 5,332,355 |
def clone_subgraph(*, outputs, inputs, new_inputs, suffix="cloned"):
"""
Take all of the tensorflow nodes between `outputs` and `inputs` and clone
them but with `inputs` replaced with `new_inputs`.
Args:
outputs (List[tf.Tensor]): list of output tensors
inputs (List[tf.Tensor]): list of... | 5,332,356 |
async def refresh_replacements(db, sample_id: str) -> list:
"""
Remove sample file `replacement` fields if the linked files have been deleted.
:param db: the application database client
:param sample_id: the id of the sample to refresh
:return: the updated files list
"""
files = await virt... | 5,332,357 |
def test_sinewaveform():
"""
Test a SineWaveform object.
Ensure that the object is callable with the correct sine waveform.
"""
t = np.random.rand(1000)
freq, offset, amp = 1e9, 1, 2
wf = SineWaveform(frequency=freq, offset=offset, amplitude=amp)
y = amp * np.sin(2 * np.pi * freq * t - ... | 5,332,358 |
def _validate_options(args, unknown, groups):
"""Validate argument options."""
valid_count = 0
invalid = False
need_targets = False
call_on = None
if (args.search or args.query) and not args.verbose:
def no_call(name):
pass
call_on = no_call
else:
def act... | 5,332,359 |
def commitTaskBySerialNo(SerialNo):
"""
根据流水号通过任务的函数
:param SerialNo: 任务流水号
:return:
"""
raw = rawSql.Raw_sql()
raw.sql = "UPDATE RMI_TASK SET State = 0 WHERE SerialNo = '%s'"%SerialNo
raw.update()
return | 5,332,360 |
def torch_model (model_name, device, checkpoint_path = None):
""" select imagenet models by their name and loading weights """
if checkpoint_path:
pretrained = False
else:
pretrained = True
model = models.__dict__ [model_name](pretrained)
if hasattr (model, 'classifier... | 5,332,361 |
def main(inargs):
"""Run the program."""
pr_cube, pr_history = gio.combine_files(inargs.pr_files, 'precipitation_flux', checks=True)
evap_cube, evap_history = gio.combine_files(inargs.evap_files, 'water_evapotranspiration_flux', checks=True)
assert pr_cube.shape == evap_cube.shape
pe_cube = pr_cub... | 5,332,362 |
def get_timezone() -> Tuple[datetime.tzinfo, str]:
"""Discover the current time zone and it's standard string representation (for source{d})."""
dt = get_datetime_now().astimezone()
tzstr = dt.strftime("%z")
tzstr = tzstr[:-2] + ":" + tzstr[-2:]
return dt.tzinfo, tzstr | 5,332,363 |
def get_model(input_shape: List[int], weight_array: np.array,
batches_per_step: int, replication_factor: int, batch_size: int,
channels: int, data_len: int, synthetic_data: bool,
buffer_streams: bool) -> Tuple:
"""Get a simple model for comparison with buffer streams on and... | 5,332,364 |
def shell_safe_json_parse(json_or_dict_string, preserve_order=False):
""" Allows the passing of JSON or Python dictionary strings. This is needed because certain
JSON strings in CMD shell are not received in main's argv. This allows the user to specify
the alternative notation, which does not have this prob... | 5,332,365 |
def get_timed_roadmaps_grid_common(
ins: Instance, T: int, size: int,
) -> list[TimedRoadmap]:
"""[deprecated] get grid roadmap shared by all agents
Args:
ins (Instance): instance
T (int): assumed makespan
size (int): size x size grid will be constructed
Returns:
list[n... | 5,332,366 |
def train(last_step, lmbdas):
"""Trains the model."""
if args.verbose:
tf.logging.set_verbosity(tf.logging.INFO)
# create input data pipeline.
with tf.device('/cpu:0'):
train_files = glob.glob(args.train_glob)
train_dataset = tf.data.Dataset.from_tensor_slices(train_files)
... | 5,332,367 |
def connect_areas_in_streams(system, cortical_areas):
"""
Dorsal / ventral aware version. Include V1 and V2 in cortical_areas, but they must be
connected to each other separately.
"""
for target in [a for a in cortical_areas if a not in ('V1', 'V2')]:
for source in data.get_source_areas(targ... | 5,332,368 |
def remove_except_npy(c: "Config", keep: str):
"""Remove files except keep .npy files with a given word in the filename."""
keep = keep.split()
print_w(f"Removing all files in: {c.generated_data_dir()}")
print_w(f"Except files containing one of: {keep}")
def clean_dir(dir_path):
for root, d... | 5,332,369 |
def arithmetic_series(a: int, n: int, d: int = 1) -> int:
"""Returns the sum of the arithmetic sequence with parameters a, n, d.
a: The first term in the sequence
n: The total number of terms in the sequence
d: The difference between any two terms in the sequence
"""
return n * (2 * a + (n - 1... | 5,332,370 |
def get_arc_proxy_user(proxy_file=None):
"""
Returns the owner of the arc proxy. When *proxy_file* is *None*, it defaults to the result of
:py:func:`get_arc_proxy_file`. Otherwise, when it evaluates to *False*, ``arcproxy`` is queried
without a custom proxy file.
"""
out = _arc_proxy_info(args=[... | 5,332,371 |
def pass_hot_potato(names, num):
"""Pass hot potato.
A hot potato is sequentially passed to ones in a queue line.
After a number of passes, the one who got the hot potato is out.
Then the passing hot potato game is launched againg,
until the last person is remaining one.
"""
name_queue = Queue()
for name in n... | 5,332,372 |
def convert_timeseries_dataframe_to_supervised(df: pd.DataFrame, namevars, target, n_in=1, n_out=0, dropT=True):
"""
Transform a time series in dataframe format into a supervised learning dataset while
keeping dataframe intact.
Returns the transformed pandas DataFrame, the name of the target column ... | 5,332,373 |
def setup_logging(options, conf):
"""
Sets up the logging options for a log with supplied name
:param options: Mapping of typed option key/values
:param conf: Mapping of untyped key/values from config file
"""
if options.get('log_config', None):
# Use a logging configuration file for al... | 5,332,374 |
def build_graph(adj_mat):
"""build sparse diffusion graph. The adjacency matrix need to preserves divergence."""
# sources, targets = adj_mat.nonzero()
# edgelist = list(zip(sources.tolist(), targets.tolist()))
# g = Graph(edgelist, edge_attrs={"weight": adj_mat.data.tolist()}, directed=True)
g = Gr... | 5,332,375 |
def retrieve_context_path_comp_service_end_point_end_point(uuid): # noqa: E501
"""Retrieve end-point
Retrieve operation of resource: end-point # noqa: E501
:param uuid: ID of uuid
:type uuid: str
:rtype: List[str]
"""
return 'do some magic!' | 5,332,376 |
def submit_pai_task(pai_cmd, datasource):
"""Submit given cmd to PAI which manipulate datasource
Args:
pai_cmd: The command to submit
datasource: The datasource this cmd will manipulate
"""
user, passwd, address, project = MaxComputeConnection.get_uri_parts(
datasource)
cmd ... | 5,332,377 |
def test_step8():
"""8. If the remaining string is empty, return a slash."""
assert check(["dirname", "///"]).stdout == "/\n" | 5,332,378 |
def get_external_repos(gh):
"""
Get all external repositories from the `repos.config` file
"""
external_repos = []
with open("repos.config") as f:
content = f.readlines()
content = [x.strip() for x in content]
for entry in content:
org_name, repo_name = entry.sp... | 5,332,379 |
def handle_standard_table(pgconn, table_name, columns, record):
"""
:param pgconn:
:param table_name:
:param columns:
:param record:
:return:
"""
data = dict(record)
log.debug("Standard handler: {}".format(data))
if 'id' in columns:
data_exists = pgconn.execute(
... | 5,332,380 |
def load_fit_profile():
"""
This methods return the FIT profile types based on the Profile.xslx that is included in the Garmin FIT SDK (https://developer.garmin.com/fit/download/).
The returned profile can be used to translate e.g. Garmin product names to their corresponding integer product ids.
"""
... | 5,332,381 |
def mmethod(path, *args, **kwargs):
"""
Returns a mapper function that runs the path method for each instance of
the iterable collection.
>>> mmethod('start')
is equivalent to
>>> lambda thread: thread.start()
>>> mmethod('book_set.filter', number_of_pages__gte=100)
is equivalent to
... | 5,332,382 |
def create_crd_from_yaml(
api_extensions_v1_beta1: ApiextensionsV1beta1Api, name, yaml_manifest
) -> None:
"""
Create a specific CRD based on yaml file.
:param api_extensions_v1_beta1: ApiextensionsV1beta1Api
:param name: CRD name
:param yaml_manifest: an absolute path to file
"""
print... | 5,332,383 |
def download_peakfile(source_url, filename, destination_dir):
"""Download peakfile from encode"""
response = requests.get(source_url, stream=True)
with open(os.path.join(destination_dir, filename), 'wb') as f:
shutil.copyfileobj(response.raw, f)
with gzip.open(os.path.join(destination_dir, file... | 5,332,384 |
def generate_test_demand_design_image() -> TestDataSet:
"""
Returns
-------
test_data : TestDataSet
2800 points of test data, uniformly sampled from (price, time, emotion). Emotion is transformed into img.
"""
org_test: TestDataSet = generate_test_demand_design(False)
treatment = org... | 5,332,385 |
def run_sim(
params: SimulationParams,
gen_factory: TransactionGeneratorFactory,
sched_factory: TransactionSchedulerFactory,
executor: TransactionExecutor = DEFAULT_EXECUTOR,
obj_set_maker_factory: ObjSetMakerFactory = DEFAULT_OBJ_SET_MAKER_FACTORY,
):
"""Yield index and path through the state s... | 5,332,386 |
def rename(src, dst):
"""Rename file."""
makedirs(dst)
os.rename(src, dst) | 5,332,387 |
def test_connection_error_with_response():
"""
Test error string is formatted correctly
when exception is initialized with response
"""
Response = namedtuple("Response", "status_code reason content")
response = Response(status_code="404", reason="Not found", content="Here some content")
erro... | 5,332,388 |
def main(args):
"""Main CLI function
"""
args = parse_args(args)
setup_logging(args.loglevel)
stitcher = Stitcher(args.input)
stitcher.generate(args.output, args.cleanup) | 5,332,389 |
def value_iteration(game, depth_limit, threshold):
"""Solves for the optimal value function of a game.
For small games only! Solves the game using value iteration,
with the maximum error for the value function less than threshold.
This algorithm works for sequential 1-player games or 2-player zero-sum
games,... | 5,332,390 |
def printable_dataframe(data: typing.List[typing.Mapping], ignore_phase: bool = True) -> pd.DataFrame:
""" Print performance results using pandas data frames.
TODO: Re-write me.
"""
columns = {'name': 'Model', 'input_shape': 'Input shape', 'num_parameters': '#Parameters',
'param_memor... | 5,332,391 |
def _import_and_infer(save_dir, inputs):
"""Import a SavedModel into a TF 1.x-style graph and run `signature_key`."""
graph = ops.Graph()
with graph.as_default(), session_lib.Session() as session:
model = loader.load(session, [tag_constants.SERVING], save_dir)
signature = model.signature_def[
sign... | 5,332,392 |
def new_module(fname, main=False, parser_vmx=None):
"""
`fname` is Python str (or None for internal Module)
`main` is Python True for main program (from command line)
`argv` is Python list of str (if main is True)
`parser_vmx` is Python str for parser VMX file to use
returns (CModule, CClosure) ... | 5,332,393 |
def test_question_load_two_answer(monkeypatch):
"""load a complete question and two answers
"""
class MonkeyAnswer(exam2pdf.Answer):
def __init__(self):
super().__init__()
self._attr_load_sequence = ("text", "image")
self._type_caster_sequence = (str, Path)
... | 5,332,394 |
def url_by_properties(
config_properties,
db_type,
submit_dir=None,
top_dir=None,
rundir_properties=None,
cl_properties=None,
props=None,
):
""" Get URL from the property file """
# Validate parameters
if not db_type:
raise ConnectionError(
"A type should be p... | 5,332,395 |
def draw_map_24(inputs):
"""draw 24+1 maps of a day"""
draw_map = DrawMap(inputs)
draw_map.read_head()
for n in range(draw_map.reader.ini_ntime, 25+draw_map.reader.ini_ntime):
draw_map.create_title(n)
draw_map.reader_uv_by_time(n)
print(draw_map.title_full)
draw_map.draw... | 5,332,396 |
def nth(seq, idx):
"""Return the nth item of a sequence. Constant time if list, tuple, or str;
linear time if a generator"""
return get(seq, idx) | 5,332,397 |
def db_session(db: log_database.Database) -> log_database.Database.SessionType:
"""A test fixture which yields an empty graph proto database."""
with db.Session() as session:
yield session | 5,332,398 |
def test_expm_depletion():
"""Test that depletion is carried out properly"""
# -------------------------------------------------------------------------
# DEPLETION
# -------------------------------------------------------------------------
dep = MainDepletion(0.0, data)
... | 5,332,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.