content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def pomodoro_timer():
"""
25 min timer popup window acting as a callback function to the work timer button
"""
global popup_1
popup_1 = tk.Toplevel(root)
popup_1.title("Work Timer!")
popup_1.geometry("370x120")
round = 0
try:
# Creating a continous loop of text of time on th... | 5,347,500 |
def save_video_list_to_hdf5(video_list_path, save_path):
"""Store the unique videos in the given video list in an HDF5 file.
:param video_list_path: Path to a video list
:param save_path: The path to the HDF5 file to create
"""
with open(video_list_path, 'r') as f:
lines = [line.stri... | 5,347,501 |
def getCredibleInterval(df):
"""
compute 95% credible interval (bayesian approach)
Args:
dataframe: first column is name(string), second column is score(numeric)
Return:
dataframe(three columns:name,lower_bound,upper_bound)
"""
pass | 5,347,502 |
def add_mutes(guild_id: int, role_id: int, user_id: int, author_id: int, datetime_to_parse: str):
"""
Add a temporary mute to a user.
NOTE: datetime_to_parse should be a string like: "1 hour 30 minutes"
"""
with open("data/unmutes.json", "r+", newline='\n', encoding='utf-8') as temp_file:
mu... | 5,347,503 |
def operation_dict(ts_epoch, request_dict):
"""An operation as a dictionary."""
return {
"model": request_dict,
"model_type": "Request",
"args": [request_dict["id"]],
"kwargs": {"extra": "kwargs"},
"target_garden_name": "child",
"source_garden_name": "parent",
... | 5,347,504 |
def setdlopenflags(n): # real signature unknown; restored from __doc__
"""
setdlopenflags(n) -> None
Set the flags used by the interpreter for dlopen calls, such as when the
interpreter loads extension modules. Among other things, this will enable
a lazy resolving of symbols when importing a m... | 5,347,505 |
def unix_timestamp(s=None, p="yyyy-MM-dd HH:mm:ss"):
"""
:rtype: Column
>>> import os, time
>>> os.environ['TZ'] = 'Europe/Paris'
>>> if hasattr(time, 'tzset'): time.tzset()
>>> from pysparkling import Context, Row
>>> from pysparkling.sql.session import SparkSession
>>> spark = SparkSe... | 5,347,506 |
def memory_index(indices, t):
"""Location of an item in the underlying memory."""
memlen, itemsize, ndim, shape, strides, offset = t
p = offset
for i in range(ndim):
p += strides[i] * indices[i]
return p | 5,347,507 |
def createExpData(f, xVals):
"""Asssumes f is an exponential function of one argument
xVals is an array of suitable arguments for f
Returns array containing results of applying f to the
elements of xVals"""
yVals = []
for i in range(len(xVals)):
yVals.append(f(x... | 5,347,508 |
def main() -> None:
"""
Calculate and output the solutions based on the real puzzle input.
"""
data = aocd.get_data(year=2016, day=25)
print(f"Part 1: {find_starting_a_for_clock_output(data)}") | 5,347,509 |
def run_macs2_ATAC(Configuration):
"""
run macs2 application
"""
logging.info("running macs2")
cleaned_align_output_dir = os.path.join(Configuration.cleaned_alignments_dir, Configuration.file_to_process)
filtered_align_file = cleaned_align_output_dir + f"/{Configuration.file_to_process}_al... | 5,347,510 |
def discrete_one_samp_ks(distribution1: np.array, distribution2: np.array, num_samples: int) -> Tuple[float, bool]:
"""Uses the one-sample Kolmogorov-Smirnov test to determine if the empirical results in
distribution1 come from the distribution represented in distribution2
:param distribution1: empirical d... | 5,347,511 |
def main():
"""
Main
"""
deamonize("myserver-server")
HOST, PORT = "localhost", 9999
LOG.info("** Starting myserver server on https://%s:%d **" % (HOST, PORT))
server = MyServer((HOST, PORT))
# For SSL - uncomment the following line
#server.socket = ssl.wrap_socket(server.socket, key... | 5,347,512 |
def test_get_live_markets():
"""Test get_live_markets."""
assert all(isinstance(market_info, MarketInfo) for market_info in get_live_markets()) | 5,347,513 |
def _get_product_refs(pkgs):
"""Returns a list of product references as declared in the specified packages list.
Args:
pkgs: A `list` of package declarations (`struct`) as created by
`packages.create()`, `packages.pkg_json()` or `spm_pkg()`.
Returns:
A `list` of product refer... | 5,347,514 |
def run_equilb_ensemble_gomc_command(job):
"""Run the gomc equilb_ensemble simulation."""
for run_equilb_ensemble_i in range(
job.doc.equilb_design_ensemble_number, equilb_design_ensemble_max_number
):
print("#**********************")
print("# Started the run_equilb_ensemble_gomc_com... | 5,347,515 |
def merge_intervals(interval_best_predictors):
"""
Merge intervals with the same best predictor
"""
predictor2intervals = defaultdict(set)
for interval, best_predictor in interval_best_predictors.items():
predictor2intervals[best_predictor].update(interval)
merged_intervals = {best_predi... | 5,347,516 |
def build_pixel_sampler(cfg, **default_args):
"""Build pixel sampler for segmentation map."""
return build_module_from_cfg(cfg, PIXEL_SAMPLERS, default_args) | 5,347,517 |
def solution_to_schedule(solution, events, slots):
"""Convert a schedule from solution to schedule form
Parameters
----------
solution : list or tuple
of tuples of event index and slot index for each scheduled item
events : list or tuple
of :py:class:`resources.Event` instances
... | 5,347,518 |
def flip_tiles( tiles ):
"""
Initially all tiles are white. Every time, a tile is visited based on the
directions, it is flipped (to black, or to white again).
The directions are represented in (x,y) coordinates starting from reference
tile at (0,0).
Based on the given directions to each ... | 5,347,519 |
def version() -> int:
"""Return the version number of the libpq currently loaded.
The number is in the same format of `~psycopg.ConnectionInfo.server_version`.
Certain features might not be available if the libpq library used is too old.
"""
return impl.PQlibVersion() | 5,347,520 |
def feature_predictors_from_ensemble(features, verbose=False):
"""generates a dictionary of the form
{"offset":offset_predictor, "sigma":sigma_predictor, ...}
where the predictors are generated from the center and spread statistics
of the feature ensemble.
features: list
the feature ... | 5,347,521 |
def remoteLoggingConfig(host, args, session):
"""
Called by the logging function. Configures remote logging (rsyslog).
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used by the logging sub command
@param session: the active... | 5,347,522 |
def _merge_3d_t1w(filename: Union[str, PathLike]) -> pathlib.Path:
"""
Merges T1w images that have been split into two volumes
Parameters
----------
filename : str or pathlib.Path
Path to T1w image that needs to be merged
Returns
-------
filename : pathlib.Path
Path to merged T1w image
"""
import numpy... | 5,347,523 |
def write_model(outfile, best):
""" write top individual out to model file """
functions = [str(b) for b in best]
penalized_igs = [b.fitness.values[0] for b in best]
lengths = [b.fitness.values[1] for b in best]
model_df = pd.DataFrame(np.array([penalized_igs, lengths, functions]).T)
model_df.co... | 5,347,524 |
def get_partial_results(case_name, list_of_variables):
""" Get a dictionary with the variable names and the time series for `list_of_variables`
"""
reader = get_results(case_name)
d = dict()
read_time = True
for v in list_of_variables:
if read_time:
d['time'] = reader.values(... | 5,347,525 |
def take_with_time(self, duration, scheduler=None):
"""Takes elements for the specified duration from the start of the
observable source sequence, using the specified scheduler to run timers.
Example:
res = source.take_with_time(5000, [optional scheduler])
Description:
This operator accumulat... | 5,347,526 |
def add_label(hdf5_filename, key, peak, label):
"""
Function that adds a label to a peak dataset in the hdf5 file.It
has to be iterated over every single peak.
Parameters:
hdf5_filename (string): filename of experimental file
key (string): key within `hdf5_filename` of experime... | 5,347,527 |
def test_aws_binary_which(host):
"""
Tests the output to confirm aws's binary location.
"""
assert host.check_output('which aws') == PACKAGE_BINARY | 5,347,528 |
def _infer_color_variable_kind(color_variable, data):
"""Determine whether color_variable is array, pandas dataframe, callable,
or scikit-learn (fit-)transformer."""
if hasattr(color_variable, "dtype") or hasattr(color_variable, "dtypes"):
if len(color_variable) != len(data):
raise Value... | 5,347,529 |
def ParseChromeosImage(chromeos_image):
"""Parse the chromeos_image string for the image and version.
The chromeos_image string will probably be in one of two formats:
1: <path-to-chroot>/src/build/images/<board>/<ChromeOS-version>.<datetime>/ \
chromiumos_test_image.bin
2: <path-to-chroot>/chroot/tmp/<bu... | 5,347,530 |
def save_model(_clf, save_folder, filename, logger):
"""
Dumps a given classifier to the specific folder with the given name
"""
_path = os.path.join(save_folder, filename)
logger.debug("save model to " + _path)
with open(_path, 'wb') as handle:
pickle.dump(_clf, handle, protocol=pickle.... | 5,347,531 |
def update_alias(AliasName=None, TargetKeyId=None):
"""
Associates an existing AWS KMS alias with a different customer master key (CMK). Each alias is associated with only one CMK at a time, although a CMK can have multiple aliases. The alias and the CMK must be in the same AWS account and region. You cannot pe... | 5,347,532 |
def Dense(name, out_dim, W_init=stax.glorot(), b_init=stax.randn()):
"""Layer constructor function for a dense (fully-connected) layer."""
def init_fun(rng, example_input):
input_shape = example_input.shape
k1, k2 = random.split(rng)
W, b = W_init(k1, (out_dim, input_shape[-1])), b_init(... | 5,347,533 |
def datetime_to_epoch(date_time: datetime) -> int:
"""Convert a datetime object to an epoch integer (seconds)."""
return int(date_time.timestamp()) | 5,347,534 |
def parse_arguments():
"""
Merge the scar.conf parameters, the cmd parameters and the yaml
file parameters in a single dictionary.
The precedence of parameters is CMD >> YAML >> SCAR.CONF
That is, the CMD parameter will override any other configuration,
and the YAML parameters will override the... | 5,347,535 |
def write_pcd_results(network_manager, folder, year, pop_scenario,
throughput_scenario, intervention_strategy, cost_by_pcd, lad_areas):
"""
Write postcode sector results to .csv file.
"""
suffix = _get_suffix(pop_scenario, throughput_scenario, intervention_strategy)
if not os.path.exists(folder... | 5,347,536 |
def check_signature(stream: BinaryIO) -> str:
"""
Check signature of the model file and return characters used by the model.
The characters returned are sorted in lexicographical order.
"""
uzmodel_tag = stream.read(8)
if uzmodel_tag != b'UZMODEL ':
raise IOError('invalid uzmodel_tag')
... | 5,347,537 |
def Validate(expected_schema, datum):
"""Determines if a python datum is an instance of a schema.
Args:
expected_schema: Schema to validate against.
datum: Datum to validate.
Returns:
True if the datum is an instance of the schema.
"""
schema_type = expected_schema.type
if schema_type == 'null'... | 5,347,538 |
def get_main_play_action(action: PlayerAction) -> PlayerAction:
"""
Gets the main play, e.g., FLYOUT or SINGLE
:param action:
:return:
"""
print("Searching for main play")
# find out if the string contains any of the allowed actions
for i in PlayerActionEnum:
if i.value in acti... | 5,347,539 |
def inet_aton(s):
"""Convert a dotted-quad to an int."""
try:
addr = list(map(int, s.split('.')))
addr = reduce(lambda a,b: a+b, [addr[i] << (3-i)*8 for i in range(4)])
except (ValueError, IndexError):
raise ValueError('illegal IP: {0}'.format(s))
return addr | 5,347,540 |
def welcome_and_instruct():
""" Prints welcome and instructions upon program start """
for x in range(5):
print('\r\n')
figlet = pyfiglet.figlet_format('Tweet Annotation Tool', font='slant')
print(figlet)
print('by Kris Bolton')
print('v0.2.0-alpha')
print('\r\n')
print('INFORMAT... | 5,347,541 |
def local_principals(context, principals):
""" The idea behind this is to process __ac_local_roles__ (and a boolean __ac_local_roles_block__
to disable) and add local principals. This only works if you're in correct context, though,
which does not seem to be the case.
"""
local_principals = ... | 5,347,542 |
def dfs_paths(graph, start, end=None):
"""Find all paths in digraph, return a generator of tuples
Input: adjacency list in a dict:
{
node1: set([node1, node2, node3]),
node2: set([node2, node3]),
node3: set(),
}
"""
if not graph or start not in graph:
return
... | 5,347,543 |
def exportSchemaAsXSD(schema, versionNumber, filePath):
"""
Exports the given schema as an XSD document.
Parameters
----------
schema : Schema
The schema to export.
versionNumber : string
The version number of the schema.
filePath : string
The path to which to save t... | 5,347,544 |
def helper():
"""I'm useful helper"""
data = {
"31 Dec 2019": "Wuhan Municipal Health Commission, China, reported a cluster of cases of pneumonia in Wuhan, Hubei Province. A novel coronavirus was eventually identified.",
"1 January 2020": "WHO had set up the IMST (Incident Management Support Tea... | 5,347,545 |
def canonicalize_specification(expr, syn_ctx, theory):
"""Performs a bunch of operations:
1. Checks that the expr is "well-bound" to the syn_ctx object.
2. Checks that the specification has the single-invocation property.
3. Gathers the set of synth functions (should be only one).
4. Gathers the var... | 5,347,546 |
def human_time(seconds, granularity=2):
"""Returns a human readable time string like "1 day, 2 hours"."""
result = []
for name, count in _INTERVALS:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip("s")
... | 5,347,547 |
def main():
"""Create the model and start the evaluation process."""
args = get_arguments()
if args.data_path is not None:
args.img_path = args.data_path + args.img_path
# Prepare image.
og = tf.image.decode_jpeg(tf.read_file(args.img_path), channels=3)
# Compress and reconstruct ... | 5,347,548 |
def _galaxy_loc_iter(loc_file, galaxy_dt, need_remap=False):
"""Iterator returning genome build and references from Galaxy *.loc file.
"""
if "column" in galaxy_dt:
dbkey_i = galaxy_dt["column"].index("dbkey")
path_i = galaxy_dt["column"].index("path")
else:
dbkey_i = None
if... | 5,347,549 |
def cmorlet_wavelet(x, fs, freq_vct, n=6, normalization=True):
"""Perform the continuous wavelet (CWT) tranform using the complex Morlet wavelet.
Parameters
----------
x : 1D array with shape (n_samples) or
2D array with shape (n_samples, n_channels)
fs : Sampling frequency
... | 5,347,550 |
def update(key=None, value=None, cache_type=None, file_path=None):
"""Set the cache that depends on the file access time
:param key: the key for the cache
:param value: the value in the cache
:param cache_type: when we are using cache in different modules this param
can protects from the ove... | 5,347,551 |
def add_fake_planet(
stack: np.ndarray,
parang: np.ndarray,
psf_template: np.ndarray,
polar_position: Tuple[Quantity, Quantity],
magnitude: float,
extra_scaling: float,
dit_stack: float,
dit_psf_template: float,
return_planet_positions: bool = False,
interpolation: str = 'bilinea... | 5,347,552 |
def base_subs_test():
"""Base substitution."""
seq = 'ACGT'
sub_pts = [0, 1, 2, 3]
t_mat = [[0.0, 0.3, 0.3, 0.3],
[0.3, 0.0, 0.3, 0.3],
[0.3, 0.3, 0.0, 0.3],
[0.3, 0.3, 0.3, 0.0]]
rng = MockRng([0.5, 0.5, 0.5, 0.5])
# -> G G C C
base_subbed = mitty.lib.util.base_subs(seq... | 5,347,553 |
def update_cluster_cli(args: Namespace):
"""Updates the cluster configuration of the databricks instance defined in the current profile
:param Namespace args: The arguments from the cli
:return:
"""
# Set the name
cluster_name = args.name.lower()
# Get the base profile
profile, base_co... | 5,347,554 |
def migrate_all(src, dst, replace=True, nprocs=1):
"""Migrates entire dataset from source host to destination host using multiprocessing"""
srchost, srcport, _ = parse_uri(src)
srcr = redis.StrictRedis(host=srchost, port=srcport, charset='utf8')
keyspace = srcr.info('keyspace')
freeze_support() # ... | 5,347,555 |
def make_cache(channel, subdir):
"""Reads and/or generates the cachefile and returns the cache"""
# load cache
channel_name = _get_channel_name(channel)
cachefile = f"{channel_name}.{subdir}.cache.json"
if os.path.exists(cachefile):
print(f"Loading cache from {cachefile}")
with open(... | 5,347,556 |
def _BD_from_Av_for_dereddening(line_lambdas, line_fluxes, A_v):
"""
Find the de-reddened Balmer decrement (BD) that would arise from "removing"
an extinction of A_v (magnitudes) from the line_fluxes.
line_lambdas, line_fluxes: As in the function "deredden".
A_v: The extinction (magnitudes), as a sc... | 5,347,557 |
def otherEnd(contours, top, limit):
"""
top与end太近了,找另一个顶部的点,与top距离最远
"""
tt = (0, 9999)
for li in contours:
for pp in li:
p = pp[0]
if limit(p[0]) and top[1] - p[1] < 15 and abs(top[0] - p[0]) > 50 and p[1] < tt[1]:
tt = p
return tt | 5,347,558 |
def plivo_webhook(event, context):
"""
Receives SMS messages and forwards them to telegram
"""
CHAT_ID = int(os.environ['CHAT_ID'])
bot = configure_telegram()
logger.info('Plivo Event: {}'.format(event))
try:
body = parse_plivo_msg(event)
except AssertionError as e:
log... | 5,347,559 |
def convert(input_format, output_format, input_path, output_path):
""" Run: qemu-img -f <input-format> -O <output-format> <input-path> <output-path> """
print(f"qemu-img -f {input_format} -O {output_format} {input_path} {output_path}")
if input_format not in FORMATS or output_format not in FORMATS:
... | 5,347,560 |
def test_award_update_contract_txn_with_list():
"""Test optional parameter to update specific awards from txn contract."""
awards = mommy.make('awards.Award', _quantity=5)
txn = mommy.make('awards.TransactionNormalized', award=awards[0])
mommy.make(
'awards.TransactionFPDS',
transaction... | 5,347,561 |
async def reset(dut, time=20):
""" Reset the design """
dut.reset = 1
await Timer(time, units="ns")
await RisingEdge(dut.clk)
dut.reset = 0
await RisingEdge(dut.clk) | 5,347,562 |
def castep_phonon_prerelax(computer, calc_doc, seed):
""" Run a singleshot geometry optimisation before an SCF-style calculation.
This is typically used to ensure phonon calculations start successfully.
The phonon calculation will then be restarted from the .check file produced here.
Parameters:
... | 5,347,563 |
def get_external_links(soup):
"""Retrieve the different links from a `Lyric Wiki` page.
The links returned can be found in the `External Links` page section,
and usually references to other platforms (like Last.fm, Amazon, iTunes etc.).
Args:
soup (bs4.element.Tag): connection to the `Lyric Wik... | 5,347,564 |
def gcc():
"""Return the current container, that is the widget holding the figure and all the control widgets, buttons etc."""
gcf() # make sure we have something..
return current.container | 5,347,565 |
def axis_val_hud(*args):
"""
Toggle the presence of a heads-up-display (HUD) for viewing axes in Maya.
:param args:
:return:
"""
robots = get_robot_roots(1)
if not robots:
print 'No Robots in Scene'
if pm.headsUpDisplay('a1_hud', exists=True):
for i in range(6):
... | 5,347,566 |
def preprocessing(string):
"""helper function to remove punctuation froms string"""
string = string.replace(',', ' ').replace('.', ' ')
string = string.replace('(', '').replace(')', '')
words = string.split(' ')
return words | 5,347,567 |
def firetime(tstart, Tfire):
""" Highly accurate sub-millisecond absolute timing based on GPSDO 1PPS and camera fire feedback.
Right now we have some piecemeal methods to do this, and it's time to make it industrial strength
code.
"""
raise NotImplementedError("Yes this is a priority, would you lik... | 5,347,568 |
def add_input_arguments(argument_parser_object):
"""Adds input args for this script to `argparse.ArgumentParser` object.
:param argument_parser_object: `argparse.ArgumentParser` object, which may
or may not already contain input args.
:return: argument_parser_object: Same as input object, but with ... | 5,347,569 |
def fullUnitSphere(res):
"""Generates a unit sphere in the same way as :func:`unitSphere`, but
returns all vertices, instead of the unique vertices and an index array.
:arg res: Resolution - the number of angles to sample.
:returns: A ``numpy.float32`` array of size ``(4 * (res - 1)**2, 3)``
... | 5,347,570 |
def prompt_for_word_removal(words_to_ignore=None):
"""
Prompts the user for words that should be ignored in kewword extraction.
Parameters
----------
words_to_ignore : str or list
Words that should not be included in the output.
Returns
-------
ignore words, words_a... | 5,347,571 |
def wait_for_image_property(identifier, property, cmp_func,
wait=20,
maxtries=10):
"""Wait for an image to have a given property.
Raises TimeoutError on failure.
:param identifier: the image identifier
:param property: the name of the property
... | 5,347,572 |
def make_sample_ensemble_seg_plot(model2, model3, sample_filenames, test_samples_fig, flag='binary'):
"""
"make_sample_ensemble_seg_plot(model2, model3, sample_filenames, test_samples_fig, flag='binary')"
This function uses two trained models to estimate the label image from each input image
It then use... | 5,347,573 |
def mock_requests_get_json_twice(mocker: MockerFixture) -> MagicMock:
"""Mock two pages of results returned from the parliament open data API."""
mock: MagicMock = mocker.patch("requests.get")
mock.return_value.__enter__.return_value.json.side_effect = [
{
"columnNames": ["column1", "col... | 5,347,574 |
def _get_rating_accuracy_stats(population, ratings):
"""
Calculate how accurate our ratings were.
:param population:
:param ratings:
:return:
"""
num_overestimates = 0
num_underestimates = 0
num_correct = 0
for employee, rating in zip(population, ratings):
if rating < em... | 5,347,575 |
def genb58seed(entropy=None):
"""
Generate a random Family Seed for Ripple. (Private Key)
entropy = String of any random data. Please ensure high entropy.
## Note: ecdsa library's randrange() uses os.urandom() to get its entropy.
## This should be secure enough... but just in case, I added the... | 5,347,576 |
def convert_nhwc_to_nchw(data: np.array) -> np.array:
"""Convert data to NCHW."""
return np.transpose(data, [0, 3, 1, 2]) | 5,347,577 |
def get_mfcc_features(wave_data: pd.Series, n_mfcc):
"""
mfcc_feature
"""
x = wave_data.apply(lambda d: (d-np.mean(d))/(np.std(d)))
# x = wave_data
x, max_length = utils.padding_to_max(x)
features = []
for i in range(x.shape[0]):
t1 = mfcc(x[i], sr=16000, n_mfcc=n_mfcc)
t... | 5,347,578 |
def project_screen_group():
"""
Mengelola screen pada spesifik project.
""" | 5,347,579 |
def _upload_to_s3(md5: str, local_file_path: str, metadata: Dict[str, str]) -> None:
"""Upload the binary contents to S3 along with the given object metadata.
Args:
md5: CarbonBlack MD5 key (used as the S3 object key).
local_file_path: Path to the file to upload.
metadata: Binary metada... | 5,347,580 |
def run(
tag,
env,
parallel,
runner,
is_async,
node_names,
to_nodes,
from_nodes,
from_inputs,
load_version,
pipeline,
config,
params,
):
"""Run the pipeline."""
if parallel and runner:
raise KedroCliError(
"Both --parallel and --runner opti... | 5,347,581 |
def test_repr_diagnostic_task(diagnostic_task):
"""Test printing a diagnostic task."""
diagnostic_task.name = 'diag_1/script_1'
result = str(diagnostic_task)
print(result)
reference = textwrap.dedent("""
DiagnosticTask: diag_1/script_1
script: /some/where/esmvaltool/diag_scripts/test.py
... | 5,347,582 |
def download_instance_func(instance_id):
"""Download a DICOM Instance as DCM"""
file_bytes = client.orthanc.download_instance_dicom(instance_id)
return flask.send_file(BytesIO(file_bytes), mimetype='application/dicom', as_attachment=True, attachment_filename=f'{instance_id}.dcm') | 5,347,583 |
def test_cloud_vendor_azure_fetch_error():
"""
Test failure fetching Azure data with HTTP
"""
tempdir = tempfile.mkdtemp()
prefixes = Prefixes(cache_directory=tempdir)
vendor = prefixes.get_vendor('azure')
with patch('netlookup.network_sets.azure.AZURE_SERVICES_URL', INVALID_URL):
w... | 5,347,584 |
def generate_random_initial_params(n_qubits, n_layers=1, topology='all', min_val=0., max_val=1., n_par=0, seed=None):
"""Generate random parameters for the QCBM circuit (iontrap ansatz).
Args:
n_qubits (int): number of qubits in the circuit.
n_layers (int): number of entangling layers in the ci... | 5,347,585 |
def locate_alien():
"""Locate an alien and add it to the DB
Locating an alien in this implementation is as simple
as naming it using a random uuid
"""
# Generate a name for the alien
alien_name = base64.urlsafe_b64encode(uuid.uuid4().bytes)
# Get DB session
session = db.get_session()
... | 5,347,586 |
def number_of_friends(user):
"""How many friends does this user have?"""
user_id = user["id"]
friend_ids = friendships[user_id]
return len(friend_ids) | 5,347,587 |
def get_serializer_class(format=None):
"""Convenience function returns serializer or raises SerializerNotFound."""
if not format:
serializer = BaseSerializer()
elif format == 'json-ld':
serializer = JsonLDSerializer()
elif format == 'json':
serializer = JsonSerializer()
else:... | 5,347,588 |
def get_or_create_mpc_section(
mp_controls: "MpConfigControls", section: str, subkey: Optional[str] = None # type: ignore
) -> Any:
"""
Return (and create if it doesn't exist) a settings section.
Parameters
----------
mp_controls : MpConfigControls
The MP Config database.
section :... | 5,347,589 |
def get_sql_table_headers(csv_dict_reader: csv.DictReader) -> str:
""" This takes in a csv dictionary reader type, and returns a list of the headings needed to make a table """
column_names = []
for row in csv_dict_reader:
for column in row:
column_names.append('{} {} '.format(column, ge... | 5,347,590 |
def greater_than(val1, val2):
"""Perform inequality check on two unsigned 32-bit numbers (val1 > val2)"""
myStr = flip_string(val1) + flip_string(val2)
call(MATH_32BIT_GREATER_THAN,myStr)
return ord(myStr[0]) == 1 | 5,347,591 |
def upsampling_2x_blocks(n_speakers, speaker_dim, target_channels, dropout):
"""Return a list of Layers that upsamples the input by 2 times in time dimension.
Args:
n_speakers (int): number of speakers of the Conv1DGLU layers used.
speaker_dim (int): speaker embedding size of the Conv1DGLU laye... | 5,347,592 |
def actor_path(data, actor_id_1, goal_test_function):
"""
Creates the shortest possible path from the given actor ID to
any actor that satisfies the goal test function.
Returns a a list containing actor IDs.
If no actors satisfy the goal condition, returns None.
"""
agenda = {actor... | 5,347,593 |
def write_data_v1(people, filename):
"""Writes in-memory data objects about Peers or MPs to an external file."""
csv_file = open(filename, 'wb')
writer = csv.writer(csv_file)
headings = ['Member_Id', 'Dods_Id', 'Pims_Id', 'DisplayAs', 'ListAs', 'FullTitle', 'LayingMinisterName',
'DateOfB... | 5,347,594 |
def create_script_run(snapshot_root_directory: Optional[Path] = None,
entry_script: Optional[PathOrString] = None,
script_params: Optional[List[str]] = None) -> ScriptRunConfig:
"""
Creates an AzureML ScriptRunConfig object, that holds the information about the snapsh... | 5,347,595 |
def test_super_tensor_property():
"""
Tensor: Super_tensor correctly tensors on underlying spaces.
"""
U1 = rand_unitary(3)
U2 = rand_unitary(5)
U = tensor(U1, U2)
S_tens = to_super(U)
S_supertens = super_tensor(to_super(U1), to_super(U2))
assert_(S_tens == S_supertens)
assert... | 5,347,596 |
def test_merge_anime_info():
"""Test_merge_anime_info."""
expected_data = {
'ageRating': 'R',
'amazon': 'https://www.amazon.com/gp/video/detail/B06VW8K7ZJ/',
'averageRating': '82.69',
'canonicalTitle': 'Cowboy Bebop',
'categories': [
'science-fiction', 'space'... | 5,347,597 |
def M_to_E(M, ecc):
"""Eccentric anomaly from mean anomaly.
.. versionadded:: 0.4.0
Parameters
----------
M : float
Mean anomaly (rad).
ecc : float
Eccentricity.
Returns
-------
E : float
Eccentric anomaly.
"""
with u.set_enabled_equivalencies(u.di... | 5,347,598 |
def load_beijing():
"""Load and return the Beijing air quality dataset."""
module_path = os.path.dirname(__file__)
data = pd.read_csv(
os.path.join(module_path, 'data', 'beijing_air_quality.csv'))
return data | 5,347,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.