コード例 #1
0
    def worker(self):
        try:
            signal.signal(signal.SIGHUP, signal.SIG_IGN)
            signal.signal(signal.SIGINT, signal.SIG_IGN)

            while self.maxreqs:
                with suspended_signals(signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
                    # fixme - periodic hooks go here
                    pass
                try:
                    conn, addr = self.sock.accept()
                except (socket.timeout, socket.error):
                    continue
                with suspended_signals(signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
                    log.debug('client %s:%d: connected', *addr)
                    self.maxreqs -= 1
                    try:
                        while True:
                            res = Response(conn)
                            try:
                                try:
                                    req = Request(conn, timeout=self.timeout)
                                    # hmm - it may not make sense to allow pipelining by default - look for magic header
                                    if 'HTTP/1.1' == req.version and ('x-please-pipeline' not in req.headers or self.maxreqs is 0):
                                        res.headers.set('Connection', 'close')
                                    self.process(req, res)
                                except HTTPError as e:
                                    log.info('HTTP error %s', e)
                                    res.error(e.code, e.message, *e.headers)
                            except ErrorCompleted:
                                pass
                            ended = time.time()
                            log.debug('response/finished ms: %d/%d', res.delay_ms, int((ended - res.start) * 1000))
                            if 'HTTP/1.1' != req.version:
                                raise Disconnected('not HTTP/1.1', level='debug')
                            elif res.headers.contains('Connection', 'close'):
                                raise Disconnected('handler closed', level='debug')
                    except Disconnected as e:
                        pass
                    except socket.timeout:
                        log.warning('client %s:%d: timed out', *addr)
                    except Exception as e:
                        info = sys.exc_info()
                        log.error('Unhandled exception: %s', traceback.print_exception(*info))
                        sys.exit(1)
                    finally:
                        try:
                            conn.shutdown(socket.SHUT_RDWR)
                        except Exception:
                            pass
                        conn.close()
                        log.debug('client %s:%d: finished', *addr)
        except Graceful:
#            if e.reload:
#                log.info("*master(%d): re-exec!", os.getpid())
#                log.warn(repr(cmd))
                #if __package__ is not None:
                    #sys.argv[0] = '-m%s' % __loader__.name
                #os.execl(sys.executable, sys.executable, *sys.argv)
            pass
コード例 #2
0
def main_loop(fn, period=None):
    exit = Value(ctypes.c_bool)

    def sigint_handler(signal, frame):
        print('Picked up interrupt, pausing at next break point')
        exit.value = True

    signal.signal(signal.SIGINT, sigint_handler)

    def sigterm_handler(signal, frame):
        print('Picked up sigterm, pausing at next break point')
        exit.value = True

    signal.signal(signal.SIGTERM, sigterm_handler)

    sleep_until = 0
    while not exit.value:
        if period is not None:
            if time.time() < sleep_until:
                time.sleep(min(1, sleep_until - time.time()))
                continue
            sleep_until = time.time() + period

        with suspended_signals(signal.SIGINT, signal.SIGTERM):
            try:
                fn()
            except ExitLoop:
                break

        if period is not None:
            total_sleep = sleep_until - time.time()
            if total_sleep > 1:
                logger.info('Waiting %.1f until loop period' % total_sleep)
コード例 #3
0
ファイル: cv_imshow.py プロジェクト: adihayat/GDBUtils
    def plot_thread(img, n_channel, width, height):
        with pysigset.suspended_signals(
                signal.SIGCHLD):  # Disable signals here!
            import matplotlib
            matplotlib.use('TKAgg')
            import matplotlib.pyplot as pl
            fig = pl.figure()
            b = fig.add_subplot(111)
            if n_channel == 1:
                b.imshow(img, cmap=pl.cm.Greys_r, interpolation='nearest')
            elif n_channel == 3:
                b.imshow(img, interpolation='nearest')

            def format_coord(x, y):
                col = int(x + 0.5)
                row = int(y + 0.5)
                if col >= 0 and col < width and row >= 0 and row < height:
                    if n_channel == 1:
                        z = img[row, col]
                        return '(%d, %d), [%1.2f]' % (col, row, z)
                    elif n_channel == 3:
                        z0 = img[row, col, 0]
                        z1 = img[row, col, 1]
                        z2 = img[row, col, 2]
                        return '(%d, %d), [%1.2f, %1.2f, %1.2f]' % (col, row,
                                                                    z0, z1, z2)
                else:
                    return 'x=%d, y=%d' % (col, row)

            b.format_coord = format_coord
            pl.show()
            pass
コード例 #4
0
ファイル: cv_imshow.py プロジェクト: adihayat/GDBUtils
 def __init__(self):
     with pysigset.suspended_signals(signal.SIGCHLD):
         super(cv_imshow,
               self).__init__('cv_imshow', gdb.COMMAND_SUPPORT,
                              gdb.COMPLETE_SYMBOL)
         self.dont_repeat()
         pass
コード例 #5
0
 def save(self, fname=None):
     self.concat()
     self.enumerate()
     with pysigset.suspended_signals(signal.SIGCHLD):
         logfile = open(fname, 'wb') if fname else sys.stdout
         logfile.write('journal=' + str(self))
         logfile.close()
コード例 #6
0
 def on_status(self, status):
     with suspended_signals(SIGINT):
         self.last_id = status.id
         self.facet.emit(status._json)
         self.progress.next(status)
         if self.finished_fn(status):
             progress.finish()
             return False
コード例 #7
0
 def on_status(self, status):
     with suspended_signals(SIGINT):
         self.last_id = status.id
         self.facet.emit(status._json)
         self.progress.next(status)
         if self.finished_fn(status):
             progress.finish()
             return False
コード例 #8
0
ファイル: core.py プロジェクト: yewang15215/voltron
 def run_listener(name, cls, arg):
     with pysigset.suspended_signals(signal.SIGCHLD):
         log.debug("Starting listener for {} socket on {}".format(
             name, str(arg)))
         s = cls(*arg)
         t = threading.Thread(target=s.serve_forever)
         t.start()
         self.threads.append(t)
         self.listeners.append(s)
コード例 #9
0
def blobget(arg):
    """Diplays the content of an opencv image"""

    # Access the variable from gdb.
    args = gdb.string_to_argv(arg)
    val = gdb.parse_and_eval(args[0])
    with pysigset.suspended_signals(signal.SIGCHLD):

        blob_info = get_blob_info(val)
        return get_blob_vals(*blob_info)
コード例 #10
0
ファイル: proctor.py プロジェクト: mahmoud/tectonic
    def run(self):
        signals = {signal.SIGCHLD: self.process_cycle,
                   signal.SIGTERM: self.shutdown,
                   signal.SIGINT: self.shutdown}

        with pysigset.suspended_signals(*signals.keys()):
            for signo, handler in signals.items():
                signal.signal(signo, handler)

            self.respawn()

        while self.running:
            pysigset.sigsuspend(pysigset.SIGSET())
コード例 #11
0
def initialize_window():
    ##
    # Initialize imagewatch window
    with pysigset.suspended_signals(signal.SIGCHLD):
        # By default, my new threads will be the ones receiving the precious
        # signals from the operating system. These signals should go to GDB so
        # it could do its thing, and since it doesnt get them, my thread will
        # make gdb hang. The solution is to configure the new thread to forward
        # the signal back to the main thread, which is done by pysigset.
        wnd_thread_instance=threading.Thread(target=lib.initialize_window, args=(FETCH_BUFFER_CBK_TYPE(plot_variable_cbk),))
        wnd_thread_instance.daemon=True
        wnd_thread_instance.start()
        pass
    pass
コード例 #12
0
def initialize_window():
    ##
    # Initialize imagewatch window
    with pysigset.suspended_signals(signal.SIGCHLD):
        # By default, my new threads will be the ones receiving the precious
        # signals from the operating system. These signals should go to GDB so
        # it could do its thing, and since it doesnt get them, my thread will
        # make gdb hang. The solution is to configure the new thread to forward
        # the signal back to the main thread, which is done by pysigset.
        wnd_thread_instance=threading.Thread(target=lib.initialize_window, args=(FETCH_BUFFER_CBK_TYPE(plot_variable_cbk),))
        wnd_thread_instance.daemon=True
        wnd_thread_instance.start()
        pass
    pass
コード例 #13
0
ファイル: cv_imshow.py プロジェクト: adihayat/GDBUtils
        def invoke(self, arg, from_tty):
            # Access the variable from gdb.
            args = gdb.string_to_argv(arg)
            val = gdb.parse_and_eval(args[0])
            with pysigset.suspended_signals(signal.SIGCHLD):
                if str(val.type.strip_typedefs()) == 'IplImage *':
                    img_info = self.get_iplimage_info(val)
                else:
                    img_info = self.get_cvmat_info(val)

                if img_info: self.show_image(*img_info)

                self.dont_repeat()
                pass
コード例 #14
0
    def cvget(arg):
        """Diplays the content of an opencv image"""

        # Access the variable from gdb.
        args = gdb.string_to_argv(arg)
        val = gdb.parse_and_eval(args[0])
        with pysigset.suspended_signals(signal.SIGCHLD):
            if str(val.type.strip_typedefs()) == 'IplImage *':
                img_info = get_iplimage_info(val)
            else:
                img_info = get_cvmat_info(val)

            if img_info:
                return get_vals(*img_info)
            return None
コード例 #15
0
    def inner(*args, **kwargs):
        try:
            import gdb
            PROTECT = True
        except ImportError:
            PROTECT = False

        if sys.platform == 'darwin':
            PROTECT = False

        if PROTECT:
            import pysigset
            with pysigset.suspended_signals(signal.SIGCHLD):
                return func(*args, **kwargs)
        else:
            return func(*args, **kwargs)
コード例 #16
0
ファイル: common.py プロジェクト: dzabraev/mcgdb
    def __init__(self):
        if not is_gdb_version_correct():
            return
        if not is_python_version_correct():
            return
        gdb_print('\nmcgdb version: {major}.{minor}\n'.format(
            major=MCGDB_VERSION.major, minor=MCGDB_VERSION.minor))
        gdb_print('python version: {major}.{minor}.{micor}\n'.format(
            major=sys.version_info.major,
            minor=sys.version_info.minor,
            micor=sys.version_info.micro))
        gdb_print('gdb version: {VERSION}\n'.format(VERSION=gdb.VERSION))
        gdb_print(get_prompt())
        gdb_rfd, gdb_wfd = os.pipe(
        )  #Through gdb_[rw]fd main pythread will be send commands to another thread
        self.gdb_wfd = gdb_wfd
        gdb.execute('set pagination off', False, False)
        gdb.execute('source {}'.format(PATH_TO_DEFINES_MCGDB))
        gethread = GEThread(gdb_rfd, main_thread_ident)
        with pysigset.suspended_signals(signal.SIGCHLD):
            event_thread = threading.Thread(
                target=gethread,
                args=())  #this thread will be communicate with editors
            event_thread.start()

        self.event_thread = event_thread

        #unused events commented
        #gdb.events.cont.connect(               self.notify_gdb_cont )
        gdb.events.exited.connect(self.notify_gdb_exited)
        gdb.events.stop.connect(self.notify_gdb_stop)
        gdb.events.new_objfile.connect(self.notify_gdb_new_objfile)
        gdb.events.clear_objfiles.connect(self.notify_gdb_clear_objfiles)
        #gdb.events.inferior_call_pre.connect(  self.notify_gdb_inferior_call_pre )
        #gdb.events.inferior_call_post.connect( self.notify_gdb_inferior_call_post )
        gdb.events.memory_changed.connect(self.notify_gdb_memory_changed)
        gdb.events.register_changed.connect(self.notify_gdb_register_changed)
        gdb.events.breakpoint_created.connect(
            self.notify_gdb_breakpoint_created)
        gdb.events.breakpoint_deleted.connect(
            self.notify_gdb_breakpoint_deleted)
        gdb.events.breakpoint_modified.connect(
            self.notify_gdb_breakpoint_modified)

        for win_name in ['src', 'aux', 'asm']:
            if win_name in WIN_LIST:
                self.open_window(win_name)
コード例 #17
0
	def run(self):
		config = self.config["imap"]

		server = imapclient.IMAPClient(config["server"], port=config["port"], ssl=config["ssl"])
		server.login(config["username"], config["password"])

		server.debug=config.get("debug", False)

		while True:
			target_folder = "Hochgeladen {0}".format( datetime.date.today().year )
			if not server.folder_exists(target_folder):
				server.create_folder(target_folder)
				server.subscribe_folder(target_folder)

			select_info = server.select_folder('INBOX')
			if select_info[b"EXISTS"]:
				messages = server.search(['NOT', 'DELETED', 'NOT', 'SEEN'])
				
				with suspended_signals(SIGINT, SIGTERM):
					response = server.fetch(messages, ['RFC822'])

					for msgid, data in response.items():
						body = data[b'RFC822']
						target = None
						result = PROCESSING_RESULT.ERROR

						try:
							message = email.message_from_bytes(body)

							result = self.handle_mail(message)

						except:
							self.logger.exception("Fehler beim Bearbeiten der Mail {0}".format(msgid))

						finally:
							if result is PROCESSING_RESULT.UPLOADED:
								server.add_flags(msgid, [imapclient.SEEN])
								server.copy(msgid, target_folder)
								server.delete_messages(msgid)
								server.expunge()
							elif result in (PROCESSING_RESULT.IGNORE, PROCESSING_RESULT.OTHER):
								server.remove_flags(msgid, [imapclient.SEEN])


			server.idle()
			server.idle_check(timeout=300)  # Do a normal poll every 5 minutes, just in case
			server.idle_done()
コード例 #18
0
def resize(path, outpath):
    with suspended_signals(SIGINT, SIGTERM):
        try:
            fh = os.open(outpath, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0666)
        except OSError as e:
            if e.errno == errno.EEXIST:
                return
            else:
                raise

        try:
            with os.fdopen(fh, 'w') as out:
                img = Image.open(path)
                box = (299, 299)

                #calculate the cropping box and get the cropped part
                x1 = y1 = 0
                x2, y2 = img.size
                wRatio = 1.0 * x2 / box[0]
                hRatio = 1.0 * y2 / box[1]
                if hRatio > wRatio:
                    y1 = int(y2 / 2 - box[1] * wRatio / 2)
                    y2 = int(y2 / 2 + box[1] * wRatio / 2)
                else:
                    x1 = int(x2 / 2 - box[0] * hRatio / 2)
                    x2 = int(x2 / 2 + box[0] * hRatio / 2)
                img = img.crop((x1, y1, x2, y2))

                img.thumbnail(box, Image.LANCZOS)

                # This is necessary when saving to PNG, as it doesn't support CMYK
                if img.mode == "CMYK":
                    img = img.convert("RGB")

                img.save(out, "PNG", optimize=True)
                # TensorFlow doesn't support webp yet, so we'll go with the larger png
                #img.save(out, "WebP", lossless=True)

        except Exception as e:
            sys.stdout.write('failed:' + path + ',' +
                             str(e).replace('\n', '\\n') + '\n')
            try:
                os.remove(outpath)
            except OSError:
                pass
コード例 #19
0
 def initialize_window(self):
     """
     Launch the ImageWatch window.
     """
     ##
     # Initialize imagewatch window
     with pysigset.suspended_signals(signal.SIGCHLD):
         # By default, my new threads will be the ones receiving the
         # precious signals from the operating system. These signals should
         # go to GDB so it could do its thing, and since it doesnt get them,
         # my thread will make gdb hang. The solution is to configure the
         # new thread to forward the signal back to the main thread, which
         # is done by pysigset.
         wnd_thread_instance = threading.Thread(target=self._ui_thread,
                                                args=(FETCH_BUFFER_CBK_TYPE(
                                                    self.plot_variable), ))
         wnd_thread_instance.daemon = True
         wnd_thread_instance.start()
コード例 #20
0
ファイル: model.py プロジェクト: xxks-kkk/KV-store
 def put(self, item):
     """
     Put request from client that is passed from the server module
     :param item: a dictionary with "key", "value", "serverId", "timeStamp", "messageId"
     :return:
     """
     id = str(uuid.uuid1())
     item['messageId'] = id
     # log.msg("Key {} received: {}".format(item["key"], item))
     with suspended_signals(SIGKILL, SIGINT, SIGTERM):
         # Signals (SIGKILL, SIGINT, SIGTERM) are blocked here
         self.fileDict.put(item)
         self.writeLog[id] = ["put", item, list(self.receiptVector)]
     # Any pending signal is fired now ...
     for i in range(config.NUM_SERVER):
         if i != self.serverProxy.serverId:
             self.serverProxy.sendMessage({
                 "ReceiverId": i,
                 "MessageId": id,
                 "Method": "Put",
                 "Payload": item
             })
コード例 #21
0
 def _search(self, query_terms, query_ops, page_limit, progress, facet):
     # Are we resuming after an error
     if self.last_id:
         print('Restarting with id={0}'.format(tg.last_id))
         query_ops['max_id']=self.last_id
     # max out tweets per page
     if 'count' not in query_ops:
         query_ops['count']=1000
     
     q = '(' + ' OR '.join(query_terms) + ')'
     
     for page in tweepy.Cursor(self.api.search,
                               q=urllib.quote_plus(q),
                               **query_ops).pages(page_limit):
         # Block/unblock signals between pages, to allow responsive ctrl-c
         # while honoring syntactic boundaries
         with suspended_signals(SIGINT):
             for tweet in page:
                 facet.emit(tweet._json)
                 if 'id' in tweet._json:
                     last_id = tweet._json['id']
                     last_date = tweet.created_at.date()
                 progress.next(tweet)
コード例 #22
0
    def _search(self, query_terms, query_ops, page_limit, progress, facet):
        # Are we resuming after an error
        if self.last_id:
            print('Restarting with id={0}'.format(tg.last_id))
            query_ops['max_id'] = self.last_id
        # max out tweets per page
        if 'count' not in query_ops:
            query_ops['count'] = 1000

        q = '(' + ' OR '.join(query_terms) + ')'

        for page in tweepy.Cursor(self.api.search,
                                  q=urllib.quote_plus(q),
                                  **query_ops).pages(page_limit):
            # Block/unblock signals between pages, to allow responsive ctrl-c
            # while honoring syntactic boundaries
            with suspended_signals(SIGINT):
                for tweet in page:
                    facet.emit(tweet._json)
                    if 'id' in tweet._json:
                        last_id = tweet._json['id']
                        last_date = tweet.created_at.date()
                    progress.next(tweet)
コード例 #23
0
    def daemon(self, poll=250, maxopen=1000):
        poll /= 1000.0
        ticker = self.ticker()
        todo = deque()

        # count fds in use - just check first 100 or so
        pad = 0
        for fd in xrange(0, 100):
            try:
                os.fstat(fd)
                pad += 1
            except:
                pass

        # check limits
        soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
        if maxopen + pad > soft:
            soft = min(maxopen + pad, hard)
            resource.setrlimit(resource.RLIMIT_NOFILE, (soft, hard))
            maxopen = soft - pad

        map_age = 0
        log.info('using %d max open graphs' % maxopen)
        while True:
            next(ticker)
            sleep(poll)
            map_age += poll
            if map_age >= 60:
                self.db.remap()
                map_age = 0
            self.db.sync(force=True)
            with self.context(write=False) as ctx:
                try:
                    if ctx.updatedDB.empty:
                        continue
                except KeyError:
                    continue

            # Note - we assume user is not using DB_WRITEMAP which is reasonable because:
            #   LemonGraph explicitly disables that
            # Otherwise, we might have to mmap the whole region and msync it - maybe?
            # Opening it via LemonGraph adds overhead, burns double the file descriptors, and
            # currently explodes if I try to set RLIMIT_NOFILE > 2050. I know not why.
            # We also assume that fdatasync() is good, which it is for Linux >= 3.6
            count = 0
            backlog = True
            while backlog:
                with suspended_signals(signal.SIGTERM, signal.SIGINT,
                                       signal.SIGHUP):
                    try:
                        log.debug("syncing")
                        with self.context(write=True) as ctx:
                            uuids = ctx.updatedDB.pop(n=maxopen)
                            for uuid in uuids:
                                age = ctx.updatedDB_idx.pop(uuid)
                                try:
                                    fd = os.open(self.graph_path(uuid),
                                                 os.O_RDONLY)
                                    todo.append(fd)
                                except OSError as e:
                                    # may have been legitimately deleted already
                                    if e.errno != errno.ENOENT:
                                        log.warning(
                                            'error syncing graph %s: %s', uuid,
                                            str(e))
                            count += len(uuids)
                            backlog = len(ctx.updatedDB)
                        for fd in todo:
                            os.fdatasync(fd)
                    finally:
                        for fd in todo:
                            os.close(fd)
                        todo.clear()
                log.info("synced %d, backlog %d, age %.1fs", count, backlog,
                         time() - age)
コード例 #24
0
    def daemon(self, poll=250, maxopen=1000):
        poll /= 1000.0
        wrote = None
        ticker = self.ticker()
        todo = deque()

        # count fds in use - just check first 100 or so
        pad = 0
        for fd in xrange(0, 100):
            try:
                os.fstat(fd)
                pad += 1
            except:
                pass

        # check limits
        soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
        if maxopen + pad > soft:
            soft = min(maxopen + pad, hard)
            resource.setrlimit(resource.RLIMIT_NOFILE, (soft, hard))
            maxopen = soft - pad

        map_age = 0
        log.info('using %d max open graphs' % maxopen)
        while True:
            ticker.next()
            sleep(poll)
            map_age += poll
            if map_age >= 60:
                self.db.remap()
                map_age = 0
            self.db.sync(force=True)
            with self.context(write=False) as ctx:
                try:
                    if ctx.updatedDB.empty:
                        continue
                except KeyError:
                    continue

            # Note - we assume user is not using MDB_WRITEMAP which is reasonable because:
            #   LemonGraph does not currently expose that
            # If it did, we might have to mmap the whole region and msync it - maybe?
            # Opening it via LemonGraph adds overhead, burns double the file descriptors, and
            # currently explodes if I try to set RLIMIT_NOFILE > 2050. I know not why.
            # We also assume that fdatasync() is good, which it is for Linux >= 3.6
            count = 0
            backlog = True
            while backlog:
                with suspended_signals(signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
                    try:
                        log.debug("syncing")
                        with self.context(write=True) as ctx:
                            uuids = ctx.updatedDB.pop(n=maxopen)
                            for uuid in uuids:
                                age = ctx.updatedDB_idx.pop(uuid)
                                try:
                                    fd = os.open(self.graph_path(uuid), os.O_RDONLY)
                                    todo.append(fd)
                                except OSError as e:
                                    # may have been legitimately deleted already
                                    if e.errno != errno.ENOENT:
                                        log.warning('error syncing graph %s: %s', uuid, str(e))
                            count += len(uuids)
                            backlog = len(ctx.updatedDB)
                        for fd in todo:
                            os.fdatasync(fd)
                    finally:
                        for fd in todo:
                            os.close(fd)
                        todo.clear()
                log.info("synced %d, backlog %d, age %.1fs", count, backlog, time() - age)
コード例 #25
0
 def uninterruptible_section():
     with pysigset.suspended_signals(signal.SIGINT):
         yield
コード例 #26
0
ファイル: main.py プロジェクト: henryk/mailping
    def run(self):
        self.imap_client = imapclient.IMAPClient(settings.IMAP_HOSTNAME,
                                                 port=settings.IMAP_PORT,
                                                 ssl=settings.IMAP_SSL)
        self.imap_client.login(settings.IMAP_USERNAME, settings.IMAP_PASSWORD)

        self.imap_client.debug = settings.IMAP_DEBUG

        known_mails = set()
        first_run = True

        while True:
            mail_info = set()
            select_info = self.imap_client.select_folder("INBOX")
            if select_info[b"EXISTS"]:
                messages = self.imap_client.search(
                    ["NOT", "DELETED", "NOT", "SEEN"])

                with suspended_signals(SIGINT, SIGTERM):
                    response = self.imap_client.fetch(messages, ["ENVELOPE"])

                    for msgid, data in response.items():
                        envelope = data[b"ENVELOPE"]

                        mail_info.add("{:%Y-%m-%d %H:%M:%S} - {}".format(
                            envelope.date,
                            envelope.subject[:30].decode("us-ascii",
                                                         errors="replace")))

                new_mails = mail_info.difference(known_mails)

                if new_mails and not first_run:

                    subject = "{0} neue Mail(s) eingegangen".format(
                        len(new_mails))
                    message = "Folgende Mails sind dazugekommen\n\n" + (
                        "\n  * ".join(sorted(list(new_mails)))) + "\n"

                    if settings.SMTP_SSL:
                        smtpfactory = smtplib.SMTP_SSL
                    else:
                        smtpfactory = smtplib.SMTP
                    smtp_con = smtpfactory(host=settings.SMTP_HOSTNAME,
                                           port=settings.SMTP_PORT)
                    if settings.SMTP_STARTTLS:
                        smtp_con.starttls()

                    smtp_con.login(settings.SMTP_USERNAME,
                                   settings.SMTP_PASSWORD)

                    smtp_con.sendmail(
                        to_addrs=[settings.NOTIFICATION_TO],
                        from_addr=settings.NOTIFICATION_FROM,
                        msg=dedent("""\
                        From: {from_}
                        To: {to}
                        Date: {date}
                        Message-ID: {msgid}
                        Subject: {subject}
                        
                        {message}
                        """).format(
                            from_=settings.NOTIFICATION_FROM,
                            to=settings.NOTIFICATION_TO,
                            date=email.utils.formatdate(),
                            msgid=str(uuid.uuid4()) + "." +
                            settings.NOTIFICATION_FROM,
                            subject=subject,
                            message=message,
                        ),
                    )

                    smtp_con.quit()

                known_mails = mail_info
                first_run = False

            self.imap_client.idle()
            self.imap_client.idle_check(
                timeout=300)  # Do a normal poll every 5 minutes, just in case
            self.imap_client.idle_done()
コード例 #27
0
ファイル: cv_imshow.py プロジェクト: adihayat/GDBUtils
        def show_image(width, height, n_channel, line_step, data_address,
                       data_symbol):
            """ Copies the image data to a PIL image and shows it.

            Args:
                width: The image width, in pixels.
                height: The image height, in pixels.
                n_channel: The number of channels in image.
                line_step: The offset to change to pixel (i+1, j) being
                    in pixel (i, j), in bytes.
                data_address: The address of image data in memory.
                data_symbol: Python struct module code to the image data type.
            """
            width = int(width)
            height = int(height)
            n_channel = int(n_channel)
            line_step = int(line_step)
            data_address = int(data_address)

            infe = gdb.inferiors()
            memory_data = infe[0].read_memory(data_address, line_step * height)

            # Calculate the memory padding to change to the next image line.
            # Either due to memory alignment or a ROI.
            if data_symbol in ('b', 'B'):
                elem_size = 1
            elif data_symbol in ('h', 'H'):
                elem_size = 2
            elif data_symbol in ('i', 'f'):
                elem_size = 4
            elif data_symbol == 'd':
                elem_size = 8
            padding = line_step - width * n_channel * elem_size

            # Format memory data to load into the image.
            image_data = []
            if n_channel == 1:
                mode = 'L'
                fmt = '%d%s%dx' % (width, data_symbol, padding)
                for line in chunker(memory_data, line_step):
                    image_data.extend(struct.unpack(fmt, line))
            elif n_channel == 3:
                mode = 'RGB'
                fmt = '%d%s%dx' % (width * 3, data_symbol, padding)
                for line in chunker(memory_data, line_step):
                    image_data.extend(struct.unpack(fmt, line))
            else:
                gdb.write('Only 1 or 3 channels supported\n', gdb.STDERR)
                return

            # Fit the opencv elemente data in the PIL element data
            if data_symbol == 'b':
                image_data = [i + 128 for i in image_data]
            elif data_symbol == 'H':
                image_data = [i >> 8 for i in image_data]
            elif data_symbol == 'h':
                image_data = [(i + 32768) >> 8 for i in image_data]
            elif data_symbol == 'i':
                image_data = [(i + 2147483648) >> 24 for i in image_data]
            elif data_symbol in ('f', 'd'):
                # A float image is discretized in 256 bins for display.
                max_image_data = max(image_data)
                min_image_data = min(image_data)
                img_range = max_image_data - min_image_data
                if img_range > 0:
                    image_data = [int(255 * (i - min_image_data) / img_range) \
                                  for i in image_data]
                else:
                    image_data = [0 for i in image_data]

            if n_channel == 3:
                # OpenCV stores the channels in BGR mode. Convert to RGB while packing.
                image_data = list(zip(*[image_data[i::3] for i in [2, 1, 0]]))

            img = None
            if mode == 'L':
                img = np.reshape(image_data, (height, width)).astype(np.uint8)
            elif mode == 'RGB':
                img = np.reshape(image_data,
                                 (height, width, 3)).astype(np.uint8)

            import threading
            with pysigset.suspended_signals(
                    signal.SIGCHLD):  # Disable signals here!
                plot_thread_instance = threading.Thread(
                    target=plot_thread, args=[img, n_channel, width, height])
                plot_thread_instance.daemon = True
                plot_thread_instance.start()
                plot_thread_instance.join()
コード例 #28
0
ファイル: cv_imshow.py プロジェクト: adihayat/GDBUtils
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import pysigset, signal  # Import these packages!

with pysigset.suspended_signals(signal.SIGCHLD):  # Disable signals here!
    from builtins import str as text
    from builtins import range
    import gdb
    import numpy as np
    import struct

    def chunker(seq, size):
        return (seq[pos:pos + size] for pos in range(0, len(seq), size))

    def plot_thread(img, n_channel, width, height):
        with pysigset.suspended_signals(
                signal.SIGCHLD):  # Disable signals here!
            import matplotlib
            matplotlib.use('TKAgg')
            import matplotlib.pyplot as pl
コード例 #29
0
laser = Driver(port)


def signal_handler(signal, frame):
    print('You pressed Ctrl+C!')
    laser.laserOff()

    time.sleep(5)
    sys.exit(0)


if __name__ == '__main__':

    signal.signal(signal.SIGINT, signal_handler)

    print(laser.getSensorState())
    laser.laserOn()

    plt.ion()

    while True:
        with suspended_signals(SIGINT, SIGTERM):
            angles, distances, _ = laser.getScan()
            for i in range(len(angles)):
                if angles[i] < 0:
                    angles[i] += 360
                angles[i] = angles[i] * np.pi / 180
            plt.gcf().clear()
            plt.polar(angles, distances, color='r')
            plt.pause(0.0001)
コード例 #30
0
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import pysigset, signal
with pysigset.suspended_signals(signal.SIGCHLD):
    from builtins import str as text
    from builtins import range

    import gdb
    #import matplotlib
    #matplotlib.use('TKAgg')
    #import matplotlib.pyplot as pl

    import numpy as np
    import struct

    ##pl.ion()


    def get_cvmat_info(val):