content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def gomc_sim_completed_properly(job, control_filename_str): """General check to see if the gomc simulation was completed properly.""" job_run_properly_bool = False output_log_file = "out_{}.dat".format(control_filename_str) if job.isfile(output_log_file): with open(job.fn(f"{output_log_file}"), ...
542c22836e22a3cc97a38744959dcb21b833c7a0
73,600
from pathlib import Path from typing import Dict from typing import Any import warnings def fetch_openml_dataset(dataset_id: int, data_directory: Path = get_data_dir(), ) -> Dict[str, Any]: """ Gets a dataset from OpenML (https://www.openml.org), or from t...
b26eea4057bbe45d72314de43b20756aec8e10ad
73,601
import json def build(**kwargs): """ build message, return dict """ t = Template(template()) content = t.substitute(**kwargs) return json.loads(content)
1e9dd75f385e0cb8f5cfe92f04a4823c98dd70a4
73,602
import torch def gcxgcywh_to_cxcywh(boxes, anchors): """ Decode bounding box coordinates predicted by the model, since they are encoded in the form mentioned in the encoding function. They are decoded into center-size XYWH coordinates. :param boxes: encoded bounding boxes, i.e. output of the mod...
c4dda7ea9696fb4620079f06a59e7e672e29d8d3
73,603
import sqlite3 def connect_db(): """Connects to the specific database.""" rv = sqlite3.connect(db_uri, uri=True) rv.row_factory = sqlite3.Row return rv
79734752d6fbae92f736f59fa40d9b5ab0090ca6
73,604
from unittest.mock import patch async def setup_unifi_integration( hass, config, options, clients_response, devices_response, clients_all_response ): """Create the UniFi controller.""" hass.data[UNIFI_CONFIG] = [] hass.data[UNIFI_WIRELESS_CLIENTS] = unifi.UnifiWirelessClients(hass) config_entry = ...
d031e0244cfe315c66b137fd7967d40cfef7a385
73,605
def mean(data, key=None): """ mean with data type check :param data: points :param key: key function :return: """ if key is not None: data = [key(point) for point in data] data = filter(lambda x: isinstance(x, (int, float, long)), data) if len(data) < 1: return None ...
92e7142628706a467875b03d88dcb1a748e85068
73,606
def SqrNorm(x): """Square of the norm. :param x: return sum(x*x) :return: return sum(x*x) """ return sum(x*x)
03f35a7395ba74981eace38b634a14210932cffd
73,607
from pathlib import Path def create_h5temp_global() -> Path: """Create temporary global HDF5 rawfile. Returns: Path: Path object of filename. """ fn = Path("/tmp/data/MXD13A2.006.VIM.h5") rows = 2000 cols = 7200 with h5py.File(fn, "a", driver="core", backing_store=True) as h5f...
02f884b613f2da23ce2344adf70e9f9707cab3a9
73,608
from typing import Tuple from typing import Sequence def sample_text_elements(workspace_id: str, dataset_name: str, sample_size: int, filter_func, remove_duplicates=False, random_state=None) -> Tuple[Sequence, int]: """ :param sample_size: if None, return all elements without samplin...
a603cd188bc5d593abb20b51fd99286bf49ac53d
73,609
import socket def create_connection(server=None, port=None, timeout=None, use_ssl=False): """Create a socket or a secure ssl socket. Hopefully some day such functionality will be included in python3. :returns socket :rtype socket.SocketType """ # based on socket.create_connection() if us...
8596d3dc7c0cf7e75933618c0c302f5ddb63a420
73,610
def image_can_fit_message(image, message): """Returns whether or not the given image can accommodate the given message""" # Get the number of bands per pixel. This is how many bytes are used to represent each pixel. # For example, an RGBA pixel will have 4 bands, giving us four pixels to update. pixel_...
f23a17234b9575fbca702a918f8f257ebb29e927
73,611
def build_cudnn_layers(layers, units, activation, memory_cell, direction, dropout, name): """ Builds layers optimized for CuDNN if hparams.use_cudnn_layers is True. Args: layers: The number of layers. units: The number of units per layer. activation: Activation function to ...
872b86984d2771e0b9c6425534ef567789a28e7d
73,612
from typing import Union from datetime import datetime def get_next_trading_date(date: Union[str, datetime.date, datetime.datetime, pd.Timestamp], n:int=1) -> pd.Timestamp: """ 获取指定日期之后的第 n 个交易日 :param date: 指定日期 :param n: 第 n 个交易日 :example: .. code-block:: python3 ...
e177529697377be8c5c86c7bd05b75419a65e9f4
73,613
def new_superuser(db, new_superuser_factory): """Return a new superuser""" return new_superuser_factory()
7b0751788c9aea1cd37b7e26deb5a7f6e1d6a35f
73,614
def _parse_numpy_pixeltype_from_string(s): """ example: "image_FLOAT_3D.nii.gz" -> 'float32' """ if 'UNSIGNEDCHAR' in s: return 'uint8' elif 'CHAR' in s: return 'int8' elif 'UNSIGNEDSHORT' in s: return 'uint16' elif 'SHORT' in s: return 'int16' elif 'UNSIG...
8066c9eab8b31fa290ac68d44b6bd448a3a689de
73,615
def _compute_distance(x1, x2, mean_vector, epsilon=0.0000001): """ Compute distances between data points by using L1 on normalized data : sum(abs(x1-x2)/(mean_vector+epsilon)) Parameters ---------- x1 : array First vector x2 : array Second vector mean_vector : array ...
358c728862703dd4b83ec423caf69910a51bc1f7
73,616
def scan(name, work_queue, result_queue): """Loads data into work_queue, then gets results from result_queue.""" try: with open(name, 'rb') as f: for i in read_in_chunks(f): work_queue.put(i) except IOError: return 'Error' else: work_queue.join() ...
efcc9309ea7c3b229489df209e2a797cf8d62ba2
73,617
from vtk import vtkImageBlend def combine_images(*images): """ Layer images onto each other (centered) and return the output """ width, height = 0, 0 for i in images: new_w, new_h, _ = i.GetDimensions() if new_w > width: width = new_w if new_h > height: ...
630a141f26a2347710f9eb851fa04ffe700a1a0f
73,618
def calc_dist_folded(x,y,z,unitcells,shifts=None,matrix=False,npt=False): """New: take into account pbc danger of accumulative error x -- x-coordinates of positions, ntime x natom y -- y-coordinates of positions, ntime x natom z -- z-coordinates of positions, ntime x natom unitcells -- array wi...
29b9f925df52c5a548be2224d680005a9691a25a
73,619
def ortho(modes): """\ Orthogonalize the given list of modes. """ N = len(modes) A = np.array([[np.vdot(p2,p1) for p1 in modes] for p2 in modes]) print 'A.shape ',A.shape e,v = np.linalg.eig(A) print 'e', e print 'v', v print v[:,0] ei = (-e).argsort() print 'ei', ei ...
1aa604023614fe0415cf4bb20bdcb600bf18e791
73,620
def get_databases_list(server_uri, query): """ List databases on a specified MySQL server Arguments: server_uri : URI of MySQL server e.g. mysql://user@host:3306/ query : optional regular expression to filter databases e.g. .*_core_.* """ if db_uri.startswith('mysql') is False: r...
7ebd266b08712d3ba1b5bcaac4271e0e669140cf
73,621
import re def remove_superscripts(word: str) -> str: """ This function removes all superscripts from a given word. :param word: A given word :return: The given word stripped from superscripts. """ rx = '[' + re.escape(''.join(SUPERSCRIPTS_TO_UNICODE_CHARS.keys())) + ']' return re.sub(rx, ...
6cfbb0d4cbe64c9ec488c64adad8d1f6941afaa7
73,622
import urllib import json def get_articles(id): """Function to retrieve news sources list from the News api""" get_articles_url ='https://newsapi.org/v1/articles?source={}&apiKey={}'.format(id,api_key) with urllib.request.urlopen(get_articles_url) as url: get_articles_data = url.read() ...
dfcbfcc48d8739cb6e9a69692604704cbf7333c4
73,623
import os def execute(args): """Executes the ``delete`` command.""" def stdout(message, end='\n'): # print a message to stdout only if not in quiet mode if args.quiet: return print(message, end=end) def proceed(): # returns a bool for whether to proceed with t...
8971fb3fbbb74376c5bada17f666da51b98a9ea4
73,624
def set_zenangle(profs, zen=None): """Set zenith angles to a new value. If zen is missing, angles cycle in steps of 10 degrees between 0 and 70 over the profile set.""" if zen: zenlist = [zen] else: zenlist = range(0, 71, 10) for p in range(profs['nprof']): profs[p]['zena...
41d7099e7eb7ac9da1532c28be00b1a574e84e6e
73,625
def preprocess(X): """ Optional preprocessing for secondary data format. @param X: list of lists of lists (glogs, function calls, function call + attributes) """ for i in range(len(X)): for j in range(len(X[i])): X[i][j] = ' '.join([str(x) for x in X[i][j]]) X[i] = '\n'.j...
b759c0353dfeb5c2d4292fd541c8dba507c1ccea
73,626
import requests from bs4 import BeautifulSoup def question_info_get(qid): """ 获取问题的标签 Parameters ---------- qid : int question id. Returns ------- keywords:list 问题关键词 """ headers = { "User-Agent": "", "Connection": "", "Accept": "", "Accept-La...
fb5f1d6bf41a267237f24d677e43c51c474a90f7
73,627
def initialize_logger(options): """Initialize logger instance.""" # Default of None means to use colorama's autodetection to determine whether or not to use color color = None if options.get("force_color"): color = True if options.get("no_color"): color = False enable_logging(ve...
041b9df2be0ce015aa79650b4eb0599c1ef5ae12
73,628
from typing import Tuple def filter_gaussian_mean(X: np.ndarray, eps: float = 0.1, tau: float = 0.1, cher: float = 2.5, use_randomized_svd: bool = True, debug: bool = False, ...
20ec94381d1f86640c7f20f921e23be843b60dca
73,629
def get_registration_extension_form(*args, **kwargs): """ Convenience function for getting the custom form set in settings.REGISTRATION_EXTENSION_FORM. An example form app for this can be found at http://github.com/open-craft/custom-form-app """ if not getattr(settings, 'REGISTRATION_EXTENSION_FORM...
d07155c013ea62ce1c8aa96bbab2b2fa66b15633
73,630
def _add_one_hot_encoding(df, skip_one_hot_columns=None, one_hot_columns=None): """ integer columns are converted to onehot columns. This is helpful in gradient based models LR,NN. Returns a dict mapping old column to new column names. """ new_columns_dict = {} dtypes_df = df.dtypes if one...
4ea21a4383ef921848594e387ba650c72234850e
73,631
import yaml def read_config(filename): """Read configuration file. :param filename: Path to configuration file. """ with open(filename) as f: params = yaml.safe_load(f) return params
7fb88e746c7cdc234a648a3a6216fa49f682f9d9
73,632
def reverse_dict(d): """Reverses direction of dependence dict >>> d = {'a': (1, 2), 'b': (2, 3), 'c':()} >>> reverse_dict(d) # doctest: +SKIP {1: ('a',), 2: ('a', 'b'), 3: ('b',)} :note: dict order are not deterministic. As we iterate on the input dict, it make the output of this function d...
95bd1f427a4e6635b678e129c8f2d69b4b083f9f
73,633
def compute_absolute_power(freqs, powers, band, method='sum'): """Compute absolute power for a given frequency band. Parameters ---------- freqs : 1d array Frequency values. powers : 1d array Power spectrum power values. band : list of [float, float] Band definition. ...
92db5c6b62bd778b708168de85277265682c5da8
73,634
from typing import Optional def get_server_trust_group(location_name: Optional[str] = None, resource_group_name: Optional[str] = None, server_trust_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> Awaitab...
8e84a2d0d0b0ac3a93bb9bec1cd54c3bfaadf455
73,635
import os def load_model(path, run_id=None): """ Load a H2O model from a local file (if run_id is None) or a run. This function expects there is a h2o instance initialised with `h2o.init()`. """ if run_id is not None: path = mlflow.tracking._get_model_log_dir(model_name=path, run_id=r...
29e6ceee62901aa093ee409adf4295d40f6ce207
73,636
def get_csr(ttl=None, common_name=None, locality=None, country=None, province=None, organization=None, organizational_unit=None): """Generate a csr for the vault Intermediate Authority Depending on the configuration of the CA signing this CR some of the fields embedded in the CSR ma...
f3362a7ba941e2f625da2badd3dd1fddb2894062
73,637
def set_unauthorized(nxt: HTTPFunc, ctx: HTTPContext) -> Future[HTTPContext | None]: """Sets response status code to UNAUTHORIZED. Args: nxt (HTTPFunc): to run next. ctx (HTTPContext): to process. """ return set_status(UNAUTHORIZED)(nxt, ctx)
60b9bda0b1db5426f7ec6d535c5ab4b5fe458ed8
73,638
from typing import List from typing import Dict def flatten_dict(d) -> List[Dict]: """ Use this helper functon to flatten a dict holding API response data and namespace the attributes. """ def expand(key, val): if isinstance(val, dict): return [(key + "." + k, v) for k, v in f...
be0f0df42048276e1c16cfcf117de4c7d096e7be
73,639
def argmax(array): """Return the index of the minimum element of an array. Examples -------- >>> _argmin(np.array([1,-1,2,3])) (3,) >>> _argmin(np.array([[0,1],[2,1]])) (1, 0) """ return np.unravel_index(np.argmax(array), array.shape)
d3e4914fd00eb13cc91c53159f7b95c9d92359b8
73,640
def spectroscopic2name(el,roman): """ Convert from spectroscopic notation, e.g. Fe XI to 'fe_11'. Parameters ---------- el : `str` Elemental symbol, e.g. Fe for iron roman : `str` Roman numeral spectroscopic symbol """ elu = el.lower() romanu = roman.upper() idx...
ca48b58f525333b4a9c1d5ae475a2c752dcc4c10
73,641
def poly_fit(traj, traj_len=30, threshold=0.002): """ Input: - traj: Numpy array of shape (2, traj_len) - traj_len: Len of trajectory - threshold: Minimum error to be considered for non linear traj Output: - int: 1 -> Non Linear 0-> Linear """ t = np.linspace(0, traj_len - 1, traj_le...
16daa3f38fd8b0c073dbe014585e29aade3e04b9
73,642
def get_all_classes_properties_numerical(endpoint=None): """ search for all class/property combinations with numerical objects. here we are relying on the defined structure using rdfs:range and rdfs:domain (TBOX) and not on the data level :param endpoint: :return: a list of class/property combinatio...
3ab48c9b38ce29a5f63295750fe5130a2cb75ec4
73,643
def dup(integer): # real signature unknown; restored from __doc__ """ dup(integer) -> integer Duplicate an integer socket file descriptor. This is like os.dup(), but for sockets; on some platforms os.dup() won't work for socket file descriptors. """ return 0
aac98f8c767d2224b3949aea4aafcb83d0c0ee1c
73,644
def evaluate(session, loss_op, accuracy_op, feed_dict): """Evaluate the model. Computes the loss and accuracy with repeated calls with the specified feed_dict. Halts, when session.run raises an tf.errors.OutOfRangeError (i.e. the whole dataset was iterated trough once and returns the average loss and accurac...
0d01b28f11ef054f6319bfa27ec9107c9cc6d853
73,645
import torch def communities_to_labels(n_nodes, communities): """ For n_nodes nad a communties dictionary or list of lists returns a list with size 'n_nodes' assigning to each node index the corresponding node community. :param n_nodes: :param communities: :return: """ comm_labels = t...
e961568fff8959e909f0b44469a745d33ff5233d
73,646
import torch def to_q(mod, dim=0, CHUNK_SIZE=128): """Var approx distribution generator for a convolutional layer.""" assert isinstance(mod, ConvNdGaussianMixin) def q(mean, log_var, dim=1 + len(mod.kernel_size)): r"""Reinterpret fully factorized Gaussian `q` as factorized by slice. Deta...
0d47ce2d71ad7aa5ea20b707ddc995d0a0057b23
73,647
def build_orthogonalizer(S): """ Form the orthogonalization matrix A = S^{-1/2} using pure NumPy. """ # Application of a function to a matrix requires transforming to # the diagonal basis, applying the function to the diagonal form, # then backtransformation to the original basis. eigval, ei...
fbed8405fddb8857d98219ba1c10841e0f00b404
73,648
def process_raw(procstatus, dscfg, radar_list=None): """ Dummy function that returns the initial input data set Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, 2 post-processing dscfg : dictionary of dictionaries data set co...
42af295ccb30a521f1c0502628d66826a550558a
73,649
def load_data(filename: str): """ Load house prices dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (prices) - either as a single DataFrame or a Tuple[DataFrame, Series] """ ...
c1120d155f784f0ea17dbaf7afe2f2545c2a591f
73,650
import os def get_linked_libraries(exes, libs=[]): """ Get a list of libraries linked to the list of executables and (optional) find realpath to libraries """ _linked_libs = [] for exe in exes: output = None exe = os.path.realpath(exe) if not os.path.exists(exe): ...
5a65339ea37bed8d860e2f4f20d65ea97eda6568
73,651
def check_intensifiers(text, INTENSIFIER_MAP): """ Utility function to check intensifiers of an emotion :param text: text chunk with the emotion term :return: boolean value and booster value for intensifiers """ # BOOSTER_MAP = {"B_INCR": 2, # "B_DECR": 0.5} intensity_word...
2c35b6b66395bc7105b9fb1b9cf7f04b5686cb8d
73,652
from mlp.utils import check_path import logging import math import time def generate_wholebody_tsid(cfg, cs_ref, fullBody=None, viewer=None, robot=None, queue_qt = None): """ Generate the whole body motion corresponding to the given contactSequence :param cs: Contact sequence containing the references, ...
d2c8d45c68e426a63740507ddb4727ad00261954
73,653
def create_email_message(to_emails, from_email, subject, text, html): """ Create the appropriate plaintext or html email object. Returns: email - an instance of either `django.core.mail.EmailMessage` or `django.core.mail.EmailMulitiAlternatives` based on whether or not `html_message` ...
45049b4230e761487383879b5a3a65ca2c1260d5
73,654
import yaml import os def create_dataset(config_file, output_run=None): """ create data structure from input data files """ with open(config_file) as config_fh: data_config = yaml.load(config_fh) data_root = data_config['data_root'] if not os.path.isabs(data_root): # relati...
cd5308f38c2acbee93369945bd7ac1770fa8d749
73,655
def get_next_code(last_code): """Generate next code based on the last_code.""" return (last_code * 252533) % 33554393
9fcf416df3448a8ca46a55073f66d12cd8fc2593
73,656
import shutil from pathlib import Path import os def is_ffmpeg_installed(ffmpeg: str = "ffmpeg") -> bool: """ Check if ffmpeg is installed. """ if ffmpeg == "ffmpeg": # use shutil.which to find ffmpeg in system path return shutil.which("ffmpeg") is not None abs_path = str(Path(ff...
16fc862ab68313e6df9d41156856bf68b26b9192
73,657
from typing import Optional def get_app_sec_security_policy(config_id: Optional[int] = None, security_policy_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppSecSecurityPolicyResult: """ Use this data sou...
9ee579e5d116aef2bdf915030de1de93f847efe7
73,658
def mixer_b32_224(pretrained=False, **kwargs): """ Mixer-B/32 224x224 Paper: 'MLP-Mixer: An all-MLP Architecture for Vision' - https://arxiv.org/abs/2105.01601 """ model_args = dict(patch_size=32, num_blocks=12, hidden_dim=768, **kwargs) model = _create_mixer('mixer_b32_224', pretrained=pretrained,...
da7283d4286ec3f900a6abc2a39d3b386857ef1d
73,659
from typing import List def read_data(file: str) -> List[LabeledSentence]: """ Reads a dataset in the CoNLL format from a file The format is one token per line: [word] [POS] [syntactic chunk] *potential junk column* [NER tag] One blank line appears after each sentence :param file: string filen...
c89bad6fd011722daa5e6b7c92a97b5947296590
73,660
import requests def get_histogram(ID, filename): """ GET request to get histogram image from server/database Args: ID (str): user name filename (str): filename Returns: i (nparray) : array of histogram image """ djson = { "username": ID, "filename": fi...
ebbabb5847dea64c46daa0f802c15a3816b98b09
73,661
def detach_flc_policy(session, lc_policy_id, volume_id, return_type=None, **kwargs): """ Detach a volume from a file lifecycle policy. :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type lc_policy_id: str :para...
bd2a944eba3f999f7c132d2292448dfd6506298a
73,662
import base64 def decode(b64): """ Decode given attribute encoded by using Base64 encoding. The result is returned as regular Python string. Note that TypeError might be thrown when the input data are not encoded properly. """ barray = base64.b64decode(b64) return barray.decode('ascii')
5c04c43247d1415ca8f1398c3b8206c50a7e0fa4
73,663
from unittest.mock import patch async def async_setup_sdm(hass, config=CONFIG, with_config=True): """Prepare test setup.""" if with_config: create_config_entry(hass) with patch( "homeassistant.helpers.config_entry_oauth2_flow.async_get_config_entry_implementation" ): return awa...
e5e649e7bdc4428f578a85c2979077152e635902
73,664
def get_date(s): """Returns date object from string.""" if s.find(".") != -1: # DD.MM.YYYY(.) format args = s.split(".") if args[len(args) - 1] == "": args.pop() args.reverse() else: # YYYY-MM-DD format args = s.split("-") args = list(map(int,...
83145a9775685808aaf4855265dcdd37e37fb746
73,665
def _get_x_ranges(obs_mean, obs_cov): """Get integration limits (8 sigma interval, includes > 99.99% of area).""" x_ranges = [] for (idx, var) in enumerate(np.diag(obs_cov)): std = np.sqrt(var) x_range = [obs_mean[0][idx] - 4.0 * std, obs_mean[0][idx] + 4.0 * std] x_ranges.append(x_r...
0d2174acfa264079e688db75e38f7ce4ff342570
73,666
import subprocess def run_with_logging(cmd, logger): """ Run cmd and wait for it to finish. While cmd is running, we read it's output and print it to a logger. """ process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output_lines = [] while True: line =...
eceffe7417a445d2b3adb7605b3a4e2679cfcca6
73,667
def _strip(value): """ Strip the input value if it is a string and returns None if it had only whitespaces """ if isinstance(value, basestring): value = value.strip() if len(value) == 0: return None return value
958d385d20260dc61d7b069911365242bcc73463
73,668
from typing import Union from typing import Tuple from typing import Any from typing import Dict def _tupleize_compound_item(k: Union[Tuple, str], v: Any) -> Dict: """ converts a JSON-input compound key/value pair into a dictionary of tuples """ if _is_compound_key(k): return {_tupleize_compound_key(k): _tupl...
63ec7fc8eae7a6240cd633143851ed422e951e6c
73,669
def norm_minmax(pixspec, vmin=None, vmax=None, axis=0): """Normalize features in the [0,1] range. Parameters ---------- pixspec: ndarray the set of spectra to normalize vmin: float custom minimum value; if None, computed from data vmax: float custom maximum value; if Non...
f2c00fa6f5211d14129d09f00f557e05358cb796
73,670
def read_traj_clusters(filename): """ Parses a textfile of online clusters, where each line contains the space-separated values of one cluster-center. """ read_line = lambda s: [float(p) for p in s.split(" ")] with open(filename, "r") as infile: traj_clusters = np.array([read_line(line) ...
4dcb0fc538b72a9dc2f3b91512b82348259712f1
73,671
import os def create(output, result, output_format=None, output_style=None): """Create a status badge. The badge file will only be written if it doesn't exist, or if the existing badge file does not require any updates. .. versionchanged:: 1.3.1 Only generate badge file if its contents chang...
80f8266fae1ae3fdd8483f01e34c4f6778db97b5
73,672
import requests def get_multizone_status(host, services=None, zconf=None): """ :param host: Hostname or ip to fetch status from :type host: str :return: The multizone status as a named tuple. :rtype: pychromecast.dial.MultizoneStatus or None """ try: status = status = _get_status(...
59c7be58cf276ec5e5b1bb2352563494f87f3d06
73,673
import json def load_global(what): """ Load data that is not specific to a single issue/MR. For example users, milestones, issue list or MR list. """ path = DIR / f"{what}.json" if not path.exists(): return fetch_global(what) with open(path) as f: return json.load(f)
fa9718d6111a091758bae38c6147586b6deaa5fe
73,674
def pdvec(data, Nint, epsmax=1): """make persistence vector with the top Nint persistences using rips complex""" digs, ints0, ints1 = gettree_int(data, edgelen=edgelen) out1 = _pdproc(ints1, Nint) out0 = _pdproc(ints0, Nint) return (out0, out1)
cfd719eb7f3f4d877499ad6d2779424fec9b03fd
73,675
def glsl_parse_flow(source): """Parse flow block.""" (name, terminator, remaining) = extract_tokens(source, ("?n", "?;")) if name in ("break", "continue"): (statement, discarded) = glsl_parse_statement([name, terminator]) if discarded: raise RuntimeError("discarded elements after...
908e1d3d2a998527ffffa1e0ef75555cc70a6d94
73,676
import sounddevice as sd def configure_sounddevice(sd=None, output='sysdefault', samplerate=44100): """ Will import, configure, and return sounddevice module to play sounds using onboard sound card. :param sd: sounddevice module to be configured, defaults to None, will import new module i...
b05546018479f6606f6938c5066eb2951199913a
73,677
def upload_role_chef_server(chef_conn_obj, file_name="sonic.json"): """ :param chef_conn_obj: :param file_name: :return: """ if not chef_conn_obj: return False command = "sudo knife role from file {}".format(file_name) st.log("Remote Command: {}".format(command)) console_log ...
f796c275dd8f19ab748c094bbc4afd95ab0eb894
73,678
def as_torch(dt, upcast=True): """Convert a generic data type to a torch type Parameters ---------- dt : dtype_like Input data type upcast : bool, default=True If True, authorize upcasting the input type Returns ------- torch.dtype Torch data type """ r...
f64b17f9f4590fdef8adb25fbf61b02beba714a5
73,679
def _MatchCharClassEsc(text, position): """Parse a U{charClassEsc<http://www.w3.org/TR/xmlschema-2/#nt-charClassEsc>} term. This is one of: - U{SingleCharEsc<http://www.w3.org/TR/xmlschema-2/#nt-SingleCharEsc>}, an escaped single character such as C{E{\}n} - U{MultiCharEsc<http://www.w3.org...
3e3c6a7cbe94122fbbd97c3f434447b459ed6ec6
73,680
def compute_sd_of_dist(dist, pgrid, Nitem): """ Compute SD of probability distribution""" m = compute_mean_of_dist(dist, pgrid) v = dist.transpose().dot(pgrid**2) - m**2 return np.sqrt(v)
444df144d172f8a1d130ef3b7ceb4933c0badb20
73,681
import torch def load_proposal_obj(obj): """ Load a set of proposals into memory :param obj: Object to load proposals off of :return: BBoxes object denoted proposal """ if obj['proposals'] is None: return None np_arr = np.array(obj['proposals']) bbox_absolute = torch.from_numpy...
42d839a3453d81e495fe8d556a74dbc4abe8a917
73,682
import argparse def parse_args(): """ Parse command line arguments. """ parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, add_help=False) group_general = add_general_parameters(parser) group_instance = parser.add_argument_group('Instance Selection') ...
7d840db620c1c2212d1e504a703c7fba460ba088
73,683
def api_get_all_categories(): """ returns all categories as JSON """ categories = session.query(Category).all() results = [category.serialize for category in categories] return jsonify({"categories": results})
698bd218bc1334b430649de6e822aaabb650eec4
73,684
import argparse def parse_args(): """Parse arguments. Returns: args: The parsed arguments. """ parser = argparse.ArgumentParser() parser.add_argument( '--data', dest='data_dir', type=str, help='Path to the training set.', required=True) args =...
bb589e28bfcfce372740cee45786c2ff4fa62b60
73,685
def spatialresolutions_id_put(id, user=None, spatial_resolution=None): # noqa: E501 """Update an existing SpatialResolution Updates an existing SpatialResolution (more information in https://w3id.org/okn/o/sdm#SpatialResolution) # noqa: E501 :param id: The ID of the SpatialResolution to be retrieved ...
3998b1ac3371e3df4e6e6d8775204b229cc4dfbe
73,686
import pdb def debug(func): """debug is a method decorator that invokes the python integrated debugger in a given method. Use it to step through tricky code. Note that pdb is not integrated with emacs or anything like that, so you'll need a shell to see what's going on. """ def method(*args,...
76ed776b8f43a02f719d9101e480d41d958c9d91
73,687
def prony(t, F, m): """Input : real arrays t, F of the same size (ti, Fi): integer m - the number of modes in the exponential fit Output : arrays a and b such that F(t) ~ sum ai exp(bi*t) """ # Solve LLS problem in step 1 # Amat is (N-m)*m and bmat is N-m*1 N = len(t) Amat = np.zeros((N - ...
7a4ae656f6d049661310ff12f769fc3467a34092
73,688
def g_MAD(w, x, y): """Compute gradient of Minimum Absolute Deviation (MAD) loss g = 1/n * d/dw \sum{ |y - x.w| } = 1/n * \sum{ sign(e) * (-x) } where e = y - x.w """ e = y - x.dot(w) grad = np.multiply(-x, np.transpose([np.sign(e)])) mean_grad = np.mean(grad, axis=0) # logger.debug(m...
eb2d59c361beb0b9f1ca31a3012f723c02a92bc4
73,689
def plot_outlier(spark, idf, col, split_var=None, sample_size=500000): """ Parameters ---------- spark Spark Session idf Input dataframe which would be referred for capturing the outliers in form of violin charts col Analysis column split_var Column which is ...
e5a7c232653e1b895595ef32ab67bc0b427d9dcb
73,690
import pathlib def _rename_destination_blob(blob_name: str, src: _GCSURL, dst: _GCSURL) -> pathlib.Path: """ Rename destination blob name to achieve gsutil-like cp -r behaviour. Gsutil behavior for recursive copy commands on Google cloud depends on trailing slash. | e...
85fa9a7758f696b9820528d7d81af5326327af34
73,691
from re import U def press2alt(P, press_units=default_press_units, alt_units=default_alt_units): """ Return the altitude corresponding to the specified pressure, with pressure in inches of HG, mm of HG, psi, psf (lb per sq. ft), pa, hpa or mb. The altitude is in units of feet (...
e68ad74d7993df1fcb85127106f649876228bef9
73,692
import os from datetime import datetime import requests def get_sos(xml_file=None): """Return a SensorObservationService instance""" if xml_file is None: data_dir = ircelsos_data_dir() if not os.path.exists(data_dir): os.makedirs(data_dir) xml_file = os.path.join(data_dir,...
5a71931f8c36f011a67fddfb8c62381b40f6382a
73,693
def gluNurbsSurface( baseFunction, nurb, sKnots, tKnots, control, type ): """Pythonic version of gluNurbsSurface Calculates knotCount, stride, and order automatically """ sKnots = arrays.GLfloatArray.asArray( sKnots ) sKnotCount = arrays.GLfloatArray.arraySize( sKnots ) tKnots = arrays.GLfloatA...
127c733a6058c74af62a9990ff2a770a9e287cee
73,694
from typing import Counter def session_referer_class(session): """Most common referer class in session (categorical).""" referer_class = Counter([r['referer_class'] for r in session]).most_common(1)[0][0] return referer_class
0b4047ea63063b7535bbaea7c67756de15561522
73,695
def _get_Is_from_Imidval(reflections, Imid): """Intepret the Imid value to extract and return the Icomb and Vcomb values.""" if Imid == 0: # special value to trigger prf Int = reflections["intensity.prf.value"] Var = reflections["intensity.prf.variance"] elif Imid == 1: # special value to ...
1b23a8218fbdd15ede2f27a6ca0fb531befe18ae
73,696
import argparse def parse_arguments(): """Parse arguments""" parser = argparse.ArgumentParser() parser.add_argument( "-i", "--input", type=str, default="output/optimized_timetable", help="Input directory", ) parser.add_argument( "-or", "--ori...
ea7e944a5a07f29bb52217d0aeaafa287f0b6c47
73,697
import warnings import atexit import os import time def optimize_stellar_parameters_2(initial_guess, transitions, EWs=None, alphafe=0.4, expot_balance_species=26.0, ionization_balance_species_1=26.0, ...
7bde5d12859a5ada88e9bbd864d20727e28c8869
73,698
import json def lambda_handler(event, context): """ 注文情報を登録する Parameters ---------- event : dict フロントより渡されたパラメータ context : dict コンテキスト内容 Returns ------- payment_id : dict 会計ID """ # パラメータログ logger.info(event) if event['body'] is None: ...
ef7f718a7ef216b49865d93f1d1888c132609ab8
73,699