コード例 #1
0
 def save_configuration(self, configuration: Union[Dict[str, Any],
                                                   None]) -> None:
     self.save_to_file(
         configuration,
         QFileDialog.getSaveFileName(
             self, "Save Configuration",
             str(pathlib.Path(__file__).parent.resolve()),
             "CDS Configuration (*.json);;All Files (*)")[0])
コード例 #2
0
ファイル: main_window.py プロジェクト: DataManagementLab/ASET
    def save_matching_phase_to_config_task(self):
        logger.info("Execute task 'save_matching_phase_to_config_task'.")

        if self.matching_phase is not None:
            path = str(QFileDialog.getSaveFileName(self, "Choose where to save the configuration .json file!")[0])
            if path != "":
                self.disable_global_input()
                # noinspection PyUnresolvedReferences
                self.save_matching_phase_to_config.emit(path, self.matching_phase)
コード例 #3
0
ファイル: main_window.py プロジェクト: DataManagementLab/ASET
    def save_table_to_csv_task(self):
        logger.info("Execute task 'save_table_to_csv_task'.")

        if self.document_base is not None:
            path = str(QFileDialog.getSaveFileName(self, "Choose where to save the table .csv file!")[0])
            if path != "":
                self.disable_global_input()
                # noinspection PyUnresolvedReferences
                self.save_table_to_csv.emit(path, self.document_base)
コード例 #4
0
ファイル: main_window.py プロジェクト: DataManagementLab/ASET
    def save_statistics_to_json_task(self):
        logger.info("Execute task 'save_statistics_to_json_task'.")

        if self.statistics is not None:
            path = str(QFileDialog.getSaveFileName(self, "Choose where to save the statistics .json file!")[0])
            if path != "":
                self.disable_global_input()
                # noinspection PyUnresolvedReferences
                self.save_statistics_to_json.emit(path, self.statistics)
コード例 #5
0
ファイル: main_window.py プロジェクト: DataManagementLab/ASET
    def save_document_base_to_bson_task(self):
        logger.info("Execute task 'save_document_base_to_bson_task'.")

        if self.document_base is not None:
            path, ok = QFileDialog.getSaveFileName(self, "Choose where to save the document collection .bson file!")
            if ok:
                self.disable_global_input()
                # noinspection PyUnresolvedReferences
                self.save_document_base_to_bson.emit(str(path), self.document_base)
コード例 #6
0
    def saveImage(self):
        """Save the image displayed in the label."""
        #TODO: Add different functionality for the way in which the user can save their image.
        if self.image.isNull() == False:
            image_file, _ = QFileDialog.getSaveFileName(
                self, "Save Image", "",
                "PNG Files (*.png);;JPG Files (*.jpeg *.jpg );;Bitmap Files (*.bmp);;\
                    GIF Files (*.gif)")

            if image_file and self.image.isNull() == False:
                self.image.save(image_file)
            else:
                QMessageBox.information(self, "Error", "Unable to save image.",
                                        QMessageBox.Ok)
        else:
            QMessageBox.information(self, "Empty Image",
                                    "There is no image to save.",
                                    QMessageBox.Ok)
コード例 #7
0
    def saveMaskFile(self):
        creation_datetime, width, height = getVideoMetadata(self.videoFile)
        item = self.gView.gPolyItem  #self.gView.unsavedZones[0]
        mask_polygon = item.polygon()
        xy = []
        for p in mask_polygon:
            xy.append((p.x(), p.y()))

        img = Image.new('RGB', (width, height), color='black')
        img1 = ImageDraw.Draw(img)
        img1.polygon(xy, fill="white", outline="white")

        fileName, _ = QFileDialog.getSaveFileName(self, "Open database file",
                                                  QDir.homePath(),
                                                  "PNG files (*.png)")
        if fileName != '':
            img.save(fileName)

        self.gView.scene().removeItem(item)
        self.gView.unsavedZones = []
コード例 #8
0
    def file_save_as(self):
        path, _ = QFileDialog.getSaveFileName(
            self,
            "Save file",
            "",
            "Text documents (*.txt);;All files (*.*)",
        )

        if not path:
            return

        text = self.editor.toPlainText() if splitext(
            path) in TEXT_EXTENSIONS else self.editor.toPlainText()

        try:
            with open(path, "w") as f:
                f.write(text)

        except Exception as e:
            self.dialog_critical(str(e))

        else:
            self.path = path
            self.update_title()
コード例 #9
0
ファイル: spiki.py プロジェクト: threeme3/spiki
    def writeModule(self):
        fname, ok = QFileDialog.getSaveFileName(self, 'Save Module', '.', 'Footprint (*.kicad_mod);;Any File (*)')
        if (not fname):
            return
        if (not fname.endswith('.kicad_mod')):
            fname = fname + '.kicad_mod'

        nTurns = float(self.nTurnsLineEdit.text())
        innerRadius = float(self.innerRadiusLineEdit.text())
        pitch = float(self.pitchLineEdit.text())
        spacing = float(self.spacingLineEdit.text())
        traceWidth = float(self.traceWidthLineEdit.text())
        nLayers = int(self.nLayersLineEdit.text())
        d = float(self.drawTolLineEdit.text())
        
        polygonVertexCount = None

        geometricPrimitives = None
        dir = 1
        inductorStyleIndex = self.indStyleCB.currentIndex()
        if (inductorStyleIndex == InductorStyle.CIRCULAR_SEGMENTS): # circular segments
            geometricPrimitives = dos.circ_spiral(nTurns, innerRadius, pitch, dir, d)
        elif (inductorStyleIndex == InductorStyle.CIRCULAR_ARCS): # circular arcs
            polygonVertexCount = int(self.polygonVertexCountLineEdit.text())
            geometricPrimitives = dos.arcs_spiral(nTurns, innerRadius, pitch, dir, polygonVertexCount)
        elif (inductorStyleIndex == InductorStyle.SQUARE): # rectangle
            geometricPrimitives = dos.square_spiral(nTurns, innerRadius, pitch)
          
        # Check if making an inductor from the given parameters is at all possible
        if (geometricPrimitives is None):
            self.showInvalidParametersErrorMsg()
        else:
            sm = dos.kmodule(fname)
            sm.write_header(name='SIND', descr='spiral inductor', tags='SMD')
            if (inductorStyleIndex == InductorStyle.CIRCULAR_SEGMENTS): # circular segments
                vx = geometricPrimitives
                sm.add_circ_spiral(vx, 'F.Cu', traceWidth)
                if (nLayers == 2):
                    pad1 = vx[-1] # inductor starts at end of top spiral
                    vx = dos.circ_spiral(nTurns, innerRadius, pitch, -dir, d)
                    sm.add_circ_spiral(vx, 'B.Cu', traceWidth)
                    sm.add_thru_pad('lc', 'circle', vx[0], dos.Point(0.6, 0.6), 0.3)
                    end_layer = 'B'
                else: # single-layer spiral
                    pad1 = vx[0] # inductor starts at center of spiral
                    end_layer = 'F'
                pad2 = vx[-1] # inductor ends always at end of last spiral
            elif (inductorStyleIndex == InductorStyle.CIRCULAR_ARCS): # circular arcs
                arcs = geometricPrimitives
                sm.add_arc_spiral(arcs, 'F.Cu', traceWidth)
                if (nLayers == 2):
                    # inductor starts at end of top spiral
                    p_end = arcs[-1][1].copy() # starting point of the last arc
                    p_center = arcs[-1][0] # centre of the last arc
                    theta = arcs[-1][2] # arc starting point
                    p_end.rotate_about(p_center, theta)  # end point of the circular arc
                    pad1 = p_end
                    arcs = dos.arcs_spiral(nTurns, innerRadius, pitch, -dir, polygonVertexCount)
                    sm.add_arc_spiral(arcs, 'B.Cu', traceWidth)
                    sm.add_thru_pad('lc', 'circle', arcs[0][1], dos.Point(0.6, 0.6), 0.3)
                    end_layer = 'B'
                else: # single-layer spiral
                    # inductor starts at center of spiral
                    pad1 = arcs[0][1] # starting point of the last arc
                    end_layer = 'F'
                # inductor ends always at end of last spiral
                p_end = arcs[-1][1].copy() # starting point of the last arc
                p_center = arcs[-1][0] # centre of the last arc
                theta = arcs[-1][2] # arc starting point
                p_end.rotate_about(p_center, theta)  # end point of the circular arc
                pad2 = p_end
            elif (inductorStyleIndex == InductorStyle.SQUARE): # rectangle
                vx = geometricPrimitives                
                sm.add_circ_spiral(vx, 'F.Cu', traceWidth)
                # single-layer spiral
                pad1 = vx[0] # inductor starts at center of spiral
                end_layer = 'F'
                
                pad2 = vx[-1] # inductor ends always at end of last spiral
            else:
                pass

            # add SMD pads at the beginning and end
            padSize = dos.Point(traceWidth/2.0, traceWidth/2.0)
            sm.add_smd_pad('1', 'rect', pad1, padSize, 'F')
            sm.add_smd_pad('2', 'rect', pad2, padSize, end_layer)

            #draw_arcs_spiral(nTurns, innerRadius, pitch, traceWidth, N, dir)
            sm.write_refs(0, 0, ref='REF**', value='LLL')
            sm.close()
コード例 #10
0
ファイル: __main__.py プロジェクト: wingtorres/morphometrix
    def export_measurements(self):

        fac = max(self.iw.pixmap.width(), self.iw.pixmap.height()) / max(
            self.iw.pixmap_fit.width(),
            self.iw.pixmap_fit.height())  #scale pixel -> m by scaled image
        name = QFileDialog.getSaveFileName(
            self, 'Save File', self.image_name[0].split('.', 1)[0])[0]
        self.pixeldim = float(self.subWin.pixeldim.text())
        self.altitude = float(self.subWin.altitude.text())
        self.focal = float(self.subWin.focal.text())
        #okay in mm https://www.imaging-resource.com/PRODS/sony-a5100/sony-a5100DAT.HTM
        if name:

            #Convert pixels to meters
            #measurements = [ f * fac * self.pixeldim * self.altitude / self.focal for f in self.iw.measurements]
            #lengths = [ f * fac * self.pixeldim * self.altitude / self.focal for f in self.iw.lengths]
            #print(self.iw.widths)
            areas = self.iw.areaValues * (
                fac * self.pixeldim * self.altitude / self.focal)**2
            values_optical = np.array([
                self.subWin.id.text(), self.image_name[0], self.focal,
                self.altitude, self.pixeldim
            ])
            names_optical = [
                'Image ID', 'Image Path', 'Focal Length', 'Altitude',
                'Pixel Dimension'
            ]
            names_widths = ['Object'] +  ['Length (m)'] + ['Widths (%)'] # + self.iw.widthNames[0]
            #names_widths.append([self.iw.widthNames[0]])

	    #Write .csv file
            print(f"Writing {name} to file")
            with open(name + '.csv', 'w') as csvfile:
                writer = csv.writer(csvfile)
                for (f, g) in zip(names_optical, values_optical):
                    writer.writerow([f, g])
                writer.writerow(['Notes', self.subWin.notes.toPlainText()])

                writer.writerow([''])
                writer.writerow(names_widths)

                for k,m in enumerate(self.lengthNames):
                    #format and convert pixel length measurement
                    l =  "{0:.2f}".format( self.iw.lengths[k] * fac * self.pixeldim * self.altitude / self.focal )

                    if any(self.iw.widths[k]): #check if width measurement exists for length
                        n = self.iw.widthNames[k]
                        writer.writerow( [''] + [''] + n )
                        #format and convert pixel width measurement
                        vals = [ "{0:.2f}".format(g * fac * self.pixeldim * self.altitude / self.focal) for g in self.iw.widths[k]]
                        line = [m] + [l] + list(vals)
                    else:
                        #vals = l #f.copy()
                        line = [m] + [l]

                    writer.writerow(line)

                writer.writerow([''])
                writer.writerow(['Object'] + ['Angle'])

                for k, f in enumerate(self.angleNames):  #write angles
                    line = [[f] + ["{0:.3f}".format(self.iw.angleValues[k])]]  #need to convert NaNs to empty
                    writer.writerows(line)

                writer.writerow([''])
                writer.writerow(['Object'] + ['Area (m\u00B2)'])

                for k, f in enumerate(self.areaNames):  #write areas
                    line = [[f] + ["{0:.3f}".format(areas[k])]]  #need to convert NaNs to empty
                    writer.writerows(line)

            #Export image
            self.iw.fitInView(self.iw.scene.sceneRect(), QtCore.Qt.AspectRatioMode.KeepAspectRatio)
            pix = QtGui.QPixmap(self.iw.viewport().size())
            self.iw.viewport().render(pix)
            pix.save(name + '-measurements.png')
コード例 #11
0
    def saveProject(self):

        if self.projectFile == '':
            fileDir = QDir.homePath()
        else:
            fileDir = self.projectFile

        self.projectFile, _ = QFileDialog.getSaveFileName(
            self, "Save project file", fileDir, "Project (*.prj)")
        # fileName = "/Users/Abbas/project.xml"
        if self.projectFile == '':
            return

        file = QFile(self.projectFile)
        if (not file.open(QIODevice.OpenModeFlag.WriteOnly
                          | QIODevice.OpenModeFlag.Text)):
            return

        xmlWriter = QXmlStreamWriter(file)
        xmlWriter.setAutoFormatting(True)
        xmlWriter.writeStartDocument()

        xmlWriter.writeStartElement('project')

        xmlWriter.writeStartElement('database')
        xmlWriter.writeTextElement("fileName", self.obsTb.dbFilename)
        xmlWriter.writeEndElement()

        xmlWriter.writeStartElement('video')
        xmlWriter.writeTextElement(
            "fileName",
            self.videoFile)  #mediaPlayer.media().canonicalUrl().path())
        xmlWriter.writeTextElement("sliderValue",
                                   str(self.mediaPlayer.position()))
        xmlWriter.writeEndElement()

        xmlWriter.writeStartElement('trajectory')
        xmlWriter.writeTextElement("metadata", self.obsTb.mdbFileLedit.text())
        xmlWriter.writeTextElement(
            "site", str(self.obsTb.siteNameCombobx.currentIndex()))
        xmlWriter.writeTextElement(
            "cam_view", str(self.obsTb.camViewCombobx.currentIndex()))
        xmlWriter.writeTextElement("traj_db",
                                   str(self.obsTb.trjDbCombobx.currentIndex()))
        xmlWriter.writeEndElement()

        xmlWriter.writeStartElement('window')
        xmlWriter.writeTextElement(
            "mainWin_size", "{},{}".format(int(self.width()),
                                           int(self.height())))
        xmlWriter.writeTextElement(
            "mainWin_pos", "{},{}".format(int(self.x()), int(self.y())))
        xmlWriter.writeTextElement("obsTbx_open", str(self.obsTb.isVisible()))
        xmlWriter.writeTextElement(
            "obsTbx_size", "{},{}".format(int(self.obsTb.width()),
                                          int(self.obsTb.height())))
        xmlWriter.writeTextElement(
            "obsTbx_pos", "{},{}".format(int(self.obsTb.x()),
                                         int(self.obsTb.y())))
        xmlWriter.writeEndElement()

        xmlWriter.writeEndElement()

        self.setWindowTitle('{} - {}'.format(
            os.path.basename(self.videoFile),
            os.path.basename(self.projectFile)))
        if self.obsTb.dbFilename != None:
            self.obsTb.setWindowTitle('{} - {}'.format(
                os.path.basename(self.obsTb.dbFilename),
                os.path.basename(self.projectFile)))
コード例 #12
0
    def exportData(self) -> None:
        # thanks to Aldo Hoeben / fieldOfView for this part of the code
        file_name = ""
        if VERSION_QT5:
            file_name = QFileDialog.getSaveFileName(
                parent = None,
                caption = catalog.i18nc("@title:window", "Save as"),
                directory = self._preferences.getValue("import_export_tools/dialog_path"),
                filter = "CSV files (*.csv)",
                options = self._dialog_options
            )[0]
        else:
            dialog = QFileDialog()
            dialog.setWindowTitle(catalog.i18nc("@title:window", "Save as"))
            dialog.setDirectory(self._preferences.getValue("import_export_tools/dialog_path"))
            dialog.setNameFilters(["CSV files (*.csv)"])
            dialog.setAcceptMode(QFileDialog.AcceptMode.AcceptSave)
            dialog.setFileMode(QFileDialog.FileMode.AnyFile)
            if dialog.exec():
                file_name = dialog.selectedFiles()[0]
                
                
        if not file_name:
            Logger.log("d", "No file to export selected")
            return

        self._preferences.setValue("import_export_tools/dialog_path", os.path.dirname(file_name))
        # -----
        
        machine_manager = CuraApplication.getInstance().getMachineManager()        
        stack = CuraApplication.getInstance().getGlobalContainerStack()

        global_stack = machine_manager.activeMachine

        # Get extruder count
        extruder_count=stack.getProperty("machine_extruder_count", "value")
        
        # for name in sorted(csv.list_dialects()):
        #             Logger.log("d", "Dialect = %s" % name)
        #             dialect = csv.get_dialect(name)
        #             Logger.log("d", "Delimiter = %s" % dialect.delimiter)
        
        exported_count = 0
        try:
            with open(file_name, 'w', newline='') as csv_file:
                # csv.QUOTE_MINIMAL  or csv.QUOTE_NONNUMERIC ?
                csv_writer = csv.writer(csv_file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
                # E_dialect = csv.get_dialect("excel")
                # csv_writer = csv.writer(csv_file, dialect=E_dialect)
                
                csv_writer.writerow([
                    "Section",
                    "Extruder",
                    "Key",
                    "Type",
                    "Value"
                ])
                 
                # Date
                self._WriteRow(csv_writer,"general",0,"Date","str",datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
                # Platform
                self._WriteRow(csv_writer,"general",0,"Os","str",str(platform.system()) + " " + str(platform.version())) 
                # Version  
                self._WriteRow(csv_writer,"general",0,"Cura_Version","str",CuraVersion)
                # Profile
                P_Name = global_stack.qualityChanges.getMetaData().get("name", "")
                self._WriteRow(csv_writer,"general",0,"Profile","str",P_Name)
                # Quality
                Q_Name = global_stack.quality.getMetaData().get("name", "")
                self._WriteRow(csv_writer,"general",0,"Quality","str",Q_Name)
                # Extruder_Count
                self._WriteRow(csv_writer,"general",0,"Extruder_Count","int",str(extruder_count))
                
                # Material
                # extruders = list(global_stack.extruders.values())  
                extruder_stack = CuraApplication.getInstance().getExtruderManager().getActiveExtruderStacks()
 
                # Define every section to get the same order as in the Cura Interface
                # Modification from global_stack to extruders[0]
                i=0
                for Extrud in extruder_stack:    
                    i += 1                        
                    self._doTree(Extrud,"resolution",csv_writer,0,i)
                    # Shell before 4.9 and now Walls
                    self._doTree(Extrud,"shell",csv_writer,0,i)
                    # New section Arachne and 4.9 ?
                    if self.Major > 4 or ( self.Major == 4 and self.Minor >= 9 ) :
                        self._doTree(Extrud,"top_bottom",csv_writer,0,i)
                    self._doTree(Extrud,"infill",csv_writer,0,i)
                    self._doTree(Extrud,"material",csv_writer,0,i)
                    self._doTree(Extrud,"speed",csv_writer,0,i)
                    self._doTree(Extrud,"travel",csv_writer,0,i)
                    self._doTree(Extrud,"cooling",csv_writer,0,i)
                    # If single extruder doesn't export the data
                    if extruder_count>1 :
                        self._doTree(Extrud,"dual",csv_writer,0,i)
                        
                    self._doTree(Extrud,"support",csv_writer,0,i)
                    self._doTree(Extrud,"platform_adhesion",csv_writer,0,i)                   
                    self._doTree(Extrud,"meshfix",csv_writer,0,i)             
                    self._doTree(Extrud,"blackmagic",csv_writer,0,i)
                    self._doTree(Extrud,"experimental",csv_writer,0,i)
                    
                    # machine_settings
                    self._Section ="machine_settings"
                    # self._doTree(Extrud,"machine_nozzle_size",csv_writer,0,i)
                    
        except:
            Logger.logException("e", "Could not export profile to the selected file")
            return

        Message().hide()
        Message("Exported data for profil %s" % P_Name, title = "Import Export CSV Profiles Tools").show()