def playDungeon(self): if self.workerThread is not None: self.stopDungeon() self.workerThread = WorkerThread() self.setEngineState(EngineState.Playing) self.workerThread.function = self.engine.start_infinite_play self.workerThread.start()
def __init__(self): WorkerThread.__init__(self) self.setName("CalculationWorker") self.privateRun = False #setup the IOs self.privateA = IO_POINT_T() self.privateB = IO_POINT_T() self.privateC = IO_POINT_T() self.privateA.name = "io-a" self.privateB.name = "io-b" self.privateC.name = "io-c" self.privateA.ion_data_type = 8 self.privateB.ion_data_type = 8 self.privateC.ion_data_type = 8 self.privateA.io_id = 1 self.privateB.io_id = 2 self.privateC.io_id = 3 self.sleep_interval = 60 self.target_device_id = 274 self.simulator_csv_path = os.path.join(script_dir, "simulated_data.csv") #flag to stop csv simulator self.csv_stop = False
def start(self): #Read config self.__config_file = Defaults.ServerConfigDir + Defaults.ConfigDefaults['config_file'] self.__max_threads = int(ConfDB().get('Server', 'max_threads', Defaults.ConfigDefaults['max_threads'])) self.__max_clients = int(ConfDB().get('Server', 'max_clients', Defaults.ConfigDefaults['max_clients'])) self.__max_request_size = int(ConfDB().get('Server', 'max_request_size', Defaults.ConfigDefaults['max_request_size'])) ports = ConfDB().get('Server', 'listening_ports', Defaults.ConfigDefaults['listening_ports']).split() for port in ports: sock = ServerSocket('127.0.0.1', int(port)) self.__listening_sockets.append(sock) self.__mutex = threading.RLock() self.__cond = threading.Condition() self.__queue = Queue(self.__max_clients) self.__sq_full = threading.Condition() self.__sq_empty = threading.Condition() #Start master (listening) thread master_thread = MasterThread('MasterThread') master_thread.start() #Start worker threads for i in range(self.__max_threads): try: worker_thread = WorkerThread(str(i)) worker_thread.start() self.__num_threads += 1 except: print 'some error'
def __init__(self, parentThread, layer, idx, max_zone=None, filler=0): WorkerThread.__init__(self, parentThread) self.layer = layer self.idx = idx self.max_zone = max_zone self.matrix = None self.error = None self.filler = filler
def __init__(self, parentThread, graph, result): WorkerThread.__init__(self, parentThread) self.graph = graph self.result = result self.skim_matrices = np.zeros((result.zones, result.zones, result.num_skims), np.float64) #self.cores = cores self.error = None self.evol_bar = 0 #evol_bar
def pauseDungeon(self): if self.workerThread is not None: try: self.setEngineState(EngineState.StopInvoked) new_thread = WorkerThread() new_thread.function = self._stopEngineUnsafe new_thread.start() except Exception as e: logger.info("Trying to kill process resulted in: %s" % str(e))
def __init__(self): self.connected = False self._client: AdbClient = None self.my_device: Device = None self._host = '127.0.0.1' self._port = 5037 self.connectionChangedFunctions = [] self.checkingConnectionFunctions = [] self.connectionCheckThread = WorkerThread() self._continousCheckStopRequired = False self._startConnectionCheck()
class MainController(object): def __init__(self, model): self.model = model def run_test(self, test_name): if test_name == 'testAll': self.model.prepare_test(6) # 6 means a total of six tests will be run. self.test_all = TestAllThread(self.model) self.test_all.start() else: self.model.prepare_test(1) self.worker = WorkerThread(self.model, test_name) self.worker.start()
def __init__(self, parentThread, netlayer, linkid, ablength, bidirectional, directionfield, balength, skims, selected_only, featcount): WorkerThread.__init__(self, parentThread) self.netlayer = netlayer self.linkid = linkid self.ablength = ablength self.balength = balength self.bidirectional = bidirectional self.directionfield = directionfield self.skims = skims self.selected_only = selected_only self.features = None self.featcount = featcount self.error = None
def __init__(self, parentThread, flayer, tlayer, ffield, tfield, fmatch, tmatch, operation): WorkerThread.__init__(self, parentThread) self.flayer = flayer self.tlayer = tlayer self.ffield = ffield self.tfield = tfield self.fmatch = fmatch self.tmatch = tmatch self.operation = operation self.error = None self.sequence_of_searches = [ 1, 5, 10, 20 ] # The second element of this list is the number of nearest
def __init__(self, parentThread, line_layer, new_line_layer, node_layer=False, node_ids=False, new_node_layer=False, node_start=0): WorkerThread.__init__(self, parentThread) self.line_layer = line_layer self.node_layer = node_layer self.node_ids = node_ids self.new_node_layer = new_node_layer self.new_line_layer = new_line_layer self.node_start = node_start self.error = None
def run_test(self, test_name): if test_name == 'testAll': self.model.prepare_test(6) # 6 means a total of six tests will be run. self.test_all = TestAllThread(self.model) self.test_all.start() else: self.model.prepare_test(1) self.worker = WorkerThread(self.model, test_name) self.worker.start()
def __init__(self, parentThread, node_layer_name, link_layer_name, centroid_layer_name, node_ids, centroids_ids, max_length, max_connectors, new_line_layer_name, new_node_layer_name, selection_only): WorkerThread.__init__(self, parentThread) self.link_layer_name = link_layer_name self.node_layer_name = node_layer_name self.centroid_layer_name = centroid_layer_name self.node_ids = node_ids self.centroids_ids = centroids_ids if max_length is None: max_length = 1000000000000 self.max_length = max_length self.max_connectors = max_connectors self.new_line_layer_name = new_line_layer_name self.new_node_layer_name = new_node_layer_name self.selection_only = selection_only self.error = None
def __init__(self, parent=None): QWidget.__init__(self, parent) self.ui = uic.loadUi("Beamshutter.ui", self) self.control = QAxContainer.QAxWidget(self) self.control.setControl('{3CE35BF3-1E13-4D2C-8C0B-DEF6314420B3}') self.control.setProperty("HWSerialNum", 85845031) self.control.setGeometry(0, 0, 600, 400) self.mutex = QMutex(mode=QMutex.Recursive) self.shutterReplied = False self.shut = Beamshutter(self) self.worker = WorkerThread() self.ui.mainLayout.addWidget(self.control) self.layout().setAlignment(Qt.AlignCenter) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHeightForWidth(True) self.setSizePolicy(sizePolicy)
def __init__(self): WorkerThread.__init__(self) self.setName("CalculationWorker") self.privateRun = False #setup the IOs self.privateA = IO_POINT_T() self.privateB = IO_POINT_T() self.privateC = IO_POINT_T() self.privateA.name = "io-a" self.privateB.name = "io-b" self.privateC.name = "io-c" self.privateA.ion_data_type = 8 self.privateB.ion_data_type = 8 self.privateC.ion_data_type = 8 self.privateA.io_id = 1 self.privateB.io_id = 2 self.privateC.io_id = 3
def __init__(self, address, port): self.server_address = address self.server_port = port self.socket_family = socket.AF_INET self.socket_type = socket.SOCK_STREAM self.socket = socket.socket(self.socket_family, self.socket_type) self.socket.bind((self.server_address, self.server_port)) self.socket.listen(10) self.socket.setblocking(False) self.connection_queue = [] self.lock = threading.Lock() self.running = False self.worker = WorkerThread(self)
def __init__(self,parent=None): QWidget.__init__(self,parent) self.ui=uic.loadUi("Beamshutter.ui",self) self.control = QAxContainer.QAxWidget(self) self.control.setControl('{3CE35BF3-1E13-4D2C-8C0B-DEF6314420B3}') self.control.setProperty("HWSerialNum",85845031) self.control.setGeometry(0,0,600,400) self.mutex=QMutex(mode =QMutex.Recursive) self.shutterReplied=False self.shut=Beamshutter(self) self.worker=WorkerThread() self.ui.mainLayout.addWidget(self.control) self.layout().setAlignment(Qt.AlignCenter) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHeightForWidth(True) self.setSizePolicy(sizePolicy)
def start_btn_clicked(self): if self.is_file_selected is True: self.ui.open_file_btn.setEnabled(False) self.ui.start_btn.setEnabled(False) # Pass the function to execute worker = WorkerThread(self.file_path, self.neuralNetwork.learn) worker.signals.finished.connect(self.learning_complete) worker.signals.error.connect(self.learning_error) worker.signals.result.connect(self.learning_result) worker.signals.progress.connect(self.learning_progress_update) # Execute self.thread_pool.start(worker) else: msgBox = QMessageBox() msgBox.setWindowTitle("Грешка") msgBox.setText("Моля изберете файл") ret = msgBox.exec()
def do(self): tpool = WorkerThreadPool() i = 0 results = [] while True: for x in range(0, int(self.__threads)): try: proxy = self.__proxies.pop() proxy = "{0}:{1}".format(proxy[0], proxy[1]) thread = WorkerThread(func=self.__testProxyThreaded, args=[results, proxy]) tpool.addThread(thread) i += 1 except IndexError: pass tpool.isAllThreadsDone() print("Proxies left to check: {0}".format(len(self.__proxies))) if len(self.__proxies) == 0: break return results
def init(self): """ Designated initializer. Returns self (as per ObjC designated initializer definition, unlike Python's __init__() method). """ self.bookmarksArray = [] #NSMutableArray.array() self = self.initWithWindowNibName_("EYETest") self._toolbarItems = {} self._toolbarDefaultItemIdentifiers = [] self._toolbarAllowedItemIdentifiers = [] self._editorname = "/Applications/TextEdit.app" self.searchTextField="" self._methodList = [] self._working = 0 self._windowIsClosing = 0 self._workerThread = WorkerThread() self._workerThread.start() NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "handleEditorChange:",u"JMEditorChanged",None) return self
class GameControllerModel(QObject): engineStatechanged = pyqtSignal(EngineState) connectionStateChanged = pyqtSignal(bool) checkConnectionStateChanged = pyqtSignal(bool) resolutionChanged = pyqtSignal(str) dataFolderChanged = pyqtSignal(str) def __init__(self): super(QObject, self).__init__() # Default data self.engine = CaveEngine() self.engine.device_connector.setFunctionToCallOnConnectionStateChanged( self.onDevConnChanged) self.engine.device_connector.setFunctionToCallOnCheckingConnectionStateChanged( self.onDevCheckConnectionChanged) self.dict_buttons = "data.py" self.ch_images_path = "ui_chapters/" self.ch_image_ext = ".png" self.icon_path = "icons" self.icons_dataset = self.load_icons() self.currentEngineState: EngineState = EngineState.Ready self.chapters = [ "1. Verdant Prairie", "2. Storm Desert", "3. Abandoned Dungeon", "4. Crystal Mines", "5. Lost Castle", "6. Cave of Bones", "7. Barens of Shadow", "8. Silent Expanse", "9. Frozen Pinnacle", "10. Land of Doom", "11. The Capital", "12. Dungeon of Traps", "13. Lava Land", "14. Eskimo Lands", ] self.allowed_chapters = [3, 6, 10] self.workerThread: WorkerThread = None def connected(self): return self.engine.device_connector.connected def onDevConnChanged(self): self.connectionStateChanged.emit( self.engine.device_connector.connected) def onDevCheckConnectionChanged(self, state): self.checkConnectionStateChanged.emit(state) def requestClose(self): self.engine.device_connector.stopConnectionCheck() if self.currentEngineState == EngineState.Ready: logger.info("Stopping engine... ") self._stopEngineUnsafe() self.workerThread = None self.engine = None def _changeConnectedstate(self, conn: bool): self.connectionStateChanged.emit(conn) def load_data(self): pass def getLevelsNames(self): return self.engine.levels_type def load_icons(self): icons_dts = {} icons_dts["prev"] = "Start.png" icons_dts["play"] = "Play.png" icons_dts["pause"] = "Pause.png" icons_dts["next"] = "End.png" icons_dts["stop"] = "Stop.png" return icons_dts def getChapters(self) -> list: return self.chapters def getChapterImagePath(self, ch_number: int) -> str: return os.path.join(self.ch_images_path, "ch" + str(ch_number) + self.ch_image_ext) def getChNumberFromString(self, ch_str) -> int: for i, ch in enumerate(self.chapters): if ch == ch_str: return i + 1 return -1 def getIconPath(self, icon_name): if icon_name in self.icons_dataset.keys(): path = os.path.join(self.icon_path, self.icons_dataset[icon_name]) else: path = os.path.join(self.icon_path, "Error-Delete-Icon.png") return path def playDungeon(self): if self.workerThread is not None: self.stopDungeon() self.workerThread = WorkerThread() self.setEngineState(EngineState.Playing) self.workerThread.function = self.engine.start_infinite_play self.workerThread.start() def waitForEngineEnd(self): if self.workerThread is not None: self.workerThread.join() def setEngineState(self, state: EngineState): self.currentEngineState = state self.engineStatechanged.emit(state) def _stopEngineUnsafe(self): try: self.engine.setStopRequested() self.waitForEngineEnd() self.workerThread = None self.setEngineState(EngineState.Ready) except Exception as e: logger.info("Trying to kill process resulted in: %s" % str(e)) def pauseDungeon(self): if self.workerThread is not None: try: self.setEngineState(EngineState.StopInvoked) new_thread = WorkerThread() new_thread.function = self._stopEngineUnsafe new_thread.start() except Exception as e: logger.info("Trying to kill process resulted in: %s" % str(e)) def stopDungeon(self): self.pauseDungeon() self.engine.changeCurrentLevel(0) def changeChapterToPlay(self, new_chapter): self.engine.changeChapter(new_chapter)
def __init__(self): #INITIALIZE AND SHOW GUI... super(Main, self).__init__() self.ui=CC_Main() self.ui.setupUi(self) self.ui.lineEdit.setText("Programmer") self.ui.lineEdit_3.setText("Toronto") self.ui.tableWidget.addFuncPointers({"getProfileData": self.getProfileData}) self.show() #Used to keep the log from being finalized multiple times... self.run_once = 0 self.widgets_on = True #Keep track of which positions are valid for automation... self.good_list = [] self.complex_list = [] self.bad_list = [] #See if saved data exists, and load if it does... fin = None try: fin = open("./data/past_app_sessions.pickle", "rb") log.append("Found previous application history data! loading into memory...", entity="main") except: log.append("No previous application history data found... skipping load.", entity="main") if fin != None: container = p_load(fin) self.good_list = container['good_list'] self.complex_list = container['complex_list'] self.bad_list = container['bad_list'] self.last_row = -1 log.append('Initializing...') #Redirect STDOUT and STDERR self.redir = StdRedir(log) self.ui.logWidget.loadConnection(self.redir.stdout_receiver.new_data) self.ui.logWidget.setLog(log) self.ui.tableWidget.setLog(log) self.redir.startThreads() #SETUP SIGNALS/SLOTS... self.ui.pushButton_2.clicked.connect(self.do_search) self.ui.pushButton_4.clicked.connect(self.applyToSelected) self.ui.lineEdit.returnPressed.connect(self.do_search) self.ui.lineEdit_3.returnPressed.connect(self.do_search) self.ui.newStyleButton.clicked.connect(self.ui.tableWidget._newStyle) app.aboutToQuit.connect(self.closingCode) #SETUP *CUSTOM* WORKERTHEAD SIGNALS self.worker = WorkerThread("*****@*****.**", "unkQRXen9", log) self.worker.search_complete.connect(self.process_search) self.worker.profiling_complete.connect(self.ui.tableWidget.setRowData) self.worker.job_tasks.connect(self.ui.loadBar.prepLoadBar) self.worker.task_complete.connect(self.ui.loadBar.updateLoadBar) self.worker.finished.connect(self.release_widgets) self.worker.submission_complete.connect(self.done_application) #LOGIN TO SITE! self.lockout_widgets() self.worker.start() log.append('Initialization Complete!') #Set focus to the search button initially... self.ui.pushButton_2.setFocus()
class Main(QMainWindow): def closingCode(self): #Everything is enclosed in this condition to prevent operations occuring multiple times... if self.run_once == 0: self.run_once = 1 #Create and display the HTML-Log log.writeLog() #Save job application data... fout = open("./data/past_app_sessions.pickle", "wb") all_lists = {"good_list": self.good_list, "complex_list": self.complex_list, "bad_list": self.bad_list} p_dump(all_lists, fout) #Exit the program sys.exit(0) def process_search(self, status, results): log.append("Beginning to add search results to table...", entity="main") if not self.ui.checkBox.isChecked(): log.append("Performing new search and NOT appending results to previous one...", entity="main") self.ui.tableWidget.removeAllRows() #Loop through results and add to table... for i, row in enumerate(results): rowData = {'Position': row[0][1], 'Company': row[2][1], 'Location': row[4][1], 'Date': row[3][1], 'Link': row[1][1], 'Job Address': "N/A", 'Job ID': "N/A"} self.ui.tableWidget.addRow(rowData) log.append("Search job has been completed!") def do_search(self): self.lockout_widgets() self.worker.setAction("SEARCH", position=str(self.ui.lineEdit.text()), location=str(self.ui.lineEdit_3.text())) self.worker.start() def adjust_string(self, text): text = str(text) for i in reversed(range(len(text))): if text[i:i+1].isalpha() or text[i:i+1] == ')' or text[i:i+1] == ']': return text[:i+1] def saveReport(self): rep = Report('D:\\Projects\\CC v2\\', 'Application Report - '+str(time.strftime("%B %d, %Y"))+'.docx') rep.addList(self.good_list, "1 - Applications which went through successfully:") rep.addList(self.complex_list, "2 - Applications which did NOT go through, but were close:") rep.addList(self.bad_list, "3 - Applications which cannot be automated:") rep.saveReport() #for item in self.good_list: def applyToSelected(self): #Lock input widgets if they are not already... if self.widgets_on: self.lockout_widgets() #Get cover-letter stuff ready... cl_template = None cover_letter1 = None with open("Templates/Cover Letters/COVERLETTER_TEMPLATE.txt", "rb") as fin: cl_template = fin.read() #Cycle through all results, only acting on those with a chosen template... finished_applications = True for i in range(self.last_row + 1, self.ui.tableWidget.rowCount()): log.append("Checking row #"+str(i+1)+"...", entity="main") posting = self.ui.tableWidget.getRow(i) style = self.ui.tableWidget.getRowStyle(i) if style[0] != "None": finished_applications = False log.append("Row #"+str(i+1)+" has a set style! Preparing cover letter...", entity="main") #Fill in key data pertaining to this application cover_letter1 = cl_template.replace("<<DATE>>", str(time.strftime("%B %d, %Y"))) cover_letter1 = cover_letter1.replace("<<COMPANY>>", self.adjust_string(posting['Company'])) if posting['Job Address'] == "N/A": cover_letter1 = cover_letter1.replace("<<ADDRESS>>", self.adjust_string(posting['Job Address'])) else: cover_letter1 = cover_letter1.replace("<<ADDRESS>>", self.adjust_string(posting['Location'])) cover_letter1 = cover_letter1.replace("<<COUNTRY>>", "Canada") cover_letter1 = cover_letter1.replace("<<POSITION>>", self.adjust_string(posting['Position'])) cover_letter1 = cover_letter1.replace("<<SERVICE>>", "Monster.ca") cover_letter1 = cover_letter1.replace("<<MAIN_BODY>>", style[1]) print cover_letter1 #TESTING: CHECK END-RESULT COVER LETTER self.current_row = i self.worker.setAction("APPLY", posting_link=posting['Link'], job_id=str(str(posting['Job ID'])), cover_letter=cover_letter1) self.worker.start() self.last_row = i break if finished_applications: msgBox = QMessageBox() msgBox.setText("Applications have been completed! Click Ok to save report and finish.") msgBox.exec_() self.saveReport() self.release_widgets() def lockout_widgets(self): self.ui.pushButton.setDisabled(True) self.ui.pushButton_2.setDisabled(True) self.ui.newStyleButton.setDisabled(True) self.ui.pushButton_4.setDisabled(True) self.ui.comboBox.setDisabled(True) self.ui.lineEdit.returnPressed.disconnect() self.ui.lineEdit_3.returnPressed.disconnect() self.widgets_on = False def done_application(self, status): log.append("Control back at main thread; checking application result...", entity="main") if status == 0: log.append("Application success! continuing to next one...", entity="main") self.good_list.append((self.last_row, self.ui.tableWidget.getRow(self.last_row), str(time.strftime("%I:%M.%Y %p")))) elif status == 1: log.append("Unexpected page! Skipping for now...", entity="main") self.complex_list.append((self.last_row, self.ui.tableWidget.getRow(self.last_row), str(time.strftime("%I:%M.%Y %p")))) while True: try: path = "d:\\Projects\\Career Crawler\\temp_file.html" webDiag = WebAlert(QUrl().fromLocalFile(path)) except: log.append("Error opening web dialog: "+str(sys.exc_info()[0]), entity="stderr") if webDiag.exec_(): data = webDiag.getFormFields() self.worker.setAction("RETRY", data) self.worker.start() while True: if self.worker.isFinished(): break try: self.mnstr.resp.index("Check your email for a detailed confirmation of this application.") log.append("Confirmation page reached! Continuing to next task...", entity="worker") log.append("Application success! continuing to next one...", entity="main") self.good_list.append(self.current_row) break #Success! except: log.append("Unexpected page reached... displaying page and waiting for input...", entity="stderr") self.mnstr.out2file("temp_file") else: log.append("Marking this application as Un-Automatable...", entity="main") self.bad_list.append((self.last_row, self.ui.tableWidget.getRow(self.last_row), str(time.strftime("%I:%M.%Y %p")))) #Go to the next application... self.applyToSelected() def getProfileData(self, p_link): self.worker.setAction("PROFILE", posting_link=p_link) self.worker.start() def release_widgets(self): if not self.widgets_on: self.ui.pushButton.setEnabled(True) self.ui.pushButton_2.setEnabled(True) self.ui.newStyleButton.setEnabled(True) self.ui.pushButton_4.setEnabled(True) self.ui.comboBox.setEnabled(True) self.ui.lineEdit.returnPressed.connect(self.do_search) self.ui.lineEdit_3.returnPressed.connect(self.do_search) self.widgets_on = True def __init__(self): #INITIALIZE AND SHOW GUI... super(Main, self).__init__() self.ui=CC_Main() self.ui.setupUi(self) self.ui.lineEdit.setText("Programmer") self.ui.lineEdit_3.setText("Toronto") self.ui.tableWidget.addFuncPointers({"getProfileData": self.getProfileData}) self.show() #Used to keep the log from being finalized multiple times... self.run_once = 0 self.widgets_on = True #Keep track of which positions are valid for automation... self.good_list = [] self.complex_list = [] self.bad_list = [] #See if saved data exists, and load if it does... fin = None try: fin = open("./data/past_app_sessions.pickle", "rb") log.append("Found previous application history data! loading into memory...", entity="main") except: log.append("No previous application history data found... skipping load.", entity="main") if fin != None: container = p_load(fin) self.good_list = container['good_list'] self.complex_list = container['complex_list'] self.bad_list = container['bad_list'] self.last_row = -1 log.append('Initializing...') #Redirect STDOUT and STDERR self.redir = StdRedir(log) self.ui.logWidget.loadConnection(self.redir.stdout_receiver.new_data) self.ui.logWidget.setLog(log) self.ui.tableWidget.setLog(log) self.redir.startThreads() #SETUP SIGNALS/SLOTS... self.ui.pushButton_2.clicked.connect(self.do_search) self.ui.pushButton_4.clicked.connect(self.applyToSelected) self.ui.lineEdit.returnPressed.connect(self.do_search) self.ui.lineEdit_3.returnPressed.connect(self.do_search) self.ui.newStyleButton.clicked.connect(self.ui.tableWidget._newStyle) app.aboutToQuit.connect(self.closingCode) #SETUP *CUSTOM* WORKERTHEAD SIGNALS self.worker = WorkerThread("*****@*****.**", "unkQRXen9", log) self.worker.search_complete.connect(self.process_search) self.worker.profiling_complete.connect(self.ui.tableWidget.setRowData) self.worker.job_tasks.connect(self.ui.loadBar.prepLoadBar) self.worker.task_complete.connect(self.ui.loadBar.updateLoadBar) self.worker.finished.connect(self.release_widgets) self.worker.submission_complete.connect(self.done_application) #LOGIN TO SITE! self.lockout_widgets() self.worker.start() log.append('Initialization Complete!') #Set focus to the search button initially... self.ui.pushButton_2.setFocus()
class EYETestWindowController(NibClassBuilder.AutoBaseClass): """ As per the definition in the NIB file, EYETestWindowController is a subclass of NSWindowController. """ bookmarksArray = ivar('bookmarksArray') def testWindowController(self): """ Create and return a default test window instance. """ return EYETestWindowController.alloc().init() testWindowController = classmethod(testWindowController) def init(self): """ Designated initializer. Returns self (as per ObjC designated initializer definition, unlike Python's __init__() method). """ self.bookmarksArray = [] #NSMutableArray.array() self = self.initWithWindowNibName_("EYETest") self._toolbarItems = {} self._toolbarDefaultItemIdentifiers = [] self._toolbarAllowedItemIdentifiers = [] self._editorname = "/Applications/TextEdit.app" self.searchTextField="" self._methodList = [] self._working = 0 self._windowIsClosing = 0 self._workerThread = WorkerThread() self._workerThread.start() NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "handleEditorChange:",u"JMEditorChanged",None) return self def awakeFromNib(self): """ Invoked when the NIB file is loaded. Initializes the various UI widgets. """ self.retain() # balanced by autorelease() in windowWillClose_ self.methods.setDoubleAction_("openEditor:") self.statusTextField.setStringValue_(u"") self.progressIndicator.setStyle_(NSProgressIndicatorSpinningStyle) self.progressIndicator.setDisplayedWhenStopped_(NO) self.createToolbar() # read in the editor from the prefs. self.setEditor() def setEditor(self): editor = NSUserDefaults.standardUserDefaults().objectForKey_(u"ODBTextEditor") if not editor: self._editorname = u"/Applications/TextEdit.app" bundle = NSBundle.mainBundle() editorDict = NSDictionary.dictionaryWithContentsOfFile_(bundle.pathForResource_ofType_("ODBEditors","plist" )) editorList=editorDict.objectForKey_(u"ODBEditors") for editorItem in editorList: name = editorItem.objectForKey_(u"ODBEditorName") if name == editor: bundleID = editorItem.objectForKey_(u"ODBEditorBundleID") self._editorname = NSWorkspace.sharedWorkspace().absolutePathForAppBundleWithIdentifier_(bundleID) break # check to see if the editor is run on the CLI if editorItem.objectForKey_(u"ODBEditorLaunchStyle") == 1: self._editorname =editorItem.objectForKey_(u"ODBEditorPath") def windowWillClose_(self, aNotification): """ Clean up when the document window is closed. """ # We must stop the worker thread and wait until it actually finishes before # we can allow the window to close. Weird stuff happens if we simply let the # thread run. When this thread is idle (blocking in queue.get()) there is # no problem and we can almost instantly close the window. If it's actually # in the middle of working it may take a couple of seconds, as we can't # _force_ the thread to stop: we have to ask it to to stop itself. self._windowIsClosing = 1 # try to stop the thread a.s.a.p. self._workerThread.stop() # signal the thread that there is no more work to do self._workerThread.join() # wait until it finishes self.autorelease() def createToolbar(self): """ Creates and configures the toolbar to be used by the window. """ toolbar = NSToolbar.alloc().initWithIdentifier_(u"EYE Test Window") toolbar.setDelegate_(self) toolbar.setAllowsUserCustomization_(YES) toolbar.setAutosavesConfiguration_(YES) self.createToolbarItems() self.window().setToolbar_(toolbar) #lastURL = NSUserDefaults.standardUserDefaults().stringForKey_("LastURL") #if lastURL and len(lastURL): # self.urlTextField.setStringValue_(lastURL) def createToolbarItems(self): """ Creates all of the toolbar items that can be made available in the toolbar. The actual set of available toolbar items is determined by other mechanisms (user defaults, for example). """ addToolbarItem(self, kEYEReloadContentsToolbarItemIdentifier, "Check", "Check", "Run Check", None, "reloadVisibleData:", NSImage.imageNamed_(u"beholder"), None) addToolbarItem(self, kEYEPreferencesToolbarItemIdentifier, "Preferences", "Preferences", "Show Preferences", None, "orderFrontPreferences:", NSImage.imageNamed_(u"Preferences"), None) addToolbarItem(self, kEYESearchFieldToolbarItemIdentifier, "Search", "Search", "Placeholder", None, None, self.searchField, None) # self._toolbarDefaultItemIdentifiers = [ kEYEReloadContentsToolbarItemIdentifier, kEYESearchFieldToolbarItemIdentifier, NSToolbarSeparatorItemIdentifier, NSToolbarCustomizeToolbarItemIdentifier, ] self._toolbarAllowedItemIdentifiers = [ kEYEReloadContentsToolbarItemIdentifier, kEYESearchFieldToolbarItemIdentifier, NSToolbarSeparatorItemIdentifier, NSToolbarSpaceItemIdentifier, NSToolbarFlexibleSpaceItemIdentifier, NSToolbarPrintItemIdentifier, kEYEPreferencesToolbarItemIdentifier, NSToolbarCustomizeToolbarItemIdentifier, ] def toolbarDefaultItemIdentifiers_(self, anIdentifier): """ Return an array of toolbar item identifiers that identify the set, in order, of items that should be displayed on the default toolbar. """ return self._toolbarDefaultItemIdentifiers def toolbarAllowedItemIdentifiers_(self, anIdentifier): """ Return an array of toolbar items that may be used in the toolbar. """ return self._toolbarAllowedItemIdentifiers def toolbar_itemForItemIdentifier_willBeInsertedIntoToolbar_(self, toolbar, itemIdentifier, flag): """ Delegate method fired when the toolbar is about to insert an item into the toolbar. Item is identified by itemIdentifier. Effectively makes a copy of the cached reference instance of the toolbar item identified by itemIdentifier. """ newItem = NSToolbarItem.alloc().initWithItemIdentifier_(itemIdentifier) item = self._toolbarItems[itemIdentifier] newItem.setLabel_( item.label() ) newItem.setPaletteLabel_( item.paletteLabel() ) if item.view(): newItem.setView_( item.view() ) else: newItem.setImage_( item.image() ) newItem.setToolTip_( item.toolTip() ) newItem.setTarget_( item.target() ) newItem.setAction_( item.action() ) newItem.setMenuFormRepresentation_( item.menuFormRepresentation() ) if newItem.view(): newItem.setMinSize_( item.minSize() ) newItem.setMaxSize_( item.maxSize() ) return newItem def setStatusTextFieldMessage_(self, aMessage): """ Sets the contents of the statusTextField to aMessage and forces the field's contents to be redisplayed. """ if not aMessage: aMessage = u"Displaying information about " +`len(self._methodList)` +" methods." +`self._working` self.statusTextField.performSelectorOnMainThread_withObject_waitUntilDone_( "setStringValue:", unicode(aMessage), 0) def startWorking(self): """Signal the UI there's work goin on.""" if not self._working: self.progressIndicator.startAnimation_(self) self._working += 1 def stopWorking(self): """Signal the UI that the work is done.""" self._working -= 1 if not self._working: self.progressIndicator.performSelectorOnMainThread_withObject_waitUntilDone_( "stopAnimation:", self, 0) # external editor protocol as described here http://www.codingmonkeys.de/techpubs/externaleditor/pbxexternaleditor.html def openInExternalEditor(self, _filePath, _lnnum): from aem.send import Application import struct from Carbon.File import FSSpec SelectionRange=struct.pack('hhllll', 0, int(_lnnum)-1, 1,1,0,0) try: Application(self._editorname).event('aevtodoc',{'----':FSSpec(_filePath),'kpos':SelectionRange}).send() except: print "error;" pass def testAction_(self, sender): self.reloadVisibleData_(sender) def openEditor_(self): #row=self.methods.selectedRow() aDict=self.tableContentController.selectedObjects()[0] #loc =self.bookmarksArray[row]["Location"] self.openInExternalEditor(aDict["Path"], aDict["Location"][aDict["Location"].rfind(":")+1:]) def handleEditorChange_(self, note): self.setEditor() def reloadVisibleData_(self, sender): if self._working: # don't start a new job while there's an unfinished one return self.setStatusTextFieldMessage_(u"Checking ...") self.startWorking() self.bookmarksArray=[] url = self._server self._workerThread.scheduleWork(self.getMethods, url) def getMethods(self, url): pool = NSAutoreleasePool.alloc().init() self.startWorking() # Start Process indicator filelist =GlobDirectoryWalker(url, "*.m") if not filelist: self.setStatusTextFieldMessage_(u"No Objective-C files found") for filename in filelist: if self._windowIsClosing: return self.receiveMethods(filename) self.setStatusTextFieldMessage_(unicode("Found " + str(len(self.bookmarksArray))+" methods.")) self.stopWorking() del pool if self._windowIsClosing: return self.stopWorking() def receiveMethods(self, filename): a = hbalance.maine(filename) if a : # a can be None #self.bookmarksArray+=a for b in a: path = b[1] self.tableContentController.performSelectorOnMainThread_withObject_waitUntilDone_("addObject:",{"Message":b[0],"Location":path[path.rfind("/")+1:],"Method":b[2],"Path":path[:path.rfind(":")]},0)
class UsbConnector(object): def __init__(self): self.connected = False self._client: AdbClient = None self.my_device: Device = None self._host = '127.0.0.1' self._port = 5037 self.connectionChangedFunctions = [] self.checkingConnectionFunctions = [] self.connectionCheckThread = WorkerThread() self._continousCheckStopRequired = False self._startConnectionCheck() def _changeConnectedState(self, c): if self.connected != c: self.connected = c for f in self.connectionChangedFunctions: f() def checkingConnectionChange(self, state: bool): for f in self.checkingConnectionFunctions: f(state) def stopConnectionCheck(self): print("Stopping continous device check") self._continousCheckStopRequired = True def setFunctionToCallOnConnectionStateChanged(self, function): if function not in self.connectionChangedFunctions: self.connectionChangedFunctions.append(function) def setFunctionToCallOnCheckingConnectionStateChanged(self, function): if function not in self.checkingConnectionFunctions: self.checkingConnectionFunctions.append(function) def getDeviceSerialNo(self): try: device = os.popen("adb devices").read().split('\n', 1)[1].split("device")[0].strip() device = None if device == '' else device return device except: return None # def checkDeviceAvailable(self): # # try: # # device = os.popen("adb devices").read().split('\n', 1)[1].split("device")[0].strip() # # device = None if device == '' else device # # return device != '' and device != None # # except: # # return False def tryConnect(self) -> bool: # Default is "127.0.0.1" and 5037, but nox is 62001 if self.connected and self.getDeviceSerialNo() is not None: return True self._changeConnectedState(False) self.checkingConnectionChange(True) ports = [5037, 62001] ok = False os.system("adb disconnect") dev = 'device' for p in ports: os.system("adb connect {}:{}".format(self._host, p)) dev = self.getDeviceSerialNo() if dev is not None: if 'offline' not in dev: self._port = 5037 ok = True break os.system("adb disconnect") if ok: self._client = AdbClient(host=self._host, port=self._port) self.my_device = self._client.device(dev) self._changeConnectedState(True) else: self._changeConnectedState(False) self.checkingConnectionChange(False) return self.connected def disconnect(self) -> bool: if not self.connected: return True self.my_device = None self._client = None self._changeConnectedState(False) return True def _get_device_id(self) -> str: if not self.connected: return '' return self.my_device.get_serial_no() def adb_get_size(self) -> tuple: if not self.connected: return 0, 0 bytes_screen = self.my_device.screencap() im = Image.open(io.BytesIO(bytes_screen)) w, h = im.size im.close() return w, h def adb_screen(self, name: str = "screen.png") -> bool: if not self.connected: return False """ Executes a screen and saved it in current folder as 'screen.png' :return: """ os.system("adb exec-out screencap -p > " + name) return True def adb_screen_getpixels(self): if not self.connected: return np.zeros((1080, 2220)) bytes_screen = self.my_device.screencap() with Image.open(io.BytesIO(bytes_screen)) as im: pixval = np.array(im.getdata()) return pixval def adb_swipe(self, locations, s) -> bool: if not self.connected: return False """ Executes sdb swipe function Parameters: locations (array(int), size=4): [x1,y1,x2,y2] coords duration (int): duration (seconds) """ s = int(s * 1000) x1, y1, x2, y2 = locations[0], locations[1], locations[2], locations[3] self.my_device.input_swipe(int(x1), int(y1), int(x2), int(y2), s) return True def adb_tap(self, coord) -> bool: if not self.connected: return False """ Executes sdb tap function Parameters: coord (tuple(x, y)): coordinate of tap """ x, y = coord[0], coord[1] self.my_device.input_tap(int(x), int(y)) return True keycodes = { "KEYCODE_UNKNOWN": 0, "KEYCODE_MENU": 1, "KEYCODE_SOFT_RIGHT": 2, "KEYCODE_HOME": 3, "KEYCODE_BACK": 4, "KEYCODE_CALL": 5, "KEYCODE_ENDCALL": 6, "KEYCODE_0": 7, "KEYCODE_1": 8, "KEYCODE_2": 9, "KEYCODE_3": 10, "KEYCODE_4": 11, "KEYCODE_5": 12, "KEYCODE_6": 13, "KEYCODE_7": 14, "KEYCODE_8": 15, "KEYCODE_9": 16, "KEYCODE_STAR": 17, "KEYCODE_POUND": 18, "KEYCODE_DPAD_UP": 19, "KEYCODE_DPAD_DOWN": 20, "KEYCODE_DPAD_LEFT": 21, "KEYCODE_DPAD_RIGHT": 22, "KEYCODE_DPAD_CENTER": 23, "KEYCODE_VOLUME_UP": 24, "KEYCODE_VOLUME_DOWN": 25, "KEYCODE_POWER": 26, "KEYCODE_CAMERA": 27, "KEYCODE_CLEAR": 28, "KEYCODE_A": 29, "KEYCODE_B": 30, "KEYCODE_C": 31, "KEYCODE_D": 32, "KEYCODE_E": 33, "KEYCODE_F": 34, "KEYCODE_G": 35, "KEYCODE_H": 36, "KEYCODE_I": 37, "KEYCODE_J": 38, "KEYCODE_K": 39, "KEYCODE_L": 40, "KEYCODE_M": 41, "KEYCODE_N": 42, "KEYCODE_O": 43, "KEYCODE_P": 44, "KEYCODE_Q": 45, "KEYCODE_R": 46, "KEYCODE_S": 47, "KEYCODE_T": 48, "KEYCODE_U": 49, "KEYCODE_V": 50, "KEYCODE_W": 51, "KEYCODE_X": 52, "KEYCODE_Y": 53, "KEYCODE_Z": 54, "KEYCODE_COMMA": 55, "KEYCODE_PERIOD": 56, "KEYCODE_ALT_LEFT": 57, "KEYCODE_ALT_RIGHT": 58, "KEYCODE_SHIFT_LEFT": 59, "KEYCODE_SHIFT_RIGHT": 60, "KEYCODE_TAB": 61, "KEYCODE_SPACE": 62, "KEYCODE_SYM": 63, "KEYCODE_EXPLORER": 64, "KEYCODE_ENVELOPE": 65, "KEYCODE_ENTER": 66, "KEYCODE_DEL": 67, "KEYCODE_GRAVE": 68, "KEYCODE_MINUS": 69, "KEYCODE_EQUALS": 70, "KEYCODE_LEFT_BRACKET": 71, "KEYCODE_RIGHT_BRACKET": 72, "KEYCODE_BACKSLASH": 73, "KEYCODE_SEMICOLON": 74, "KEYCODE_APOSTROPHE": 75, "KEYCODE_SLASH": 76, "KEYCODE_AT": 77, "KEYCODE_NUM": 78, "KEYCODE_HEADSETHOOK": 79, "KEYCODE_FOCUS": 80, "KEYCODE_PLUS": 81, "KEYCODE_MENU_2": 82, "KEYCODE_NOTIFICATION": 83, "KEYCODE_SEARCH": 84, "TAG_LAST_KEYCODE": 85, } def adb_tap_key(self, keycode: str) -> bool: if not self.connected: return False if keycode in self.keycodes: self.my_device.input_keyevent(self.keycodes[keycode]) else: return False return True def _oneCheck(self): time.sleep(1) while True: if self._continousCheckStopRequired: break c = self.tryConnect() if c != self.connected: if self.connected: self.disconnect() else: self._changeConnectedState(True) # self.connect() changed into tryConnect time.sleep(5) def _startConnectionCheck(self): self._continousCheckStopRequired = False self.connectionCheckThread.function = self._oneCheck self.connectionCheckThread.start()
"rabbitmq", "http", } or not heartbeat.isnumeric()): parser.print_help() exit() print(f"intuitiveNMS worker: {worker_type}") print(f" ---- intuitiveNMS: {intuitiveNMS}") print(f" ---- serial: {serial_no}") print(f" ---- connection: {connection_type}") print(f" ---- heartbeat: {heartbeat}") print() workerThread = WorkerThread(intuitivenms=intuitiveNMS, worker_type=worker_type, serial_no=serial_no, connection_type=connection_type, heartbeat=heartbeat) # try: workerThread.start() def shutdown(): print(f"\n\n\n---> {worker_type} worker: Entering shutdown sequence") workerThread.terminate = True workerThread.join() print( f"\n---> {worker_type} worker: all worker threads shut down, terminating." )
class BeamshutterWidget(QWidget): currentShutterState=pyqtSignal(str,name='currentShutterState') def __init__(self,parent=None): QWidget.__init__(self,parent) self.ui=uic.loadUi("Beamshutter.ui",self) self.control = QAxContainer.QAxWidget(self) self.control.setControl('{3CE35BF3-1E13-4D2C-8C0B-DEF6314420B3}') self.control.setProperty("HWSerialNum",85845031) self.control.setGeometry(0,0,600,400) self.mutex=QMutex(mode =QMutex.Recursive) self.shutterReplied=False self.shut=Beamshutter(self) self.worker=WorkerThread() self.ui.mainLayout.addWidget(self.control) self.layout().setAlignment(Qt.AlignCenter) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHeightForWidth(True) self.setSizePolicy(sizePolicy) def heightForWidth(self, width): return width*0.75 @pyqtSlot() def on_BInitializeShutter_clicked(self): if not self.LEDShutter.isChecked(): self.initialize() else: self.finalize() def initialize(self): with self.check(timeOut=10): self.worker.executeFunction(self.shut.initialize) self.ui.LEDShutter.setChecked(True) def finalize(self): with self.check(): self.worker.executeFunction(self.shut.finalize) self.LEDShutter.setChecked(False) def enable(self): with self.check(): self.worker.executeFunction(self.shut.enable) def disable(self): with self.check(): self.worker.executeFunction(self.shut.disable) def _del(self): if self.ui.LEDShutter.isChecked(): self.finalize() def heightForWidth(self,w): return(w) @contextmanager def check(self,timeOut=2): out=datetime.datetime.now()+datetime.timedelta(seconds=timeOut) self.shutterReplied=shutterReplied=False yield while datetime.datetime.now()<out and shutterReplied==False: self.mutex.lock() shutterReplied=self.shutterReplied self.mutex.unlock() if shutterReplied==False: raise Exception("ThorlabsShutter timed out and might be Crashed")
# create task buffer queue to hold all parsed item ro be transmitted to database worker_queue = Queue(max_task_size) producer_threads = [] for i in range(num_producer_thread): producer = ProducerThread(url_queue, data_queue) producer.start() producer_threads.append(producer) scheduler = SchedulerThread(data_queue, worker_queue) scheduler.start() worker_threads = [] for i in range(num_worker_thread): worker = WorkerThread(worker_queue, client) worker.start() worker_threads.append(worker) count = 0 while True: ts = time.time() # crawler begin for category, url in zip(categories, urls): url_queue.put((category, url), block=True) # block until finish one round of all url parsing url_queue.join() data_queue.join() worker_queue.join()
class BasicServer(object): def __init__(self, address, port): self.server_address = address self.server_port = port self.socket_family = socket.AF_INET self.socket_type = socket.SOCK_STREAM self.socket = socket.socket(self.socket_family, self.socket_type) self.socket.bind((self.server_address, self.server_port)) self.socket.listen(10) self.socket.setblocking(False) self.connection_queue = [] self.lock = threading.Lock() self.running = False self.worker = WorkerThread(self) def serve_forever(self): print("[MAIN] Started listening on ", self.server_address, ":", self.server_port) self.running = True self.worker.start() read_list = [self.socket, sys.stdin] while self.running: # Check for new connections (read, write, error) = select.select(read_list, [], [], 0) # We have received a new connection for input in read: if input is self.socket: # Accept the request (request, client_address) = self.socket.accept() request.setblocking(False) # Add the request to the queue self.connection_queue.append(Connection(request, client_address, self)) self.worker.log.log_event("connect", client_address, "main") #print("[MAIN]", client_address, " has connected!") elif input is sys.stdin: stuff = sys.stdin.readline().rstrip('\n') if stuff == "exit": self.running = False else: print("you typed %s" % (stuff)) # If there are connections waiting to be server if len(self.connection_queue) > 0: for conn in self.connection_queue: # Check the connection status. # If its closed, i.e. all request from that connection # were processed, remove it from the list if conn.closed: #print("[MAIN] Connection ", conn.client_address, " was closed! Removing from list ...") self.connection_queue.remove(conn) # There is more work to be done. # Hand this connection to the thread (if free slots are available) else: if self.worker.has_free_slots(): # First acquire a lock so that we don't do something # strange self.lock.acquire() if conn not in self.worker.connections: conn.parent = self.worker if not conn.closed: #print("[MAIN] Assigned ", conn.client_address, " to ", self.worker.name) self.worker.connections.append(conn) self.lock.release() else: # No free slots, nothing more that can be done, the connection # will have to wait #print("[MAIN] No free slot for ", conn.client_address) break # Sleep and let the thread work some time.sleep(0.001) self.socket.close() self.worker.running = False
if (worker_type not in {"capture", "portscan", "traceroute"} or connection_type not in {"rabbitmq", "http"} or not heartbeat.isnumeric()): parser.print_help() exit() print(f"Quokka worker: {worker_type}") print(f" ---- quokka: {quokka}") print(f" ---- serial: {serial_no}") print(f" ---- connection: {connection_type}") print(f" ---- heartbeat: {heartbeat}") print() workerThread = WorkerThread(quokka=quokka, worker_type=worker_type, serial_no=serial_no, connection_type=connection_type, heartbeat=heartbeat) workerThread.start() def shutdown(): print(f"\n\n\n---> {worker_type} worker: Entering shutdown sequence") workerThread.terminate = True workerThread.join() print( f"\n---> {worker_type} worker: all worker threads shut down, terminating." )
class BeamshutterWidget(QWidget): currentShutterState = pyqtSignal(str, name='currentShutterState') def __init__(self, parent=None): QWidget.__init__(self, parent) self.ui = uic.loadUi("Beamshutter.ui", self) self.control = QAxContainer.QAxWidget(self) self.control.setControl('{3CE35BF3-1E13-4D2C-8C0B-DEF6314420B3}') self.control.setProperty("HWSerialNum", 85845031) self.control.setGeometry(0, 0, 600, 400) self.mutex = QMutex(mode=QMutex.Recursive) self.shutterReplied = False self.shut = Beamshutter(self) self.worker = WorkerThread() self.ui.mainLayout.addWidget(self.control) self.layout().setAlignment(Qt.AlignCenter) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHeightForWidth(True) self.setSizePolicy(sizePolicy) def heightForWidth(self, width): return width * 0.75 @pyqtSlot() def on_BInitializeShutter_clicked(self): if not self.LEDShutter.isChecked(): self.initialize() else: self.finalize() def initialize(self): with self.check(timeOut=10): self.worker.executeFunction(self.shut.initialize) self.ui.LEDShutter.setChecked(True) def finalize(self): with self.check(): self.worker.executeFunction(self.shut.finalize) self.LEDShutter.setChecked(False) def enable(self): with self.check(): self.worker.executeFunction(self.shut.enable) def disable(self): with self.check(): self.worker.executeFunction(self.shut.disable) def _del(self): if self.ui.LEDShutter.isChecked(): self.finalize() def heightForWidth(self, w): return (w) @contextmanager def check(self, timeOut=2): out = datetime.datetime.now() + datetime.timedelta(seconds=timeOut) self.shutterReplied = shutterReplied = False yield while datetime.datetime.now() < out and shutterReplied == False: self.mutex.lock() shutterReplied = self.shutterReplied self.mutex.unlock() if shutterReplied == False: raise Exception("ThorlabsShutter timed out and might be Crashed")