Example #1
0
    def __init__(self, crypter, negotiator):
        asynchat.async_chat.__init__(self)
        self.received_data = ''
        self.crypter = crypter
        self.negotiator = negotiator
        self.set_terminator(MessageManager.MULTI_MESSAGE_DELIMITER)
        self.negotiation_lock = mutex.mutex()
        self.progress_lock = mutex.mutex()
        self.in_step_through_mode = False
        self.shared_secret = ""
        self.integrity_hash = None

        self.logger = None
        self.debugger = None
        self.debugger_raw = None
Example #2
0
def compare_all_files(file_name='file', magdir='Magdir', exact=False):
    pool = ThreadPool(4)
    m = mutex.mutex()

    split_patterns(magdir, file_name)
    compile_patterns(file_name)
    compiled = is_compilation_supported(file_name)

    entries = get_stored_files("db")

    def store_mimedata(data):
        metadata = get_full_metadata(data[0], file_name, compiled)
        stored_metadata = get_stored_metadata(data[0])
        text = "PASS " + data[0]
        if is_regression(stored_metadata, metadata, exact):
            text = "FAIL " + data[0] + "\n" + get_diff(stored_metadata,
                                                       metadata, exact)
        return text

    def data_print(data):
        print data
        m.unlock()

    def data_stored(data):
        m.lock(data_print, data)

    for i, entry in enumerate(entries):
        # Insert tasks into the queue and let them run
        pool.queueTask(store_mimedata, (entry, i % 2), data_stored)

    # When all tasks are finished, allow the threads to terminate
    pool.joinAll()
    print ''
Example #3
0
 def __init__(self,
              name,
              dim=100,
              window=10,
              min_count=1,
              parallelism=1,
              use_stem=False,
              iterations=100,
              learning_rate=0.025):
     self.name = name
     self.dimension = dim
     self.window = window
     self.min_count = min_count
     self.parallelism = parallelism
     self.sample = 1
     self.iterations = iterations
     self.alpha = learning_rate
     self.sentence_func = self.strip_non_ascii
     self.stemmer = PorterStemmer().stem if use_stem else lambda e: e
     self.stop_words = stopwords.words('english')
     self.stopwords = {self.stemmer(w): True for w in self.stop_words}
     self.tokenizer = self.form_sentences
     self.train_lock = mutex.mutex()
     self.doc_tags = {}
     self.model = None
Example #4
0
    def __init__(self, needed_caps):
        self._width = None
        self._height = None
        self._current_frame = None
        gobject.threads_init()
        self._mutex = mutex()
        gst.Bin.__init__(self)
        self._capsfilter = gst.element_factory_make('capsfilter', 'capsfilter')

        self.set_caps(needed_caps)
        self.add(self._capsfilter)

        fakesink = gst.element_factory_make('fakesink', 'fakesink')
        fakesink.set_property("sync", True)
        self.add(fakesink)
        self._capsfilter.link(fakesink)

        pad = self._capsfilter.get_pad("sink")
        ghostpad = gst.GhostPad("sink", pad)

        pad2probe = fakesink.get_pad("sink")
        pad2probe.add_buffer_probe(self.buffer_probe)

        self.add_pad(ghostpad)
        self.sink = self._capsfilter
 def __init__(self, uid, path):
   self.id = None
   self.proxy = None
   self.uid = uid
   self.path = path
   self.mutex = mutex.mutex()
   self.loaded = False
Example #6
0
 def __init__(self, screen, num, image, sprites):
     """
     initialising
     :param screen: main view screen
     :param num: number of client
     :param image: image of player
     :param sprites: another objects in game
     :param players: another players
     :return:
     """
     self.active = False
     self.sprites = sprites
     self.movingright = False
     self.movingleft = False
     self.num = num
     self.__posx = random.randint(0, LENGTH_BOUND)
     self.__posy = random.randint(MAGIC_TWNT, HIGH_BOUND - DIST_DIFF)
     self.playerview = PlayerView(screen, self, image)
     self.dx = 0
     self.jumping = False
     self.jump_speed = 0
     self.jump_acceleration = 0
     self.landed = False
     self.died = False
     self.send_died = False
     self.score = 0
     self.onboard = False
     self.movingactions = dict()
     self.movingactions[LEFT] = self.lefthandler
     self.movingactions[RIGHT] = self.righthandler
     self.movingactions[JUMP] = self.jumphandler
     self.mutex = mutex.mutex()
Example #7
0
    def __init__(self, nResolutionW, nResolutionH):
        self.nResolutionW = nResolutionW  # rendeing resolution, could and will be different than window size
        self.nResolutionH = nResolutionH
        # but for the moment, they are of the same size
        self.listPts = [
        ]  # a list of list of coord (one for each trace) (currently traced)

        self.listFigures = []
        self.listLinks = []

        # this is an image used for shape sorting: each inner shape will be paint with a specific color
        # and then a direct piking from mouse pointing will tell us, if we're inside or outside...
        # index => index of shape
        # 0 .. 1023 => rect (actually 0 .. kNbrFiguresPerShapeStyle
        # 1024.. 2047 => rect with title
        # ...
        self.kNbrFiguresPerShapeStyle = 1024
        #self.sortbuf = numpy.zeros((nResolutionH,nResolutionW,1), numpy.uint16)
        self.repaintSortBuf()

        self.nGridSize = 20
        self.bMouseDown = False
        self.aMouseDownPos = []
        self.mutexMouse = mutex.mutex()

        self.figMoved = None  # a shape currently moving with mouse
        self.nIdxFigSelected = -1

        self.strSaveFilename = "/tmp/fastscheme.dat"
        self.loadFromDisk()
Example #8
0
 def __init__(self):
     pos_dist = np.load("/home/ubuntu/TLD/posDist.npy").tolist()
     neg_dist = np.load("/home/ubuntu/TLD/negDist.npy").tolist()
     self.active = True
     self.bridge = CvBridge()
     self.Detector = Detector()
     self.Detector.set_posterior(pos_dist, neg_dist)
     self.Tracker = Tracker()
     self.tracking = False
     self.sub_image = rospy.Subscriber(
         "/autopilot/camera_node/image/compressed",
         CompressedImage,
         self.cbImage,
         queue_size=1)
     self.pub_image = rospy.Publisher("~image_with_detection",
                                      Image,
                                      queue_size=1)
     self.pub_vehicle_detected = rospy.Publisher("~vehicle_detected",
                                                 VehicleDetected,
                                                 queue_size=1)
     self.pub_vehicle_bbox = rospy.Publisher("~vehicle_bounding_box",
                                             VehicleBoundingBox,
                                             queue_size=1)
     self.lock = mutex()
     bbox = []
     self.tracking = True
Example #9
0
    def __init__(self, needed_caps):
        self._width = None
        self._height = None
        self._current_frame = None
        gobject.threads_init()
        self._mutex = mutex()
        gst.Bin.__init__(self)
        self._capsfilter = gst.element_factory_make('capsfilter', 'capsfilter')

        self.set_caps(needed_caps)
        self.add(self._capsfilter)
        
        fakesink = gst.element_factory_make('fakesink', 'fakesink')
        fakesink.set_property("sync", True)
        self.add(fakesink)
        self._capsfilter.link(fakesink)
        
        pad = self._capsfilter.get_pad("sink")
        ghostpad = gst.GhostPad("sink", pad)
        
        pad2probe = fakesink.get_pad("sink")
        pad2probe.add_buffer_probe(self.buffer_probe)

        self.add_pad(ghostpad)
        self.sink = self._capsfilter
Example #10
0
    def __init__(self):
        self.node_name = rospy.get_name()
        self.bridge = CvBridge()

        self.distance_between_centers = self.setupParam(
            'distance_between_centers', 0.0125)
        self.max_reproj_pixelerror_pose_estimation = self.setupParam(
            'max_reproj_pixelerror_pose_estimation', 5)

        self.sub_corners = rospy.Subscriber("~corners",
                                            VehicleCorners,
                                            self.processCorners,
                                            queue_size=1)

        self.pub_pose = rospy.Publisher("~pose", VehiclePose, queue_size=1)
        self.sub_info = rospy.Subscriber("~camera_info",
                                         CameraInfo,
                                         self.processCameraInfo,
                                         queue_size=1)
        self.pub_time_elapsed = rospy.Publisher("~pose_calculation_time",
                                                Float32,
                                                queue_size=1)
        self.pcm = PinholeCameraModel()
        rospy.loginfo("[%s] Initialization completed" % (self.node_name))
        self.lock = mutex()
 def __init__(self):
   try:
     self.mutex
   except:
     self.audioProxy = naoqi.ALProxy("ALAudioPlayer")        
     self.mutex = mutex.mutex()
     self.aSoundBank = {}
Example #12
0
    def __init__(self):
        if (system.isOnNao()):
            self.strFileName = "/home/nao/www/blog/index.html"
        elif (system.isOnWin32()):
            self.strFileName = "D:/ApacheRootWebSite2/htdocs/naoblog/index.html"
        else:
            self.strFileName = "/www/blog"

        self.strImgFolderAbs = os.path.dirname(self.strFileName) + "/img/"
        self.strImgFolderLocal = "img/"
        self.strEmoFolderAbs = os.path.dirname(self.strFileName) + "/emo/"
        self.strEmoFolderLocal = "emo/"

        self.logMutex = mutex.mutex()
        self.logLastTime = None

        # constants:
        self.none = 0
        self.happy = 1
        self.sad = 2
        self.proud = 3
        self.excitement = 4
        self.fear = 5
        self.anger = 6
        self.neutral = 7
        self.hot = 8
Example #13
0
	def __init__(self):
		self.node_name = rospy.get_name()
		self.bridge = CvBridge()
		self.active = True
		self.config	= self.setupParam("~config", "baseline")
		self.cali_file_name = self.setupParam("~cali_file_name", "default")
		rospack = rospkg.RosPack()
		self.cali_file = rospack.get_path('duckietown') + \
				"/config/" + self.config + \
				"/vehicle_detection/vehicle_detection_node/" +  \
				self.cali_file_name + ".yaml"
		if not os.path.isfile(self.cali_file):
			rospy.logwarn("[%s] Can't find calibration file: %s.\n" 
					% (self.node_name, self.cali_file))
		self.loadConfig(self.cali_file)
		self.sub_image = rospy.Subscriber("~image", Image, 
				self.cbImage, queue_size=1)
		self.sub_switch = rospy.Subscriber("~switch", BoolStamped,
				self.cbSwitch, queue_size=1)
		self.pub_detection = rospy.Publisher("~detection", 
				BoolStamped, queue_size=1)
		self.pub_circlepattern_image = rospy.Publisher("~circlepattern_image", 
				Image, queue_size=1)
		self.pub_time_elapsed = rospy.Publisher("~detection_time",
			Float32, queue_size=1)
		self.lock = mutex()
		rospy.loginfo("[%s] Initialization completed" % (self.node_name))
Example #14
0
 def __init__(self, value_type=None, py_value=None):
     self._del_mutex = mutex.mutex()
     GObjectModule.Value.__init__(self)
     if value_type is not None:
         self.init(value_type)
         if py_value is not None:
             self.set_value(py_value)
Example #15
0
 def __init__(self):
     try:
         self.mutex
     except:
         self.audioProxy = naoqi.ALProxy("ALAudioPlayer")
         self.mutex = mutex.mutex()
         self.aSoundBank = {}
Example #16
0
 def __init__(self, uid, path):
     self.id = None
     self.proxy = None
     self.uid = uid
     self.path = path
     self.mutex = mutex.mutex()
     self.loaded = False
Example #17
0
    def __init__(self):
        self.node_name = rospy.get_name()
        self.bridge = CvBridge()
        self.active = True

        self.publish_freq = self.setupParam("~publish_freq", 2.0)
        self.circlepattern_dims = tuple(self.setupParam('~circlepattern_dims/data', [7, 3]))
        self.blobdetector_min_area = self.setupParam('~blobdetector_min_area', 10)
        self.blobdetector_min_dist_between_blobs = self.setupParam('~blobdetector_min_dist_between_blobs', 2)
        self.publish_circles = self.setupParam('~publish_circles', True)

        self.publish_duration = rospy.Duration.from_sec(1.0/self.publish_freq)
        self.last_stamp = rospy.Time.now()


        self.lock = mutex()
        self.sub_image = rospy.Subscriber("~image", CompressedImage,
                                          self.processImage, buff_size=921600, 
                                          queue_size=1)
        self.sub_switch = rospy.Subscriber("~switch", BoolStamped,
                                           self.cbSwitch, queue_size=1)
        self.pub_detection = rospy.Publisher("~detection",
                                             BoolStamped, queue_size=1)
        self.pub_corners = rospy.Publisher("~corners",
                                           VehicleCorners, queue_size=1)
        self.pub_circlepattern_image = rospy.Publisher("~circlepattern_image",
                                                       Image, queue_size=1)
        self.pub_time_elapsed = rospy.Publisher("~detection_time",
                                                Float32, queue_size=1)

        rospy.loginfo("[%s] Initialization completed" % (self.node_name))
Example #18
0
    def __init__(self):
        self.node_name = rospy.get_name()
        self.bridge = CvBridge()

        self.config = self.setupParam("~config", "baseline")
        self.cali_file_name = self.setupParam("~cali_file_name", "default")
        rospack = rospkg.RosPack()
        self.cali_file = "/code/catkin_ws/src/dt-core/packages/vehicle_detection/config/vehicle_filter_node/" +  \
            self.cali_file_name + ".yaml"
        if not os.path.isfile(self.cali_file):
            rospy.logwarn("[%s] Can't find calibration file: %s.\n" %
                          (self.node_name, self.cali_file))
        self.loadConfig(self.cali_file)

        self.sub_corners = rospy.Subscriber("~corners",
                                            VehicleCorners,
                                            self.processCorners,
                                            queue_size=1)

        self.pub_pose = rospy.Publisher("~pose", VehiclePose, queue_size=1)
        self.sub_info = rospy.Subscriber("~camera_info",
                                         CameraInfo,
                                         self.processCameraInfo,
                                         queue_size=1)
        self.pub_time_elapsed = rospy.Publisher("~pose_calculation_time",
                                                Float32,
                                                queue_size=1)
        self.pcm = PinholeCameraModel()
        rospy.loginfo("[%s] Initialization completed" % (self.node_name))
        self.lock = mutex()
Example #19
0
 def __init__(self):
     if( system.isOnNao() ):
         self.strFileName = "/home/nao/www/blog/index.html";
     elif( system.isOnWin32() ):
         self.strFileName = "D:/ApacheRootWebSite2/htdocs/naoblog/index.html";
     else:
         self.strFileName = "/www/blog";
         
     self.strImgFolderAbs = os.path.dirname( self.strFileName ) + "/img/";
     self.strImgFolderLocal = "img/";        
     self.strEmoFolderAbs = os.path.dirname( self.strFileName ) + "/emo/";
     self.strEmoFolderLocal = "emo/";
     
     self.logMutex = mutex.mutex();
     self.logLastTime = None;
     
     # constants:
     self.none = 0;
     self.happy = 1;
     self.sad = 2;
     self.proud = 3;
     self.excitement = 4;
     self.fear = 5;
     self.anger = 6;
     self.neutral = 7;
     self.hot= 8;
Example #20
0
    def __init__(self):
        self.node_name = rospy.get_name()
        self.bridge = CvBridge()

        self.config = self.setupParam("~config", "baseline")
        self.cali_file_name = self.setupParam("~cali_file_name", "default")
        rospack = rospkg.RosPack()
        self.cali_file = rospack.get_path('duckietown') + \
          "/config/" + self.config + \
          "/vehicle_detection/vehicle_filter_node/" +  \
          self.cali_file_name + ".yaml"
        if not os.path.isfile(self.cali_file):
            rospy.logwarn("[%s] Can't find calibration file: %s.\n" %
                          (self.node_name, self.cali_file))
        self.loadConfig(self.cali_file)
        self.sub_corners = rospy.Subscriber("~corners",
                                            VehicleCorners,
                                            self.cbCorners,
                                            queue_size=1)
        self.pub_pose = rospy.Publisher("~pose", VehiclePose, queue_size=1)
        self.sub_info = rospy.Subscriber("~camera_info",
                                         CameraInfo,
                                         self.cbCameraInfo,
                                         queue_size=1)
        self.pcm = PinholeCameraModel()
        rospy.loginfo("[%s] Initialization completed" % (self.node_name))
        self.lock = mutex()
Example #21
0
def compare_all_files(file_name = 'file', magdir = 'Magdir', exact = False):
	pool = ThreadPool(4)
	m = mutex.mutex()

	split_patterns(magdir, file_name)
	compile_patterns(file_name)
	compiled = is_compilation_supported(file_name)

	entries = get_stored_files("db")

	def store_mimedata(data):
		metadata = get_full_metadata(data[0], file_name, compiled)
		stored_metadata = get_stored_metadata(data[0])
		text = "PASS " + data[0]
		if is_regression(stored_metadata, metadata, exact):
			text = "FAIL " + data[0] + "\n" + get_diff(stored_metadata, metadata, exact)
		return text

	def data_print(data):
		print data
		m.unlock()

	def data_stored(data):
		m.lock(data_print, data)

	for i,entry in enumerate(entries):
		# Insert tasks into the queue and let them run
		pool.queueTask(store_mimedata, (entry, i % 2), data_stored)

	# When all tasks are finished, allow the threads to terminate
	pool.joinAll()
	print ''
Example #22
0
    def __init__(self, nImgSizeW, nImgSizeH, nScreenSizeW, nScreenSizeH):
        self.nImgSizeW = nImgSizeW  # rendering resolution, could and will be different than window size
        self.nImgSizeH = nImgSizeH
        self.nScreenSizeW = nScreenSizeW  # rendering resolution, could and will be different than window size
        self.nScreenSizeH = nScreenSizeH

        self.resetPixels()

        self.colors = []
        self.colors.append((0, 0, 0))
        self.colors.append((255, 255, 255))
        self.colors.append((127, 127, 127))
        self.colors.append((0, 0, 255))
        self.colors.append((0, 255, 0))
        self.colors.append((255, 0, 0))
        self.nExtraColorIndex = 2

        # test:
        self.pixels[0][0] = 0
        self.pixels[-1][-1] = 0
        self.bMouseDown = False

        self.lastDrawX = self.lastDrawY = -1
        self.currentColorIndex = -1
        self.bAlreadyToggled = False

        self.mutexMouse = mutex.mutex()

        self.strSaveFilename = "/tmp/fastscheme.dat"
        self.loadFromDisk()

        self.computeScreenLayout()

        self.timeBeginDraw = time.time()
	def __init__(self):
		self.node_name = rospy.get_name()
		self.bridge = CvBridge()
		self.active = True
		self.config	= self.setupParam("~config", "baseline")
		self.cali_file_name = self.setupParam("~cali_file_name", "default")
		rospack = rospkg.RosPack()
		self.cali_file = rospack.get_path('duckietown') + \
				"/config/" + self.config + \
				"/vehicle_detection/vehicle_detection_node/" +  \
				self.cali_file_name + ".yaml"
		if not os.path.isfile(self.cali_file):
			rospy.logwarn("[%s] Can't find calibration file: %s.\n" 
					% (self.node_name, self.cali_file))
		self.loadConfig(self.cali_file)
		self.sub_image = rospy.Subscriber("~image", Image, 
				self.cbImage, queue_size=1)
		self.sub_switch = rospy.Subscriber("~switch", BoolStamped,
				self.cbSwitch, queue_size=1)
		self.pub_detection = rospy.Publisher("~detection", 
				BoolStamped, queue_size=1)
		self.pub_circlepattern_image = rospy.Publisher("~circlepattern_image", 
				Image, queue_size=1)
		self.pub_time_elapsed = rospy.Publisher("~detection_time",
			Float32, queue_size=1)
		self.lock = mutex()
		rospy.loginfo("[%s] Initialization completed" % (self.node_name))
Example #24
0
 def __init__(self):
     self.map_data = {}
     self.building_names = {}
     self.map_mutex = mutex.mutex()
     for i in range(10000):
         self.map_data[i] = UDMapEntry(i)
     self.load()
     self.load_types()
 def __init__(self):
     debug.debug( "INF: PersistentMemoryDataManager.__init__ called" );
     self.allData = {};
     self.mutexListData = mutex.mutex();
     try:
         os.makedirs( PersistentMemoryData.getVarPath() );
     except:
         pass # le dossier existe deja !
Example #26
0
  def __init__(self, settings, camera):
    self.settings = settings
    self.camera = camera
    self.mutex = mutex.mutex()

    self.jancodes = []
    self.last_appear_time = time.time()
    self.shuttered = False
Example #27
0
 def __init__(self):
     debug.debug("INF: PersistentMemoryDataManager.__init__ called")
     self.allData = {}
     self.mutexListData = mutex.mutex()
     try:
         os.makedirs(PersistentMemoryData.getVarPath())
     except:
         pass  # le dossier existe deja !
 def __init__(self):
   try:
     self.mutex
   except:
     self.fm = naoqi.ALProxy("ALFrameManager")
     self.mutex = mutex.mutex()
     self.aLoaded = {}
     self.aRunning = {}
Example #29
0
 def __init__(self):
   try:
     self.mutex
   except:
     self.fm = naoqi.ALProxy("ALFrameManager")        
     self.mutex = mutex.mutex()
     self.aLoaded = {}
     self.aRunning = {}
Example #30
0
 def __init__(self) :
     self.map_data = {}
     self.building_names = {}
     self.map_mutex = mutex.mutex()
     for i in range(10000) :
         self.map_data[i] = UDMapEntry(i)
     self.load()
     self.load_types()
Example #31
0
	def __init__(self):
		self.__cmdRegex = re.compile("(?P<qtype>who|what|where|when) (?P<verb>is|are|was|were) (?P<query>[^?]+)", re.I)
		self.__cacheFile = "googlism_cache"
		try: self.__cache = shelve.open(self.__cacheFile, protocol=2)
		except TypeError:
			# pre-2.3 didn't have a protocol argument.
			self.__cache = shelve.open(self.__cacheFile)
		self.__cacheMutex = mutex.mutex()
		self.__cacheKeys = self.__cache.keys()
Example #32
0
	def __init__(self):
		self.__cmdRegex = re.compile("(?P<qtype>who|what|where|when) (?P<verb>is|are|was|were) (?P<query>[^?]+)", re.I)
		self.__cacheFile = "var/cache/inet/google_cache"
		try: self.__cache = shelve.open(self.__cacheFile, protocol=2)
		except TypeError:
			# pre-2.3 didn't have a protocol argument.
			self.__cache = shelve.open(self.__cacheFile)
		self.__cacheMutex = mutex.mutex()
		self.__cacheKeys = self.__cache.keys()
Example #33
0
 def __init__(self, eventTgt):
     logging.debug( 'Harmony __INIT__ ' )
     self._eventTgt = eventTgt
     threading.Thread.__init__(self)
     self.harmonySkt = None
     self.bufferedData = ""
     self.opened = False
     self.running = True
     self.mut = mutex.mutex()
 def __init__(self, strName = None ):
     self.mutex = mutex.mutex();        
     self.strName = strName;
     self.allValue = [];  # a big array of triple [time, type, value] but because type is self explained => [time, value]  # from older to newer
     # precomputed value:
     self.lastValue = None; 
     if( strName != None ):
         self.readFromFile();
     self.timeLastSave = time.time(); # for autosaving
Example #35
0
    def __init__(self, tmp_dir, final_dir):
        self.tmp_dir = tmp_dir
        self.final_dir = final_dir

        self.filename = None
        self.fh = None

        self.mutex = mutex.mutex()

        self.roll()
Example #36
0
 def __init__(self, strName=None):
     self.mutex = mutex.mutex()
     self.strName = strName
     self.allValue = []
     # a big array of triple [time, type, value] but because type is self explained => [time, value]  # from older to newer
     # precomputed value:
     self.lastValue = None
     if (strName != None):
         self.readFromFile()
     self.timeLastSave = time.time()
Example #37
0
    def __init__(self, port, baud, target):
        self.data = 0
        self.command = 0
        self.port = serial.Serial(port, baudrate=baud, timeout=5)
        self.lock = mutex.mutex()
        self.target = target

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True  # Daemonize thread
        thread.start()  # Start the execution
def _install_restore_mode_child():
    global _mode_write_pipe
    global _restore_mode_child_installed

    if _restore_mode_child_installed:
        return

    # Parent communicates to child by sending "mode packets" through a pipe:
    mode_read_pipe, _mode_write_pipe = os.pipe()

    if os.fork() == 0:
        # Child process (watches for parent to die then restores video mode(s).
        os.close(_mode_write_pipe)

        # Set up SIGHUP to be the signal for when the parent dies.
        PR_SET_PDEATHSIG = 1
        libc = ctypes.cdll.LoadLibrary('libc.so.6')
        libc.prctl.argtypes = (ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong,
                               ctypes.c_ulong, ctypes.c_ulong)
        libc.prctl(PR_SET_PDEATHSIG, signal.SIGHUP, 0, 0, 0)

        # SIGHUP indicates the parent has died.  The child mutex is unlocked, it
        # stops reading from the mode packet pipe and restores video modes on
        # all displays/screens it knows about.
        def _sighup(signum, frame):
            parent_wait_mutex.unlock()
        parent_wait_mutex = mutex.mutex()
        parent_wait_mutex.lock(lambda arg: arg, None)
        signal.signal(signal.SIGHUP, _sighup)

        # Wait for parent to die and read packets from parent pipe
        packets = []
        buffer = ''
        while parent_wait_mutex.test():
            try:
                data = os.read(mode_read_pipe, ModePacket.size)
                buffer += data
                # Decode packets
                while len(buffer) >= ModePacket.size:
                    packet = ModePacket.decode(buffer[:ModePacket.size])
                    packets.append(packet)
                    buffer = buffer[ModePacket.size:]
            except OSError:
                pass # Interrupted system call

        for packet in packets:
            packet.set()
        os._exit(0)
        
    else:
        # Parent process.  Clean up pipe then continue running program as
        # normal.  Send mode packets through pipe as additional
        # displays/screens are mode switched.
        os.close(mode_read_pipe)
        _restore_mode_child_installed = True
	def __init__(self):
		self.node_name = "Image Average"
		self.bridge = CvBridge()
		self.pub_image = rospy.Publisher("~average_image", Image, queue_size=1)
		self.sub_image = rospy.Subscriber("/ferrari/camera_node/image/compressed", CompressedImage, 
				self.cbImage, queue_size=1)
		rospy.loginfo("Initialization of [%s] completed" % (self.node_name))
		self.lock = mutex()
		self.lock.unlock()
		self.avg_img = None
		self.count_images = 0
Example #40
0
    def __init__(self):
        self.urlhost    = ""
        self.urlport    = 0
        self.ssl        = ""

        self.id         = None
        self.fd         = None
        self.inited     = False
        
        # thread safe by grace of mutexing ...
        self.outbuffer  = ""
        self.inbuffer   = ""

        self.timeout    = 5
        self.closed     = False

        self.lastoutlen = 0
        self.outMutex   = mutex.mutex()
        self.inMutex    = mutex.mutex()

        return
Example #41
0
    def __init__(self, person_no,conf):
        self.me = person_no
        self.realme = person_no
        self.mutex = mutex.mutex()
        self.conf = conf
        
        if conf.has_key('divert_incoming_to'):
            self.me = int(conf['divert_incoming_to'])

        t=threading.Thread(target=self.jabbermain)
        t.setDaemon(1)
        t.start()
Example #42
0
 def __init__(self):
     print('intiailizing processing')
     self.gpsmutex = mutex()
     self.estmutex = mutex()
     self.attmutex = mutex()
     self.radarmutex = mutex()
     self.radarmsgavailable = False
     self.gpsavail = threading.Event()
     self.estavail = threading.Event()
     self.attavail = threading.Event()
     self.radarupdate = threading.Event()
     self.att = None
     self.est = None
     self.gps = None
     self.lastatt = None
     self.lastest = None
     self.lastgps = None
     self.I = None
     self.lastI = None
     self.radarmsgavailable = False
     self.shutdown = False
Example #43
0
def _install_restore_mode_child():
    global _mode_write_pipe
    global _restore_mode_child_installed

    if _restore_mode_child_installed:
        return

    # Parent communicates to child by sending "mode packets" through a pipe:
    mode_read_pipe, _mode_write_pipe = os.pipe()

    if os.fork() == 0:
        # Child process (watches for parent to die then restores video mode(s).
        os.close(_mode_write_pipe)

        # Set up SIGHUP to be the signal for when the parent dies.
        PR_SET_PDEATHSIG = 1
        libc = ctypes.cdll.LoadLibrary('libc.so.6')
        libc.prctl.argtypes = (ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong,
                               ctypes.c_ulong, ctypes.c_ulong)
        libc.prctl(PR_SET_PDEATHSIG, signal.SIGHUP, 0, 0, 0)

        # SIGHUP indicates the parent has died.  The child mutex is unlocked, it
        # stops reading from the mode packet pipe and restores video modes on
        # all displays/screens it knows about.
        def _sighup(signum, frame):
            parent_wait_mutex.unlock()

        parent_wait_mutex = mutex.mutex()
        parent_wait_mutex.lock(lambda arg: arg, None)
        signal.signal(signal.SIGHUP, _sighup)

        # Wait for parent to die and read packets from parent pipe
        packets = list()
        buffer = ''
        while parent_wait_mutex.test():
            data = os.read(mode_read_pipe, ModePacket.size)
            buffer += data
            # Decode packets
            while len(buffer) >= ModePacket.size:
                packet = ModePacket.decode(buffer[:ModePacket.size])
                packets.append(packet)
                buffer = buffer[ModePacket.size:]

        for packet in packets:
            packet.set()
        sys.exit(0)

    else:
        # Parent process.  Clean up pipe then continue running program as
        # normal.  Send mode packets through pipe as additional
        # displays/screens are mode switched.
        os.close(mode_read_pipe)
        _restore_mode_child_installed = True
Example #44
0
def test_all_files(exact=False, binary="file"):
    """Compare output of given file(1) binary with db for all entries."""
    global ret
    ret = 0

    print_file_info(binary)

    print_lock = mutex.mutex()

    entries = sorted(get_stored_files("db"))

    def store_mimedata(filename):
        """Compare file(1) output with db for single entry."""
        metadata = get_simple_metadata(filename, binary)
        try:
            stored_metadata = get_stored_metadata(filename)
        except IOError:
            # file not found or corrupt
            text = "FAIL " + filename + "\n" + \
                   "FAIL   could not find stored metadata!\n" + \
                   "This can mean that the File failed to generate " + \
                   "any output for this file."
        else:
            text = "PASS " + filename
            if is_regression(stored_metadata, metadata, exact):
                text = "FAIL " + filename + "\n" + \
                       get_diff(stored_metadata, metadata, exact)
        return text

    def data_print(data):
        """Print given text, set global return value, unlock print lock."""
        print(data)
        if data[0] == "F":
            global ret
            ret = 1
        print_lock.unlock()

    def data_stored(data):
        """Acquire print lock and call :py:function:`data_print`."""
        print_lock.lock(data_print, data)

    # create here so program exits if error occurs earlier
    n_threads = 1
    pool = ThreadPool(n_threads)

    for entry in entries:
        # Insert tasks into the queue and let them run
        pool.queueTask(store_mimedata, entry, data_stored)

    # When all tasks are finished, allow the threads to terminate
    pool.joinAll()
    print('')
    return ret
def test_all_files(exact=False, binary="file"):
    """Compare output of given file(1) binary with db for all entries."""
    global ret
    ret = 0

    print_file_info(binary)

    print_lock = mutex.mutex()

    entries = sorted(get_stored_files("db"))

    def store_mimedata(filename):
        """Compare file(1) output with db for single entry."""
        metadata = get_simple_metadata(filename, binary)
        try:
            stored_metadata = get_stored_metadata(filename)
        except IOError:
            # file not found or corrupt
            text = "FAIL " + filename + "\n" + \
                   "FAIL   could not find stored metadata!\n" + \
                   "This can mean that the File failed to generate " + \
                   "any output for this file."
        else:
            text = "PASS " + filename
            if is_regression(stored_metadata, metadata, exact):
                text = "FAIL " + filename + "\n" + \
                       get_diff(stored_metadata, metadata, exact)
        return text

    def data_print(data):
        """Print given text, set global return value, unlock print lock."""
        print(data)
        if data[0] == "F":
            global ret
            ret = 1
        print_lock.unlock()

    def data_stored(data):
        """Acquire print lock and call :py:function:`data_print`."""
        print_lock.lock(data_print, data)

    # create here so program exits if error occurs earlier
    n_threads = 1
    pool = ThreadPool(n_threads)

    for entry in entries:
        # Insert tasks into the queue and let them run
        pool.queueTask(store_mimedata, entry, data_stored)

    # When all tasks are finished, allow the threads to terminate
    pool.joinAll()
    print('')
    return ret
    def __init__(self, parent):
        """クラスの初期化


        [引数]
        parent -- 親クラス

        [戻り値]
        void
        """
        RtmDictCore.__init__(self, parent)
        self.parent = parent
        self.Mutex = mutex.mutex()
Example #47
0
    def __init__(self, parent):
        """クラスの初期化


        [引数]
        parent -- 親クラス

        [戻り値]
        void
        """
        RtmDictCore.__init__(self, parent)
        self.parent = parent
        self.Mutex = mutex.mutex()
    def __init__(self, indexes, dataPuller, blockSize, temporaryStorageSize=1):
        self.__dataPuller = dataPuller
        self.__indexes = indexes
        if blockSize > len(indexes):
            blockSize = len(indexes)
        self.__blockSize = blockSize
        self.__indexesBlockBorders = self._getBlockBorders(
            self.__blockSize, len(self.__indexes))
        self.__len = len(self.__indexesBlockBorders)
        if temporaryStorageSize > self.__len:
            temporaryStorageSize = self.__len
        self.__temporaryStorageSize = max(temporaryStorageSize, 1)

        self.__getItemMutex = mutex.mutex()
Example #49
0
	def __init__(self, name, notebook):
		wx.PyLog.__init__(self)
		self.tc = wx.TextCtrl(notebook, -1, style = wx.TE_MULTILINE|wx.TE_READONLY)
		self.logTime = True
		self.mutex = mutex.mutex() #control access to text controls
		self.name = name
		try:
			os.mkdir('logs')
		except OSError:
			#directory already exists
			pass
			
		self.filename = 'logs/'+time.strftime("%Y%m%d-%H%M")+self.name+'.txt'
		self.logfile_opened = False
Example #50
0
    def __init__(self,
                 servername,
                 username,
                 nQueueLen=40,
                 nNbrSimultaneousSend=1):
        self.nQueueLen = nQueueLen
        self.nNbrSimultaneousSend = nNbrSimultaneousSend  # NDEV
        self.servername = servername
        self.username = username

        self.listWaiting = []  # a list of pair src/dst file(s) to be send
        self.mutex = mutex.mutex()

        self.bst = None
        self.launchBackgroundThread()
Example #51
0
 def __init__(self, mpdclient, library, config):
     '''
     Initialize all models.
     '''
     self.mpdclient = mpdclient
     self.library = library
     self.config = config
     self.libraryMutex = mutex.mutex()
     self.playQueue = PlayQueueModel(mpdclient, library, config)
     self.playlists = PlaylistsModel(mpdclient, library)
     self.fileSystem = FileSystemModel(library)
     self.artists = ArtistsModel(library)
     self.albums = AlbumsModel(library)
     self.tracks = TracksModel(library)
     self.playerState = PlayerState(self.mpdclient, self.playQueue)
 def __init__(self):
     try:
         self.path = "RecordDB.db"
         self.table = "Record"
         SlaveNode.__init__(self)    # parent class, to do the internal database operation.
         self.connect = sqlite3.connect(self.path)
         self.cursor = self.connect.cursor()
         self.cursor.execute("select * from sqlite_master where tbl_name = '%s'" % self.table)
         self.data_row = self.cursor.fetchone()
         self.mutex = mutex.mutex()
         self.sync = 0
         if not self.data_row:
             self.cursor.execute("CREATE TABLE %s %s" % (self.table, self.template))
     except Exception, e:
         print("MoDb init failed\n")
         print(e)
Example #53
0
  def __init__(self):
    self.bt = Serial();
    self.bt.port = '/dev/cu.Group_2_are_shit-SPP'
    self.bt.baudrate = 57600
    self.bt.timeout = 1
    self.camera = Camera(self.bt)
    self.camera_state = 'idle'
    self.mut = mutex()

    fd = sys.stdin.fileno()
    tty.setcbreak(sys.stdin.fileno())

    try:
      self.bt.open()
    except SerialException, e:
      sys.stderr.write("Could not open serial port %s: %s\n" % (self.bt.portstr, e)) 
      sys.exit(1)
 def __init__(self, name, dim=100, window=10, min_count=1,
              parallelism=1, use_stem=False, iterations=100, learning_rate=0.025):
     self.name = name
     self.dimension = dim
     self.window = window
     self.min_count = min_count
     self.parallelism = parallelism
     self.sample = 1
     self.iterations = iterations
     self.alpha = learning_rate
     self.sentence_func = self.strip_non_ascii
     self.stemmer = PorterStemmer().stem if use_stem else lambda e: e
     self.stop_words = stopwords.words('english')
     self.stopwords = {self.stemmer(w): True for w in self.stop_words}
     self.tokenizer = self.form_sentences
     self.train_lock = mutex.mutex()
     self.model = None
Example #55
0
    def __init__(self, id=None, factory=None):
        """
        Create an element. As optional parameters an id and factory can be
        given.

        Id is a serial number for the element. The default id is None and will
        result in an automatic creation of an id. An existing id (such as an
        int or string) can be provided as well. An id False will result in no
        id being  given (for "transient" or helper classes).

        Factory can be provided to refer to the class that maintains the
        lifecycle of the element.
        """
        self._id = id or (id is not False and str(uuid.uuid1()) or False)
        # The factory this element belongs to.
        self._factory = factory
        self.__in_unlink = mutex.mutex()
Example #56
0
    def __init__(self, **kwargs):
        self.__query = kwargs.get('query')
        self.__numItems = 0
        self.__mutex = mutex()
        #self.__fbid = kwargs.get('user_id')
        self.__user = kwargs.get('user')
        
        #self.__access_token = kwargs.get('token')
        #self.__index_location_base = kwargs.get('index_loc')

        self.__cursor_handler = kwargs.get('cursor_handler')
        self.__THRESHOLD_MULTIPLIER = 1

        # Not sure what this is doing?
        mda =  md5.new()
        mda.update(str(self.__user.getId()) + '-' + datetime.datetime.now().isoformat())
        self.__id = mda.hexdigest()  
def test_all_files(exact = False, binary = "file"):

	global ret
	ret = 0

	print_file_info(binary)

	m = mutex.mutex()

	entries = sorted(get_stored_files("db"))

	def store_mimedata(filename):
		metadata = get_simple_metadata(filename, binary)
		try:
			stored_metadata = get_stored_metadata(filename)
		except IOError:
			# file not found or corrupt
			text = "FAIL " + filename + "\n" + "FAIL   could not find stored metadata!\n\
			This can mean that the File failed to generate any output for this file."
		else:
			text = "PASS " + filename
			if is_regression(stored_metadata, metadata, exact):
				text = "FAIL " + filename + "\n" + get_diff(stored_metadata, metadata, exact)
		return text

	def data_print(data):
		print data
		if data[0] == "F":
			global ret
			ret = 1
		m.unlock()

	def data_stored(data):
		m.lock(data_print, data)

	pool = ThreadPool(4)  # create here so program exits if error occurs earlier

	for entry in entries:
		# Insert tasks into the queue and let them run
		pool.queueTask(store_mimedata, entry, data_stored)

	# When all tasks are finished, allow the threads to terminate
	pool.joinAll()
	print ''
	return ret
Example #58
0
    def __init__(self, func, interval, maxn, args, kwargs):
        # Thread Initialize
        threading.Thread.__init__(self)
        self.setDaemon(True)

        # Event lock
        self.lock = threading.Event()
        self.addlock = mutex.mutex()

        self.func = func
        self.interval = interval
        self.lastid = None
        self.timeline = set()

        # API Arguments
        self.args = args
        self.kwargs = kwargs
        self.kwargs["count"] = maxn