idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
46,500 | def on_save_as ( self ) : self . tabWidget . save_current_as ( ) self . _update_status_bar ( self . tabWidget . current_widget ( ) ) | Save the current editor document as . |
46,501 | def close_all ( self ) : if self . _try_close_dirty_tabs ( ) : while self . count ( ) : widget = self . widget ( 0 ) self . remove_tab ( 0 ) self . tab_closed . emit ( widget ) return True return False | Closes all editors |
46,502 | def _close_widget ( widget ) : if widget is None : return try : widget . document ( ) . setParent ( None ) widget . syntax_highlighter . setParent ( None ) except AttributeError : pass clones = [ ] if hasattr ( widget , 'original' ) and widget . original : widget . original . clones . remove ( widget ) try : widget . setDocument ( None ) except AttributeError : pass elif hasattr ( widget , 'clones' ) : clones = widget . clones try : widget . close ( clear = len ( clones ) == 0 ) except ( AttributeError , TypeError ) : widget . close ( ) return clones | Closes the given widgets and handles cases where the widget has been clone or is a clone of another widget |
46,503 | def remove_tab ( self , index ) : widget = self . widget ( index ) try : document = widget . document ( ) except AttributeError : document = None clones = self . _close_widget ( widget ) self . tab_closed . emit ( widget ) self . removeTab ( index ) self . _restore_original ( clones ) widget . _original_tab_widget . _tabs . remove ( widget ) if self . count ( ) == 0 : self . last_tab_closed . emit ( ) if SplittableTabWidget . tab_under_menu == widget : SplittableTabWidget . tab_under_menu = None if not clones : widget . setParent ( None ) else : try : clones [ 0 ] . syntax_highlighter . setDocument ( document ) except AttributeError : pass | Overrides removeTab to emit tab_closed and last_tab_closed signals . |
46,504 | def _on_split_requested ( self ) : orientation = self . sender ( ) . text ( ) widget = self . widget ( self . tab_under_menu ( ) ) if 'horizontally' in orientation : self . split_requested . emit ( widget , QtCore . Qt . Horizontal ) else : self . split_requested . emit ( widget , QtCore . Qt . Vertical ) | Emits the split requested signal with the desired orientation . |
46,505 | def addTab ( self , tab , * args ) : tab . parent_tab_widget = self super ( BaseTabWidget , self ) . addTab ( tab , * args ) | Adds a tab to the tab widget this function set the parent_tab_widget attribute on the tab instance . |
46,506 | def add_context_action ( self , action ) : self . main_tab_widget . context_actions . append ( action ) for child_splitter in self . child_splitters : child_splitter . add_context_action ( action ) | Adds a custom context menu action |
46,507 | def add_tab ( self , tab , title = '' , icon = None ) : if icon : tab . _icon = icon if not hasattr ( tab , 'clones' ) : tab . clones = [ ] if not hasattr ( tab , 'original' ) : tab . original = None if icon : self . main_tab_widget . addTab ( tab , icon , title ) else : self . main_tab_widget . addTab ( tab , title ) self . main_tab_widget . setCurrentIndex ( self . main_tab_widget . indexOf ( tab ) ) self . main_tab_widget . show ( ) tab . _uuid = self . _uuid try : scroll_bar = tab . horizontalScrollBar ( ) except AttributeError : pass else : scroll_bar . setValue ( 0 ) tab . setFocus ( ) tab . _original_tab_widget = self self . _tabs . append ( tab ) self . _on_focus_changed ( None , tab ) | Adds a tab to main tab widget . |
46,508 | def split ( self , widget , orientation ) : if widget . original : base = widget . original else : base = widget clone = base . split ( ) if not clone : return if orientation == int ( QtCore . Qt . Horizontal ) : orientation = QtCore . Qt . Horizontal else : orientation = QtCore . Qt . Vertical self . setOrientation ( orientation ) splitter = self . _make_splitter ( ) splitter . show ( ) self . addWidget ( splitter ) self . child_splitters . append ( splitter ) if clone not in base . clones : base . clones . append ( clone ) clone . original = base splitter . _parent_splitter = self splitter . last_tab_closed . connect ( self . _on_last_child_tab_closed ) splitter . tab_detached . connect ( self . tab_detached . emit ) if hasattr ( base , '_icon' ) : icon = base . _icon else : icon = None splitter . _uuid = self . _uuid splitter . add_tab ( clone , title = self . main_tab_widget . tabText ( self . main_tab_widget . indexOf ( widget ) ) , icon = icon ) self . setSizes ( [ 1 for i in range ( self . count ( ) ) ] ) return splitter | Split the the current widget in new SplittableTabWidget . |
46,509 | def widgets ( self , include_clones = False ) : widgets = [ ] for i in range ( self . main_tab_widget . count ( ) ) : widget = self . main_tab_widget . widget ( i ) try : if widget . original is None or include_clones : widgets . append ( widget ) except AttributeError : pass for child in self . child_splitters : widgets += child . widgets ( include_clones = include_clones ) return widgets | Recursively gets the list of widgets . |
46,510 | def get_filter ( cls , mimetype ) : filters = ' ' . join ( [ '*%s' % ext for ext in mimetypes . guess_all_extensions ( mimetype ) ] ) return '%s (%s)' % ( mimetype , filters ) | Returns a filter string for the file dialog . The filter is based on the mime type . |
46,511 | def addTab ( self , widget , * args ) : widget . dirty_changed . connect ( self . _on_dirty_changed ) super ( CodeEditTabWidget , self ) . addTab ( widget , * args ) | Re - implements addTab to connect to the dirty changed signal and setup some helper attributes . |
46,512 | def _ask_path ( cls , editor ) : try : filter = cls . get_filter ( editor . mimetypes [ 0 ] ) except IndexError : filter = _ ( 'All files (*)' ) return QtWidgets . QFileDialog . getSaveFileName ( editor , _ ( 'Save file as' ) , cls . default_directory , filter ) | Shows a QFileDialog and ask for a save filename . |
46,513 | def save_widget ( cls , editor ) : if editor . original : editor = editor . original if editor . file . path is None or not os . path . exists ( editor . file . path ) : path , filter = cls . _ask_path ( editor ) if not path : return False if not os . path . splitext ( path ) [ 1 ] : if len ( editor . mimetypes ) : path += mimetypes . guess_extension ( editor . mimetypes [ 0 ] ) try : _logger ( ) . debug ( 'saving %r as %r' , editor . file . _old_path , path ) except AttributeError : _logger ( ) . debug ( 'saving %r as %r' , editor . file . path , path ) editor . file . _path = path else : path = editor . file . path try : editor . file . save ( path ) except Exception as e : QtWidgets . QMessageBox . warning ( editor , "Failed to save file" , 'Failed to save %r.\n\nError="%s"' % ( path , e ) ) else : tw = editor . parent_tab_widget text = tw . tabText ( tw . indexOf ( editor ) ) . replace ( '*' , '' ) tw . setTabText ( tw . indexOf ( editor ) , text ) for clone in [ editor ] + editor . clones : if clone != editor : tw = clone . parent_tab_widget tw . setTabText ( tw . indexOf ( clone ) , text ) return True | Implements SplittableTabWidget . save_widget to actually save the code editor widget . |
46,514 | def save_current_as ( self ) : if not self . current_widget ( ) : return mem = self . current_widget ( ) . file . path self . current_widget ( ) . file . _path = None self . current_widget ( ) . file . _old_path = mem CodeEditTabWidget . default_directory = os . path . dirname ( mem ) widget = self . current_widget ( ) try : success = self . main_tab_widget . save_widget ( widget ) except Exception as e : QtWidgets . QMessageBox . warning ( self , _ ( 'Failed to save file as' ) , _ ( 'Failed to save file as %s\nError=%s' ) % ( widget . file . path , str ( e ) ) ) widget . file . _path = mem else : if not success : widget . file . _path = mem else : CodeEditTabWidget . default_directory = os . path . expanduser ( '~' ) self . document_saved . emit ( widget . file . path , '' ) tw = widget . parent_tab_widget tw . setTabText ( tw . indexOf ( widget ) , os . path . split ( widget . file . path ) [ 1 ] ) return self . current_widget ( ) . file . path | Save current widget as . |
46,515 | def save_current ( self ) : if self . current_widget ( ) is not None : editor = self . current_widget ( ) self . _save ( editor ) | Save current editor . If the editor . file . path is None a save as dialog will be shown . |
46,516 | def closeEvent ( self , event ) : dirty_widgets = [ ] for w in self . widgets ( include_clones = False ) : if w . dirty : dirty_widgets . append ( w ) filenames = [ ] for w in dirty_widgets : if os . path . exists ( w . file . path ) : filenames . append ( w . file . path ) else : filenames . append ( w . documentTitle ( ) ) if len ( filenames ) == 0 : self . close_all ( ) return dlg = DlgUnsavedFiles ( self , files = filenames ) if dlg . exec_ ( ) == dlg . Accepted : if not dlg . discarded : for item in dlg . listWidget . selectedItems ( ) : filename = item . text ( ) widget = None for widget in dirty_widgets : if widget . file . path == filename or widget . documentTitle ( ) == filename : break tw = widget . parent_tab_widget tw . save_widget ( widget ) tw . remove_tab ( tw . indexOf ( widget ) ) self . close_all ( ) else : event . ignore ( ) | Saves dirty editors on close and cancel the event if the user choosed to continue to work . |
46,517 | def _hide_popup ( self ) : debug ( 'hide popup' ) if ( self . _completer . popup ( ) is not None and self . _completer . popup ( ) . isVisible ( ) ) : self . _completer . popup ( ) . hide ( ) self . _last_cursor_column = - 1 self . _last_cursor_line = - 1 QtWidgets . QToolTip . hideText ( ) | Hides the completer popup |
46,518 | def _update_model ( self , completions ) : cc_model = QtGui . QStandardItemModel ( ) self . _tooltips . clear ( ) for completion in completions : name = completion [ 'name' ] item = QtGui . QStandardItem ( ) item . setData ( name , QtCore . Qt . DisplayRole ) if 'tooltip' in completion and completion [ 'tooltip' ] : self . _tooltips [ name ] = completion [ 'tooltip' ] if 'icon' in completion : icon = completion [ 'icon' ] if isinstance ( icon , list ) : icon = QtGui . QIcon . fromTheme ( icon [ 0 ] , QtGui . QIcon ( icon [ 1 ] ) ) else : icon = QtGui . QIcon ( icon ) item . setData ( QtGui . QIcon ( icon ) , QtCore . Qt . DecorationRole ) cc_model . appendRow ( item ) try : self . _completer . setModel ( cc_model ) except RuntimeError : self . _create_completer ( ) self . _completer . setModel ( cc_model ) return cc_model | Creates a QStandardModel that holds the suggestion from the completion models for the QCompleter |
46,519 | def create ( client , _type , ** kwargs ) : obj = client . factory . create ( "ns0:%s" % _type ) for key , value in kwargs . items ( ) : setattr ( obj , key , value ) return obj | Create a suds object of the requested _type . |
46,520 | def invoke ( client , method , ** kwargs ) : try : result = getattr ( client . service , method ) ( ** kwargs ) except AttributeError : logger . critical ( "Unknown method: %s" , method ) raise except URLError as e : logger . debug ( pprint ( e ) ) logger . debug ( "A URL related error occurred while invoking the '%s' " "method on the VIM server, this can be caused by " "name resolution or connection problems." , method ) logger . debug ( "The underlying error is: %s" , e . reason [ 1 ] ) raise except suds . client . TransportError as e : logger . debug ( pprint ( e ) ) logger . debug ( "TransportError: %s" , e ) except suds . WebFault as e : logger . critical ( "SUDS Fault: %s" % e . fault . faultstring ) if len ( e . fault . faultstring ) > 0 : raise detail = e . document . childAtPath ( "/Envelope/Body/Fault/detail" ) fault_type = detail . getChildren ( ) [ 0 ] . name fault = create ( fault_type ) if isinstance ( e . fault . detail [ 0 ] , list ) : for attr in e . fault . detail [ 0 ] : setattr ( fault , attr [ 0 ] , attr [ 1 ] ) else : fault [ "text" ] = e . fault . detail [ 0 ] raise VimFault ( fault ) return result | Invoke a method on the underlying soap service . |
46,521 | def prettydate ( date ) : now = datetime . now ( timezone . utc ) diff = now - date if diff . days > 7 : return date . strftime ( "%d. %b %Y" ) return arrow . get ( date ) . humanize ( ) | Return the relative timeframe between the given date and now . |
46,522 | def discovery ( self , compute_resource ) : if compute_resource is None : cr_list = ComputeResource . all ( self . client ) print ( "ERROR: You must specify a ComputeResource." ) print ( "Available ComputeResource's:" ) for cr in cr_list : print ( cr . name ) sys . exit ( 1 ) try : ccr = ComputeResource . get ( self . client , name = compute_resource ) except ObjectNotFoundError : print ( "ERROR: Could not find ComputeResource with name %s" % compute_resource ) sys . exit ( 1 ) print ( 'Cluster: %s (%s hosts)' % ( ccr . name , len ( ccr . host ) ) ) ccr . preload ( "host" , properties = [ "name" , "vm" ] ) for host in ccr . host : print ( ' Host: %s (%s VMs)' % ( host . name , len ( host . vm ) ) ) host . preload ( "vm" , properties = [ "name" ] ) for vm in host . vm : print ( ' VM: %s' % vm . name ) | An example that discovers hosts and VMs in the inventory . |
46,523 | def _get_app_auth_headers ( self ) : now = datetime . now ( timezone . utc ) expiry = now + timedelta ( minutes = 5 ) data = { "iat" : now , "exp" : expiry , "iss" : self . app_id } app_token = jwt . encode ( data , self . app_key , algorithm = "RS256" ) . decode ( "utf-8" ) headers = { "Accept" : PREVIEW_JSON_ACCEPT , "Authorization" : "Bearer {}" . format ( app_token ) , } return headers | Set the correct auth headers to authenticate against GitHub . |
46,524 | def _get_installation_key ( self , project , user_id = None , install_id = None , reprime = False ) : installation_id = install_id if project is not None : installation_id = self . installation_map . get ( project , { } ) . get ( "installation_id" ) if not installation_id : if reprime : self . _prime_install_map ( ) return self . _get_installation_key ( project , user_id = user_id , install_id = install_id , reprime = False ) LOGGER . debug ( "No installation ID available for project %s" , project ) return "" now = datetime . now ( timezone . utc ) token , expiry = self . installation_token_cache . get ( installation_id , ( None , None ) ) if ( not expiry ) or ( not token ) or ( now >= expiry ) : LOGGER . debug ( "Requesting new token for installation %s" , installation_id ) headers = self . _get_app_auth_headers ( ) url = "{}/installations/{}/access_tokens" . format ( self . api_url , installation_id ) json_data = { "user_id" : user_id } if user_id else None response = requests . post ( url , headers = headers , json = json_data ) response . raise_for_status ( ) data = response . json ( ) token = data [ "token" ] expiry = datetime . strptime ( data [ "expires_at" ] , "%Y-%m-%dT%H:%M:%SZ" ) expiry = expiry . replace ( tzinfo = timezone . utc ) expiry -= timedelta ( minutes = 2 ) self . installation_token_cache [ installation_id ] = ( token , expiry ) return token | Get the auth token for a project or installation id . |
46,525 | def _prime_install_map ( self ) : url = "{}/app/installations" . format ( self . api_url ) headers = self . _get_app_auth_headers ( ) LOGGER . debug ( "Fetching installations for GitHub app" ) response = requests . get ( url , headers = headers ) response . raise_for_status ( ) data = response . json ( ) for install in data : install_id = install . get ( "id" ) token = self . _get_installation_key ( project = None , install_id = install_id ) headers = { "Accept" : PREVIEW_JSON_ACCEPT , "Authorization" : "token {}" . format ( token ) , } url = "{}/installation/repositories?per_page=100" . format ( self . api_url ) while url : LOGGER . debug ( "Fetching repos for installation %s" , install_id ) response = requests . get ( url , headers = headers ) response . raise_for_status ( ) repos = response . json ( ) for repo in repos . get ( "repositories" , [ ] ) : project_name = repo [ "full_name" ] self . installation_map [ project_name ] = { "installation_id" : install_id , "default_branch" : repo [ "default_branch" ] , } url = response . links . get ( "next" , { } ) . get ( "url" ) | Fetch all installations and look up the ID for each . |
46,526 | def _clear_deco ( self ) : if self . _decoration : self . editor . decorations . remove ( self . _decoration ) self . _decoration = None | Clear line decoration |
46,527 | def save_current ( self , path = None ) : try : if not path and not self . _current . file . path : path , filter = QtWidgets . QFileDialog . getSaveFileName ( self , _ ( 'Choose destination path' ) ) if not path : return False old_path = self . _current . file . path code_edit = self . _current self . _save_editor ( code_edit , path ) path = code_edit . file . path if path and old_path != path : self . _ensure_unique_name ( code_edit , code_edit . file . name ) self . setTabText ( self . currentIndex ( ) , code_edit . _tab_name ) ext = os . path . splitext ( path ) [ 1 ] old_ext = os . path . splitext ( old_path ) [ 1 ] if ext != old_ext or not old_path : icon = QtWidgets . QFileIconProvider ( ) . icon ( QtCore . QFileInfo ( code_edit . file . path ) ) self . setTabIcon ( self . currentIndex ( ) , icon ) return True except AttributeError : pass return False | Save current editor content . Leave file to None to erase the previous file content . If the current editor s file_path is None and path is None the function will call QtWidgets . QFileDialog . getSaveFileName to get a valid save filename . |
46,528 | def index_from_filename ( self , path ) : if path : for i in range ( self . count ( ) ) : widget = self . widget ( i ) try : if widget . file . path == path : return i except AttributeError : pass return - 1 | Checks if the path is already open in an editor tab . |
46,529 | def add_code_edit ( self , code_edit , name = None ) : if code_edit . file . path == '' : cnt = 0 for i in range ( self . count ( ) ) : tab = self . widget ( i ) if tab . file . path . startswith ( name [ : name . find ( '%' ) ] ) : cnt += 1 name %= ( cnt + 1 ) code_edit . file . _path = name index = self . index_from_filename ( code_edit . file . path ) if index != - 1 : self . setCurrentIndex ( index ) self . _del_code_edit ( code_edit ) return - 1 self . _ensure_unique_name ( code_edit , name ) index = self . addTab ( code_edit , code_edit . file . icon , code_edit . _tab_name ) self . setCurrentIndex ( index ) self . setTabText ( index , code_edit . _tab_name ) try : code_edit . setFocus ( ) except TypeError : code_edit . setFocus ( ) try : file_watcher = code_edit . modes . get ( FileWatcherMode ) except ( KeyError , AttributeError ) : pass else : file_watcher . file_deleted . connect ( self . _on_file_deleted ) return index | Adds a code edit tab sets its text as the editor . file . name and sets it as the active tab . |
46,530 | def addTab ( self , elem , icon , name ) : self . _widgets . append ( elem ) return super ( TabWidget , self ) . addTab ( elem , icon , name ) | Extends QTabWidget . addTab to keep an internal list of added tabs . |
46,531 | def _name_exists ( self , name ) : for i in range ( self . count ( ) ) : if self . tabText ( i ) == name : return True return False | Checks if we already have an opened tab with the same name . |
46,532 | def _rename_duplicate_tabs ( self , current , name , path ) : for i in range ( self . count ( ) ) : if self . widget ( i ) . _tab_name == name and self . widget ( i ) != current : file_path = self . widget ( i ) . file . path if file_path : parent_dir = os . path . split ( os . path . abspath ( os . path . join ( file_path , os . pardir ) ) ) [ 1 ] new_name = os . path . join ( parent_dir , name ) self . setTabText ( i , new_name ) self . widget ( i ) . _tab_name = new_name break if path : parent_dir = os . path . split ( os . path . abspath ( os . path . join ( path , os . pardir ) ) ) [ 1 ] return os . path . join ( parent_dir , name ) else : return name | Rename tabs whose title is the same as the name |
46,533 | def removeTab ( self , index ) : widget = self . widget ( index ) try : self . _widgets . remove ( widget ) except ValueError : pass self . tab_closed . emit ( widget ) self . _del_code_edit ( widget ) QTabWidget . removeTab ( self , index ) if widget == self . _current : self . _current = None | Removes tab at index index . |
46,534 | def _try_close_dirty_tabs ( self , exept = None ) : widgets , filenames = self . _collect_dirty_tabs ( exept = exept ) if not len ( filenames ) : return True dlg = DlgUnsavedFiles ( self , files = filenames ) if dlg . exec_ ( ) == dlg . Accepted : if not dlg . discarded : for item in dlg . listWidget . selectedItems ( ) : filename = item . text ( ) widget = None for widget in widgets : if widget . file . path == filename : break if widget != exept : self . _save_editor ( widget ) self . removeTab ( self . indexOf ( widget ) ) return True return False | Tries to close dirty tabs . Uses DlgUnsavedFiles to ask the user what he wants to do . |
46,535 | def edit_encoding ( cls , parent ) : dlg = cls ( parent ) if dlg . exec_ ( ) == dlg . Accepted : settings = Cache ( ) settings . preferred_encodings = dlg . get_preferred_encodings ( ) return True return False | Static helper method that shows the encoding editor dialog If the dialog was accepted the new encodings are added to the settings . |
46,536 | def choose_encoding ( cls , parent , path , encoding ) : dlg = cls ( parent , path , encoding ) dlg . exec_ ( ) return dlg . ui . comboBoxEncodings . current_encoding | Show the encodings dialog and returns the user choice . |
46,537 | def pty_wrapper_main ( ) : sys . path . insert ( 0 , os . path . dirname ( __file__ ) ) import _pty _pty . spawn ( sys . argv [ 1 : ] ) | Main function of the pty wrapper script |
46,538 | def create_menu ( self ) : menu = QtWidgets . QMenu ( self . editor ) menu . setTitle ( _ ( 'Select' ) ) menu . menuAction ( ) . setIcon ( QtGui . QIcon . fromTheme ( 'edit-select' ) ) menu . addAction ( self . action_select_word ) menu . addAction ( self . action_select_extended_word ) menu . addAction ( self . action_select_matched ) menu . addAction ( self . action_select_line ) menu . addSeparator ( ) menu . addAction ( self . editor . action_select_all ) icon = QtGui . QIcon . fromTheme ( 'edit-select-all' , QtGui . QIcon ( ':/pyqode-icons/rc/edit-select-all.png' ) ) self . editor . action_select_all . setIcon ( icon ) return menu | Creates the extended selection menu . |
46,539 | def to_dict ( self ) : ddict = { 'name' : self . name , 'icon' : self . icon , 'line' : self . line , 'column' : self . column , 'children' : [ ] , 'description' : self . description , 'user_data' : self . user_data , 'path' : self . file_path } for child in self . children : ddict [ 'children' ] . append ( child . to_dict ( ) ) return ddict | Serializes a definition to a dictionary ready for json . |
46,540 | def from_dict ( ddict ) : d = Definition ( ddict [ 'name' ] , ddict [ 'line' ] , ddict [ 'column' ] , ddict [ 'icon' ] , ddict [ 'description' ] , ddict [ 'user_data' ] , ddict [ 'path' ] ) for child_dict in ddict [ 'children' ] : d . children . append ( Definition . from_dict ( child_dict ) ) return d | Deserializes a definition from a simple dict . |
46,541 | def indent_selection ( self , cursor ) : doc = self . editor . document ( ) tab_len = self . editor . tab_length cursor . beginEditBlock ( ) nb_lines = len ( cursor . selection ( ) . toPlainText ( ) . splitlines ( ) ) c = self . editor . textCursor ( ) if c . atBlockStart ( ) and c . position ( ) == c . selectionEnd ( ) : nb_lines += 1 block = doc . findBlock ( cursor . selectionStart ( ) ) i = 0 while i < nb_lines : nb_space_to_add = tab_len cursor = QtGui . QTextCursor ( block ) cursor . movePosition ( cursor . StartOfLine , cursor . MoveAnchor ) if self . editor . use_spaces_instead_of_tabs : for _ in range ( nb_space_to_add ) : cursor . insertText ( " " ) else : cursor . insertText ( '\t' ) block = block . next ( ) i += 1 cursor . endEditBlock ( ) | Indent selected text |
46,542 | def show_tooltip ( self , pos , tooltip , _sender_deco = None ) : if _sender_deco is not None and _sender_deco not in self . decorations : return QtWidgets . QToolTip . showText ( pos , tooltip [ 0 : 1024 ] , self ) | Show a tool tip at the specified position |
46,543 | def setPlainText ( self , txt , mime_type , encoding ) : self . file . mimetype = mime_type self . file . _encoding = encoding self . _original_text = txt self . _modified_lines . clear ( ) import time t = time . time ( ) super ( CodeEdit , self ) . setPlainText ( txt ) _logger ( ) . log ( 5 , 'setPlainText duration: %fs' % ( time . time ( ) - t ) ) self . new_text_set . emit ( ) self . redoAvailable . emit ( False ) self . undoAvailable . emit ( False ) | Extends setPlainText to force the user to setup an encoding and a mime type . |
46,544 | def add_action ( self , action , sub_menu = 'Advanced' ) : if sub_menu : try : mnu = self . _sub_menus [ sub_menu ] except KeyError : mnu = QtWidgets . QMenu ( sub_menu ) self . add_menu ( mnu ) self . _sub_menus [ sub_menu ] = mnu finally : mnu . addAction ( action ) else : self . _actions . append ( action ) action . setShortcutContext ( QtCore . Qt . WidgetShortcut ) self . addAction ( action ) | Adds an action to the editor s context menu . |
46,545 | def insert_action ( self , action , prev_action ) : if isinstance ( prev_action , QtWidgets . QAction ) : index = self . _actions . index ( prev_action ) else : index = prev_action action . setShortcutContext ( QtCore . Qt . WidgetShortcut ) self . _actions . insert ( index , action ) | Inserts an action to the editor s context menu . |
46,546 | def add_separator ( self , sub_menu = 'Advanced' ) : action = QtWidgets . QAction ( self ) action . setSeparator ( True ) if sub_menu : try : mnu = self . _sub_menus [ sub_menu ] except KeyError : pass else : mnu . addAction ( action ) else : self . _actions . append ( action ) return action | Adds a sepqrator to the editor s context menu . |
46,547 | def add_menu ( self , menu ) : self . _menus . append ( menu ) self . _menus = sorted ( list ( set ( self . _menus ) ) , key = lambda x : x . title ( ) ) for action in menu . actions ( ) : action . setShortcutContext ( QtCore . Qt . WidgetShortcut ) self . addActions ( menu . actions ( ) ) | Adds a sub - menu to the editor context menu . |
46,548 | def duplicate_line ( self ) : cursor = self . textCursor ( ) assert isinstance ( cursor , QtGui . QTextCursor ) has_selection = True if not cursor . hasSelection ( ) : cursor . select ( cursor . LineUnderCursor ) has_selection = False line = cursor . selectedText ( ) line = '\n' . join ( line . split ( '\u2029' ) ) end = cursor . selectionEnd ( ) cursor . setPosition ( end ) cursor . beginEditBlock ( ) cursor . insertText ( '\n' ) cursor . insertText ( line ) cursor . endEditBlock ( ) if has_selection : pos = cursor . position ( ) cursor . setPosition ( end + 1 ) cursor . setPosition ( pos , cursor . KeepAnchor ) self . setTextCursor ( cursor ) | Duplicates the line under the cursor . If multiple lines are selected only the last one is duplicated . |
46,549 | def cut ( self ) : tc = self . textCursor ( ) helper = TextHelper ( self ) tc . beginEditBlock ( ) no_selection = False sText = tc . selection ( ) . toPlainText ( ) if not helper . current_line_text ( ) and sText . count ( "\n" ) > 1 : tc . deleteChar ( ) else : if not self . textCursor ( ) . hasSelection ( ) : no_selection = True TextHelper ( self ) . select_whole_line ( ) super ( CodeEdit , self ) . cut ( ) if no_selection : tc . deleteChar ( ) tc . endEditBlock ( ) self . setTextCursor ( tc ) | Cuts the selected text or the whole line if no text was selected . |
46,550 | def resizeEvent ( self , e ) : super ( CodeEdit , self ) . resizeEvent ( e ) self . panels . resize ( ) | Overrides resize event to resize the editor s panels . |
46,551 | def paintEvent ( self , e ) : self . _update_visible_blocks ( e ) super ( CodeEdit , self ) . paintEvent ( e ) self . painted . emit ( e ) | Overrides paint event to update the list of visible blocks and emit the painted event . |
46,552 | def keyPressEvent ( self , event ) : if self . isReadOnly ( ) : return initial_state = event . isAccepted ( ) event . ignore ( ) self . key_pressed . emit ( event ) state = event . isAccepted ( ) if not event . isAccepted ( ) : if event . key ( ) == QtCore . Qt . Key_Tab and event . modifiers ( ) == QtCore . Qt . NoModifier : self . indent ( ) event . accept ( ) elif event . key ( ) == QtCore . Qt . Key_Backtab and event . modifiers ( ) == QtCore . Qt . NoModifier : self . un_indent ( ) event . accept ( ) elif event . key ( ) == QtCore . Qt . Key_Home and int ( event . modifiers ( ) ) & QtCore . Qt . ControlModifier == 0 : self . _do_home_key ( event , int ( event . modifiers ( ) ) & QtCore . Qt . ShiftModifier ) if not event . isAccepted ( ) : event . setAccepted ( initial_state ) super ( CodeEdit , self ) . keyPressEvent ( event ) new_state = event . isAccepted ( ) event . setAccepted ( state ) self . post_key_pressed . emit ( event ) event . setAccepted ( new_state ) | Overrides the keyPressEvent to emit the key_pressed signal . |
46,553 | def keyReleaseEvent ( self , event ) : if self . isReadOnly ( ) : return initial_state = event . isAccepted ( ) event . ignore ( ) self . key_released . emit ( event ) if not event . isAccepted ( ) : event . setAccepted ( initial_state ) super ( CodeEdit , self ) . keyReleaseEvent ( event ) | Overrides keyReleaseEvent to emit the key_released signal . |
46,554 | def focusInEvent ( self , event ) : self . focused_in . emit ( event ) super ( CodeEdit , self ) . focusInEvent ( event ) | Overrides focusInEvent to emits the focused_in signal |
46,555 | def mousePressEvent ( self , event ) : initial_state = event . isAccepted ( ) event . ignore ( ) self . mouse_pressed . emit ( event ) if event . button ( ) == QtCore . Qt . LeftButton : cursor = self . cursorForPosition ( event . pos ( ) ) for sel in self . decorations : if sel . cursor . blockNumber ( ) == cursor . blockNumber ( ) : if sel . contains_cursor ( cursor ) : sel . signals . clicked . emit ( sel ) if not event . isAccepted ( ) : event . setAccepted ( initial_state ) super ( CodeEdit , self ) . mousePressEvent ( event ) | Overrides mousePressEvent to emits mouse_pressed signal |
46,556 | def mouseReleaseEvent ( self , event ) : initial_state = event . isAccepted ( ) event . ignore ( ) self . mouse_released . emit ( event ) if not event . isAccepted ( ) : event . setAccepted ( initial_state ) super ( CodeEdit , self ) . mouseReleaseEvent ( event ) | Emits mouse_released signal . |
46,557 | def wheelEvent ( self , event ) : initial_state = event . isAccepted ( ) event . ignore ( ) self . mouse_wheel_activated . emit ( event ) if not event . isAccepted ( ) : event . setAccepted ( initial_state ) super ( CodeEdit , self ) . wheelEvent ( event ) | Emits the mouse_wheel_activated signal . |
46,558 | def mouseMoveEvent ( self , event ) : cursor = self . cursorForPosition ( event . pos ( ) ) self . _last_mouse_pos = event . pos ( ) block_found = False for sel in self . decorations : if sel . contains_cursor ( cursor ) and sel . tooltip : if ( self . _prev_tooltip_block_nbr != cursor . blockNumber ( ) or not QtWidgets . QToolTip . isVisible ( ) ) : pos = event . pos ( ) pos . setX ( pos . x ( ) + self . panels . margin_size ( ) ) pos . setY ( pos . y ( ) + self . panels . margin_size ( 0 ) ) self . _tooltips_runner . request_job ( self . show_tooltip , self . mapToGlobal ( pos ) , sel . tooltip [ 0 : 1024 ] , sel ) self . _prev_tooltip_block_nbr = cursor . blockNumber ( ) block_found = True break if not block_found and self . _prev_tooltip_block_nbr != - 1 : QtWidgets . QToolTip . hideText ( ) self . _prev_tooltip_block_nbr = - 1 self . _tooltips_runner . cancel_requests ( ) self . mouse_moved . emit ( event ) super ( CodeEdit , self ) . mouseMoveEvent ( event ) | Overrides mouseMovedEvent to display any decoration tooltip and emits the mouse_moved event . |
46,559 | def showEvent ( self , event ) : super ( CodeEdit , self ) . showEvent ( event ) self . panels . refresh ( ) | Overrides showEvent to update the viewport margins |
46,560 | def get_context_menu ( self ) : mnu = QtWidgets . QMenu ( ) mnu . addActions ( self . _actions ) mnu . addSeparator ( ) for menu in self . _menus : mnu . addMenu ( menu ) return mnu | Gets the editor context menu . |
46,561 | def _show_context_menu ( self , point ) : tc = self . textCursor ( ) nc = self . cursorForPosition ( point ) if not nc . position ( ) in range ( tc . selectionStart ( ) , tc . selectionEnd ( ) ) : self . setTextCursor ( nc ) self . _mnu = self . get_context_menu ( ) if len ( self . _mnu . actions ( ) ) > 1 and self . show_context_menu : self . _mnu . popup ( self . mapToGlobal ( point ) ) | Shows the context menu |
46,562 | def _set_whitespaces_flags ( self , show ) : doc = self . document ( ) options = doc . defaultTextOption ( ) if show : options . setFlags ( options . flags ( ) | QtGui . QTextOption . ShowTabsAndSpaces ) else : options . setFlags ( options . flags ( ) & ~ QtGui . QTextOption . ShowTabsAndSpaces ) doc . setDefaultTextOption ( options ) | Sets show white spaces flag |
46,563 | def _init_style ( self ) : self . _background = QtGui . QColor ( 'white' ) self . _foreground = QtGui . QColor ( 'black' ) self . _whitespaces_foreground = QtGui . QColor ( 'light gray' ) app = QtWidgets . QApplication . instance ( ) self . _sel_background = app . palette ( ) . highlight ( ) . color ( ) self . _sel_foreground = app . palette ( ) . highlightedText ( ) . color ( ) self . _font_size = 10 self . font_name = "" | Inits style options |
46,564 | def _update_visible_blocks ( self , * args ) : self . _visible_blocks [ : ] = [ ] block = self . firstVisibleBlock ( ) block_nbr = block . blockNumber ( ) top = int ( self . blockBoundingGeometry ( block ) . translated ( self . contentOffset ( ) ) . top ( ) ) bottom = top + int ( self . blockBoundingRect ( block ) . height ( ) ) ebottom_top = 0 ebottom_bottom = self . height ( ) while block . isValid ( ) : visible = ( top >= ebottom_top and bottom <= ebottom_bottom ) if not visible : break if block . isVisible ( ) : self . _visible_blocks . append ( ( top , block_nbr , block ) ) block = block . next ( ) top = bottom bottom = top + int ( self . blockBoundingRect ( block ) . height ( ) ) block_nbr = block . blockNumber ( ) | Updates the list of visible blocks |
46,565 | def _on_text_changed ( self ) : if not self . _cleaning : ln = TextHelper ( self ) . cursor_position ( ) [ 0 ] self . _modified_lines . add ( ln ) | Adjust dirty flag depending on editor s content |
46,566 | def cached ( key , timeout = 3600 ) : def decorator ( f ) : @ wraps ( f ) def wrapped ( * args , ** kwargs ) : cache = get_cache ( ) if callable ( key ) : cache_key = key ( * args , ** kwargs ) else : cache_key = key cached_val = cache . get ( cache_key ) if cached_val is None : cached_val = f ( * args , ** kwargs ) cache . set ( cache_key , cached_val , timeout ) return cached_val return wrapped return decorator | Cache the return value of the decorated function with the given key . |
46,567 | def _copy_cell_text ( self ) : txt = self . currentItem ( ) . text ( ) QtWidgets . QApplication . clipboard ( ) . setText ( txt ) | Copies the description of the selected message to the clipboard |
46,568 | def clear ( self ) : QtWidgets . QTableWidget . clear ( self ) self . setRowCount ( 0 ) self . setColumnCount ( 4 ) self . setHorizontalHeaderLabels ( [ "Type" , "File name" , "Line" , "Description" ] ) | Clears the tables and the message list |
46,569 | def add_message ( self , msg ) : row = self . rowCount ( ) self . insertRow ( row ) item = QtWidgets . QTableWidgetItem ( self . _make_icon ( msg . status ) , msg . status_string ) item . setFlags ( QtCore . Qt . ItemIsEnabled | QtCore . Qt . ItemIsSelectable ) item . setData ( QtCore . Qt . UserRole , msg ) self . setItem ( row , COL_TYPE , item ) item = QtWidgets . QTableWidgetItem ( QtCore . QFileInfo ( msg . path ) . fileName ( ) ) item . setFlags ( QtCore . Qt . ItemIsEnabled | QtCore . Qt . ItemIsSelectable ) item . setData ( QtCore . Qt . UserRole , msg ) self . setItem ( row , COL_FILE_NAME , item ) if msg . line < 0 : item = QtWidgets . QTableWidgetItem ( "-" ) else : item = QtWidgets . QTableWidgetItem ( str ( msg . line + 1 ) ) item . setFlags ( QtCore . Qt . ItemIsEnabled | QtCore . Qt . ItemIsSelectable ) item . setData ( QtCore . Qt . UserRole , msg ) self . setItem ( row , COL_LINE_NBR , item ) item = QtWidgets . QTableWidgetItem ( msg . description ) item . setFlags ( QtCore . Qt . ItemIsEnabled | QtCore . Qt . ItemIsSelectable ) item . setData ( QtCore . Qt . UserRole , msg ) self . setItem ( row , COL_MSG , item ) | Adds a checker message to the table . |
46,570 | def _on_item_activated ( self , item ) : msg = item . data ( QtCore . Qt . UserRole ) self . msg_activated . emit ( msg ) | Emits the message activated signal |
46,571 | def showDetails ( self ) : msg = self . currentItem ( ) . data ( QtCore . Qt . UserRole ) desc = msg . description desc = desc . replace ( '\r\n' , '\n' ) . replace ( '\r' , '\n' ) desc = desc . replace ( '\n' , '<br/>' ) QtWidgets . QMessageBox . information ( self , _ ( 'Message details' ) , _ ( ) % ( desc , msg . path , msg . line + 1 , ) ) | Shows the error details . |
46,572 | def get_line ( cls , parent , current_line , line_count ) : dlg = DlgGotoLine ( parent , current_line + 1 , line_count ) if dlg . exec_ ( ) == dlg . Accepted : return dlg . spinBox . value ( ) - 1 , True return current_line , False | Gets user selected line . |
46,573 | def close_panel ( self ) : self . hide ( ) self . lineEditReplace . clear ( ) self . lineEditSearch . clear ( ) | Closes the panel |
46,574 | def request_search ( self , txt = None ) : if self . checkBoxRegex . isChecked ( ) : try : re . compile ( self . lineEditSearch . text ( ) , re . DOTALL ) except sre_constants . error as e : self . _show_error ( e ) return else : self . _show_error ( None ) if txt is None or isinstance ( txt , int ) : txt = self . lineEditSearch . text ( ) if txt : self . job_runner . request_job ( self . _exec_search , txt , self . _search_flags ( ) ) else : self . job_runner . cancel_requests ( ) self . _clear_occurrences ( ) self . _on_search_finished ( ) | Requests a search operation . |
46,575 | def select_next ( self ) : current_occurence = self . _current_occurrence ( ) occurrences = self . get_occurences ( ) if not occurrences : return current = self . _occurrences [ current_occurence ] cursor_pos = self . editor . textCursor ( ) . position ( ) if cursor_pos not in range ( current [ 0 ] , current [ 1 ] + 1 ) or current_occurence == - 1 : current_occurence = 0 for i , ( start , end ) in enumerate ( self . _occurrences ) : if end > cursor_pos : current_occurence = i break else : if ( current_occurence == - 1 or current_occurence >= len ( occurrences ) - 1 ) : current_occurence = 0 else : current_occurence += 1 self . _set_current_occurrence ( current_occurence ) try : cursor = self . editor . textCursor ( ) cursor . setPosition ( occurrences [ current_occurence ] [ 0 ] ) cursor . setPosition ( occurrences [ current_occurence ] [ 1 ] , cursor . KeepAnchor ) self . editor . setTextCursor ( cursor ) return True except IndexError : return False | Selects the next occurrence . |
46,576 | def replace ( self , text = None ) : if text is None or isinstance ( text , bool ) : text = self . lineEditReplace . text ( ) current_occurences = self . _current_occurrence ( ) occurrences = self . get_occurences ( ) if current_occurences == - 1 : self . select_next ( ) current_occurences = self . _current_occurrence ( ) try : try : self . editor . textChanged . disconnect ( self . request_search ) except ( RuntimeError , TypeError ) : pass occ = occurrences [ current_occurences ] cursor = self . editor . textCursor ( ) cursor . setPosition ( occ [ 0 ] ) cursor . setPosition ( occ [ 1 ] , cursor . KeepAnchor ) len_to_replace = len ( cursor . selectedText ( ) ) len_replacement = len ( text ) offset = len_replacement - len_to_replace cursor . insertText ( text ) self . editor . setTextCursor ( cursor ) self . _remove_occurrence ( current_occurences , offset ) current_occurences -= 1 self . _set_current_occurrence ( current_occurences ) self . select_next ( ) self . cpt_occurences = len ( self . get_occurences ( ) ) self . _update_label_matches ( ) self . _update_buttons ( ) return True except IndexError : return False finally : self . editor . textChanged . connect ( self . request_search ) | Replaces the selected occurrence . |
46,577 | def replace_all ( self , text = None ) : cursor = self . editor . textCursor ( ) cursor . beginEditBlock ( ) remains = self . replace ( text = text ) while remains : remains = self . replace ( text = text ) cursor . endEditBlock ( ) | Replaces all occurrences in the editor s document . |
46,578 | def _create_decoration ( self , selection_start , selection_end ) : deco = TextDecoration ( self . editor . document ( ) , selection_start , selection_end ) deco . set_background ( QtGui . QBrush ( self . background ) ) deco . set_outline ( self . _outline ) deco . set_foreground ( QtCore . Qt . black ) deco . draw_order = 1 return deco | Creates the text occurences decoration |
46,579 | def _send_request ( self ) : if isinstance ( self . _worker , str ) : classname = self . _worker else : classname = '%s.%s' % ( self . _worker . __module__ , self . _worker . __name__ ) self . request_id = str ( uuid . uuid4 ( ) ) self . send ( { 'request_id' : self . request_id , 'worker' : classname , 'data' : self . _args } ) | Sends the request to the backend . |
46,580 | def _connect ( self ) : if self is None : return comm ( 'connecting to 127.0.0.1:%d' , self . _port ) address = QtNetwork . QHostAddress ( '127.0.0.1' ) self . connectToHost ( address , self . _port ) if sys . platform == 'darwin' : self . waitForConnected ( ) | Connects our client socket to the backend socket |
46,581 | def _on_ready_read ( self ) : while self . bytesAvailable ( ) : if not self . _header_complete : self . _read_header ( ) else : self . _read_payload ( ) | Read bytes when ready read |
46,582 | def _on_process_started ( self ) : comm ( 'backend process started' ) if self is None : return self . starting = False self . running = True | Logs process started |
46,583 | def _on_process_error ( self , error ) : if self is None : return if error not in PROCESS_ERROR_STRING : error = - 1 if not self . _prevent_logs : _logger ( ) . warning ( PROCESS_ERROR_STRING [ error ] ) | Logs process error |
46,584 | def _on_process_stdout_ready ( self ) : if not self : return o = self . readAllStandardOutput ( ) try : output = bytes ( o ) . decode ( self . _encoding ) except TypeError : output = bytes ( o . data ( ) ) . decode ( self . _encoding ) for line in output . splitlines ( ) : self . _srv_logger . log ( 1 , line ) | Logs process output |
46,585 | def replace_pattern ( tokens , new_pattern ) : for state in tokens . values ( ) : for index , pattern in enumerate ( state ) : if isinstance ( pattern , tuple ) and pattern [ 1 ] == new_pattern [ 1 ] : state [ index ] = new_pattern | Given a RegexLexer token dictionary tokens replace all patterns that match the token specified in new_pattern with new_pattern . |
46,586 | def set_mime_type ( self , mime_type ) : try : self . set_lexer_from_mime_type ( mime_type ) except ClassNotFound : _logger ( ) . exception ( 'failed to get lexer from mimetype' ) self . _lexer = TextLexer ( ) return False except ImportError : _logger ( ) . warning ( 'failed to get lexer from mimetype (%s)' % mime_type ) self . _lexer = TextLexer ( ) return False else : return True | Update the highlighter lexer based on a mime type . |
46,587 | def set_lexer_from_mime_type ( self , mime , ** options ) : self . _lexer = get_lexer_for_mimetype ( mime , ** options ) _logger ( ) . debug ( 'lexer for mimetype (%s): %r' , mime , self . _lexer ) | Sets the pygments lexer from mime type . |
46,588 | def highlight_block ( self , text , block ) : if self . color_scheme . name != self . _pygments_style : self . _pygments_style = self . color_scheme . name self . _update_style ( ) original_text = text if self . editor and self . _lexer and self . enabled : if block . blockNumber ( ) : prev_data = self . _prev_block . userData ( ) if prev_data : if hasattr ( prev_data , "syntax_stack" ) : self . _lexer . _saved_state_stack = prev_data . syntax_stack elif hasattr ( self . _lexer , '_saved_state_stack' ) : del self . _lexer . _saved_state_stack index = 0 usd = block . userData ( ) if usd is None : usd = TextBlockUserData ( ) block . setUserData ( usd ) tokens = list ( self . _lexer . get_tokens ( text ) ) for token , text in tokens : length = len ( text ) fmt = self . _get_format ( token ) if token in [ Token . Literal . String , Token . Literal . String . Doc , Token . Comment ] : fmt . setObjectType ( fmt . UserObject ) self . setFormat ( index , length , fmt ) index += length if hasattr ( self . _lexer , '_saved_state_stack' ) : setattr ( usd , "syntax_stack" , self . _lexer . _saved_state_stack ) del self . _lexer . _saved_state_stack text = original_text expression = QRegExp ( r'\s+' ) index = expression . indexIn ( text , 0 ) while index >= 0 : index = expression . pos ( 0 ) length = len ( expression . cap ( 0 ) ) self . setFormat ( index , length , self . _get_format ( Whitespace ) ) index = expression . indexIn ( text , index + length ) self . _prev_block = block | Highlights the block using a pygments lexer . |
46,589 | def goto_line ( self , line , column = 0 , move = True ) : text_cursor = self . move_cursor_to ( line ) if column : text_cursor . movePosition ( text_cursor . Right , text_cursor . MoveAnchor , column ) if move : block = text_cursor . block ( ) try : folding_panel = self . _editor . panels . get ( 'FoldingPanel' ) except KeyError : pass else : from pyqode . core . api . folding import FoldScope if not block . isVisible ( ) : block = FoldScope . find_parent_scope ( block ) if TextBlockHelper . is_collapsed ( block ) : folding_panel . toggle_fold_trigger ( block ) self . _editor . setTextCursor ( text_cursor ) return text_cursor | Moves the text cursor to the specified position .. |
46,590 | def select_lines ( self , start = 0 , end = - 1 , apply_selection = True ) : editor = self . _editor if end == - 1 : end = self . line_count ( ) - 1 if start < 0 : start = 0 text_cursor = self . move_cursor_to ( start ) if end > start : text_cursor . movePosition ( text_cursor . Down , text_cursor . KeepAnchor , end - start ) text_cursor . movePosition ( text_cursor . EndOfLine , text_cursor . KeepAnchor ) elif end < start : text_cursor . movePosition ( text_cursor . EndOfLine , text_cursor . MoveAnchor ) text_cursor . movePosition ( text_cursor . Up , text_cursor . KeepAnchor , start - end ) text_cursor . movePosition ( text_cursor . StartOfLine , text_cursor . KeepAnchor ) else : text_cursor . movePosition ( text_cursor . EndOfLine , text_cursor . KeepAnchor ) if apply_selection : editor . setTextCursor ( text_cursor ) return text_cursor | Selects entire lines between start and end line numbers . |
46,591 | def line_indent ( self , line_nbr = None ) : if line_nbr is None : line_nbr = self . current_line_nbr ( ) elif isinstance ( line_nbr , QtGui . QTextBlock ) : line_nbr = line_nbr . blockNumber ( ) line = self . line_text ( line_nbr ) indentation = len ( line ) - len ( line . lstrip ( ) ) return indentation | Returns the indent level of the specified line |
46,592 | def get_right_word ( self , cursor = None ) : if cursor is None : cursor = self . _editor . textCursor ( ) cursor . movePosition ( QtGui . QTextCursor . WordRight , QtGui . QTextCursor . KeepAnchor ) return cursor . selectedText ( ) . strip ( ) | Gets the character on the right of the text cursor . |
46,593 | def search_text ( self , text_cursor , search_txt , search_flags ) : def compare_cursors ( cursor_a , cursor_b ) : return ( cursor_b . selectionStart ( ) >= cursor_a . selectionStart ( ) and cursor_b . selectionEnd ( ) <= cursor_a . selectionEnd ( ) ) text_document = self . _editor . document ( ) occurrences = [ ] index = - 1 cursor = text_document . find ( search_txt , 0 , search_flags ) original_cursor = text_cursor while not cursor . isNull ( ) : if compare_cursors ( cursor , original_cursor ) : index = len ( occurrences ) occurrences . append ( ( cursor . selectionStart ( ) , cursor . selectionEnd ( ) ) ) cursor . setPosition ( cursor . position ( ) + 1 ) cursor = text_document . find ( search_txt , cursor , search_flags ) return occurrences , index | Searches a text in a text document . |
46,594 | def match_select ( self , ignored_symbols = None ) : def filter_matching ( ignored_symbols , matching ) : if ignored_symbols is not None : for symbol in matching . keys ( ) : if symbol in ignored_symbols : matching . pop ( symbol ) return matching def find_opening_symbol ( cursor , matching ) : start_pos = None opening_char = None closed = { k : 0 for k in matching . values ( ) if k not in [ '"' , "'" ] } stop = False while not stop and not cursor . atStart ( ) : cursor . clearSelection ( ) cursor . movePosition ( cursor . Left , cursor . KeepAnchor ) char = cursor . selectedText ( ) if char in closed . keys ( ) : closed [ char ] += 1 elif char in matching . keys ( ) : opposite = matching [ char ] if opposite in closed . keys ( ) and closed [ opposite ] : closed [ opposite ] -= 1 continue else : start_pos = cursor . position ( ) + 1 stop = True opening_char = char return opening_char , start_pos def find_closing_symbol ( cursor , matching , opening_char , original_pos ) : end_pos = None cursor . setPosition ( original_pos ) rev_matching = { v : k for k , v in matching . items ( ) } opened = { k : 0 for k in rev_matching . values ( ) if k not in [ '"' , "'" ] } stop = False while not stop and not cursor . atEnd ( ) : cursor . clearSelection ( ) cursor . movePosition ( cursor . Right , cursor . KeepAnchor ) char = cursor . selectedText ( ) if char in opened . keys ( ) : opened [ char ] += 1 elif char in rev_matching . keys ( ) : opposite = rev_matching [ char ] if opposite in opened . keys ( ) and opened [ opposite ] : opened [ opposite ] -= 1 continue elif matching [ opening_char ] == char : end_pos = cursor . position ( ) - 1 stop = True return end_pos matching = { '(' : ')' , '{' : '}' , '[' : ']' , '"' : '"' , "'" : "'" } filter_matching ( ignored_symbols , matching ) cursor = self . _editor . textCursor ( ) original_pos = cursor . position ( ) end_pos = None opening_char , start_pos = find_opening_symbol ( cursor , matching ) if opening_char : end_pos = find_closing_symbol ( cursor , matching , opening_char , original_pos ) if start_pos and end_pos : cursor . setPosition ( start_pos ) cursor . movePosition ( cursor . Right , cursor . KeepAnchor , end_pos - start_pos ) self . _editor . setTextCursor ( cursor ) return True else : return False | Performs matched selection selects text between matching quotes or parentheses . |
46,595 | def main ( ) : parser = argparse . ArgumentParser ( ) subparsers = parser . add_subparsers ( ) appengine . register_commands ( subparsers ) requirements . register_commands ( subparsers ) pylint . register_commands ( subparsers ) args = parser . parse_args ( ) args . func ( args ) | Entrypoint for the console script gcp - devrel - py - tools . |
46,596 | async def outlook ( self ) -> dict : try : return await self . _request ( 'get' , 'https://www.pollen.com/api/forecast/outlook' ) except RequestError as err : if '404' in str ( err ) : raise InvalidZipError ( 'No data returned for ZIP code' ) else : raise RequestError ( err ) | Get allergen outlook . |
46,597 | def dev ( ) : env . roledefs = { 'web' : [ '192.168.1.2' ] , 'lb' : [ '192.168.1.2' ] , } env . user = 'vagrant' env . backends = env . roledefs [ 'web' ] env . server_name = 'django_search_model-dev.net' env . short_server_name = 'django_search_model-dev' env . static_folder = '/site_media/' env . server_ip = '192.168.1.2' env . no_shared_sessions = False env . server_ssl_on = False env . goal = 'dev' env . socket_port = '8001' env . map_settings = { } execute ( build_env ) | Define dev stage |
46,598 | def install_postgres ( user = None , dbname = None , password = None ) : execute ( pydiploy . django . install_postgres_server , user = user , dbname = dbname , password = password ) | Install Postgres on remote |
46,599 | def field_to_dict ( fields ) : field_dict = { } for field in fields : d_tmp = field_dict for part in field . split ( LOOKUP_SEP ) [ : - 1 ] : d_tmp = d_tmp . setdefault ( part , { } ) d_tmp = d_tmp . setdefault ( field . split ( LOOKUP_SEP ) [ - 1 ] , deepcopy ( EMPTY_DICT ) ) . update ( deepcopy ( EMPTY_DICT ) ) return field_dict | Build dictionnary which dependancy for each field related to root |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.