code
stringlengths
1
18.2k
def get_job_list(self, project_name): """ Get the list of pending, running and finished jobs of some project. :param project_name: the project name :return: a dictionary that list inculde job name and status example: {"status": "ok", "pending": [{"id": "78391cc0fcaf11e1b0090800272a6d06", "spider": "spider1"}], "running...
def get_logs(self, project_name, spider_name): """ Get urls that scrapyd logs file by project name and spider name :param project_name: the project name :param spider_name: the spider name :return: two list of the logs file name and logs file url """ url, method = self.command_set['logs'][0] + project_name + '/' + spid...
def lspci(vendor=None, device=None): """Collect PCI information and return its list. Parameters ---------- vendor : int Return only devices with specified vendor ID. device : int Return only devices with specified device ID. Returns ------- list List of PCI device information. Information are stored in PCIConfigHeader ...
def read(bar, offset, size): """Read PCI data register. Parameters ---------- bar : BaseAddressRegister BAR to read. offset : int Address offset in BAR to read. size : int Data size to read. Returns ------- bytes Data read from BAR Examples -------- >>> b = pypci.lspci(vendor=0x1147, device=3214) >>> pypci.read(b[0].ba...
def write(bar, offset, data): """Write data to PCI board. Parameters ---------- bar : BaseAddressRegister BAR to write. offset : int Address offset in BAR to write. data : bytes Data to write. Returns ------- None Examples -------- >>> b = pypci.lspci(vendor=0x1147, device=3214) >>> pypci.write(b[0].bar[2], 0x04, b'\x0...
def get_data_files(): """ Returns the path of data files, which are installed to the package directory. """ import os path = os.path.dirname(__file__) path = os.path.join(path, 'data') r = dict( Alpha_inf_hyrec_file = os.path.join(path, 'hyrec', 'Alpha_inf.dat'), R_inf_hyrec_file = os.path.join(path, 'hyrec', 'R_inf.da...
def _find_file(filename): """ Find the file path, first checking if it exists and then looking in the data directory """ import os if os.path.exists(filename): path = filename else: path = os.path.dirname(__file__) path = os.path.join(path, 'data', filename) if not os.path.exists(path): raise ValueError("cannot locate ...
def load_precision(filename): """ Load a CLASS precision file into a dictionary. Parameters ---------- filename : str the name of an existing file to load, or one in the files included as part of the CLASS source Returns ------- dict : the precision parameters loaded from file """ # also look in data dir path = _find_f...
def load_ini(filename): """ Read a CLASS ``.ini`` file, returning a dictionary of parameters Parameters ---------- filename : str the name of an existing parameter file to load, or one included as part of the CLASS source Returns ------- dict : the input parameters loaded from file """ # also look in data dir path = _f...
pars[fields[0].strip()] = fields[1].strip() return pars
def extract_noun_phrases(tagged_doc): """ (From textblob) """ tags = _normalize_tags(tagged_doc) merge = True while merge: merge = False for x in range(0, len(tags) - 1): t1 = tags[x] t2 = tags[x + 1] key = t1[1], t2[1] value = CFG.get(key, '') if value: merge = True tags.pop(x) tags.pop(x) match = '%s %s' % (t1[0], t2...
def _normalize_tags(chunk): """ (From textblob) Normalize the corpus tags. ("NN", "NN-PL", "NNS") -> "NN" """ ret = [] for word, tag in chunk: if tag == 'NP-TL' or tag == 'NP': ret.append((word, 'NNP')) continue if tag.endswith('-TL'): ret.append((word, tag[:-3])) continue if tag.endswith('S'): ret.append((word, tag[:-...
def save_patt(patt, filename): """Saves ScalarPatternUniform object 'patt' to file. The first line of the file has the number of rows and the number of columns in the pattern separated by a comma (single sphere data). The remaining lines have the form: 0, 1, 3.14, 2.718 The first two numbers are index for the row and i...
def save_coef(scoef, filename): """Saves ScalarCoeffs object 'scoef' to file. The first line of the file has the max number N and the max number M of the scoef structure separated by a comma. The remaining lines have the form 3.14, 2.718 The first number is the real part of the mode and the second is the imaginary. """...
def load_patt(filename): """Loads a file that was saved with the save_patt routine.""" with open(filename) as f: lines = f.readlines() lst = lines[0].split(',') patt = np.zeros([int(lst[0]), int(lst[1])], dtype=np.complex128) lines.pop(0) for line in lines: lst = line.split(',') n = int(lst[0]) m = int(lst[1]) re = flo...
def load_vpatt(filename1, filename2): """Loads a VectorPatternUniform pattern that is saved between two files. """ with open(filename1) as f: lines = f.readlines() lst = lines[0].split(',') patt1 = np.zeros([int(lst[0]), int(lst[1])], dtype=np.complex128) lines.pop(0) for line in lines: lst = line.split(',') n = int(ls...
def load_coef(filename): """Loads a file that was saved with save_coef.""" with open(filename) as f: lines = f.readlines() lst = lines[0].split(',') nmax = int(lst[0]) mmax = int(lst[1]) L = (nmax + 1) + mmax * (2 * nmax - mmax + 1); vec = np.zeros(L, dtype=np.complex128) lines.pop(0) for n, line in enumerate(lines): l...
def load_vcoef(filename): """Loads a set of vector coefficients that were saved in MATLAB. The third number on the first line is the directivity calculated within the MATLAB code.""" with open(filename) as f: lines = f.readlines() lst = lines[0].split(',') nmax = int(lst[0]) mmax = int(lst[1]) directivity = float(lst[2...
def parse(cls, filename, max_life=None): """ Parse barcode from gudhi output. """ data = np.genfromtxt(filename) #data = np.genfromtxt(filename, dtype= (int, int, float, float)) if max_life is not None: data[np.isinf(data)] = max_life return data
def plot(self, dimension): """ Plot barcode using matplotlib. """ import matplotlib.pyplot as plt life_lines = self.get_life_lines(dimension) x, y = zip(*life_lines) plt.scatter(x, y) plt.xlabel("Birth") plt.ylabel("Death") if self.max_life is not None: plt.xlim([0, self.max_life]) plt.title("Persistence Homology Dimen...
def from_config(cls, name, config): """ Returns a Configurable instance with the given name and config. By default this is a simple matter of calling the constructor, but subclasses that are also `Pluggable` instances override this in order to check that the plugin is installed correctly first. """ cls.validate_config(...
def get_args(): """ Supports the command-line arguments listed below. """ parser = argparse.ArgumentParser( description="Provision multiple VM's through mist.io. You can get " "information returned with the name of the virtual machine created " "and its main mac and ip address in IPv4 format. A post-script can be " "sp...
required=False, help='The name of the backend to use for provisioning.' ' Defaults to the first available backend', dest='backend_name', type=str) parser.add_argument('-I', '--image-id', required=True, help='The image to deploy', dest='image_id') parser.add_argument('-S', '--size-id', required=True, help='The id of the...
user is prompted at runtime for' ' a password', dest='password', type=str) parser.add_argument('-v', '--verbose', required=False, help='Enable verbose output', dest='verbose', action='store_true') parser.add_argument('-w', '--wait-max', nargs=1, required=False, help='Maximum amount of seconds to wait when gathering' ' ...
def command(state, args): """List file priority rules.""" rules = query.files.get_priority_rules(state.db) print(tabulate(rules, headers=['ID', 'Regexp', 'Priority']))
def filter_support(candidates, transactions, min_sup): """ Filter candidates to a frequent set by some minimum support. """ counts = defaultdict(lambda: 0) for transaction in transactions: for c in (c for c in candidates if set(c).issubset(transaction)): counts[c] += 1 return {i for i in candidates if counts[i]/len(tra...
def generate_candidates(freq_set, k): """ Generate candidates for an iteration. Use this only for k >= 2. """ single_set = {(i,) for i in set(flatten(freq_set))} # TO DO generating all combinations gets very slow for large documents. # Is there a way of doing this without exhaustively searching all combinations? cands ...
def validate_candidate(candidate, freq_set, k): """ Checks if we should keep a candidate. We keep a candidate if all its k-1-sized subsets are present in the frequent sets. """ for subcand in combinations(candidate, k-1): if subcand not in freq_set: return False return True
def tokenize(self, docs): """ The first pass consists of converting documents into "transactions" (sets of their tokens) and the initial frequency/support filtering. Then iterate until we close in on a final set. `docs` can be any iterator or generator so long as it yields lists. Each list represents a document (i.e. i...
phrases. for doc in POSTokenizer().tokenize(docs): transaction = set(doc) candidates = candidates.union({(t,) for t in transaction}) transactions.append(transaction) freq_set = filter_support(candidates, transactions, self.min_sup) # Iterate k = 2 last_set = set() while freq_set != set(): last_set = freq_set cands = ge...
def compile_tag_re(self, tags): """ Return the regex used to look for Mustache tags compiled to work with specific opening tags, close tags, and tag types. """ return re.compile(self.raw_tag_re % tags, self.re_flags)
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." User = orm[user_orm_label] try: user = User.objects.all()[0] for article in orm.Article.objects.all(): article.author = user article.save() except IndexError: pass
def dumps(value,encoding=None): """dumps(object,encoding=None) -> string This function dumps a python object as a tnetstring. """ # This uses a deque to collect output fragments in reverse order, # then joins them together at the end. It's measurably faster # than creating all the intermediate strings. # If you're read...
def _rdumpq(q,size,value,encoding=None): """Dump value as a tnetstring, to a deque instance, last chunks first. This function generates the tnetstring representation of the given value, pushing chunks of the output onto the given deque instance. It pushes the last chunk first, then recursively generates more chunks. Wh...
value is False: write("5:false!") return size + 8 if isinstance(value,(int,long)): data = str(value) ldata = len(data) span = str(ldata) write("#") write(data) write(":") write(span) return size + 2 + len(span) + ldata if isinstance(value,(float,)): # Use repr() for float rather than str(). # It round-trips more accura...
1 + len(span) if isinstance(value,dict): write("}") init_size = size = size + 1 for (k,v) in value.iteritems(): size = _rdumpq(q,size,v,encoding) size = _rdumpq(q,size,k,encoding) span = str(size - init_size) write(":") write(span) return size + 1 + len(span) if isinstance(value,unicode): if encoding is None: raise Val...
def _gdumps(value,encoding): """Generate fragments of value dumped as a tnetstring. This is the naive dumping algorithm, implemented as a generator so that it's easy to pass to "".join() without building a new list. This is mainly here for comparison purposes; the _rdumpq version is measurably faster as it doesn't have...
yield "]" elif isinstance(value,(dict,)): sub = [] for (k,v) in value.iteritems(): sub.extend(_gdumps(k)) sub.extend(_gdumps(v)) sub = "".join(sub) yield str(len(sub)) yield ":" yield sub yield "}" elif isinstance(value,(unicode,)): if encoding is None: raise ValueError("must specify encoding to dump unicode strings") ...
def load(file,encoding=None): """load(file,encoding=None) -> object This function reads a tnetstring from a file and parses it into a python object. The file must support the read() method, and this function promises not to read more data than necessary. """ # Read the length prefix one char at a time. # Note that the ...
# Now we can read and parse the payload. # This repeats the dispatch logic of pop() so we can avoid # re-constructing the outermost tnetstring. data = file.read(datalen) if len(data) != datalen: raise ValueError("not a tnetstring: length prefix too big") type = file.read(1) if type == ",": if encoding is not None: retu...
if type == "]": l = [] while data: (item,data) = pop(data,encoding) l.append(item) return l if type == "}": d = {} while data: (key,data) = pop(data,encoding) (val,data) = pop(data,encoding) d[key] = val return d raise ValueError("unknown type tag")
def pop(string,encoding=None): """pop(string,encoding=None) -> (object, remain) This function parses a tnetstring into a python object. It returns a tuple giving the parsed object and a string containing any unparsed data from the end of the string. """ # Parse out data length, type and remaining string. try: (dlen,res...
ValueError: raise ValueError("not a tnetstring: invalid integer literal") if type == "^": try: return (float(data),remain) except ValueError: raise ValueError("not a tnetstring: invalid float literal") if type == "!": if data == "true": return (True,remain) elif data == "false": return (False,remain) else: raise ValueE...
def log_magnitude_spectrum(frames): """Compute the log of the magnitude spectrum of frames""" return N.log(N.abs(N.fft.rfft(frames)).clip(1e-5, N.inf))
def RMS_energy(frames): """Computes the RMS energy of frames""" f = frames.flatten() return N.sqrt(N.mean(f * f))
def normalize_features(features): """Standardizes features array to fall between 0 and 1""" return (features - N.min(features)) / (N.max(features) - N.min(features))
def zero_crossing_last(frames): """Finds the last zero crossing in frames""" frames = N.array(frames) crossings = N.where(N.diff(N.sign(frames))) # crossings = N.where(frames[:n] * frames[1:n + 1] < 0) if len(crossings[0]) == 0: print "No zero crossing" return len(frames) - 1 return crossings[0][-1]
def limiter(arr): """ Restrict the maximum and minimum values of arr """ dyn_range = 32767.0 / 32767.0 lim_thresh = 30000.0 / 32767.0 lim_range = dyn_range - lim_thresh new_arr = arr.copy() inds = N.where(arr > lim_thresh)[0] new_arr[inds] = (new_arr[inds] - lim_thresh) / lim_range new_arr[inds] = (N.arctan(new_arr[ind...
def linear(arr1, arr2): """ Create a linear blend of arr1 (fading out) and arr2 (fading in) """ n = N.shape(arr1)[0] try: channels = N.shape(arr1)[1] except: channels = 1 f_in = N.linspace(0, 1, num=n) f_out = N.linspace(1, 0, num=n) # f_in = N.arange(n) / float(n - 1) # f_out = N.arange(n - 1, -1, -1) / float(n) if ch...
def equal_power(arr1, arr2): """ Create an equal power blend of arr1 (fading out) and arr2 (fading in) """ n = N.shape(arr1)[0] try: channels = N.shape(arr1)[1] except: channels = 1 f_in = N.arange(n) / float(n - 1) f_out = N.arange(n - 1, -1, -1) / float(n) if channels > 1: f_in = N.tile(f_in, (channels, 1)).T f_out =...
def segment_array(arr, length, overlap=.5): """ Segment array into chunks of a specified length, with a specified proportion overlap. Operates on axis 0. :param integer length: Length of each segment :param float overlap: Proportion overlap of each frame """ arr = N.array(arr) offset = float(overlap) * length total_seg...
def _reorder_via_klist(d,nkl,**kwargs): ''' d = {'scheme': 'http', 'path': '/index.php', 'params': 'params', 'query': 'username=query', 'fragment': 'frag', 'username': '', 'password': '', 'hostname': 'www.baidu.com', 'port': ''} pobj(d) nkl = ['scheme', 'username', 'password', 'hostname', 'port', 'path', 'params', 'que...
def _keys_via_value_nonrecur(d,v): ''' #non-recursive d = {1:'a',2:'b',3:'a'} _keys_via_value_nonrecur(d,'a') ''' rslt = [] for key in d: if(d[key] == v): rslt.append(key) return(rslt)
def _keys_via_value(d,value,**kwargs): ''' d = { 'x': { 'x2': 'x22', 'x1': 'x11' }, 'y': { 'y1': 'v1', 'y2': { 'y4': 'v4', 'y3': 'v3', }, 'xx': { 'x2': 'x22', 'x1': 'x11' } }, 't': 20, 'u': { 'u1': 20 } } ''' km,vm = _d2kvmatrix(d) rvmat = _get_rvmat(d) depth = rvmat.__len__() ## #print(km) ## kdmat = _scankm(km) if('l...
cond2 = (kdmat[i][j]['leaf'] == True) elif(non_leaf_only == True): cond2 = (kdmat[i][j]['leaf'] == False) else: cond2 = True cond = (cond1 & cond2) if(cond): rslt.append(kdmat[i][j]['path']) else: pass return(rslt)
def d2kvlist(d): ''' d = {'GPSImgDirectionRef': 'M', 'GPSVersionID': b'\x02\x03\x00\x00', 'GPSImgDirection': (21900, 100)} pobj(d) kl,vl = d2kvlist(d) pobj(kl) pobj(vl) ''' kl = list(d.keys()) vl = list(d.values()) return((kl,vl))
def klviavl(d,vl): ''' must be 1:1 map ''' dkl,dvl = d2kvlist(d) kl = [] for i in range(vl.__len__()): v = vl[i] index = dvl.index(v) kl.append(dkl[index]) return(kl)
def brkl2d(arr,interval): ''' arr = ["color1","r1","g1","b1","a1","color2","r2","g2","b2","a2"] >>> brkl2d(arr,5) [{'color1': ['r1', 'g1', 'b1', 'a1']}, {'color2': ['r2', 'g2', 'b2', 'a2']}] ''' lngth = arr.__len__() brkseqs = elel.init_range(0,lngth,interval) l = elel.broken_seqs(arr,brkseqs) d = elel.mapv(l,lambda el...
def _vksdesc(d): ''' d = {'a':1,'b':2,'c':2,'d':4} desc = _vksdesc(d) pobj(desc) ''' pt = copy.deepcopy(d) seqs_for_del =[] vset = set({}) for k in pt: vset.add(pt[k]) desc = {} for v in vset: desc[v] = [] for k in pt: desc[pt[k]].append(k) return(desc)
def tlist2dict(tuple_list,**kwargs): ''' #duplicate keys will lost tl = [(1,2),(3,4),(1,5)] tlist2dict(tl) ''' if('deepcopy' in kwargs): deepcopy = kwargs['deepcopy'] else: deepcopy = 1 if('check' in kwargs): check = kwargs['check'] else: check = 1 if(check): if(tltl.is_tlist(tuple_list)): pass else: return(None) else:...
def dict2tlist(this_dict,**kwargs): ''' #sequence will be losted d = {'a':'b','c':'d'} dict2tlist(d) ''' if('check' in kwargs): check = kwargs['check'] else: check = 1 if(check): if(isinstance(this_dict,dict)): pass else: return(None) else: pass if('deepcopy' in kwargs): deepcopy = kwargs['deepcopy'] else: deepcopy = 1...
def is_mirrable(d): ''' d = {1:'a',2:'a',3:'b'} ''' vl = list(d.values()) lngth1 = vl.__len__() uvl = elel.uniqualize(vl) lngth2 = uvl.__len__() cond = (lngth1 == lngth2) return(cond)
def dict_mirror(d,**kwargs): ''' d = {1:'a',2:'a',3:'b'} ''' md = {} if('sort_func' in kwargs): sort_func = kwargs['sort_func'] else: sort_func = sorted vl = list(d.values()) uvl = elel.uniqualize(vl) for v in uvl: kl = _keys_via_value_nonrecur(d,v) k = sorted(kl)[0] md[v] = k return(md)
def _cond_select_key_nonrecur(d,cond_match=None,**kwargs): ''' d = { "ActiveArea":"50829", "Artist":"315", "AsShotPreProfileMatrix":"50832", "AnalogBalance":"50727", "AsShotICCProfile":"50831", "AsShotProfileName":"50934", "AntiAliasStrength":"50738", "AsShotNeutral":"50728", "AsShotWhiteXY":"50729" } _cond_select_key_...
def _cond_select_value_nonrecur(d,cond_match=None,**kwargs): ''' d = { "ActiveArea":"50829", "Artist":"315", "AsShotPreProfileMatrix":"50832", "AnalogBalance":"50727", "AsShotICCProfile":"50831", "AsShotProfileName":"50934", "AntiAliasStrength":"50738", "AsShotNeutral":"50728", "AsShotWhiteXY":"50729" } _cond_select_va...
def _diff_internal(d1,d2): ''' d1 = {'a':'x','b':'y','c':'z'} d2 = {'a':'x','b':'u','d':'v'} _diff_internal(d1,d2) _diff_internald2,d1) ''' same =[] kdiff =[] vdiff = [] for key in d1: value = d1[key] if(key in d2): if(value == d2[key]): same.append(key) else: vdiff.append(key) else: kdiff.append(key) return({'same':sa...
def _union(d1,d2): ''' d1 = {'a':'x','b':'y','c':'z'} d2 = {'a':'x','b':'u','d':'v'} _union(d1,d2) _union(d2,d1) ''' u = {} ds = _diff_internal(d1,d2) for key in ds['same']: u[key] = d1[key] for key in ds['vdiff']: u[key] = d1[key] for key in ds['kdiff']: u[key] = d1[key] ds = _diff_internal(d2,d1) for key in ds['kdiff...
def _diff(d1,d2): ''' d1 = {'a':'x','b':'y','c':'z'} d2 = {'a':'x','b':'u','d':'v'} _diff(d1,d2) _diff(d2,d1) ''' d = {} ds = _diff_internal(d1,d2) for key in ds['vdiff']: d[key] = d1[key] for key in ds['kdiff']: d[key] = d1[key] return(d)
def _intersection(d1,d2): ''' d1 = {'a':'x','b':'y','c':'z'} d2 = {'a':'x','b':'u','d':'v'} _intersection(d1,d2) _intersection(d2,d1) ''' i = {} ds = _diff_internal(d1,d2) for key in ds['same']: i[key] = d1[key] return(i)
def _complement(d1,d2): ''' d1 = {'a':'x','b':'y','c':'z'} d2 = {'a':'x','b':'u','d':'v'} complement(d1,d2) complement(d2,d1) ''' u = _union(d1,d2) c = _diff(u,d1) return(c)
def _uniqualize(d): ''' d = {1:'a',2:'b',3:'c',4:'b'} _uniqualize(d) ''' pt = copy.deepcopy(d) seqs_for_del =[] vset = set({}) for k in pt: vset.add(pt[k]) tslen = vset.__len__() freq = {} for k in pt: v = pt[k] if(v in freq): freq[v] = freq[v] + 1 seqs_for_del.append(k) else: freq[v] = 0 npt = {} for k in pt: if(k in ...
def _extend(dict1,dict2,**kwargs): ''' dict1 = {1:'a',2:'b',3:'c',4:'d'} dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'} d = _extend(dict1,dict2) pobj(d) dict1 = {1:'a',2:'b',3:'c',4:'d'} dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'} d = _extend(dict1,dict2,overwrite=1) pobj(d) ''' if('deepcopy' in kwargs): deepcopy=kwargs['deepcopy...
def _comprise(dict1,dict2): ''' dict1 = {'a':1,'b':2,'c':3,'d':4} dict2 = {'b':2,'c':3} _comprise(dict1,dict2) ''' len_1 = dict1.__len__() len_2 = dict2.__len__() if(len_2>len_1): return(False) else: for k2 in dict2: v2 = dict2[k2] if(k2 in dict1): v1 = dict1[k2] if(v1 == v2): return(True) else: return(False) else: ret...
def _update_intersection(dict1,dict2,**kwargs): ''' dict1 = {1:'a',2:'b',3:'c',4:'d'} dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'} _update_intersection(dict1,dict2) pobj(dict1) pobj(dict2) ''' if('deepcopy' in kwargs): deepcopy = kwargs['deepcopy'] else: deepcopy = 1 if(deepcopy == 1): dict1 = copy.deepcopy(dict1) else: pas...
def _update(dict1,dict2,**kwargs): ''' dict1 = {1:'a',2:'b',3:'c',4:'d'} dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'} _update(dict1,dict2) pobj(dict1) pobj(dict2) ''' if('deepcopy' in kwargs): deepcopy = kwargs['deepcopy'] else: deepcopy = 1 if(deepcopy == 1): dict1 = copy.deepcopy(dict1) else: pass dict1 = _extend(dict1,di...
def _setdefault_via_pathlist(external_dict,path_list,**kwargs): ''' #if path_list already in external_dict, will do nothing y = {} path_list = ['c','b'] _setdefault_via_pathlist(y,path_list) y _setdefault_via_pathlist(y,path_list) y = {} _setdefault_via_pathlist(y,path_list) y ''' if('s2n' in kwargs): s2n = kwargs['s2n...
def _setitem_via_pathlist(external_dict,path_list,value,**kwargs): ''' y = {'c': {'b': {}}} _setitem_via_pathlist(y,['c','b'],200) ''' if('s2n' in kwargs): s2n = kwargs['s2n'] else: s2n = 0 if('n2s' in kwargs): n2s = kwargs['n2s'] else: n2s = 0 this = external_dict for i in range(0,path_list.__len__()-1): key = path_li...
def _getitem_via_pathlist(external_dict,path_list,**kwargs): ''' y = {'c': {'b': 200}} _getitem_via_pathlist(y,['c','b']) ''' if('s2n' in kwargs): s2n = kwargs['s2n'] else: s2n = 0 if('n2s' in kwargs): n2s = kwargs['n2s'] else: n2s = 0 this = external_dict for i in range(0,path_list.__len__()): key = path_list[i] if(n2...
def _include_pathlist(external_dict,path_list,**kwargs): ''' y = { 'a': {'x':88}, 'b': { 'x': {'c':66} } } _include_pathlist(y,['a']) _include_pathlist(y,['a','x']) _include_pathlist(y,['b','x','c']) ''' if('s2n' in kwargs): s2n = kwargs['s2n'] else: s2n = 0 if('n2s' in kwargs): n2s = kwargs['n2s'] else: n2s = 0 this =...
def max_word_width(myDict): ''' currd = {0:'AutoPauseSpeed', 125:'HRLimitLow', 6:'Activity'} max_wordwidth(currd) ''' maxValueWidth = 0 for each in myDict: eachValueWidth = myDict[each].__len__() if(eachValueWidth > maxValueWidth): maxValueWidth = eachValueWidth return(maxValueWidth)
def max_display_width(myDict): ''' currd = {0:'你们大家好', 125:'ABCDE', 6:'1234567'} dict_get_max_word_displaywidth(currd) ''' maxValueWidth = 0 for each in myDict: eachValueWidth = str_display_width(myDict[each]) if(eachValueWidth > maxValueWidth): maxValueWidth = eachValueWidth return(maxValueWidth)
def is_leaf(obj): ''' the below is for nested-dict any type is not dict will be treated as a leaf empty dict will be treated as a leaf from edict.edict import * is_leaf(1) is_leaf({1:2}) is_leaf({}) ''' if(is_dict(obj)): length = obj.__len__() if(length == 0): return(True) else: return(False) else: return(True)
def _d2kvmatrix(d): ''' d = {1: 2, 3: {'a': 'b'}} km,vm = _d2kvmatrix(d) d = {1: {2:{22:222}}, 3: {'a': 'b'}} km,vm = _d2kvmatrix(d) ## km: 按照层次存储pathlist,层次从0开始, { 1: 2, 3: { 'a': 'b' } } km[0] = [[1],[3]] km[1] = [[3,'a']] vm: vm比较特殊,不太好理解,请参照函数elel.get_wfs 和_kvmatrix2d vm的数组表示层次 rvmat: 与km对应,存储key对应的value,不过对应层次使km的...
vm[0] return((km,vm))
def show_kmatrix(km): ''' d = {1: {2: {22: 222}}, 3: {'a': 'b'}} km = [[[1], [3]], [[1, 2], [3, 'a']], [[1, 2, 22]]] show_kmatrix(km) ''' rslt = [] for i in range(0,km.__len__()): level = km[i] for j in range(0,level.__len__()): kpl = level[j] print(kpl) rslt.append(kpl) return(rslt)
def show_vmatrix(vm): ''' d = {1: {2: {22: 222}}, 3: {'a': 'b'}} vm = [[[222]], ['b']] show_vmatrix(vm) ''' unhandled = vm while(unhandled.__len__()>0): next_unhandled = [] for i in range(0,unhandled.__len__()): ele = unhandled[i] print(ele) cond = elel.is_leaf(ele) if(cond): pass else: children = ele[0] next_unhandled...
def _kvmatrix2d(km,vm): ''' km = [[[1], [3]], [[1, 2], [3, 'a']], [[1, 2, 22]]] show_kmatrix(km) vm = [[[222]], ['b']] show_vmatrix(vm) d = _kvmatrix2d(km,vm) ''' d = {} kmwfs = get_kmwfs(km) vmwfs = elel.get_wfs(vm) lngth = vmwfs.__len__() for i in range(0,lngth): value = elel.getitem_via_pathlist(vm,vmwfs[i]) cond = ...
def _get_rvmat(d): ''' d = { 'x': { 'x2': 'x22', 'x1': 'x11' }, 'y': { 'y1': 'v1', 'y2': { 'y4': 'v4', 'y3': 'v3' } }, 't': 20, 'u': { 'u1': 'u2' } } ''' km,vm = _d2kvmatrix(d) def map_func(ele,indexc,indexr): return(_getitem_via_pathlist(d,ele)) rvmat = elel.matrix_map(km,map_func) rvmat = elel.prepend(rvmat,[]) retur...
def get_vndmat_attr(d,keypath,attr,**kwargs): ''' get_vndmat_attr(d,['x'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['t'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['u'],'lsib_path',path2keypath=True) get_vndmat_attr(d,['y'],'lsib_path',path2keypath=True) ''' kt,vn = _d2kvmatrix(d) kdmat = _scankm(kt) ltr...
def sub_via_value(self,*vs,**kwargs): ''' d= {1:'a',2:'b',3:'a',4:'d',5:'e'} ed = eded.Edict(d) ed.sub_via_value('a','d') ''' sd = _select_norecur_via_value(self.dict,*vs,**kwargs) return(Edict(sd))
def radpress_get_markup_descriptions(): """ Provides markup options. It used for adding descriptions in admin and zen mode. :return: list """ result = [] for markup in get_markup_choices(): markup_name = markup[0] result.append({ 'name': markup_name, 'title': markup[1], 'description': trim(get_reader(markup=markup_name...
def _get_parser(description): """Build an ArgumentParser with common arguments for both operations.""" parser = argparse.ArgumentParser(description=description) parser.add_argument('key', help="Camellia key.") parser.add_argument('input_file', nargs='*', help="File(s) to read as input data. If none are " "provided, ass...
def _get_crypto(keylen, hexkey, key): """Return a camcrypt.CamCrypt object based on keylen, hexkey, and key.""" if keylen not in camcrypt.ACCEPTABLE_KEY_LENGTHS: raise ValueError("key length must be one of 128, 192, or 256") if hexkey: key = key.decode('hex') return camcrypt.CamCrypt(keylen=keylen, key=key)
def _get_data(filenames): """Read data from file(s) or STDIN. Args: filenames (list): List of files to read to get data. If empty or None, read from STDIN. """ if filenames: data = "" for filename in filenames: with open(filename, "rb") as f: data += f.read() else: data = sys.stdin.read() return data
def _print_results(filename, data): """Print data to a file or STDOUT. Args: filename (str or None): If None, print to STDOUT; otherwise, print to the file with this name. data (str): Data to print. """ if filename: with open(filename, 'wb') as f: f.write(data) else: print data
def timestamp(self, value): """ The local time when the message was written. Must follow the format 'Mmm DD HH:MM:SS'. If the day of the month is less than 10, then it MUST be represented as a space and then the number. """ if not self._timestamp_is_valid(value): value = self._calculate_current_timestamp() self._timest...
def hostname(self, value): """ The hostname where the log message was created. Should be the first part of the hostname, or an IP address. Should NOT be set to a fully qualified domain name. """ if value is None: value = socket.gethostname() self._hostname = value
def tag(self, value): """The name of the program that generated the log message. The tag can only contain alphanumeric characters. If the tag is longer than {MAX_TAG_LEN} characters it will be truncated automatically. """ if value is None: value = sys.argv[0] self._tag = value[:self.MAX_TAG_LEN]
def content(self, value): """The main component of the log message. The content field is a freeform field that often begins with the process ID (pid) of the program that created the message. """ value = self._prepend_seperator(value) self._content = value
def log(self, facility, level, text, pid=False): """Send the message text to all registered hosts. The facility and level will be used to create the packet's PRI part. The HEADER will be automatically determined from the current time and hostname. The MSG will be set from the running program's name and the text paramet...