def __setObj(self, result): '''Crea un objeto tipo Conctact y lo retorna @param (obj) result @return (obj) contact''' myinspection = Inspection() myinspection.id_inspeccion = result.value(1) myinspection.id_vehiculo = result.value(2) myinspection.id_contacto = result.value(3) id_ciudad = result.value(4) myinspection.periodo = result.value(5) fecha = result.value(6) notas = result.value(7) registro = result.value(8) #verificamos los nulos devueltos por la consulta if isinstance(id_ciudad,QVariant): myinspection.id_ciudad = None if isinstance(notas, QVariant): myinspection.notas = None #se validan las fechas myinspection.registro = registro.toString() myinspection.fecha = fecha.toString() qDebug('[Debug] se crea un objeto tipo inspeccion validando los campos NULL') return myinspection
def __set_selected_vis_object_by_path(self, path): for vo in self._vis_objects: if vo.has_path(path): self.selected_vis_object = vo return else: qDebug("no vis object found for path: "+str(path))
def createProvider(self,provider): '''Crea un proveedor @param (obj) provider @return (bool) | (int) ''' values = { 'id_proveedor' : provider.id_proveedor, 'id_ciudad' : provider.id_ciudad, 'id_contacto' : provider.id_contacto, 'nombre' : provider.nombre, 'direccion' : provider.direccion, 'telefono' : provider.telefono, 'email' : provider.email, 'credito' : provider.credito, 'notas' : provider.notas } result = self.MyDb.insertQuery(self.table,values) if(result.numRowsAffected()>0): qDebug('[Debug] se crea un priveedor en la base de datos') return str(result.lastInsertId()) else: qDebug('[Debug] problemas para crear un proveedor de la base de datos') return False
def __setObj(self, result): '''Crea un objeto tipo Conctact y lo retorna @param (obj) result @return (obj) Buy''' mybuy = Buy() mybuy.id_compra = result.value(0) mybuy.id_inventario = result.value(1) mybuy.id_proveedor = result.value(2) mybuy.id_tecnico = result.value(3) mybuy.nro_factura = result.value(4) fecha = result.value(5) mybuy.cantidad = result.value(6) mybuy.costo = result.value(7) mybuy.notas = result.value(8) registro = result.value(9) #Se validan las variables nulas if isinstance(mybuy.notas,QVariant): mybuy.notas = None #se validan las fechas mybuy.fecha = fecha.toString('dd/MM/yyyy') mybuy.registro = registro.toString() qDebug('[Debug] se crea una venta validando los campos NULL y Fechas') return mybuy
def connect_camera(self): if self.use_gst: options = gstreamer_pipeline(cam_id=self.device_id, flip_method=self.flip_method) self.cap.open(options, self.api_preference) else: self.cap.open(self.device_id) # return false if failed to open camera if not self.cap.isOpened(): qDebug("Cannot open camera {}".format(self.device_id)) return False else: # try to set camera resolution if self.resolution is not None: width, height = self.resolution self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width) self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height) # some camera may become closed if the resolution is not supported if not self.cap.isOpened(): qDebug( "Resolution not supported by camera device: {}".format( self.resolution)) return False # use the default resolution else: width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) self.resolution = (width, height) return True
def __init__(self, parent, labelpixmap, labelid, labelsize, labelname, labeltext='', booltxt=False): super(TNLabel, self).__init__(parent) self.parent = parent # build picture if labelid is None and labelpixmap is None: # no cover : blank labelpixmap = QPixmap(PICM_NCO) booltxt = True elif labelid is not None: # extract picture labelpixmap, booltxt = self.extractCover(labelid) # resize if labelpixmap.width() != labelsize or labelpixmap.height( ) != labelsize: qDebug('resize picture') labelpixmap = labelpixmap.scaled(labelsize, labelsize, Qt.IgnoreAspectRatio, Qt.FastTransformation) # write text if booltxt: labelpixmap = self.writeText(labelpixmap, labelsize, labeltext) # label self.setPixmap(labelpixmap) self.setFixedSize(labelsize, labelsize) self.setStyleSheet("border: 2px solid white") self.Name = labelname
def convert_object_to_qjsvalue(obj, jsengine): """ Convert any python object into a QJSValue. The conversion must happen in the GUI thread. :param obj: :param jsengine: :return: """ if obj is None: return QJSValue() elif isinstance(obj, list) or isinstance(obj, tuple): length = len(obj) array = jsengine.newArray(length) for i, v in enumerate(obj): array.setProperty(i, convert_object_to_qjsvalue(v, jsengine)) return array elif isinstance(obj, dict): array = jsengine.newArray() for k, v in obj.items(): array.setProperty(k, convert_object_to_qjsvalue(v, jsengine)) return array else: try: return QJSValue(obj) except TypeError: qDebug("unknown type: "+str(obj)) return QJSValue()
def on_LoginBtn_clicked(self): self.LogInfo.emit("[MSG]Log in...\n") if self.session: self.session.close() self.seesion = None jaccount = self.Jaccount.text() password = self.Password.text() if (not jaccount) or (not password): return qDebug(jaccount) qDebug(password) self.session = login(url="https://oc.sjtu.edu.cn/login/openid_connect", parent=self, username=jaccount, password=password) if self.session: self.LogInfo.emit("[MSG]Log in Successfully!\n") loginInfo = {} if self.isSave.isChecked(): loginInfo['jaccount'] = jaccount loginInfo['password'] = password with open(os.path.join(self.log_dir, 'loginInfo.json'), 'w') as f: f.write(json.dumps(loginInfo)) else: self.LogInfo.emit("[ERROR]Log in Fail!\n")
def __load_next_core_app(self): if self.__app_candidates is None: core_apps_json = os.path.join(self.application_dir, "core_apps", "core_apps.json") self.__app_candidates = JsonList(core_apps_json) if self.__current_loading_core_app_index == len(self.__app_candidates): return core_app_name = self.__app_candidates[self.__current_loading_core_app_index] qDebug("load "+core_app_name) self.__current_loading_core_app_index += 1 core_app = self.__create_core_app(core_app_name) if core_app is not None: core_app.load() core_app.completed.connect(self.__continue_loading_apps) self.core_app_loaded.emit(core_app) # set really special core apps if core_app.name == "Home": self.home = core_app elif core_app.name == "Desk": self.desk = core_app elif core_app.name == "Settings": self.settings = core_app else: raise Exception("Could not load "+core_app_name)
def convert_object_to_qjsvalue(obj, jsengine): """ Convert any python object into a QJSValue. The conversion must happen in the GUI thread. :param obj: :param jsengine: :return: """ if obj is None: return QJSValue() elif isinstance(obj, list) or isinstance(obj, tuple): length = len(obj) array = jsengine.newArray(length) for i, v in enumerate(obj): array.setProperty(i, convert_object_to_qjsvalue(v, jsengine)) return array elif isinstance(obj, dict): array = jsengine.newArray() for k, v in obj.items(): array.setProperty(k, convert_object_to_qjsvalue(v, jsengine)) return array else: try: return QJSValue(obj) except TypeError: qDebug("unknown type: " + str(obj)) return QJSValue()
def addView(self, view: View, forceRangeReset=None): qDebug(f'Adding {view.renderer.name}') if forceRangeReset is not None: rangeReset = forceRangeReset else: if len(self.main_window.model.panels) == 1: rangeReset = not (bool(self.vbs)) else: rangeReset = False ax, vb = view.renderer.render(self) self.main_window.joinGroup(view) self.axes[view] = ax self.vbs[view] = vb self.updateWidestAxis() self.updateViews() if view.show is False: self.hideView(view) self.axis_bottom.show() # this fixes the bottom axis mirroring on macOS old_size = self.size() self.resize(QtCore.QSize(old_size.width() + 1, old_size.height())) self.resize(old_size) self.layout.update() if rangeReset: self.main_window.zoomFit()
def _start_pid(self): self.task.start() self.running = True i = 0 while self._running: self._input = self.get_volt() error = (self._volt - self._target) if self._inverse: error = -error self._output = self.step(error) if self._output > 100.: self._output = 100. self.running = False if self._output < 0.: self._output = 0. self.running = False self.laser.set_volt(self._output) if i % 5 is 0: self.inputChanged.emit() self.outputChanged.emit() qDebug("%.3f V" % volt) self.task.StopTask() qDebug("stopped") self.inputChanged.emit() self.outputChanged.emit()
def invoke_xyz(self, method_name, x, y, z, x_type=None, y_type=None, z_type=None, connection=Qt.QueuedConnection): if x_type is None: arg_x = Q_ARG(type(x), x) else: arg_x = Q_ARG(x_type, x) if x_type is None: arg_y = Q_ARG(type(y), y) else: arg_y = Q_ARG(y_type, y) if x_type is None: arg_z = Q_ARG(type(z), z) else: arg_z = Q_ARG(z_type, z) try: self._methods[method_name].invoke(self._object, connection, arg_x, arg_y, arg_z) except KeyError: qDebug("no method " + str(method_name) + " found in " + str(self._object)) qDebug("methods: " + str(self._methods))
def updateProvider(self, oldProvider, provider): '''Actualiza un proveedor @param (obj) tipo proveedor @param (obj) tipo proveedor @return (bool) ''' condition = {' id_proveedor = ' : str(oldProvider.id_proveedor)} values = { 'id_ciudad' : provider.id_ciudad, 'id_contacto' : provider.id_contacto, 'nombre' : provider.nombre, 'direccion' : provider.direccion, 'telefono' : provider.telefono, 'email' : provider.email, 'credito' : provider.credito, 'notas' : provider.notas, 'registro' : provider.registro } result = self.MyDb.updateQuery(self.table,values) if(result.numRowsAffected()>0): qDebug('[Debug] se Actualiza un priveedor en la base de datos') return True else: qDebug('[Debug] problemas para Actualizar un priveedor en la base de datos') return False
def stopProcessingThread(self): qDebug("[%s] About to stop processing thread..." % self.deviceUrl) self.processingThread.stop() self.sharedImageBuffer.wakeAll( ) # This allows the thread to be stopped if it is in a wait-state self.processingThread.wait() qDebug("[%s] Processing thread successfully stopped." % self.deviceUrl)
def __init__(self, parent=None): super(Window, self).__init__(parent) # a figure instance to plot on self.figure = plt.figure() # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init__ self.canvas = FigureCanvas(self.figure) # this is the Navigation widget # it takes the Canvas widget and a parent self.toolbar = NavigationToolbar(self.canvas, self) d = "test" + str("dss") qDebug(d) # Just some button connected to `plot` method self.button = QPushButton('Plot') self.button.clicked.connect(self.plot) # set the layout layout = QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) layout.addWidget(self.button) self.setLayout(layout)
def parseProfileList(shortGameName: str): # the profile list is stored in Roaming/zEdit/profiles.json result = [] gameMode = ZEditConfig.getZEditGameMode(shortGameName) if gameMode is None: qWarning("Game type is not supported by zMerge.") return result appData = QDir( QStandardPaths.writableLocation(QStandardPaths.AppDataLocation)) profilesPath = appData.absoluteFilePath( ZEditConfig.RELATIVE_ZEDIT_PROFILES_FILE) if not appData.exists(ZEditConfig.RELATIVE_ZEDIT_PROFILES_FILE): qDebug('"{}" does not exist'.format(profilesPath)) return result try: file = open(profilesPath, "r", encoding="utf8") profiles = json.load(file) for profile in profiles: if profile["gameMode"] == gameMode: result.append(profile["name"]) except OSError: qWarning('Failed to read "profiles.json".') return [] except (TypeError, ValueError): qWarning('"profiles.json" has unknown file structure.') return result
def on_view_visibility_changed(self, visible: bool): dock_widget = self.sender() if dock_widget is None: return qDebug("{} visibility_changed({})".format(dock_widget.objectName(), visible))
def __init__(self, **kwargs): super().__init__(**kwargs) self.camera = None self.clip_size = None self.ndarray_available.connect(self.clip_array) self.ndarray_available.connect(self.convert_to_grayscale) self.plugin_loader = PluginLoader() self.plugins = self.plugin_loader.plugins for plugin in self.plugins: try: plugin.message.connect(self.message) except: qDebug("Cannot connect to messages from {}".format(plugin.getName())) self.ndarray_available.connect(self.plugin_loader.ndarray_available) self.ndarray_bw_available.connect(self.plugin_loader.ndarray_bw_available) self.clipped_ndarray_available.connect(self.plugin_loader.clipped_ndarray_available) self.clipped_ndarray_bw_available.connect(self.plugin_loader.clipped_ndarray_bw_available) self.data_saver = DataSaver() self.ndarray_bw_available.connect(self.data_saver.set_array) self.save_file.connect(self.data_saver.save_image) self.data_saver.message.connect(self.message) # this limits the global frame rate in this program: self.last_frame_time = time.time() self.frame_interval = 0.1
def __setObj(self,result): '''Crea un objeto tipo repair @return (obj) repair ''' myrepair = Repair() myrepair.id_reparacion = result.value(0) myrepair.id_viaje = result.value(1) myrepair.id_vehiculo = result.value(2) myrepair.id_ciudad = result.value(3) myrepair.periodo = result.value(4) myrepair.kilometros = result.value(5) fecha_entrada = result.value(6) fecha_salida = result.value(7) myrepair.notas = result.value(8) registro = result.value(9) #validamos los campos nulos if isinstance(myrepair.id_ciudad,QVariant): myrepair.id_ciudad = None if isinstance(myrepair.notas,QVariant): myrepair.notas = None #Se Validan las Fechas myrepair.fecha_entrada = fecha_entrada.toString() myrepair.fecha_salida = fecha_salida.toString() myrepair.registro = registro.toString() qDebug('Se crea una reparacion validados los campos nulos') return myrepair
def _handleDBObjects(self): """ Compares the existing tables in the database with the registered objects and adds tables and columns for any changes. If dangerousMode is set then redundant tables and columns will be deleted """ existingDBModel = self._constructDBModel() newModel = QSqlUpgradeManager._DBObjects existingDBTables = set(existingDBModel.keys()) newTables = set(newModel.keys()) # Create new tables for tableName in newTables.difference(existingDBTables): schema = newModel[tableName] self._query.CreateTable(tableName, schema) qDebug("Created new table " + tableName) # Update tables for tableName in existingDBTables.intersection(newTables): existingSchema = existingDBModel[tableName] newSchema = newModel[tableName] if existingSchema != newSchema: self._handleNewColumns(tableName, existingSchema, newSchema) # Remove any redundant tables if dangerousMode is on if self._dangerousMode: for tableName in existingDBTables.difference(newTables): self._query.DropTable(tableName) qDebug("Dropped table " + tableName)
def createRepair(self, repair): ''''Crea una reparacion @param (obj) Repair @return (bool) | (int)''' values = { 'id_reparacion' : repair.id_reparacion, 'id_viaje' : repair.id_viaje, 'id_vehiculo' : repair.id_vehiculo, 'id_ciudad' : repair.id_ciudad, 'periodo' : repair.periodo, 'kilometros' : repair.kilometros, 'fecha_salida' : repair.fecha_salida, 'fecha_entrada' : repair.fecha_entrada, 'notas' : repair.notas } result = self.MyDb.insertQuery(self.table, values) if(result.numRowsAffected()>0): qDebug('[Debug] se crea una reparacion') return str(result.lastInsertId()) else: qDebug('[Debug] No se crea una reparacion') return False
def updateRepair(self,oldRepair,repair): '''Actualiza una reparacion @param (obj) repair @param (obj) repair @return (bool) ''' condition = {' id_reparacion = ' : str(oldRepair.id_reparacion)} values = { 'id_viaje' : repair.id_viaje, 'id_vehiculo' : repair.id_vehiculo, 'id_ciudad' : repair.id_ciudad, 'periodo' : repair.periodo, 'kilometros' : repair.kilometros, 'fecha_salida' : repair.fecha_salida, 'fecha_entrada' : repair.fecha_entrada, 'notas' : repair.notas } result = self.MyDb.updateQuery(self.table,values,condition) if(result.numRowsAffected()>0): qDebug('[Debug] se Actualiza una reparacion') return True else: qDebug('[Debug] No se Actualiza una reparacion') return False
def sort_dicts(self): ''' Creates a tree according to dakota specs from parsed dict_list :return: ''' # run one time to setup top structure list # ======================================== for block_dict in self.parsed_dicts_list: for key in block_dict: self.blocks_key_list.append(key) if self.is_top_node(key): block_dict[key] = OrderedDict() self.sorted_blocks.append(block_dict) # create key-path dict for the rest # ================================= # print(self.find_key_path(self.dakota_specs, 'sampling')[0]) for block_dict in self.parsed_dicts_list: for key in block_dict: key_path = self.find_key_path(self.dakota_specs, key)[0] value = block_dict[key] if len(key_path) != 0: self.__create_dict(self.sorted_blocks, key_path, key, value) else: self.unknown_keyword(key, value) qDebug("Unknown keyword "+key)
def __setObj(self, result): '''Crea un objeto tipo inventary y lo retorna @param (obj) result @return (obj) inventary''' myinventary = Inventary() myinventary.id_inventario = result.value(0) fecha = result.value(1) myinventary.nombre = result.value(2) myinventary.descripcion = result.value(3) myinventary.unidad = result.value(4) myinventary.stok_min = result.value(5) myinventary.marca = result.value(6) myinventary.ubicacion = result.value(7) myinventary.notas = result.value(8) registro = result.value(9) #se validan los campos con null if isinstance(myinventary.marca, QVariant): myinventary.marca = None if isinstance(myinventary.notas, QVariant): myinventary.notas = None #Se validan las fechas myinventary.fecha = fecha.toString() myinventary.registro = registro.toString() qDebug('[Debug] se crea un objeto inventario validado los campos NULL') return myinventary
def updatePlatform(self): qDebug('updatePlatform()') #* Platform Model if self.platformModel: self.platformModel.SetXLength(self.platformWidth) self.platformModel.SetYLength(self.platformDepth) self.platformModel.SetZLength(self.platformThickness) self.platformModel.SetCenter(0.0, 0.0, -self.platformThickness / 2) #* Platform Grid gridPoints = vtk.vtkPoints() gridCells = vtk.vtkCellArray() i = -self.platformWidth / 2 while i <= self.platformWidth / 2: self.createLine(i, -self.platformDepth / 2, self.gridBottomHeight, i, self.platformDepth / 2, self.gridBottomHeight, gridPoints, gridCells) i += self.gridSize i = -self.platformDepth / 2 while i <= self.platformDepth / 2: self.createLine(-self.platformWidth / 2, i, self.gridBottomHeight, self.platformWidth / 2, i, self.gridBottomHeight, gridPoints, gridCells) i += self.gridSize self.platformGrid.SetPoints(gridPoints) self.platformGrid.SetLines(gridCells)
def getProfiles(shortGameName, zEditInstallFolder) -> List[Merges]: """ This returns the content of each profiles 'merges.json' """ result = [] zEditProfileDir = QDir(zEditInstallFolder + "/" + ZEditConfig.RELATIVE_PROFILE_DIR) if not zEditProfileDir.exists(): qDebug("Profiles path does not exist: {}".format( zEditProfileDir.absolutePath())) return result profiles = ZEditConfig.parseProfileList(shortGameName) for name in profiles: relName = name + "/merges.json" if not zEditProfileDir.exists(relName): continue try: filePath = zEditProfileDir.absoluteFilePath(relName) with open(filePath) as f: m = Merges(json.load(f)) m.profileName = name m.profilePath = filePath result.append(m) except ValueError as ex: qWarning('Invalid file "{}": {}'.format(filePath, str(ex))) return result
def __load_next_core_app(self): if self.__app_candidates is None: core_apps_json = os.path.join(self.application_dir, "core_apps", "core_apps.json") self.__app_candidates = JsonList(core_apps_json) if self.__current_loading_core_app_index == len(self.__app_candidates): return core_app_name = self.__app_candidates[ self.__current_loading_core_app_index] qDebug("load " + core_app_name) self.__current_loading_core_app_index += 1 core_app = self.__create_core_app(core_app_name) if core_app is not None: core_app.load() core_app.completed.connect(self.__continue_loading_apps) self.core_app_loaded.emit(core_app) # set really special core apps if core_app.name == "Home": self.home = core_app elif core_app.name == "Desk": self.desk = core_app elif core_app.name == "Settings": self.settings = core_app else: raise Exception("Could not load " + core_app_name)
def loadStamps(self): prefs = preferences.Preferences.instance() stampsDirectory = prefs.stampsDirectory() stampsDir = QDir(stampsDirectory) iterator = QDirIterator(stampsDirectory, ["*.stamp"], QDir.Files | QDir.Readable) while (iterator.hasNext()): stampFileName = iterator.next() stampFile = QFile(stampFileName) if (not stampFile.open(QIODevice.ReadOnly)): continue data = stampFile.readAll() document = QJsonDocument.fromBinaryData(data) if (document.isNull()): # document not valid binary data, maybe it's an JSON text file error = QJsonParseError() document = QJsonDocument.fromJson(data, error) if (error.error != QJsonParseError.NoError): qDebug("Failed to parse stamp file:" + error.errorString()) continue stamp = TileStamp.fromJson(document.object(), stampsDir) if (stamp.isEmpty()): continue stamp.setFileName(iterator.fileInfo().fileName()) self.mTileStampModel.addStamp(stamp) index = stamp.quickStampIndex() if (index >= 0 and index < self.mQuickStamps.size()): self.mQuickStamps[index] = stamp
def updateVehicle(self,old_vehicle,vehicle): '''Actualiza un vehiculo @param (obj) vehicle @param (obj) vehicle @return (boo) ''' condition = {' id_vehiculo = ' : str(old_vehicle.id_vehiculo)} values = { 'id_vehiculo' : vehicle.id_vehiculo, 'id_cliente' : vehicle.id_cliente, 'id_contacto' : vehicle.id_contacto, 'id_ciudad' : vehicle.id_ciudad, 'modelo' : vehicle.modelo, 'nro_motor' : vehicle.nro_motor, 'ingreso' : vehicle.ingreso, 'notas' : vehicle.notas } result = self.MyDb.updateQuery(self.table,values,condition) if (result.numRowsAffected() > 0): qDebug('[Debug] se Actualiza un vehiculo a la tabla') return True else: qDebug('[Debug] problemas para actualizar un vehiculo a la tabla') return False
def initPlatform(self): qDebug('initPlatform()') #* Platform Model platformModelMapper = vtk.vtkPolyDataMapper() self.platformModel = vtk.vtkCubeSource() platformModelMapper.SetInputConnection( self.platformModel.GetOutputPort()) self.platformModelActor = vtk.vtkActor() self.platformModelActor.SetMapper(platformModelMapper) self.platformModelActor.GetProperty().SetColor(1, 1, 1) self.platformModelActor.GetProperty().LightingOn() self.platformModelActor.GetProperty().SetOpacity(1) self.platformModelActor.GetProperty().SetAmbient(0.45) self.platformModelActor.GetProperty().SetDiffuse(0.4) self.platformModelActor.PickableOff() self.renderer.AddActor(self.platformModelActor) #* Platform Grid self.platformGrid = vtk.vtkPolyData() platformGridMapper = vtk.vtkPolyDataMapper() platformGridMapper.SetInputData(self.platformGrid) self.platformGridActor = vtk.vtkActor() self.platformGridActor.SetMapper(platformGridMapper) self.platformGridActor.GetProperty().LightingOff() self.platformGridActor.GetProperty().SetColor(0.45, 0.45, 0.45) self.platformGridActor.GetProperty().SetOpacity(1) self.platformGridActor.PickableOff() self.renderer.AddActor(self.platformGridActor) self.updatePlatform()
def arrayCardsToSql(self, operation, arraydata, tablename, columnnamekey): listcolumns = self.getListColumnsTable(tablename) if len(listcolumns) == 0: qDebug(tablename) return False numberscolumns = len(listcolumns) if operation == 'INSERT': # build query insert request = 'INSERT INTO ' + tablename + '(' request += ', '.join('`{0}`'.format(w) for w in listcolumns) + ') VALUES ' request += '(' + ', '.join( ['?'] * numberscolumns) +')' elif operation == 'UPDATE': # build query update listcolumns.remove(columnnamekey) numberscolumns = len(listcolumns) request = 'UPDATE ' + tablename + ' SET ' request += '= ?, '.join('`{0}`'.format(w) for w in listcolumns) + '= ? ' request += ' WHERE ' + columnnamekey + ' = ? ;' else: qDebug(operation) return False # repeat query insert if isinstance(arraydata, list): # multi card for row in arraydata: if not self.arrayCardToSql(operation, row, columnnamekey, request, listcolumns): return False else: # one card if not self.arrayCardToSql(operation, arraydata, columnnamekey, request, listcolumns): return False return True
def addBook(self, book: Book): query = QSqlQuery() query.prepare(''' INSERT INTO books (book_id, title, author, publisher, genre_id, year, summary, price) SELECT NULL, :title, :author, :editor, genre_id, :year, :summary, :price FROM genres WHERE genres.genre = :genre ''') query.bindValue(":title", book.title) query.bindValue(":author", book.author) query.bindValue(":editor", book.editor) query.bindValue(":genre", book.genre) query.bindValue(":year", book.year) query.bindValue(":summary", book.summary) query.bindValue(":price", book.price) query.exec_() qDebug(query.lastError().text()) id_book = query.lastInsertId() book = Book(id_book, *book[1:]) indexBook = len(self.books) self.beginInsertRows(QModelIndex(), indexBook, indexBook) self.books.append(book) self.endInsertRows()
def __init__(self, but_img): super().__init__() self.pos_x = None self.pos_y = None self.flag = True self.min = 1 self.max = 8 self.isAnimation = False self.isWin = False pixmap = QPixmap() ret = pixmap.load(but_img) if not ret: qDebug(f"{but_img}加载失败") self.setFixedSize(pixmap.width(), pixmap.height()) self.setStyleSheet("QPushButton{border:0px;}") self.setIcon(QIcon(pixmap)) self.setIconSize(pixmap.size()) # 监听正面翻转的信号槽 self.timer1 = QTimer() self.timer1.timeout.connect(self.timer1_slot) self.timer2 = QTimer() self.timer2.timeout.connect(self.timer2_slot)
def updateInvoice(self,oldInvoice,invoice): '''Actualiza una factura @param (obj) invoice @param (obj) invoice @return (bool) ''' condition = {' id_factura = ' : str(oldInvoice.id_factura)} values = { 'id_factura' : invoice.id_factura, 'id_cliente' : invoice.id_cliente, 'id_contacto' : invoice.id_contacto, 'fecha' : invoice.fecha, 'fecha_envio' : invoice.fecha_envio, 'guia_envio' : invoice.guia_envio, 'servicio_envio' : invoice.servicio_envio, 'estado' : invoice.estado, 'archivo' : invoice.archivo, 'notas' : invoice.notas } result = self.MyDb.updateQuery(self.table,values,condition) if (result.numRowsAffected() > 0): qDebug('[Debug] Se actualiza una factura') return True else: qDebug('[Debug] No se actualiza una factura') return False
def createInvoice(self,invoice): '''Crea una factura @param (obj) Invoice @return (obj) | (int) ''' values = { 'id_factura' : invoice.id_factura, 'id_cliente' : invoice.id_cliente, 'id_contacto' : invoice.id_contacto, 'fecha' : invoice.fecha, 'fecha_envio' : invoice.fecha_envio, 'guia_envio' : invoice.guia_envio, 'servicio_envio' : invoice.servicio_envio, 'estado' : invoice.estado, 'archivo' : invoice.archivo, 'notas' : invoice.notas } result = self.MyDb.insertQuery(self.table,values) if (result.numRowsAffected() > 0): qDebug('[Debug] se Crea una factura') return result.lastInsertId() else: qDebug('[Debug] No se Crea una factura') return False
def parseBSOld(s: str): try: rows = [] for l in s.split('\n'): l = l.strip().strip("{}") if not l or not l.startswith("BS"): continue if l.startswith("BS-map"): continue count = int(l[2]) row = l.split("|")[1:] i = 0 while i < len(row): if row[i].startswith("O") and i > 0: x = row[i].split('=')[1] row[i - 1] = row[i - 1] + [x] if isinstance( row[i - 1], list) else [row[i - 1], x] row = row[:i] + row[i + 1:] else: i = i + 1 if len(row) > count: row[count - 1] = ' '.join(row[count:]).strip() row = row[:count] rows.append(row) return rows except Exception as e: qDebug('parse {}'.format(e).encode('utf-8')) return []
def btnClk(self, btn): '''copy selected color-scheme to kdeglobals or close''' if btn == self.buttonBox.button(QDialogButtonBox.Apply): qDebug("apply") if self.comboBox.currentText() != "None": for f in self.files: s = QSettings(self.schemeDir + f, QSettings.NativeFormat) if (s.value("ColorScheme") == self.comboBox.currentText()): copyfile(self.schemeDir + f, self.confFile) else: os.remove(self.confFile) if self.horizontalSlider.value != self.checkTransparency(): settings = QSettings(str(self.rcFile), QSettings.NativeFormat) settings.beginGroup("Style") settings.setValue("MenuOpacity", self.horizontalSlider.value()) filename = self.bindir + '/breeze-config' print(filename) # subprocess.Popen(filename) subprocess.Popen([ filename, '--data-dir', self.datadir, '--bin-dir', self.bindir ]) sys.exit(0) elif btn == self.buttonBox.button(QDialogButtonBox.Close): exit(0)
def __make_app_instance(self, package, instance_name, status=BasicApp.IDLE): """ Creates and loads an instance of the app as given by package. This method can be called from another than this thread. Hence the parent of the app (this desk), is not set in the constructor but later, after the app is moved to this thread. Only then the load method of the app is called. :param package: :param instance_name: :param status: :return: BasicApp """ class_object = self.__get_app_class(package) if class_object is None: return None try: app = class_object(None, instance_name, status) except: # any exception might happen here from traceback import format_exc exc = format_exc() qDebug(exc) return None self.__loaded_app_instances[instance_name] = app app.moveToThread(self.thread()) app.setParent(self) app.load_internal() app.load() return app
def __setObj(self, result): '''Crea un objeto tipo Maintenance y lo retorna @param (obj) result @return (obj) Maintenance''' mymaintenance = Maintenance() mymaintenance.id_mantenimiento = result.value(0) mymaintenance.id_viaje = result.value(1) mymaintenance.id_vehiculo = result.value(2) mymaintenance.id_ciudad = result.value(3) mymaintenance.periodo = result.value(4) fecha = result.value(5) mymaintenance.kilometros = result.value(6) mymaintenance.notas = result.value(7) registro = result.value(8) #Se validan los campos NULL if isinstance(mymaintenance.id_ciudad,QVariant): mymaintenance.id_ciudad = None if isinstance(mymaintenance.notas,QVariant): mymaintenance.notas = None #validamos las fechas mymaintenance.fecha = fecha.toString() mymaintenance.registro = registro.toString() qDebug('[Debug] se crea un objeto Maintenance validando los campos NULL') return mymaintenance
def updateMaintenance(self,oldMaintenance, maintenance): '''Actualiza un mantenimiento @param (obj) maintenance @param (obj) maintenance @return (bool) ''' values = { 'id_vehiculo': maintenance.id_vehiculo, 'id_ciudad': maintenance.id_ciudad, 'periodo': maintenance.periodo, 'fecha': maintenance.fecha, 'kilometros': maintenance.kilometros, 'notas': maintenance.notas } condition = {' id_mantenimiento = ' : str(oldMaintenance.id_mantenimiento)} result = self.MyDb.updateQuery(self.table,values,condition) if(result.numRowsAffected()>0): qDebug('[Debug] Se actualiza un mantenimiento en la base') return True else: qDebug('[Debug] No se Actualiza un mantenimiento en la base') return False
def __setObj(self, result): '''crea un objeto tipo tecnicos @param result @return objeto tipo technical''' mytechnical = Technical() mytechnical.id_tecnico = result.value(0) mytechnical.nombres = result.value(1) mytechnical.telefono = result.value(2) mytechnical.celular = result.value(3) mytechnical.email = result.value(4) mytechnical.notas = result.value(5) registro = result.value(6) #verificamos los nulos devueltos por la consulta if isinstance(mytechnical.telefono, QVariant): mytechnical.telefono = None if isinstance(mytechnical.celular, QVariant): mytechnical.celular = None if isinstance(mytechnical.email, QVariant): mytechnical.email = None if isinstance(mytechnical.notas, QVariant): mytechnical.notas = None #se validan las fechas mytechnical.registro = registro.toString() qDebug('[Debug] Se crea un objeto typo tecnico validando los campos tipo null ') return mytechnical
def setup(self): """ This is where most of the setup takes place! """ qDebug("Hello Setup") action = Krita.instance().createAction("hello_python", "hello") action.triggered.connect(hello)
def paintGL(self): qDebug("paintGL()") gl = QOpenGLContext.currentContext().versionFunctions(glVersionProfile) vaoBinder = QOpenGLVertexArrayObject.Binder(self.vao) # Draw checkerboard so transparency is obvious self.transparecyProgram.bind() if self.backgroundColour and self.backgroundColour.isValid(): self.transparecyProgram.setUniformValue("backgroundColour", self.backgroundColour) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6) self.transparecyProgram.release() self.program.bind() if self.texture: self.texture.bind() gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6) if self.texture: self.texture.release() self.program.release()
def __setObj(self, result): '''crea un objeto tipo tecnicos @param result @return objeto tipo technical''' myMaintenanceItem = MaintenanceItem() myMaintenanceItem.id_mantenimiento_detalle = result.value(0) myMaintenanceItem.id_mantenimiento = result.value(1) myMaintenanceItem.id_inventario = result.value(2) fecha = result.value(3) myMaintenanceItem.estado = result.value(4) myMaintenanceItem.cantidad = result.value(5) myMaintenanceItem.notas = result.value(6) registro = result.value(7) #verificamos los nulos devueltos por la consulta if isinstance(myMaintenanceItem.notas, QVariant): myMaintenanceItem.notas = None #Validamos las fechas myMaintenanceItem.fecha = fecha.toString() myMaintenanceItem.registro = registro.toString() qDebug('[Debug] Se crea un objeto typo tecnico validando los campos tipo null ') return mytechnical
def PickFile(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog self.loadFileName = QFileDialog.getOpenFileName( self.dlg, 'Open File', "") qDebug(str(self.loadFileName[0])) self.LoadSkeleton(str(self.loadFileName[0]))
def __setObj(self, result): '''Crea un objeto tipo Conctact y lo retorna @param (obj) result @return (obj) contact''' mycontact = Contact() mycontact.id_contacto = result.value(0) mycontact.id_ciudad = result.value(1) mycontact.nombre = result.value(2) mycontact.telefono = result.value(3) mycontact.celular = result.value(4) mycontact.email = result.value(5) mycontact.notas = result.value(6) registro = result.value(7) #Se validan las variables nulas if isinstance(mycontact.id_ciudad,QVariant): mycontact.id_ciudad = None if isinstance(mycontact.telefono,QVariant): mycontact.telefono = None if isinstance(mycontact.celular,QVariant): mycontact.celular = None if isinstance(mycontact.email,QVariant): mycontact.email = None if isinstance(mycontact.notas,QVariant): mycontact.notas = None mycontact.registro = registro.toString() qDebug('[Se crea un objeto contacto validando los campos NULL]') return mycontact
def __init__(self, parent=None): QWidget.__init__(self, parent) self.setWindowTitle('Local watcher') self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) # media content self.screen = app.primaryScreen() self.mediaPLayer = QMediaPlayer() url = QUrl.fromLocalFile(QFileInfo("D:\\1.mp3").absoluteFilePath()) qDebug(QDir.currentPath()) content = QMediaContent(url) self.mediaPLayer.setMedia(content) self.mediaPLayer.setVolume(50) ## self.rect = {'x': 424, 'y': 42, 'w': 88, 'h': 400} ## Settings self.initUi() self.timer = QTimer() self.timer.timeout.connect(self.onTimer) self.timer.start(300)
def __setObj(self,result): '''Crea un objeto tipo repairItem @return (repairItem)''' myrepairItem = repairItem() myrepairItem.id_reparacion_detalle = result.value(0) myrepairItem.id_reparacion = result.value(1) myrepairItem.id_inventario = result.value(2) fecha = result.value(3) myrepairItem.estado = result.value(4) myrepairItem.cantidad = result.value(5) myrepairItem.notas = result.value(6) registro = result.value(7) #validamos los campos null if isinstance(myrepairItem.estado, QVariant): myrepairItem.estado = None if isinstance(myrepairItem.notas, QVariant): myrepairItem.notas = None #Validamos las fechas myrepairItem.fecha = fecha.toString() myrepairItem.registro = registro.toString() qDebug('[Debug] Se crea un item de reparacion validados los campos NULL') return myrepairItem
def initializeExistingGeoreferencing(self, dataset, georef): # georef can have scaling, rotation or translation rotation = 180 / math.pi * -math.atan2(georef[4], georef[1]) sx = math.sqrt(georef[1] ** 2 + georef[4] ** 2) sy = math.sqrt(georef[2] ** 2 + georef[5] ** 2) i_center_x = self.image.width() / 2 i_center_y = self.image.height() / 2 center = QgsPointXY(georef[0] + georef[1] * i_center_x + georef[2] * i_center_y, georef[3] + georef[4] * i_center_x + georef[5] * i_center_y) qDebug(repr(rotation) + " " + repr((sx, sy)) + " " + repr(center)) self.setRotation(rotation) self.setCenter(center) # keep yScale positive self.setScale(sx, sy) self.commitTransformParameters() crs_wkt = dataset.GetProjection() message_shown = False if crs_wkt: qcrs = QgsCoordinateReferenceSystem(crs_wkt) if qcrs != self.crs(): # reproject try: self.reprojectTransformParameters(qcrs, self.crs()) self.commitTransformParameters() self.showBarMessage( "Transform parameters changed", "Found existing georeferencing in raster but " "its CRS does not match the CRS of the map. " "Reprojected the extent.", Qgis.Warning, 5) message_shown = True except Exception as ex: QgsMessageLog.logMessage(repr(ex)) self.showBarMessage( "CRS does not match", "Found existing georeferencing in raster but " "its CRS does not match the CRS of the map. " "Unable to reproject.", Qgis.Warning, 5) message_shown = True # if no projection info, assume it is the same CRS # as the map and no warning if not message_shown: self.showBarMessage( "Georeferencing loaded", "Found existing georeferencing in raster", Qgis.Info, 3) # zoom (assume the user wants to work on the image) self.iface.mapCanvas().setExtent(self.extent())
def remove_vis_object(self, vo): try: self._vis_objects.remove(vo) self.vis_objects_changed.emit() self.__update_vis_objects_tree() self.camera.update() except ValueError: qDebug("removing "+str(vo)+" which is not in vis_objects")
def _onItemSelectionChanged(self): itemText = self._twMenu.selectedItems()[0].text(0) if itemText == "Plugins": qDebug("update pluginspage") self._pluginsPage.update(helper.getPlugins()) elif itemText == "Install": qDebug("update installpage") self._installPage.update(helper.getPlugins())
def __init__(self): '''Instancializacion de la clase creamos el objeto MyDb creamos la variable con el nombre de la tabla ''' super(stateCatalog, self).__init__() self.table = 'provincia' self.MyDb = DB() qDebug('[Debug] se instancia la clase stateCatalog')
def __setObj(self,result): '''coloca las propiedades de un estado @return (obj) estado''' mystate = State() mystate.id_provincia = str(result.value(0)) mystate.nombre = str(result.value(1)) qDebug('[Debug] se crea un objeto tipo estado validando los NULL') return mystate
def send_qml_signal(self, name, arguments=()): if name in self._qml_callbacks: for cb in self._qml_callbacks[name]: try: cb.call([convert_object_to_qjsvalue(arg, self.dice.qml_engine) for arg in arguments]) except BaseException as e: qDebug("Could not send signal "+str(name)+"::"+str(arguments)) self.dice.process_exception(e)