content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def create_cell(cell_classname, cell_params):
""" Creates RNN cell.
Args:
cell_classname: The name of the cell class,
e.g. "LSTMCell", "GRUCell" and so on.
cell_params: A dictionary of parameters to pass
to the cell constructor.
Returns:
A `tf.contrib.rnn.RNNCel... | 21,600 |
def get_myia_tag(rtag):
"""Return the myia tag for a constructor.
This will fail if you haven't properly called fill_reverse_tag_map().
"""
return rev_tag_map[rtag] | 21,601 |
def get_priority(gene, phenotype):
"""
Get matched priority from the phenotype table.
Parameters
----------
gene : str
Gene name.
phenotype : str
Phenotype name.
Returns
-------
str
EHR priority.
Examples
--------
>>> import pypgx
>>> pypgx... | 21,602 |
def _generator3(path):
"""
Args:
path: path of the dataframe
Returns:
yield outputs of X and Y pairs
"""
args = init_args()
catalog = load_catalog(path)
def preprocess(x, y=None):
zero = False
if not np.any(x):
zero = True
img = (x - avg_x... | 21,603 |
def _extract_gsi(name):
"""
Extract a normalised groundstation if available.
:param name:
:rtype: str
>>> _extract_gsi('LANDSAT-7.76773.S3A1C2D2R2')
>>> _extract_gsi('AQUA.60724.S1A1C2D2R2')
>>> _extract_gsi('TERRA.73100.S1A2C2D4R4')
>>> _extract_gsi('LANDSAT-8.3108')
>>> _extract_g... | 21,604 |
def array_at_verts_basic2d(a):
"""
Computes values at cell vertices on 2d array using neighbor averaging.
Parameters
----------
a : ndarray
Array values at cell centers, could be a slice in any orientation.
Returns
-------
averts : ndarray
Array values at cell vertices,... | 21,605 |
def get_subquestion_answer(response, questions, subquestion):
"""
Return the answer to a subquestion from ``response``.
"""
question_id = subquestion[0]
answers = response[question_id]
dim = len(subquestion) - 1
for answer in answers:
matched = True
if subquestion[1] != answe... | 21,606 |
def convert_dir_save(inputdir, outputdir, templatedir, temporarydir, prefix):
"""
Converts all .msg files in inputdir to uORB header files
Unchanged existing files are not overwritten.
"""
# Create new headers in temporary output directory
convert_dir(inputdir, temporaryd... | 21,607 |
def uniform_centroids(dist_map, n_centroids):
"""
Uniformly space `n_centroids` seeds in a naive way
:param dist_map: sparse distance map
:param n_centroids: number of seeds to place
:return: (n_centroids, ) integer arrays with the indices of the seeds
"""
def get_dist(idx_vertex):
... | 21,608 |
def main():
"""
This program creates lines on an instance of GWindow class.
There is a circle indicating the user’s first click. A line appears
at the condition where the circle disappears as the user clicks
on the canvas for the second time.
"""
onmouseclicked(draw_circle_or_draw_lin... | 21,609 |
def collate_custom(batch,key=None):
""" Custom collate function for the Dataset class
* It doesn't convert numpy arrays to stacked-tensors, but rather combines them in a list
* This is useful for processing annotations of different sizes
"""
# this case will occur in first pass, and will ... | 21,610 |
def get_horizon(latitude, longitude, dem, ellipsoid=Ellipsoid("WGS84"), distance=0.5, precision=1):
""" Compute local get_horizon obstruction from Digital Elevation Model
This function is mainly based on a previous Matlab function
(see https://fr.mathworks.com/matlabcentral/fileexchange/59421-dem-based-top... | 21,611 |
def get_articles(language, no_words, max_no_articles, search, **kwargs):
""" Retrieve articles from Wikipedia """
wikipedia.set_rate_limiting(True) # be polite
wikipedia.set_lang(language)
if search is not None:
titles = wikipedia.search(search, results = max_no_articles)
else:
titl... | 21,612 |
def gen_urdf_material(color_rgba):
"""
:param color_rgba: Four element sequence (0 to 1) encoding an rgba colour tuple, ``seq(float)``
:returns: urdf element sequence for an anonymous material definition containing just a color element, ``str``
"""
return '<material name=""><color rgba="{0} {1} {2} ... | 21,613 |
def _add_temp_index(db):
"""Add an index to the 'identifier' column to make queries faster."""
add_identifier_index = """
CREATE INDEX CONCURRENTLY {identifier_index_name} ON {case_index_table} (identifier)
""".format(
case_index_table=CommCareCaseIndexSQL._meta.db_table,
identifier_... | 21,614 |
def plot(self, class_=None, show_plot=True, plot_3D=True, plot_probs=True,
plot_dominant_classes=True, plot_poly=False, plot_normals=False,
plot_subclasses=False, plot_legend=True, fig=None, ax=None,
title='Softmax Classification',
**kwargs):
"""Display the class and/or PDF plots... | 21,615 |
def roll_timeseries(arr, timezones):
"""
Roll timeseries from UTC to local time. Automatically compute time-shift
from UTC offset (timezone) and time-series length.
Parameters
----------
arr : ndarray
Input timeseries array of form (time, sites)
timezones : ndarray | list
Ve... | 21,616 |
def is_linear(a, eps=1e-3):
"""Check if array of numbers is approximately linear."""
x = np.diff(a[1:-1]).std() / np.diff(a[1:-1]).mean()
return x < eps | 21,617 |
def faces_sphere(src, show_path):
"""
Compute vertices and faces of Sphere input for plotting.
Parameters
----------
- src (source object)
- show_path (bool or int)
Returns
-------
vert, faces (returns all faces when show_path=int)
"""
# pylint: disable=protected-access
... | 21,618 |
def pronto_signals_to_iguana_signals(carrier_frequency, signals):
"""Convert the pronto format into iguana format, where the pulses and spaces
are represented in number of microseconds.
"""
return [carrier_cycles_to_microseconds(carrier_frequency, signal) | command
for signal, command in
... | 21,619 |
def test_helper_functions():
"""
Test for get_atomic_num_one_hot(), get_atom_chiral_tag_one_hot() and get_atom_mass() helper functions
"""
smiles = 'C'
m = Chem.MolFromSmiles(smiles)
atom = m.GetAtoms()[0]
f_atomic = get_atomic_num_one_hot(
atom, GraphConvConstants.ATOM_FEATURES['atomic_num'])
req... | 21,620 |
def stack_xarray_repdim(da, **dims):
"""Like xarrays stack, but with partial support for repeated dimensions
The xarray.DataArray.stack method fails when any dimension occurs
multiple times, as repeated dimensions are not currently very well
supported in xarray (2018-03-26). This method provides a wor... | 21,621 |
def compute_pnorm(model: nn.Module) -> float:
"""
Computes the norm of the parameters of a model.
:param model: A PyTorch model.
:return: The norm of the parameters of the model.
"""
return math.sqrt(sum([p.norm().item() ** 2 for p in model.parameters()])) | 21,622 |
def atomic_brute_cast(tree: Element) -> Element:
"""
Cast every node's text into an atomic string to prevent further processing on it.
Since we generate the final HTML with Jinja templates, we do not want other inline or tree processors
to keep modifying the data, so this function is used to mark the c... | 21,623 |
def _sync_batch_changes(tasks_list: DbTasksChange):
"""Dummy function to perform the write in db"""
with TASK_TABLE.batch_writer() as batch:
for task in tasks_list.tasks_to_update:
batch.put_item(Item=_serialize_downward_task(task))
for task_id in tasks_list.ids_to_remove:
... | 21,624 |
def rsa_keys(p: int = None, q: int = None, e: int = 3) -> RSA_Keys:
"""
Generate a new set of RSA keys.
If p and q are not provided (<= 1),
then they will be generated.
:param p: A big prime.
:param q: A big prime.
:param e: The default public key.
:return: The RSA private and public ke... | 21,625 |
def chunk_file(file_path, chunks, work_dir):
"""Splits a large file by line into number of chunks and writes them into work_dir"""
with open(file_path) as fin:
num_lines = sum(1 for line in fin)
chunk_size = math.ceil(num_lines / chunks)
output_file_paths = []
with contextlib.ExitStack() as... | 21,626 |
def _get_closest_station_by_zcta_ranked(zcta):
""" Selects the nth ranked station from a list of ranked stations
Parameters
----------
zcta : string
ZIP Code Tabulation Area (ZCTA)
Returns
-------
station : string
Station that was found
warnings : list
List of w... | 21,627 |
def display_percentage(context: ExecutionContext, event: events.AfterExecution) -> None:
"""Add the current progress in % to the right side of the current line."""
operations_count = cast(int, context.operations_count) # is already initialized via `Initialized` event
current_percentage = get_percentage(con... | 21,628 |
def label_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if not title:
... | 21,629 |
def run_sample():
"""Runs the sample."""
# !!! ATTENTION !!!
# Running this sample may change/delete your Google Analytics account
# configuration. Make sure to not use the Google Analytics property ID from
# your production environment below.
# TODO(developer): Replace this variable with y... | 21,630 |
def lowpass(data,in_t=None,cutoff=None,order=4,dt=None,axis=-1,causal=False):
"""
data: vector of data
in_t: sample times
cutoff: cutoff period in the same units as in_t
returns vector same as data, but with high frequencies removed
"""
# Step 1: Determine dt from data or from user if ... | 21,631 |
def gather_along_dim_with_dim_single(x, target_dim, source_dim, indices):
"""
This function indexes out a target dimension of a tensor in a structured way,
by allowing a different value to be selected for each member of a flat index
tensor (@indices) corresponding to a source dimension. This can be int... | 21,632 |
def resolve_parallelism(parallel):
"""Decide what level of parallelism to use.
Parameters
----------
parallel : integer or None
The user's specification
Returns
-------
A positive integer giving the parallelization level.
"""
if parallel is None:
if mp.get_start_me... | 21,633 |
def get_queue(launcher=None):
"""Get the name of the queue used in an allocation.
:param launcher: Name of the WLM to use to collect allocation info. If no launcher
is provided ``detect_launcher`` is used to select a launcher.
:type launcher: str | None
:returns: Name of the queue
... | 21,634 |
def _initial_logs():
"""write some initial logs"""
logger.info(f"Username: {getpass.getuser()}")
logger.info(
f"Most recent git commit hash: {subprocess.getoutput('git rev-parse HEAD')} "
)
logger.info(
f"Git remote and branch info: {subprocess.getoutput('git remote show origin')}"
... | 21,635 |
def get_openmc_geometry(openmoc_geometry):
"""Return an OpenMC geometry corresponding to an OpenMOC geometry.
Parameters
----------
openmoc_geometry : openmoc.Geometry
OpenMOC geometry
Returns
-------
openmc_geometry : openmc.Geometry
Equivalent OpenMC geometry
"""
... | 21,636 |
def distinct(xs):
"""Get the list of distinct values with preserving order."""
# don't use collections.OrderedDict because we do support Python 2.6
seen = set()
return [x for x in xs if x not in seen and not seen.add(x)] | 21,637 |
def get_price_to_free_cash_flow_ratio(equity, year=None, market_cap=None):
"""
This ratio can be found by dividing the current price of the stock by its free cash flow per share,
Easy way is to get it from the ratios object extracted from investing.
"""
try:
price_to_free_cash_flow = None
... | 21,638 |
def _parse_train_configs(train_config):
"""
check if user's train configs are valid.
Args:
train_config(dict): user's train config.
Return:
configs(dict): final configs will be used.
"""
configs = copy.deepcopy(_train_config_default)
configs.update(train_config)
assert ... | 21,639 |
def as_region(region):
"""
Convert string to :class:`~GenomicRegion`.
This function attempts to convert any string passed to it
to a :class:`~GenomicRegion`. Strings are expected to be
of the form <chromosome>[:<start>-<end>[:[strand]], e.g.
chr1:1-1000, 2:2mb-5mb:-, chrX:1.5kb-3mb, ...
Nu... | 21,640 |
def android_patch() -> None:
"""Run necessary patches on an android archive before building."""
fname = 'src/cpython/Modules/Setup.dist'
txt = efrotools.readfile(fname)
# Need to switch some flags on this one.
txt = efrotools.replace_one(txt, '#zlib zlibmodule.c',
'z... | 21,641 |
def premetadata_create_account_stat_table(self, conn, put_timestamp):
"""
Copied from AccountBroker before the metadata column was
added; used for testing with TestAccountBrokerBeforeMetadata.
Create account_stat table which is specific to the account DB.
:param conn: DB connection object
:par... | 21,642 |
def parse_user_next_stable(user):
"""
Parse the specified user-defined string containing the next stable version
numbers and returns the discretized matches in a dictionary.
"""
try:
data = re.match(user_version_matcher, user).groupdict()
if len(data) < 3:
raise Attribute... | 21,643 |
def interp_ADCP_2D(
sadcp,
mask,
depth,
lon,
lat,
time,
time_win=360.0,
rmax=15.0,
vmax=2.0,
range_min=4.0,
):
"""
This is essentially a loop over the interp_ADCP function with some additional NaN handling.
Assume data is of the form D[i, j] where each j represents a... | 21,644 |
def extract_p(path, dict_obj, default):
"""
try to extract dict value in key path, if key error provide default
:param path: the nested dict key path, separated by '.'
(therefore no dots in key names allowed)
:param dict_obj: the dictinary object from which to extract
:param default: a default r... | 21,645 |
def default_lscolors(env):
"""Gets a default instanse of LsColors"""
inherited_lscolors = os_environ.get("LS_COLORS", None)
if inherited_lscolors is None:
lsc = LsColors.fromdircolors()
else:
lsc = LsColors.fromstring(inherited_lscolors)
# have to place this in the env, so it is appl... | 21,646 |
def get_indices_by_sent(start, end, offsets, tokens):
"""
Get sentence index for textbounds
"""
# iterate over sentences
sent_start = None
sent_end = None
token_start = None
token_end = None
for i, sent in enumerate(offsets):
for j, (char_start, char_end) in enumerate(sent... | 21,647 |
def get_server_object_by_id(nova, server_id):
"""
Returns a server with a given id
:param nova: the Nova client
:param server_id: the server's id
:return: an SNAPS-OO VmInst object or None if not found
"""
server = __get_latest_server_os_object_by_id(nova, server_id)
return __map_os_serv... | 21,648 |
def _test_resource_get(req=None, res=None):
"""Handle Test Resource GET requests."""
res.status = falcon.HTTP_200
res.body = ('This is me, Falcon, serving a resource!') | 21,649 |
def download_file( token, file_id, file_name, file_size, check_sum, num_connections, key, output_file=None ):
"""Download an individual file"""
if key is not None:
raise ValueError('key parameter: encrypted downloads are not supported yet')
if file_name.endswith(".gpg"):
logging.info(... | 21,650 |
def delete_report(report_uuid: str, database):
"""Delete a report."""
report = latest_report(report_uuid, database)
report["deleted"] = "true"
insert_new_report(report, database) | 21,651 |
def get_tasks(container_name):
"""Get the list of tasks in a container."""
file_name = tasks_path(container_name)
try:
tasks = [x.rstrip() for x in open(file_name).readlines()]
except IOError:
if os.path.exists(file_name):
raise
tasks = [] # container doesn't exist ... | 21,652 |
def get_args() -> argparse.Namespace:
"""Get script command line arguments."""
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument(
"-i",
"--input-files",
required=True,
nargs="+",
type=helpers.check_file_arg,
help="Path to... | 21,653 |
def _get_archive(software, version):
"""
Gets the downloaded source archive for a software version.
:param software: software to get the downloaded source archive for
:type software: str
:param version: software release
:type version: str
"""
download_dir = get_download_location()
... | 21,654 |
def make_odm(study_oid, environment, site_oid, subject_oid, mapping,
retrieved_datetime, transfer_user, transfer_identifier, freeze=True):
"""Receives a mapping like:
[
dict(folder_oid="SCRN", form_oid="DM", field_oid="SEX", value="M", cdash_domain="DM", cdash_element="SEX"),
... | 21,655 |
def parse_string(xml):
""" Returns a slash-formatted string from the given XML representation.
The return value is a TokenString (see mbsp.py).
"""
string = ""
from xml.dom.minidom import parseString
dom = parseString(xml)
# Traverse all the <sentence> elements in the XML.
for senten... | 21,656 |
def join_ad_domain_by_taking_over_existing_computer_using_session(
ad_session: ADSession, computer_name=None, computer_password=None, old_computer_password=None,
computer_key_file_path=DEFAULT_KRB5_KEYTAB_FILE_LOCATION) -> ManagedADComputer:
""" A fairly simple 'join a domain' function using pre-cre... | 21,657 |
def test_ValidateAccessToken_empty_env():
"""Test nothing is found in an empty environment.
"""
environ = {}
start_response = lambda x: x
fsr = FakeSecretRecover("the wrong secret")
assert fsr.access_secret == "the wrong secret"
assert fsr.access_token_given is None
app = MockApp()
... | 21,658 |
def clone_repositories(githuburl,githubuser,githubtoken):
"""
Delete existing directories and clone all repositories for the given user
"""
github_token = Github(githubtoken)
user = github_token.get_user()
repos = github_token.get_user(githubuser).get_repos()
for repo in repos:
rep... | 21,659 |
def peak_sound_pressure(pressure, axis=-1):
"""
Peak sound pressure :math:`p_{peak}` is the greatest absolute sound pressure during a certain time interval.
:param pressure: Instantaneous sound pressure :math:`p`.
:param axis: Axis.
.. math:: p_{peak} = \\mathrm{max}(|p|)
"""
return np.ab... | 21,660 |
def _download_and_prepare(
args: argparse.Namespace,
builder: tfds.core.DatasetBuilder,
) -> None:
"""Generate a single builder."""
logging.info(f'download_and_prepare for dataset {builder.info.full_name}...')
dl_config = _make_download_config(args)
if args.add_name_to_manual_dir:
dl_config.manual_... | 21,661 |
def test2_RPY_to_RotZYX():
"""
Test2 the method RPY_to_RotZYX
"""
roll: float = 1.8
pitch: float = 1.8
yaw: float = 1.8
rot_obtained = RPY_to_RotZYX(roll, pitch, yaw)
rot_expected = array([[0.0516208, 0.0057865, 0.9986500],
[-0.2212602, 0.9751976, 0.0057865],
... | 21,662 |
def field_filter_query(field, values):
"""Need to define work-around for full-text fields."""
values = ensure_list(values)
if not len(values):
return {'match_all': {}}
if field in ['_id', 'id']:
return {'ids': {'values': values}}
if len(values) == 1:
if field in ['names', 'ad... | 21,663 |
def export_categories(filename, memmaps, regionlist):
""" make CSV with on eline per mem_map of regions
- in regionlist order
"""
print memmaps
outf = open(filename, 'w')
# title line
outf.write("%s, " % "system")
for name in regionlist[:-1]: outf.write("%s, " % name)
outf.write... | 21,664 |
def compute_investigation_stats(inv, exact=True, conf=0.95, correct=True):
"""
Compute all statistics for all protected features of an investigation
Parameters
----------
inv :
the investigation
exact :
whether exact tests should be used
conf :
overall confidence l... | 21,665 |
def UpdatePackageContents(change_report, package_cp, portage_root=None):
"""Add newly created files/directors to package contents.
Given an ItemizedChangeReport, add the newly created files and directories
to the CONTENTS of an installed portage package, such that these files are
considered owned by that packa... | 21,666 |
def group_bars(note_list):
"""
Returns a list of bars, where each bar is a list of notes. The
start and end times of each note are rescaled to units of bars, and
expressed relative to the beginning of the current bar.
Parameters
----------
note_list : list of tuples
List of not... | 21,667 |
def get_vmexpire_id_from_ref(vmexpire_ref):
"""Parse a container reference and return the container ID
The container ID is the right-most element of the URL
:param container_ref: HTTP reference of container
:return: a string containing the ID of the container
"""
vmexpire_id = vmexpire_ref.rspl... | 21,668 |
def create_A_and_B_state_ligand(line, A_B_state='vdwq_q'):
"""Create A and B state topology for a ligand.
Parameters
----------
line : str
'Atom line': with atomtype, mass, charge,...
A_B_state : str
Interactions in the A state and in the B state.
vdwq_vdwq: ligand fully inte... | 21,669 |
def pytask_resolve_dependencies_select_execution_dag(dag):
"""Select the tasks which need to be executed."""
scheduler = TopologicalSorter.from_dag(dag)
visited_nodes = []
for task_name in scheduler.static_order():
if task_name not in visited_nodes:
have_changed = _have_task_or_neig... | 21,670 |
def test(model, model_path, device, data_path, data_transform, batch_size, classes):
"""
Test the given model with the given weights and dataset
Parameters
----------
`model`: network model to be trained
`model_path`: path to load the model weights from
`device`: device to be used for testi... | 21,671 |
def clean_params(estimator, n_jobs=None):
"""clean unwanted hyperparameter settings
If n_jobs is not None, set it into the estimator, if applicable
Return
------
Cleaned estimator object
"""
ALLOWED_CALLBACKS = (
"EarlyStopping",
"TerminateOnNaN",
"ReduceLROnPlateau... | 21,672 |
def getValidOauth2TxtCredentials(force_refresh=False, api=None):
"""Gets OAuth2 credentials which are guaranteed to be fresh and valid."""
try:
credentials = auth.get_admin_credentials(api)
except gam.auth.oauth.InvalidCredentialsFileError:
doRequestOAuth() # Make a new request which should... | 21,673 |
def get_combinations_sar(products, aoi):
"""Get a dataframe with all possible combinations of products and calculate
their coverage of the AOI and the temporal distance between the products.
Parameters
----------
products : dataframe
Search results with product identifiers as index.
aoi... | 21,674 |
def sample(s, n):
"""Show a sample of string s centered at position n"""
start = max(n - 8, 0)
finish = min(n + 24, len(s))
return re.escape(s[start:finish]) | 21,675 |
def monkey_patch():
"""Patches decorators for all functions in a specified module.
If the CONF.monkey_patch set as True,
this function patches a decorator
for all functions in specified modules.
You can set decorators for each modules
using CONF.monkey_patch_modules.
The format is "Module ... | 21,676 |
def getNeededLibraries(binary_filepath):
"""
Get all libraries given binary depends on.
"""
if False:
return getNeededLibrariesLDD(binary_filepath)
else:
return getNeededLibrariesOBJDUMP(binary_filepath) | 21,677 |
def load_transformer(input_paths:List[str], input_type:str=None) -> Transformer:
"""
Creates a transformer for the appropriate file type and loads the data into
it from file.
"""
if input_type is None:
input_types = [get_type(i) for i in input_paths]
for t in input_types:
... | 21,678 |
def consult_filme():
"""
Consulta filme
"""
print('==>Consulta filme:')
id_movie = input("Entre com o ID do filme: ")
url = f'{url_base}{id_movie}'
print(f'Requisição get: {url}')
r = requests.get(url)
if (r.status_code >= 400 and r.status_code <= 499):
print("Filme não loca... | 21,679 |
def delete_and_create_osd_node_aws_upi(osd_node_name):
"""
Unschedule, drain and delete osd node, and creating a new osd node.
At the end of the function there should be the same number of osd nodes as
it was in the beginning, and also ceph health should be OK.
This function is for AWS UPI.
Arg... | 21,680 |
def encode_integer_compact(value: int) -> bytes:
"""Encode an integer with signed VLQ encoding.
:param int value: The value to encode.
:return: The encoded integer.
:rtype: bytes
"""
if value == 0:
return b"\0"
if value < 0:
sign_bit = 0x40
value = -value
else:... | 21,681 |
def kin_phos_query(kin_accession):
"""
Query to pull related phosphosites using kinase accession
:param kin_accession: string kinase accession
:return: Flask_Table Phosphosite_results object
"""
session = create_sqlsession()
q = session.query(Kinase).filter_by(kin_accession= kin_accession)
... | 21,682 |
def max_surplus(redemptions, costs, traders):
"""
Calculates the maximum possible surplus
"""
surplus = 0
transactions = 0.5 * traders
for redemption, cost in zip(redemptions, costs):
if redemption >= cost:
surplus += ((redemption - cost) * transactions)
return surplus | 21,683 |
def generate_create_account_key():
"""
Generates a random account creation key. Implementation is very similar to
generate_reset_key().
"""
chars = string.ascii_lowercase + string.digits
return misc_utils.generate_random_string(constants.CREATE_ACCOUNT_KEY_LENGTH,
chars=chars) | 21,684 |
def nyu_single_set_multiple_tokens(slug_set, slug_sets, rtypes):
"""
Check for multiple token relations on a single hit/slug_set pair. If the two baskets share
a common main entry, the cuttoff for multiple relations is actually:
number-of-slugs-in-main-entry + 1
"""
intersections = [s for s ... | 21,685 |
def parse_dblife(file):
"""Parse an DBLife file, returning a tuple:
positions: list of (x,y) co-ordinates
comments: all comments in file, as a list of strings, one per line.
"""
lines = file.split("\n")
comments = []
positions = []
x = 0
y = 0
dblife_pattern = r"((\d*... | 21,686 |
def db_handle_error(logger: Logger, default_return_val: Any) \
-> Any:
"""Handle operational database errors via decorator."""
def decorator(func: Callable) -> Any:
def wrapper(*args, **kwargs): # type: ignore
# Bypass attempt to perform query and just return default value
... | 21,687 |
def climb_directory_tree(starting_path: PathOrStr, file_patterns: Iterable[str]) -> Optional[List[Path]]:
"""Climb the directory tree looking for file patterns."""
current_dir: Path = Path(starting_path).absolute()
if current_dir.is_file():
current_dir = current_dir.parent
while current_dir.roo... | 21,688 |
def serve_file(request, token, require_requester=True, verify_requester=True, signer=None):
"""Basic view to serve a file.
Uses ``evaluate_request`` under the hood. Please refer to that function to view information about exceptions.
:param request: the file request
:type request: bgfiles.models.FileRe... | 21,689 |
def test_quadbin_toparent_neg_res():
"""Throws error for negative resolution"""
with pytest.raises(Exception):
run_query('SELECT QUADBIN_TOPARENT(5209574053332910079, -1)') | 21,690 |
def d2_rho_heterodyne(t, rho_vec, A, args):
"""
Need to cythonize, docstrings
"""
M = A[0] + A[3]
e1 = cy_expect_rho_vec(M, rho_vec, 0)
d1 = spmv(M, rho_vec) - e1 * rho_vec
M = A[0] - A[3]
e1 = cy_expect_rho_vec(M, rho_vec, 0)
d2 = spmv(M, rho_vec) - e1 * rho_vec
return [1.0 / np... | 21,691 |
def plot_driver(est_dict, fname, plot_type):
""" Drive usage of Plotter given a dictionary of estimates """
plotter = plot_type(fname)
for key, est in est_dict.iteritems():
plotter.estimator_plot(est, key)
plotter.out() | 21,692 |
def get_venv():
"""Return virtual environment path or throw an error if not found"""
env = environ.get("VIRTUAL_ENV", None)
if env:
return Path(env)
else:
raise EnvironmentError("No virtual environment found.") | 21,693 |
def test_output_format_raw(tmpdir):
"""Verify raw output format."""
# Attachment
attachment_path = Path(tmpdir/"attachment.txt")
attachment_path.write_text("Hello world\n")
# Simple template
template_path = Path(tmpdir/"mailmerge_template.txt")
template_path.write_text(textwrap.dedent("""\
... | 21,694 |
def parse_pascal_voc_anno(
anno_path: str, labels: List[str] = None, keypoint_meta: Dict = None
) -> Tuple[List[AnnotationBbox], Union[str, Path], np.ndarray]:
""" Extract the annotations and image path from labelling in Pascal VOC format.
Args:
anno_path: the path to the annotation xml file
... | 21,695 |
def load_user(user_id):
"""Login manager load user method."""
return User.query.get(int(user_id)) | 21,696 |
def write_dataframe_to_files(
df,
filename_prefix='dpdd_object',
output_dir='./',
hdf_key_prefix='object',
parquet_scheme='simple',
parquet_engine='fastparquet',
parquet_compression='gzip',
append=True,
verbose=True,
write=('parquet',),
... | 21,697 |
def test_depolarizing_channel():
"""
Description: Test depolarizing channel
Expectation: success.
"""
sim2 = Simulator('projectq', 1)
sim2.apply_gate(C.DepolarizingChannel(0).on(0))
assert np.allclose(sim2.get_qs(), np.array([1.0 + 0.0j, 0.0 + 0.0j])) | 21,698 |
def test_interpolate_energy_dispersion():
"""Test of interpolation of energy dispersion matrix using a simple dummy model."""
x = [0.9, 1.1]
y = [8., 11.5]
n_grid = len(x) * len(y)
n_offset = 1
n_en = 30
n_mig = 20
clip_level = 1.e-3
# define simple dummy bias and resolution model u... | 21,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.