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,700 | def get_below_left_key_rect ( self ) : key_left = self . row , self . col - 1 , self . tab key_below_left = self . row + 1 , self . col - 1 , self . tab border_width_right = float ( self . cell_attributes [ key_below_left ] [ "borderwidth_right" ] ) / 2.0 border_width_bottom = float ( self . cell_attributes [ key_left ] [ "borderwidth_bottom" ] ) / 2.0 rect_below_left = ( self . x - border_width_right , self . y - self . height , border_width_right , border_width_bottom ) return key_below_left , rect_below_left | Returns tuple key rect of below left cell | 167 | 8 |
230,701 | def get_below_right_key_rect ( self ) : key_below_right = self . row + 1 , self . col + 1 , self . tab border_width_right = float ( self . cell_attributes [ self . key ] [ "borderwidth_right" ] ) / 2.0 border_width_bottom = float ( self . cell_attributes [ self . key ] [ "borderwidth_bottom" ] ) / 2.0 rect_below_right = ( self . x + self . width , self . y - self . height , border_width_right , border_width_bottom ) return key_below_right , rect_below_right | Returns tuple key rect of below right cell | 146 | 8 |
230,702 | def _get_bottom_line_coordinates ( self ) : rect_x , rect_y , rect_width , rect_height = self . rect start_point = rect_x , rect_y + rect_height end_point = rect_x + rect_width , rect_y + rect_height return start_point , end_point | Returns start and stop coordinates of bottom line | 75 | 8 |
230,703 | def _get_bottom_line_color ( self ) : color = self . cell_attributes [ self . key ] [ "bordercolor_bottom" ] return tuple ( c / 255.0 for c in color_pack2rgb ( color ) ) | Returns color rgb tuple of bottom line | 57 | 7 |
230,704 | def _get_right_line_color ( self ) : color = self . cell_attributes [ self . key ] [ "bordercolor_right" ] return tuple ( c / 255.0 for c in color_pack2rgb ( color ) ) | Returns color rgb tuple of right line | 57 | 7 |
230,705 | def get_b ( self ) : start_point , end_point = self . _get_bottom_line_coordinates ( ) width = self . _get_bottom_line_width ( ) color = self . _get_bottom_line_color ( ) return CellBorder ( start_point , end_point , width , color ) | Returns the bottom border of the cell | 73 | 7 |
230,706 | def get_r ( self ) : start_point , end_point = self . _get_right_line_coordinates ( ) width = self . _get_right_line_width ( ) color = self . _get_right_line_color ( ) return CellBorder ( start_point , end_point , width , color ) | Returns the right border of the cell | 73 | 7 |
230,707 | def get_t ( self ) : cell_above = CellBorders ( self . cell_attributes , * self . cell . get_above_key_rect ( ) ) return cell_above . get_b ( ) | Returns the top border of the cell | 48 | 7 |
230,708 | def get_l ( self ) : cell_left = CellBorders ( self . cell_attributes , * self . cell . get_left_key_rect ( ) ) return cell_left . get_r ( ) | Returns the left border of the cell | 48 | 7 |
230,709 | def get_tl ( self ) : cell_above_left = CellBorders ( self . cell_attributes , * self . cell . get_above_left_key_rect ( ) ) return cell_above_left . get_r ( ) | Returns the top left border of the cell | 54 | 8 |
230,710 | def get_tr ( self ) : cell_above = CellBorders ( self . cell_attributes , * self . cell . get_above_key_rect ( ) ) return cell_above . get_r ( ) | Returns the top right border of the cell | 48 | 8 |
230,711 | def get_rt ( self ) : cell_above_right = CellBorders ( self . cell_attributes , * self . cell . get_above_right_key_rect ( ) ) return cell_above_right . get_b ( ) | Returns the right top border of the cell | 54 | 8 |
230,712 | def get_rb ( self ) : cell_right = CellBorders ( self . cell_attributes , * self . cell . get_right_key_rect ( ) ) return cell_right . get_b ( ) | Returns the right bottom border of the cell | 48 | 8 |
230,713 | def get_br ( self ) : cell_below = CellBorders ( self . cell_attributes , * self . cell . get_below_key_rect ( ) ) return cell_below . get_r ( ) | Returns the bottom right border of the cell | 48 | 8 |
230,714 | def get_bl ( self ) : cell_below_left = CellBorders ( self . cell_attributes , * self . cell . get_below_left_key_rect ( ) ) return cell_below_left . get_r ( ) | Returns the bottom left border of the cell | 54 | 8 |
230,715 | def get_lb ( self ) : cell_left = CellBorders ( self . cell_attributes , * self . cell . get_left_key_rect ( ) ) return cell_left . get_b ( ) | Returns the left bottom border of the cell | 48 | 8 |
230,716 | def get_lt ( self ) : cell_above_left = CellBorders ( self . cell_attributes , * self . cell . get_above_left_key_rect ( ) ) return cell_above_left . get_b ( ) | Returns the left top border of the cell | 54 | 8 |
230,717 | def gen_all ( self ) : borderfuncs = [ self . get_b , self . get_r , self . get_t , self . get_l , self . get_tl , self . get_tr , self . get_rt , self . get_rb , self . get_br , self . get_bl , self . get_lb , self . get_lt , ] for borderfunc in borderfuncs : yield borderfunc ( ) | Generator of all borders | 99 | 5 |
230,718 | def draw ( self ) : # Lines should have a square cap to avoid ugly edges self . context . set_line_cap ( cairo . LINE_CAP_SQUARE ) self . context . save ( ) self . context . rectangle ( * self . rect ) self . context . clip ( ) cell_borders = CellBorders ( self . cell_attributes , self . key , self . rect ) borders = list ( cell_borders . gen_all ( ) ) borders . sort ( key = attrgetter ( 'width' , 'color' ) ) for border in borders : border . draw ( self . context ) self . context . restore ( ) | Draws cell border to context | 142 | 6 |
230,719 | def _draw_cursor ( self , dc , grid , row , col , pen = None , brush = None ) : # If in full screen mode draw no cursor if grid . main_window . IsFullScreen ( ) : return key = row , col , grid . current_table rect = grid . CellToRect ( row , col ) rect = self . get_merged_rect ( grid , key , rect ) # Check if cell is invisible if rect is None : return size = self . get_zoomed_size ( 1.0 ) caret_length = int ( min ( [ rect . width , rect . height ] ) / 5.0 ) color = get_color ( config [ "text_color" ] ) if pen is None : pen = wx . Pen ( color ) if brush is None : brush = wx . Brush ( color ) pen . SetWidth ( size ) # Inner right and lower borders border_left = rect . x + size - 1 border_right = rect . x + rect . width - size - 1 border_upper = rect . y + size - 1 border_lower = rect . y + rect . height - size - 1 points_lr = [ ( border_right , border_lower - caret_length ) , ( border_right , border_lower ) , ( border_right - caret_length , border_lower ) , ( border_right , border_lower ) , ] points_ur = [ ( border_right , border_upper + caret_length ) , ( border_right , border_upper ) , ( border_right - caret_length , border_upper ) , ( border_right , border_upper ) , ] points_ul = [ ( border_left , border_upper + caret_length ) , ( border_left , border_upper ) , ( border_left + caret_length , border_upper ) , ( border_left , border_upper ) , ] points_ll = [ ( border_left , border_lower - caret_length ) , ( border_left , border_lower ) , ( border_left + caret_length , border_lower ) , ( border_left , border_lower ) , ] point_list = [ points_lr , points_ur , points_ul , points_ll ] dc . DrawPolygonList ( point_list , pens = pen , brushes = brush ) self . old_cursor_row_col = row , col | Draws cursor as Rectangle in lower right corner | 527 | 10 |
230,720 | def update_cursor ( self , dc , grid , row , col ) : old_row , old_col = self . old_cursor_row_col bgcolor = get_color ( config [ "background_color" ] ) self . _draw_cursor ( dc , grid , old_row , old_col , pen = wx . Pen ( bgcolor ) , brush = wx . Brush ( bgcolor ) ) self . _draw_cursor ( dc , grid , row , col ) | Whites out the old cursor and draws the new one | 112 | 11 |
230,721 | def get_merged_rect ( self , grid , key , rect ) : row , col , tab = key # Check if cell is merged: cell_attributes = grid . code_array . cell_attributes merge_area = cell_attributes [ ( row , col , tab ) ] [ "merge_area" ] if merge_area is None : return rect else : # We have a merged cell top , left , bottom , right = merge_area # Are we drawing the top left cell? if top == row and left == col : # Set rect to merge area ul_rect = grid . CellToRect ( row , col ) br_rect = grid . CellToRect ( bottom , right ) width = br_rect . x - ul_rect . x + br_rect . width height = br_rect . y - ul_rect . y + br_rect . height rect = wx . Rect ( ul_rect . x , ul_rect . y , width , height ) return rect | Returns cell rect for normal or merged cells and None for merged | 214 | 12 |
230,722 | def _get_drawn_rect ( self , grid , key , rect ) : rect = self . get_merged_rect ( grid , key , rect ) if rect is None : # Merged cell is drawn if grid . is_merged_cell_drawn ( key ) : # Merging cell is outside view row , col , __ = key = self . get_merging_cell ( grid , key ) rect = grid . CellToRect ( row , col ) rect = self . get_merged_rect ( grid , key , rect ) else : return return rect | Replaces drawn rect if the one provided by wx is incorrect | 122 | 13 |
230,723 | def _get_draw_cache_key ( self , grid , key , drawn_rect , is_selected ) : row , col , tab = key cell_attributes = grid . code_array . cell_attributes zoomed_width = drawn_rect . width / self . zoom zoomed_height = drawn_rect . height / self . zoom # Button cells shall not be executed for preview if grid . code_array . cell_attributes [ key ] [ "button_cell" ] : cell_preview = repr ( grid . code_array ( key ) ) [ : 100 ] __id = id ( grid . code_array ( key ) ) else : cell_preview = repr ( grid . code_array [ key ] ) [ : 100 ] __id = id ( grid . code_array [ key ] ) sorted_keys = sorted ( grid . code_array . cell_attributes [ key ] . iteritems ( ) ) key_above_left = row - 1 , col - 1 , tab key_above = row - 1 , col , tab key_above_right = row - 1 , col + 1 , tab key_left = row , col - 1 , tab key_right = row , col + 1 , tab key_below_left = row + 1 , col - 1 , tab key_below = row + 1 , col , tab borders = [ ] for k in [ key , key_above_left , key_above , key_above_right , key_left , key_right , key_below_left , key_below ] : borders . append ( cell_attributes [ k ] [ "borderwidth_bottom" ] ) borders . append ( cell_attributes [ k ] [ "borderwidth_right" ] ) borders . append ( cell_attributes [ k ] [ "bordercolor_bottom" ] ) borders . append ( cell_attributes [ k ] [ "bordercolor_right" ] ) return ( zoomed_width , zoomed_height , is_selected , cell_preview , __id , tuple ( sorted_keys ) , tuple ( borders ) ) | Returns key for the screen draw cache | 455 | 7 |
230,724 | def _get_cairo_bmp ( self , mdc , key , rect , is_selected , view_frozen ) : bmp = wx . EmptyBitmap ( rect . width , rect . height ) mdc . SelectObject ( bmp ) mdc . SetBackgroundMode ( wx . SOLID ) mdc . SetBackground ( wx . WHITE_BRUSH ) mdc . Clear ( ) mdc . SetDeviceOrigin ( 0 , 0 ) context = wx . lib . wxcairo . ContextFromDC ( mdc ) context . save ( ) # Zoom context zoom = self . zoom context . scale ( zoom , zoom ) # Set off cell renderer by 1/2 a pixel to avoid blurry lines rect_tuple = - 0.5 , - 0.5 , rect . width / zoom + 0.5 , rect . height / zoom + 0.5 spell_check = config [ "check_spelling" ] cell_renderer = GridCellCairoRenderer ( context , self . data_array , key , rect_tuple , view_frozen , spell_check = spell_check ) # Draw cell cell_renderer . draw ( ) # Draw selection if present if is_selected : context . set_source_rgba ( * self . selection_color_tuple ) context . rectangle ( * rect_tuple ) context . fill ( ) context . restore ( ) return bmp | Returns a wx . Bitmap of cell key in size rect | 306 | 13 |
230,725 | def Draw ( self , grid , attr , dc , rect , row , col , isSelected ) : key = row , col , grid . current_table # If cell is merge draw the merging cell if invisibile if grid . code_array . cell_attributes [ key ] [ "merge_area" ] : key = self . get_merging_cell ( grid , key ) drawn_rect = self . _get_drawn_rect ( grid , key , rect ) if drawn_rect is None : return cell_cache_key = self . _get_draw_cache_key ( grid , key , drawn_rect , isSelected ) mdc = wx . MemoryDC ( ) if vlc is not None and key in self . video_cells and grid . code_array . cell_attributes [ key ] [ "panel_cell" ] : # Update video position of previously created video panel self . video_cells [ key ] . SetClientRect ( drawn_rect ) elif cell_cache_key in self . cell_cache : mdc . SelectObject ( self . cell_cache [ cell_cache_key ] ) else : code = grid . code_array ( key ) if vlc is not None and code is not None and grid . code_array . cell_attributes [ key ] [ "panel_cell" ] : try : # A panel is to be displayed panel_cls = grid . code_array [ key ] # Assert that we have a subclass of a wxPanel that we # can instantiate assert issubclass ( panel_cls , wx . Panel ) video_panel = panel_cls ( grid ) video_panel . SetClientRect ( drawn_rect ) # Register video cell self . video_cells [ key ] = video_panel return except Exception , err : # Someting is wrong with the panel to be displayed post_command_event ( grid . main_window , self . StatusBarMsg , text = unicode ( err ) ) bmp = self . _get_cairo_bmp ( mdc , key , drawn_rect , isSelected , grid . _view_frozen ) else : bmp = self . _get_cairo_bmp ( mdc , key , drawn_rect , isSelected , grid . _view_frozen ) # Put resulting bmp into cache self . cell_cache [ cell_cache_key ] = bmp dc . Blit ( drawn_rect . x , drawn_rect . y , drawn_rect . width , drawn_rect . height , mdc , 0 , 0 , wx . COPY ) # Draw cursor if grid . actions . cursor [ : 2 ] == ( row , col ) : self . update_cursor ( dc , grid , row , col ) | Draws the cell border and content using pycairo | 601 | 11 |
230,726 | def choose_key ( gpg_private_keys ) : uid_strings_fp = [ ] uid_string_fp2key = { } current_key_index = None for i , key in enumerate ( gpg_private_keys ) : fingerprint = key [ 'fingerprint' ] if fingerprint == config [ "gpg_key_fingerprint" ] : current_key_index = i for uid_string in key [ 'uids' ] : uid_string_fp = '"' + uid_string + ' (' + fingerprint + ')' uid_strings_fp . append ( uid_string_fp ) uid_string_fp2key [ uid_string_fp ] = key msg = _ ( 'Choose a GPG key for signing pyspread save files.\n' 'The GPG key must not have a passphrase set.' ) dlg = wx . SingleChoiceDialog ( None , msg , _ ( 'Choose key' ) , uid_strings_fp , wx . CHOICEDLG_STYLE ) childlist = list ( dlg . GetChildren ( ) ) childlist [ - 3 ] . SetLabel ( _ ( "Use chosen key" ) ) childlist [ - 2 ] . SetLabel ( _ ( "Create new key" ) ) if current_key_index is not None : # Set choice to current key dlg . SetSelection ( current_key_index ) if dlg . ShowModal ( ) == wx . ID_OK : uid_string_fp = dlg . GetStringSelection ( ) key = uid_string_fp2key [ uid_string_fp ] else : key = None dlg . Destroy ( ) return key | Displays gpg key choice and returns key | 384 | 9 |
230,727 | def _register_key ( fingerprint , gpg ) : for private_key in gpg . list_keys ( True ) : try : if str ( fingerprint ) == private_key [ 'fingerprint' ] : config [ "gpg_key_fingerprint" ] = repr ( private_key [ 'fingerprint' ] ) except KeyError : pass | Registers key in config | 75 | 5 |
230,728 | def has_no_password ( gpg_secret_keyid ) : if gnupg is None : return False gpg = gnupg . GPG ( ) s = gpg . sign ( "" , keyid = gpg_secret_keyid , passphrase = "" ) try : return s . status == "signature created" except AttributeError : # This may happen on Windows if hasattr ( s , "stderr" ) : return "GOOD_PASSPHRASE" in s . stderr | Returns True iif gpg_secret_key has a password | 114 | 13 |
230,729 | def genkey ( key_name = None ) : if gnupg is None : return gpg_key_param_list = [ ( 'key_type' , 'DSA' ) , ( 'key_length' , '2048' ) , ( 'subkey_type' , 'ELG-E' ) , ( 'subkey_length' , '2048' ) , ( 'expire_date' , '0' ) , ] gpg = gnupg . GPG ( ) gpg . encoding = 'utf-8' # Check if standard key is already present pyspread_key_fingerprint = config [ "gpg_key_fingerprint" ] gpg_private_keys = [ key for key in gpg . list_keys ( secret = True ) if has_no_password ( key [ "keyid" ] ) ] gpg_private_fingerprints = [ key [ 'fingerprint' ] for key in gpg . list_keys ( secret = True ) if has_no_password ( key [ "keyid" ] ) ] pyspread_key = None for private_key , fingerprint in zip ( gpg_private_keys , gpg_private_fingerprints ) : if str ( pyspread_key_fingerprint ) == fingerprint : pyspread_key = private_key if gpg_private_keys : # If GPG are available, choose one pyspread_key = choose_key ( gpg_private_keys ) if pyspread_key : # A key has been chosen config [ "gpg_key_fingerprint" ] = repr ( pyspread_key [ 'fingerprint' ] ) else : # No key has been chosen --> Create new one if key_name is None : gpg_key_parameters = get_key_params_from_user ( gpg_key_param_list ) if gpg_key_parameters is None : # No name entered return else : gpg_key_param_list . append ( ( 'name_real' , '{key_name}' . format ( key_name = key_name ) ) ) gpg_key_parameters = dict ( gpg_key_param_list ) input_data = gpg . gen_key_input ( * * gpg_key_parameters ) # Generate key # ------------ if key_name is None : # Show information dialog style = wx . ICON_INFORMATION | wx . DIALOG_NO_PARENT | wx . OK | wx . CANCEL pyspread_key_uid = gpg_key_parameters [ "name_real" ] short_message = _ ( "New GPG key" ) . format ( pyspread_key_uid ) message = _ ( "After confirming this dialog, a new GPG key " ) + _ ( "'{key}' will be generated." ) . format ( key = pyspread_key_uid ) + _ ( " \n \nThis may take some time.\nPlease wait." ) dlg = wx . MessageDialog ( None , message , short_message , style ) dlg . Centre ( ) if dlg . ShowModal ( ) == wx . ID_OK : dlg . Destroy ( ) gpg_key = gpg . gen_key ( input_data ) _register_key ( gpg_key , gpg ) fingerprint = gpg_key . fingerprint else : dlg . Destroy ( ) return else : gpg_key = gpg . gen_key ( input_data ) _register_key ( gpg_key , gpg ) fingerprint = gpg_key . fingerprint return fingerprint | Creates a new standard GPG key | 809 | 8 |
230,730 | def fingerprint2keyid ( fingerprint ) : if gnupg is None : return gpg = gnupg . GPG ( ) private_keys = gpg . list_keys ( True ) keyid = None for private_key in private_keys : if private_key [ 'fingerprint' ] == config [ "gpg_key_fingerprint" ] : keyid = private_key [ 'keyid' ] break return keyid | Returns keyid from fingerprint for private keys | 94 | 8 |
230,731 | def sign ( filename ) : if gnupg is None : return gpg = gnupg . GPG ( ) with open ( filename , "rb" ) as signfile : keyid = fingerprint2keyid ( config [ "gpg_key_fingerprint" ] ) if keyid is None : msg = "No private key for GPG fingerprint '{}'." raise ValueError ( msg . format ( config [ "gpg_key_fingerprint" ] ) ) signed_data = gpg . sign_file ( signfile , keyid = keyid , detach = True ) return signed_data | Returns detached signature for file | 129 | 5 |
230,732 | def verify ( sigfilename , filefilename = None ) : if gnupg is None : return False gpg = gnupg . GPG ( ) with open ( sigfilename , "rb" ) as sigfile : verified = gpg . verify_file ( sigfile , filefilename ) pyspread_keyid = fingerprint2keyid ( config [ "gpg_key_fingerprint" ] ) if verified . valid and verified . key_id == pyspread_keyid : return True return False | Verifies a signature returns True if successful else False . | 108 | 11 |
230,733 | def _len_table_cache ( self ) : length = 0 for table in self . _table_cache : length += len ( self . _table_cache [ table ] ) return length | Returns the length of the table cache | 40 | 7 |
230,734 | def _update_table_cache ( self ) : self . _table_cache . clear ( ) for sel , tab , val in self : try : self . _table_cache [ tab ] . append ( ( sel , val ) ) except KeyError : self . _table_cache [ tab ] = [ ( sel , val ) ] assert len ( self ) == self . _len_table_cache ( ) | Clears and updates the table cache to be in sync with self | 90 | 13 |
230,735 | def get_merging_cell ( self , key ) : row , col , tab = key # Is cell merged merge_area = self [ key ] [ "merge_area" ] if merge_area : return merge_area [ 0 ] , merge_area [ 1 ] , tab | Returns key of cell that merges the cell key | 61 | 10 |
230,736 | def _get_data ( self ) : data = { } data [ "shape" ] = self . shape data [ "grid" ] = { } . update ( self . dict_grid ) data [ "attributes" ] = [ ca for ca in self . cell_attributes ] data [ "row_heights" ] = self . row_heights data [ "col_widths" ] = self . col_widths data [ "macros" ] = self . macros return data | Returns dict of data content . | 106 | 6 |
230,737 | def _set_data ( self , * * kwargs ) : if "shape" in kwargs : self . shape = kwargs [ "shape" ] if "grid" in kwargs : self . dict_grid . clear ( ) self . dict_grid . update ( kwargs [ "grid" ] ) if "attributes" in kwargs : self . attributes [ : ] = kwargs [ "attributes" ] if "row_heights" in kwargs : self . row_heights = kwargs [ "row_heights" ] if "col_widths" in kwargs : self . col_widths = kwargs [ "col_widths" ] if "macros" in kwargs : self . macros = kwargs [ "macros" ] | Sets data from given parameters | 180 | 6 |
230,738 | def get_row_height ( self , row , tab ) : try : return self . row_heights [ ( row , tab ) ] except KeyError : return config [ "default_row_height" ] | Returns row height | 45 | 3 |
230,739 | def get_col_width ( self , col , tab ) : try : return self . col_widths [ ( col , tab ) ] except KeyError : return config [ "default_col_width" ] | Returns column width | 45 | 3 |
230,740 | def _set_shape ( self , shape ) : # Delete each cell that is beyond new borders old_shape = self . shape deleted_cells = { } if any ( new_axis < old_axis for new_axis , old_axis in zip ( shape , old_shape ) ) : for key in self . dict_grid . keys ( ) : if any ( key_ele >= new_axis for key_ele , new_axis in zip ( key , shape ) ) : deleted_cells [ key ] = self . pop ( key ) # Set dict_grid shape attribute self . dict_grid . shape = shape self . _adjust_rowcol ( 0 , 0 , 0 ) self . _adjust_cell_attributes ( 0 , 0 , 0 ) # Undo actions yield "_set_shape" self . shape = old_shape for key in deleted_cells : self [ key ] = deleted_cells [ key ] | Deletes all cells beyond new shape and sets dict_grid shape | 196 | 13 |
230,741 | def get_last_filled_cell ( self , table = None ) : maxrow = 0 maxcol = 0 for row , col , tab in self . dict_grid : if table is None or tab == table : maxrow = max ( row , maxrow ) maxcol = max ( col , maxcol ) return maxrow , maxcol , table | Returns key for the bottommost rightmost cell with content | 74 | 11 |
230,742 | def cell_array_generator ( self , key ) : for i , key_ele in enumerate ( key ) : # Get first element of key that is a slice if type ( key_ele ) is SliceType : slc_keys = xrange ( * key_ele . indices ( self . dict_grid . shape [ i ] ) ) key_list = list ( key ) key_list [ i ] = None has_subslice = any ( type ( ele ) is SliceType for ele in key_list ) for slc_key in slc_keys : key_list [ i ] = slc_key if has_subslice : # If there is a slice left yield generator yield self . cell_array_generator ( key_list ) else : # No slices? Yield value yield self [ tuple ( key_list ) ] break | Generator traversing cells specified in key | 184 | 8 |
230,743 | def _shift_rowcol ( self , insertion_point , no_to_insert ) : # Shift row heights new_row_heights = { } del_row_heights = [ ] for row , tab in self . row_heights : if tab > insertion_point : new_row_heights [ ( row , tab + no_to_insert ) ] = self . row_heights [ ( row , tab ) ] del_row_heights . append ( ( row , tab ) ) for row , tab in new_row_heights : self . set_row_height ( row , tab , new_row_heights [ ( row , tab ) ] ) for row , tab in del_row_heights : if ( row , tab ) not in new_row_heights : self . set_row_height ( row , tab , None ) # Shift column widths new_col_widths = { } del_col_widths = [ ] for col , tab in self . col_widths : if tab > insertion_point : new_col_widths [ ( col , tab + no_to_insert ) ] = self . col_widths [ ( col , tab ) ] del_col_widths . append ( ( col , tab ) ) for col , tab in new_col_widths : self . set_col_width ( col , tab , new_col_widths [ ( col , tab ) ] ) for col , tab in del_col_widths : if ( col , tab ) not in new_col_widths : self . set_col_width ( col , tab , None ) | Shifts row and column sizes when a table is inserted or deleted | 357 | 13 |
230,744 | def _get_adjusted_merge_area ( self , attrs , insertion_point , no_to_insert , axis ) : assert axis in range ( 2 ) if "merge_area" not in attrs or attrs [ "merge_area" ] is None : return top , left , bottom , right = attrs [ "merge_area" ] selection = Selection ( [ ( top , left ) ] , [ ( bottom , right ) ] , [ ] , [ ] , [ ] ) selection . insert ( insertion_point , no_to_insert , axis ) __top , __left = selection . block_tl [ 0 ] __bottom , __right = selection . block_br [ 0 ] # Adjust merge area if it is beyond the grid shape rows , cols , tabs = self . shape if __top < 0 and __bottom < 0 or __top >= rows and __bottom >= rows or __left < 0 and __right < 0 or __left >= cols and __right >= cols : return if __top < 0 : __top = 0 if __top >= rows : __top = rows - 1 if __bottom < 0 : __bottom = 0 if __bottom >= rows : __bottom = rows - 1 if __left < 0 : __left = 0 if __left >= cols : __left = cols - 1 if __right < 0 : __right = 0 if __right >= cols : __right = cols - 1 return __top , __left , __bottom , __right | Returns updated merge area | 322 | 4 |
230,745 | def set_row_height ( self , row , tab , height ) : try : old_height = self . row_heights . pop ( ( row , tab ) ) except KeyError : old_height = None if height is not None : self . row_heights [ ( row , tab ) ] = float ( height ) | Sets row height | 70 | 4 |
230,746 | def set_col_width ( self , col , tab , width ) : try : old_width = self . col_widths . pop ( ( col , tab ) ) except KeyError : old_width = None if width is not None : self . col_widths [ ( col , tab ) ] = float ( width ) | Sets column width | 70 | 4 |
230,747 | def _make_nested_list ( self , gen ) : res = [ ] for ele in gen : if ele is None : res . append ( None ) elif not is_string_like ( ele ) and is_generator_like ( ele ) : # Nested generator res . append ( self . _make_nested_list ( ele ) ) else : res . append ( ele ) return res | Makes nested list from generator for creating numpy . array | 87 | 12 |
230,748 | def _get_assignment_target_end ( self , ast_module ) : if len ( ast_module . body ) > 1 : raise ValueError ( "More than one expression or assignment." ) elif len ( ast_module . body ) > 0 and type ( ast_module . body [ 0 ] ) is ast . Assign : if len ( ast_module . body [ 0 ] . targets ) != 1 : raise ValueError ( "More than one assignment target." ) else : return len ( ast_module . body [ 0 ] . targets [ 0 ] . id ) return - 1 | Returns position of 1st char after assignment traget . | 126 | 12 |
230,749 | def _get_updated_environment ( self , env_dict = None ) : if env_dict is None : env_dict = { 'S' : self } env = globals ( ) . copy ( ) env . update ( env_dict ) return env | Returns globals environment with magic variable | 55 | 7 |
230,750 | def _eval_cell ( self , key , code ) : # Flatten helper function def nn ( val ) : """Returns flat numpy arraz without None values""" try : return numpy . array ( filter ( None , val . flat ) ) except AttributeError : # Probably no numpy array return numpy . array ( filter ( None , val ) ) # Set up environment for evaluation env_dict = { 'X' : key [ 0 ] , 'Y' : key [ 1 ] , 'Z' : key [ 2 ] , 'bz2' : bz2 , 'base64' : base64 , 'charts' : charts , 'nn' : nn , 'R' : key [ 0 ] , 'C' : key [ 1 ] , 'T' : key [ 2 ] , 'S' : self , 'vlcpanel_factory' : vlcpanel_factory } env = self . _get_updated_environment ( env_dict = env_dict ) #_old_code = self(key) # Return cell value if in safe mode if self . safe_mode : return code # If cell is not present return None if code is None : return elif is_generator_like ( code ) : # We have a generator object return numpy . array ( self . _make_nested_list ( code ) , dtype = "O" ) # If only 1 term in front of the "=" --> global try : assignment_target_error = None module = ast . parse ( code ) assignment_target_end = self . _get_assignment_target_end ( module ) except ValueError , err : assignment_target_error = ValueError ( err ) except AttributeError , err : # Attribute Error includes RunTimeError assignment_target_error = AttributeError ( err ) except Exception , err : assignment_target_error = Exception ( err ) if assignment_target_error is None and assignment_target_end != - 1 : glob_var = code [ : assignment_target_end ] expression = code . split ( "=" , 1 ) [ 1 ] expression = expression . strip ( ) # Delete result cache because assignment changes results self . result_cache . clear ( ) else : glob_var = None expression = code if assignment_target_error is not None : result = assignment_target_error else : try : import signal signal . signal ( signal . SIGALRM , self . handler ) signal . alarm ( config [ "timeout" ] ) except : # No POSIX system pass try : result = eval ( expression , env , { } ) except AttributeError , err : # Attribute Error includes RunTimeError result = AttributeError ( err ) except RuntimeError , err : result = RuntimeError ( err ) except Exception , err : result = Exception ( err ) finally : try : signal . alarm ( 0 ) except : # No POSIX system pass # Change back cell value for evaluation from other cells #self.dict_grid[key] = _old_code if glob_var is not None : globals ( ) . update ( { glob_var : result } ) return result | Evaluates one cell and returns its result | 671 | 9 |
230,751 | def pop ( self , key ) : try : self . result_cache . pop ( repr ( key ) ) except KeyError : pass return DataArray . pop ( self , key ) | Pops dict_grid with undo and redo support | 38 | 11 |
230,752 | def reload_modules ( self ) : import src . lib . charts as charts from src . gui . grid_panels import vlcpanel_factory modules = [ charts , bz2 , base64 , re , ast , sys , wx , numpy , datetime ] for module in modules : reload ( module ) | Reloads modules that are available in cells | 68 | 9 |
230,753 | def clear_globals ( self ) : base_keys = [ 'cStringIO' , 'IntType' , 'KeyValueStore' , 'undoable' , 'is_generator_like' , 'is_string_like' , 'bz2' , 'base64' , '__package__' , 're' , 'config' , '__doc__' , 'SliceType' , 'CellAttributes' , 'product' , 'ast' , '__builtins__' , '__file__' , 'charts' , 'sys' , 'is_slice_like' , '__name__' , 'copy' , 'imap' , 'wx' , 'ifilter' , 'Selection' , 'DictGrid' , 'numpy' , 'CodeArray' , 'DataArray' , 'datetime' , 'vlcpanel_factory' ] for key in globals ( ) . keys ( ) : if key not in base_keys : globals ( ) . pop ( key ) | Clears all newly assigned globals | 228 | 7 |
230,754 | def execute_macros ( self ) : if self . safe_mode : return '' , "Safe mode activated. Code not executed." # Windows exec does not like Windows newline self . macros = self . macros . replace ( '\r\n' , '\n' ) # Set up environment for evaluation globals ( ) . update ( self . _get_updated_environment ( ) ) # Create file-like string to capture output code_out = cStringIO . StringIO ( ) code_err = cStringIO . StringIO ( ) err_msg = cStringIO . StringIO ( ) # Capture output and errors sys . stdout = code_out sys . stderr = code_err try : import signal signal . signal ( signal . SIGALRM , self . handler ) signal . alarm ( config [ "timeout" ] ) except : # No POSIX system pass try : exec ( self . macros , globals ( ) ) try : signal . alarm ( 0 ) except : # No POSIX system pass except Exception : # Print exception # (Because of how the globals are handled during execution # we must import modules here) from traceback import print_exception from src . lib . exception_handling import get_user_codeframe exc_info = sys . exc_info ( ) user_tb = get_user_codeframe ( exc_info [ 2 ] ) or exc_info [ 2 ] print_exception ( exc_info [ 0 ] , exc_info [ 1 ] , user_tb , None , err_msg ) # Restore stdout and stderr sys . stdout = sys . __stdout__ sys . stderr = sys . __stderr__ results = code_out . getvalue ( ) errs = code_err . getvalue ( ) + err_msg . getvalue ( ) code_out . close ( ) code_err . close ( ) # Reset result cache self . result_cache . clear ( ) # Reset frozen cache self . frozen_cache . clear ( ) return results , errs | Executes all macros and returns result string | 441 | 8 |
230,755 | def _sorted_keys ( self , keys , startkey , reverse = False ) : tuple_key = lambda t : t [ : : - 1 ] if reverse : tuple_cmp = lambda t : t [ : : - 1 ] > startkey [ : : - 1 ] else : tuple_cmp = lambda t : t [ : : - 1 ] < startkey [ : : - 1 ] searchkeys = sorted ( keys , key = tuple_key , reverse = reverse ) searchpos = sum ( 1 for _ in ifilter ( tuple_cmp , searchkeys ) ) searchkeys = searchkeys [ searchpos : ] + searchkeys [ : searchpos ] for key in searchkeys : yield key | Generator that yields sorted keys starting with startkey | 148 | 10 |
230,756 | def findnextmatch ( self , startkey , find_string , flags , search_result = True ) : assert "UP" in flags or "DOWN" in flags assert not ( "UP" in flags and "DOWN" in flags ) if search_result : def is_matching ( key , find_string , flags ) : code = self ( key ) if self . string_match ( code , find_string , flags ) is not None : return True else : res_str = unicode ( self [ key ] ) return self . string_match ( res_str , find_string , flags ) is not None else : def is_matching ( code , find_string , flags ) : code = self ( key ) return self . string_match ( code , find_string , flags ) is not None # List of keys in sgrid in search order reverse = "UP" in flags for key in self . _sorted_keys ( self . keys ( ) , startkey , reverse = reverse ) : try : if is_matching ( key , find_string , flags ) : return key except Exception : # re errors are cryptical: sre_constants,... pass | Returns a tuple with the position of the next match of find_string | 250 | 14 |
230,757 | def Validate ( self , win ) : val = self . GetWindow ( ) . GetValue ( ) for x in val : if x not in string . digits : return False return True | Returns True if Value in digits False otherwise | 39 | 8 |
230,758 | def OnChar ( self , event ) : key = event . GetKeyCode ( ) if key < wx . WXK_SPACE or key == wx . WXK_DELETE or key > 255 or chr ( key ) in string . digits : event . Skip ( ) | Eats event if key not in digits | 63 | 8 |
230,759 | def Draw ( self , grid , attr , dc , rect , row , col , is_selected ) : render = wx . RendererNative . Get ( ) # clear the background dc . SetBackgroundMode ( wx . SOLID ) if is_selected : dc . SetBrush ( wx . Brush ( wx . BLUE , wx . SOLID ) ) dc . SetPen ( wx . Pen ( wx . BLUE , 1 , wx . SOLID ) ) else : dc . SetBrush ( wx . Brush ( wx . WHITE , wx . SOLID ) ) dc . SetPen ( wx . Pen ( wx . WHITE , 1 , wx . SOLID ) ) dc . DrawRectangleRect ( rect ) cb_lbl = grid . GetCellValue ( row , col ) string_x = rect . x + 2 string_y = rect . y + 2 dc . DrawText ( cb_lbl , string_x , string_y ) button_x = rect . x + rect . width - self . iconwidth button_y = rect . y button_width = self . iconwidth button_height = rect . height button_size = button_x , button_y , button_width , button_height render . DrawComboBoxDropButton ( grid , dc , button_size , wx . CONTROL_CURRENT ) | Draws the text and the combobox icon | 298 | 10 |
230,760 | def _setup_param_widgets ( self ) : for parameter in self . csv_params : pname , ptype , plabel , phelp = parameter label = wx . StaticText ( self . parent , - 1 , plabel ) widget = self . type2widget [ ptype ] ( self . parent ) # Append choicebox items and bind handler if pname in self . choices : widget . AppendItems ( self . choices [ pname ] ) widget . SetValue = widget . Select widget . SetSelection ( 0 ) # Bind event handler to widget if ptype is types . StringType or ptype is types . UnicodeType : event_type = wx . EVT_TEXT elif ptype is types . BooleanType : event_type = wx . EVT_CHECKBOX else : event_type = wx . EVT_CHOICE handler = getattr ( self , self . widget_handlers [ pname ] ) self . parent . Bind ( event_type , handler , widget ) # Tool tips label . SetToolTipString ( phelp ) widget . SetToolTipString ( phelp ) label . __name__ = wx . StaticText . __name__ . lower ( ) widget . __name__ = self . type2widget [ ptype ] . __name__ . lower ( ) self . param_labels . append ( label ) self . param_widgets . append ( widget ) self . __setattr__ ( "_" . join ( [ label . __name__ , pname ] ) , label ) self . __setattr__ ( "_" . join ( [ widget . __name__ , pname ] ) , widget ) | Creates the parameter entry widgets and binds them to methods | 357 | 11 |
230,761 | def _do_layout ( self ) : sizer_csvoptions = wx . FlexGridSizer ( 5 , 4 , 5 , 5 ) # Adding parameter widgets to sizer_csvoptions leftpos = wx . LEFT | wx . ADJUST_MINSIZE rightpos = wx . RIGHT | wx . EXPAND current_label_margin = 0 # smaller for left column other_label_margin = 15 for label , widget in zip ( self . param_labels , self . param_widgets ) : sizer_csvoptions . Add ( label , 0 , leftpos , current_label_margin ) sizer_csvoptions . Add ( widget , 0 , rightpos , current_label_margin ) current_label_margin , other_label_margin = other_label_margin , current_label_margin sizer_csvoptions . AddGrowableCol ( 1 ) sizer_csvoptions . AddGrowableCol ( 3 ) self . sizer_csvoptions = sizer_csvoptions | Sizer hell returns a sizer that contains all widgets | 218 | 11 |
230,762 | def _update_settings ( self , dialect ) : # the first parameter is the dialect itself --> ignore for parameter in self . csv_params [ 2 : ] : pname , ptype , plabel , phelp = parameter widget = self . _widget_from_p ( pname , ptype ) if ptype is types . TupleType : ptype = types . ObjectType digest = Digest ( acceptable_types = [ ptype ] ) if pname == 'self.has_header' : if self . has_header is not None : widget . SetValue ( digest ( self . has_header ) ) else : value = getattr ( dialect , pname ) widget . SetValue ( digest ( value ) ) | Sets the widget settings to those of the chosen dialect | 153 | 11 |
230,763 | def _widget_from_p ( self , pname , ptype ) : widget_name = self . type2widget [ ptype ] . __name__ . lower ( ) widget_name = "_" . join ( [ widget_name , pname ] ) return getattr ( self , widget_name ) | Returns a widget from its ptype and pname | 66 | 10 |
230,764 | def OnDialectChoice ( self , event ) : dialect_name = event . GetString ( ) value = list ( self . choices [ 'dialects' ] ) . index ( dialect_name ) if dialect_name == 'sniffer' : if self . csvfilepath is None : event . Skip ( ) return None dialect , self . has_header = sniff ( self . csvfilepath ) elif dialect_name == 'user' : event . Skip ( ) return None else : dialect = csv . get_dialect ( dialect_name ) self . _update_settings ( dialect ) self . choice_dialects . SetValue ( value ) | Updates all param widgets confirming to the selcted dialect | 143 | 13 |
230,765 | def OnWidget ( self , event ) : self . choice_dialects . SetValue ( len ( self . choices [ 'dialects' ] ) - 1 ) event . Skip ( ) | Update the dialect widget to user | 41 | 6 |
230,766 | def get_dialect ( self ) : parameters = { } for parameter in self . csv_params [ 2 : ] : pname , ptype , plabel , phelp = parameter widget = self . _widget_from_p ( pname , ptype ) if ptype is types . StringType or ptype is types . UnicodeType : parameters [ pname ] = str ( widget . GetValue ( ) ) elif ptype is types . BooleanType : parameters [ pname ] = widget . GetValue ( ) elif pname == 'quoting' : choice = self . choices [ 'quoting' ] [ widget . GetSelection ( ) ] parameters [ pname ] = getattr ( csv , choice ) else : raise TypeError ( _ ( "{type} unknown." ) . format ( type = ptype ) ) has_header = parameters . pop ( "self.has_header" ) try : csv . register_dialect ( 'user' , * * parameters ) except TypeError , err : msg = _ ( "The dialect is invalid. \n " "\nError message:\n{msg}" ) . format ( msg = err ) dlg = wx . MessageDialog ( self . parent , msg , style = wx . ID_CANCEL ) dlg . ShowModal ( ) dlg . Destroy ( ) raise TypeError ( err ) return csv . get_dialect ( 'user' ) , has_header | Returns a new dialect that implements the current selection | 314 | 9 |
230,767 | def OnMouse ( self , event ) : self . SetGridCursor ( event . Row , event . Col ) self . EnableCellEditControl ( True ) event . Skip ( ) | Reduces clicks to enter an edit control | 38 | 8 |
230,768 | def OnGridEditorCreated ( self , event ) : editor = event . GetControl ( ) editor . Bind ( wx . EVT_KILL_FOCUS , self . OnGridEditorClosed ) event . Skip ( ) | Used to capture Editor close events | 49 | 6 |
230,769 | def OnGridEditorClosed ( self , event ) : try : dialect , self . has_header = self . parent . csvwidgets . get_dialect ( ) except TypeError : event . Skip ( ) return 0 self . fill_cells ( dialect , self . has_header , choices = False ) | Event handler for end of output type choice | 66 | 8 |
230,770 | def get_digest_keys ( self ) : digest_keys = [ ] for col in xrange ( self . GetNumberCols ( ) ) : digest_key = self . GetCellValue ( self . has_header , col ) if digest_key == "" : digest_key = self . digest_types . keys ( ) [ 0 ] digest_keys . append ( digest_key ) return digest_keys | Returns a list of the type choices | 88 | 7 |
230,771 | def OnButtonApply ( self , event ) : try : dialect , self . has_header = self . csvwidgets . get_dialect ( ) except TypeError : event . Skip ( ) return 0 self . preview_textctrl . fill ( data = self . data , dialect = dialect ) event . Skip ( ) | Updates the preview_textctrl | 68 | 7 |
230,772 | def _set_properties ( self ) : self . codetext_ctrl . SetToolTipString ( _ ( "Enter python code here." ) ) self . apply_button . SetToolTipString ( _ ( "Apply changes to current macro" ) ) self . splitter . SetBackgroundStyle ( wx . BG_STYLE_COLOUR ) self . result_ctrl . SetMinSize ( ( 10 , 10 ) ) | Setup title size and tooltips | 91 | 6 |
230,773 | def OnApply ( self , event ) : # See if we have valid python try : ast . parse ( self . macros ) except : # Grab the traceback and print it for the user s = StringIO ( ) e = exc_info ( ) # usr_tb will more than likely be none because ast throws # SytnaxErrorsas occurring outside of the current # execution frame usr_tb = get_user_codeframe ( e [ 2 ] ) or None print_exception ( e [ 0 ] , e [ 1 ] , usr_tb , None , s ) post_command_event ( self . parent , self . MacroErrorMsg , err = s . getvalue ( ) ) success = False else : self . result_ctrl . SetValue ( '' ) post_command_event ( self . parent , self . MacroReplaceMsg , macros = self . macros ) post_command_event ( self . parent , self . MacroExecuteMsg ) success = True event . Skip ( ) return success | Event handler for Apply button | 219 | 5 |
230,774 | def update_result_ctrl ( self , event ) : # Check to see if macro window still exists if not self : return printLen = 0 self . result_ctrl . SetValue ( '' ) if hasattr ( event , 'msg' ) : # Output of script (from print statements, for example) self . result_ctrl . AppendText ( event . msg ) printLen = len ( event . msg ) if hasattr ( event , 'err' ) : # Error messages errLen = len ( event . err ) errStyle = wx . TextAttr ( wx . RED ) self . result_ctrl . AppendText ( event . err ) self . result_ctrl . SetStyle ( printLen , printLen + errLen , errStyle ) if not hasattr ( event , 'err' ) or event . err == '' : # No error passed. Close dialog if user requested it. if self . _ok_pressed : self . Destroy ( ) self . _ok_pressed = False | Update event result following execution by main window | 211 | 8 |
230,775 | def _ondim ( self , dimension , valuestring ) : try : self . dimensions [ dimension ] = int ( valuestring ) except ValueError : self . dimensions [ dimension ] = 1 self . textctrls [ dimension ] . SetValue ( str ( 1 ) ) if self . dimensions [ dimension ] < 1 : self . dimensions [ dimension ] = 1 self . textctrls [ dimension ] . SetValue ( str ( 1 ) ) | Converts valuestring to int and assigns result to self . dim | 95 | 15 |
230,776 | def OnOk ( self , event ) : # Get key values from textctrls key_strings = [ self . row_textctrl . GetValue ( ) , self . col_textctrl . GetValue ( ) , self . tab_textctrl . GetValue ( ) ] key = [ ] for key_string in key_strings : try : key . append ( int ( key_string ) ) except ValueError : key . append ( 0 ) # Post event post_command_event ( self . parent , self . GotoCellMsg , key = tuple ( key ) ) | Posts a command event that makes the grid show the entered cell | 121 | 12 |
230,777 | def _set_properties ( self ) : self . SetTitle ( _ ( "About pyspread" ) ) label = _ ( "pyspread {version}\nCopyright Martin Manns" ) label = label . format ( version = VERSION ) self . about_label . SetLabel ( label ) | Setup title and label | 64 | 4 |
230,778 | def get_max_dim ( self , obj ) : try : iter ( obj ) except TypeError : return 0 try : for o in obj : iter ( o ) break except TypeError : return 1 return 2 | Returns maximum dimensionality over which obj is iterable < = 2 | 44 | 13 |
230,779 | def alter ( self , operation , timeout = None , metadata = None , credentials = None ) : return self . stub . Alter ( operation , timeout = timeout , metadata = metadata , credentials = credentials ) | Runs alter operation . | 41 | 5 |
230,780 | def query ( self , req , timeout = None , metadata = None , credentials = None ) : return self . stub . Query ( req , timeout = timeout , metadata = metadata , credentials = credentials ) | Runs query operation . | 41 | 5 |
230,781 | def mutate ( self , mutation , timeout = None , metadata = None , credentials = None ) : return self . stub . Mutate ( mutation , timeout = timeout , metadata = metadata , credentials = credentials ) | Runs mutate operation . | 43 | 6 |
230,782 | def commit_or_abort ( self , ctx , timeout = None , metadata = None , credentials = None ) : return self . stub . CommitOrAbort ( ctx , timeout = timeout , metadata = metadata , credentials = credentials ) | Runs commit or abort operation . | 51 | 7 |
230,783 | def check_version ( self , check , timeout = None , metadata = None , credentials = None ) : return self . stub . CheckVersion ( check , timeout = timeout , metadata = metadata , credentials = credentials ) | Returns the version of the Dgraph instance . | 44 | 9 |
230,784 | def alter ( self , operation , timeout = None , metadata = None , credentials = None ) : new_metadata = self . add_login_metadata ( metadata ) try : return self . any_client ( ) . alter ( operation , timeout = timeout , metadata = new_metadata , credentials = credentials ) except Exception as error : if util . is_jwt_expired ( error ) : self . retry_login ( ) new_metadata = self . add_login_metadata ( metadata ) return self . any_client ( ) . alter ( operation , timeout = timeout , metadata = new_metadata , credentials = credentials ) else : raise error | Runs a modification via this client . | 135 | 8 |
230,785 | def txn ( self , read_only = False , best_effort = False ) : return txn . Txn ( self , read_only = read_only , best_effort = best_effort ) | Creates a transaction . | 48 | 5 |
230,786 | def query ( self , query , variables = None , timeout = None , metadata = None , credentials = None ) : new_metadata = self . _dg . add_login_metadata ( metadata ) req = self . _common_query ( query , variables = variables ) try : res = self . _dc . query ( req , timeout = timeout , metadata = new_metadata , credentials = credentials ) except Exception as error : if util . is_jwt_expired ( error ) : self . _dg . retry_login ( ) new_metadata = self . _dg . add_login_metadata ( metadata ) res = self . _dc . query ( req , timeout = timeout , metadata = new_metadata , credentials = credentials ) else : raise error self . merge_context ( res . txn ) return res | Adds a query operation to the transaction . | 175 | 8 |
230,787 | def mutate ( self , mutation = None , set_obj = None , del_obj = None , set_nquads = None , del_nquads = None , commit_now = None , ignore_index_conflict = None , timeout = None , metadata = None , credentials = None ) : mutation = self . _common_mutate ( mutation = mutation , set_obj = set_obj , del_obj = del_obj , set_nquads = set_nquads , del_nquads = del_nquads , commit_now = commit_now , ignore_index_conflict = ignore_index_conflict ) new_metadata = self . _dg . add_login_metadata ( metadata ) mutate_error = None try : assigned = self . _dc . mutate ( mutation , timeout = timeout , metadata = new_metadata , credentials = credentials ) except Exception as error : if util . is_jwt_expired ( error ) : self . _dg . retry_login ( ) new_metadata = self . _dg . add_login_metadata ( metadata ) try : assigned = self . _dc . mutate ( mutation , timeout = timeout , metadata = new_metadata , credentials = credentials ) except Exception as error : mutate_error = error else : mutate_error = error if mutate_error is not None : try : self . discard ( timeout = timeout , metadata = metadata , credentials = credentials ) except : # Ignore error - user should see the original error. pass self . _common_except_mutate ( mutate_error ) if mutation . commit_now : self . _finished = True self . merge_context ( assigned . context ) return assigned | Adds a mutate operation to the transaction . | 371 | 9 |
230,788 | def commit ( self , timeout = None , metadata = None , credentials = None ) : if not self . _common_commit ( ) : return new_metadata = self . _dg . add_login_metadata ( metadata ) try : self . _dc . commit_or_abort ( self . _ctx , timeout = timeout , metadata = new_metadata , credentials = credentials ) except Exception as error : if util . is_jwt_expired ( error ) : self . _dg . retry_login ( ) new_metadata = self . _dg . add_login_metadata ( metadata ) try : self . _dc . commit_or_abort ( self . _ctx , timeout = timeout , metadata = new_metadata , credentials = credentials ) except Exception as error : return self . _common_except_commit ( error ) self . _common_except_commit ( error ) | Commits the transaction . | 191 | 5 |
230,789 | def discard ( self , timeout = None , metadata = None , credentials = None ) : if not self . _common_discard ( ) : return new_metadata = self . _dg . add_login_metadata ( metadata ) try : self . _dc . commit_or_abort ( self . _ctx , timeout = timeout , metadata = new_metadata , credentials = credentials ) except Exception as error : if util . is_jwt_expired ( error ) : self . _dg . retry_login ( ) new_metadata = self . _dg . add_login_metadata ( metadata ) self . _dc . commit_or_abort ( self . _ctx , timeout = timeout , metadata = new_metadata , credentials = credentials ) else : raise error | Discards the transaction . | 166 | 5 |
230,790 | def merge_context ( self , src = None ) : if src is None : # This condition will be true only if the server doesn't return a # txn context after a query or mutation. return if self . _ctx . start_ts == 0 : self . _ctx . start_ts = src . start_ts elif self . _ctx . start_ts != src . start_ts : # This condition should never be true. raise Exception ( 'StartTs mismatch' ) self . _ctx . keys . extend ( src . keys ) self . _ctx . preds . extend ( src . preds ) | Merges context from this instance with src . | 130 | 9 |
230,791 | def generate_token ( self , * args , * * kwargs ) : # determine the length based on min_length and max_length length = random . randint ( self . min_length , self . max_length ) # generate the token using os.urandom and hexlify return binascii . hexlify ( os . urandom ( self . max_length ) ) . decode ( ) [ 0 : length ] | generates a pseudo random code using os . urandom and binascii . hexlify | 93 | 20 |
230,792 | def get_text ( self , node ) : try : return node . children [ 0 ] . content or "" except ( AttributeError , IndexError ) : return node . content or "" | Try to emit whatever text is in the node . | 39 | 10 |
230,793 | def emit_children ( self , node ) : return "" . join ( [ self . emit_node ( child ) for child in node . children ] ) | Emit all the children of a node . | 32 | 9 |
230,794 | def emit_node ( self , node ) : emit = getattr ( self , "%s_emit" % node . kind , self . default_emit ) return emit ( node ) | Emit a single node . | 40 | 6 |
230,795 | def ajax_preview ( request , * * kwargs ) : data = { "html" : render_to_string ( "pinax/blog/_preview.html" , { "content" : parse ( request . POST . get ( "markup" ) ) } ) } return JsonResponse ( data ) | Currently only supports markdown | 71 | 5 |
230,796 | def set_system_lock ( cls , redis , name , timeout ) : pipeline = redis . pipeline ( ) pipeline . zadd ( name , SYSTEM_LOCK_ID , time . time ( ) + timeout ) pipeline . expire ( name , timeout + 10 ) # timeout plus buffer for troubleshooting pipeline . execute ( ) | Set system lock for the semaphore . | 69 | 9 |
230,797 | def acquire ( self ) : acquired , locks = self . _semaphore ( keys = [ self . name ] , args = [ self . lock_id , self . max_locks , self . timeout , time . time ( ) ] ) # Convert Lua boolean returns to Python booleans acquired = True if acquired == 1 else False return acquired , locks | Obtain a semaphore lock . | 74 | 8 |
230,798 | def renew ( self , new_timeout ) : if self . local . token is None : raise LockError ( "Cannot extend an unlocked lock" ) if self . timeout is None : raise LockError ( "Cannot extend a lock with no timeout" ) return self . do_renew ( new_timeout ) | Sets a new timeout for an already acquired lock . | 66 | 11 |
230,799 | def task ( self , _fn = None , queue = None , hard_timeout = None , unique = None , lock = None , lock_key = None , retry = None , retry_on = None , retry_method = None , schedule = None , batch = False , max_queue_size = None ) : def _delay ( func ) : def _delay_inner ( * args , * * kwargs ) : return self . delay ( func , args = args , kwargs = kwargs ) return _delay_inner # Periodic tasks are unique. if schedule is not None : unique = True def _wrap ( func ) : if hard_timeout is not None : func . _task_hard_timeout = hard_timeout if queue is not None : func . _task_queue = queue if unique is not None : func . _task_unique = unique if lock is not None : func . _task_lock = lock if lock_key is not None : func . _task_lock_key = lock_key if retry is not None : func . _task_retry = retry if retry_on is not None : func . _task_retry_on = retry_on if retry_method is not None : func . _task_retry_method = retry_method if batch is not None : func . _task_batch = batch if schedule is not None : func . _task_schedule = schedule if max_queue_size is not None : func . _task_max_queue_size = max_queue_size func . delay = _delay ( func ) if schedule is not None : serialized_func = serialize_func_name ( func ) assert serialized_func not in self . periodic_task_funcs , "attempted duplicate registration of periodic task" self . periodic_task_funcs [ serialized_func ] = func return func return _wrap if _fn is None else _wrap ( _fn ) | Function decorator that defines the behavior of the function when it is used as a task . To use the default behavior tasks don t need to be decorated . | 428 | 31 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.