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... | 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 = Fal... | 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 . _wasUnd... | 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 ( ... | 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, # hen... | 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 ... | 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 ( ) - ... | 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 reall... | 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 ca... | 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... | 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:... | 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 winI... | 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 . activate... | 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 ( ) : re... | 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 = ... | 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... | 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... | 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 . ... | 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 # au... | 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 ( m... | 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 == '__QtmacsLayoutS... | 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 ``Qtmac... | 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 ... | 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 ( ) # ... | 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 ( hookNam... | 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 == '' : pa... | 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... | 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 ma... | 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 ] macr... | 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 . qteI... | 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 'macroNam... | 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 hasatt... | 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 = ... | 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 ( wi... | 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 . qte... | 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... | 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 # ... | 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 ] els... | 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 . qteGet... | 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 ( ) #... | 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... | 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 Non... | 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_l... | 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 ] } # ... | 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 . urlope... | 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 , l... | 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... | 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 , Namespac... | 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 pro... | 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 ... | 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 . projec... | 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... | 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... | 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... | 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 . pro... | 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 , ret... | 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 ( c... | 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 ... | 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... | 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 libra... | 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 [ "... | 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 : ] : st... | 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 wit... | 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 = { ... | 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 , * * kw... | 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 ... | 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 ( 'b... | 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`.""" ... | 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... | 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.