idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
33,000 | def munge_source ( v ) : lines = v . split ( '\n' ) if not lines : return tuple ( ) , '' firstline = lines [ 0 ] . lstrip ( ) while firstline == '' or firstline [ 0 ] == '@' : del lines [ 0 ] firstline = lines [ 0 ] . lstrip ( ) if not lines : return tuple ( ) , '' params = tuple ( parm . strip ( ) for parm in sig_ex .... | Take Python source code return a pair of its parameters and the rest of it dedented |
33,001 | def redata ( self , * args , ** kwargs ) : select_name = kwargs . get ( 'select_name' ) if not self . store : Clock . schedule_once ( self . redata ) return self . data = list ( map ( self . munge , enumerate ( self . _iter_keys ( ) ) ) ) if select_name : self . _trigger_select_name ( select_name ) | Update my data to match what s in my store |
33,002 | def select_name ( self , name , * args ) : self . boxl . select_node ( self . _name2i [ name ] ) | Select an item by its name highlighting |
33,003 | def save ( self , * args ) : if self . name_wid is None or self . store is None : Logger . debug ( "{}: Not saving, missing name_wid or store" . format ( type ( self ) . __name__ ) ) return if not ( self . name_wid . text or self . name_wid . hint_text ) : Logger . debug ( "{}: Not saving, no name" . format ( type ( se... | Put text in my store return True if it changed |
33,004 | def delete ( self , * args ) : key = self . name_wid . text or self . name_wid . hint_text if not hasattr ( self . store , key ) : return delattr ( self . store , key ) try : return min ( kee for kee in dir ( self . store ) if kee > key ) except ValueError : return '+' | Remove the currently selected item from my store |
33,005 | def advance_dialog ( self , * args ) : self . clear_widgets ( ) try : self . _update_dialog ( self . todo [ self . idx ] ) except IndexError : pass | Try to display the next dialog described in my todo . |
33,006 | def ok ( self , * args , cb = None ) : self . clear_widgets ( ) if cb : cb ( ) self . idx += 1 self . advance_dialog ( ) | Clear dialog widgets call cb if provided and advance the dialog queue |
33,007 | def add_child ( self , child ) : if not isinstance ( child , Node ) : raise TypeError ( "child must be a Node" ) self . children . append ( child ) child . parent = self | Add child to Node object |
33,008 | def contract ( self ) : if self . is_root ( ) : return for c in self . children : if self . edge_length is not None and c . edge_length is not None : c . edge_length += self . edge_length self . parent . add_child ( c ) self . parent . remove_child ( self ) | Contract this Node by directly connecting its children to its parent |
33,009 | def newick ( self ) : node_to_str = dict ( ) for node in self . traverse_postorder ( ) : if node . is_leaf ( ) : if node . label is None : node_to_str [ node ] = '' else : node_to_str [ node ] = str ( node . label ) else : out = [ '(' ] for c in node . children : out . append ( node_to_str [ c ] ) if c . edge_length is... | Newick string conversion starting at this Node object |
33,010 | def remove_child ( self , child ) : if not isinstance ( child , Node ) : raise TypeError ( "child must be a Node" ) try : self . children . remove ( child ) child . parent = None except : raise RuntimeError ( "Attempting to remove non-existent child" ) | Remove child from Node object |
33,011 | def resolve_polytomies ( self ) : q = deque ( ) q . append ( self ) while len ( q ) != 0 : node = q . popleft ( ) while len ( node . children ) > 2 : c1 = node . children . pop ( ) c2 = node . children . pop ( ) nn = Node ( edge_length = 0 ) node . add_child ( nn ) nn . add_child ( c1 ) nn . add_child ( c2 ) q . extend... | Arbitrarily resolve polytomies below this Node with 0 - lengthed edges . |
33,012 | def set_parent ( self , parent ) : if not isinstance ( parent , Node ) : raise TypeError ( "parent must be a Node" ) self . parent = parent | Set the parent of this Node object . Use this carefully otherwise you may damage the structure of this Tree object . |
33,013 | def traverse_ancestors ( self , include_self = True ) : if not isinstance ( include_self , bool ) : raise TypeError ( "include_self must be a bool" ) if include_self : c = self else : c = self . parent while c is not None : yield c c = c . parent | Traverse over the ancestors of this Node |
33,014 | def traverse_inorder ( self , leaves = True , internal = True ) : c = self s = deque ( ) done = False while not done : if c is None : if len ( s ) == 0 : done = True else : c = s . pop ( ) if ( leaves and c . is_leaf ( ) ) or ( internal and not c . is_leaf ( ) ) : yield c if len ( c . children ) == 0 : c = None elif le... | Perform an inorder traversal starting at this Node object |
33,015 | def traverse_levelorder ( self , leaves = True , internal = True ) : q = deque ( ) q . append ( self ) while len ( q ) != 0 : n = q . popleft ( ) if ( leaves and n . is_leaf ( ) ) or ( internal and not n . is_leaf ( ) ) : yield n q . extend ( n . children ) | Perform a levelorder traversal starting at this Node object |
33,016 | def traverse_postorder ( self , leaves = True , internal = True ) : s1 = deque ( ) s2 = deque ( ) s1 . append ( self ) while len ( s1 ) != 0 : n = s1 . pop ( ) s2 . append ( n ) s1 . extend ( n . children ) while len ( s2 ) != 0 : n = s2 . pop ( ) if ( leaves and n . is_leaf ( ) ) or ( internal and not n . is_leaf ( ) ... | Perform a postorder traversal starting at this Node object |
33,017 | def traverse_preorder ( self , leaves = True , internal = True ) : s = deque ( ) s . append ( self ) while len ( s ) != 0 : n = s . pop ( ) if ( leaves and n . is_leaf ( ) ) or ( internal and not n . is_leaf ( ) ) : yield n s . extend ( n . children ) | Perform a preorder traversal starting at this Node object |
33,018 | def merge_with ( self , other ) : result = ValuesAggregation ( ) result . total = self . total + other . total result . count = self . count + other . count result . min = min ( self . min , other . min ) result . max = max ( self . max , other . max ) return result | Merge this ValuesAggregation with another one |
33,019 | def parse_url_rules ( urls_fp ) : url_rules = [ ] for line in urls_fp : re_url = line . strip ( ) if re_url : url_rules . append ( { 'str' : re_url , 're' : re . compile ( re_url ) } ) return url_rules | URL rules from given fp |
33,020 | def force_bytes ( s , encoding = 'utf-8' , errors = 'strict' ) : if isinstance ( s , bytes ) : if encoding == 'utf-8' : return s else : return s . decode ( 'utf-8' , errors ) . encode ( encoding , errors ) else : return s . encode ( encoding , errors ) | A function turns s into bytes object similar to django . utils . encoding . force_bytes |
33,021 | def force_text ( s , encoding = 'utf-8' , errors = 'strict' ) : if issubclass ( type ( s ) , str ) : return s try : if isinstance ( s , bytes ) : s = str ( s , encoding , errors ) else : s = str ( s ) except UnicodeDecodeError as e : raise DjangoUnicodeDecodeError ( s , * e . args ) return s | A function turns s into text type similar to django . utils . encoding . force_text |
33,022 | def set_XRef ( self , X = None , indtX = None , indtXlamb = None ) : out = self . _checkformat_inputs_XRef ( X = X , indtX = indtX , indXlamb = indtXlamb ) X , nnch , indtX , indXlamb , indtXlamb = out self . _ddataRef [ 'X' ] = X self . _ddataRef [ 'nnch' ] = nnch self . _ddataRef [ 'indtX' ] = indtX self . _ddataRef ... | Reset the reference X |
33,023 | def set_dtreat_indt ( self , t = None , indt = None ) : lC = [ indt is not None , t is not None ] if all ( lC ) : msg = "Please provide either t or indt (or none)!" raise Exception ( msg ) if lC [ 1 ] : ind = self . select_t ( t = t , out = bool ) else : ind = _format_ind ( indt , n = self . _ddataRef [ 'nt' ] ) self .... | Store the desired index array for the time vector |
33,024 | def set_dtreat_indch ( self , indch = None ) : if indch is not None : indch = np . asarray ( indch ) assert indch . ndim == 1 indch = _format_ind ( indch , n = self . _ddataRef [ 'nch' ] ) self . _dtreat [ 'indch' ] = indch self . _ddata [ 'uptodate' ] = False | Store the desired index array for the channels |
33,025 | def set_dtreat_indlamb ( self , indlamb = None ) : if not self . _isSpectral ( ) : msg = "The wavelength can only be set with DataSpectral object !" raise Exception ( msg ) if indlamb is not None : indlamb = np . asarray ( indlamb ) assert indlamb . ndim == 1 indlamb = _format_ind ( indlamb , n = self . _ddataRef [ 'nl... | Store the desired index array for the wavelength |
33,026 | def set_dtreat_interp_indt ( self , indt = None ) : lC = [ indt is None , type ( indt ) in [ np . ndarray , list ] , type ( indt ) is dict ] assert any ( lC ) if lC [ 2 ] : lc = [ type ( k ) is int and k < self . _ddataRef [ 'nch' ] for k in indt . keys ( ) ] assert all ( lc ) for k in indt . keys ( ) : assert hasattr ... | Set the indices of the times for which to interpolate data |
33,027 | def set_dtreat_interp_indch ( self , indch = None ) : lC = [ indch is None , type ( indch ) in [ np . ndarray , list ] , type ( indch ) is dict ] assert any ( lC ) if lC [ 2 ] : lc = [ type ( k ) is int and k < self . _ddataRef [ 'nt' ] for k in indch . keys ( ) ] assert all ( lc ) for k in indch . keys ( ) : assert ha... | Set the indices of the channels for which to interpolate data |
33,028 | def set_dtreat_dfit ( self , dfit = None ) : warnings . warn ( "Not implemented yet !, dfit forced to None" ) dfit = None assert dfit is None or isinstance ( dfit , dict ) if isinstance ( dfit , dict ) : assert 'type' in dfit . keys ( ) assert dfit [ 'type' ] in [ 'svd' , 'fft' ] self . _dtreat [ 'dfit' ] = dfit self .... | Set the fitting dictionnary |
33,029 | def set_dtreat_interpt ( self , t = None ) : if t is not None : t = np . unique ( np . asarray ( t , dtype = float ) . ravel ( ) ) self . _dtreat [ 'interp-t' ] = t | Set the time vector on which to interpolate the data |
33,030 | def set_dtreat_order ( self , order = None ) : if order is None : order = list ( self . _ddef [ 'dtreat' ] [ 'order' ] ) assert type ( order ) is list and all ( [ type ( ss ) is str for ss in order ] ) if not all ( [ ss in [ 'indt' , 'indch' , 'indlamb' ] for ss in order ] [ - 4 : - 1 ] ) : msg = "indt and indch must b... | Set the order in which the data treatment should be performed |
33,031 | def clear_ddata ( self ) : self . _ddata = dict . fromkeys ( self . _get_keys_ddata ( ) ) self . _ddata [ 'uptodate' ] = False | Clear the working copy of data |
33,032 | def dchans ( self , key = None ) : if self . _dtreat [ 'indch' ] is None or np . all ( self . _dtreat [ 'indch' ] ) : dch = dict ( self . _dchans ) if key is None else self . _dchans [ key ] else : dch = { } lk = self . _dchans . keys ( ) if key is None else [ key ] for kk in lk : if self . _dchans [ kk ] . ndim == 1 :... | Return the dchans updated with indch |
33,033 | def select_t ( self , t = None , out = bool ) : assert out in [ bool , int ] ind = _select_ind ( t , self . _ddataRef [ 't' ] , self . _ddataRef [ 'nt' ] ) if out is int : ind = ind . nonzero ( ) [ 0 ] return ind | Return a time index array |
33,034 | def select_lamb ( self , lamb = None , out = bool ) : if not self . _isSpectral ( ) : msg = "" raise Exception ( msg ) assert out in [ bool , int ] ind = _select_ind ( lamb , self . _ddataRef [ 'lamb' ] , self . _ddataRef [ 'nlamb' ] ) if out is int : ind = ind . nonzero ( ) [ 0 ] return ind | Return a wavelength index array |
33,035 | def plot ( self , key = None , cmap = None , ms = 4 , vmin = None , vmax = None , vmin_map = None , vmax_map = None , cmap_map = None , normt_map = False , ntMax = None , nchMax = None , nlbdMax = 3 , lls = None , lct = None , lcch = None , lclbd = None , cbck = None , inct = [ 1 , 10 ] , incX = [ 1 , 5 ] , inclbd = [ ... | Plot the data content in a generic interactive figure |
33,036 | def plot_compare ( self , lD , key = None , cmap = None , ms = 4 , vmin = None , vmax = None , vmin_map = None , vmax_map = None , cmap_map = None , normt_map = False , ntMax = None , nchMax = None , nlbdMax = 3 , lls = None , lct = None , lcch = None , lclbd = None , cbck = None , inct = [ 1 , 10 ] , incX = [ 1 , 5 ] ... | Plot several Data instances of the same diag |
33,037 | def calc_spectrogram ( self , fmin = None , method = 'scipy-fourier' , deg = False , window = 'hann' , detrend = 'linear' , nperseg = None , noverlap = None , boundary = 'constant' , padded = True , wave = 'morlet' , warn = True ) : if self . _isSpectral ( ) : msg = "spectrogram not implemented yet for spectral data cl... | Return the power spectrum density for each channel |
33,038 | def plot_spectrogram ( self , fmin = None , fmax = None , method = 'scipy-fourier' , deg = False , window = 'hann' , detrend = 'linear' , nperseg = None , noverlap = None , boundary = 'constant' , padded = True , wave = 'morlet' , invert = True , plotmethod = 'imshow' , cmap_f = None , cmap_img = None , ms = 4 , ntMax ... | Plot the spectrogram of all channels with chosen method |
33,039 | def calc_svd ( self , lapack_driver = 'gesdd' ) : if self . _isSpectral ( ) : msg = "svd not implemented yet for spectral data class" raise Exception ( msg ) chronos , s , topos = _comp . calc_svd ( self . data , lapack_driver = lapack_driver ) return u , s , v | Return the SVD decomposition of data |
33,040 | def plot_svd ( self , lapack_driver = 'gesdd' , modes = None , key = None , Bck = True , Lplot = 'In' , cmap = None , vmin = None , vmax = None , cmap_topos = None , vmin_topos = None , vmax_topos = None , ntMax = None , nchMax = None , ms = 4 , inct = [ 1 , 10 ] , incX = [ 1 , 5 ] , incm = [ 1 , 5 ] , lls = None , lct... | Plot the chosen modes of the svd decomposition |
33,041 | def plot ( self , key = None , invert = None , plotmethod = 'imshow' , cmap = plt . cm . gray , ms = 4 , Max = None , fs = None , dmargin = None , wintit = None , draw = True , connect = True ) : dax , KH = _plot . Data_plot ( self , key = key , invert = invert , Max = Max , plotmethod = plotmethod , cmap = cmap , ms =... | Plot the data content in a predefined figure |
33,042 | def LOS_PRMin ( Ds , dus , kPOut = None , Eps = 1.e-12 , Test = True ) : if Test : assert Ds . ndim in [ 1 , 2 ] and 3 in Ds . shape and Ds . shape == dus . shape assert kPOut is None or ( Ds . ndim == 1 and not hasattr ( kPOut , '__iter__' ) ) or ( Ds . ndim == 2 and kPOut . shape == ( Ds . size / 3 , ) ) v = Ds . ndi... | Compute the point on the LOS where the major radius is minimum |
33,043 | def LOS_get_sample ( D , u , dL , DL = None , dLMode = 'abs' , method = 'sum' , Test = True ) : if Test : assert all ( [ type ( dd ) is np . ndarray and dd . shape == ( 3 , ) for dd in [ D , u ] ] ) assert not hasattr ( dL , '__iter__' ) assert DL is None or all ( [ hasattr ( DL , '__iter__' ) , len ( DL ) == 2 , all (... | Return the sampled line with the specified method |
33,044 | def isInside ( self , pts , In = '(X,Y,Z)' ) : ind = _GG . _Ves_isInside ( pts , self . Poly , Lim = self . Lim , nLim = self . _dgeom [ 'noccur' ] , VType = self . Id . Type , In = In , Test = True ) return ind | Return an array of booleans indicating whether each point lies inside the Struct volume |
33,045 | def get_InsideConvexPoly ( self , RelOff = _def . TorRelOff , ZLim = 'Def' , Spline = True , Splprms = _def . TorSplprms , NP = _def . TorInsideNP , Plot = False , Test = True ) : return _comp . _Ves_get_InsideConvexPoly ( self . Poly_closed , self . dgeom [ 'P2Min' ] , self . dgeom [ 'P2Max' ] , self . dgeom [ 'BaryS'... | Return a polygon that is a smaller and smoothed approximation of Ves . Poly useful for excluding the divertor region in a Tokamak |
33,046 | def get_sampleEdge ( self , res , DS = None , resMode = 'abs' , offsetIn = 0. ) : pts , dlr , ind = _comp . _Ves_get_sampleEdge ( self . Poly , res , DS = DS , dLMode = resMode , DIn = offsetIn , VIn = self . dgeom [ 'VIn' ] , margin = 1.e-9 ) return pts , dlr , ind | Sample the polygon edges with resolution res |
33,047 | def get_sampleCross ( self , res , DS = None , resMode = 'abs' , ind = None ) : args = [ self . Poly , self . dgeom [ 'P1Min' ] [ 0 ] , self . dgeom [ 'P1Max' ] [ 0 ] , self . dgeom [ 'P2Min' ] [ 1 ] , self . dgeom [ 'P2Max' ] [ 1 ] , res ] kwdargs = dict ( DS = DS , dSMode = resMode , ind = ind , margin = 1.e-9 ) pts ... | Sample with resolution res the 2D cross - section |
33,048 | def get_sampleS ( self , res , DS = None , resMode = 'abs' , ind = None , offsetIn = 0. , Out = '(X,Y,Z)' , Ind = None ) : if Ind is not None : assert self . dgeom [ 'Multi' ] kwdargs = dict ( DS = DS , dSMode = resMode , ind = ind , DIn = offsetIn , VIn = self . dgeom [ 'VIn' ] , VType = self . Id . Type , VLim = np .... | Sample with resolution res the surface defined by DS or ind |
33,049 | def get_sampleV ( self , res , DV = None , resMode = 'abs' , ind = None , Out = '(X,Y,Z)' ) : args = [ self . Poly , self . dgeom [ 'P1Min' ] [ 0 ] , self . dgeom [ 'P1Max' ] [ 0 ] , self . dgeom [ 'P2Min' ] [ 1 ] , self . dgeom [ 'P2Max' ] [ 1 ] , res ] kwdargs = dict ( DV = DV , dVMode = resMode , ind = ind , VType =... | Sample with resolution res the volume defined by DV or ind |
33,050 | def plot ( self , lax = None , proj = 'all' , element = 'PIBsBvV' , dP = None , dI = _def . TorId , dBs = _def . TorBsd , dBv = _def . TorBvd , dVect = _def . TorVind , dIHor = _def . TorITord , dBsHor = _def . TorBsTord , dBvHor = _def . TorBvTord , Lim = None , Nstep = _def . TorNTheta , dLeg = _def . TorLegd , indic... | Plot the polygon defining the vessel in chosen projection |
33,051 | def plot_sino ( self , ax = None , Ang = _def . LOSImpAng , AngUnit = _def . LOSImpAngUnit , Sketch = True , dP = None , dLeg = _def . TorLegd , draw = True , fs = None , wintit = None , Test = True ) : if Test : msg = "The impact parameters must be set ! (self.set_dsino())" assert not self . dsino [ 'RefPt' ] is None ... | Plot the sinogram of the vessel polygon by computing its envelopp in a cross - section can also plot a 3D version of it |
33,052 | def lStruct ( self ) : lStruct = [ ] for k in self . _dStruct [ 'lorder' ] : k0 , k1 = k . split ( '_' ) lStruct . append ( self . _dStruct [ 'dObj' ] [ k0 ] [ k1 ] ) return lStruct | Return the list of Struct that was used for creation |
33,053 | def lStructIn ( self ) : lStruct = [ ] for k in self . _dStruct [ 'lorder' ] : k0 , k1 = k . split ( '_' ) if type ( self . _dStruct [ 'dObj' ] [ k0 ] [ k1 ] ) is str : if any ( [ ss in self . _dStruct [ 'dObj' ] [ k0 ] [ k1 ] for ss in [ 'Ves' , 'PlasmaDomain' ] ] ) : lStruct . append ( self . _dStruct [ 'dObj' ] [ k0... | Return the list of StructIn contained in self . lStruct |
33,054 | def get_summary ( self , verb = False , max_columns = 100 , width = 1000 ) : msg = "The data is not accessible because self.strip(2) was used !" assert self . _dstrip [ 'strip' ] < 2 , msg d = self . _dStruct [ 'dObj' ] data = [ ] for k in self . _ddef [ 'dStruct' ] [ 'order' ] : if k not in d . keys ( ) : continue for... | Summary description of the object content as a pandas DataFrame |
33,055 | def isInside ( self , pts , In = '(X,Y,Z)' , log = 'any' ) : msg = "Arg pts must be a 1D or 2D np.ndarray !" assert isinstance ( pts , np . ndarray ) and pts . ndim in [ 1 , 2 ] , msg msg = "Arg log must be in ['any','all']" assert log in [ 'any' , 'all' ] , msg if pts . ndim == 1 : msg = "Arg pts must contain the coor... | Return a 2D array of bool |
33,056 | def get_sample ( self , res , resMode = 'abs' , DL = None , method = 'sum' , ind = None , compact = False ) : ind = self . _check_indch ( ind ) kIn = self . kIn kOut = self . kOut if DL is None : DL = np . array ( [ kIn [ ind ] , kOut [ ind ] ] ) elif np . asarray ( DL ) . size == 2 : DL = np . tile ( np . asarray ( DL... | Return a linear sampling of the LOS |
33,057 | def calc_kInkOut_IsoFlux ( self , lPoly , lVIn = None , Lim = None , kInOut = True ) : nPoly , lPoly , lVIn = self . _kInOut_IsoFlux_inputs_usr ( lPoly , lVIn = lVIn ) kIn = np . full ( ( self . nRays , nPoly ) , np . nan ) kOut = np . full ( ( self . nRays , nPoly ) , np . nan ) assert ( self . _method in [ 'ref' , 'o... | Calculate the intersection points of each ray with each isoflux |
33,058 | def get_touch_dict ( self , ind = None , out = bool ) : if self . config is None : msg = "Config must be set in order to get touch dict !" raise Exception ( msg ) dElt = { } ind = self . _check_indch ( ind , out = bool ) for ss in self . lStruct_computeInOut : kn = "%s_%s" % ( ss . __class__ . __name__ , ss . Id . Name... | Get a dictionnary of Cls_Name struct with indices of Rays touching |
33,059 | def merge_urls_data_to ( to , food = { } ) : if not to : to . update ( food ) for url , data in food . items ( ) : if url not in to : to [ url ] = data else : to [ url ] = to [ url ] . merge_with ( data ) | Merge urls data |
33,060 | def merge_requests_data_to ( to , food = { } ) : if not to : to . update ( food ) to [ 'requests_counter' ] [ 'normal' ] += food [ 'requests_counter' ] [ 'normal' ] to [ 'requests_counter' ] [ 'slow' ] += food [ 'requests_counter' ] [ 'slow' ] to [ 'total_slow_duration' ] += food [ 'total_slow_duration' ] for group_nam... | Merge a small analyzed result to a big one this function will modify the original to |
33,061 | def format_data ( raw_data , limit_per_url_group = LIMIT_PER_URL_GROUP , limit_url_groups = LIMIT_URL_GROUPS ) : data = copy . deepcopy ( raw_data ) for k , v in list ( data [ 'data_details' ] . items ( ) ) : v [ 'urls' ] = sorted ( list ( v [ 'urls' ] . items ( ) ) , key = lambda k_v : k_v [ 1 ] . total , reverse = Tr... | Fomat data from LogAnalyzer for render purpose |
33,062 | def classify ( self , url_path ) : for dict_api_url in self . user_defined_rules : api_url = dict_api_url [ 'str' ] re_api_url = dict_api_url [ 're' ] if re_api_url . match ( url_path [ 1 : ] ) : return api_url return self . RE_SIMPLIFY_URL . sub ( r'(\\d+)/' , url_path ) | Classify an url |
33,063 | def annotate_rule_violation ( self , rule : ValidationRule ) -> None : if self . errors . get ( rule . label ) is None : self . errors [ rule . label ] = [ ] self . errors [ rule . label ] . append ( rule . get_error_message ( ) ) | Takes note of a rule validation failure by collecting its error message . |
33,064 | def get_PolyFromPolyFileObj ( PolyFileObj , SavePathInp = None , units = 'm' , comments = '#' , skiprows = 0 , shape0 = 2 ) : assert type ( PolyFileObj ) in [ list , str ] or hasattr ( PolyFileObj , "Poly" ) or np . asarray ( PolyFileObj ) . ndim == 2 , "Arg PolyFileObj must be str (PathFileExt), a ToFu object with att... | Return a polygon as a np . ndarray extracted from a txt file or from a ToFu object with appropriate units |
33,065 | def CheckSameObj ( obj0 , obj1 , LFields = None ) : A = True if LField is not None and obj0 . __class__ == obj1 . __class__ : assert type ( LFields ) in [ str , list ] if type ( LFields ) is str : LFields = [ LFields ] assert all ( [ type ( s ) is str for s in LFields ] ) ind = [ False for ii in range ( 0 , len ( LFiel... | Check if two variables are the same instance of a ToFu class |
33,066 | def Save_Generic ( obj , SaveName = None , Path = './' , Mode = 'npz' , compressed = False , Print = True ) : assert type ( obj . __class__ ) is type if SaveName is not None : C = type ( SaveName ) is str and not ( SaveName [ - 4 ] == '.' ) assert C , "SaveName should not include the extension !" assert Path is None or... | Save a ToFu object under file name SaveName in folder Path |
33,067 | def Open ( pathfileext = None , shot = None , t = None , Dt = None , Mesh = None , Deg = None , Deriv = None , Sep = True , Pos = True , OutPath = None , ReplacePath = None , Ves = None , out = 'full' , Verb = False , Print = True ) : assert None in [ pathfileext , shot ] and not ( pathfileext is None and shot is None ... | Open a ToFu object saved file |
33,068 | def set_LObj ( self , LObj = None ) : self . _LObj = { } if LObj is not None : if type ( LObj ) is not list : LObj = [ LObj ] for ii in range ( 0 , len ( LObj ) ) : if type ( LObj [ ii ] ) is ID : LObj [ ii ] = LObj [ ii ] . _todict ( ) ClsU = list ( set ( [ oo [ 'Cls' ] for oo in LObj ] ) ) for c in ClsU : self . _LOb... | Set the LObj attribute storing objects the instance depends on |
33,069 | def set_USRdict ( self , USRdict = { } ) : self . _check_inputs ( USRdict = USRdict ) self . _USRdict = USRdict | Set the USRdict containing user - defined info about the instance |
33,070 | def create_config ( case = None , Exp = 'Dummy' , Type = 'Tor' , Lim = None , Bump_posextent = [ np . pi / 4. , np . pi / 4 ] , R = 2.4 , r = 1. , elong = 0. , Dshape = 0. , divlow = True , divup = True , nP = 200 , out = 'object' , SavePath = './' ) : if case is not None : conf = _create_config_testcase ( config = cas... | Create easily a tofu . geom . Config object |
33,071 | def analyze_log ( fp , configs , url_rules ) : url_classifier = URLClassifier ( url_rules ) analyzer = LogAnalyzer ( url_classifier = url_classifier , min_msecs = configs . min_msecs ) for line in fp : analyzer . analyze_line ( line ) return analyzer . get_data ( ) | Analyze log file |
33,072 | def _spectrogram_scipy_fourier ( data , fs , nt , nch , fmin = None , window = ( 'tukey' , 0.25 ) , deg = False , nperseg = None , noverlap = None , detrend = 'linear' , stft = False , boundary = 'constant' , padded = True , warn = True ) : if nperseg is None and fmin is None : fmin = _fmin_coef * ( fs / nt ) if warn :... | Return a spectrogram for each channel and a common frequency vector |
33,073 | def filter_svd ( data , lapack_driver = 'gesdd' , modes = [ ] ) : modes = np . asarray ( modes , dtype = int ) assert modes . ndim == 1 assert modes . size >= 1 , "No modes selected !" u , s , v = scplin . svd ( data , full_matrices = False , compute_uv = True , overwrite_a = False , check_finite = True , lapack_driver... | Return the svd - filtered signal using only the selected mode |
33,074 | def render_requests_data_to_html ( self , data , file_name , context = { } ) : file_path = os . path . join ( self . html_dir , file_name ) logger . info ( 'Rendering HTML file %s...' % file_path ) data = format_data ( data ) data . update ( context ) data . update ( domain = self . domain ) with open ( file_path , 'w'... | Render to HTML file |
33,075 | def get_figuresize ( fs , fsdef = ( 12 , 6 ) , orient = 'landscape' , method = 'xrandr' ) : assert fs is None or type ( fs ) in [ str , tuple ] if fs is None : fs = fsdef elif type ( fs ) is str : if fs == 'a4' : fs = ( 8.27 , 11.69 ) if orient == 'landscape' : fs = ( fs [ 1 ] , fs [ 0 ] ) elif fs == 'full' : assert me... | Generic function to return figure size in inches |
33,076 | def _set_arrayorder ( obj , arrayorder = 'C' ) : msg = "Arg arrayorder must be in ['C','F']" assert arrayorder in [ 'C' , 'F' ] , msg d = obj . to_dict ( strip = - 1 ) account = { 'Success' : [ ] , 'Failed' : [ ] } for k , v in d . items ( ) : if type ( v ) is np . array and v . ndim > 1 : try : if arrayorder == 'C' : ... | Set the memory order of all np . ndarrays in a tofu object |
33,077 | def save ( obj , path = None , name = None , sep = _sep , deep = False , mode = 'npz' , strip = None , compressed = False , verb = True , return_pfe = False ) : msg = "Arg obj must be a tofu subclass instance !" assert issubclass ( obj . __class__ , ToFuObject ) , msg msg = "Arg path must be None or a str (folder) !" a... | Save the ToFu object |
33,078 | def load ( name , path = None , strip = None , verb = True ) : lmodes = [ '.npz' , '.mat' , '.txt' ] name , mode , pfe = _filefind ( name = name , path = path , lmodes = lmodes ) if mode == 'txt' : obj = _load_from_txt ( name , pfe ) else : if mode == 'npz' : dd = _load_npz ( pfe ) elif mode == 'mat' : dd = _load_mat (... | Load a tofu object file |
33,079 | def to_dict ( self , strip = None , sep = _sep , deep = 'ref' ) : if deep not in [ 'ref' , 'copy' , 'dict' ] : msg = "Arg deep must be a flag in ['ref','copy','dict'] !" raise Exception ( msg ) if strip is None : strip = self . _dstrip [ 'strip' ] if self . _dstrip [ 'strip' ] != strip : self . strip ( strip ) dd = sel... | Return a flat dict view of the object s attributes |
33,080 | def from_dict ( self , fd , sep = _sep , strip = None ) : self . _reset ( ) dd = reshape_dict ( fd ) self . _from_dict ( dd ) self . _dstrip . update ( ** dd [ 'dstrip' ] ) if 'dId' in dd . keys ( ) : self . _set_Id ( Id = ID ( fromdict = dd [ 'dId' ] ) ) if strip is None : strip = self . _dstrip [ 'strip' ] if self . ... | Populate the instances attributes using an input dict |
33,081 | def copy ( self , strip = None , deep = 'ref' ) : dd = self . to_dict ( strip = strip , deep = deep ) return self . __class__ ( fromdict = dd ) | Return another instance of the object with the same attributes |
33,082 | def set_lObj ( self , lObj = None ) : if self . lObj is None and lObj is not None : self . _dall [ 'lObj' ] = { } if lObj is not None : if type ( lObj ) is not list : lObj = [ lObj ] for ii in range ( 0 , len ( lObj ) ) : if type ( lObj [ ii ] ) is ID : lObj [ ii ] = lObj [ ii ] . to_dict ( ) ClsU = list ( set ( [ oo [... | Set the lObj attribute storing objects the instance depends on |
33,083 | def seek_line_forward ( self ) : pos = start_pos = self . file . tell ( ) bytes_read , read_str = self . read ( self . read_size ) start = 0 if bytes_read and read_str [ 0 ] in self . line_terminators : start += 1 while bytes_read > 0 : i = start while i < bytes_read : if read_str [ i ] in self . line_terminators : sel... | \ Searches forward from the current file position for a line terminator and seeks to the charachter after it . |
33,084 | def seek_line ( self ) : pos = end_pos = self . file . tell ( ) read_size = self . read_size if pos > read_size : pos -= read_size else : pos = 0 read_size = end_pos self . seek ( pos ) bytes_read , read_str = self . read ( read_size ) if bytes_read and read_str [ - 1 ] in self . line_terminators : bytes_read -= 1 if r... | \ Searches backwards from the current file position for a line terminator and seeks to the charachter after it . |
33,085 | def tail ( self , lines = 10 ) : self . seek_end ( ) end_pos = self . file . tell ( ) for i in range ( lines ) : if not self . seek_line ( ) : break data = self . file . read ( end_pos - self . file . tell ( ) - 1 ) if data : return self . splitlines ( data ) else : return [ ] | \ Return the last lines of the file . |
33,086 | def head ( self , lines = 10 ) : self . seek ( 0 ) for i in range ( lines ) : if not self . seek_line_forward ( ) : break end_pos = self . file . tell ( ) self . seek ( 0 ) data = self . file . read ( end_pos - 1 ) if data : return self . splitlines ( data ) else : return [ ] | \ Return the top lines of the file . |
33,087 | def get_html_tree ( filename_url_or_filelike ) : try : handler = ( HTTPSHandler if filename_url_or_filelike . lower ( ) . startswith ( 'https' ) else HTTPHandler ) cj = CookieJar ( ) opener = build_opener ( handler ) opener . add_handler ( HTTPCookieProcessor ( cj ) ) resp = opener . open ( filename_url_or_filelike ) e... | From some file path input stream or URL construct and return an HTML tree . |
33,088 | def calc_across_paths_textnodes ( paths_nodes , dbg = False ) : for path_nodes in paths_nodes : cnt = len ( path_nodes [ 1 ] [ 0 ] ) ttl = sum ( [ len ( s ) for s in paths_nodes [ 1 ] [ 0 ] ] ) path_nodes [ 1 ] [ 1 ] = cnt path_nodes [ 1 ] [ 2 ] = ttl path_nodes [ 1 ] [ 3 ] = ttl / cnt if dbg : print ( path_nodes [ 1 ]... | Given a list of parent paths tupled with children textnodes plus initialized feature values we calculate the total and average string length of the parent s children textnodes . |
33,089 | def extract ( filename_url_or_filelike ) : pars_tnodes = get_parent_xpaths_and_textnodes ( filename_url_or_filelike ) calc_across_paths_textnodes ( pars_tnodes ) avg , _ , _ = calc_avgstrlen_pathstextnodes ( pars_tnodes ) filtered = [ parpath_tnodes for parpath_tnodes in pars_tnodes if parpath_tnodes [ 1 ] [ 2 ] > avg ... | A more precise algorithm over the original eatiht algorithm |
33,090 | def extract ( filename_url_filelike_or_htmlstring ) : html_tree = get_html_tree ( filename_url_filelike_or_htmlstring ) subtrees = get_textnode_subtrees ( html_tree ) avg , _ , _ = calcavg_avgstrlen_subtrees ( subtrees ) filtered = [ subtree for subtree in subtrees if subtree . ttl_strlen > avg ] paths = [ subtree . pa... | An improved algorithm over the original eatiht algorithm |
33,091 | def __learn_oneself ( self ) : if not self . __parent_path or not self . __text_nodes : raise Exception ( "This error occurred because the step constructor\
had insufficient textnodes or it had empty string\
for its parent xpath" ) self . tnodes_cnt = len ( self .... | calculate cardinality total and average string length |
33,092 | def __make_tree ( self ) : div = E . DIV ( E . CLASS ( "container" ) ) div . append ( E . H2 ( self . __title ) ) for subtree in self . __subtrees : div . append ( subtree . get_html ( ) ) body = E . BODY ( div ) self . __htmltree = E . HTML ( E . HEAD ( E . TITLE ( self . __title ) ) , body ) | Build a tree using lxml . html . builder and our subtrees |
33,093 | def get_html ( self ) : if self . __htmltree is not None : return self . __htmltree else : self . __make_tree ( ) return self . __htmltree | Generates if need be and returns a simpler html document with text |
33,094 | def get_html_string ( self ) : if self . __htmltree is not None : return htmltostring ( self . __htmltree ) else : self . __make_tree ( ) return htmltostring ( self . __htmltree ) | Generates if need be and returns a simpler html string with extracted text |
33,095 | def get_text ( self ) : if self . __fulltext : return self . __fulltext else : self . __fulltext = "\n\n" . join ( text . get_text ( ) for text in self . __subtrees ) return self . __fulltext | Return all joined text from each subtree |
33,096 | def bootstrapify ( self ) : if self . __htmltree is None : self . __make_tree ( ) self . __htmltree . find ( 'head' ) . append ( E . LINK ( rel = "stylesheet" , href = "//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" , type = "text/css" ) ) for img_parent in self . __htmltree . xpath ( "//img/.." ) : i... | Add bootstrap cdn to headers of html |
33,097 | def rar3_type ( btype ) : if btype < rf . RAR_BLOCK_MARK or btype > rf . RAR_BLOCK_ENDARC : return "*UNKNOWN*" return block_strs [ btype - rf . RAR_BLOCK_MARK ] | RAR3 type code as string . |
33,098 | def xprint ( m , * args ) : if sys . hexversion < 0x3000000 : m = m . decode ( 'utf8' ) if args : m = m % args if sys . hexversion < 0x3000000 : m = m . encode ( 'utf8' ) sys . stdout . write ( m ) sys . stdout . write ( '\n' ) | Print string to stdout . |
33,099 | def render_flags ( flags , bit_list ) : res = [ ] known = 0 for bit in bit_list : known = known | bit [ 0 ] if flags & bit [ 0 ] : res . append ( bit [ 1 ] ) unknown = flags & ~ known n = 0 while unknown : if unknown & 1 : res . append ( "UNK_%04x" % ( 1 << n ) ) unknown = unknown >> 1 n += 1 if not res : return '-' re... | Show bit names . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.