idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
23,000 | def getdata ( self , blc = ( ) , trc = ( ) , inc = ( ) ) : return self . _getdata ( self . _adjustBlc ( blc ) , self . _adjustTrc ( trc ) , self . _adjustInc ( inc ) ) | Get image data . |
23,001 | def getmask ( self , blc = ( ) , trc = ( ) , inc = ( ) ) : return numpy . logical_not ( self . _getmask ( self . _adjustBlc ( blc ) , self . _adjustTrc ( trc ) , self . _adjustInc ( inc ) ) ) | Get image mask . |
23,002 | def get ( self , blc = ( ) , trc = ( ) , inc = ( ) ) : return nma . masked_array ( self . getdata ( blc , trc , inc ) , self . getmask ( blc , trc , inc ) ) | Get image data and mask . |
23,003 | def putdata ( self , value , blc = ( ) , trc = ( ) , inc = ( ) ) : return self . _putdata ( value , self . _adjustBlc ( blc ) , self . _adjustInc ( inc ) ) | Put image data . |
23,004 | def putmask ( self , value , blc = ( ) , trc = ( ) , inc = ( ) ) : return self . _putmask ( ~ value , self . _adjustBlc ( blc ) , self . _adjustInc ( inc ) ) | Put image mask . |
23,005 | def put ( self , value , blc = ( ) , trc = ( ) , inc = ( ) ) : if isinstance ( value , nma . MaskedArray ) : self . putdata ( value . data , blc , trc , inc ) self . putmask ( nma . getmaskarray ( value ) , blc , trc , inc ) else : self . putdata ( value , blc , trc , inc ) | Put image data and mask . |
23,006 | def subimage ( self , blc = ( ) , trc = ( ) , inc = ( ) , dropdegenerate = True ) : return image ( self . _subimage ( self . _adjustBlc ( blc ) , self . _adjustTrc ( trc ) , self . _adjustInc ( inc ) , dropdegenerate ) ) | Form a subimage . |
23,007 | def info ( self ) : return { 'coordinates' : self . _coordinates ( ) , 'imageinfo' : self . _imageinfo ( ) , 'miscinfo' : self . _miscinfo ( ) , 'unit' : self . _unit ( ) } | Get coordinates image info and unit . |
23,008 | def tofits ( self , filename , overwrite = True , velocity = True , optical = True , bitpix = - 32 , minpix = 1 , maxpix = - 1 ) : return self . _tofits ( filename , overwrite , velocity , optical , bitpix , minpix , maxpix ) | Write the image to a file in FITS format . |
23,009 | def saveas ( self , filename , overwrite = True , hdf5 = False , copymask = True , newmaskname = "" , newtileshape = ( ) ) : self . _saveas ( filename , overwrite , hdf5 , copymask , newmaskname , newtileshape ) | Write the image to disk . |
23,010 | def statistics ( self , axes = ( ) , minmaxvalues = ( ) , exclude = False , robust = True ) : return self . _statistics ( self . _adaptAxes ( axes ) , "" , minmaxvalues , exclude , robust ) | Calculate statistics for the image . |
23,011 | def regrid ( self , axes , coordsys , outname = "" , overwrite = True , outshape = ( ) , interpolation = "linear" , decimate = 10 , replicate = False , refchange = True , forceregrid = False ) : return image ( self . _regrid ( self . _adaptAxes ( axes ) , outname , overwrite , outshape , coordsys . dict ( ) , interpolation , decimate , replicate , refchange , forceregrid ) ) | Regrid the image to a new image object . |
23,012 | def view ( self , tempname = '/tmp/tempimage' ) : import os if os . system ( 'test -x `which casaviewer` > /dev/null 2>&1' ) == 0 : six . print_ ( "Starting casaviewer in the background ..." ) self . unlock ( ) if self . ispersistent ( ) : os . system ( 'casaviewer ' + self . name ( ) + ' &' ) elif len ( tempname ) > 0 : six . print_ ( " making a persistent copy in " + tempname ) six . print_ ( " which should be deleted after the viewer has ended" ) self . saveas ( tempname ) os . system ( 'casaviewer ' + tempname + ' &' ) else : six . print_ ( "Cannot view because the image is in memory only." ) six . print_ ( "You can browse a persistent copy of the image like:" ) six . print_ ( " t.view('/tmp/tempimage')" ) else : six . print_ ( "casaviewer cannot be found" ) | Display the image using casaviewer . |
23,013 | def find_library_file ( libname ) : parser = argparse . ArgumentParser ( add_help = False ) parser . add_argument ( "--library-dirs" , "-L" , default = '' ) args , unknown = parser . parse_known_args ( ) user_lib_dirs = args . library_dirs . split ( ':' ) lib_dirs = user_lib_dirs + [ os . path . join ( sys . prefix , 'lib' ) , '/usr/local/lib' , '/usr/lib' , '/usr/lib/x86_64-linux-gnu' ] compiler = ccompiler . new_compiler ( ) return compiler . find_library_file ( lib_dirs , libname ) | Try to get the directory of the specified library . It adds to the search path the library paths given to distutil s build_ext . |
23,014 | def find_boost ( ) : short_version = "{}{}" . format ( sys . version_info [ 0 ] , sys . version_info [ 1 ] ) boostlibnames = [ 'boost_python-py' + short_version , 'boost_python' + short_version , 'boost_python' , ] if sys . version_info [ 0 ] == 2 : boostlibnames += [ "boost_python-mt" ] else : boostlibnames += [ "boost_python3-mt" ] for libboostname in boostlibnames : if find_library_file ( libboostname ) : return libboostname warnings . warn ( no_boost_error ) return boostlibnames [ 0 ] | Find the name of the boost - python library . Returns None if none is found . |
23,015 | def put ( self , rownr , value , matchingfields = True ) : self . _put ( rownr , value , matchingfields ) | Put the values into the given row . |
23,016 | def quantity ( * args ) : if len ( args ) == 1 : if isinstance ( args [ 0 ] , str ) : return Quantity ( from_string ( args [ 0 ] ) ) elif isinstance ( args [ 0 ] , dict ) : if hasattr ( args [ 0 ] [ "value" ] , "__len__" ) : return QuantVec ( from_dict_v ( args [ 0 ] ) ) else : return Quantity ( from_dict ( args [ 0 ] ) ) elif isinstance ( args [ 0 ] , Quantity ) or isinstance ( args [ 0 ] , QuantVec ) : return args [ 0 ] else : raise TypeError ( "Invalid argument type for" ) else : if hasattr ( args [ 0 ] , "__len__" ) : return QuantVec ( * args ) else : return Quantity ( * args ) | Create a quantity . This can be from a scalar or vector . |
23,017 | def getvariable ( name ) : import inspect fr = inspect . currentframe ( ) try : while fr : fr = fr . f_back vars = fr . f_locals if name in vars : return vars [ name ] except : pass return None | Get the value of a local variable somewhere in the call stack . |
23,018 | def substitute ( s , objlist = ( ) , globals = { } , locals = { } ) : if not locals : locals = getlocals ( 3 ) backslash = False dollar = False nparen = 0 name = '' evalstr = '' squote = False dquote = False out = '' for tmp in s : if backslash : out += tmp backslash = False continue if dollar and nparen == 0 : if tmp == '_' or ( 'a' <= tmp <= 'z' ) or ( 'A' <= tmp <= 'Z' ) : name += tmp continue if '0' <= tmp <= '9' and name != '' : name += tmp continue if tmp == '(' and name == '' : nparen = 1 evalstr = '' continue out += substitutename ( name , objlist , globals , locals ) dollar = False if tmp == '"' and not squote : dquote = not dquote elif tmp == "'" and not dquote : squote = not squote if not dquote and not squote : if nparen > 0 : if tmp == '(' : nparen += 1 elif tmp == ')' : nparen -= 1 if nparen == 0 : out += substituteexpr ( evalstr , globals , locals ) dollar = False evalstr += tmp continue if tmp == '$' : dollar = True name = '' continue if nparen == 0 : out += tmp else : evalstr += tmp if tmp == '\\' : backslash = True if dollar : out += substitutename ( name , objlist , globals , locals ) else : if nparen > 0 : out += '$(' + evalstr return out | Substitute global python variables in a command string . |
23,019 | def taql ( command , style = 'Python' , tables = [ ] , globals = { } , locals = { } ) : cmd = command tabs = [ ] for tab in tables : tabs += [ tab ] try : import casacore . util if len ( locals ) == 0 : locals = casacore . util . getlocals ( 3 ) cmd = casacore . util . substitute ( cmd , [ ( table , '' , tabs ) ] , globals , locals ) except Exception : pass if style : cmd = 'using style ' + style + ' ' + cmd tab = table ( cmd , tabs , _oper = 2 ) result = tab . _getcalcresult ( ) if len ( result ) == 0 : return tab return result [ 'values' ] | Execute a TaQL command and return a table object . |
23,020 | def iter ( self , columnnames , order = '' , sort = True ) : from . tableiter import tableiter return tableiter ( self , columnnames , order , sort ) | Return a tableiter object . |
23,021 | def index ( self , columnnames , sort = True ) : from . tableindex import tableindex return tableindex ( self , columnnames , sort ) | Return a tableindex object . |
23,022 | def toascii ( self , asciifile , headerfile = '' , columnnames = ( ) , sep = ' ' , precision = ( ) , usebrackets = True ) : msg = self . _toascii ( asciifile , headerfile , columnnames , sep , precision , usebrackets ) if len ( msg ) > 0 : six . print_ ( msg ) | Write the table in ASCII format . |
23,023 | def copy ( self , newtablename , deep = False , valuecopy = False , dminfo = { } , endian = 'aipsrc' , memorytable = False , copynorows = False ) : t = self . _copy ( newtablename , memorytable , deep , valuecopy , endian , dminfo , copynorows ) return table ( t , _oper = 3 ) | Copy the table and return a table object for the copy . |
23,024 | def copyrows ( self , outtable , startrowin = 0 , startrowout = - 1 , nrow = - 1 ) : self . _copyrows ( outtable , startrowin , startrowout , nrow ) | Copy the contents of rows from this table to outtable . |
23,025 | def rownumbers ( self , table = None ) : if table is None : return self . _rownumbers ( Table ( ) ) return self . _rownumbers ( table ) | Return a list containing the row numbers of this table . |
23,026 | def getcolshapestring ( self , columnname , startrow = 0 , nrow = - 1 , rowincr = 1 ) : return self . _getcolshapestring ( columnname , startrow , nrow , rowincr , True ) | Get the shapes of all cells in the column in string format . |
23,027 | def getcellnp ( self , columnname , rownr , nparray ) : if not nparray . flags . c_contiguous or nparray . size == 0 : raise ValueError ( "Argument 'nparray' has to be a contiguous " + "numpy array" ) return self . _getcellvh ( columnname , rownr , nparray ) | Get data from a column cell into the given numpy array . |
23,028 | def getcellslice ( self , columnname , rownr , blc , trc , inc = [ ] ) : return self . _getcellslice ( columnname , rownr , blc , trc , inc ) | Get a slice from a column cell holding an array . |
23,029 | def getcellslicenp ( self , columnname , nparray , rownr , blc , trc , inc = [ ] ) : if not nparray . flags . c_contiguous or nparray . size == 0 : raise ValueError ( "Argument 'nparray' has to be a contiguous " + "numpy array" ) return self . _getcellslicevh ( columnname , rownr , blc , trc , inc , nparray ) | Get a slice from a column cell into the given numpy array . |
23,030 | def getcolnp ( self , columnname , nparray , startrow = 0 , nrow = - 1 , rowincr = 1 ) : if ( not nparray . flags . c_contiguous ) or nparray . size == 0 : raise ValueError ( "Argument 'nparray' has to be a contiguous " + "numpy array" ) return self . _getcolvh ( columnname , startrow , nrow , rowincr , nparray ) | Get the contents of a column or part of it into the given numpy array . |
23,031 | def getcolslice ( self , columnname , blc , trc , inc = [ ] , startrow = 0 , nrow = - 1 , rowincr = 1 ) : return self . _getcolslice ( columnname , blc , trc , inc , startrow , nrow , rowincr ) | Get a slice from a table column holding arrays . |
23,032 | def getcolslicenp ( self , columnname , nparray , blc , trc , inc = [ ] , startrow = 0 , nrow = - 1 , rowincr = 1 ) : if not nparray . flags . c_contiguous or nparray . size == 0 : raise ValueError ( "Argument 'nparray' has to be a contiguous " + "numpy array" ) return self . _getcolslicevh ( columnname , blc , trc , inc , startrow , nrow , rowincr , nparray ) | Get a slice from a table column into the given numpy array . |
23,033 | def putcell ( self , columnname , rownr , value ) : self . _putcell ( columnname , rownr , value ) | Put a value into one or more table cells . |
23,034 | def putcellslice ( self , columnname , rownr , value , blc , trc , inc = [ ] ) : self . _putcellslice ( columnname , rownr , value , blc , trc , inc ) | Put into a slice of a table cell holding an array . |
23,035 | def putcolslice ( self , columnname , value , blc , trc , inc = [ ] , startrow = 0 , nrow = - 1 , rowincr = 1 ) : self . _putcolslice ( columnname , value , blc , trc , inc , startrow , nrow , rowincr ) | Put into a slice in a table column holding arrays . |
23,036 | def addcols ( self , desc , dminfo = { } , addtoparent = True ) : tdesc = desc if 'name' in desc : import casacore . tables . tableutil as pt if len ( desc ) == 2 and 'desc' in desc : tdesc = pt . maketabdesc ( desc ) elif 'valueType' in desc : cd = pt . makecoldesc ( desc [ 'name' ] , desc ) tdesc = pt . maketabdesc ( cd ) self . _addcols ( tdesc , dminfo , addtoparent ) self . _makerow ( ) | Add one or more columns . |
23,037 | def renamecol ( self , oldname , newname ) : self . _renamecol ( oldname , newname ) self . _makerow ( ) | Rename a single table column . |
23,038 | def fieldnames ( self , keyword = '' ) : if isinstance ( keyword , str ) : return self . _getfieldnames ( '' , keyword , - 1 ) else : return self . _getfieldnames ( '' , '' , keyword ) | Get the names of the fields in a table keyword value . |
23,039 | def colfieldnames ( self , columnname , keyword = '' ) : if isinstance ( keyword , str ) : return self . _getfieldnames ( columnname , keyword , - 1 ) else : return self . _getfieldnames ( columnname , '' , keyword ) | Get the names of the fields in a column keyword value . |
23,040 | def getkeyword ( self , keyword ) : if isinstance ( keyword , str ) : return self . _getkeyword ( '' , keyword , - 1 ) else : return self . _getkeyword ( '' , '' , keyword ) | Get the value of a table keyword . |
23,041 | def getcolkeyword ( self , columnname , keyword ) : if isinstance ( keyword , str ) : return self . _getkeyword ( columnname , keyword , - 1 ) else : return self . _getkeyword ( columnname , '' , keyword ) | Get the value of a column keyword . |
23,042 | def getsubtables ( self ) : keyset = self . getkeywords ( ) names = [ ] for key , value in keyset . items ( ) : if isinstance ( value , str ) and value . find ( 'Table: ' ) == 0 : names . append ( _do_remove_prefix ( value ) ) return names | Get the names of all subtables . |
23,043 | def putkeyword ( self , keyword , value , makesubrecord = False ) : val = value if isinstance ( val , table ) : val = _add_prefix ( val . name ( ) ) if isinstance ( keyword , str ) : return self . _putkeyword ( '' , keyword , - 1 , makesubrecord , val ) else : return self . _putkeyword ( '' , '' , keyword , makesubrecord , val ) | Put the value of a table keyword . |
23,044 | def removekeyword ( self , keyword ) : if isinstance ( keyword , str ) : self . _removekeyword ( '' , keyword , - 1 ) else : self . _removekeyword ( '' , '' , keyword ) | Remove a table keyword . |
23,045 | def removecolkeyword ( self , columnname , keyword ) : if isinstance ( keyword , str ) : self . _removekeyword ( columnname , keyword , - 1 ) else : self . _removekeyword ( columnname , '' , keyword ) | Remove a column keyword . |
23,046 | def getdesc ( self , actual = True ) : tabledesc = self . _getdesc ( actual , True ) hcdefs = tabledesc . get ( '_define_hypercolumn_' , { } ) for c , hcdef in hcdefs . iteritems ( ) : if "HCcoordnames" in hcdef and len ( hcdef [ "HCcoordnames" ] ) == 0 : del hcdef [ "HCcoordnames" ] if "HCidnames" in hcdef and len ( hcdef [ "HCidnames" ] ) == 0 : del hcdef [ "HCidnames" ] return tabledesc | Get the table description . |
23,047 | def getcoldesc ( self , columnname , actual = True ) : return self . _getcoldesc ( columnname , actual , True ) | Get the description of a column . |
23,048 | def coldesc ( self , columnname , actual = True ) : import casacore . tables . tableutil as pt return pt . makecoldesc ( columnname , self . getcoldesc ( columnname , actual ) ) | Make the description of a column . |
23,049 | def getdminfo ( self , columnname = None ) : dminfo = self . _getdminfo ( ) if columnname is None : return dminfo for fld in dminfo . values ( ) : if columnname in fld [ "COLUMNS" ] : fldc = fld . copy ( ) del fldc [ 'COLUMNS' ] return fldc raise KeyError ( "Column " + columnname + " does not exist" ) | Get data manager info . |
23,050 | def setdmprop ( self , name , properties , bycolumn = True ) : return self . _setdmprop ( name , properties , bycolumn ) | Set properties of a data manager . |
23,051 | def showstructure ( self , dataman = True , column = True , subtable = False , sort = False ) : return self . _showstructure ( dataman , column , subtable , sort ) | Show table structure in a formatted string . |
23,052 | def summary ( self , recurse = False ) : six . print_ ( 'Table summary:' , self . name ( ) ) six . print_ ( 'Shape:' , self . ncols ( ) , 'columns by' , self . nrows ( ) , 'rows' ) six . print_ ( 'Info:' , self . info ( ) ) tkeys = self . getkeywords ( ) if ( len ( tkeys ) > 0 ) : six . print_ ( 'Table keywords:' , tkeys ) columns = self . colnames ( ) if ( len ( columns ) > 0 ) : six . print_ ( 'Columns:' , columns ) for column in columns : ckeys = self . getcolkeywords ( column ) if ( len ( ckeys ) > 0 ) : six . print_ ( column , 'keywords:' , ckeys ) if ( recurse ) : for key , value in tkeys . items ( ) : tabname = _remove_prefix ( value ) six . print_ ( 'Summarizing subtable:' , tabname ) lt = table ( tabname ) if ( not lt . summary ( recurse ) ) : break return True | Print a summary of the table . |
23,053 | def selectrows ( self , rownrs ) : t = self . _selectrows ( rownrs , name = '' ) return table ( t , _oper = 3 ) | Return a reference table containing the given rows . |
23,054 | def query ( self , query = '' , name = '' , sortlist = '' , columns = '' , limit = 0 , offset = 0 , style = 'Python' ) : if not query and not sortlist and not columns and limit <= 0 and offset <= 0 : raise ValueError ( 'No selection done (arguments query, ' + 'sortlist, columns, limit, and offset are empty)' ) command = 'select ' if columns : command += columns command += ' from $1' if query : command += ' where ' + query if sortlist : command += ' orderby ' + sortlist if limit > 0 : command += ' limit %d' % limit if offset > 0 : command += ' offset %d' % offset if name : command += ' giving ' + name return tablecommand ( command , style , [ self ] ) | Query the table and return the result as a reference table . |
23,055 | def sort ( self , sortlist , name = '' , limit = 0 , offset = 0 , style = 'Python' ) : command = 'select from $1 orderby ' + sortlist if limit > 0 : command += ' limit %d' % limit if offset > 0 : command += ' offset %d' % offset if name : command += ' giving ' + name return tablecommand ( command , style , [ self ] ) | Sort the table and return the result as a reference table . |
23,056 | def select ( self , columns , name = '' , style = 'Python' ) : command = 'select ' + columns + ' from $1' if name : command += ' giving ' + name return tablecommand ( command , style , [ self ] ) | Select columns and return the result as a reference table . |
23,057 | def browse ( self , wait = True , tempname = "/tmp/seltable" ) : import os if os . system ( 'test `which casabrowser`x != x' ) == 0 : waitstr1 = "" waitstr2 = "foreground ..." if not wait : waitstr1 = " &" waitstr2 = "background ..." if self . iswritable ( ) : six . print_ ( "Flushing data and starting casabrowser in the " + waitstr2 ) else : six . print_ ( "Starting casabrowser in the " + waitstr2 ) self . flush ( ) self . unlock ( ) if os . system ( 'test -e ' + self . name ( ) + '/table.dat' ) == 0 : os . system ( 'casabrowser ' + self . name ( ) + waitstr1 ) elif len ( tempname ) > 0 : six . print_ ( " making a persistent copy in table " + tempname ) self . copy ( tempname ) os . system ( 'casabrowser ' + tempname + waitstr1 ) if wait : from casacore . tables import tabledelete six . print_ ( " finished browsing" ) tabledelete ( tempname ) else : six . print_ ( " after browsing use tabledelete('" + tempname + "') to delete the copy" ) else : six . print_ ( "Cannot browse because the table is in memory only" ) six . print_ ( "You can browse a (shallow) persistent copy " + "of the table like: " ) six . print_ ( " t.browse(True, '/tmp/tab1')" ) else : try : import wxPython except ImportError : six . print_ ( 'casabrowser nor wxPython can be found' ) return from wxPython . wx import wxPySimpleApp import sys app = wxPySimpleApp ( ) from wxtablebrowser import CasaTestFrame frame = CasaTestFrame ( None , sys . stdout , self ) frame . Show ( True ) app . MainLoop ( ) | Browse a table using casabrowser or a simple wxwidget based browser . |
23,058 | def view ( self , wait = True , tempname = "/tmp/seltable" ) : import os viewed = False type = self . info ( ) [ "type" ] if type == "Measurement Set" or type == "Image" : if os . system ( 'test -x `which casaviewer` > /dev/null 2>&1' ) == 0 : waitstr1 = "" waitstr2 = "foreground ..." if not wait : waitstr1 = " &" waitstr2 = "background ..." if self . iswritable ( ) : six . print_ ( "Flushing data and starting casaviewer " + "in the " + waitstr2 ) else : six . print_ ( "Starting casaviewer in the " + waitstr2 ) self . flush ( ) self . unlock ( ) if os . system ( 'test -e ' + self . name ( ) + '/table.dat' ) == 0 : os . system ( 'casaviewer ' + self . name ( ) + waitstr1 ) viewed = True elif len ( tempname ) > 0 : six . print_ ( " making a persistent copy in table " + tempname ) self . copy ( tempname ) os . system ( 'casaviewer ' + tempname + waitstr1 ) viewed = True if wait : from casacore . tables import tabledelete six . print_ ( " finished viewing" ) tabledelete ( tempname ) else : six . print_ ( " after viewing use tabledelete('" + tempname + "') to delete the copy" ) else : six . print_ ( "Cannot browse because the table is " + "in memory only." ) six . print_ ( "You can browse a (shallow) persistent " + "copy of the table like:" ) six . print_ ( " t.view(True, '/tmp/tab1')" ) if not viewed : self . browse ( wait , tempname ) | View a table using casaviewer casabrowser or wxwidget based browser . |
23,059 | def _repr_html_ ( self ) : out = "<table class='taqltable' style='overflow-x:auto'>\n" if not ( all ( [ colname [ : 4 ] == "Col_" for colname in self . colnames ( ) ] ) ) : out += "<tr>" for colname in self . colnames ( ) : out += "<th><b>" + colname + "</b></th>" out += "</tr>" cropped = False rowcount = 0 for row in self : rowout = _format_row ( row , self . colnames ( ) , self ) rowcount += 1 out += rowout if "\n" in rowout : out += "\n" out += "\n" if rowcount >= 20 : cropped = True break if out [ - 2 : ] == "\n\n" : out = out [ : - 1 ] out += "</table>" if cropped : out += ( "<p style='text-align:center'>(" + str ( self . nrows ( ) - 20 ) + " more rows)</p>\n" ) return out | Give a nice representation of tables in notebooks . |
23,060 | def nth ( lst , n ) : expect_type ( n , ( String , Number ) , unit = None ) if isinstance ( n , String ) : if n . value . lower ( ) == 'first' : i = 0 elif n . value . lower ( ) == 'last' : i = - 1 else : raise ValueError ( "Invalid index %r" % ( n , ) ) else : i = n . to_python_index ( len ( lst ) , circular = True ) return lst [ i ] | Return the nth item in the list . |
23,061 | def handle_import ( self , name , compilation , rule ) : path = PurePosixPath ( name ) search_exts = list ( compilation . compiler . dynamic_extensions ) if path . suffix and path . suffix in search_exts : basename = path . stem else : basename = path . name relative_to = path . parent search_path = [ ] if relative_to . is_absolute ( ) : relative_to = PurePosixPath ( * relative_to . parts [ 1 : ] ) elif rule . source_file . origin : search_path . append ( ( rule . source_file . origin , rule . source_file . relpath . parent / relative_to , ) ) search_path . extend ( ( origin , relative_to ) for origin in compilation . compiler . search_path ) for prefix , suffix in product ( ( '_' , '' ) , search_exts ) : filename = prefix + basename + suffix for origin , relative_to in search_path : relpath = relative_to / filename relpath = PurePosixPath ( os . path . normpath ( str ( relpath ) ) ) if rule . source_file . key == ( origin , relpath ) : continue path = origin / relpath if not path . exists ( ) : continue return SourceFile . read ( origin , relpath ) | Implementation of the core Sass import mechanism which just looks for files on disk . |
23,062 | def print_error ( input , err , scanner ) : p = err . pos line = input [ : p ] . count ( '\n' ) print err . msg + " on line " + repr ( line + 1 ) + ":" text = input [ max ( p - 80 , 0 ) : p + 80 ] p = p - max ( p - 80 , 0 ) i = text [ : p ] . rfind ( '\n' ) j = text [ : p ] . rfind ( '\r' ) if i < 0 or ( 0 <= j < i ) : i = j if 0 <= i < p : p = p - i - 1 text = text [ i + 1 : ] i = text . find ( '\n' , p ) j = text . find ( '\r' , p ) if i < 0 or ( 0 <= j < i ) : i = j if i >= 0 : text = text [ : i ] while len ( text ) > 70 and p > 60 : text = "..." + text [ 10 : ] p = p - 7 print '> ' , text print '> ' , ' ' * p + '^' print 'List of nearby tokens:' , scanner | This is a really dumb long function to print error messages nicely . |
23,063 | def equal_set ( self , a , b ) : "See if a and b have the same elements" if len ( a ) != len ( b ) : return 0 if a == b : return 1 return self . subset ( a , b ) and self . subset ( b , a ) | See if a and b have the same elements |
23,064 | def add_to ( self , parent , additions ) : "Modify parent to include all elements in additions" for x in additions : if x not in parent : parent . append ( x ) self . changed ( ) | Modify parent to include all elements in additions |
23,065 | def declare_alias ( self , name ) : def decorator ( f ) : self . _auto_register_function ( f , name ) return f return decorator | Insert a Python function into this Namespace with an explicitly - given name but detect its argument count automatically . |
23,066 | def collect ( self ) : for func in self . _caches : cache = { } for key in self . _caches [ func ] : if ( time . time ( ) - self . _caches [ func ] [ key ] [ 1 ] ) < self . _timeouts [ func ] : cache [ key ] = self . _caches [ func ] [ key ] self . _caches [ func ] = cache | Clear cache of results which have timed out |
23,067 | def extend_unique ( seq , more ) : seen = set ( seq ) new = [ ] for item in more : if item not in seen : seen . add ( item ) new . append ( item ) return seq + type ( seq ) ( new ) | Return a new sequence containing the items in seq plus any items in more that aren t already in seq preserving the order of both . |
23,068 | def with_more_selectors ( self , selectors ) : if self . headers and self . headers [ - 1 ] . is_selector : new_selectors = extend_unique ( self . headers [ - 1 ] . selectors , selectors ) new_headers = self . headers [ : - 1 ] + ( BlockSelectorHeader ( new_selectors ) , ) return RuleAncestry ( new_headers ) else : new_headers = self . headers + ( BlockSelectorHeader ( selectors ) , ) return RuleAncestry ( new_headers ) | Return a new ancestry that also matches the given selectors . No nesting is done . |
23,069 | def parse_interpolations ( self , string ) : if '#' not in string : return Literal ( String . unquoted ( string ) ) return self . parse_expression ( string , 'goal_interpolated_literal' ) | Parse a string for interpolations but don t treat anything else as Sass syntax . Returns an AST node . |
23,070 | def parse_vars_and_interpolations ( self , string ) : if '#' not in string and '$' not in string : return Literal ( String . unquoted ( string ) ) return self . parse_expression ( string , 'goal_interpolated_literal_with_vars' ) | Parse a string for variables and interpolations but don t treat anything else as Sass syntax . Returns an AST node . |
23,071 | def reject ( lst , * values ) : lst = List . from_maybe ( lst ) values = frozenset ( List . from_maybe_starargs ( values ) ) ret = [ ] for item in lst : if item not in values : ret . append ( item ) return List ( ret , use_comma = lst . use_comma ) | Removes the given values from the list |
23,072 | def add_error_marker ( text , position , start_line = 1 ) : indent = " " lines = [ ] caret_line = start_line for line in text . split ( "\n" ) : lines . append ( indent + line ) if 0 <= position <= len ( line ) : lines . append ( indent + ( " " * position ) + "^" ) caret_line = start_line position -= len ( line ) position -= 1 start_line += 1 return "\n" . join ( lines ) , caret_line | Add a caret marking a given position in a string of input . |
23,073 | def format_sass_stack ( self ) : if not self . rule_stack : return "" ret = [ "on " , self . format_file_and_line ( self . rule_stack [ 0 ] ) , "\n" ] last_file = self . rule_stack [ 0 ] . source_file for rule in self . rule_stack [ 1 : ] : if rule . source_file is not last_file : ret . extend ( ( "imported from " , self . format_file_and_line ( rule ) , "\n" ) ) last_file = rule . source_file return "" . join ( ret ) | Return a traceback of Sass imports . |
23,074 | def format_python_stack ( self ) : ret = [ "Traceback:\n" ] ret . extend ( traceback . format_tb ( self . original_traceback ) ) return "" . join ( ret ) | Return a traceback of Python frames from where the error occurred to where it was first caught and wrapped . |
23,075 | def to_css ( self ) : prefix = self . format_prefix ( ) original_error = self . format_original_error ( ) sass_stack = self . format_sass_stack ( ) message = prefix + "\n" + sass_stack + original_error message = message . replace ( '\\' , '\\\\' ) message = message . replace ( '"' , '\\"' ) message = message . replace ( '\n' , '\\00000A' ) return BROWSER_ERROR_TEMPLATE . format ( '"' + message + '"' ) | Return a stylesheet that will show the wrapped error at the top of the browser window . |
23,076 | def compile_string ( string , compiler_class = Compiler , ** kwargs ) : compiler = compiler_class ( ** kwargs ) return compiler . compile_string ( string ) | Compile a single string and return a string of CSS . |
23,077 | def parse_selectors ( self , raw_selectors ) : raw_selectors = _spaces_re . sub ( ' ' , raw_selectors ) parts = _xcss_extends_re . split ( raw_selectors , 1 ) if len ( parts ) > 1 : unparsed_selectors , unsplit_parents = parts unparsed_parents = unsplit_parents . split ( '&' ) else : unparsed_selectors , = parts unparsed_parents = ( ) selectors = Selector . parse_many ( unparsed_selectors ) parents = [ Selector . parse_one ( parent ) for parent in unparsed_parents ] return selectors , parents | Parses out the old xCSS foo extends bar syntax . |
23,078 | def _get_properties ( self , rule , scope , block ) : prop , raw_value = ( _prop_split_re . split ( block . prop , 1 ) + [ None ] ) [ : 2 ] if raw_value is not None : raw_value = raw_value . strip ( ) try : is_var = ( block . prop [ len ( prop ) ] == '=' ) except IndexError : is_var = False if is_var : warn_deprecated ( rule , "Assignment with = is deprecated; use : instead." ) calculator = self . _make_calculator ( rule . namespace ) prop = prop . strip ( ) prop = calculator . do_glob_math ( prop ) if not prop : return _prop = ( scope or '' ) + prop if is_var or prop . startswith ( '$' ) and raw_value is not None : is_default = False is_global = True while True : splits = raw_value . rsplit ( None , 1 ) if len ( splits ) < 2 or not splits [ 1 ] . startswith ( '!' ) : break raw_value , flag = splits if flag == '!default' : is_default = True elif flag == '!global' : is_global = True else : raise ValueError ( "Unrecognized flag: {0}" . format ( flag ) ) _prop = normalize_var ( _prop ) try : existing_value = rule . namespace . variable ( _prop ) except KeyError : existing_value = None is_defined = existing_value is not None and not existing_value . is_null if is_default and is_defined : pass else : if is_defined and prop . startswith ( '$' ) and prop [ 1 ] . isupper ( ) : log . warn ( "Constant %r redefined" , prop ) value = calculator . calculate ( raw_value , divide = True ) rule . namespace . set_variable ( _prop , value , local_only = not is_global ) else : _prop = calculator . apply_vars ( _prop ) if raw_value is None : value = None else : value = calculator . calculate ( raw_value ) if value is None : pass elif isinstance ( value , six . string_types ) : pass else : if value . is_null : return style = rule . legacy_compiler_options . get ( 'style' , self . compiler . output_style ) compress = style == 'compressed' value = value . render ( compress = compress ) rule . properties . append ( ( _prop , value ) ) | Implements properties and variables extraction and assignment |
23,079 | def _constrain ( value , lb = 0 , ub = 1 ) : if value < lb : return lb elif value > ub : return ub else : return value | Helper for Color constructors . Constrains a value to a range . |
23,080 | def _add_sub ( self , other , op ) : if not isinstance ( other , Number ) : return NotImplemented if self . is_unitless or other . is_unitless : return Number ( op ( self . value , other . value ) , unit_numer = self . unit_numer or other . unit_numer , unit_denom = self . unit_denom or other . unit_denom , ) if self . value == 0 : return Number ( op ( self . value , other . value ) , unit_numer = other . unit_numer , unit_denom = other . unit_denom , ) elif other . value == 0 : return Number ( op ( self . value , other . value ) , unit_numer = self . unit_numer , unit_denom = self . unit_denom , ) left = self . to_base_units ( ) right = other . to_base_units ( ) if left . unit_numer != right . unit_numer or left . unit_denom != right . unit_denom : raise ValueError ( "Can't reconcile units: %r and %r" % ( self , other ) ) new_amount = op ( left . value , right . value ) if left . value != 0 : new_amount = new_amount * self . value / left . value return Number ( new_amount , unit_numer = self . unit_numer , unit_denom = self . unit_denom ) | Implements both addition and subtraction . |
23,081 | def to_base_units ( self ) : amount = self . value numer_factor , numer_units = convert_units_to_base_units ( self . unit_numer ) denom_factor , denom_units = convert_units_to_base_units ( self . unit_denom ) return Number ( amount * numer_factor / denom_factor , unit_numer = numer_units , unit_denom = denom_units , ) | Convert to a fixed set of base units . The particular units are arbitrary ; what s important is that they re consistent . |
23,082 | def wrap_python_function ( cls , fn ) : def wrapped ( sass_arg ) : python_arg = sass_arg . value python_ret = fn ( python_arg ) sass_ret = cls ( python_ret , unit_numer = sass_arg . unit_numer , unit_denom = sass_arg . unit_denom ) return sass_ret return wrapped | Wraps an unary Python math function translating the argument from Sass to Python on the way in and vice versa for the return value . |
23,083 | def to_python_index ( self , length , check_bounds = True , circular = False ) : if not self . is_unitless : raise ValueError ( "Index cannot have units: {0!r}" . format ( self ) ) ret = int ( self . value ) if ret != self . value : raise ValueError ( "Index must be an integer: {0!r}" . format ( ret ) ) if ret == 0 : raise ValueError ( "Index cannot be zero" ) if check_bounds and not circular and abs ( ret ) > length : raise ValueError ( "Index {0!r} out of bounds for length {1}" . format ( ret , length ) ) if ret > 0 : ret -= 1 if circular : ret = ret % length return ret | Return a plain Python integer appropriate for indexing a sequence of the given length . Raise if this is impossible for any reason whatsoever . |
23,084 | def maybe_new ( cls , values , use_comma = True ) : if len ( values ) == 1 : return values [ 0 ] else : return cls ( values , use_comma = use_comma ) | If values contains only one item return that item . Otherwise return a List as normal . |
23,085 | def from_maybe_starargs ( cls , args , use_comma = True ) : if len ( args ) == 1 : if isinstance ( args [ 0 ] , cls ) : return args [ 0 ] elif isinstance ( args [ 0 ] , ( list , tuple ) ) : return cls ( args [ 0 ] , use_comma = use_comma ) return cls ( args , use_comma = use_comma ) | If args has one element which appears to be a list return it . Otherwise return a list as normal . |
23,086 | def from_name ( cls , name ) : self = cls . __new__ ( cls ) self . original_literal = name r , g , b , a = COLOR_NAMES [ name ] self . value = r , g , b , a return self | Build a Color from a CSS color name . |
23,087 | def unquoted ( cls , value , literal = False ) : return cls ( value , quotes = None , literal = literal ) | Helper to create a string with no quotes . |
23,088 | def _is_combinator_subset_of ( specific , general , is_first = True ) : if is_first and general == ' ' : return True if specific == general : return True if specific == '>' and general == ' ' : return True if specific == '+' and general == '~' : return True return False | Return whether specific matches a non - strict subset of what general matches . |
23,089 | def _weave_conflicting_selectors ( prefixes , a , b , suffix = ( ) ) : both = a and b for prefix in prefixes : yield prefix + a + b + suffix if both : yield prefix + b + a + suffix | Part of the selector merge algorithm above . Not useful on its own . Pay no attention to the man behind the curtain . |
23,090 | def _merge_simple_selectors ( a , b ) : if a . is_superset_of ( b ) : return b elif b . is_superset_of ( a ) : return a else : return None | Merge two simple selectors for the purposes of the LCS algorithm below . |
23,091 | def longest_common_subsequence ( a , b , mergefunc = None ) : if mergefunc is None : def mergefunc ( a , b ) : if a == b : return a return None eq = { } for ai , aval in enumerate ( a ) : for bi , bval in enumerate ( b ) : eq [ ai , bi ] = mergefunc ( aval , bval ) prefix_lcs_length = { } for ai in range ( - 1 , len ( a ) ) : for bi in range ( - 1 , len ( b ) ) : if ai == - 1 or bi == - 1 : l = 0 elif eq [ ai , bi ] : l = prefix_lcs_length [ ai - 1 , bi - 1 ] + 1 else : l = max ( prefix_lcs_length [ ai , bi - 1 ] , prefix_lcs_length [ ai - 1 , bi ] ) prefix_lcs_length [ ai , bi ] = l ai = len ( a ) - 1 bi = len ( b ) - 1 ret = [ ] while ai >= 0 and bi >= 0 : merged = eq [ ai , bi ] if merged is not None : ret . append ( ( ai , bi , merged ) ) ai -= 1 bi -= 1 elif prefix_lcs_length [ ai , bi - 1 ] > prefix_lcs_length [ ai - 1 , bi ] : bi -= 1 else : ai -= 1 ret . reverse ( ) return ret | Find the longest common subsequence between two iterables . |
23,092 | def is_superset_of ( self , other , soft_combinator = False ) : if soft_combinator and self . combinator == ' ' : combinator_superset = True else : combinator_superset = ( self . combinator == other . combinator or ( self . combinator == ' ' and other . combinator == '>' ) or ( self . combinator == '~' and other . combinator == '+' ) ) return ( combinator_superset and set ( self . tokens ) <= set ( other . tokens ) ) | Return True iff this selector matches the same elements as other and perhaps others . |
23,093 | def substitute ( self , target , replacement ) : p_before , p_extras , p_after = self . break_around ( target . simple_selectors ) r_trail = replacement . simple_selectors [ : - 1 ] r_extras = replacement . simple_selectors [ - 1 ] focal_nodes = ( p_extras . merge_into ( r_extras ) , ) befores = _merge_selectors ( p_before , r_trail ) cls = type ( self ) return [ cls ( before + focal_nodes + p_after ) for before in befores ] | Return a list of selectors obtained by replacing the target selector with replacement . |
23,094 | def convert_units_to_base_units ( units ) : total_factor = 1 new_units = [ ] for unit in units : if unit not in BASE_UNIT_CONVERSIONS : continue factor , new_unit = BASE_UNIT_CONVERSIONS [ unit ] total_factor *= factor new_units . append ( new_unit ) new_units . sort ( ) return total_factor , tuple ( new_units ) | Convert a set of units into a set of base units . |
23,095 | def count_base_units ( units ) : ret = { } for unit in units : factor , base_unit = get_conversion_factor ( unit ) ret . setdefault ( base_unit , 0 ) ret [ base_unit ] += 1 return ret | Returns a dict mapping names of base units to how many times they appear in the given iterable of units . Effectively this counts how many length units you have how many time units and so forth . |
23,096 | def cancel_base_units ( units , to_remove ) : to_remove = to_remove . copy ( ) remaining_units = [ ] total_factor = Fraction ( 1 ) for unit in units : factor , base_unit = get_conversion_factor ( unit ) if not to_remove . get ( base_unit , 0 ) : remaining_units . append ( unit ) continue total_factor *= factor to_remove [ base_unit ] -= 1 return total_factor , remaining_units | Given a list of units remove a specified number of each base unit . |
23,097 | def is_builtin_css_function ( name ) : name = name . replace ( '_' , '-' ) if name in BUILTIN_FUNCTIONS : return True if name [ 0 ] == '-' and '-' in name [ 1 : ] : return True return False | Returns whether the given name looks like the name of a builtin CSS function . |
23,098 | def determine_encoding ( buf ) : bom_encoding = 'UTF-8' if not buf : return bom_encoding if isinstance ( buf , six . text_type ) : if buf [ 0 ] == '\ufeff' : buf = buf [ 0 : ] charset_start = '@charset "' charset_end = '";' if buf . startswith ( charset_start ) : start = len ( charset_start ) end = buf . index ( charset_end , start ) return buf [ start : end ] else : return bom_encoding if buf [ : 3 ] == b'\xef\xbb\xbf' : bom_encoding = 'UTF-8' buf = buf [ 3 : ] if buf [ : 4 ] == b'\x00\x00\xfe\xff' : bom_encoding = 'UTF-32BE' buf = buf [ 4 : ] elif buf [ : 4 ] == b'\xff\xfe\x00\x00' : bom_encoding = 'UTF-32LE' buf = buf [ 4 : ] if buf [ : 4 ] == b'\x00\x00\xff\xfe' : raise UnicodeError ( "UTF-32-2143 is not supported" ) elif buf [ : 4 ] == b'\xfe\xff\x00\x00' : raise UnicodeError ( "UTF-32-2143 is not supported" ) elif buf [ : 2 ] == b'\xfe\xff' : bom_encoding = 'UTF-16BE' buf = buf [ 2 : ] elif buf [ : 2 ] == b'\xff\xfe' : bom_encoding = 'UTF-16LE' buf = buf [ 2 : ] charset_start = '@charset "' . encode ( bom_encoding ) charset_end = '";' . encode ( bom_encoding ) if buf . startswith ( charset_start ) : start = len ( charset_start ) end = buf . index ( charset_end , start ) encoded_encoding = buf [ start : end ] encoding = encoded_encoding . decode ( bom_encoding ) encoded_charset = buf [ : end + len ( charset_end ) ] if ( encoded_charset . decode ( encoding ) != encoded_charset . decode ( bom_encoding ) ) : raise UnicodeError ( "@charset {0} is incompatible with detected encoding {1}" . format ( bom_encoding , encoding ) ) else : encoding = bom_encoding return encoding | Return the appropriate encoding for the given CSS source according to the CSS charset rules . |
23,099 | def maybe ( cls , parts , quotes = None , type = String , ** kwargs ) : if len ( parts ) > 1 : return cls ( parts , quotes = quotes , type = type , ** kwargs ) if quotes is None and type is String : return Literal . from_bareword ( parts [ 0 ] ) return Literal ( type ( parts [ 0 ] , quotes = quotes , ** kwargs ) ) | Returns an interpolation if there are multiple parts otherwise a plain Literal . This keeps the AST somewhat simpler but also is the only way Literal . from_bareword gets called . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.