content
stringlengths
22
815k
id
int64
0
4.91M
def loglikehood_coefficient(n_items, X, Y): """ Considering the rows of X (and Y=X) as vectors, compute the distance matrix between each pair of vectors. Parameters ---------- n_items: int Number of items in the model. X: array of shape (n_samples_1, n_features) Y: array of sh...
5,334,300
def get_archive_by_path(db, vault_name, path, retrieve_subpath_archs=False): """ Will attempt to find the most recent version of an archive representing a given path. If retrieve_subpath_archs is True, then will also retrieve latest versions of archives representing subdirs of the path. :param path:...
5,334,301
def superpixel_colors( num_pix:int = 1536, schema:str = 'rgb', interleave:int = 1, stroke:str = '', ) -> list: """ Generate color (attribute) list for superpixel SVG paths Parameters ---------- num_pix : int Number of super pixels to account for (default = 1536) sche...
5,334,302
def build_module_op_list(m: tq.QuantumModule, x=None) -> List: """ serialize all operations in the module and generate a list with [{'name': RX, 'has_params': True, 'trainable': True, 'wires': [0], n_wires: 1, 'params': [array([[0.01]])]}] so that an identity module can be reconstructed The modu...
5,334,303
def test_support_different_io_size(cache_mode): """ title: OpenCAS supports different IO sizes description: OpenCAS supports IO of size in rage from 512b to 128K pass_criteria: - No IO errors """ with TestRun.step("Prepare devices"): cache_disk = TestRun.disks["cache"] core...
5,334,304
def _get_args(): """ Parses the command line arguments and returns them. """ parser = argparse.ArgumentParser(description=__doc__) # Argument for the mode of execution (human or random): parser.add_argument( "--mode", "-m", type=str, default="human", choices=["human", 'r...
5,334,305
def test_no_lstrip_blocks(gen_paths: typing.Any, run_nnvg: typing.Callable) -> None: """ Ensure that lstrip_blocks if false if --lstrip-blocks is not supplied. """ testtype_path = get_path_to_TestType_0_2(gen_paths) nnvg_args0 = ['--templates', str(gen_paths.templates_dir), '-O', str(...
5,334,306
def file_to_dict(filename, data): """Converts JSON file to dict :param filename: filename :param data: string :return: dict object """ try: try: json_data = to_json(data) return json.loads(json_data) except Exception as _: return json.loads(da...
5,334,307
def reorganizeArray(id_A, id_B, gids_tuple, unordered_coordinates ): """ From a tuple of genome ID's representing a coordinate array's structure (gidI, gidJ). and the corresponding coordinate np-array (n x 4) of design [[locI1, locJ1, fidI1, fidJ2, Kn, Ks], ...
5,334,308
def get_table_entries(table, ports): """Fills the dict with the ports that aren't unassigned """ for row in table.find_all('tr')[2:]: items = row.find_all('td') if items[3].text.encode('utf-8') != b'Unassigned': ports[items[0].text.encode('utf-8')] =\ minify(items[3].text).encode('utf-8')
5,334,309
def test_extract_x_all(): """Test all know variants.""" allitems = ( "RFC1234", ("RFC 2345", "RFC2345"), "IEEE 802.1x", ("801.2x", "IEEE 801.2x"), "ITU-T G.1111.1", "3GPP Release 11", "GR-1111-CORE", "ITU-T I.111", "gnmi.proto version 0.0.1...
5,334,310
def compile_model_output(i,j,files,model): """ compiles the model variables over severl files into a single array at a j,i grid point. Model can be "Operational", "Operational_old", "GEM". returns wind speed, wind direction, time,pressure, temperature, solar radiation, thermal radiation and humidity. "...
5,334,311
def make_config(experiment: sacred.Experiment) -> None: """Adds configs and named configs to `experiment`. The standard config parameters it defines are: - env_name (str): The environment name in the Gym registry of the rewards to compare. - x_reward_cfgs (Iterable[common_config.RewardCfg]): tu...
5,334,312
def read_audio(path, Fs=None, mono=False): """Read an audio file into a np.ndarray. Args: path (str): Path to audio file Fs (scalar): Resample audio to given sampling rate. Use native sampling rate if None. (Default value = None) mono (bool): Convert multi-channel file to mono. (Default...
5,334,313
def evaluate_and_export(estimator #: BaseEstimator, , X: np.ndarray, filename: str): """ Export to specified file the prediction results of given estimator on given testset. File saved is in csv format with a single column named 'predicted_values' and n_samples rows containing p...
5,334,314
def test_get_matrix(): """ test Description: Expectation: """ circ = Circuit().ry('a', 0).rz('b', 0).ry('c', 0) m = circ.matrix(np.array([7.902762e-01, 2.139225e-04, 7.795934e-01])) assert np.allclose(m[0, 0], 0.70743435 - 1.06959724e-04j)
5,334,315
def energies_from_mbe_log(filename): """Monomer dimer energies from log file.""" monomers, dimers, trimers, tetramers = {}, {}, {}, {} hf, os_, ss_ = True, False, False mons, dims, tris, tets = True, False, False, False energies = False def storeEnergy(dict_, key, energy): """Store ene...
5,334,316
def build_varied_y_node_mesh(osi, xs, ys, zs=None, active=None): """ Creates an array of nodes that in vertical lines, but vary in height The mesh has len(xs)=ln(ys) nodes in the x-direction and len(ys[0]) in the y-direction. If zs is not None then has len(zs) in the z-direction. Parameters --...
5,334,317
def self_quarantine_end_10(): """ Real Name: b'self quarantine end 10' Original Eqn: b'50' Units: b'Day' Limits: (None, None) Type: constant b'' """ return 50
5,334,318
def main(): """Make a jazz noise here""" args = get_args() file_arg = args.FILE skip_arg = args.skip key_arg = args.keyword out_arg = args.output if not os.path.isfile(file_arg): die('"{}" is not a file'.format(file_arg)) skip_arg = [j.lower() for j in skip_arg] key_arg = [...
5,334,319
def spexsxd_scatter_model(dat, halfwid=48, xlims=[470, 1024], ylims=[800, 1024], full_output=False, itime=None): """Model the scattered light seen in SpeX/SXD K-band frames. :INPUTS: dat : str or numpy array filename of raw SXD frame to be corrected, or a Numpy array containing its dat...
5,334,320
def test_ap_track_sta_no_auth_passive(dev, apdev): """AP rejecting authentication from dualband STA on 2.4 GHz (passive)""" try: _test_ap_track_sta_no_auth_passive(dev, apdev) finally: subprocess.call(['iw', 'reg', 'set', '00'])
5,334,321
def newff(minmax, size, transf=None): """ Create multilayer perceptron :Parameters: minmax: list of list, the outer list is the number of input neurons, inner lists must contain 2 elements: min and max Range of input value size: the length of list equal to the number of laye...
5,334,322
def write(*args, package="gw", file_format="dat", **kwargs): """Read in a results file. Parameters ---------- args: tuple all args are passed to write function package: str the package you wish to use file_format: str the file format you wish to use. Default None. If Non...
5,334,323
def photo(el, dict_class, img_with_alt, base_url=''): """Find an implied photo property Args: el (bs4.element.Tag): a DOM element dict_class: a python class used as a dictionary (set by the Parser object) img_with_alt: a flag to enable experimental parsing of alt attribute with img (set by th...
5,334,324
def calc_TOF(t_pulse, t_signal): """Calculate TOF from pulse and signal time arrays.""" tof = [] idxs = [-1] dbls = [] for t in t_signal: idx = bisect_left(t_pulse, t) if idx == len(t_pulse): t_0 = t_pulse[-1] else: t_0 = t_pulse[idx - 1] if id...
5,334,325
def get_nodes_ips(node_subnets): """Get the IPs of the trunk ports associated to the deployment.""" trunk_ips = [] os_net = clients.get_network_client() tags = CONF.neutron_defaults.resource_tags if tags: ports = os_net.ports(status='ACTIVE', tags=tags) else: # NOTE(ltomasbo: if ...
5,334,326
def get_visualizations_info(exp_id, state_name, interaction_id): """Returns a list of visualization info. Each item in the list is a dict with keys 'data' and 'options'. Args: exp_id: str. The ID of the exploration. state_name: str. Name of the state. interaction_id: str. The intera...
5,334,327
def push(array, *items): """Push items onto the end of `array` and return modified `array`. Args: array (list): List to push to. items (mixed): Items to append. Returns: list: Modified `array`. Warning: `array` is modified in place. Example: >>> array = [...
5,334,328
def compute_list(commandline_argument): """ Returns a list of booking or revenue data opening booking data file with first parameter """ # utf-8_sig # Open booking CSV and read everything into memory with open(commandline_argument, "r", encoding="shift_jis") as database: data = csv....
5,334,329
def write_xyz(file_path, points: np.ndarray, normals=None, colors=None): """ Write point cloud file. :param file_path: :param points: :param normals: :param colors: :return: None """ file_utils.make_dir_for_file(file_path) if points.shape == (3,): points = np.expand_dim...
5,334,330
def calculate_saving(deal, item_prices): """ Parse the deal string and calculate how much money is saved when this deal gets applied. Also returns deal requirement. Args: deal (str): deal information item_prices (dict): {item: price} Returns: requirements (collections.Counter...
5,334,331
def assert_file_exists(file_path: str) -> None: """Assert filepath exists. Give verbose error messages. Args: file_path (str): file path e.g. abc/xyz.csv or xyz.csv """ dir = dirname(file_path) assert dir == "" or isdir(dir), f"{dirname} directory doesn't exist.." assert isfile( ...
5,334,332
def fetchone_from_table(database, table, values_dict, returning): """ Constructs a generic fetchone database command from a generic table with provided table_column:value_dictionary mapping. Mostly used for other helper functions. :param database: Current active database connection. :param table: ...
5,334,333
def reset_errformat(with_func = errformat): """ Restore the original excformat function. """ global errformat errformat = with_func
5,334,334
def read_and_search(treap, data): """ Search for each character in the given file (non-case-sensitive) in the given Treap. Repeats this operation TIMED_COUNT times and prints out the average time. Raises: AssertionError: If a character (A-Z) is not found. """ # define core search method ...
5,334,335
def copy_datastore(src, dst): """ Copy datastore so that the destination datastore is an replica of the source datastore 'Hidden' keys starting with '_' will not be copied. This is important because keys like ``_kombu*`` created by Redis do not have a string type and thus cannot be moved between da...
5,334,336
def capture_user_interruption(): """ Tries to hide to the user the ugly python backtraces generated by pressing Ctrl-C. """ signal.signal(signal.SIGINT, lambda x, y: sys.exit(0))
5,334,337
def main() -> None: """ネットワーク構成を確認するためのスクリプト.""" torchinfo.summary(Mnist())
5,334,338
def test_tag_field_is_used_in_load_process(): """ Confirm that the `_TAG` field is used when de-serializing to a dataclass instance (even for nested dataclasses) when a value is set in the `Meta` config for a JSONWizard sub-class. """ @dataclass class Data(ABC): """ base class for a...
5,334,339
def report(function, *args, **kwds): """Run a function, catch, report and discard exceptions""" try: function(*args, **kwds) except Exception: traceback.print_exc()
5,334,340
def recover_buildpack(app_folder): """ Given the path to an app folder where an app was just built, return a BuildPack object pointing to the dir for the buildpack used during the build. Relies on the builder.sh script storing the buildpack location in /.buildpack inside the container. """ ...
5,334,341
def ParseMultiCpuMask(cpu_mask): """Parse a multiple CPU mask definition and return the list of CPU IDs. CPU mask format: colon-separated list of comma-separated list of CPU IDs or dash-separated ID ranges, with optional "all" as CPU value Example: "0-2,5:all:1,5,6:2" -> [ [ 0,1,2,5 ], [ -1 ], [ 1, 5, 6 ], [ 2...
5,334,342
def get_network_insights_analysis_output(network_insights_analysis_id: Optional[pulumi.Input[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetNetworkInsightsAnalysisResult]: """ Resource schema for AWS::EC2::NetworkInsightsAnalysis """ ...
5,334,343
def _call(arg): """Shortcut for comparing call objects """ return _Call(((arg, ), ))
5,334,344
def gather_directives( type_object: GraphQLNamedType, ) -> List[DirectiveNode]: """Get all directive attached to a type.""" directives: List[DirectiveNode] = [] if hasattr(type_object, "extension_ast_nodes"): if type_object.extension_ast_nodes: for ast_node in type_object.extension_...
5,334,345
def start_moderating(): """Main driver for the moderation action.""" print("🙈 Attempting to moderate \"" + EXTENSION_NAME + "\" extension") success = False found_at_least_one_match = False # Iterate through all extension folders looking for the manifest.json # so we can find the extension name....
5,334,346
def test_fooof_load(): """Test load into FOOOF. Note: loads files from test_core_io.""" # Test loading just results tfm = FOOOF(verbose=False) file_name_res = 'test_fooof_res' tfm.load(file_name_res, TEST_DATA_PATH) # Check that result attributes get filled for result in OBJ_DESC['results']...
5,334,347
def test_multiple_geospatial_types() -> None: """Multiple photo_type""" collection = Collection("fake_collection") item_a = Item("id_0") item_a.linz_geospatial_type = "black and white image" collection.add_item(item_a) item_b = Item("id_1") item_b.linz_geospatial_type = "black and white i...
5,334,348
def get_request(language=None): """ Returns a Request instance populated with cms specific attributes. """ request_factory = RequestFactory() request = request_factory.get("/") request.session = {} request.LANGUAGE_CODE = language or settings.LANGUAGE_CODE request.current_page = None ...
5,334,349
def validate_hash(value: str) -> bool: """ Validates a hash value. """ return cast(bool, HASH_RE.match(value))
5,334,350
def pytorch_mnist(filename='pytorch_mnist.py'): """ Returns a Pytorch MNIST Classifier template. """ with open(filename, 'w') as f: f.write("""import torch import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import transforms, datasets def load_mnist(): ...
5,334,351
def string_to_digit(string, output): """Convert string to float/int if possible (designed to extract number from a price sting, e.g. 250 EUR -> 250) :argument string: string to convert :type string: str :argument output: output type :type output: type :returns float/int or None """ ...
5,334,352
def calc_B_phasors(current, xp, yp, cable_array): """It calculates the phasors of the x and y components of the magnetic induction field B in a given point for a given cable. Given the input, the function rectifies the current phase extracting respectively the real and imaginary part of it. Then, ...
5,334,353
def get_shortest_text_value(entry): """Given a JSON-LD entry, returns the text attribute that has the shortest length. Parameters ---------- entry: dict A JSON-LD entry parsed into a nested python directionary via the json module Returns ------- short_text: str ...
5,334,354
def generate_token(user_id, expires_in=3600): """Generate a JWT token. :param user_id the user that will own the token :param expires_on expiration time in seconds """ secret_key = current_app.config['JWT_SECRET_KEY'] return jwt.encode( {'user_id': user_id, 'exp': datetime.utcn...
5,334,355
def debom(s): """ 此函数是去除字符串中bom字符, 由于此字符出现再文件的头位置 所以对csv 的header造成的影响, 甚至乱码 通过此函数可以避免这种情况 """ boms = [ k for k in dir(codecs) if k.startswith('BOM') ] for bom in boms: s = s.replace(getattr(codecs, bom), '') return s
5,334,356
def rolling_window(array, window): """ apply a rolling window to a np.ndarray :param array: (np.ndarray) the input Array :param window: (int) length of the rolling window :return: (np.ndarray) rolling window on the input array """ shape = array.shape[:-1] + (array.shape[-1] - window + 1, wi...
5,334,357
def calculate_timezone_distance_matrix(df): """ Calculate timezone distance matrix from a given dataframe """ n_users = len(df) timezone_df = df[['idx', 'timezone', 'second_timezone']] timezone_df.loc[:, 'timezone'] = timezone_df.timezone.map( lambda t: remove_text_parentheses(t).split('...
5,334,358
def pyxstyle_path(x, venv_dir="venv"): """Calculate the path to py{x}style in the venv directory relative to project root.""" extension = ".exe" if platform.system() == "Windows" else "" bin_dir = "Scripts" if platform.system() == "Windows" else "bin" return [str(path_here / f"{venv_dir}/{bin_dir}/py{x}...
5,334,359
def show_mode(loop): """Show mode without genetic algorithm. Used only for displaying the results""" '''loop = input('How many times you want to display last population?\n') try: loop = int(loop) except ValueError: print('Invalid number!')''' for iterator in range(loop): sco...
5,334,360
def update_tc_junit_resultfile(tc_junit_obj, kw_junit_list, tc_timestamp): """loop through kw_junit object and attach keyword result to testcase Arguments: 1. tc_junit_obj = target testcase 2. kw_junit_list = list of keyword junit objects 3. tc_timestamp = target testcase timestamp """ for m...
5,334,361
def checkFramebufferStatus(): """Utility method to check status and raise errors""" status = glCheckFramebufferStatus( GL_FRAMEBUFFER ) if status == GL_FRAMEBUFFER_COMPLETE: return True from OpenGL.error import GLError description = None for error_constant in [ GL_FRAMEB...
5,334,362
def listen(host, port, datadir, postProcessing, iridiumHost, iridiumPort): """ Run server to listen for transmissions """ logger = logging.getLogger('DirectIP') logger.info('Executing runserver.') if host is None: logger.critical('Invalid host: "%s"' % host) assert host is not None ...
5,334,363
def reset_xform_and_collapse(node_name, freeze=False): """ Resets the xform and collapse the stack of the given node :param node_name: str :param freeze: bool """ node = node_utils.get_pymxs_node(node_name) rt.ResetXForm(node) rt.CollapseStack(node) if freeze: freeze_transfo...
5,334,364
def load_sentences(filename): """give us a list of sentences where each sentence is a list of tokens. Assumes the input file is one sentence per line, pre-tokenized.""" out = [] with open(filename) as infile: for line in infile: line = line.strip() tokens = line.split() out.a...
5,334,365
def imageSequenceRepr(files, strFormat='{pre}[{firstNum}:{lastNum}]{post}', forceRepr=False): """ Takes a list of files and creates a string that represents the sequence. Args: files (list): A list of files in the image sequence. format (str): Used to format the output. Uses str.format() command and requires the ...
5,334,366
def farthest_point_sampling(D, k, random_init=True): """ Samples points using farthest point sampling Parameters ------------------------- D : (n,n) distance matrix between points k : int - number of points to sample random_init : Whether to sample the first point random...
5,334,367
def part2(lines): """ >>> part2(load_example(__file__, '9')) 982 """ return run(lines, max)
5,334,368
def use_in_cluster_config(token_file="/var/run/secrets/kubernetes.io/serviceaccount/token", # nosec ca_cert_file="/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"): """ Configure the client using the recommended configuration for accessing the API from within a Kubernetes cluster...
5,334,369
def load_description(): """ Reads pandas dataframe with name(description) and category for FG phenos """ description = "./description.txt" if not os.path.isfile(description): cmd = f"gsutil cp {pheno_description} {description}" subprocess.call(shlex.split(cmd)) d = pandas.read_c...
5,334,370
def country_call_code(): """Get information about the calling code of a country""" pass
5,334,371
def get_utility_function(args): """ Select the utility function. :param args: the arguments for the program. :return: the utility function (handler). """ if args.mode == 'entropy': utility_function = compute_utility_scores_entropy elif args.mode == 'entropyrev': # Reverse entropy m...
5,334,372
def convertRequestToStringWhichMayBeEmpty(paramName, source): """ Handle strings which may be empty or contain "None". Empty strings should be treated as "None". The "None" strings are from the timeSlicesValues div on the runPage. Args: paramName (str): Name of the parameter in which we ar...
5,334,373
def find_am(list_tokens:list): """[summary] Parameters ---------- list_tokens : list list of tokens Returns ------- tuple(list,list) matches tokens, token indexes """ string = "START"+" ".join(list_tokens).lower() match = re.findall(am_pattern, stri...
5,334,374
def fetch_seq_assembly(mygroup, assembly_final_df, keyargs): """ Function that will fetch the genome from the taxid in group and concat the assembly that is created by ngs """ keyargs['taxids'] = [str(taxid) for taxid in mygroup.TaxId.tolist()] #ngd.download(**keyargs) get_cmdline_ndg(*...
5,334,375
def calculate_min_cost_path(source_node: int, target_node: int, graph: nx.Graph) -> (list, int): """ Calculates the minimal cost path with respect to node-weights from terminal1 to terminal2 on the given graph by converting the graph into a line graph (converting nodes to edges) and solving the respective s...
5,334,376
def promote(name): """ Promotes a clone file system to no longer be dependent on its "origin" snapshot. .. note:: This makes it possible to destroy the file system that the clone was created from. The clone parent-child dependency relationship is reversed, so that the origin fi...
5,334,377
def otp_verification(request): """Api view for verifying OTPs """ if request.method == 'POST': serializer = OTPVerifySerializer(data = request.data) if serializer.is_valid(): data = serializer.verify_otp(request) return Response(data, status=status.HT...
5,334,378
def handler(event, context): """ Collects the report for a URL given in the SQS ``message`` from VirusTotal's API. """ message_json = json.loads(event['Records'][0]['body']) asset_type = message_json['type'] domain_or_ip = message_json[asset_type] print(f'Domain or IP: {domain_or_ip}') ...
5,334,379
def test_pod_status_parser(config, expected_status): """测试 Pod 状态解析逻辑""" actual_status = PodStatusParser(config).parse() assert actual_status == expected_status
5,334,380
def AddGnuIncludeDirectivesToMakefile(infile, outfile): """Adds GNU-style include directives to a Makefile. Inserts GNU-style include directives for the top-level configure.mk file and directory-level .d files. Should be applied before makedepend output has been stripped. This effectively converts the Makefile...
5,334,381
def resetThreeDViews(): """Reset focal view around volumes """ import slicer slicer.app.layoutManager().resetThreeDViews()
5,334,382
def parse_tag_file(doc: ET.ElementTree) -> dict: """ Takes in an XML tree from a Doxygen tag file and returns a dictionary that looks something like: .. code-block:: python {'PolyVox': Entry(...), 'PolyVox::Array': Entry(...), 'PolyVox::Array1DDouble': Entry(...), 'PolyV...
5,334,383
def hpd_grid(sample, alpha=0.05, roundto=2): """Calculate highest posterior density (HPD) of array for given alpha. The HPD is the minimum width Bayesian credible interval (BCI). The function works for multimodal distributions, returning more than one mode Parameters ---------- s...
5,334,384
def ecdf_numerical(data, cols_num, col_target=None, grid_c=3, w=15, h_factor=3.5): """ Empirical Cumulative Distribution Function plot. Useful for KS-test. Parameters ---------- data : pandas.DataFrame dataframe without infinite values. will drop null values while plotting. cols_num : l...
5,334,385
def install_compressed_xml(corpus, xmlfile, out, export_path, host): """Install xml file on remote server.""" if not host: raise Exception("No host provided! Export not installed.") filename = corpus + ".xml.bz2" remote_file_path = os.path.join(export_path, filename) util.install_file(host, ...
5,334,386
def get_internal_modules(key='exa'): """ Get a list of modules belonging to the given package. Args: key (str): Package or library name (e.g. "exa") """ key += '.' return [v for k, v in sys.modules.items() if k.startswith(key)]
5,334,387
def emph_rule(phrase: str) -> Rule: """ Check if the phrase only ever appears with or without a surrounding \\emph{...}. For example, "et al." can be spelled like "\\emph{et al.}" or "et al.", but it should be consistent. """ regex = r"(?:\\emph\{)?" regex += r"(?:" + re.escape(phrase) + r"...
5,334,388
def parse_amwg_obs(file): """Atmospheric observational data stored in""" file = pathlib.Path(file) info = {} try: stem = file.stem split = stem.split('_') source = split[0] temporal = split[-2] if len(temporal) == 2: month_number = int(temporal) ...
5,334,389
def taylor(x,f,i,n): """taylor(x,f,i,n): This function approximates the function f over the domain x, using a taylor expansion centered at x[i] with n+1 terms (starts counting from 0). Args: x: The domain of the function f: The function that will be expanded/approximated i: ...
5,334,390
def precision_and_recall_at_k(ground_truth, prediction, k=-1): """ :param ground_truth: :param prediction: :param k: how far down the ranked list we look, set to -1 (default) for all of the predictions :return: """ if k == -1: k = len(prediction) prediction = prediction[0:k] ...
5,334,391
def bubble_sort(array: list, key_func=lambda x: x) -> list: """ best:O(N) avg:O(N^2) worst:O(N^2) """ if key_func is not None: assert isfunction(key_func) for pos in range(0, len(array)): for idx in range(0, len(array) - pos - 1): if key_func(array[idx]) > key_func(a...
5,334,392
def limit_paulis(mat, n=5, sparsity=None): """ Limits the number of Pauli basis matrices of a hermitian matrix to the n highest magnitude ones. Args: mat (np.ndarray): Input matrix n (int): number of surviving Pauli matrices (default=5) sparsity (float): sparsity of matrix < 1 ...
5,334,393
def list_clusters(configuration: Configuration = None, secrets: Secrets = None) -> AWSResponse: """ List EKS clusters available to the authenticated account. """ client = aws_client("eks", configuration, secrets) logger.debug("Listing EKS clusters") return client.list_clusters(...
5,334,394
def tar_cat(tar, path): """ Reads file and returns content as bytes """ mem = tar.getmember(path) with tar.extractfile(mem) as f: return f.read()
5,334,395
def __get_base_name(input_path): """ /foo/bar/test/folder/image_label.ext --> test/folder/image_label.ext """ return '/'.join(input_path.split('/')[-3:])
5,334,396
def or_ipf28(xpath): """change xpath to match ipf <2.8 or >2.9 (for noise range)""" xpath28 = xpath.replace('noiseRange', 'noise').replace('noiseAzimuth', 'noise') if xpath28 != xpath: xpath += " | %s" % xpath28 return xpath
5,334,397
def make_form(x, current_dict, publication_dict): """Create or update a Taxon of rank Form. Some forms have no known names between species and form. These keep the form name in the ``infra_name`` field. e.g. Caulerpa brachypus forma parvifolia Others have a known subspecies/variety/subv...
5,334,398
def render_view(func): """ Render this view endpoint's specified template with the provided context, with additional context parameters as specified by context_config(). @app.route('/', methods=['GET']) @render_view def view_function(): return 'template_name.html', {'con...
5,334,399