How to use extract_keys method in localstack

Best Python code snippet using localstack_python

weights.py

Source:weights.py Github

copy

Full Screen

1"""Weights are associated with nodes/elements and/or edges.2To each node/edge, multiple weights can be given.3Weights are stored as a dictionary:4- nbr_n : int: Number of nodes/edges.5- nbr_c : int: Number of criteria: number of weights per node/edge.6- weights: ((int, ...), ...): In cell (i, c): the cth weight of7 the ith node/edge.8- totals : (int, ...): If cell c: the sum of the cth weight of all9 nodes/edges10"""11__author__ = "Rémi Barat"12__version__ = "1.0"13from crack.utils.errors import crack_error14######################15### Initialization ###16######################17def format_crit(crit_spec):18 """Format the criteria as a list of int. Criteria can be entered19 as:20 - an int21 >>> crit: 1 # outputs: [1]22 - a list of int23 >>> crit: [0, 2] # outputs: [0, 2]24 - a string seperating numbers with ',' and/or '-'25 >>> crit: 0, 2-4 # outputs: [0, 2, 3, 4]26 """27 if isinstance(crit_spec, int):28 crit = [crit_spec]29 elif isinstance(crit_spec, list):30 crit = crit_spec31 elif isinstance(crit_spec, str):32 crit = []33 for subc in crit_spec.split(","):34 if "-" in subc:35 begin, end = tuple(subc.split("-"))36 crit.extend(range(int(begin), int(end)))37 else:38 crit.append(int(subc))39 else:40 crack_error(ValueError, "init_Weights_...",41 "Unrecognized 'crit' (got {}). Should be an int, or list of int, or str of int and ',' and '-'.".format(crit_spec))42 return crit43def _add_wgts_key(models, key_in, key_out, nbr_n, nbr_c, entity):44 """If [key_out] (typically, "nweights") is not in [models],45 add it and initialize its fields. [key_in] is the list of the46 weights keys (used to automatically modify the weights when47 coarsening/prolonging).48 """49 if not isinstance(key_in, list):50 key_in = [key_in]51 if key_out in models:52 wgts = models[key_out]53 c_old = wgts["nbr_c"]54 if nbr_c > c_old:55 d = nbr_c - c_old56 wgts["nbr_c" ] = nbr_c57 wgts["weights"] = [w + [0] * d for w in wgts["weights"]]58 wgts["totals" ] = wgts["totals"] + [0] * d59 for k in key_in:60 if k not in wgts["keys"]:61 wgts["keys"].append(key_in)62 else:63 models[key_out] = {64 "entity" : entity,65 "nbr_n" : nbr_n,66 "nbr_c" : nbr_c,67 "weights": [[0] * nbr_c for _ in range(nbr_n)],68 "totals" : [0] * nbr_c,69 "keys" : key_in,70 }71# Called before the nweights/eweights initialization functions72def condition_models(init_fct, models, records, crit, key_out, entity, **kwargs):73 """Prepare the [models] to the [init_fct].74 Indeed, an init_[NEH]Weights_xxx function will add the computed75 weights to *models[key_out][c]* where c are specified in [crit].76 Arguments:77 crit: int or list of int or str. See *format_crit* function.78 key_out: str79 """80 keys_in = kwargs.get("key_in")81 if isinstance(keys_in, list):82 key_in = keys_in[0]83 else:84 key_in = keys_in85 if key_in is not None:86 kwargs["key_in"] = key_in87 # Format the list of criteria that will be initialized88 crit = format_crit(crit)89 nbr_c = max(crit) + 190 for c in crit:91 wgts = init_fct(models, records, **kwargs)92 nbr_n = len(wgts)93 if key_out not in models or nbr_c > models[key_out]["nbr_c"]:94 _add_wgts_key(models, keys_in, key_out, nbr_n, nbr_c, entity)95 totc = 096 for i, w in enumerate(wgts):97 models[key_out]["weights"][i][c] += w98 totc += w99 models[key_out]["totals"][c] += totc100#*********************************#101# Common initialization functions #102#*********************************#103# (that are not specific to nweights/eweights)104def init_Weights_from_file(models, records, filename=None, extract_keys=None):105 """Initialize the weights from data stored in a file.106 Arguments:107 models: dict: The Weights will be stored here.108 filename: str: Path to the file which contains the data. An109 example of such file is provided below.110 Optional Arguments:111 extract_keys: str or list of str or dict: The keys of the112 weights that will be extracted. If dict, maps the extracted113 keys with the keys that will be used in the current session.114 If None, all weights will be extracted.115 Example: 2 node weights of 3 criteria, 2 edge weights of 1 criterion116 >>> # weights nweights 2 3117 >>> 10 80 13118 >>> 100 93 12119 >>> # weights my_edge_wgts 2 1120 >>> 12121 >>> 39122 If [extract_keys] is None, [models] will be updated with:123 >>> "nweights": {124 >>> "entity" : "weights",125 >>> "nbr_n" : 2,126 >>> "nbr_c" : 3,127 >>> "weights": ((10, 80, 13), (100, 93, 12)),128 >>> "totals" : (110, 173, 25)129 >>> }130 >>> "my_edge_wgts": {131 >>> "entity" : "weights",132 >>> "nbr_n" : 2,133 >>> "nbr_c" : 1,134 >>> "weights": ((12,), (39,))135 >>> "totals" : (51,)136 >>> }137 """138 if filename is None:139 crack_error(ValueError, "init_Weights_from_file",140 "Need to provide a 'filename' from which the Weights will be read.")141 # Which keys will we retrieve data from?142 if extract_keys is not None:143 if isinstance(extract_keys, str):144 extract_keys = {extract_keys: extract_keys}145 elif isinstance(extract_keys, list):146 extract_keys = {k: k for k in extract_keys}147 elif not isinstance(extract_keys, dict):148 crack_error(ValueError, "init_Weights_from_file",149 "Wrong type of 'extract_keys' (should be str, list or dict).")150 # Read file to retrieve data151 with open(filename, "r") as f:152 for line in f:153 if not line or line[0] != "#":154 continue155 words = line.split()156 if words[1] != "weights":157 continue158 key_out = None159 if extract_keys is None:160 key_out = words[2]161 elif words[2] in extract_keys:162 key_out = extract_keys[words[2]]163 if key_out is not None:164 nbr_n = int(words[3])165 nbr_c = int(words[4])166 wgts = [None] * nbr_n167 tots = [0] * nbr_c168 for i in range(nbr_n):169 line = f.readline()170 wgts[i] = [int(w) for w in line.split()]171 for c, w in enumerate(wgts):172 tots[c] += w173 models[key_out] = {174 "entity" : "weights",175 "nbr_n" : nbr_n,176 "nbr_c" : nbr_c,177 "weights": wgts,178 "totals" : tots,179 }180def init_Weights_normalized(models, records, key_in, key_out=None):181 """Create a normalized weight distribution (in [key_out]) from the182 weight distribution in [key_in].183 """184 if key_out is None:185 key_out = key_in + "__norm"186 wgts = models[key_in]["weights"]187 tots = models[key_in]["totals"]188 models[key_out] = {189 "entity" : "weights",190 "nbr_n" : models[key_in]["nbr_n"],191 "nbr_c" : models[key_in]["nbr_c"],192 "weights": [193 [wc / tot_c for wc, tot_c in zip(w, tots)]194 for w in wgts195 ],196 "totals" : [1] * models[key_in]["nbr_c"],...

Full Screen

Full Screen

phase_data_interpolate.py

Source:phase_data_interpolate.py Github

copy

Full Screen

1#!/usr/bin/env python32# -*- coding: utf-8 -*-3"""4Created on Tue Jul 28 23:38:23 20205@author: tquah6"""7import pickle8import numpy as np9import os10import matplotlib.pyplot as plt11from scipy.interpolate import interp1d12import pandas as pd13import argparse14import glob15import shutil 16if __name__ == '__main__':17 parser = argparse.ArgumentParser(description='Tool to compute phase boundaries')18 parser.add_argument('-dp', '--dict_path', action='store', default='data.dict',help='Dictionary import that has all Free energy data')19 parser.add_argument('-dir', '--dirname', action='store', default='Interpolated',help='Directory export name')20 parser.add_argument('-e', '--export_path', action='store', default=os.getcwd(),help='Export Path for mass files')21 parser.add_argument('-n', '--Neff', action='store', default=2100,help='N_eff values',type = float)22 parser.add_argument('-dx', '--dx', action='store', default=0.005,help='dx to create',type = float)23 parser.add_argument('-r', '--reference_phase', action='store', default='',help='Reference phase',type = str)24 parser.add_argument('-diagnostic', '--plot_diagnositic', action='store', default=False,help='Diagnostic Tools for Phase Diagrams',type = bool)25 parser.add_argument('-k', '--keywrd', action='store', default=[''],help='Keyword used to name dimensions',type = str)26 parser.add_argument('-f', '--filename', action='store', default='F0_phases.dat',help='file that contains the phases and free energies at each phase point')27 args = parser.parse_args()28 29 args.dict_path = '/home/tquah/IMPORT_BRAID/diblock_phasediagram/data.dict'30 args.export_path = '/home/tquah/IMPORT_BRAID/'31 args.keywrd = ['chi','f']32 # os.chdir(args.dict_path)33 export_path_full = os.path.join(args.export_path,args.dirname)34 with open(args.dict_path, 'rb') as handle:35 F0dat = pickle.load(handle)36 F0_interp = dict()37 extract_keys = []38 for i in range(0,len(list(F0dat)[0])):39 extract_keys.append([])40 41 42 43 for i in range(0,len(F0dat)):44 for j in range(0,len(list(F0dat)[0])):45 extract_keys[j].append(list(F0dat)[i][j])46 for i in range(0,len(list(F0dat)[0])):47 extract_keys[i] = sorted(list(set(extract_keys[i])))48 49 50 oldindex = extract_keys[-1].index('DIS')51 52 extract_keys[-1].insert(0, extract_keys[-1].pop(oldindex))53 if len(list(F0dat)[0])==2:54 55 for i in range(0,len(extract_keys[1])):56 for j in range(0,len(extract_keys[0])):57 if (extract_keys[0][j],extract_keys[1][i]) in F0dat:58 data_array = F0dat[extract_keys[0][j],extract_keys[1][i]]59 if len(np.shape(data_array))>1:60 data_array = data_array[data_array[:,0].argsort()]61 62 fmin = np.min(data_array[:,0])63 fmax = np.max(data_array[:,0])64 fun = interp1d(data_array[:,0],data_array[:,1])65 farray = np.around(np.arange(fmin,fmax+1e-6,args.dx),5)66 yarray = fun(farray)67 68 for k in range(0,len(farray)):69 chiN = extract_keys[0][j]*args.Neff70 71 fullexportname = f'{args.keywrd[0]}_{chiN:0.3f}/{args.keywrd[1]}{farray[k]:0.5f}' 72 fullexportpath = os.path.join(export_path_full,fullexportname)73 if os.path.exists(fullexportpath):74 pass75 else:76 os.makedirs(fullexportpath)77 filepath = os.path.join(fullexportpath,args.filename)78 if extract_keys[1][i]=='DIS': 79 f0 = open(filepath,'w')80 f0.write(f'{extract_keys[1][i]}Phase {yarray[k]} 2')81 f0.write('\n')82 f0.close()83 else:84 f0 = open(filepath,'a')85 f0.write(f'{extract_keys[1][i]}Phase {yarray[k]} 2')86 f0.write('\n')87 f0.close()88 else:89 print('Dimension is not 2')90 91 # for i in range(0,len(list(F0dat))):92 # F0_interp[list(F0dat)] = dict()93 # if len(np.shape(F0dat[list(F0dat)[i]]))>1:94 # array = F0dat[list(F0dat)[i]][F0dat[list(F0dat)[i]][:,0].argsort()]95 96 97 98 # else:...

Full Screen

Full Screen

settle_fida_event.py

Source:settle_fida_event.py Github

copy

Full Screen

...10 fila[n] = row11 n += 112 fil.close()13 return fila14def extract_keys(fil_in_put,info):15 16 if info == 'market_serum':17 li = 018 if info == 'secret_b58':19 li = 120 if info == 'public_key_sol':21 li = 222 if info == 'token_mint_wallet_bas':23 li = 324 if info == 'token_mint_wallet_quo':25 li = 426 line = fil_in_put[li][0]27 lon =len(line)28 ch = 029 key = ''30 for i in range(lon):31 if ch == 1 and int(ord(line[i])) != 39:32 key = key + line[i]33 if int(ord(line[i])) == 39:34 if ch == 0:35 ch = 136 else:37 ch = 038 return key39market_serum = extract_keys(fich_input('info_market_wallet'),'market_serum') #address of the iso market FIDA-USDT40secret_b58 = extract_keys(fich_input('info_market_wallet'),'secret_b58') #secret key from sollet.io41public_key_sol = extract_keys(fich_input('info_market_wallet'),'public_key_sol') #wallet SOL42token_mint_wallet_bas = extract_keys(fich_input('info_market_wallet'),'token_mint_wallet_bas') #wallet mint FIDA43token_mint_wallet_quo = extract_keys(fich_input('info_market_wallet'),'token_mint_wallet_quo') #wallet mint USDT44cfApisol = cfApi_sol.SolSerumClient(secret_b58=secret_b58,market_address=market_serum, owner_wallet=public_key_sol,\45 token_mint_wallet_bas=token_mint_wallet_bas, token_mint_wallet_quo=token_mint_wallet_quo)46print(cfApisol.check_pub_key())47cfApisol.settl_withCheck_done(0,0)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful