idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
230,500
def set_plot_type ( self , plot_type ) : ptypes = [ pt [ "type" ] for pt in self . plot_types ] self . plot_panel = ptypes . index ( plot_type )
Sets plot type
48
4
230,501
def update ( self , series_list ) : if not series_list : self . series_notebook . AddPage ( wx . Panel ( self , - 1 ) , _ ( "+" ) ) return self . updating = True # Delete all tabs in the notebook self . series_notebook . DeleteAllPages ( ) # Add as many tabs as there are series in code for page , attrdict in enumerate ( series_list ) : series_panel = SeriesPanel ( self . grid , attrdict ) name = "Series" self . series_notebook . InsertPage ( page , series_panel , name ) self . series_notebook . AddPage ( wx . Panel ( self , - 1 ) , _ ( "+" ) ) self . updating = False
Updates widget content from series_list
164
8
230,502
def OnSeriesChanged ( self , event ) : selection = event . GetSelection ( ) if not self . updating and selection == self . series_notebook . GetPageCount ( ) - 1 : # Add new series new_panel = SeriesPanel ( self , { "type" : "plot" } ) self . series_notebook . InsertPage ( selection , new_panel , _ ( "Series" ) ) event . Skip ( )
FlatNotebook change event handler
93
7
230,503
def update ( self , figure ) : if hasattr ( self , "figure_canvas" ) : self . figure_canvas . Destroy ( ) self . figure_canvas = self . _get_figure_canvas ( figure ) self . figure_canvas . SetSize ( self . GetSize ( ) ) figure . subplots_adjust ( ) self . main_sizer . Add ( self . figure_canvas , 1 , wx . EXPAND | wx . FIXED_MINSIZE , 0 ) self . Layout ( ) self . figure_canvas . draw ( )
Updates figure on data change
127
6
230,504
def get_figure ( self , code ) : # Caching for fast response if there are no changes if code == self . figure_code_old and self . figure_cache : return self . figure_cache self . figure_code_old = code # key is the current cursor cell of the grid key = self . grid . actions . cursor cell_result = self . grid . code_array . _eval_cell ( key , code ) # If cell_result is matplotlib figure if isinstance ( cell_result , matplotlib . pyplot . Figure ) : # Return it self . figure_cache = cell_result return cell_result else : # Otherwise return empty figure self . figure_cache = charts . ChartFigure ( ) return self . figure_cache
Returns figure from executing code in grid
162
7
230,505
def set_code ( self , code ) : # Get attributes from code attributes = [ ] strip = lambda s : s . strip ( 'u' ) . strip ( "'" ) . strip ( '"' ) for attr_dict in parse_dict_strings ( unicode ( code ) . strip ( ) [ 19 : - 1 ] ) : attrs = list ( strip ( s ) for s in parse_dict_strings ( attr_dict [ 1 : - 1 ] ) ) attributes . append ( dict ( zip ( attrs [ : : 2 ] , attrs [ 1 : : 2 ] ) ) ) if not attributes : return # Set widgets from attributes # --------------------------- # Figure attributes figure_attributes = attributes [ 0 ] for key , widget in self . figure_attributes_panel : try : obj = figure_attributes [ key ] kwargs_key = key + "_kwargs" if kwargs_key in figure_attributes : widget . set_kwargs ( figure_attributes [ kwargs_key ] ) except KeyError : obj = "" widget . code = charts . object2code ( key , obj ) # Series attributes self . all_series_panel . update ( attributes [ 1 : ] )
Update widgets from code
264
4
230,506
def get_code ( self ) : def dict2str ( attr_dict ) : """Returns string with dict content with values as code Code means that string identifiers are removed """ result = u"{" for key in attr_dict : code = attr_dict [ key ] if key in self . string_keys : code = repr ( code ) elif code and key in self . tuple_keys and not ( code [ 0 ] in [ "[" , "(" ] and code [ - 1 ] in [ "]" , ")" ] ) : code = "(" + code + ")" elif key in [ "xscale" , "yscale" ] : if code : code = '"log"' else : code = '"linear"' elif key in [ "legend" ] : if code : code = '1' else : code = '0' elif key in [ "xtick_params" ] : code = '"x"' elif key in [ "ytick_params" ] : code = '"y"' if not code : if key in self . empty_none_keys : code = "None" else : code = 'u""' result += repr ( key ) + ": " + code + ", " result = result [ : - 2 ] + u"}" return result # cls_name inludes full class name incl. charts cls_name = "charts." + charts . ChartFigure . __name__ attr_dicts = [ ] # Figure attributes attr_dict = { } # figure_attributes is a dict key2code for key , widget in self . figure_attributes_panel : if key == "type" : attr_dict [ key ] = widget else : attr_dict [ key ] = widget . code try : attr_dict [ key + "_kwargs" ] = widget . get_kwargs ( ) except AttributeError : pass attr_dicts . append ( attr_dict ) # Series_attributes is a list of dicts key2code for series_panel in self . all_series_panel : attr_dict = { } for key , widget in series_panel : if key == "type" : attr_dict [ key ] = widget else : attr_dict [ key ] = widget . code attr_dicts . append ( attr_dict ) code = cls_name + "(" for attr_dict in attr_dicts : code += dict2str ( attr_dict ) + ", " code = code [ : - 2 ] + ")" return code
Returns code that generates figure from widgets
558
7
230,507
def OnUpdateFigurePanel ( self , event ) : if self . updating : return self . updating = True self . figure_panel . update ( self . get_figure ( self . code ) ) self . updating = False
Redraw event handler for the figure panel
46
8
230,508
def parameters ( self ) : return self . block_tl , self . block_br , self . rows , self . cols , self . cells
Returns tuple of selection parameters of self
31
7
230,509
def get_access_string ( self , shape , table ) : rows , columns , tables = shape # Negative dimensions cannot be assert all ( dim > 0 for dim in shape ) # Current table has to be in dimensions assert 0 <= table < tables string_list = [ ] # Block selections templ = "[(r, c, {}) for r in xrange({}, {}) for c in xrange({}, {})]" for ( top , left ) , ( bottom , right ) in izip ( self . block_tl , self . block_br ) : string_list += [ templ . format ( table , top , bottom + 1 , left , right + 1 ) ] # Fully selected rows template = "[({}, c, {}) for c in xrange({})]" for row in self . rows : string_list += [ template . format ( row , table , columns ) ] # Fully selected columns template = "[(r, {}, {}) for r in xrange({})]" for column in self . cols : string_list += [ template . format ( column , table , rows ) ] # Single cells for row , column in self . cells : string_list += [ repr ( [ ( row , column , table ) ] ) ] key_string = " + " . join ( string_list ) if len ( string_list ) == 0 : return "" elif len ( self . cells ) == 1 and len ( string_list ) == 1 : return "S[{}]" . format ( string_list [ 0 ] [ 1 : - 1 ] ) else : template = "[S[key] for key in {} if S[key] is not None]" return template . format ( key_string )
Returns a string with which the selection can be accessed
367
10
230,510
def shifted ( self , rows , cols ) : shifted_block_tl = [ ( row + rows , col + cols ) for row , col in self . block_tl ] shifted_block_br = [ ( row + rows , col + cols ) for row , col in self . block_br ] shifted_rows = [ row + rows for row in self . rows ] shifted_cols = [ col + cols for col in self . cols ] shifted_cells = [ ( row + rows , col + cols ) for row , col in self . cells ] return Selection ( shifted_block_tl , shifted_block_br , shifted_rows , shifted_cols , shifted_cells )
Returns a new selection that is shifted by rows and cols .
152
13
230,511
def grid_select ( self , grid , clear_selection = True ) : if clear_selection : grid . ClearSelection ( ) for ( tl , br ) in zip ( self . block_tl , self . block_br ) : grid . SelectBlock ( tl [ 0 ] , tl [ 1 ] , br [ 0 ] , br [ 1 ] , addToSelected = True ) for row in self . rows : grid . SelectRow ( row , addToSelected = True ) for col in self . cols : grid . SelectCol ( col , addToSelected = True ) for cell in self . cells : grid . SelectBlock ( cell [ 0 ] , cell [ 1 ] , cell [ 0 ] , cell [ 1 ] , addToSelected = True )
Selects cells of grid with selection content
167
8
230,512
def object2code ( key , code ) : if key in [ "xscale" , "yscale" ] : if code == "log" : code = True else : code = False else : code = unicode ( code ) return code
Returns code for widget from dict object
51
7
230,513
def fig2bmp ( figure , width , height , dpi , zoom ) : dpi *= float ( zoom ) figure . set_figwidth ( width / dpi ) figure . set_figheight ( height / dpi ) figure . subplots_adjust ( ) with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) try : # The padding is too small for small sizes. This fixes it. figure . tight_layout ( pad = 1.0 / zoom ) except ValueError : pass figure . set_canvas ( FigureCanvas ( figure ) ) png_stream = StringIO ( ) figure . savefig ( png_stream , format = 'png' , dpi = ( dpi ) ) png_stream . seek ( 0 ) img = wx . ImageFromStream ( png_stream , type = wx . BITMAP_TYPE_PNG ) return wx . BitmapFromImage ( img )
Returns wx . Bitmap from matplotlib chart
207
11
230,514
def fig2x ( figure , format ) : # Save svg to file like object svg_io io = StringIO ( ) figure . savefig ( io , format = format ) # Rewind the file like object io . seek ( 0 ) data = io . getvalue ( ) io . close ( ) return data
Returns svg from matplotlib chart
67
8
230,515
def _xdate_setter ( self , xdate_format = '%Y-%m-%d' ) : if xdate_format : # We have to validate xdate_format. If wrong then bail out. try : self . autofmt_xdate ( ) datetime . date ( 2000 , 1 , 1 ) . strftime ( xdate_format ) except ValueError : self . autofmt_xdate ( ) return self . __axes . xaxis_date ( ) formatter = dates . DateFormatter ( xdate_format ) self . __axes . xaxis . set_major_formatter ( formatter )
Makes x axis a date axis with auto format
141
10
230,516
def _setup_axes ( self , axes_data ) : self . __axes . clear ( ) key_setter = [ ( "title" , self . __axes . set_title ) , ( "xlabel" , self . __axes . set_xlabel ) , ( "ylabel" , self . __axes . set_ylabel ) , ( "xscale" , self . __axes . set_xscale ) , ( "yscale" , self . __axes . set_yscale ) , ( "xticks" , self . __axes . set_xticks ) , ( "xtick_labels" , self . __axes . set_xticklabels ) , ( "xtick_params" , self . __axes . tick_params ) , ( "yticks" , self . __axes . set_yticks ) , ( "ytick_labels" , self . __axes . set_yticklabels ) , ( "ytick_params" , self . __axes . tick_params ) , ( "xlim" , self . __axes . set_xlim ) , ( "ylim" , self . __axes . set_ylim ) , ( "xgrid" , self . __axes . xaxis . grid ) , ( "ygrid" , self . __axes . yaxis . grid ) , ( "xdate_format" , self . _xdate_setter ) , ] key2setter = OrderedDict ( key_setter ) for key in key2setter : if key in axes_data and axes_data [ key ] : try : kwargs_key = key + "_kwargs" kwargs = axes_data [ kwargs_key ] except KeyError : kwargs = { } if key == "title" : # Shift title up kwargs [ "y" ] = 1.08 key2setter [ key ] ( axes_data [ key ] , * * kwargs )
Sets up axes for drawing chart
447
7
230,517
def draw_chart ( self ) : if not hasattr ( self , "attributes" ) : return # The first element is always axes data self . _setup_axes ( self . attributes [ 0 ] ) for attribute in self . attributes [ 1 : ] : series = copy ( attribute ) # Extract chart type chart_type_string = series . pop ( "type" ) x_str , y_str = self . plot_type_xy_mapping [ chart_type_string ] # Check xdata length if x_str in series and len ( series [ x_str ] ) != len ( series [ y_str ] ) : # Wrong length --> ignore xdata series [ x_str ] = range ( len ( series [ y_str ] ) ) else : # Solve the problem that the series data may contain utf-8 data series_list = list ( series [ x_str ] ) series_unicode_list = [ ] for ele in series_list : if isinstance ( ele , types . StringType ) : try : series_unicode_list . append ( ele . decode ( 'utf-8' ) ) except Exception : series_unicode_list . append ( ele ) else : series_unicode_list . append ( ele ) series [ x_str ] = tuple ( series_unicode_list ) fixed_attrs = [ ] if chart_type_string in self . plot_type_fixed_attrs : for attr in self . plot_type_fixed_attrs [ chart_type_string ] : # Remove attr if it is a fixed (non-kwd) attr # If a fixed attr is missing, insert a dummy try : fixed_attrs . append ( tuple ( series . pop ( attr ) ) ) except KeyError : fixed_attrs . append ( ( ) ) # Remove contour chart label info from series cl_attrs = { } for contour_label_attr in self . contour_label_attrs : if contour_label_attr in series : cl_attrs [ self . contour_label_attrs [ contour_label_attr ] ] = series . pop ( contour_label_attr ) # Remove contourf attributes from series cf_attrs = { } for contourf_attr in self . contourf_attrs : if contourf_attr in series : cf_attrs [ self . contourf_attrs [ contourf_attr ] ] = series . pop ( contourf_attr ) if not fixed_attrs or all ( fixed_attrs ) : # Draw series to axes # Do we have a Sankey plot --> build it if chart_type_string == "Sankey" : Sankey ( self . __axes , * * series ) . finish ( ) else : chart_method = getattr ( self . __axes , chart_type_string ) plot = chart_method ( * fixed_attrs , * * series ) # Do we have a filled contour? try : if cf_attrs . pop ( "contour_fill" ) : cf_attrs . update ( series ) if "linewidths" in cf_attrs : cf_attrs . pop ( "linewidths" ) if "linestyles" in cf_attrs : cf_attrs . pop ( "linestyles" ) if not cf_attrs [ "hatches" ] : cf_attrs . pop ( "hatches" ) self . __axes . contourf ( plot , * * cf_attrs ) except KeyError : pass # Do we have a contour chart label? try : if cl_attrs . pop ( "contour_labels" ) : self . __axes . clabel ( plot , * * cl_attrs ) except KeyError : pass # The legend has to be set up after all series are drawn self . _setup_legend ( self . attributes [ 0 ] )
Plots chart from self . attributes
860
7
230,518
def GetSource ( self , row , col , table = None ) : if table is None : table = self . grid . current_table value = self . code_array ( ( row , col , table ) ) if value is None : return u"" else : return value
Return the source string of a cell
57
7
230,519
def GetValue ( self , row , col , table = None ) : if table is None : table = self . grid . current_table try : cell_code = self . code_array ( ( row , col , table ) ) except IndexError : cell_code = None # Put EOLs into result if it is too long maxlength = int ( config [ "max_textctrl_length" ] ) if cell_code is not None and len ( cell_code ) > maxlength : chunk = 80 cell_code = "\n" . join ( cell_code [ i : i + chunk ] for i in xrange ( 0 , len ( cell_code ) , chunk ) ) return cell_code
Return the result value of a cell line split if too much data
150
13
230,520
def SetValue ( self , row , col , value , refresh = True ) : # Join code that has been split because of long line issue value = "" . join ( value . split ( "\n" ) ) key = row , col , self . grid . current_table old_code = self . grid . code_array ( key ) if old_code is None : old_code = "" if value != old_code : self . grid . actions . set_code ( key , value )
Set the value of a cell merge line breaks
104
9
230,521
def UpdateValues ( self ) : # This sends an event to the grid table # to update all of the values msg = wx . grid . GridTableMessage ( self , wx . grid . GRIDTABLE_REQUEST_VIEW_GET_VALUES ) self . grid . ProcessTableMessage ( msg )
Update all displayed values
65
4
230,522
def post_command_event ( target , msg_cls , * * kwargs ) : msg = msg_cls ( id = - 1 , * * kwargs ) wx . PostEvent ( target , msg )
Posts command event to main window
49
6
230,523
def _convert_clipboard ( self , datastring = None , sep = '\t' ) : if datastring is None : datastring = self . get_clipboard ( ) data_it = ( ( ele for ele in line . split ( sep ) ) for line in datastring . splitlines ( ) ) return data_it
Converts data string to iterable .
76
8
230,524
def get_clipboard ( self ) : bmpdata = wx . BitmapDataObject ( ) textdata = wx . TextDataObject ( ) if self . clipboard . Open ( ) : is_bmp_present = self . clipboard . GetData ( bmpdata ) self . clipboard . GetData ( textdata ) self . clipboard . Close ( ) else : wx . MessageBox ( _ ( "Can't open the clipboard" ) , _ ( "Error" ) ) if is_bmp_present : return bmpdata . GetBitmap ( ) else : return textdata . GetText ( )
Returns the clipboard content
131
4
230,525
def set_clipboard ( self , data , datatype = "text" ) : error_log = [ ] if datatype == "text" : clip_data = wx . TextDataObject ( text = data ) elif datatype == "bitmap" : clip_data = wx . BitmapDataObject ( bitmap = data ) else : msg = _ ( "Datatype {type} unknown" ) . format ( type = datatype ) raise ValueError ( msg ) if self . clipboard . Open ( ) : self . clipboard . SetData ( clip_data ) self . clipboard . Close ( ) else : wx . MessageBox ( _ ( "Can't open the clipboard" ) , _ ( "Error" ) ) return error_log
Writes data to the clipboard
165
6
230,526
def draw_rect ( grid , attr , dc , rect ) : dc . SetBrush ( wx . Brush ( wx . Colour ( 15 , 255 , 127 ) , wx . SOLID ) ) dc . SetPen ( wx . Pen ( wx . BLUE , 1 , wx . SOLID ) ) dc . DrawRectangleRect ( rect )
Draws a rect
79
4
230,527
def _is_aborted ( self , cycle , statustext , total_elements = None , freq = None ) : if total_elements is None : statustext += _ ( "{nele} elements processed. Press <Esc> to abort." ) else : statustext += _ ( "{nele} of {totalele} elements processed. " "Press <Esc> to abort." ) if freq is None : show_msg = False freq = 1000 else : show_msg = True # Show progress in statusbar each freq (1000) cells if cycle % freq == 0 : if show_msg : text = statustext . format ( nele = cycle , totalele = total_elements ) try : post_command_event ( self . main_window , self . StatusBarMsg , text = text ) except TypeError : # The main window does not exist any more pass # Now wait for the statusbar update to be written on screen if is_gtk ( ) : try : wx . Yield ( ) except : pass # Abort if we have to if self . need_abort : # We have to abort` return True # Continue return False
Displays progress and returns True if abort
257
8
230,528
def validate_signature ( self , filename ) : if not GPG_PRESENT : return False sigfilename = filename + '.sig' try : with open ( sigfilename ) : pass except IOError : # Signature file does not exist return False # Check if the sig is valid for the sigfile # TODO: Check for whitespace in filepaths return verify ( sigfilename , filename )
Returns True if a valid signature is present for filename
83
10
230,529
def leave_safe_mode ( self ) : self . code_array . safe_mode = False # Clear result cache self . code_array . result_cache . clear ( ) # Execute macros self . main_window . actions . execute_macros ( ) post_command_event ( self . main_window , self . SafeModeExitMsg )
Leaves safe mode
75
4
230,530
def approve ( self , filepath ) : try : signature_valid = self . validate_signature ( filepath ) except ValueError : # GPG is not installed signature_valid = False if signature_valid : self . leave_safe_mode ( ) post_command_event ( self . main_window , self . SafeModeExitMsg ) statustext = _ ( "Valid signature found. File is trusted." ) post_command_event ( self . main_window , self . StatusBarMsg , text = statustext ) else : self . enter_safe_mode ( ) post_command_event ( self . main_window , self . SafeModeEntryMsg ) statustext = _ ( "File is not properly signed. Safe mode " "activated. Select File -> Approve to leave safe mode." ) post_command_event ( self . main_window , self . StatusBarMsg , text = statustext )
Sets safe mode if signature missing of invalid
197
9
230,531
def clear_globals_reload_modules ( self ) : self . code_array . clear_globals ( ) self . code_array . reload_modules ( ) # Clear result cache self . code_array . result_cache . clear ( )
Clears globals and reloads modules
56
8
230,532
def _get_file_version ( self , infile ) : # Determine file version for line1 in infile : if line1 . strip ( ) != "[Pyspread save file version]" : raise ValueError ( _ ( "File format unsupported." ) ) break for line2 in infile : return line2 . strip ( )
Returns infile version string .
71
6
230,533
def clear ( self , shape = None ) : # Without setting this explicitly, the cursor is set too late self . grid . actions . cursor = 0 , 0 , 0 self . grid . current_table = 0 post_command_event ( self . main_window . grid , self . GotoCellMsg , key = ( 0 , 0 , 0 ) ) # Clear cells self . code_array . dict_grid . clear ( ) # Clear attributes del self . code_array . dict_grid . cell_attributes [ : ] if shape is not None : # Set shape self . code_array . shape = shape # Clear row heights and column widths self . code_array . row_heights . clear ( ) self . code_array . col_widths . clear ( ) # Clear macros self . code_array . macros = "" # Clear caches self . code_array . result_cache . clear ( ) # Clear globals self . code_array . clear_globals ( ) self . code_array . reload_modules ( )
Empties grid and sets shape to shape
222
9
230,534
def open ( self , event ) : filepath = event . attr [ "filepath" ] try : filetype = event . attr [ "filetype" ] except KeyError : try : file_ext = filepath . strip ( ) . split ( "." ) [ - 1 ] except : file_ext = None if file_ext in [ "pys" , "pysu" , "xls" , "xlsx" , "ods" ] : filetype = file_ext else : filetype = "pys" type2opener = { "pys" : ( Bz2AOpen , [ filepath , "r" ] , { "main_window" : self . main_window } ) , "pysu" : ( AOpen , [ filepath , "r" ] , { "main_window" : self . main_window } ) } if xlrd is not None : type2opener [ "xls" ] = ( xlrd . open_workbook , [ filepath ] , { "formatting_info" : True } ) type2opener [ "xlsx" ] = ( xlrd . open_workbook , [ filepath ] , { "formatting_info" : False } ) if odf is not None and Ods is not None : type2opener [ "ods" ] = ( open , [ filepath , "rb" ] , { } ) # Specify the interface that shall be used opener , op_args , op_kwargs = type2opener [ filetype ] Interface = self . type2interface [ filetype ] # Set state for file open self . opening = True try : with opener ( * op_args , * * op_kwargs ) as infile : # Make loading safe self . approve ( filepath ) if xlrd is None : interface_errors = ( ValueError , ) else : interface_errors = ( ValueError , xlrd . biffh . XLRDError ) try : wx . BeginBusyCursor ( ) self . grid . Disable ( ) self . clear ( ) interface = Interface ( self . grid . code_array , infile ) interface . to_code_array ( ) self . grid . main_window . macro_panel . codetext_ctrl . SetText ( self . grid . code_array . macros ) except interface_errors , err : post_command_event ( self . main_window , self . StatusBarMsg , text = str ( err ) ) finally : self . grid . GetTable ( ) . ResetView ( ) post_command_event ( self . main_window , self . ResizeGridMsg , shape = self . grid . code_array . shape ) self . grid . Enable ( ) wx . EndBusyCursor ( ) # Execute macros self . main_window . actions . execute_macros ( ) self . grid . GetTable ( ) . ResetView ( ) self . grid . ForceRefresh ( ) # File sucessfully opened. Approve again to show status. self . approve ( filepath ) # Change current directory to file directory filedir = os . path . dirname ( filepath ) os . chdir ( filedir ) except IOError , err : txt = _ ( "Error opening file {filepath}:" ) . format ( filepath = filepath ) txt += " " + str ( err ) post_command_event ( self . main_window , self . StatusBarMsg , text = txt ) return False except EOFError : # Normally on empty grids pass finally : # Unset state for file open self . opening = False
Opens a file that is specified in event . attr
789
12
230,535
def sign_file ( self , filepath ) : if not GPG_PRESENT : return signed_data = sign ( filepath ) signature = signed_data . data if signature is None or not signature : statustext = _ ( 'Error signing file. ' ) + signed_data . stderr try : post_command_event ( self . main_window , self . StatusBarMsg , text = statustext ) except TypeError : # The main window does not exist any more pass return with open ( filepath + '.sig' , 'wb' ) as signfile : signfile . write ( signature ) # Statustext differs if a save has occurred if self . code_array . safe_mode : statustext = _ ( 'File saved and signed' ) else : statustext = _ ( 'File signed' ) try : post_command_event ( self . main_window , self . StatusBarMsg , text = statustext ) except TypeError : # The main window does not exist any more pass
Signs file if possible
219
5
230,536
def _set_save_states ( self ) : wx . BeginBusyCursor ( ) self . saving = True self . grid . Disable ( )
Sets application save states
33
5
230,537
def _release_save_states ( self ) : self . saving = False self . grid . Enable ( ) wx . EndBusyCursor ( ) # Mark content as unchanged try : post_command_event ( self . main_window , self . ContentChangedMsg ) except TypeError : # The main window does not exist any more pass
Releases application save states
72
5
230,538
def _move_tmp_file ( self , tmpfilepath , filepath ) : try : shutil . move ( tmpfilepath , filepath ) except OSError , err : # No tmp file present post_command_event ( self . main_window , self . StatusBarMsg , text = err )
Moves tmpfile over file after saving is finished
67
10
230,539
def _save_xls ( self , filepath ) : Interface = self . type2interface [ "xls" ] workbook = xlwt . Workbook ( ) interface = Interface ( self . grid . code_array , workbook ) interface . from_code_array ( ) try : workbook . save ( filepath ) except IOError , err : try : post_command_event ( self . main_window , self . StatusBarMsg , text = err ) except TypeError : # The main window does not exist any more pass
Saves file as xls workbook
115
8
230,540
def _save_pys ( self , filepath ) : try : with Bz2AOpen ( filepath , "wb" , main_window = self . main_window ) as outfile : interface = Pys ( self . grid . code_array , outfile ) interface . from_code_array ( ) except ( IOError , ValueError ) , err : try : post_command_event ( self . main_window , self . StatusBarMsg , text = err ) return except TypeError : # The main window does not exist any more pass return not outfile . aborted
Saves file as pys file and returns True if save success
124
13
230,541
def _save_sign ( self , filepath ) : if self . code_array . safe_mode : msg = _ ( "File saved but not signed because it is unapproved." ) try : post_command_event ( self . main_window , self . StatusBarMsg , text = msg ) except TypeError : # The main window does not exist any more pass else : try : self . sign_file ( filepath ) except ValueError , err : msg = "Signing file failed. " + unicode ( err ) post_command_event ( self . main_window , self . StatusBarMsg , text = msg )
Sign so that the new file may be retrieved without safe mode
134
12
230,542
def save ( self , event ) : filepath = event . attr [ "filepath" ] try : filetype = event . attr [ "filetype" ] except KeyError : filetype = "pys" # If saving is already in progress abort if self . saving : return # Use tmpfile to make sure that old save file does not get lost # on abort save __ , tmpfilepath = tempfile . mkstemp ( ) if filetype == "xls" : self . _set_save_states ( ) self . _save_xls ( tmpfilepath ) self . _move_tmp_file ( tmpfilepath , filepath ) self . _release_save_states ( ) elif filetype == "pys" or filetype == "all" : self . _set_save_states ( ) if self . _save_pys ( tmpfilepath ) : # Writing was successful self . _move_tmp_file ( tmpfilepath , filepath ) self . _save_sign ( filepath ) self . _release_save_states ( ) elif filetype == "pysu" : self . _set_save_states ( ) if self . _save_pysu ( tmpfilepath ) : # Writing was successful self . _move_tmp_file ( tmpfilepath , filepath ) self . _save_sign ( filepath ) self . _release_save_states ( ) else : os . remove ( tmpfilepath ) msg = "Filetype {filetype} unknown." . format ( filetype = filetype ) raise ValueError ( msg ) try : os . remove ( tmpfilepath ) except OSError : pass
Saves a file that is specified in event . attr
361
12
230,543
def set_row_height ( self , row , height ) : # Mark content as changed post_command_event ( self . main_window , self . ContentChangedMsg ) tab = self . grid . current_table self . code_array . set_row_height ( row , tab , height ) self . grid . SetRowSize ( row , height )
Sets row height and marks grid as changed
76
9
230,544
def insert_rows ( self , row , no_rows = 1 ) : # Mark content as changed post_command_event ( self . main_window , self . ContentChangedMsg ) tab = self . grid . current_table self . code_array . insert ( row , no_rows , axis = 0 , tab = tab )
Adds no_rows rows before row appends if row > maxrows
70
14
230,545
def delete_rows ( self , row , no_rows = 1 ) : # Mark content as changed post_command_event ( self . main_window , self . ContentChangedMsg ) tab = self . grid . current_table try : self . code_array . delete ( row , no_rows , axis = 0 , tab = tab ) except ValueError , err : post_command_event ( self . main_window , self . StatusBarMsg , text = err . message )
Deletes no_rows rows and marks grid as changed
102
11
230,546
def set_col_width ( self , col , width ) : # Mark content as changed post_command_event ( self . main_window , self . ContentChangedMsg ) tab = self . grid . current_table self . code_array . set_col_width ( col , tab , width ) self . grid . SetColSize ( col , width )
Sets column width and marks grid as changed
76
9
230,547
def insert_cols ( self , col , no_cols = 1 ) : # Mark content as changed post_command_event ( self . main_window , self . ContentChangedMsg ) tab = self . grid . current_table self . code_array . insert ( col , no_cols , axis = 1 , tab = tab )
Adds no_cols columns before col appends if col > maxcols
73
16
230,548
def delete_cols ( self , col , no_cols = 1 ) : # Mark content as changed post_command_event ( self . main_window , self . ContentChangedMsg ) tab = self . grid . current_table try : self . code_array . delete ( col , no_cols , axis = 1 , tab = tab ) except ValueError , err : post_command_event ( self . main_window , self . StatusBarMsg , text = err . message )
Deletes no_cols column and marks grid as changed
105
12
230,549
def insert_tabs ( self , tab , no_tabs = 1 ) : # Mark content as changed post_command_event ( self . main_window , self . ContentChangedMsg ) self . code_array . insert ( tab , no_tabs , axis = 2 ) # Update TableChoiceIntCtrl shape = self . grid . code_array . shape post_command_event ( self . main_window , self . ResizeGridMsg , shape = shape )
Adds no_tabs tabs before table appends if tab > maxtabs
100
16
230,550
def delete_tabs ( self , tab , no_tabs = 1 ) : # Mark content as changed post_command_event ( self . main_window , self . ContentChangedMsg ) try : self . code_array . delete ( tab , no_tabs , axis = 2 ) # Update TableChoiceIntCtrl shape = self . grid . code_array . shape post_command_event ( self . main_window , self . ResizeGridMsg , shape = shape ) except ValueError , err : post_command_event ( self . main_window , self . StatusBarMsg , text = err . message )
Deletes no_tabs tabs and marks grid as changed
132
12
230,551
def on_key ( self , event ) : # If paste is running and Esc is pressed then we need to abort if event . GetKeyCode ( ) == wx . WXK_ESCAPE and self . pasting or self . grid . actions . saving : self . need_abort = True event . Skip ( )
Sets abort if pasting and if escape is pressed
70
11
230,552
def _get_full_key ( self , key ) : length = len ( key ) if length == 3 : return key elif length == 2 : row , col = key tab = self . grid . current_table return row , col , tab else : msg = _ ( "Key length {length} not in (2, 3)" ) . format ( length = length ) raise ValueError ( msg )
Returns full key even if table is omitted
85
8
230,553
def _show_final_overflow_message ( self , row_overflow , col_overflow ) : if row_overflow and col_overflow : overflow_cause = _ ( "rows and columns" ) elif row_overflow : overflow_cause = _ ( "rows" ) elif col_overflow : overflow_cause = _ ( "columns" ) else : raise AssertionError ( _ ( "Import cell overflow missing" ) ) statustext = _ ( "The imported data did not fit into the grid {cause}. " "It has been truncated. Use a larger grid for full import." ) . format ( cause = overflow_cause ) post_command_event ( self . main_window , self . StatusBarMsg , text = statustext )
Displays overflow message after import in statusbar
169
9
230,554
def _show_final_paste_message ( self , tl_key , no_pasted_cells ) : plural = "" if no_pasted_cells == 1 else _ ( "s" ) statustext = _ ( "{ncells} cell{plural} pasted at cell {topleft}" ) . format ( ncells = no_pasted_cells , plural = plural , topleft = tl_key ) post_command_event ( self . main_window , self . StatusBarMsg , text = statustext )
Show actually pasted number of cells
120
7
230,555
def paste_to_current_cell ( self , tl_key , data , freq = None ) : self . pasting = True grid_rows , grid_cols , __ = self . grid . code_array . shape self . need_abort = False tl_row , tl_col , tl_tab = self . _get_full_key ( tl_key ) row_overflow = False col_overflow = False no_pasted_cells = 0 for src_row , row_data in enumerate ( data ) : target_row = tl_row + src_row if self . grid . actions . _is_aborted ( src_row , _ ( "Pasting cells... " ) , freq = freq ) : self . _abort_paste ( ) return False # Check if rows fit into grid if target_row >= grid_rows : row_overflow = True break for src_col , cell_data in enumerate ( row_data ) : target_col = tl_col + src_col if target_col >= grid_cols : col_overflow = True break if cell_data is not None : # Is only None if pasting into selection key = target_row , target_col , tl_tab try : CellActions . set_code ( self , key , cell_data ) no_pasted_cells += 1 except KeyError : pass if row_overflow or col_overflow : self . _show_final_overflow_message ( row_overflow , col_overflow ) else : self . _show_final_paste_message ( tl_key , no_pasted_cells ) self . pasting = False
Pastes data into grid from top left cell tl_key
374
13
230,556
def selection_paste_data_gen ( self , selection , data , freq = None ) : ( bb_top , bb_left ) , ( bb_bottom , bb_right ) = selection . get_grid_bbox ( self . grid . code_array . shape ) bbox_height = bb_bottom - bb_top + 1 bbox_width = bb_right - bb_left + 1 for row , row_data in enumerate ( itertools . cycle ( data ) ) : # Break if row is not in selection bbox if row >= bbox_height : break # Duplicate row data if selection is wider than row data row_data = list ( row_data ) duplicated_row_data = row_data * ( bbox_width // len ( row_data ) + 1 ) duplicated_row_data = duplicated_row_data [ : bbox_width ] for col in xrange ( len ( duplicated_row_data ) ) : if ( bb_top , bb_left + col ) not in selection : duplicated_row_data [ col ] = None yield duplicated_row_data
Generator that yields data for selection paste
256
8
230,557
def paste_to_selection ( self , selection , data , freq = None ) : ( bb_top , bb_left ) , ( bb_bottom , bb_right ) = selection . get_grid_bbox ( self . grid . code_array . shape ) adjusted_data = self . selection_paste_data_gen ( selection , data ) self . paste_to_current_cell ( ( bb_top , bb_left ) , adjusted_data , freq = freq )
Pastes data into grid selection
112
6
230,558
def paste ( self , tl_key , data , freq = None ) : # Get selection bounding box selection = self . get_selection ( ) # Mark content as changed post_command_event ( self . main_window , self . ContentChangedMsg ) if selection : # There is a selection. Paste into it self . paste_to_selection ( selection , data , freq = freq ) else : # There is no selection. Paste from top left cell. self . paste_to_current_cell ( tl_key , data , freq = freq )
Pastes data into grid marks grid changed
123
8
230,559
def change_grid_shape ( self , shape ) : # Mark content as changed post_command_event ( self . main_window , self . ContentChangedMsg ) self . code_array . shape = shape # Update TableChoiceIntCtrl post_command_event ( self . main_window , self . ResizeGridMsg , shape = shape ) # Change grid table dimensions self . grid . GetTable ( ) . ResetView ( ) # Clear caches self . code_array . result_cache . clear ( )
Grid shape change event handler marks content as changed
107
9
230,560
def replace_cells ( self , key , sorted_row_idxs ) : row , col , tab = key new_keys = { } del_keys = [ ] selection = self . grid . actions . get_selection ( ) for __row , __col , __tab in self . grid . code_array : if __tab == tab and ( not selection or ( __row , __col ) in selection ) : new_row = sorted_row_idxs . index ( __row ) if __row != new_row : new_keys [ ( new_row , __col , __tab ) ] = self . grid . code_array ( ( __row , __col , __tab ) ) del_keys . append ( ( __row , __col , __tab ) ) for key in del_keys : self . grid . code_array . pop ( key ) for key in new_keys : CellActions . set_code ( self , key , new_keys [ key ] )
Replaces cells in current selection so that they are sorted
210
11
230,561
def new ( self , event ) : # Grid table handles interaction to code_array self . grid . actions . clear ( event . shape ) _grid_table = GridTable ( self . grid , self . grid . code_array ) self . grid . SetTable ( _grid_table , True ) # Update toolbars self . grid . update_entry_line ( ) self . grid . update_attribute_toolbar ( )
Creates a new spreadsheet . Expects code_array in event .
90
14
230,562
def _zoom_rows ( self , zoom ) : self . grid . SetDefaultRowSize ( self . grid . std_row_size * zoom , resizeExistingRows = True ) self . grid . SetRowLabelSize ( self . grid . row_label_size * zoom ) for row , tab in self . code_array . row_heights : if tab == self . grid . current_table and row < self . grid . code_array . shape [ 0 ] : base_row_width = self . code_array . row_heights [ ( row , tab ) ] if base_row_width is None : base_row_width = self . grid . GetDefaultRowSize ( ) zoomed_row_size = base_row_width * zoom self . grid . SetRowSize ( row , zoomed_row_size )
Zooms grid rows
183
5
230,563
def _zoom_cols ( self , zoom ) : self . grid . SetDefaultColSize ( self . grid . std_col_size * zoom , resizeExistingCols = True ) self . grid . SetColLabelSize ( self . grid . col_label_size * zoom ) for col , tab in self . code_array . col_widths : if tab == self . grid . current_table and col < self . grid . code_array . shape [ 1 ] : base_col_width = self . code_array . col_widths [ ( col , tab ) ] if base_col_width is None : base_col_width = self . grid . GetDefaultColSize ( ) zoomed_col_size = base_col_width * zoom self . grid . SetColSize ( col , zoomed_col_size )
Zooms grid columns
184
5
230,564
def _zoom_labels ( self , zoom ) : labelfont = self . grid . GetLabelFont ( ) default_fontsize = get_default_font ( ) . GetPointSize ( ) labelfont . SetPointSize ( max ( 1 , int ( round ( default_fontsize * zoom ) ) ) ) self . grid . SetLabelFont ( labelfont )
Adjust grid label font to zoom factor
79
7
230,565
def zoom ( self , zoom = None ) : status = True if zoom is None : zoom = self . grid . grid_renderer . zoom status = False # Zoom factor for grid content self . grid . grid_renderer . zoom = zoom # Zoom grid labels self . _zoom_labels ( zoom ) # Zoom rows and columns self . _zoom_rows ( zoom ) self . _zoom_cols ( zoom ) if self . main_window . IsFullScreen ( ) : # Do not display labels in fullscreen mode self . main_window . handlers . row_label_size = self . grid . GetRowLabelSize ( ) self . main_window . handlers . col_label_size = self . grid . GetColLabelSize ( ) self . grid . HideRowLabels ( ) self . grid . HideColLabels ( ) self . grid . ForceRefresh ( ) if status : statustext = _ ( u"Zoomed to {0:.2f}." ) . format ( zoom ) post_command_event ( self . main_window , self . StatusBarMsg , text = statustext )
Zooms to zoom factor
244
6
230,566
def zoom_in ( self ) : zoom = self . grid . grid_renderer . zoom target_zoom = zoom * ( 1 + config [ "zoom_factor" ] ) if target_zoom < config [ "maximum_zoom" ] : self . zoom ( target_zoom )
Zooms in by zoom factor
65
7
230,567
def zoom_out ( self ) : zoom = self . grid . grid_renderer . zoom target_zoom = zoom * ( 1 - config [ "zoom_factor" ] ) if target_zoom > config [ "minimum_zoom" ] : self . zoom ( target_zoom )
Zooms out by zoom factor
65
7
230,568
def _get_rows_height ( self ) : tab = self . grid . current_table no_rows = self . grid . code_array . shape [ 0 ] default_row_height = self . grid . code_array . cell_attributes . default_cell_attributes [ "row-height" ] non_standard_row_heights = [ ] __row_heights = self . grid . code_array . row_heights for __row , __tab in __row_heights : if __tab == tab : non_standard_row_heights . append ( __row_heights [ ( __row , __tab ) ] ) rows_height = sum ( non_standard_row_heights ) rows_height += ( no_rows - len ( non_standard_row_heights ) ) * default_row_height return rows_height
Returns the total height of all grid rows
188
8
230,569
def _get_cols_width ( self ) : tab = self . grid . current_table no_cols = self . grid . code_array . shape [ 1 ] default_col_width = self . grid . code_array . cell_attributes . default_cell_attributes [ "column-width" ] non_standard_col_widths = [ ] __col_widths = self . grid . code_array . col_widths for __col , __tab in __col_widths : if __tab == tab : non_standard_col_widths . append ( __col_widths [ ( __col , __tab ) ] ) cols_width = sum ( non_standard_col_widths ) cols_width += ( no_cols - len ( non_standard_col_widths ) ) * default_col_width return cols_width
Returns the total width of all grid cols
194
9
230,570
def zoom_fit ( self ) : zoom = self . grid . grid_renderer . zoom grid_width , grid_height = self . grid . GetSize ( ) rows_height = self . _get_rows_height ( ) + ( float ( self . grid . GetColLabelSize ( ) ) / zoom ) cols_width = self . _get_cols_width ( ) + ( float ( self . grid . GetRowLabelSize ( ) ) / zoom ) # Check target zoom for rows zoom_height = float ( grid_height ) / rows_height # Check target zoom for columns zoom_width = float ( grid_width ) / cols_width # Use the minimum target zoom from rows and column target zooms target_zoom = min ( zoom_height , zoom_width ) # Zoom only if between min and max if config [ "minimum_zoom" ] < target_zoom < config [ "maximum_zoom" ] : self . zoom ( target_zoom )
Zooms the rid to fit the window .
214
10
230,571
def on_mouse_over ( self , key ) : def split_lines ( string , line_length = 80 ) : """Returns string that is split into lines of length line_length""" result = u"" line = 0 while len ( string ) > line_length * line : line_start = line * line_length result += string [ line_start : line_start + line_length ] result += '\n' line += 1 return result [ : - 1 ] row , col , tab = key # If the cell is a button cell or a frozen cell then do nothing cell_attributes = self . grid . code_array . cell_attributes if cell_attributes [ key ] [ "button_cell" ] or cell_attributes [ key ] [ "frozen" ] : return if ( row , col ) != self . prev_rowcol and row >= 0 and col >= 0 : self . prev_rowcol [ : ] = [ row , col ] max_result_length = int ( config [ "max_result_length" ] ) table = self . grid . GetTable ( ) hinttext = table . GetSource ( row , col , tab ) [ : max_result_length ] if hinttext is None : hinttext = '' post_command_event ( self . main_window , self . StatusBarMsg , text = hinttext ) cell_res = self . grid . code_array [ row , col , tab ] if cell_res is None : self . grid . SetToolTip ( None ) return try : cell_res_str = unicode ( cell_res ) except UnicodeEncodeError : cell_res_str = unicode ( cell_res , encoding = 'utf-8' ) if len ( cell_res_str ) > max_result_length : cell_res_str = cell_res_str [ : max_result_length ] + ' [...]' self . grid . SetToolTipString ( split_lines ( cell_res_str ) )
Displays cell code of cell key in status bar
428
10
230,572
def get_visible_area ( self ) : grid = self . grid top = grid . YToRow ( grid . GetViewStart ( ) [ 1 ] * grid . ScrollLineX ) left = grid . XToCol ( grid . GetViewStart ( ) [ 0 ] * grid . ScrollLineY ) # Now start at top left for determining the bottom right visible cell bottom , right = top , left while grid . IsVisible ( bottom , left , wholeCellVisible = False ) : bottom += 1 while grid . IsVisible ( top , right , wholeCellVisible = False ) : right += 1 # The derived lower right cell is *NOT* visible bottom -= 1 right -= 1 return ( top , left ) , ( bottom , right )
Returns visible area
158
3
230,573
def switch_to_table ( self , event ) : newtable = event . newtable no_tabs = self . grid . code_array . shape [ 2 ] - 1 if 0 <= newtable <= no_tabs : self . grid . current_table = newtable self . grid . SetToolTip ( None ) # Delete renderer cache self . grid . grid_renderer . cell_cache . clear ( ) # Delete video cells video_cells = self . grid . grid_renderer . video_cells for key in video_cells : video_panel = video_cells [ key ] video_panel . player . stop ( ) video_panel . player . release ( ) video_panel . Destroy ( ) video_cells . clear ( ) # Hide cell editor cell_editor = self . grid . GetCellEditor ( self . grid . GetGridCursorRow ( ) , self . grid . GetGridCursorCol ( ) ) try : cell_editor . Reset ( ) except AttributeError : # No cell editor open pass self . grid . HideCellEditControl ( ) # Change value of entry_line and table choice post_command_event ( self . main_window , self . TableChangedMsg , table = newtable ) # Reset row heights and column widths by zooming self . zoom ( )
Switches grid to table
278
5
230,574
def set_cursor ( self , value ) : shape = self . grid . code_array . shape if len ( value ) == 3 : self . grid . _last_selected_cell = row , col , tab = value if row < 0 or col < 0 or tab < 0 or row >= shape [ 0 ] or col >= shape [ 1 ] or tab >= shape [ 2 ] : raise ValueError ( "Cell {value} outside of {shape}" . format ( value = value , shape = shape ) ) if tab != self . cursor [ 2 ] : post_command_event ( self . main_window , self . GridActionTableSwitchMsg , newtable = tab ) if is_gtk ( ) : try : wx . Yield ( ) except : pass else : row , col = value if row < 0 or col < 0 or row >= shape [ 0 ] or col >= shape [ 1 ] : raise ValueError ( "Cell {value} outside of {shape}" . format ( value = value , shape = shape ) ) self . grid . _last_selected_cell = row , col , self . grid . current_table if not ( row is None and col is None ) : if not self . grid . IsVisible ( row , col , wholeCellVisible = True ) : self . grid . MakeCellVisible ( row , col ) self . grid . SetGridCursor ( row , col )
Changes the grid cursor cell .
301
6
230,575
def get_selection ( self ) : # GetSelectedCells: individual cells selected by ctrl-clicking # GetSelectedRows: rows selected by clicking on the labels # GetSelectedCols: cols selected by clicking on the labels # GetSelectionBlockTopLeft # GetSelectionBlockBottomRight: For blocks selected by dragging # across the grid cells. block_top_left = self . grid . GetSelectionBlockTopLeft ( ) block_bottom_right = self . grid . GetSelectionBlockBottomRight ( ) rows = self . grid . GetSelectedRows ( ) cols = self . grid . GetSelectedCols ( ) cells = self . grid . GetSelectedCells ( ) return Selection ( block_top_left , block_bottom_right , rows , cols , cells )
Returns selected cells in grid as Selection object
177
8
230,576
def select_cell ( self , row , col , add_to_selected = False ) : self . grid . SelectBlock ( row , col , row , col , addToSelected = add_to_selected )
Selects a single cell
46
5
230,577
def select_slice ( self , row_slc , col_slc , add_to_selected = False ) : if not add_to_selected : self . grid . ClearSelection ( ) if row_slc == row_slc == slice ( None , None , None ) : # The whole grid is selected self . grid . SelectAll ( ) elif row_slc . stop is None and col_slc . stop is None : # A block is selected: self . grid . SelectBlock ( row_slc . start , col_slc . start , row_slc . stop - 1 , col_slc . stop - 1 ) else : for row in xrange ( row_slc . start , row_slc . stop , row_slc . step ) : for col in xrange ( col_slc . start , col_slc . stop , col_slc . step ) : self . select_cell ( row , col , add_to_selected = True )
Selects a slice of cells
218
6
230,578
def delete_selection ( self , selection = None ) : # Mark content as changed post_command_event ( self . main_window , self . ContentChangedMsg ) if selection is None : selection = self . get_selection ( ) current_table = self . grid . current_table for row , col , tab in self . grid . code_array . dict_grid . keys ( ) : if tab == current_table and ( row , col ) in selection : self . grid . actions . delete_cell ( ( row , col , tab ) ) self . grid . code_array . result_cache . clear ( )
Deletes selection marks content as changed
131
7
230,579
def delete ( self ) : if self . grid . IsSelection ( ) : # Delete selection self . grid . actions . delete_selection ( ) else : # Delete cell at cursor cursor = self . grid . actions . cursor self . grid . actions . delete_cell ( cursor ) # Update grid self . grid . ForceRefresh ( )
Deletes a selection if any else deletes the cursor cell
71
12
230,580
def quote_selection ( self ) : selection = self . get_selection ( ) current_table = self . grid . current_table for row , col , tab in self . grid . code_array . dict_grid . keys ( ) : if tab == current_table and ( row , col ) in selection : self . grid . actions . quote_code ( ( row , col , tab ) ) self . grid . code_array . result_cache . clear ( )
Quotes selected cells marks content as changed
99
7
230,581
def copy_selection_access_string ( self ) : selection = self . get_selection ( ) if not selection : cursor = self . grid . actions . cursor selection = Selection ( [ ] , [ ] , [ ] , [ ] , [ tuple ( cursor [ : 2 ] ) ] ) shape = self . grid . code_array . shape tab = self . grid . current_table access_string = selection . get_access_string ( shape , tab ) # Copy access string to clipboard self . grid . main_window . clipboard . set_clipboard ( access_string ) # Display copy operation and access string in status bar statustext = _ ( "Cell reference copied to clipboard: {access_string}" ) statustext = statustext . format ( access_string = access_string ) post_command_event ( self . main_window , self . StatusBarMsg , text = statustext )
Copys access_string to selection to the clipboard
193
10
230,582
def copy_format ( self ) : row , col , tab = self . grid . actions . cursor code_array = self . grid . code_array # Cell attributes new_cell_attributes = [ ] selection = self . get_selection ( ) if not selection : # Current cell is chosen for selection selection = Selection ( [ ] , [ ] , [ ] , [ ] , [ ( row , col ) ] ) # Format content is shifted so that the top left corner is 0,0 ( ( top , left ) , ( bottom , right ) ) = selection . get_grid_bbox ( self . grid . code_array . shape ) cell_attributes = code_array . cell_attributes for __selection , table , attrs in cell_attributes : if tab == table : new_selection = selection & __selection if new_selection : new_shifted_selection = new_selection . shifted ( - top , - left ) if "merge_area" not in attrs : selection_params = new_shifted_selection . parameters cellattribute = selection_params , table , attrs new_cell_attributes . append ( cellattribute ) # Rows shifted_new_row_heights = { } for row , table in code_array . row_heights : if tab == table and top <= row <= bottom : shifted_new_row_heights [ row - top , table ] = code_array . row_heights [ row , table ] # Columns shifted_new_col_widths = { } for col , table in code_array . col_widths : if tab == table and left <= col <= right : shifted_new_col_widths [ col - left , table ] = code_array . col_widths [ col , table ] format_data = { "cell_attributes" : new_cell_attributes , "row_heights" : shifted_new_row_heights , "col_widths" : shifted_new_col_widths , } attr_string = repr ( format_data ) self . grid . main_window . clipboard . set_clipboard ( attr_string )
Copies the format of the selected cells to the Clipboard
466
12
230,583
def paste_format ( self ) : row , col , tab = self . grid . actions . cursor selection = self . get_selection ( ) if selection : # Use selection rather than cursor for top left cell if present row , col = [ tl if tl is not None else 0 for tl in selection . get_bbox ( ) [ 0 ] ] cell_attributes = self . grid . code_array . cell_attributes string_data = self . grid . main_window . clipboard . get_clipboard ( ) format_data = ast . literal_eval ( string_data ) ca = format_data [ "cell_attributes" ] rh = format_data [ "row_heights" ] cw = format_data [ "col_widths" ] assert isinstance ( ca , types . ListType ) assert isinstance ( rh , types . DictType ) assert isinstance ( cw , types . DictType ) # Cell attributes for selection_params , tab , attrs in ca : base_selection = Selection ( * selection_params ) shifted_selection = base_selection . shifted ( row , col ) if "merge_area" not in attrs : # Do not paste merge areas because this may have # inintended consequences for existing merge areas new_cell_attribute = shifted_selection , tab , attrs cell_attributes . append ( new_cell_attribute ) # Row heights row_heights = self . grid . code_array . row_heights for __row , __tab in rh : row_heights [ __row + row , tab ] = rh [ __row , __tab ] # Column widths col_widths = self . grid . code_array . col_widths for __col , __tab in cw : col_widths [ __col + col , tab ] = cw [ ( __col , __tab ) ]
Pastes cell formats
406
4
230,584
def find_all ( self , find_string , flags ) : code_array = self . grid . code_array string_match = code_array . string_match find_keys = [ ] for key in code_array : if string_match ( code_array ( key ) , find_string , flags ) is not None : find_keys . append ( key ) return find_keys
Return list of all positions of event_find_string in MainGrid .
83
15
230,585
def find ( self , gridpos , find_string , flags , search_result = True ) : findfunc = self . grid . code_array . findnextmatch if "DOWN" in flags : if gridpos [ 0 ] < self . grid . code_array . shape [ 0 ] : gridpos [ 0 ] += 1 elif gridpos [ 1 ] < self . grid . code_array . shape [ 1 ] : gridpos [ 1 ] += 1 elif gridpos [ 2 ] < self . grid . code_array . shape [ 2 ] : gridpos [ 2 ] += 1 else : gridpos = ( 0 , 0 , 0 ) elif "UP" in flags : if gridpos [ 0 ] > 0 : gridpos [ 0 ] -= 1 elif gridpos [ 1 ] > 0 : gridpos [ 1 ] -= 1 elif gridpos [ 2 ] > 0 : gridpos [ 2 ] -= 1 else : gridpos = [ dim - 1 for dim in self . grid . code_array . shape ] return findfunc ( tuple ( gridpos ) , find_string , flags , search_result )
Return next position of event_find_string in MainGrid
237
12
230,586
def _replace_bbox_none ( self , bbox ) : ( bb_top , bb_left ) , ( bb_bottom , bb_right ) = bbox if bb_top is None : bb_top = 0 if bb_left is None : bb_left = 0 if bb_bottom is None : bb_bottom = self . code_array . shape [ 0 ] - 1 if bb_right is None : bb_right = self . code_array . shape [ 1 ] - 1 return ( bb_top , bb_left ) , ( bb_bottom , bb_right )
Returns bbox in which None is replaced by grid boundaries
143
11
230,587
def get_filetypes2wildcards ( filetypes ) : def is_available ( filetype ) : return filetype not in FILETYPE_AVAILABILITY or FILETYPE_AVAILABILITY [ filetype ] available_filetypes = filter ( is_available , filetypes ) return OrderedDict ( ( ft , FILETYPE2WILDCARD [ ft ] ) for ft in available_filetypes )
Returns OrderedDict of filetypes to wildcards
88
11
230,588
def get_key_params_from_user ( gpg_key_param_list ) : params = [ [ _ ( 'Real name' ) , 'name_real' ] ] vals = [ "" ] * len ( params ) while "" in vals : dlg = GPGParamsDialog ( None , - 1 , "Enter GPG key parameters" , params ) dlg . CenterOnScreen ( ) for val , textctrl in zip ( vals , dlg . textctrls ) : textctrl . SetValue ( val ) if dlg . ShowModal ( ) != wx . ID_OK : dlg . Destroy ( ) return vals = [ textctrl . Value for textctrl in dlg . textctrls ] dlg . Destroy ( ) if "" in vals : msg = _ ( "Please enter a value in each field." ) dlg = GMD . GenericMessageDialog ( None , msg , _ ( "Missing value" ) , wx . OK | wx . ICON_ERROR ) dlg . ShowModal ( ) dlg . Destroy ( ) for ( __ , key ) , val in zip ( params , vals ) : gpg_key_param_list . insert ( - 2 , ( key , val ) ) return dict ( gpg_key_param_list )
Displays parameter entry dialog and returns parameter dict
293
9
230,589
def get_dimensions_from_user ( self , no_dim ) : # Grid dimension dialog if no_dim != 3 : raise NotImplementedError ( _ ( "Currently, only 3D grids are supported." ) ) dim_dialog = DimensionsEntryDialog ( self . main_window ) if dim_dialog . ShowModal ( ) != wx . ID_OK : dim_dialog . Destroy ( ) return dim = tuple ( dim_dialog . dimensions ) dim_dialog . Destroy ( ) return dim
Queries grid dimensions in a model dialog and returns n - tuple
113
13
230,590
def get_preferences_from_user ( self ) : dlg = PreferencesDialog ( self . main_window ) change_choice = dlg . ShowModal ( ) preferences = { } if change_choice == wx . ID_OK : for ( parameter , _ ) , ctrl in zip ( dlg . parameters , dlg . textctrls ) : if isinstance ( ctrl , wx . Choice ) : value = ctrl . GetStringSelection ( ) if value : preferences [ parameter ] = repr ( value ) else : preferences [ parameter ] = repr ( ctrl . Value ) dlg . Destroy ( ) return preferences
Launches preferences dialog and returns dict with preferences
142
9
230,591
def get_save_request_from_user ( self ) : msg = _ ( "There are unsaved changes.\nDo you want to save?" ) dlg = GMD . GenericMessageDialog ( self . main_window , msg , _ ( "Unsaved changes" ) , wx . YES_NO | wx . ICON_QUESTION | wx . CANCEL ) save_choice = dlg . ShowModal ( ) dlg . Destroy ( ) if save_choice == wx . ID_YES : return True elif save_choice == wx . ID_NO : return False
Queries user if grid should be saved
135
8
230,592
def get_filepath_findex_from_user ( self , wildcard , message , style , filterindex = 0 ) : dlg = wx . FileDialog ( self . main_window , wildcard = wildcard , message = message , style = style , defaultDir = os . getcwd ( ) , defaultFile = "" ) # Set the initial filterindex dlg . SetFilterIndex ( filterindex ) filepath = None filter_index = None if dlg . ShowModal ( ) == wx . ID_OK : filepath = dlg . GetPath ( ) filter_index = dlg . GetFilterIndex ( ) dlg . Destroy ( ) return filepath , filter_index
Opens a file dialog and returns filepath and filterindex
156
12
230,593
def display_warning ( self , message , short_message , style = wx . OK | wx . ICON_WARNING ) : dlg = GMD . GenericMessageDialog ( self . main_window , message , short_message , style ) dlg . ShowModal ( ) dlg . Destroy ( )
Displays a warning message
70
5
230,594
def get_warning_choice ( self , message , short_message , style = wx . YES_NO | wx . NO_DEFAULT | wx . ICON_WARNING ) : dlg = GMD . GenericMessageDialog ( self . main_window , message , short_message , style ) choice = dlg . ShowModal ( ) dlg . Destroy ( ) return choice == wx . ID_YES
Launches proceeding dialog and returns True if ok to proceed
93
11
230,595
def get_print_setup ( self , print_data ) : psd = wx . PageSetupDialogData ( print_data ) # psd.EnablePrinter(False) psd . CalculatePaperSizeFromId ( ) dlg = wx . PageSetupDialog ( self . main_window , psd ) dlg . ShowModal ( ) # this makes a copy of the wx.PrintData instead of just saving # a reference to the one inside the PrintDialogData that will # be destroyed when the dialog is destroyed data = dlg . GetPageSetupData ( ) new_print_data = wx . PrintData ( data . GetPrintData ( ) ) new_print_data . PaperId = data . PaperId new_print_data . PaperSize = data . PaperSize dlg . Destroy ( ) return new_print_data
Opens print setup dialog and returns print_data
187
10
230,596
def get_csv_import_info ( self , path ) : csvfilename = os . path . split ( path ) [ 1 ] try : filterdlg = CsvImportDialog ( self . main_window , csvfilepath = path ) except csv . Error , err : # Display modal warning dialog msg = _ ( "'{filepath}' does not seem to be a valid CSV file.\n \n" "Opening it yielded the error:\n{error}" ) msg = msg . format ( filepath = csvfilename , error = err ) short_msg = _ ( 'Error reading CSV file' ) self . display_warning ( msg , short_msg ) return if filterdlg . ShowModal ( ) == wx . ID_OK : dialect , has_header = filterdlg . csvwidgets . get_dialect ( ) digest_types = filterdlg . grid . dtypes encoding = filterdlg . csvwidgets . encoding else : filterdlg . Destroy ( ) return filterdlg . Destroy ( ) return dialect , has_header , digest_types , encoding
Launches the csv dialog and returns csv_info
239
12
230,597
def get_csv_export_info ( self , preview_data ) : preview_rows = 100 preview_cols = 100 export_preview = list ( list ( islice ( col , None , preview_cols ) ) for col in islice ( preview_data , None , preview_rows ) ) filterdlg = CsvExportDialog ( self . main_window , data = export_preview ) if filterdlg . ShowModal ( ) == wx . ID_OK : dialect , has_header = filterdlg . csvwidgets . get_dialect ( ) digest_types = [ types . StringType ] else : filterdlg . Destroy ( ) return filterdlg . Destroy ( ) return dialect , has_header , digest_types
Shows csv export preview dialog and returns csv_info
166
13
230,598
def get_cairo_export_info ( self , filetype ) : export_dlg = CairoExportDialog ( self . main_window , filetype = filetype ) if export_dlg . ShowModal ( ) == wx . ID_OK : info = export_dlg . get_info ( ) export_dlg . Destroy ( ) return info else : export_dlg . Destroy ( )
Shows Cairo export dialog and returns info
88
8
230,599
def get_int_from_user ( self , title = "Enter integer value" , cond_func = lambda i : i is not None ) : is_integer = False while not is_integer : dlg = wx . TextEntryDialog ( None , title , title ) if dlg . ShowModal ( ) == wx . ID_OK : result = dlg . GetValue ( ) else : return None dlg . Destroy ( ) try : integer = int ( result ) if cond_func ( integer ) : is_integer = True except ValueError : pass return integer
Opens an integer entry dialog and returns integer
127
9