content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def is_valid_dim(x: Any) -> bool:
"""determine if the argument will be valid dim when included in torch.Size.
"""
return isinstance(x, int) and x > 0 | 5,340,900 |
def compute_alpha(n, S_d, d_min):
"""
Approximate the alpha of a power law distribution.
Parameters
----------
n: int or np.array of int
Number of entries that are larger than or equal to d_min
S_d: float or np.array of float
Sum of log degrees in the distribution that are lar... | 5,340,901 |
def _head_object(
s3_conn: S3Client, bucket: str, key: str
) -> Optional[HeadObjectOutputTypeDef]:
"""Retrieve information about an object in S3 if it exists.
Args:
s3_conn: S3 connection to use for operations.
bucket: name of the bucket containing the key.
key: name of the key to l... | 5,340,902 |
def Residual(feat_maps_in, feat_maps_out, prev_layer):
"""
A customizable residual unit with convolutional and shortcut blocks
Args:
feat_maps_in: number of channels/filters coming in, from input or previous layer
feat_maps_out: how many output channels/filters this block will produce
prev... | 5,340,903 |
def test_p4():
""" Test some simple base cases using D with varying bases """
for i in range(2, 10):
d = D([str(_) for _ in range(i)], [1/i]*i)
d.set_base(i)
yield assert_almost_equal, P(d), i | 5,340,904 |
def clean_detail_line_data(detail_row: List[str], date: str) -> List[str]:
"""
:param detail_row: uncleaned detail row
:param date: job data to be added to data
:return: a cleaned list of details fields
"""
if not detail_row:
print('detail_row:', detail_row)
return detail_row
... | 5,340,905 |
def lammps_prod(job):
"""Run npt ensemble production."""
in_script_name = "in.prod"
modify_submit_lammps(in_script_name, job.sp)
msg = f"sbatch submit.slurm {in_script_name} {job.sp.replica} {job.sp.temperature} {job.sp.pressure} {job.sp.cutoff}"
return msg | 5,340,906 |
def gather_tensors(tensors, indices):
"""Performs a tf.gather operation on a set of Tensors.
Args:
tensors: A potentially nested tuple or list of Tensors.
indices: The indices to use for the gather operation.
Returns:
gathered_tensors: A potentially nested tuple or list of Tensors with the
sa... | 5,340,907 |
def test_nldi(gage, loc, comid):
"""Test nldi functions used in processes.
Args:
gage (string): USGS Gage id string.
loc (list): List of lon and lat
comid (str): Expected comid returned from NLDI query.
"""
locarray = array(loc)
gageloc = NLDI().getfeature_byid("nwissite", g... | 5,340,908 |
def delete_image_when_image_changed(sender, instance, **kwargs) -> None:
"""
Delete image if it was switched.
:param sender: models.Model child class
:param instance: sender instance
:param kwargs: additional parameters
:return: None
"""
# Don't run on initial save
if not instance.p... | 5,340,909 |
def _get_log_level(log_level_name):
"""
Get numeric log level corresponding to specified log level name
"""
# TODO: Is there a built-in method to do a reverse lookup?
if log_level_name == LOG_LEVEL_NAME_CRITICAL:
return logging.CRITICAL
elif log_level_name == LOG_LEVEL_NAME_ERROR:
... | 5,340,910 |
def __initialize_storage__():
# type: () -> None
""" Initializes the dummy storage backend.
Compiles the dummy storage backend from the tests sources.
Sets the JAVA_API_JAR on the first call to this initialization.
:return: None
"""
global JAVA_API_JAR
global STORAGE_API
current_pat... | 5,340,911 |
def show_report(total_time, total_files):
"""prints out brief report
"""
hours = total_time // 3600
minutes = (total_time % 3600) // 60
seconds = total_time % 60
print("""
file processed: {0}
time taken: {1} hours {2} minutes {3} seconds
the results are in the folder 'ou... | 5,340,912 |
def is_iterator(obj):
"""
Predicate that returns whether an object is an iterator.
"""
import types
return type(obj) == types.GeneratorType or ('__iter__' in dir(obj) and 'next' in dir(obj)) | 5,340,913 |
def delete_entries(keytab_file: str, slots: t.List[int]) -> bool:
"""
Deletes one or more entries from a Kerberos keytab.
This function will only delete slots that exist within the keylist.
Once the slots are deleted, the current keylist will be written to
a temporary file. This avoids having... | 5,340,914 |
def detect(environ, context=None):
"""
parse HTTP user agent string and detect a mobile device.
"""
context = context or Context()
try:
## if key 'HTTP_USER_AGENT' doesn't exist,
## we are not able to decide agent class in the first place.
## so raise KeyError to return NonMo... | 5,340,915 |
def _sniff_scheme(uri_as_string):
"""Returns the scheme of the URL only, as a string."""
#
# urlsplit doesn't work on Windows -- it parses the drive as the scheme...
# no protocol given => assume a local file
#
if os.name == 'nt' and '://' not in uri_as_string:
uri_as_string = 'file://' ... | 5,340,916 |
def update_running_status(results):
"""
Signal that the queries for the home page statistics finished running.
"""
cache_id = HOME_STATS_LOCK_ID
cache_ttl = HOME_STATS_LOCK_TTL
if cache.get(cache_id):
cache.set(cache_id, False, cache_ttl) | 5,340,917 |
async def get_product(id: UUID4): # noqa: A002
"""Return ProductGinoModel instance."""
return await ProductGinoModel.get_or_404(id) | 5,340,918 |
def LSIIR_unc(H,UH,Nb,Na,f,Fs,tau=0):
"""Design of stabel IIR filter as fit to reciprocal of given frequency response with uncertainty
Least-squares fit of a digital IIR filter to the reciprocal of a given set
of frequency response values with given associated uncertainty. Propagation of uncertainties is
carried o... | 5,340,919 |
def genMeasureCircuit(H, Nq, commutativity_type, clique_cover_method=BronKerbosch):
"""
Take in a given Hamiltonian, H, and produce the minimum number of
necessary circuits to measure each term of H.
Returns:
List[QuantumCircuits]
"""
start_time = time.time()
term_reqs = np.full(... | 5,340,920 |
def run_test(session, m, data, batch_size, num_steps):
"""Runs the model on the given data."""
costs = 0.0
iters = 0
state = session.run(m.initial_state)
for step, (x, y) in enumerate(reader.dataset_iterator(data, batch_size, num_steps)):
cost, state = session.run([m.cost, m.fina... | 5,340,921 |
def chunks(l, n):
"""
Yield successive n-sized chunks from l.
Source: http://stackoverflow.com/a/312464/902751
"""
for i in range(0, len(l), n):
yield l[i:i + n] | 5,340,922 |
def table_to_dict(table):
"""Convert Astropy Table to Python dict.
Numpy arrays are converted to lists. This Can work with multi-dimensional
array columns, by representing them as list of list.
e.g. This is useful in the following situation.
foo = Table.read('foo.fits')
foo.to_pandas(... | 5,340,923 |
def margin_loss(y_true, y_pred):
"""
Margin loss for Eq.(4). When y_true[i, :] contains not just one `1`, this loss should work too. Not test it.
:param y_true: [None, n_classes]
:param y_pred: [None, num_capsule]
:return: a scalar loss value.
"""
L = y_true * K.square(K.maximum(0., 0.9 - y_... | 5,340,924 |
def strip_quotes(string):
"""Remove quotes from front and back of string
>>> strip_quotes('"fred"') == 'fred'
True
"""
if not string:
return string
first_ = string[0]
last = string[-1]
if first_ == last and first_ in '"\'':
return string[1:-1]
return string | 5,340,925 |
def clear_all_tables(retain=[]):
"""Like ``clear_all_models`` above, except **much** faster."""
for table in reversed(Base.metadata.sorted_tables):
if table.name not in retain:
Session.execute(table.delete())
Session.commit() | 5,340,926 |
def generate_local_dict(locale: str, init_english: bool = False):
"""Generate a dictionary with keys for each indicators and translatable attributes.
Parameters
----------
locale : str
Locale in the IETF format
init_english : bool
If True, fills the initial dictionary with the engli... | 5,340,927 |
def generate_scheme_from_file(filename=None, fileobj=None, filetype='bson', alimit=1000, verbose=0, encoding='utf8', delimiter=",", quotechar='"'):
"""Generates schema of the data BSON file"""
if not filetype and filename is not None:
filetype = __get_filetype_by_ext(filename)
datacache = []
if ... | 5,340,928 |
def getTests():
"""Returns a dictionary of document samples for the Entity Types Person, Location, and Organization.
Returns:
[type] -- Returns a dictionary of document samples for the Entity Types Person, Location, and Organization.
"""
personDocument = gtWorkingCopy.find_one({"$and": [{'enti... | 5,340,929 |
def ts_cor(a, b, min_sample = 3, axis = 0, data = None, state = None):
"""
ts_cor(a) is equivalent to a.cor()[0][1]
- supports numpy arrays
- handles nan
- supports state management
:Example: matching pandas
-------------------------
>>> # create sample data:
>>> from pyg_... | 5,340,930 |
def get_robin_bndry_conditions(kappa,alpha,Vh):
"""
Do not pass element=function_space.ufl_element()
as want forcing to be a scalar pass degree instead
"""
bndry_obj = get_2d_unit_square_mesh_boundaries()
boundary_conditions=[]
ii=0
for phys_var in [0,1]:
for normal in [1,-1]:
... | 5,340,931 |
def _AddComputeMetadata(client, server, metadata):
"""Updates the metadata with network compute metadata."""
compute_metadata = {
# test_instance_id, test_region and meta_os_info are informational and
# used in conjunction with saving results.
'test_instance_id': server.machine_type,
'test_r... | 5,340,932 |
def versions_banner():
"""The top-level method to draw banner for showing versions of T_System.
"""
import t_system.__init__
if not os.path.exists(t_system.dot_t_system_dir):
os.mkdir(t_system.dot_t_system_dir)
from t_system.logging import LogManager
t_system.log_manager = LogManager... | 5,340,933 |
def create_original_list_of_columns(dataframe):
""" Gets the original dataframe list
Args:
dataframe (df): Pandas dataframe
"""
new_columns = []
list_of_columns = '/home/connormcdowall/finance-honours/data/178-factors.txt'
file = open(list_of_columns, 'r')
lines = file.readlines()
... | 5,340,934 |
def get_prop_datatypes(labels, propnames, MB=None):
"""Retrieve the per-property output datatypes."""
rp = regionprops(labels, intensity_image=MB, cache=True)
datatypes = []
for propname in propnames:
if np.array(rp[0][propname]).dtype == 'int64':
datatypes.append('int32')
e... | 5,340,935 |
def parse_html(html: str) -> Tuple[str, str]:
"""
This function parses the html, strips the tags an return
the title and the body of the html file.
Parameters
----------
html : str
The HTML text
Returns
-------
Tuple[str, str]
A tuple of (title, body)
"""
#... | 5,340,936 |
def block(keyword, multi=False, noend=False):
"""Decorate block writing functions."""
def decorator(func):
from .._common import header
@wraps(func)
def wrapper(*args, **kwargs):
head_fmt = "{:5}{}" if noend else "{:5}{}\n"
out = [head_fmt.format(keyword, header... | 5,340,937 |
def show_choices(choices):
"""
Print the available choices for a specific selection by the user.
Paramters
---------
choices: dict or list
Dictionary or list containing the available choices. If a dictionary,
its keys will be used as bullet for the printed list.
"""
if isi... | 5,340,938 |
def data(path):
"""Get the file from the specified path from the data directory.
Parameters
----------
path : str
The relative path to the file in the data directory.
Returns
-------
file : File
The requested file.
"""
return send_from_directory(app.config['DATA_DI... | 5,340,939 |
def search_software_fuzzy(query, max=None, csv_filename=None):
"""Returns a list of dict for the software results.
"""
results = _search_software(query)
num = 0
softwares = []
while True:
for r in results:
r = _remove_useless_keys(r)
softwares.append(r)
n... | 5,340,940 |
def fitCirc(x,y,xerr = None, rIni = None, aveR=False):
"""
Performs a circle fit to data using least square residuals.
Parameters
----------
x : An array of length N.
y : An array of length N.
xerr : None or an array of length N,
If provided, it is the standard-deviation of poi... | 5,340,941 |
def get_clients():
"""
Return current clients
---
tags:
- clients
operationId: listClients
produces:
- application/json
schemes: ['http', 'https']
responses:
200:
description: List of clients
schema:
type: array
items:
$re... | 5,340,942 |
def GetInstanceListForHypervisor(hname, hvparams=None,
get_hv_fn=hypervisor.GetHypervisor):
"""Provides a list of instances of the given hypervisor.
@type hname: string
@param hname: name of the hypervisor
@type hvparams: dict of strings
@param hvparams: hypervisor parameters... | 5,340,943 |
def check_cutoff_properties(cutoffs):
"""Helper function to test common properties of cutoffs"""
assert isinstance(cutoffs, np.ndarray)
assert all([is_int(cutoff) for cutoff in cutoffs])
assert cutoffs.ndim == 1
assert len(cutoffs) > 0 | 5,340,944 |
def is_nersc_system(system = system()):
"""Whether current system is a supported NERSC system."""
return (system is not None) and (system in _system_params.keys()) | 5,340,945 |
def main():
"""get a list of all installed cameras"""
# create file strings from os environment variables
lbplog = os.environ['LBPLOG'] + "/synology/synology.log"
lbpdata = os.environ['LBPDATA'] + "/synology/cameras.dat"
# creating log file and set log format
logging.basicConfig(filename=lbplog... | 5,340,946 |
def is_string_type_suspicious_score(confidence_score, params):
"""
determine if string type confidence score is suspicious in reputation_params
"""
return not isinstance(confidence_score, int) and CONFIDENCE_LEVEL_PRIORITY.get(
params['override_confidence_level_suspicious'], 10) <= CONFIDENC... | 5,340,947 |
def align_embeddings(base_embed, other_embed, sample_size=1):
"""Fit the regression that aligns model1 and model2."""
regression = fit_w2v_regression(base_embed, other_embed, sample_size)
aligned_model = apply_w2v_regression(base_embed, regression)
return aligned_model | 5,340,948 |
def test_skip_fixture(executed_docstring_source):
"""
>>> import pytest
>>> @pytest.fixture
... def skip_fixture():
... pytest.skip()
>>> def test_skip_fixture_example(skip_fixture):
... pass
"""
assert_that(executed_docstring_source.allure_report,
has_test... | 5,340,949 |
def validate_dict_keys(dict_to_check: dict,
allowed_keys: set,
necessary_keys: Optional[set] = None,
dict_name: Optional[str] = None) -> bool:
"""If you use dictionaries to pass parameters, there are two common errors:
* misspelled keys
... | 5,340,950 |
def data_unmerged():
"""
Load HEWL diffraction data from APS 24-ID-C
"""
datapath = ["data", "data_unmerged.mtz"]
return load_dataset(datapath) | 5,340,951 |
def copy(object, *args):
"""Copy the object."""
copiedWrapper = wrapCopy( object )
try: copiedWrapper.name = copiedWrapper.name + "_Copy"
except AttributeError: pass
return copiedWrapper.createAndFillObject(None, *args) | 5,340,952 |
def convert_to_n0(n):
"""
Convert count vector to vector of "greater than" counts.
Parameters
-------
n : 1D array, size K
each entry k represents the count of items assigned to comp k.
Returns
-------
n0 : 1D array, size K
each entry k gives the total count of items at... | 5,340,953 |
def application(environ, start_response):
"""Serve the button HTML."""
with open('wsgi/button.html') as f:
response_body = f.read()
status = '200 OK'
response_headers = [
('Content-Type', 'text/html'),
('Content-Length', str(len(response_body))),
]
start_response(status, ... | 5,340,954 |
def main(args):
"""Handle the CLI command."""
# Track if anything was bad
anything_suspicious = False
anything_bad = False
dump_dirs_all = []
# Unpack into bools
mode_mac = args.mode in ["both", "mac"]
mode_iphone = args.mode in ["both", "iphone"]
method_attachments = args.method in... | 5,340,955 |
def get_handler():
"""
Return the handler configured by the most recent call to
:func:`configure`.
If :func:`configure` has not yet been called, this returns ``None``.
"""
return current_handler | 5,340,956 |
def display_rf_feature_importance(cache, save_location: str = None):
"""
Displays which pixels have the most influence in the model's decision.
This is based on sklearn,ensemble.RandomForestClassifier's feature_importance array
Parameters
----------
save_location : str
the location to s... | 5,340,957 |
def btc_command(update: Update, _: CallbackContext) -> None:
"""Send a message when the command /btc is issued."""
btc = cg.get_price(ids='bitcoin', vs_currencies='usd')
#btc = cg.get_coins_markets(vs_currency='usd')
update.message.reply_text(btc) | 5,340,958 |
def first_order(A, AB, B):
"""
First order estimator following Saltelli et al. 2010 CPC, normalized by
sample variance
"""
return np.mean(B * (AB - A), axis=0) / np.var(np.r_[A, B], axis=0) | 5,340,959 |
def test_cray_ims_base(cli_runner, rest_mock):
""" Test cray ims base command """
runner, cli, _ = cli_runner
result = runner.invoke(cli, ['ims'])
assert result.exit_code == 0
outputs = [
"deleted",
"public-keys",
"recipes",
"images",
"jobs"
]
compar... | 5,340,960 |
def test_invalid_env():
"""Verifies that an invalid environment variable will cause the CLI to exit
with a non-zero status code."""
helpers.log_status(cast(FrameType, currentframe()).f_code.co_name)
result = helpers.execute_command(
["-v", "--env", "COMPOSE_PROJECT_NAMEtest", "version"]
)
... | 5,340,961 |
def mod_df(arr,timevar,istart,istop,mod_name,ts):
"""
return time series (DataFrame) from model interpolated onto uniform time base
"""
t=timevar.points[istart:istop]
jd = timevar.units.num2date(t)
# eliminate any data that is closer together than 10 seconds
# this was required to handle is... | 5,340,962 |
def generate(schema_file: str,
output_dir: str,
prefix: str,
unmask: bool = False,
builtins: bool = False) -> None:
"""
Generate C code for the given schema into the target directory.
:param schema_file: The primary QAPI schema file.
:param output_dir... | 5,340,963 |
def hydrate_reserve_state(data={}):
"""
Given a dictionary, allow the viewmodel to hydrate the data needed by this view
"""
vm = State()
return vm.hydrate(data) | 5,340,964 |
def get_devstudio_versions ():
"""Get list of devstudio versions from the Windows registry. Return a
list of strings containing version numbers; the list will be
empty if we were unable to access the registry (eg. couldn't import
a registry-access module) or the appropriate registry keys weren... | 5,340,965 |
def doctest_ObjectWriter_get_state_Persistent():
"""ObjectWriter: get_state(): Persistent objects
>>> writer = serialize.ObjectWriter(dm)
>>> top = Top()
>>> pprint.pprint(writer.get_state(top))
{'_py_type': 'DBREF',
'database': 'pjpersist_test',
'id': '0001020304050607080a0b... | 5,340,966 |
def mapDictToProfile(wordD, tdm):
"""
Take the document in as a dictionary with word:wordcount format, and map
it to a p profile
Parameters
----------
wordD : Dictionary
Dictionary where the keys are words, and the values are the corrosponding word
count
tdm : termDo... | 5,340,967 |
def create_monthly_network_triplets_country_partition(conn, *, month, year, suffix='', num_physical_shards=None,
fillfactor=45):
"""
Function to DRY out creation of a new month/year partition for monthly_network_triplets_country.
Arguments:
conn... | 5,340,968 |
def test_compare_numpy_dictionaries():
""" Unit test for the compare_numpy_dictionaries function. """
dict1 = {1: np.zeros((2, 2)), 2: np.ones((2, 2))}
dict2 = {1: np.zeros((2, 2)), 2: np.ones((2, 2))}
dict3 = {1: np.ones((2, 2)), 2: np.zeros((2, 2))}
dict4 = {0: np.ones((2, 2)), 1: np.zeros((2, 2)... | 5,340,969 |
def _to_tikz(g: BaseGraph[VT,ET],
xoffset:FloatInt=0, yoffset:FloatInt=0, idoffset:int=0) -> Tuple[List[str],List[str]]:
"""Converts a ZX-graph ``g`` to a string representing a tikz diagram.
The optional arguments are used by :func:`to_tikz_sequence`.
"""
verts = []
maxindex = idoffset
for ... | 5,340,970 |
def _fix_server_adress(raw_server):
""" Prepend http:// there. """
if not raw_server.startswith("http://"):
raw_server = "http://" + raw_server
return raw_server | 5,340,971 |
def _get_all_subdirs(path):
"""Example: For path='prod/ext/test' it returns ['prod/ext/test', 'prod/ext', 'prod', '']"""
while True:
parent, base = os.path.split(path)
if base:
yield path
if not parent or path == parent:
break
path = parent
yield '' | 5,340,972 |
def _parse_output_keys(val):
"""Parse expected output keys from string, handling records.
"""
out = {}
for k in val.split(","):
# record output
if ":" in k:
name, attrs = k.split(":")
out[name] = attrs.split(";")
else:
out[k] = None
return ... | 5,340,973 |
def dfs_stats(path):
"""Print statistics about the file/directory at path"""
client = get_dfs_client()
client.start()
print(client.status(path, strict=True))
client.stop() | 5,340,974 |
def when_ready(server):
""" server hook that only runs when the gunicorn master process loads """
import os
import traceback
import rethinkdb as r
try:
server.log.info("rethinkdb initialising")
DB_HOST = os.environ.get("RETHINKDB_HOST")
DB_PORT = os.environ.get("RETHINKDB_... | 5,340,975 |
def check(sync_urls: list, cursor: sqlite3.Cursor, db: sqlite3.Connection, status: str):
"""Checking update in the back.
Args:
sync_urls: URL(s) to be checked as a list
cursor: Cursor object of sqlite3
db: Connection object of sqlite3
status: 'viewed' or 'unviewed'
Return:
... | 5,340,976 |
def _get_output_structure(
text: str,
model: PreTrainedModel,
tokenizer: PreTrainedTokenizer,
tokenizer_args: Dict,
) -> Tuple[OrderedDict, Type]:
"""Function needed for saving in a dictionary the output structure of the
transformers model.
"""
encoded_input = tokenizer([text], **tokeniz... | 5,340,977 |
def encode_board(board):
""" Encode the 2D board list to a 64-bit integer """
new_board = 0
for row in board.board:
for tile in row:
new_board <<= 4
if tile is not None:
new_board += tile.val
return new_board | 5,340,978 |
def main():
"""
Run serial communication.
"""
global ser # serial communication handler
global version
print 'Welcome to DigCam Terminal!'
# if can't open USB port, quit
if openSerialPort() == -1:
sys.exit()
# display instructions
helpMessage... | 5,340,979 |
def get_symbol(i):
"""Get the symbol corresponding to int ``i`` - runs through the usual 52
letters before resorting to unicode characters, starting at ``chr(192)``.
Examples
--------
>>> get_symbol(2)
'c'
>>> oe.get_symbol(200)
'Ŕ'
>>> oe.get_symbol(20000)
'京'
"""
if ... | 5,340,980 |
def longest_common_substring(string1, string2):
"""
Function to find the longest common substring of two strings
"""
m = [[0] * (1 + len(string2)) for i in range(1 + len(string1))]
longest, x_longest = 0, 0
for x in range(1, 1 + len(string1)):
for y in range(1, 1 + len(string2)):
... | 5,340,981 |
def check_output(output_fields):
"""
Sample helper function used to check the output fields
sent by SPARKL. It is referenced by the set of test data
below.
Each helper function takes as parameter a dictionary
that contains all output fields. E.g.:
{
'sample_out_field1' : 3,
... | 5,340,982 |
def elapsed_time_id(trace, event_index: int):
"""Calculate elapsed time by event index in trace
:param trace:
:param event_index:
:return:
"""
try:
event = trace[event_index]
except IndexError:
# catch for 0 padding.
# calculate using the last event in trace
... | 5,340,983 |
async def roots2(ctx, n1: float, n2: float):
"""Root an poly"""
author = ctx.message.author
num = [n1, n2]
answer = numpy.roots(num)
embed = discord.Embed(color=discord.Color.from_rgb(222, 137, 127))
embed.set_author(name=author.display_name, url="https://youtu.be/dQw4w9WgXcQ", icon_url=author.a... | 5,340,984 |
def save_pos(nestable=False):
"""Save the cursor position.
This function is a context manager for use in ``with`` statements.
It saves the cursor position when the context is entered and restores the
cursor to the saved position when the context is exited.
If ``nestable=False`` the ANSI control se... | 5,340,985 |
def test_find_microbit_posix_missing():
"""
Simulate being on os.name == 'posix' and a call to "mount" returns a
no records associated with a micro:bit device.
"""
with open('tests/mount_missing.txt', 'rb') as fixture_file:
fixture = fixture_file.read()
with mock.patch('os.name', 'po... | 5,340,986 |
def build_candidate_digest(proof, leaf_hash):
"""
Build the candidate digest representing the entire ledger from the Proof hashes.
:type proof: dict
:param proof: The Proof object.
:type leaf_hash: bytes
:param leaf_hash: The revision hash to pair with the first hash in the Proof hashes list.
... | 5,340,987 |
def register_configs(settings_cls: Optional[Type[Settings]] = None, settings_group: Optional[str] = None):
"""
Register configuration options in the main ConfigStore.instance().
The term `config` is used for a StructuredConfig at the root level (normally switchable with `-cn`
flag in Hydra, here we use... | 5,340,988 |
def test_about(client):
"""Tests the about route."""
assert client.get('/about').status_code == 200 | 5,340,989 |
def confusion_matrix_eval(cnn, data_loader):
"""Retrieves false positives and false negatives for further investigation
Parameters
----------
cnn : torchvision.models
A trained pytorch model.
data_loader : torch.utils.data.DataLoader
A dataloader iterating through the holdout test s... | 5,340,990 |
def test_export_convert_to_jpeg_quality():
"""test --convert-to-jpeg --jpeg-quality"""
import glob
import os
import os.path
import pathlib
from osxphotos.cli import export
runner = CliRunner()
cwd = os.getcwd()
# pylint: disable=not-context-manager
with runner.isolated_filesyst... | 5,340,991 |
def match_by_hashed_faceting(*keys):
"""Match method 3 - Hashed Faceted Search"""
matches = []
hfs = []
for i in range(len(__lookup_attrs__)):
key = [x for x in keys if x[0] == __lookup_attrs__[i]]
if key:
hfs.append(key[0])
hashed_val = hashlib.sha256(str(hfs).encode('utf-8')).hexdigest()
has... | 5,340,992 |
def get_derivative_density_matrix(mat_diag,mat_Rabi,sigma_moins_array,**kwargs):
"""
Returns function for t-evolution using the numerical integration of the density matrix
\dot{\rho}=-i(H_eff \rho-\rho H_eff^{\dagger})
+\Gamma \sum_j \sigma_j^_ \rho \sigma_j^+
"""
dim=len(mat_diag)
tunneling... | 5,340,993 |
def create_alien(setting, screen, aliens, alien_number, row_number):
"""
"""
alien = Alien(setting, screen)
alien_width = alien.rect.width
alien.x = alien_width + 2 * alien_width * alien_number
alien.rect.x = alien.x
alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
a... | 5,340,994 |
def start_http_server():
"""Starts a simple http server for the test files"""
# For the http handler
os.chdir(TEST_FILES_DIR)
handler = SimpleHTTPServer.SimpleHTTPRequestHandler
handler.extensions_map['.html'] = 'text/html; charset=UTF-8'
httpd = ThreadedTCPServer(("localhost", 0), handler)
... | 5,340,995 |
def area_of_polygon(polygon):
"""
Returns the area of an OpenQuake polygon in square kilometres
"""
lon0 = np.mean(polygon.lons)
lat0 = np.mean(polygon.lats)
# Transform to lamber equal area projection
x, y = lonlat_to_laea(polygon.lons, polygon.lats, lon0, lat0)
# Build shapely polygons... | 5,340,996 |
def build_dataset_values(claim_object, data_value):
""" Build results with different datasets.
Parameters:
claim_object (obj): Onject to modify and add to rows .
data_value (obj): result object
Returns:
Modified claim_boject according to data_value.type
"""
... | 5,340,997 |
def get_yolk_dir():
"""Return location we store config files and data."""
return os.path.abspath('%s/.yolk' % os.path.expanduser('~')) | 5,340,998 |
def mapfile_fsc3d(
input_filename1, input_filename2, output_filename=None, kernel=9, resolution=None
):
"""
Compute the local FSC of the map
Args:
input_filename1 (str): The input map filename
input_filename2 (str): The input map filename
output_filename (str): The output map fi... | 5,340,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.