idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
56,300
def toseries ( self ) : from thunder . series . series import Series if self . mode == 'spark' : values = self . values . values_to_keys ( tuple ( range ( 1 , len ( self . shape ) ) ) ) . unchunk ( ) if self . mode == 'local' : values = self . values . unchunk ( ) values = rollaxis ( values , 0 , values . ndim ) return Series ( values )
Converts blocks to series .
56,301
def toarray ( self ) : if self . mode == 'spark' : return self . values . unchunk ( ) . toarray ( ) if self . mode == 'local' : return self . values . unchunk ( )
Convert blocks to local ndarray
56,302
def flatten ( self ) : size = prod ( self . shape [ : - 1 ] ) return self . reshape ( size , self . shape [ - 1 ] )
Reshape all dimensions but the last into a single dimension
56,303
def tospark ( self , engine = None ) : from thunder . series . readers import fromarray if self . mode == 'spark' : logging . getLogger ( 'thunder' ) . warn ( 'images already in local mode' ) pass if engine is None : raise ValueError ( 'Must provide SparkContext' ) return fromarray ( self . toarray ( ) , index = self . index , labels = self . labels , engine = engine )
Convert to spark mode .
56,304
def sample ( self , n = 100 , seed = None ) : if n < 1 : raise ValueError ( "Number of samples must be larger than 0, got '%g'" % n ) if seed is None : seed = random . randint ( 0 , 2 ** 32 ) if self . mode == 'spark' : result = asarray ( self . values . tordd ( ) . values ( ) . takeSample ( False , n , seed ) ) else : basedims = [ self . shape [ d ] for d in self . baseaxes ] inds = [ unravel_index ( int ( k ) , basedims ) for k in random . rand ( n ) * prod ( basedims ) ] result = asarray ( [ self . values [ tupleize ( i ) + ( slice ( None , None ) , ) ] for i in inds ] ) return self . _constructor ( result , index = self . index )
Extract random sample of records .
56,305
def map ( self , func , index = None , value_shape = None , dtype = None , with_keys = False ) : if value_shape is None and index is not None : value_shape = len ( index ) if isinstance ( value_shape , int ) : values_shape = ( value_shape , ) new = super ( Series , self ) . map ( func , value_shape = value_shape , dtype = dtype , with_keys = with_keys ) if index is not None : new . index = index else : if len ( new . index ) == len ( self . index ) : new . index = self . index return new
Map an array - > array function over each record .
56,306
def mean ( self ) : return self . _constructor ( self . values . mean ( axis = self . baseaxes , keepdims = True ) )
Compute the mean across records
56,307
def sum ( self ) : return self . _constructor ( self . values . sum ( axis = self . baseaxes , keepdims = True ) )
Compute the sum across records .
56,308
def max ( self ) : return self . _constructor ( self . values . max ( axis = self . baseaxes , keepdims = True ) )
Compute the max across records .
56,309
def min ( self ) : return self . _constructor ( self . values . min ( axis = self . baseaxes , keepdims = True ) )
Compute the min across records .
56,310
def reshape ( self , * shape ) : if prod ( self . shape ) != prod ( shape ) : raise ValueError ( "Reshaping must leave the number of elements unchanged" ) if self . shape [ - 1 ] != shape [ - 1 ] : raise ValueError ( "Reshaping cannot change the size of the constituent series (last dimension)" ) if self . labels is not None : newlabels = self . labels . reshape ( * shape [ : - 1 ] ) else : newlabels = None return self . _constructor ( self . values . reshape ( shape ) , labels = newlabels ) . __finalize__ ( self , noprop = ( 'labels' , ) )
Reshape the Series object
56,311
def between ( self , left , right ) : crit = lambda x : left <= x < right return self . select ( crit )
Select subset of values within the given index range .
56,312
def select ( self , crit ) : import types if not isinstance ( crit , types . FunctionType ) : if isinstance ( crit , string_types ) : critlist = set ( [ crit ] ) else : try : critlist = set ( crit ) except TypeError : critlist = set ( [ crit ] ) crit = lambda x : x in critlist index = self . index if size ( index ) == 1 : if crit ( index [ 0 ] ) : return self else : raise Exception ( 'No indices found matching criterion' ) newindex = [ i for i in index if crit ( i ) ] if len ( newindex ) == 0 : raise Exception ( 'No indices found matching criterion' ) if array ( newindex == index ) . all ( ) : return self subinds = where ( [ crit ( i ) for i in index ] ) new = self . map ( lambda x : x [ subinds ] , index = newindex ) if len ( newindex ) == 1 : new = new . map ( lambda x : x [ 0 ] , index = newindex ) val = new . first ( ) if size ( val ) == 1 : newindex = [ newindex [ 0 ] ] else : newindex = arange ( 0 , size ( val ) ) new . _index = newindex return new
Select subset of values that match a given index criterion .
56,313
def center ( self , axis = 1 ) : if axis == 1 : return self . map ( lambda x : x - mean ( x ) ) elif axis == 0 : meanval = self . mean ( ) . toarray ( ) return self . map ( lambda x : x - meanval ) else : raise Exception ( 'Axis must be 0 or 1' )
Subtract the mean either within or across records .
56,314
def standardize ( self , axis = 1 ) : if axis == 1 : return self . map ( lambda x : x / std ( x ) ) elif axis == 0 : stdval = self . std ( ) . toarray ( ) return self . map ( lambda x : x / stdval ) else : raise Exception ( 'Axis must be 0 or 1' )
Divide by standard deviation either within or across records .
56,315
def zscore ( self , axis = 1 ) : if axis == 1 : return self . map ( lambda x : ( x - mean ( x ) ) / std ( x ) ) elif axis == 0 : meanval = self . mean ( ) . toarray ( ) stdval = self . std ( ) . toarray ( ) return self . map ( lambda x : ( x - meanval ) / stdval ) else : raise Exception ( 'Axis must be 0 or 1' )
Subtract the mean and divide by standard deviation within or across records .
56,316
def squelch ( self , threshold ) : func = lambda x : zeros ( x . shape ) if max ( x ) < threshold else x return self . map ( func )
Set all records that do not exceed the given threhsold to 0 .
56,317
def correlate ( self , signal ) : s = asarray ( signal ) if s . ndim == 1 : if size ( s ) != self . shape [ - 1 ] : raise ValueError ( "Length of signal '%g' does not match record length '%g'" % ( size ( s ) , self . shape [ - 1 ] ) ) return self . map ( lambda x : corrcoef ( x , s ) [ 0 , 1 ] , index = [ 1 ] ) elif s . ndim == 2 : if s . shape [ 1 ] != self . shape [ - 1 ] : raise ValueError ( "Length of signal '%g' does not match record length '%g'" % ( s . shape [ 1 ] , self . shape [ - 1 ] ) ) newindex = arange ( 0 , s . shape [ 0 ] ) return self . map ( lambda x : array ( [ corrcoef ( x , y ) [ 0 , 1 ] for y in s ] ) , index = newindex ) else : raise Exception ( 'Signal to correlate with must have 1 or 2 dimensions' )
Correlate records against one or many one - dimensional arrays .
56,318
def _check_panel ( self , length ) : n = len ( self . index ) if divmod ( n , length ) [ 1 ] != 0 : raise ValueError ( "Panel length '%g' must evenly divide length of series '%g'" % ( length , n ) ) if n == length : raise ValueError ( "Panel length '%g' cannot be length of series '%g'" % ( length , n ) )
Check that given fixed panel length evenly divides index .
56,319
def mean_by_panel ( self , length ) : self . _check_panel ( length ) func = lambda v : v . reshape ( - 1 , length ) . mean ( axis = 0 ) newindex = arange ( length ) return self . map ( func , index = newindex )
Compute the mean across fixed sized panels of each record .
56,320
def _makemasks ( self , index = None , level = 0 ) : if index is None : index = self . index try : dims = len ( array ( index ) . shape ) if dims == 1 : index = array ( index , ndmin = 2 ) . T except : raise TypeError ( 'A multi-index must be convertible to a numpy ndarray' ) try : index = index [ : , level ] except : raise ValueError ( "Levels must be indices into individual elements of the index" ) lenIdx = index . shape [ 0 ] nlevels = index . shape [ 1 ] combs = product ( * [ unique ( index . T [ i , : ] ) for i in range ( nlevels ) ] ) combs = array ( [ l for l in combs ] ) masks = array ( [ [ array_equal ( index [ i ] , c ) for i in range ( lenIdx ) ] for c in combs ] ) return zip ( * [ ( masks [ x ] , combs [ x ] ) for x in range ( len ( masks ) ) if masks [ x ] . any ( ) ] )
Internal function for generating masks for selecting values based on multi - index values .
56,321
def _map_by_index ( self , function , level = 0 ) : if type ( level ) is int : level = [ level ] masks , ind = self . _makemasks ( index = self . index , level = level ) nMasks = len ( masks ) newindex = array ( ind ) if len ( newindex [ 0 ] ) == 1 : newindex = ravel ( newindex ) return self . map ( lambda v : asarray ( [ array ( function ( v [ masks [ x ] ] ) ) for x in range ( nMasks ) ] ) , index = newindex )
An internal function for maping a function to groups of values based on a multi - index
56,322
def aggregate_by_index ( self , function , level = 0 ) : result = self . _map_by_index ( function , level = level ) return result . map ( lambda v : array ( v ) , index = result . index )
Aggregrate data in each record grouping by index values .
56,323
def gramian ( self ) : if self . mode == 'spark' : rdd = self . values . tordd ( ) from pyspark . accumulators import AccumulatorParam class MatrixAccumulator ( AccumulatorParam ) : def zero ( self , value ) : return zeros ( shape ( value ) ) def addInPlace ( self , val1 , val2 ) : val1 += val2 return val1 global mat init = zeros ( ( self . shape [ 1 ] , self . shape [ 1 ] ) ) mat = rdd . context . accumulator ( init , MatrixAccumulator ( ) ) def outer_sum ( x ) : global mat mat += outer ( x , x ) rdd . values ( ) . foreach ( outer_sum ) return self . _constructor ( mat . value , index = self . index ) if self . mode == 'local' : return self . _constructor ( dot ( self . values . T , self . values ) , index = self . index )
Compute gramian of a distributed matrix .
56,324
def times ( self , other ) : if isinstance ( other , ScalarType ) : other = asarray ( other ) index = self . index else : if isinstance ( other , list ) : other = asarray ( other ) if isinstance ( other , ndarray ) and other . ndim < 2 : other = expand_dims ( other , 1 ) if not self . shape [ 1 ] == other . shape [ 0 ] : raise ValueError ( 'shapes %s and %s are not aligned' % ( self . shape , other . shape ) ) index = arange ( other . shape [ 1 ] ) if self . mode == 'local' and isinstance ( other , Series ) and other . mode == 'spark' : raise NotImplementedError if self . mode == 'spark' and isinstance ( other , Series ) and other . mode == 'spark' : raise NotImplementedError if self . mode == 'local' and isinstance ( other , ( ndarray , ScalarType ) ) : return self . _constructor ( dot ( self . values , other ) , index = index ) if self . mode == 'local' and isinstance ( other , Series ) : return self . _constructor ( dot ( self . values , other . values ) , index = index ) if self . mode == 'spark' and isinstance ( other , ( ndarray , ScalarType ) ) : return self . map ( lambda x : dot ( x , other ) , index = index ) if self . mode == 'spark' and isinstance ( other , Series ) : return self . map ( lambda x : dot ( x , other . values ) , index = index )
Multiply a matrix by another one .
56,325
def _makewindows ( self , indices , window ) : div = divmod ( window , 2 ) before = div [ 0 ] after = div [ 0 ] + div [ 1 ] index = asarray ( self . index ) indices = asarray ( indices ) if where ( index == max ( indices ) ) [ 0 ] [ 0 ] + after > len ( index ) : raise ValueError ( "Maximum requested index %g, with window %g, exceeds length %g" % ( max ( indices ) , window , len ( index ) ) ) if where ( index == min ( indices ) ) [ 0 ] [ 0 ] - before < 0 : raise ValueError ( "Minimum requested index %g, with window %g, is less than 0" % ( min ( indices ) , window ) ) masks = [ arange ( where ( index == i ) [ 0 ] [ 0 ] - before , where ( index == i ) [ 0 ] [ 0 ] + after , dtype = 'int' ) for i in indices ] return masks
Make masks used by windowing functions
56,326
def mean_by_window ( self , indices , window ) : masks = self . _makewindows ( indices , window ) newindex = arange ( 0 , len ( masks [ 0 ] ) ) return self . map ( lambda x : mean ( [ x [ m ] for m in masks ] , axis = 0 ) , index = newindex )
Average series across multiple windows specified by their centers .
56,327
def subsample ( self , sample_factor = 2 ) : if sample_factor < 0 : raise Exception ( 'Factor for subsampling must be postive, got %g' % sample_factor ) s = slice ( 0 , len ( self . index ) , sample_factor ) newindex = self . index [ s ] return self . map ( lambda v : v [ s ] , index = newindex )
Subsample series by an integer factor .
56,328
def downsample ( self , sample_factor = 2 ) : if sample_factor < 0 : raise Exception ( 'Factor for subsampling must be postive, got %g' % sample_factor ) newlength = floor ( len ( self . index ) / sample_factor ) func = lambda v : v [ 0 : int ( newlength * sample_factor ) ] . reshape ( - 1 , sample_factor ) . mean ( axis = 1 ) newindex = arange ( newlength ) return self . map ( func , index = newindex )
Downsample series by an integer factor by averaging .
56,329
def fourier ( self , freq = None ) : def get ( y , freq ) : y = y - mean ( y ) nframes = len ( y ) ft = fft . fft ( y ) ft = ft [ 0 : int ( fix ( nframes / 2 ) ) ] ampFt = 2 * abs ( ft ) / nframes amp = ampFt [ freq ] ampSum = sqrt ( sum ( ampFt ** 2 ) ) co = amp / ampSum ph = - ( pi / 2 ) - angle ( ft [ freq ] ) if ph < 0 : ph += pi * 2 return array ( [ co , ph ] ) if freq >= int ( fix ( size ( self . index ) / 2 ) ) : raise Exception ( 'Requested frequency, %g, is too high, ' 'must be less than half the series duration' % freq ) index = [ 'coherence' , 'phase' ] return self . map ( lambda x : get ( x , freq ) , index = index )
Compute statistics of a Fourier decomposition on series data .
56,330
def convolve ( self , signal , mode = 'full' ) : from numpy import convolve s = asarray ( signal ) n = size ( self . index ) m = size ( s ) if mode == 'same' : newmax = max ( n , m ) elif mode == 'valid' : newmax = max ( m , n ) - min ( m , n ) + 1 else : newmax = n + m - 1 newindex = arange ( 0 , newmax ) return self . map ( lambda x : convolve ( x , signal , mode ) , index = newindex )
Convolve series data against another signal .
56,331
def crosscorr ( self , signal , lag = 0 ) : from scipy . linalg import norm s = asarray ( signal ) s = s - mean ( s ) s = s / norm ( s ) if size ( s ) != size ( self . index ) : raise Exception ( 'Size of signal to cross correlate with, %g, ' 'does not match size of series' % size ( s ) ) if lag is not 0 : shifts = range ( - lag , lag + 1 ) d = len ( s ) m = len ( shifts ) sshifted = zeros ( ( m , d ) ) for i in range ( 0 , len ( shifts ) ) : tmp = roll ( s , shifts [ i ] ) if shifts [ i ] < 0 : tmp [ ( d + shifts [ i ] ) : ] = 0 if shifts [ i ] > 0 : tmp [ : shifts [ i ] ] = 0 sshifted [ i , : ] = tmp s = sshifted else : shifts = [ 0 ] def get ( y , s ) : y = y - mean ( y ) n = norm ( y ) if n == 0 : b = zeros ( ( s . shape [ 0 ] , ) ) else : y /= n b = dot ( s , y ) return b return self . map ( lambda x : get ( x , s ) , index = shifts )
Cross correlate series data against another signal .
56,332
def detrend ( self , method = 'linear' , order = 5 ) : check_options ( method , [ 'linear' , 'nonlinear' ] ) if method == 'linear' : order = 1 def func ( y ) : x = arange ( len ( y ) ) p = polyfit ( x , y , order ) p [ - 1 ] = 0 yy = polyval ( p , x ) return y - yy return self . map ( func )
Detrend series data with linear or nonlinear detrending .
56,333
def normalize ( self , method = 'percentile' , window = None , perc = 20 , offset = 0.1 ) : check_options ( method , [ 'mean' , 'percentile' , 'window' , 'window-exact' ] ) from warnings import warn if not ( method == 'window' or method == 'window-exact' ) and window is not None : warn ( 'Setting window without using method "window" has no effect' ) if method == 'mean' : baseFunc = mean if method == 'percentile' : baseFunc = lambda x : percentile ( x , perc ) if method == 'window' : from scipy . ndimage . filters import percentile_filter baseFunc = lambda x : percentile_filter ( x . astype ( float64 ) , perc , window , mode = 'nearest' ) if method == 'window-exact' : if window & 0x1 : left , right = ( ceil ( window / 2 ) , ceil ( window / 2 ) + 1 ) else : left , right = ( window / 2 , window / 2 ) n = len ( self . index ) baseFunc = lambda x : asarray ( [ percentile ( x [ max ( ix - left , 0 ) : min ( ix + right + 1 , n ) ] , perc ) for ix in arange ( 0 , n ) ] ) def get ( y ) : b = baseFunc ( y ) return ( y - b ) / ( b + offset ) return self . map ( get )
Normalize by subtracting and dividing by a baseline .
56,334
def toimages ( self , chunk_size = 'auto' ) : from thunder . images . images import Images if chunk_size is 'auto' : chunk_size = str ( max ( [ int ( 1e5 / prod ( self . baseshape ) ) , 1 ] ) ) n = len ( self . shape ) - 1 if self . mode == 'spark' : return Images ( self . values . swap ( tuple ( range ( n ) ) , ( 0 , ) , size = chunk_size ) ) if self . mode == 'local' : return Images ( self . values . transpose ( ( n , ) + tuple ( range ( 0 , n ) ) ) )
Converts to images data .
56,335
def tobinary ( self , path , prefix = 'series' , overwrite = False , credentials = None ) : from thunder . series . writers import tobinary tobinary ( self , path , prefix = prefix , overwrite = overwrite , credentials = credentials )
Write data to binary files .
56,336
def addextension ( path , ext = None ) : if ext : if '*' in path : return path elif os . path . splitext ( path ) [ 1 ] : return path else : if not ext . startswith ( '.' ) : ext = '.' + ext if not path . endswith ( ext ) : if not path . endswith ( os . path . sep ) : path += os . path . sep return path + '*' + ext else : return path else : return path
Helper function for handling of paths given separately passed file extensions .
56,337
def select ( files , start , stop ) : if start or stop : if start is None : start = 0 if stop is None : stop = len ( files ) files = files [ start : stop ] return files
Helper function for handling start and stop indices
56,338
def listrecursive ( path , ext = None ) : filenames = set ( ) for root , dirs , files in os . walk ( path ) : if ext : if ext == 'tif' or ext == 'tiff' : tmp = fnmatch . filter ( files , '*.' + 'tiff' ) files = tmp + fnmatch . filter ( files , '*.' + 'tif' ) else : files = fnmatch . filter ( files , '*.' + ext ) for filename in files : filenames . add ( os . path . join ( root , filename ) ) filenames = list ( filenames ) filenames . sort ( ) return sorted ( filenames )
List files recurisvely
56,339
def listflat ( path , ext = None ) : if os . path . isdir ( path ) : if ext : if ext == 'tif' or ext == 'tiff' : files = glob . glob ( os . path . join ( path , '*.tif' ) ) files = files + glob . glob ( os . path . join ( path , '*.tiff' ) ) else : files = glob . glob ( os . path . join ( path , '*.' + ext ) ) else : files = [ os . path . join ( path , fname ) for fname in os . listdir ( path ) ] else : files = glob . glob ( path ) files = [ fpath for fpath in files if not isinstance ( fpath , list ) and not os . path . isdir ( fpath ) ] return sorted ( files )
List files without recursion
56,340
def normalize_scheme ( path , ext ) : path = addextension ( path , ext ) parsed = urlparse ( path ) if parsed . scheme : return path else : import os dirname , filename = os . path . split ( path ) if not os . path . isabs ( dirname ) : dirname = os . path . abspath ( dirname ) path = os . path . join ( dirname , filename ) return "file://" + path
Normalize scheme for paths related to hdfs
56,341
def list ( path , ext = None , start = None , stop = None , recursive = False ) : files = listflat ( path , ext ) if not recursive else listrecursive ( path , ext ) if len ( files ) < 1 : raise FileNotFoundError ( 'Cannot find files of type "%s" in %s' % ( ext if ext else '*' , path ) ) files = select ( files , start , stop ) return files
Get sorted list of file paths matching path and extension
56,342
def read ( self , path , ext = None , start = None , stop = None , recursive = False , npartitions = None ) : path = uri_to_path ( path ) files = self . list ( path , ext = ext , start = start , stop = stop , recursive = recursive ) nfiles = len ( files ) self . nfiles = nfiles if spark and isinstance ( self . engine , spark ) : npartitions = min ( npartitions , nfiles ) if npartitions else nfiles rdd = self . engine . parallelize ( enumerate ( files ) , npartitions ) return rdd . map ( lambda kv : ( kv [ 0 ] , readlocal ( kv [ 1 ] ) , kv [ 1 ] ) ) else : return [ ( k , readlocal ( v ) , v ) for k , v in enumerate ( files ) ]
Sets up Spark RDD across files specified by dataPath on local filesystem .
56,343
def list ( path , filename = None , start = None , stop = None , recursive = False , directories = False ) : path = uri_to_path ( path ) if not filename and recursive : return listrecursive ( path ) if filename : if os . path . isdir ( path ) : path = os . path . join ( path , filename ) else : path = os . path . join ( os . path . dirname ( path ) , filename ) else : if os . path . isdir ( path ) and not directories : path = os . path . join ( path , "*" ) files = glob . glob ( path ) if not directories : files = [ fpath for fpath in files if not os . path . isdir ( fpath ) ] files . sort ( ) files = select ( files , start , stop ) return files
List files specified by dataPath .
56,344
def parse_query ( query , delim = '/' ) : key = '' prefix = '' postfix = '' parsed = urlparse ( query ) query = parsed . path . lstrip ( delim ) bucket = parsed . netloc if not parsed . scheme . lower ( ) in ( '' , "gs" , "s3" , "s3n" ) : raise ValueError ( "Query scheme must be one of '', 'gs', 's3', or 's3n'; " "got: '%s'" % parsed . scheme ) storage = parsed . scheme . lower ( ) if not bucket . strip ( ) and query : toks = query . split ( delim , 1 ) bucket = toks [ 0 ] if len ( toks ) == 2 : key = toks [ 1 ] else : key = '' if not bucket . strip ( ) : raise ValueError ( "Could not parse bucket name from query string '%s'" % query ) tokens = query . split ( "*" ) n = len ( tokens ) if n == 0 : pass elif n == 1 : key = tokens [ 0 ] elif n == 2 : index = tokens [ 0 ] . rfind ( delim ) if index >= 0 : key = tokens [ 0 ] [ : ( index + 1 ) ] prefix = tokens [ 0 ] [ ( index + 1 ) : ] if len ( tokens [ 0 ] ) > ( index + 1 ) else '' else : prefix = tokens [ 0 ] postfix = tokens [ 1 ] else : raise ValueError ( "Only one wildcard ('*') allowed in query string, got: '%s'" % query ) return storage , bucket , key , prefix , postfix
Parse a boto query
56,345
def retrieve_keys ( bucket , key , prefix = '' , postfix = '' , delim = '/' , directories = False , recursive = False ) : if key and prefix : assert key . endswith ( delim ) key += prefix if not key . endswith ( delim ) and key : if BotoClient . check_prefix ( bucket , key + delim , delim = delim ) : key += delim listdelim = delim if not recursive else None results = bucket . list ( prefix = key , delimiter = listdelim ) if postfix : func = lambda k_ : BotoClient . filter_predicate ( k_ , postfix , inclusive = True ) return filter ( func , results ) elif not directories : func = lambda k_ : BotoClient . filter_predicate ( k_ , delim , inclusive = False ) return filter ( func , results ) else : return results
Retrieve keys from a bucket
56,346
def getfiles ( self , path , ext = None , start = None , stop = None , recursive = False ) : from . utils import connection_with_anon , connection_with_gs parse = BotoClient . parse_query ( path ) scheme = parse [ 0 ] bucket_name = parse [ 1 ] if scheme == 's3' or scheme == 's3n' : conn = connection_with_anon ( self . credentials ) bucket = conn . get_bucket ( parse [ 1 ] ) elif scheme == 'gs' : conn = connection_with_gs ( bucket_name ) bucket = conn . get_bucket ( ) else : raise NotImplementedError ( "No file reader implementation for URL scheme " + scheme ) keys = BotoClient . retrieve_keys ( bucket , parse [ 2 ] , prefix = parse [ 3 ] , postfix = parse [ 4 ] , recursive = recursive ) keylist = [ key . name for key in keys ] if ext : if ext == 'tif' or ext == 'tiff' : keylist = [ keyname for keyname in keylist if keyname . endswith ( 'tif' ) ] keylist . append ( [ keyname for keyname in keylist if keyname . endswith ( 'tiff' ) ] ) else : keylist = [ keyname for keyname in keylist if keyname . endswith ( ext ) ] keylist . sort ( ) keylist = select ( keylist , start , stop ) return scheme , bucket . name , keylist
Get scheme bucket and keys for a set of files
56,347
def list ( self , dataPath , ext = None , start = None , stop = None , recursive = False ) : scheme , bucket_name , keylist = self . getfiles ( dataPath , ext = ext , start = start , stop = stop , recursive = recursive ) return [ "%s:///%s/%s" % ( scheme , bucket_name , key ) for key in keylist ]
List files from remote storage
56,348
def read ( self , path , ext = None , start = None , stop = None , recursive = False , npartitions = None ) : from . utils import connection_with_anon , connection_with_gs path = addextension ( path , ext ) scheme , bucket_name , keylist = self . getfiles ( path , start = start , stop = stop , recursive = recursive ) if not keylist : raise FileNotFoundError ( "No objects found for '%s'" % path ) credentials = self . credentials self . nfiles = len ( keylist ) if spark and isinstance ( self . engine , spark ) : def getsplit ( kvIter ) : if scheme == 's3' or scheme == 's3n' : conn = connection_with_anon ( credentials ) bucket = conn . get_bucket ( bucket_name ) elif scheme == 'gs' : conn = boto . storage_uri ( bucket_name , 'gs' ) bucket = conn . get_bucket ( ) else : raise NotImplementedError ( "No file reader implementation for URL scheme " + scheme ) for kv in kvIter : idx , keyname = kv key = bucket . get_key ( keyname ) buf = key . get_contents_as_string ( ) yield idx , buf , keyname npartitions = min ( npartitions , self . nfiles ) if npartitions else self . nfiles rdd = self . engine . parallelize ( enumerate ( keylist ) , npartitions ) return rdd . mapPartitions ( getsplit ) else : if scheme == 's3' or scheme == 's3n' : conn = connection_with_anon ( credentials ) bucket = conn . get_bucket ( bucket_name ) elif scheme == 'gs' : conn = connection_with_gs ( bucket_name ) bucket = conn . get_bucket ( ) else : raise NotImplementedError ( "No file reader implementation for URL scheme " + scheme ) def getsplit ( kv ) : idx , keyName = kv key = bucket . get_key ( keyName ) buf = key . get_contents_as_string ( ) return idx , buf , keyName return [ getsplit ( kv ) for kv in enumerate ( keylist ) ]
Sets up Spark RDD across S3 or GS objects specified by dataPath .
56,349
def getkeys ( self , path , filename = None , directories = False , recursive = False ) : from . utils import connection_with_anon , connection_with_gs parse = BotoClient . parse_query ( path ) scheme = parse [ 0 ] bucket_name = parse [ 1 ] key = parse [ 2 ] if scheme == 's3' or scheme == 's3n' : conn = connection_with_anon ( self . credentials ) bucket = conn . get_bucket ( bucket_name ) elif scheme == 'gs' : conn = connection_with_gs ( bucket_name ) bucket = conn . get_bucket ( ) else : raise NotImplementedError ( "No file reader implementation for URL scheme " + scheme ) if filename : if not key . endswith ( "/" ) : if self . check_prefix ( bucket , key + "/" ) : key += "/" else : index = key . rfind ( "/" ) if index >= 0 : key = key [ : ( index + 1 ) ] else : key = "" key += filename keylist = BotoClient . retrieve_keys ( bucket , key , prefix = parse [ 3 ] , postfix = parse [ 4 ] , directories = directories , recursive = recursive ) return scheme , keylist
Get matching keys for a path
56,350
def getkey ( self , path , filename = None ) : scheme , keys = self . getkeys ( path , filename = filename ) try : key = next ( keys ) except StopIteration : raise FileNotFoundError ( "Could not find object for: '%s'" % path ) nextKey = None try : nextKey = next ( keys ) except StopIteration : pass if nextKey : raise ValueError ( "Found multiple keys for: '%s'" % path ) return scheme , key
Get single matching key for a path
56,351
def list ( self , path , filename = None , start = None , stop = None , recursive = False , directories = False ) : storageScheme , keys = self . getkeys ( path , filename = filename , directories = directories , recursive = recursive ) keys = [ storageScheme + ":///" + key . bucket . name + "/" + key . name for key in keys ] keys . sort ( ) keys = select ( keys , start , stop ) return keys
List objects specified by path .
56,352
def read ( self , path , filename = None , offset = None , size = - 1 ) : storageScheme , key = self . getkey ( path , filename = filename ) if offset or ( size > - 1 ) : if not offset : offset = 0 if size > - 1 : sizeStr = offset + size - 1 else : sizeStr = "" headers = { "Range" : "bytes=%d-%s" % ( offset , sizeStr ) } return key . get_contents_as_string ( headers = headers ) else : return key . get_contents_as_string ( )
Read a file specified by path .
56,353
def open ( self , path , filename = None ) : scheme , key = self . getkey ( path , filename = filename ) return BotoReadFileHandle ( scheme , key )
Open a file specified by path .
56,354
def check_path ( path , credentials = None ) : from thunder . readers import get_file_reader reader = get_file_reader ( path ) ( credentials = credentials ) existing = reader . list ( path , directories = True ) if existing : raise ValueError ( 'Path %s appears to already exist. Specify a new directory, ' 'or call with overwrite=True to overwrite.' % path )
Check that specified output path does not already exist
56,355
def connection_with_anon ( credentials , anon = True ) : from boto . s3 . connection import S3Connection from boto . exception import NoAuthHandlerFound try : conn = S3Connection ( aws_access_key_id = credentials [ 'access' ] , aws_secret_access_key = credentials [ 'secret' ] ) return conn except NoAuthHandlerFound : if anon : conn = S3Connection ( anon = True ) return conn else : raise
Connect to S3 with automatic handling for anonymous access .
56,356
def activate ( self , path , isdirectory ) : from . utils import connection_with_anon , connection_with_gs parsed = BotoClient . parse_query ( path ) scheme = parsed [ 0 ] bucket_name = parsed [ 1 ] key = parsed [ 2 ] if scheme == 's3' or scheme == 's3n' : conn = connection_with_anon ( self . credentials ) bucket = conn . get_bucket ( bucket_name ) elif scheme == 'gs' : conn = connection_with_gs ( bucket_name ) bucket = conn . get_bucket ( ) else : raise NotImplementedError ( "No file reader implementation for URL scheme " + scheme ) if isdirectory and ( not key . endswith ( "/" ) ) : key += "/" self . _scheme = scheme self . _conn = conn self . _key = key self . _bucket = bucket self . _active = True
Set up a boto connection .
56,357
def topng ( images , path , prefix = "image" , overwrite = False , credentials = None ) : value_shape = images . value_shape if not len ( value_shape ) in [ 2 , 3 ] : raise ValueError ( "Only 2D or 3D images can be exported to png, " "images are %d-dimensional." % len ( value_shape ) ) from scipy . misc import imsave from io import BytesIO from thunder . writers import get_parallel_writer def tobuffer ( kv ) : key , img = kv fname = prefix + "-" + "%05d.png" % int ( key ) bytebuf = BytesIO ( ) imsave ( bytebuf , img , format = 'PNG' ) return fname , bytebuf . getvalue ( ) writer = get_parallel_writer ( path ) ( path , overwrite = overwrite , credentials = credentials ) images . foreach ( lambda x : writer . write ( tobuffer ( x ) ) )
Write out PNG files for 2d image data .
56,358
def tobinary ( images , path , prefix = "image" , overwrite = False , credentials = None ) : from thunder . writers import get_parallel_writer def tobuffer ( kv ) : key , img = kv fname = prefix + "-" + "%05d.bin" % int ( key ) return fname , img . copy ( ) writer = get_parallel_writer ( path ) ( path , overwrite = overwrite , credentials = credentials ) images . foreach ( lambda x : writer . write ( tobuffer ( x ) ) ) config ( path , list ( images . value_shape ) , images . dtype , overwrite = overwrite )
Write out images as binary files .
56,359
def yearInfo2yearDay ( yearInfo ) : yearInfo = int ( yearInfo ) res = 29 * 12 leap = False if yearInfo % 16 != 0 : leap = True res += 29 yearInfo //= 16 for i in range ( 12 + leap ) : if yearInfo % 2 == 1 : res += 1 yearInfo //= 2 return res
calculate the days in a lunar year from the lunar year s info
56,360
def cleanupFilename ( self , name ) : context = self . context id = '' name = name . replace ( '\\' , '/' ) name = name . split ( '/' ) [ - 1 ] for c in name : if c . isalnum ( ) or c in '._' : id += c if context . check_id ( id ) is None and getattr ( context , id , None ) is None : return id count = 1 while 1 : if count == 1 : sc = '' else : sc = str ( count ) newid = "copy{0:s}_of_{1:s}" . format ( sc , id ) if context . check_id ( newid ) is None and getattr ( context , newid , None ) is None : return newid count += 1
Generate a unique id which doesn t match the system generated ids
56,361
def parse_data_slots ( value ) : value = unquote ( value ) if '>' in value : wrappers , children = value . split ( '>' , 1 ) else : wrappers = value children = '' if '*' in children : prepends , appends = children . split ( '*' , 1 ) else : prepends = children appends = '' wrappers = list ( filter ( bool , list ( map ( str . strip , wrappers . split ( ) ) ) ) ) prepends = list ( filter ( bool , list ( map ( str . strip , prepends . split ( ) ) ) ) ) appends = list ( filter ( bool , list ( map ( str . strip , appends . split ( ) ) ) ) ) return wrappers , prepends , appends
Parse data - slots value into slots used to wrap node prepend to node or append to node .
56,362
def cook_layout ( layout , ajax ) : layout = re . sub ( '\r' , '\n' , re . sub ( '\r\n' , '\n' , layout ) ) if isinstance ( layout , six . text_type ) : result = getHTMLSerializer ( [ layout . encode ( 'utf-8' ) ] , encoding = 'utf-8' ) else : result = getHTMLSerializer ( [ layout ] , encoding = 'utf-8' ) if '<![CDATA[' in layout : result . serializer = html . tostring all_slots = [ ] for layoutPanelNode in slotsXPath ( result . tree ) : data_slots = layoutPanelNode . attrib [ 'data-slots' ] all_slots += wrap_append_prepend_slots ( layoutPanelNode , data_slots ) del layoutPanelNode . attrib [ 'data-slots' ] if len ( all_slots ) == 0 : for node in result . tree . xpath ( '//*[@data-panel="content"]' ) : wrap_append_prepend_slots ( node , 'content > body header main * content-core' ) head = result . tree . getroot ( ) . find ( 'head' ) if not ajax and head is not None : for name in [ 'top_slot' , 'head_slot' , 'style_slot' , 'javascript_head_slot' ] : slot = etree . Element ( '{{{0:s}}}{1:s}' . format ( NSMAP [ 'metal' ] , name ) , nsmap = NSMAP ) slot . attrib [ 'define-slot' ] = name head . append ( slot ) template = TEMPLATE metal = 'xmlns:metal="http://namespaces.zope.org/metal"' return ( template % '' . join ( result ) ) . replace ( metal , '' )
Return main_template compatible layout
56,363
def existing ( self ) : catalog = api . portal . get_tool ( 'portal_catalog' ) results = [ ] layout_path = self . _get_layout_path ( self . request . form . get ( 'layout' , '' ) ) for brain in catalog ( layout = layout_path ) : results . append ( { 'title' : brain . Title , 'url' : brain . getURL ( ) } ) return json . dumps ( { 'total' : len ( results ) , 'data' : results } )
find existing content assigned to this layout
56,364
def load_reader_options ( ) : options = os . environ [ 'PANDOC_READER_OPTIONS' ] options = json . loads ( options , object_pairs_hook = OrderedDict ) return options
Retrieve Pandoc Reader options from the environment
56,365
def yaml_filter ( element , doc , tag = None , function = None , tags = None , strict_yaml = False ) : assert ( tag is None ) + ( tags is None ) == 1 if tags is None : tags = { tag : function } if type ( element ) == CodeBlock : for tag in tags : if tag in element . classes : function = tags [ tag ] if not strict_yaml : raw = re . split ( "^([.]{3,}|[-]{3,})$" , element . text , 1 , re . MULTILINE ) data = raw [ 2 ] if len ( raw ) > 2 else '' data = data . lstrip ( '\n' ) raw = raw [ 0 ] try : options = yaml . safe_load ( raw ) except yaml . scanner . ScannerError : debug ( "panflute: malformed YAML block" ) return if options is None : options = { } else : options = { } data = [ ] raw = re . split ( "^([.]{3,}|[-]{3,})$" , element . text , 0 , re . MULTILINE ) rawmode = True for chunk in raw : chunk = chunk . strip ( '\n' ) if not chunk : continue if rawmode : if chunk . startswith ( '---' ) : rawmode = False else : data . append ( chunk ) else : if chunk . startswith ( '---' ) or chunk . startswith ( '...' ) : rawmode = True else : try : options . update ( yaml . safe_load ( chunk ) ) except yaml . scanner . ScannerError : debug ( "panflute: malformed YAML block" ) return data = '\n' . join ( data ) return function ( options = options , data = data , element = element , doc = doc )
Convenience function for parsing code blocks with YAML options
56,366
def _set_content ( self , value , oktypes ) : if value is None : value = [ ] self . _content = ListContainer ( * value , oktypes = oktypes , parent = self )
Similar to content . setter but when there are no existing oktypes
56,367
def offset ( self , n ) : idx = self . index if idx is not None : sibling = idx + n container = self . container if 0 <= sibling < len ( container ) : return container [ sibling ]
Return a sibling element offset by n
56,368
def search ( self , term : str , case_sensitive : bool = False ) -> 'PrettyDir' : if case_sensitive : return PrettyDir ( self . obj , [ pattr for pattr in self . pattrs if term in pattr . name ] ) else : term = term . lower ( ) return PrettyDir ( self . obj , [ pattr for pattr in self . pattrs if term in pattr . name . lower ( ) ] )
Searches for names that match some pattern .
56,369
def properties ( self ) -> 'PrettyDir' : return PrettyDir ( self . obj , [ pattr for pattr in self . pattrs if category_match ( pattr . category , AttrCategory . PROPERTY ) ] , )
Returns all properties of the inspected object .
56,370
def methods ( self ) -> 'PrettyDir' : return PrettyDir ( self . obj , [ pattr for pattr in self . pattrs if category_match ( pattr . category , AttrCategory . FUNCTION ) ] , )
Returns all methods of the inspected object .
56,371
def public ( self ) -> 'PrettyDir' : return PrettyDir ( self . obj , [ pattr for pattr in self . pattrs if not pattr . name . startswith ( '_' ) ] )
Returns public attributes of the inspected object .
56,372
def own ( self ) -> 'PrettyDir' : return PrettyDir ( self . obj , [ pattr for pattr in self . pattrs if pattr . name in type ( self . obj ) . __dict__ or pattr . name in self . obj . __dict__ ] , )
Returns attributes that are not inhterited from parent classes .
56,373
def get_oneline_doc ( self ) -> str : attr = self . attr_obj if self . display_group == AttrCategory . DESCRIPTOR : if isinstance ( attr , property ) : doc_list = [ '@property with getter' ] if attr . fset : doc_list . append ( SETTER ) if attr . fdel : doc_list . append ( DELETER ) else : doc_list = [ 'class %s' % attr . __class__ . __name__ ] if hasattr ( attr , '__get__' ) : doc_list . append ( GETTER ) if hasattr ( attr , '__set__' ) : doc_list . append ( SETTER ) if hasattr ( attr , '__delete__' ) : doc_list . append ( DELETER ) doc_list [ 0 ] = ' ' . join ( [ doc_list [ 0 ] , 'with' , doc_list . pop ( 1 ) ] ) if attr . __doc__ is not None : doc_list . append ( inspect . getdoc ( attr ) . split ( '\n' , 1 ) [ 0 ] ) return ', ' . join ( doc_list ) if hasattr ( attr , '__doc__' ) : doc = inspect . getdoc ( attr ) return doc . split ( '\n' , 1 ) [ 0 ] if doc else '' return ''
Doc doesn t necessarily mean doctring . It could be anything that should be put after the attr s name as an explanation .
56,374
def format_pattrs ( pattrs : List [ 'api.PrettyAttribute' ] ) -> str : output = [ ] pattrs . sort ( key = lambda x : ( _FORMATTER [ x . display_group ] . display_index , x . display_group , x . name , ) ) for display_group , grouped_pattrs in groupby ( pattrs , lambda x : x . display_group ) : output . append ( _FORMATTER [ display_group ] . formatter ( display_group , grouped_pattrs ) ) return '\n' . join ( output )
Generates repr string given a list of pattrs .
56,375
def get_attr_from_dict ( inspected_obj : Any , attr_name : str ) -> Any : if inspect . isclass ( inspected_obj ) : obj_list = [ inspected_obj ] + list ( inspected_obj . __mro__ ) else : obj_list = [ inspected_obj ] + list ( inspected_obj . __class__ . __mro__ ) for obj in obj_list : if hasattr ( obj , '__dict__' ) and attr_name in obj . __dict__ : return obj . __dict__ [ attr_name ] return attr_name
Ensures we get descriptor object instead of its return value .
56,376
def attr_category_postprocess ( get_attr_category_func ) : @ functools . wraps ( get_attr_category_func ) def wrapped ( name : str , attr : Any , obj : Any ) -> Tuple [ AttrCategory , ... ] : category = get_attr_category_func ( name , attr , obj ) category = list ( category ) if isinstance ( category , tuple ) else [ category ] if is_slotted_attr ( obj , name ) : category . append ( AttrCategory . SLOT ) return tuple ( category ) return wrapped
Unifies attr_category to a tuple add AttrCategory . SLOT if needed .
56,377
def get_peak_mem ( ) : import resource rusage_denom = 1024. if sys . platform == 'darwin' : rusage_denom = rusage_denom * rusage_denom mem = resource . getrusage ( resource . RUSAGE_SELF ) . ru_maxrss / rusage_denom return mem
this returns peak memory use since process starts till the moment its called
56,378
def dfs_do_func_on_graph ( node , func , * args , ** kwargs ) : for _node in node . tree_iterator ( ) : func ( _node , * args , ** kwargs )
invoke func on each node of the dr graph
56,379
def sparse_is_desireable ( lhs , rhs ) : return False if len ( lhs . shape ) == 1 : return False else : lhs_rows , lhs_cols = lhs . shape if len ( rhs . shape ) == 1 : rhs_rows = 1 rhs_cols = rhs . size else : rhs_rows , rhs_cols = rhs . shape result_size = lhs_rows * rhs_cols if sp . issparse ( lhs ) and sp . issparse ( rhs ) : return True elif sp . issparse ( lhs ) : lhs_zero_rows = lhs_rows - np . unique ( lhs . nonzero ( ) [ 0 ] ) . size rhs_zero_cols = np . all ( rhs == 0 , axis = 0 ) . sum ( ) elif sp . issparse ( rhs ) : lhs_zero_rows = np . all ( lhs == 0 , axis = 1 ) . sum ( ) rhs_zero_cols = rhs_cols - np . unique ( rhs . nonzero ( ) [ 1 ] ) . size else : lhs_zero_rows = np . all ( lhs == 0 , axis = 1 ) . sum ( ) rhs_zero_cols = np . all ( rhs == 0 , axis = 0 ) . sum ( ) num_zeros = lhs_zero_rows * rhs_cols + rhs_zero_cols * lhs_rows - lhs_zero_rows * rhs_zero_cols return ( float ( num_zeros ) / float ( size ) ) >= 0.5
Examines a pair of matrices and determines if the result of their multiplication should be sparse or not .
56,380
def convert_inputs_to_sparse_if_necessary ( lhs , rhs ) : if not sp . issparse ( lhs ) or not sp . issparse ( rhs ) : if sparse_is_desireable ( lhs , rhs ) : if not sp . issparse ( lhs ) : lhs = sp . csc_matrix ( lhs ) if not sp . issparse ( rhs ) : rhs = sp . csc_matrix ( rhs ) return lhs , rhs
This function checks to see if a sparse output is desireable given the inputs and if so casts the inputs to sparse in order to make it so .
56,381
def dr_wrt ( self , wrt , profiler = None ) : if wrt is self . x : jacs = [ ] for fvi , freevar in enumerate ( self . free_variables ) : tm = timer ( ) if isinstance ( freevar , ch . Select ) : new_jac = self . obj . dr_wrt ( freevar . a , profiler = profiler ) try : new_jac = new_jac [ : , freevar . idxs ] except : new_jac = new_jac . tocsc ( ) [ : , freevar . idxs ] else : new_jac = self . obj . dr_wrt ( freevar , profiler = profiler ) pif ( 'dx wrt {} in {}sec, sparse: {}' . format ( freevar . short_name , tm ( ) , sp . issparse ( new_jac ) ) ) if self . _make_dense and sp . issparse ( new_jac ) : new_jac = new_jac . todense ( ) if self . _make_sparse and not sp . issparse ( new_jac ) : new_jac = sp . csc_matrix ( new_jac ) if new_jac is None : raise Exception ( 'Objective has no derivative wrt free variable {}. ' 'You should likely remove it.' . format ( fvi ) ) jacs . append ( new_jac ) tm = timer ( ) utils . dfs_do_func_on_graph ( self . obj , clear_cache_single ) pif ( 'dfs_do_func_on_graph in {}sec' . format ( tm ( ) ) ) tm = timer ( ) J = hstack ( jacs ) pif ( 'hstack in {}sec' . format ( tm ( ) ) ) return J
Loop over free variables and delete cache for the whole tree after finished each one
56,382
def J ( self ) : result = self . dr_wrt ( self . x , profiler = self . profiler ) . copy ( ) if self . profiler : self . profiler . harvest ( ) return np . atleast_2d ( result ) if not sp . issparse ( result ) else result
Compute Jacobian . Analyze dr graph first to disable unnecessary caching
56,383
def sid ( self ) : pnames = list ( self . terms ) + list ( self . dterms ) pnames . sort ( ) return ( self . __class__ , tuple ( [ ( k , id ( self . __dict__ [ k ] ) ) for k in pnames if k in self . __dict__ ] ) )
Semantic id .
56,384
def compute_dr_wrt ( self , wrt ) : if wrt is self : return sp . eye ( self . x . size , self . x . size ) return None
Default method for objects that just contain a number or ndarray
56,385
def get_ubuntu_release_from_sentry ( self , sentry_unit ) : msg = None cmd = 'lsb_release -cs' release , code = sentry_unit . run ( cmd ) if code == 0 : self . log . debug ( '{} lsb_release: {}' . format ( sentry_unit . info [ 'unit_name' ] , release ) ) else : msg = ( '{} `{}` returned {} ' '{}' . format ( sentry_unit . info [ 'unit_name' ] , cmd , release , code ) ) if release not in self . ubuntu_releases : msg = ( "Release ({}) not found in Ubuntu releases " "({})" . format ( release , self . ubuntu_releases ) ) return release , msg
Get Ubuntu release codename from sentry unit .
56,386
def validate_services ( self , commands ) : self . log . debug ( 'Checking status of system services...' ) self . log . warn ( 'DEPRECATION WARNING: use ' 'validate_services_by_name instead of validate_services ' 'due to init system differences.' ) for k , v in six . iteritems ( commands ) : for cmd in v : output , code = k . run ( cmd ) self . log . debug ( '{} `{}` returned ' '{}' . format ( k . info [ 'unit_name' ] , cmd , code ) ) if code != 0 : return "command `{}` returned {}" . format ( cmd , str ( code ) ) return None
Validate that lists of commands succeed on service units . Can be used to verify system services are running on the corresponding service units .
56,387
def validate_services_by_name ( self , sentry_services ) : self . log . debug ( 'Checking status of system services...' ) systemd_switch = self . ubuntu_releases . index ( 'vivid' ) for sentry_unit , services_list in six . iteritems ( sentry_services ) : release , ret = self . get_ubuntu_release_from_sentry ( sentry_unit ) if ret : return ret for service_name in services_list : if ( self . ubuntu_releases . index ( release ) >= systemd_switch or service_name in [ 'rabbitmq-server' , 'apache2' , 'memcached' ] ) : cmd = 'sudo service {} status' . format ( service_name ) output , code = sentry_unit . run ( cmd ) service_running = code == 0 elif self . ubuntu_releases . index ( release ) < systemd_switch : cmd = 'sudo status {}' . format ( service_name ) output , code = sentry_unit . run ( cmd ) service_running = code == 0 and "start/running" in output self . log . debug ( '{} `{}` returned ' '{}' . format ( sentry_unit . info [ 'unit_name' ] , cmd , code ) ) if not service_running : return u"command `{}` returned {} {}" . format ( cmd , output , str ( code ) ) return None
Validate system service status by service name automatically detecting init system based on Ubuntu release codename .
56,388
def _get_config ( self , unit , filename ) : file_contents = unit . file_contents ( filename ) config = configparser . ConfigParser ( allow_no_value = True ) config . readfp ( io . StringIO ( file_contents ) ) return config
Get a ConfigParser object for parsing a unit s config file .
56,389
def validate_config_data ( self , sentry_unit , config_file , section , expected ) : self . log . debug ( 'Validating config file data ({} in {} on {})' '...' . format ( section , config_file , sentry_unit . info [ 'unit_name' ] ) ) config = self . _get_config ( sentry_unit , config_file ) if section != 'DEFAULT' and not config . has_section ( section ) : return "section [{}] does not exist" . format ( section ) for k in expected . keys ( ) : if not config . has_option ( section , k ) : return "section [{}] is missing option {}" . format ( section , k ) actual = config . get ( section , k ) v = expected [ k ] if ( isinstance ( v , six . string_types ) or isinstance ( v , bool ) or isinstance ( v , six . integer_types ) ) : if actual != v : return "section [{}] {}:{} != expected {}:{}" . format ( section , k , actual , k , expected [ k ] ) elif not v ( actual ) : return "section [{}] {}:{} != expected {}:{}" . format ( section , k , actual , k , expected [ k ] ) return None
Validate config file data .
56,390
def _validate_dict_data ( self , expected , actual ) : self . log . debug ( 'actual: {}' . format ( repr ( actual ) ) ) self . log . debug ( 'expected: {}' . format ( repr ( expected ) ) ) for k , v in six . iteritems ( expected ) : if k in actual : if ( isinstance ( v , six . string_types ) or isinstance ( v , bool ) or isinstance ( v , six . integer_types ) ) : if v != actual [ k ] : return "{}:{}" . format ( k , actual [ k ] ) elif not v ( actual [ k ] ) : return "{}:{}" . format ( k , actual [ k ] ) else : return "key '{}' does not exist" . format ( k ) return None
Validate dictionary data .
56,391
def validate_relation_data ( self , sentry_unit , relation , expected ) : actual = sentry_unit . relation ( relation [ 0 ] , relation [ 1 ] ) return self . _validate_dict_data ( expected , actual )
Validate actual relation data based on expected relation data .
56,392
def _validate_list_data ( self , expected , actual ) : for e in expected : if e not in actual : return "expected item {} not found in actual list" . format ( e ) return None
Compare expected list vs actual list data .
56,393
def service_restarted ( self , sentry_unit , service , filename , pgrep_full = None , sleep_time = 20 ) : self . log . warn ( 'DEPRECATION WARNING: use ' 'validate_service_config_changed instead of ' 'service_restarted due to known races.' ) time . sleep ( sleep_time ) if ( self . _get_proc_start_time ( sentry_unit , service , pgrep_full ) >= self . _get_file_mtime ( sentry_unit , filename ) ) : return True else : return False
Check if service was restarted .
56,394
def service_restarted_since ( self , sentry_unit , mtime , service , pgrep_full = None , sleep_time = 20 , retry_count = 30 , retry_sleep_time = 10 ) : unit_name = sentry_unit . info [ 'unit_name' ] self . log . debug ( 'Checking that %s service restarted since %s on ' '%s' % ( service , mtime , unit_name ) ) time . sleep ( sleep_time ) proc_start_time = None tries = 0 while tries <= retry_count and not proc_start_time : try : proc_start_time = self . _get_proc_start_time ( sentry_unit , service , pgrep_full ) self . log . debug ( 'Attempt {} to get {} proc start time on {} ' 'OK' . format ( tries , service , unit_name ) ) except IOError as e : self . log . debug ( 'Attempt {} to get {} proc start time on {} ' 'failed\n{}' . format ( tries , service , unit_name , e ) ) time . sleep ( retry_sleep_time ) tries += 1 if not proc_start_time : self . log . warn ( 'No proc start time found, assuming service did ' 'not start' ) return False if proc_start_time >= mtime : self . log . debug ( 'Proc start time is newer than provided mtime' '(%s >= %s) on %s (OK)' % ( proc_start_time , mtime , unit_name ) ) return True else : self . log . warn ( 'Proc start time (%s) is older than provided mtime ' '(%s) on %s, service did not ' 'restart' % ( proc_start_time , mtime , unit_name ) ) return False
Check if service was been started after a given time .
56,395
def config_updated_since ( self , sentry_unit , filename , mtime , sleep_time = 20 , retry_count = 30 , retry_sleep_time = 10 ) : unit_name = sentry_unit . info [ 'unit_name' ] self . log . debug ( 'Checking that %s updated since %s on ' '%s' % ( filename , mtime , unit_name ) ) time . sleep ( sleep_time ) file_mtime = None tries = 0 while tries <= retry_count and not file_mtime : try : file_mtime = self . _get_file_mtime ( sentry_unit , filename ) self . log . debug ( 'Attempt {} to get {} file mtime on {} ' 'OK' . format ( tries , filename , unit_name ) ) except IOError as e : self . log . debug ( 'Attempt {} to get {} file mtime on {} ' 'failed\n{}' . format ( tries , filename , unit_name , e ) ) time . sleep ( retry_sleep_time ) tries += 1 if not file_mtime : self . log . warn ( 'Could not determine file mtime, assuming ' 'file does not exist' ) return False if file_mtime >= mtime : self . log . debug ( 'File mtime is newer than provided mtime ' '(%s >= %s) on %s (OK)' % ( file_mtime , mtime , unit_name ) ) return True else : self . log . warn ( 'File mtime is older than provided mtime' '(%s < on %s) on %s' % ( file_mtime , mtime , unit_name ) ) return False
Check if file was modified after a given time .
56,396
def validate_service_config_changed ( self , sentry_unit , mtime , service , filename , pgrep_full = None , sleep_time = 20 , retry_count = 30 , retry_sleep_time = 10 ) : service_restart = self . service_restarted_since ( sentry_unit , mtime , service , pgrep_full = pgrep_full , sleep_time = sleep_time , retry_count = retry_count , retry_sleep_time = retry_sleep_time ) config_update = self . config_updated_since ( sentry_unit , filename , mtime , sleep_time = sleep_time , retry_count = retry_count , retry_sleep_time = retry_sleep_time ) return service_restart and config_update
Check service and file were updated after mtime
56,397
def file_to_url ( self , file_rel_path ) : _abs_path = os . path . abspath ( file_rel_path ) return urlparse . urlparse ( _abs_path , scheme = 'file' ) . geturl ( )
Convert a relative file path to a file URL .
56,398
def check_commands_on_units ( self , commands , sentry_units ) : self . log . debug ( 'Checking exit codes for {} commands on {} ' 'sentry units...' . format ( len ( commands ) , len ( sentry_units ) ) ) for sentry_unit in sentry_units : for cmd in commands : output , code = sentry_unit . run ( cmd ) if code == 0 : self . log . debug ( '{} `{}` returned {} ' '(OK)' . format ( sentry_unit . info [ 'unit_name' ] , cmd , code ) ) else : return ( '{} `{}` returned {} ' '{}' . format ( sentry_unit . info [ 'unit_name' ] , cmd , code , output ) ) return None
Check that all commands in a list exit zero on all sentry units in a list .
56,399
def get_unit_process_ids ( self , unit_processes , expect_success = True , pgrep_full = False ) : pid_dict = { } for sentry_unit , process_list in six . iteritems ( unit_processes ) : pid_dict [ sentry_unit ] = { } for process in process_list : pids = self . get_process_id_list ( sentry_unit , process , expect_success = expect_success , pgrep_full = pgrep_full ) pid_dict [ sentry_unit ] . update ( { process : pids } ) return pid_dict
Construct a dict containing unit sentries process names and process IDs .