content
stringlengths
22
815k
id
int64
0
4.91M
def determine_fit_quality(imglist, filtered_table, catalogs_remaining, print_fit_parameters=True): """Determine the quality of the fit to the data Parameters ---------- imglist : list output of interpret_fits. Contains sourcelist tables, newly computed WCS info, etc. for every chip of e...
75,400
def fetch_movies_for(category_id): """ Fetches movies for the selected category Updates the placeholder text for the Movies column :param category_id: :return: index.html """ categories = Category.query.order_by(Category.name).all() selected_category = Category.query.filter_by( c...
75,401
def interp1d(x, y, target): """ return 1d linear interpolation """ return np.interp(target, x, y)
75,402
def get_vm_ip(vmName, poolName): """Get IP address for a VM on a NIMBUS cluster 'vmName' is required. For example, vmName='pgu-repTest-01' """ command = 'NIMBUS=%s /mts/git/bin/nimbus-ctl ip %s' % (poolName, vmName) output = run_cmd_on_pdc(command) print 'Got IP address on %s for %s: %s' % (pool...
75,403
def fin_diff(): """Pytest fixture for basic FiniteDifference class with centered method.""" dic = {"Grid": {"N": 10, "r_min": 0, "r_max": 10}, "Clock": {"start_time": 0, "end_time": 10, "num_steps": 100}, "Tools": {}, "PhysicsModules": {...
75,404
def macula_kernel_64(t, theta, tstart, tend, fmod): """ t: (ndata,) theta: (ntrials, jmax) nspots: int tstart: (mmax,) tend: (mmax,) fmod: (ntrials, ndata) """ x, y = cuda.grid(2) dx, dy = cuda.gridsize(2) pstar = 12 pspot = 8 pinst = 2 pLD = 5 ndata = t.shap...
75,405
def chunks(l, n): """ Yield n successive chunks from l. """ n = (len(l) / n) + 1 for i in xrange(0, len(l), n): yield l[i:i + n]
75,406
def scope_symbols(dfg): """ Returns all symbols used in scopes within the given DFG, separated into (iteration variables, symbols used in subsets). """ iteration_variables = collections.OrderedDict() subset_symbols = collections.OrderedDict() for n in dfg.nodes(): if isinstance(n, dace.g...
75,407
def query(): """ Query the attached TEMPer device via temper-query command and parse the result. """ p = subprocess.run(['/usr/local/bin/temper_query'], stdout=subprocess.PIPE) p.check_returncode() temp = float(p.stdout.decode(encoding='ascii').strip()) return temp
75,408
def cli(title, fields, freespace, size, randomize, bgcolor, fontpath, color, fontsize, padding, dimensions): """ Bingo generator. \n FIELDS: Input bingo fields formatted as CSV string \n TITLE: Title of the Bingo. \n """ entries = list(csv.reader(StringIO(" ".join(i for i in fields))))[0] B...
75,409
def solve(moves, nr=16): """Return program order after doing all the moves. :moves: dance moves, separated by commas :nr: number of programs :returns: program order >>> solve('s1,x3/4,pe/b', nr=5) 'baedc' """ pgms = list(string.ascii_lowercase[:nr]) for move in moves.split(','): ...
75,410
def values(): """Get the full current set of B3 values. :return: A dict containing the keys "X-B3-TraceId", "X-B3-ParentSpanId", "X-B3-SpanId", "X-B3-Sampled" and "X-B3-Flags" for the current span or subspan. NB some of the values are likely be None, but all keys will be present. """ result = {}...
75,411
def sort_flavors(flavors): """ Sorting flavors, flavors with low resources first :param flavors: flavor list in JSON :return: sorted flavor list in JSON """ return sorted(flavors, key=compare_flavors)
75,412
def convert_file_encoding(filename: str, target_encoding: str): """Convert the text encoding of the file to the desired one. The file may already be in the target encoding, in which case nothing is changed. Parameters ---------- 1. filename : str - The full path and name of the file in ques...
75,413
def test_decorator(f): """Decorator that does nothing""" return f
75,414
def get_audio(file_path: str) -> mutagen.File: """Get audio object from file""" return mutagen.File(file_path)
75,415
def find_machine_id(agents, host): """ :param agents: Array of mesos agents properties (machine_id + additional infos) :type: list of dict :param host: Host to find. Can be ip, hostname of agent ID :type: string :returns: a machine_id :rtype: dict """ for agent in agents: # d...
75,416
def get_unit_values(ds_inds, ds_vals, dim_names=None, all_dim_names=None, is_spec=None, verbose=False): """ Gets the unit arrays of values that describe the spectroscopic dimensions Parameters ---------- ds_inds : h5py.Dataset or numpy.ndarray Spectroscopic or Position Indices dataset d...
75,417
def test_team_selection_event(): """Test TeamSelectionEvent""" log_line = ''.join([ 'L 01/12/2013 - 00:57:01: "foobar<21><STEAM_0:0:12345><>" ', 'joined team "Spectators"', ]) check_event(generic.TeamSelectionEvent, log_line)
75,418
def test_email_renderer(): """Test the email rendering helper.""" template = email_tools.render_email( 'report.html', domain='www.example.com', new=(('www.examp1e.com', '127.0.0.1', 'http://dnstwister.report/analyse/1234'),), updated=(('www.exampl3.com', '127.0.0.1', '127.0...
75,419
def get_connection_string(include_password=True): """ Return the connection string based on the configuration specified in the `merlin.yaml` config file. """ broker = CONFIG.broker.name config_path = CONFIG.celery.certs if broker not in BROKERS: raise ValueError(f"Error: {broker} is...
75,420
def unzip_fgdc(): """ Assume a directory structure as can be understood from the simple code below. """ to_dir = "data/fgdc/" from_dir = "data/archive/" for file_ in os.listdir(from_dir): full_to_dir = to_dir + re.findall("20[01][0-9]", file_)[0] if not os.path.isdir(full_to...
75,421
def train(train_path, learning_rate, latent_dim, batch_size=128, device='cpu', num_iters=10000, **kwargs): """ Train a 64x64 DCGAN network. """ dis = DCGANDiscriminator().to(device) gen = DCGANGenerator(nz=latent_dim).to(device) image_size = kwargs.get('image_size', (64, 64)) lo...
75,422
def _create_Particles_dict() -> Dict[str, dict]: """ Create a dictionary of dictionaries that contains physical information for particles and antiparticles that are not elements or ions. The keys of the top-level dictionary are the standard particle symbols. The values of the top-level dictiona...
75,423
def load_from_secretsmanager(environment=None): """ Load the secrets into a dictionary, skip if no environment available """ if environment is None: try: environment = environ["MICROCOSM_ENVIRONMENT"] except KeyError: # noop return load_from_dict(dict...
75,424
def _dfs_out(atom): """Traverse an Atom's outgoing neighborhood iteratively with a depth-first search.""" atoms = [atom] stack = list(atom.out) while stack: atom = stack.pop(0) atoms.append(atom) stack[0:0] = atom.out return atoms
75,425
async def test_setup_auth_failed(setup_component, hass, config_entry, smarttub_api): """Test setup when the credentials are invalid.""" smarttub_api.login.side_effect = LoginFailed config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) assert config_entry.state ...
75,426
def _read_csv_with_fallback_encoding(filepath, dtypes=None): """read a CSV to a pandas DataFrame using default utf-8 encoding, but try alternate Windows-compatible cp1252 if unicode fails """ try: logger.info('Reading CSV file %s' % filepath) df = pd.read_csv(filepath, comment='#', dty...
75,427
def _ensure_pt_install(): # pylint: disable=g-statement-before-imports """Attempt to import Pytorch, and ensure its version is sufficient. Raises: ImportError: if either Pytorch is not importable or its version is inadequate. """ try: import torch except ImportError: # Print...
75,428
def cnn_model(features, labels, mode): """CNN model function. Arguments: features -- Batch features from input function labels -- Batch labels from input function mode -- train, eval, predict, instance of tf.estimator.Modekeys Returns: The estimator spec depending on the chosen mode """ ...
75,429
def test(): """This is a testing""" import sys from Process_Partial_Dos import DOS from Read_File import read_DOS_file, parse_setting_file dos1 = DOS(read_DOS_file("DOS123")) dos2 = DOS(read_DOS_file("DOS052")) print("total_dos_cal_test ---> write into total_dos_cal_test") dos1.cal_...
75,430
def __kill(): """Kills the server if it isn't dead yet""" ret_code = proc.poll() if ret_code == None: proc.kill() proc.wait()
75,431
async def test_receive_payment_meets_travel_rule_threshold_receiver_kyc_data_is_rejected_by_the_sender( currency: str, travel_rule_threshold: int, target_client: RestClient, stub_client: RestClient, ) -> None: """ Test Plan: 1. Create sender account with minimum valid kyc data and enough ba...
75,432
def evaluate_deepar(config): """ Pass DeepAR to evaluate_gluon""" from gluonts.model.deepar import DeepAREstimator model = DeepAREstimator(freq=config['freq'], use_feat_dynamic_real=config['params'].get('use_feat_dynamic_real', False), predic...
75,433
def create_classification_dataset(n_samples, n_features, n_informative, n_redundant, n_repeated, n_clusters_per_class, weights, n_classes, random_state=None): """ Creates a binary classifier dataset :param n_samples: number of observations :param n_features: number of ...
75,434
def median(data, interval=34): """Calculate the median and ``interval`` size quartile uncertainties. Parameters ---------- data: numpy.nparray Needs to be an 1D array. interval: int The percentile (to one side) you want for uncertainties. Returns ------- numpy.nparray...
75,435
def npgettext(context, singular, plural, num, **variables): """Translates `singular` and `plural` and returns the appropriate string based on `number` and `context`. """ return _translate('npgettext', context, singular, plural, num, **variables)
75,436
def load_data(in_path, out_path, in_vocab, out_vocab, max_input_len=56, max_output_len=66): """Loads the data from the given path and preprocesses the data by converting the tokens into ID's using the vocab dictionary. Additionally, token...
75,437
def is_compatible(subreddit, index_type, status): """ Checks if the submission exists and belongs to the required type of subreddit """ if status == 'Exists': if index_type == 'AV': keys = list(subreddits[index_type].keys()) for key in keys: if s...
75,438
def makePoint(x, y): """ create a point or a dict """ if type(x) == float: return Point(x, y) else: return { 'x': x, 'y': y }
75,439
def search_page(): """Page Search DICOM Instances""" def get_unique_series_ids(instances): """Retrieve the list of series ID related to the instances""" result = [] for instance in instances: series_id = instance[1] if not series_id in result: result.append(series_id) return r...
75,440
def _tack_on_child(session, parent_t2: Task_v2, child_t1: Task_v1): """ Merge a Task, its scopes, and its child Tasks Key thing is to treat linkages as the data object, and then dedupe them when it's closer to DB commit time. We're merging them via markdown formatting anyway, it's not like there's ...
75,441
def _insert_rows_with_retries(bq, bq_table, bq_rows): """Insert rows to bq table. Retry on error.""" # BigQuery sometimes fails with large uploads, so batch 1,000 rows at a time. for i in range((len(bq_rows) / 1000) + 1): max_retries = 3 for attempt in range(max_retries): if big_...
75,442
def post_new(): """ Post a new snippet and redirect the user to the generated unique URL for the snippet. :param code: (form) required snippet text, can alternativaly be sent as a Multi-Part utf-8 file :param lang: (form) optional language :param maxusage: (form) optional maximum download of th...
75,443
def convert_confusion_matrix_to_MCM(conf_matrix): """ Converts a confusion matrix into the MCM format for precision/recall/fscore/ support computation by sklearn. The format is as specified by sklearn below: In multilabel confusion matrix :math:`MCM`, the count of true negatives is :math:`MCM_{:,0,0...
75,444
def test_mean_to_mid_with_uneven_distribution(): """Tests that the CvtToFuzzyMeanToMid command works when the largest raw value is much larger than other values""" arr = numpy.ma.array([0, 25, 88, 999], dtype=float) command = create_command_with_result("Result", arr) answer = numpy.ma.array([-1.0, -0.4...
75,445
def test_conllable_throws_exception(): """ Test that the base Conllable implementation throws an exception. """ c = Conllable() with pytest.raises(NotImplementedError): c.conll()
75,446
def setup(hass, config): """Setup the Hello State component. """ _LOGGER.info("The 'hello state' component is ready!") # Get the text from the configuration. Use DEFAULT_TEXT if no name is provided. text = config[DOMAIN].get(CONF_TEXT, DEFAULT_TEXT) # States are in the format DOMAIN.OBJECT_ID ...
75,447
def render_report(jobs_with_error): """Build a text report for the jobs with errors """ output = [] for job in jobs_with_error: errors_count = job.info.get('errors_count', 0) close_reason = job.info.get('close_reason') job_id = job.info["id"].split('/') url = 'https://ap...
75,448
def _prune_files(expt, session, files, delete=True): """Delete or mark as not present the database entries that are not present in the list of files """ if len(expt.ncfiles) == 0: # No entries in DB, special case just return as there is nothing # to prune and trying to do so will raise e...
75,449
def in_range(target, bounds): """ Check whether target integer x lies within the closed interval [a,b] where bounds (a,b) are given as a tuple of integers. Returns boolean value of the expression a <= x <= b """ lower, upper = bounds return lower <= target <= upper
75,450
def intervals_remove( subparser: argparse._SubParsersAction = None, args: argparse.Namespace = None ): """Forward to /intervals/remove?id={identifier} Args: subparser (argparse._SubParsersAction, optional): Parser for command 'intervals-remove'. Defaults to None. args (argpa...
75,451
def get_default_settings(): """Return a dict of default values.""" default_settings = { 'debug': False, 'parse_lines': False, 'output_file': False, 'output_mqtt': False, 'frequency': 433748300, 'binary': "/usr/bin/rtl_433", 'file_path': "/tmp/433sensors", ...
75,452
def score_sent(text, sent_data, normalize=False): """ Evaluate the data """ test_sent = next(iter(sent_data.values())) sents = np.zeros_like(test_sent).astype(np.float).reshape(-1) tokens = word_tokenize(text.lower()) for token in tokens: try: sent = np.array(sent_data[t...
75,453
def close_window(window): """Close an X window.""" xkill('-id', window)
75,454
def main(argv): """Runs main code for result analysis Parameters: argv (array): console arguments if given Returns: None """ # # open rasters # fgc_pred = gdal.Open( # FCG_SRC + "rasterized_generated.tif", gdal.GA_ReadOnly) # fgc_true = gdal.Open( # FCG_SRC +...
75,455
def is_master_process(rank=0): """Check if master process or not..""" if not dist.is_initialized(): return True if rank == dist.get_rank(): return True return False
75,456
def test_integ_copy_and_rename(source, target, default_transfer_config): """Test for integrating a copy and move into single target.""" file1 = source.local_path("inside/file1") file2 = source.local_path("inside/file2") file3 = source.local_path("inside/file3") file1.write_bytes(b"Test content") ...
75,457
def _parse_id(kwargs, _not=False) -> Iterable[str]: """Find the id key, if ``_not`` is True, return the keys that are not the id key. """ for k in kwargs.keys(): if _not is False and 'id' in k: yield k elif _not is True and 'id' not in k: yield k
75,458
def test_zmq_with_poller(count): """single thread zmq with poller""" print(".", end="", flush=True) ctx = zmq.Context() router = ctx.socket(zmq.ROUTER) router.bind("tcp://127.0.0.1:*") address = router.getsockopt(zmq.LAST_ENDPOINT).rstrip(b"\0") dealer = ctx.socket(zmq.DEALER) dealer.con...
75,459
def _parse_path_segment(acc, segment): """ Parse a single path segment. If the segment is an identifier or wildcard, it's constraint is also derived. :param _ParsedRoutePath acc: Accumulated parse result. :param unicode segment: Path segment. :rtype: _ParsedRoutePath """ match = _t...
75,460
def valid_chrom(): """ Valid chromosomes should be 1 - 22, X, Y, and MT. Validity is not checked or enforced """ return '1'
75,461
def annotateTree(bT, fn): """ annotate a tree in an external array using the given function """ l = [None]*bT.traversalID.midEnd def fn2(bT): l[bT.traversalID.mid] = fn(bT) if bT.internal: fn2(bT.left) fn2(bT.right) fn2(bT) return l
75,462
def plotRadiants(pickle_trajs, plot_type='geocentric', ra_cent=None, dec_cent=None, radius=1, plt_handle=None, label=None, plot_stddev=True, **kwargs): """ Plots geocentric radiants of the given pickle files. Arguments: pickle_trajs: [list] A list of trajectory objects loaded from .pickle files. ...
75,463
def test_gammas(): """Checking: Cp/Cv = γ·g/(γ·g-Γ²)""" d = {} for key in ['g', 'Gamma', 'gamma_3']: d[key] = tab.q[key](X,Y) F0 = tab.q['Cp'](X,Y)/tab.q['Cv'](X,Y) F1 = d['gamma_3']*d['g']/(d['gamma_3']*d['g'] - d['Gamma']) yield np.testing.assert_allclose, F0, F1, 1e-5
75,464
def arc_to_parquet( context: MLClientCtx, archive_url: Union[str, Path, IO[AnyStr]], header: Optional[List[str]] = None, target_path: str = "", name: str = "", chunksize: int = 10_000, log_data: bool = True, add_uid: bool = False, key: str = "raw_data", ) -> None: """Open a file/...
75,465
def read_o01(fn): """Read a formatted output file of the ENVIRO program and extract the electric and magnetic fields across the model's transect, returning them in a DataFrame args: fn - str, path to the target file, must have a ".o01" extension returns: df - DataFrame of fields across the t...
75,466
def median_squared_percentage_error( y_true, y_pred, horizon_weight=None, multioutput="uniform_average", square_root=False, symmetric=True, **kwargs, ): """Median squared percentage error (MdSPE) or square root version. If `square_root` is False then calculates MdSPE and if `square...
75,467
def error_response(ex): """ Handles any errors raised in the execution of the backend Builds a JSON representation of the error messages, to be handled by the client Complies with the Swagger definnition of an error response """ if 'code' in ex: code = ex.code elif 'errno' in ex: ...
75,468
def simulate_from_psd(S_func, m=2000, dt=1, ymean=0, sigma=0.2, size=1, seed=None, **args): """ Simulate light curve given input times, model PSD, and ymean S_func: model PSD function S(omega) [note omega = 2 pi f] m: number of bins [output will have length 2(m - 1)] dt: equal spacing in time ...
75,469
def eta_error_no_initial(ratio, k1, k2, k3, p1, p2, p3, sratio, sp1, sp2, sp3): """ :param ratio: :param k1: :param k2: :param k3: :param p1: :param p2: :param p3: :param sratio: :param sp1: :param sp2: :param sp3: :return: """ aux0 = ((((-((1. +ratio) ** -2....
75,470
def ExecuteJarTool(java_bin, jar_dir, jar_name, classname, flags=None, *args): """Execute a given jar with the given args and command line. Args: java_bin: str, path to the system Java binary jar_dir: str, the directory the jar is located in jar_name: str, file name of the jar under tool_dir classn...
75,471
def preprocess_request(): """Before processing each request, make the current user available to everyone via flask g object, and store activity time""" db.connect() g.user = User.get( User.id == int( session[ 'user_id' ] ) ) if 'user_id' in session else None if g.user is not None: g.user.update_acti...
75,472
def beta_gen_lasso(p): """ Generate the linear model coefficient in constrained lasso case. @param p int: dimension. @return np.array(p,1): the coefficient. """ cardi = 0.005 return np.array([0]*int(p-int(cardi*p)) + [1]*int(cardi*p))
75,473
def extract_bibliographic_data(node: ET.Element) -> Optional[Dict]: """ Find bibliographic data like title, authors and editors """ data = dict() title = node.find(f"{TEI}titleStmt") if not title is None: extract_title(title, data) date = node.find(f"{TEI}publicationStmt/{TEI}date")...
75,474
def adjust_brightness(input: T, *args: Any, **kwargs: Any) -> T: """TODO: add docstring""" ...
75,475
def whiten( strain, dt, phase_shift=0, time_shift=0, interp_psd: Optional[np.ndarray] = None, psd: Optional[np.ndarray] = None, ): """Whitens strain data given the psd and sample rate, also applying a phase shift and time shift. Args: strain (ndarray): strain data in...
75,476
def hrm_human_resource_onaccept(form): """ On-accept for HR records """ if "vars" in form: # e.g. coming from staff/create vars = form.vars elif "id" in form: # e.g. coming from user/create or from hrm_site_onaccept vars = form elif hasattr(form, "vars"): # SQLFO...
75,477
def main(): """Cloudflare API code - example""" cf = CloudFlare.CloudFlare() zones = cf.zones.get(params={'per_page':50}) for zone in zones: zone_name = zone['name'] zone_id = zone['id'] settings_ipv6 = cf.zones.settings.ipv6.get(zone_id) ipv6_on = settings_ipv6['value']...
75,478
def separator(node, label=None): """Create a visual separator for the channel box using a dummy attribute. This create a maya enum attribute at the last position of the channel box. The name section will be left empty, and the enum section will be filled with the value specified in the ``label`` param...
75,479
def find_operating_point( x: np.ndarray, y: np.ndarray, z: np.ndarray, required_x: float ) -> Tuple[float, Optional[float], Optional[float]]: """ Find the highest y (and corresponding z) with x at least `required_x`. Returns ------- x, y, z The best operating point (highest y) with x at...
75,480
def test_160912_missing(dbcursor): """see why this series failed in production""" for i in range(4): prod = vtecparser(get_test_file("RFWVEF/RFW_%02i.txt" % (i,))) prod.sql(dbcursor) warnings = filter_warnings(prod.warnings) assert not warnings
75,481
def parse_mailboxes(data): """ Parse a raw data returned by conn.list() and return a list of Mailbox objects. :param data: Raw mailbox data as returned by conn.list() :type data: ``list`` """ for line in data: mailbox = parse_mailbox(line) yield mailbox
75,482
def save_request(url, output_file): """ Attempts to read from file. If there's no file, then it will save the contents of a url in json/html """ # check for cached version try: with open(output_file) as fp: data = fp.read() try: data = json.loads(d...
75,483
def load_dependency_files(path): """ Recursively (if necessary) gather all the manifests referenced by the starting_path and return as list :param starting_path: :return: """ f = load_dependency_file(path) files = [f] # recursively call if f.dparser: for file in f.dparser.re...
75,484
def p_extract_2(t): """ extract : R_EXTRACT S_PARIZQ optsExtract R_FROM columnName S_PARDER """ temp = expression.C3D("", "", t.slice[1].lineno, t.slice[1].lexpos) t[0] = code.FunctionCall( "extract", [t[3], temp, t[5]], isBlock, newTemp(), t.slice[1].lineno, ...
75,485
def accuracy(pred, target, topk): """accuracy = top-k correct""" correct_k = topk_correct(pred, target, topk) accuracy_list = [(x / pred.size(0)) * 100.0 for x in correct_k] return accuracy_list
75,486
def load_tests(loader, tests, ignore): """Run doctests and file-based doctests.""" tests.addTests(doctest.DocTestSuite(server)) return tests
75,487
def get_avg_heart_rate(envelope=None, sampling_rate=1000.): """Compute average heart rate from the signal's homomorphic envelope. Follows the approach described by Schmidt et al. [Schimdt10]_, with code adapted from David Springer [Springer16]_. Parameters ---------- envelope : ar...
75,488
def busqueda_local(solucion_inicial, evaluacion, obtener_vecinos, T_max, T_min, reduccion): """ Simulated Annealing. """ from random import random solucion_mejor = solucion_actual = solucion_inicial evaluacion_mejor = evaluacion_actual = evaluacion(solucion_actual) s...
75,489
def _get_aggregate_funcs( df: DataFrame, aggregates: Dict[str, Dict[str, Any]], ) -> Dict[str, NamedAgg]: """ Converts a set of aggregate config objects into functions that pandas can use as aggregators. Currently only numpy aggregators are supported. :param df: DataFrame on which to perform ag...
75,490
def distance_weights( X: "npt.ArrayLike", y: "npt.ArrayLike", grouping: "Optional[npt.ArrayLike]" = None, ) -> np.ndarray: """ Compute weights based on Manhattan distance of the X-values. This function ignores information in the y-values. Examples: >>> import numpy as np >>> from selec...
75,491
def flatten_array(grid): """ Takes a multi-dimensional array and returns a 1 dimensional array with the same contents. """ grid = [grid[i][j] for i in range(len(grid)) for j in range(len(grid[i]))] while type(grid[0]) is list: grid = flatten_array(grid) return grid
75,492
def plot_2d(*plotters: Callable) -> Tuple: """Plot multiple spatial objects in 2D.""" fig, ax = plt.subplots() for plotter in plotters: plotter(ax) return fig, ax
75,493
def cosine_sim(x1, x2, dim=1, eps=1e-8): """Returns cosine similarity between x1 and x2, computed along dim.""" x1 = torch.tensor(x1) x2 = torch.tensor(x2) w12 = torch.sum(x1 * x2, dim) w1 = torch.norm(x1, 2, dim) w2 = torch.norm(x2, 2, dim) return (w12 / (w1 * w2).clamp(min=eps)).s...
75,494
def find_files(path, exts=None): """ 查找路径下的文件,返回指定类型的文件列表 :param: * path: (string) 查找路径 * exts: (list) 文件类型列表,默认为空 :return: * files_list: (list) 文件列表 举例如下:: print('--- find_files demo ---') path1 = '/root/fishbase_issue' all_files = find_files(path...
75,495
def cut_descendants(D, nodes, page_tree): """Given the distance matrix D, a set of nodes and a PageTree perform a multicut of the complete graph of nodes separating the nodes that are descendant/ascendants of each other according to the PageTree""" index = {node: i for i, node in enumerate(nodes)} ...
75,496
def plot_logs(data, delz, borehole: int=0, apa=0.7, z_extent: float=6000., col_dict: dict={}): """Plot temperature logs of simulated and observed temperatures with lithologies as background Args: data (pandas Dataframe)): dataframe with borehole temperature data and cell values, i.e. i,j,k delz...
75,497
def rotate_around_point(xy, radians, origin=(0, 0)): """Rotate a point around a given point. I call this the "high performance" version since we're caching some values that are needed >1 time. It's less readable than the previous function but it's faster. """ x, y = xy offset_x, offset_...
75,498
def test_model_multiple(model_generator, train_dataset, test_dataset, epochs=50, num_tries=10, \ loss_name="mean_squared_error", measure_name="val_mean_squared_error", \ print_data=False): """Testing of model in multiple tries""" loss_history_sum = np.single(0) ...
75,499