idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
10,900
def refreshButton ( self ) : collapsed = self . isCollapsed ( ) btn = self . _collapseButton if not btn : return btn . setMaximumSize ( MAX_SIZE , MAX_SIZE ) if self . orientation ( ) == Qt . Vertical : btn . setMaximumHeight ( 12 ) else : btn . setMaximumWidth ( 12 ) icon = '' if self . orientation ( ) == Qt . Vertical : if collapsed : self . setFixedWidth ( self . _collapsedSize ) btn . setMaximumHeight ( MAX_SIZE ) btn . setArrowType ( Qt . RightArrow ) else : self . setMaximumWidth ( MAX_SIZE ) self . _precollapseSize = None btn . setMaximumHeight ( 12 ) btn . setArrowType ( Qt . LeftArrow ) else : if collapsed : self . setFixedHeight ( self . _collapsedSize ) btn . setMaximumWidth ( MAX_SIZE ) btn . setArrowType ( Qt . DownArrow ) else : self . setMaximumHeight ( 1000 ) self . _precollapseSize = None btn . setMaximumWidth ( 12 ) btn . setArrowType ( Qt . UpArrow ) for index in range ( 1 , self . layout ( ) . count ( ) ) : item = self . layout ( ) . itemAt ( index ) if not item . widget ( ) : continue if collapsed : item . widget ( ) . setMaximumSize ( 0 , 0 ) else : item . widget ( ) . setMaximumSize ( MAX_SIZE , MAX_SIZE ) if not self . isCollapsable ( ) : btn . hide ( ) else : btn . show ( )
Refreshes the button for this toolbar .
10,901
def match ( self , url ) : return list ( { message for message in self . active ( ) if message . is_global or message . match ( url ) } )
Return a list of all active Messages which match the given URL .
10,902
def paint ( self , painter , option , widget ) : scene = self . scene ( ) if not scene : return scene . chart ( ) . renderer ( ) . drawItem ( self , painter , option )
Draws this item with the inputed painter . This will call the scene s renderer to draw this item .
10,903
def is_pg_at_least_nine_two ( self ) : if self . _is_pg_at_least_nine_two is None : results = self . version ( ) regex = re . compile ( "PostgreSQL (\d+\.\d+\.\d+) on" ) matches = regex . match ( results [ 0 ] . version ) version = matches . groups ( ) [ 0 ] if version > '9.2.0' : self . _is_pg_at_least_nine_two = True else : self . _is_pg_at_least_nine_two = False return self . _is_pg_at_least_nine_two
Some queries have different syntax depending what version of postgres we are querying against .
10,904
def execute ( self , statement ) : sql = statement . replace ( '\n' , '' ) sql = ' ' . join ( sql . split ( ) ) self . cursor . execute ( sql ) return self . cursor . fetchall ( )
Execute the given sql statement .
10,905
def calls ( self , truncate = False ) : if self . pg_stat_statement ( ) : if truncate : select = else : select = 'SELECT query,' return self . execute ( sql . CALLS . format ( select = select ) ) else : return [ self . get_missing_pg_stat_statement_error ( ) ]
Show 10 most frequently called queries . Requires the pg_stat_statements Postgres module to be installed .
10,906
def blocking ( self ) : return self . execute ( sql . BLOCKING . format ( query_column = self . query_column , pid_column = self . pid_column ) )
Display queries holding locks other queries are waiting to be released .
10,907
def outliers ( self , truncate = False ) : if self . pg_stat_statement ( ) : if truncate : query = else : query = 'query' return self . execute ( sql . OUTLIERS . format ( query = query ) ) else : return [ self . get_missing_pg_stat_statement_error ( ) ]
Show 10 queries that have longest execution time in aggregate . Requires the pg_stat_statments Postgres module to be installed .
10,908
def long_running_queries ( self ) : if self . is_pg_at_least_nine_two ( ) : idle = "AND state <> 'idle'" else : idle = "AND current_query <> '<IDLE>'" return self . execute ( sql . LONG_RUNNING_QUERIES . format ( pid_column = self . pid_column , query_column = self . query_column , idle = idle ) )
Show all queries longer than five minutes by descending duration .
10,909
def locks ( self ) : return self . execute ( sql . LOCKS . format ( pid_column = self . pid_column , query_column = self . query_column ) )
Display queries with active locks .
10,910
def ps ( self ) : if self . is_pg_at_least_nine_two ( ) : idle = "AND state <> 'idle'" else : idle = "AND current_query <> '<IDLE>'" return self . execute ( sql . PS . format ( pid_column = self . pid_column , query_column = self . query_column , idle = idle ) )
View active queries with execution time .
10,911
def publish ( self , metrics , config ) : if len ( metrics ) > 0 : with open ( config [ "file" ] , 'a' ) as outfile : for metric in metrics : outfile . write ( json_format . MessageToJson ( metric . _pb , including_default_value_fields = True ) )
Publishes metrics to a file in JSON format .
10,912
def clean_name ( self ) : "Avoid name clashes between static and dynamic attributes." name = self . cleaned_data [ 'name' ] reserved_names = self . _meta . model . _meta . get_all_field_names ( ) if name not in reserved_names : return name raise ValidationError ( _ ( 'Attribute name must not clash with reserved names' ' ("%s")' ) % '", "' . join ( reserved_names ) )
Avoid name clashes between static and dynamic attributes .
10,913
def save ( self , commit = True ) : if self . errors : raise ValueError ( "The %s could not be saved because the data didn't" " validate." % self . instance . _meta . object_name ) instance = super ( BaseDynamicEntityForm , self ) . save ( commit = False ) for name in instance . get_schema_names ( ) : value = self . cleaned_data . get ( name ) setattr ( instance , name , value ) if commit : instance . save ( ) return instance
Saves this form s cleaned_data into model instance self . instance and related EAV attributes .
10,914
def refresh ( self ) : table = self . tableType ( ) search = nativestring ( self . _pywidget . text ( ) ) if search == self . _lastSearch : return self . _lastSearch = search if not search : return if search in self . _cache : records = self . _cache [ search ] else : records = table . select ( where = self . baseQuery ( ) , order = self . order ( ) ) records = list ( records . search ( search , limit = self . limit ( ) ) ) self . _cache [ search ] = records self . _records = records self . model ( ) . setStringList ( map ( str , self . _records ) ) self . complete ( )
Refreshes the contents of the completer based on the current text .
10,915
def initialize ( self , force = False ) : if force or ( self . isVisible ( ) and not self . isInitialized ( ) and not self . signalsBlocked ( ) ) : self . _initialized = True self . initialized . emit ( )
Initializes the view if it is visible or being loaded .
10,916
def destroySingleton ( cls ) : singleton_key = '_{0}__singleton' . format ( cls . __name__ ) singleton = getattr ( cls , singleton_key , None ) if singleton is not None : setattr ( cls , singleton_key , None ) singleton . close ( ) singleton . deleteLater ( )
Destroys the singleton instance of this class if one exists .
10,917
def adjustSize ( self ) : align = self . closeAlignment ( ) if align & QtCore . Qt . AlignTop : y = 6 else : y = self . height ( ) - 38 if align & QtCore . Qt . AlignLeft : x = 6 else : x = self . width ( ) - 38 self . _closeButton . move ( x , y ) widget = self . centralWidget ( ) if widget is not None : center = self . rect ( ) . center ( ) widget . move ( center . x ( ) - widget . width ( ) / 2 , center . y ( ) - widget . height ( ) / 2 )
Adjusts the size of this widget as the parent resizes .
10,918
def keyPressEvent ( self , event ) : if event . key ( ) == QtCore . Qt . Key_Escape : self . reject ( ) super ( XOverlayWidget , self ) . keyPressEvent ( event )
Exits the modal window on an escape press .
10,919
def eventFilter ( self , object , event ) : if object == self . parent ( ) and event . type ( ) == QtCore . QEvent . Resize : self . resize ( event . size ( ) ) elif event . type ( ) == QtCore . QEvent . Close : self . setResult ( 0 ) return False
Resizes this overlay as the widget resizes .
10,920
def resizeEvent ( self , event ) : super ( XOverlayWidget , self ) . resizeEvent ( event ) self . adjustSize ( )
Handles a resize event for this overlay centering the central widget if one is found .
10,921
def setCentralWidget ( self , widget ) : self . _centralWidget = widget if widget is not None : widget . setParent ( self ) widget . installEventFilter ( self ) effect = QtGui . QGraphicsDropShadowEffect ( self ) effect . setColor ( QtGui . QColor ( 'black' ) ) effect . setBlurRadius ( 80 ) effect . setOffset ( 0 , 0 ) widget . setGraphicsEffect ( effect )
Sets the central widget for this overlay to the inputed widget .
10,922
def setClosable ( self , state ) : self . _closable = state if state : self . _closeButton . show ( ) else : self . _closeButton . hide ( )
Sets whether or not the user should be able to close this overlay widget .
10,923
def setVisible ( self , state ) : super ( XOverlayWidget , self ) . setVisible ( state ) if not state : self . setResult ( 0 )
Closes this widget and kills the result .
10,924
def showEvent ( self , event ) : super ( XOverlayWidget , self ) . showEvent ( event ) self . raise_ ( ) self . _closeButton . setVisible ( self . isClosable ( ) ) widget = self . centralWidget ( ) if widget : center = self . rect ( ) . center ( ) start_x = end_x = center . x ( ) - widget . width ( ) / 2 start_y = - widget . height ( ) end_y = center . y ( ) - widget . height ( ) / 2 start = QtCore . QPoint ( start_x , start_y ) end = QtCore . QPoint ( end_x , end_y ) anim = QtCore . QPropertyAnimation ( self ) anim . setPropertyName ( 'pos' ) anim . setTargetObject ( widget ) anim . setStartValue ( start ) anim . setEndValue ( end ) anim . setDuration ( 500 ) anim . setEasingCurve ( QtCore . QEasingCurve . InOutQuad ) anim . finished . connect ( anim . deleteLater ) anim . start ( )
Ensures this widget is the top - most widget for its parent .
10,925
def modal ( widget , parent = None , align = QtCore . Qt . AlignTop | QtCore . Qt . AlignRight , blurred = True ) : if parent is None : parent = QtGui . QApplication . instance ( ) . activeWindow ( ) overlay = XOverlayWidget ( parent ) overlay . setAttribute ( QtCore . Qt . WA_DeleteOnClose ) overlay . setCentralWidget ( widget ) overlay . setCloseAlignment ( align ) overlay . show ( ) return overlay
Creates a modal dialog for this overlay with the inputed widget . If the user accepts the widget then 1 will be returned otherwise 0 will be returned .
10,926
def applyCommand ( self ) : cursor = self . textCursor ( ) cursor . movePosition ( cursor . EndOfLine ) line = projex . text . nativestring ( cursor . block ( ) . text ( ) ) at_end = cursor . atEnd ( ) modifiers = QApplication . instance ( ) . keyboardModifiers ( ) mod_mode = at_end or modifiers == Qt . ShiftModifier if mod_mode and line . endswith ( ':' ) : cursor . movePosition ( cursor . EndOfLine ) line = re . sub ( '^>>> ' , '' , line ) line = re . sub ( '^\.\.\. ' , '' , line ) count = len ( line ) - len ( line . lstrip ( ) ) + 4 self . insertPlainText ( '\n... ' + count * ' ' ) return False elif mod_mode and line . startswith ( '...' ) and ( line . strip ( ) != '...' or not at_end ) : cursor . movePosition ( cursor . EndOfLine ) line = re . sub ( '^\.\.\. ' , '' , line ) count = len ( line ) - len ( line . lstrip ( ) ) self . insertPlainText ( '\n... ' + count * ' ' ) return False elif line . startswith ( '>>>' ) or line . startswith ( '...' ) : line = projex . text . nativestring ( cursor . block ( ) . text ( ) ) while line . startswith ( '...' ) : cursor . movePosition ( cursor . PreviousBlock ) line = projex . text . nativestring ( cursor . block ( ) . text ( ) ) cursor . movePosition ( cursor . EndOfLine ) line = projex . text . nativestring ( cursor . block ( ) . text ( ) ) ended = False lines = [ ] while True : lines . append ( line ) if cursor . atEnd ( ) : ended = True break cursor . movePosition ( cursor . NextBlock ) cursor . movePosition ( cursor . EndOfLine ) line = projex . text . nativestring ( cursor . block ( ) . text ( ) ) if not line . startswith ( '...' ) : break command = '\n' . join ( lines ) if not ( ended and command ) : self . waitForInput ( ) self . insertPlainText ( command . replace ( '>>> ' , '' ) ) cursor . movePosition ( cursor . End ) return False else : self . waitForInput ( ) return False self . executeCommand ( command ) return True
Applies the current line of code as an interactive python command .
10,927
def gotoHome ( self ) : mode = QTextCursor . MoveAnchor if QApplication . instance ( ) . keyboardModifiers ( ) == Qt . ShiftModifier : mode = QTextCursor . KeepAnchor cursor = self . textCursor ( ) block = projex . text . nativestring ( cursor . block ( ) . text ( ) ) cursor . movePosition ( QTextCursor . StartOfBlock , mode ) if block . startswith ( '>>> ' ) : cursor . movePosition ( QTextCursor . Right , mode , 4 ) elif block . startswith ( '... ' ) : match = re . match ( '...\s*' , block ) cursor . movePosition ( QTextCursor . Right , mode , match . end ( ) ) self . setTextCursor ( cursor )
Navigates to the home position for the edit .
10,928
def waitForInput ( self ) : self . _waitingForInput = False try : if self . isDestroyed ( ) or self . isReadOnly ( ) : return except RuntimeError : return self . moveCursor ( QTextCursor . End ) if self . textCursor ( ) . block ( ) . text ( ) == '>>> ' : return newln = '>>> ' if projex . text . nativestring ( self . textCursor ( ) . block ( ) . text ( ) ) : newln = '\n' + newln self . setCurrentMode ( 'standard' ) self . insertPlainText ( newln ) self . scrollToEnd ( ) self . _blankCache = ''
Inserts a new input command into the console editor .
10,929
def accept ( self ) : for i in range ( self . uiConfigSTACK . count ( ) ) : widget = self . uiConfigSTACK . widget ( i ) if ( not widget ) : continue if ( not widget . save ( ) ) : self . uiConfigSTACK . setCurrentWidget ( widget ) return False for i in range ( self . uiConfigSTACK . count ( ) ) : widget = self . uiConfigSTACK . widget ( i ) if ( not widget ) : continue widget . close ( ) if ( self == XConfigDialog . _instance ) : XConfigDialog . _instance = None super ( XConfigDialog , self ) . accept ( )
Saves all the current widgets and closes down .
10,930
def reject ( self ) : if ( self == XConfigDialog . _instance ) : XConfigDialog . _instance = None super ( XConfigDialog , self ) . reject ( )
Overloads the reject method to clear up the instance variable .
10,931
def showConfig ( self ) : item = self . uiPluginTREE . currentItem ( ) if not isinstance ( item , PluginItem ) : return plugin = item . plugin ( ) widget = self . findChild ( QWidget , plugin . uniqueName ( ) ) if ( not widget ) : widget = plugin . createWidget ( self ) widget . setObjectName ( plugin . uniqueName ( ) ) self . uiConfigSTACK . addWidget ( widget ) self . uiConfigSTACK . setCurrentWidget ( widget )
Show the config widget for the currently selected plugin .
10,932
def cli ( server , port , client ) : tn = telnetlib . Telnet ( host = server , port = port ) tn . write ( 'kill %s\n' % client . encode ( 'utf-8' ) ) tn . write ( 'exit\n' ) os . _exit ( 0 )
OpenVPN client_kill method
10,933
def adjustButtons ( self ) : tabbar = self . tabBar ( ) tabbar . adjustSize ( ) w = self . width ( ) - self . _optionsButton . width ( ) - 2 self . _optionsButton . move ( w , 0 ) if self . count ( ) : need_update = self . _addButton . property ( 'alone' ) != False if need_update : self . _addButton . setProperty ( 'alone' , False ) self . _addButton . move ( tabbar . width ( ) , 1 ) self . _addButton . setFixedHeight ( tabbar . height ( ) ) else : need_update = self . _addButton . property ( 'alone' ) != True if need_update : self . _addButton . setProperty ( 'alone' , True ) self . _addButton . move ( tabbar . width ( ) + 2 , 1 ) self . _addButton . stackUnder ( self . currentWidget ( ) ) if need_update : app = QApplication . instance ( ) app . setStyleSheet ( app . styleSheet ( ) )
Updates the position of the buttons based on the current geometry .
10,934
def publish ( self , message , routing_key = None ) : if routing_key is None : routing_key = self . routing_key return self . client . publish_to_exchange ( self . name , message = message , routing_key = routing_key )
Publish message to exchange
10,935
def publish ( self , message ) : return self . client . publish_to_queue ( self . name , message = message )
Publish message to queue
10,936
def adjustContentsMargins ( self ) : anchor = self . anchor ( ) mode = self . currentMode ( ) if ( mode == XPopupWidget . Mode . Dialog ) : self . setContentsMargins ( 0 , 0 , 0 , 0 ) elif ( anchor & ( XPopupWidget . Anchor . TopLeft | XPopupWidget . Anchor . TopCenter | XPopupWidget . Anchor . TopRight ) ) : self . setContentsMargins ( 0 , self . popupPadding ( ) + 5 , 0 , 0 ) elif ( anchor & ( XPopupWidget . Anchor . BottomLeft | XPopupWidget . Anchor . BottomCenter | XPopupWidget . Anchor . BottomRight ) ) : self . setContentsMargins ( 0 , 0 , 0 , self . popupPadding ( ) ) elif ( anchor & ( XPopupWidget . Anchor . LeftTop | XPopupWidget . Anchor . LeftCenter | XPopupWidget . Anchor . LeftBottom ) ) : self . setContentsMargins ( self . popupPadding ( ) , 0 , 0 , 0 ) else : self . setContentsMargins ( 0 , 0 , self . popupPadding ( ) , 0 ) self . adjustMask ( )
Adjusts the contents for this widget based on the anchor and \ mode .
10,937
def adjustMask ( self ) : if self . currentMode ( ) == XPopupWidget . Mode . Dialog : self . clearMask ( ) return path = self . borderPath ( ) bitmap = QBitmap ( self . width ( ) , self . height ( ) ) bitmap . fill ( QColor ( 'white' ) ) with XPainter ( bitmap ) as painter : painter . setRenderHint ( XPainter . Antialiasing ) pen = QPen ( QColor ( 'black' ) ) pen . setWidthF ( 0.75 ) painter . setPen ( pen ) painter . setBrush ( QColor ( 'black' ) ) painter . drawPath ( path ) self . setMask ( bitmap )
Updates the alpha mask for this popup widget .
10,938
def adjustSize ( self ) : widget = self . centralWidget ( ) if widget is None : super ( XPopupWidget , self ) . adjustSize ( ) return widget . adjustSize ( ) hint = widget . minimumSizeHint ( ) size = widget . minimumSize ( ) width = max ( size . width ( ) , hint . width ( ) ) height = max ( size . height ( ) , hint . height ( ) ) width += 20 height += 20 if self . _buttonBoxVisible : height += self . buttonBox ( ) . height ( ) + 10 if self . _titleBarVisible : height += max ( self . _dialogButton . height ( ) , self . _closeButton . height ( ) ) + 10 curr_w = self . width ( ) curr_h = self . height ( ) anchor = self . anchor ( ) if anchor & ( self . Anchor . LeftBottom | self . Anchor . RightBottom | self . Anchor . BottomLeft | self . Anchor . BottomCenter | self . Anchor . BottomRight ) : delta_y = height - curr_h elif anchor & ( self . Anchor . LeftCenter | self . Anchor . RightCenter ) : delta_y = ( height - curr_h ) / 2 else : delta_y = 0 if anchor & ( self . Anchor . RightTop | self . Anchor . RightCenter | self . Anchor . RightTop | self . Anchor . TopRight ) : delta_x = width - curr_w elif anchor & ( self . Anchor . TopCenter | self . Anchor . BottomCenter ) : delta_x = ( width - curr_w ) / 2 else : delta_x = 0 self . setMinimumSize ( width , height ) self . resize ( width , height ) pos = self . pos ( ) pos . setX ( pos . x ( ) - delta_x ) pos . setY ( pos . y ( ) - delta_y ) self . move ( pos )
Adjusts the size of this popup to best fit the new widget size .
10,939
def close ( self ) : widget = self . centralWidget ( ) if widget and not widget . close ( ) : return super ( XPopupWidget , self ) . close ( )
Closes the popup widget and central widget .
10,940
def refreshLabels ( self ) : itemCount = self . itemCount ( ) title = self . itemsTitle ( ) if ( not itemCount ) : self . _itemsLabel . setText ( ' %s per page' % title ) else : msg = ' %s per page, %i %s total' % ( title , itemCount , title ) self . _itemsLabel . setText ( msg )
Refreshes the labels to display the proper title and count information .
10,941
def import_modules_from_package ( package ) : path = [ os . path . dirname ( __file__ ) , '..' ] + package . split ( '.' ) path = os . path . join ( * path ) for root , dirs , files in os . walk ( path ) : for filename in files : if filename . startswith ( '__' ) or not filename . endswith ( '.py' ) : continue new_package = "." . join ( root . split ( os . sep ) ) . split ( "...." ) [ 1 ] module_name = '%s.%s' % ( new_package , filename [ : - 3 ] ) if module_name not in sys . modules : __import__ ( module_name )
Import modules from package and append into sys . modules
10,942
def request ( self , request_method , api_method , * args , ** kwargs ) : url = self . _build_url ( api_method ) resp = requests . request ( request_method , url , * args , ** kwargs ) try : rv = resp . json ( ) except ValueError : raise RequestFailedError ( resp , 'not a json body' ) if not resp . ok : raise RequestFailedError ( resp , rv . get ( 'error' ) ) return rv
Perform a request .
10,943
def updateCurrentValue ( self , value ) : xsnap = None ysnap = None if value != self . endValue ( ) : xsnap = self . targetObject ( ) . isXSnappedToGrid ( ) ysnap = self . targetObject ( ) . isYSnappedToGrid ( ) self . targetObject ( ) . setXSnapToGrid ( False ) self . targetObject ( ) . setYSnapToGrid ( False ) super ( XNodeAnimation , self ) . updateCurrentValue ( value ) if value != self . endValue ( ) : self . targetObject ( ) . setXSnapToGrid ( xsnap ) self . targetObject ( ) . setYSnapToGrid ( ysnap )
Disables snapping during the current value update to ensure a smooth transition for node animations . Since this can only be called via code we don t need to worry about snapping to the grid for a user .
10,944
def adjustTitleFont ( self ) : left , top , right , bottom = self . contentsMargins ( ) r = self . roundingRadius ( ) left += 5 + r / 2 top += 5 + r / 2 right += 5 + r / 2 bottom += 5 + r / 2 r = self . rect ( ) rect_l = r . left ( ) + left rect_r = r . right ( ) - right rect_t = r . top ( ) + top rect_b = r . bottom ( ) - bottom rect = QRect ( rect_l , rect_t , rect_r - rect_l , rect_b - rect_t ) if rect . width ( ) < 10 : return font = XFont ( QApplication . font ( ) ) font . adaptSize ( self . displayName ( ) , rect , wordWrap = self . wordWrap ( ) ) self . _titleFont = font
Adjusts the font used for the title based on the current with and \ display name .
10,945
def adjustSize ( self ) : cell = self . scene ( ) . cellWidth ( ) * 2 minheight = cell minwidth = 2 * cell metrics = QFontMetrics ( QApplication . font ( ) ) width = metrics . width ( self . displayName ( ) ) + 20 width = ( ( width / cell ) * cell ) + ( cell % width ) height = self . rect ( ) . height ( ) icon = self . icon ( ) if icon and not icon . isNull ( ) : width += self . iconSize ( ) . width ( ) + 2 height = max ( height , self . iconSize ( ) . height ( ) + 2 ) w = max ( width , minwidth ) h = max ( height , minheight ) max_w = self . maximumWidth ( ) max_h = self . maximumHeight ( ) if max_w is not None : w = min ( w , max_w ) if max_h is not None : h = min ( h , max_h ) self . setMinimumWidth ( w ) self . setMinimumHeight ( h ) self . rebuild ( )
Adjusts the size of this node to support the length of its contents .
10,946
def isEnabled ( self ) : if ( self . _disableWithLayer and self . _layer ) : lenabled = self . _layer . isEnabled ( ) else : lenabled = True return self . _enabled and lenabled
Returns whether or not this node is enabled .
10,947
def popitem ( self ) : try : item = dict . popitem ( self ) return ( item [ 0 ] , item [ 1 ] [ 0 ] ) except KeyError , e : raise BadRequestKeyError ( str ( e ) )
Pop an item from the dict .
10,948
def emitCurrentRecordChanged ( self ) : record = unwrapVariant ( self . itemData ( self . currentIndex ( ) , Qt . UserRole ) ) if not Table . recordcheck ( record ) : record = None self . _currentRecord = record if not self . signalsBlocked ( ) : self . _changedRecord = record self . currentRecordChanged . emit ( record )
Emits the current record changed signal for this combobox provided \ the signals aren t blocked .
10,949
def emitCurrentRecordEdited ( self ) : if self . _changedRecord == - 1 : return if self . signalsBlocked ( ) : return record = self . _changedRecord self . _changedRecord = - 1 self . currentRecordEdited . emit ( record )
Emits the current record edited signal for this combobox provided the signals aren t blocked and the record has changed since the last time .
10,950
def focusInEvent ( self , event ) : self . _changedRecord = - 1 super ( XOrbRecordBox , self ) . focusInEvent ( event )
When this widget loses focus try to emit the record changed event signal .
10,951
def hidePopup ( self ) : if self . _treePopupWidget and self . showTreePopup ( ) : self . _treePopupWidget . close ( ) super ( XOrbRecordBox , self ) . hidePopup ( )
Overloads the hide popup method to handle when the user hides the popup widget .
10,952
def markLoadingStarted ( self ) : if self . isThreadEnabled ( ) : XLoaderWidget . start ( self ) if self . showTreePopup ( ) : tree = self . treePopupWidget ( ) tree . setCursor ( Qt . WaitCursor ) tree . clear ( ) tree . setUpdatesEnabled ( False ) tree . blockSignals ( True ) self . _baseHints = ( self . hint ( ) , tree . hint ( ) ) tree . setHint ( 'Loading records...' ) self . setHint ( 'Loading records...' ) else : self . _baseHints = ( self . hint ( ) , '' ) self . setHint ( 'Loading records...' ) self . setCursor ( Qt . WaitCursor ) self . blockSignals ( True ) self . setUpdatesEnabled ( False ) self . clear ( ) use_dummy = not self . isRequired ( ) or self . isCheckable ( ) if use_dummy : self . addItem ( '' ) self . loadingStarted . emit ( )
Marks this widget as loading records .
10,953
def markLoadingFinished ( self ) : XLoaderWidget . stop ( self , force = True ) hint , tree_hint = self . _baseHints self . setHint ( hint ) if self . showTreePopup ( ) : tree = self . treePopupWidget ( ) tree . setHint ( tree_hint ) tree . unsetCursor ( ) tree . setUpdatesEnabled ( True ) tree . blockSignals ( False ) self . unsetCursor ( ) self . blockSignals ( False ) self . setUpdatesEnabled ( True ) self . loadingFinished . emit ( )
Marks this widget as finished loading records .
10,954
def destroy ( self ) : try : tree = self . treeWidget ( ) tree . destroyed . disconnect ( self . destroy ) except StandardError : pass for movie in set ( self . _movies . values ( ) ) : try : movie . frameChanged . disconnect ( self . _updateFrame ) except StandardError : pass
Destroyes this item by disconnecting any signals that may exist . This is called when the tree clears itself or is deleted . If you are manually removing an item you should call the destroy method yourself . This is required since Python allows for non - QObject connections and since QTreeWidgetItem s are not QObjects they do not properly handle being destroyed with connections on them .
10,955
def ensureVisible ( self ) : parent = self . parent ( ) while parent : parent . setExpanded ( True ) parent = parent . parent ( )
Expands all the parents of this item to ensure that it is visible to the user .
10,956
def initGroupStyle ( self , useIcons = True , columnCount = None ) : flags = self . flags ( ) if flags & QtCore . Qt . ItemIsSelectable : flags ^= QtCore . Qt . ItemIsSelectable self . setFlags ( flags ) if useIcons : ico = QtGui . QIcon ( resources . find ( 'img/treeview/triangle_right.png' ) ) expand_ico = QtGui . QIcon ( resources . find ( 'img/treeview/triangle_down.png' ) ) self . setIcon ( 0 , ico ) self . setExpandedIcon ( 0 , expand_ico ) palette = QtGui . QApplication . palette ( ) line_clr = palette . color ( palette . Mid ) base_clr = palette . color ( palette . Button ) text_clr = palette . color ( palette . ButtonText ) gradient = QtGui . QLinearGradient ( ) gradient . setColorAt ( 0.00 , line_clr ) gradient . setColorAt ( 0.03 , line_clr ) gradient . setColorAt ( 0.04 , base_clr . lighter ( 105 ) ) gradient . setColorAt ( 0.25 , base_clr ) gradient . setColorAt ( 0.96 , base_clr . darker ( 105 ) ) gradient . setColorAt ( 0.97 , line_clr ) gradient . setColorAt ( 1.00 , line_clr ) h = self . _fixedHeight if not h : h = self . sizeHint ( 0 ) . height ( ) if not h : h = 18 gradient . setStart ( 0.0 , 0.0 ) gradient . setFinalStop ( 0.0 , h ) brush = QtGui . QBrush ( gradient ) tree = self . treeWidget ( ) columnCount = columnCount or ( tree . columnCount ( ) if tree else self . columnCount ( ) ) for i in range ( columnCount ) : self . setForeground ( i , text_clr ) self . setBackground ( i , brush )
Initialzes this item with a grouping style option .
10,957
def takeFromTree ( self ) : tree = self . treeWidget ( ) parent = self . parent ( ) if parent : parent . takeChild ( parent . indexOfChild ( self ) ) else : tree . takeTopLevelItem ( tree . indexOfTopLevelItem ( self ) )
Takes this item from the tree .
10,958
def find ( self , * args , ** kwargs ) : self . print_cursor ( self . collection . find ( * args , ** kwargs ) )
Run the pymongo find command against the default database and collection and paginate the output to the screen .
10,959
def find_one ( self , * args , ** kwargs ) : self . print_doc ( self . collection . find_one ( * args , ** kwargs ) )
Run the pymongo find_one command against the default database and collection and paginate the output to the screen .
10,960
def insert_one ( self , * args , ** kwargs ) : result = self . collection . insert_one ( * args , ** kwargs ) return result . inserted_id
Run the pymongo insert_one command against the default database and collection and returne the inserted ID .
10,961
def insert_many ( self , * args , ** kwargs ) : result = self . collection . insert_many ( * args , ** kwargs ) return result . inserted_ids
Run the pymongo insert_many command against the default database and collection and return the list of inserted IDs .
10,962
def delete_one ( self , * args , ** kwargs ) : result = self . collection . delete_one ( * args , ** kwargs ) return result . raw_result
Run the pymongo delete_one command against the default database and collection and return the deleted IDs .
10,963
def delete_many ( self , * args , ** kwargs ) : result = self . collection . delete_many ( * args , ** kwargs ) return result . raw_result
Run the pymongo delete_many command against the default database and collection and return the deleted IDs .
10,964
def count_documents ( self , filter = { } , * args , ** kwargs ) : result = self . collection . count_documents ( filter , * args , ** kwargs ) return result
Count all the documents in a collection accurately
10,965
def _get_collections ( self , db_names = None ) : if db_names : db_list = db_names else : db_list = self . client . list_database_names ( ) for db_name in db_list : db = self . client . get_database ( db_name ) for col_name in db . list_collection_names ( ) : size = db [ col_name ] . g yield f"{db_name}.{col_name}"
Internal function to return all the collections for every database . include a list of db_names to filter the list of collections .
10,966
def pager ( self , lines ) : try : line_count = 0 if self . _output_filename : print ( f"Output is also going to '{self.output_file}'" ) self . _output_file = open ( self . _output_filename , "a+" ) terminal_columns , terminal_lines = shutil . get_terminal_size ( fallback = ( 80 , 24 ) ) lines_left = terminal_lines for i , l in enumerate ( lines , 1 ) : line_residue = 0 if self . line_numbers : output_line = f"{i:<4} {l}" else : output_line = l line_overflow = int ( len ( output_line ) / terminal_columns ) if line_overflow : line_residue = len ( output_line ) % terminal_columns if line_overflow >= 1 : lines_left = lines_left - line_overflow else : lines_left = lines_left - 1 if line_residue > 1 : lines_left = lines_left - 1 print ( output_line ) if self . _output_file : self . _output_file . write ( f"{l}\n" ) self . _output_file . flush ( ) if ( lines_left - self . overlap - 1 ) <= 0 : if self . paginate : print ( "Hit Return to continue (q or quit to exit)" , end = "" ) user_input = input ( ) if user_input . lower ( ) . strip ( ) in [ "q" , "quit" , "exit" ] : break terminal_columns , terminal_lines = shutil . get_terminal_size ( fallback = ( 80 , 24 ) ) lines_left = terminal_lines if self . _output_file : self . _output_file . close ( ) except KeyboardInterrupt : print ( "ctrl-C..." ) if self . _output_file : self . _output_file . close ( )
Outputs lines to a terminal . It uses shutil . get_terminal_size to determine the height of the terminal . It expects an iterator that returns a line at a time and those lines should be terminated by a valid newline sequence .
10,967
def groupQuery ( self ) : items = self . uiQueryTREE . selectedItems ( ) if ( not len ( items ) > 2 ) : return if ( isinstance ( items [ - 1 ] , XJoinItem ) ) : items = items [ : - 1 ] tree = self . uiQueryTREE parent = items [ 0 ] . parent ( ) if ( not parent ) : parent = tree preceeding = items [ - 1 ] tree . blockSignals ( True ) tree . setUpdatesEnabled ( False ) grp_item = XQueryItem ( parent , Q ( ) , preceeding = preceeding ) for item in items : parent = item . parent ( ) if ( not parent ) : tree . takeTopLevelItem ( tree . indexOfTopLevelItem ( item ) ) else : parent . takeChild ( parent . indexOfChild ( item ) ) grp_item . addChild ( item ) grp_item . update ( ) tree . blockSignals ( False ) tree . setUpdatesEnabled ( True )
Groups the selected items together into a sub query
10,968
def removeQuery ( self ) : items = self . uiQueryTREE . selectedItems ( ) tree = self . uiQueryTREE for item in items : parent = item . parent ( ) if ( parent ) : parent . takeChild ( parent . indexOfChild ( item ) ) else : tree . takeTopLevelItem ( tree . indexOfTopLevelItem ( item ) ) self . setQuery ( self . query ( ) )
Removes the currently selected query .
10,969
def runWizard ( self ) : plugin = self . currentPlugin ( ) if ( plugin and plugin . runWizard ( self ) ) : self . accept ( )
Runs the current wizard .
10,970
def showDescription ( self ) : plugin = self . currentPlugin ( ) if ( not plugin ) : self . uiDescriptionTXT . setText ( '' ) else : self . uiDescriptionTXT . setText ( plugin . description ( ) )
Shows the description for the current plugin in the interface .
10,971
def showWizards ( self ) : self . uiWizardTABLE . clear ( ) item = self . uiPluginTREE . currentItem ( ) if ( not ( item and item . parent ( ) ) ) : plugins = [ ] else : wlang = nativestring ( item . parent ( ) . text ( 0 ) ) wgrp = nativestring ( item . text ( 0 ) ) plugins = self . plugins ( wlang , wgrp ) if ( not plugins ) : self . uiWizardTABLE . setEnabled ( False ) self . uiDescriptionTXT . setEnabled ( False ) return self . uiWizardTABLE . setEnabled ( True ) self . uiDescriptionTXT . setEnabled ( True ) colcount = len ( plugins ) / 2 if ( len ( plugins ) % 2 ) : colcount += 1 self . uiWizardTABLE . setRowCount ( 2 ) self . uiWizardTABLE . setColumnCount ( colcount ) header = self . uiWizardTABLE . verticalHeader ( ) header . setResizeMode ( 0 , header . Stretch ) header . setResizeMode ( 1 , header . Stretch ) header . setMinimumSectionSize ( 64 ) header . hide ( ) header = self . uiWizardTABLE . horizontalHeader ( ) header . setMinimumSectionSize ( 64 ) header . hide ( ) col = - 1 row = 1 for plugin in plugins : if ( row ) : col += 1 row = int ( not row ) widget = PluginWidget ( self , plugin ) self . uiWizardTABLE . setItem ( row , col , QTableWidgetItem ( ) ) self . uiWizardTABLE . setCellWidget ( row , col , widget )
Show the wizards widget for the currently selected plugin .
10,972
def registerToDataTypes ( cls ) : from projexui . xdatatype import registerDataType registerDataType ( cls . __name__ , lambda pyvalue : pyvalue . toString ( ) , lambda qvariant : cls . fromString ( unwrapVariant ( qvariant ) ) )
Registers this class as a valid datatype for saving and loading via the datatype system .
10,973
def enterEvent ( self , event ) : super ( XViewPanelItem , self ) . enterEvent ( event ) self . _hovered = True self . update ( )
Mark the hovered state as being true .
10,974
def leaveEvent ( self , event ) : super ( XViewPanelItem , self ) . leaveEvent ( event ) self . _hovered = False self . update ( )
Mark the hovered state as being false .
10,975
def mousePressEvent ( self , event ) : self . _moveItemStarted = False rect = QtCore . QRect ( 0 , 0 , 12 , self . height ( ) ) if not self . _locked and rect . contains ( event . pos ( ) ) : tabbar = self . parent ( ) panel = tabbar . parent ( ) index = tabbar . indexOf ( self ) view = panel . widget ( index ) pixmap = QtGui . QPixmap . grabWidget ( view ) drag = QtGui . QDrag ( panel ) data = QtCore . QMimeData ( ) data . setData ( 'x-application/xview/tabbed_view' , QtCore . QByteArray ( str ( index ) ) ) drag . setMimeData ( data ) drag . setPixmap ( pixmap ) if not drag . exec_ ( ) : cursor = QtGui . QCursor . pos ( ) geom = self . window ( ) . geometry ( ) if not geom . contains ( cursor ) : view . popout ( ) elif not self . _locked and self . isActive ( ) : self . _moveItemStarted = self . parent ( ) . count ( ) > 1 else : self . activate ( ) super ( XViewPanelItem , self ) . mousePressEvent ( event )
Creates the mouse event for dragging or activating this tab .
10,976
def setFixedHeight ( self , height ) : super ( XViewPanelItem , self ) . setFixedHeight ( height ) self . _dragLabel . setFixedHeight ( height ) self . _titleLabel . setFixedHeight ( height ) self . _searchButton . setFixedHeight ( height ) self . _closeButton . setFixedHeight ( height )
Sets the fixed height for this item to the inputed height amount .
10,977
def clear ( self ) : self . blockSignals ( True ) items = list ( self . items ( ) ) for item in items : item . close ( ) self . blockSignals ( False ) self . _currentIndex = - 1 self . currentIndexChanged . emit ( self . _currentIndex )
Clears out all the items from this tab bar .
10,978
def closeTab ( self , item ) : index = self . indexOf ( item ) if index != - 1 : self . tabCloseRequested . emit ( index )
Requests a close for the inputed tab item .
10,979
def items ( self ) : output = [ ] for i in xrange ( self . layout ( ) . count ( ) ) : item = self . layout ( ) . itemAt ( i ) try : widget = item . widget ( ) except AttributeError : break if isinstance ( widget , XViewPanelItem ) : output . append ( widget ) else : break return output
Returns a list of all the items associated with this panel .
10,980
def moveTab ( self , fromIndex , toIndex ) : try : item = self . layout ( ) . itemAt ( fromIndex ) self . layout ( ) . insertItem ( toIndex , item . widget ( ) ) except StandardError : pass
Moves the tab from the inputed index to the given index .
10,981
def removeTab ( self , index ) : curr_index = self . currentIndex ( ) items = list ( self . items ( ) ) item = items [ index ] item . close ( ) if index <= curr_index : self . _currentIndex -= 1
Removes the tab at the inputed index .
10,982
def requestAddMenu ( self ) : point = QtCore . QPoint ( self . _addButton . width ( ) , 0 ) point = self . _addButton . mapToGlobal ( point ) self . addRequested . emit ( point )
Emits the add requested signal .
10,983
def requestOptionsMenu ( self ) : point = QtCore . QPoint ( 0 , self . _optionsButton . height ( ) ) point = self . _optionsButton . mapToGlobal ( point ) self . optionsRequested . emit ( point )
Emits the options request signal .
10,984
def setCurrentIndex ( self , index ) : if self . _currentIndex == index : return self . _currentIndex = index self . currentIndexChanged . emit ( index ) for i , item in enumerate ( self . items ( ) ) : item . setMenuEnabled ( i == index ) self . repaint ( )
Sets the current item to the item at the inputed index .
10,985
def setFixedHeight ( self , height ) : super ( XViewPanelBar , self ) . setFixedHeight ( height ) if self . layout ( ) : for i in xrange ( self . layout ( ) . count ( ) ) : try : self . layout ( ) . itemAt ( i ) . widget ( ) . setFixedHeight ( height ) except StandardError : continue
Sets the fixed height for this bar to the inputed height .
10,986
def setTabText ( self , index , text ) : try : self . items ( ) [ index ] . setText ( text ) except IndexError : pass
Returns the text for the tab at the inputed index .
10,987
def closePanel ( self ) : for i in range ( self . count ( ) ) : if not self . widget ( i ) . canClose ( ) : return False container = self . parentWidget ( ) viewWidget = self . viewWidget ( ) for i in xrange ( self . count ( ) - 1 , - 1 , - 1 ) : self . widget ( i ) . close ( ) self . tabBar ( ) . clear ( ) if isinstance ( container , XSplitter ) : parent_container = container . parentWidget ( ) if container . count ( ) == 2 : if isinstance ( parent_container , XSplitter ) : sizes = parent_container . sizes ( ) widget = container . widget ( int ( not container . indexOf ( self ) ) ) index = parent_container . indexOf ( container ) parent_container . insertWidget ( index , widget ) container . setParent ( None ) container . close ( ) container . deleteLater ( ) parent_container . setSizes ( sizes ) elif parent_container . parentWidget ( ) == viewWidget : widget = container . widget ( int ( not container . indexOf ( self ) ) ) widget . setParent ( viewWidget ) if projexui . QT_WRAPPER == 'PySide' : _ = viewWidget . takeWidget ( ) else : old_widget = viewWidget . widget ( ) old_widget . setParent ( None ) old_widget . close ( ) old_widget . deleteLater ( ) QtGui . QApplication . instance ( ) . processEvents ( ) viewWidget . setWidget ( widget ) else : container . setParent ( None ) container . close ( ) container . deleteLater ( ) else : self . setFocus ( ) self . _hintLabel . setText ( self . hint ( ) ) self . _hintLabel . show ( ) return True
Closes a full view panel .
10,988
def ensureVisible ( self , viewType ) : view = self . currentView ( ) if type ( view ) == viewType : return view self . blockSignals ( True ) self . setUpdatesEnabled ( False ) for i in xrange ( self . count ( ) ) : widget = self . widget ( i ) if type ( widget ) == viewType : self . setCurrentIndex ( i ) view = widget break else : view = self . addView ( viewType ) self . blockSignals ( False ) self . setUpdatesEnabled ( True ) return view
Find and switch to the first tab of the specified view type . If the type does not exist add it .
10,989
def insertTab ( self , index , widget , title ) : self . insertWidget ( index , widget ) tab = self . tabBar ( ) . insertTab ( index , title ) tab . titleChanged . connect ( widget . setWindowTitle )
Inserts a new tab for this widget .
10,990
def markCurrentChanged ( self ) : view = self . currentView ( ) if view : view . setCurrent ( ) self . setFocus ( ) view . setFocus ( ) self . _hintLabel . hide ( ) else : self . _hintLabel . show ( ) self . _hintLabel . setText ( self . hint ( ) ) if not self . count ( ) : self . tabBar ( ) . clear ( ) self . adjustSizeConstraint ( )
Marks that the current widget has changed .
10,991
def refreshTitles ( self ) : for index in range ( self . count ( ) ) : widget = self . widget ( index ) self . setTabText ( index , widget . windowTitle ( ) )
Refreshes the titles for each view within this tab panel .
10,992
def setCurrentIndex ( self , index ) : super ( XViewPanel , self ) . setCurrentIndex ( index ) self . tabBar ( ) . setCurrentIndex ( index )
Sets the current index on self and on the tab bar to keep the two insync .
10,993
def switchCurrentView ( self , viewType ) : if not self . count ( ) : return self . addView ( viewType ) view = self . currentView ( ) if type ( view ) == viewType : return view self . blockSignals ( True ) self . setUpdatesEnabled ( False ) index = self . indexOf ( view ) if not view . close ( ) : return None index = self . currentIndex ( ) new_view = viewType . createInstance ( self . viewWidget ( ) , self . viewWidget ( ) ) self . insertTab ( index , new_view , new_view . windowTitle ( ) ) self . blockSignals ( False ) self . setUpdatesEnabled ( True ) self . setCurrentIndex ( index ) return new_view
Swaps the current tab view for the inputed action s type .
10,994
async def keys ( self , prefix , * , dc = None , separator = None , watch = None , consistency = None ) : response = await self . _read ( prefix , dc = dc , separator = separator , keys = True , watch = watch , consistency = consistency ) return consul ( response )
Returns a list of the keys under the given prefix
10,995
async def get_tree ( self , prefix , * , dc = None , separator = None , watch = None , consistency = None ) : response = await self . _read ( prefix , dc = dc , recurse = True , separator = separator , watch = watch , consistency = consistency ) result = response . body for data in result : data [ "Value" ] = decode_value ( data [ "Value" ] , data [ "Flags" ] ) return consul ( result , meta = extract_meta ( response . headers ) )
Gets all keys with a prefix of Key during the transaction .
10,996
async def cas ( self , key , value , * , flags = None , index ) : value = encode_value ( value , flags ) index = extract_attr ( index , keys = [ "ModifyIndex" , "Index" ] ) response = await self . _write ( key , value , flags = flags , cas = index ) return response . body is True
Sets the key to the given value with check - and - set semantics .
10,997
async def lock ( self , key , value , * , flags = None , session ) : value = encode_value ( value , flags ) session_id = extract_attr ( session , keys = [ "ID" ] ) response = await self . _write ( key , value , flags = flags , acquire = session_id ) return response . body is True
Locks the Key with the given Session .
10,998
async def unlock ( self , key , value , * , flags = None , session ) : value = encode_value ( value , flags ) session_id = extract_attr ( session , keys = [ "ID" ] ) response = await self . _write ( key , value , flags = flags , release = session_id ) return response . body is True
Unlocks the Key with the given Session .
10,999
async def delete_tree ( self , prefix , * , separator = None ) : response = await self . _discard ( prefix , recurse = True , separator = separator ) return response . body is True
Deletes all keys with a prefix of Key .