content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_top_experts_per_item_dispatcher(gates: Array, name: str,
num_selected_experts: int,
batch_priority: bool,
capacity: Optional[int] = None,
capacity_facto... | 20,600 |
def main(argv=None):
"""Run a Tensorflow model on the Iris dataset."""
args = parse_arguments(sys.argv if argv is None else argv)
env = json.loads(os.environ.get('TF_CONFIG', '{}'))
# First find out if there's a task value on the environment variable.
# If there is none or it is empty define a default one.
... | 20,601 |
def nix_prefetch_url(url, algo='sha256'):
"""Prefetches the content of the given URL."""
print(f'nix-prefetch-url {url}')
out = subprocess.check_output(['nix-prefetch-url', '--type', algo, url])
return out.decode('utf-8').rstrip() | 20,602 |
def find_files_list(*args, **kwargs):
""" Returns a list of find_files generator"""
return list(find_files(*args, **kwargs)) | 20,603 |
def bool_from_string(subject, strict=False, default=False):
"""Interpret a subject as a boolean.
A subject can be a boolean, a string or an integer. Boolean type value
will be returned directly, otherwise the subject will be converted to
a string. A case-insensitive match is performed such that strings... | 20,604 |
def create_db():
"""Create the database using sqlalchemy."""
database_url = str(database.url).replace("mysql://", "mysql+pymysql://")
engine = sqlalchemy.create_engine(database_url)
sqlalchemy_metadata.create_all(engine) | 20,605 |
def scan_quality_check(label: str,
pivots: list,
energies: list,
scan_res: float = rotor_scan_resolution,
used_methods: Optional[list] = None,
log_file: Optional[str] = None,
species... | 20,606 |
def delete(group_name: str) -> None:
"""Delete a task group"""
delete_group(group_name) | 20,607 |
def highlight(elements, effect_time=None, color=None, border=None, create_dump=False):
"""Highlights (blinks) a Selenium WebDriver element"""
if effect_time is None:
effect_time = DEFAULT_EFFECT_TIME
if color is None:
color = DEFAULT_EFFECT_COLOR
if border is None:
border = DEF... | 20,608 |
def save_log(epoch, dataset_name, results_train, results_val):
"""
:param epoch:
:param dataset_name:
:param results_train: (per-step log in dataframe, epoch time) from training data
:param results_val: (per-step log in dataframe, epoch time) from validation data
"""
summ_cols = ["loss", "tr... | 20,609 |
def cachecontrol_logging_hook(app):
"""
Reroute cachecontrol logger to use cement log handlers.
"""
from cachecontrol.controller import logger
formatter = logging.Formatter(LOG_FORMAT)
for handler in app.log.backend.handlers:
handler.setFormatter(formatter)
logger.addHandler(han... | 20,610 |
def get_msg_timeout(options):
"""Reads the configured sbd message timeout from each device.
Key arguments:
options -- options dictionary
Return Value:
msg_timeout (integer, seconds)
"""
# get the defined msg_timeout
msg_timeout = -1 # default sbd msg timeout
cmd = generate_sbd_co... | 20,611 |
def odata_getone(url, headers):
"""
Get a single object from Odata
"""
r = requests.get(url, headers=headers)
if not r.ok:
logging.warning(f"Fetch url {url} hit {r.status_code}")
return None
rjson = r.json()
if 'error' in rjson:
logging.warning(f"Fetching of {url} ret... | 20,612 |
def test_create_pause_action(
decoy: Decoy,
session_view: SessionView,
engine_store: EngineStore,
unique_id: str,
current_time: datetime,
client: TestClient,
) -> None:
"""It should handle a pause action."""
session_created_at = datetime.now()
actions = SessionAction(
action... | 20,613 |
def _tokenizer_from_json(json_string):
"""Parses a JSON tokenizer configuration file and returns a
tokenizer instance.
# Arguments
json_string: JSON string encoding a tokenizer configuration.
# Returns
A Keras Tokenizer instance
"""
tokenizer_config = json.loads(json_string)
... | 20,614 |
def test_get_timerange(dataset_container):
"""Test that timerange returns a list with the correct timestamps."""
dataset_container.append(datetime(2018, 1, 1, 12, 0, 0), 1)
dataset_container.append(datetime(2018, 1, 1, 12, 1, 0), 2)
dataset_container.append(datetime(2018, 1, 1, 12, 2, 0), 3)
timeran... | 20,615 |
def get_all_pip_requirements_files() -> List[Path]:
"""
If the root level hi-ml directory is available (e.g. it has been installed as a submodule or
downloaded directly into a parent repo) then we must add it's pip requirements to any environment
definition. This function returns a list of the necessary... | 20,616 |
def load_data(dataset_name: str, split: str) -> object:
"""
Load the data from datasets library and convert to dataframe
Parameters
----------
dataset_name : str
name of the dataset to be downloaded.
split : str
type of split (train or test).
Returns
-------
... | 20,617 |
def horizontal_south_link_neighbor(shape, horizontal_ids, bad_index_value=-1):
"""ID of south horizontal link neighbor.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
horizontal_ids : array of int
Array of all horizontal link ids *must be of len(horizontal_links)... | 20,618 |
def main():
""" Copy necessary arduino files to their appropriate locations. """
args = get_args()
# Select option based on argparse results
if args.all is not False:
# Copy `lib` to all directories.
directories = os.listdir(".")
exclude_dirs = [".git", "lib"]
for direct... | 20,619 |
def _get_output(algorithm, iport=0, iconnection=0, oport=0, active_scalar=None,
active_scalar_field='point'):
"""A helper to get the algorithm's output and copy input's vtki meta info"""
ido = algorithm.GetInputDataObject(iport, iconnection)
data = wrap(algorithm.GetOutputDataObject(oport))
... | 20,620 |
def test_annotated_top_images_dataset_init_annotation_count(
top_images_root, top_images_annotations_csv_file,
top_image_annotations, annotation_count):
"""Test AnnotatedTopImagesDataset.__init__, setting annotation_count."""
# Remove all L0 annotations.
banned = conftest.layer(0)
rows =... | 20,621 |
def read_cesar_out(cesar_line):
"""Return ref and query sequence."""
cesar_content = cesar_line.split("\n")
# del cesar_content[0]
fractions = parts(cesar_content, 4)
cesar_fractions = []
for fraction in fractions:
if len(fraction) == 1:
continue
ref_seq = fraction[1]... | 20,622 |
def aa_i2c_slave_write_stats (aardvark):
"""usage: int return = aa_i2c_slave_write_stats(Aardvark aardvark)"""
if not AA_LIBRARY_LOADED: return AA_INCOMPATIBLE_LIBRARY
# Call API function
return api.py_aa_i2c_slave_write_stats(aardvark) | 20,623 |
def detect_os():
"""
Detects the Operating System and sets a global variable to target OS
specific features to the right platform.
Options for g_platform_os are: win, lin, mac
"""
global g_platform_os
os = platform.system()
if os == "Windows":
g_platform_os = "windows"
elif o... | 20,624 |
def get_aliases_user(request):
"""
Returns all the Aliases
API_ENDPOINT:api/v1/aliases
----------
payload
{
"email":"a@a.com"
}
"""
alias_array = []
payload = {}
print("came to get_aliases_user()")
data_received = json.loads(request.body)
email = data_received["em... | 20,625 |
def _sorted_attributes(features, attrs, attribute):
"""
When the list of attributes is a dictionary, use the
sort key parameter to order the feature attributes.
evaluate it as a function and return it. If it's not
in the right format, attrs isn't a dict then returns
None.
"""
sort_key =... | 20,626 |
def get_gpus(num_gpu=1, worker_index=-1, format=AS_STRING):
"""Get list of free GPUs according to nvidia-smi.
This will retry for ``MAX_RETRIES`` times until the requested number of GPUs are available.
Args:
:num_gpu: number of GPUs desired.
:worker_index: index "hint" for allocation of available GPUs.
... | 20,627 |
def ldensity_laplace_uniform_dist(prob_laplace, location, scale, low, high,
val):
"""
A mixture of a Laplace and a uniform distribution
"""
return np.log((prob_laplace * np.exp(-np.abs(val - location) / scale) / (2 * scale))
+ ((1 - prob_laplace) / (hi... | 20,628 |
def readConfirmInput():
"""asks user for confirmation
Returns:
bool: True if user confirms, False if doesn't
"""
try:
result = readUserInput("(y/n): ") # UnrecognisedSelectionException
return 'y' in result[0].lower() # IndexError
except (UnrecognisedSelectionExcept... | 20,629 |
def add_iSWAP_like_twoQ_clifford(index, gate_seq_1, gate_seq_2, **kwargs):
"""Add iSWAP like two Qubit Clifford.
(24*24*3*3 = 5184)
(gate_seq_1: gate seq. of qubit #1, gate_seq_t: gate seq. of qubit #2)
"""
generator = kwargs.get('generator', 'CZ')
# randomly sample from single qubit cliffords... | 20,630 |
def linkElectron(inLep, inLepIdx, lepCollection, genPartCollection):
"""process input Electron, find lineage within gen particles
pass "find" as inLepIdx of particle to trigger finding within the method"""
linkChain = []
lepIdx = -1
if inLepIdx == "find":
for Idx, lep in enumerate(lepCollec... | 20,631 |
def status():
"""Determines whether or not if CrowdStrike Falcon is loaded.
:return: A Boolean on whether or not crowdstrike is loaded.
:rtype: bool
.. code-block:: bash
salt '*' crowdstrike.status
"""
if not __salt__['crowdstrike.system_extension']():
# if we should be using... | 20,632 |
def sparse_search(arr, s):
""" 10.5 Sparse Search: Given a sorted array of strings that is interspersed
with empty strings, write a method to find the location of a given string.
EXAMPLE:
Input: find "ball" in {"at", "", "", "" , "ball", "", "", "car", "" , "" , "dad", ""}
Output: 4
"""
def ... | 20,633 |
def iterDirXML(dirname):
"""Given a directory, iterate over the content of the .txt files in that directory as Trees"""
for filename in os.listdir(dirname):
fullpath = os.path.join(dirname, filename)
if os.path.isfile(fullpath):
_, ext = os.path.splitext(fullpath)
if ext ... | 20,634 |
def uuid_pk():
"""
Generate uuid1 and cut it to 12.
UUID default size is 32 chars.
"""
return uuid.uuid1().hex[:12] | 20,635 |
def infected_symptomatic_00x80():
"""
Real Name: b'Infected symptomatic 00x80'
Original Eqn: b'Infected symptomatic 00+Infected symptomatic 80'
Units: b'person'
Limits: (None, None)
Type: component
b''
"""
return infected_symptomatic_00() + infected_symptomatic_80() | 20,636 |
def main():
"""Make a jazz noise here"""
args = get_args()
#print(args.positional)
with open('process_one_set.sh', 'r') as f:
line_list = f.readlines()
for line in line_list:
if 'HPC_PATH=' in line:
replacing = line.split('=')[-1]
replace... | 20,637 |
def test_finetune_full():
""" finetuning using 'full'.
"""
DATASET_PATH = ROOT_PATH+'/data/SS-Youtube/raw.pickle'
nb_classes = 2
# Keras and pyTorch implementation of the Adam optimizer are slightly different and change a bit the results
# We reduce the min accuracy needed here to pass the test
... | 20,638 |
def stencilCompare(firstElem, secondElem):
"""
stencilCompare(const std::pair< int, FP_PRECISION > &firstElem, const std::pair< int,
FP_PRECISION > &secondElem) -> bool
Comparitor for sorting k-nearest stencil std::pair objects
"""
return _openmoc.stencilCompare(firstElem, secondElem) | 20,639 |
def bisect_profiles_wrapper(decider, good, bad, perform_check=True):
"""Wrapper for recursive profile bisection."""
# Validate good and bad profiles are such, otherwise bisection reports noise
# Note that while decider is a random mock, these assertions may fail.
if perform_check:
if decider.run(good, save... | 20,640 |
def add_article_to_db(
table: str, article_title: str, article_url: str, article_date: str
) -> None:
""" Add a new article title and date to the database
Args:
table (str): current table
article_title (str): The title of an article
article_url (str): The url of an article
ar... | 20,641 |
def rolling_median_with_nan_forward_fill(vector: typing.List[float], window_length: int) -> typing.List[float]:
"""Computes a rolling median of a vector of floats and returns the results. NaNs will be forward filled."""
forward_fill(vector)
return rolling_median_no_nan(vector, window_length) | 20,642 |
def build_class_docstring(class_to_doc: ClassToDocument, formatter: Formatter) -> str:
"""A function to build the docstring of a class
Parameters
----------
class_to_doc : ClassToDocument
The class to document
formatter : Formatter
The formatter to use
Returns
-------
docstring : str
The docstring for... | 20,643 |
def test_thread_safety():
""" test context keeps separate correlation ID per thread """
class _SampleThread(threading.Thread):
def __init__(self):
super(_SampleThread, self).__init__()
self.correlation_id = str(uuid.uuid1())
self.read_correlation_id = ''
def ... | 20,644 |
def Subprocess(
identifier: Optional[str] = None, variables: Optional[Dict] = None,
env: Optional[Dict] = None, volume: Optional[str] = None
) -> Dict:
"""Get base configuration for a subprocess worker with the given optional
arguments.
Parameters
----------
identifier: string, default=None... | 20,645 |
def maybe_start_instance(instance):
"""Starts instance if it's stopped, no-op otherwise."""
if not instance:
return
if instance.state['Name'] == 'stopped':
instance.start()
while True:
print(f"Waiting for {instance} to start.")
instance.reload()
if instance.state['Name'] == 'runni... | 20,646 |
def ensure_folder_exist(foldername):
"""Create folder (with whole path) if it doesn't exist yet."""
if not os.access(foldername, os.R_OK|os.W_OK|os.X_OK):
os.makedirs(foldername) | 20,647 |
async def print_roles(ctx):
""" Imprimir no chat as regras atribuidas ao usuário """
await ctx.send('Resource still under development, being released for use in the near future')
return
print(">> Comando de listagem de regras executado _print_roles_")
if ctx.author.nick == None:
await ctx.se... | 20,648 |
def get_var(name):
"""
Returns the value of a settings variable.
The full name is CONTROLLED_VOCABULARY_ + name.
First look into django settings.
If not found there, use the value defined in this file.
"""
full_name = "CONTROLLED_VOCABULARY_" + name
ret = globals().get(full_name, None)
... | 20,649 |
def test_do_post_no_data_returns_400():
"""Make a POST request to /cow with no data and expect status code 400."""
response = req.post('http://127.0.0.1:5000/cow')
assert response.status_code == 400 | 20,650 |
def get_schema_from_dataset_url_carbon(dataset_url,
key=None,
secret=None,
endpoint=None,
proxy=None,
proxy_port=None,
... | 20,651 |
def test_Drop_Disk_At_NoDisk(score, max_score):
"""Function drop_disk_at: No disk."""
max_score.value += 20
try:
set_up()
the_board = Board.init_board(
dimension=6, given_disks=
( (wrapped_disk_value_1,),
(cracked_disk_value_2,cracked_disk_value_2_B),
... | 20,652 |
def parse_args():
"""
standard command line parsing
"""
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--label', required=True)
parser.add_argument('--h5file' )
parser.add_argument('--neg', action='store_true', default=False)
parser.add_argument('... | 20,653 |
def get_all_metrics(model, epoch, val_x, val_y, start_time, loss_fn):
"""每个epoch结束后在发展集上预测,得到一些指标
:param model: tf.keras.Model, epoch训练后的模型
:param epoch: int, 轮数
:param val_x: tf.data.Dataset, 发展集的输入, 和val_y一样的sample_size
:param val_y: tf.data.Dataset, 发展集的标签
:param start_time: time.time, 开始时间
... | 20,654 |
def configure_ssl_off(units, model_name=None, max_wait=60):
"""Turn RabbitMQ charm SSL config option off.
Turn ssl charm config option off, confirm that it is disabled
on every unit.
:param units: list of units
:param max_wait: maximum time to wait in seconds to confirm
:returns: None if succes... | 20,655 |
def get_labels(decode_steps: DecodeSteps) -> LabelsDict:
"""Returns labels dict given DecodeSteps."""
return {
"target_action_types": decode_steps.action_types,
"target_action_ids": decode_steps.action_ids,
} | 20,656 |
def test_abstract_methods():
"""Abstract methods must be implemented."""
ERROR_MSG_REGEX = "^Can't instantiate abstract class .* with abstract method"
# create artifact file for model init
with tempfile.NamedTemporaryFile(delete=False) as tempf:
pickle.dump("foo", tempf)
try:
for m... | 20,657 |
def get_body_barycentric_posvel(body, time, ephemeris=None):
"""Calculate the barycentric position and velocity of a solar system body.
Parameters
----------
body : str or other
The solar system body for which to calculate positions. Can also be a
kernel specifier (list of 2-tuples) if... | 20,658 |
async def test_unschedule_all_schedulers(
startup_and_shutdown_uvicorn, host, port, tmp_path
):
""" unschedule a scheduler. """
client = ClientAsync(host=host, port=port)
await reset_dispatcher(client, str(tmp_path))
action1 = file_x.FileAppend(
relative_to_output_dir=False,
file=st... | 20,659 |
def set_sequences(fastq_file, sequence_dict, as_rna=False):
"""
Set sequences in a `FastqFile` instance from a dictionary.
Parameters
----------
fastq_file : FastqFile
The `FastqFile` to be accessed.
sequence_dict : dict
A dictionary containing the sequences and scores to be... | 20,660 |
def recurDraw(num, data):
"""
Purpose: to draw polygons
Parameters: num - indicator of what layer the program is on, data - instance
of the Data class
Returns: data - instance of the data class
Calls: recurDraw - itself, Data - data processing class, toDraw - drawing
intermediary func... | 20,661 |
def cont4():
"""
Two clusters, namely <cont1> (5 contours) and <cont3> 4 contours).
The enclosing contours of the clusters have a different value.
Contains 3 minima.
"""
cont_min = [
cncc(5, (6.00, 3.00), 0.2, (1, 1)),
cncc(2, (7.00, 4.00), 0.1, (4, 1), rmin=0.15),
cncc(2... | 20,662 |
def predict(test_data, qrnn, add_noise = False):
"""
predict the posterior mean and median
"""
if add_noise:
x_noise = test_data.add_noise(test_data.x, test_data.index)
x = (x_noise - test_data.mean)/test_data.std
y_prior = x_noise
y = test_data.y_noise
y... | 20,663 |
def handle_login_GET():
"""
Displays the index (the login page).
"""
if request.args.get('next'):
url_kwargs = dict(next=request.args.get('next'))
else:
url_kwargs = {}
try:
weblab_api.api.check_user_session()
except SessionNotFoundError:
pass # Expected beha... | 20,664 |
def get_role_actions():
"""Returns the possible role to actions items in the application.
Returns:
dict(str, list(str)). A dict presenting key as role and values as list
of actions corresponding to the given role.
"""
return copy.deepcopy(_ROLE_ACTIONS) | 20,665 |
def jsons_str_tuple_to_jsons_tuple(ctx, param, value):
"""
Converts json str into python map
"""
if value is None:
return []
else:
return [json.loads(a) for a in value] | 20,666 |
def get_webelements_in_active_area(xpath, **kwargs):
"""Find element under another element.
If ${ACTIVE_AREA_FUNC} returns an element then the xpath is searched from
that element. Otherwise the element is searched under body element.
Parameters
----------
xpath : str
Xpath expression w... | 20,667 |
def test_lemmatizer_reflects_lookups_changes():
"""Test for an issue that'd cause lookups available in a model loaded from
disk to not be reflected in the lemmatizer."""
nlp = Language()
assert Doc(nlp.vocab, words=["foo"])[0].lemma_ == "foo"
table = nlp.vocab.lookups.add_table("lemma_lookup")
t... | 20,668 |
def create_double_group():
"""
Returns: Create two simple control for all object under selected
"""
selections = cm.ls(selection=True)
if len(selections) < 1:
return om.MGlobal.displayError("This function need at lest two object to work with")
for selection in selections:
if... | 20,669 |
def voucher_and_partial_matches_with_coupons(voucher_and_partial_matches):
"""
Returns a voucher with partial matching CourseRuns and valid coupons
"""
context = voucher_and_partial_matches
products = [
ProductFactory(content_object=course_run)
for course_run in context.partial_match... | 20,670 |
def one_transit(t=np.linspace(0,27,19440),
per=1., rp=0.1, t0=1., a=15., inc=87., ecc=0.,
w=90., limb_dark ='nonlinear', u=[0.5,0.1,0.1,-0.1]):
"""
~Simulates a one-sector long TESS light curve with injected planet transits per input parameters.~
Requires: batman; numpy
... | 20,671 |
async def master_loop_error(error):
"""Handler of exceptions in master game loop"""
try:
raise error
except Exception:
await botutils.send_lobby(error_str)
await botutils.log(botutils.Level.error, traceback.format_exc())
finally:
master_game_loop.cancel() | 20,672 |
def scrape_md_file(md_path):
"""
Yield the Python scripts and URLs in the md_file in path.
Parameters
----------
md_path : str
path to md file to scrape
Returns
-------
python_examples : List[str]
The list of Python scripts included in the provided file.
urls :... | 20,673 |
def activate(request: Request) -> dict:
"""View to activate user after clicking email link.
:param request: Pyramid request.
:return: Context to be used by the renderer.
"""
code = request.matchdict.get('code', None)
registration_service = get_registration_service(request)
return registrati... | 20,674 |
def showMovie(frames, movSz, fps=20, transpose=False):
"""Show a movie using OpenCV.
Takes a numpy matrix (with images as columns) and shows the images in
a video at a specified frame rate.
Parameters
----------
frames : numpy array, shape = (N, D)
Input data with N images as ... | 20,675 |
def build_feed(posts):
"""Generate Atom feed file"""
feed = Atom1Feed(
title="~tym smol pomes", description="", link=f"{SITEURL}/", language="en"
)
for post in posts:
slug = post["metadata"]["slug"]
stamp = post["metadata"]["stamp"]
content = post["content"]
feed.... | 20,676 |
def _create_eval_metrics_fn(
dataset_name, is_regression_task
):
"""Creates a function that computes task-relevant metrics.
Args:
dataset_name: TFDS name of dataset.
is_regression_task: If true, includes Spearman's rank correlation
coefficient computation in metric function; otherwise, defaults t... | 20,677 |
def brighter(rgb):
"""
Make the color (rgb-tuple) a tad brighter.
"""
_rgb = tuple([ int(np.sqrt(a/255) * 255) for a in rgb ])
return _rgb | 20,678 |
def open_browser_with_timeout(driver, browser):
"""
Opens Chromium, sets a timeout for the script to finish and takes a screenshot
:param driver: Browser driver
:param browser: Browser
:return: None
"""
try:
if browser.case == "expired" or browser.case == "wrong-host" or browser.case... | 20,679 |
def delete_workspace_config(namespace, workspace, cnamespace, config):
"""Delete method configuration in workspace.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
mnamespace (str): Method namespace
method (str): Method name
Swagger... | 20,680 |
def test_filled_transparent_graphs_2():
""" Two functions with transparend grid over them """
coordinate_system = cartesius.CoordinateSystem()
coordinate_system.add(
charts.Function(
math.sin,
start = -4,
end = 5,
s... | 20,681 |
def get_shader_code(name):
""" Returns the shader as a string """
fname = op.join( op.dirname(__file__), name )
if op.exists( fname ):
with open(fname) as f:
return f.read() | 20,682 |
def compute_translation_error(pred_pose, gt_pose, reduction="mean"):
"""
Computes the error (meters) in translation components of pose prediction.
Inputs:
pred_pose - (bs, 3) --- (x, y, theta)
gt_pose - (bs, 3) --- (x, y, theta)
Note: x, y must be in meters.
"""
error = torch.... | 20,683 |
def get_base_snippet_action_menu_items(model):
"""
Retrieve the global list of menu items for the snippet action menu,
which may then be customised on a per-request basis
"""
menu_items = [
SaveMenuItem(order=0),
DeleteMenuItem(order=10),
]
for hook in hooks.get_hooks('regis... | 20,684 |
def assign_file(package, source):
"""Initializes package output class.
Parameters
----------
package : :obj:`str`
Name of the package that generated the trajectory file.
source : :obj:`str`
Path to the trajectory file.
Returns
-------
The class corresponding to the ... | 20,685 |
def _magpie_register_services_with_db_session(services_dict, db_session, push_to_phoenix=False,
force_update=False, update_getcapabilities_permissions=False):
# type: (ServicesSettings, Session, bool, bool, bool) -> bool
"""
Registration procedure of :term:`Serv... | 20,686 |
def journal(client):
"""
Fetch journal entries which reference a member.
"""
client.require_auth()
with (yield from nwdb.connection()) as conn:
cursor = yield from conn.cursor()
yield from cursor.execute("""
select A.tx_id, A.wallet_id, A.debit, A.credit, B.currency_id, C.nar... | 20,687 |
def test_get_version(check):
"""
Test _get_version() to make sure the check is properly parsing Postgres versions
"""
db = MagicMock()
# Test #.#.# style versions
db.cursor().fetchone.return_value = ['9.5.3']
assert check._get_version('regular_version', db) == [9, 5, 3]
# Test #.# styl... | 20,688 |
def test_coerce__to_bool(value, expected):
"""Ensure we are properly coercing to boolean."""
assert configure.coerce_to_expected(value, "foo", bool) is expected | 20,689 |
def computer_config_show(computer, user, current, as_option_string):
"""Show the current or default configuration for COMPUTER."""
import tabulate
from aiida.common.utils import escape_for_bash
config = {}
table = []
transport_cls = computer.get_transport_class()
option_list = [
pa... | 20,690 |
def triplet_to_rrggbb(rgbtuple):
"""Converts a (red, green, blue) tuple to #rrggbb."""
hexname = _tripdict.get(rgbtuple)
if hexname is None:
hexname = '#%02x%02x%02x' % rgbtuple
_tripdict[rgbtuple] = hexname
return hexname | 20,691 |
def stab_cholesky(M):
""" A numerically stable version of the Cholesky decomposition.
Used in the GLE implementation. Since many of the matrices used in this
algorithm have very large and very small numbers in at once, to handle a
wide range of frequencies, a naive algorithm can end up having to calculate
... | 20,692 |
def prodNeventsTrend(request):
"""
The view presents historical trend of nevents in different states for various processing types
Default time window - 1 week
"""
valid, response= initRequest(request)
defaultdays = 7
equery = {}
if 'days' in request.session['requestParams'] and request.... | 20,693 |
def create_storage_policy_zios(session, cloud_name, zios_id, policy_name, drive_type, drive_quantity,
policy_type_id, description=None, return_type=None, **kwargs):
"""
Creates a new policy to ZIOS.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.... | 20,694 |
def format_tooltips(G, **kwargs):
""" Annotate G, format tooltips.
"""
# node data = [(n, {...}), ...]
node_data = {}
if isinstance(G, nx.Graph):
node_data = G.nodes(True)
elif 'nodes' in G:
node_data = [(d["id"], d) for d in G['nodes']]
# unique ids
member_uids = np.sor... | 20,695 |
def copy_files(extension, source, target=None):
"""Copy matching files from source to target.
Scan the ``source`` folder and copy any file that end with
the given ``extension`` to the ``target`` folder.
Both ``source`` and ``target`` are expected to be either a ``str`` or a
list or tuple of string... | 20,696 |
def add_centroid_frags(fragList, atmList):
"""Add centroid to each fragment."""
for frag in fragList:
atoms = [atmList[i] for i in frag['ids']]
frag['cx'], frag['cy'], frag['cz'] = centroid_atmList(atoms)
return fragList | 20,697 |
def load_mat(path: str, mat: str, fid: str, size: Optional[int] = None, overwrite: Optional[bool] = False, loop: Optional[int] = 0) -> np.ndarray:
"""Get the raw data for one individual file.
If the file does not exist in the specified path then tries to download it
from Google Drive.
"""
filepath... | 20,698 |
def assert_stats_are_equal(state1: Any, state2: Any):
"""Asserts that the activation statistics in two Flax states are almost equal."""
for layer_name, state1_stats, state2_stats in _iterate_stats(state1, state2):
# The tolerance was chosen empirically to make the tests pass reliably for a
# 3-layer model.... | 20,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.