def newPage(self): #print("newPage") self.flagPage = True self.flagNormal = False self.paint = Paint(self) self.paint.setSceneRect(0,0,0,0) self.tabWidget.addTab(self.paint,"Page "+str(self.tabWidget.count()+1))
def __init__(self): super(Aplikacja, self).__init__() self.interfejs() self.paint = Paint(self.predict) self.paint.show() self.loaded_model = 0
def init_UI(self): self.paint = Paint() self.ui.layout.addWidget(self.paint) self.ui.put_points.clicked.connect(self.put_points) self.ui.put_clusters.clicked.connect(self.put_clusters) self.ui.clear.clicked.connect(self.clear) self.ui.calculation.clicked.connect(self.calculation) self.ui.step.clicked.connect(self.step) self.ui.comboBox.addItems(['Euclid', 'Chebyshev']) self.ui.comboBox.activated.connect(self.select_mode)
def test_rectangle(self): picture = Paint(15, 10) expected = """----------------- | xxxxx | | x x | | xxxxx | | | | | | | | | | | | | | | -----------------""" picture.rectangle(13, 1, 9, 3) self.assertEqual(str(picture.draw_me()), expected)
def semiSegCanvas(): try: imagemNomeConservado = ed.get() formato = imagemNomeConservado.split(".") try: if (formato[1] != 'png'): img = cv2.imread(imagemNomeConservado) cv2.imwrite(formato[0] + ".png", img, [cv2.IMWRITE_PNG_COMPRESSION]) imagemNomeConservado = formato[0] + ".png" Paint(imagemNomeConservado) except (IndexError): lb = Label(window, text="IMAGEM NAO ENCONTRADA OU DE FORMATO INVALIDO") lb.pack() return 0 except (TclError): lb = Label(window, text="IMAGEM NAO ENCONTRADA OU DE FORMATO INVALIDO") lb.pack() return 0
def run_programm(): #Инициализация модулей pygame, создание экземпляра Settings и создание объекта экрана pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) screen.fill(ai_settings.bg_color) pygame.display.set_caption('Классификатор рукописных цифр') #Создание экземпляров InfoBoard и Paint infob = InfoBoard(screen, ai_settings) paint = Paint(screen, ai_settings, infob) #Фиксируем fps clock = pygame.time.Clock() fps = 60 #Запуск основного цикла классификатора while True: clock.tick(fps) #Отображения доски рисования paint.blit_bb() #Вывод основной информации классификатора infob.show_info() #Отслеживание событий мыши и клавиатуры paint.check_event() #Обновление экрана pygame.display.flip()
def __init__(self): super().__init__() paint = Paint(300, 300) paint.setPenWidth(5) paint.setPenColor('#EB5160') self.setCentralWidget(paint)
class TestLine(unittest.TestCase): picture = Paint(15, 10) def test_borders(self): expected = """----------------- | | | | | | | | | | | | | | | | | | | | -----------------""" self.assertEqual(str(self.picture.draw_me()), expected) def test_horizontal(self): expected = """----------------- | | | xxxxx | | | | | | | | | | | | | | | | | -----------------""" self.picture.line(2, 2, 6, 2) self.assertEqual(str(self.picture.draw_me()), expected) def test_vertical(self): expected = """----------------- | | | xxxxx | | x | | x | | | | | | | | | | | | | -----------------""" self.picture.line(4, 3, 4, 4) self.assertEqual(str(self.picture.draw_me()), expected)
def test_floodfill(self): picture = Paint(15, 10) expected = """----------------- |ooooooooxxxxxoo| |oooooooox xoo| |ooooooooxxxxxoo| |ooooooooooooooo| |ooooooooooooooo| |ooooooooooooooo| |ooooooooooooooo| |ooooooooooooooo| |ooooooooooooooo| |ooooooooooooooo| -----------------""" picture.rectangle(13, 1, 9, 3) picture.bucket_fill(1, 9, "o") self.assertEqual(str(picture.draw_me()), expected)
def draw(self, input_file="input.txt", output_file="output.txt"): inp = [] with open(input_file, "r") as f: raw_input = [row.strip() for row in f] for raw in raw_input: inp.append(raw.split()) if inp[0][0] != "C": raise ValueError( "first parameter should be canvas, chech your inp.txt") else: picture = Paint(int(inp[0][1]), int(inp[0][2])) with open(output_file, "a") as f: f.write(f"{picture.draw_me()}\n") for inp_line in inp: token = inp_line[0] if token == "L": x1 = int(inp_line[1]) y1 = int(inp_line[2]) x2 = int(inp_line[3]) y2 = int(inp_line[4]) picture.line(x1, y1, x2, y2) with open(output_file, "a") as f: f.write(f"{picture.draw_me()}\n") elif token == "R": x1 = int(inp_line[1]) y1 = int(inp_line[2]) x2 = int(inp_line[3]) y2 = int(inp_line[4]) picture.rectangle(x1, y1, x2, y2) with open(output_file, "a") as f: f.write(f"{picture.draw_me()}\n") elif token == "B": x = int(inp_line[1]) y = int(inp_line[2]) color = inp_line[3] picture.bucket_fill(x, y, color) with open(output_file, "a") as f: f.write(f"{picture.draw_me()}\n")
def loop(game: Game, collector: Collector, save: Save = None, teleporter=None, teleporter2=None) -> Iterator[int]: if isServer: tid, f = time() + 3600 * game.hours - 300, 0 while time() < tid: f += 1 yield f else: from pynput.keyboard import Key, Listener, Events from paint import Paint current = set() order = [None, None, None] def waitForResume(): action = None while action == None and States.running: with Events() as events: event = events.get() if event.__class__ == Events.Press: if event.key == Key.pause: action = True States.isPaused = False elif event.key in {Key.shift_l, Key.shift_r}: action = True def on_press(key): current.add(key) order.append(key) ctrl: bool = Key.ctrl_l in current or Key.ctrl_r in current alt: bool = Key.alt_l in current speed = 300 zoom = 15 if [Key.esc, Key.esc, Key.esc] == order[-3:]: Paint.stop() States.running = False elif Key.f2 == key: States.switchPlot = True elif Key.f7 == key: States.save = True elif Key.f4 == key: Paint.switch(game.layers.width, game.layers.height) elif Key.left == key and ctrl: Paint.dim = (Paint.dim - 1) % game.layers.batch elif Key.right == key and ctrl: Paint.dim = (Paint.dim + 1) % game.layers.batch elif Key.f3 == key: States.slow = not States.slow elif Key.right == key and alt: Paint.move(speed, 0, game.layers.width, game.layers.height) elif Key.left == key and alt: Paint.move(-speed, 0, game.layers.width, game.layers.height) elif Key.down == key and alt: Paint.move(0, speed, game.layers.width, game.layers.height) elif Key.up == key and alt: Paint.move(0, -speed, game.layers.width, game.layers.height) elif Key.down == key and ctrl: Paint.zoom(-zoom, game.layers.width, game.layers.height) elif Key.up == key and ctrl: Paint.zoom(zoom, game.layers.width, game.layers.height) elif Key.pause == key: States.isPaused = True def on_release(key): try: current.remove(key) except KeyError: pass Listener(on_press=on_press, on_release=on_release).start() f = 0 while States.running: f += 1 if States.draw: Paint(game, f, teleporter, teleporter2) if States.switchPlot: States.showPrint = not States.showPrint States.switchPlot = False collector.show(game) if States.save: if save != None: save.save() States.save = False if States.isPaused: waitForResume() yield f
class Aplikacja(QWidget): def __init__(self): super(Aplikacja, self).__init__() self.interfejs() self.paint = Paint(self.predict) self.paint.show() self.loaded_model = 0 def predict(self, image): if self.loaded_model == 0: pass else: # użycie modelu do przewidzenia jaki jest liczba na obrazie prediction = self.loaded_model.predict(image) # wyświetlenie wartości zwróconych przez sieć print(prediction) # wysiwetlenie indeksu najwiekszego elementu self.liczba.setText(str(np.argmax(prediction))) def interfejs(self): # etykiety etykieta1 = QLabel("Ilość epok", self) etykieta2 = QLabel("Batch size", self) etykieta3 = QLabel("Ilość neuronów", self) etykieta4 = QLabel("Wybierz model",self) etykieta5 = QLabel("Wykryta liczba",self) etykieta6 = QLabel("Odczytywane pixele", self) etykieta7 = QLabel("Nazwa pliku modelu", self) etykieta8 = QLabel("Nazwa pliku z wagami", self) # przypisanie widgetów do układu tabeli ukladT = QGridLayout() ukladT.addWidget(etykieta1, 0, 0) ukladT.addWidget(etykieta2, 1, 0) ukladT.addWidget(etykieta3, 2, 0) ukladT.addWidget(etykieta4, 7, 0) ukladT.addWidget(etykieta5, 8, 0) ukladT.addWidget(etykieta6, 3, 0) ukladT.addWidget(etykieta7, 4, 0) ukladT.addWidget(etykieta8, 5, 0) # 1-liniowe pola edycyjne self.epoki = QLineEdit() self.batch = QLineEdit() self.neurony = QLineEdit() self.pixels = QLineEdit() self.liczba = QLineEdit() self.nmodel = QLineEdit() self.nwagi = QLineEdit() self.liczba.setDisabled(True) ukladT.addWidget(self.epoki, 0, 1) ukladT.addWidget(self.batch, 1, 1) ukladT.addWidget(self.neurony, 2, 1) ukladT.addWidget(self.liczba, 8, 1) ukladT.addWidget(self.pixels, 3, 1) ukladT.addWidget(self.nmodel, 4, 1) ukladT.addWidget(self.nwagi, 5, 1) # przyciski wybierzBtn = QPushButton("&Wybierz", self) wybierzBtn.clicked.connect(self.wyborSieci) uczBtn = QPushButton("&Stwórz model", self) uczBtn.clicked.connect(self.tworzenieModelu) uczBtn.resize(uczBtn.sizeHint()) zamknijBtn = QPushButton("&Zamknij", self) zamknijBtn.clicked.connect(quit) ukladT.addWidget(wybierzBtn, 7, 1) ukladT.addWidget(uczBtn, 6, 0, 1, 2) ukladT.addWidget(zamknijBtn, 9, 1) # przypisanie utworzonego układu do okna self.setLayout(ukladT) self.setGeometry(928, 400, 300, 150) self.setWindowTitle("Tworzenie Modelu") self.show() def wyborSieci(self): # Wczytanie modelu z pliku json_file, _ = QFileDialog.getOpenFileName(self, "Wybierz model", "", "Modele(*.json)") with open(json_file, 'r') as plik: loaded_model_json = plik.read() self.loaded_model = model_from_json(loaded_model_json) # Wczytanie wag h5_file, _ = QFileDialog.getOpenFileName(self, "Wybierz wagi", "", "Wagi(*.h5)") self.loaded_model.load_weights(h5_file) def tworzenieModelu(self): nadawca = self.sender() try: epoch = int(self.epoki.text()) batching = int(self.batch.text()) neuronsNumber = int(self.neurony.text()) pixelRead = int(self.pixels.text()) nmodel = self.nmodel.text() nwagi = self.nwagi.text() if nadawca.text() == "&Stwórz model": network.tworzenieModelu(pixelRead, neuronsNumber, epoch, batching, nmodel, nwagi) except ValueError: QMessageBox.warning(self, "Błąd", "Błędne dane", QMessageBox.Ok)
class Root(QMainWindow): def __init__(self): super(Root, self).__init__() self.setWindowTitle('GraHID') self.mdiArea = QMdiArea(self) # self.setStyleSheet(dark_style) # ------- ICON CONFIGURATION ------- # self.setCentralWidget(self.mdiArea) self.setWindowIcon(QIcon('Images/main.ico')) # ------ INITIAL DATA ------ # self.preferences_data = [3, 25, '0.001', 1] self.viewData = [[8, [255, 0, 0]], [1, [0, 100, 0]], [ 0, 0, 0, QFont('MS Shell Dlg 2', 8, 50, False), 'N', 'T', 'R' ], [0, 1, 0], [250, 250, 205]] self.default_data = [['0', '200', '254', '0.00006'], [0, 0, [0, '1.14e-06'], [1, '15'], [1, '100']]] self.summary_data = [0, 0, 0, 0, 0, 0, '', '' ] # #nodos # tubs #Bombas # Res # Flow units # ------ CURSOR ---------# self.bar_cursor = QCursor(QPixmap('Images/index.png')) self.nod_cursor = QCursor(QPixmap('Images/nod_cursor.png')) self.bomb_cursor = QCursor(QPixmap('Images/bomb_cursor.png')) # ------ STATUS BAR --------# self.statusBar() # ------ ACTIONS IN MENU BAR -------# self.menu_bar = self.menuBar() self.fileMenu = self.menu_bar.addMenu('&Archivo') self.newAction = QAction(QIcon('Images/new.png'), 'Nuevo', self) self.newAction.setShortcut('Ctrl+N') self.newAction.triggered.connect(self.new_project) self.newAction.setStatusTip('Crea un nuevo proyecto.') self.openAction = QAction(QIcon('Images/open.png'), 'Abrir', self) self.openAction.triggered.connect(self.open_project) self.openAction.setShortcut('Ctrl+O') self.openAction.setStatusTip('Abre un proyecto existente.') self.saveAction = QAction(QIcon('Images/save.png'), 'Guardar', self) self.saveAction.triggered.connect(self.save_project) self.saveAction.setShortcut('Ctrl+S') self.saveAction.setStatusTip('Guarda el proyecto actual.') self.importAction = QAction('Importar', self) self.importAction.setShortcut('Ctrl+I') self.importAction.setStatusTip('Importa data externa al programa.') self.importAction.triggered.connect(self.import_project) self.exportAction = QAction('Exportar', self) self.exportAction.setShortcut('Ctrl+E') self.exportAction.setStatusTip('Exporta data a programas externos.') self.exportAction.triggered.connect(self.export_project) self.preferencesAction = QAction('Preferencias', self) self.preferencesAction.triggered.connect(self.preferencesFunction) self.preferencesAction.setStatusTip( 'Configura las propiedades iniciales del proyecto.') self.closeAction = QAction('Salir', self) self.closeAction.setShortcut('Alt+X') self.closeAction.triggered.connect(self.close) self.fileMenu.addAction(self.newAction) self.fileMenu.addAction(self.openAction) self.fileMenu.addAction(self.saveAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.importAction) self.fileMenu.addAction(self.exportAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.preferencesAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.closeAction) self.viewMenu = self.menu_bar.addMenu('&Ver') self.optionsAction = QAction('Opciones', self) self.optionsAction.setStatusTip( 'Configura las opciones de visualización del ventana del proyecto.' ) self.optionsAction.triggered.connect(self.viewOptions) self.viewMenu.addAction(self.optionsAction) self.projectMenu = self.menu_bar.addMenu('&Proyecto') self.summaryAction = QAction(QIcon('Images/resumen.png'), 'Resumen', self) self.summaryAction.triggered.connect(self.summary_win) self.summaryAction.setStatusTip( 'Visualiza los valores iniciales para el análisis.') self.defaultAction = QAction('Valores por defecto', self) self.defaultAction.setStatusTip( 'Configura las opciones hidráulicas del proyecto.') self.defaultAction.triggered.connect(self.defaultOptions) self.calculateAction = QAction(QIcon('Images/run3.png'), 'Iniciar Análisis', self) self.calculateAction.triggered.connect(self.calculate_all) self.calculateAction.setStatusTip( 'Inicia con el análisis y/o cálculo del proyecto.') self.dataAction = QAction(QIcon('Images/tables.png'), 'Datos', self) self.dataAction.setStatusTip( 'Visualiza y configura los datos iniciales del proyecto.') self.dataAction.triggered.connect(self.properties_win) self.projectMenu.addAction(self.dataAction) self.projectMenu.addAction(self.summaryAction) self.projectMenu.addAction(self.defaultAction) self.projectMenu.addSeparator() self.projectMenu.addAction(self.calculateAction) self.informMenu = self.menu_bar.addMenu('&Informe') self.completeAction = QAction('Completo', self) self.completeAction.setStatusTip( 'Visualiza los resultados generales del analisis del proyecto.') self.iterationsAction = QAction(QIcon('Images/iter.png'), 'Iteraciones', self) self.iterationsAction.setStatusTip( 'Visualiza todas las iteraciones realizadas por el programa.') self.graphActions = QAction(QIcon('Images/graph.png'), 'Gráficas', self) self.graphActions.setStatusTip( 'Visualiza los gráficos resultantes del proyecto.') self.tablesMenu = QMenu('Tablas', self) self.resultsAction = QAction(QIcon('Images/tables.png'), 'Resultados', self) self.resultsAction.setStatusTip( 'Visualiza las tablas resultantes del proyecto.') self.resultsAction.triggered.connect(self.viewResults) self.tablesMenu.addAction(self.resultsAction) self.informMenu.addAction(self.completeAction) self.informMenu.addAction(self.iterationsAction) self.informMenu.addSeparator() self.informMenu.addAction(self.graphActions) self.informMenu.addMenu(self.tablesMenu) self.helpMenu = self.menu_bar.addMenu('A&yuda') self.helpAction = QAction(QIcon('Images/help.png'), r'Acerca de...', self) self.helpAction.setStatusTip( 'Visualiza el contenido de ayuda y datos del programador.') self.helpMenu.addAction(self.helpAction) # ------ ACTIONS IN TOOLBAR -------# self.tool_bar_1 = self.addToolBar('Estandar') self.tool_bar_1.addAction(self.newAction) self.tool_bar_1.addAction(self.openAction) self.tool_bar_1.addAction(self.saveAction) self.tool_bar_1.addSeparator() self.tool_bar_1.addAction(self.calculateAction) self.tool_bar_1.addSeparator() self.tool_bar_1.addAction(self.summaryAction) self.tool_bar_1.addAction(self.iterationsAction) self.tool_bar_1.addAction(self.graphActions) self.tool_bar_1.addAction(self.resultsAction) self.tool_bar_1.addSeparator() self.tool_bar_1.addAction(self.helpAction) #self.tool_bar_1.addAction(self.reAction) # ------ BUTTONS IN TOOLBAR -------# self.nod_button = QToolButton(self) self.nod_button.setIcon(QIcon('Images/nod.png')) self.nod_button.setCheckable(True) self.nod_button.clicked.connect(self.is_node) self.nod_button.setStatusTip('Dibuja un nodo.') self.pipe_button = QToolButton(self) self.pipe_button.setIcon(QIcon('Images/bar.png')) self.pipe_button.setCheckable(True) self.pipe_button.clicked.connect(self.is_pipe) self.pipe_button.setStatusTip( 'Dibuja una conexion o Tubería entre Nodos.') self.sel_button = QToolButton(self) self.sel_button.setIcon(QIcon('Images/cursor.png')) self.sel_button.setCheckable(True) self.sel_button.clicked.connect(self.is_select) self.sel_button.setStatusTip( 'Selecciona un elemento para ver y/o modificar sus propiedades') self.sel_area_button = QToolButton(self) self.sel_area_button.setIcon(QIcon('Images/area_s.png')) self.sel_area_button.setCheckable(True) self.sel_area_button.clicked.connect(self.is_select_area) self.sel_area_button.setStatusTip( 'Selecciona varios elementos para eliminar o mover') self.bomb_button = QToolButton(self) self.bomb_button.setIcon(QIcon('Images/bomb.png')) self.bomb_button.clicked.connect(self.is_bomb) self.bomb_button.setCheckable(True) self.bomb_button.setStatusTip( 'Agrega una bomba seleccionando una tubería') self.res_button = QToolButton(self) self.res_button.setIcon(QIcon('Images/reser.png')) self.res_button.setCheckable(True) self.res_button.clicked.connect(self.is_reservoir) self.move_button = QToolButton(self) self.move_button.setIcon(QIcon('Images/move_el.png')) self.move_button.setStatusTip( 'Mueva un item manteniedo pulsado sobre ella y moviendo el cursor.' ) self.move_button.setCheckable(True) #self.move_button.clicked.connect(self.isMove) self.b_toolbar = QToolBar(self) self.b_toolbar.setWindowTitle('Elementos') self.b_toolbar.setIconSize(QSize(16, 16)) self.addToolBar(Qt.LeftToolBarArea, self.b_toolbar) self.b_toolbar.addWidget(self.sel_button) self.b_toolbar.addWidget(self.move_button) self.b_toolbar.addWidget(self.sel_area_button) self.b_toolbar.addSeparator() self.b_toolbar.addWidget(self.nod_button) self.b_toolbar.addWidget(self.pipe_button) self.b_toolbar.addWidget(self.res_button) self.b_toolbar.addWidget(self.bomb_button) self.paint = None self.new_project() self.win_show_results = WinResults(self, self.paint) self.mdiArea.tileSubWindows() self.routeFile = "" def is_node(self): if not self.paint.is_node: self.paint.is_node = True else: self.paint.is_node = False self.paint.is_pipe = False self.pipe_button.setChecked(False) self.paint.is_select = False self.sel_button.setChecked(False) self.paint.is_move = False self.move_button.setChecked(False) self.paint.is_area_select = False self.sel_area_button.setChecked(False) self.paint.is_reservoir = False self.res_button.setChecked(False) self.paint.is_bomb = False self.bomb_button.setChecked(False) def is_pipe(self): if not self.paint.is_pipe: self.paint.is_pipe = True else: self.paint.is_pipe = False self.paint.is_node = False self.nod_button.setChecked(False) self.paint.is_select = False self.sel_button.setChecked(False) self.paint.is_move = False self.move_button.setChecked(False) self.paint.is_area_select = False self.sel_area_button.setChecked(False) self.paint.is_reservoir = False self.res_button.setChecked(False) self.paint.is_bomb = False self.bomb_button.setChecked(False) def is_select(self): if not self.paint.is_select: self.paint.is_select = True self.sel_button.setChecked(True) else: self.paint.is_select = False self.paint.is_node = False self.nod_button.setChecked(False) self.paint.is_pipe = False self.pipe_button.setChecked(False) self.paint.is_move = False self.move_button.setChecked(False) self.paint.is_area_select = False self.sel_area_button.setChecked(False) self.paint.is_reservoir = False self.res_button.setChecked(False) self.paint.is_bomb = False self.bomb_button.setChecked(False) def is_select_area(self): if not self.paint.is_area_select: self.paint.is_area_select = True else: self.paint.is_area_select = False self.paint.is_node = False self.nod_button.setChecked(False) self.paint.is_pipe = False self.pipe_button.setChecked(False) self.paint.is_move = False self.move_button.setChecked(False) self.paint.is_select = False self.sel_button.setChecked(False) self.paint.is_reservoir = False self.res_button.setChecked(False) self.paint.is_bomb = False self.bomb_button.setChecked(False) def is_reservoir(self): if not self.paint.is_reservoir: self.paint.is_reservoir = True else: self.paint.is_reservoir = False self.paint.is_node = False self.nod_button.setChecked(False) self.paint.is_pipe = False self.pipe_button.setChecked(False) self.paint.is_move = False self.move_button.setChecked(False) self.paint.is_select = False self.sel_button.setChecked(False) self.paint.is_area_select = False self.sel_area_button.setChecked(False) self.paint.is_bomb = False self.bomb_button.setChecked(False) def is_bomb(self): if not self.paint.is_bomb: self.paint.is_bomb = True else: self.paint.is_bomb = False self.paint.is_node = False self.nod_button.setChecked(False) self.paint.is_pipe = False self.pipe_button.setChecked(False) self.paint.is_move = False self.move_button.setChecked(False) self.paint.is_select = False self.sel_button.setChecked(False) self.paint.is_area_select = False self.sel_area_button.setChecked(False) self.paint.is_reservoir = False self.res_button.setChecked(False) def new_project(self): self.paint = Paint(self.viewData, self) self.mdiArea.addSubWindow(self.paint) self.changedViewOptions() self.paint.show() def save_project(self): file, cond = QFileDialog.getSaveFileName( self, "Guardar", self.routeFile, "All Files (*);;Archivo WaterHID (*.wh)") if cond: self.routeFile = file l_all = graphToStr(self.paint) file_p = open(self.routeFile, "w") file_p.write(l_all) file_p.close() def import_project(self): file, cond = QFileDialog.getOpenFileName( self, "Abrir", self.routeFile, "All Files (*);;AutoCAD (*.dxf)") if cond: self.routeFile = file file_to_import = EasyDXF(file) l_res, l_nodes, l_pipes = file_to_import.read() paint_All(l_res, l_nodes, l_pipes, self.paint) def export_project(self): file, cond = QFileDialog.getSaveFileName( self, "Exportar...", self.routeFile, "All Files (*);;AutoCAD (*.dxf)") if cond: self.routeFile = file l_all = graphToStr(self.paint) file_to_export = EasyDXF(file) file_to_export.write(l_all) def open_project(self): file, cond = QFileDialog.getOpenFileName( self, "Abrir", self.routeFile, "All Files (*);; Archivo WaterHID (*wh)") if cond: self.routeFile = file file_o = open(self.routeFile, "r") a = file_o.readlines() l_res = eval(a[0]) l_nodes = eval(a[1]) l_pipes = eval(a[2]) paint_All(l_res, l_nodes, l_pipes, self.paint) def calculate_all(self): show_text_default(self.paint) self.changedViewOptions() if len(self.paint.l_pipes): n_i = [i.n_i for i in self.paint.l_pipes] n_f = [i.n_f for i in self.paint.l_pipes] for i in self.paint.l_nodes: if i not in n_i and i not in n_f: return QMessageBox.warning( self, 'Error', 'There are untied knots.\nExisten nudos sin unir.') eq = ['D-W', 'H-W', 'C-M'][self.default_data[1][1]] error, i_max = float(self.preferences_data[2]), float( self.preferences_data[1]) if self.default_data[1][4][0]: flow_i = float(self.default_data[1][4][1]) / 1000 else: flow_i = sum([i.demand for i in self.paint.l_nodes]) / len( self.paint.l_nodes) for i in self.paint.l_pipes: i.flow = flow_i try: cond, res = water_net(self.paint.l_pipes, self.paint.l_nodes, self.paint.l_reservoir, self.statusBar(), eq=eq, error=error, i_max=i_max) if cond: QMessageBox.information(self, 'Success', ' It was executed successfully') put_text(self.paint.l_pipes, self.paint.l_nodes, self.paint.l_reservoir, eq.lower(), self.preferences_data[0]) self.win_show_results.show() else: QMessageBox.information( self, 'Error', 'There was an error during the execution') show_text_default(self.paint) #self.win_show_results.hide() except ZeroDivisionError: show_text_default(self.paint) else: #self.win_show_results.hide() QMessageBox.warning(self, 'Error', "Don't exist any pipe") def preferencesFunction(self): win_preferences = Preferences(self.preferences_data) win_preferences.exec_() self.preferences_data = win_preferences.data if self.preferences_data[3]: self.default_data[1][2][0] = 1 self.default_data[1][3][0] = 0 else: self.default_data[1][2][0] = 0 self.default_data[1][3][0] = 1 def viewOptions(self): winViewOptions = ViewOptions(self.viewData) winViewOptions.exec_() self.viewData = winViewOptions.data self.changedViewOptions() show_text_default(self.paint) def viewResults(self): self.win_show_results.hide() win = ResultsView(self, self.paint) win.exec_() self.win_show_results.show() def changedViewOptions(self): self.paint.setStyleSheet( 'QGraphicsView {background-color: %s }' % QColor(self.viewData[4][0], self.viewData[4][1], self.viewData[4][2]).name()) self.paint.node_color = QColor(self.viewData[0][1][0], self.viewData[0][1][1], self.viewData[0][1][2]) self.paint.node_size = self.viewData[0][0] self.paint.pipe_color = QColor(self.viewData[1][1][0], self.viewData[1][1][1], self.viewData[1][1][2]) self.paint.pipe_width = self.viewData[1][0] self.paint.text_font = self.viewData[2][3] self.paint.text_visible_node = bool(self.viewData[2][0]) self.paint.text_visible_pipe = bool(self.viewData[2][1]) self.paint.text_visible_res = bool(self.viewData[2][2]) old_text_node = self.paint.pref_node old_text_pipe = self.paint.pref_pipe old_text_res = self.paint.pref_res self.paint.pref_node = self.viewData[2][4] self.paint.pref_pipe = self.viewData[2][5] self.paint.pref_res = self.viewData[2][6] for item in self.paint.scene_v.items(): if item.type() == 4: item.setPen(self.paint.node_color) item.setBrush(QBrush(self.paint.node_color, Qt.SolidPattern)) #QGraphicsEllipseItem.rect() e = QPointF( self.paint.l_nodes[self.paint.l_i_nodes.index(item)].x, self.paint.l_nodes[self.paint.l_i_nodes.index(item)].y) item.setRect(e.x() - self.paint.node_size / 2, e.y() - self.paint.node_size / 2, self.paint.node_size, self.paint.node_size) if item.type() == 6: pen = QPen(self.paint.pipe_color) pen.setWidth(self.paint.pipe_width) item.setPen(pen) if item.type() == 8: item.setFont(self.paint.text_font) if self.paint.text_visible_node and item in self.paint.text_node: text = item.toPlainText().replace(old_text_node, self.paint.pref_node) item.setPlainText(text) item.show() elif self.paint.text_visible_pipe and item in self.paint.text_pipe: text = item.toPlainText() text = text.replace(old_text_pipe, self.paint.pref_pipe) item.setPlainText(text) item.show() elif self.paint.text_visible_res and item in self.paint.text_res: text = item.toPlainText() text = text.replace(old_text_res, self.paint.pref_res) item.setPlainText(text) item.show() else: item.hide() def defaultOptions(self): win_default = DefaultValues(self.default_data) win_default.exec_() self.default_data = win_default.data self.preferences_data[3] = self.default_data[1][2][0] for i in self.paint.l_pipes: if self.default_data[1][1] == 0: i.ks = float(self.default_data[0][3]) elif self.default_data[1][1] == 1: i.C = float(self.default_data[0][3]) elif self.default_data[1][1] == 2: i.n_m = float(self.default_data[0][3]) def properties_win(self): win_properties = PropertiesData(self, self.paint, self.default_data[1][1]) win_properties.exec_() def summary_win(self): self.summary_data[0] = len(self.paint.l_nodes) self.summary_data[1] = len(self.paint.l_pipes) self.summary_data[2] = 0 self.summary_data[3] = len(self.paint.l_reservoir) self.summary_data[4] = 'm3s' self.summary_data[5] = 'd-w' win_summary = SummaryWindow(self.summary_data, self.paint) win_summary.exec_() self.summary_data = win_summary.data
def new_project(self): self.paint = Paint(self.viewData, self) self.mdiArea.addSubWindow(self.paint) self.changedViewOptions() self.paint.show()
def main(): global X, y try: df = pd.read_csv("./datasets/digits.csv", header=None) X = df.values df = pd.read_csv("./datasets/labels.csv", header=None) y = df.values except: X = np.array([[]]) y = np.array([[]]) sel = np.random.permutation(X) sel = sel[0:100] if len(X[0]) != 0: display_data(sel) input_layer_size = 400 hidden_layer_size = 25 num_labels = 10 shape = (input_layer_size, hidden_layer_size, num_labels) for i in range(1, 11): prevLen = len(y) print(f'Write example for {i if i < 10 else 0}') f = lambda x: addTrainingExample(x, [[i]]) Paint(func=f) if len(y) == prevLen: break if len(X[0]) == 0: print("Not enough data... Exiting") return nn = NeuralNetwork(shape) nn.Lambda = 1 initial_Theta1 = nn.rand_initialize_weights(input_layer_size, hidden_layer_size) initial_Theta2 = nn.rand_initialize_weights(hidden_layer_size, num_labels) initial_nn_params = np.array(initial_Theta1.flatten().tolist() + initial_Theta2.flatten().tolist()) f = lambda p: nn.cost_function(p, X, y)[0] gradf = lambda p: nn.cost_function(p, X, y)[1] print('Training Neural Network... (This can take a while)') nn_params = optimize.fmin_cg(f, initial_nn_params, fprime=gradf, maxiter=250) shape = hidden_layer_size, (input_layer_size + 1) idx = hidden_layer_size * (input_layer_size + 1) Theta1 = np.reshape(nn_params[0:idx], shape) display_data(Theta1[:, 1:]) pred = nn.predict(nn_params, X) print(f'Training Set Accuracy: {np.mean(pred == y.T) * 100}%') p = lambda x: nn.predict(nn_params, x) Paint(predict=p) file = open("./datasets/digits.csv", 'w+') for i in range(len(X)): file.write(f'{", ".join(str(x) for x in X[i])}\n') file.close() file = open("./datasets/labels.csv", 'w+') for l in y: file.write(f'{l[0]}\n') file.close()
class MainWindow(QtWidgets.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.init_UI() self.mode = RANGE_OF_EUCLID self.cluster_analysis = None self.btnDefault = "background-color: #87CEFA" self.btnActive = "background-color: #4682B4" def init_UI(self): self.paint = Paint() self.ui.layout.addWidget(self.paint) self.ui.put_points.clicked.connect(self.put_points) self.ui.put_clusters.clicked.connect(self.put_clusters) self.ui.clear.clicked.connect(self.clear) self.ui.calculation.clicked.connect(self.calculation) self.ui.step.clicked.connect(self.step) self.ui.comboBox.addItems(['Euclid', 'Chebyshev']) self.ui.comboBox.activated.connect(self.select_mode) def select_mode(self, index): dictionary = {0: RANGE_OF_EUCLID, 1: RANGE_OF_CHEBYSHEV} self.mode = dictionary[index] def resizeEvent(self, event): self.paint.setSceneRect(QRectF(self.paint.viewport().rect())) def put_points(self): self.paint.paint = True self.paint.put_clusters = False self.ui.put_points.setStyleSheet(self.btnActive) self.ui.put_clusters.setStyleSheet(self.btnDefault) def put_clusters(self): self.paint.paint = True self.paint.put_clusters = True self.ui.put_points.setStyleSheet(self.btnDefault) self.ui.put_clusters.setStyleSheet(self.btnActive) def clear(self): self.paint.isdelete = True self.ui.comboBox.setEnabled(True) self.ui.put_points.setStyleSheet(self.btnDefault) self.ui.put_clusters.setStyleSheet(self.btnDefault) self.ui.put_points.setEnabled(True) self.ui.put_clusters.setEnabled(True) self.ui.step.setDisabled(True) self.ui.calculation.setEnabled(True) self.paint.paint = False self.paint.coords_clusters.clear() self.paint.coords_points.clear() self.paint.clusters.clear() self.paint.points.clear() self.paint.scene.clear() self.cluster_analysis = None def calculation(self): if len(self.paint.clusters) < 1: return self.ui.put_points.setStyleSheet(self.btnDefault) self.ui.put_clusters.setStyleSheet(self.btnDefault) self.ui.put_points.setDisabled(True) self.ui.put_clusters.setDisabled(True) self.ui.step.setEnabled(True) self.ui.comboBox.setDisabled(True) self.ui.calculation.setDisabled(True) self.cluster_analysis = Cluster_Analysis(self.paint.coords_points, self.paint.coords_clusters, self.mode) def step(self): result, coords = self.cluster_analysis.step() self.last_step(coords) if result else self.intermed_step(coords) def intermed_step(self, coords_clusters): self.paint.coords_clusters = deepcopy(coords_clusters) for coords, clusters in zip(coords_clusters, self.paint.clusters): clusters.setRect(QRectF(coords[0], coords[1], 15, 15)) def last_step(self, coords_poins): self.ui.put_points.setEnabled(True) self.ui.put_clusters.setEnabled(True) self.ui.step.setDisabled(True) self.ui.comboBox.setEnabled(True) self.ui.calculation.setEnabled(True) self.paint.redraw_points(coords_poins)
onvalue=1, offvalue=0, command=trainTrack) trainBox.grid(row=0, column=2, padx=(10, 0), pady=(10, 0)) targetMsg = StringVar(root, value=0) targetInput = Entry(textvariable=targetMsg, width=3, font=("TimesNewRoman", 15), justify="center") targetInput.grid(row=0, column=3, padx=(10, 0), pady=(10, 0)) targetInput.bind("<Key>", targetChange) paintFrame = Frame(root, width=200, height=200, bd=1) paintApp = Paint(paintFrame) paintFrame.grid(row=1, column=0, columnspan=4, padx=10, pady=(10, 0)) predictionFrame = Frame(root) predictionFrame.grid(row=2, column=0, sticky="we", columnspan=4, pady=10) predictionFrame.columnconfigure(3, weight=0) predictionFrame.rowconfigure(0, weight=0) predictionLabel = Label(predictionFrame, text="Prediction: ", font=("TimesNewRoman", 10)) predictionLabel.grid(row=0, column=0, columnspan=2, padx=(10, 0), pady=10) predictionEntry = Label(predictionFrame, text=0,
def showEvent(self,event): print("ShowEvent") if self.flagWmin != True: #Para ubuntu se necesito esta bandera self.flagWmin = True #if MainWindow.isMinimized(): #Para mac # pass #else: #----------------------------------- Obtiene hostname, port , addrs / serverConfig.ini ------------------------# settaddrs = QtCore.QSettings('/home/ditsa/DitsaNet/Settings/ServerConfig.ini',QtCore.QSettings.NativeFormat) if settaddrs.value('/home/ditsa/DitsaNet/Settings/ServerConfig.ini') !='': tmpAddr = settaddrs.value("servers") #nombre de server y port for i in range(3,len(tmpAddr),4): self.tmp_server.clear() x = tmpAddr[i].rpartition('-') val1 = int(x[0]) #val2 = int(x[2]) self.tmp_server.append(str(val1)) for j in range(15): y = val1 + j + 1 self.tmp_server.append(str(y)) self.tempAddr.append(self.tmp_server[:]) self.tmp_total.append(str(self.tmp_server[:])) for k in range(0,len(tmpAddr),4): #guarda el hostname, el port y password useHostname.append(tmpAddr[k]+".local") usePort.append(int(tmpAddr[k+1])) usePassw.append(tmpAddr[k+2]) ''' settprog = QtCore.QSettings('/home/ditsa/DitsaNet/Settings/fileprograms.ini', QtCore.QSettings.NativeFormat) if settprog.value('/home/ditsa/DitsaNet/Settings/fileprograms.ini') !='': tmp = settprog.value("saveprograms") if tmp != None and len(tmp) != 0: self.saveprograms = tmp[:] self.flagProg = True print("savePR:",self.saveprograms) #esta opcion no puede ser viable por que los gabinetes y addr puede cambiar ''' #-----------------------------------Obtiene mylist, mylabel, rowcol / archivo.ini -----------------------------# settings = QtCore.QSettings('/home/ditsa/DitsaNet/Settings/archivo.ini', QtCore.QSettings.NativeFormat) if settings.value('/home/ditsa/DitsaNet/Settings/archivo.ini')!='': self.settingsList = settings.value("mylist") self.settingsLabel = settings.value("mylabel") self.settingsRowCol = settings.value("rowcol") if self.settingsRowCol != None and len(self.settingsRowCol) !=0: self.rowCol = self.settingsRowCol[:] else: self.rowCol.append('1%') self.rowCol.append('R=10 C=10') if self.settingsList != None: self.mylist = self.settingsList[:] #para que no correspondan con el mismo objeto for i in range(2,len(self.mylist),4): self.newlist.append(self.mylist[i].replace('N=','')) ordName = NameOrdened(self.newlist) #manda a llamar la clase NameOrdened x = ordName.cod() #ordena los elementos de la lista de < a > self.newlist.clear() #Los valores de neewlist son todas las addr que se muestran en la app DitsaEditor for i in range(len(x)): #Extrae address ingresados en DitsaEditor for j in range(2,len(self.mylist),4): if "N="+str(x[i]) == self.mylist[j]: self.newlist.append(self.mylist[j-2]) self.newlist.append(self.mylist[j-1]) self.newlist.append(self.mylist[j]) self.newlist.append(self.mylist[j+1]) if self.settingsLabel != None: self.mylabel = self.settingsLabel[:] #para que no correspondan con el mismo objeto if self.settingsList != None or self.settingsLabel != None: # Populate Tables self.populateTabs() self.paint = Paint(self) self.tabWidget.addTab(self.paint, "Page 1") tabC = self.tabWidget.count() MainWindow.showMaximized() self.paint.setSceneRect(0,0,0,0) if (self.settingsList != None and len(self.settingsList)!=0) or (self.settingsLabel != None and len(self.settingsLabel)!=0): for i in range(int(self.numTabT)-tabC): self.newPage() self.onCmbZoom() for j in range(len(useHostname)): BCmb.pingDataClient(useHostname[j],usePort[j],self.tmp_total[j]) #envia las addr de los modulos print("Inicia Poleo") #poleo es lo primero en iniciar despues de llenar screen self.threadData(True) #Inicia el poleo time.sleep(0.3) self.valueData() #obtiene los valores del poleo del sever
class Ui_DitsaNet(object): def __init__(self,MainWindow, parent=None): #def setupUi(self, MainWindow): object.__init__(parent) MainWindow.setObjectName("MainWindow") MainWindow.resize(1280, 523) #1280,700 1476 523 #MainWindow.setFixedSize(1280,523) self.centralWidget = QtWidgets.QWidget(MainWindow) self.centralWidget.setObjectName("centralWidget") self.gridLayout = QtWidgets.QGridLayout(self.centralWidget) self.gridLayout.setContentsMargins(11, 11, 11, 11) self.gridLayout.setSpacing(6) self.gridLayout.setObjectName("gridLayout") self.cmdIniciar = QtWidgets.QPushButton(self.centralWidget) ###### self.cmdIniciar.setObjectName("cmdIniciar") self.gridLayout.addWidget(self.cmdIniciar, 0, 1, 1, 1) self.comboBox = QtWidgets.QComboBox(self.centralWidget) self.comboBox.setObjectName("comboBox") self.gridLayout.addWidget(self.comboBox, 0, 4, 1, 1) #0,3,1,1 self.cmdCargar = QtWidgets.QPushButton(self.centralWidget) self.cmdCargar.setObjectName("cmdCargar") self.gridLayout.addWidget(self.cmdCargar, 0, 0, 1, 1) self.cmbZoom = QtWidgets.QComboBox(self.centralWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cmbZoom.sizePolicy().hasHeightForWidth()) self.cmbZoom.setSizePolicy(sizePolicy) self.cmbZoom.setObjectName("cmbZoom") self.gridLayout.addWidget(self.cmbZoom, 0, 5, 1, 1) #0,4,1,1 self.cmdDetener = QtWidgets.QPushButton(self.centralWidget) self.cmdDetener.setObjectName("cmdDetener") self.gridLayout.addWidget(self.cmdDetener, 0, 3, 1, 1) #0,2,1,1 self.cmdPausar = QtWidgets.QPushButton(self.centralWidget) self.cmdPausar.setObjectName("cmdPausar") self.gridLayout.addWidget(self.cmdPausar, 0, 2, 1, 1) #0,1,1,1 self.tabWidget = QtWidgets.QTabWidget(self.centralWidget) font = QtGui.QFont() #font.setFamily("Ubuntu") font.setPointSize(12) font.setBold(False) font.setWeight(50) self.tabWidget.setFont(font) self.tabWidget.setStyleSheet("") self.tabWidget.setLocale(QtCore.QLocale(QtCore.QLocale.Spanish, QtCore.QLocale.Mexico)) self.tabWidget.setObjectName("tabWidget") # self.tab = QtWidgets.QWidget() # self.tab.setObjectName("tab") # self.gridLayout_2 = QtWidgets.QGridLayout(self.tab) # self.gridLayout_2.setContentsMargins(11, 11, 11, 11) # self.gridLayout_2.setSpacing(6) # self.gridLayout_2.setObjectName("gridLayout_2") #self.tabWidget.addTab(self.tab, "") #form = Ui_Form(self) #self.tab_2 = QtWidgets.QWidget() #self.tab_2.setObjectName("tab_2") #self.tabWidget.addTab(self.tab_2, "") self.gridLayout.addWidget(self.tabWidget, 1, 0, 1, 6) #1,0,1,5 MainWindow.setCentralWidget(self.centralWidget) self.menuBar = QtWidgets.QMenuBar(MainWindow) self.menuBar.setGeometry(QtCore.QRect(0, 0, 1476, 22)) self.menuBar.setObjectName("menuBar") self.menuArchivo = QtWidgets.QMenu(self.menuBar) self.menuArchivo.setObjectName("menuArchivo") self.menuCircuito = QtWidgets.QMenu(self.menuBar) self.menuCircuito.setObjectName("menuCircuito") self.menuHerramientas = QtWidgets.QMenu(self.menuBar) self.menuHerramientas.setObjectName("menuHerramientas") MainWindow.setMenuBar(self.menuBar) self.statusBar = QtWidgets.QStatusBar(MainWindow) self.statusBar.setObjectName("statusBar") MainWindow.setStatusBar(self.statusBar) self.actionExit = QtWidgets.QAction(MainWindow) self.actionExit.setObjectName("actionExit") self.actionLoadSt = QtWidgets.QAction(MainWindow) self.actionLoadSt.setObjectName("actionLoadSt") self.actionStart = QtWidgets.QAction(MainWindow) self.actionStart.setObjectName("actionStart") self.actionPau = QtWidgets.QAction(MainWindow) self.actionPau.setObjectName("actionPau") self.actionSt = QtWidgets.QAction(MainWindow) self.actionSt.setObjectName("actionSt") self.actionEd = QtWidgets.QAction(MainWindow) self.actionEd.setObjectName("actionEd") self.actionRep = QtWidgets.QAction(MainWindow) self.actionRep.setObjectName("actionRep") self.menuArchivo.addAction(self.actionExit) self.menuCircuito.addAction(self.actionLoadSt) self.menuCircuito.addAction(self.actionStart) self.menuCircuito.addAction(self.actionPau) self.menuCircuito.addAction(self.actionSt) self.menuHerramientas.addAction(self.actionEd) self.menuHerramientas.addAction(self.actionRep) self.menuBar.addAction(self.menuArchivo.menuAction()) self.menuBar.addAction(self.menuCircuito.menuAction()) self.menuBar.addAction(self.menuHerramientas.menuAction()) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) self.comboBox.addItems(['Current','Voltage','Temperature','AH step','AH accum','Time']) self.cmbZoom.setEditable(True) self.cmbZoom.setValidator(QtGui.QRegExpValidator(QtCore.QRegExp("\\d\\d\\d?$"),self.centralWidget)) self.cmbZoom.addItems(['25%','50%','75%','100%','125%','150%','175%','200%']) self.cmbZoom.lineEdit().setAlignment(QtCore.Qt.AlignCenter) self.cmbZoom.setCurrentIndex(3) # self.comboBox.activated.connect(self.onCombo) self.cmbZoom.activated.connect(self.onCmbZoom) self.cmdDetener.clicked.connect(self.btnDetener) self.cmdPausar.clicked.connect(self.btnPausar) self.cmdIniciar.clicked.connect(self.btnIniciar) self.cmdCargar.clicked.connect(self.btnCargar) #self.paint = Paint(self) #self.selAllShort = QtWidgets.QShortcut(QtGui.QKeySequence(QtGui.QKeySequence.ZoomIn),self.paint,context= QtCore.Qt.WidgetShortcut,) #self.selAllShort.activated.connect(self.zoom_in) #self.selAllShort = QtWidgets.QShortcut(QtGui.QKeySequence(QtGui.QKeySequence.ZoomOut),self.paint,context= QtCore.Qt.WidgetShortcut,) #self.selAllShort.activated.connect(self.zoom_out) MainWindow.showEvent = self.showEvent MainWindow.closeEvent = self.closeEvent MainWindow.resizeEvent = self.resizeEvent self.tmp_server = list() # list temporal de Server self.tmp_total = list() # self.mylist = list() self.mylabel = list() self.rowCol = list() self.newlist = list() #addr con columnas self.tempAddr = list() self.maxTabs = list() #self.saveprograms = list() #guarda programs's name self.flagPage = False self.flagNormal = True self.flagWmin = False #Flag para ubuntu self.flagClose = False #self.flagProg = False # ------- list de moludos , labels,progressB,nameModules --------# self.labels = list() #self.progress = list() self.lblmodule = list() #self.scaleFactor = 1.0 self.MainWindow = MainWindow def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Formation Viewer")) self.cmdIniciar.setText(_translate("MainWindow", "Start")) self.cmdCargar.setText(_translate("MainWindow", "Load Programs / Start")) self.cmdDetener.setText(_translate("MainWindow", "Stop")) self.cmdPausar.setText(_translate("MainWindow", "Pause")) #self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Tab 1")) #self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Tab 2")) self.menuArchivo.setTitle(_translate("MainWindow", "File")) self.menuCircuito.setTitle(_translate("MainWindow", "Circuit")) self.menuHerramientas.setTitle(_translate("MainWindow", "Tools")) self.actionExit.setText(_translate("MainWindow", "Exit")) self.actionLoadSt.setText(_translate("MainWindow", "Load Programs / Start")) self.actionStart.setText(_translate("MainWindow", "Start")) self.actionPau.setText(_translate("MainWindow", "Pause")) self.actionSt.setText(_translate("MainWindow", "Stop")) self.actionEd.setText(_translate("MainWindow", "Profile Editor")) self.actionRep.setText(_translate("MainWindow", "Reports")) self.actionExit.triggered.connect(self.exitWindow) self.actionLoadSt.triggered.connect(self.btnCargar) self.actionStart.triggered.connect(self.btnIniciar) self.actionPau.triggered.connect(self.btnPausar) self.actionSt.triggered.connect(self.btnDetener) self.actionEd.triggered.connect(self.execProfileEd) self.actionRep.triggered.connect(self.fileReport) def showEvent(self,event): print("ShowEvent") if self.flagWmin != True: #Para ubuntu se necesito esta bandera self.flagWmin = True #if MainWindow.isMinimized(): #Para mac # pass #else: #----------------------------------- Obtiene hostname, port , addrs / serverConfig.ini ------------------------# settaddrs = QtCore.QSettings('/home/ditsa/DitsaNet/Settings/ServerConfig.ini',QtCore.QSettings.NativeFormat) if settaddrs.value('/home/ditsa/DitsaNet/Settings/ServerConfig.ini') !='': tmpAddr = settaddrs.value("servers") #nombre de server y port for i in range(3,len(tmpAddr),4): self.tmp_server.clear() x = tmpAddr[i].rpartition('-') val1 = int(x[0]) #val2 = int(x[2]) self.tmp_server.append(str(val1)) for j in range(15): y = val1 + j + 1 self.tmp_server.append(str(y)) self.tempAddr.append(self.tmp_server[:]) self.tmp_total.append(str(self.tmp_server[:])) for k in range(0,len(tmpAddr),4): #guarda el hostname, el port y password useHostname.append(tmpAddr[k]+".local") usePort.append(int(tmpAddr[k+1])) usePassw.append(tmpAddr[k+2]) ''' settprog = QtCore.QSettings('/home/ditsa/DitsaNet/Settings/fileprograms.ini', QtCore.QSettings.NativeFormat) if settprog.value('/home/ditsa/DitsaNet/Settings/fileprograms.ini') !='': tmp = settprog.value("saveprograms") if tmp != None and len(tmp) != 0: self.saveprograms = tmp[:] self.flagProg = True print("savePR:",self.saveprograms) #esta opcion no puede ser viable por que los gabinetes y addr puede cambiar ''' #-----------------------------------Obtiene mylist, mylabel, rowcol / archivo.ini -----------------------------# settings = QtCore.QSettings('/home/ditsa/DitsaNet/Settings/archivo.ini', QtCore.QSettings.NativeFormat) if settings.value('/home/ditsa/DitsaNet/Settings/archivo.ini')!='': self.settingsList = settings.value("mylist") self.settingsLabel = settings.value("mylabel") self.settingsRowCol = settings.value("rowcol") if self.settingsRowCol != None and len(self.settingsRowCol) !=0: self.rowCol = self.settingsRowCol[:] else: self.rowCol.append('1%') self.rowCol.append('R=10 C=10') if self.settingsList != None: self.mylist = self.settingsList[:] #para que no correspondan con el mismo objeto for i in range(2,len(self.mylist),4): self.newlist.append(self.mylist[i].replace('N=','')) ordName = NameOrdened(self.newlist) #manda a llamar la clase NameOrdened x = ordName.cod() #ordena los elementos de la lista de < a > self.newlist.clear() #Los valores de neewlist son todas las addr que se muestran en la app DitsaEditor for i in range(len(x)): #Extrae address ingresados en DitsaEditor for j in range(2,len(self.mylist),4): if "N="+str(x[i]) == self.mylist[j]: self.newlist.append(self.mylist[j-2]) self.newlist.append(self.mylist[j-1]) self.newlist.append(self.mylist[j]) self.newlist.append(self.mylist[j+1]) if self.settingsLabel != None: self.mylabel = self.settingsLabel[:] #para que no correspondan con el mismo objeto if self.settingsList != None or self.settingsLabel != None: # Populate Tables self.populateTabs() self.paint = Paint(self) self.tabWidget.addTab(self.paint, "Page 1") tabC = self.tabWidget.count() MainWindow.showMaximized() self.paint.setSceneRect(0,0,0,0) if (self.settingsList != None and len(self.settingsList)!=0) or (self.settingsLabel != None and len(self.settingsLabel)!=0): for i in range(int(self.numTabT)-tabC): self.newPage() self.onCmbZoom() for j in range(len(useHostname)): BCmb.pingDataClient(useHostname[j],usePort[j],self.tmp_total[j]) #envia las addr de los modulos print("Inicia Poleo") #poleo es lo primero en iniciar despues de llenar screen self.threadData(True) #Inicia el poleo time.sleep(0.3) self.valueData() #obtiene los valores del poleo del sever def closeEvent(self,event): print("closeEvent") self.flagClose = True time.sleep(0.5) self.threadTimer(False) self.threadData(False) def threadData(self,flag): #print("threadData") if flag == True: shared.lock_client.acquire() self.dataThread = None self.dataThread = DataListenerMemory(self.testsCallback) self.dataThread.start() shared.lock_client.release() else: self.dataThread.stop() def exitWindow(self): self.MainWindow.close() def execProfileEd(self): #open otra gui diferente subprocess.Popen(['python3','/opt/Ditsa/ProfileEditor/ProfileEditorApp.py']) def fileReport(self): print("REPORT") #verificar esta parte como realizarla mas eficiente QtGui.QGuiApplication.processEvents() FilesReport(usePassw) #recibe carpeta(FormationDataFiles) de server ventana = QtWidgets.QWidget() uif = Ui_FormTable() uif.setupUi(ventana) ventana.show() def threadTimer(self,flag): #print("ThreadTimer") if flag == True: self.t = None self.t = threading.Timer(1, self.valueData) self.t.start() else: self.t.cancel() def populateTabs(self): #print("populateTabs") for i in range(0,len(self.settingsList),4): self.maxTabs.append(self.settingsList[i]) for i in range(0,len(self.settingsLabel),3): self.maxTabs.append(self.settingsLabel[i]) if len(self.maxTabs)!= 0: y = max(self.maxTabs) self.numTabT = y.replace('%','') self.maxTabs.clear() def newPage(self): #print("newPage") self.flagPage = True self.flagNormal = False self.paint = Paint(self) self.paint.setSceneRect(0,0,0,0) self.tabWidget.addTab(self.paint,"Page "+str(self.tabWidget.count()+1)) def onCmbZoom(self): ###verificar funcionamiento print("cmbZoom") ##se puede cambiar aun no finalizado textcmb = self.cmbZoom.currentText() y = textcmb.split('%') value = ''.join(y) det = int(value) / 125 form = self.tabWidget.currentWidget() form.zoomCmb(det) def testsCallback(self, msg): _translate = QtCore.QCoreApplication.translate if "DL[PASS]" in msg: msg = msg.replace("DL[PASS]:","") cbText = self.comboBox.currentText() #cbText2 = self.comboBox.currentIndex()+1 if cbText == 'Current': cbText2 = 1 pref = " A" elif cbText == 'Voltage': cbText2 = 2 pref = " V" elif cbText == 'Temperature': cbText2 = 3 pref = " C" elif cbText == 'Time': cbText2 = 8 pref = '' elif cbText == 'AH step': cbText2 = 4 pref = " AH" elif cbText == 'AH accum': pref = " AH" cbText2 = 5 for i in range(1,len(self.labels),3): addr = self.labels[i+1] font = QtGui.QFont() font.setFamily("Ubuntu Light") font.setPointSize(12) #checar si es necesario cambiar font.setBold(True) font.setWeight(75) self.labels[i].setFont(font) if shared.DEV[addr][0] == False: # state - No comm font = QtGui.QFont() font.setFamily("Ubuntu Light") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.labels[i].setFont(font) self.labels[i].setText("NO COMM") self.labels[i].setStyleSheet("QLabel {background-color : gold; color : black; border: 1px solid black;} ") self.labels[i].setAlignment(QtCore.Qt.AlignCenter) else: self.labels[i].setText(shared.DEV[addr][cbText2]+pref) self.labels[i].setToolTip(_translate("MainWindow", "Name: "+self.lblmodule[i].text()+"\n" "Status: "+shared.DEV[addr][12]+"\n" #ch,pause,finished "Current: "+shared.DEV[addr][1]+"\n" "Voltage: "+shared.DEV[addr][2]+"\n" "Temperature: "+shared.DEV[addr][3]+"\n" "AH: "+shared.DEV[addr][4]+"\n" "AHc: "+shared.DEV[addr][5]+"\n" "Program Name: "+shared.DEV[addr][11]+"\n" "Program Step: "+shared.DEV[addr][6]+"\n" "Step State: "+shared.DEV[addr][7]+"\n" "Step time: "+shared.DEV[addr][8]+"\n")) #"Tiempo Restante: 00:00\n" #"End Time: 12/04/2019 20:13\n")) #"ServerID: 0\n" #"FirstN: 0")) if (shared.DEV[addr][12] == 'I') or (shared.DEV[addr][12] == 'S'): #state - Stop or Initial self.labels[i].setStyleSheet("QLabel {background-color : lightblue; color : black; border: 1px solid black;} ") self.labels[i].setAlignment(QtCore.Qt.AlignCenter) #self.progress[i].setValue(0) elif shared.DEV[addr][12] == 'E': #state - End Program self.labels[i].setStyleSheet("QLabel {background-color : orange; color : black; border: 1px solid black;} ") self.labels[i].setAlignment(QtCore.Qt.AlignCenter) #self.progress[i].setValue(0) elif shared.DEV[addr][12] == 'R': #state - Running self.labels[i].setStyleSheet("QLabel {background-color : limegreen; color : black; border: 1px solid black;} ") self.labels[i].setAlignment(QtCore.Qt.AlignCenter) elif shared.DEV[addr][12] == 'P': #state - Pause self.labels[i].setStyleSheet("QLabel {background-color : mediumpurple; color : black; border: 1px solid black;} ") self.labels[i].setAlignment(QtCore.Qt.AlignCenter) elif (shared.DEV[addr][12] == 'T') or (shared.DEV[addr][12] == 'W'): #state - temp-hight or current warning self.labels[i].setStyleSheet("QLabel {background-color : red; color : black; border: 1px solid black;} ") self.labels[i].setAlignment(QtCore.Qt.AlignCenter) #red ''' #-------------------------- Progress Bar ---------------------------# for j in range(1,len(self.progress),3): addr = self.progress[j+1] if shared.DEV[addr][0] != False: if float(shared.DEV[addr][6])*100 == 0: self.progress[j].setValue(0) else: value = float(shared.DEV[addr][6])*100 / float(shared.DEV[addr][7]) self.progress[j].setValue(value) ''' def valueData(self): print("VALUEDATA") shared.lock_client.acquire() for j in range(len(useHostname)): memoryData = BCmb.memoryDataClient(useHostname[j],usePort[j]) #time.sleep(0.3) if memoryData!= None: #Tiene comm con server addr_list = self.tempAddr[j] for i in range(len(addr_list)): address = int(addr_list[i]) TempData = memoryData[i].split(',') #print("TempData:",TempData) dat1 = str(TempData[0]).replace('{','') #print("data1:",dat1) if dat1 == 'True' and len(TempData) == 13: TempData[12] = str(TempData[12]).replace('}','') TempData[0] = True shared.DEV[address][0] = TempData[0] #we store current shared.DEV[address][1] = str(TempData[1].replace('I','')) #we store voltage shared.DEV[address][2] = str(TempData[2].replace('V','')) #we store temperature shared.DEV[address][3] = str(TempData[3].replace('T','')) #we store step number and type shared.DEV[address][4] = str(TempData[4].replace('AH','')) #we store amper accumulate shared.DEV[address][5] = str(TempData[5].replace('AC','')) #we store step number shared.DEV[address][6] = str(TempData[6].replace('P','')) #we store time of current status shared.DEV[address][7] = str(TempData[7].replace('S','')) #we store current time program shared.DEV[address][8] = str(TempData[8].replace('t','')) #we store the total time program shared.DEV[address][9] = str(TempData[9].replace('Tt','')) #we store the total time program shared.DEV[address][10] = str(TempData[10].replace('TT','')) #we store the name program shared.DEV[address][11] = str(TempData[11].replace('N','')) #we store the total time program shared.DEV[address][12] = str(TempData[12].replace('','')) elif dat1 == 'False}': TempData[0] = str(TempData[0]).replace('}','') shared.DEV[address][0] = False #print("TempData2:",TempData) if self.flagClose != True: self.threadTimer(True) else: self.threadTimer(False) shared.lock_client.release() count = 0 def resizeEvent(self,event): #verificar con ubuntu como trabaja #print("changeEvent") self.count+= 1 if self.count != 1: if MainWindow.isMaximized() and self.flagNormal != True: self.flagNormal = True #MainWindow.showNormal() #asigna el valor original del resize x = self.tabWidget.currentWidget() x.showEvent(event) else: self.flagPage = False self.flagNormal = False #MainWindow.showMaximized() x = self.tabWidget.currentWidget() x.showEvent(event) def btnDetener(self): print("Detener") Ui_stopModule(self).exec_() #self.threadData(True) def btnPausar(self): print("Pausar") Ui_pauseModule(self).exec_() #self.threadData(True) def btnIniciar(self): print("Iniciar") Ui_runModule(self).exec_() #self.threadData(True) def btnCargar(self): print("Cargar") Ui_WindowCh(self).exec_() self.threadData(True) self.valueData() '''
def on_press(key): current.add(key) order.append(key) ctrl: bool = Key.ctrl_l in current or Key.ctrl_r in current alt: bool = Key.alt_l in current speed = 300 zoom = 15 if [Key.esc, Key.esc, Key.esc] == order[-3:]: Paint.stop() States.running = False elif Key.f2 == key: States.switchPlot = True elif Key.f7 == key: States.save = True elif Key.f4 == key: Paint.switch(game.layers.width, game.layers.height) elif Key.left == key and ctrl: Paint.dim = (Paint.dim - 1) % game.layers.batch elif Key.right == key and ctrl: Paint.dim = (Paint.dim + 1) % game.layers.batch elif Key.f3 == key: States.slow = not States.slow elif Key.right == key and alt: Paint.move(speed, 0, game.layers.width, game.layers.height) elif Key.left == key and alt: Paint.move(-speed, 0, game.layers.width, game.layers.height) elif Key.down == key and alt: Paint.move(0, speed, game.layers.width, game.layers.height) elif Key.up == key and alt: Paint.move(0, -speed, game.layers.width, game.layers.height) elif Key.down == key and ctrl: Paint.zoom(-zoom, game.layers.width, game.layers.height) elif Key.up == key and ctrl: Paint.zoom(zoom, game.layers.width, game.layers.height) elif Key.pause == key: States.isPaused = True
new_saver.restore(sess, os.path.join("saved", "model")) x = graph.get_operation_by_name("x").outputs[0] y_ = graph.get_operation_by_name("y_").outputs[0] keep_prob = graph.get_operation_by_name("keep_prob").outputs[0] conv = tf.get_collection("conv")[0] while not done_ref[0]: mnist_like_image = [ np.array(list(img_ref.resize([28, 28]).tobytes()), dtype='float32') ] res = conv.eval(feed_dict={ x: mnist_like_image, y_: [[0 for x in range(10)]], keep_prob: 1.0 }) data_ref[:] = [] data_ref.extend(res[0]) time.sleep(0.1) if __name__ == '__main__': img = Image.new("P", [600, 600]) data = [0.1 for x in range(0, 10)] done = [False] t = threading.Thread(target=th1, args=(img, data, done)) t.start() ge = Paint(img, data) done[0] = True
user32 = ctypes.windll.user32 user32.SetProcessDPIAware() [monitor_width, monitor_height] = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)] face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') # capture = cv2.VideoCapture('http://192.168.43.245:8080/video') capture = cv2.VideoCapture(0) ret, frame = capture.read() paint = Paint(frame) paint.color_changer_colors.extend([(255, 0, 0), (255, 255, 0), (0, 255, 255), (128, 128, 128), (150, 75, 0), (255, 127, 0), (191, 0, 255), (0, 0, 0), (255, 0, 255), (0, 255, 255), (143, 0, 255)]) paint.pause = True exit = False while not exit: ret, frame = capture.read() # flip kamera supaya mirror img = cv2.flip(frame, 1) # painting
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1233, 862) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.label_3 = QtWidgets.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(840, 300, 51, 16)) self.label_3.setObjectName("label_3") self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(840, 130, 41, 21)) self.label_2.setObjectName("label_2") self.label_4 = QtWidgets.QLabel(self.centralwidget) self.label_4.setGeometry(QtCore.QRect(840, 240, 61, 16)) self.label_4.setObjectName("label_4") self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setGeometry(QtCore.QRect(910, 130, 221, 20)) self.lineEdit_2.setObjectName("lineEdit_2") self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setGeometry(QtCore.QRect(910, 90, 221, 20)) self.lineEdit.setObjectName("lineEdit") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(840, 180, 71, 23)) self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(1060, 180, 71, 23)) self.pushButton_2.setObjectName("pushButton_2") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(840, 90, 41, 21)) self.label.setObjectName("label") self.textEdit = QtWidgets.QTextEdit(self.centralwidget) self.textEdit.setGeometry(QtCore.QRect(840, 340, 291, 301)) self.textEdit.setObjectName("textEdit") self.label_5 = QtWidgets.QLabel(self.centralwidget) self.label_5.setGeometry(QtCore.QRect(960, 240, 111, 16)) self.label_5.setObjectName("label_5") self.openGLWidget = Paint(self.centralwidget) self.openGLWidget.setGeometry(QtCore.QRect(100, 90, 591, 551)) self.openGLWidget.setObjectName("openGLWidget") self.pushButton_RST = QtWidgets.QPushButton(self.centralwidget) self.pushButton_RST.setGeometry(QtCore.QRect(840, 720, 291, 61)) self.pushButton_RST.setObjectName("pushButton_RST") self.horizontalSlider = QtWidgets.QSlider(self.centralwidget) self.horizontalSlider.setGeometry(QtCore.QRect(100, 680, 591, 31)) self.horizontalSlider.setMaximum(5760) self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider.setObjectName("horizontalSlider") self.horizontalSlider_2 = QtWidgets.QSlider(self.centralwidget) self.horizontalSlider_2.setGeometry(QtCore.QRect(100, 720, 591, 31)) self.horizontalSlider_2.setMaximum(5760) self.horizontalSlider_2.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider_2.setObjectName("horizontalSlider_2") self.horizontalSlider_3 = QtWidgets.QSlider(self.centralwidget) self.horizontalSlider_3.setGeometry(QtCore.QRect(100, 760, 591, 31)) self.horizontalSlider_3.setMaximum(5760) self.horizontalSlider_3.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider_3.setObjectName("horizontalSlider_3") self.label_x = QtWidgets.QLabel(self.centralwidget) self.label_x.setGeometry(QtCore.QRect(710, 680, 51, 31)) self.label_x.setObjectName("label_x") self.label_y = QtWidgets.QLabel(self.centralwidget) self.label_y.setGeometry(QtCore.QRect(710, 720, 51, 31)) self.label_y.setObjectName("label_y") self.label_z = QtWidgets.QLabel(self.centralwidget) self.label_z.setGeometry(QtCore.QRect(710, 760, 51, 31)) self.label_z.setObjectName("label_z") self.pushButton_CL = QtWidgets.QPushButton(self.centralwidget) self.pushButton_CL.setGeometry(QtCore.QRect(840, 650, 291, 61)) self.pushButton_CL.setObjectName("pushButton_CL") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1233, 23)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow)