Python threading.ThreadError() Examples

The following are code examples for showing how to use threading.ThreadError(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: GAMADV-XTD   Author: taers232c   File: process_lock.py    (license) View Source Project 6 votes vote down vote up
def _try_acquire(self, blocking, watch):
        try:
            self.trylock()
        except IOError as e:
            if e.errno in (errno.EACCES, errno.EAGAIN):
                if not blocking or watch.expired():
                    return False
                else:
                    raise _utils.RetryAgain()
            else:
                raise threading.ThreadError("Unable to acquire lock on"
                                            " `%(path)s` due to"
                                            " %(exception)s" %
                                            {
                                                'path': self.path,
                                                'exception': e,
                                            })
        else:
            return True 
Example 2
Project: GAMADV-XTD   Author: taers232c   File: process_lock.py    (license) View Source Project 6 votes vote down vote up
def release(self):
        """Release the previously acquired lock."""
        if not self.acquired:
            raise threading.ThreadError("Unable to release an unacquired"
                                        " lock")
        try:
            self.unlock()
        except IOError:
            self.logger.exception("Could not unlock the acquired lock opened"
                                  " on `%s`", self.path)
        else:
            self.acquired = False
            try:
                self._do_close()
            except IOError:
                self.logger.exception("Could not close the file handle"
                                      " opened on `%s`", self.path)
            else:
                self.logger.log(_utils.BLATHER,
                                "Unlocked and closed file lock open on"
                                " `%s`", self.path) 
Example 3
Project: OSPTF   Author: xSploited   File: PupyJob.py    (license) View Source Project 6 votes vote down vote up
def _get_my_tid(self):
        """determines this (self's) thread id"""
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")
        
        # do we have it cached?
        if hasattr(self, "_thread_id"):
            return self._thread_id
        
        # no, look for it in the _active dict
        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid
        
        raise AssertionError("could not determine the thread's id") 
Example 4
Project: deb-python-fasteners   Author: openstack   File: process_lock.py    (license) View Source Project 6 votes vote down vote up
def _try_acquire(self, blocking, watch):
        try:
            self.trylock()
        except IOError as e:
            if e.errno in (errno.EACCES, errno.EAGAIN):
                if not blocking or watch.expired():
                    return False
                else:
                    raise _utils.RetryAgain()
            else:
                raise threading.ThreadError("Unable to acquire lock on"
                                            " `%(path)s` due to"
                                            " %(exception)s" %
                                            {
                                                'path': self.path,
                                                'exception': e,
                                            })
        else:
            return True 
Example 5
Project: pupy   Author: ru-faraon   File: PupyJob.py    (license) View Source Project 6 votes vote down vote up
def _get_my_tid(self):
        """determines this (self's) thread id"""
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")
        
        # do we have it cached?
        if hasattr(self, "_thread_id"):
            return self._thread_id
        
        # no, look for it in the _active dict
        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid
        
        raise AssertionError("could not determine the thread's id") 
Example 6
Project: RKSV   Author: ztp-at   File: main.py    (license) View Source Project 6 votes vote down vote up
def _get_my_tid(self):
            """determines this (self's) thread id
            CAREFUL : this function is executed in the context of the caller
            thread, to get the identity of the thread represented by this
            instance.
            """
            if not self.isAlive():
                raise threading.ThreadError("the thread is not active")

            # do we have it cached?
            if hasattr(self, "_thread_id"):
                return self._thread_id

            # no, look for it in the _active dict
            for tid, tobj in threading._active.items():
                if tobj is self:
                    self._thread_id = tid
                    return tid

            # TODO: in python 2.6, there's a simpler way to do : self.ident

            raise AssertionError("could not determine the thread's id") 
Example 7
Project: RKSV   Author: ztp-at   File: rktool.py    (license) View Source Project 6 votes vote down vote up
def _get_my_tid(self):
            """determines this (self's) thread id
            CAREFUL : this function is executed in the context of the caller
            thread, to get the identity of the thread represented by this
            instance.
            """
            if not self.isAlive():
                raise threading.ThreadError("the thread is not active")

            # do we have it cached?
            if hasattr(self, "_thread_id"):
                return self._thread_id

            # no, look for it in the _active dict
            for tid, tobj in threading._active.items():
                if tobj is self:
                    self._thread_id = tid
                    return tid

            # TODO: in python 2.6, there's a simpler way to do : self.ident

            raise AssertionError("could not determine the thread's id") 
Example 8
Project: GAMADV-X   Author: taers232c   File: process_lock.py    (license) View Source Project 6 votes vote down vote up
def _try_acquire(self, blocking, watch):
        try:
            self.trylock()
        except IOError as e:
            if e.errno in (errno.EACCES, errno.EAGAIN):
                if not blocking or watch.expired():
                    return False
                else:
                    raise _utils.RetryAgain()
            else:
                raise threading.ThreadError("Unable to acquire lock on"
                                            " `%(path)s` due to"
                                            " %(exception)s" %
                                            {
                                                'path': self.path,
                                                'exception': e,
                                            })
        else:
            return True 
Example 9
Project: GAMADV-X   Author: taers232c   File: process_lock.py    (license) View Source Project 6 votes vote down vote up
def release(self):
        """Release the previously acquired lock."""
        if not self.acquired:
            raise threading.ThreadError("Unable to release an unacquired"
                                        " lock")
        try:
            self.unlock()
        except IOError:
            self.logger.exception("Could not unlock the acquired lock opened"
                                  " on `%s`", self.path)
        else:
            self.acquired = False
            try:
                self._do_close()
            except IOError:
                self.logger.exception("Could not close the file handle"
                                      " opened on `%s`", self.path)
            else:
                self.logger.log(_utils.BLATHER,
                                "Unlocked and closed file lock open on"
                                " `%s`", self.path) 
Example 10
Project: deb-python-fasteners   Author: openstack   File: test_process_lock.py    (license) View Source Project 5 votes vote down vote up
def test_bad_acquire(self):
        lock_file = os.path.join(self.lock_dir, 'lock')
        lock = BrokenLock(lock_file, errno.EBUSY)
        self.assertRaises(threading.ThreadError, lock.acquire) 
Example 11
Project: deb-python-fasteners   Author: openstack   File: test_process_lock.py    (license) View Source Project 5 votes vote down vote up
def test_bad_release(self):
        lock_file = os.path.join(self.lock_dir, 'lock')
        lock = pl.InterProcessLock(lock_file)
        self.assertRaises(threading.ThreadError, lock.release) 
Example 12
Project: deb-python-fasteners   Author: openstack   File: process_lock.py    (license) View Source Project 5 votes vote down vote up
def __enter__(self):
        gotten = self.acquire()
        if not gotten:
            # This shouldn't happen, but just incase...
            raise threading.ThreadError("Unable to acquire a file lock"
                                        " on `%s` (when used as a"
                                        " context manager)" % self.path)
        return self 
Example 13
Project: zippy   Author: securesystemslab   File: test_multiprocessing.py    (license) View Source Project 5 votes vote down vote up
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release) 
Example 14
Project: zippy   Author: securesystemslab   File: test_threading.py    (license) View Source Project 5 votes vote down vote up
def test_limbo_cleanup(self):
        # Issue 7481: Failure to start thread should cleanup the limbo map.
        def fail_new_thread(*args):
            raise threading.ThreadError()
        _start_new_thread = threading._start_new_thread
        threading._start_new_thread = fail_new_thread
        try:
            t = threading.Thread(target=lambda: None)
            self.assertRaises(threading.ThreadError, t.start)
            self.assertFalse(
                t in threading._limbo,
                "Failed to cleanup _limbo map on failure of Thread.start().")
        finally:
            threading._start_new_thread = _start_new_thread 
Example 15
Project: oil   Author: oilshell   File: test_multiprocessing.py    (license) View Source Project 5 votes vote down vote up
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release) 
Example 16
Project: python2-tracer   Author: extremecoders-re   File: test_multiprocessing.py    (license) View Source Project 5 votes vote down vote up
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release) 
Example 17
Project: orizonhub   Author: gumblex   File: libirc.py    (license) View Source Project 5 votes vote down vote up
def acquire_lock(self, blocking=True):
        if self.lock.acquire(blocking):
            return True
        elif blocking:
            raise threading.ThreadError('Cannot acquire lock.')
        else:
            return False 
Example 18
Project: web_ctp   Author: molebot   File: test_multiprocessing.py    (license) View Source Project 5 votes vote down vote up
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release) 
Example 19
Project: web_ctp   Author: molebot   File: test_threading.py    (license) View Source Project 5 votes vote down vote up
def test_limbo_cleanup(self):
        # Issue 7481: Failure to start thread should cleanup the limbo map.
        def fail_new_thread(*args):
            raise threading.ThreadError()
        _start_new_thread = threading._start_new_thread
        threading._start_new_thread = fail_new_thread
        try:
            t = threading.Thread(target=lambda: None)
            self.assertRaises(threading.ThreadError, t.start)
            self.assertFalse(
                t in threading._limbo,
                "Failed to cleanup _limbo map on failure of Thread.start().")
        finally:
            threading._start_new_thread = _start_new_thread 
Example 20
Project: cpy2py   Author: maxfischer2781   File: thread_tools.py    (license) View Source Project 5 votes vote down vote up
def put(self, item):
        """Put a single item in the queue"""
        with self._queue_mutex:
            self._queue_content.append(item)
            for w_idx in range(len(self._waiters)):
                try:
                    self._waiters[w_idx].release()
                except (ThreadError, RuntimeError, thread_error):
                    continue
                else:
                    break 
Example 21
Project: RKSV   Author: ztp-at   File: main.py    (license) View Source Project 5 votes vote down vote up
def __thread_apply__(f, args, callback):
        try:
            callback(f(*args))
        except threading.ThreadError:
            pass 
Example 22
Project: RKSV   Author: ztp-at   File: main.py    (license) View Source Project 5 votes vote down vote up
def __thread_map__(f, iterable, callback):
        try:
            callback(map(f, iterable))
        except threading.ThreadError:
            pass 
Example 23
Project: RKSV   Author: ztp-at   File: main.py    (license) View Source Project 5 votes vote down vote up
def terminate(self):
            try:
                if self._thread:
                    self._thread.raiseExc(threading.ThreadError)
            except (threading.ThreadError, TypeError, ValueError, SystemError):
                pass

            self._thread = None 
Example 24
Project: RKSV   Author: ztp-at   File: rktool.py    (license) View Source Project 5 votes vote down vote up
def __thread_map__(f, iterable, callback):
        try:
            callback(map(f, iterable))
        except threading.ThreadError:
            pass 
Example 25
Project: RKSV   Author: ztp-at   File: rktool.py    (license) View Source Project 5 votes vote down vote up
def terminate(self):
            try:
                if self._thread:
                    self._thread.raiseExc(threading.ThreadError)
            except (threading.ThreadError, TypeError, ValueError, SystemError):
                pass

            self._thread = None 
Example 26
Project: pefile.pypy   Author: cloudtracer   File: test_multiprocessing.py    (license) View Source Project 5 votes vote down vote up
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release) 
Example 27
Project: ouroboros   Author: pybee   File: _test_multiprocessing.py    (license) View Source Project 5 votes vote down vote up
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release) 
Example 28
Project: ouroboros   Author: pybee   File: test_threading.py    (license) View Source Project 5 votes vote down vote up
def test_limbo_cleanup(self):
        # Issue 7481: Failure to start thread should cleanup the limbo map.
        def fail_new_thread(*args):
            raise threading.ThreadError()
        _start_new_thread = threading._start_new_thread
        threading._start_new_thread = fail_new_thread
        try:
            t = threading.Thread(target=lambda: None)
            self.assertRaises(threading.ThreadError, t.start)
            self.assertFalse(
                t in threading._limbo,
                "Failed to cleanup _limbo map on failure of Thread.start().")
        finally:
            threading._start_new_thread = _start_new_thread 
Example 29
Project: python_data_tools   Author: king3366ster   File: DataThreadModel.py    (license) View Source Project 5 votes vote down vote up
def _get_my_tid(self):
        """determines this (self's) thread id"""
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")
        # do we have it cached?
        if hasattr(self, "_thread_id"):
            return self._thread_id
        # no, look for it in the _active dict
        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid
        raise AssertionError("could not determine the thread's id") 
Example 30
Project: ndk-python   Author: gittor   File: test_multiprocessing.py    (license) View Source Project 5 votes vote down vote up
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release) 
Example 31
Project: zenchmarks   Author: squeaky-pl   File: test_threadworker.py    (license) View Source Project 5 votes vote down vote up
def release(self):
        """
        Release the lock.  Raise an exception if the lock is not presently
        acquired.
        """
        if not self.acquired:
            raise ThreadError()
        self.acquired = False 
Example 32
Project: zenchmarks   Author: squeaky-pl   File: test_threadworker.py    (license) View Source Project 5 votes vote down vote up
def test_fakeDoubleRelease(self):
        """
        The L{FakeLock} test fixture will alert us if there's a potential
        double-release.
        """
        lock = FakeLock()
        self.assertRaises(ThreadError, lock.release)
        lock.acquire()
        self.assertEqual(None, lock.release())
        self.assertRaises(ThreadError, lock.release) 
Example 33
Project: plex-for-kodi-mod   Author: mrclemds   File: threadutils.py    (license) View Source Project 5 votes vote down vote up
def _get_my_tid(self):
        """determines this (self's) thread id

        CAREFUL : this function is executed in the context of the caller
        thread, to get the identity of the thread represented by this
        instance.
        """
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")

        return self.ident 
Example 34
Project: plex-for-kodi-mod   Author: mrclemds   File: threadutils.py    (license) View Source Project 5 votes vote down vote up
def kill(self, force_and_wait=False):
        try:
            self._raiseExc(KillThreadException)

            if force_and_wait:
                time.sleep(0.1)
                while self.isAlive():
                    self._raiseExc(KillThreadException)
                    time.sleep(0.1)
        except threading.ThreadError:
            pass 
Example 35
Project: wade   Author: chartbeat-labs   File: chorus.py    (license) View Source Project 5 votes vote down vote up
def close(self):
        try:
            self.lock.release()
        except threading.ThreadError: 
            pass # lock may not have been acquired. 
        self.socket.close() 
Example 36
Project: kbe_server   Author: xiaohaoppy   File: _test_multiprocessing.py    (license) View Source Project 5 votes vote down vote up
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release) 
Example 37
Project: kbe_server   Author: xiaohaoppy   File: test_threading.py    (license) View Source Project 5 votes vote down vote up
def test_limbo_cleanup(self):
        # Issue 7481: Failure to start thread should cleanup the limbo map.
        def fail_new_thread(*args):
            raise threading.ThreadError()
        _start_new_thread = threading._start_new_thread
        threading._start_new_thread = fail_new_thread
        try:
            t = threading.Thread(target=lambda: None)
            self.assertRaises(threading.ThreadError, t.start)
            self.assertFalse(
                t in threading._limbo,
                "Failed to cleanup _limbo map on failure of Thread.start().")
        finally:
            threading._start_new_thread = _start_new_thread 
Example 38
Project: PKM2   Author: Szonek   File: ai-ballSTREAM.py    (license) View Source Project 5 votes vote down vote up
def run(self):
        bytes = b''
        while not self.thread_cancelled:
            try:
                bytes += self.stream.raw.read(1024)
                a = bytes.find(b'\xff\xd8')
                b = bytes.find(b'\xff\xd9')
                if a != -1 and b != -1:
                    jpg = bytes[a:b + 2]
                    bytes = bytes[b + 2:]
                    frame = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
                    #------------------ insert algorythms HERE ------------------

                    # Display the resulting frame
                    cv2.imshow('Video', frame)
                    # ------------------ algorythms end HERE ------------------
                    if cv2.waitKey(1) & 0xFF == ord('q'):
                        exit(0)
            except ThreadError:
                self.thread_cancelled = True 
Example 39
Project: PKM2   Author: Szonek   File: ai-ball_FaceDetect.py    (license) View Source Project 5 votes vote down vote up
def run(self):
        bytes = b''
        while not self.thread_cancelled:
            try:
                bytes += self.stream.raw.read(1024)
                a = bytes.find(b'\xff\xd8')
                b = bytes.find(b'\xff\xd9')
                if a != -1 and b != -1:
                    jpg = bytes[a:b + 2]
                    bytes = bytes[b + 2:]
                    frame = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
                    #------------------ insert algorythms HERE ------------------
                    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

                    faces = faceCascade.detectMultiScale(
                        gray,
                        scaleFactor=1.15,
                        minNeighbors=5,
                        minSize=(20, 20),
                        flags=cv2.CASCADE_SCALE_IMAGE
                    )

                    # Draw a rectangle around the faces
                    for (x, y, w, h) in faces:
                        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)

                    # Display the resulting frame
                    cv2.imshow('Video', frame)
                    # ------------------ algorythms end HERE ------------------
                    if cv2.waitKey(1) & 0xFF == ord('q'):
                        exit(0)
            except ThreadError:
                self.thread_cancelled = True 
Example 40
Project: GAMADV-XTD   Author: taers232c   File: lock.py    (license) View Source Project 4 votes vote down vote up
def locked(*args, **kwargs):
    """A locking **method** decorator.

    It will look for a provided attribute (typically a lock or a list
    of locks) on the first argument of the function decorated (typically this
    is the 'self' object) and before executing the decorated function it
    activates the given lock or list of locks as a context manager,
    automatically releasing that lock on exit.

    NOTE(harlowja): if no attribute name is provided then by default the
    attribute named '_lock' is looked for (this attribute is expected to be
    the lock/list of locks object/s) in the instance object this decorator
    is attached to.

    NOTE(harlowja): a custom logger (which will be used if lock release
    failures happen) can be provided by passing a logger instance for keyword
    argument ``logger``.
    """

    def decorator(f):
        attr_name = kwargs.get('lock', '_lock')
        logger = kwargs.get('logger')

        @six.wraps(f)
        def wrapper(self, *args, **kwargs):
            attr_value = getattr(self, attr_name)
            if isinstance(attr_value, (tuple, list)):
                with _utils.LockStack(logger=logger) as stack:
                    for i, lock in enumerate(attr_value):
                        if not stack.acquire_lock(lock):
                            raise threading.ThreadError("Unable to acquire"
                                                        " lock %s" % (i + 1))
                    return f(self, *args, **kwargs)
            else:
                lock = attr_value
                with lock:
                    return f(self, *args, **kwargs)

        return wrapper

    # This is needed to handle when the decorator has args or the decorator
    # doesn't have args, python is rather weird here...
    if kwargs or not args:
        return decorator
    else:
        if len(args) == 1:
            return decorator(args[0])
        else:
            return decorator 
Example 41
Project: deb-python-fasteners   Author: openstack   File: lock.py    (license) View Source Project 4 votes vote down vote up
def locked(*args, **kwargs):
    """A locking **method** decorator.

    It will look for a provided attribute (typically a lock or a list
    of locks) on the first argument of the function decorated (typically this
    is the 'self' object) and before executing the decorated function it
    activates the given lock or list of locks as a context manager,
    automatically releasing that lock on exit.

    NOTE(harlowja): if no attribute name is provided then by default the
    attribute named '_lock' is looked for (this attribute is expected to be
    the lock/list of locks object/s) in the instance object this decorator
    is attached to.

    NOTE(harlowja): a custom logger (which will be used if lock release
    failures happen) can be provided by passing a logger instance for keyword
    argument ``logger``.
    """

    def decorator(f):
        attr_name = kwargs.get('lock', '_lock')
        logger = kwargs.get('logger')

        @six.wraps(f)
        def wrapper(self, *args, **kwargs):
            attr_value = getattr(self, attr_name)
            if isinstance(attr_value, (tuple, list)):
                with _utils.LockStack(logger=logger) as stack:
                    for i, lock in enumerate(attr_value):
                        if not stack.acquire_lock(lock):
                            raise threading.ThreadError("Unable to acquire"
                                                        " lock %s" % (i + 1))
                    return f(self, *args, **kwargs)
            else:
                lock = attr_value
                with lock:
                    return f(self, *args, **kwargs)

        return wrapper

    # This is needed to handle when the decorator has args or the decorator
    # doesn't have args, python is rather weird here...
    if kwargs or not args:
        return decorator
    else:
        if len(args) == 1:
            return decorator(args[0])
        else:
            return decorator 
Example 42
Project: captiv8   Author: wraith-wireless   File: collect.py    (license) View Source Project 4 votes vote down vote up
def _setup(self):
        """ setup radio and tuning thread """
        # set up the radio for collection
        nlsock = None
        try:
            # get a netlink socket for this
            nlsock = nl.nl_socket_alloc()

            # get dev info for dev and it's phy index
            self._dinfo = pyw.devinfo(self._dev,nlsock)
            phy = self._dinfo['card'].phy

            # delete all associated interfaces
            for c,_ in pyw.ifaces(self._dinfo['card'],nlsock): pyw.devdel(c,nlsock)

            # create a new card in monitor mode
            self._card = pyw.phyadd(phy,'cap8','monitor',None,nlsock)
            pyw.up(self._card)

            # determine scannable channels, then go to first channel
            scan = []
            for rf in pyw.devfreqs(self._card,nlsock):
                for chw in channels.CHTYPES:
                    try:
                        pyw.freqset(self._card,rf,chw,nlsock)
                        scan.append((rf, chw))
                    except pyric.error as e:
                        if e.errno != pyric.EINVAL: raise
            assert scan
            pyw.freqset(self._card,scan[0][0],scan[0][1],nlsock)

            # create the tuner & sniffer
            self._pktq = mp.Queue()
            self._tuner = Tuner(self._card,scan)
            self._sniffer = Sniffer(self._pktq,self._card.dev)
        except RuntimeError as e:
            self._teardown()
            raise RuntimeError("Error binding socket {0}".format(e))
        except threading.ThreadError as e:
            self._teardown()
            raise RuntimeError("Unexepected error in the workers {0}".format(e))
        except AssertionError:
            self._teardown()
            raise RuntimeError("No valid scan channels found")
        except nl.error as e:
            self._teardown()
            raise RuntimeError("ERRNO {0} {1}".format(e.errno, e.strerror))
        except pyric.error as e:
            self._teardown() # attempt to restore
            raise RuntimeError("ERRNO {0} {1}".format(e.errno, e.strerror))
        finally:
            nl.nl_socket_free(nlsock) 
Example 43
Project: vision-code   Author: FIRST-Team-1699   File: python.py    (license) View Source Project 4 votes vote down vote up
def run(self):
    bytes='' 
    while not self.thread_cancelled:
      try:
        bytes+=self.stream.raw.read(1024) 
        a = bytes.find('\xff\xd8')
        b = bytes.find('\xff\xd9')
        if a!=-1 and b!=-1:
          jpg = bytes[a:b+2]
          bytes= bytes[b+2:]
          img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR)

          # Convert BGR to HSV
          hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
          # define range of blue color in HSV
          #lower_blue = np.array([self.L_RED, self.L_GREEN, self.L_BLUE], np.uint8)
          #upper_blue = np.array([self.U_RED, self.U_GREEN, self.L_BLUE], np.uint8)

          # Threshold the HSV image to get only blue colors
          mask = cv2.inRange(hsv, np.array([53,187,37]), np.array([97,244,153]))

          # Bitwise-AND mask and original image
          res = cv2.bitwise_and(img,img, mask= mask)
####        blurred = cv2.GaussianBlur(mask, (5, 5), 0)
          blurred = cv2.boxFilter(mask, 0, (7, 7), mask, (-1, -1), False, cv2.BORDER_DEFAULT)
          thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
          cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
          cnts = cnts[0] if imutils.is_cv2() else cnts[1]
          cv2.filterSpeckles(mask, 0, 100, 25)
##          cv2.filterSpeckles(mask, 0, 50, 25)
##          cv2.filterSpeckles(mask, 0, 100, 100)
          for c in cnts:
              M = cv2.moments(c)
              if int(M["m00"]) != 0:
                  cX = int(M["m10"] / M["m00"])
                  cY = int(M["m01"] / M["m00"])
              else:
                  (cX, cY) = (0, 0)
              print(cX, cY)
              cv2.drawContours(res, [c], -1, (0, 255, 0), 2)
              cv2.circle(res, (cX, cY), 7, (255, 255, 255), 1)

             # table.putNumber("center X", cX)
          cv2.imshow('img',img)
          cv2.imshow('mask',mask)
          cv2.imshow('Final',res)
          cv2.imshow('cam',img)
          #sd.putNumber('Center X', cX) ##send the x value of the center
          #sd.putNumber('Center Y', cY) ##send the y value of the center
##          print(sd.getNumber('Center Y'), sd.getNumber('Center X'))
          if cv2.waitKey(1) ==27:
            exit(0)
      except ThreadError:
        self.thread_cancelled = True 
Example 44
Project: vision-code   Author: FIRST-Team-1699   File: PythonVideoVision2017.py    (license) View Source Project 4 votes vote down vote up
def run(self):
    bytes='' 
    while not self.thread_cancelled:  ####see lines 18, 80, 88 ....
      try:        
        bytes+=self.stream.raw.read(1024) ##limit max bytes read in 1 itteration? need to read more on this
        a = bytes.find('\xff\xd8')##find start of stream of data  
        b = bytes.find('\xff\xd9')##find our end of data stream
        if a!=-1 and b!=-1:  ##so as long as we have a stream of data....do the following
          jpg = bytes[a:b+2]  ##converts to image or a specific variable...
          bytes= bytes[b+2:]  
          img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR)  ##decode the data

          # Convert BGR to HSV
          hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)  ##converting color format for easier proccessing/ math
          # define range of blue color in HSV
          #lower_blue = np.array([self.L_RED, self.L_GREEN, self.L_BLUE], np.uint8)
          #upper_blue = np.array([self.U_RED, self.U_GREEN, self.L_BLUE], np.uint8)

          # Threshold the HSV image to get only blue colors
          mask = cv2.inRange(hsv, np.array([53,187,37]), np.array([97,244,153]))  ##get colors in the range of these HSV values

          # Bitwise-AND mask and original image
          res = cv2.bitwise_and(img,img, mask= mask)

          blurred = cv2.boxFilter(mask, 0, (7, 7), mask, (-1, -1), False, cv2.BORDER_DEFAULT) ##the next few line create outlines and 
          thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]                      ##remove any noise
          cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)  #find countors
          cnts = cnts[0] if imutils.is_cv2() else cnts[1]   
          cv2.filterSpeckles(mask, 0, 100, 25)      ##remove speckles aka random dots and white noise
          for c in cnts:
              M = cv2.moments(c)
              if int(M["m00"]) != 0:  ##Checks for division by zero
                  cX = int(M["m10"] / M["m00"])
                  cY = int(M["m01"] / M["m00"])
              else:
                  (cX, cY) = (0, 0)
              cv2.drawContours(res, [c], -1, (0, 255, 0), 2)  ##draw box/highlighting 
              cv2.circle(res, (cX, cY), 7, (255, 255, 255), 1)  ##draw box/highlighting 
              
              ##Try-Catch for appending cX to table
              try:
                self.table.putNumber('centerX', cX)  ##Adds cX to the networktables
              except KeyError:
                print("centerX failed.")
              
          cv2.imshow('img',img)   ##display original image
          cv2.imshow('mask',mask)  ##display masked image
          cv2.imshow('Final',res)  ##show final image
          
          
          cv2.imshow('cam',img)  ##see line 71/comments
          if cv2.waitKey(1) ==27:  ##now we close if esc key is pressed
            exit(0)
      except ThreadError:
        self.thread_cancelled = True 
Example 45
Project: GAMADV-X   Author: taers232c   File: lock.py    (license) View Source Project 4 votes vote down vote up
def locked(*args, **kwargs):
    """A locking **method** decorator.

    It will look for a provided attribute (typically a lock or a list
    of locks) on the first argument of the function decorated (typically this
    is the 'self' object) and before executing the decorated function it
    activates the given lock or list of locks as a context manager,
    automatically releasing that lock on exit.

    NOTE(harlowja): if no attribute name is provided then by default the
    attribute named '_lock' is looked for (this attribute is expected to be
    the lock/list of locks object/s) in the instance object this decorator
    is attached to.

    NOTE(harlowja): a custom logger (which will be used if lock release
    failures happen) can be provided by passing a logger instance for keyword
    argument ``logger``.
    """

    def decorator(f):
        attr_name = kwargs.get('lock', '_lock')
        logger = kwargs.get('logger')

        @six.wraps(f)
        def wrapper(self, *args, **kwargs):
            attr_value = getattr(self, attr_name)
            if isinstance(attr_value, (tuple, list)):
                with _utils.LockStack(logger=logger) as stack:
                    for i, lock in enumerate(attr_value):
                        if not stack.acquire_lock(lock):
                            raise threading.ThreadError("Unable to acquire"
                                                        " lock %s" % (i + 1))
                    return f(self, *args, **kwargs)
            else:
                lock = attr_value
                with lock:
                    return f(self, *args, **kwargs)

        return wrapper

    # This is needed to handle when the decorator has args or the decorator
    # doesn't have args, python is rather weird here...
    if kwargs or not args:
        return decorator
    else:
        if len(args) == 1:
            return decorator(args[0])
        else:
            return decorator