idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
7,700 | def postproc ( self , close = True , * * kwargs ) : import matplotlib . pyplot as plt import seaborn as sns # for nice plot styles self . app_main ( * * kwargs ) # ---- load the data indata = np . loadtxt ( self . exp_config [ 'infile' ] ) outdata = np . loadtxt ( self . exp_config [ 'output' ] ) x_data = np . linspace ( - np . pi , np . pi ) # ---- make the plot fig = plt . figure ( ) # plot input data plt . plot ( x_data , indata , label = 'input' ) # plot output data plt . plot ( x_data , outdata , label = 'squared' ) # draw a legend plt . legend ( ) # use the description of the experiment as title plt . title ( self . exp_config . get ( 'description' ) ) # ---- save the plot 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 | 294 | 6 |
7,701 | 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 . | 70 | 12 |
7,702 | def push ( self , undoObj ) : # Check type of input arguments. if not isinstance ( undoObj , QtmacsUndoCommand ) : raise QtmacsArgumentError ( 'undoObj' , 'QtmacsUndoCommand' , inspect . stack ( ) [ 0 ] [ 3 ] ) # Flag that the last action was not an undo action and push # the command to the stack. self . _wasUndo = False self . _push ( undoObj ) | Add undoObj command to stack and run its commit method . | 102 | 12 |
7,703 | def undo ( self ) : # If it is the first call to this method after a ``push`` then # reset ``qteIndex`` to the last element, otherwise just # decrease it. if not self . _wasUndo : self . _qteIndex = len ( self . _qteStack ) else : self . _qteIndex -= 1 # Flag that the last action was an `undo` operation. self . _wasUndo = True if self . _qteIndex <= 0 : return # Make a copy of the command and push it to the stack. undoObj = self . _qteStack [ self . _qteIndex - 1 ] undoObj = QtmacsUndoCommand ( undoObj ) self . _push ( undoObj ) # If the just pushed undo object restored the last saved state # then trigger the ``qtesigSavedState`` signal and set the # _qteLastSaveUndoIndex variable again. This is necessary # because an undo command will not *remove* any elements from # the undo stack but *add* the inverse operation to the # stack. Therefore, when enough undo operations have been # performed to reach the last saved state that means that the # last addition to the stack is now implicitly the new last # save point. if ( self . _qteIndex - 1 ) == self . _qteLastSavedUndoIndex : self . qtesigSavedState . emit ( QtmacsMessage ( ) ) self . saveState ( ) | Undo the last command by adding its inverse action to the stack . | 317 | 14 |
7,704 | 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 . | 79 | 24 |
7,705 | 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 . | 57 | 10 |
7,706 | 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 . | 50 | 12 |
7,707 | def keyPressEvent ( self , keyEvent ) : undoObj = UndoSelfInsert ( self , keyEvent . text ( ) ) self . qteUndoStack . push ( undoObj ) | Insert the character at the current cursor position . | 41 | 9 |
7,708 | def get_schema_version_from_xml ( xml ) : if isinstance ( xml , six . string_types ) : xml = StringIO ( xml ) try : tree = ElementTree . parse ( xml ) except ParseError : # Not an XML file 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 | 82 | 22 |
7,709 | 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 . | 149 | 18 |
7,710 | 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 . | 48 | 42 |
7,711 | 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 . | 76 | 7 |
7,712 | 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 . | 100 | 15 |
7,713 | def type_check ( func_handle ) : def checkType ( var_name , var_val , annot ) : # Retrieve the annotation for this variable and determine # if the type of that variable matches with the annotation. # This annotation is stored in the dictionary ``annot`` # but contains only variables for such an annotation exists, # hence the if/else branch. if var_name in annot : # Fetch the type-annotation of the variable. var_anno = annot [ var_name ] # Skip the type check if the variable is none, otherwise # check if it is a derived class. The only exception from # the latter rule are binary values, because in Python # # >> isinstance(False, int) # True # # and warrants a special check. 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 : # Variable without annotation are compatible by assumption. var_anno = 'Unspecified' type_ok = True # If the check failed then raise a QtmacsArgumentError. 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 ) : # Retrieve information about all arguments passed to the function, # as well as their annotations in the function signature. argspec = inspect . getfullargspec ( func_handle ) # Convert all variable annotations that were not specified as a # tuple or list into one, eg. str --> will become (str,) annot = { } for key , val in argspec . annotations . items ( ) : if isinstance ( val , tuple ) or isinstance ( val , list ) : annot [ key ] = val else : annot [ key ] = val , # Note the trailing colon! # Prefix the argspec.defaults tuple with **None** elements to make # its length equal to the number of variables (for sanity in the # code below). Since **None** types are always ignored by this # decorator this change is neutral. 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 # Shorthand for the number of unnamed arguments. ofs = len ( args ) # Process the unnamed arguments. These are always the first ``ofs`` # elements in argspec.args. for idx , var_name in enumerate ( argspec . args [ : ofs ] ) : # Look up the value in the ``args`` variable. var_val = args [ idx ] checkType ( var_name , var_val , annot ) # Process the named- and default arguments. for idx , var_name in enumerate ( argspec . args [ ofs : ] ) : # Extract the argument value. If it was passed to the # function as a named (ie. keyword) argument then extract # it from ``kwds``, otherwise look it up in the tuple with # the default values. 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 . | 812 | 12 |
7,714 | 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 | 81 | 6 |
7,715 | 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 | 57 | 8 |
7,716 | 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 | 80 | 125 |
7,717 | def qteAdjustWidgetSizes ( self , handlePos : int = None ) : # Do not adjust anything if there are less than two widgets. if self . count ( ) < 2 : return if self . orientation ( ) == QtCore . Qt . Horizontal : totDim = self . size ( ) . width ( ) - self . handleWidth ( ) else : totDim = self . size ( ) . height ( ) - self . handleWidth ( ) # Assign both widgets the same size if no handle position provided. if handlePos is None : handlePos = ( totDim + self . handleWidth ( ) ) // 2 # Sanity check. if not ( 0 <= handlePos <= totDim ) : return # Compute widget sizes according to handle position. newSize = [ handlePos , totDim - handlePos ] # Assign the widget sizes. self . setSizes ( newSize ) | Adjust the widget size inside the splitter according to handlePos . | 189 | 13 |
7,718 | def qteAddWidget ( self , widget ) : # Add ``widget`` to the splitter. self . addWidget ( widget ) # Show ``widget``. If it is a ``QtmacsSplitter`` instance then its # show() methods has no argument, whereas ``QtmacsApplet`` instances # have overloaded show() methods because they should not be called # unless you really know what you are doing (it will mess with Qtmacs # layout engine). if widget . _qteAdmin . widgetSignature == '__QtmacsLayoutSplitter__' : widget . show ( ) else : widget . show ( True ) # Adjust the sizes of the widgets inside the splitter according to # the handle position. self . qteAdjustWidgetSizes ( ) | Add a widget to the splitter and make it visible . | 162 | 12 |
7,719 | def qteInsertWidget ( self , idx , widget ) : # Insert the widget into the splitter. self . insertWidget ( idx , widget ) # Show ``widget``. If it is a ``QtmacsSplitter`` instance then its # show() methods has no argument, whereas ``QtmacsApplet`` instances # have overloaded show() methods because they should not be called # unless you really know what you are doing (it will mess with Qtmacs # layout engine). if widget . _qteAdmin . widgetSignature == '__QtmacsLayoutSplitter__' : widget . show ( ) else : widget . show ( True ) # Adjust the sizes of the widgets inside the splitter according to # the handle position. self . qteAdjustWidgetSizes ( ) | Insert widget to the splitter at the specified idx position and make it visible . | 167 | 17 |
7,720 | def timerEvent ( self , event ) : self . killTimer ( event . timerId ( ) ) if event . timerId ( ) == self . _qteTimerRunMacro : # Declare the macro execution timer event handled. self . _qteTimerRunMacro = None # If we are in this branch then the focus manager was just # executed, the event loop has updated all widgets and # cleared out all signals, and there is at least one macro # in the macro queue and/or at least one key to emulate # in the key queue. Execute the macros/keys and trigger # the focus manager after each. The macro queue is cleared # out first and the keys are only emulated if no more # macros are left. while True : if len ( self . _qteMacroQueue ) > 0 : ( macroName , qteWidget , event ) = self . _qteMacroQueue . pop ( 0 ) self . _qteRunQueuedMacro ( macroName , qteWidget , event ) elif len ( self . _qteKeyEmulationQueue ) > 0 : # Determine the recipient of the event. This can # be, in order of preference, the active widget in # the active applet, or just the active applet (if # it has no widget inside), or the active window # (if no applets are available). if self . _qteActiveApplet is None : receiver = self . qteActiveWindow ( ) else : if self . _qteActiveApplet . _qteActiveWidget is None : receiver = self . _qteActiveApplet else : receiver = self . _qteActiveApplet . _qteActiveWidget # Call the event filter directly and trigger the focus # manager again. keysequence = self . _qteKeyEmulationQueue . pop ( 0 ) self . _qteEventFilter . eventFilter ( receiver , keysequence ) else : # If we are in this branch then no more macros are left # to run. So trigger the focus manager one more time # and then leave the while-loop. self . _qteFocusManager ( ) break self . _qteFocusManager ( ) elif event . timerId ( ) == self . debugTimer : #win = self.qteNextWindow() #self.qteMakeWindowActive(win) #self.debugTimer = self.startTimer(1000) pass else : # Should not happen. print ( 'Unknown timer ID' ) pass | Trigger the focus manager and work off all queued macros . | 528 | 12 |
7,721 | def _qteMouseClicked ( self , widgetObj ) : # ------------------------------------------------------------ # The following cases for widgetObj have to be distinguished: # 1: not part of the Qtmacs widget hierarchy # 2: part of the Qtmacs widget hierarchy but not registered # 3: registered with Qtmacs and an applet # 4: registered with Qtmacs and anything but an applet # ------------------------------------------------------------ # Case 1: return immediately if widgetObj is not part of the # Qtmacs widget hierarchy; otherwise, declare the applet # containing the widgetObj active. app = qteGetAppletFromWidget ( widgetObj ) if app is None : return else : self . _qteActiveApplet = app # Case 2: unregistered widgets are activated immediately. if not hasattr ( widgetObj , '_qteAdmin' ) : self . _qteActiveApplet . qteMakeWidgetActive ( widgetObj ) else : if app . _qteAdmin . isQtmacsApplet : # Case 3: widgetObj is a QtmacsApplet instance; do not # focus any of its widgets as the focus manager will # take care of it. self . _qteActiveApplet . qteMakeWidgetActive ( None ) else : # Case 4: widgetObj was registered with qteAddWidget # and can thus be focused directly. self . _qteActiveApplet . qteMakeWidgetActive ( widgetObj ) # Trigger the focus manager. self . _qteFocusManager ( ) | Update the Qtmacs internal focus state as the result of a mouse click . | 320 | 16 |
7,722 | def qteFocusChanged ( self , old , new ) : # Do nothing if new is old. if old is new : return # If neither is None but both have the same top level # window then do nothing. 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 . | 78 | 19 |
7,723 | def qteIsMiniApplet ( self , obj ) : try : ret = obj . _qteAdmin . isMiniApplet except AttributeError : ret = False return ret | Test if instance obj is a mini applet . | 38 | 10 |
7,724 | def qteNewWindow ( self , pos : QtCore . QRect = None , windowID : str = None ) : # Compile a list of all window IDs. winIDList = [ _ . _qteWindowID for _ in self . _qteWindowList ] # If no window ID was supplied simply count until a new and # unique ID was found. if windowID is None : cnt = 0 while str ( cnt ) in winIDList : cnt += 1 windowID = str ( cnt ) # If no position was specified use a default one. if pos is None : pos = QtCore . QRect ( 500 , 300 , 1000 , 500 ) # Raise an error if a window with this ID already exists. if windowID in winIDList : msg = 'Window with ID <b>{}</b> already exists.' . format ( windowID ) raise QtmacsOtherError ( msg ) # Instantiate a new window object. window = QtmacsWindow ( pos , windowID ) # Add the new window to the window list and make it visible. self . _qteWindowList . append ( window ) window . show ( ) # Trigger the focus manager once the event loop is in control again. return window | Create a new empty window with windowID at position pos . | 263 | 12 |
7,725 | def qteMakeWindowActive ( self , windowObj : QtmacsWindow ) : if windowObj in self . _qteWindowList : # This will trigger the focusChanged slot which, in # conjunction with the focus manager, will take care of # the rest. Note that ``activateWindow`` is a native Qt # method, not a Qtmacs invention. windowObj . activateWindow ( ) else : self . qteLogger . warning ( 'Window to activate does not exist' ) | Make the window windowObj active and focus the first applet therein . | 103 | 14 |
7,726 | 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 : # Find the active window. for win in self . _qteWindowList : if win . isActiveWindow ( ) : return win # Return the first window if none is active. return self . _qteWindowList [ 0 ] | Return the currently active QtmacsWindow object . | 119 | 10 |
7,727 | def qteNextWindow ( self ) : # Get the currently active window. win = self . qteActiveWindow ( ) if win in self . _qteWindowList : # Find the index of the window in the window list and # cyclically move to the next element in this list to find # the next window object. 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 . | 145 | 8 |
7,728 | def qteRunMacro ( self , macroName : str , widgetObj : QtGui . QWidget = None , keysequence : QtmacsKeysequence = None ) : # Add the new macro to the queue and call qteUpdate to ensure # that the macro is processed once the event loop is idle again. self . _qteMacroQueue . append ( ( macroName , widgetObj , keysequence ) ) self . qteUpdate ( ) | Queue a previously registered macro for execution once the event loop is idle . | 96 | 14 |
7,729 | def _qteRunQueuedMacro ( self , macroName : str , widgetObj : QtGui . QWidget = None , keysequence : QtmacsKeysequence = None ) : # Fetch the applet holding the widget (this may be None). app = qteGetAppletFromWidget ( widgetObj ) # Double check that the applet still exists, unless there is # no applet (can happen when the windows are empty). 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 # Fetch a signature compatible macro object. macroObj = self . qteGetMacroObject ( macroName , widgetObj ) # Log an error if no compatible macro was found. 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 # Update the 'last_key_sequence' variable in case the macros, # or slots triggered by that macro, have access to it. self . qteDefVar ( 'last_key_sequence' , keysequence , doc = "Last valid key sequence that triggered a macro." ) # Set some variables in the macro object for convenient access # from inside the macro. if app is None : macroObj . qteApplet = macroObj . qteWidget = None else : macroObj . qteApplet = app macroObj . qteWidget = widgetObj # Run the macro and trigger the focus manager. macroObj . qtePrepareToRun ( ) | Execute the next macro in the macro queue . | 407 | 10 |
7,730 | def qteNewApplet ( self , appletName : str , appletID : str = None , windowObj : QtmacsWindow = None ) : # Use the currently active window if none was specified. 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 # Determine an automatic applet ID if none was provided. if appletID is None : cnt = 0 while True : appletID = appletName + '_' + str ( cnt ) if self . qteGetAppletHandle ( appletID ) is None : break else : cnt += 1 # Return immediately if an applet with the same ID already # exists. 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 # Verify that the requested applet class was registered # beforehand and fetch it. 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 to instantiate the class. 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 # Ensure the applet class has an applet signature. 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 # Add the applet to the list of instantiated Qtmacs applets. self . _qteAppletList . insert ( 0 , app ) # If the new applet does not yet have an internal layout then # arrange all its children automatically. The layout used for # this is horizontal and the widgets are added in the order in # which they were registered with Qtmacs. if app . layout ( ) is None : appLayout = QtGui . QHBoxLayout ( ) for handle in app . _qteAdmin . widgetList : appLayout . addWidget ( handle ) app . setLayout ( appLayout ) # Initially, the window does not have a parent. A parent will # be assigned automatically once the applet is made visible, # in which case it is re-parented into a QtmacsSplitter. app . qteReparent ( None ) # Emit the init hook for this applet. self . qteRunHook ( 'init' , QtmacsMessage ( None , app ) ) # Return applet handle. return app | Create a new instance of appletName and assign it the appletID . | 744 | 16 |
7,731 | def qteAddMiniApplet ( self , appletObj : QtmacsApplet ) : # Do nothing if a custom mini applet has already been # installed. if self . _qteMiniApplet is not None : msg = 'Cannot replace mini applet more than once.' self . qteLogger . warning ( msg ) return False # Arrange all registered widgets inside this applet # automatically if the mini applet object did not install its # own layout. if appletObj . layout ( ) is None : appLayout = QtGui . QHBoxLayout ( ) for handle in appletObj . _qteAdmin . widgetList : appLayout . addWidget ( handle ) appletObj . setLayout ( appLayout ) # Now that we have decided to install this mini applet, keep a # reference to it and set the mini applet flag in the # applet. This flag is necessary for some methods to separate # conventional applets from mini applets. appletObj . _qteAdmin . isMiniApplet = True self . _qteMiniApplet = appletObj # Shorthands. app = self . _qteActiveApplet appWin = self . qteActiveWindow ( ) # Remember which window and applet spawned this mini applet. self . _qteMiniApplet . _qteCallingApplet = app self . _qteMiniApplet . _qteCallingWindow = appWin del app # Add the mini applet to the applet registry, ie. for most # purposes the mini applet is treated like any other applet. self . _qteAppletList . insert ( 0 , self . _qteMiniApplet ) # Add the mini applet to the respective splitter in the window # layout and show it. appWin . qteLayoutSplitter . addWidget ( self . _qteMiniApplet ) self . _qteMiniApplet . show ( True ) # Give focus to first focusable widget in the mini applet # applet (if one exists) wid = self . _qteMiniApplet . qteNextWidget ( numSkip = 0 ) self . _qteMiniApplet . qteMakeWidgetActive ( wid ) self . qteMakeAppletActive ( self . _qteMiniApplet ) # Mini applet was successfully installed. return True | Install appletObj as the mini applet in the window layout . | 503 | 14 |
7,732 | def qteKillMiniApplet ( self ) : # Sanity check: is the handle valid? if self . _qteMiniApplet is None : return # Sanity check: is it really a mini applet? 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 : # Something is wrong because the mini applet is not part # of the applet list. msg = 'Custom mini applet not in applet list --> Bug.' self . qteLogger . warning ( msg ) else : # Inform the mini applet that it is about to be killed. try : self . _qteMiniApplet . qteToBeKilled ( ) except Exception : msg = 'qteToBeKilledRoutine is faulty' self . qteLogger . exception ( msg , exc_info = True , stack_info = True ) # Shorthands to calling window. win = self . _qteMiniApplet . _qteCallingWindow # We need to move the focus from the mini applet back to a # regular applet. Therefore, first look for the next # visible applet in the current window (ie. the last one # that was made active). app = self . qteNextApplet ( windowObj = win ) if app is not None : # Found another (visible or invisible) applet --> make # it active/visible. self . qteMakeAppletActive ( app ) else : # No visible applet available in this window --> look # for an invisible one. app = self . qteNextApplet ( skipInvisible = False , skipVisible = True ) if app is not None : # Found an invisible applet --> make it # active/visible. self . qteMakeAppletActive ( app ) else : # There is no other visible applet in this window. # The focus manager will therefore make a new applet # active. self . _qteActiveApplet = None self . _qteAppletList . remove ( self . _qteMiniApplet ) # Close the mini applet applet and schedule it for deletion. self . _qteMiniApplet . close ( ) self . _qteMiniApplet . deleteLater ( ) # Clear the handle to the mini applet. self . _qteMiniApplet = None | Remove the mini applet . | 551 | 6 |
7,733 | def _qteFindAppletInSplitter ( self , appletObj : QtmacsApplet , split : QtmacsSplitter ) : def splitterIter ( split ) : """ Iterator over all QtmacsSplitters. """ for idx in range ( split . count ( ) ) : subSplitter = split . widget ( idx ) subID = subSplitter . _qteAdmin . widgetSignature if subID == '__QtmacsLayoutSplitter__' : yield from splitterIter ( subSplitter ) yield split # Traverse all QtmacsSplitter until ``appletObj`` was found. for curSplit in splitterIter ( split ) : if appletObj in curSplit . children ( ) : return curSplit # No splitter holds ``appletObj``. return None | Return the splitter that holds appletObj . | 175 | 10 |
7,734 | def qteReplaceAppletInLayout ( self , newApplet : ( QtmacsApplet , str ) , oldApplet : ( QtmacsApplet , str ) = None , windowObj : QtmacsWindow = None ) : # If ``oldAppObj`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``oldAppObj`` is already an instance of ``QtmacsApplet`` # then use it directly. if isinstance ( oldApplet , str ) : oldAppObj = self . qteGetAppletHandle ( oldApplet ) else : oldAppObj = oldApplet # If ``newAppObj`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``newAppObj`` is already an instance of ``QtmacsApplet`` # then use it directly. if isinstance ( newApplet , str ) : newAppObj = self . qteGetAppletHandle ( newApplet ) else : newAppObj = newApplet # Use the currently active window if none was specified. 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 the main splitter contains no applet then just add newAppObj. if windowObj . qteAppletSplitter . count ( ) == 0 : windowObj . qteAppletSplitter . qteAddWidget ( newAppObj ) return # If no oldAppObj was specified use the currently active one # instead. Do not use qteActiveApplet to determine it, though, # because it may point to a mini buffer. If it is, then we # need the last active Qtmacs applet. In either case, the # qteNextApplet method will take care of these distinctions. if oldAppObj is None : oldAppObj = self . qteNextApplet ( numSkip = 0 , windowObj = windowObj ) # Sanity check: the applet to replace must exist. if oldAppObj is None : msg = 'Applet to replace does not exist.' self . qteLogger . error ( msg , stack_info = True ) return # Sanity check: do nothing if the old- and new applet are the # same. if newAppObj is oldAppObj : return # Sanity check: do nothing if both applets are already # visible. if oldAppObj . qteIsVisible ( ) and newAppObj . qteIsVisible ( ) : return # Search for the splitter that contains 'oldAppObj'. 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 # Determine the position of oldAppObj inside the splitter. oldAppIdx = split . indexOf ( oldAppObj ) # Replace oldAppObj with newAppObj but maintain the widget sizes. To do # so, first insert newAppObj into the splitter at the position of # oldAppObj. Afterwards, remove oldAppObj by re-parenting it, make # it invisible, and restore the widget sizes. sizes = split . sizes ( ) split . qteInsertWidget ( oldAppIdx , newAppObj ) oldAppObj . hide ( True ) split . setSizes ( sizes ) | Replace oldApplet with newApplet in the window layout . | 814 | 14 |
7,735 | def qteKillApplet ( self , appletID : str ) : # Compile list of all applet IDs. ID_list = [ _ . qteAppletID ( ) for _ in self . _qteAppletList ] if appletID not in ID_list : # Do nothing if the applet does not exist. return else : # Get a reference to the actual applet object based on the # name. idx = ID_list . index ( appletID ) appObj = self . _qteAppletList [ idx ] # Mini applets are killed with a special method. if self . qteIsMiniApplet ( appObj ) : self . qteKillMiniApplet ( ) return # Inform the applet that it is about to be killed. appObj . qteToBeKilled ( ) # Determine the window of the applet. window = appObj . qteParentWindow ( ) # Get the previous invisible applet (*may* come in handy a few # lines below). newApplet = self . qteNextApplet ( numSkip = - 1 , skipInvisible = False , skipVisible = True ) # If there is no invisible applet available, or the only available # applet is the one to be killed, then set newApplet to None. if ( newApplet is None ) or ( newApplet is appObj ) : newApplet = None else : self . qteReplaceAppletInLayout ( newApplet , appObj , window ) # Ensure that _qteActiveApplet does not point to the applet # to be killed as it will otherwise result in a dangling # pointer. if self . _qteActiveApplet is appObj : self . _qteActiveApplet = newApplet # Remove the applet object from the applet list. self . qteLogger . debug ( 'Kill applet: <b>{}</b>' . format ( appletID ) ) self . _qteAppletList . remove ( appObj ) # Close the applet and schedule it for destruction. Explicitly # call the sip.delete() method to ensure that all signals are # *immediately* disconnected, as otherwise there is a good # chance that Qtmacs segfaults if Python/Qt thinks the slots # are still connected when really the object does not exist # anymore. appObj . close ( ) sip . delete ( appObj ) | Destroy the applet with ID appletID . | 525 | 10 |
7,736 | def qteRunHook ( self , hookName : str , msgObj : QtmacsMessage = None ) : # Shorthand. reg = self . _qteRegistryHooks # Do nothing if there are not recipients for the hook. if hookName not in reg : return # Create an empty ``QtmacsMessage`` object if none was provided. if msgObj is None : msgObj = QtmacsMessage ( ) # Add information about the hook that will deliver ``msgObj``. msgObj . setHookName ( hookName ) # Try to call each slot. Intercept any errors but ensure that # really all slots are called, irrespective of how many of them # raise an error during execution. for fun in reg [ hookName ] : try : fun ( msgObj ) except Exception as err : # Format the error message. 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 ) # Log the error. self . qteLogger . exception ( msg , exc_info = True , stack_info = True ) | Trigger the hook named hookName and pass on msgObj . | 279 | 12 |
7,737 | def qteConnectHook ( self , hookName : str , slot : ( types . FunctionType , types . MethodType ) ) : # Shorthand. reg = self . _qteRegistryHooks if hookName in reg : reg [ hookName ] . append ( slot ) else : reg [ hookName ] = [ slot ] | Connect the method or function slot to hookName . | 72 | 10 |
7,738 | def qteDisconnectHook ( self , hookName : str , slot : ( types . FunctionType , types . MethodType ) ) : # Shorthand. reg = self . _qteRegistryHooks # Return immediately if no hook with that name exists. if hookName not in reg : msg = 'There is no hook called <b>{}</b>.' self . qteLogger . info ( msg . format ( hookName ) ) return False # Return immediately if the ``slot`` is not connected to the hook. 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 # Remove ``slot`` from the list. reg [ hookName ] . remove ( slot ) # If the list is now empty, then remove it altogether. if len ( reg [ hookName ] ) == 0 : reg . pop ( hookName ) return True | Disconnect slot from hookName . | 234 | 7 |
7,739 | def qteImportModule ( self , fileName : str ) : # Split the absolute file name into the path- and file name. path , name = os . path . split ( fileName ) name , ext = os . path . splitext ( name ) # If the file name has a path prefix then search there, otherwise # search the default paths for Python. if path == '' : path = sys . path else : path = [ path ] # Try to locate the module. 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 to import the module. 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 : # According to the imp documentation the file pointer # should always be closed explicitly. if fp : fp . close ( ) | Import fileName at run - time . | 256 | 8 |
7,740 | def qteMacroNameMangling ( self , macroCls ) : # Replace camel bump as hyphenated lower case string. macroName = re . sub ( r"([A-Z])" , r'-\1' , macroCls . __name__ ) # If the first character of the class name was a # capital letter (likely) then the above substitution would have # resulted in a leading hyphen. Remove it. if macroName [ 0 ] == '-' : macroName = macroName [ 1 : ] # Return the lower case string. return macroName . lower ( ) | Convert the class name of a macro class to macro name . | 125 | 13 |
7,741 | def qteRegisterMacro ( self , macroCls , replaceMacro : bool = False , macroName : str = None ) : # Check type of input arguments. if not issubclass ( macroCls , QtmacsMacro ) : args = ( 'macroCls' , 'class QtmacsMacro' , inspect . stack ( ) [ 0 ] [ 3 ] ) raise QtmacsArgumentError ( * args ) # Try to instantiate the macro class. 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 # The three options to determine the macro name, in order of # precedence, are: passed to this function, specified in the # macro constructor, name mangled. if macroName is None : # No macro name was passed to the function. if macroObj . qteMacroName ( ) is None : # The macro has already named itself. macroName = self . qteMacroNameMangling ( macroCls ) else : # The macro name is inferred from the class name. macroName = macroObj . qteMacroName ( ) # Let the macro know under which name it is known inside Qtmacs. macroObj . _qteMacroName = macroName # Ensure the macro has applet signatures. if len ( macroObj . qteAppletSignature ( ) ) == 0 : msg = 'Macro <b>{}</b> has no applet signatures.' . format ( macroName ) self . qteLogger . error ( msg , stack_info = True ) return None # Ensure the macro has widget signatures. if len ( macroObj . qteWidgetSignature ( ) ) == 0 : msg = 'Macro <b>{}</b> has no widget signatures.' . format ( macroName ) self . qteLogger . error ( msg , stack_info = True ) return None # Flag to indicate that at least one new macro type was # registered. anyRegistered = False # Iterate over all applet signatures. for app_sig in macroObj . qteAppletSignature ( ) : # Iterate over all widget signatures. for wid_sig in macroObj . qteWidgetSignature ( ) : # Infer the macro name from the class name of the # passed macro object. macroNameInternal = ( macroName , app_sig , wid_sig ) # If a macro with this name already exists then either # replace it, or skip the registration process for the # new one. if macroNameInternal in self . _qteRegistryMacros : if replaceMacro : # Remove existing macro. 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 ) # Macro was not registered for this widget # signature. continue # Add macro object to the registry. self . _qteRegistryMacros [ macroNameInternal ] = macroObj msg = ( 'Macro <b>{}</b> successfully registered.' . format ( macroNameInternal ) ) self . qteLogger . info ( msg ) anyRegistered = True # Return the name of the macro, irrespective of whether or not # it is a newly created macro, or if the old macro was kept # (in case of a name conflict). return macroName | Register a macro . | 834 | 4 |
7,742 | def qteGetAllMacroNames ( self , widgetObj : QtGui . QWidget = None ) : # The keys of qteRegistryMacros are (macroObj, app_sig, # wid_sig) tuples. Get them, extract the macro names, and # remove all duplicates. macro_list = tuple ( self . _qteRegistryMacros . keys ( ) ) macro_list = [ _ [ 0 ] for _ in macro_list ] macro_list = tuple ( set ( macro_list ) ) # If no widget object was supplied then omit the signature # check and return the macro list verbatim. if widgetObj is None : return macro_list else : # Use qteGetMacroObject to compile a list of macros that # are compatible with widgetObj. This list contains # (macroObj, macroName, app_sig, wid_sig) tuples. macro_list = [ self . qteGetMacroObject ( macroName , widgetObj ) for macroName in macro_list ] # Remove all elements where macroObj=None. This is the # case if no compatible macro with the specified name # could be found for widgetObj. macro_list = [ _ . qteMacroName ( ) for _ in macro_list if _ is not None ] return macro_list | Return all macro names known to Qtmacs as a list . | 288 | 13 |
7,743 | def qteBindKeyGlobal ( self , keysequence , macroName : str ) : # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsOtherError if the conversion is impossible. keysequence = QtmacsKeysequence ( keysequence ) # Sanity check: the macro must have been registered # beforehand. 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 # Insert/overwrite the key sequence and associate it with the # new macro. self . _qteGlobalKeyMap . qteInsertKey ( keysequence , macroName ) # Now update the local key map of every applet. Note that # globally bound macros apply to every applet (hence the loop # below) and every widget therein (hence the "*" parameter for # the widget signature). for app in self . _qteAppletList : self . qteBindKeyApplet ( keysequence , macroName , app ) return True | Associate macroName with keysequence in all current applets . | 253 | 13 |
7,744 | def qteBindKeyApplet ( self , keysequence , macroName : str , appletObj : QtmacsApplet ) : # Convert the key sequence into a QtmacsKeysequence object, or # raise a QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence ( keysequence ) # Verify that Qtmacs knows a macro named 'macroName'. 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 # Bind the key also to the applet itself because it can # receive keyboard events (eg. when it is empty). appletObj . _qteAdmin . keyMap . qteInsertKey ( keysequence , macroName ) # Update the key map of every widget inside the applet. for wid in appletObj . _qteAdmin . widgetList : self . qteBindKeyWidget ( keysequence , macroName , wid ) return True | Bind macroName to all widgets in appletObj . | 247 | 11 |
7,745 | def qteBindKeyWidget ( self , keysequence , macroName : str , widgetObj : QtGui . QWidget ) : # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence ( keysequence ) # Check type of input arguments. if not hasattr ( widgetObj , '_qteAdmin' ) : msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError ( msg ) # Verify that Qtmacs knows a macro named 'macroName'. 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 # Associate 'keysequence' with 'macroName' for 'widgetObj'. 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 . | 291 | 13 |
7,746 | def qteUnbindKeyApplet ( self , applet : ( QtmacsApplet , str ) , keysequence ) : # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance ( applet , str ) : appletObj = self . qteGetAppletHandle ( applet ) else : appletObj = applet # Return immediately if the appletObj is invalid. if appletObj is None : return # Convert the key sequence into a QtmacsKeysequence object, or # raise a QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence ( keysequence ) # Remove the key sequence from the applet window itself. appletObj . _qteAdmin . keyMap . qteRemoveKey ( keysequence ) for wid in appletObj . _qteAdmin . widgetList : self . qteUnbindKeyFromWidgetObject ( keysequence , wid ) | Remove keysequence bindings from all widgets inside applet . | 242 | 11 |
7,747 | def qteUnbindKeyFromWidgetObject ( self , keysequence , widgetObj : QtGui . QWidget ) : # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsKeysequenceError if the conversion is # impossible. keysequence = QtmacsKeysequence ( keysequence ) # Check type of input arguments. if not hasattr ( widgetObj , '_qteAdmin' ) : msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError ( msg ) # Remove the key sequence from the local key maps. widgetObj . _qteAdmin . keyMap . qteRemoveKey ( keysequence ) | Disassociate the macro triggered by keysequence from widgetObj . | 166 | 13 |
7,748 | def qteUnbindAllFromApplet ( self , applet : ( QtmacsApplet , str ) ) : # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance ( applet , str ) : appletObj = self . qteGetAppletHandle ( applet ) else : appletObj = applet # Return immediately if the appletObj is invalid. if appletObj is None : return # Remove the key sequence from the applet window itself. appletObj . _qteAdmin . keyMap = self . qteCopyGlobalKeyMap ( ) # Restore the global key-map for every widget. for wid in appletObj . _qteAdmin . widgetList : wid . _qteAdmin . keyMap = self . qteCopyGlobalKeyMap ( ) | Restore the global key - map for all widgets inside applet . | 214 | 14 |
7,749 | def qteUnbindAllFromWidgetObject ( self , widgetObj : QtGui . QWidget ) : # Check type of input arguments. if not hasattr ( widgetObj , '_qteAdmin' ) : msg = '<widgetObj> was probably not added with <qteAddWidget>' msg += ' method because it lacks the <_qteAdmin> attribute.' raise QtmacsOtherError ( msg ) # Install the global key-map for this widget. widgetObj . _qteAdmin . keyMap = self . qteCopyGlobalKeyMap ( ) | Reset the local key - map of widgetObj to the current global key - map . | 122 | 18 |
7,750 | def qteRegisterApplet ( self , cls , replaceApplet : bool = False ) : # Check type of input arguments. if not issubclass ( cls , QtmacsApplet ) : args = ( 'cls' , 'class QtmacsApplet' , inspect . stack ( ) [ 0 ] [ 3 ] ) raise QtmacsArgumentError ( * args ) # Extract the class name as string, because this is the name # under which the applet will be known. class_name = cls . __name__ # Issue a warning if an applet with this name already exists. 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 # Execute the classmethod __qteRegisterAppletInit__ to # allow the applet to make global initialisations that do # not depend on a particular instance, eg. the supported # file types. cls . __qteRegisterAppletInit__ ( ) # Add the class (not instance!) to the applet registry. self . _qteRegistryApplets [ class_name ] = cls self . qteLogger . info ( 'Applet <b>{}</b> now registered.' . format ( class_name ) ) return class_name | Register cls as an applet . | 339 | 8 |
7,751 | def qteGetAppletHandle ( self , appletID : str ) : # Compile list of applet Ids. id_list = [ _ . qteAppletID ( ) for _ in self . _qteAppletList ] # If one of the applets has ``appletID`` then return a # reference to it. if appletID in id_list : idx = id_list . index ( appletID ) return self . _qteAppletList [ idx ] else : return None | Return a handle to appletID . | 113 | 8 |
7,752 | def qteMakeAppletActive ( self , applet : ( QtmacsApplet , str ) ) : # If ``applet`` was specified by its ID (ie. a string) then # fetch the associated ``QtmacsApplet`` instance. If # ``applet`` is already an instance of ``QtmacsApplet`` then # use it directly. if isinstance ( applet , str ) : appletObj = self . qteGetAppletHandle ( applet ) else : appletObj = applet # Sanity check: return if the applet does not exist. if appletObj not in self . _qteAppletList : return False # If ``appletObj`` is a mini applet then double check that it # is actually installed and visible. If it is a conventional # applet then insert it into the layout. 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 ( ) : # Add the applet to the layout by replacing the # currently active applet. self . qteReplaceAppletInLayout ( appletObj ) # Update the qteActiveApplet pointer. Note that the actual # focusing is done exclusively in the focus manager. self . _qteActiveApplet = appletObj return True | Make applet visible and give it the focus . | 360 | 10 |
7,753 | def qteCloseQtmacs ( self ) : # Announce the shutdown. msgObj = QtmacsMessage ( ) msgObj . setSignalName ( 'qtesigCloseQtmacs' ) self . qtesigCloseQtmacs . emit ( msgObj ) # Kill all applets and update the GUI. for appName in self . qteGetAllAppletIDs ( ) : self . qteKillApplet ( appName ) self . _qteFocusManager ( ) # Kill all windows and update the GUI. for window in self . _qteWindowList : window . close ( ) self . _qteFocusManager ( ) # Schedule QtmacsMain for deletion. self . deleteLater ( ) | Close Qtmacs . | 153 | 5 |
7,754 | def qteDefVar ( self , varName : str , value , module = None , doc : str = None ) : # Use the global name space per default. if module is None : module = qte_global # Create the documentation dictionary if it does not exist # already. if not hasattr ( module , '_qte__variable__docstring__dictionary__' ) : module . _qte__variable__docstring__dictionary__ = { } # Set the variable value and documentation string. setattr ( module , varName , value ) module . _qte__variable__docstring__dictionary__ [ varName ] = doc return True | Define and document varName in an arbitrary name space . | 140 | 12 |
7,755 | def qteGetVariableDoc ( self , varName : str , module = None ) : # Use the global name space per default. if module is None : module = qte_global # No documentation for the variable can exists if the doc # string dictionary is undefined. if not hasattr ( module , '_qte__variable__docstring__dictionary__' ) : return None # If the variable is undefined then return **None**. if varName not in module . _qte__variable__docstring__dictionary__ : return None # Return the requested value. return module . _qte__variable__docstring__dictionary__ [ varName ] | Retrieve documentation for varName defined in module . | 140 | 10 |
7,756 | def qteEmulateKeypresses ( self , keysequence ) : # Convert the key sequence into a QtmacsKeysequence object, or # raise an QtmacsOtherError if the conversion is impossible. keysequence = QtmacsKeysequence ( keysequence ) key_list = keysequence . toQKeyEventList ( ) # Do nothing if the key list is empty. if len ( key_list ) > 0 : # Add the keys to the queue which the event timer will # process. for event in key_list : self . _qteKeyEmulationQueue . append ( event ) | Emulate the Qt key presses that define keysequence . | 126 | 11 |
7,757 | 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 . | 31 | 15 |
7,758 | 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 . | 56 | 7 |
7,759 | 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 ] } # Add the initial package itself. root = root . as_requirement ( ) dependencies [ root . name ] = root . installed_version # Retrieve information on additional packages such as build tools. 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 . | 188 | 9 |
7,760 | 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 . | 74 | 10 |
7,761 | 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 . | 74 | 8 |
7,762 | 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 | 95 | 11 |
7,763 | 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 | 105 | 21 |
7,764 | 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 . | 64 | 20 |
7,765 | 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 | 64 | 4 |
7,766 | 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 | 136 | 8 |
7,767 | 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 """ continue to run queries as long as we - don't exceed the call call_count - don't see results that are less than the limited length (the end) """ while call_count != max_calls and len ( result_set ) >= limit_to : record_index += len ( result_set ) # should be `limit_to` 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 | 422 | 14 |
7,768 | 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 | 89 | 5 |
7,769 | 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 | 41 | 7 |
7,770 | 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 : # don't make modifications for info 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 | 371 | 6 |
7,771 | def projectname ( self ) : if self . _projectname is None : exps = self . config . experiments if self . _experiment is not None and self . _experiment in exps : return exps [ self . _experiment ] [ 'project' ] try : self . _projectname = list ( self . config . projects . keys ( ) ) [ - 1 ] except IndexError : # no project has yet been created ever raise ValueError ( "No experiment has yet been created! Please run setup " "before." ) return self . _projectname | The name of the project that is currently processed | 120 | 9 |
7,772 | def experiment ( self ) : if self . _experiment is None : self . _experiment = list ( self . config . experiments . keys ( ) ) [ - 1 ] return self . _experiment | The identifier or the experiment that is currently processed | 43 | 9 |
7,773 | def app_main ( self , experiment = None , last = False , new = False , verbose = False , verbosity_level = None , no_modification = False , match = False ) : if match : patt = re . compile ( experiment ) matches = list ( filter ( patt . search , self . config . experiments ) ) if len ( matches ) > 1 : raise ValueError ( "Found multiple matches for %s: %s" % ( experiment , matches ) ) elif len ( matches ) == 0 : raise ValueError ( "No experiment matches %s" % experiment ) experiment = matches [ 0 ] if last and self . config . experiments : self . experiment = None elif new and self . config . experiments : try : self . experiment = utils . get_next_name ( self . experiment ) except ValueError : raise ValueError ( "Could not estimate an experiment id! Please use the " "experiment argument to provide an id." ) else : self . _experiment = experiment if verbose : verbose = logging . DEBUG elif verbosity_level : if verbosity_level in [ 'DEBUG' , 'INFO' , 'WARNING' , 'ERROR' ] : verbose = getattr ( logging , verbosity_level ) else : verbose = int ( verbosity_level ) if verbose : logging . getLogger ( utils . get_toplevel_module ( inspect . getmodule ( self ) ) ) . setLevel ( verbose ) self . logger . setLevel ( verbose ) self . no_modification = no_modification | The main function for parsing global arguments | 338 | 7 |
7,774 | def setup ( self , root_dir , projectname = None , link = False , * * kwargs ) : projects = self . config . projects if not projects and projectname is None : projectname = self . name + '0' elif projectname is None : # try to increment a number in the last used try : projectname = utils . get_next_name ( self . projectname ) except ValueError : raise ValueError ( "Could not estimate a project name! Please use the " "projectname argument to provide a project name." ) self . app_main ( * * kwargs ) root_dir = osp . abspath ( osp . join ( root_dir , projectname ) ) projects [ projectname ] = OrderedDict ( [ ( 'name' , projectname ) , ( 'root' , root_dir ) , ( 'timestamps' , OrderedDict ( ) ) ] ) data_dir = self . config . global_config . get ( 'data' , osp . join ( root_dir , 'data' ) ) projects [ projectname ] [ 'data' ] = data_dir self . projectname = projectname self . logger . info ( "Initializing project %s" , projectname ) self . logger . debug ( " Creating root directory %s" , root_dir ) if not osp . exists ( root_dir ) : os . makedirs ( root_dir ) return root_dir | Perform the initial setup for the project | 314 | 8 |
7,775 | def init ( self , projectname = None , description = None , * * kwargs ) : self . app_main ( * * kwargs ) experiments = self . config . experiments experiment = self . _experiment if experiment is None and not experiments : experiment = self . name + '_exp0' elif experiment is None : try : experiment = utils . get_next_name ( self . experiment ) except ValueError : raise ValueError ( "Could not estimate an experiment id! Please use the " "experiment argument to provide an id." ) self . experiment = experiment if self . is_archived ( experiment ) : raise ValueError ( "The specified experiment has already been archived! Run " "``%s -id %s unarchive`` first" % ( self . name , experiment ) ) if projectname is None : projectname = self . projectname else : self . projectname = projectname self . logger . info ( "Initializing experiment %s of project %s" , experiment , projectname ) exp_dict = experiments . setdefault ( experiment , OrderedDict ( ) ) if description is not None : exp_dict [ 'description' ] = description exp_dict [ 'project' ] = projectname exp_dict [ 'expdir' ] = exp_dir = osp . join ( 'experiments' , experiment ) exp_dir = osp . join ( self . config . projects [ projectname ] [ 'root' ] , exp_dir ) exp_dict [ 'timestamps' ] = OrderedDict ( ) if not os . path . exists ( exp_dir ) : self . logger . debug ( " Creating experiment directory %s" , exp_dir ) os . makedirs ( exp_dir ) self . fix_paths ( exp_dict ) return exp_dict | Initialize a new experiment | 389 | 5 |
7,776 | def get_value ( self , keys , exp_path = False , project_path = False , complete = False , on_projects = False , on_globals = False , projectname = None , no_fix = False , only_keys = False , base = '' , return_list = False , archives = False , * * kwargs ) : def pretty_print ( val ) : if isinstance ( val , dict ) : if only_keys : val = list ( val . keys ( ) ) return ordered_yaml_dump ( val , default_flow_style = False ) . rstrip ( ) return str ( val ) config = self . info ( exp_path = exp_path , project_path = project_path , complete = complete , on_projects = on_projects , on_globals = on_globals , projectname = projectname , no_fix = no_fix , return_dict = True , insert_id = False , archives = archives , * * kwargs ) ret = [ 0 ] * len ( keys ) for i , key in enumerate ( keys ) : if base : key = base + key key , sub_config = utils . go_through_dict ( key , config ) ret [ i ] = sub_config [ key ] if return_list : return ret return ( self . print_ or six . print_ ) ( '\n' . join ( map ( pretty_print , ret ) ) ) | Get one or more values in the configuration | 315 | 8 |
7,777 | def del_value ( self , keys , complete = False , on_projects = False , on_globals = False , projectname = None , base = '' , dtype = None , * * kwargs ) : config = self . info ( complete = complete , on_projects = on_projects , on_globals = on_globals , projectname = projectname , return_dict = True , insert_id = False , * * kwargs ) for key in keys : if base : key = base + key key , sub_config = utils . go_through_dict ( key , config ) del sub_config [ key ] | Delete a value in the configuration | 141 | 6 |
7,778 | def configure ( self , global_config = False , project_config = False , ifile = None , forcing = None , serial = False , nprocs = None , update_from = None , * * kwargs ) : if global_config : d = self . config . global_config elif project_config : self . app_main ( * * kwargs ) d = self . config . projects [ self . projectname ] else : d = self . config . experiments [ self . experiment ] if ifile is not None : d [ 'input' ] = osp . abspath ( ifile ) if forcing is not None : d [ 'forcing' ] = osp . abspath ( forcing ) if update_from is not None : with open ( 'update_from' ) as f : d . update ( yaml . load ( f ) ) global_config = self . config . global_config if serial : global_config [ 'serial' ] = True elif nprocs : nprocs = int ( nprocs ) if nprocs != 'all' else nprocs global_config [ 'serial' ] = False global_config [ 'nprocs' ] = nprocs | Configure the project and experiments | 260 | 6 |
7,779 | def set_value ( self , items , complete = False , on_projects = False , on_globals = False , projectname = None , base = '' , dtype = None , * * kwargs ) : def identity ( val ) : return val config = self . info ( complete = complete , on_projects = on_projects , on_globals = on_globals , projectname = projectname , return_dict = True , insert_id = False , * * kwargs ) if isinstance ( dtype , six . string_types ) : dtype = getattr ( builtins , dtype ) elif dtype is None : dtype = identity for key , value in six . iteritems ( dict ( items ) ) : if base : key = base + key key , sub_config = utils . go_through_dict ( key , config , setdefault = OrderedDict ) if key in self . paths : if isinstance ( value , six . string_types ) : value = osp . abspath ( value ) else : value = list ( map ( osp . abspath , value ) ) sub_config [ key ] = dtype ( value ) | Set a value in the configuration | 257 | 6 |
7,780 | def rel_paths ( self , * args , * * kwargs ) : return self . config . experiments . rel_paths ( * args , * * kwargs ) | Fix the paths in the given dictionary to get relative paths | 39 | 11 |
7,781 | def abspath ( self , path , project = None , root = None ) : if root is None : root = self . config . projects [ project or self . projectname ] [ 'root' ] return osp . join ( root , path ) | Returns the path from the current working directory | 52 | 8 |
7,782 | def relpath ( self , path , project = None , root = None ) : if root is None : root = self . config . projects [ project or self . projectname ] [ 'root' ] return osp . relpath ( path , root ) | Returns the relative path from the root directory of the project | 53 | 11 |
7,783 | def setup_parser ( self , parser = None , subparsers = None ) : commands = self . commands [ : ] parser_cmds = self . parser_commands . copy ( ) if subparsers is None : if parser is None : parser = FuncArgParser ( self . name ) subparsers = parser . add_subparsers ( chain = True ) ret = { } for i , cmd in enumerate ( commands [ : ] ) : func = getattr ( self , cmd ) parser_cmd = parser_cmds . setdefault ( cmd , cmd . replace ( '_' , '-' ) ) ret [ cmd ] = sp = parser . setup_subparser ( func , name = parser_cmd , return_parser = True ) sp . setup_args ( func ) modifier = getattr ( self , '_modify_' + cmd , None ) if modifier is not None : modifier ( sp ) self . parser_commands = parser_cmds parser . setup_args ( self . app_main ) self . _modify_app_main ( parser ) self . parser = parser self . subparsers = ret return parser , subparsers , ret | Create the argument parser for this instance | 253 | 7 |
7,784 | def get_parser ( cls ) : organizer = cls ( ) organizer . setup_parser ( ) organizer . _finish_parser ( ) return organizer . parser | Function returning the command line parser for this class | 35 | 9 |
7,785 | def is_archived ( self , experiment , ignore_missing = True ) : if ignore_missing : if isinstance ( self . config . experiments . get ( experiment , True ) , Archive ) : return self . config . experiments . get ( experiment , True ) else : if isinstance ( self . config . experiments [ experiment ] , Archive ) : return self . config . experiments [ experiment ] | Convenience function to determine whether the given experiment has been archived already | 82 | 14 |
7,786 | def _archive_extensions ( ) : if six . PY3 : ext_map = { } fmt_map = { } for key , exts , desc in shutil . get_unpack_formats ( ) : fmt_map [ key ] = exts [ 0 ] for ext in exts : ext_map [ ext ] = key else : ext_map = { '.tar' : 'tar' , '.tar.bz2' : 'bztar' , '.tar.gz' : 'gztar' , '.tar.xz' : 'xztar' , '.tbz2' : 'bztar' , '.tgz' : 'gztar' , '.txz' : 'xztar' , '.zip' : 'zip' } fmt_map = { 'bztar' : '.tar.bz2' , 'gztar' : '.tar.gz' , 'tar' : '.tar' , 'xztar' : '.tar.xz' , 'zip' : '.zip' } return ext_map , fmt_map | Create translations from file extension to archive format | 237 | 8 |
7,787 | def loadFile ( self , fileName ) : # Test if the file exists. if not QtCore . QFile ( fileName ) . exists ( ) : msg = "File <b>{}</b> does not exist" . format ( self . qteAppletID ( ) ) self . qteLogger . info ( msg ) self . fileName = None return # Store the file name and load the PDF document with the # Poppler library. self . fileName = fileName doc = popplerqt4 . Poppler . Document . load ( fileName ) # Enable antialiasing to improve the readability of the fonts. doc . setRenderHint ( popplerqt4 . Poppler . Document . Antialiasing ) doc . setRenderHint ( popplerqt4 . Poppler . Document . TextAntialiasing ) # Convert each page to an image, then install that image as the # pixmap of a QLabel, and finally insert that QLabel into a # vertical layout. hbox = QtGui . QVBoxLayout ( ) for ii in range ( doc . numPages ( ) ) : pdf_img = doc . page ( ii ) . renderToImage ( ) pdf_label = self . qteAddWidget ( QtGui . QLabel ( ) ) pdf_label . setPixmap ( QtGui . QPixmap . fromImage ( pdf_img ) ) hbox . addWidget ( pdf_label ) # Use an auxiliary widget to hold that layout and then place # that auxiliary widget into a QScrollView. The auxiliary # widget is necessary because QScrollArea can only display a # single widget at once. tmp = self . qteAddWidget ( QtGui . QWidget ( self ) ) tmp . setLayout ( hbox ) self . qteScroll . setWidget ( tmp ) | Load and display the PDF file specified by fileName . | 401 | 11 |
7,788 | def get_product ( membersuite_id , client = None ) : if not membersuite_id : return None client = client or get_new_client ( request_session = True ) object_query = "SELECT Object() FROM PRODUCT WHERE ID = '{}'" . format ( membersuite_id ) result = client . execute_object_query ( object_query ) msql_result = result [ "body" ] [ "ExecuteMSQLResult" ] if msql_result [ "Success" ] : membersuite_object_data = ( msql_result [ "ResultValue" ] [ "SingleObject" ] ) else : raise ExecuteMSQLError ( result = result ) return Product ( membersuite_object_data = membersuite_object_data ) | Return a Product object by ID . | 173 | 7 |
7,789 | def __watchers_callbacks_exec ( self , signal_name ) : def callback_fn ( ) : for watcher in self . __watchers_callbacks [ signal_name ] : if watcher is not None : watcher . notify ( ) return callback_fn | Generate callback for a queue | 59 | 6 |
7,790 | def py_doc_trim ( docstring ) : if not docstring : return '' # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring . expandtabs ( ) . splitlines ( ) # Determine minimum indentation (first line doesn't count): indent = sys . maxint for line in lines [ 1 : ] : stripped = line . lstrip ( ) if stripped : indent = min ( indent , len ( line ) - len ( stripped ) ) # Remove indentation (first line is special): trimmed = [ lines [ 0 ] . strip ( ) ] if indent < sys . maxint : for line in lines [ 1 : ] : trimmed . append ( line [ indent : ] . rstrip ( ) ) # Strip off trailing and leading blank lines: while trimmed and not trimmed [ - 1 ] : trimmed . pop ( ) while trimmed and not trimmed [ 0 ] : trimmed . pop ( 0 ) # The single string returned by the original function joined = '\n' . join ( trimmed ) # Return a version that replaces single newlines with spaces return newline_substitution_regex . sub ( " " , joined ) | Trim a python doc string . | 253 | 7 |
7,791 | def _fix_up_fields ( cls ) : cls . _fields = { } if cls . __module__ == __name__ and cls . __name__ != 'DebugResource' : return for name in set ( dir ( cls ) ) : attr = getattr ( cls , name , None ) if isinstance ( attr , BaseField ) : if name . startswith ( '_' ) : raise TypeError ( "Resource field %s cannot begin with an " "underscore. Underscore attributes are reserved " "for instance variables that aren't intended to " "propagate out to the HTTP caller." % name ) attr . _fix_up ( cls , name ) cls . _fields [ attr . name ] = attr if cls . _default_fields is None : cls . _default_fields = tuple ( cls . _fields . keys ( ) ) | Add names to all of the Resource fields . | 198 | 9 |
7,792 | def _render_serializable ( self , obj , context ) : logging . info ( """Careful, you're calling ._render_serializable on the base resource, which is probably not what you actually want to be doing!""" ) if obj is None : logging . debug ( "_render_serializable passed a None obj, returning None" ) return None output = { } if self . _fields_to_render is None : return output for field in self . _fields_to_render : renderer = self . _fields [ field ] . render output [ field ] = renderer ( obj , field , context ) return output | Renders a JSON - serializable version of the object passed in . Usually this means turning a Python object into a dict but sometimes it might make sense to render a list or a string or a tuple . | 132 | 41 |
7,793 | def _render_serializable ( self , list_of_objs , context ) : output = [ ] for obj in list_of_objs : if obj is not None : item = self . _item_resource . _render_serializable ( obj , context ) output . append ( item ) return output | Iterates through the passed in list_of_objs and calls the _render_serializable method of each object s Resource type . | 66 | 28 |
7,794 | def critical_section_dynamic_lock ( lock_fn , blocking = True , timeout = None , raise_exception = True ) : if blocking is False or timeout is None : timeout = - 1 def first_level_decorator ( decorated_function ) : def second_level_decorator ( original_function , * args , * * kwargs ) : lock = lock_fn ( * args , * * kwargs ) if lock . acquire ( blocking = blocking , timeout = timeout ) is True : try : result = original_function ( * args , * * kwargs ) return result finally : lock . release ( ) elif raise_exception is True : raise WCriticalSectionError ( 'Unable to lock critical section\n' ) return decorator ( second_level_decorator ) ( decorated_function ) return first_level_decorator | Protect a function with a lock that was get from the specified function . If a lock can not be acquire then no function call will be made | 188 | 28 |
7,795 | def generate_json_docs ( module , pretty_print = False , user = None ) : indent = None separators = ( ',' , ':' ) if pretty_print : indent = 4 separators = ( ',' , ': ' ) module_doc_dict = generate_doc_dict ( module , user ) json_str = json . dumps ( module_doc_dict , indent = indent , separators = separators ) return json_str | Return a JSON string format of a Pale module s documentation . | 96 | 12 |
7,796 | def generate_raml_docs ( module , fields , shared_types , user = None , title = "My API" , version = "v1" , api_root = "api" , base_uri = "http://mysite.com/{version}" ) : output = StringIO ( ) # Add the RAML header info output . write ( '#%RAML 1.0 \n' ) output . write ( 'title: ' + title + ' \n' ) output . write ( 'baseUri: ' + base_uri + ' \n' ) output . write ( 'version: ' + version + '\n' ) output . write ( 'mediaType: application/json\n\n' ) output . write ( 'documentation:\n' ) output . write ( ' - title: Welcome\n' ) output . write ( ' content: |\n' ) output . write ( """\ Welcome to the Loudr API Docs.\n You'll find comprehensive documentation on our endpoints and resources here. """ ) output . write ( "\n###############\n# Resource Types:\n###############\n\n" ) output . write ( 'types:\n' ) basic_fields = [ ] for field_module in inspect . getmembers ( fields , inspect . ismodule ) : for field_class in inspect . getmembers ( field_module [ 1 ] , inspect . isclass ) : basic_fields . append ( field_class [ 1 ] ) pale_basic_types = generate_basic_type_docs ( basic_fields , { } ) output . write ( "\n# Pale Basic Types:\n\n" ) output . write ( pale_basic_types [ 0 ] ) shared_fields = [ ] for shared_type in shared_types : for field_class in inspect . getmembers ( shared_type , inspect . isclass ) : shared_fields . append ( field_class [ 1 ] ) pale_shared_types = generate_basic_type_docs ( shared_fields , pale_basic_types [ 1 ] ) output . write ( "\n# Pale Shared Types:\n\n" ) output . write ( pale_shared_types [ 0 ] ) raml_resource_types = generate_raml_resource_types ( module ) output . write ( "\n# API Resource Types:\n\n" ) output . write ( raml_resource_types ) raml_resources = generate_raml_resources ( module , api_root , user ) output . write ( "\n\n###############\n# API Endpoints:\n###############\n\n" ) output . write ( raml_resources ) raml_docs = output . getvalue ( ) output . close ( ) return raml_docs | Return a RAML file of a Pale module s documentation as a string . | 597 | 15 |
7,797 | def generate_doc_dict ( module , user ) : from pale import extract_endpoints , extract_resources , is_pale_module if not is_pale_module ( module ) : raise ValueError ( """The passed in `module` (%s) is not a pale module. `paledoc` only works on modules with a `_module_type` set to equal `pale.ImplementationModule`.""" ) module_endpoints = extract_endpoints ( module ) ep_doc = { ep . _route_name : document_endpoint ( ep ) for ep in module_endpoints } ep_doc_filtered = { } for endpoint in ep_doc : # check if user has permission to view this endpoint # this is currently an on/off switch: if any endpoint has a "@requires_permission" # decorator, user.is_admin must be True for the user to see documentation # @TODO - make this permission more granular if necessary if ep_doc [ endpoint ] . get ( "requires_permission" ) != None and user != None and user . is_admin or ep_doc [ endpoint ] . get ( "requires_permission" ) == None : ep_doc_filtered [ endpoint ] = ep_doc [ endpoint ] module_resources = extract_resources ( module ) res_doc = { r . _value_type : document_resource ( r ) for r in module_resources } return { 'endpoints' : ep_doc_filtered , 'resources' : res_doc } | Compile a Pale module s documentation into a python dictionary . | 333 | 12 |
7,798 | def document_endpoint ( endpoint ) : descr = clean_description ( py_doc_trim ( endpoint . __doc__ ) ) docs = { 'name' : endpoint . _route_name , 'http_method' : endpoint . _http_method , 'uri' : endpoint . _uri , 'description' : descr , 'arguments' : extract_endpoint_arguments ( endpoint ) , 'returns' : format_endpoint_returns_doc ( endpoint ) , } if hasattr ( endpoint , "_success" ) : docs [ "success" ] = endpoint . _success if hasattr ( endpoint , "_requires_permission" ) : docs [ "requires_permission" ] = endpoint . _requires_permission return docs | Extract the full documentation dictionary from the endpoint . | 163 | 10 |
7,799 | def extract_endpoint_arguments ( endpoint ) : ep_args = endpoint . _arguments if ep_args is None : return None arg_docs = { k : format_endpoint_argument_doc ( a ) for k , a in ep_args . iteritems ( ) } return arg_docs | Extract the argument documentation from the endpoint . | 66 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.