idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
22,900
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 .
66
6
22,901
def statistics ( self , axes = ( ) , minmaxvalues = ( ) , exclude = False , robust = True ) : return self . _statistics ( self . _adaptAxes ( axes ) , "" , minmaxvalues , exclude , robust )
Calculate statistics for the image .
53
8
22,902
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 .
106
10
22,903
def view ( self , tempname = '/tmp/tempimage' ) : import os # Test if casaviewer can be found. # On OS-X 'which' always returns 0, so use test on top of it. 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 .
272
9
22,904
def find_library_file ( libname ) : # Use a dummy argument parser to get user specified library dirs 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 ( ':' ) # Append default search path (not a complete list) 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 .
190
28
22,905
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 .
152
17
22,906
def put ( self , rownr , value , matchingfields = True ) : self . _put ( rownr , value , matchingfields )
Put the values into the given row .
31
8
22,907
def quantity ( * args ) : if len ( args ) == 1 : if isinstance ( args [ 0 ] , str ) : # use copy constructor to create quantity from string 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 .
193
14
22,908
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 .
55
13
22,909
def substitute ( s , objlist = ( ) , globals = { } , locals = { } ) : # Get the local variables at the caller level if not given. if not locals : locals = getlocals ( 3 ) # Initialize some variables. backslash = False dollar = False nparen = 0 name = '' evalstr = '' squote = False dquote = False out = '' # Loop through the entire string. for tmp in s : if backslash : out += tmp backslash = False continue # If a dollar is found, we might have a name or expression. # Alphabetics and underscore are always part of name. if dollar and nparen == 0 : if tmp == '_' or ( 'a' <= tmp <= 'z' ) or ( 'A' <= tmp <= 'Z' ) : name += tmp continue # Numerics are only part if not first character. if '0' <= tmp <= '9' and name != '' : name += tmp continue # $( indicates the start of an expression to evaluate. if tmp == '(' and name == '' : nparen = 1 evalstr = '' continue # End of name found. Try to substitute. out += substitutename ( name , objlist , globals , locals ) dollar = False # Handle possible single or double quotes. if tmp == '"' and not squote : dquote = not dquote elif tmp == "'" and not dquote : squote = not squote if not dquote and not squote : # Count the number of balanced parentheses # (outside quoted strings) in the subexpression. if nparen > 0 : if tmp == '(' : nparen += 1 elif tmp == ')' : nparen -= 1 if nparen == 0 : # The last closing parenthese is found. # Evaluate the subexpression. # Add the result to the output. out += substituteexpr ( evalstr , globals , locals ) dollar = False evalstr += tmp continue # Set a switch if we have a dollar (outside quoted # and eval strings). if tmp == '$' : dollar = True name = '' continue # No special character; add it to output or evalstr. # Set a switch if we have a backslash. if nparen == 0 : out += tmp else : evalstr += tmp if tmp == '\\' : backslash = True # The entire string has been handled. # Substitute a possible last name. # Insert a possible incomplete eval string as such. if dollar : out += substitutename ( name , objlist , globals , locals ) else : if nparen > 0 : out += '$(' + evalstr return out
Substitute global python variables in a command string .
562
11
22,910
def taql ( command , style = 'Python' , tables = [ ] , globals = { } , locals = { } ) : # Substitute possible tables given as $name. cmd = command # Copy the tables argument and make sure it is a list tabs = [ ] for tab in tables : tabs += [ tab ] try : import casacore . util if len ( locals ) == 0 : # local variables in caller are 3 levels up from getlocals 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 result is empty, it was a normal TaQL command resulting in a table. # Otherwise it is a record containing calc values. if len ( result ) == 0 : return tab return result [ 'values' ]
Execute a TaQL command and return a table object .
227
12
22,911
def iter ( self , columnnames , order = '' , sort = True ) : from . tableiter import tableiter return tableiter ( self , columnnames , order , sort )
Return a tableiter object .
37
6
22,912
def index ( self , columnnames , sort = True ) : from . tableindex import tableindex return tableindex ( self , columnnames , sort )
Return a tableindex object .
31
6
22,913
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 .
85
7
22,914
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 ) # copy returns a Table object, so turn that into table. return table ( t , _oper = 3 )
Copy the table and return a table object for the copy .
103
12
22,915
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 .
49
12
22,916
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 .
37
11
22,917
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 .
55
13
22,918
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 .
85
13
22,919
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 .
49
11
22,920
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 .
107
14
22,921
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 .
106
17
22,922
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 .
68
10
22,923
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 .
127
14
22,924
def putcell ( self , columnname , rownr , value ) : self . _putcell ( columnname , rownr , value )
Put a value into one or more table cells .
31
10
22,925
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 .
52
12
22,926
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 .
71
11
22,927
def addcols ( self , desc , dminfo = { } , addtoparent = True ) : tdesc = desc # Create a tabdesc if only a coldesc is given. if 'name' in desc : import casacore . tables . tableutil as pt if len ( desc ) == 2 and 'desc' in desc : # Given as output from makecoldesc tdesc = pt . maketabdesc ( desc ) elif 'valueType' in desc : # Given as output of getcoldesc (with a name field added) cd = pt . makecoldesc ( desc [ 'name' ] , desc ) tdesc = pt . maketabdesc ( cd ) self . _addcols ( tdesc , dminfo , addtoparent ) self . _makerow ( )
Add one or more columns .
172
6
22,928
def renamecol ( self , oldname , newname ) : self . _renamecol ( oldname , newname ) self . _makerow ( )
Rename a single table column .
33
7
22,929
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 .
51
12
22,930
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 .
57
12
22,931
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 .
50
8
22,932
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 .
56
8
22,933
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 .
72
8
22,934
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 .
95
8
22,935
def removekeyword ( self , keyword ) : if isinstance ( keyword , str ) : self . _removekeyword ( '' , keyword , - 1 ) else : self . _removekeyword ( '' , '' , keyword )
Remove a table keyword .
48
5
22,936
def removecolkeyword ( self , columnname , keyword ) : if isinstance ( keyword , str ) : self . _removekeyword ( columnname , keyword , - 1 ) else : self . _removekeyword ( columnname , '' , keyword )
Remove a column keyword .
54
5
22,937
def getdesc ( self , actual = True ) : tabledesc = self . _getdesc ( actual , True ) # Strip out 0 length "HCcoordnames" and "HCidnames" # as these aren't valid. (See tabledefinehypercolumn) 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 .
177
5
22,938
def getcoldesc ( self , columnname , actual = True ) : return self . _getcoldesc ( columnname , actual , True )
Get the description of a column .
30
7
22,939
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 .
47
7
22,940
def getdminfo ( self , columnname = None ) : dminfo = self . _getdminfo ( ) if columnname is None : return dminfo # Find the info for the given column for fld in dminfo . values ( ) : if columnname in fld [ "COLUMNS" ] : fldc = fld . copy ( ) del fldc [ 'COLUMNS' ] # remove COLUMNS field return fldc raise KeyError ( "Column " + columnname + " does not exist" )
Get data manager info .
119
5
22,941
def setdmprop ( self , name , properties , bycolumn = True ) : return self . _setdmprop ( name , properties , bycolumn )
Set properties of a data manager .
32
7
22,942
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 .
44
8
22,943
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 .
251
7
22,944
def selectrows ( self , rownrs ) : t = self . _selectrows ( rownrs , name = '' ) # selectrows returns a Table object, so turn that into table. return table ( t , _oper = 3 )
Return a reference table containing the given rows .
51
9
22,945
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 .
176
12
22,946
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 .
90
12
22,947
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 .
53
11
22,948
def browse ( self , wait = True , tempname = "/tmp/seltable" ) : import os # Test if casabrowser can be found. # On OS-X 'which' always returns 0, so use test on top of it. # Nothing is written on stdout if not found. 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 .
501
18
22,949
def view ( self , wait = True , tempname = "/tmp/seltable" ) : import os # Determine the table type. # Test if casaviewer can be found. # On OS-X 'which' always returns 0, so use test on top of it. 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')" ) # Could not view the table, so browse it. if not viewed : self . browse ( wait , tempname )
View a table using casaviewer casabrowser or wxwidget based browser .
475
19
22,950
def _repr_html_ ( self ) : out = "<table class='taqltable' style='overflow-x:auto'>\n" # Print column names (not if they are all auto-generated) 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 : # Double space after multiline rows 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 .
263
9
22,951
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 : # DEVIATION: nth treats lists as circular lists i = n . to_python_index ( len ( lst ) , circular = True ) return lst [ i ]
Return the nth item in the list .
127
9
22,952
def handle_import ( self , name , compilation , rule ) : # TODO this is all not terribly well-specified by Sass. at worst, # it's unclear how far "upwards" we should be allowed to go. but i'm # also a little fuzzy on e.g. how relative imports work from within a # file that's not actually in the search path. # TODO i think with the new origin semantics, i've made it possible to # import relative to the current file even if the current file isn't # anywhere in the search path. is that right? 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 = [ ] # tuple of (origin, start_from) if relative_to . is_absolute ( ) : relative_to = PurePosixPath ( * relative_to . parts [ 1 : ] ) elif rule . source_file . origin : # Search relative to the current file first, only if not doing an # absolute import 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 # Lexically (ignoring symlinks!) eliminate .. from the part # of the path that exists within Sass-space. pathlib # deliberately doesn't do this, but os.path does. relpath = PurePosixPath ( os . path . normpath ( str ( relpath ) ) ) if rule . source_file . key == ( origin , relpath ) : # Avoid self-import # TODO is this what ruby does? continue path = origin / relpath if not path . exists ( ) : continue # All good! # TODO if this file has already been imported, we'll do the # source preparation twice. make it lazy. return SourceFile . read ( origin , relpath )
Implementation of the core Sass import mechanism which just looks for files on disk .
506
16
22,953
def print_error ( input , err , scanner ) : p = err . pos # Figure out the line number line = input [ : p ] . count ( '\n' ) print err . msg + " on line " + repr ( line + 1 ) + ":" # Now try printing part of the line text = input [ max ( p - 80 , 0 ) : p + 80 ] p = p - max ( p - 80 , 0 ) # Strip to the left 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 : ] # Strip to the right 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 ] # Now shorten the text while len ( text ) > 70 and p > 60 : # Cut off 10 chars text = "..." + text [ 10 : ] p = p - 7 # Now print the string, along with an indicator print '> ' , text print '> ' , ' ' * p + '^' print 'List of nearby tokens:' , scanner
This is a really dumb long function to print error messages nicely .
304
13
22,954
def equal_set ( self , a , b ) : 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
50
9
22,955
def add_to ( self , parent , additions ) : for x in additions : if x not in parent : parent . append ( x ) self . changed ( )
Modify parent to include all elements in additions
34
9
22,956
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 .
35
21
22,957
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
90
8
22,958
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 .
53
26
22,959
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 .
122
17
22,960
def parse_interpolations ( self , string ) : # Shortcut: if there are no #s in the string in the first place, it # must not have any interpolations, right? 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 .
82
22
22,961
def parse_vars_and_interpolations ( self , string ) : # Shortcut: if there are no #s or $s in the string in the first place, # it must not have anything of interest. 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 .
100
24
22,962
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
80
8
22,963
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 # for the newline start_line += 1 return "\n" . join ( lines ) , caret_line
Add a caret marking a given position in a string of input .
123
14
22,964
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 # TODO this could go away if rules knew their import chains... # TODO this doesn't mention mixins or function calls. really need to # track the call stack better. atm we skip other calls in the same # file because most of them are just nesting, but they might not be! # TODO the line number is wrong here for @imports, because we don't # have access to the UnparsedBlock representing the import! # TODO @content is completely broken; it's basically textual inclusion 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 .
246
8
22,965
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 .
48
21
22,966
def to_css ( self ) : # TODO should this include the traceback? any security concerns? prefix = self . format_prefix ( ) original_error = self . format_original_error ( ) sass_stack = self . format_sass_stack ( ) message = prefix + "\n" + sass_stack + original_error # Super simple escaping: only quotes and newlines are illegal in css # strings message = message . replace ( '\\' , '\\\\' ) message = message . replace ( '"' , '\\"' ) # use the maximum six digits here so it doesn't eat any following # characters that happen to look like hex 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 .
180
18
22,967
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 .
42
12
22,968
def parse_selectors ( self , raw_selectors ) : # Fix tabs and spaces in selectors raw_selectors = _spaces_re . sub ( ' ' , raw_selectors ) parts = _xcss_extends_re . split ( raw_selectors , 1 ) # handle old xCSS extends if len ( parts ) > 1 : unparsed_selectors , unsplit_parents = parts # Multiple `extends` are delimited by `&` 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 .
184
13
22,969
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 : # Pop off any flags: !default, !global is_default = False is_global = True # eventually sass will default this to false 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 ) ) # Variable assignment _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 ) # Variable assignment is an expression, so it always performs # real division value = calculator . calculate ( raw_value , divide = True ) rule . namespace . set_variable ( _prop , value , local_only = not is_global ) else : # Regular property destined for output _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 ) : # TODO kill this branch 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
612
9
22,970
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 .
36
15
22,971
def _add_sub ( self , other , op ) : if not isinstance ( other , Number ) : return NotImplemented # If either side is unitless, inherit the other side's units. Skip all # the rest of the conversion math, too. 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 , ) # Likewise, if either side is zero, it can auto-cast to any units 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 , ) # Reduce both operands to the same units 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 ) # Convert back to the left side's units 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 .
392
9
22,972
def to_base_units ( self ) : # Convert to "standard" units, as defined by the conversions dict above 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 .
116
25
22,973
def wrap_python_function ( cls , fn ) : def wrapped ( sass_arg ) : # TODO enforce no units for trig? 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 .
100
27
22,974
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 .
167
26
22,975
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 .
49
17
22,976
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 .
99
21
22,977
def from_name ( cls , name ) : self = cls . __new__ ( cls ) # TODO 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 .
63
9
22,978
def unquoted ( cls , value , literal = False ) : return cls ( value , quotes = None , literal = literal )
Helper to create a string with no quotes .
29
9
22,979
def _is_combinator_subset_of ( specific , general , is_first = True ) : if is_first and general == ' ' : # First selector always has a space to mean "descendent of root", which # still holds if any other selector appears above it 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 .
101
14
22,980
def _weave_conflicting_selectors ( prefixes , a , b , suffix = ( ) ) : # OK, what this actually does: given a list of selector chains, two # "conflicting" selector chains, and an optional suffix, return a new list # of chains like this: # prefix[0] + a + b + suffix, # prefix[0] + b + a + suffix, # prefix[1] + a + b + suffix, # ... # In other words, this just appends a new chain to each of a list of given # chains, except that the new chain might be the superposition of two # other incompatible chains. both = a and b for prefix in prefixes : yield prefix + a + b + suffix if both : # Only use both orderings if there's an actual conflict! 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 .
185
24
22,981
def _merge_simple_selectors ( a , b ) : # TODO what about combinators 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 .
59
15
22,982
def longest_common_subsequence ( a , b , mergefunc = None ) : if mergefunc is None : # Stupid default, just in case def mergefunc ( a , b ) : if a == b : return a return None # Precalculate equality, since it can be a tad expensive and every pair is # compared at least once eq = { } for ai , aval in enumerate ( a ) : for bi , bval in enumerate ( b ) : eq [ ai , bi ] = mergefunc ( aval , bval ) # Build the "length" matrix, which provides the length of the LCS for # arbitrary-length prefixes. -1 exists only to support the base case 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 # The interesting part. The key insight is that the bottom-right value in # the length matrix must be the length of the LCS because of how the matrix # is defined, so all that's left to do is backtrack from the ends of both # sequences in whatever way keeps the LCS as long as possible, and keep # track of the equal pairs of elements we see along the way. # Wikipedia does this with recursion, but the algorithm is trivial to # rewrite as a loop, as below. 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 has the latest items first, which is backwards ret . reverse ( ) return ret
Find the longest common subsequence between two iterables .
509
11
22,983
def is_superset_of ( self , other , soft_combinator = False ) : # Combinators must match, OR be compatible -- space is a superset of >, # ~ is a superset of + 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 .
154
16
22,984
def substitute ( self , target , replacement ) : # Find the target in the parent selector, and split it into # before/after p_before , p_extras , p_after = self . break_around ( target . simple_selectors ) # The replacement has no hinge; it only has the most specific simple # selector (which is the part that replaces "self" in the parent) and # whatever preceding simple selectors there may be r_trail = replacement . simple_selectors [ : - 1 ] r_extras = replacement . simple_selectors [ - 1 ] # TODO what if the prefix doesn't match? who wins? should we even get # this far? 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 .
216
15
22,985
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 .
95
13
22,986
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 .
55
40
22,987
def cancel_base_units ( units , to_remove ) : # Copy the dict since we're about to mutate it 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 .
120
14
22,988
def is_builtin_css_function ( name ) : name = name . replace ( '_' , '-' ) if name in BUILTIN_FUNCTIONS : return True # Vendor-specific functions (-foo-bar) are always okay 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 .
75
16
22,989
def determine_encoding ( buf ) : # The ultimate default is utf8; bravo, W3C bom_encoding = 'UTF-8' if not buf : # What return bom_encoding if isinstance ( buf , six . text_type ) : # We got a file that, for whatever reason, produces already-decoded # text. Check for the BOM (which is useless now) and believe # whatever's in the @charset. if buf [ 0 ] == '\ufeff' : buf = buf [ 0 : ] # This is pretty similar to the code below, but without any encoding # double-checking. 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 # BOMs 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 : ] # The spec requires exactly this syntax; no escapes or extra spaces or # other shenanigans, thank goodness. 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 ) # Ensure that decoding with the specified encoding actually produces # the same @charset rule 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 : # With no @charset, believe the BOM encoding = bom_encoding return encoding
Return the appropriate encoding for the given CSS source according to the CSS charset rules .
708
17
22,990
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 .
96
37
22,991
def image_height ( image ) : image_size_cache = _get_cache ( 'image_size_cache' ) if not Image : raise SassMissingDependency ( 'PIL' , 'image manipulation' ) filepath = String . unquoted ( image ) . value path = None try : height = image_size_cache [ filepath ] [ 1 ] except KeyError : height = 0 IMAGES_ROOT = _images_root ( ) if callable ( IMAGES_ROOT ) : try : _file , _storage = list ( IMAGES_ROOT ( filepath ) ) [ 0 ] except IndexError : pass else : path = _storage . open ( _file ) else : _path = os . path . join ( IMAGES_ROOT , filepath . strip ( os . sep ) ) if os . path . exists ( _path ) : path = open ( _path , 'rb' ) if path : image = Image . open ( path ) size = image . size height = size [ 1 ] image_size_cache [ filepath ] = size return Number ( height , 'px' )
Returns the height of the image found at the path supplied by image relative to your project s images directory .
237
21
22,992
def path ( self ) : if self . origin : return six . text_type ( self . origin / self . relpath ) else : return six . text_type ( self . relpath )
Concatenation of origin and relpath as a string . Used in stack traces and other debugging places .
41
22
22,993
def from_filename ( cls , path_string , origin = MISSING , * * kwargs ) : path = Path ( path_string ) return cls . from_path ( path , origin , * * kwargs )
Read Sass source from a String specifying the path
50
9
22,994
def from_file ( cls , f , origin = MISSING , relpath = MISSING , * * kwargs ) : contents = f . read ( ) encoding = determine_encoding ( contents ) if isinstance ( contents , six . binary_type ) : contents = contents . decode ( encoding ) if origin is MISSING or relpath is MISSING : filename = getattr ( f , 'name' , None ) if filename is None : origin = None relpath = repr ( f ) else : origin , relpath = cls . _key_from_path ( Path ( filename ) , origin ) return cls ( origin , relpath , contents , encoding = encoding , * * kwargs )
Read Sass source from a file or file - like object .
150
12
22,995
def from_string ( cls , string , relpath = None , encoding = None , is_sass = None ) : if isinstance ( string , six . text_type ) : # Already decoded; we don't know what encoding to use for output, # though, so still check for a @charset. # TODO what if the given encoding conflicts with the one in the # file? do we care? if encoding is None : encoding = determine_encoding ( string ) byte_contents = string . encode ( encoding ) text_contents = string elif isinstance ( string , six . binary_type ) : encoding = determine_encoding ( string ) byte_contents = string text_contents = string . decode ( encoding ) else : raise TypeError ( "Expected text or bytes, got {0!r}" . format ( string ) ) origin = None if relpath is None : m = hashlib . sha256 ( ) m . update ( byte_contents ) relpath = repr ( "string:{0}:{1}" . format ( m . hexdigest ( ) [ : 16 ] , text_contents [ : 100 ] ) ) return cls ( origin , relpath , text_contents , encoding = encoding , is_sass = is_sass , )
Read Sass source from the contents of a string .
281
10
22,996
def hit ( self , rect ) : # Find the hits at the current level. hits = { tuple ( self . items [ i ] ) for i in rect . collidelistall ( self . items ) } # Recursively check the lower quadrants. if self . nw and rect . left <= self . cx and rect . top <= self . cy : hits |= self . nw . hit ( rect ) if self . sw and rect . left <= self . cx and rect . bottom >= self . cy : hits |= self . sw . hit ( rect ) if self . ne and rect . right >= self . cx and rect . top <= self . cy : hits |= self . ne . hit ( rect ) if self . se and rect . right >= self . cx and rect . bottom >= self . cy : hits |= self . se . hit ( rect ) return hits
Returns the items that overlap a bounding rectangle .
186
10
22,997
def scroll ( self , vector ) : self . center ( ( vector [ 0 ] + self . view_rect . centerx , vector [ 1 ] + self . view_rect . centery ) )
scroll the background in pixels
42
5
22,998
def center ( self , coords ) : x , y = round ( coords [ 0 ] ) , round ( coords [ 1 ] ) self . view_rect . center = x , y mw , mh = self . data . map_size tw , th = self . data . tile_size vw , vh = self . _tile_view . size # prevent camera from exposing edges of the map if self . clamp_camera : self . _anchored_view = True self . view_rect . clamp_ip ( self . map_rect ) x , y = self . view_rect . center # calc the new position in tiles and pixel offset left , self . _x_offset = divmod ( x - self . _half_width , tw ) top , self . _y_offset = divmod ( y - self . _half_height , th ) right = left + vw bottom = top + vh if not self . clamp_camera : # not anchored, so the rendered map is being offset by values larger # than the tile size. this occurs when the edges of the map are inside # the screen. a situation like is shows a background under the map. self . _anchored_view = True dx = int ( left - self . _tile_view . left ) dy = int ( top - self . _tile_view . top ) if mw < vw or left < 0 : left = 0 self . _x_offset = x - self . _half_width self . _anchored_view = False elif right > mw : left = mw - vw self . _x_offset += dx * tw self . _anchored_view = False if mh < vh or top < 0 : top = 0 self . _y_offset = y - self . _half_height self . _anchored_view = False elif bottom > mh : top = mh - vh self . _y_offset += dy * th self . _anchored_view = False # adjust the view if the view has changed without a redraw dx = int ( left - self . _tile_view . left ) dy = int ( top - self . _tile_view . top ) view_change = max ( abs ( dx ) , abs ( dy ) ) if view_change and ( view_change <= self . _redraw_cutoff ) : self . _buffer . scroll ( - dx * tw , - dy * th ) self . _tile_view . move_ip ( dx , dy ) self . _queue_edge_tiles ( dx , dy ) self . _flush_tile_queue ( self . _buffer ) elif view_change > self . _redraw_cutoff : logger . info ( 'scrolling too quickly. redraw forced' ) self . _tile_view . move_ip ( dx , dy ) self . redraw_tiles ( self . _buffer )
center the map on a pixel
630
6
22,999
def draw ( self , surface , rect , surfaces = None ) : if self . _zoom_level == 1.0 : self . _render_map ( surface , rect , surfaces ) else : self . _render_map ( self . _zoom_buffer , self . _zoom_buffer . get_rect ( ) , surfaces ) self . scaling_function ( self . _zoom_buffer , rect . size , surface ) return self . _previous_blit . copy ( )
Draw the map onto a surface
106
6