content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def is_gate_this_standard_unitary(gate_unitary, standard_gate_name): """ Whether a unitary is, up to a phase, the standard gate specified by the name `standard_gate_name`. The correspondence between the standard names and unitaries is w.r.t the internally-used gatenames (see internal_gate_unitaries())....
2fa182c31172e498103491e2da0029bb0bcbbd6f
55,500
def topodic_supported_languages(): """ Show supported languages. This will show the user which languages are currently supported. And this path operation will: * return a dictionary of supported languages along with their ISO2 language codes """ return settings.LANGUAGE_DICT
dcdc366f2e795e64897f65350b7d8bb9eca483b0
55,501
def find_values(result): """ extract values from resultset returns <dict>[instance] = <tuple>values """ values = {} for metric_series in result.value: instance = metric_series.id.instance values[instance] = metric_series.value return values
50e2206eb46ff3594658ff7f87461dc778dedd3e
55,502
def process_results(results): """ Gets user choice that needs to be played :param results: stores the results which we got from get_items :return: user choice """ if len(results) >= 1: temp_data = {} count = 1 print("Here are the top {} results for your query, which one w...
23d3087ddf39ab6fa94072fabaa2bcde68add2a9
55,503
def get_fun_inter_sequence_diagram(fun_inter_str, **kwargs): """ Check and get all "show sequence Fun_inter" strings, find Fun_inter obj and then get/filter needed lists for plantuml_adapter. Args: fun_inter_str: functional interface name/alias from input cell **kwargs: whole lists ...
aa1e1eec5c63e1115530407fc1544d06807dc7db
55,504
def sia_thickness_via_optim(slope, width, flux, shape='rectangular', glen_a=None, fs=None, t_lambda=None): """Compute the thickness numerically instead of analytically. It's the only way that works for trapezoid shapes. Parameters ---------- slope : -np.gradient(hgt, dx...
4ed34ecac2a1ffcfaa287a268a88eccb396365e8
55,505
def generate_alpha(scores, length): """ Generates a scoring vector with given length from a list of scores. """ assert isinstance(scores, list) len_scores = len(scores) if len_scores > length: return np.array(scores)[:length] return np.pad(scores, (0, length-len_scores), 'constant', constan...
1d31ccc730468fff434640d91ff38467f616372d
55,506
import os def sort_file(filename): """sort file data by the time""" data = [] with open(filename, 'r') as file_object: line = file_object.readline() while line: line_data = [name.strip() for name in line.split(' ')] row = { 'lat': line_data[0], ...
d93a3fb79d54c8120965236bbd9ebb36dcd817cb
55,507
def speech_to_text(file): """ Applies SpeechRecognition to the audio files """ recognizer = sr.Recognizer() a = '' with sr.AudioFile(file) as source: #recognizer.adjust_for_ambient_noise(source) # adjust for noisy audio audio = recognizer.record(source) try: ...
d26597e88d84b7b1b0e886dbec251ef8b8c4a0a5
55,508
def create_socket(app): """Create a socketio object""" # We don't want to monkey patch the naive python functions # which destuct some of the PyPPL functionalities # We might be swtiching to gevent or eventlet if PyPPL is # switching to greenlet. namespace = RootNamespace('/') socketio = Soc...
8c6a1872dd43a4a4e83720b2ca1a56c104c93cc9
55,509
import numpy def svdown(omega, wvno, d, a, b, rho): """ Find the values of the Haskell vectors for Rayleigh-wave. Values are calculated at each layer boundaries from top layer downward. """ mmax = len(d) aa0 = numpy.zeros(4, dtype=numpy.float64) vv = numpy.zeros((mmax, 4), dtype=numpy.f...
11cd910813324b9f5f2de3147f53d598975849f4
55,510
def load_train_valid_test_data(DisNet_dataDict_save_path): """ load train valid test data from npy file :param DisNet_dataDict_save_path: npy file which contains training data :return: """ data_dict = np.load(DisNet_dataDict_save_path).item() X_train_distance = data_dict["X_train_distance"] ...
6024ee6629eb938738e8b7b571c01621646818c5
55,511
import re def pem_as_string(cert): """ Only return False if the certificate is a file path. Otherwise it is a file object or raw string and will need to be fed to the file open context. """ if hasattr(cert, 'read'): # File object - return as is return cert cert = cert.encode('utf-8...
c4ada5957115fce9a31775d33e1787482fab8c9f
55,512
def bit_perm_2_mat(a): """transforms a permutation into a bit matrix. Representation of permutations and bit matrices see comment on module. """ if isinteger(a): return a return [1 << x for x in a]
d58ba0ebc38690ad23b7972b634f29674419faaa
55,513
def box_refinement(box, gt_box): """Compute refinement needed to transform box to gt_box. box and gt_box are [N, (center_x, center_y, center_z, l, w, h)] """ box = tf.cast(box, tf.float32) gt_box = tf.cast(gt_box, tf.float32) dz = (gt_box[:,2] - box[:,2]) / (box[:,5]+1e-8) dy = (gt_box[:,1]...
146b261033cba10df109eeb5956aa637c566932f
55,514
def initializer(name, storage_socket, meta, molecule): """Initializes a service from a API call Parameters ---------- name : str Description storage_socket : StorageSocket A StorageSocket to the currently active database meta : dict A JSON blob with the required keys for...
a3c6a49f70062f66ebce08807bea376ab3f69dc6
55,515
def preprocess_image(x, mode='caffe'): """ Preprocess an image by subtracting the ImageNet mean. Args x: np.array of shape (None, None, 3) or (3, None, None). mode: One of "caffe" or "tf". - caffe: will zero-center each color channel with respect to the ImageNet data...
4b17cd2db37aa037d1e773823ee796899d7be2f2
55,516
def slice_score_path(filepath, exp_str): """ Highest-level selection function; creates a selection from a MusicXML filepath and EMA expression string. :param filepath: A filepath to a MusicXML score. :type filepath: str :param exp_str: A string describing an EMA selection. :type exp_str: str :r...
ec3705434ba529c671e968a127d8e0a140eb21ef
55,517
def format_secret(secret): """ Format secret to compatible decrypt string Args: secret (string): KMS secret hash Returns: formatted ef resolvable KMS decrypt string Raises: None """ return "{{aws:kms:decrypt,%s}}" % secret
274a0686db07621d657ebc29eda21ec18c1d0afa
55,518
import types def arrangeDictbySecondaryKey(data, labels, sep='__'): """Re-arrange a dict of dicts by each records secondary keys""" newdata = {} if not type(data) is types.DictType: return data key1 = data.keys()[0] if type(data[key1]) is types.DictType: fields = data[key1].keys()...
47381c90ccb624015ad0bb936b01e0eec33aa19a
55,519
def mmr_load_params(param_config): """ Loads parameters for the MMR algorithm from YAML configuration Parameters ---------- param_config: dict YAML config dict containing parameters for the MMR algorithm Returns ------- params: dict a dictionary of loaded parameters for...
ce726a5ae22ef53b393ec36915072a6405770df6
55,520
from io import StringIO import sys def wait3D(matrix, sysname, job): """Display a waiting page while we calculate a 3D plot""" sys.stdout = outbuffer = StringIO() writeHeader(outbuffer, "Young 3D for " + removeHTMLTags(sysname)) print(""" <div class="content"> <img src="/loading.gif" alt="[l...
ef06c2e052c6736480d958aa726ac99b63955cd9
55,521
from typing import Sequence def compute_success( ground_truth: pd.DataFrame, prediction: pd.DataFrame, iou_thresholds: Sequence[float] = np.linspace(0.5, 0.95, 10), mode: str = "take_max_stiou", ) -> np.ndarray: """Compute success %, i.e., the % of cases where there is sufficient overlap betwe...
ee5fb6956faff7f223fd1494996e912221a9cfbc
55,522
from datetime import datetime def get_patched_is_natively_supported(mpl): """Returns a patched version of `matplotlib.units._is_natively_supported`""" mpl_native = mpl.units._is_natively_supported def is_natively_supported(x, *args, **kwargs): # returns false if x is a timedelta # cal...
5b03616ffc0a65af83f359ba11f696c93127ee20
55,523
def get_projected_coords(c, ref_c): """ Parameters ---------- c : `astropy.coordinates.SkyCoord` The coordinates that you want to project. ref_c : `astropy.coordinates.SkyCoord` The reference coordinates, e.g., could be of the progenitor like in the case of Pal 5. Return...
45caebd1b04d8bcd8fe9245b0be4a31ec28fa148
55,524
def detect_pbl_gradient_method( data, min_pbl=200, max_pbl=2000, sigma_smoothing=3, pbl_to_cloudbase_min=100, take_log_of_rcs=False, ): """TODO scipy.ndimage.gaussian_filter rcs is indexed by rcs[time, range] """ t = data["time"] r = data["range"] rcs = data["rcs_91...
2501cc1aa01088f25a2d78ef4c8df7104508d6f9
55,525
def to_jraph(neighbor: NeighborList, mask: Array = None) -> jraph.GraphsTuple: """Convert a sparse neighbor list to a `jraph.GraphsTuple`. As in jraph, padding here is accomplished by adding a ficticious graph with a single node. Args: neighbor: A neighbor list that we will convert to the jraph format. Mu...
cf9c3016684d02ac7a69c4e454a2698868627f10
55,526
async def search(request: Request, args: SearchJSON): """Handles search query""" args = args.dict() if not is_valid_payload(args): return Response(content="Invalid data", status_code=400) offers = await parse_offers(**args, parsers=config.PARSERS, semaphore=app.semaphore) return app.templat...
b9773d4891d2fcea6dbcb8a74176ee55c139b7e7
55,527
def standardize_colorfulness(img, c=DEFAULT_COLOR_STD_C, h=0): """Give image constant colorfulness and hue Image is converted to cylindrical CAM-16UCS assigned a constant hue and colorfulness, and then coverted back to RGB. Parameters ---------- img : ndarray Image to be processed ...
ce49cf179454454b2e79705a72453c45bb7a2d78
55,528
def randomTerminals(PCSFInputObj, seed, excludeT): """ Selects nodes with a similar degree distribution to the original terminals, and assigns the prizes to them. INPUT: a PCSFInput object seed - number to give to the random number generator RETURNS: a new PCSFInput object with a new lis...
c1050dbf8b5a110c1b557442aec05bb6c25b6c63
55,529
from typing import Tuple from typing import List def opr_test( cases, func, mode=("eager", "static", "dynamic_shape"), compare_fn=_default_compare_fn, ref_fn=None, **kwargs ): """ mode: the list of test mode which are eager, static and dynamic_shape will test all the cases if...
fb305714f48db0e22f0c46f673982e5c00531253
55,530
import torch def le(a, b, square=False, **kwargs): """ Encodes the loss function for "a <= b". If square is false d = |a - b| is used, else d = (a - b)^2. """ if square: return torch.clamp((a - b).sign() * (a - b) * (a - b), min=0) else: return torch.clamp(a - b, min=0)
02c8a2f5255255f754be6335a7ed8c55a1910192
55,531
def split_list(l, sizes): """ Split a list into several chunks, each chunk with a size in `sizes`. """ chunks = [] offset = 0 for size in sizes: chunks.append(l[offset:offset + size]) offset += size return chunks
cac573660717e9b1782810ef948f510c07f530c1
55,532
def randomize_box(bit_array, targets, epsilon): """ The object detection unary encoding method. """ assert isinstance(bit_array, tensor) img = symmetric_tensor_encoding(bit_array, 1) label = symmetric_tensor_encoding(bit_array, epsilon) targets_new = targets.clone() targets_new = targets...
dbef8e3b08a0a5fd684a4c7eaeff9e39142fb72c
55,533
from typing import Dict from typing import Any import os import logging def get_key_value(d: Dict, key, default=None) -> Any: """Return value for the key either from the dict or environmental variable or default. Raises error if value is not found and there is no default.""" if key not in d: if k...
57b9a859c8934b16dca5529ec53248f1b44fcec5
55,534
import sys def batch_end(segments, bstart, batch_max): """ Determine the batch end that will keep the batch length under the given max. """ bi = bstart blength = 0 while bi < len(segments) and blength < batch_max: chrom, seg_start, seg_end = segments[bi] blength += seg_end - seg_start ...
437729d43c3d569861feb25e0366f84d99f1a943
55,535
def make_tensor_list_set_item_tests(options): """Make a set of tests to do TensorListSetItem.""" test_parameters = [ { "element_dtype": [tf.float32, tf.int32], "num_elements": [4, 5, 6], "element_shape": [[], [5], [3, 3]], "index": [0, 1, 2, 3], }, ] def bui...
ffac8496c96434da912a00514053983cd2dbb0e5
55,536
import random def get_fixed_samples(a_list, num=20000): """ 固定数量的样本 """ if num <= 0: return a_list a_n = len(a_list) n_piece = num // a_n + 1 x_list = a_list * n_piece random.seed(47) random.shuffle(x_list) x_list = x_list[:num] return x_list
fe7c22329001ea0cde155a6077c28aeaffeb0a65
55,537
def SI_prefix_and_scale_factor(val, unit=None): """ Takes in a value and unit and if applicable returns the proper scale factor and SI prefix. If the unit is None, no scaling is done. If the unit is "SI_PREFIX_ONLY", the value is scaled and an SI prefix is applied without a base unit. Para...
045e844be712f03b5fe65826cc103f34da8de072
55,538
def amp_ppm(moms): """ Amplitude for k^+(k) -> pi^+(p1) + pi^+(p2) + pi^-(p3) Parameters ---------- moms : ndarray[dim=2] moms[0] = pi moms[1] = pi moms[2] = pi """ p1 = moms[0] p2 = moms[1] p3 = moms[2] k = p1 + p2 + p3 s0 = (1.0 / 3.0) * (mk ** 2 ...
dd4a89a3916e5ef418501d8c97fb3bd463071458
55,539
def template_json(data): """Returns json as a str Normally json is rendered as bytes, but putting bytes in a template that is itself encoded to bytes causes problems when trying to re-read the json from the template (with javascript). :arg data: the data to jsonify. :returns: str """ ...
098f0de06ad6bdffe1ab3bef92bd7e9f79ff7c48
55,540
def csrf(): """Provide a csrf token for the registration form. https://medium.com/@iaincollins/csrf-tokens-via-ajax-a885c7305d4a """ form = RegistrationForm() return flask.jsonify({"token": form.csrf_token.current_token})
1a13b013a29f152c775f4020ca801d9ec3ca2381
55,541
from . import dlgconnect from typing import Optional def show_connection_dialog(app: "QtWidgets.QApplication") -> Optional["ProjectConfig"]: """Show the connection dialog, and configure the project accordingly.""" connection_window = dlgconnect.DlgConnect() connection_window.load() connection_window....
940784ee98f6d9452253ccb4e975186d0df7fb0b
55,542
import torch def get_junction_loss_and_weight(model_cfg, global_w_policy): """ Get the junction loss function and weight. """ junction_loss_cfg = model_cfg.get("junction_loss_cfg", {}) # Get the junction loss weight w_policy = junction_loss_cfg.get("policy", global_w_policy) if w_policy == "s...
f528f43f4ec5cb540a30bbee6e304c53b3e11b64
55,543
def scatter_geo( data_frame=None, lat=None, lon=None, locations=None, locationmode=None, geojson=None, featureidkey=None, color=None, text=None, symbol=None, facet_row=None, facet_col=None, facet_col_wrap=0, facet_row_spacing=None, facet_col_spacing=None, ...
481b6c326ace1411fe6465ea714eda42b5c5e40d
55,544
import io def bytes_image_output(f): """ Decorator which marks that function returns images stored as bytes objects. :param f: function to decorate :return: decorated function """ @wraps(f) def inner(*args, **kwargs): im = f(*args, **kwargs) buffer = io.BytesIO() ...
03b82f74ea00d66c4485c0605ce5bf9c3da1b473
55,545
def remove_item(commons: dict = Depends(common_parameters)): """ Endpoint. Removes an item from cart. :param Depends(common_parameters) commons: args from `common_parameters` function :return: dict with cart and message :rtype: dict """ logger.info(f'Request@/remove_item/{commons["cart_id"]...
ae5453f86d157d11b429a3f68fc08cb794ef4b31
55,546
def intersect(*selects, **kwargs): """Return an ``INTERSECT`` of multiple selectables. The returned object is an instance of :class:`.CompoundSelect`. \*selects a list of :class:`.Select` instances. \**kwargs available keyword arguments are the same as those of :func:`select`. ...
f394fa6f0ba621858bacc7c7bb3cfbc89e9e32bc
55,547
import numpy def CalculateSimpleTopoIndex(mol): """ ################################################################# Calculation of the logarithm of the simple topological index by Narumi, which is defined as the product of the vertex degree. ---->Sito Usage: ...
9d8ebb84d491fd91cd1d9e2ebd2198dd731de0f2
55,548
import os import json def save_data(outputfilepath,summary): """ This will save a simba3d result Summary is the result of the experiment """ ext=os.path.splitext(outputfilepath)[-1].lower() if ext=='.mat': savemat(outputfilepath,summary,long_field_names=True) return outputfile...
9979aec81f3758f9df42f2902b17db5c04aef6e8
55,549
def num2date(num): """num2date wrapper""" return mpl.dates.num2date(num).replace(tzinfo=None)
a8b5ed7d89a67a28b053e955658240164bc46eac
55,550
def replace_question_mark_with_nan(data_table: pd.DataFrame) -> pd.DataFrame: """ Replace question mark with NaN :return: None """ return data_table.replace(Values.RAW_DATA_NULL.value, np.nan)
bd4723f03de8e770fee671273e62520bf3b4d4aa
55,551
import itertools def infer_impact_of_variables_2by2(tabnum, protocols): """Builds the first table of my report""" for n, p in enumerate(protocols): print( "\nTable %d: Variable combinations, 2x2 for Protocol `%s`:" % (n + tabnum, p) ) print(60 * "-") ...
0d6fff2d8ad52a01a9a1767d9aee152154b2e0d7
55,552
from typing import Dict def create_security_context_xsuaa(token, service_credentials: Dict[str, str]): """ Creates the XSUAA Security Context by validating the received access token. :param token: string containing the access_token :param service_credentials: dict containing the uaa/ias credentials ...
0e1ce70f7ce32844107b420516e3d0c18d316a92
55,553
def read_distributed_data(db, cursor, mode='promiscuous', normalize=None, load_history=False, exclude_keys=None, format='dask', npartitions=None, spark_context=None, data_tag=None): """ This function should be used to read an entire dataset that is to be handled by subsequent paral...
bdfdce3a86bf2eb195f824da426b32ca422343a3
55,554
import random from functools import reduce def diceroll (dice, sides): """ Simulate rolling d dice of s sides each From Python Cookbook1st Edn pg 531 See the Python Cookbook entry on this function for the non-standard use of 'reduce' for example diceroll(5, 6) would be 5 rolls of a 6 sided...
ad51a53a9df1df2c64e7ad7f361365ff8df219c6
55,555
import math def get_installation_path(): """ Returns 3ds Max installation folder NOTE: This function is added here to avoid some errors related with 3ds Max PATH env var setup This functionality is available in dcclib for each specific DCC :return: str """ version_id = MaxPlus.Application...
d86a3aa38c5e96e1174a33300654aa829238cdcd
55,556
import sympy def collect(expr,lst): """ Wrapper for sympy.collect. """ lst = MV.scalar_to_symbol(lst) return(sympy.collect(expr,lst))
00097d0eab616fb302d15fdafd8afb62486aab01
55,557
def decrement(name, num_shards, delta=-1, do_transaction=True, use_memcache=True ): """ Decrement the value for a given sharded counter. This will create the counter if it does not exist. Args: name: The name of the counter. num_shards: the number of shards in the counter """ retu...
1b4d88a6409cf11209d965ba7fe7fc2f917cb7eb
55,558
import functools import types def memoize_method(func): """ A decorator to remember the result of the method call """ @functools.wraps(func) def wrapped(self, *args, **kwargs): name = '_memoize_{}'.format(func.__name__) try: return getattr(self, name) except Att...
f3a43d03e9b34c7a623452868ff2d33fed299dd9
55,559
def get_random_data(data, n=10, seed=1): """ :param data: np.ndarray :param n: int :param seed: int :return: np.ndarray """ np.random.seed(seed) ind = np.random.choice(data.shape[0], n) return data[ind]
7b9951d2bae537062d1ef7ada7622ece13b6a9e9
55,560
import sqlite3 def get_groups_per_sweep(sweep, include, query, db_path): """pulls out all the data in a sweep and structures it as a dict. String of integers (`peaks`) is transformed into a list of ints or empty list.""" con = db.persistent_connection_to_db(db_path) con.row_factory = sqlite3.Row d...
b936534df39183c05418b1c4afc4b146f9d75e94
55,561
import time def searchForCamptown(rhyming_dict, attempts=MAX_ATTEMPTS, backoff=BACKOFF): """Loop MAX_ATTEMPT times, searching for a Camptown meter wikipedia title. Args: Integer: attempts, retries remaining. Integer: backoff, seconds to wait between each loop. Returns: String or F...
5c8e85c4712f1b18be31f248f9b4706612e9d65e
55,562
def example_boxplot(): """Generate an example box plot.""" non_symmetric = _non_symmetric_data() # find the quartiles and iqr q1_y, median_y, q3_y = non_symmetric.quantile([0.25, 0.5, 0.75]) iqr = q3_y - q1_y # make the boxplot ax = non_symmetric.plot(kind='box', figsize=(6, 6), title='Box...
63d558439323464234122478fcdb9ebf0845bf6b
55,563
def dfs(graph, start): """Depth first search Args: graph (dict): graph start (node): some key of the graph """ seen = set() path = [] stack = [start] while stack: current = stack.pop() if current not in seen: seen.add(current) path.appe...
ca4a8260e3e27d73852c27b3d07b0cf248b25be8
55,564
def get_reverse(rna_sequence): """Reverse orientation of `sequence`. Returns a string with `sequence` in the reverse order. If `sequence` is empty, an empty string is returned. """ sequence = rna_sequence.upper() rev_seq = sequence[::-1] if len(sequence) == 0: return "" else: ...
497ad7c4d16fddb6f7d9f657f0a63632e1d8ebdb
55,565
def beautify_latex(expr): """convert string to latex-compatible expression""" return substr_replace(expr, [ ('**', '^'), ('plus', '+'), ('minus', '-'), ('comma', ','), ('LEFT', '\\left ('), ('RIGHT', '\\right )'), ('integral', '\\int'), ('rvert', '...
876364a2b41d147fe6d98954359b7a8fe71e2eaf
55,566
def a(P, T): """Isobaric cubic expansion coefficient [1 / K]""" pi = P / Ps tau = Ts / T return ((1 + pi * gammaR_pi(pi, tau) - tau * pi* gammaR_pitau(pi, tau)) / (1 + pi * gammaR_pi(pi, tau))) / T
faa27a987a474aeadd03212c4f29e0e603cdbe25
55,567
def added_fields(): """Return list of col. names that should be added to csv """ return [cn for rgcn,cn in COLUMNS_MAPPING]
af16b8d18d60c9e190b3ced6eaf48bb50d456a8e
55,568
def one_hot(length, index): """Return an nd array of given `length` filled with 0s and a 1 at `index`.""" result = np.zeros(length) result[index] = 1 return result
07f23d4e17df78e3e607326e15f9fefbd1bcd168
55,569
def optimize_lsq( mesh_conductor, bfield_specification, reg=1e3, objective="minimum_inductive_energy" ): """ Optimization of coil stream function according to a specified objective using least-squares. Parameters ---------- mesh_conductor: MeshConductor object Contains Trimesh mesh as w...
531eaf8d569e4460089142706487941b1c8e4d37
55,570
import json def getHesitationAndTypingTimeFromResponseChanges(json_data): """ get hesitation and typing time from response changes(i.e list of time stamps) """ if json_data != None: changes = json.loads(json_data) else: changes = [] if len(changes) >= 2: hesitation_tim...
0f6df94fee9c1bff602dfbdf7000628d9edc2dde
55,571
import functools def translate_server_exception(method): """Transforms the exception for the instance. Note: keeps its traceback intact. """ @functools.wraps(method) def wrapper(self, ctx, instance_id, *args, **kwargs): try: res = method(self, ctx, instance_id, *args, **kwarg...
45fdcdec2d3be7ef2ee21f0017c8e8f3e09a1b28
55,572
from pathlib import Path import io from unittest.mock import patch async def test_upload_view(hass, hass_client, temp_dir, hass_admin_user): """Allow uploading media.""" img = (Path(__file__).parent.parent / "image/logo.png").read_bytes() def get_file(name): pic = io.BytesIO(img) pic.nam...
6bdc05a17a44c4ae016ae8c8fc40bfceb2072c7f
55,573
import argparse import getpass def get_args(): """ Get arguments from CLI """ parser = argparse.ArgumentParser( description='Arguments for VM relocation') parser.add_argument('-s', '--host', required=True, action='store', hel...
82e536c056eaa558a1df1ea61d4f36a8a29384de
55,574
def calculate_COM(offsets): """ Determine the centre of mass (COM) in a collection of offsets. The COM is a basis to span the vectors in ``offsets``. Also return the distance of each element E in ``offsets`` from the COM (i.e., the coefficients that when multiplied by the COM give exactly E). ...
b789c45ff6ba84ef170df881b0936879fd9d3781
55,575
import os def test_plot_fleur_single_orbcontrol_wc_matplotlib(import_with_migrate): """ Test of visualization of single Orbcontrol workchain with matplotlib """ file_path = '../workflows/caches/fleur_orbcontrol_structure.tar.gz' thisfilefolder = os.path.dirname(os.path.abspath(__file__)) EXPO...
bf12dadb4afc99a885a9fe988f9508e658bdda06
55,576
def datapoints_to_datalist(datapoints, avoid=[], verbose=True): """Removes the outer layer of the datapoints dictionary, i.e. sample. The second organizational level (i.e., molecule) becomes the outermost level. Lists and arrays are appended. In other words, it just lumps all samples together. """ ...
3a5f4d4caa434b91e76f2d15a1b79b9686f9ee92
55,577
def fastq( draw, size=0, min_score: int = 0, max_score: int = 62, offset: int = 64, add_comment: bool = True, additional_description: bool = True, ) -> str: """Generate strings representing sequences in FASTQ format. Arguments: - `size`: Size of the sequence and quality string. ...
4de1e651192b1e17b3809135bbc51e1e8f7477ff
55,578
import torch def mixup(data, targets, alpha): """ original mixup. """ indices = torch.randperm(data.size(0)) shuffled_data = data[indices] shuffled_targets = targets[indices] lam = np.random.beta(alpha, alpha) data = data * lam + shuffled_data * (1 - lam) results = { 'tar...
69153f3fc5d0565a96ded7671bbe737600504a86
55,579
def euclidean_dist_ttr(c1, c2): """ Computes Euclidean distance between two cities """ x1, y1 = vertex_coordinates[c1] x2, y2 = vertex_coordinates[c2] return ((x1 - x2)**2 + (y1 - y2)**2)**0.5
0fac4c1a822aa1a065087ca791839874704eb9ea
55,580
def scatter_data(file): """ return the data for the scatter plot for both debits and credits. It would be a visual method to see the values of debits and credits. One can find out what is the highest dollar entry or around what value it lies. """ df = pd.DataFrame( file.groupby(["Date", ...
c2729de0898df497573bfc56dc80e7da964d9ae2
55,581
import configparser import re def load_file( file, ndim, scan_ratio=None, scan_seed=None, dev=None, verbose=True): """This function loads a STEM acquisition based on a configuration .conf file path. The number of dimensions ndim should also be given. The Path is generated from a scan file gi...
14e82240041290c36296889df6fea406dd764352
55,582
def viterbi(state_matrix,pointers): """Get viterbi path from state_matrix and pointers output of make_dynamic Args: state_matrix : :class:`~numpy:numpy.array` matrix where each column gives the prob of max prob path to that state, where each row is IBD 0,1,2 pointers : :class:`~numpy...
e38f3569838167520d10fbdf527bd2fa89275f9d
55,583
def get_task_related_entities(request): """TODO: Add Docstring please """ logger.debug('get_task_related_entity is running') task_id = request.matchdict.get('id') task = Task.query.get(task_id) entity_type = request.matchdict.get('e_type') dep_type = request.matchdict.get('d_type') logg...
1978bccfa9d513286d30b0a7a465b1d16e6e8351
55,584
def add_global_mean_vars(xr_ds_: xr.Dataset, variable_list, prefix='glmean_', weighting_var='area_p', averaging_dims=('ncol') ) -> xr.Dataset: """ For each variable in the input list, we add an accompanying variable that represents a global ...
345c9453914fbaa396214445f0e49274c99d2655
55,585
def find_center_of_rotation(projection, background_internsity=0.9, method="center_of_gravity"): """ Find the axis of rotation of the object in the projection Parameters ---------- projection : ndarray The projection, normalized between 0 and 1 background_internsity : flo...
b21ee3f308fff8f1b21056b68989433de953336b
55,586
def _is_valid_rng(rng: Array): """Checks whether rng is a valid JAX PRNGKey, also handling custom prngs.""" # New-style JAX KeyArrays have a base type. if jax_config.jax_enable_custom_prng: if not isinstance(rng, jax.random.KeyArray): return False # Old-style JAX PRNGKeys are plain uint32 arrays. el...
7bb77578d9aa74528b2d5f25b1d0bbe6ea57f1da
55,587
import re import itertools def extract_and_update_methylation_index_from_single_end_read(read, AlignmentFile, methylation_m_tuples, m, all_combinations, methylation_type, methylation_pattern, ignore_read_1_pos, min_qual, phred_offset, ob_strand_offset): """Extracts m-tuples of methylation loci from a single-end r...
34d103fd24dfcd72c058d847f59adf8b9c3addc8
55,588
def mask_above_key(ccd_in, bmp_meta=None, key=None, margin=0.1, **kwargs): """CorMultiPipe post-processing routine to mask pixels > input key """ if key is None: raise ValueError('key must be specified') masklevel = ccd_in.meta.get(key.lower()) if masklevel is None: return ccd cc...
49df5541f605b532bfa6364709c593609ce36ad5
55,589
def list_services(): """ GET /system/services :param request_inputs: :return: """ request_inputs = anchore_engine.services.common.do_request_prep(request, default_params={}) user_auth = request_inputs['auth'] params = request_inputs['params'] return_object = [] httpcode = 500 ...
1d9f5160fc926c6920daa7038573835d32786578
55,590
def users_list(): """ JSON {"key":str} username, password, text - строки :return: {'users':list} """ key = request.json['key'] username = get_by_value(key, key_stor) if not username: return { 'ok': False, 'message': 'Сначала пройдите регистрацию или автори...
d02618306828322212bf224435cc76e3a822d4f8
55,591
def findRoot(value, x_low, x_high, function): """Use the bisection method to find root such that function(root) == value.""" guess = (x_high + x_low) / 2.0 v = function(guess) difference = v - value i = 0 while abs(difference) > ACCURACY and i < MAX_ITERATIONS: i += 1 if differe...
2113077eb5439a014b4fa2406a7d0ebfb7c5a795
55,592
def iss(): """ Return the token issuer (``USER_API``). """ return USER_API
c601488aa87d0b72415de2c95c6483d91c9c2c01
55,593
def scan_buildings(): """ Creates a list of lists of buildings in current village and returns it. Each tile element is a string. Must be on building view. Returns ------- [[buildingSlot, a#, g#, aid#, roman, buildingLVL]] All strings in list. g# is building ID. """ result = [] ...
f39ca8a8cfb5aeeee0f00de644a620be22b28029
55,594
def password_success(request): """ redirect to the registraion successful page """ return render(request, 'registration/password_success.html', {})
54b34f9a71ce13fc5f0d61db1b7a4db79f41b2dd
55,595
def officer_confirm_view(request, pk): """Officer views and confirms a challenge request after clicking email link. Only the officer who gave the challenge can review it.""" challenge = OffChallenge.objects.get(id=pk) if request.user.id != challenge.officer.id: raise PermissionDenied # not the ...
d6276f03507d0aa9b597aead5eab47e814a08109
55,596
def process_stn_activation(df, side): """ Calculates STN activation percentage :param df: dictionary containing STN volume and active STN volume for patients :param side: side of the brain 'L' or 'R' :return: STN activation percentage for each side for all patients """ #print(list(df)) ...
6ed2a21e547a0ed9f35a77fed02e6f4fbf59cb6a
55,597
import string def GetTestWrapper(func_name): """Return a C preprocessor token to test in order to wrap code. This handles extensions. Example: GetTestWrapper("glActiveTextureARB") = "CR_multitexture" Example: GetTestWrapper("glBegin") = "" """ cat = apiutil.Category(func_name) if (cat == "1.0" or cat == "1.1...
4e7f0f6dc9c656229fd92aa2673a71606d20a556
55,598
import logging def plot(f): """ Plot function decorator. Calls the function, does several generic tasks, and saves the figure as the function name. """ def wrapper(*args, **kwargs): logging.info('generating plot: %s', f.__name__) f(*args, **kwargs) fig = plt.gcf() ...
0e98ad95a7578490558f2c104ac732b7b11beb71
55,599