def searchForPassphrase():
    # Get the selected wallet from the main screen
    wlt = self.getSelectedWlt()
    if wlt and not wlt.watchingOnly and wlt.isLocked:
       self.resultStr = ''
       self.passPhraseFinder = PassPhraseFinder(wlt)
       self.resultsDisplay.setText(QString(''))
       self.main.extraHeartbeatAlways.append(updateDisplay)
       if len(self.segOrdStrSet) > 0:
          # From self.segOrdStrList, create a list of lists of indexes that describe the segment orderings to search
          # In other words convert all of the strings in orderings list to lists of integers
          segOrdIntListList = []
          for ordStr in self.segOrdStrSet:
             # The indexes provided by the users are 1 based, and the list indexes ought to be 0 based
             segOrdIntListList.append([int(indexStr)-1 for indexStr in ordStr.split(',')])
          self.searchThread = PyBackgroundThread(self.passPhraseFinder.searchForPassPhrase, 
             [segDef.getSegList() for segDef in self.segDefList], 
             segOrdIntListList, 
             updateResults,
             terminateSearch )
          # Reset the isSearchOver flag
          self.isSearchOver = False
          self.searchThread.start()
          
          # Disable search button adn enabled stop button
          self.stopButton.setEnabled(True)
          self.searchButton.setEnabled(False)
       else:
          QMessageBox.warning(self.main, tr('Invalid'), tr("""
             There are no valid segment combinations to search.
             Please add at least one segment and ordering to search."""), QMessageBox.Ok)
    else:
       QMessageBox.warning(self.main, tr('Invalid'), tr("""
          No valid wallet is selected. Please select a locked
          non-watching-only from Available Wallets."""), QMessageBox.Ok)
    def _assignPeptideSequence(self):
        """
        (private)
        Slot for the "editingFinished()" signal generated by the PM_TextEdit
        whenever the user presses the Enter key in the sequence text edit field.

        Assigns the amino acid sequence in the sequence editor text field to
        the current protein.

        @attention: this method is not implemented yet. If called, it will
        display a messagebox warning the user that this is not implement yet.
        """
        if not self.current_protein:
            return

        sequenceString = self.getPlainSequence()
        sequenceString = str(sequenceString)

        #assign sequence only if it not the same as the current sequence
        seq = self.current_protein.protein.get_sequence_string()

        if seq != sequenceString:
            #self.current_protein.setSequence(sequenceString)
            #self.updateSequence(cursorPos = self.getCursorPosition())
            msg = "We are sorry. You cannot change the sequence since "\
                "this feature is not yet supported."
            QMessageBox.warning(self.win, "Warning!", msg)
            self._suppress_textChanged_signal = False

        self.updateSequence(self.current_protein)
        return
 def canvasReleaseEvent(self, event):
     x = event.pos().x()
     y = event.pos().y()
     
     # TODO layer automatisch speichern damit das polygon eine id von der db kriegt
     
     # Ugly hack to identify the clicked element. For some reasons if InfoPointTool inherits from QgsMapToolIdentify,
     # canvasRealeaseEvent isn't called.
     tool = QgsMapToolIdentify(self.canvas)
     results = tool.identify(x,y, tool.ActiveLayer, tool.AllLayers)
     if not results:
         return
     
     guiName = self.canvas.currentLayer().name()
     dbName = self.canvas.currentLayer().dataProvider().dataSourceUri().split(' ')[0].split('=')[1].replace("'", '')
     
     result = results[0]
     
     feat = result.mFeature
     attrs = feat.attributes()
     fields = feat.fields().toList()
     fieldId = None
     
     for i, attr in enumerate(attrs):
         name = fields[i].name()
         if name == 'id' and attr is not None:
             fieldId = str(attr)
             break
     
     if fieldId is None:
         QMessageBox.warning(None, "Ungespeicherte Aenderungen", "Sie muessen das Polygon zuerst speichern")
         return
     
     DynamicGuiLoader(dbName, guiName, fieldId)
Exemple #4
0
 def _validate_create_filename(self, path=None, check=True):
     if path is None:
         path = str(self.wcreate.text())
     # if we have already validated this path, then return the last validation result.
     # This is mostly to keep from bombarding the user with repeated error dialogs.
     if self._validated_create_path == path:
         return self._validated_result
     self._validated_create_path = path
     self._validated_result = False;  # set to True if all checks pass
     # now process the path. Normalize it, and expand "~"
     path = os.path.expanduser(os.path.normpath(path))
     # if not absolute, join to current directory
     if not os.path.isabs(path):
         path = os.path.join(self.dirname, path)
     # collapse to "~" (for error messages)
     path0 = Kittens.utils.collapseuser(path)
     if os.path.exists(path):
         QMessageBox.warning(self, "Can't create purrlog",
                             """Unable to create purrlog <tt>%s</tt>: file or directory already exists. Please select another name""" % path0)
         self.create_path and self.wcreate.setText(Kittens.utils.collapseuser(self.create_path))
         return False
     if not os.access(os.path.dirname(os.path.normpath(path)) or '.', os.W_OK):
         QMessageBox.warning(self, "Can't create purrlog",
                             """Unable to create purrlog <tt>%s</tt>: can't write to parent directory. Please select another path.""" % path0)
         self.create_path and self.wcreate.setText(Kittens.utils.collapseuser(self.create_path))
         return False
     self.create_path = path
     self.wcreate.setText(path0)
     self._validated_result = True;  # set to True if all checks pass
     if check:
         self.checkCompleteness()
     return True
Exemple #5
0
 def showMessageDialog(self, msg_type, msg):
   
   print "showMessageDialog"
   
   # Warning
   if msg_type == 'w':
     print "warning"
     QMessageBox.warning(self, 
                         "Warning", 
                         msg, 
                         buttons=QMessageBox.Ok, 
                         defaultButton=QMessageBox.NoButton)
     
   # Information
   elif msg_type == 'i':
     print "information"
     QMessageBox.information(self, 
                             "Info", 
                             msg, 
                             buttons=QMessageBox.Ok, 
                             defaultButton=QMessageBox.NoButton)
     
   # Critical
   elif msg_type == 'c':
     print "critical"
     QMessageBox.critical(self, 
                          "Critical", 
                          msg, 
                          buttons=QMessageBox.Ok, 
                          defaultButton=QMessageBox.NoButton)
   
   # Nothing to do, the type is not correct
   else: 
     pass
 def give_error(self, message, clear_client = False):
     if not self.signing:
         QMessageBox.warning(QDialog(), _('Warning'), _(message), _('OK'))
     else:
         self.signing = False
     if clear_client:
         self.client.bad = True
     raise Exception(message)                
Exemple #7
0
 def configure(self):
     super(SDEPlugin, self).configure()
     while self.optimize_enabled and \
           self.maximum_kernel <= self.minimum_kernel:
         QMessageBox.warning(None, 'Unable to set parameters',
             'Maximum kernel size needs to be larger than ' +
             'minimum kernel size!')
         super(SDEPlugin, self).configure()
Exemple #8
0
 def give_error(self, message, clear_client=False):
     if not self.signing:
         QMessageBox.warning(QDialog(), _('Warning'), _(message), _('OK'))
     else:
         self.signing = False
     if clear_client and self.client is not None:
         self.client.bad = True
         self.device_checked = False
     raise Exception(message)
 def addToList(self):
     if self._rddtDataExtractor.currentlyDownloading:
         QMessageBox.warning(QMessageBox(), "Data Extractor for reddit",
                             "Cannot add while currently downloading. Please wait.")
         return
     model = self.model()
     if model is not None:
         model.insertRows(model.rowCount(), 1)
         self._gui.setUnsavedChanges(True)
 def addOrdering():
    if len(self.segDefList) > 0:
       dlgSpecifyOrdering = DlgSpecifyOrdering(main, main, len(self.segDefList))     
       if dlgSpecifyOrdering.exec_():
          self.segOrdStrSet.add(str(dlgSpecifyOrdering.parseOrderingList()).strip('[]'))
          self.updateOrderingListBox()
    else:
       QMessageBox.warning(self.main, tr('Not Ready'), tr("""
          No segments have been entered. You must enter some segments before you can order them."""), QMessageBox.Ok)
Exemple #11
0
 def give_error(self, message, clear_client = False):
     if not self.signing:
         QMessageBox.warning(QDialog(), _('Warning'), _(message), _('OK'))
     else:
         self.signing = False
     if clear_client and self.client is not None:
         self.client.bad = True
         self.device_checked = False
     raise Exception(message)                
def getTitleData(self, titleToGet):
    data = json.dumps({'command':'get_title', 'title':titleToGet}) 

    data = requests.post('http://shinowa.tk/lab6/add_book.php', data)

    if(data.status_code != 200):
        QMessageBox.warning(None, "Failure", "Connection failure")
        return "Empty"
    return data.json()[0]
def removeTitle(titleToRemove):
        data = json.dumps({'command':'remove_book', 
        'titleToRemove':titleToRemove}) 

        r = requests.post('http://shinowa.tk/lab6/add_book.php', data)
        print r.status_code
        if(r.status_code == 200):
            QMessageBox.warning(None, "Success", "Title removed successfully")
        elif(r.status_code == 404):
            QMessageBox.warning(None, "Failure", "Failed to remove title")
Exemple #14
0
 def addToList(self):
     if self._rddtDataExtractor.currentlyDownloading:
         QMessageBox.warning(
             QMessageBox(), "Data Extractor for reddit",
             "Cannot add while currently downloading. Please wait.")
         return
     model = self.model()
     if model is not None:
         model.insertRows(model.rowCount(), 1)
         self._gui.setUnsavedChanges(True)
 def _get_int(self, i, j):
     try:
         if not self._is_empty(i,j):
             int_val = int(float(self.two_by_two_table.item(i, j).text()))
             return int_val
     except:
         # Should never appear....
         msg = "Could not convert %s to integer" % self.two_by_two_table.item(i, j)
         QMessageBox.warning(self.parent(), "whoops", msg)
         raise Exception("Could not convert %s to int" % self.two_by_two_table.item(i, j))
Exemple #16
0
    def load_scenarios(self):

        if not self.project.load_tranus_folder(self.tranus_project):
            self.tranus_workspace.setText('')
            self.save_settings()
            QMessageBox.warning(None, "Invalid Tranus project",
                                "Please select a valid workspace")
            print "Invalid Tranus project , Please select a valid workspace"

        self.reload_scenarios()
        self.activate_launch_button()
 def deleteFromList(self):
     if self._rddtDataExtractor.currentlyDownloading:
         QMessageBox.warning(QMessageBox(), "Data Extractor for reddit",
                             "Cannot remove while currently downloading. Please wait.")
         return
     model = self.model()
     index = self.getCurrentSelectedIndex()
     if model is not None and index is not None:
         row = index.row()
         model.removeRows(row, 1)
         self._gui.setUnsavedChanges(True)
 def accept(self):
    orderingList = self.parseOrderingList() 
    if len(orderingList) < 1:
       QMessageBox.warning(self.main, tr('Invalid'), tr("""
          Some segment indices are invalid."""), QMessageBox.Ok)
       return
    for segIndex in orderingList:
       if segIndex > self.maxSeg or segIndex < 1:
          QMessageBox.warning(self.main, tr('Invalid'), tr("""
             Some segment indices are out of range."""), QMessageBox.Ok)
          return
    super(DlgSpecifyOrdering, self).accept()  
 def connect(self, HOST, PORT):        
     global sock
     try:
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sock.connect((HOST,PORT))
         sock.settimeout(10)
         self.setWindowTitle("Book Library (Connected)")
         self.dialog.hide()
     except:
         self.dialog.show()
         self.setWindowTitle("Book Library (Disconnected)")
         QMessageBox.warning(self, "Failure", "Connection failed")
Exemple #20
0
 def _select_other_dialog(self):
     path = str(QFileDialog.getExistingDirectory(self, "Select purrlog", self.dirname))
     if not path:
         return
     if not Purr.Purrer.is_purrlog(path):
         QMessageBox.warning(self, "Invalid purrlog",
                             "The path you have selected, <tt>%s</tt>, does not refer to a valid purrlog." % Kittens.utils.collapseuser(
                                 path))
         return
     self.load_path = path
     self.wother.setText(Kittens.utils.collapseuser(path))
     self.checkCompleteness()
def getTitleData(self, titleToGet):
    global sock
    try:
        command = "GET_TITLE_DATA "+titleToGet
        sock.send(command)
        data = sock.recv(1024)
        token = data.split(' ', 1)
        return token[1]
    except socket.timeout:
        QMessageBox.warning(self.parent(), "Failure", "Connection timed out...")
    except:
        QMessageBox.warning(self.parent(), "Failure", "Connect to the server before refreshing.")
        self.setWindowTitle("Book Library (Disconnected)")
 def disconnect(self):
     global sock
     
     try:
         sock.send("EXIT")
         data = sock.recv(1024)
         if data == "200 OK":
             sock.close()
             self.setWindowTitle('Book Library (Disconnected)')
             self.dialog.show()
     except:
         self.dialog.hide()
         QMessageBox.warning(self, "Error", "Failed to disconnect from server")
def importFromIOSFile(assy, fileName1):
    """
    Imports optimized sequences to NE-1 from IOS file
    @param assy: the NE1 assy.
    @type  assy: L{assembly}

    @param fileName1: IOS Import file
    @type fileName1: string
    @return: Returns True or False based on whether import was successful

    @note: Since DNA Strand Chunks do not get stored in the mmp file, there's no
           way, chunk by chunk info can be verified between the structure on the
           NE-1 window and that in the IOS file. The most that can be done is to
           verify the name of the strand Name info and their lengths. For instance
           if two NE-1 structures have the same name and number of strands,each
           of same length, but their pairing info is different, there's no way
           to check that and the sequences will get imported anyways. There IOS
           import happens at the user's risk.
    """

    strandsOnScreen = checkStrandsOnNE_1Window(assy)
    if strandsOnScreen == False:
        msg = "Cannot import since currently IOS import is supported only for DNA strands and there are no DNA strands on the screen. There is also no support for importing into clipboard."
        QMessageBox.warning(assy.win, "Warning!", msg)
        return False

    fileName2 = doInitialProcessingOnXMLFile(fileName1)
    strandNameSeqDict = getHybridizationInfo(fileName2)

    if strandNameSeqDict is None:
        # Can remove the temp file
        if os.path.exists(fileName2):
            os.remove(fileName2)
        return False

    infoCorrect = verifyStructureInfo(assy, strandNameSeqDict)

    if infoCorrect:
        #import optimized bases from the IOS file
        importBases(assy, strandNameSeqDict)
    else:
        if os.path.exists(fileName2):
            os.remove(fileName2)
        return False

    if os.path.exists(fileName2):
        os.remove(fileName2)

    return True
Exemple #24
0
def importFromIOSFile(assy, fileName1):
    """
    Imports optimized sequences to NE-1 from IOS file
    @param assy: the NE1 assy.
    @type  assy: L{assembly}
    
    @param fileName1: IOS Import file
    @type fileName1: string
    @return: Returns True or False based on whether import was successful
    
    @note: Since DNA Strand Chunks do not get stored in the mmp file, there's no
           way, chunk by chunk info can be verified between the structure on the
           NE-1 window and that in the IOS file. The most that can be done is to 
           verify the name of the strand Name info and their lengths. For instance
           if two NE-1 structures have the same name and number of strands,each
           of same length, but their pairing info is different, there's no way 
           to check that and the sequences will get imported anyways. There IOS 
           import happens at the user's risk.
    """
    
    strandsOnScreen = checkStrandsOnNE_1Window(assy)
    if strandsOnScreen == False:
        msg = "Cannot import since currently IOS import is supported only for DNA strands and there are no DNA strands on the screen. There is also no support for importing into clipboard."
        QMessageBox.warning(assy.win, "Warning!", msg)
        return False
        
    fileName2 = doInitialProcessingOnXMLFile(fileName1)
    strandNameSeqDict = getHybridizationInfo(fileName2)
    
    if strandNameSeqDict is None:
        # Can remove the temp file
        if os.path.exists(fileName2):
            os.remove(fileName2)
        return False
    
    infoCorrect = verifyStructureInfo(assy, strandNameSeqDict)
    
    if infoCorrect:
        #import optimized bases from the IOS file
        importBases(assy, strandNameSeqDict)
    else:
        if os.path.exists(fileName2):
            os.remove(fileName2)
        return False
        
    if os.path.exists(fileName2):
        os.remove(fileName2)
    
    return True
 def _checkClientIdLineEdit(self):
     if len(self.clientIdLineEdit.text()) <= 0:
         QMessageBox.warning(
             QMessageBox(), "Data Extractor for reddit",
             "Please enter your client-id in the box and then press 'Enter Client-id'."
         )
         return False
     if not self._validClientId():
         QMessageBox.warning(
             QMessageBox(), "Data Extractor for reddit",
             "The client-id you entered does not appear to be valid. Check the value and try again."
         )
         return False
     self.accept()
     return True
Exemple #26
0
    def simAbort(self):
        """
        Slot for Abort button.
        """
        if debug_flags.atom_debug and self.sim_abort_button_pressed:  # bruce 060106
            print "atom_debug: self.sim_abort_button_pressed is already True before we even put up our dialog"

        # Added confirmation before aborting as part of fix to bug 915. Mark 050824.
        # Bug 915 had to do with a problem if the user accidently hit the space bar or espace key,
        # which would call this slot and abort the simulation.  This should no longer be an issue here
        # since we aren't using a dialog.  I still like having this confirmation anyway.
        # IMHO, it should be kept. Mark 060106.
        ret = QMessageBox.warning(
            self,
            "Confirm",
            "Please confirm you want to abort.\n",
            "Confirm",
            "Cancel",
            "",
            1,  # The "default" button, when user presses Enter or Return (1 = Cancel)
            1,
        )  # Escape (1= Cancel)

        if ret == 0:  # Confirmed
            for abortHandler in self.abortableCommands.values():
                abortHandler.pressed()
Exemple #27
0
def _dialogToOfferPluginPrefsFixup(caption, text):
    """
    [private helper for _fixPluginProblem()]

    Offer the user a chance to fix a plugin problem.

    @param caption: The dialog border caption.
    @type  caption: text

    @param text: The dialog text.
    @type  text: text

    @return: 0 if they accept (after letting them try),
             1 if they decline.
    @rtype: int
    """

    win = env.mainwindow()

    ret = QMessageBox.warning(win, caption, text,
        "&OK", "Cancel", "",
        0, 1 )
    if ret == 0: # User clicked "OK"
        win.userPrefs.show(pagename = 'Plug-ins') # Show Preferences | Plug-in.
        return 0 # let caller figure out whether user fixed the problem
    elif ret == 1: # User clicked "Cancel"
        return 1
    pass
Exemple #28
0
    def simAbort(self):
        """
        Slot for Abort button.
        """
        if debug_flags.atom_debug and self.sim_abort_button_pressed:  #bruce 060106
            print "atom_debug: self.sim_abort_button_pressed is already True before we even put up our dialog"

        # Added confirmation before aborting as part of fix to bug 915. Mark 050824.
        # Bug 915 had to do with a problem if the user accidently hit the space bar or espace key,
        # which would call this slot and abort the simulation.  This should no longer be an issue here
        # since we aren't using a dialog.  I still like having this confirmation anyway.
        # IMHO, it should be kept. Mark 060106.
        ret = QMessageBox.warning(
            self,
            "Confirm",
            "Please confirm you want to abort.\n",
            "Confirm",
            "Cancel",
            "",
            1,  # The "default" button, when user presses Enter or Return (1 = Cancel)
            1)  # Escape (1= Cancel)

        if ret == 0:  # Confirmed
            for abortHandler in self.abortableCommands.values():
                abortHandler.pressed()
    def set_multiplicity(self, val):
        """
        Enable/disable widgets when user changes Multiplicity.
        """
        if val != 0:
            qt4todo("if scftyp[self.scftyp_btngrp.selectedId()] != 'RHF':")
            #if scftyp[self.scftyp_btngrp.selectedId()] != 'RHF':
            #    self.rhf_radiobtn.setEnabled(0)
            #    return

            ret = QMessageBox.warning( self, "Multiplicity Conflict",
                "If Multiplicity is greater than 1, then <b>UHF</b> or <b>ROHF</b> must be selected.\n"
                "Select Cancel to keep <b>RHF</b>.",
                "&UHF", "&ROHF", "Cancel",
                0, 2 )

            if ret == 0: # UHF
                self.uhf_radiobtn.toggle()
                self.rhf_radiobtn.setEnabled(0)

            elif ret == 1: # ROHF
                self.rohf_radiobtn.toggle()
                self.rhf_radiobtn.setEnabled(0)

            elif ret == 2: # Cancel
                self.multi_combox.setCurrentIndex(0)

        elif val == 0:
            self.rhf_radiobtn.setEnabled(1)
Exemple #30
0
    def onDeleteAction(self, val):
        '''
        Prepares for deletion of selected folders and files.
        If the user is sure, it will invoke deleteAction on a worker thread.
        '''
        utils.trace("ActionManager","onDeleteAction","")

        from AppController import AppController
        bloopTree = AppController.getInstance().getMainViewController().getBloopTree()

        # Grab the currently selected items (could be multiple selections)
        currentItems = bloopTree.selectedItems() 

        if currentItems is None:
            return

        if len(currentItems) > 0:
            from PyQt4.Qt import QMessageBox
            delConfirmMsg = i18n.LABEL_CONFIRM_FILE_DELETION_MESSAGE if len(currentItems) == 1 else i18n.LABEL_CONFIRM_FILES_DELETION_MESSAGE
            confirmDelete = QMessageBox.warning(AppController.getInstance().getMainView(), 
                                                i18n.LABEL_CONFIRM_FILES_DELETION_TITLE,
                                                delConfirmMsg,
                                                QMessageBox.Yes | QMessageBox.Cancel,
                                                QMessageBox.Yes);
            if confirmDelete == QMessageBox.Cancel:
                AppController.getInstance().getMainView().statusBar().showMessage("")
                return
            
        AppController.getInstance().getMainView().statusBar().showMessage(i18n.LABEL_BLOOPTREE_STATUS_BAR_DELETING)
        self.hireWorker(self.deleteAction, currentItems)
Exemple #31
0
    def set_multiplicity(self, val):
        """
        Enable/disable widgets when user changes Multiplicity.
        """
        if val != 0:
            qt4todo("if scftyp[self.scftyp_btngrp.selectedId()] != 'RHF':")
            #if scftyp[self.scftyp_btngrp.selectedId()] != 'RHF':
            #    self.rhf_radiobtn.setEnabled(0)
            #    return

            ret = QMessageBox.warning(
                self, "Multiplicity Conflict",
                "If Multiplicity is greater than 1, then <b>UHF</b> or <b>ROHF</b> must be selected.\n"
                "Select Cancel to keep <b>RHF</b>.", "&UHF", "&ROHF", "Cancel",
                0, 2)

            if ret == 0:  # UHF
                self.uhf_radiobtn.toggle()
                self.rhf_radiobtn.setEnabled(0)

            elif ret == 1:  # ROHF
                self.rohf_radiobtn.toggle()
                self.rhf_radiobtn.setEnabled(0)

            elif ret == 2:  # Cancel
                self.multi_combox.setCurrentIndex(0)

        elif val == 0:
            self.rhf_radiobtn.setEnabled(1)
Exemple #32
0
def _dialogToOfferPluginPrefsFixup(caption, text):
    """
    [private helper for _fixPluginProblem()]

    Offer the user a chance to fix a plugin problem.

    @param caption: The dialog border caption.
    @type  caption: text

    @param text: The dialog text.
    @type  text: text

    @return: 0 if they accept (after letting them try),
             1 if they decline.
    @rtype: int
    """

    win = env.mainwindow()

    ret = QMessageBox.warning(win, caption, text, "&OK", "Cancel", "", 0, 1)
    if ret == 0:  # User clicked "OK"
        win.userPrefs.show(pagename='Plug-ins')  # Show Preferences | Plug-in.
        return 0  # let caller figure out whether user fixed the problem
    elif ret == 1:  # User clicked "Cancel"
        return 1
    pass
    def sendBookData(self, author, title, genre, genre2, dateRead, grade, comments):
        data = json.dumps({'command':'add_book', 
        'title':title,
        'author':author,
        'genre':genre,
        'genre2':genre2,
        'dateRead':dateRead,
        'grade':grade,
        'comments':comments}) 

        r = requests.post('http://shinowa.tk/lab6/add_book.php', data)
        print r.status_code
        if(r.status_code == 200):
            QMessageBox.warning(None, "Success", "Data added successfully")
        elif(r.status_code == 404):
            QMessageBox.warning(None, "Failure", "Failed to add data")
Exemple #34
0
def activate_nh_plugin(win):
    """
    Opens a message box informing the user that the Nano-Hive plugin
    needs to be enabled and asking if they wish to do so.
    win is the main window object.
    """
    from PyQt4.Qt import QMessageBox

    ret = QMessageBox.warning(
        win,
        "Activate Nano-Hive Plug-in",
        "Nano-Hive plug-in not enabled. Please select <b>OK</b> to \n"
        "activate the Nano-Hive plug-in from the Preferences dialog.",
        "&OK",
        "Cancel",
        "",
        0,
        1,
    )

    if ret == 0:  # OK
        win.userPrefs.showDialog("Plug-ins")  # Show Preferences | Plug-in.
        if not env.prefs[nanohive_enabled_prefs_key]:
            return 1  # Nano-Hive was not enabled by user.

    elif ret == 1:  # Cancel
        return 1

    return 0
Exemple #35
0
 def startqueue(self):
     data=self.calibeditor.model.getjson()
     self.calibeditor.model.save()
     argu=["new", data]
     result={}
     title = str(data['Title'])
     usrfolder = str(data['Directory'][0])
     titlestr='The title and the selected user folder do NOT match. Are you sure you are user: '******' ?' 
     if title.find(usrfolder)==-1:
         res=QMessageBox.warning(self, self.tr("User folder"),self.tr(titlestr), QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
     else:
         res = QMessageBox.Yes
     if res==QMessageBox.Yes:
         try:
             result=json.loads(Leash.initcommand(self.options,argu,self.netconf))
         except Exception as e:
             self.errormessage.setWindowTitle("Server Error")
             self.errormessage.setMinimumSize(400, 300)
             self.errormessage.showMessage( str(e))
         if 'result' in result and result['result']=="new queue":
             self.setqueuesynced()
             self.plotthread.start()
         else:
             self.errormessage.setWindowTitle("Server Error")
             self.errormessage.setMinimumSize(400, 300)
             self.errormessage.showMessage( result["data"]["Error"])
Exemple #36
0
    def func(node):
        if isinstance(node, assy.DnaStrand):
            #retrive its name and see if it exists in the dictionary, if yes
            # then assign the base sequence
            try:
                seq = strandNameSeqDict[node.name]
                node.setStrandSequence(seq, False)

                for node in assy.part.topnode.members:
                    for nodeChild in node.members:
                        if isinstance(nodeChild, assy.DnaStrand):
                            seq = nodeChild.getStrandSequence()

            except KeyError:
                msg = "Cannot import IOS file since strand %s does not exist in the IOS file" % node.name
                QMessageBox.warning(assy.win, "Warning!", msg)
                return
Exemple #37
0
    def select_bin_path(self):

        self.tranus_binaries = QtGui.QFileDialog.getExistingDirectory(
            self, "Select directory")
        if self.tranus_binaries:
            self.tranus_bin_path.setText(self.tranus_binaries)
            if not os.path.isfile(
                    os.path.join(self.tranus_binaries,
                                 'lcal.exe')) or not os.path.isfile(
                                     os.path.join(self.tranus_binaries,
                                                  'pasos.exe')):
                QMessageBox.warning(
                    None, "Tranus binaries error",
                    "Tranus binaries not found in : %s" % self.tranus_binaries)
                print 'Tranus binaries not found in : %s' % self.tranus_binaries
                self.tranus_bin_path.setText('')
            self.save_settings()
 def _checkClientIdLineEdit(self):
     if len(self.clientIdLineEdit.text()) <= 0:
         QMessageBox.warning(
             QMessageBox(),
             "Data Extractor for reddit",
             "Please enter your client-id in the box and then press 'Enter Client-id'.",
         )
         return False
     if not self._validClientId():
         QMessageBox.warning(
             QMessageBox(),
             "Data Extractor for reddit",
             "The client-id you entered does not appear to be valid. Check the value and try again.",
         )
         return False
     self.accept()
     return True
 def checkFilterTable(self):
     """
     Make sure the user entered a value in the textedit field
     """
     if self.filterExternalContentCheckBox.isChecked(
     ) or self.filterSubmissionContentCheckBox.isChecked():
         for row in range(self.filterTable.rowCount()):
             if self.filterTable.cellWidget(
                     row, self.filtTableValCol) is None or len(
                         self.filterTable.cellWidget(
                             row, self.filtTableValCol).toPlainText()) <= 0:
                 QMessageBox.warning(
                     QMessageBox(), "Data Extractor for reddit",
                     "Please enter text in the value column or uncheck that you would like to filter content."
                 )
                 return False
     return True
 def checkFilterTable(self):
     """
     Make sure the user entered a value in the textedit field
     """
     if self.filterExternalContentCheckBox.isChecked() or self.filterSubmissionContentCheckBox.isChecked():
         for row in range(self.filterTable.rowCount()):
             if (
                 self.filterTable.cellWidget(row, self.filtTableValCol) is None
                 or len(self.filterTable.cellWidget(row, self.filtTableValCol).toPlainText()) <= 0
             ):
                 QMessageBox.warning(
                     QMessageBox(),
                     "Data Extractor for reddit",
                     "Please enter text in the value column or uncheck that you would like to filter content.",
                 )
                 return False
     return True
Exemple #41
0
 def _fileSelected(self, filename, quiet=False):
     self.wokbtn.setEnabled(False)
     if not filename:
         return None
     # check that filename matches model
     if not os.path.samefile(self._model_dir, os.path.dirname(filename)):
         self.wfile.setFilename('')
         if not quiet:
             QMessageBox.warning(
                 self, "Directory mismatch",
                 """<P>The FITS file must reside in the same directory
       as the current sky model.</P>""")
         self.wfile.setDirectory(self._model_dir)
         return None
     # read fits file
     busy = BusyIndicator()
     try:
         input_hdu = pyfits.open(filename)[0]
         hdr = input_hdu.header
         # get frequency, if specified
         for axis in range(1, hdr['NAXIS'] + 1):
             if hdr['CTYPE%d' % axis].upper() == 'FREQ':
                 self.wfreq.setText(str(hdr['CRVAL%d' % axis] / 1e+6))
                 break
     except Exception as err:
         busy = None
         self.wfile.setFilename('')
         if not quiet:
             QMessageBox.warning(
                 self, "Error reading FITS",
                 "Error reading FITS file %s: %s" % (filename, str(err)))
         return None
     self.wokbtn.setEnabled(True)
     # if filename is not in model already, enable the "add to model" control
     for src in self.model.sources:
         if isinstance(getattr(src, 'shape', None), ModelClasses.FITSImage) \
                 and os.path.exists(src.shape.filename) and os.path.exists(filename) \
                 and os.path.samefile(src.shape.filename, filename):
             self.wadd.setChecked(True)
             self.wadd.setEnabled(False)
             self.wadd.setText("image already in sky model")
             break
     else:
         self.wadd.setText("add image to sky model")
     return filename
    def makegamess(self):
        """
        Makes a GAMESS jig from the selected chunks or atoms.
        """
        # [mark 2007-05-07 modified docstring]

        if sys.platform == "win32":
            gms_str = "PC GAMESS"
        else:
            gms_str = "GAMESS"

        cmd = greenmsg(gms_str + ": ")

        atoms = []

        # Get a list of atoms from the selected chunks or atoms.
        atoms = self.assy.selected_atoms_list(
            include_atoms_in_selected_chunks = True)

        if not atoms:
            msg = "At least one atom must be selected to create a " + \
                  gms_str + " jig."
            env.history.message(cmd + redmsg(msg))
            return

        # Make sure that no more than 200 atoms are selected.
        nsa = len(atoms)
        if nsa > 200:
            msg = str(nsa) + " atoms selected.  The limit is 200."
            env.history.message(cmd + redmsg(msg))
            return

        # Bug 742.    Mark 050731.
        if nsa > 50:
            ret = QMessageBox.warning( self.assy.w, "Too many atoms?",
                gms_str + " jigs with more than 50 atoms may take an\n"
                "excessively long time to compute (days or weeks).\n"
                "Are you sure you want to continue?",
                "&Continue", "Cancel", "",
                0, 1 )

            if ret == 1: # Cancel
                return

        from analysis.GAMESS.jig_Gamess import Gamess
        m = Gamess(self.assy, atoms)
        m.edit()
            #bruce 050701 split edit method out of the constructor, so the
            # dialog doesn't show up when the jig is read from an mmp file
        if m.cancelled: # User hit 'Cancel' button in the jig dialog.
            env.history.message(cmd + "Cancelled")
            return
        self.unpickall_in_GLPane()
        self.place_new_jig(m)

        env.history.message(cmd + gms_str + " jig created")
        self.assy.w.win_update()
Exemple #43
0
    def makegamess(self):
        """
        Makes a GAMESS jig from the selected chunks or atoms.
        """
        # [mark 2007-05-07 modified docstring]

        if sys.platform == "win32":
            gms_str = "PC GAMESS"
        else:
            gms_str = "GAMESS"

        cmd = greenmsg(gms_str + ": ")

        atoms = []

        # Get a list of atoms from the selected chunks or atoms.
        atoms = self.assy.selected_atoms_list(
            include_atoms_in_selected_chunks=True)

        if not atoms:
            msg = "At least one atom must be selected to create a " + \
                  gms_str + " jig."
            env.history.message(cmd + redmsg(msg))
            return

        # Make sure that no more than 200 atoms are selected.
        nsa = len(atoms)
        if nsa > 200:
            msg = str(nsa) + " atoms selected.  The limit is 200."
            env.history.message(cmd + redmsg(msg))
            return

        # Bug 742.    Mark 050731.
        if nsa > 50:
            ret = QMessageBox.warning(
                self.assy.w, "Too many atoms?",
                gms_str + " jigs with more than 50 atoms may take an\n"
                "excessively long time to compute (days or weeks).\n"
                "Are you sure you want to continue?", "&Continue", "Cancel",
                "", 0, 1)

            if ret == 1:  # Cancel
                return

        from analysis.GAMESS.jig_Gamess import Gamess
        m = Gamess(self.assy, atoms)
        m.edit()
        #bruce 050701 split edit method out of the constructor, so the
        # dialog doesn't show up when the jig is read from an mmp file
        if m.cancelled:  # User hit 'Cancel' button in the jig dialog.
            env.history.message(cmd + "Cancelled")
            return
        self.unpickall_in_GLPane()
        self.place_new_jig(m)

        env.history.message(cmd + gms_str + " jig created")
        self.assy.w.win_update()
    def MakeGcode(self):
        path = QFileDialog.getSaveFileName(self, u"选择保存路径", "", " (*.nc)")
        if path == "":
            QMessageBox.warning(self, u"发生错误", u"路径错误!!")
            return

        f = open(path, 'w')
        f.write("M5\n")

        for i in range(self.resultImage.width()):
            flag = False
            #检测这一行是否有点
            for j in range(self.resultImage.height()):
                if self.resultImage.pixelIndex(i, j) < 128:
                    flag = True
                    break
            #如果这一行都没有点则跳过这一行
            if flag:
                f.write("G0 Y%f\n" % (i * self.pixDoubleSpinBox.value()))
            else:
                continue

            if (i % 2) > 0:
                for j in range(self.resultImage.height()):
                    if self.resultImage.pixelIndex(i, j) < 128:
                        f.write("G0 X%f\n" %
                                (j * self.pixDoubleSpinBox.value()))
                        f.write("M3\n")
                        f.write("G4 P%f\n" % self.timeDoubleSpinBox.value())
                        f.write("M5\n")
            else:
                for j in range(self.resultImage.height())[::-1]:
                    if self.resultImage.pixelIndex(i, j) < 128:
                        f.write("G0 X%f\n" %
                                (j * self.pixDoubleSpinBox.value()))
                        f.write("M3\n")
                        f.write("G4 P%f\n" % self.timeDoubleSpinBox.value())
                        f.write("M5\n")

        f.write("M5\n")
        f.write("G0 X0 Y0\n")
        f.close()
        QMessageBox.information(self, u"成功", u"生成G代码文件成功!!")
Exemple #45
0
 def removeCurrent(self, confirm=True):
     sel = self.selectedItems()
     if sel:
         if confirm:
             if QMessageBox.warning(
                     self, "Detaching from directory",
                     """Do you really want to stop monitoring the directory <tt>%s</tt>?"""
                     % sel[0].pathname(), QMessageBox.Yes,
                     QMessageBox.No) == QMessageBox.Yes:
                 return self._removeItem(sel[0])
     return None
    def LoadImageButtonClicked(self):
        self.filePath = QFileDialog.getOpenFileName(self, u"选择图片文件", "",
                                                    "Images (*.bmp)")
        if self.filePath == "":
            QMessageBox.warning(self, u"发生错误", u"没有选择可以识别的文件!!")
            return

        self.srcImage = QImage(self.filePath)
        self.grayImage = QImage(self.srcImage.size(), QImage.Format_Indexed8)

        for i in range(256):
            self.grayImage.setColor(i, qRgb(i, i, i))

        for i in range(self.srcImage.width()):
            for j in range(self.srcImage.height()):
                temp = qGray(self.srcImage.pixel(i, j))
                self.grayImage.setPixel(i, j, temp)

        self.srcImage = QImage(self.grayImage)
        self.resultImage = QImage(self.grayImage)
        self.imageLabel.setPixmap(QPixmap(self.srcImage))
 def viewDownloadedContent(self):
     """
     Show the downloaded content dialog GUI for the selected user / subreddit
     """
     if self._rddtDataExtractor.currentlyDownloading:
         QMessageBox.warning(QMessageBox(), "Data Extractor for reddit",
                             "Cannot view downloads while currently downloading. Please wait.")
         return
     model = self.model()
     index = self.getCurrentSelectedIndex()
     if model is not None and index is not None:
         selected = model.getObjectInLst(index)
         downloadedContent = selected.redditSubmissions
         if downloadedContent is not None and len(downloadedContent) > 0:
             downloadedContentGUI = DownloadedContentGUI(selected, self.model(), confirmDialog, self._gui.saveState)
             downloadedContentGUI.exec_()
         else:
             QMessageBox.information(QMessageBox(), "Data Extractor for reddit",
                                     selected.name + " has no downloaded content. Download some by hitting the download button.")
     elif index is None:
         QMessageBox.information(QMessageBox(), "Data Extractor for reddit",
                                 "To view a " + self.objectName() + "'s downloaded content, please select a " + self.objectName() + " in the " + self.objectName() + " list.")
Exemple #48
0
 def _deleteSelectedEntries(self):
     remaining_entries = []
     del_entries = list(self.etw.iterator(self.etw.Iterator.Selected))
     remaining_entries = list(
         self.etw.iterator(self.etw.Iterator.Unselected))
     if not del_entries:
         return
     hide_viewer = bool([
         item for item in del_entries
         if self._viewing_ientry == item._ientry
     ])
     del_entries = [
         self.purrer.entries[self.etw.indexOfTopLevelItem(item)]
         for item in del_entries
     ]
     remaining_entries = [
         self.purrer.entries[self.etw.indexOfTopLevelItem(item)]
         for item in remaining_entries
     ]
     # ask for confirmation
     if len(del_entries) == 1:
         msg = """<P><NOBR>Permanently delete the log entry</NOBR> "%s"?</P>""" % del_entries[
             0].title
         if del_entries[0].dps:
             msg += """<P>%d data product(s) saved with this
               entry will be deleted as well.</P>""" % len(
                 del_entries[0].dps)
     else:
         msg = """<P>Permanently delete the %d selected log entries?</P>""" % len(
             del_entries)
         ndp = 0
         for entry in del_entries:
             ndp += len([dp for dp in entry.dps if not dp.ignored])
         if ndp:
             msg += """<P>%d data product(s) saved with these entries will be deleted as well.</P>""" % ndp
     if QMessageBox.warning(self, "Deleting log entries", msg,
                            QMessageBox.Yes,
                            QMessageBox.No) != QMessageBox.Yes:
         return
     if hide_viewer:
         self.view_entry_dialog.hide()
     # reset entries in purrer and in our log window
     self._setEntries(remaining_entries)
     self.purrer.deleteLogEntries(del_entries)
     #    self.purrer.setLogEntries(remaining_entries)
     # log will have changed, so update the viewer
     self._updateViewer()
     # delete entry files
     for entry in del_entries:
         entry.remove_directory()
 def viewRemainingImgurRequests(self):
     if self._rddtDataExtractor.currentlyDownloading:
         QMessageBox.warning(QMessageBox(), "Data Extractor for reddit",
                             "Cannot view imgur requests while currently downloading. Please wait.")
         return
     msgBox = QMessageBox()
     msgBox.setWindowTitle("Data Extractor for reddit")
     if self._rddtDataExtractor.imgurAPIClientID is not None:
         headers = {'Authorization': 'Client-ID ' + self._rddtDataExtractor.imgurAPIClientID}
         apiURL = "https://api.imgur.com/3/credits"
         requestsSession = requests.session()
         requestsSession.headers[
             'User-Agent'] = 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36'
         json = exceptionSafeJsonRequest(requestsSession, apiURL, headers=headers, stream=True,
                                         verify='RedditDataExtractor/cacert.pem')
         if json is not None and json.get('data') is not None and json.get('data').get('ClientRemaining'):
             msgBox.setText("You have " + str(json.get('data').get('ClientRemaining')) + " requests remaining.")
         else:
             msgBox.setText(
                 "A problem occurred using the Imgur API. Check that you are connected to the internet and make sure your client-id is correct.")
     else:
         msgBox.setText(
             "You do not currently have an Imgur client-id set. To set one, go to settings and check 'Change / Reset Client-id'")
     msgBox.exec()
Exemple #50
0
 def accept(self):
     """When dialog is accepted with a default (bool) tag type,
     check if the user hasn't entered a name=value entry in the tag name field.
     This is a common mistake, and should be treated as a shortcut for setting string tags."""
     if isinstance(self.valedit.getValue(), bool):
         tagval = str(self.wtagsel.currentText()).split("=", 1)
         if len(tagval) > 1:
             #        print tagval
             if QMessageBox.warning(self,
                                    "Set a string tag instead?", """<P>You have included an "=" sign in the tag name. 
         Perhaps you actually mean to set tag "%s" to the string value "%s"?</P>""" % tuple(tagval),
                                    QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) == QMessageBox.No:
                 return
             self.wtagsel.setEditText(tagval[0])
             self.valedit.setValue(tagval[1])
     return QDialog.accept(self)
    def _job_cancelation_confirmed(self):
        ret = QMessageBox.warning(
            None,
            "Confirm",
            "Please confirm you want to abort the GAMESS simulation.\n",
            "Confirm",
            "Cancel",
            "",
            1,  # The "default" button, when user presses Enter or Return (1 = Cancel)
            1)  # Escape (1= Cancel)

        if ret == 0:  # Confirmed
            print "CONFIRMED"
            return True
        else:
            print "CANCELLED"
            return False
Exemple #52
0
 def startqueue(self):
     data = self.calibeditor.model.getjson()
     try:
         title = str(data['Title'])
     except Exception as e:
         return
     self.calibeditor.model.save()
     argu = ["new", data]
     result = {}
     title = str(data['Title'])
     usrfolder = str(data['Directory'][0])
     titlestr = 'The title and the selected user folder do NOT match. Are you sure you are user: '******' ?'
     if title.find(usrfolder) == -1:
         res = QMessageBox.warning(self, self.tr("User folder"),
                                   self.tr(titlestr),
                                   QMessageBox.Yes | QMessageBox.No,
                                   QMessageBox.No)
     else:
         res = QMessageBox.Yes
     if res == QMessageBox.Yes:
         try:
             result = json.loads(
                 Leash.initcommand(self.options, argu, self.netconf))
         except Exception as e:
             self.errormessage.setWindowTitle("Server Error")
             self.errormessage.setMinimumSize(400, 300)
             self.errormessage.showMessage(str(e))
         if 'result' in result and result['result'] == "new queue":
             self.setqueuesynced()
             self.plotthread.start()
             self.consolidatepanel.submitbutton.setEnabled(True)
             folderpath = "/"
             for text in data['Directory']:
                 folderpath += text + "/"
             titlestr = 'Successfully loaded new calibration to Server!\n\nDo you want to re-integrate all images in ' + folderpath + ' ?'
             res = QMessageBox.information(self, self.tr("Re-integrate?"),
                                           self.tr(titlestr),
                                           QMessageBox.Yes | QMessageBox.No,
                                           QMessageBox.No)
             if res == QMessageBox.Yes:
                 self.menue.queueRedoAllImmages()
         else:
             self.errormessage.setWindowTitle("Server Error")
             self.errormessage.setMinimumSize(400, 300)
             self.errormessage.showMessage(result["data"]["Error"])
Exemple #53
0
    def saveStrandSequence(self):
        """
        Save the strand sequence entered in the Strand text edit in the 
        specified file. 
        """
        if not self.sequenceFileName:  
            sdir = env.prefs[workingDirectory_prefs_key]
        else:
            sdir = self.sequenceFileName
           
        fileName = QFileDialog.getSaveFileName(
                     self,              
                     "Save Strand Sequence As ...",
                     sdir,
                    "Strand Sequence File (*.txt)"
                     )
        
        if fileName:
            fileName = str(fileName)
            if fileName[-4] != '.':
                fileName += '.txt'
               
            if os.path.exists(fileName):
                
                # ...and if the "Save As" file exists...
                # ... confirm overwrite of the existing file.
                
                ret = QMessageBox.warning( 
                    self, 
                    "Save Strand Sequence...", 
                    "The file \"" + fileName + "\" already exists.\n"\
                    "Do you want to overwrite the existing file or cancel?",
                    "&Overwrite", "&Cancel", "",
                    0, # Enter == button 0
                    1 ) # Escape == button 1

                if ret == 1:
                    # The user cancelled
                    return 
                    
            # write the current set of element colors into a file    
            self._writeStrandSequenceFile(
                fileName,
                str(self.sequenceTextEdit.toPlainText()))
        return
    def _validate_gamess_program(self):
        """
        Private method:
        Checks that the GAMESS program path exists in the user pref database
        and that the file it points to exists.  If the GAMESS path does not exist, the
        user will be prompted with the file chooser to select the GAMESS executable.
        This function does not check whether the GAMESS path is actually GAMESS 
        or if it is the correct version of GAMESS for this platform (i.e. PC GAMESS for Windows).
        Returns:  0 = Valid
                  1 = Invalid
        """
        # Get GAMESS executable path from the user preferences
        prefs = preferences.prefs_context()
        self.server.program = prefs.get(gmspath_prefs_key)

        if not self.server.program:
            msg = "The GAMESS executable path is not set.\n"
        elif os.path.exists(self.server.program):
            return 0
        else:
            msg = self.server.program + " does not exist.\n"

        # GAMESS Prop Dialog is the parent for messagebox and file chooser.
        parent = self.edit_cntl

        ret = QMessageBox.warning(
            parent, "GAMESS Executable Path", msg +
            "Please select OK to set the location of GAMESS for this computer.",
            "&OK", "Cancel", "", 0, 1)

        if ret == 0:  # OK
            self.server.program = \
                get_filename_and_save_in_prefs(parent, gmspath_prefs_key, "Choose GAMESS Executable")
            if not self.server.program:
                return 1  # Cancelled from file chooser.

            # Enable GAMESS Plug-in. Mark 060112.
            env.prefs[gamess_enabled_prefs_key] = True

        elif ret == 1:  # Cancel
            return 1

        return 0
Exemple #55
0
    def write_element_rgb_table(self):
        """
        Save the current set of element preferences into an external file --
        currently only r,g,b color of each element will be saved.
        """
        if not self.fileName:
            from utilities.prefs_constants import workingDirectory_prefs_key
            sdir = env.prefs[workingDirectory_prefs_key]
        else:
            sdir = self.fileName

        fn = QFileDialog.getSaveFileName(self, "Save Element Colors As ...",
                                         sdir, "Element Color File (*.txt)")

        if fn:
            fn = str(fn)
            if fn[-4] != '.':
                fn += '.txt'

            import os
            if os.path.exists(fn):  # ...and if the "Save As" file exists...
                # ... confirm overwrite of the existing file.
                ret = QMessageBox.warning(
                    self,
                    "Save Element Colors...",
                    "The file \"" + fn + "\" already exists.\n"
                    "Do you want to overwrite the existing file or cancel?",
                    "&Overwrite",
                    "&Cancel",
                    "",
                    0,  # Enter == button 0
                    1)  # Escape == button 1

                if ret == 1:  # The user cancelled
                    return

            # write the current set of element colors into a file
            saveElementColors(fn, self.elemTable.getAllElements())
            env.history.message("Element colors saved in file: [" + fn + "]")
            #After saving a file, reset the flag
            self.isFileSaved = True
Exemple #56
0
def activate_nh_plugin(win):
    """
    Opens a message box informing the user that the Nano-Hive plugin
    needs to be enabled and asking if they wish to do so.
    win is the main window object.
    """
    from PyQt4.Qt import QMessageBox
    ret = QMessageBox.warning( win, "Activate Nano-Hive Plug-in",
        "Nano-Hive plug-in not enabled. Please select <b>OK</b> to \n" \
        "activate the Nano-Hive plug-in from the Preferences dialog.",
        "&OK", "Cancel", "",
        0, 1 )
            
    if ret == 0: # OK
        win.userPrefs.showDialog('Plug-ins') # Show Preferences | Plug-in.
        if not env.prefs[nanohive_enabled_prefs_key]:
            return 1 # Nano-Hive was not enabled by user.
        
    elif ret == 1: # Cancel
        return 1

    return 0
Exemple #57
0
def _dialog_to_offer_prefs_fixup(
        win, caption, text,
        macwarning_ok):  #bruce 060710 [use Plugin.py instead?]
    """
    Offer the user a chance to fix a problem.
    Return 0 if they accept (after letting them try), 1 if they decline.
    """
    # modified from (now-removed) activate_plugin() which had similar code
    macwarning = ""
    if sys.platform == 'darwin' and macwarning_ok:
        macwarning = "\n"\
                   "  Warning: Mac GUI versions of POV-Ray or MegaPOV won't work,\n"\
                   "but the Unix command-line versions can be compiled on the Mac\n"\
                   "and should work. Contact [email protected] for more info."
    ret = QMessageBox.warning(win, caption, text + macwarning, "&OK", "Cancel",
                              "", 0, 1)
    if ret == 0:  # OK
        win.userPrefs.show(pagename='Plug-ins')  # Show Preferences | Plug-ins.
        return 0  # let caller figure out whether user fixed the problem
    elif ret == 1:  # Cancel
        return 1
    pass
Exemple #58
0
def verifyStructureInfo(assy, iosSeqNameDict):
    """
    Verify that the structure info in the IOS file matches with that of the NE-1 part.
    @param part: the NE1 part.
    @type  part: L{assembly}

    @param iosSeqNameDict: dictionary containing strand and basestring
                           from the IOS file
    @type compInfoDict: dict
    @return: True or False based on if the structure in the IOS file matches up
             with the structure in the NE-1 window.
    """
    strandListFromNE_1, baseStringListFromNE_1 = getStrandsBaseInfoFromNE_1(
        assy)
    #check their lengths first
    dictLength = len(iosSeqNameDict)
    strandListFromNE_1Length = len(strandListFromNE_1)
    if dictLength != strandListFromNE_1Length:
        msg = "IOS import aborted since the number of strands in the IOS file "\
            "does not equal the number of strands in the current model."
        QMessageBox.warning(assy.win, "Warning!", msg)
        return False

    for strand in iosSeqNameDict:

        baseString = iosSeqNameDict[strand]
        try:
            index = strandListFromNE_1.index(strand)
            baseStringFromNE_1 = baseStringListFromNE_1[index]
        except ValueError:
            msg = "IOS import aborted since strand '%s' in the IOS file does"\
                "not exist in the current model." % strand
            QMessageBox.warning(assy.win, "Warning!", msg)
            return False

        if len(baseStringFromNE_1) != len(baseString):
            msg = "IOS import aborted since the length of strand '%s' "\
                 "(%s bases) in the current model does not match the length "\
                 "of strand '%s' found in the IOS file (%d bases)." % \
                (strandListFromNE_1[index],
                 len(baseStringFromNE_1),
                 strand,
                 len(baseString))
            QMessageBox.warning(assy.win, "Warning!", msg)
            return False
    return True