content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def reference(t, viscosity, density, concentration_init, concentration_init_dev, solutes, permittivity, enable_NS, enable_EC, **namespace): """ This contains the analytical reference for convergence analysis. """ mu = viscosity[0] rho_0 = density[0] ...
388e74271c17029e4477407d0048e931e756f48b
3,629,600
def std_err_mean(data): """ calculates deviation from mean. data: all spikes """ return data.std(0).mean()/np.sqrt(data.shape[0])
53f6aecf543617f5d85ddca88c193c41605ab668
3,629,601
import copy from unittest.mock import patch def mock_history(initial): """ mock the commands that interact with the .history file, to fake history management """ releases = copy.copy(initial) project = 'project' def list_releases(): return releases def _append_to_history(rel...
ae65684fe3c1fda6bbecc73a84bb767aa5d92713
3,629,602
def _EpoOff(opts, node_list, inst_map): """Does the actual power off. @param opts: The command line options selected by the user @param node_list: The list of nodes to operate on (all need to support OOB) @param inst_map: A dict of inst -> nodes mapping @return: The desired exit status """ if not _Insta...
9e23d1979813fadb54b168b2f57a546275b3cf8b
3,629,603
def available_numbers(request): """Uses the Twilio API to generate a list of available phone numbers""" form = AreaCodeForm(request.POST) if form.is_valid(): # We received a valid area code - query the Twilio API area_code = form.cleaned_data['area_code'] available_numbers = search...
b00cabe2a2c276f09d5185b46f20d0640e66a672
3,629,604
def get_julia_version(path): """Return version of the Julia installed in *path*""" return exec_shell_cmd('julia.exe -v', path).splitlines()[0].split(" ")[-1]
8421a6de683b7c364e835c6070c8de9f17a4a3c0
3,629,605
def get_pvc_file(flags, spa, pvc_name): """ Get pvc config """ outfile = os.path.join(os.getenv('TMPDIR', '/tmp'), pvc_name + '.yaml') args = [ 'spa', 'get', '-A', flags.account_arg, '--id', spa['meta']['id'], '-K', 'k8sPvcYaml', '-...
611f3f9878db66b30d4119364c754a3c11af41c6
3,629,606
def video_feed(): """Video streaming route. Put this in the src attribute of an img tag.""" return Response(attendence(), mimetype='multipart/x-mixed-replace; boundary=frame')
0ba1d98a4287406f364900eda2b12faeac491237
3,629,607
def current(ticker): """ Return the current price for a stock """ return rh.get_latest_price(ticker)[0]
abfa290c79267981571ae25ee7bd1827b4182141
3,629,608
import os def _file(*args): """ Wrapper around os.path.join and os.makedirs.""" filename = os.path.join(*args) _makedirs_for_file(filename) return filename
c8cb9e7a05b09ada4d0d5ac682a4fbdb394a2475
3,629,609
import os def get_root_data_dir() -> str: """ Return the directory where the mephisto data is expected to go """ global loaded_data_dir if loaded_data_dir is None: default_data_dir = os.path.join(get_root_dir(), "data") actual_data_dir = get_config_arg(CORE_SECTION, DATA_STORAGE_KE...
ef0d97940c7086918e34e8d63ee3e6e36e8de439
3,629,610
from typing import Optional from typing import Tuple def fetch_indicators_command( client, initial_interval, limit, last_run_ctx, fetch_full_feed: bool = False, filter_args: Optional[dict] = None, ) -> Tuple[list, dict]: """ Fetch indicators from TAXII 2 server :param client: Taxii...
e527391a0055c7604d4423e0565cf04b017e8038
3,629,611
def aggregate(loss, weights=None, mode='mean'): """Aggregates an element- or item-wise loss to a scalar loss. Parameters ---------- loss : Theano tensor The loss expression to aggregate. weights : Theano tensor, optional The weights for each element or item, must be broadcastable to...
6d888d1854cfa78e13fcd5eba412e224164386d7
3,629,612
def mirror_ud(image): """Mirrors an image between up and down :param image: An input image to convert :type image: array_like :return: Mirrored image. Same dimensions as input. :rtype: ndarray """ return np.flipud(image)
8a8113fcc4d7335fcaa7bd5a259b19e856408814
3,629,613
import torch def ifftn(input, s=None, dim=-1, norm='backward', real=None): """N-dimensional discrete inverse Fourier transform. Parameters ---------- input : tensor Input signal. If torch <= 1.5, the last dimension must be of length 2 and contain the real and imaginary parts o...
0fa3c678a6747d25634f5a68e78fa3d4597ac587
3,629,614
def list_del(): """ del """ mylist = ['dog', 'lion', 'snake', 'elephant', 'cow', 'donkey', 'goat', 'duck'] del mylist[2] return mylist
716fbb915bc477f4232e66b6b7fcb720bb0520f4
3,629,615
def _get_group_definition(group): """Get an instance of the group definition for the specified item. This definition can be used to clone or download the group. Keyword arguments: group - The arcgis.GIS.Group to get the definition for.""" return _GroupDefinition(dict(group), thumbnail=None, portal_grou...
7a00dc3117ec725bbd9eef2dbafe39e1d39d9de7
3,629,616
import os import urllib def fetch_bike_dataset(years, data_dir="data"): """ Dowload bike dataset for a given year and return the list of files. """ base_url = "https://s3.amazonaws.com/capitalbikeshare-data/" files = [] for year in years: filename = str(year) + "-capitalbikeshare-tripdata....
55733e7fa65299c3f4f23125dde80c83fb7caae2
3,629,617
def assert_rank(x, rank, data=None, summarize=None, message=None, name=None): """Assert `x` has rank equal to `rank`. Example of adding a dependency to an operation: ```python with tf.control_dependencies([tf.compat.v1.assert_rank(x, 2)]): output = tf.reduce_sum(x) ``` Args: x: Numeric `Tensor`....
447f95b909b21aa5c918bae2eccd327fb3bdb463
3,629,618
def get_lo_hi_from_CI(s, exclude=None): """ Parse the confidence interval from CI. >>> get_lo_hi_from_CI("20-20/40-60") (40, 60) """ a, b = s.split("|") ai, aj = a.split("-") bi, bj = b.split("-") los = [int(ai), int(bi)] his = [int(aj), int(bj)] if exclude and exclude in l...
69c0fb14afd18444465cb7b0f8b23990d044a2b9
3,629,619
import transformers def get_pretrained_model(path='saved_models/checkpoint-1480'): """Gets a BERT classification model from a given pretrained model checkpoint (supplied with a filepath). Args: path (str): a valid filepath that contains the checkpoint of a DistilBert model Returns: transformers.DistilBertFor...
49a6a8603a7dc221f4ec9b85ef24ff2c422d0b51
3,629,620
from typing import Type from typing import Iterable from typing import Optional def get_docstring_summary( cls: Type, *, fallback_to_ancestors: bool = False, ignored_ancestors: Iterable[Type] = (object,) ) -> Optional[str]: """Get the summary line(s) of docstring for a class. If the summary is one more t...
0fbd076962dd08e4b537d00dd39e473a94331a5c
3,629,621
import logging def get_input_evaluation_tensors(reader, data_pattern, batch_size=1024, num_readers=1): """Creates the section of the graph which reads the evaluation data. Args: reader: A class which pars...
6f677a368ab55b8ecc4816f104484444ed8bfa3c
3,629,622
def load_extensions(app): """ To load navitaire extension :param app: :param name: :return: """ if 'stargate' not in app.extensions: raise GeneralError({ "code": "General Error", "description": "{name} not exist".format(name='stargate') }, 'info', http...
6239bc9cafdc1a948634b1b7329cfd6f1bbc1a4f
3,629,623
def blur(img): """ This function will blur the original image --------------------------------------------- :param img: SimpleImage, the original image :return: SimpleImage, the blurred image """ new_img = SimpleImage.blank(img.width, img.height) for x in range(img.width): for y ...
b41784396ff4f4402a7a8604796a32089f328b30
3,629,624
import requests import logging def check_virustotal(domain, api_key, threshold): """ Checks VirusTotal to see if the domain is malicious """ #resource = "{0}domain".format("http://www.", domain) url = 'https://www.virustotal.com/vtapi/v2/url/report' params = {'resource': domain, 'apike...
1e7330a41c95eec7372aa001093c872ee97b633e
3,629,625
def describe_db_instances( name=None, filters=None, jmespath="DBInstances", region=None, key=None, keyid=None, profile=None, ): """ Return a detailed listing of some, or all, DB Instances visible in the current scope. Arbitrary subelements or subsections of the returned dataset ...
6393a969fd421fe966b593213acf8edc47520665
3,629,626
import imp import os def get_parent_until(path): """ Given a file path, determine the full module path. e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields 'numpy.core' """ dirname = osp.dirname(path) try: mod = osp.basename(path) mod = osp.splitext(mod)...
abf283df8ead744b4f1fc7df93fb721064e9268d
3,629,627
import os def DSHAPE(tmpdir_factory): """Run DSHAPE example.""" input_path = ".//tests//inputs//DSHAPE" output_dir = tmpdir_factory.mktemp("result") desc_h5_path = output_dir.join("DSHAPE_out.h5") desc_nc_path = output_dir.join("DSHAPE_out.nc") vmec_nc_path = ".//tests//inputs//wout_DSHAPE.nc"...
f5d07a9f4f97ccb90281f6c4c9d8b205b051d11e
3,629,628
def get_control_changes(midi, use_drums=True): """Retrieves a list of control change events from a given MIDI song. Arguments: midi (PrettyMIDI): The MIDI song. """ midi_control_changes = [] for num_instrument, midi_instrument in enumerate(midi.instruments): if not midi_instrument.i...
c3c264c11f9ef38aa79c24cd795e35145139beb1
3,629,629
def is_workinprogress(change): """Return True if the patchset is WIP :param dict change: De-serialized dict of a gerrit change :return: True if one of the votes on the review sets it to WIP. """ # This indicates WIP for older Gerrit versions if change['status'] != 'NEW': return True ...
ac2f5ba1ab8d5fd432ef7b13c5b033e0c3710fd4
3,629,630
def get_bot() -> NoneBot: """ 获取全局 NoneBot 对象。可用于在计划任务的回调中获取当前 NoneBot 对象。 返回: NoneBot: 全局 NoneBot 对象 异常: ValueError: 全局 NoneBot 对象尚未初始化 用法: ```python bot = nonebot.get_bot() ``` """ if _bot is None: raise ValueError('NoneBot instance has no...
175c53c0b3bc73d303e1b766df94fcfb074f3de0
3,629,631
def nbr(nir_agg: xr.DataArray, swir2_agg: xr.DataArray, name='nbr'): """ Computes Normalized Burn Ratio. Used to identify burned areas and provide a measure of burn severity. Parameters ---------- nir_agg : xr.DataArray 2D array of near-infrared band. swir_agg : xr.D...
7e83911382f484a201df93e1eb31510860100c41
3,629,632
def white_noise(sigma, T, seed): """Реализация независимого белого шума длины T, ε ~ N(0, sigma^2)""" np.random.seed(seed) noise = np.random.normal(loc=0, scale=sigma, size=(1, T)) return noise
e6c88bd9f6857ff6aa0cb6f4af916fecb7aa04a7
3,629,633
def register_serializable(cls): """A class decorator registering the class for serialization.""" __types[type2str(cls)] = cls return cls
f6f65288235a291b9cb064b179e454580ecff280
3,629,634
import io from datetime import datetime def generate_realized_trips_from_gtfs(gtfs_path): """Transforms a GTFS feed to realized_trips format (see README for specification). It can either read a feed zip file or a folder. Parameters ---------- gtfs_path : str GTFS feed zip file or fol...
4a5050ebf63d39cb3d800adbc42d98410857e302
3,629,635
def get_stockdata_from_sql(mode,begin,end,name): """ get stock market data from sql,include: [Open,High,Low,Close,Pctchg,Vol, Amount,total_shares,free_float_shares,Vwap] """ try: conn = pymysql.connect(**config) cursor = conn.cursor() if mode == 0: query = "SELECT...
a9456019e51e1049d1bcedb1be45e40304de373f
3,629,636
def full_isomorphism(gra1, gra2): """ full graph isomorphism """ assert gra1 == explicit(gra1) and gra2 == explicit(gra2) nxg1 = _networkx.from_graph(gra1) nxg2 = _networkx.from_graph(gra2) iso_dct = _networkx.isomorphism(nxg1, nxg2) return iso_dct
086b0f85e72beb4b30f405706c0d0896cb65c002
3,629,637
def likelihood_overlap(lk1, lk2): """ Returns overlap area of two likelihood functions. Parameters ---------- lk1 : numpy.ndarray First likelihood function. lk2 : numpy.ndarray Second likelihood function. Returns ------- overlap : float Overlap area. ""...
d5af7b90ad7eac5fe47d7444e284317b573d8780
3,629,638
import resource def get_total_cpu_time_and_memory_usage(): """ Gives the total cpu time of itself and all its children, and the maximum RSS memory usage of itself and its single largest child. """ me = resource.getrusage(resource.RUSAGE_SELF) children = resource.getrusage(resource.RUSAGE_CHILD...
2073440a0ef6e9185b5b4c7613a56c902a722dc3
3,629,639
def require_single_skillet(func): """Commands decorated with this require one skillet to be uniquely specified""" def wrap(command): if not command.sli.options.get("name") and len(command.sli.skillets) > 1: raise InvalidArgumentsException( f"Specify a skillet to run with --n...
98b79706d1b2281a30bfa4a8dc10120a9631f620
3,629,640
def get_ecf_player(database, key): """Return ECFrefDBrecordECFplayer instance for dbrecord[key].""" p = database.get_primary_record(filespec.ECFPLAYER_FILE_DEF, key) pr = ECFrefDBrecordECFplayer() pr.load_record(p) return pr
189ab0219c8a730d7f416aa8419d3ef00352d6f5
3,629,641
import pickle def pickle_load(namefile: str): """Load Python variable, given name of file. :param namefile: A string of file to load. :return output: A loaded variable. """ with open(namefile, 'rb') as load_file: output = pickle.load(load_file) return output
425e53b8daf69bf832abc45a4270cc01f383c50e
3,629,642
import pkg_resources def load_preset_linelist(name): """ Returns one of our preset line lists, loaded into an astropy QTable """ metadata = get_linelist_metadata() if name not in metadata.keys(): raise ValueError("Line name not in available set of line lists. " + "...
ea435e63f30eaab8748fb01a7214050349cd89df
3,629,643
def scale_matrix(matrix): """ nn works best with values between 0.01 and 1 """ return matrix / 255 * 0.99 + 0.01
b4c0d34a21724ee5712caf8dca131b3e1e1d0753
3,629,644
import os def load_record_set(path): """ 加载训练/测试集 """ record_list = [] if not os.path.isfile(path): raise IOError("File not Found!") with open(path, "r") as f: content = list(f) record_list = encapsule(content) return record_list
148ec3300b5afe122bc794e0a96fbec467481d7c
3,629,645
def negate(condition): """ Returns a CPP conditional that is the opposite of the conditional passed in. """ if condition.startswith('!'): return condition[1:] return "!" + condition
5f31ed3ee2f16a53674f830402fdec890af25032
3,629,646
import maya.utils as utils import hdefereval import multiprocessing def __worker(func): """ thread runner Args: func: Returns: """ if env.Maya(): utils.executeDeferred(func) # https://forums.odforce.net/topic/22570-execute-in-main-thread-with-results/ elif env.Houdi...
a6d7635a09fe02975ed802cd4b59d70d2e163090
3,629,647
def _compute_n50_and_n95_np(readlengths): """ Numpy implementation of N50/N95 calculation. """ if isinstance(readlengths, list): readlengths = np.array(readlengths) readlengths[::-1].sort() # = np.sort(readlengths) total_length = np.sum(readlengths) csum = np.cumsum(readlengths) ...
9a3ac1ccdd3a2af10e76524cc6c628b8868d758b
3,629,648
def get_dominant_horizontal_line_colour(ip): """ >>> get_dominant_horizontal_line_colour(np.array([[0,0,0], [1,1,1], [1,0,0], [2,2,2],[0,0,0]])) {1, 2} """ #get unique list of colours per row row_info = ([np.unique(row) for row in ip]) # identify the whole colour lines, we do this if th...
e955b76940f85bf448e959e29f5134b1247d45ab
3,629,649
def _filter_out_disabled(d): """ Helper to remove Nones (actually any false-like type) from the scrubbers. This is needed so we can disable global scrubbers in a per-model basis. """ return {k: v for k, v in d.items() if v}
64a4577d6e5998e647ef82f126c50360388aba9a
3,629,650
def main(): """See fplutil/disttools/push_package.py. Returns: 0 if successful, non-zero otherwise. """ return disttools.push_package.main(disttools.push_package.parse_arguments( project_dir=PROJECT_DIR, config_json=CONFIG_JSON))
9e6ccf0d7654d980361e0ef446a0674344a8d3a5
3,629,651
import glob import os def extractRotationInteractively(input_dir,zmax_identifier): """ Rotation based on zmax image. Loads zmax image, then asks user to draw a line along the long axis. Rotation is the angle of the line. """ # find & open image with zmax projection try: fn_zmax=glob.glob(input_dir+os.sep+"*"...
e4dbcc9ad945a2e7d95cf214c16a071f66760c88
3,629,652
def _check_supports_private_deps(repository_ctx, swiftc_path, temp_dir): """Returns True if `swiftc` supports implementation-only imports.""" source_file = _scratch_file( repository_ctx, temp_dir, "main.swift", """\ @_implementationOnly import Foundation print("Hello") """, )...
4971d84914b957f80e467b6956395806e06117bf
3,629,653
import os def can_reuse(fpath, cmp_f, silent=False): """Check if a file `fpath` exists, is non-empty and is more recent than `cmp_f` """ do_reuse = os.environ.get('REUSE', '1') if do_reuse == '0': return False if not fpath or not isfile(fpath): return False elif verify_file(fpa...
5d9cfae7994b19265327cdc0da9988835621d20a
3,629,654
def createNullOperator(context, domain, range, dualToRange, label=None): """ Create and return a null (zero-valued) operator. *Parameters:* - context (Context) A Context object to control the assembly of the weak form of the newly constructed operator. - domain (Space)...
149ee689c30f6da1ac47c418de41533dc1706663
3,629,655
def stsb(dataset): """Convert STSB examples to text2text format. STSB maps two sentences to a floating point number between 1 and 5 representing their semantic similarity. Since we are treating all tasks as text-to-text tasks we need to convert this floating point number to a string. The vast majority of the...
a19664d2fd7b24efa132852fbb39dd9300b73f59
3,629,656
def getString(data: dict = None, separater: str = " ") -> str: """Debug message when debug is enabled. :param data: The value in either str or list. :type data: str,list :param separater: The separater between the words. :type separater: str :rtype: str :return: The message in string. "...
026dd1838213a48c3bf65c33ce1820a0e2867b79
3,629,657
import os import re def make_spectrograms_old(spectros=None, overwrite=False, cmap='magma', subdirs=['no_sax', 'sax_sec', 'sax_solo'] ): """ *** VERSION 1, USES OLD FILE FORMAT *** Makes spectrograms f...
8e9ef34b35158eecf947823a3c4d6a35f6fe35ed
3,629,658
def scatter_matrix(df,theme=None,bins=10,color='grey',size=2): """ Displays a matrix with scatter plot for each pair of Series in the DataFrame. The diagonal shows a histogram for each of the Series Parameters: ----------- df : DataFrame Pandas DataFrame theme : string Theme to be used (if not the defa...
db92ed3b03ecb081364e7f50ddbb9b0a777ce820
3,629,659
def _gr1_sorted_ ( graph , reverse = False ) : """Make sorted graph >>> graph = ... >>> s = graph.sorted() """ oitems = ( i for i in graph.iteritems() ) sitems = sorted ( oitems , key = lambda s :s[1].value() , reverse = reverse ) new_graph = ROOT.TGraphErrors ( len( g...
147edad4505c9d7ab5df181d6e731e8c7f6713b3
3,629,660
def compute_features_paa(filename, with_timebase=False, verbose=False): """compute_features_paa Compute a bag of standard audio features to be used for some downstream task. """ if verbose: print('compute_features_paa loading from {0}'.format(filename)) [Fs, x_] = audioBasicIO.read_audi...
2a91c4dfc64bcae6b79c6a5f0bfd5f7fdeac2db6
3,629,661
def str_match_end(name, strip): """ :param name: :param strip: :return: """ if name is None: return False if name[len(name)-len(strip):len(name)] == strip: return True return False
ba9c84644d22f0b2ce68f7cb6efb1279209084f8
3,629,662
import subprocess def run_post_script(logger, post_script, vm, mac_ip, custom_mac): """ Runs a post script for a vm """ if mac_ip: logger.info('Running post-script command: %s %s %s %s' % (post_script, vm.config.name, mac_ip[0], mac_ip[1])) retcode = subprocess.call([post_script, vm.co...
4e089308b60524839acec0138245664a2d37e572
3,629,663
def points(start, end): """ Bresenham's Line Drawing Algorithm in 2D """ l = [] x0, y0 = start x1, y1 = end dx = abs(x1 - x0) dy = abs(y1 - y0) if x0 < x1: sx = 1 else: sx = -1 if y0 < y1: sy = 1 else: sy = -1 err = dx - dy whil...
ffa8be5eb09e2b454242e4095883bfee239e5319
3,629,664
import re def ExtractIconReps(icon_file_name): """Reads the contents of the given icon file and returns a dictionary of icon sizes to vector commands for different icon representations stored in that file. Args: icon_file_name: The file path of the icon file to read. """ with open(icon_file_n...
14cbe3a9d8ee107fd60643dc61648cfeba3167ae
3,629,665
def _is_device_list_local(devices): """Checks whether the devices list is for local or multi-worker. Args: devices: a list of device strings, either local for remote devices. Returns: a boolean indicating whether these device strings are for local or for remote. Raises: ValueError: if device ...
adb1c414f8e22ecab3a31a0cd61666d96af1acfd
3,629,666
def ab_from_mv(m, v): """ estimate beta parameters (a,b) from given mean and variance; return (a,b). Note, for uniform distribution on [0,1], (m,v)=(0.5,1/12) """ phi = m*(1-m)/v - 1 # z = 2 for uniform distribution return (phi*m, phi*(1-m))
0326c165e44c1ab9df091e0344f12b9fab8c0e19
3,629,667
def get_credentials(): """Get the Google credentials needed to access our services.""" credentials = GoogleCredentials.get_application_default() if credentials.create_scoped_required(): credentials = credentials.create_scoped(SCOPES) return credentials
196013b7e49a87ca43a6824a02cf72db830e5420
3,629,668
def mtrax_mat_to_big_arrays(data): """translation of code sent to me by alice""" if np.any(~np.isfinite(data['identity'])): # make sure no funny numbers raise ValueError('cannot handle non-finite data on identity') identity = np.array( data['identity'], dtype=int ) # cast to int assert np.allclo...
f7c7b2d9c3e731cf7af05aa771e3739ddc66df95
3,629,669
from typing import Union def normalize_class(c:Union[str,int], ensure_scored:bool=False) -> str: """ finished, checked, normalize the class name to its abbr., facilitating the computation of the `load_weights` function Parameters ---------- c: str or int, abbr. or SNOMEDCTCode of the...
320710e59ba585c1de276be4b0195335127c08c8
3,629,670
def appearance_kernel(x_1: int, y_1: int, p_1: np.ndarray, x_2: int, y_2: int, p_2: np.ndarray, theta_alpha: float, theta_beta: float) -> float: """Compute appearance kernel. Args: x_1: X coordinate of first pixel. y_1: Y coordinate of first pixel. ...
4d9f70268baba752352de5e3c692e0bc2ceaac64
3,629,671
def update_game_log_tables(player_id, season): """ Loads player's game for specific season as pandas DataFrame :param player_id: string, :param season: int :return: column names, table data for 'games-table' object and table title for text object """ global df_reg_games, df_po_games, df_ids ...
0627694434e26118b93587265bde710840f8d4a2
3,629,672
from datetime import datetime def _convert_relative_time(relative_time): """ Convert a Cb Response relative time boundary (i.e., start:-1440m) to a device_timestamp: device_timestamp:[2019-06-02T00:00:00Z TO 2019-06-03T23:59:00Z] """ time_format = "%Y-%m-%dT%H:%M:%SZ" minus_minutes = relative_...
533b2c6b53d9f34754f8d5f1452c9b4caf93108c
3,629,673
def NTFSolve_conv(M, Mmis, Mt0, Mw0, Mb0, nc, tolerance, LogIter, Status0, MaxIterations, NMFFixUserLHE, NMFFixUserRHE, NMFFixUserBHE, NMFSparseLevel, NTFUnimodal, NTFSmooth, NTFLeftComponents, NTFRightComponents, NTFBlockComponents, NBlocks, NTFNConv, NMFPriors, myStatusBox): """Estimate NTF matrices ...
a84e5e561ac692f7996c675a26b0e8eaf791d50c
3,629,674
def fds_remove_crc_gaps(rom): """Remove each block's CRC padding so it can be played by FDS https://wiki.nesdev.org/w/index.php/FDS_disk_format """ offset = 0x0 def get_block(size, crc_gap=2): nonlocal offset block = rom[offset : offset + size] offset += size + crc_gap ...
935ecb4ac01c1256ec074f6888704fdd1db63ea4
3,629,675
def _apply_categorical_projection_naive(y, y_probs, z): """Naively implemented categorical projection for checking results. See (7) in https://arxiv.org/abs/1802.08163. """ batch_size, n_atoms = y.shape assert z.shape == (n_atoms,) assert y_probs.shape == (batch_size, n_atoms) v_min = z[0] ...
3674e57a75508a22a3b12cda52e4fc06fa947d20
3,629,676
def calculate_xdf( arr, method="truncate", methodparam="adaptive", truncate_extrema=True, ): """Calculate xDF-corrected statistics for correlation coefficients. Parameters ---------- arr : numpy.ndarray of shape (S, T) S is features, T is time points method : {"truncate", "t...
d0863b6680bf09926013458c1dc006120ce12a01
3,629,677
def truncatewords(base, length, ellipsis="..."): """Truncate a string by words""" # do we need to preserve the whitespaces? baselist = base.split() lenbase = len(baselist) if length >= lenbase: return base # instead of collapsing them into just a single space? return " ".join(baseli...
f6472c7511e7e9abf03d4da3ed10c94ef070f78a
3,629,678
def normalising_general(data,scoreMAX=[20,27,100,21],scoreMIN=[0,0,0,0],cumsum=True): """Normalises the data of the patient with missing count. Parameters ---------- data : numpy data, [number of observations, number of features] scoreMAX: max scores for asrm and qids scoreMIN: min scores for a...
560e63c79777ab3c3cb4550142ee68bd0ea3c621
3,629,679
import os import json def extract_csv_from_t2out(json_output=False): """It writes the parameter for every block from the last output file of TOUGH2 simulation on csv or json Parameters ---------- json_output : bool If True a json file is save on ../output/PT/json/ Returns ------- file PT.csv: on ../out...
1f6d457bc8b752d342db57a6a88e0d89b201cc06
3,629,680
import tokenize import io import token def fix_lazy_json(in_text): """ This function modifies JS-contained JSON to be valid. Posted in http://stackoverflow.com/questions/4033633/handling-lazy-json-\ in-python-expecting-property-name by Pau Sánchez (codigomanso.com) """ tokengen = toke...
9d46297d9beb21fc2368322fe69cd9ab266f733b
3,629,681
def get_project_family(repo, namespace=None, username=None): """Return the family of projects for the specified project { code: 'OK', family: [ ] } """ allows_pr = flask.request.form.get("allows_pr", "").lower().strip() in [ "1", "true", ] allows_iss...
3a208818e3a30911cd58e459de139aceb485ceb0
3,629,682
import warnings def transform( f, apply_rng=False, state=False, ) -> Transformed: """Transforms a function using Haiku modules into a pair of pure functions. The first thing to do is to define a `Module`. A module encapsulates some parameters and a computation on those parameters: >>> class MyMo...
422fe9850df87ac3db738e889461405b36443413
3,629,683
def direct_to_waypoint(aircraft_id, waypoint_name): """ Request aircraft to change heading toward a waypoint. Parameters ---------- aircraft_id : str A string aircraft identifier. For the BlueSky simulator, this has to be at least three characters. waypoint_name : str A ...
0c26bc72a994f14dc4df4c56de24b4637dd5f383
3,629,684
import re def username_allowed(username): """Returns True if the given username is not a blatent bad word.""" if not username: return False blacklist = cache.get(USERNAME_CACHE_KEY) if blacklist is None: f = open(settings.USERNAME_BLACKLIST, "r") blacklist = [w.strip() for w i...
42f856baf3d5e704af0ce0780a9ecbb0984b465b
3,629,685
def satisfiability(p=5, ratio=2.0, pr_edge=0.5, pr_exo=0.3, dsp_scm=True): """ Count the number of attempts to generate a linear P-SCM that can be uniquely recovered (i.e., satisfies the derived conditions). :param p: Number of observed nodes :param ratio: Source to observed node ratio. (Num...
596b8267b915f8b0dcf0e7bc993fa5ff9a62e1b9
3,629,686
import os def get_uri(env_var='DATABASE_URL'): """Grab and parse the url from the environment.""" parsed_result = urlparse( # Trick python3's urlparse into raising when env var is missing os.environ.get(env_var, 1337) ) meta = { 'scheme': parsed_result.scheme, 'username...
91cad8b1a2fef783ce9f33066c461db1b0f87fd2
3,629,687
def next_update_time(m): """Return the next update time. If the UpdateFrequency or Modified """ last_mod = m.doc['Root'].find_first_value('Root.Modified') if last_mod: last_mod = parse(last_mod) else: return False uf = m.doc['Root'].find_first_value('Root.UpdateFrequency') ...
8bd149b95719691a83563111a196e2b8ab900f99
3,629,688
import random def random_permutation(iterable, r=None): """Random selection from itertools.permutations(iterable, r)""" pool = tuple(iterable) if r is None: r = len(pool) return list(random.sample(pool, r))
09e9f22def2c1125bf0ffc50db73659eaac65105
3,629,689
def rabin_karp_pattern_set(test_file_text, k): """ Given a document to detect matches for, creates a set of for the "rolling" hashcodes of each shingle. Runtime: O(len(test_file_text)) with a very small constant factor @param test_file_text: string of file to detect matchse for @param k: length of shingles @re...
dda851974207490717f9dcd1449cc83905fe7e83
3,629,690
def get_hms(t_sec): """Converts time in seconds to hours, minutes, and seconds. :param t_sec: time in seconds :return: time in hours, minutes, and seconds :rtype: list """ h = t_sec//3600 m = (t_sec - h*3600)//60 s = t_sec%60 return h,m,s
f873ea04905ebcc5b41a394a4dd880a566623c83
3,629,691
from typing import Dict def check_model_version_name(model_name: Text, model_version: Dict) -> bool: """Check model version name. Args: model_name {Text}: model name model_version {Dict}: model version dictionary Returns: True if model names are matches, otherwise false """ ...
eed0b9a8a9b25fac8c1818ed18fa59a01a55b5f3
3,629,692
import logging def current_page_name(webdriver: webdriver, valid_url: str = "tricount.com") -> str: """ Checks current page for content, determines name. Returns: page name, according to names in PAGE_NAV_ORDER Raises: AssertionError - webdriver.current_url doesn't match expected vali...
652133e53883eaa839441dfbd15ce6fddd99f383
3,629,693
def task_jshat_app_watch(): """JsHat application - build all on change""" return {'actions': ['yarn run --silent watch ' '--config webpack.app.config.js'], 'task_dep': ['jshat_deps']}
96d9d42e5145cfb2aef3cc91362eb3c9da244ff7
3,629,694
from etools_permissions.models import Realm def get_realm(request): """ Currently not setting realm in session, so using user to get realm Expect tenant attribute to be set on request in Workspace in use, if user not set or user is superuser, then no tenant """ realm = None if request.use...
b3c0a678553d2cd1da982a44a8376686a6f0f7af
3,629,695
def _marked_merging(A, criterion_fn, node_weights=None): """ Method of paper 'Weighted Graph Cuts without Eigenvectors: A Multilevel Approach' """ if node_weights is None: node_weights = np.ones(A.shape[0]) unmarked_vertices = list(np.arange(A.shape[0])) edges_to_merge = np.zeros_like(A) whi...
11fe427a8cd0697c123a8c503afdde28dba3b824
3,629,696
def fast_aggregate(X, Y): """If X has dims (T, ...) and Y has dims (T, ...), do dot product for each T to get length-T vector. Identical to np.sum(X*Y, axis=(1,...,X.ndim-1)) but avoids costly creation of intermediates, useful for speeding up aggregation in td by factor of 4 to 5.""" T = X.shape[0] ...
dfcb15bdb9555fead4d37ab03c5112a13f944f52
3,629,697
def GroupConv2D(filters, kernel_size, strides=(1, 1), groups=32, kernel_initializer='he_uniform', use_bias=True, activation='linear', padding='valid', **kwargs): """ Grouped Convolutio...
16f4162859bd2186f508800fae04b1a493aa7a33
3,629,698
def shift(seq: Sequent) -> Sequent: """ The :math:`\\textbf{Opt${}^?$}` :math:`\\texttt{shift}` rule. From an :math:`n`-opetope :math:`\\omega`, creates the globular :math:`(n+1)`-opetope :math:`\\lbrace []: \\omega`. """ n = seq.source.dimension ctx = Context(n + 1) for a in seq.sou...
d306604f6f809a2b38fb147e68f76b7d6e733435
3,629,699