Example #1
0
    def run_windows_service(config):
        """ Initialize the web application and run it in the background, while
            displaying a small system tray icon to interact with the it.
        """
        import webbrowser
        from winservice import SysTrayIcon

        app = WebApplication(config)
        server_thread = Thread(target=app.run_server)
        server_thread.start()

        def on_quit(systray):
            """ Callback that stops the application. """
            IOLoop.instance().stop()
            server_thread.join()

        listening_port = config['web']['port'].get(int)
        open_browser = (
            lambda x: webbrowser.open_new_tab("http://127.0.0.1:{0}"
                                              .format(listening_port)))
        menu_options = (('Open in browser', None, open_browser),)

        SysTrayIcon(
            icon=os.path.join(os.path.dirname(sys.argv[0]), 'spreads.ico'),
            hover_text="Spreads Web Service",
            menu_options=menu_options,
            on_quit=on_quit,
            default_menu_index=1,
            on_click=open_browser)
Example #2
0
 def __init__(self, req, proxy, logger, task, exit_check=None, ignored_errors=[]):
     Thread.__init__(self, name = "monitor%s" % task.guid)
     Thread.setDaemon(self, True)
     # the count of votes per error code
     self.vote_result = {}
     # the error code to be ignored
     self.vote_cleared = set().union(ignored_errors)
     self.thread_last_seen = {}
     self.dctlock = RLock()
     self.votelock = RLock()
     self.thread_ref = {}
     self.thread_zombie = set()
     # HttpReq instance
     self.req = req
     # proxy.Pool instance
     self.proxy = proxy
     self.logger = logger
     self.task = task
     self._exit = exit_check if exit_check else lambda x: False
     self._cleaning_up = False
     if os.name == "nt":
         self.set_title = lambda s:os.system("TITLE %s" % (
             s if PY3K else s.encode(CODEPAGE, 'replace')))
     elif os.name == 'posix':
         import sys
         self.set_title = lambda s:sys.stdout.write("\033]2;%s\007" % (
             s if PY3K else s.encode(CODEPAGE, 'replace')))
Example #3
0
 def __init__(self, newJobsQueue, updatedJobsQueue, boss):
     Thread.__init__(self)
     self.newJobsQueue = newJobsQueue
     self.updatedJobsQueue = updatedJobsQueue
     self.currentjobs = list()
     self.runningjobs = set()
     self.boss = boss
Example #4
0
 def __init__(self, interval_sec, get_connection_holders):
     Thread.__init__(self, name="Connection heartbeat")
     self._interval = interval_sec
     self._get_connection_holders = get_connection_holders
     self._shutdown_event = Event()
     self.daemon = True
     self.start()
    def __init__(self):
        self.title = self.empty_title

        # we are listening to i3 events in a separate thread
        t = Thread(target=self._loop)
        t.daemon = True
        t.start()
Example #6
0
def run(data, d=None):
	global timer
	print(data)

	if data == "ring":
		if int(d) == 1:
			if timer:
				timer.cancel()

			timer = Timer(60, genugdavon)
			timer.start()

			check = Thread(target=check_locks)
			check.start()

			putfile('/sys/class/gpio/gpio11/value', '0')

			playsound("/root/ring-bb.wav")
		else:
			playsound("/root/ring-fis.wav")
	

	if data == "open":
#		if not locked_oben:
		playsound("/root/open.wav")
	
	if data == "summ":
		if timer:
			timer.cancel()

#		if not locked_oben:
		putfile('/sys/class/gpio/gpio11/value', '1')
		playsound("/root/summ.wav")
Example #7
0
class AntiFlapping(object):
    """
    AntiFlapping class to process event in a timely maneer
    """
    def __init__(self, window):
        self.window = window
        self.tasks = Queue(maxsize=1)
        self._window_ended = True
        self._thread = Thread(name="AntiFlapping", target=self._run)
        self._thread.start()

    def newEvent(self, func, kwargs={}):
        """
        newEvent Triggered.
        """
        if not self.tasks.full() and self._window_ended:
            self.tasks.put({'func': func, 'args':kwargs})

    def _run(self):
        """
        internal runloop that will fire tasks in order.
        """
        while True:
            task = self.tasks.get()
            self._window_ended = False
            sleep(self.window)
            self._window_ended = True
            if task['args']:
                task['func'](**task['args'])
            else:
                task['func']()
Example #8
0
    def get_stock(self):
        self.sku = self.sku_input.get().strip()
        self.client_id = self.client_id_input.get().strip()
        self.cycle = 1

        region = self.region_input.get()

        if self.refresh_var.get():
            validity = self.refresh_is_valid()
            if not validity[0]:
                self.update_status(validity[1])
                return
            else:
                amt = int(self.refresh_amt_input.get())
                dly = float(self.refresh_dly_input.get())

                if amt <= 0:
                    self.update_status('Please enter a non-zero/negative amount.')
                    return
                if dly < 0:
                    self.update_status('Please enter a non-negative delay.')
                    return
        else:
            amt = 1
            dly = 1

        thread = Thread(name=self.sku+'_'+region, target=self.check_stock, args=[region, amt, dly])
        thread.daemon = True
        thread.start()

        self.disable_submit()
Example #9
0
    def __init__(self, log = None):
        from threading import Event

        Thread.__init__(self)

        self.__mytid = P.mytid()

        try:
            ## get process ID of parent
            self.__parent = P.parent()
        except:
            self.__parent = None

        self.__bindings = {}
        self.__stop = 0
        self.__tasks = {}

        self.setMessageLoopDelay(0.1)
        self.__loopEvent = Event()

        if log: self.__log = Logfile()
        else: self.__log = None

        ## add ping-mechanism

        self.setPingTimeout(5.)
        self.bind(MSG_PING, -1, self._ping)
Example #10
0
	def __init__(self, settings, on_loaded = lambda: None):
		self.__loaded = False
		self.__on_loaded = on_loaded
		self.__sp = self.__open(settings)
		t = Thread(target=self.__consume_beginning)
		t.daemon = True
		t.start()
Example #11
0
    def looped(window, *args, **kwargs):
        if hasattr(linux_native_dialog, 'native_failed'):
            import importlib
            m = importlib.import_module('calibre.gui2.qt_file_dialogs')
            qfunc = getattr(m, 'choose_' + name)
            return qfunc(window, *args, **kwargs)
        try:
            if window is None:
                return func(window, *args, **kwargs)
            ret = [None, None]
            loop = QEventLoop(window)

            def r():
                try:
                    ret[0] = func(window, *args, **kwargs)
                except:
                    ret[1] = sys.exc_info()
                    sys.exc_clear()
                while not loop.isRunning():
                    time.sleep(0.001)  # yield so that loop starts
                loop.quit()
            t = Thread(name='FileDialogHelper', target=r)
            t.daemon = True
            t.start()
            loop.exec_(QEventLoop.ExcludeUserInputEvents)
            if ret[1] is not None:
                raise ret[1][0], ret[1][1], ret[1][2]
            return ret[0]
        except Exception:
            linux_native_dialog.native_failed = True
            import traceback
            traceback.print_exc()
            return looped(window, *args, **kwargs)
Example #12
0
 def __init__(self, config, pipe_name=PIPE):
     """@param pipe_name: Cuckoo PIPE server name."""
     Thread.__init__(self)
     self.pipe_name = pipe_name
     self.config = config
     self.options = config.get_options()
     self.do_run = True
Example #13
0
 def start(self, *args):
     """ Creates a subprocess of nping and invokes it
         with the given arguments."""
     cline = [BotConfig.NPING_PATH]
     cline = cline + args[0]
     t = Thread(target=self.__run, args=[cline])
     t.start()
 def __init__(self, stationBase):
     Thread.__init__(self)
     self.stationBase = stationBase
     self.imageVirtuelle = None
     self.anciennePosRobot = []
     self.police = cv2.FONT_HERSHEY_SIMPLEX
     self.chargerImageVirtuelle()
 def __init__(self, server):
     """
     constructor
     @param      server to run
     """
     Thread.__init__(self)
     self.server = server
Example #16
0
class NonBlockingStreamReader:
    def __init__(self, stream):
        '''
        stream: the stream to read from.
                Usually a process' stdout or stderr.
        '''

        self._s = stream
        self._q = Queue()

        def _populateQueue(stream, queue):
            '''
            Collect lines from 'stream' and put them in 'quque'.
            '''

            while True:
                line = stream.readline()
                if line:
                    queue.put(line)
                else:
                    break

        self._t = Thread(target = _populateQueue,
                         args = (self._s, self._q))
        self._t.daemon = True
        self._t.start() #start collecting lines from the stream

    def readline(self, timeout = None):
        try:
            return self._q.get(block = timeout is not None,
                               timeout = timeout)
        except Empty:
            return None
Example #17
0
    def __init__(self, n_threads):

        self.n_threads = n_threads

        self._running = True

        self.input_queues = []
        self.output_queues = []
        self.exception_queues = []
        self.threads = []
        for i in range(n_threads):
            input_queue = queue.Queue()
            output_queue = queue.Queue()
            exception_queue = queue.Queue()
            thread = Thread(
                    target=self._thread_func,
                    args=(input_queue, output_queue, exception_queue))
            thread.daemon = True

            self.input_queues.append(input_queue)
            self.output_queues.append(output_queue)
            self.exception_queues.append(exception_queue)
            self.threads.append(thread)

            thread.start()
Example #18
0
def rpc_server(handler, address, authkey):
    sock = Listener(address, authkey=authkey)
    while True:
        client = sock.accept()
        t = Thread(target=handler.handle_connection, args=(client,))
        t.daemon = True
        t.start()
Example #19
0
    def __init__(self, prompt="> ", stdin=None, stdout=None):
        if _debug: ConsoleCmd._debug("__init__")
        cmd.Cmd.__init__(self, stdin=stdin, stdout=stdout)
        Thread.__init__(self, name="ConsoleCmd")

        # check to see if this is running interactive
        self.interactive = sys.__stdin__.isatty()

        # save the prompt for interactive sessions, otherwise be quiet
        if self.interactive:
            self.prompt = prompt
        else:
            self.prompt = ''

        # gc counters
        self.type2count = {}
        self.type2all = {}

        # logging handlers
        self.handlers = {}

        # set a INT signal handler, ^C will only get sent to the
        # main thread and there's no way to break the readline
        # call initiated by this thread - sigh
        if hasattr(signal, 'SIGINT'):
            signal.signal(signal.SIGINT, console_interrupt)

        # start the thread
        self.start()
Example #20
0
 def __init__(self, name, event, function, args=[], period = 5.0):
     Thread.__init__(self)
     self.name = name
     self.stopped = event
     self.period = period
     self.function = function
     self.args = args
Example #21
0
 def __init__(self, port, deviceFd, deviceLock, debug = False, aexServer = None):
     '''
     Constructor
     '''
     self.running = False
     
     self.__dataQueue = Queue(0)
     
     self.__clients = []
     self.debug = debug
     
     self.__deviceFd = deviceFd
     self.deviceLock = deviceLock
     self.aexServer=aexServer
     
     self.runningTime = 0
     self.receivingTime = 0
     self.packetsReceived = 0
     self.sleepingTimes = 0
     
     ThreadingTCPServer.__init__(self, ("", port), StimNetCom, False)
     
     ThreadingTCPServer.allow_reuse_address = True
     
     self.server_bind()
     self.server_activate()
     
     Thread.__init__(self)
Example #22
0
def Watch( Module, Callback, * Args, ** Kwds ):
  if Module.__file__ in WatchList:
    return

  T = Thread(target = WatchThread, args=(Module,Callback,Args,Kwds))
  T.setDaemon(True)
  T.start()
def runWorker(w, args, checklist, quithooks, queue=None):
    global killed
    global workers
    
    thrdRun = Thread(target=run, args=(w, args))
    thrdRun.daemon = True
    
    thrdRun.start()
    time.sleep(1)
    
    while (w.hasLines() or not w.isDone()) and not killed:
        line = w.nextLine()
        
        if line != None:
            message("Line", "Out", line.strip(), False)
            logLine(line)
            
            if maintainChecklist(w, checklist, line):
                if isChecklistDone(checklist):
                    message(w.fullName(), "Run complete", "Moving into background")
                    break
            else:
                if checkQuitHooks(w, quithooks, line):
                    globalKill()
        
        if queue:
            try:
                queued_command = queue.get_nowait()
                
                if queued_command == "quit":
                    w.kill()
                    queue.put("ok")
            except Empty:
                pass
Example #24
0
	def __init__(self):
		Tk.__init__(self)

		self.isAndroidConnected = True
		self.isKinectConnected = False
		self.isOpen = True

		self.label_android_connected = Label(self,text="No Android connected");
		self.label_android_connected.pack()

		self.android_connection_thread = Thread(target=self.androidConnection)
		self.android_connection_thread.start()

		self.android_start_thread = Thread(target=self.androidWaitStart)

		self.button_start_kinect = Button(self,text="Demarrer Kinect",command=self.startKinect)
		self.button_start_kinect.pack()

		self.button_start_recording = Button(self,text="Demarrer enregistrement",command=self.startRecording)
		self.button_start_recording.pack()
		self.button_start_recording.config(state="disabled")

		self.spin_box_duree = Spinbox(self, from_=1, to=5)
		self.spin_box_duree.pack()

		self.label_log = Label(self,text="");
		self.label_log.pack()
Example #25
0
    def __init__(self, tname, task_queue, flt, suc, fail, headers={}, proxy=None, proxy_policy=None,
            retry=3, timeout=10, logger=None, keep_alive=None, stream_mode=False):
        """
        Construct a new 'HttpWorker' obkect

        :param tname: The name of this http worker
        :param task_queue: The task Queue instance
        :param flt: the filter function
        :param suc: the function to call when succeeded
        :param fail: the function to call when failed
        :param headers: custom HTTP headers
        :param proxy: proxy dict
        :param proxy_policy: a function to determine whether proxy should be used
        :param retry: retry count
        :param timeout: timeout in seconds
        :param logger: the Logger instance
        :param keep_alive: the callback to send keep alive
        :param stream_mode: set the request to use stream mode, keep_alive will be called every iteration
        :return: returns nothing
        """
        HttpReq.__init__(self, headers, proxy, proxy_policy, retry, timeout, logger, tname = tname)
        Thread.__init__(self, name = tname)
        Thread.setDaemon(self, True)
        self.task_queue = task_queue
        self.logger = logger
        self._keepalive = keep_alive
        self._exit = lambda x: False
        self.flt = flt
        self.f_suc = suc
        self.f_fail = fail
        self.stream_mode = stream_mode
        # if we don't checkin in this zombie_threshold time, monitor will regard us as zombie
        self.zombie_threshold = timeout * (retry + 1) 
        self.run_once = False
 def send_async(cls, port, message):
     """ Starts a new thread which sends a given message to a port """
     thread = Thread(target=cls.__send_message_async, args=(port, message),
                     name="NC-SendAsync")
     thread.setDaemon(True)
     thread.start()
     return thread
Example #27
0
	def loop(self):
		if self.authorization_failed: return
		super(GetworkSource, self).loop()

		thread = Thread(target=self.long_poll_thread)
		thread.daemon = True
		thread.start()

		while True:
			if self.should_stop: return

			if self.check_failback():
				return True

			try:
				with self.switch.lock:
					miner = self.switch.updatable_miner()
					while miner:
						work = self.getwork()
						self.queue_work(work, miner)
						miner = self.switch.updatable_miner()

				self.process_result_queue()
				sleep(1)
			except Exception:
				say_exception("Unexpected error:")
				break
 def listen_threaded(cls, port, callback):
     """ Starts a new thread listening to the given port """
     thread = Thread(target=cls.__listen_forever, args=(port, callback),
                     name="NC-ListenForever")
     thread.setDaemon(True)
     thread.start()
     return thread
Example #29
0
def main():
    """
    Main function of the proxy scanner.
    """
    global pl, output, q

    parser = ArgumentParser(description='Scans a list of proxies to determine which work for HTTPS.')
    parser.add_argument('--output', default='output/proxies.txt', type=str,
        help='The file in which to store the found proxies.')
    parser.add_argument('--threads', default=10, type=int,
        help='Number of threads to use.')

    args = parser.parse_args()
    output = args.output

    threads = args.threads
    q = Queue(threads * 3)

    print 'Starting threads.'
    for x in xrange(threads):
        t = Thread(target=check_proxies)
        t.daemon = True
        t.start()

    print 'Queueing proxies.'
    for proxy in proxies.proxies:
        q.put(proxy)
    q.join()

    save_proxies()
 def __init__(self, params):
     Thread.__init__(self)
     self.tid          = params['tid']                              #work线程id
     self.apns_gateway = ApnsGateway(certfile=params['certfile'],   #apns连接
                                         host=params['host'],
                                         port=params['port'],
                                        retry=params['retry'])