content
stringlengths
22
815k
id
int64
0
4.91M
def get_ndjson(obj, jobType): """ Given an S3 object that points to a JSON file, read it into memory and return an ndjson string representation """ json_content = json.loads(obj.get()['Body'].read().decode('utf-8')) output_records =[] for record in json_content: output_record = {} comp...
5,322,400
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the Lutron Caseta switch platform. Adds switches from the Caseta bridge associated with the config_entry as switch entities. """ data = hass.data[CA...
5,322,401
def render_to_json(data, is_json=False): """Create a JSON response from a data dictionary and return a Django response object.""" if not is_json: js = json.dumps(data, cls=DjangoJSONEncoder) else: js = data mime = mimetype = "application/json;charset=utf-8" response = http.HttpRe...
5,322,402
def create_link(src:pathlib.Path, tgt:pathlib.Path, copy): """ Helper function to create a directory link or copy a directory. On windows, this will be a directory junction, and on mac/linux this will be a soft link :param src: The name of the link to create :param tgt: The target of the ne...
5,322,403
def get_ctd_from_txt(fname, summary, source, sea_name, p_lat, p_lon, p_time, ca=[]): """ Create an ambient.Profile object from a text file of ocean property data Read the CTD and current data in the given filename (fname) and use that data to create an ambient.Profile object for use in TAMOC. This ...
5,322,404
def delete(event, _): """ This function is responsible for deleting the redirect URIs secret """ print(event) secrets_manager = boto3.client('secretsmanager', config=user_config) # delete the secret value secret_id = f'{event["ResourceProperties"]["SecretPrefix"]}/redirect_uris' secrets_...
5,322,405
def test_web3_middleware_type1(yield_dongle): """Test LedgerSignerMiddleware with type 1 transactions""" provider = EthereumTesterProvider() web3 = Web3(provider) clean_web3 = Web3(provider) alice_address = web3.eth.accounts[0] with yield_dongle() as dongle: # Inject our middlware ...
5,322,406
def get_ndimage_module(*args): """ Returns either the scipy.ndimage or cupyx.scipy.ndimage module, cupy module is returned if any argument is on the GPU. """ return cupyx.scipy.ndimage if any(is_on_gpu(arg) for arg in args) else scipy.ndimage
5,322,407
def sensitivity_plot_comparison(n_bins_energy, energy, sensitivity): """ Main sensitivity plot. We plot the sensitivity achieved, MAGIC sensitivity and Crab SEDs Parameters -------- n_bins_energy: `int` number of bins in energy energy: `numpy.ndarray` sensitivity array sens: `num...
5,322,408
def test_get_sum_anions_3(test_data_bas_vdg): """ Test based on Bas vd Grift bug report """ df = test_data_bas_vdg df.hgc.consolidate(use_ph='lab', use_ec='lab', use_temp=None, use_so4=None, use_o2=None) sum_anions = df.hgc.get_sum_anions(inplace=False) np.testing.assert_almost_equal(sum_anions.val...
5,322,409
def factor(from_units, to_units, units_class=None): """ Return a conversion factor: >>> value_in_cm = 25 >>> value_in_cm * factor('cm', 'mm') 250 class: If specified, the class of the units must match the class provided. """ if (from_units is None or not len(from_units)) a...
5,322,410
def fibonacci_index(index): """ Returns fibonacci sequence with the given index being the last value. raises a type error if given index is a string, float, zero or negative number. returns a string for given indexes that are 1 and 2. """ try: if type(index) == str or type(index) ...
5,322,411
def get_history_file_path(): """Returns path to the training command history file.""" return Path(__file__).parent / 'history'
5,322,412
def _traverse_with_names(tree): """Traverses nested dicts/dataclasses and emits (leaf_name, leaf_val).""" if dataclasses.is_dataclass(tree): tree = flax.serialization.to_state_dict(tree) if isinstance(tree, dict) or isinstance(tree, flax.core.FrozenDict): keys = sorted(tree.keys()) for key in keys: ...
5,322,413
def var_is_protein_effecting(variant_data): """Check if variant has a MED or HIGH impact :param variant_data: A GeminiRow for a single variant. :type variant_data: GeminiRow. :returns: bool -- True or False. """ if variant_data.INFO.get('impact_severity') != "LOW": return True else:...
5,322,414
def check(ctx, pty=True): """Run code quality checks.""" print_header('Django check') ctx.run('python manage.py check', pty=pty) print_header('Flake8') ctx.run('flake8', pty=pty) print_header('eslint') js_files = ' '.join(glob('scrappyr/static/js/**/*.js', recursive=True)) ctx.run(f'./...
5,322,415
def put_df (nb, df_name, data, labels): """ write a dataframe in a notebook, appending a new cell if needed """ # create a code cell to represent a pandas dataframe buf = [] buf.append(df_name + " = pd.DataFrame.from_records(") buf.append(repr(data) + ", columns=" + repr(labels) + ")") b...
5,322,416
def center_embeddings(X, Y): """ Copied from Alvarez-Melis & Jaakkola (2018) """ X -= X.mean(axis=0) Y -= Y.mean(axis=0) return X, Y
5,322,417
def verification_code_form(request): """ form to enter the verification code """ if request.method == 'POST': code = request.POST['code'] return _verify_code(request, code) return {}
5,322,418
def _ProcessGccConfig(target, output_dir): """Do what gcc-config would have done""" binpath = '/bin' envd = os.path.join(output_dir, 'etc', 'env.d', 'gcc', '*') srcpath = _EnvdGetVar(envd, 'GCC_PATH') for prog in os.listdir(output_dir + srcpath): # Skip binaries already wrapped. if (not prog.endswith(...
5,322,419
def symbol_directory(date: Union[str, datetime.date, None] = None, filter: str = ''): """ Args:This call returns an array of all IEX-listed securities and their corresponding data fields. The IEX-Listed Symbol Directory Daily List is initially generated and posted to the IEX website at 8:30 p.m. Eastern Tim...
5,322,420
def read_requirements(*parts): """ Return requirements from parts. Given a requirements.txt (or similar style file), returns a list of requirements. Assumes anything after a single '#' on a line is a comment, and ignores empty lines. :param parts: list of filenames which contain the instal...
5,322,421
def build_persistence(config): """ Factory method to build a Persistence object from the given config """ try: if config.getboolean("taky", "redis"): return RedisPersistence(config.get("taky", "hostname")) return Persistence() except (AttributeError, ValueError): ...
5,322,422
def EulerP_G(e0,e1,e2,e3): """ Angular velocity matrix such that omega_global = G theta_dot for Euler parameters G = 2 E Shabana (2.35, 2.54) """ G = 2*np.array([ [-e1 , e0, -e3, e2], [-e2 , e3, e0, -e1], [-e3 ,-e2, e1, e0]]) return G
5,322,423
def scale_range(x, x_range, y_range=(0.0, 1.0)): """ scale the number x from the range specified by x_range to the range specified by y_range :param x: the number to scale :type x: float :param x_range: the number range that x belongs to :type x_range: tuple :param y_range: the number range...
5,322,424
async def validate_user_password( email: str, api_key: str, user_password: str, hass: core.HomeAssistant ) -> None: """ Validates a GitHub access token. Raises a ValueError if the auth token is invalid. """ session = async_get_clientsession(hass) helper = Helper(email=email, api_key=api_key...
5,322,425
def generate_packaging(config_bundle, output_dir, repo_version='bundle', repo_hash='SKIP', build_output=DEFAULT_BUILD_OUTPUT): """ Generates an Arch Linux PKGBUILD into output_dir config_bundle is the config.ConfigBundle to use for configuration output_dir is the pathlib.Path dir...
5,322,426
def test_disabled_no_default(disabled_console): """If input is disabled and there is no default, an error is raised.""" prompt = "> " with pytest.raises(InputDisabled): disabled_console.text_input(prompt=prompt, default=None) disabled_console.rich_console.input.assert_not_called()
5,322,427
async def test_setup_unload_entry(opp, mock_remote): """Test if config entry is unloaded.""" mock_entry = MockConfigEntry( domain=DOMAIN, unique_id=MOCK_DEVICE_INFO[ATTR_UDN], data=MOCK_CONFIG_DATA ) mock_entry.add_to_opp(opp) await opp.config_entries.async_setup(mock_entry.entry_id) a...
5,322,428
def circular_difference(num1, num2): """Cicrular Difference on ring: num1 - num2 Arguments: num1 {Integer} num2 {Integer} Returns: Integer -- Circular Difference """ global M if num1 > num2: return num1 - num2 else: return int(math.pow(2, M))...
5,322,429
def find_free_port(ports_socket, name): """Retrieve a free TCP port from test server.""" request_name = '-'.join((name, str(os.getpid()))) while True: port = test_server_request(ports_socket, request_name, GETPORT) if not tcp_listening(port): return port error('port %u is...
5,322,430
def make_leaderboard() -> dict: """ make a leaderboard from the data. :rtype: dict :return: """ sync_data() # order function order = sorted(users.items(), key=lambda val: val[1]['wallet'], reverse=True) # ranks dict names = { 'first': {'id': 0, 'name': "None", 'score': 0...
5,322,431
def resolve_value_descriptor(value_descriptor: Union[str, dict]) -> Optional: """ Resolves the value of a value descriptor, which may be an environment variable name, or a map with keys `env` (the environment variable name) and `value` (the value to use if `env` is not specified or if the environment va...
5,322,432
def simple_rouse_mid_msd(t, b, N, kbT=1, xi=1, num_modes=1000): """ modified from Weber Phys Rev E 2010, Eq. 24. """ rouse_corr = 0 for p in range(1, num_modes+1): k2p = rouse_mode_coef(2*p, b, N, kbT) rouse_corr += 12*kbT/k2p*(1 - np.exp(-k2p*t/(N*xi))) return rouse_corr + 6*kbT...
5,322,433
def get_output(img): """ Input: Image as numpy array. """ height, width = img.shape c = Canvas() with open("out.txt",'w') as f: for h in range(height): for w in range(width): if img[h,w] == 255: c.set(w,h) f.write(c.frame()) ...
5,322,434
def threshold_binarize(x, threshold=0.5): """ Thresholds tensor, making each element that is more than 0.5 equal to 1. """ ge = tf.greater_equal(x, tf.constant(threshold)) y = tf.where(ge, x=tf.ones_like(x), y=tf.zeros_like(x)) return y
5,322,435
def dir_io_surface(links, nodes, dims): """ Set directionality by first building a "DEM surface" where inlets are "hills" and outlets are "depressions," then setting links such that they flow downhill. """ from scipy.stats import linregress from scipy.spatial import ConvexHull fr...
5,322,436
def guardian_join(team): """Returns a string of all of the parent guardians on the team joined together""" guardian_names = [] for player in team['team_players']: guardian_names.extend(player['guardians']) guardian_string = ", " guardian_string = guardian_string.join(guardian_names) retu...
5,322,437
def LCF_graph(n,shift_list,repeats,create_using=None): """ Return the cubic graph specified in LCF notation. LCF notation (LCF=Lederberg-Coxeter-Fruchte) is a compressed notation used in the generation of various cubic Hamiltonian graphs of high symmetry. See, for example, dodecahedral_graph, d...
5,322,438
def download_images(img_urls, dest_dir): """Given the urls already in the correct order, downloads each image into the given directory. Gives the images local filenames img0, img1, and so on. Creates an index.html in the directory with an img tag to show each local image file. Creates the directory if neces...
5,322,439
def is_prefix_of(prefix: ByteString, label: ByteString) -> bool: """ Whether label starts with prefix """ if len(prefix) > len(label): return False for (a,b) in zip(prefix, label): if a != b: return False return True
5,322,440
def lung_extraction(image, modality="proton", antsxnet_cache_directory=None, verbose=None): """ Perform proton or ct lung extraction using U-net. Arguments --------- image : ANTsImage input image modality : string Mod...
5,322,441
def adjective_to_verb(sentence, index): """ :param sentence: str that uses the word in sentence :param index: index of the word to remove and transform :return: str word that changes the extracted adjective to a verb. A function takes a `sentence` using the vocabulary word, and the `index` o...
5,322,442
def chunks(files, chunksize, max_q_size=4, shuffle=True, max_count=None): """Yield successive n-sized chunks from a and b.""" i_chunk = 0 for file in files: f = tables.open_file(file, 'r') nrows = f.root.label.nrows for istart in range(0,nrows,max_q_size*chunksize): ...
5,322,443
def test_predict_single_original_labels(): """Predict a single observation sequence and return the original label, without the un-normalized posterior scores""" prediction = hmm_clf.predict(x, prior='uniform', return_scores=False, original_labels=True) assert prediction == 'c0'
5,322,444
async def async_setup_entry(hass, config_entry): """Load the saved entities.""" _LOGGER.info( "Version %s is starting, if you have any issues please report" " them here: %s", VERSION, ISSUE_URL, ) config_entry.options = config_entry.data config_entry.add_update_listener(updat...
5,322,445
def entry(request): """ๅพฎไฟกๅค„็†ๅ…ฅๅฃ """ msg_crypt = WXBizMsgCrypt( Conf.get('WECHAT_TOKEN'), Conf.get('WECHAT_ENCODING_AES_KEY'), Conf.get('WECHAT_CORPID')) msg_signature = request.GET.get('msg_signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce'...
5,322,446
def unit2internal(src_unit: Union[str, float]): """ Convert unit to internal unit system defined above. Args: src_unit (str, float): Name of unit Returns: float: conversion factor from external to internal unit system. """ return _parse_unit(src_unit, conversion_factor=_convers...
5,322,447
def createCylinder( basePoint=(0,-1,0), tipPoint=(0,1,0), radius = 1.0, colour=(0.6,0.6,0.6), samples = 20 ): """ Creates the mesh for a cylinder between the two specified points. Colour should be a 3-tuple (R,G,B) or a 4-tuple (R,G,B,A) """ basePoint = PyUtils.toPoint3d(basePoint) tipPoint...
5,322,448
def create_dicts(dataset, sub_data_folder, num_words=30000): """ create dictionaries for seqs and comms. :param dataset: dataset_train_val_test.pkl :param sub_data_folder: each model has his onw sub_data_folder :param num_words: max num of words in the dictionary :return: """ sbts, nodes...
5,322,449
def print_bintree(tree, indent=' '): """print a binary tree""" for n in sorted(tree.keys()): print("%s%s" % (indent * depth(n,tree), n))
5,322,450
def site_disabled(config): """ Require an Apache site to be disabled. This will cause Apache to reload its configuration. :: from fabtools import require require.apache.site_disabled('default') """ disable_site(config) reload_service('apache2')
5,322,451
def clojure_find(db): """ Lazy find using __clojure_find and shelve """ str_clojure = '' if myos.iswin() or myos.islinux(): file = [] valid_file = [] if const.CLOJURE in db: file = db[const.CLOJURE] for item in file: if os...
5,322,452
def _sample_rois_manually(gt_boxes_origin, fg_rois_per_image, rois_per_image, num_classes, gt_truncated, im_info): """Args: gt_boxes_origin: Variable, [gt_num, 5], [x1, y1, x2, y2, class_id] fg_rois_per_image: int, 64 rois_per_image: float, 256.0 num_classes: int, 21 gt_truncated: ndarray.bool, ...
5,322,453
def get_worker_list(AnnotationSet): """ return a list of worker IDs """ return list(AnnotationSet.dataframe.columns)[1:]
5,322,454
def stop_talking(): """ Stop the current utterance. """ _voice.Speak("", 3)
5,322,455
def cli(): """Command-line interface for the holcrawl package.""" pass
5,322,456
def is_string(data): """ Check property string validity """ if not len(data): return None if data[-1] != 0: return None pos = 0 while pos < len(data): posi = pos while pos < len(data) and \ data[pos] != 0 and \ data[pos] in printable.encode...
5,322,457
def test_create_from_jwt_token(session): """Assert User is created from the JWT fields.""" token = {'username': 'username', 'given_name': 'given_name', 'family_name': 'family_name', 'iss': 'iss', 'sub': 'sub' } u = User.create_from_jwt_token(t...
5,322,458
def create_track_instances(f, file_instance): """ Function to parse GPX file, create new GPXtrack instances and save to database. Using gpxpy package. :param f: file path :param file_instance: file orm instance :return: """ f.name = re.sub('[()]', '', f.name) gpx_file = open(setting...
5,322,459
def find_file_in_path( filename, search_path='.', pathsep=os.pathsep, walkdir=False, path_only=False): """ Find a file matching the given name in a given search path of directories. :Parameters: filename: str The name of the file to be located. searc...
5,322,460
def Gen_DocumentTermMatrix(df_column, linguagem, stopwords, quer_stemming='True'): """Faz todo o processo de geraรงรฃo da matrix de termos dos documentos. Realiza as seguintes atividades:Stemming das palavras, geraรงรฃo do TfidfVectorizer (12000 palavr...
5,322,461
def create_hdfs_metadata_pipeline(pipeline_builder, pipeline_title, hdfs_directory, hdfs_metadata): """Helper function to create and return a pipeline with HDFS File Metadata The Deduplicator assures there is only one ingest to HDFS. The pipeline looks like: dev_raw_data_source >> record_deduplicator >>...
5,322,462
def print_process_error(err: subprocess.CalledProcessError) -> None: """ Pretty-prints the output of a failed process. Parameters ---------- err The error """ # Print output of failed command for debugging col_red = col("\033[1;31m") col_yellow = col("\033[1;33m") col...
5,322,463
def expected_file_and_data(backup=False, new_data=False): """Test of expected files and data""" assert exists("%s/%s" % (BASE_FOLDER, DATA_FOLDER_TEST1)) is True assert exists("%s/%s" % (BASE_FOLDER, DATA_FOLDER_TEST2)) is True assert exists("%s/%s" % (BASE_FOLDER, DATA_FOLDER_TEST1_FILE_1)) is True ...
5,322,464
def dqpar_interpol(xfit, dqpars, ipkey='temperature'): """return interpolated parameters at temperature or exc_current Arguments: xfit -- temperature or exc_current to fit dqpars dqpars -- list of dict with id, iq (or i1, beta), Psid and Psiq values ipkey -- key (string) to interpolate ""...
5,322,465
def writeconfig(configbase, config): """ Write supplied configuration dictionary to indicated directory """ try: os.makedirs(configbase) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(configbase): pass else: raise ...
5,322,466
def visflow_par_str(direc, size, str_type="file"): """ visflow_par_str() Returns a string with stim type, as well as size (e.g., 128, 256) and direction (e.g., "right", "left") parameters, unless all possible visual flow parameters values are passed. Required args: - direc (str or li...
5,322,467
def setup(client): """Entry point for loading extension.""" client.add_cog(Poll(client))
5,322,468
def download_from_sftp(remote: str, local: str) -> None: """Download a file from remote to local. Args: remote (str): Remote path (SFTP). local (str): Local path (local filesystem). """ try: from paramiko import AutoAddPolicy, RSAKey, SSHClient except ImportError as e: ...
5,322,469
def equ2gal(equ): """Convert single Equatorial J2000d to Galactic coordinates.""" import math as m from math import sin, cos, atan, asin, floor ra, dec = equ OB = m.radians(23.4333334); dec = m.radians(dec) ra = m.radians(ra) a = 27.128251 # The RA of the North Galactic Pole d =...
5,322,470
def main(): # pragma: no cover """Main entry point. Look for a ``cli.py``, and, if found, add its commands to `kedro`'s before invoking the CLI. """ _init_plugins() cli_collection = KedroCLI(project_path=Path.cwd()) cli_collection()
5,322,471
def pre_residual_correlation(labels, model_out, label_idx, **trash): """Generates the initial labels used for residual correlation""" # what happened: # z = model_out; y = labels # it take inputs of BOTH model_out and labels # then, assign (y-z) at indexed locs, and 0 elsewhere. lab...
5,322,472
def trimesh2Panda(trimesh, name = "auto"): """ cvt trimesh models to panda models :param trimesh: :return: """ return packpandanp_fn(trimesh.vertices, trimesh.face_normals, trimesh.faces)
5,322,473
def reachabilityquicktest_update(request, reachabilityquicktest_id, **params): """Update a reachability quick test. :param request: request context :param tenant_id: (optional) tenant id of the reachability test modified :param name: name of the reachability test :param src_tenant_id: tenant id of ...
5,322,474
def compute_similarity(left, right, tokenize=False, stop_words=None, **kwds): """Compute cosine similarity from tfidf-weighted matrix consisting of two vectors (left and right). """ from sklearn.feature_extraction.text import TfidfVectorizer def tokenize_and_stem(text): """Auxiliary functio...
5,322,475
def solve(dataframe:pd.DataFrame): """ # scripting out ortools model construction and run # df: dataframe input containing every shipment. # distances: distance matrix of all point to point calculations. # [[n0-n0, n0-n1, n0-n2, n0-n3], [...], ...] # vehicles: matrix for truck definition. #...
5,322,476
def load_config(config_file_path, seed=-1, gpuid=-1): """ Read config and set up the logger :param config_file_path: path to the config file in the yaml format :return: config, logger """ with open(config_file_path, 'r') as config_file: config = yaml.load(config_file.read()) config_...
5,322,477
def hr_max_sqi(nn_intervals): """ Function returning the max heart rate . The input nn_interval in ms is converted into heart rate bpm (beat per minute) unit Parameters --------- nn_intervals : list Normal to Normal Interval Returns --------- : float The maximum...
5,322,478
def fft(x): """ Layer that performs a fast Fourier-Transformation. """ img_size = x.size(1) // 2 # sort the incoming tensor in real and imaginary part arr_real = x[:, 0:img_size].reshape(-1, int(sqrt(img_size)), int(sqrt(img_size))) arr_imag = x[:, img_size:].reshape(-1, int(sqrt(img_size)),...
5,322,479
def generate_elgamal_auxiliary_key_pair( owner_id: GUARDIAN_ID, sequence_order: int ) -> AuxiliaryKeyPair: """ Generate auxiliary key pair using elgamal :return: Auxiliary key pair """ elgamal_key_pair = elgamal_keypair_random() return AuxiliaryKeyPair( owner_id, sequence_ord...
5,322,480
def helpeePart(bot, trigger): """Dispatch for removing somebode from the helpee list when they leave the channel.""" if trigger.sender != bot.config.helpbot.channel: return else: removeHelpee(bot, trigger)
5,322,481
def gene_knowledge_graph(anno_dir, data_dir): """ This function is to generate the knowledge graph including nodes and its edges. :param anno_dir: the annotation file directions :param data_dir: the data file directions :return: graph """ node_representation = np.zeros((6, 256)) # in...
5,322,482
def test_dummy(): """Dummy to quiet pytest for now""" assert True
5,322,483
def addExpressConfig(config, streamName, **options): """ _addExpressConfig_ Add an express configuration to a given stream. """ streamConfig = retrieveStreamConfig(config, streamName) streamConfig.ProcessingStyle = "Express" streamConfig.VersionOverride = options.get("versionOverride", {}...
5,322,484
def benchmark_random(backtest, random_strategy, nsim=100): """ Given a backtest and a random strategy, compare backtest to a number of random portfolios. The idea here is to benchmark your strategy vs a bunch of random strategies that have a similar structure but execute some part of the logic ...
5,322,485
def detachStatement(request): """ ํ•˜๋‚˜์˜ ์ „์ž๋ช…์„ธ์„œ์— ์ฒจ๋ถ€๋œ ๋‹ค๋ฅธ ์ „์ž๋ช…์„ธ์„œ๋ฅผ ํ•ด์ œํ•ฉ๋‹ˆ๋‹ค. - https://docs.popbill.com/statement/python/api#DetachStatement """ try: # ํŒ๋นŒํšŒ์› ์‚ฌ์—…์ž๋ฒˆํ˜ธ CorpNum = settings.testCorpNum # ํŒ๋นŒํšŒ์› ์•„์ด๋”” UserID = settings.testUserID # ์ „์ž๋ช…์„ธ์„œ ์ข…๋ฅ˜์ฝ”๋“œ, 121-๋ช…์„ธ์„œ, 122-์ฒญ๊ตฌ์„œ, 123...
5,322,486
def this(func, cache_obj=CACHE_OBJ, key=None, ttl=None, *args, **kwargs): """ Store the output from the decorated function in the cache and pull it from the cache on future invocations without rerunning. Normally, the value will be stored under a key which takes into account all of the parameters t...
5,322,487
def get_data(table,cid,fields=None,date=None): """ table = name of database table fields = list of database fields to return key = dict with unique identifier and value """ status = False sql = "SELECT " if fields: sql += ','.join(fields) else: sql += "*" s...
5,322,488
def jwt_perm_required(perms: List[str]) -> Callable: """ Receives a list of permissions and only process the inner function if the jwt token available in the input request have the required permissions. """ def process_func(func: Callable) -> Callable: """ Similar to the original Dja...
5,322,489
def test_filters(): """ Testing export movie with temporal and spatial filters """ export_fake_data_movie({"Signal_Signal_FilterSpaceFlag": True, "Signal_Signal_FilterSpaceSize": 3}, "space_filter_3") export_fake_data_movie({"Signal_Signal_FilterTimeFlag": True, "Signal_Signal_FilterTimeSize": 3}, ...
5,322,490
def get_park1_function_caller(**kwargs): """ Returns the park1 function caller. """ opt_val = 25.5872304 opt_pt = None func = lambda x: park1(x, opt_val) domain_bounds = [[0, 1]] * 4 return get_euc_function_caller_from_function(func, domain_bounds, vectorised=False, opt_val=opt_val, opt_pt=opt_pt...
5,322,491
def univariate_analysis(groups): """Mean, median, variance""" groups_to_analyze = [] basic = {} central_tendencies = {} dispersion = {} all_vals = np.array([]) for group in groups: all_vals = np.concatenate((all_vals, group['vals']), axis=0) groups_to_analyze.append(group) ...
5,322,492
def closedoor(): """Runs motor backwards""" GPIO.output(M1_IN2, False) GPIO.output(M1_IN1, True)
5,322,493
async def test_kubernetes_api_error_handling(aiohttp_server, config, db, loop): """Test the behavior of the Controller in case of a Kubernetes error.""" # Create an actual "kubernetes cluster" with no route, so it responds wrongly # to the requests of the Controller. kubernetes_app = web.Application() ...
5,322,494
def init_weights(net, init_type='normal', init_gain=0.02): """Initialize network weights. Parameters: net (network) -- network to be initialized init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal init_gain (float) -- scaling factor...
5,322,495
def create_version_dialog(request): """creates a create_version_dialog by using the given task """ logger.debug('inside create_version_dialog') # get logged in user logged_in_user = get_logged_in_user(request) task_id = request.matchdict.get('tid', -1) task = Task.query.filter(Task.task_id...
5,322,496
def create_qnode_for_causx(): """create a custom qnode""" project = get_project() request_json = request.get_json() try: label = request_json.pop("label") # is_prop=node_id[0].lower()=="p" is_prop = request_json.pop("is_property") if is_prop: data_type = reque...
5,322,497
def smape(actual_series: TimeSeries, pred_series: TimeSeries, intersect: bool = True, reduction: Callable[[np.ndarray], float] = np.mean) -> float: """ symmetric Mean Absolute Percentage Error (sMAPE). Given a time series of actual values :math:`y_t` and a time series of predicted...
5,322,498
def func_two(x): """ Harder function for testing on. """ return np.sin(4 * (x - 1/4)) + x + x**20 - 1
5,322,499