content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import collections import json def _convert_validators_to_mapping(validators): """ convert validators list to mapping. Args: validators (list): validators in list Returns: dict: validators mapping, use (check, comparator) as key. Examples: >>> validators = [ ...
656df1f29ab537ab0d4ec1186c31b2c92b6d8c64
77,262
from typing import Iterable from typing import Union from functools import reduce def merge_all(item: Iterable[Union[dict, partials.Partial]]) -> dict: """Merge contexts of an arbitrary number of items.""" dicts = [] for elem in item: dicts.append(elem if isinstance(elem, dict) else elem.context) ...
e4dded6fae3a5f6475ddc2ea22445403bbaa3e6f
77,263
def numpy_quaternion_to_icv_quaternion(numpy_quaternion): """ Convert a quaternion from transforms to a icv msg quaternion :param numpy_quaternion: a numpy quaternion :type numpy_quaternion: numpy.array :return: a icv quaternion :rtype: geometry_msgs.msg.Quaternion """ icv_quaternion = ...
a44d65be59e3b83fba75a746ee80f65dfb4a5d4c
77,265
import six def _process_annotation_items(items, hyphens_as_underscores): """ Process annotation items after the scalyr config prefix has been stripped """ def sort_annotation(pair): (key, value) = pair m = SCALYR_ANNOTATION_ELEMENT_RE.match(key) if m: root_key = m.grou...
a3b8987ece108c8526119d7150fe670e06dc3018
77,266
def decompose(polygon, origin=None, width=1.0): """ Decompose the field into a list of points to cover the field. """ p = generate_intersections(polygon, width) if origin == None: return order_points(p, polygon.bounds[0:2]) else: return order_points(p, origin)
2222fbd462f8d1f21e355757e0da4317b6b2d01a
77,267
def add_doubles(x=float, y=float): """ return x+y; """ return float
78a9c21f6bf746a4e232c4f841c2f7a6547beefe
77,268
def frontend_url(name, **query_args): """Build a URL for a Frontend Link. Builds a URL for the Jade Tree frontend using the Frontend URL list loaded from the application configuration. Any `query_args` parameters will be included as GET query arguments in the URL. Args: name: Name of the f...
b694ae9b38b038efb9abc0f8532824cb6ca382bc
77,269
def sort_and_pick_median(seq): """Standard and most apparent way or algorithm to find median of some sequence or list O(nlog(n)) :param seq: list, string, tuple, or other type :return: the value of the median of the sequence """ i = (len(seq) - 1) // 2 return sorted(seq)[i]
7f8566493d8764a9b6e68cbf798117ae2cdbc9dc
77,270
def nest_any_node(ren_args: RenArgs) -> str: """Nest both operation & data under `parent`'s name (if given) but NOT jsonparts. :return: the nested name of the operation or data """ def prefixed(name): return f"{ren_args.parent.name}.{name}" if ren_args.parent else name if not ren_...
a43b8679e35b079ac697aad0e164bc4a24507e80
77,271
import torch def torch_isOverlap(V, W, ind, classId, isUsingGPU = False): """ Checking overlap between hyperbox ind and remaning hyperboxes (1 vs many) INPUT V Hyperbox lower bounds W Hyperbox upper bounds ind Index of the hyperbox to be checked for...
f19689efa36b98165f9f5921a0237c8492b26a42
77,272
def one_compound_ingredient(one_ingredient_series_static, compound_ingredient_label, chemdf_dict): """ Parameters ---------- ingredient_series : ex. as generated by expworkup.ingredients.get_ingredients_df() _raw_reagent_2_chemicals_0_inchikey VAWHFUNJDMQUSB-UHFFFAOYSA-N ...
8e94f89075bd3e8276c626ab1c12eb95beeebee5
77,273
def spectral_perturbation_correlation( pert_fn, diff_fn, pred_fn, n_layers, inputs, n_iterations, batch_size=30, seed=((2017, 7, 10)), ): """Calculates perturbation correlations for layers in network by perturbing either amplitudes or phases Parameters ---------- pert_fn...
6359ed25c39e843e66c3b3068231cf28b09973c1
77,274
import requests import csv def load_insteval(): """Loads the InstEval data set. It contains 73,421 university lecture evaluations by students at ETH Zurich with a total of 2,972 students, 2,160 professors and lecturers, and several student, lecture, and lecturer attributes. Implementation is buil...
8f683207b48e784dfe4f0f1e63e8afdc90e10a3e
77,275
def load_data(args): """Load data from HDF5 file if required""" if hasattr(args, "data"): return args.data, args.targets data_root = h5py.File(args.data_filename, "r") data = data_root[constants.DATA][...] targets = data_root[constants.TARGETS][...] return data, targets
b645c5ad383ea571ad4ce47ad96a5144f0bc2141
77,276
from typing import Optional from typing import Set def create_entity_menu_item(db, attributes=None, mixin=None): """ Creates and returns a menu item entity to mapping in the database. Arguments: db (pony.orm.Database): database instance. attributes (dict): entity Attributes. mixin...
391b58508c8f4ee0654584741bdb338fa7541456
77,277
import cv2 as cv import torch def rot_to_euler(R: np.array) -> np.array: """ :return: Euler angles in rad in ZYX """ if torch.is_tensor(R): R = R.detach().cpu().numpy() angles = np.radians(cv.RQDecomp3x3(R)[0]) angles[0], angles[2] = angles[2], angles[0] return angles
b55c480c76452d16a8fca04cfa00dcbebf6dd28b
77,278
import collections def create_report_dictionary(report_list, seq_list, id_column='SeqID'): """ :param report_list: List of paths to report files :param seq_list: List of OLC Seq IDs :param id_column: Column used to specify primary key :return: Dictionary containing Seq IDs as keys and dataframes a...
22d873f7060009e9ded958c9ce1fbf5b68216d66
77,279
def find_style(term): """Return a list of styles the names of which include a search term. Keyword arguments: term-- a string to search """ styles = all_styles() found_styles = [] if term =='': return found_styles else: for style in styles: if term in s...
f1600ae982ec067e7b5f54c3eb74e347da3a5bc9
77,280
def get_users_router( fastapi_users_objects=None, route_settings=DEFAULT_USERS_ROUTE_SETTINGS, *args, **kwargs): """ Get a users router. Parameters ---------- fastapi_users_objects : dict Dictionary returned from :func:`msdss_users_api.tools.create_fastapi_users_objects`. ro...
db30b637f7db606224d2113a92c12e6773566cd2
77,281
from typing import List def fetch_common_ixps(peers: List[Peer]) -> List[str]: """Return a list of common IXPs. Arguments: peers: A list of Peer objects for a given ASN. Returns: A list of common IX points, based in their name. """ common_ix = set([i.name for i in peers[0].peerin...
3db3f1e2b5386f9c4f22dbb2dcbf1e786ad3d7ac
77,282
def match(substrate, target): """ Compare two sequences of the same length and return indexes of the positions where the sequences differ. """ if len(substrate) != len(target): log("WARNING: len(substrate) != len(target) "+str(len(substrate)) +'!='+ str(len(target))) return ...
1b8e29bbe4b5710a88b42a581ba82606a4748409
77,283
def dataDirection_1(datas, offset=0): """ 极小型指标正向化 :param datas: 迭代器 :param offset: 防止出现除以 0 的错误 """ def normalization(data): return 1 / (data + offset) return list(map(normalization, datas))
d5a70e8e3b0e232d6e3f7a420b815a2323efe065
77,284
def is_consistent( topology_matrix: TopologyMatrix ) -> bool: """ Checks whether an SDF graph has consistent firing rates """ _, matrix = topology_matrix num_agents = len(matrix[0]) return np.linalg.matrix_rank(matrix) == num_agents - 1
1c6625e30599c51d47992006c9ff37b727cc22a9
77,285
def single_file_output(in_file): """ Extract sample name from file ie. /path/to/test.fa --> test :param in_file: path/to/file (str) :return: extracted sample name (str) """ return in_file.split('/')[-1].split('.')[-2]
4dd5c5f0de584f479fdf91e88cdede33c8072f10
77,288
def _roll_once( tensor: tf.Tensor, shift: int, axis: int, ) -> tf.Tensor: """Roll along a single dimension like tf.roll().""" if not shift: return tensor axis = _normalize_axis(axis, len(tensor.shape)) slice_left = (slice(None),) * axis + (slice(-shift, None),) slice_right = (slice(None),) * a...
2d7cc5862703ec77065fe4f2fba3e0f7f2dc6361
77,289
def create_context_path_comp_service_path_comp_service_by_id(uuid, path_comp_service): # noqa: E501 """Create path-comp-service by ID Create operation of resource: path-comp-service # noqa: E501 :param uuid: ID of uuid :type uuid: str :param path_comp_service: path-comp-servicebody object :ty...
51653f14c31685950a7b88e925dfd5f7d1edc573
77,290
def single_exon_transcript(single_exon_dict,transiddict): """Give single exon reads a transcript. Parameters ---------- single_exon_dict : dict read id is key, value is list [chromosome,start,end,strand] transiddict : dict read id is key, transcript id is value Returns ------- dict a dictionary of sin...
215e7e2c67ab5f880db58a3a5efd03c5397e9ab4
77,291
def get_host_component(host_component_id): """ Returns host_component object in dictionary format :param host_component_id: Object ID :type host_component_id: int :return: HostComponent object :rtype: dict """ fields = ( 'cluster', 'host', 'service', 'com...
1325cf49d92a3839623d938e66bdae8309d3cd08
77,293
def VerifyFileID(fi_disk, fi_ours): """Verifies that two file IDs are matching. Differences in the inode/device are not accepted, but and older timestamp for fi_disk is accepted. @param fi_disk: tuple (dev, inode, mtime) representing the actual file data @param fi_ours: tuple (dev, inode, mtime) repre...
c32acadd21b249904374eb44bcab3db42fe3972c
77,294
def rxp(r, p): """ Multiply a p-vector by a r-matrix. :param r: rotation matrix. :type r: array-like of shape (3,3) :param p: p-vector. :type p: array-like of shape (1,3) :returns: r * p as a numpy.matrix of shape 1x3. .. seealso:: |MANUAL| page 196 """ rp = _np.asmatrix(_np.zero...
b5d1e7e7401ae71046a8cf9f01d334c991d01925
77,295
def getPodName(ctx): """ Get the name of the pod in which our current deployment is running """ return _getPodProperty(ctx, 'name', '.metadata.name')
834e40fc0487ef70ae2b9b0c0eadd2f334a0510f
77,296
def _c2_prob_ ( s ) : """Chi2 probabiilty >>> r = h.hfit ( ... ) >>> r.Prob() """ dofs = s.points() - s.size() return ROOT.TMath.Prob ( s.chi2() , dofs )
55d901138d82b4e1c0b90c0a4e24204f8cd975c6
77,297
def dist2(a, b): """Return the square distance between two vectors. Parameters ---------- a : np.array b : np.array """ return norm2(a - b)
5349883b2a1934ffe6754098ed1c4b833a60cf13
77,298
def argument(*name_or_flags, **kwargs): """Convenience function to properly format arguments to pass to the subcommand decorator. """ return (list(name_or_flags), kwargs)
c92fb9d2aaea1e2db6354ba7fff7c267c7932556
77,299
def parse_node_metrics(nodes_data: dict, node_id_mapping: dict, os_idrac_hostname_mapping: dict): """parse_node_metrics Parse Node Metircs Parse Nodes metrics get from Slurm API Args: nodes_data (dict): Nodes data get from Slurm APi node_id_ma...
f2d093cf0f782c698a92a542328d303797488e0b
77,300
import json def landsat_config_file(tile_path): """ Read a LandSat MTL config file to a Python dict """ f = open(tile_path) group_path = [] config = {} for line in f: line = line.lstrip(' ').rstrip() #remove leading whitespaces and trainling newlines if line.startswith(...
c32374f8ac4ce9378db32c7fa734de259fa8f844
77,301
def get_shadowset_members(shadowset='dsa0:'): """ Returns an array with the members of a shadowset """ members = run('SHOW DEVICE {} /BRIEF | SEA SYS$PIPE ShadowSetMember'. format(shadowset)) return [member.split()[0] for member in members.splitlines()]
e8304df26b13a186e948e5e694b8e88f21710b69
77,302
import re def shn_split_multi_value(value): """ @author: Michael Howden (michael@aidiq.com) Converts a series of numbers delimited by |, or already in a string into a list If value = None, returns [] """ if not value: return [] elif isinstance(value, ( str ) ): if "[...
df68123661dc1f5ebed2abf734880da975aeb0ad
77,304
def resblock_g(h, y, scopename, n_classes, maps, kernel=(3, 3), pad=(1, 1), stride=(1, 1), upsample=True, test=False, sn=True, coefs=[1.0]): """Residual block for generator""" s = h _, c, _, _ = h.shape with nn.parameter_scope(scopename): # BN -> Relu -> Upsample -...
6339f1a58976b6f5b82a6b696bd008108be2e848
77,305
from typing import Dict from typing import List def get_excluded_shipping_methods_or_fetch( webhooks: QuerySet, event_type: str, payload: str, cache_key: str ) -> Dict[str, List[ExcludedShippingMethod]]: """Return data of all excluded shipping methods. The data will be fetched from the cache. If missing ...
c7dd78422dbc7c49c01cf62c6845342c59c85aef
77,306
import joblib def dt_eval(data, target, depth=4, class_weight="balanced"): """ evals a single data set against itself target is the class variable, all other variables are used for training """ class_var = target features = data.columns.values[~data.columns.str.contains(class_var)] clf =...
42b7871b574387779ad40997f99e42578a440058
77,307
def list_subscriptions(subscription_key=None, subscription_type=None): """ GET /subscriptions :return: list of subscription objects serialized into json """ request_inputs = anchore_engine.apis.do_request_prep( request, default_params={ "subscription_key": subscription_k...
eb31e943b32aa09dba5d48bf238ec100fb8d3923
77,308
def _softmax(x): # softmax over 4 dim matrix """ Numpy-based reference softmax over 4 dim matrix""" output = np.zeros(x.shape, dtype=np.float32) for i in range(x.shape[0]): for j in range(x.shape[1]): for k in range(x.shape[2]): x_curr = x[i, j, k, :] e_x...
429e50ce2e7b42a9f6b2422dadbe88432bdf899f
77,309
from core.models.coreproxy import ScheduleConfigProxy, JobsProxy from datetime import datetime def check_config(user_id, schedule, schedule_configs): """ check and update schedule config """ message = [] sch_configs = [] """ remove existing records """ ScheduleConfigProxy.o...
8e41d30855b3a4b65984f2c30bdcb59cb46b7b38
77,310
def get_download_url_from_tag(package, version, data = None): """ Return the download URL for a given version (which is tag). @package - :user/:repo combination """ tags = get_tags(package, package) this_ver = which_tag(version, tags, package.split('/')[1]) return "https://codeload...
09de38f137230d0e032d813b9f1a0eac3bd59553
77,311
def new(): """ :return: a new preview collection. :rtype: :class:`ImagePreviewCollection` """ return ImagePreviewCollection()
6feab8b09bc3b1bc17dc16bf4da763d2232ef933
77,312
import random def language(): """Random language name, e.g. ``Polish``.""" return random.choice(get_dictionary('languages')).strip()
7da8ce06929fdc74eaf55c5109ab445bf6341d90
77,313
def _lstm_model(params, args, nb_classes, embedding_matrix): """ BD LSTM-RNN :param args: :param embedding_matrix: :return: """ lstm_hs = params['lstm_hs'] use_embeddings = params['use_embeddings'] embeddings_trainable = params['embeddings_trainable'] input = Input(shape=(args....
30b56d7f21aa9a1b757d6141dff2e136780068f1
77,314
import six def list_as_string(option): """Returns the argument as a string. Useful for insuring that ConfigObj options are always returned as a string, despite the presence of a comma in the middle. Example: >>> print(list_as_string('a string')) a string >>> print(list_as_string(...
0bd269fb455ce8eb20c4c0838fd4611832686baf
77,315
import shutil def first_order_of_motion(state, source): """ Peforms first order of motion, updates the state, and returns whether the operation was successful """ source_path = ( "./vision/first_order_motion/data/" + str(source.lower().replace(" ", "_")) + ".png" ) ...
f2de05a9f19c5bf66271f1aaae45d633698cb2e4
77,316
def load_medical_image(patient_id, medical_image): """Loads specified medical image GET request, queries the server for a specific medical image specified by the input medical image name. :param patient_id: int containing patient ID :param medical_image: str containing medical image file name ...
3e8d159b41a9d966dcca2dc3e2699170758025db
77,319
def nip(string): """ Rather than escaping special chars like above, this simply deletes them. For use in CSS classes and other restrictive environments. N.B. THIS ALSO PUTS EVERYTHING IN LOWERCASE FOR CONSISTENCY """ out = "" for char in string.lower(): if char.isalnum() or char in ...
cf01e0d2736bbbf1b8046d23bc1f1d2dbfba6da9
77,320
from pm4py.objects.log.util import dataframe_utils from pm4py.objects.log.util import artificial from typing import Union def insert_artificial_start_end(log: Union[EventLog, pd.DataFrame]) -> Union[EventLog, pd.DataFrame]: """ Inserts the artificial start/end activities in an event log / Pandas dataframe ...
d107be94017fabe4d68a6726b76228adb0961c8e
77,321
def sequences_to_char_form(seqs_lst, biomolecule): """Give a list of sequences whose residues are represented by integers, this function converts the sequences in which the residues are represented by characters. Note that this function does not read from FASTA files. Parameters ---------- ...
1007f8fef33ab294171315f011232ffbe063b757
77,323
def sing_RS256(message, key): """ Generates a sign using SHA256withRSA (also known as RSASSA-PKCS1-V1_5-SIGN with the SHA-256 hash function). Needed to make an Signed JSON Web Tokens request (Signed JWT assertion) """ if isinstance(key, StringTypes): if len(key) > 800: # key as string ...
2d28e8ed2c1df8a5422560aec24503899b486967
77,325
def rewriter(field, rules): """Create a template field function that rewrites the given field with the given rewriting rules. ``rules`` must be a list of (pattern, replacement) pairs. """ def fieldfunc(item): value = item._values_fixed[field] for pattern, replacement in rules: ...
c9cfba499f1dc8683df3918a9f497ec69ad07700
77,326
from gkutils.commonutils import Struct import MySQLdb def followupListQuery(listId, djangoRawObject = None, conn = None): """followupListQuery. Args: listId: djangoRawObject: conn: """ resultset = [] if djangoRawObject: # Assume a Django query by default resultset = ...
e43039aca91e5f2c070de5330eb0e24e0429fd9b
77,327
def get_response_headers(response): """ Django 3.2+ comes with changes to the repsonse headers and the _headers is not present in the newer versions. So this method checks if it's present in the response or not, else returns the newer attribute headers from the response. """ if hasattr(response,...
a4b135dffbe9ee85c602ea665e43590ff8beedd1
77,328
import torch def circular_correlation( a: torch.FloatTensor, b: torch.FloatTensor, ) -> torch.FloatTensor: """ Compute the circular correlation between to vectors. .. note :: The implementation uses FFT. :param a: shape: s_1 The tensor with the first vectors. :param b: ...
1fd2c08f032867821d22335574b642dcff37451e
77,329
def similarity(event, places): """ Return a list of dissimilar events to the given event. This is the successor function used in the search tree: a node's successors are the list of dissimilar options for the next choice. event (dict): A potential place/event. places (list): All potential places...
ca9a171abe37e7e9d48a604ca92c56092d4fa8c8
77,331
def get_iou(mask, label): """ :param mask: predicted mask with 0 for background and 1 for object :param label: label :return: iou """ #mask = mask.numpy() #label = labels.numpy() size = mask.shape mask = mask.flatten() label = label.flatten() m = mask + label i = len(np.a...
29af779d31c5f5c4718d063c557f027957b60365
77,332
def define_band_colors(): """ Define dictionary of colors to be used in plots (e.g. histograms) for representing data in specific bands """ band_color_rep = {'B': 'blue', 'G': 'green', 'R': 'red', 'N': 'black', ...
a17bf7d0a2742e2cf2c94beec3f97b27e1c640e3
77,334
def _raster_mask(raster, geodataframe, driver, output_type, no_data, all_touched, window_size, nb_processes, chunksize): """ Apply mask into raster """ mask = raster.__class__.rasterize(geodataframe, raster.crs.to_wkt(), ...
9debf76be160c10ac8b5767e8880c52a88e1555b
77,335
def get_varinfo_from_table(discipline,parmcat,parmnum): """ Return the GRIB2 variable information given values of `discipline`, `parmcat`, and `parmnum`. NOTE: This functions allows for all arguments to be converted to a string type if arguments are integer. Parameters ---------- **`discip...
d6e3b08dfcbfb023a2725ef1ffbb44448881fa64
77,336
import requests def WaitForOperation(operation_service, operation, max_retries=None, retry_interval=None, retry_callback=None): """Wait until the operation is complete or times out. Args: operation_service: The apitools service type for operation...
7277b37ee885431125cc927c00f5babe93ea871d
77,337
import random def evolve(pop, mut_rate, mu, lambda_): """ Evolve the population *pop* using the mu + lambda evolutionary strategy :param pop: a list of individuals, whose size is mu + lambda. The first mu ones are previous parents. :param mut_rate: mutation rate :return: a new generation of indiv...
e2510d0ce92d0c5703b9166778f48581db4aca2f
77,338
def state_from_id(index, dims_state_grid): """Convert *idx* to state array structured according to *dims_state_grid*""" entries = [index] * len(dims_state_grid) for i in range(1, len(dims_state_grid)): value = 1 for j in range(i, len(dims_state_grid)): value *= dims_state_grid[j...
14cbd17feb842eef6ae466c46ee8781dd6682aca
77,339
import re def strip_comments(source_code): """ Strips comments from source code to increase analysis accuracy. The function is similar to strip_quotations. It removes all comments from the source_code. It is also used to prevent false positives. It uses a regex to match and remove line comments a...
7e3842940367caaae875ec6c24a1a40fdf7efbc0
77,340
def parse_xyz(xyz_path): """Parses atomic structure, charge and spin from xyz file. The second line of the xyz file is assumed to contains two integers, representing charge and spin multiplicity (spin + 1). Args: xyz_path: String, the path to the xyz file. Returns: atom: String, the atomic structur...
f60afed4c1d47002f898f1df761a6b1016d599ee
77,341
def calculate_log_2_factor(value): """ Function that calculates the logarithmic term!""" result = np.log2(1 + value) return result
dcc01dfba8a9b8795bc9f3f8439192532f8fb918
77,342
def parse_dj_database_url(url): """Parse a database URI into a Django db config dictionary. Also adds an ``ENGINE`` key: ``django.db.backends.postgresql_psycopg2`` for Postgres. No other database is supported. E.g. parses ``postgres://user:pass@host:port/dbname`` into:: { 'NAME': ...
3e5091cef84c90247c8e257ae9101b6884309f48
77,343
def TwitterCheck(handle): """ Return list of success and failures for Twitter handles list, with total counts. """ TwitterMessageList = ["TWITTER TESTING\n\n"] TWfound = 0 TWmissing = 0 # check whether token works by testing URL for a controlled page TokenStatus, TokenMessage = Test...
06793e9a83b77fd8af0257afa6e478cab22b6755
77,344
def partial_dwptn(data, wavelet, mode='symmetric', axes=None, approx_only=False): """ Partial Single-level n-dimensional Discrete Wavelet Packet Transform. Computes only approximation subband Parameters ---------- data : array_like n-dimensional array with input data. wavelet : Wavel...
2ed4e701e7fadf3eda39de3a4fb09e4b9e98b577
77,345
def preprocess_data(data, label_encoder): """ Get input columns from raw data """ # Remove Tree Name column input_data = data """ Encode Categorical variables """ for i,item in enumerate(input_data[0,:]): if isinstance(item, str) is True: input_data[:, i] = label_encoder.fit_tra...
50f03f59a3ea98915d760f74a888780af69b1c68
77,347
def apply_action(action, state, step_number): """ Method to apply the control action to the cart-pole simulation. Arguments: action: The binary action defining direction of force to be applied. state: The state variables (x, x_dot, theta1, theta1_dot, theta...
5e07ac96b299a2d445d0f11ba1eae302b1bcf0f2
77,348
def parse_repository_name(pull_spec_reference: str) -> str: """ Parse repository name from container pull spec Args: pull_spec_reference (str): Container pull specification Returns: str: Repository name """ pull_spec = pull_spec_reference if not pull_spec_reference.startswi...
0829d25eaa2cece7f24953d839eb5eea343dc711
77,349
def euclid(a, b): """returns the Greatest Common Divisor of a and b""" a = abs(a) b = abs(b) if a < b: a, b = b, a while b != 0: a, b = b, a % b return a
861fb3e979ec4d6b5f171a62a5b2bfb044094b8f
77,352
import configparser def check_test_case_config_vs_web( case_idx=0, verbose=True, refresh=True, session=None, rtol=1e-5, atol=1e-8, case_file='no_test_cases.ini', official_func=None): """ this checks the config tax number vs the web number """ input_struct = {} cases = configparser.ConfigPa...
ad99527c1f1ff743d490702e6ac029e67a26f965
77,353
def stack(*tables, **kwargs): """Concatenate tables, without trying to match headers. E.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar'], ... [1, 'A'], ... [2, 'B']] >>> table2 = [['bar', 'baz'], ... ['C', True], ... ...
7035abbceeaa4b2008985ba72bfd43a914d507b9
77,354
def geomTree(X, k, gamma, n_grid=None, verbose=True): """ Construct a level set tree, from soup to nuts. This function assumes a k-nearest neighbor similarity graph and k-nearest neighbor density estimate, which is less flexible than building the similarity graphy, estimating the (pseudo-) density, constructing th...
e94a914e296d5ef8d1f69abe46730186c542a12f
77,355
def make_ratings_hash(ratings): """ Make a hashtable of ratings indexed by itemId and pointing to the vector (genres, decade) that fully characterize an item. """ rhash = {} # For every rating, check if the relevant item is already in the map. # If not, add it to the map. Key...
e105f08dbdbec544dccdcd299aaf189ef64691b7
77,356
import importlib def get_func(func_name): """Helper to return a function object by name. func_name must identify a function in this module or the path to a function relative to the base 'modeling' module. """ if func_name == '': return None try: parts = func_name.split('.') ...
9ac2dbd03cf4c82c00eb1aa8a4ceb2dc39bc2d08
77,357
def check_repository_modify_status(repo_path): """检查仓库是否有文件修改 :param repo_path 仓库路径 :type repo_path str :example repo_path /tmp/git :rtype result bool :return result 检查结果 True 仓库有文件进行了修改未提交 False 仓库没有文件进行了修改 >>> check_repository_modify_status("`pwd`")#doctest: +ELLIPSIS ...
a39e71eff4b6192d287d625a56ae940087e4ead2
77,358
def hierarchical_cluster(features: np.ndarray, t: float, distance_metric: str = 'cosine', linkage_method: str = 'average', criterion: str = 'maxclust'): """ Perform hierarchical correlation cluster on a given DISTANCE matrix. Args: features: A 2D numpy array (N * P). The N ...
ac8d8a3d51bc0be5f88b6afa10dad34e545de539
77,359
from scipy.ndimage import gaussian_filter def prepare_image(rgb, crop=None, embed=None, white_cutoff=225, gauss_sigma=5, background=0.01): """ Transforms rgb image array into 2D-density and energy Parameters ---------- density : ndarray(width, height) Probability density energy : ndarray...
40dc92bcca7ad2e0b931f83232522a4fd57f9b74
77,360
def predecessor(self, root): """ One step left and then always right """ root = root.left while root.right: root = root.right return root.val
77b22323f4623df3002b9e7d12123d4ee9a98cad
77,361
def create_policy_check(environ, entity, usersign): """ Determine if the user in ``usersign`` can create ``entity`` type. """ try: entity_policy = '%s_create_policy' % entity policy = environ['tiddlyweb.config'][entity_policy] except KeyError: raise ForbiddenError('create pol...
61ec47a0aee97ae134a510ef41767771a680459e
77,362
import tqdm def load_txt_to_list(file_path, spliter=None, terminator="\n"): """ Load file.txt by lines, convert it to list. """ txt_list = [] with open(file=file_path, mode='r', encoding='utf-8') as fi: for i, line in enumerate(tqdm(fi)): if spliter is None: line = line...
d908d44242bd2a091a6bb7deb529da23108eab3d
77,363
def agri_sup_frm_sw(): """ Real Name: b'Agri sup frm SW' Original Eqn: b'MIN("Agri def aftr ab-bn sup", "Tj Div aftr Ab-bn Spill")' Units: b'' Limits: (None, None) Type: component b'' """ return np.minimum(agri_def_aftr_abbn_sup(), tj_div_aftr_abbn_spill())
acd71260641f851312c2bb26ad7890e1bde6b548
77,364
def _get_lang(lang_name: str): """ get language from query parameters param lang_name: name of the language return language """ lang_manager = LangsManager() if not lang_manager.is_support_lang(lang_name): raise ValueError("API not support `lang`={}".format(lang_name)) return ...
495b7c3224043a036e7f116d165f65407069f584
77,366
def get_user_orgs_count(user_stats_dict): """ Gets the count of the orgs that users belong to and populates the onging data structure""" client_orgs = MongoClient(mongoDB_metrics_connection+to_groups) db_orgs = client_orgs.groups orgs_query = db_orgs.groups.find({},{"name":1,"memb.user":1,"_id":0}) ...
c8142fa2e39fdd7740c99be91cb26f9207bc1d06
77,367
def update_graph(gene2graph, cog, signif_struct_info, struct, radius): """Updates the residue neighbor graph based on the current structure. Residues are linked by edges if they are within the provided radius and are on the same gene. Parameters ---------- gene2graph : dict dictionary ...
0c55cc1053924439df934f96e0b660e5f0731b4d
77,368
import torch def psnr( pred: torch.Tensor, target: torch.Tensor, data_range: float = None, base: float = 10.0, reduction: str = 'elementwise_mean' ) -> torch.Tensor: """ Computes the peak signal-to-noise ratio Args: pred: estimated signal target: groun truth signal ...
9370a233cf9a5a75fb0bcaac51bcedcd14e86f34
77,369
def get_rules(rules_module): """ Get rule functions from module :param rules_module: module with rules implementations :return: rule functions """ rules = [] for item in dir(rules_module): if item.startswith("rule"): rules.append(getattr(rules_module, item)) return ru...
41b9428f0893a153700a19f4237453af8910a759
77,370
def format_pun_list(header, entries, footer, *, cnt=1): """ Generate the management list of entries. """ msg = header for ent in entries: msg += '{}) {}\n Hits: {:4d}\n\n'.format(cnt, ent.text, ent.hits) cnt += 1 msg = msg.rstrip() msg += footer return msg
3393c0f01fba1cef412a5b68e1ca180af86b3693
77,371
def Btu_hft2F2W_m2K(x): """Btu/(h-ft^2-F) -> W/(m^2-K)""" return 5.678*x
320d77742f5f62584268e261d145031e2e93c4f3
77,372
def _collect_module_inputs(module_input_map, extra_inputs, directs, dep): """ Put together inputs coming from direct and transitive dependencies. Args: module_input_map: maps labels of dependencies to all the inputs they require extra_inputs: an addition depset of inputs to include directs: i...
8d4f8906042a31c70042433271e8a31fe857dce6
77,373
from pathlib import Path async def delete_note( note_id: str = Path(..., title="The id of the note to delete") ) -> JSONResponse: """Delete a note.""" if ( delete_result := await crud.delete(note_id) ) and delete_result.deleted_count == 1: return Response(status_code=status.HTTP_204_NO...
42a9716ed35020c8ffc4b64f33c8b5cdb50c1a0e
77,374
from datetime import datetime def get_series_datetime(dataset): """ Return a datetime object containing the Series Date and Series Time, or None is they are not in the dataset. """ series_datetime = None if "series_date" in dataset : series_datetime = parse_da(dataset.series_date)...
18c345256a25af1b213a33be8fcab1fc96ce83e1
77,375
import requests def _download_chunk(args): """Download a single chunk. :param args: Tuple consisting of (url, start, finish) with start and finish being byte offsets. :return: Tuple of chunk id and chunk data """ idx, args = args url, start, finish = args range_string = '{}-'.format(start...
eb88e1200fff8d336908d2247e12c46576bb4422
77,376