예제 #1
0
    def _get_data(self):
        if self.ARG not in self.ACCEPTABLE_ARGS:
            self._error('No acceptable argument passed')

        try_count = 1

        while True:
            if try_count >= self.PULL_MAX_RETRIES:
                self._error('Max retries reached')

            try:
                if self.ARG == 'humidity':
                    data = self.sensor.humidity
                    if self._value_check(data=data,
                                         value_max=self.MAX_HUMIDITY,
                                         value_min=self.MIN_HUMIDITY):
                        break

                elif self.ARG == 'temperature':
                    data = self.sensor.temperature
                    if self._value_check(data=data,
                                         value_max=self.MAX_TEMPERATURE,
                                         value_min=self.MIN_TEMPERATURE):
                        break

            except RuntimeError as error:
                if str(error).find('Not running on a RPi') != -1:
                    self._error(
                        "The executing user is not member of the 'gpio' group!"
                    )

            time_sleep(self.PULL_INTERVAL)
            try_count += 1

        return {'data': "%.2f" % data}
예제 #2
0
    def get_lon_lat_time(self, cache, dsURL):
        ### Get TIME, LAT, LON
        # first try from cache
        print 'Get lon, lat, time'
        lon, lat, time  = None, None, None
        if cache:
            gridFile = os.path.join(cache, os.path.split(dsURL)[1]+'_grid.npz')
            if os.path.exists(gridFile):
                try:
                    lon = np.load(gridFile)['lon']
                    lat = np.load(gridFile)['lat']
                    time = np.load(gridFile)['time']
                except:
                    time_sleep(0.5)
                    lon = np.load(gridFile)['lon']
                    lat = np.load(gridFile)['lat']
                    time = np.load(gridFile)['time']

        # if cache does not exist try to fetch from remote dataset
        if lon is None:
            ds = Dataset(dsURL)
            lat = ds.variables['lat'][:]
            lon = ds.variables['lon'][:]
            timeCCI = ds.variables['time'][:]
            time = self.timecci2time(timeCCI, dsURL)

        # cache grid specs
        if cache:
            np.savez_compressed(gridFile, lon=lon, lat=lat, time=time)

        return lon, lat, time
예제 #3
0
def badoo_send_message(text):
    sent_messages_counter = 0
    login(cookie_filename='cookies_badoo_(keep_this_file_save_!_).txt',
          url=badoo_messages_url)
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located(locator=(By.CLASS_NAME,
                                                'contacts__users')))
    users_parent_elem = driver.find_element_by_class_name(
        name='contacts__users')  # To exclude itself from list
    scroll_down_users_elem(users_parent_elem=users_parent_elem)
    users = users_parent_elem.find_elements_by_class_name(
        name='contacts__item.js-contacts-item')
    for user in users:
        try:
            # Sort by a default message after a match (no need to open a dialog)
            if any(word in user.text
                   for word in ('симпатия', 'хочет общаться')):
                user.click()  # Open a chat with a user
                time_sleep(
                    1
                )  # No wait because of old element whit same id will be trigger (?)
                driver.find_element_by_id(id_='t').send_keys(text, Keys.ENTER)
                # Skip pop up AFTER sending a message after pressing an "ENTER" key)
                time_sleep(1)
                webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()
                sent_messages_counter += 1
        except Exception as e:
            print(e)
    print(f'Sent messages: {sent_messages_counter}')
예제 #4
0
    def post(self):
        user_email = self.request.get('user_email')
        root_name = self.request.get('root_name')
        title_name = self.request.get('title_name')
        plus_id = self.request.get('plus_id')
        rt_node = Node(name=root_name, title=title_name, childrenIDs=[], reference=[])
        rt_node.put()
        rtIDlist = [str(rt_node.key.id())]
        # titlelist = [title_name]
        new_clipboard = Node(name="Clipboard", title="Clipboard", childrenIDs=[], reference=[])
        new_clipboard.put()
        caction = Action(nodeid = str(rt_node.key.id()), plusid = plus_id)
        caction.put()

        ACTION_QUEUE.actions.append(caction)
        delete_list = []
        i = 0
        while i < len(ACTION_QUEUE.actions):
            if datetime.now() - ACTION_QUEUE.actions[i].lastmodified > timedelta(minutes = SOCIAL_TIME_WINDOW):
                ACTION_QUEUE.actions.remove(ACTION_QUEUE.actions[i])
            else:
                break

        ACTION_QUEUE.put()

        new_user_prof = User(email=user_email, plusid = plus_id , rootID=rtIDlist, currentrootID=rtIDlist[0], clipboardID=str(new_clipboard.key.id()))
        new_user_prof.put()
        time_sleep(NDB_UPDATE_SLEEP_TIME)

        self.redirect('/graph')
        return
예제 #5
0
파일: testing.py 프로젝트: upiq/zc.async
def wait_for_deactivation(dispatcher, seconds=6):
    for i in range(seconds * 10):
        if dispatcher.activated == False:
            break
        time_sleep(0.1)
    else:
        assert False, 'dispatcher never deactivated'
예제 #6
0
    def flush(self):
        """ Wait for playing to stop.

        """

        while bool(_espeak.espeak_IsPlaying()):
            time_sleep(0.02)
예제 #7
0
def play_proc(msg_dict):
    """ Player process

    """

    print("Playing: %s" % msg_dict['filename'])
    with AudioIO(**msg_dict) as file:
        DevIO = get_io(file)
        with DevIO(rate=file.rate, channels=file.channels,
                   depth=file.depth, bigendian=file.bigendian,
                   unsigned=file.unsigned) as device:
            file.loops = 2
            print(repr(device))
            print(repr(file))
            print(file)
            for buf in file:
                # print(len(buf))
                written = device.write(buf)
                # print(written, 'bytes written')
                if not msg_dict['playing'] or not buf and not written:
                    stdout.flush()
                    break
                while msg_dict.get('paused', False):
                    time_sleep(0.1)
                if file.length > 0:
                    perc_done = (file.position * 100) / file.length
                    perc_str = 'Position: %.2f%%' % perc_done
                    format_len = len(perc_str) + 2
                    print('\033[%dD\033[K%s' % (format_len, perc_str), end='')
                    stdout.flush()
            device.flush()
    print("\nDone.")
예제 #8
0
    def get(self, id):
        user = users.get_current_user()
        if user is None:
            # go to login page
            print("View Stream Handler: Not logged in")
            self.redirect(users.create_login_page(self.request.uri))
            return

        current_stream = stream.get_by_id(int(id))
        if not current_stream:
            self.redirect("/error/" + 'Wrong stream or page number')
            return

        if current_stream:
            # delete all the imgs, because they are huge
            for i in current_stream.figures:
                if(not i.external):
                    blobstore.delete(i.blob_key)
            queried_user_profile = user_profile.query(user_profile.user_id == user.user_id()).get()
            if queried_user_profile:
                if current_stream.name in queried_user_profile.own_streams:
                    queried_user_profile.own_streams.remove(str(current_stream.name))
                if (not queried_user_profile.own_streams) and (not queried_user_profile.subscribed_streams):
                    # no own_streams nor subscribed_streams
                    queried_user_profile.key.delete()
                else:
                    queried_user_profile.put()
            current_stream.key.delete()
        time_sleep(NDB_UPDATE_SLEEP_TIME)
        self.redirect('/management')
        return
예제 #9
0
def wait_for_deactivation(dispatcher, seconds=6):
    for i in range(seconds * 10):
        if dispatcher.activated == False:
            break
        time_sleep(0.1)
    else:
        assert False, 'dispatcher never deactivated'
예제 #10
0
    def get_lon_lat(self, cache, dsURL):
        ### Get TIME, LAT, LON
        # first try from cache
        print 'Get lon, lat'
        lon, lat  = None, None
        if cache:
            gridFile = os.path.join(cache, self.cachePrefix+'_grid.npz')
            if os.path.exists(gridFile):
                try:
                    lon = np.load(gridFile)['lon']
                    lat = np.load(gridFile)['lat']
                except:
                    time_sleep(0.5)
                    lon = np.load(gridFile)['lon']
                    lat = np.load(gridFile)['lat']

        # if cache does not exist try to fetch from remote dataset
        if lon is None:
            ds = Dataset(dsURL)
            lat = ds.variables['lat'][:]
            lon = ds.variables['lon'][:]

        # cache grid specs
        if cache:
            np.savez_compressed(gridFile, lon=lon, lat=lat)

        return lon, lat
예제 #11
0
def play_proc(msg_dict):
    """ Player process

    """

    print("Playing: %s" % msg_dict['filename'])
    with AudioIO(**msg_dict) as file:
        DevIO = get_io(file)
        with DevIO(rate=file.rate,
                   channels=file.channels,
                   depth=file.depth,
                   bigendian=file.bigendian,
                   unsigned=file.unsigned) as device:
            file.loops = 2
            print(repr(device))
            print(repr(file))
            print(file)
            for buf in file:
                # print(len(buf))
                written = device.write(buf)
                # print(written, 'bytes written')
                if not msg_dict['playing'] or not buf and not written:
                    stdout.flush()
                    break
                while msg_dict.get('paused', False):
                    time_sleep(0.1)
                if file.length > 0:
                    perc_done = (file.position * 100) / file.length
                    perc_str = 'Position: %.2f%%' % perc_done
                    format_len = len(perc_str) + 2
                    print('\033[%dD\033[K%s' % (format_len, perc_str), end='')
                    stdout.flush()
            device.flush()
    print("\nDone.")
예제 #12
0
def waitInterfaceLink(interface, server):
    """ Waits for an interface to get ready. Some interfaces need some 
        time before they are able to send/receive packets after coming
        up.
    """
    logging.debugv("functions/linux.py->waitInterfaceLink(interface, server)",
                   [interface, server])
    from time import sleep as time_sleep

    cmd = ['ping', '-I', interface, '-c 1', server]
    timeout = 60
    done = 0

    while (timeout > 0 and not done):
        try:
            runWrapper(cmd)
            done = 1
        except:
            time_sleep(1)
            timeout -= 1

    if (timeout == 0):
        msg = "Interface %s did not get a link in 60 seconds" % (interface)
        logging.warning(msg)
    else:
        logging.debug("network device up after %d seconds" % (60 - timeout))
예제 #13
0
    def flush(self):
        """ Wait for playing to stop.

        """

        while bool(_espeak.espeak_IsPlaying()):
            time_sleep(0.02)
    def ntp_sync_func(self ):
        print("\n\n\n ntp server -> " + str(self.ntp_server))
        while( True ):
            actual_time_offset = ntp_time_sync(verbose=False  , ntp_server = self.ntp_server )
        
            if(self.to_log_syncer):
                self.logger_sync.debug(' __sync_func__ actual_time_offset -> {} '.format(actual_time_offset) )
            
            if ( -self.sync_lock_precision <= actual_time_offset <= self.sync_lock_precision ):
                self.ntp_sync_wait = self.slow_sync_wait
                self.time_offset = actual_time_offset
                
                if(self.to_log_syncer):
                    self.logger_sync.debug(' __sync_func__ LOCKED actual , framed -> {} - {}'.format(actual_time_offset,self.time_offset) )
            
            elif( self.sync_lock_upperbound <= abs(actual_time_offset) ):
                self.ntp_sync_wait = self.fast_sync_wait
                self.time_offset = actual_time_offset

                if(self.to_log_syncer):
                    self.logger_sync.debug(' __sync_func__ PASSED actual , framed -> {} - {}'.format(actual_time_offset,self.time_offset) )
            
            else :
                self.ntp_sync_wait = self.fast_sync_wait
                self.time_offset = actual_time_offset
            #change this sleep pattern
            time_sleep(self.ntp_sync_wait)
예제 #15
0
    def _block_root_process(self) -> None:
        while True:
            try:
                time_sleep(1)

            except KeyboardInterrupt:
                self.stop()
예제 #16
0
    def pull_save_data(self, times=2, delay=1):
        """ Perform pull and data some

        Parameters
        ----------
        times: int
            How many times loop will run

        delay: int
            Delay in seconds for performing requests
        """

        i = 0

        while i < times:

            # run task
            self.pull_data()
            self.save_data()

            # increment count
            i += 1

            # wait a while
            time_sleep(delay)
예제 #17
0
 def post(self):
     user = users.get_current_user()
     if user is None:
         self.redirect(users.create_login_url(self.request.uri))
         return        
     return_url = str(self.request.get('return_url','/'))
     stream_id = int(self.request.get('stream_id'))
     print ('UnsubscribeHandler: Return Url: '+ return_url)
     queried_stream = stream.get_by_id(stream_id)
     if queried_stream:
         for temp_user in queried_stream.subscribers:
             if user.user_id() == temp_user.user_id():
                 queried_stream.subscribers.remove(temp_user)
                 queried_stream.put()
                 break
         queried_user_profile = user_profile.query(user_profile.user_id == user.user_id()).get()
         if queried_user_profile:
             queried_user_profile.subscribed_streams.remove(queried_stream.name)
             if  (not queried_user_profile.own_streams) and (not queried_user_profile.subscribed_streams):
                 # no own_streams nor subscribed_streams
                 queried_user_profile.key.delete()
             else:
                 queried_user_profile.put()
     
     time_sleep(NDB_UPDATE_SLEEP_TIME)
     self.redirect(return_url)
예제 #18
0
    def _unix_sock():
        try:
            sock = config.AGENT.sql_socket

            if os_path.exists(sock):
                return sock

            else:
                if subprocess(command=f"systemctl status {config.AGENT.sql_service} | grep 'Active:'").find('Active: inactive') != -1:
                    if subprocess(command=f'systemctl start {config.AGENT.sql_service}').find('Not able to start') != -1:
                        return False

                    time_sleep(3)
                    if os_path.exists(sock):
                        return sock

                    else:
                        sock = False

                        with open(config.AGENT.sql_config, 'r') as _:
                            for line in _.readlines():
                                if line.find('socket') != -1:
                                    sock = line.split('=')[1].strip()
                                    break

            return sock

        except IndexError:
            return False
예제 #19
0
    def get(self, id, fig_key):
        user = users.get_current_user()
        if user is None:
        # go to login page
            print("View Stream Handler: Not logged in")
            self.redirect(users.create_login_page(self.request.uri))
            return



        current_stream = stream.get_by_id(int(id))
        if(not current_stream):
            self.redirect("/error/" + 'Wrong stream or page number')
            return

        flag = False
        if current_stream:
            #delete all the imgs, because they are huge
            for i in current_stream.figures:
                if str(i.blob_key) == fig_key:
                    blobstore.delete(i.blob_key)
                    current_stream.figures.remove(i)
                    flag = True
                    break

        if(not flag):
            self.redirect("/error/" + 'Designated fig does not exist')
            return
        current_stream.num_of_pics -= 1
        current_stream.put()
        time_sleep(NDB_UPDATE_SLEEP_TIME)

        return
예제 #20
0
def waitInterfaceLink(interface, server):
    """ Waits for an interface to get ready. Some interfaces need some 
        time before they are able to send/receive packets after coming
        up.
    """
    logging.debugv("functions/linux.py->waitInterfaceLink(interface, server)", [interface, server])
    from time import sleep as time_sleep
    
    cmd = ['ping',  '-I', interface, '-c 1', server]
    timeout = 60
    done = 0

    while (timeout > 0 and not done):
        try:
            runWrapper(cmd)
            done = 1
        except:
            time_sleep(1)
            timeout -= 1
  
    if (timeout == 0):
        msg = "Interface %s did not get a link in 60 seconds" % (interface)
        logging.warning(msg)
    else:
        logging.debug("network device up after %d seconds" % (60-timeout))
예제 #21
0
    def _throttle(self, url):
        host = urlparse(url).netloc.lower()
        if host.startswith('www.'):
            host = host[4:]

        now = time_monotonic()

        # load state
        if host not in self.buckets:
            tokens = self.maxTokens
            lastToken = now
        else:
            tokens, lastToken = self.buckets[host]

        # refill bucket
        if tokens < self.maxTokens:
            newTokens = (now - lastToken) * self.tokenRate
            tokens = min(self.maxTokens, tokens + newTokens)
        lastToken = now

        # wait for it to fill
        if tokens >= 1:
            tokens -= 1
        else:
            wait = (1 - tokens) / self.tokenRate
            wait = math.ceil(wait * 1000) / 1000
            time_sleep(wait)

            tokens = 0
            lastToken = time_monotonic()

        # store state
        self.buckets[host] = (tokens, lastToken)
예제 #22
0
파일: nicehash.py 프로젝트: jragbeer/Random
def add_most_recent_rig_device_stats_table():
    time_sleep(15)
    engine = sqlite3.connect(data_path + "nicehash_data_new.db")
    damn = build_basic_rig_stats_df()
    cur_time = datetime.datetime.now()
    damn.to_sql('most_recent_rig_device_stats', engine, if_exists='replace', index=False)
    logging.info(f"most_recent_rig_device_stats SQL table updated {cur_time}")
예제 #23
0
def game_loop(Game, GameIsRunning):
    www = threading.Thread(target=webSession,
                           args=(session, game_queue),
                           daemon=True)
    www.start()
    initalize_creatures()
    while GameIsRunning:
        Game.tick()
        while True:
            print("Getting queue")
            try:
                msg = game_queue.get_nowait()
            except queue.Empty:
                break
        print(msg)
        if msg["for"] == 'sys':
            print(msg["data"])
        if msg['for'] == 'combat':
            #start_combat_handler(msg['data'], Game.current_time)
            pass

        if msg['for'] == 'creatures':
            print("GETTING ALL CREATURES")
            creatures = get_all_creatures()
            game_queue.put({"for": "web_creatures", "data": creatures})
        #takeShortRest("1", Game)
        time_sleep(1.0)
예제 #24
0
def wait_for_death(da, seconds=6):
    for i in range(seconds * 10):
        _ = transaction.begin()
        if da.dead:
            break
        time_sleep(0.1)
    else:
        assert False, 'dispatcher agent never died'
예제 #25
0
 def register_neopixel(self, klass, **kwargs):
     if LED_OFF:
         return
     if self.neopixel:
         self.neopixel.stop()
         time_sleep(CYCLE_SLEEP)
     self.neopixel = klass(self.led_instrument, **kwargs)
     self.neopixel.start()
예제 #26
0
 def top(self):
     from time import sleep as time_sleep
     while True:
         os_system(config.command_clear)
         self.list_currently_working_processes(
             config.ps_command, config.column_with_pid_for_ps_command)
         self.check_processes()
         time_sleep(config.refresh_interwal_in_seconds)
예제 #27
0
파일: testing.py 프로젝트: upiq/zc.async
def wait_for_death(da, seconds=6):
    for i in range(seconds * 10):
        _ = transaction.begin()
        if da.dead:
            break
        time_sleep(0.1)
    else:
        assert False, 'dispatcher agent never died'
예제 #28
0
def step(sleep=True, external=True, simulate=False):
    """Do one step forward in the main loop. First all timers are checked for
	expiration and if necessary the accociated callback function is called.
	After that the timer list is searched for the next timer that will expire.
	This will define the maximum timeout for the following select statement
	evaluating the registered sockets. Returning from the select statement the
	callback functions from the sockets reported by the select system call are
	invoked. As a final task in a notifier step all registered external
	dispatcher functions are invoked."""

    global __in_step, __step_depth, __step_depth_max

    __in_step = True
    __step_depth += 1

    try:
        if __step_depth > __step_depth_max:
            log.exception('maximum recursion depth reached')
            return

        # get minInterval for max timeout
        timeout = None
        if not sleep:
            timeout = 0
        else:
            now = int(time() * 1000)
            for interval, timestamp, callback in __timers.values():
                if not timestamp:
                    # timer is blocked (recursion), ignore it
                    continue
                nextCall = timestamp - now
                if timeout == None or nextCall < timeout:
                    if nextCall > 0:
                        timeout = nextCall
                    else:
                        timeout = 0
                        break
            if timeout == None:
                if dispatch.dispatcher_count():
                    timeout = dispatch.MIN_TIMER
                else:
                    # No timers and no dispatchers, timeout could be infinity.
                    timeout = 30000
            if __min_timer and __min_timer < timeout: timeout = __min_timer

        # wait for event
        sockets_ready = None
        if __sockets[IO_READ] or __sockets[IO_WRITE] or __sockets[IO_EXCEPT]:
            try:
                sockets_ready = select(__sockets[IO_READ].keys(),
                                       __sockets[IO_WRITE].keys(),
                                       __sockets[IO_EXCEPT].keys(),
                                       timeout / 1000.0)
            except select_error, e:
                if e.args[0] != errno.EINTR:
                    raise e
        elif timeout:
            time_sleep(timeout / 1000.0)
예제 #29
0
def get_poll(dispatcher, count=None, seconds=6):
    if count is None:
        count = len(dispatcher.polls)
    for i in range(seconds * 10):
        if len(dispatcher.polls) > count:
            return dispatcher.polls.first()
        time_sleep(0.1)
    else:
        assert False, 'no poll!'
예제 #30
0
    def poll_sleep(self, poll_interval: int):
        """
        Sleep a given amount of seconds

        Seconds to sleep may be reduced for testing reasons
        """
        sleep_time = poll_interval / self.poll_scaling
        logger.debug('Sleeping %ds..' % sleep_time)
        time_sleep(sleep_time)
예제 #31
0
파일: nf_generic.py 프로젝트: clones/kaa
def step( sleep = True, external = True, simulate = False ):
	"""Do one step forward in the main loop. First all timers are checked for
	expiration and if necessary the accociated callback function is called.
	After that the timer list is searched for the next timer that will expire.
	This will define the maximum timeout for the following select statement
	evaluating the registered sockets. Returning from the select statement the
	callback functions from the sockets reported by the select system call are
	invoked. As a final task in a notifier step all registered external
	dispatcher functions are invoked."""

	global __in_step, __step_depth, __step_depth_max

	__in_step = True
	__step_depth += 1

	try:
		if __step_depth > __step_depth_max:
			log.exception( 'maximum recursion depth reached' )
			return

		# get minInterval for max timeout
		timeout = None
		if not sleep:
			timeout = 0
		else:
			now = int( time() * 1000 )
			for interval, timestamp, callback in __timers.values():
				if not timestamp:
					# timer is blocked (recursion), ignore it
					continue
				nextCall = timestamp - now
				if timeout == None or nextCall < timeout:
					if nextCall > 0:
						timeout = nextCall
					else:
						timeout = 0
						break
			if timeout == None:
				if dispatch.dispatcher_count():
					timeout = dispatch.MIN_TIMER
				else:
					# No timers and no dispatchers, timeout could be infinity.
					timeout = 30000
			if __min_timer and __min_timer < timeout: timeout = __min_timer


		# wait for event
		sockets_ready = None
		if __sockets[ IO_READ ] or __sockets[ IO_WRITE ] or __sockets[ IO_EXCEPT ]:
			try:
				sockets_ready = select( __sockets[ IO_READ ].keys(), __sockets[ IO_WRITE ].keys(),
				                        __sockets[ IO_EXCEPT ].keys(), timeout / 1000.0 )
			except select_error, e:
				if e[ 0 ] != errno.EINTR:
					raise e
		elif timeout:
			time_sleep(timeout / 1000.0)
예제 #32
0
 def calculateDistance(self, fromLat, fromLng, toLat, toLng):
     global REQ_DIS_CNT
     disRes, disStr = '相距', '未知'
     disResF, disStrF = '距离福师大', '未知'
     try:
         if self.mtype == 'QQ':
             response = requests_get(
                 f'{QQ_API_URL_DISTANCE}from={fromLng},{fromLat}&to={toLng},{toLat};{FJNU_Lng},{FJNU_Lat}&key={self.apiKey}'
             )
         elif self.mtype == 'AMAP':
             response = requests_get(
                 f'{AMAP_API_URL_DISTANCE}origins={fromLat},{fromLng}|{FJNU_Lat},{FJNU_Lng}&destination={toLat},{toLng}&type=0&key={self.apiKey}'
             )
         REQ_DIS_CNT += 1
         if response.status_code != 200:
             log.error(f'获取地址失败: status_code={response.status_code}',
                       exc_info=True)
         else:
             dist, distF = -1, -1
             res = json_loads(response.text)
             if self.mtype == 'QQ' and res['status'] != 0:
                 log.error(
                     f"腾讯地图API错误(距离计算): {res['message']}!from={fromLng},{fromLat}&to={toLng},{toLat};{FJNU_Lng},{FJNU_Lat}"
                 )
             elif self.mtype == 'QQ' and res['status'] == 0:
                 dist = res['result']['elements'][0]['distance']
                 distF = res['result']['elements'][1]['distance']
             elif self.mtype == 'AMAP' and int(res['status']) == 0:
                 log.error(
                     f"高德地图API错误(距离计算): {res['info']}!origins={fromLat},{fromLng}|{FJNU_Lat},{FJNU_Lng}&destination={toLat},{toLng}"
                 )
             elif self.mtype == 'AMAP' and int(res['status']) == 1:
                 # log.debug(res['results'])
                 dist = int(res['results'][0]['distance'])
                 distF = int(res['results'][1]['distance'])
             # 两日距离
             if dist > 1000:
                 disStr = f"<span style='color:blue'>{round(dist/1000, 2)}公里</span>"
             elif dist >= 0:
                 disStr = f'{dist}米'
             # 距离福师大
             if distF > 1000:
                 disStrF = f'{round(distF/1000, 2)}公里'
             elif 0 < distF < 1000:
                 disStrF = f'{distF}米'
             if 0 < distF < 10000:
                 disStrF = f"<span style='color:blue'>{disStrF}</span>"
         if REQ_DIS_CNT % eval(self.mtype + '_MAX_CNT_PER_SEC') == 0:
             time_sleep(1)
     except exceptions.ConnectTimeout:
         #FIXME: 无效
         self._signal.emit('提示: ConnectTimeout请求超时')
     except exceptions.Timeout:
         self._signal.emit('提示: Timeout请求超时')
     except Exception as e:
         log.error(f'计算距离出错:{e}', exc_info=True)
     return f'({disRes}{disStr}, {disResF}{disStrF})'
예제 #33
0
파일: testing.py 프로젝트: upiq/zc.async
def get_poll(dispatcher, count=None, seconds=6):
    if count is None:
        count = len(dispatcher.polls)
    for i in range(seconds * 10):
        if len(dispatcher.polls) > count:
            return dispatcher.polls.first()
        time_sleep(0.1)
    else:
        assert False, 'no poll!'
예제 #34
0
def start_badoo_liker(count):
    login('cookies_badoo_(keep_this_file_save_!_).txt', url=badoo_matches_url)
    for i in tqdm(iterable=range(int(count)), desc='swipes done',
                  unit='swipe'):  # tqdm for progress bar
        try:
            swipe_badoo_user()
            time_sleep(random_uniform(1.0, 2.0))
        except Exception as e:
            print(e)
예제 #35
0
    def autoMemorize(self, gui):
        # クリップボードのコピー内容を消去
        clipboard.EmptyClipboard()
        # 開いているウィンドウのハンドル一覧を取得
        windowHandles = self.getWindowHandles()

        # 最前面にあるウィンドウがブラウザならURLを取得
        firstElememt = findwindows.find_element(handle=windowHandles[0])
        # Mozilla FirefoxからURL取得
        if re_search('Mozilla Firefox', str(firstElememt)) is not None:
            keyboard.send('ctrl+l,shift,ctrl+c')
        elif re_search('Google Chrome', str(firstElememt)) is not None:
            keyboard.send('ctrl+l,shift,ctrl+c')
        else:
            # 対応ブラウザでない場合は取得中止
            return
        # 0.5秒までの間にクリップボードにコピーされたら途中で抜ける
        for t in range(5):
            if clipboard.GetClipboardFormats() != []:
                break
            time_sleep(0.1)  # コピーが間に合わなければ0.1秒待つ
        # クリップボードが空なら中止(フォーマットが取得されないことで判定)
        if clipboard.GetClipboardFormats() == []:
            return
        # クリップボードにコピーしたURLを取得
        copiedURL = clipboard.GetData()
        # print(copiedURL)
        # 何もコピーされていないなら中止
        if len(copiedURL) == 0:
            return
        URL_pattern = []
        # URL文字数を30から順に区切る
        if len(copiedURL) >= 15:
            if len(copiedURL) >= 20:
                if len(copiedURL) >= 25:
                    if len(copiedURL) >= 30:
                        URL_pattern.append(copiedURL[0:30])
                    URL_pattern.append(copiedURL[0:25])
                URL_pattern.append(copiedURL[0:20])
            URL_pattern.append(copiedURL[0:15])
        else:
            URL_pattern.append(copiedURL)

        # URL文字数を30,25,20,15の順に減らしながら,含まれるアカウントを探す
        # 該当アカウントが1つだけならユーザID/Mailとパスワードを取得
        for i in range(len(URL_pattern)):
            # print(URL_pattern[i])
            IDandPass = gui.cmdEvt.autoFindByURL(URL_pattern[i])
            if IDandPass != {}:
                serviceName = IDandPass['Service']
                IDorMail = IDandPass['ID']
                passWord = IDandPass['Pass']
                # ユーザID/Mailとパスワードの一時保存
                # つまり自動memorize
                gui.cmdEvt.setMemorize(serviceName, IDorMail, passWord)
                break
예제 #36
0
 def _read_real_instruments(self):
     out = {}
     for gate in self.instruments:
         try:
             response = self.instruments[gate].read_registers(GATE_ADDRESS, 1)[0]
         except builtins.OSError:
             response = None  # TODO: nevim jestli to nebudu muset osetrit jinak, v Dockeru se mi to tady seklo a vyhnilo; minimalne bych mel zurive logovat
         out[gate] = response
         time_sleep(INSTRUMENT_SLEEP)
     return out
예제 #37
0
def iterate_pins(shift_register, pin_list, pause_seconds=0.5):
    '''
		Iterate through the given pin
		numbers with the given interval
		(defaults toe every half second).
	'''
    for pin in pin_list:
        shift_register.from_pin_list([pin])
        time_sleep(pause_seconds)
    shift_register.clear()
 def _ptp_sync_func(self ):
     while( True ):
         actual_time_offset = ptp_time_sync()
     
         if(self.to_log_syncer):
             self.logger_sync.debug(' __sync_func__ actual_time_offset -> {} '.format(actual_time_offset) )
         
         self._time_offset   = actual_time_offset
         #change this sleep pattern
         time_sleep(self._ptp_sync_wait)
예제 #39
0
def main(board=4, total_page=2):
    base_url = 'http://maoyan.com/board/{}?offset={}'
    user_agent = UserAgent()
    ua = user_agent.random
    for cur_page in range(total_page):
        print("******************** 第{}页 ******************".format(cur_page +
                                                                    1))
        url = base_url.format(board, cur_page * 10)
        html = get_one_page(url, ua)
        parse_html(html)
        time_sleep(randint(1, 3))
예제 #40
0
def get_object_retry_errors(bucket: str, key: str, error_codes: list = ['NoSuchKey', 'AccessDenied'], retries=5, sleep=3):
    exception = None
    for i in range(retries):
        try:
            return boto_client('s3').get_object(Bucket=bucket, Key=key)
        except ClientError as e:
            exception = e
            if e.response["Error"]["Code"] in error_codes:
                logger.warning(e.response['Error']['Message'])
                time_sleep(sleep + i)
    raise exception
예제 #41
0
def flash_random(shift_register, iterations, pause_seconds):
    '''
		Iterate through the given number of random
		output configurations, pausing for the given
		number of seconds inbetween each, using
		the given shift register.
	'''
    for i in range(iterations):
        shift_register.from_list(
            [random_getrandbits(1) for a in range(len(shift_register))], )
        time_sleep(pause_seconds)
예제 #42
0
 def connect(self):
     """
     Connect to a broker
     """
     self.client.connect(self.broker_hostname, self.broker_port)
     logger.info("Connected to broker {}:{}".format(self.broker_hostname,
                                                    self.broker_port))
     self.subscribe_to_one_topic(self.echo_hello,
                                 self.__on_echo_hello_message)
     self.client.loop_start()
     time_sleep(4)
예제 #43
0
파일: testing.py 프로젝트: upiq/zc.async
def wait_for_result(job, seconds=6):
    for i in range(seconds * 10):
        t = transaction.begin()
        try:
            if job.status == zc.async.interfaces.COMPLETED:
                return job.result
        except ZODB.POSException.ReadConflictError:
            # storage does not have MVCC
            pass
        time_sleep(0.1)
    else:
        assert False, 'job never completed'
예제 #44
0
def wait_for_result(job, seconds=6):
    for i in range(seconds * 10):
        t = transaction.begin()
        try:
            if job.status == zc. async .interfaces.COMPLETED:
                return job.result
        except ZODB.POSException.ReadConflictError:
            # storage does not have MVCC
            pass
        time_sleep(0.1)
    else:
        assert False, 'job never completed'
예제 #45
0
파일: testing.py 프로젝트: upiq/zc.async
def wait_for_annotation(job, name):
    for i in range(60):
        t = transaction.begin()
        try:
            if name in job.annotations:
                return job.annotations[name]
        except ZODB.POSException.ReadConflictError:
            # storage does not have MVCC
            pass
        time_sleep(0.1)
    else:
        assert False, 'annotation never found'
예제 #46
0
def wait_for_annotation(job, name):
    for i in range(60):
        t = transaction.begin()
        try:
            if name in job.annotations:
                return job.annotations[name]
        except ZODB.POSException.ReadConflictError:
            # storage does not have MVCC
            pass
        time_sleep(0.1)
    else:
        assert False, 'annotation never found'
예제 #47
0
파일: main.py 프로젝트: Pixelsuft/bhop.py
def mainloop():
    if game_window:
        while True:
            if GetText(GetCurrentWindow()) == game_window:
                if KeyState(bunny_hop_key):
                    scroll_mouse(-scroll)
            else:
                time_sleep(wait_game_interval / 1000)
    else:
        while True:
            if KeyState(bunny_hop_key):
                scroll_mouse(-scroll)
예제 #48
0
def step( sleep = True, external = True ):
	"""Do one step forward in the main loop. First all timers are
	checked for expiration and if necessary the associated callback
	function is called. After that the timer list is searched for the
	next timer that will expire. This will define the maximum timeout
	for the following poll statement evaluating the registered
	sockets. Returning from the pool statement the callback functions
	from the sockets reported by the poll system call are invoked. As a
	final task in a notifier step all registered external dispatcher
	functions are invoked."""

	global __in_step, __step_depth, __step_depth_max, __min_timer, _options

	__in_step = True
	__step_depth += 1

	try:
		if __step_depth > __step_depth_max:
			log.exception( 'maximum recursion depth reached' )
			raise NotifierException( 'error: maximum recursion depth reached' )

		# get minInterval for max timeout
		timeout = None
		if not sleep:
			timeout = 0
		else:
			now = int( time() * 1000 )
			for interval, timestamp, callback in __timers.values():
				if not timestamp:
					# timer is blocked (recursion), ignore it
					continue
				nextCall = timestamp - now
				if timeout == None or nextCall < timeout:
					if nextCall > 0:
						timeout = nextCall
					else:
						timeout = 0
						break
			if __min_timer and ( __min_timer < timeout or timeout is None ):
				timeout = __min_timer

		# wait for event
		fds = []
		if __sockets[ IO_READ ] or __sockets[ IO_WRITE ] or __sockets[ IO_EXCEPT ]:
			try:
				fds = __poll.poll( timeout )
			except select.error, e:
				log.error( 'error: poll system call interrupted: %s' % str( e ) )
				if not _options[ 'catch_select_errors' ]:
					raise
		elif timeout:
			time_sleep( timeout / 1000.0 )
예제 #49
0
파일: CMDSnake.py 프로젝트: pyfn/CMDSnake
def gameloop(check):
	global input_thread
	while True:
		os_system(CLEAR_SCREEN)
		printScreen()
		if input_thread == None or not input_thread.isAlive():
			input_thread = Thread(target=getMove)
			input_thread.start()
		time_sleep(0.3)
		if check >= 8:
			createFood()
			check = 0
		nextSnakePos(_NEXT_MOVE,_PREV_MOVE)
		check += 1
예제 #50
0
파일: testing.py 프로젝트: upiq/zc.async
 def wait_for(self, *jobs, **kwargs):
     poll_interval = kwargs.get('poll_interval', 5)
     self.time_flies(poll_interval) # starts thread
     # now we wait for the thread
     for i in range(kwargs.get('attempts', 10)):
         while self.time_passes():
             pass
         transaction.begin()
         for j in jobs:
             if j.status != zc.async.interfaces.COMPLETED:
                 break
         else:
             break
         time_sleep(0.1)
예제 #51
0
    def post(self):

        node_id = self.request.get("node_ID")

        cNode = Node.get_by_id(int(node_id))
        response = {"status":"success",
                    "message": "Ref updated",}
        if not cNode:
            response["status"] = "error"
            response["message"] = "can not find node " + str(node_id)
        else:
            time_sleep(NDB_UPDATE_SLEEP_TIME)
            response["new_data"]=node_collapse(cNode)
        self.response.out.write(json.dumps(response))
        return
예제 #52
0
def waitInterfaceLink(interface):
    from time import sleep as time_sleep

    gw = getGw(interface)
    cmd= ['ping',  '-I', interface,  '-c 1', gw]
    timeout = 60
    done = 0

    while (timeout > 0 and not done):
        try:
            runWrapper(cmd)
            done = 1
        except excepts.RunException, msg:
            time_sleep(1)
            timeout -= 1
예제 #53
0
파일: util.py 프로젝트: BaseBot/triangula
 def sleep(self):
     """
     Sleep, if necessary, until the minimum interval has elapsed. If the last run time is not set this function will
     set it as a side effect, but will not sleep in this case. Calling sleep() repeatedly will therefore not sleep
     on the first invocation but will subsequently do so each time.
     """
     now = time()
     if self.last_time is None:
         self.last_time = now
         return
     elif now - self.last_time > self.interval:
         return
     else:
         remaining_interval = self.interval - (now - self.last_time)
         time_sleep(remaining_interval)
         self.last_time = now + remaining_interval
예제 #54
0
 def send_message(self, message):
     
     while True:
         try:
             sock = socket.socket(socket.AF_INET, # Internet
                                  socket.SOCK_DGRAM) # UDP
         except socket.error, err:
             time_sleep(1)
             logging.error("Error sending data: %s" %repr(err))
             pass
         else:
             for element in message:
                 json_dumped = json.dumps(message[element])
                 sock.sendto(json_dumped, 
                             (self.server, self.port))
             sock.close()
             return True
예제 #55
0
    def read_resp(self, channel,timeout=4):
        buffer = ''


        while not channel.recv_ready():
            time_sleep(timeout)
            #continue
            #print "WAIT"

        while channel.recv_ready():
            try:
                buffer += channel.recv(1024)
                #time.sleep(0.2)
            except socket_timeout:
                break

        # Read data
        '''
        try:
            # Set non-bloking socket mode
            channel.settimeout(0.0)


            while True:
                # Use select for checking data readiness
                r, w, e = select.select([channel], [], [], timeout)
                # Check channel data ready
                if channel in r:
                    try:
                        x = channel.recv(1024)
                        buffer += x

                        if len(x) == 0:
                            break
                    # Catch socket timeout for non-blocking
                    except socket.timeout:
                        break
                # Close channel by timeout
                else:
                    break
        finally:
            #print buffer
            pass
        '''
        return buffer
예제 #56
0
def safe_copy(infile, outfile, **kwargs):
    kwargs.setdefault('sleep', 10)
    kwargs.setdefault('attempts', 10)
    kwargs.setdefault('debug', False)
    kwargs.setdefault('checksum', False)
    kwargs.setdefault("checksum_blocksize", 4096)
    kwargs.setdefault('mkdir',False)
    sleep = parse_sleep(kwargs['sleep'])
    xrootd = False    
    if kwargs['mkdir']: mkdir(dirname(outfile))            
    if kwargs['debug']:
        print 'cp %s -> %s' % (infile, outfile)
    # Try not to step on any toes....
    infile = expandvars(infile)
    outfile = expandvars(outfile)
    cmnd = "cp %s %s" % (infile, outfile)
    if infile.startswith("root:"):
        if kwargs['debug']: print 'input file is on xrootd - switching to XRD library'
        xrootd = True
    if outfile.startswith("root:"):
        if kwargs['debug']: print 'output file is on xrootd - switching to XRD library'
        xrootd = True
    if xrootd:
        cmnd = "xrdcp -f %s %s" % (infile, outfile)
    md5in = md5out = None
    if kwargs['checksum'] and not xrootd:
        md5in = md5sum(infile, blocksize=kwargs['checksum_blocksize'])
    i = 1
    while i < kwargs['attempts']:
        if kwargs['debug'] and i > 0:
            print "Attempting to copy file..."
        status = sub.call(shlex_split(cmnd))
        if status == 0:
            if kwargs['checksum'] and not xrootd:
                md5out = md5sum(outfile, blocksize=kwargs['checksum_blocksize'])
            if md5in == md5out:
                return status
            else:
                print '%i - copy successful but checksum does not match, try again in 5s'
                time_sleep(5)
        else:
            print "%i - Copy failed; sleep %ss" % (i, sleep)
            time_sleep(sleep)
        i += 1
    raise IOError("Failed to copy file")
예제 #57
0
파일: testing.py 프로젝트: upiq/zc.async
 def time_flies(self, seconds):
     if not self.started:
         raise ValueError('not started')
     end = _now + datetime.timedelta(seconds=seconds)
     ct = 0
     next = self._get_next(end)
     then = None
     while next is not None:
         now, callable, args, kw = next
         if then is None or then != now:
             time_sleep(0.5) # give threads a chance to work
             set_now(now)
         callable(*args, **kw) # normally this would get try...except
         ct += 1
         next = self._get_next(end)
         then = now
     if ct:
         time_sleep(0.5)
     set_now(end)
     return ct
예제 #58
0
    def _read_fake_instruments(self):
        # read directory structure and look for files like ~/gates/1/1
        out = {}
        files = [i.decode('ascii').split('/')[-2:] \
                 for i in subprocess.check_output(['find', self.debug_path]).splitlines() \
                 if self.GATE_RE.match(i.decode('ascii'))]
        files = sorted(files, key=lambda a: a[0])

        # construct fake instrument structure
        for gate in self.instruments:
            out[gate] = 0
        for f in files:
            out[int(f[0])] = int(f[1])
            time_sleep(INSTRUMENT_SLEEP)

        # remove files in ~/gates
        for parts in files:
            path = os.path.join(self.debug_path, *parts)
            cmd = 'rm {path}'.format(path=path)
            subprocess.call(shlex.split(cmd))
        return out
예제 #59
0
    def _retension_thread_procedure(self):
        log('FileStorage: Retension thread started')
        previous_check_time = 0
        while True:
            try:
                now = time_time()
                if now - previous_check_time > 10 * 60:  # every 10 minutes
                    log('FileStorage: Check for outdated files')
                    previous_check_time = time_time()
                    self._check_retention()

                # Wait for 60 seconds with a possibility
                # to be interrupted through stop() call:
                with self._condition_stop:
                    if not self._stopping:
                        self._condition_stop.wait(60)
                    if self._stopping:
                        log('Retension thread found stop signal')
                        break
            except Exception:
                logging_error(traceback_format_exc())
                time_sleep(60)  # prevent from flooding
예제 #60
0
파일: speaker.py 프로젝트: zepto/clipspeak
    def _play_proc(self, msg_dict: dict, pipe: Pipe):
        """ Player process

        """

        # Open the file to play.
        with EspeakText(**msg_dict) as fileobj:

            # Put the file info in msg_dict.
            # msg_dict['info'] = str(fileobj)
            msg_dict['length'] = fileobj.length

            # Open an audio output device that can handle the data from
            # fileobj.
            # with AudioDevice(rate=22050, channels=1) as device:

            device = AudioDevice(rate=22050, channels=1)
            try:

                # Set the default number of loops to infinite.
                fileobj.loops = msg_dict.get('loops', -1)

                # Initialize variable.
                buf = b'\x00' * device.buffer_size
                written = 0

                # Loop until stopped or nothing read or written.
                while msg_dict['playing'] and (buf or written):
                    # Keep playing if not paused.
                    if not msg_dict.get('paused', False):
                        # Re-open the device if it was closed.
                        if device.closed:
                            device = AudioDevice(rate=22050, channels=1)

                        # Read the next buffer full of data.
                        buf = fileobj.readline()

                        # Write buf.
                        written = device.write(buf)
                    else:
                        # Close the device when paused and sleep to
                        # open the audio for another process and
                        # save cpu cycles.
                        if not device.closed:
                            device.close()

                        time_sleep(0.05)

                        # Write a buffer of null bytes so the audio
                        # system can keep its buffer full.
                        # device.write(b'\x00' * device.buffer_size)

                    # Get and process any commands from the parent process.
                    if pipe.poll():
                        # Get the data into temp.
                        command = pipe.recv()

                        if 'getposition' in command:
                            pipe.send(fileobj.position)
                        elif 'setposition' in command:
                            fileobj.position = command['setposition']
            except Exception as err:
                print(err)
            finally:
                if not device.closed:
                    device.close()

        # Set playing to False for the parent.
        msg_dict['playing'] = False