idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
7,700
def get_individuals_for_primary_organization ( self , organization ) : if not self . client . session_id : self . client . request_session ( ) object_query = ( "SELECT Objects() FROM Individual WHERE " "PrimaryOrganization = '{}'" . format ( organization . membersuite_account_num ) ) result = self . client . execute_object_query ( object_query ) msql_result = result [ "body" ] [ "ExecuteMSQLResult" ] if msql_result [ "Success" ] : membersuite_objects = ( msql_result [ "ResultValue" ] [ "ObjectSearchResult" ] [ "Objects" ] ) else : raise ExecuteMSQLError ( result = result ) individuals = [ ] if membersuite_objects is not None : for membersuite_object in membersuite_objects [ "MemberSuiteObject" ] : individuals . append ( Individual ( membersuite_object_data = membersuite_object ) ) return individuals
Returns all Individuals that have organization as a primary org .
7,701
def match ( self , keys , partial = True ) : if not partial and len ( keys ) != self . length : return False c = 0 for k in keys : if c >= self . length : return False a = self . keys [ c ] if a != "*" and k != "*" and k != a : return False c += 1 return True
Check if the value of this namespace is matched by keys
7,702
def container ( self , data = None ) : if data is None : data = { } root = p = d = { } j = 0 k = None for k in self : d [ k ] = { } p = d d = d [ k ] if k is not None : p [ k ] = data return ( root , p [ k ] )
Creates a dict built from the keys of this namespace
7,703
def update_index ( self ) : idx = { } for _ , p in sorted ( self . permissions . items ( ) , key = lambda x : str ( x [ 0 ] ) ) : branch = idx parent_p = const . PERM_DENY for k in p . namespace . keys : if not k in branch : branch [ k ] = { "__" : parent_p } branch [ k ] . update ( __implicit = True ) branch = branch [ k ] parent_p = branch [ "__" ] branch [ "__" ] = p . value branch [ "__implicit" ] = False self . index = idx ramap = { } def update_ramap ( branch_idx ) : r = { "__" : False } for k , v in list ( branch_idx . items ( ) ) : if k != "__" and k != "__implicit" : r [ k ] = update_ramap ( v ) if branch_idx [ "__" ] is not None and ( branch_idx [ "__" ] & const . PERM_READ ) != 0 : r [ "__" ] = True return r for k , v in list ( idx . items ( ) ) : ramap [ k ] = update_ramap ( v ) self . read_access_map = ramap return self . index
Regenerates the permission index for this set
7,704
def get_permissions ( self , namespace , explicit = False ) : if not isinstance ( namespace , Namespace ) : namespace = Namespace ( namespace ) keys = namespace . keys p , _ = self . _check ( keys , self . index , explicit = explicit ) return p
Returns the permissions level for the specified namespace
7,705
def check ( self , namespace , level , explicit = False ) : return ( self . get_permissions ( namespace , explicit = explicit ) & level ) != 0
Checks if the permset has permission to the specified namespace at the specified level
7,706
def hash ( self , key , message = None ) : hmac_obj = hmac . HMAC ( key , self . __digest_generator , backend = default_backend ( ) ) if message is not None : hmac_obj . update ( message ) return hmac_obj . finalize ( )
Return digest of the given message and key
7,707
def call_with_search_field ( self , name , callback ) : done = False while not done : def check ( * _ ) : if name in self . _search_fields : return True self . _found_fields = None return False self . util . wait ( check ) field = self . _search_fields [ name ] try : callback ( field ) done = True except StaleElementReferenceException : self . _found_fields = None
Calls a piece of code with the DOM element that corresponds to a search field of the table .
7,708
def determine_keymap ( qteMain = None ) : if qteMain is None : qte_global . Qt_key_map = default_qt_keymap qte_global . Qt_modifier_map = default_qt_modifier_map else : doc = 'Conversion table from local characters to Qt constants' qteMain . qteDefVar ( "Qt_key_map" , default_qt_keymap , doc = doc ) doc = 'Conversion table from local modifier keys to Qt constants' qteMain . qteDefVar ( "Qt_modifier_map" , default_qt_modifier_map , doc = doc )
Return the conversion from keys and modifiers to Qt constants .
7,709
def func ( name ) : r pexdoc . addex ( TypeError , "Argument `name` is not valid" , not isinstance ( name , str ) ) return "My name is {0}" . format ( name )
r Print your name .
7,710
def disableHook ( self , msgObj ) : macroName , keysequence = msgObj . data if macroName != self . qteMacroName ( ) : self . qteMain . qtesigKeyseqComplete . disconnect ( self . disableHook ) self . killListIdx = - 1
Disable yank - pop .
7,711
def clearHighlighting ( self ) : SCI = self . qteWidget self . qteWidget . SCISetStylingEx ( 0 , 0 , self . styleOrig ) self . selMatchIdx = 1 self . matchList = [ ]
Restore the original style properties of all matches .
7,712
def highlightNextMatch ( self ) : if self . qteText . toPlainText ( ) == '' : self . qteText . setText ( self . defaultChoice ) return if self . selMatchIdx < 0 : self . selMatchIdx = 0 return if self . selMatchIdx >= len ( self . matchList ) : self . selMatchIdx = 0 return SCI = self . qteWidget start , stop = self . matchList [ self . selMatchIdx - 1 ] line , col = SCI . lineIndexFromPosition ( start ) SCI . SendScintilla ( SCI . SCI_STARTSTYLING , start , 0xFF ) SCI . SendScintilla ( SCI . SCI_SETSTYLING , stop - start , 30 ) start , stop = self . matchList [ self . selMatchIdx ] SCI . SendScintilla ( SCI . SCI_STARTSTYLING , start , 0xFF ) SCI . SendScintilla ( SCI . SCI_SETSTYLING , stop - start , 31 ) line , col = SCI . lineIndexFromPosition ( start ) SCI . setCursorPosition ( line , col ) self . selMatchIdx += 1
Select and highlight the next match in the set of matches .
7,713
def nextMode ( self ) : if len ( self . matchList ) == 0 : self . qteAbort ( QtmacsMessage ( ) ) self . qteMain . qteKillMiniApplet ( ) return self . queryMode += 1 if self . queryMode == 1 : self . qteText . textChanged . disconnect ( self . qteTextChanged ) self . toReplace = self . qteText . toPlainText ( ) self . qteText . clear ( ) self . qteTextPrefix . setText ( 'mode 1' ) elif self . queryMode == 2 : register = self . qteMain . qteRegisterMacro bind = self . qteMain . qteBindKeyWidget self . qteMain . qteUnbindAllFromWidgetObject ( self . qteText ) macroName = register ( self . ReplaceAll , replaceMacro = True ) bind ( '!' , macroName , self . qteText ) macroName = register ( self . ReplaceNext , replaceMacro = True ) bind ( '<space>' , macroName , self . qteText ) macroName = register ( self . SkipNext , replaceMacro = True ) bind ( 'n' , macroName , self . qteText ) macroName = register ( self . Abort , replaceMacro = True ) bind ( 'q' , macroName , self . qteText ) bind ( '<enter>' , macroName , self . qteText ) self . toReplaceWith = self . qteText . toPlainText ( ) self . qteTextPrefix . setText ( 'mode 2' ) self . qteText . setText ( '<space> to replace, <n> to skip, ' '<!> to replace all.' ) else : self . qteAbort ( QtmacsMessage ( ) ) self . qteMain . qteKillMiniApplet ( )
Put the search - replace macro into the next stage . The first stage is the query stage to ask the user for the string to replace the second stage is to query the string to replace it with and the third allows to replace or skip individual matches or replace them all automatically .
7,714
def replaceAll ( self ) : while self . replaceSelected ( ) : pass self . qteWidget . SCISetStylingEx ( 0 , 0 , self . styleOrig ) self . qteMain . qteKillMiniApplet ( )
Replace all matches after the current cursor position .
7,715
def compileMatchList ( self ) : self . matchList = [ ] numChar = len ( self . toReplace ) if numChar == 0 : return stop = 0 text = self . qteWidget . text ( ) while True : start = text . find ( self . toReplace , stop ) if start == - 1 : break else : stop = start + numChar self . matchList . append ( ( start , stop ) )
Compile the list of spans of every match .
7,716
def replaceSelected ( self ) : SCI = self . qteWidget self . qteWidget . SCISetStylingEx ( 0 , 0 , self . styleOrig ) start , stop = self . matchList [ self . selMatchIdx ] line1 , col1 = SCI . lineIndexFromPosition ( start ) line2 , col2 = SCI . lineIndexFromPosition ( stop ) SCI . setSelection ( line1 , col1 , line2 , col2 ) text = SCI . selectedText ( ) text = re . sub ( self . toReplace , self . toReplaceWith , text ) SCI . replaceSelectedText ( text ) line , col = SCI . lineIndexFromPosition ( start + len ( text ) ) SCI . setCursorPosition ( line , col ) line , col = SCI . getNumLinesAndColumns ( ) text , style = self . qteWidget . SCIGetStyledText ( ( 0 , 0 , line , col ) ) self . styleOrig = style if len ( self . matchList ) == self . selMatchIdx + 1 : return False else : self . highlightAllMatches ( ) return True
Replace the currently selected string with the new one .
7,717
def scan_band ( self , band , ** kwargs ) : kal_run_line = fn . build_kal_scan_band_string ( self . kal_bin , band , kwargs ) raw_output = subprocess . check_output ( kal_run_line . split ( ' ' ) , stderr = subprocess . STDOUT ) kal_normalized = fn . parse_kal_scan ( raw_output ) return kal_normalized
Run Kalibrate for a band .
7,718
def scan_channel ( self , channel , ** kwargs ) : kal_run_line = fn . build_kal_scan_channel_string ( self . kal_bin , channel , kwargs ) raw_output = subprocess . check_output ( kal_run_line . split ( ' ' ) , stderr = subprocess . STDOUT ) kal_normalized = fn . parse_kal_channel ( raw_output ) return kal_normalized
Run Kalibrate .
7,719
def get_vars ( self ) : if self . method ( ) != 'GET' : raise RuntimeError ( 'Unable to return get vars for non-get method' ) re_search = WWebRequestProto . get_vars_re . search ( self . path ( ) ) if re_search is not None : return urllib . parse . parse_qs ( re_search . group ( 1 ) , keep_blank_values = 1 )
Parse request path and return GET - vars
7,720
def post_vars ( self ) : if self . method ( ) != 'POST' : raise RuntimeError ( 'Unable to return post vars for non-get method' ) content_type = self . content_type ( ) if content_type is None or content_type . lower ( ) != 'application/x-www-form-urlencoded' : raise RuntimeError ( 'Unable to return post vars with invalid content-type request' ) request_data = self . request_data ( ) request_data = request_data . decode ( ) if request_data is not None else '' re_search = WWebRequestProto . post_vars_re . search ( request_data ) if re_search is not None : return urllib . parse . parse_qs ( re_search . group ( 1 ) , keep_blank_values = 1 )
Parse request payload and return POST - vars
7,721
def join_path ( self , * path ) : path = self . directory_sep ( ) . join ( path ) return self . normalize_path ( path )
Unite entries to generate a single path
7,722
def full_path ( self ) : return self . normalize_path ( self . directory_sep ( ) . join ( ( self . start_path ( ) , self . session_path ( ) ) ) )
Return a full path to a current session directory . A result is made by joining a start path with current session directory
7,723
def run ( self , ** kwargs ) : from calculate import compute self . app_main ( ** kwargs ) output = osp . join ( self . exp_config [ 'expdir' ] , 'output.dat' ) self . exp_config [ 'output' ] = output data = np . loadtxt ( self . exp_config [ 'infile' ] ) out = compute ( data ) self . logger . info ( 'Saving output data to %s' , osp . relpath ( output ) ) np . savetxt ( output , out ) self . exp_config [ 'mean' ] = mean = float ( out . mean ( ) ) self . exp_config [ 'std' ] = std = float ( out . std ( ) ) self . logger . debug ( 'Mean: %s, Standard deviation: %s' , mean , std )
Run the model
7,724
def postproc ( self , close = True , ** kwargs ) : import matplotlib . pyplot as plt import seaborn as sns self . app_main ( ** kwargs ) indata = np . loadtxt ( self . exp_config [ 'infile' ] ) outdata = np . loadtxt ( self . exp_config [ 'output' ] ) x_data = np . linspace ( - np . pi , np . pi ) fig = plt . figure ( ) plt . plot ( x_data , indata , label = 'input' ) plt . plot ( x_data , outdata , label = 'squared' ) plt . legend ( ) plt . title ( self . exp_config . get ( 'description' ) ) self . exp_config [ 'plot' ] = ofile = osp . join ( self . exp_config [ 'expdir' ] , 'plot.png' ) self . logger . info ( 'Saving plot to %s' , osp . relpath ( ofile ) ) fig . savefig ( ofile ) if close : plt . close ( fig )
Postprocess and visualize the data
7,725
def _push ( self , undoObj : QtmacsUndoCommand ) : self . _qteStack . append ( undoObj ) if undoObj . nextIsRedo : undoObj . commit ( ) else : undoObj . reverseCommit ( ) undoObj . nextIsRedo = not undoObj . nextIsRedo
The actual method that adds the command object onto the stack .
7,726
def push ( self , undoObj ) : if not isinstance ( undoObj , QtmacsUndoCommand ) : raise QtmacsArgumentError ( 'undoObj' , 'QtmacsUndoCommand' , inspect . stack ( ) [ 0 ] [ 3 ] ) self . _wasUndo = False self . _push ( undoObj )
Add undoObj command to stack and run its commit method .
7,727
def undo ( self ) : if not self . _wasUndo : self . _qteIndex = len ( self . _qteStack ) else : self . _qteIndex -= 1 self . _wasUndo = True if self . _qteIndex <= 0 : return undoObj = self . _qteStack [ self . _qteIndex - 1 ] undoObj = QtmacsUndoCommand ( undoObj ) self . _push ( undoObj ) if ( self . _qteIndex - 1 ) == self . _qteLastSavedUndoIndex : self . qtesigSavedState . emit ( QtmacsMessage ( ) ) self . saveState ( )
Undo the last command by adding its inverse action to the stack .
7,728
def placeCursor ( self , pos ) : if pos > len ( self . qteWidget . toPlainText ( ) ) : pos = len ( self . qteWidget . toPlainText ( ) ) tc = self . qteWidget . textCursor ( ) tc . setPosition ( pos ) self . qteWidget . setTextCursor ( tc )
Try to place the cursor in line at col if possible . If this is not possible then place it at the end .
7,729
def reverseCommit ( self ) : print ( self . after == self . before ) pos = self . qteWidget . textCursor ( ) . position ( ) self . qteWidget . setHtml ( self . before ) self . placeCursor ( pos )
Reverse the document to the original state .
7,730
def insertFromMimeData ( self , data ) : undoObj = UndoPaste ( self , data , self . pasteCnt ) self . pasteCnt += 1 self . qteUndoStack . push ( undoObj )
Paste the MIME data at the current cursor position .
7,731
def keyPressEvent ( self , keyEvent ) : undoObj = UndoSelfInsert ( self , keyEvent . text ( ) ) self . qteUndoStack . push ( undoObj )
Insert the character at the current cursor position .
7,732
def get_schema_version_from_xml ( xml ) : if isinstance ( xml , six . string_types ) : xml = StringIO ( xml ) try : tree = ElementTree . parse ( xml ) except ParseError : return None root = tree . getroot ( ) return root . attrib . get ( 'schemaVersion' , None )
Get schemaVersion attribute from OpenMalaria scenario file xml - open file or content of xml document to be processed
7,733
def format_account ( service_name , data ) : if "username" not in data : raise KeyError ( "Account is missing a username" ) account = { "@type" : "Account" , "service" : service_name , "identifier" : data [ "username" ] , "proofType" : "http" } if ( data . has_key ( service_name ) and data [ service_name ] . has_key ( "proof" ) and data [ service_name ] [ "proof" ] . has_key ( "url" ) ) : account [ "proofUrl" ] = data [ service_name ] [ "proof" ] [ "url" ] return account
Given profile data and the name of a social media service format it for the zone file .
7,734
def swipe ( self ) : result = WBinArray ( 0 , len ( self ) ) for i in range ( len ( self ) ) : result [ len ( self ) - i - 1 ] = self [ i ] return result
Mirror current array value in reverse . Bits that had greater index will have lesser index and vice - versa . This method doesn t change this array . It creates a new one and return it as a result .
7,735
def etcd ( url = DEFAULT_URL , mock = False , ** kwargs ) : if mock : from etc . adapters . mock import MockAdapter adapter_class = MockAdapter else : from etc . adapters . etcd import EtcdAdapter adapter_class = EtcdAdapter return Client ( adapter_class ( url , ** kwargs ) )
Creates an etcd client .
7,736
def repeat_call ( func , retries , * args , ** kwargs ) : retries = max ( 0 , int ( retries ) ) try_num = 0 while True : if try_num == retries : return func ( * args , ** kwargs ) else : try : return func ( * args , ** kwargs ) except Exception as e : if isinstance ( e , KeyboardInterrupt ) : raise e try_num += 1
Tries a total of retries times to execute callable before failing .
7,737
def type_check ( func_handle ) : def checkType ( var_name , var_val , annot ) : if var_name in annot : var_anno = annot [ var_name ] if var_val is None : type_ok = True elif ( type ( var_val ) is bool ) : type_ok = ( type ( var_val ) in var_anno ) else : type_ok = True in [ isinstance ( var_val , _ ) for _ in var_anno ] else : var_anno = 'Unspecified' type_ok = True if not type_ok : args = ( var_name , func_handle . __name__ , var_anno , type ( var_val ) ) raise QtmacsArgumentError ( * args ) @ functools . wraps ( func_handle ) def wrapper ( * args , ** kwds ) : argspec = inspect . getfullargspec ( func_handle ) annot = { } for key , val in argspec . annotations . items ( ) : if isinstance ( val , tuple ) or isinstance ( val , list ) : annot [ key ] = val else : annot [ key ] = val , if argspec . defaults is None : defaults = tuple ( [ None ] * len ( argspec . args ) ) else : num_none = len ( argspec . args ) - len ( argspec . defaults ) defaults = tuple ( [ None ] * num_none ) + argspec . defaults ofs = len ( args ) for idx , var_name in enumerate ( argspec . args [ : ofs ] ) : var_val = args [ idx ] checkType ( var_name , var_val , annot ) for idx , var_name in enumerate ( argspec . args [ ofs : ] ) : if var_name in kwds : var_val = kwds [ var_name ] else : var_val = defaults [ idx + ofs ] checkType ( var_name , var_val , annot ) return func_handle ( * args , ** kwds ) return wrapper
Ensure arguments have the type specified in the annotation signature .
7,738
def start ( self ) : timeout = self . timeout ( ) if timeout is not None and timeout > 0 : self . __loop . add_timeout ( timedelta ( 0 , timeout ) , self . stop ) self . handler ( ) . setup_handler ( self . loop ( ) ) self . loop ( ) . start ( ) self . handler ( ) . loop_stopped ( )
Set up handler and start loop
7,739
def loop_stopped ( self ) : transport = self . transport ( ) if self . server_mode ( ) is True : transport . close_server_socket ( self . config ( ) ) else : transport . close_client_socket ( self . config ( ) )
Terminate socket connection because of stopping loop
7,740
def discard_queue_messages ( self ) : zmq_stream_queue = self . handler ( ) . stream ( ) . _send_queue while not zmq_stream_queue . empty ( ) : try : zmq_stream_queue . get ( False ) except queue . Empty : continue zmq_stream_queue . task_done ( )
Sometimes it is necessary to drop undelivered messages . These messages may be stored in different caches for example in a zmq socket queue . With different zmq flags we can tweak zmq sockets and contexts no to keep those messages . But inside ZMQStream class there is a queue that can not be cleaned other way then the way it does in this method . So yes it is dirty to access protected members and yes it can be broken at any moment . And yes without correct locking procedure there is a possibility of unpredicted behaviour . But still - there is no other way to drop undelivered messages
7,741
def qteProcessKey ( self , event , targetObj ) : msgObj = QtmacsMessage ( ( targetObj , event ) , None ) msgObj . setSignalName ( 'qtesigKeypressed' ) self . qteMain . qtesigKeypressed . emit ( msgObj ) if event . key ( ) in ( QtCore . Qt . Key_Shift , QtCore . Qt . Key_Control , QtCore . Qt . Key_Meta , QtCore . Qt . Key_Alt , QtCore . Qt . Key_AltGr ) : return False self . _keysequence . appendQKeyEvent ( event ) isRegisteredWidget = hasattr ( targetObj , '_qteAdmin' ) if isRegisteredWidget and hasattr ( targetObj . _qteAdmin , 'keyMap' ) : keyMap = targetObj . _qteAdmin . keyMap else : keyMap = self . qteMain . _qteGlobalKeyMapByReference ( ) ( macroName , isPartialMatch ) = keyMap . match ( self . _keysequence ) keyseq_copy = QtmacsKeysequence ( self . _keysequence ) if isPartialMatch : if macroName is None : msgObj = QtmacsMessage ( keyseq_copy , None ) msgObj . setSignalName ( 'qtesigKeyseqPartial' ) self . qteMain . qtesigKeyseqPartial . emit ( msgObj ) else : if self . _qteFlagRunMacro : self . qteMain . qteRunMacro ( macroName , targetObj , keyseq_copy ) msgObj = QtmacsMessage ( ( macroName , keyseq_copy ) , None ) msgObj . setSignalName ( 'qtesigKeyseqComplete' ) self . qteMain . qtesigKeyseqComplete . emit ( msgObj ) self . _keysequence . reset ( ) else : if isRegisteredWidget : tmp = keyseq_copy . toString ( ) tmp = tmp . replace ( '<' , '&lt;' ) tmp = tmp . replace ( '>' , '&gt;' ) msg = 'No macro is bound to <b>{}</b>.' . format ( tmp ) self . qteMain . qteLogger . warning ( msg ) msgObj = QtmacsMessage ( keyseq_copy , None ) msgObj . setSignalName ( 'qtesigKeyseqInvalid' ) self . qteMain . qtesigKeyseqInvalid . emit ( msgObj ) else : if self . _qteFlagRunMacro : self . qteMain . qteRunMacro ( self . QtDelivery , targetObj , keyseq_copy ) self . _keysequence . reset ( ) msgObj = QtmacsMessage ( ( targetObj , keyseq_copy , macroName ) , None ) msgObj . setSignalName ( 'qtesigKeyparsed' ) self . qteMain . qtesigKeyparsed . emit ( msgObj ) return isPartialMatch
If the key completes a valid key sequence then queue the associated macro .
7,742
def qteAdjustWidgetSizes ( self , handlePos : int = None ) : if self . count ( ) < 2 : return if self . orientation ( ) == QtCore . Qt . Horizontal : totDim = self . size ( ) . width ( ) - self . handleWidth ( ) else : totDim = self . size ( ) . height ( ) - self . handleWidth ( ) if handlePos is None : handlePos = ( totDim + self . handleWidth ( ) ) // 2 if not ( 0 <= handlePos <= totDim ) : return newSize = [ handlePos , totDim - handlePos ] self . setSizes ( newSize )
Adjust the widget size inside the splitter according to handlePos .
7,743
def qteAddWidget ( self , widget ) : self . addWidget ( widget ) if widget . _qteAdmin . widgetSignature == '__QtmacsLayoutSplitter__' : widget . show ( ) else : widget . show ( True ) self . qteAdjustWidgetSizes ( )
Add a widget to the splitter and make it visible .
7,744
def qteInsertWidget ( self , idx , widget ) : self . insertWidget ( idx , widget ) if widget . _qteAdmin . widgetSignature == '__QtmacsLayoutSplitter__' : widget . show ( ) else : widget . show ( True ) self . qteAdjustWidgetSizes ( )
Insert widget to the splitter at the specified idx position and make it visible .
7,745
def timerEvent ( self , event ) : self . killTimer ( event . timerId ( ) ) if event . timerId ( ) == self . _qteTimerRunMacro : self . _qteTimerRunMacro = None while True : if len ( self . _qteMacroQueue ) > 0 : ( macroName , qteWidget , event ) = self . _qteMacroQueue . pop ( 0 ) self . _qteRunQueuedMacro ( macroName , qteWidget , event ) elif len ( self . _qteKeyEmulationQueue ) > 0 : if self . _qteActiveApplet is None : receiver = self . qteActiveWindow ( ) else : if self . _qteActiveApplet . _qteActiveWidget is None : receiver = self . _qteActiveApplet else : receiver = self . _qteActiveApplet . _qteActiveWidget keysequence = self . _qteKeyEmulationQueue . pop ( 0 ) self . _qteEventFilter . eventFilter ( receiver , keysequence ) else : self . _qteFocusManager ( ) break self . _qteFocusManager ( ) elif event . timerId ( ) == self . debugTimer : pass else : print ( 'Unknown timer ID' ) pass
Trigger the focus manager and work off all queued macros .
7,746
def _qteMouseClicked ( self , widgetObj ) : app = qteGetAppletFromWidget ( widgetObj ) if app is None : return else : self . _qteActiveApplet = app if not hasattr ( widgetObj , '_qteAdmin' ) : self . _qteActiveApplet . qteMakeWidgetActive ( widgetObj ) else : if app . _qteAdmin . isQtmacsApplet : self . _qteActiveApplet . qteMakeWidgetActive ( None ) else : self . _qteActiveApplet . qteMakeWidgetActive ( widgetObj ) self . _qteFocusManager ( )
Update the Qtmacs internal focus state as the result of a mouse click .
7,747
def qteFocusChanged ( self , old , new ) : if old is new : return if ( old is not None ) and ( new is not None ) : if old . isActiveWindow ( ) is new . isActiveWindow ( ) : return
Slot for Qt native focus - changed signal to notify Qtmacs if the window was switched .
7,748
def qteIsMiniApplet ( self , obj ) : try : ret = obj . _qteAdmin . isMiniApplet except AttributeError : ret = False return ret
Test if instance obj is a mini applet .
7,749
def qteNewWindow ( self , pos : QtCore . QRect = None , windowID : str = None ) : winIDList = [ _ . _qteWindowID for _ in self . _qteWindowList ] if windowID is None : cnt = 0 while str ( cnt ) in winIDList : cnt += 1 windowID = str ( cnt ) if pos is None : pos = QtCore . QRect ( 500 , 300 , 1000 , 500 ) if windowID in winIDList : msg = 'Window with ID <b>{}</b> already exists.' . format ( windowID ) raise QtmacsOtherError ( msg ) window = QtmacsWindow ( pos , windowID ) self . _qteWindowList . append ( window ) window . show ( ) return window
Create a new empty window with windowID at position pos .
7,750
def qteMakeWindowActive ( self , windowObj : QtmacsWindow ) : if windowObj in self . _qteWindowList : windowObj . activateWindow ( ) else : self . qteLogger . warning ( 'Window to activate does not exist' )
Make the window windowObj active and focus the first applet therein .
7,751
def qteActiveWindow ( self ) : if len ( self . _qteWindowList ) == 0 : self . qteLogger . critical ( 'The window list is empty.' ) return None elif len ( self . _qteWindowList ) == 1 : return self . _qteWindowList [ 0 ] else : for win in self . _qteWindowList : if win . isActiveWindow ( ) : return win return self . _qteWindowList [ 0 ]
Return the currently active QtmacsWindow object .
7,752
def qteNextWindow ( self ) : win = self . qteActiveWindow ( ) if win in self . _qteWindowList : idx = self . _qteWindowList . index ( win ) idx = ( idx + 1 ) % len ( self . _qteWindowList ) return self . _qteWindowList [ idx ] else : msg = 'qteNextWindow method found a non-existing window.' self . qteLogger . warning ( msg ) return None
Return next window in cyclic order .
7,753
def qteNextApplet ( self , numSkip : int = 1 , ofsApp : ( QtmacsApplet , str ) = None , skipInvisible : bool = True , skipVisible : bool = False , skipMiniApplet : bool = True , windowObj : QtmacsWindow = None ) : if isinstance ( ofsApp , str ) : ofsApp = self . qteGetAppletHandle ( ofsApp ) if len ( self . _qteAppletList ) == 0 : return None if skipVisible and skipInvisible : return None appList = list ( self . _qteAppletList ) if skipInvisible : appList = [ app for app in appList if app . qteIsVisible ( ) ] if windowObj is not None : appList = [ app for app in appList if app . qteParentWindow ( ) == windowObj ] if skipVisible : appList = [ app for app in appList if not app . qteIsVisible ( ) ] if skipMiniApplet : if self . _qteMiniApplet in appList : appList . remove ( self . _qteMiniApplet ) if len ( appList ) == 0 : return None if ofsApp is None : ofsApp = self . _qteActiveApplet if ofsApp in self . _qteAppletList : if ofsApp in appList : ofsIdx = appList . index ( ofsApp ) else : ofsIdx = self . _qteAppletList . index ( ofsApp ) glob_list = self . _qteAppletList [ ofsIdx : ] glob_list += self . _qteAppletList [ : ofsIdx ] ofsIdx = [ appList . index ( _ ) for _ in glob_list if _ in appList ] if len ( ofsIdx ) == 0 : msg = ( 'No match between global and local applet list' ' ) self . qteLogger . error ( msg , stack_info = True ) return None else : ofsIdx = ofsIdx [ 0 ] else : ofsIdx = 0 ofsIdx = ( ofsIdx + numSkip ) % len ( appList ) return appList [ ofsIdx ]
Return the next applet in cyclic order .
7,754
def qteRunMacro ( self , macroName : str , widgetObj : QtGui . QWidget = None , keysequence : QtmacsKeysequence = None ) : self . _qteMacroQueue . append ( ( macroName , widgetObj , keysequence ) ) self . qteUpdate ( )
Queue a previously registered macro for execution once the event loop is idle .
7,755
def _qteRunQueuedMacro ( self , macroName : str , widgetObj : QtGui . QWidget = None , keysequence : QtmacsKeysequence = None ) : app = qteGetAppletFromWidget ( widgetObj ) if app is not None : if sip . isdeleted ( app ) : msg = 'Ignored macro <b>{}</b> because it targeted a' msg += ' nonexistent applet.' . format ( macroName ) self . qteLogger . warning ( msg ) return macroObj = self . qteGetMacroObject ( macroName , widgetObj ) if macroObj is None : msg = 'No <b>{}</b>-macro compatible with {}:{}-type applet' msg = msg . format ( macroName , app . qteAppletSignature ( ) , widgetObj . _qteAdmin . widgetSignature ) self . qteLogger . warning ( msg ) return self . qteDefVar ( 'last_key_sequence' , keysequence , doc = "Last valid key sequence that triggered a macro." ) if app is None : macroObj . qteApplet = macroObj . qteWidget = None else : macroObj . qteApplet = app macroObj . qteWidget = widgetObj macroObj . qtePrepareToRun ( )
Execute the next macro in the macro queue .
7,756
def qteNewApplet ( self , appletName : str , appletID : str = None , windowObj : QtmacsWindow = None ) : if windowObj is None : windowObj = self . qteActiveWindow ( ) if windowObj is None : msg = 'Cannot determine the currently active window.' self . qteLogger . error ( msg , stack_info = True ) return if appletID is None : cnt = 0 while True : appletID = appletName + '_' + str ( cnt ) if self . qteGetAppletHandle ( appletID ) is None : break else : cnt += 1 if self . qteGetAppletHandle ( appletID ) is not None : msg = 'Applet with ID <b>{}</b> already exists' . format ( appletID ) self . qteLogger . error ( msg , stack_info = True ) return None if appletName not in self . _qteRegistryApplets : msg = 'Unknown applet <b>{}</b>' . format ( appletName ) self . qteLogger . error ( msg , stack_info = True ) return None else : cls = self . _qteRegistryApplets [ appletName ] try : app = cls ( appletID ) except Exception : msg = 'Applet <b>{}</b> has a faulty constructor.' . format ( appletID ) self . qteLogger . exception ( msg , exc_info = True , stack_info = True ) return None if app . qteAppletSignature ( ) is None : msg = 'Cannot add applet <b>{}</b> ' . format ( app . qteAppletID ( ) ) msg += 'because it has not applet signature.' msg += ' Use self.qteSetAppletSignature in the constructor' msg += ' of the class to fix this.' self . qteLogger . error ( msg , stack_info = True ) return None self . _qteAppletList . insert ( 0 , app ) if app . layout ( ) is None : appLayout = QtGui . QHBoxLayout ( ) for handle in app . _qteAdmin . widgetList : appLayout . addWidget ( handle ) app . setLayout ( appLayout ) app . qteReparent ( None ) self . qteRunHook ( 'init' , QtmacsMessage ( None , app ) ) return app
Create a new instance of appletName and assign it the appletID .
7,757
def qteAddMiniApplet ( self , appletObj : QtmacsApplet ) : if self . _qteMiniApplet is not None : msg = 'Cannot replace mini applet more than once.' self . qteLogger . warning ( msg ) return False if appletObj . layout ( ) is None : appLayout = QtGui . QHBoxLayout ( ) for handle in appletObj . _qteAdmin . widgetList : appLayout . addWidget ( handle ) appletObj . setLayout ( appLayout ) appletObj . _qteAdmin . isMiniApplet = True self . _qteMiniApplet = appletObj app = self . _qteActiveApplet appWin = self . qteActiveWindow ( ) self . _qteMiniApplet . _qteCallingApplet = app self . _qteMiniApplet . _qteCallingWindow = appWin del app self . _qteAppletList . insert ( 0 , self . _qteMiniApplet ) appWin . qteLayoutSplitter . addWidget ( self . _qteMiniApplet ) self . _qteMiniApplet . show ( True ) wid = self . _qteMiniApplet . qteNextWidget ( numSkip = 0 ) self . _qteMiniApplet . qteMakeWidgetActive ( wid ) self . qteMakeAppletActive ( self . _qteMiniApplet ) return True
Install appletObj as the mini applet in the window layout .
7,758
def qteKillMiniApplet ( self ) : if self . _qteMiniApplet is None : return if not self . qteIsMiniApplet ( self . _qteMiniApplet ) : msg = ( 'Mini applet does not have its mini applet flag set.' ' Ignored.' ) self . qteLogger . warning ( msg ) if self . _qteMiniApplet not in self . _qteAppletList : msg = 'Custom mini applet not in applet list self . qteLogger . warning ( msg ) else : try : self . _qteMiniApplet . qteToBeKilled ( ) except Exception : msg = 'qteToBeKilledRoutine is faulty' self . qteLogger . exception ( msg , exc_info = True , stack_info = True ) win = self . _qteMiniApplet . _qteCallingWindow app = self . qteNextApplet ( windowObj = win ) if app is not None : self . qteMakeAppletActive ( app ) else : app = self . qteNextApplet ( skipInvisible = False , skipVisible = True ) if app is not None : self . qteMakeAppletActive ( app ) else : self . _qteActiveApplet = None self . _qteAppletList . remove ( self . _qteMiniApplet ) self . _qteMiniApplet . close ( ) self . _qteMiniApplet . deleteLater ( ) self . _qteMiniApplet = None
Remove the mini applet .
7,759
def _qteFindAppletInSplitter ( self , appletObj : QtmacsApplet , split : QtmacsSplitter ) : def splitterIter ( split ) : for idx in range ( split . count ( ) ) : subSplitter = split . widget ( idx ) subID = subSplitter . _qteAdmin . widgetSignature if subID == '__QtmacsLayoutSplitter__' : yield from splitterIter ( subSplitter ) yield split for curSplit in splitterIter ( split ) : if appletObj in curSplit . children ( ) : return curSplit return None
Return the splitter that holds appletObj .
7,760
def qteSplitApplet ( self , applet : ( QtmacsApplet , str ) = None , splitHoriz : bool = True , windowObj : QtmacsWindow = None ) : if isinstance ( applet , str ) : newAppObj = self . qteGetAppletHandle ( applet ) else : newAppObj = applet if windowObj is None : windowObj = self . qteActiveWindow ( ) if windowObj is None : msg = 'Cannot determine the currently active window.' self . qteLogger . error ( msg , stack_info = True ) return if splitHoriz : splitOrientation = QtCore . Qt . Horizontal else : splitOrientation = QtCore . Qt . Vertical if newAppObj is None : newAppObj = self . qteNextApplet ( skipVisible = True , skipInvisible = False ) else : if newAppObj . qteIsVisible ( ) : return False if newAppObj is None : self . qteLogger . warning ( 'All applets are already visible.' ) return False if windowObj . qteAppletSplitter . count ( ) == 0 : windowObj . qteAppletSplitter . qteAddWidget ( newAppObj ) windowObj . qteAppletSplitter . setOrientation ( splitOrientation ) return True curApp = self . qteNextApplet ( numSkip = 0 , windowObj = windowObj ) split = self . _qteFindAppletInSplitter ( curApp , windowObj . qteAppletSplitter ) if split is None : msg = 'Active applet <b>{}</b> not in the layout.' msg = msg . format ( curApp . qteAppletID ( ) ) self . qteLogger . error ( msg , stack_info = True ) return False if split is windowObj . qteAppletSplitter : if split . count ( ) == 1 : split . qteAddWidget ( newAppObj ) split . setOrientation ( splitOrientation ) return True curAppIdx = split . indexOf ( curApp ) newSplit = QtmacsSplitter ( splitOrientation , windowObj ) curApp . setParent ( None ) newSplit . qteAddWidget ( curApp ) newSplit . qteAddWidget ( newAppObj ) split . insertWidget ( curAppIdx , newSplit ) split . qteAdjustWidgetSizes ( ) return True
Reveal applet by splitting the space occupied by the current applet .
7,761
def qteReplaceAppletInLayout ( self , newApplet : ( QtmacsApplet , str ) , oldApplet : ( QtmacsApplet , str ) = None , windowObj : QtmacsWindow = None ) : if isinstance ( oldApplet , str ) : oldAppObj = self . qteGetAppletHandle ( oldApplet ) else : oldAppObj = oldApplet if isinstance ( newApplet , str ) : newAppObj = self . qteGetAppletHandle ( newApplet ) else : newAppObj = newApplet if windowObj is None : windowObj = self . qteActiveWindow ( ) if windowObj is None : msg = 'Cannot determine the currently active window.' self . qteLogger . warning ( msg , stack_info = True ) return if windowObj . qteAppletSplitter . count ( ) == 0 : windowObj . qteAppletSplitter . qteAddWidget ( newAppObj ) return if oldAppObj is None : oldAppObj = self . qteNextApplet ( numSkip = 0 , windowObj = windowObj ) if oldAppObj is None : msg = 'Applet to replace does not exist.' self . qteLogger . error ( msg , stack_info = True ) return if newAppObj is oldAppObj : return if oldAppObj . qteIsVisible ( ) and newAppObj . qteIsVisible ( ) : return split = self . _qteFindAppletInSplitter ( oldAppObj , windowObj . qteAppletSplitter ) if split is None : msg = ( 'Applet <b>{}</b> not replaced because it is not' 'in the layout.' . format ( oldAppObj . qteAppletID ( ) ) ) self . qteLogger . warning ( msg ) return oldAppIdx = split . indexOf ( oldAppObj ) sizes = split . sizes ( ) split . qteInsertWidget ( oldAppIdx , newAppObj ) oldAppObj . hide ( True ) split . setSizes ( sizes )
Replace oldApplet with newApplet in the window layout .
7,762
def qteRemoveAppletFromLayout ( self , applet : ( QtmacsApplet , str ) ) : if isinstance ( applet , str ) : appletObj = self . qteGetAppletHandle ( applet ) else : appletObj = applet for window in self . _qteWindowList : split = self . _qteFindAppletInSplitter ( appletObj , window . qteAppletSplitter ) if split is not None : break if split is None : return if ( split is window . qteAppletSplitter ) and ( split . count ( ) == 1 ) : split . widget ( 0 ) . hide ( True ) nextApp = self . qteNextApplet ( windowObj = window ) if nextApp is None : nextApp = self . qteNextApplet ( skipInvisible = False , skipVisible = True ) if nextApp is None : return split . qteAddWidget ( nextApp ) return appletIdx = split . indexOf ( appletObj ) appletObj . hide ( True ) if split . count ( ) != 1 : msg = ( 'Splitter has <b>{}</b> elements left instead of' ' exactly one.' . format ( split . count ( ) ) ) self . qteLogger . warning ( msg ) otherWidget = split . widget ( 0 ) if otherWidget . _qteAdmin . widgetSignature == '__QtmacsLayoutSplitter__' : for ii in range ( otherWidget . count ( ) ) : obj = otherWidget . widget ( 0 ) if appletIdx == 0 : split . qteAddWidget ( obj ) else : split . qteInsertWidget ( 1 + ii , obj ) otherWidget . setParent ( None ) otherWidget . close ( ) else : if split is not window . qteAppletSplitter : otherWidget . qteReparent ( split . parent ( ) ) split . setParent ( None ) split . close ( )
Remove applet from the window layout .
7,763
def qteKillApplet ( self , appletID : str ) : ID_list = [ _ . qteAppletID ( ) for _ in self . _qteAppletList ] if appletID not in ID_list : return else : idx = ID_list . index ( appletID ) appObj = self . _qteAppletList [ idx ] if self . qteIsMiniApplet ( appObj ) : self . qteKillMiniApplet ( ) return appObj . qteToBeKilled ( ) window = appObj . qteParentWindow ( ) newApplet = self . qteNextApplet ( numSkip = - 1 , skipInvisible = False , skipVisible = True ) if ( newApplet is None ) or ( newApplet is appObj ) : newApplet = None else : self . qteReplaceAppletInLayout ( newApplet , appObj , window ) if self . _qteActiveApplet is appObj : self . _qteActiveApplet = newApplet self . qteLogger . debug ( 'Kill applet: <b>{}</b>' . format ( appletID ) ) self . _qteAppletList . remove ( appObj ) appObj . close ( ) sip . delete ( appObj )
Destroy the applet with ID appletID .
7,764
def qteRunHook ( self , hookName : str , msgObj : QtmacsMessage = None ) : reg = self . _qteRegistryHooks if hookName not in reg : return if msgObj is None : msgObj = QtmacsMessage ( ) msgObj . setHookName ( hookName ) for fun in reg [ hookName ] : try : fun ( msgObj ) except Exception as err : msg = '<b>{}</b>-hook function <b>{}</b>' . format ( hookName , str ( fun ) [ 1 : - 1 ] ) msg += " did not execute properly." if isinstance ( err , QtmacsArgumentError ) : msg += '<br/>' + str ( err ) self . qteLogger . exception ( msg , exc_info = True , stack_info = True )
Trigger the hook named hookName and pass on msgObj .
7,765
def qteConnectHook ( self , hookName : str , slot : ( types . FunctionType , types . MethodType ) ) : reg = self . _qteRegistryHooks if hookName in reg : reg [ hookName ] . append ( slot ) else : reg [ hookName ] = [ slot ]
Connect the method or function slot to hookName .
7,766
def qteDisconnectHook ( self , hookName : str , slot : ( types . FunctionType , types . MethodType ) ) : reg = self . _qteRegistryHooks if hookName not in reg : msg = 'There is no hook called <b>{}</b>.' self . qteLogger . info ( msg . format ( hookName ) ) return False if slot not in reg [ hookName ] : msg = 'Slot <b>{}</b> is not connected to hook <b>{}</b>.' self . qteLogger . info ( msg . format ( str ( slot ) [ 1 : - 1 ] , hookName ) ) return False reg [ hookName ] . remove ( slot ) if len ( reg [ hookName ] ) == 0 : reg . pop ( hookName ) return True
Disconnect slot from hookName .
7,767
def qteImportModule ( self , fileName : str ) : path , name = os . path . split ( fileName ) name , ext = os . path . splitext ( name ) if path == '' : path = sys . path else : path = [ path ] try : fp , pathname , desc = imp . find_module ( name , path ) except ImportError : msg = 'Could not find module <b>{}</b>.' . format ( fileName ) self . qteLogger . error ( msg ) return None try : mod = imp . load_module ( name , fp , pathname , desc ) return mod except ImportError : msg = 'Could not import module <b>{}</b>.' . format ( fileName ) self . qteLogger . error ( msg ) return None finally : if fp : fp . close ( )
Import fileName at run - time .
7,768
def qteMacroNameMangling ( self , macroCls ) : macroName = re . sub ( r"([A-Z])" , r'-\1' , macroCls . __name__ ) if macroName [ 0 ] == '-' : macroName = macroName [ 1 : ] return macroName . lower ( )
Convert the class name of a macro class to macro name .
7,769
def qteRegisterMacro ( self , macroCls , replaceMacro : bool = False , macroName : str = None ) : if not issubclass ( macroCls , QtmacsMacro ) : args = ( 'macroCls' , 'class QtmacsMacro' , inspect . stack ( ) [ 0 ] [ 3 ] ) raise QtmacsArgumentError ( * args ) try : macroObj = macroCls ( ) except Exception : msg = 'The macro <b>{}</b> has a faulty constructor.' msg = msg . format ( macroCls . __name__ ) self . qteLogger . error ( msg , stack_info = True ) return None if macroName is None : if macroObj . qteMacroName ( ) is None : macroName = self . qteMacroNameMangling ( macroCls ) else : macroName = macroObj . qteMacroName ( ) macroObj . _qteMacroName = macroName if len ( macroObj . qteAppletSignature ( ) ) == 0 : msg = 'Macro <b>{}</b> has no applet signatures.' . format ( macroName ) self . qteLogger . error ( msg , stack_info = True ) return None if len ( macroObj . qteWidgetSignature ( ) ) == 0 : msg = 'Macro <b>{}</b> has no widget signatures.' . format ( macroName ) self . qteLogger . error ( msg , stack_info = True ) return None anyRegistered = False for app_sig in macroObj . qteAppletSignature ( ) : for wid_sig in macroObj . qteWidgetSignature ( ) : macroNameInternal = ( macroName , app_sig , wid_sig ) if macroNameInternal in self . _qteRegistryMacros : if replaceMacro : tmp = self . _qteRegistryMacros . pop ( macroNameInternal ) msg = 'Replacing existing macro <b>{}</b> with new {}.' msg = msg . format ( macroNameInternal , macroObj ) self . qteLogger . info ( msg ) tmp . deleteLater ( ) else : msg = 'Macro <b>{}</b> already exists (not replaced).' msg = msg . format ( macroNameInternal ) self . qteLogger . info ( msg ) continue self . _qteRegistryMacros [ macroNameInternal ] = macroObj msg = ( 'Macro <b>{}</b> successfully registered.' . format ( macroNameInternal ) ) self . qteLogger . info ( msg ) anyRegistered = True return macroName
Register a macro .
7,770
def qteGetMacroObject ( self , macroName : str , widgetObj : QtGui . QWidget ) : if hasattr ( widgetObj , '_qteAdmin' ) : app_signature = widgetObj . _qteAdmin . appletSignature wid_signature = widgetObj . _qteAdmin . widgetSignature if app_signature is None : msg = 'Applet has no signature.' self . qteLogger . error ( msg , stack_info = True ) return None else : wid_signature = None app = qteGetAppletFromWidget ( widgetObj ) if app is None : app_signature = None else : app_signature = app . _qteAdmin . appletSignature name_match = [ m for m in self . _qteRegistryMacros if m [ 0 ] == macroName ] app_sig_match = [ _ for _ in name_match if _ [ 1 ] in ( app_signature , '*' ) ] if wid_signature is None : wid_sig_match = [ _ for _ in app_sig_match if _ [ 2 ] == '*' ] else : wid_sig_match = [ _ for _ in app_sig_match if _ [ 2 ] in ( wid_signature , '*' ) ] if len ( wid_sig_match ) == 0 : return None elif len ( wid_sig_match ) == 1 : match = wid_sig_match [ 0 ] return self . _qteRegistryMacros [ match ] else : tmp = [ match for match in wid_sig_match if ( match [ 1 ] != '*' ) and ( match [ 2 ] != '*' ) ] if len ( tmp ) > 0 : match = tmp [ 0 ] return self . _qteRegistryMacros [ match ] tmp = [ match for match in wid_sig_match if match [ 2 ] != '*' ] if len ( tmp ) > 0 : match = tmp [ 0 ] return self . _qteRegistryMacros [ match ] tmp = [ match for match in wid_sig_match if match [ 1 ] != '*' ] if len ( tmp ) > 0 : match = tmp [ 0 ] return self . _qteRegistryMacros [ match ] tmp = [ match for match in wid_sig_match if ( match [ 1 ] == '*' ) and ( match [ 2 ] == '*' ) ] if len ( tmp ) > 0 : match = tmp [ 0 ] return self . _qteRegistryMacros [ match ] msg = 'No compatible macro found - should be impossible.' self . qteLogger . error ( msg , stack_info = True )
Return macro that is name - and signature compatible with macroName and widgetObj .
7,771
def qteGetAllMacroNames ( self , widgetObj : QtGui . QWidget = None ) : macro_list = tuple ( self . _qteRegistryMacros . keys ( ) ) macro_list = [ _ [ 0 ] for _ in macro_list ] macro_list = tuple ( set ( macro_list ) ) if widgetObj is None : return macro_list else : macro_list = [ self . qteGetMacroObject ( macroName , widgetObj ) for macroName in macro_list ] macro_list = [ _ . qteMacroName ( ) for _ in macro_list if _ is not None ] return macro_list
Return all macro names known to Qtmacs as a list .
7,772
def qteBindKeyGlobal ( self , keysequence , macroName : str ) : keysequence = QtmacsKeysequence ( keysequence ) if not self . qteIsMacroRegistered ( macroName ) : msg = 'Cannot globally bind key to unknown macro <b>{}</b>.' msg = msg . format ( macroName ) self . qteLogger . error ( msg , stack_info = True ) return False self . _qteGlobalKeyMap . qteInsertKey ( keysequence , macroName ) for app in self . _qteAppletList : self . qteBindKeyApplet ( keysequence , macroName , app ) return True
Associate macroName with keysequence in all current applets .
7,773
def qteBindKeyApplet ( self , keysequence , macroName : str , appletObj : QtmacsApplet ) : keysequence = QtmacsKeysequence ( keysequence ) if not self . qteIsMacroRegistered ( macroName ) : msg = ( 'Cannot bind key because the macro <b>{}</b> does' 'not exist.' . format ( macroName ) ) self . qteLogger . error ( msg , stack_info = True ) return False appletObj . _qteAdmin . keyMap . qteInsertKey ( keysequence , macroName ) for wid in appletObj . _qteAdmin . widgetList : self . qteBindKeyWidget ( keysequence , macroName , wid ) return True
Bind macroName to all widgets in appletObj .
7,774
def qteBindKeyWidget ( self , keysequence , macroName : str , widgetObj : QtGui . QWidget ) : keysequence = QtmacsKeysequence ( keysequence ) if not hasattr ( widgetObj , '_qteAdmin' ) : msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError ( msg ) if not self . qteIsMacroRegistered ( macroName ) : msg = ( 'Cannot bind key to unknown macro <b>{}</b>.' . format ( macroName ) ) self . qteLogger . error ( msg , stack_info = True ) return False try : widgetObj . _qteAdmin . keyMap . qteInsertKey ( keysequence , macroName ) except AttributeError : msg = 'Received an invalid macro object.' self . qteLogger . error ( msg , stack_info = True ) return False return True
Bind macroName to widgetObj and associate it with keysequence .
7,775
def qteUnbindKeyApplet ( self , applet : ( QtmacsApplet , str ) , keysequence ) : if isinstance ( applet , str ) : appletObj = self . qteGetAppletHandle ( applet ) else : appletObj = applet if appletObj is None : return keysequence = QtmacsKeysequence ( keysequence ) appletObj . _qteAdmin . keyMap . qteRemoveKey ( keysequence ) for wid in appletObj . _qteAdmin . widgetList : self . qteUnbindKeyFromWidgetObject ( keysequence , wid )
Remove keysequence bindings from all widgets inside applet .
7,776
def qteUnbindKeyFromWidgetObject ( self , keysequence , widgetObj : QtGui . QWidget ) : keysequence = QtmacsKeysequence ( keysequence ) if not hasattr ( widgetObj , '_qteAdmin' ) : msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError ( msg ) widgetObj . _qteAdmin . keyMap . qteRemoveKey ( keysequence )
Disassociate the macro triggered by keysequence from widgetObj .
7,777
def qteUnbindAllFromApplet ( self , applet : ( QtmacsApplet , str ) ) : if isinstance ( applet , str ) : appletObj = self . qteGetAppletHandle ( applet ) else : appletObj = applet if appletObj is None : return appletObj . _qteAdmin . keyMap = self . qteCopyGlobalKeyMap ( ) for wid in appletObj . _qteAdmin . widgetList : wid . _qteAdmin . keyMap = self . qteCopyGlobalKeyMap ( )
Restore the global key - map for all widgets inside applet .
7,778
def qteUnbindAllFromWidgetObject ( self , widgetObj : QtGui . QWidget ) : if not hasattr ( widgetObj , '_qteAdmin' ) : msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError ( msg ) widgetObj . _qteAdmin . keyMap = self . qteCopyGlobalKeyMap ( )
Reset the local key - map of widgetObj to the current global key - map .
7,779
def qteRegisterApplet ( self , cls , replaceApplet : bool = False ) : if not issubclass ( cls , QtmacsApplet ) : args = ( 'cls' , 'class QtmacsApplet' , inspect . stack ( ) [ 0 ] [ 3 ] ) raise QtmacsArgumentError ( * args ) class_name = cls . __name__ if class_name in self . _qteRegistryApplets : msg = 'The original applet <b>{}</b>' . format ( class_name ) if replaceApplet : msg += ' was redefined.' self . qteLogger . warning ( msg ) else : msg += ' was not redefined.' self . qteLogger . warning ( msg ) return class_name cls . __qteRegisterAppletInit__ ( ) self . _qteRegistryApplets [ class_name ] = cls self . qteLogger . info ( 'Applet <b>{}</b> now registered.' . format ( class_name ) ) return class_name
Register cls as an applet .
7,780
def qteGetAppletHandle ( self , appletID : str ) : id_list = [ _ . qteAppletID ( ) for _ in self . _qteAppletList ] if appletID in id_list : idx = id_list . index ( appletID ) return self . _qteAppletList [ idx ] else : return None
Return a handle to appletID .
7,781
def qteMakeAppletActive ( self , applet : ( QtmacsApplet , str ) ) : if isinstance ( applet , str ) : appletObj = self . qteGetAppletHandle ( applet ) else : appletObj = applet if appletObj not in self . _qteAppletList : return False if self . qteIsMiniApplet ( appletObj ) : if appletObj is not self . _qteMiniApplet : self . qteLogger . warning ( 'Wrong mini applet. Not activated.' ) print ( appletObj ) print ( self . _qteMiniApplet ) return False if not appletObj . qteIsVisible ( ) : appletObj . show ( True ) else : if not appletObj . qteIsVisible ( ) : self . qteReplaceAppletInLayout ( appletObj ) self . _qteActiveApplet = appletObj return True
Make applet visible and give it the focus .
7,782
def qteCloseQtmacs ( self ) : msgObj = QtmacsMessage ( ) msgObj . setSignalName ( 'qtesigCloseQtmacs' ) self . qtesigCloseQtmacs . emit ( msgObj ) for appName in self . qteGetAllAppletIDs ( ) : self . qteKillApplet ( appName ) self . _qteFocusManager ( ) for window in self . _qteWindowList : window . close ( ) self . _qteFocusManager ( ) self . deleteLater ( )
Close Qtmacs .
7,783
def qteDefVar ( self , varName : str , value , module = None , doc : str = None ) : if module is None : module = qte_global if not hasattr ( module , '_qte__variable__docstring__dictionary__' ) : module . _qte__variable__docstring__dictionary__ = { } setattr ( module , varName , value ) module . _qte__variable__docstring__dictionary__ [ varName ] = doc return True
Define and document varName in an arbitrary name space .
7,784
def qteGetVariableDoc ( self , varName : str , module = None ) : if module is None : module = qte_global if not hasattr ( module , '_qte__variable__docstring__dictionary__' ) : return None if varName not in module . _qte__variable__docstring__dictionary__ : return None return module . _qte__variable__docstring__dictionary__ [ varName ]
Retrieve documentation for varName defined in module .
7,785
def qteEmulateKeypresses ( self , keysequence ) : keysequence = QtmacsKeysequence ( keysequence ) key_list = keysequence . toQKeyEventList ( ) if len ( key_list ) > 0 : for event in key_list : self . _qteKeyEmulationQueue . append ( event )
Emulate the Qt key presses that define keysequence .
7,786
def process ( self , model = None , context = None ) : self . filter ( model , context ) return self . validate ( model , context )
Perform validation and filtering at the same time return a validation result object .
7,787
def get_sys_info ( ) : blob = dict ( ) blob [ "OS" ] = platform . system ( ) blob [ "OS-release" ] = platform . release ( ) blob [ "Python" ] = platform . python_version ( ) return blob
Return system information as a dict .
7,788
def get_pkg_info ( package_name , additional = ( "pip" , "flit" , "pbr" , "setuptools" , "wheel" ) ) : dist_index = build_dist_index ( pkg_resources . working_set ) root = dist_index [ package_name ] tree = construct_tree ( dist_index ) dependencies = { pkg . name : pkg . installed_version for pkg in tree [ root ] } root = root . as_requirement ( ) dependencies [ root . name ] = root . installed_version for name in additional : try : pkg = dist_index [ name ] . as_requirement ( ) dependencies [ pkg . name ] = pkg . installed_version except KeyError : continue return dependencies
Return build and package dependencies as a dict .
7,789
def print_info ( info ) : format_str = "{:<%d} {:>%d}" % ( max ( map ( len , info ) ) , max ( map ( len , info . values ( ) ) ) , ) for name in sorted ( info ) : print ( format_str . format ( name , info [ name ] ) )
Print an information dict to stdout in order .
7,790
def print_dependencies ( package_name ) : info = get_sys_info ( ) print ( "\nSystem Information" ) print ( "==================" ) print_info ( info ) info = get_pkg_info ( package_name ) print ( "\nPackage Versions" ) print ( "================" ) print_info ( info )
Print the formatted information to standard out .
7,791
def repeat_read_url_request ( url , headers = None , data = None , retries = 2 , logger = None ) : if logger : logger . debug ( "Retrieving url content: {}" . format ( url ) ) req = urllib2 . Request ( url , data , headers = headers or { } ) return repeat_call ( lambda : urllib2 . urlopen ( req ) . read ( ) , retries )
Allows for repeated http requests up to retries additional times
7,792
def repeat_read_json_url_request ( url , headers = None , data = None , retries = 2 , logger = None ) : if logger : logger . debug ( "Retrieving url json content: {}" . format ( url ) ) req = urllib2 . Request ( url , data = data , headers = headers or { } ) return repeat_call ( lambda : json . loads ( urllib2 . urlopen ( req ) . read ( ) ) , retries )
Allows for repeated http requests up to retries additional times with convienence wrapper on jsonization of response
7,793
def priv ( x ) : if x . startswith ( u'172.' ) : return 16 <= int ( x . split ( u'.' ) [ 1 ] ) < 32 return x . startswith ( ( u'192.168.' , u'10.' , u'172.' ) )
Quick and dirty method to find an IP on a private network given a correctly formatted IPv4 quad .
7,794
def create_client_socket ( self , config ) : client_socket = WUDPNetworkNativeTransport . create_client_socket ( self , config ) client_socket . setsockopt ( socket . SOL_SOCKET , socket . SO_BROADCAST , 1 ) return client_socket
Create client broadcast socket
7,795
def run_object_query ( client , base_object_query , start_record , limit_to , verbose = False ) : if verbose : print ( "[start: %d limit: %d]" % ( start_record , limit_to ) ) start = datetime . datetime . now ( ) result = client . execute_object_query ( object_query = base_object_query , start_record = start_record , limit_to = limit_to ) end = datetime . datetime . now ( ) if verbose : print ( "[%s - %s]" % ( start , end ) ) return result
inline method to take advantage of retry
7,796
def get_long_query ( self , base_object_query , limit_to = 100 , max_calls = None , start_record = 0 , verbose = False ) : if verbose : print ( base_object_query ) record_index = start_record result = run_object_query ( self . client , base_object_query , record_index , limit_to , verbose ) obj_search_result = ( result [ 'body' ] [ "ExecuteMSQLResult" ] [ "ResultValue" ] [ "ObjectSearchResult" ] ) if obj_search_result is not None : search_results = obj_search_result [ "Objects" ] else : return [ ] if search_results is None : return [ ] result_set = search_results [ "MemberSuiteObject" ] all_objects = self . result_to_models ( result ) call_count = 1 while call_count != max_calls and len ( result_set ) >= limit_to : record_index += len ( result_set ) result = run_object_query ( self . client , base_object_query , record_index , limit_to , verbose ) obj_search_result = ( result [ 'body' ] [ "ExecuteMSQLResult" ] [ "ResultValue" ] [ "ObjectSearchResult" ] ) if obj_search_result is not None : search_results = obj_search_result [ "Objects" ] else : search_results = None if search_results is None : result_set = [ ] else : result_set = search_results [ "MemberSuiteObject" ] all_objects += self . result_to_models ( result ) call_count += 1 return all_objects
Takes a base query for all objects and recursively requests them
7,797
def logger ( self ) : if self . _experiment : return logging . getLogger ( '.' . join ( [ self . name , self . experiment ] ) ) elif self . _projectname : return logging . getLogger ( '.' . join ( [ self . name , self . projectname ] ) ) else : return logging . getLogger ( '.' . join ( [ self . name ] ) )
The logger of this organizer
7,798
def main ( cls , args = None ) : organizer = cls ( ) organizer . parse_args ( args ) if not organizer . no_modification : organizer . config . save ( )
Run the organizer from the command line
7,799
def start ( self , ** kwargs ) : ts = { } ret = { } info_parts = { 'info' , 'get-value' , 'get_value' } for cmd in self . commands : parser_cmd = self . parser_commands . get ( cmd , cmd ) if parser_cmd in kwargs or cmd in kwargs : kws = kwargs . get ( cmd , kwargs . get ( parser_cmd ) ) if isinstance ( kws , Namespace ) : kws = vars ( kws ) func = getattr ( self , cmd or 'main' ) ret [ cmd ] = func ( ** kws ) if cmd not in info_parts : ts [ cmd ] = str ( dt . datetime . now ( ) ) exp = self . _experiment project_parts = { 'setup' } projectname = self . _projectname if ( projectname is not None and project_parts . intersection ( ts ) and projectname in self . config . projects ) : self . config . projects [ projectname ] [ 'timestamps' ] . update ( { key : ts [ key ] for key in project_parts . intersection ( ts ) } ) elif not ts : self . no_modification = True if exp is not None and exp in self . config . experiments : projectname = self . projectname try : ts . update ( self . config . projects [ projectname ] [ 'timestamps' ] ) except KeyError : pass if not self . is_archived ( exp ) : self . config . experiments [ exp ] [ 'timestamps' ] . update ( ts ) return Namespace ( ** ret )
Start the commands of this organizer