Пример #1
0
    def __init__(self, screen, pos, zero_pos, rad,
                 cursor_rad, success_time, min_time):
        # constants
        self.HIGHLIGHT_COLOR = 20,255,20
        self.HIGHLIGHT_COLOR_FAIL = 255,20,20
        self.CURRENT_COLOR_ACTIVE = 40,180,40
        self.CURRENT_COLOR = 40,180,40
        self.NEXT_COLOR = 40,80,40
        self.NEXT_NEXT_COLOR = 40,50,40
        self.BG_COLOR = 40,40,40
        self.DEFAULT_COLOR = self.CURRENT_COLOR
        self.DEFAULT_OUTLINE_COLOR = 20,20,20

        # display
        self.screen = screen
        self.color = self.DEFAULT_COLOR
        self.outline_color = self.DEFAULT_OUTLINE_COLOR

        # game logic
        self.pos = (zero_pos[0]+pos[0],
                    zero_pos[1]+pos[1])
        self.outline_rad = 2
        self.rad = rad
        self.cursor_rad = cursor_rad
        self.success_timer = Timer(success_time)
        self.target_timer = Timer(success_time)
        self.active_timer = Timer(min_time)
        self.highlight = False
        self.wait_prev_target = True
        self.success = True
        self.complete_success = False
Пример #2
0
    def get_pos_examples(self):
        counts = self._get_pos_counts()
        for i in range(len(counts)):
            self.trainers[i].alloc_pos(counts[i])

        _t = Timer()
        roidb = self.imdb.roidb
        num_images = len(roidb)
        for i in range(num_images):
            #im = cv2.imread(self.imdb.image_path_at(i))
            #if roidb[i]['flipped']:
            #    im = im[:, ::-1, :]
            #im = self.imdb.image_path_at(i)
            gt_inds = np.where(roidb[i]['gt_classes'] > 0)[0]
            gt_boxes = roidb[i]['boxes'][gt_inds]
            _t.tic()
            scores, boxes, feat = self.im_detect(self.net, i, gt_boxes, self.feature_scale, gt_inds, boReturnClassifierScore = False)
            _t.toc()
            #feat = self.net.blobs[self.layer].data
            for j in range(1, self.imdb.num_classes):
                cls_inds = np.where(roidb[i]['gt_classes'][gt_inds] == j)[0]
                if len(cls_inds) > 0:
                    cls_feat = feat[cls_inds, :]
                    self.trainers[j].append_pos(cls_feat)
            if i % 50 == 0:
                print('get_pos_examples: {:d}/{:d} {:.3f}s' \
                      .format(i + 1, len(roidb), _t.average_time))
Пример #3
0
def runScript(fn,argv=[]):
    """Play a formex script from file fn.

    fn is the name of a file holding a pyFormex script.
    A list of arguments can be passed. They will be available under the name
    argv. This variable can be changed by the script and the resulting argv
    is returned to the caller.
    """
    from timer import Timer
    t = Timer()
    msg = "Running script (%s)" % fn
    if pf.GUI:
        pf.GUI.scripthistory.add(fn)
        pf.board.write(msg,color='red')
    else:
        message(msg)
    pf.debug("  Executing with arguments: %s" % argv,pf.DEBUG.SCRIPT)
    pye = fn.endswith('.pye')
    if pf.GUI and getcfg('check_print'):
        pf.debug("Testing script for use of print function",pf.DEBUG.SCRIPT)
        scr = checkPrintSyntax(fn)
        #
        # TODO: if scr is a compiled object, we could just execute it
        #

    res = playScript(file(fn,'r'),fn,fn,argv,pye)
    pf.debug("  Arguments left after execution: %s" % argv,pf.DEBUG.SCRIPT)
    msg = "Finished script %s in %s seconds" % (fn,t.seconds())
    if pf.GUI:
        pf.board.write(msg,color='red')
    else:
        message(msg)
    return res
Пример #4
0
    def __init__(self, sim, manager):
        super(ScreenIO, self).__init__()

        # Keep track of the important parameters of the screen state
        # (We receive these through events from the gui)
        self.ctrlat  = 0.0
        self.ctrlon  = 0.0
        self.scrzoom = 1.0

        self.route_acid = None

        # Keep reference to parent simulation object for access to simulation data
        self.sim     = sim
        self.manager = manager

        # Timing bookkeeping counters
        self.prevtime = 0.0
        self.prevcount = 0

        # Output event timers
        self.slow_timer = Timer()
        self.slow_timer.timeout.connect(self.send_siminfo)
        self.slow_timer.timeout.connect(self.send_aman_data)
        self.slow_timer.timeout.connect(self.send_route_data)
        self.slow_timer.start(1000/self.siminfo_rate)

        self.fast_timer = Timer()
        self.fast_timer.timeout.connect(self.send_aircraft_data)
        self.fast_timer.start(1000/self.acupdate_rate)
def collectionQuery2():
    fake = Faker()
    totalRuns = config.executions
    connection = pymysql.connect(**config.dbConfig)
    cursor = connection.cursor()
    limit = 20
    timer = Timer()
    meanTime = 0
    percentConfig = totalRuns / 100
    tags = []
    config.getTags(tags)
    print("=================================== Collection Query 2 ===================================")
    print("SELECT text_id AS id, p_text AS text FROM wp_tags AS t LEFT JOIN post2tag ON t.id = tag_id LEFT JOIN tag_query2 ON post_id = text_id LEFT JOIN text ON text_id = text.id WHERE t.name = 'tagName' AND p_site = 'site' AND p_country = 1 AND p_rank < rank ORDER BY p_rank DESC LIMIT 20")
    for run in range(totalRuns):
        tagName = tags[randint(0, config.totalTags - 1)]
        postRank = randint(1, config.totalPosts)
        site = config.siteConfig[randint(0, 19)]
        country = config.countries[randint(0, 3)]
        query = "SELECT text_id AS id, p_text AS text FROM wp_tags AS t LEFT JOIN post2tag ON t.id = tag_id LEFT JOIN tag_query2 ON post_id = text_id LEFT JOIN text ON text_id = text.id WHERE t.name = '{}' AND p_site = '{}' AND p_{} = 1 AND p_rank < {} ORDER BY p_rank DESC LIMIT {}".format(tagName, site, country, postRank, limit)
        timer.restart()
        cursor.execute(query)
        meanTime += timer.get_seconds()
        percent = (run / totalRuns) * 100
        if (run % percentConfig) == 0:
            print("Completed: {:.0f} %                ".format(percent), end = '\r')
    print("Completed 100 %")
    print("Mean query execution time : {:.10f} seconds".format(meanTime / totalRuns))
    connection.close()
    print("")
    print("Example Query")
    print(query)
    print("")
    return meanTime / totalRuns
    
Пример #6
0
def acquisition(config):

    timer = Timer()
    getch = _Getch()
    last_char = ""
    last_char2 = ""
    nl_count = 0
    bs_count = 0
    char_count = 0
    quit = False

    while not quit:
        # on lit un caractère
        my_char = getch()
        char_count += 1
        # saut de ligne:
        if my_char == "\r":
            print
            nl_count += 1
            # reset le dernier caractère
            last_char = ""
            last_char2 = ""
            # autre caractère
        else:
            nl_count = 0
            # caractère BACKSPACE
            if my_char == "\x08" or my_char == "\x7f":
                # on compte le nb de backspace pour les stats
                bs_count += 1
                # écrire un backspace déplace simplement le curseur
                # il faut effacer avec un espace
                sys.stdout.write("\x08 \x08")
                # reset le dernier caractère
                last_char = ""
            else:
                sys.stdout.write(my_char)

                # si un précédent caractère était présent
                if last_char != "":
                    # récupérer le temps entre deux frappes
                    t = timer.time()

                    # ajout dans la configuration si l'intervalle semble correct
                    if t < 1:
                        config.add(last_char + my_char, t)

                    if last_char2 != "":
                        config.add(last_char2 + last_char + my_char, t)
                        # sauvegarde du dernier caractère
                last_char2 = last_char
                last_char = my_char

                # deux appuis simultanés sur ENTER quittent la boucle
        if nl_count == 2:
            quit = True

            # reset du chronomètre
        timer.start()

    return float(bs_count) / float(char_count) * 100
Пример #7
0
 def solve(self, presents_to_place):
     if self.make_timer:
         timer = Timer()
         num_total_presents = len(presents_to_place)
     gc_collect_count = 0
     presents_index = 0
     presents_last_index = len(presents_to_place)
     while 1:
         priority_pick = self.priority_pick
         new_layer = MaxRectSolver(self.width, self.height)
         try:
             presents_index = new_layer.solve(presents_to_place, presents_index, self.scorer, priority_pick)
             self._add_layer(new_layer)
             print("{} more presents".format(presents_last_index - presents_index))
             if presents_index == presents_last_index - 1:
                 break
         except NoFit:
             priority_pick -= 10
             assert priority_pick > 1
         if self.make_timer:
             ratio = presents_index / num_total_presents
             print("Time left: {}; End time: {}".format(timer.time_left(ratio), timer.time_end(ratio)))
     print("Solved with total depth {}".format(self.total_depth))
     if self.make_timer:
         print("Time taken: {}".format(timer.time_taken()))
     if self.gc_collect_cycle:
         gc_collect_count += 1
         if gc_collect_count == self.gc_collect_cycle:
             gc_collect_count = 0
             print("GC collect")
             gc.collect()
def collectionQuery3():
    totalRuns = config.executions
    connection = pymysql.connect(**config.dbConfig)
    cursor = connection.cursor()
    percentConfig = totalRuns / 100
    timer = Timer()
    meanTime = 0
    limit = 20
    print("=================================== Collection Query 3 ===================================")
    print(" SELECT text_id AS id, p_text AS text, p_published AS published FROM tag_query3 LEFT JOIN text ON text_id = text.id WHERE p_country = 1 p_type = 'postType' AND p_rank < `postRank` AND p_site = 'site' ORDER BY p_rank DESC LIMIT 20;")
    for run in range(totalRuns):
        postType = config.postTypes[randint(0, 9)]
        postRank = randint(1, config.totalPosts - 1)
        country = config.countries[randint(0, 3)]
        site = config.siteConfig[randint(0, 19)]
        query = "SELECT text_id AS id, p_text AS text, p_published AS published FROM tag_query3 LEFT JOIN text ON text_id = text.id WHERE p_{} = 1 AND p_type = '{}' AND p_rank < {} AND p_site = '{}' ORDER BY p_rank DESC LIMIT {}".format(country, postType, postRank, site, limit)
        timer.restart()
        cursor.execute(query)
        meanTime += timer.get_seconds()
        percent = (run / totalRuns) * 100
        if (run % percentConfig) == 0:
            print("Completed: {:.0f} %                ".format(percent), end = '\r')
    print("Completed 100 %")
    print("Mean query execution time : {:.10f} seconds".format(meanTime / totalRuns))
    connection.close()
    print("")
    print("Example Query")
    print(query)
    print("")
    return meanTime / totalRuns
Пример #9
0
def start():
    global DATASTORE, URL, KEY
    
    default_tmp = "/tmp/itzod"
    if sys.platform.startswith('win'):
        default_tmp = "C:\\temp\\itzod"
        
    parser = argparse.ArgumentParser()
    parser.add_argument("-H", "--host", help="Web server Host address to bind to", 
                        default="0.0.0.0", action="store", required=False)
    parser.add_argument("-p", "--port", help="Web server Port to bind to", 
                        default=8000, action="store", required=False)
    parser.add_argument("-k", "--key", help="Itzod User APIKey for accessing json urls",
                        action="store", required=True)
    parser.add_argument("-u", "--url", help="Base itzod URL for accessing api",
                        default="https://pool.itzod.ru/apiex.php",
                        action="store", required=False)
    parser.add_argument("-d", "--datadir", help="Data directory to store state",
                        default=default_tmp,
                        action="store", required=False)
    args = parser.parse_args()
    
    logging.basicConfig()
    DATASTORE = Datastore(args.datadir)
    URL = args.url
    KEY = args.key
    
    t = Timer(60, poll, ())
    t.start()
    
    run(host=args.host, port=args.port, reloader=True)
Пример #10
0
def kruskal_wallis(genotype, phenVals, useTieCorrection=True):
    t = Timer()
    num_accessions=len(genotype.accessions)
    num_snps = genotype.num_snps
    assert num_accessions== len(phenVals), "SNPs and phenotypes are not equal length."
    ranks, group_counts = _kw_get_ranks_(phenVals)
    assert len(group_counts) == len(set(ranks)), 'Somethings wrong..'
    tieCorrection = 1.0
    if useTieCorrection:
        n_total = len(ranks)
        ones_array = np.repeat(1.0, len(group_counts))
        s = np.sum(group_counts * (group_counts * group_counts - ones_array))
        s = s / (n_total * (n_total * n_total - 1.0))
        tieCorrection = 1.0 / (1 - s)

    n = len(phenVals)
    ds = np.zeros(num_snps)
    c = 12.0 / (n * (n + 1))
    snps = genotype.get_snps_iterator()
    for i, snp in enumerate(snps):
        ns = np.bincount(snp)
        rs = np.array([0.0, np.sum(snp * ranks)])
        rs[0] = np.sum(ranks) - rs[1]
        nominator = 0.0
        mean_r = (n + 1) / 2.0
        for j in range(2):
            v = (rs[j] / ns[j]) - mean_r
            nominator += ns[j] * v * v
        ds[i] = (c * nominator) * tieCorrection

    ps = sp.stats.chi2.sf(ds, 1)

    log.info('Took %s' % t.stop(True))
    return {"ps":ps, "ds":ds}
Пример #11
0
    def _get_feature_scale(self, num_images=100):
        _t = Timer()
        roidb = self.imdb.roidb
        total_norm = 0.0
        total_sum = 0.0
        count = 0.0
        num_images = min(num_images, self.imdb.num_images)
        inds = np.random.choice(range(self.imdb.num_images), size=num_images, replace=False)

        for i_, i in enumerate(inds):
            #im = cv2.imread(self.imdb.image_path_at(i))
            #if roidb[i]['flipped']:
            #    im = im[:, ::-1, :]
            #im = self.imdb.image_path_at(i)
            _t.tic()
            scores, boxes, feat = self.im_detect(self.net, i, roidb[i]['boxes'], boReturnClassifierScore = False)
            _t.toc()
            #feat = self.net.blobs[self.layer].data
            total_norm += np.sqrt((feat ** 2).sum(axis=1)).sum()
            total_sum += 1.0 * sum(sum(feat)) / len(feat)
            count += feat.shape[0]
            print('{}/{}: avg feature norm: {:.3f}, average value: {:.3f}'.format(i_ + 1, num_images,
                                                           total_norm / count, total_sum / count))

        return self.svm_targetNorm * 1.0 / (total_norm / count)
Пример #12
0
class TimerTest(unittest.TestCase):

    def setUp(self):
        self.timer=Timer(1)

    def test_parse_timer(self):
        timer = Timer('''interval: 10
                         event: test_timer_event''')

        self.assertEqual(timer.period, 10)
        self.assertEqual(timer.event, 'test_timer_event')

    def test_timer_poll(self):
        reset_time = self.timer.reset()
        while time() < reset_time + 1 - 0.05:
            self.assertEqual(self.timer.poll(), None)
        count = 0
        while time() < reset_time + 1 + 0.05:
            poll = self.timer.poll()
            if not poll == None:
                if round(poll) == 0:
                    count = count + 1
            sleep(0.01)
        self.assertEqual(count,1)

    def test_timer_poll_count(self):
        reset_time = self.timer.reset()
        count = 0
        while(time() < reset_time + 3.1):
            if self.timer.poll() != None:
                count = count + 1
            sleep(0.05)
        self.assertEqual(count,3)
    def request_file(self, file_requested = None):

            file_size = self.proxy.getFileSize(file_requested)
            print ('File size: ' + str(file_size) + ' Bytes')
            
            file_download = open(file_requested, 'w')
            
            timer = Timer()
            
            # 1.5 MB = 137 sec (1 KB)
            # 1.5 MB = 16 sec (10 KB)
            # 1.5 MB = 4 sec (50 KB)
            # 1.5 MB = 2.84 sec (100 KB)
            # 1.5 MB = 2.67 sec (150 KB)
            # 1.5 MB = 2.26 sec (500 KB)
            # 700 MB = 961 sec (16 min) (150 kb) 747 KB/s
            
            for size in range(0, file_size, self.DEFAULT_CHUNK_FILE_SIZE): # Loop each chunk size KB
                #print 'Requesting size: ' + str(size)
                async_result = self.proxy.begin_getFileChunk(file_requested, size, self.DEFAULT_CHUNK_FILE_SIZE) # Chunks
                #print 'Async call processed (' + str(size) + ')'
        
                try:
                    data = self.proxy.end_getFileChunk(async_result) # Ice::MemoryLimitException or timeout
                except Ice.CommunicatorDestroyedException as e: #@UndefinedVariable ::Ice::CommunicatorDestroyedException
                    sys.stderr.write('Error: The connection to comunicator was destroyed.\nClient abort.\n')
                    return -1
                
                except Exception as e:
                    sys.stderr.write('Error: unknown exception in request_file %s\nClient abort.\n' % str(e))
                    #print 'Message:' + e.message
                    #print 'Error:' + str(e.unknown)
                    #print 'ice_name:' + str(e.ice_name())
                    #print 'String:' + e.__str__()
                    
                    return -1
        
                speed = size / timer.duration_in_seconds()
                
                if size / 1024.0 < 1024:
                    size = str(round(size / 1024.0, 2)) + ' KB'
                elif size / (1024.0 * 1024.0) < 1024:
                    size = str(round(size / (1024.0 * 1024.0), 2)) + ' MB'
                elif size / float(1024.0 * 1024.0 * 1024.0) < 1024:
                    size = str(round(size / (1024.0 * 1024.0 * 1024.0), 2)) + ' GB'  
                
                file_download.write(data)
                
                if speed / 1024.0 < 1024:
                    speed = str(round(speed / 1024.0, 2)) + ' KB/s'
                elif speed / (1024.0 * 1024.0) < 1024:
                    speed = str(round(speed / (1024.0 * 1024.0), 2)) + ' MB/s'
                elif speed / (1024.0 * 1024.0 * 1024.0) < 1024:
                    speed = str(round(speed / (1024.0 * 1024.0 * 1024.0), 2)) + ' GB/s'   
                    
                print ('Received (' + str(size) + ') ' + 'Speed: ' + str(speed))  
                
            file_download.close()
            
            print ('Data saved in ' + str(timer.duration_in_seconds()) + ' seconds')
Пример #14
0
class PhysicsManager:
	def __init__(self):
		self.timer = Timer(PHYSICS_TIMER_INTERVAL, "physics_timer")
		self.started = False
		self.tasks = []

	def __del__(self):
		self.timer.stop()

	def update(self):
		if len(self.tasks) == 0:
			self.started = False
			self.timer.stop()
			return

		for task in self.tasks:
			vy = task.velocity[1]
			for i in [0, 1, -1]:
				v0 = task.velocity[i]
				task.velocity[i] += task.accel[i] * PHYSICS_TIMER_INTERVAL
				task.position[i] += (v0 + task.velocity[i]) / 2.0 * PHYSICS_TIMER_INTERVAL
			task.falling_time += PHYSICS_TIMER_INTERVAL
			task.falling_height += abs(task.velocity[1] + vy) / 2.0 * PHYSICS_TIMER_INTERVAL
			task.obj.update_position(task.position)

		self.timer.add_task(PHYSICS_TICK, self.update)

	# do physics to an object which has:
	#   * method update_position(position) to update its position
	def do_physics(self, position, accel, obj):
		self.tasks.append(PhysicsTask(position, accel, obj))
		if not self.started:
			self.started = True
			self.timer.add_task(PHYSICS_TICK, self.update)
			self.timer.start()
def getPostById():
    totalRuns = config.executions
    connection = pymysql.connect(**config.dbConfig)
    cursor = connection.cursor()
    timer = Timer()
    meanTime = 0
    percentConfig = totalRuns / 100
    print("==================================== Post By Id Query ====================================")
    print("SELECT obj FROM wp_posts WHERE id = post_id;")
    for run in range(totalRuns):
        postId = randint(1, config.totalPosts)
        query = "SELECT {} FROM wp_posts WHERE id = {}".format('text', postId)
        timer.restart()
        cursor.execute(query)
        meanTime += timer.get_seconds()
        percent = (run / totalRuns) * 100
        if (run % percentConfig) == 0:
            print("Completed: {:.0f} %                ".format(percent), end = '\r')
    print("Completed 100 %")
    print("Mean query execution time : {:.10f} seconds".format(meanTime / totalRuns))
    connection.close()
    print("")
    print("Example Query")
    print(query)
    print("")
    return meanTime / totalRuns
Пример #16
0
    def save(self,file):
        """
            Arguments:
                
                file: where to save (utf-8 encoding)

            Examples:
                
                ngrams.save("myfile")
        """

        file = self.__test_file(file,'w')
        n_word = len(self)

        buffer = ""

        sys.stderr.write("Saving the %i-grams...\n" % self.__max_arity)

        t = Timer(n_word,out=sys.stderr)
        t.start()
        for i in range(self.__max_arity):
            for word in self.__get_sorted_grams(i,(0,i+1)):
                buffer += "#".join(word)+"%"+str(self.__ngrams[i][word])+"\n"

                if len(buffer) > 1000:
                    file.write(buffer)
                    buffer = ""

                t.print_update(1)

        file.write(buffer)
        file.close()
Пример #17
0
class Fuzzie(TextEntity):
	def __init__(self, layer, vel_x, vel_y):
		TextEntity.__init__(self, None, layer, char = '*')
		#self.setPos(self.pos_x, s.pos_y)
		self.vel_x = vel_x
		self.vel_y = vel_y
		self.visible = True
		self.liveTimer = Timer()
		self.liveTimer.start()
		self.name = 'Fuzzie'
	
	def death(self, attacker=None, deathtype=None):
		self.health = -1

	def think(self, frameDT):
		if len(self.touching): self.collideHandler()
		if not self.health: self.death()

	def collideHandler(self):
		for partner in self.touching:
			if partner[0]:
				if partner[0].getChar() == '+':
					#print "Hit by bullet!"
					self.health = 0
		self.touching = []
Пример #18
0
    def stopall(self, timeout=10):
        """
        Stops all known child processes by calling 
        """
        all = InProgressAll(*[process.stop() for process in self.processes.keys()])
        # Normally we yield InProgressAll objects and they get implicitly connected
        # by the coroutine code.  We're not doing that here, so we connect a dummy
        # handler so the underlying IPs (the processes) get connected to the IPAll.
        all.connect(lambda *args: None)

        # XXX: I've observed SIGCHLD either not be signaled or be missed
        # with stopall() (but not so far any other time).  So this kludge
        # tries to reap all processes every 0.1s while we're killing child
        # processes.
        poll_timer = Timer(lambda: [process._check_dead() for process in self.processes.keys()])
        poll_timer.start(0.1)
        while not all.finished:
            main.step()
        poll_timer.stop()

        # Handle and log any unhandled exceptions from stop() (i.e. child
        # failed to die)
        for process in self.processes:
            try:
                inprogress(process).result
            except SystemError, e:
                log.error(e.message)
Пример #19
0
def load_program():  # Main Program
    # First Logger
    log_specifics_debug('START', 'Starting the Prime Finder.')

    # initial variable input
    try:

        # User input
        userString = raw_input("Please input an integer: ")
        userNumber = int(userString)
        log_specifics_debug('USER INPUT', 'Input was successful.')

        # Initiaties Timer class object
        t = Timer()
        start_time = t.start()

        # Prime Finder
        prime_finder(userNumber, start_time)
        log_specifics_debug('PRIME FINDER', 'prime_finder module completed.')

        # Reload prime finder
        response = raw_input("Do you want to restart the prime finder? (yes or no): ")
        if response == "yes":
            log_specifics_debug('RELOADING', 'Prime Finder is reloading.')
            new_program()
        elif response == "no":
            clear_screen()
            log_specifics_debug('CLOSING', 'Prime Finder is closing.')
            sys.exit()

    except ValueError as err:
        log_specifics_debug('USER INPUT', userString)
        log_specifics_critical('USER INPUT', 'User entered a non-integer literal.')
        # Restarts Prime Finder application
        response = raw_input("Do you want to restart the prime finder? (yes or no): ")
        if response == "yes":
            log_specifics_debug('RELOADING', 'Prime Finder is reloading.')
            new_program()
        elif response == "no":
            clear_screen()
            log_specifics_debug('CLOSING', 'Prime Finder is closing.')
            sys.exit()

    except KeyboardInterrupt as err:
        log_specifics_debug('Closing', 'User has maually closed program.')
        sys.exit()

    except RuntimeError as err:
        log_specifics_debug('RUNTIME ERROR', err)
        # Restarts Prime Finder application
        response = raw_input("Do you want to restart the prime finder? (yes or no): ")
        if response == "yes":
            log_specifics_debug('RELOADING', 'Prime Finder is reloading.')
            new_program()
        elif response == "no":
            log_specifics_debug('CLOSING', 'Prime Finder is closing.')
            clear_screen()
            sys.exit()
Пример #20
0
class KeywordClient():

    def __init__(self,server_url=""):
        self.server_url = server_url
        self.request_header = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        self.timer_started = False
        self.timer = Timer()

    def checkTimer(self):
        if not self.timer_started:
            self.timer.start()
            self.timer_started = True

    def resetTimer(self):
        self.timer_started = False
        self.timer.start()

    def getSettings(self):
        r = requests.get(self.server_url+'getSettings')
        return r.json()

    def sendCategories(self, categories):
        data = {'handle':'setCategories', 'categories':categories}
        red.publish('ambient', json.dumps(data))
        
    def addRelevantEntry(self, type, title, text, url, score, insert_before):
        self.checkTimer()
        data = {'handle':'addRelevantEntry','type':type,'entry_id': idFromTitle(title),'title':title,'text':text,'url':url,'score':score, 'insert_before': insert_before, 'time': float(self.timer.current_secs())}
        print data
        red.publish('ambient', json.dumps(data))

    def delRelevantEntry(self, type, title):
        self.checkTimer()
        data = {'handle':'delRelevantEntry','type':type,'title': title, 'entry_id': idFromTitle(title), 'time': float(self.timer.current_secs())}
        red.publish('ambient', json.dumps(data))

    def addUtterance(self, utterance, speaker):
        self.checkTimer()
        data = {'handle':'addUtterance','utterance':utterance,'speaker':speaker, 'time': float(self.timer.current_secs())}
        red.publish('ambient', json.dumps(data))

    def replaceLastUtterance(self, old_utterance, new_utterance, speaker):
        self.checkTimer()
        data = {'handle':'replaceLastUtterance','old_utterance':old_utterance,'utterance':new_utterance,'speaker':speaker, 'time': float(self.timer.current_secs())}
        red.publish('ambient', json.dumps(data))

    def completeUtterance(self, utterance, speaker):
        self.checkTimer()
        data = {'handle':'completeUtterance','utterance':utterance,'speaker':speaker , 'time': float(self.timer.current_secs())}
        print data
        red.publish('ambient_transcript_only', json.dumps(data))

    def reset(self):
        data = {'handle':'reset'}
        red.publish('ambient_transcript_only', json.dumps(data))
        self.resetTimer()
        r = requests.post(self.server_url+'reset', data=json.dumps(data), headers=self.request_header)
        return r.status_code
Пример #21
0
 def hide_hint(self):
     root = Root.instance
     self._curPosY = ValueAnimate(
             self.pos[1], root.size[1])
     if self._timer: 
         self._timer.finish()
     self._timer = Timer(0.1, self._animate)
     Timer.add(self._timer)
     self.state = self.HIDING
Пример #22
0
class PopupHinter(Label):
    SHOW_TIME = 6.
    SHOWWING = 1
    SHOWN = 2
    HIDING = 3
    HIDED = 0
    AllArgs = update_join(Label.AllArgs, 
            bgcolor="(0xf5, 0xf1, 0x28, 0xff)",
            )

    def init(self):
        self._curPosY = None
        self._timer = None
        self.state = self.HIDED
        self.hide()

    def _animate(self, dt):
        self.pos = self.pos[0], self._curPosY.get()
        if self._curPosY.is_end():
            if self.state == self.HIDING:
                self.state == self.HIDED
                if self._timer:
                    self._timer.finish()
                    self._timer = None
                self.hide()
            elif self.state == self.SHOWWING:
                self.state = self.SHOWN
                tm = Timer(self.SHOW_TIME, self.hide_hint, 1)
                Timer.add(tm)
                if self._timer: self._timer.finish()
                self._timer = tm
            return
        self.mark_redraw()

    def hide_hint(self):
        root = Root.instance
        self._curPosY = ValueAnimate(
                self.pos[1], root.size[1])
        if self._timer: 
            self._timer.finish()
        self._timer = Timer(0.1, self._animate)
        Timer.add(self._timer)
        self.state = self.HIDING

    def show_hint(self, hint):
        root = Root.instance
        self.text = hint
        tsize = self.Font.size(hint)
        self.resize((tsize[0]+6, tsize[1]+4))
        self._curPosY = ValueAnimate(
                self.pos[1], root.size[1] - self.size[1])
        if self._timer: 
            self._timer.finish()
        self._timer = Timer(1./FPS, self._animate)
        Timer.add(self._timer)
        self.show()
        self.state = self.SHOWWING
Пример #23
0
def run(path, debug, max_cycles):
    with open(path, "rb") as rom_file:
        debug_title = debug == "TITLE"
        debug_header = debug == "HEADER" or debug == "ALL"
        debug_mem = debug == "MEMORY" or debug == "ALL"
        debug_instructions = debug == "INSTRUCTIONS" or debug == "ALL"
        debug_registers = debug == "REGISTERS" or debug == "ALL"
        rom = [i for i in rom_file.read()]
        
        header = Header(rom, debug_header)
        mem = Memory(rom, header)
        if debug_title:
            print("Title: " + header.name)
        if debug_instructions:
            print("PC:    Operation")
        
        interrupts = Interrupts()
        cpu = CPU(mem, interrupts, debug_instructions, debug_registers)
        timer = Timer(interrupts)
        sound = Sound()
        link = Link()
        joypad = Joypad()
        lcdc = LCDC(mem, interrupts)
        mem.setupIO(lcdc, interrupts, timer, sound, link, joypad)
        total_cycles = 0

        try:
            pygame.init()
            while cpu.run_state != "QUIT":
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        cpu.run_state = "QUIT"
                    if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                        joypad.keyEvent(event)

                interrupts.update()
                if cpu.run_state == "RUN":
                    cpu.run()
                else:
                    cpu.cycles += 1

                timer.update(cpu.cycles)
                lcdc.update(cpu.cycles)

                total_cycles += cpu.popCycles()
                if max_cycles >= 0 and total_cycles > max_cycles:
                    cpu.run_state = "QUIT"
        except AssertionError as e:
            if debug_mem:
                mem.display()
            traceback.print_tb(e.__traceback__)
        except KeyboardInterrupt as e:
            if debug_mem:
                mem.display()
        else:
            if debug_mem:
                mem.display()
class TrayTime(gobject.GObject):
    __gsignals__ = {
        "send-time" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
                      (gobject.TYPE_PYOBJECT, gobject.TYPE_INT)),
        "hour-changed" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
                      (gobject.TYPE_PYOBJECT, gobject.TYPE_INT)),
        }        
    def __init__(self):
        gobject.GObject.__init__(self)
        self.__timer = Timer(5000)
        self.__tray_time_hour_type = TRAY_TIME_12_HOUR
        self.__timer.connect("Tick", self.__update_time)
        # setting 12/24 hour.    
        if deepin_gsettings_bool:
            self.set_date = deepin_gsettings.new("com.deepin.dde.datetime")
            self.set_date.connect("changed", self.set_date_changed)
            self.set_deepin_dde_datetime()
        # start time.
        self.__timer.Enabled  = True 

    def set_date_changed(self, key):
        self.set_deepin_dde_datetime() 

    def set_hour_type(self, hour_type):
        self.__tray_time_hour_type = hour_type
        self.emit("hour-changed", self.get_time(), self.__tray_time_hour_type)

    def set_deepin_dde_datetime(self):
        if self.set_date.get_boolean("is-24hour"):
            self.set_hour_type(TRAY_TIME_24_HOUR)
        else:
            self.set_hour_type(TRAY_TIME_12_HOUR)

    def get_time(self):
        time_struct = time.localtime(time.time())
        #
        if self.__tray_time_hour_type == TRAY_TIME_12_HOUR: 
            time_show_text = time.strftime("%P %I %M", time.localtime()).split(" ")
            if time_show_text[0].startswith(("a", "p")):
                am = _("AM")
                pm = _("PM")
                if time_show_text[0].startswith("a"):
                    time_show_text[0] = am
                elif time_show_text[0].startswith("p"):
                    time_show_text[0] = pm
        elif self.__tray_time_hour_type == TRAY_TIME_24_HOUR:
            time_show_text = time.strftime("%H %M", time.localtime()).split(" ")
        #
        return time_show_text

    def __update_time(self, timer):
        # modify interval.
        if self.__timer.Interval == 1:
            self.__timer.Interval = 1000
        # emit event.
        self.emit("send-time", self.get_time(), self.__tray_time_hour_type)
Пример #25
0
 def input(self, e):
     if e.key == K_RETURN:
         self.on_mouse_down()
         if self.is_under_mouse(mouse.pos):
             Timer.add(Timer(0.2, self.on_mouse_up, 1))
         else:
             Timer.add(Timer(0.2, self.on_mouse_out, 1))
         self.command(e)
     else:
         return True
Пример #26
0
def linear_model(snps, phenotypes, cofactors=None):
    lm = LinearModel(phenotypes)
    if cofactors:
        for cofactor in cofactors:
            lm.add_factor(cofactor)
    log.info("Running a standard linear model")
    t = Timer()
    res = lm.fast_f_test(snps)
    log.info('Took: %s' % t.stop(True))
    return res
Пример #27
0
def read_all_words():
    """Return an unsorted list of all words to process."""

    words = []

    timer = Timer()
    text = open("/usr/share/dict/words").read()
    timer.print_elapsed("Reading words file")

    timer = Timer()
    lines = text.split("\n")
    timer.print_elapsed("Splitting words file")

    timer = Timer()
    for word in lines:
        # Get rid of \n
        word = word.strip()

        # Skip capitalized words. Here we should also skip words with hyphens
        # and other symbols, but our dictionary doesn't have any anyway.
        if word and word[0].islower():
            # We work entirely in upper case.
            word = word.upper()

            # Skip short words.
            if len(word) >= 3:
                words.append(word)
    timer.print_elapsed("Processing %d words" % len(lines))

    return words
Пример #28
0
def anova(snps, phenotypes):
    """
    Run EMMAX
    """
    lmm = LinearModel(phenotypes)

    log.info("Running ANOVA")
    t = Timer()
    res = lmm.anova_f_test(snps)
    log.info('Took: %s' % t.stop(True))
    return res
Пример #29
0
def start_timer(bot):
    """Set up schedule service for bot"""
    
    tm = Timer(bot) # Set up timer, with empty joblist

    # Repeatedly send PONG to keep
    tm.add_repeat(bot.sets['bot_ping_interval'], bot.send_ping, [])
    
    tm.log.info('Starting Timer..')
    tm.start()
    return tm
Пример #30
0
 def add_location(self, pos = None):
     if pos is None:
         pos = helpers.parse_coords(self.location_str.get())
     pos = tuple(pos)
     styles = ["b", "g", "r", "c", "m", "y", "k"]
     threshold = 1e-4
     if len(pos) == 2:
         pos = pos[0], pos[1], 0.0
     if PROJECTIONS[self.opts.projection.get()] != '3d':
         pos = pos[0], pos[1], 0.0
         self.location_str.set("%0.4g, %0.4g" % (pos[0], pos[1]))
     else:
         self.location_str.set("%0.4g, %0.4g, %0.4g" % pos)
     #Search for a fixed point
     ## fp = self.system.find_fp(pos, threshold = 1e-4)
     ## if fp is not None:
     ##     fp_clean = tuple(np.round(fp, 3))
     ##     if not fp_clean in self.fixed_points:
     ##         self.fixed_points.add(fp_clean)
     ##         self.fig.draw_fp(fp_clean)
     ##         self.update_fig()
     ##         vel = self.system(fp_clean)
     ##         logging.info("Found a fixed point: %s %s\n" % (str(fp_clean), str(vel)))
     if pos in self.trajectories:
         logging.warning("Trajectory already exists.")
         self.status.info("Trajectory already exists.")
         return
     self.status.info("Computing trajectory...")
     try:
         t = Timer()
         t.start()
         traj = self.system.trajectory(pos, self.opts.tmax.get(), threshold = threshold,
             bidirectional = self.opts.reverse.get(), nsteps = 5 * (self.opts.tmax.get()/self.opts.dt.get()),
             max_step = self.opts.dt.get(), use_ode = True)
         t.stop()
         logging.debug("Computing trajectory (%d points) took %g seconds" % (len(traj.x), t.seconds()))
     except:
         pos_str = ", ".join(map(str, pos))
         logging.warning("Could not compute trajectory from: %s" % pos_str)
         logging.debug(traceback.format_exc())
         return
     #if traj.dist[-1] < 10*threshold:
     #    return
     self.trajectories[pos] = traj
     if traj.t[-1] > self.anim_tmax:
         self.anim_tmax = traj.t[-1]
     style = (len(self.trajectories) - 1) % len(styles)
     traj.style = styles[style]
     self.status.info("Drawing trajectory...")
     self.fig.add_trajectory(traj)
     self.status.clear()
     #self.fig.draw_trajectory(traj)
     self.fig.draw()
     self.last_loc = pos
Пример #31
0
    def __init__(self,
                 name=None,
                 mat=Material(),
                 vol=0.0 * units.meter**3,
                 T0=0.0 * units.kelvin,
                 alpha_temp=0 * units.delta_k / units.kelvin,
                 timer=Timer(),
                 heatgen=False,
                 power_tot=0 * units.watt,
                 sph=False,
                 ri=0 * units.meter,
                 ro=0 * units.meter):
        """Initalizes a thermal hydraulic component.
        A thermal-hydraulic component will be treated as one "lump" in the
        lumped capacitance model.

        :param name: The name of the component (i.e., "fuel" or "cool")
        :type name: str.
        :param mat: The material of this component
        :type mat: Material object
        :param vol: The volume of the component
        :type vol: float meter**3
        :param T0: The initial temperature of the component
        :type T0: float.
        :param alpha_temp: temperature coefficient of reactivity
        :type alpha_temp: float
        :param timer: The timer instance for the sim
        :type timer: Timer object
        :param heatgen: is this component a heat generator (fuel)
        :type heatgen: bool
        :param power_tot: power generated in this component
        :type power_tot: float
        :param sph: is this component a spherical component, spherical
        equations for heatgen, conduction are different,
        post-processing is different too
        :type sph: bool
        :param ri: inner radius of the sph/annular component, ri=0 for sphere
        :type ri: float
        :param ro: outer radius of the sph/annular component,
        ro=radius for sphere
        :type ro: float
        """
        self.name = name
        self.vol = vol.to('meter**3')
        self.mat = mat
        self.k = mat.k
        self.cp = mat.cp
        self.dm = mat.dm
        self.timer = timer
        self.T = units.Quantity(
            np.zeros(shape=(timer.timesteps(), ), dtype=float), 'kelvin')
        self.T[0] = T0
        self.T0 = T0
        self.alpha_temp = alpha_temp.to('delta_k/kelvin')
        self.heatgen = heatgen
        self.power_tot = power_tot
        self.cond = {}
        self.conv = {}
        self.adv = {}
        self.mass = {}
        self.cust = {}
        self.prev_t_idx = 0
        self.convBC = {}
        self.sph = sph
        self.ri = ri.to('meter')
        self.ro = ro.to('meter')
Пример #32
0
def search_frame_for_triangulation(kf1, kf2, idxs1=None, idxs2=None, 
                                   max_descriptor_distance=0.5*Parameters.kMaxDescriptorDistance):   
    idxs2_out = []
    idxs1_out = []
    num_found_matches = 0
    img2_epi = None     

    if __debug__:
        timer = Timer()
        timer.start()

    O1w = kf1.Ow
    O2w = kf2.Ow
    # compute epipoles
    e1,_ = kf1.project_point(O2w)  # in first frame 
    e2,_ = kf2.project_point(O1w)  # in second frame  
    #print('e1: ', e1)
    #print('e2: ', e2)    
    
    baseline = np.linalg.norm(O1w-O2w) 

    # if the translation is too small we cannot triangulate 
    # if baseline < Parameters.kMinTraslation:  # we assume the Inializer has been used for building the first map 
    #     Printer.red("search for triangulation: impossible with almost zero translation!")
    #     return idxs1_out, idxs2_out, num_found_matches, img2_epi # EXIT
    # else:    
    medianDepth = kf2.compute_points_median_depth()
    if medianDepth == -1:
        Printer.orange("search for triangulation: f2 with no points")        
        medianDepth = kf1.compute_points_median_depth()        
    ratioBaselineDepth = baseline/medianDepth
    if ratioBaselineDepth < Parameters.kMinRatioBaselineDepth:  
        Printer.orange("search for triangulation: impossible with too low ratioBaselineDepth!")
        return idxs1_out, idxs2_out, num_found_matches, img2_epi # EXIT        

    # compute the fundamental matrix between the two frames by using their estimated poses 
    F12, H21 = computeF12(kf1, kf2)

    if idxs1 is None or idxs2 is None:
        timerMatch = Timer()
        timerMatch.start()        
        idxs1, idxs2 = Frame.feature_matcher.match(kf1.des, kf2.des)        
        print('search_frame_for_triangulation - matching - timer: ', timerMatch.elapsed())        
    
    rot_histo = RotationHistogram()
    check_orientation = kCheckFeaturesOrientation and Frame.oriented_features     
        
    # check epipolar constraints 
    for i1,i2 in zip(idxs1,idxs2):
        if kf1.get_point_match(i1) is not None or kf2.get_point_match(i2) is not None: # we are searching for keypoint matches where both keypoints do not have a corresponding map point 
            #print('existing point on match')
            continue 
        
        descriptor_dist = Frame.descriptor_distance(kf1.des[i1], kf2.des[i2])
        if descriptor_dist > max_descriptor_distance:
            continue     
        
        kp1 = kf1.kpsu[i1]
        #kp1_scale_factor = Frame.feature_manager.scale_factors[kf1.octaves[i1]]
        #kp1_size = f1.sizes[i1]
        # discard points which are too close to the epipole            
        #if np.linalg.norm(kp1-e1) < Parameters.kMinDistanceFromEpipole * kp1_scale_factor:                 
        #if np.linalg.norm(kp1-e1) - kp1_size < Parameters.kMinDistanceFromEpipole:  # N.B.: this is too much conservative => it filters too much                                       
        #    continue   
        
        kp2 = kf2.kpsu[i2]
        kp2_scale_factor = Frame.feature_manager.scale_factors[kf2.octaves[i2]]        
        # kp2_size = f2.sizes[i2]        
        # discard points which are too close to the epipole            
        delta = kp2-e2        
        #if np.linalg.norm(delta) < Parameters.kMinDistanceFromEpipole * kp2_scale_factor:   
        if np.inner(delta,delta) < kMinDistanceFromEpipole2 * kp2_scale_factor:   # OR.            
        # #if np.linalg.norm(delta) - kp2_size < Parameters.kMinDistanceFromEpipole:  # N.B.: this is too much conservative => it filters too much                                                  
             continue           
        
        # check epipolar constraint         
        sigma2_kp2 = Frame.feature_manager.level_sigmas2[kf2.octaves[i2]]
        if check_dist_epipolar_line(kp1,kp2,F12,sigma2_kp2):
            idxs1_out.append(i1)
            idxs2_out.append(i2)
            
            if check_orientation:
                index_match = len(idxs1_out)-1
                rot = kf1.angles[i1]-kf2.angles[i2]
                rot_histo.push(rot,index_match)            
        #else:
        #    print('discarding point match non respecting epipolar constraint')
         
    if check_orientation:            
        valid_match_idxs = rot_histo.get_valid_idxs()     
        #print('checking orientation consistency - valid matches % :', len(valid_match_idxs)/max(1,len(idxs1_out))*100,'% of ', len(idxs1_out),'matches')
        #print('rotation histogram: ', rot_histo)
        idxs1_out = np.array(idxs1_out)[valid_match_idxs]
        idxs2_out = np.array(idxs2_out)[valid_match_idxs]
                 
    num_found_matches = len(idxs1_out)
             
    if __debug__:
        print('search_frame_for_triangulation - timer: ', timer.elapsed())

    return idxs1_out, idxs2_out, num_found_matches, img2_epi
Пример #33
0
class CustomControls:
    
    
    menu_spacing = 35 # distance between menu items
    top_spacing = 20  # distance between top of menu and start of menu
    left_spacing = 20 # distance between left and text for page text / command text
    menu_font_size = 32   # size of font for menu items
    status = STATUS_MENU         # Track whether to display menu or in menu etc.


    # Requires width and height - these can be the same as the screen or smaller if need to constrain menu
    # Offset and border determine distance from origin of screen and any fixed area to avoid respectively
    def __init__(self, game_controls, width=800, height=600, offset=(0,0), border=100):
        self.game_controls = game_controls
        self.width = width              # width of screen
        self.height = height            # height of screen
        self.offset = offset            # tuple x,y for offset from start of screen
        self.border = border            # single value same for x and y
        # Start position of the menu area and size
        self.start_pos = (self.offset[0]+self.border, self.offset[1]+self.border)
        self.size = (self.width-2*self.start_pos[0], self.height-2*self.start_pos[1])
        
        # Create a menu surface - this involves using pygame surface feature (rather than through pygame zero)
        # Allows for more advanced features such as alpha adjustment (partial transparency)
        self.menu_surface = Surface(self.size)
        # 75% opacity
        self.menu_surface.set_alpha(192)
        
        # Position of rect is 0,0 relative to the surface, not the screen
        self.menu_box = Rect((0,0),self.size)
        # Uses pygame rect so we can add it to own surface
        self.menu_rect = pygame.draw.rect(self.menu_surface , (200,200,200), self.menu_box)
        self.menu_pos = 0       # Tracks which menu item is selected

        
        # Timer restrict keyboard movements to prevent multiple presses
        self.menu_timer = Timer(0.12)
        
        self.updateMenuItems()
        
        
        
    # Updates the menu items - run this whenever the menu changes
    def updateMenuItems(self):
        
        self.menu_items = []
        # Store keys in an array to fix order and make easier to identify selected key
        for this_key in self.game_controls.getKeys():
            self.menu_items.append(MenuItem(this_key+" ("+str(self.game_controls.getKeyString(this_key))+")", this_key, 'control'))
                
        # Dummy entry - blank line
        self.menu_items.append(MenuItem("","","controls"))
        # Last Menu item is to save and return
        self.menu_items.append(MenuItem("Save settings", 'save', 'menu'))


        
    # Update menu based on keyboard direction
    # If return is 'controls' then still in custon controls, so don't update anything else
    # If return is 'menu' then return to main game menu
    def update(self, keyboard):
        # Handle erquest for new key
        if (self.status == STATUS_CUSTOM_KEY and self.menu_timer.getTimeRemaining() <= 0):
            keycode = self.checkKey(keyboard)
            if (keycode != None):
                self.game_controls.setKey(self.selected_key, keycode)
                self.menu_timer.startCountDown()
                self.status = STATUS_MENU
            self.updateMenuItems()
            return 'controls'
        # check if status is clicked - which means mouse was pressed on a valid entry
        if (self.status == STATUS_CLICKED):
            self.selected_key = self.menu_items[self.menu_pos].getCommand()
            self.reset()
            self.status = STATUS_CUSTOM_KEY
        # check if we are in menu timer in which case return until expired
        elif (self.menu_timer.getTimeRemaining() > 0): 
            return 'controls'
        elif (self.game_controls.isPressed(keyboard,'up') and self.menu_pos>0):
            if (self.status == STATUS_MENU):
                self.menu_pos -= 1
                self.menu_timer.startCountDown()
        elif (self.game_controls.isPressed(keyboard,'down') and self.menu_pos<len(self.menu_items)-1):
            if (self.status == STATUS_MENU):
                self.menu_pos += 1
                self.menu_timer.startCountDown()
        elif (self.game_controls.isOrPressed(keyboard,['jump','duck'])):
            if (self.status == STATUS_MENU):
                self.selected_key = self.menu_items[self.menu_pos].getCommand()
                self.reset()
                # special case where selected_key is the save option
                if (self.selected_key == 'save'):
                    # Save the controls
                    self.game_controls.saveControls()
                    return 'menu'
                # Another special case - blank entry used as a spacer
                # Ignore and continue with custom controls menu
                elif (self.selected_key == ''):
                    self.menu_timer.startCountDown()
                    return 'controls'
                self.status = STATUS_CUSTOM_KEY
        elif (self.game_controls.isPressed(keyboard,'escape')):
            return 'menu'
        return 'controls'            

    # Checks pygame event queue for last key pressed
    def checkKey(self, keyboard):
        # Check all keycodes to see if any are high
        for this_code in keycodes:
            if (keyboard[this_code]):
                    return this_code
        return None


    
    def draw(self, screen):
        # Create a rectangle across the area - provides transparancy
        screen.blit(self.menu_surface,self.start_pos)
        # draw directly onto the screen draw surface (transparency doesn't apply)
        if (self.status == STATUS_MENU):
            self.drawMenu(screen)
        elif (self.status == STATUS_CUSTOM_KEY):
            self.drawCustom(screen)
        
        
    def drawCustom(self, screen):
        screen.draw.text("Press custom key for "+self.selected_key, fontsize=self.menu_font_size, midtop=(self.width/2,self.offset[1]+self.border+(self.menu_spacing)+self.top_spacing), color=(0,0,0))
        
        
    def drawMenu(self, screen):
        for menu_num in range (0,len(self.menu_items)):
            if (menu_num == self.menu_pos):
                background_color = (255,255,255)
            else:
                background_color = None
            screen.draw.text(self.menu_items[menu_num].getText(), fontsize=self.menu_font_size, midtop=(self.width/2,self.offset[1]+self.border+(self.menu_spacing*menu_num)+self.top_spacing), color=(0,0,0), background=background_color)
           

    def mouse_move(self, pos):
        if (self.status == STATUS_MENU): 
            return_val = self.get_mouse_menu_pos(pos)
            if return_val != -1:
                self.menu_pos = return_val


    def mouse_click(self, pos):
        if (self.status == STATUS_MENU): 
            return_val = self.get_mouse_menu_pos(pos)
            if return_val != -1:
                self.menu_pos = return_val
                self.status = STATUS_CLICKED
        # If click from text page then return to menu
        elif (self.status == STATUS_PAGE):
            self.status = STATUS_MENU
    
    def select(self):
        self.menu_timer.startCountDown()
        
    
    def reset(self):
        self.menu_timer.startCountDown()
        self.menu_pos = 0
        self.status = STATUS_MENU
    
    
    # Checks if mouse is over menu and if so returns menu position
    # Otherwise returns -1
    def get_mouse_menu_pos (self, pos):
        if (pos[0] > self.start_pos[0] and pos[1] > self.start_pos[1] + self.top_spacing and pos[0] < self.start_pos[0] + self.size[0] and pos[1] < self.start_pos[1] + self.size[1]):
            start_y = self.start_pos[1] + self.top_spacing
            for this_menu_pos in range(0,len(self.menu_items)):
                if (pos[1] - start_y >= this_menu_pos * self.menu_spacing and pos[1] - start_y <= (this_menu_pos * self.menu_spacing)+self.menu_spacing):
                    return this_menu_pos
        # If not returned then not over menu
        return -1
Пример #34
0
def generate():
    try:
        tracks = []
        last = []
        wait = 2  # seconds
        d = Database()
        while test:
            yield d.merge(client.get('/tracks/73783917'))

        while True:
            log.info("Grabbing fresh tracklist from SoundCloud...")
            with Timer() as t:
                while not tracks:
                    try:
                        tracks =  client.get('/tracks', order='hotness', limit=200, offset=0)
                        tracks += client.get('/tracks', order='hotness', limit=200, offset=200)
                    except Exception as e:
                        log.warning("Got %s from SoundCloud. Retrying in %2.2f seconds...",
                                    e, wait)
                        time.sleep(wait)

            log.info("Got %d tracks in %2.2fms.", len(tracks), t.ms)
            emit('tracks_fetch', {"count": len(tracks), "ms": t.ms})

            if last and not any([t.id == last[-1].id for t in tracks]):
                tracks.append(last[-1])
            tracks = cull(tracks)

            tracks += list(get_force_mix_tracks(d))

            try:
                tracks = [d.merge(t) for t in tracks]
            except:
                log.warning("Could not merge tracks with DB due to:\n%s", traceback.format_exc())

            log.info("Solving TSP on %d tracks...", len(tracks))
            with Timer() as t:
                tracks = [tracks[i] for i in tsp.solve(tracks, distance, len(tracks) * config.tsp_mult)]
            log.info("Solved TSP in %2.2fms.", t.ms)
            emit('tsp_solve', {"count": len(tracks), "ms": t.ms})

            for track in tracks:
                for criterion in criteria:
                    criterion.postcompute(track)

            if last:
                i = getIndexOfId(tracks, last[-1].id) + 1
                tracks = tracks[i:] + tracks[:i]

            for track in tracks:
                for priority in get_immediate_tracks(d):
                    emit('decide_priority')
                    yield priority
                emit('decide_normal')
                yield track

            last = tracks
            tracks = []
    except:
        print traceback.format_exc()
        log.critical("%s", traceback.format_exc())
Пример #35
0
	def display_data(self):
		'''
		Shows the data.
		:return: str
		'''
		self.label['text'] = Timer.get_data(self)
Пример #36
0
class CruncherMenu:

    __current_menu_option = None
    #__trigger_action = None
    __lcdWidth = 0
    __lcdHeight = 0
    __menu_options = []
    __home_options = None
    __calibration_options = None
    __current_menu_option = 1
    __trigger_action = False

    __looper = False

    __paint_required = False
    __backlight_timeout = 5  # 5 seconds

    __backlight_timed_out = False

    current_menu_name = ""
    previous_menu_name = ""

    __debug = False

    def __init__(self, isDebug=False):
        self.__debug = isDebug

        self.__paint_required = True
        self.__timer = Timer(self.__backlight_timeout, self.__switch_backlight_off)
        self.init_menus()

        width, height = lcd.dimensions()
        self.__lcdWidth = width
        self.__lcdHeight = height
        # A squarer pixel font
        self.__font = ImageFont.truetype(fonts.BitocraFull, 11)

        # A slightly rounded, Ubuntu-inspired version of Bitocra
        #self.__font = ImageFont.truetype(fonts.BitbuntuFull, 10)

        self.__image = Image.new('P', (width, height))

        self.__draw = ImageDraw.Draw(self.__image)
        atexit.register(self.cleanup)
        self.set_backlight(255, 255, 255)
        self.set_menu_options()
        self.init_screen()

    async def __switch_backlight_off(self):
        if(self.__debug):
            print("Switching backlight off")

        backlight.set_all(0, 0, 0)
        backlight.show()
        self.__backlight_timed_out = True

    def __switch_backlight_on(self):
        backlight.set_all(self.__backlight_r, self.__backlight_g, self.__backlight_b)
        backlight.show()

    def init_menus(self):
        self.__home_options = [
            CruncherMenuOption('home_title', 'J2 Controller', None),
            CruncherMenuOption('home_servo_calibration', 'Servo Calibration', self.show_wheels_calibration_menu),
            CruncherMenuOption('home_servo_events', 'Events', self.show_events_menu),
            CruncherMenuOption('home_exit', 'Exit', sys.exit, (0,))
        ]
        self.__calibration_options = [
            CruncherMenuOption("sc_title",                  "Servo Calibration", None),
            CruncherMenuOption("sc_servo_indexs",           "Servo indexes", self.show_servo_index_menu),
            CruncherMenuOption("sc_servo_zero",             "Servo Zero positions", self.show_zero_position_menu),
            CruncherMenuOption("sc_save_current_status",    "Save current status", None),
            CruncherMenuOption("sc_set_actuation_angle",    "Set Actuation Angle", None),
            CruncherMenuOption("sc_reload_servo_defaults",  "Reload servo defaults", None),
            CruncherMenuOption("sc_back",                   "Back", self.set_menu_options)
        ]
        self.__servo_index_options = [
            CruncherMenuOption("wi_fl_wheel_index", "FL Wheel Index", self.show_wheels_calibration_screen),
            CruncherMenuOption("wi_fr_wheel_index", "FR Wheel Index", None),
            CruncherMenuOption("wi_rl_wheel_index", "RL Wheel Index", None),
            CruncherMenuOption("wi_rr_wheel_index", "RR Wheel Index", None),
            CruncherMenuOption("wi_fs_index",       "FS Index", None),
            CruncherMenuOption("wi_rs_index",       "RS Index", None),
            CruncherMenuOption("wi_back",           "Back", self.show_wheels_calibration_menu),

        ]
        self.__servo_zero_position_options = [
            CruncherMenuOption("wc_flw",    "Front left Wheel", self.set_front_left_wheel),
            CruncherMenuOption("wc_frw",    "Front Right Wheel", self.set_front_right_wheel),
            CruncherMenuOption("wc_rlw",    "Rear left Wheel", self.set_rear_left_wheel),
            CruncherMenuOption("wc_rrw",    "Rear right Wheel", self.set_rear_right_wheel),
            CruncherMenuOption("wc_sus",    "Suspension", self.show_suspension_screen),
            CruncherMenuOption("wc_back",   "Back", self.show_wheels_calibration_menu),
        ]

        self.__events_menu_options = [
            CruncherMenuOption("ev_title",          "Events", None),
            CruncherMenuOption("ev_space_invaders", "R:Space Invaders", None),
            CruncherMenuOption("ev_pi_noon",        "R:Pi Noon", self.invoke_pi_noon_command),
            CruncherMenuOption("ev_spirit",         "R:Spirit of Curiosity", None),
            CruncherMenuOption("ev_obstacles",      "R:Apollo 13 Obstacles", None),
            CruncherMenuOption("ev_blastoff",       "A:Blast off", None),
            CruncherMenuOption("ev_hubble",         "A:Hubble", None),
            CruncherMenuOption("ev_canyon",         "A:Canyon", None),
            CruncherMenuOption("ev_back",           "Back", self.set_menu_options)
        ]

    def set_menu_options(self, menuOptions=None):
        if(menuOptions == None):
            self.__menu_options = self.__home_options
        else:
            self.__menu_options = menuOptions
        self.__current_menu_option = 0

    def show_events_menu(self):
        self.set_menu_options(self.__events_menu_options)

    def show_wheels_calibration_menu(self):
        self.set_menu_options(self.__calibration_options)
        # self.paint_screen()

    def show_wheels_calibration_screen(self):
        return

    def set_front_left_wheel(self):
        return

    def set_front_right_wheel(self):
        return

    def set_rear_left_wheel(self):
        return

    def set_rear_right_wheel(self):
        return

    def show_suspension_screen(self):
        return

    def show_wheels_calibration_menu(self):
        return

    def show_servo_index_menu(self):
        self.set_menu_options(self.__servo_index_options)

    def show_zero_position_menu(self):
        self.set_menu_options(self.__servo_zero_position_options)

    def set_backlight(self, r, g, b):
        self.__backlight_r = r
        self.__backlight_g = g
        self.__backlight_b = b
        backlight.set_all(r, g, b)
        backlight.show()

    def handler(self, ch, event):
        # global
        if(self.__backlight_timed_out):
            self.__backlight_timed_out = False
            self.__switch_backlight_on()
            return

        if self.__timer.is_running:
            if(self.__debug):
                print("Timer is running")
            self.__timer.cancel()
            if(self.__debug):
                print("Timer Cancelled")

        if len(self.__menu_options) < self.__current_menu_option:
            self.previous_menu_name = self.__menu_options[self.__current_menu_option].name
        else:
            self.previous_menu_name = ""

        if event != 'press':
            return
        if ch == 1:
            self.__current_menu_option += 1
        if ch == 0:
            self.__current_menu_option -= 1
        if ch == 4:
            self.__trigger_action = True

        self.__current_menu_option %= len(self.__menu_options)
        self.current_menu_name = self.__menu_options[self.__current_menu_option].name
        self.__paint_required = True

    def invoke_pi_noon_command(self):

        return

    def cleanup(self):
        backlight.set_all(0, 0, 0)
        backlight.show()
        lcd.clear()
        lcd.show()

    def init_screen(self):
        for x in range(6):
            touch.set_led(x, 0)
            backlight.set_pixel(x, 255, 255, 255)
            touch.on(x, self.handler)

    # def run(self):
    #     self.init_screen()
    #
    #     backlight.show()
    #     self.set_menu_options()
    #     self.__looper = True
    #     while self.__looper:
    #         self.paint_screen()
    #         time.sleep(1.0 / 30)

    def paint_screen(self):
        try:
            self.__image.paste(0, (0, 0, self.__lcdWidth, self.__lcdHeight))

            if self.__trigger_action:
                self.__menu_options[self.__current_menu_option].trigger()
                self.__trigger_action = False

            if(len(self.__menu_options) > 0):
                self.paint_menu_buffered()
            else:
                self.paint_settings_screen()

            if(self.__timer.is_running == False):
                if(self.__debug):
                    print("Timer is not running")
                self.__timer.start()
                if(self.__debug):
                    print("Timer started")

            lcd.show()

        except KeyboardInterrupt:
            self.__looper = False
            self.cleanup()

    def paint_settings_screen(self):
        if current_menu_name == "":
            return

    def paint_menu_buffered(self):
        if(self.__paint_required == True):
            self.__paint_required = False
            offset_top = 0

            for index in range(len(self.__menu_options)):
                if index == self.__current_menu_option:
                    break
                offset_top += 12

            for index in range(len(self.__menu_options)):
                x = 10
                y = (index * 12) + (self.__lcdHeight / 2) - 4 - offset_top
                option = self.__menu_options[index]
                if index == self.__current_menu_option:
                    self.__draw.rectangle(((x - 2, y - 1), (self.__lcdWidth, y + 10)), 1)
                self.__draw.text((x, y), option.label, 0 if index == self.__current_menu_option else 1, self.__font)

            w, h = self.__font.getsize('>')
            self.__draw.text((0, (self.__lcdHeight - h) / 2), '>', 1, self.__font)

            for x in range(self.__lcdWidth):
                for y in range(self.__lcdHeight):
                    pixel = self.__image.getpixel((x, y))
                    lcd.set_pixel(x, y, pixel)
Пример #37
0
# Python file to test the basic functions of Pyfhel FHE library with a Microsoft SEAL backend.
# This demonstrates the add, subtract, multiply and exponent functions of the wrapped SEAL
# encryption library.
# By checking the level of noise in the cipher texts we can see how the operations can
# very quickly degrade the homomorphic performance. The noise level returned indicates the
# noise buffer remaining in the ciphertext, i.e. how much space we have available within a
# ciphertext to handle further operations on it, before the noise renders the result invalid.
# Note that when the noise reaches zero we will not get a valid result from any further
# operations on the ciphertext.
from Pyfhel import Pyfhel
from Pyfhel import PyCtxt
from Pyfhel import PyPtxt
from timer import Timer

# Time the operations
t = Timer()

# Generate our Pyfhel instance
pyf1 = Pyfhel()

# Create the context usingthe suggested modulus values for word and long
# Values for the modulus p (size of p):
# - 2 (Binary)
# - 257 (Byte)
# - 65537 (Word)
# - 4294967311 (Long)
# Generate the context with large noise deficit
pyf1.contextGen(65537, m=8192, sec=192, flagBatching=True)
pyf1.keyGen()
pyf1.relinKeyGen(10, 10)
Пример #38
0
    def init_objects(self):
        # Add meter
        meter = MeterPoint()
        meter.measurementType = MeasurementType.PowerReal
        meter.name = 'CampusElectricityMeter'
        meter.measurementUnit = MeasurementUnit.kWh
        self.meterPoints.append(meter)

        # Add weather forecast service
        weather_service = TemperatureForecastModel(self.config_path, self)
        self.informationServiceModels.append(weather_service)

        # Add inelastive asset
        inelastive_load = LocalAsset()
        inelastive_load.name = 'InelasticBuildings'  # Campus buildings that are not responsive
        inelastive_load.maximumPower = 0  # Remember that a load is a negative power [kW]
        inelastive_load.minimumPower = -2 * 8200  # Assume twice the average PNNL load [kW]

        # Add inelastive asset model
        inelastive_load_model = OpenLoopPnnlLoadPredictor(weather_service)
        inelastive_load_model.name = 'InelasticBuildingsModel'
        inelastive_load_model.engagementCost = [
            0, 0, 0
        ]  # Transition costs irrelevant
        inelastive_load_model.defaultPower = -6000  # [kW]
        inelastive_load_model.defaultVertices = [Vertex(0, 0, -6000.0, 1)]

        # Cross-reference asset & asset model
        inelastive_load_model.object = inelastive_load
        inelastive_load.model = inelastive_load_model

        # Add solar PV asset
        solar_pv = SolarPvResource()
        solar_pv.maximumPower = self.PV_max_kW  # [avg.kW]
        solar_pv.minimumPower = 0.0  # [avg.kW]
        solar_pv.name = 'SolarPv'
        solar_pv.description = '120 kW solar PV site on the campus'

        # Add solar PV asset model
        solar_pv_model = SolarPvResourceModel()
        solar_pv_model.cloudFactor = 1.0  # dimensionless
        solar_pv_model.engagementCost = [0, 0, 0]
        solar_pv_model.name = 'SolarPvModel'
        solar_pv_model.defaultPower = 0.0  # [avg.kW]
        solar_pv_model.defaultVertices = [Vertex(0, 0, 30.0, True)]
        solar_pv_model.costParameters = [0, 0, 0]
        solar_pv_model.inject(self, power_topic=self.solar_topic)

        # Cross-reference asset & asset model
        solar_pv.model = solar_pv_model
        solar_pv_model.object = solar_pv

        # Add inelastive and solar_pv as campus' assets
        self.localAssets.extend([inelastive_load, solar_pv])

        # Add Market
        market = Market()
        market.name = 'dayAhead'
        market.commitment = False
        market.converged = False
        market.defaultPrice = 0.04  # [$/kWh]
        market.dualityGapThreshold = self.duality_gap_threshold  # [0.02 = 2#]
        market.initialMarketState = MarketState.Inactive
        market.marketOrder = 1  # This is first and only market
        market.intervalsToClear = 1  # Only one interval at a time
        market.futureHorizon = timedelta(
            hours=24)  # Projects 24 hourly future intervals
        market.intervalDuration = timedelta(
            hours=1)  # [h] Intervals are 1 h long
        market.marketClearingInterval = timedelta(hours=1)  # [h]
        market.marketClearingTime = Timer.get_cur_time().replace(
            hour=0, minute=0, second=0,
            microsecond=0)  # Aligns with top of hour
        market.nextMarketClearingTime = market.marketClearingTime + timedelta(
            hours=1)
        self.markets.append(market)

        # City object
        city = Neighbor()
        city.name = 'CoR'
        city.description = 'City of Richland (COR) electricity supplier node'
        city.maximumPower = 20000  # Remember loads have negative power [avg.kW]
        city.minimumPower = 0  # [avg.kW]
        city.lossFactor = self.city_loss_factor

        # City model
        city_model = NeighborModel()
        city_model.name = 'CoR_Model'
        city_model.location = self.name
        city_model.transactive = True
        city_model.defaultPower = 10000  # [avg.kW]
        city_model.defaultVertices = [
            Vertex(0.046, 160, 0, True),
            Vertex(0.048,
                   160 + city.maximumPower * (0.046 + 0.5 * (0.048 - 0.046)),
                   city.maximumPower, True)
        ]
        city_model.costParameters = [0, 0, 0]
        city_model.demand_threshold_coef = self.demand_threshold_coef
        city_model.demandThreshold = self.monthly_peak_power
        city_model.inject(self,
                          system_loss_topic=self.system_loss_topic,
                          dc_threshold_topic=self.dc_threshold_topic)

        # Cross-reference object & model
        city_model.object = city
        city.model = city_model
        self.city = city

        # Add city as campus' neighbor
        self.neighbors.append(city)

        # Add buildings
        for bldg_name in self.building_names:
            bldg_neighbor = self.make_bldg_neighbor(bldg_name)
            self.neighbors.append(bldg_neighbor)
Пример #39
0
    def bounding_box_callback(self, bb_multiarray):
        """Converts 2D bounding boxes to 3D.

        Extract as many 2D bounding box corner coordinates as found in the ROS message.
        Then uses the depth image to convert the 2D bounding box to 3D.

        If MODIFY_COLOR_IMAGE, draws on the image (for each bounding box):
            1) corners of the 2D bounding box,
            2) center of the 3D bounding box (converted back to 2D),
            3) if not USE_OPTIMIZED, all the samples used.

        Parameters
        ----------
        bb_multiarray : Int32MultiArray
            An array of 2D bounding box corners, 
            with each bounding box described by 4 consecutive values.
            May contain corners of zero to many bounding boxes.

        Side effects
        ------------
        For each bounding box, places the 2D bounding box corners and 3D bounding box
        data as a key-value pair into the attribute "bounding_boxes_3d".
        """

        # Note:
        # Not using custom messages for compatibility reasons.
        # Also, commons_msgs does not have a suitable array type available.

        if self.timing_detailed:
            timer = Timer("bb_callback")

        nr_of_bounding_boxes = len(bb_multiarray.data) // 4
        self.bounding_boxes_3d = {}

        if self.timing_detailed:
            timer.update()

        for i in range(nr_of_bounding_boxes):
            self.corner_top_left = (
                bb_multiarray.data[0 + 4 * i],
                bb_multiarray.data[1 + 4 * i],
            )
            self.corner_bottom_right = (
                bb_multiarray.data[2 + 4 * i],
                bb_multiarray.data[3 + 4 * i],
            )

            if self.timing_detailed:
                timer.update()

            # Find the x, y, z and the corresponding sizes based on the 2D bounding box.
            bb_data = self.bounding_box_to_coordinates()
            self.bounding_boxes_3d[(self.corner_top_left,
                                    self.corner_bottom_right)] = bb_data

            if self.timing_detailed:
                timer.update()

            # Project the point with the median x, y, z back into a pixel to display it.
            # Can be disabled for performance reasons:
            if self.modify_color_img:
                self.point_to_image(bb_data)

        if self.modify_color_img:
            self.corners_to_image()

        if self.verbose:
            rospy.loginfo("BB 3D: " + str(self.bounding_boxes_3d))

        if self.timing_detailed:
            timer.stop()
Пример #40
0
class Jd_Mask_Spider(object):
    def __init__(self):
        # 初始化信息
        self.session = get_session()
        self.sku_id = global_config.getRaw('config', 'sku_id')
        self.seckill_init_info = dict()
        self.seckill_url = dict()
        self.seckill_order_data = dict()
        self.timers = Timer()
        self.default_user_agent = global_config.getRaw('config',
                                                       'DEFAULT_USER_AGENT')

    def login(self):
        for flag in range(1, 3):
            try:
                targetURL = 'https://order.jd.com/center/list.action'
                payload = {
                    'rid': str(int(time.time() * 1000)),
                }
                resp = self.session.get(url=targetURL,
                                        params=payload,
                                        allow_redirects=False)
                if resp.status_code == requests.codes.OK:
                    logger.info('校验是否登录[成功]')
                    logger.info('用户:{}'.format(self.get_username()))
                    return True
                else:
                    logger.info('校验是否登录[失败]')
                    logger.info('请从新输入cookie')
                    time.sleep(1)
                    continue
            except Exception as e:
                logger.info('第【%s】次失败请重新获取cookie', flag)
                time.sleep(1)
                continue
        sys.exit(1)

    def make_reserve(self):
        """商品预约"""
        logger.info('商品名称:{}'.format(get_sku_title()))
        url = 'https://yushou.jd.com/youshouinfo.action?'
        payload = {
            'callback': 'fetchJSON',
            'sku': self.sku_id,
            '_': str(int(time.time() * 1000)),
        }
        headers = {
            'User-Agent': self.default_user_agent,
            'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id),
        }
        resp = self.session.get(url=url, params=payload, headers=headers)
        resp_json = parse_json(resp.text)
        reserve_url = resp_json.get('url')
        self.timers.start()
        while True:
            try:
                self.session.get(url='https:' + reserve_url)
                logger.info('预约成功,已获得抢购资格 / 您已成功预约过了,无需重复预约')
                if global_config.getRaw('messenger', 'enable') == 'true':
                    success_message = "预约成功,已获得抢购资格 / 您已成功预约过了,无需重复预约"
                    send_wechat(success_message)
                break
            except Exception as e:
                logger.error('预约失败正在重试...')

    def get_username(self):
        """获取用户信息"""
        url = 'https://passport.jd.com/user/petName/getUserInfoForMiniJd.action'
        payload = {
            'callback': 'jQuery'.format(random.randint(1000000, 9999999)),
            '_': str(int(time.time() * 1000)),
        }
        headers = {
            'User-Agent': self.default_user_agent,
            'Referer': 'https://order.jd.com/center/list.action',
        }
        try:
            resp = self.session.get(url=url, params=payload, headers=headers)
            resp_json = parse_json(resp.text)
            # 响应中包含了许多用户信息,现在在其中返回昵称
            # jQuery2381773({"imgUrl":"//storage.360buyimg.com/i.imageUpload/xxx.jpg","lastLoginTime":"","nickName":"xxx","plusStatus":"0","realName":"xxx","userLevel":x,"userScoreVO":{"accountScore":xx,"activityScore":xx,"consumptionScore":xxxxx,"default":false,"financeScore":xxx,"pin":"xxx","riskScore":x,"totalScore":xxxxx}})
            return resp_json.get('nickName') or 'jd'
        except Exception:
            return 'jd'

    def get_seckill_url(self):
        """获取商品的抢购链接
        点击"抢购"按钮后,会有两次302跳转,最后到达订单结算页面
        这里返回第一次跳转后的页面url,作为商品的抢购链接
        :return: 商品的抢购链接
        """
        url = 'https://itemko.jd.com/itemShowBtn'
        payload = {
            'callback': 'jQuery{}'.format(random.randint(1000000, 9999999)),
            'skuId': self.sku_id,
            'from': 'pc',
            '_': str(int(time.time() * 1000)),
        }
        headers = {
            'User-Agent': self.default_user_agent,
            'Host': 'itemko.jd.com',
            'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id),
        }
        while True:
            resp = self.session.get(url=url, headers=headers, params=payload)
            resp_json = parse_json(resp.text)
            if resp_json.get('url'):
                # https://divide.jd.com/user_routing?skuId=8654289&sn=c3f4ececd8461f0e4d7267e96a91e0e0&from=pc
                router_url = 'https:' + resp_json.get('url')
                # https://marathon.jd.com/captcha.html?skuId=8654289&sn=c3f4ececd8461f0e4d7267e96a91e0e0&from=pc
                seckill_url = router_url.replace('divide', 'marathon').replace(
                    'user_routing', 'captcha.html')
                logger.info("抢购链接获取成功: %s", seckill_url)
                return seckill_url
            else:
                logger.info("抢购链接获取失败,%s不是抢购商品或抢购页面暂未刷新,1秒后重试")
                time.sleep(1)

    def request_seckill_url(self):
        """访问商品的抢购链接(用于设置cookie等"""
        logger.info('用户:{}'.format(self.get_username()))
        logger.info('商品名称:{}'.format(get_sku_title()))
        self.timers.start()
        self.seckill_url[self.sku_id] = self.get_seckill_url()
        logger.info('访问商品的抢购连接...')
        headers = {
            'User-Agent': self.default_user_agent,
            'Host': 'marathon.jd.com',
            'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id),
        }
        self.session.get(url=self.seckill_url.get(self.sku_id),
                         headers=headers,
                         allow_redirects=False)

    def request_seckill_checkout_page(self):
        """访问抢购订单结算页面"""
        logger.info('访问抢购订单结算页面...')
        url = 'https://marathon.jd.com/seckill/seckill.action'
        payload = {'skuId': self.sku_id, 'num': 1, 'rid': int(time.time())}
        headers = {
            'User-Agent': self.default_user_agent,
            'Host': 'marathon.jd.com',
            'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id),
        }
        self.session.get(url=url, params=payload, headers=headers)

    def _get_seckill_init_info(self):
        """获取秒杀初始化信息(包括:地址,发票,token)
        :return: 初始化信息组成的dict
        """
        logger.info('获取秒杀初始化信息...')
        url = 'https://marathon.jd.com/seckillnew/orderService/pc/init.action'
        data = {
            'sku': self.sku_id,
            'num': 1,
            'isModifyAddress': 'false',
        }
        headers = {
            'User-Agent': self.default_user_agent,
            'Host': 'marathon.jd.com',
        }
        resp = self.session.post(url=url, data=data, headers=headers)
        return parse_json(resp.text)

    def _get_seckill_order_data(self):
        """生成提交抢购订单所需的请求体参数
        :return: 请求体参数组成的dict
        """
        logger.info('生成提交抢购订单所需参数...')
        # 获取用户秒杀初始化信息
        self.seckill_init_info[self.sku_id] = self._get_seckill_init_info()
        init_info = self.seckill_init_info.get(self.sku_id)
        default_address = init_info['addressList'][0]  # 默认地址dict
        invoice_info = init_info.get('invoiceInfo', {})  # 默认发票信息dict, 有可能不返回
        token = init_info['token']
        data = {
            'skuId': self.sku_id,
            'num': 1,
            'addressId': default_address['id'],
            'yuShou': 'true',
            'isModifyAddress': 'false',
            'name': default_address['name'],
            'provinceId': default_address['provinceId'],
            'cityId': default_address['cityId'],
            'countyId': default_address['countyId'],
            'townId': default_address['townId'],
            'addressDetail': default_address['addressDetail'],
            'mobile': default_address['mobile'],
            'mobileKey': default_address['mobileKey'],
            'email': default_address.get('email', ''),
            'postCode': '',
            'invoiceTitle': invoice_info.get('invoiceTitle', -1),
            'invoiceCompanyName': '',
            'invoiceContent': invoice_info.get('invoiceContentType', 1),
            'invoiceTaxpayerNO': '',
            'invoiceEmail': '',
            'invoicePhone': invoice_info.get('invoicePhone', ''),
            'invoicePhoneKey': invoice_info.get('invoicePhoneKey', ''),
            'invoice': 'true' if invoice_info else 'false',
            'password': '',
            'codTimeType': 3,
            'paymentType': 4,
            'areaCode': '',
            'overseas': 0,
            'phone': '',
            'eid': global_config.getRaw('config', 'eid'),
            'fp': global_config.getRaw('config', 'fp'),
            'token': token,
            'pru': ''
        }
        return data

    def submit_seckill_order(self):
        """提交抢购(秒杀)订单
        :return: 抢购结果 True/False
        """
        url = 'https://marathon.jd.com/seckillnew/orderService/pc/submitOrder.action'
        payload = {
            'skuId': self.sku_id,
        }
        self.seckill_order_data[self.sku_id] = self._get_seckill_order_data()
        logger.info('提交抢购订单...')
        headers = {
            'User-Agent':
            self.default_user_agent,
            'Host':
            'marathon.jd.com',
            'Referer':
            'https://marathon.jd.com/seckill/seckill.action?skuId={0}&num={1}&rid={2}'
            .format(self.sku_id, 1, int(time.time())),
        }
        resp = self.session.post(url=url,
                                 params=payload,
                                 data=self.seckill_order_data.get(self.sku_id),
                                 headers=headers)
        resp_json = parse_json(resp.text)
        # 返回信息
        # 抢购失败:
        # {'errorMessage': '很遗憾没有抢到,再接再厉哦。', 'orderId': 0, 'resultCode': 60074, 'skuId': 0, 'success': False}
        # {'errorMessage': '抱歉,您提交过快,请稍后再提交订单!', 'orderId': 0, 'resultCode': 60017, 'skuId': 0, 'success': False}
        # {'errorMessage': '系统正在开小差,请重试~~', 'orderId': 0, 'resultCode': 90013, 'skuId': 0, 'success': False}
        # 抢购成功:
        # {"appUrl":"xxxxx","orderId":820227xxxxx,"pcUrl":"xxxxx","resultCode":0,"skuId":0,"success":true,"totalMoney":"xxxxx"}
        if resp_json.get('success'):
            order_id = resp_json.get('orderId')
            total_money = resp_json.get('totalMoney')
            pay_url = 'https:' + resp_json.get('pcUrl')
            logger.info('抢购成功,订单号:{}, 总价:{}, 电脑端付款链接:{}'.format(
                order_id, total_money, pay_url))
            if global_config.getRaw('messenger', 'enable') == 'true':
                success_message = "抢购成功,订单号:{}, 总价:{}, 电脑端付款链接:{}".format(
                    order_id, total_money, pay_url)
                send_wechat(success_message)
            return True
        else:
            logger.info('抢购失败,返回信息:{}'.format(resp_json))
            if global_config.getRaw('messenger', 'enable') == 'true':
                error_message = '抢购失败,返回信息:{}'.format(resp_json)
                send_wechat(error_message)
            return False
Пример #41
0
class Alien(Sprite):
    images = [[
        pg.image.load('images/alien' + str(number) + str(i) + '.png')
        for i in range(2)
    ] for number in range(3)]
    images_boom = [
        pg.image.load('images/alien_boom' + str(i) + '.png') for i in range(4)
    ]

    timers = []
    for i in range(3):
        timers.append(Timer(frames=images[i], wait=700))
    timer_boom = Timer(frames=images_boom, wait=100, looponce=True)

    def __init__(self, game, parent, number=0, x=0, y=0, speed=0):
        super().__init__()
        self.screen = game.screen
        self.settings = game.settings
        self.game = game
        self.number = number
        self.parent = parent
        self.update_requests = 0
        self.dead = False
        self.reallydead = False
        self.timer_switched = False

        self.timer = Alien.timers[number]

        self.rect = self.timer.imagerect().get_rect()

        self.rect.x = self.x = x
        self.rect.y = self.y = y

        self.x = float(self.rect.x)
        self.speed = speed

    def check_edges(self):
        r, rscreen = self.rect, self.screen.get_rect()
        return r.right >= rscreen.right or r.left <= 0

    def killed(self):
        if not self.dead and not self.timer_switched:
            self.dead = True
        if self.dead and not self.timer_switched:
            self.timer = Timer(frames=Alien.images_boom,
                               wait=400,
                               looponce=True)
            self.timer_switched = True
            self.game.stats.score += self.settings.alien_points * len(
                self.parent.alien_group)
            self.game.sb.check_high_score(self.game.stats.score)
            self.game.sb.prep_score()

    def update(self):
        if self.dead and self.timer_switched:
            if self.timer.frame_index() == len(Alien.images_boom) - 1:
                self.dead = False
                self.timer_switched = False
                self.reallydead = True
                self.parent.remove(self)
                self.timer.reset()
        delta = self.settings.alien_speed * self.settings.fleet_direction
        self.rect.x += delta
        self.x = self.rect.x

    def draw(self):
        image = self.timer.imagerect()
        rect = image.get_rect()
        rect.x, rect.y = self.rect.x, self.rect.y
        self.screen.blit(image, rect)
Пример #42
0
class Player(TextEntity):
    def __init__(self):
        TextEntity.__init__(self, self, 0)
        self.rateOfFire = 250
        self.shooting = False
        self.shootingTime = Timer().start()
        self.fire_x = 0
        self.fire_y = 0
        self.fire_vel = 50
        self.name = 'Player'

        self.moveRate = 50
        self.moving = False
        self.moveTime = Timer().start()
        self.move_vel = 7

        self.vel_y_max = 10
        self.vel_x_max = 10
        self.resistance_x = 35.0
        self.resistance_y = 35.0

        self.levelMax = 20
        self.levelCur = 0
        self.levelFuzzieEx = 5  #Chance of a fuzzie spawning during the time (20% chance)

        #self.constaccel_y = 20.0
        #self.vel_x_max = 100.0
        #self.vel_y_max = 100.0
#		self.accel_y = 0.0
#self.resistance_x = 1.0

    def left(self, key, state):
        if state == True:
            self.moving |= MOVE_LEFT
        else:
            self.moving &= ~MOVE_LEFT

    def right(self, key, state):
        if state == True:
            self.moving |= MOVE_RIGHT
        else:
            self.moving &= ~MOVE_RIGHT

    def up(self, key, state):
        if state == True:
            self.moving |= MOVE_UP
        else:
            self.moving &= ~MOVE_UP

    def down(self, key, state):
        # POWER SLIDE!!!
        #if state == True:
        #	self.resistance_x -= 600
        #else: self.resistance_x += 600
        if state == True:
            self.moving |= MOVE_DOWN
        else:
            self.moving &= ~MOVE_DOWN

    def _move(self):
        if self.moveTime.elapsed() < self.moveRate:
            return

        x = y = 0
        if self.moving & MOVE_LEFT: x -= self.move_vel
        if self.moving & MOVE_RIGHT: x += self.move_vel
        if self.moving & MOVE_UP: y -= self.move_vel
        if self.moving & MOVE_DOWN: y += self.move_vel

        self.impulse(x, y)
        self.moveTime.restart()

    def _fire(self, x, y):
        if self.shootingTime.elapsed() < self.rateOfFire:
            return
        if not x and not y: return

        getScene().add(Bullet(self, 3, x, y), 3)
        self.shootingTime.restart()

    def fireUp(self, key, state):
        if self.shooting and not state:
            self.shooting -= 1
            self.fire_y += self.fire_vel
        elif state == True:
            self.shooting += 1
            self.fire_y += -self.fire_vel

    def fireDown(self, key, state):
        if self.shooting and not state:
            self.shooting -= 1
            self.fire_y -= self.fire_vel
        elif state == True:
            self.shooting += 1
            self.fire_y += self.fire_vel

    def fireLeft(self, key, state):
        if self.shooting and not state:
            self.shooting -= 1
            self.fire_x += self.fire_vel
        elif state == True:
            self.shooting += 1
            self.fire_x += -self.fire_vel

    def fireRight(self, key, state):
        if self.shooting and not state:
            self.shooting -= 1
            self.fire_x -= self.fire_vel
        elif state == True:
            self.shooting += 1
            self.fire_x += self.fire_vel

    def think(self, frameDT):
        if len(self.touching): self.collideHandler()

        if self.shooting > 0:
            self._fire(self.fire_x, self.fire_y)
        if self.moving:
            self._move()

        if random.randint(
                1, self.levelFuzzieEx * 30
        ) == 1 and self.levelCur <= self.levelMax:  #CHANCE*CURRENT_FPS should do the trick...
            getScene().add(Fuzzie(10, 30, 30), 4)
            self.levelCur += 1
Пример #43
0
    def bounding_box_to_coordinates(self):
        """Calculates the 3D bounding box coordinates and dimensions.

        This is the core method of the module.
        It is intentionally long for performance reasons,
        also enabling to use two different versions:
        one for visualization and one for optimized performance.

        Returns
        -------
        tuple
            The coordinates (x, y, z) and 
            the dimensions (size_x, size_y, size_z) of a bounding box
            in a sextuple
            If not a valid detection, the following tuple is returned:
            (0, 0, 0, 0, 0, 0)
        """

        if self.timing_detailed:
            timer = Timer("bb_to_coord")

        bb_width = self.corner_bottom_right[0] - self.corner_top_left[0]
        bb_height = self.corner_bottom_right[1] - self.corner_top_left[1]

        if self.timing_detailed:
            timer.update()

        # Note:
        # Strides can be dynamic in order to gain a slight performance advantage.
        # Right now left as-is to be compatible with the noise analysis.
        stride_x = 20
        stride_y = 20

        if self.timing_detailed:
            timer.update()

        # Finds the amount of samples in both directions.
        times_x = int(np.ceil(bb_width / stride_x))
        times_y = int(np.ceil(bb_height / stride_y))

        if self.timing_detailed:
            timer.update()

        # Offset is needed to center the samples.
        offset_x = int((bb_width - (times_x - 1) * stride_x - 1) // 2)
        offset_y = int((bb_height - (times_y - 1) * stride_y - 1) // 2)

        if self.timing_detailed:
            timer.stop()

        # Original version
        if not self.use_optimized:
            bb_points = np.zeros((bb_height, bb_width, 3))

            for x in range(self.corner_top_left[0] + offset_x,
                           self.corner_bottom_right[0], stride_x):
                for y in range(self.corner_top_left[1] + offset_y,
                               self.corner_bottom_right[1], stride_y):
                    point = self.pixel_to_point(x, y)
                    bb_points[y - self.corner_top_left[1],
                              x - self.corner_top_left[0]] = point

                    # Display a little circle on the RGB image where each sample is located
                    if self.modify_color_img:
                        circle_color = (0, 0, 255) if point[2] > 0 else (255,
                                                                         0, 0)
                        cv2.circle(self.color_image, (x, y), 2, circle_color,
                                   2)

            # Only the points with non-zero depth
            filtered_points = bb_points[np.where(bb_points[:, :, 2] > 0)]

            # Return the median of each axis
            old_medians = (
                np.nanmedian(filtered_points[:, 0]),
                np.nanmedian(filtered_points[:, 1]),
                np.nanmedian(filtered_points[:, 2]),
            )
            medians = old_medians

        # Optimized version
        # A VERY important note:
        # only use this version when the camera's distortion coefficients are 0!!!
        if self.use_optimized or self.use_optimized is None:
            if self.timing_detailed:
                start_times = []
                stop_times = []
                start_times.append(time.perf_counter())

            # Utilizing Numpy functions in order to get rid of a double for-loop.
            # Performing sampling with given strides in both directions.
            x_range = np.arange(self.corner_top_left[0] + offset_x,
                                self.corner_bottom_right[0], stride_x)
            y_range = np.arange(self.corner_top_left[1] + offset_y,
                                self.corner_bottom_right[1], stride_y)
            xx, yy = np.meshgrid(x_range, y_range)
            # Important! Scaling by a factor of 0.001 so the results are in meters, not mm!
            depths = self.depth_image[yy, xx] * self.depth_scale
            # Creating an empty array to hold the values that are going to be calculated.
            points = np.zeros((times_y, times_x, 3))

            # Note:
            # Displaying the samples on the color image is not feasible with the optimized version.
            # Therefore, if needed, consider using the unoptimized version at a slight
            # performance cost.

            if self.timing_detailed:
                timing = time.perf_counter()
                stop_times.append(timing)
                start_times.append(timing)

            # Calculating the points if the camera's parameters are known.
            if self.intrinsics:
                # Vectorized variants of the calculations found in the RealSense library
                # https://github.com/IntelRealSense/librealsense/blob/v2.24.0/wrappers/python/examples/box_dimensioner_multicam/helper_functions.py#L121-L147
                points[:, :, 0] = (xx - self.intrinsics.ppx) / \
                    self.intrinsics.fx * depths
                points[:, :, 1] = (yy - self.intrinsics.ppy) / \
                    self.intrinsics.fy * depths
                points[:, :, 2] = depths

            if self.timing_detailed:
                timing = time.perf_counter()
                stop_times.append(timing)
                start_times.append(timing)

            # Only the points with non-zero depth (new)
            filtered_points_new = points[np.where(points[:, :, 2] > 0)]

            if self.timing_detailed:
                timing = time.perf_counter()
                stop_times.append(timing)
                start_times.append(timing)

            # The following is to catch false detections.
            # Shape of "filtered_points_new":
            #   first dimension: nr of points sampled,
            #   second dimension: 3 (that is x, y and z).
            # Therefore, if the nr of samples is 0, it's not a valid detection.
            if np.shape(filtered_points_new)[0] > 0:
                new_medians = np.nanmedian(filtered_points_new, axis=0)
            else:
                # (0, 0, 0) is indicating an invalid detection
                # (0 depth signifies error as per the RealSense library).
                new_medians = (0, 0, 0)

            if self.timing_detailed:
                timing = time.perf_counter()
                stop_times.append(timing)
                start_times.append(timing)

            new_medians = tuple(new_medians)
            medians = new_medians

            if self.timing_detailed:
                # cp.disable()
                # cp.print_stats()
                timing = time.perf_counter()
                stop_times.append(timing)
                timings = np.asarray(stop_times) - np.asarray(start_times)
                rospy.loginfo("Timings: " + str(timings * 1000) + " ms")

        if self.use_optimized is None:
            rospy.loginfo("Medians:\n" + "Old: " + str(old_medians) + "\n" +
                          "New: " + str(new_medians))

        # Added the scaling information for x and y (and also z but yet unimplemented).
        output_with_scale = []
        output_with_scale.extend(medians)
        # Note: this results in (0, 0, 0, 0, 0, 0) when the median depth is 0.
        # This is desired, as it allows to filter out false results later.
        output_with_scale.extend(
            self.get_bb_scale(medians[2], bb_width, bb_height))

        return tuple(output_with_scale)
Пример #44
0
import time

import packet
import udt
from timer import Timer

PACKET_SIZE = 1024
RECEIVER_ADDR = ('localhost', 8080)
SENDER_ADDR = ('localhost', 0)
SLEEP_INTERVAL = 0.05
TIMEOUT_INTERVAL = 0.5
WINDOW_SIZE = 4

base = 0
mutex = _thread.allocate_lock()
send_timer = Timer(TIMEOUT_INTERVAL)


def set_window_size(num_packets):
    global base
    return min(WINDOW_SIZE, num_packets - base)


def send(sock, filename, drop_prob):
    global mutex
    global base
    global send_timer

    try:
        file = open(filename, 'rb')
    except IOError:
Пример #45
0
enemies = friends = 0

#Создание меню
pause = Pause(punkts1, "Pause")
menu = Menu(punkts, "Battle city")
options = Options(punkts2, 'Options')
u_win = End_of_game(punkts3, "You win!")
u_lose = End_of_game(punkts4, 'Game over')
level_choose = Level_choose(punkts5, 'Choose level')
current_diff = 0

#Создание строки состояния
status_bar = Status_bar(0, 0)

#Создание Таймера
timer = Timer()

#Создание уровня
max_enemies = 0
spavned_enemies = 0
total_enemies = 0
stage = 0
bricks_group = []
enemy_spavner_group = []
level_num = 0
lvl_w = lvl_h = 0


def make_level(level_num, max_e, total_e, diff):
    x = y = 0
    global bricks_group, sprite_group, lvl_w, lvl_h, enemies, \
Пример #46
0
def train_agent(train_params):

    env = load_flatland_environment_from_file(
        "scratch/test-envs/Test_2/Level_1.pkl")
    env.reset(regenerate_schedule=True, regenerate_rail=True)
    # Environment parameters
    n_agents = len(env.agents)
    x_dim = env.width
    y_dim = env.height
    n_cities = 3
    #max_rails_between_cities = env_params.max_rails_between_cities
    #max_rails_in_city = env_params.max_rails_in_city
    seed = 2125

    # Observation parameters
    # observation_tree_depth = env_params.observation_tree_depth
    # observation_radius = env_params.observation_radius
    # observation_max_path_depth = env_params.observation_max_path_depth
    observation_tree_depth = 2
    observation_radius = 10
    observation_max_path_depth = 30

    # Training parameters
    eps_start = train_params.eps_start
    eps_end = train_params.eps_end
    eps_decay = train_params.eps_decay
    n_episodes = train_params.n_episodes
    checkpoint_interval = train_params.checkpoint_interval
    n_eval_episodes = train_params.n_evaluation_episodes

    # Set the seeds
    random.seed(seed)
    np.random.seed(seed)

    # Break agents from time to time
    malfunction_parameters = MalfunctionParameters(
        malfunction_rate=1. / 10000,  # Rate of malfunctions
        min_duration=15,  # Minimal duration
        max_duration=50  # Max duration
    )

    # Observation builder
    predictor = ShortestPathPredictorForRailEnv(observation_max_path_depth)
    tree_observation = TreeObsForRailEnv(max_depth=observation_tree_depth,
                                         predictor=predictor)

    # Fraction of train which each speed
    speed_profiles = {
        1.: 1.0,  # Fast passenger train
        1. / 2.: 0.0,  # Fast freight train
        1. / 3.: 0.0,  # Slow commuter train
        1. / 4.: 0.0  # Slow freight train
    }

    # Setup the environment
    # env = RailEnv(
    #     width=x_dim,
    #     height=y_dim,
    #     rail_generator=sparse_rail_generator(
    #         max_num_cities=n_cities,
    #         grid_mode=False,
    #         max_rails_between_cities=max_rails_between_cities,
    #         max_rails_in_city=max_rails_in_city
    #     ),
    #     schedule_generator=sparse_schedule_generator(speed_profiles),
    #     number_of_agents=n_agents,
    #     malfunction_generator_and_process_data=malfunction_from_params(malfunction_parameters),
    #     obs_builder_object=tree_observation,
    #     random_seed=seed
    #

    # env.reset(regenerate_schedule=True, regenerate_rail=True)

    # Setup renderer
    if train_params.render:
        env_renderer = RenderTool(env, gl="PGL")

    # Calculate the state size given the depth of the tree observation and the number of features
    n_features_per_node = env.obs_builder.observation_dim
    n_nodes = 0
    for i in range(observation_tree_depth + 1):
        n_nodes += np.power(4, i)
    state_size = n_features_per_node * n_nodes

    # The action space of flatland is 5 discrete actions
    action_size = 5

    # Max number of steps per episode
    # This is the official formula used during evaluations
    # See details in flatland.envs.schedule_generators.sparse_schedule_generator
    max_steps = int(4 * 2 * (env.height + env.width + (n_agents / n_cities)))
    print("max_steps1= ", max_steps)
    max_steps2 = env._max_episode_steps
    print("max_steps2= ", max_steps2)

    action_count = [0] * action_size
    action_dict = dict()
    agent_obs = [None] * env.get_num_agents()
    agent_prev_obs = [None] * env.get_num_agents()
    agent_prev_action = [2] * env.get_num_agents()
    update_values = False
    smoothed_normalized_score = -1.0
    smoothed_eval_normalized_score = -1.0
    smoothed_completion = 0.0
    smoothed_eval_completion = 0.0

    # Double Dueling DQN policy
    policy = DDDQNPolicy(state_size, action_size, train_params)

    # TensorBoard writer
    writer = SummaryWriter()
    writer.add_hparams(vars(train_params), {})
    #writer.add_hparams(vars(env_params), {})

    training_timer = Timer()
    training_timer.start()

    print(
        "\n🚉 Training {} trains on {}x{} grid for {} episodes, evaluating on {} episodes every {} episodes.\n"
        .format(env.get_num_agents(), x_dim, y_dim, n_episodes,
                n_eval_episodes, checkpoint_interval))

    for episode_idx in range(n_episodes + 1):
        # Timers
        step_timer = Timer()
        reset_timer = Timer()
        learn_timer = Timer()
        preproc_timer = Timer()

        # Reset environment
        reset_timer.start()
        obs, info = env.reset(regenerate_rail=True, regenerate_schedule=True)
        reset_timer.end()

        if train_params.render:
            env_renderer.set_new_rail()

        score = 0
        nb_steps = 0
        actions_taken = []

        # Build agent specific observations
        for agent in env.get_agent_handles():
            if obs[agent]:
                agent_obs[agent] = normalize_observation(
                    obs[agent],
                    observation_tree_depth,
                    observation_radius=observation_radius)
                agent_prev_obs[agent] = agent_obs[agent].copy()

        # Run episode
        for step in range(max_steps - 1):
            for agent in env.get_agent_handles():
                if info['action_required'][agent]:
                    # If an action is required, we want to store the obs at that step as well as the action
                    update_values = True
                    action = policy.act(agent_obs[agent], eps=eps_start)
                    action_count[action] += 1
                    actions_taken.append(action)
                else:
                    update_values = False
                    action = 0
                action_dict.update({agent: action})

            # Environment step
            step_timer.start()
            next_obs, all_rewards, done, info = env.step(action_dict)
            step_timer.end()

            if train_params.render and episode_idx % checkpoint_interval == 0:
                env_renderer.render_env(show=True,
                                        frames=False,
                                        show_observations=False,
                                        show_predictions=False)

            for agent in range(env.get_num_agents()):
                # Update replay buffer and train agent
                # Only update the values when we are done or when an action was taken and thus relevant information is present
                if update_values or done[agent]:
                    learn_timer.start()
                    policy.step(agent_prev_obs[agent],
                                agent_prev_action[agent], all_rewards[agent],
                                agent_obs[agent], done[agent])
                    learn_timer.end()

                    agent_prev_obs[agent] = agent_obs[agent].copy()
                    agent_prev_action[agent] = action_dict[agent]

                # Preprocess the new observations
                if next_obs[agent]:
                    preproc_timer.start()
                    agent_obs[agent] = normalize_observation(
                        next_obs[agent],
                        observation_tree_depth,
                        observation_radius=observation_radius)
                    preproc_timer.end()

                score += all_rewards[agent]

            nb_steps = step

            if done['__all__']:
                break

        # Epsilon decay
        eps_start = max(eps_end, eps_decay * eps_start)

        # Collection information about training
        tasks_finished = sum(done[idx] for idx in env.get_agent_handles())
        completion = tasks_finished / max(1, env.get_num_agents())
        normalized_score = score / (max_steps * env.get_num_agents())
        action_probs = action_count / np.sum(action_count)
        action_count = [1] * action_size

        # Smoothed values for terminal display and for more stable hyper-parameter tuning
        smoothing = 0.99
        smoothed_normalized_score = smoothed_normalized_score * smoothing + normalized_score * (
            1.0 - smoothing)
        smoothed_completion = smoothed_completion * smoothing + completion * (
            1.0 - smoothing)

        # Print logs
        if episode_idx % checkpoint_interval == 0:
            torch.save(policy.qnetwork_local,
                       './checkpoints/obs_multi-' + str(episode_idx) + '.pth')
            if train_params.render:
                env_renderer.close_window()

        print('\r🚂 Episode {}'
              '\t 🏆 Score: {:.3f}'
              ' Avg: {:.3f}'
              '\t 💯 Done: {:.2f}%'
              ' Avg: {:.2f}%'
              '\t 🎲 Epsilon: {:.2f} '
              '\t 🔀 Action Probs: {}'.format(episode_idx, normalized_score,
                                             smoothed_normalized_score,
                                             100 * completion,
                                             100 * smoothed_completion,
                                             eps_start,
                                             format_action_prob(action_probs)),
              end=" ")

        # Evaluate policy
        if episode_idx % train_params.checkpoint_interval == 0:
            scores, completions, nb_steps_eval = eval_policy(
                env, policy, n_eval_episodes, max_steps)
            writer.add_scalar("evaluation/scores_min", np.min(scores),
                              episode_idx)
            writer.add_scalar("evaluation/scores_max", np.max(scores),
                              episode_idx)
            writer.add_scalar("evaluation/scores_mean", np.mean(scores),
                              episode_idx)
            writer.add_scalar("evaluation/scores_std", np.std(scores),
                              episode_idx)
            writer.add_histogram("evaluation/scores", np.array(scores),
                                 episode_idx)
            writer.add_scalar("evaluation/completions_min",
                              np.min(completions), episode_idx)
            writer.add_scalar("evaluation/completions_max",
                              np.max(completions), episode_idx)
            writer.add_scalar("evaluation/completions_mean",
                              np.mean(completions), episode_idx)
            writer.add_scalar("evaluation/completions_std",
                              np.std(completions), episode_idx)
            writer.add_histogram("evaluation/completions",
                                 np.array(completions), episode_idx)
            writer.add_scalar("evaluation/nb_steps_min", np.min(nb_steps_eval),
                              episode_idx)
            writer.add_scalar("evaluation/nb_steps_max", np.max(nb_steps_eval),
                              episode_idx)
            writer.add_scalar("evaluation/nb_steps_mean",
                              np.mean(nb_steps_eval), episode_idx)
            writer.add_scalar("evaluation/nb_steps_std", np.std(nb_steps_eval),
                              episode_idx)
            writer.add_histogram("evaluation/nb_steps",
                                 np.array(nb_steps_eval), episode_idx)

            smoothing = 0.9
            smoothed_eval_normalized_score = smoothed_eval_normalized_score * smoothing + np.mean(
                scores) * (1.0 - smoothing)
            smoothed_eval_completion = smoothed_eval_completion * smoothing + np.mean(
                completions) * (1.0 - smoothing)
            writer.add_scalar("evaluation/smoothed_score",
                              smoothed_eval_normalized_score, episode_idx)
            writer.add_scalar("evaluation/smoothed_completion",
                              smoothed_eval_completion, episode_idx)

        # Save logs to tensorboard
        writer.add_scalar("training/score", normalized_score, episode_idx)
        writer.add_scalar("training/smoothed_score", smoothed_normalized_score,
                          episode_idx)
        writer.add_scalar("training/completion", np.mean(completion),
                          episode_idx)
        writer.add_scalar("training/smoothed_completion",
                          np.mean(smoothed_completion), episode_idx)
        writer.add_scalar("training/nb_steps", nb_steps, episode_idx)
        writer.add_histogram("actions/distribution", np.array(actions_taken),
                             episode_idx)
        writer.add_scalar("actions/nothing",
                          action_probs[RailEnvActions.DO_NOTHING], episode_idx)
        writer.add_scalar("actions/left",
                          action_probs[RailEnvActions.MOVE_LEFT], episode_idx)
        writer.add_scalar("actions/forward",
                          action_probs[RailEnvActions.MOVE_FORWARD],
                          episode_idx)
        writer.add_scalar("actions/right",
                          action_probs[RailEnvActions.MOVE_RIGHT], episode_idx)
        writer.add_scalar("actions/stop",
                          action_probs[RailEnvActions.STOP_MOVING],
                          episode_idx)
        writer.add_scalar("training/epsilon", eps_start, episode_idx)
        writer.add_scalar("training/buffer_size", len(policy.memory),
                          episode_idx)
        writer.add_scalar("training/loss", policy.loss, episode_idx)
        writer.add_scalar("timer/reset", reset_timer.get(), episode_idx)
        writer.add_scalar("timer/step", step_timer.get(), episode_idx)
        writer.add_scalar("timer/learn", learn_timer.get(), episode_idx)
        writer.add_scalar("timer/preproc", preproc_timer.get(), episode_idx)
        writer.add_scalar("timer/total", training_timer.get_current(),
                          episode_idx)
Пример #47
0
def test_num(img):
    # cv2.imshow('img', img)
    # cv2.waitKey(0)
    # timer = Timer().start()
    test = img.reshape(1, 784)
    test = test.astype('float32')
    test /= 255
    return np.int8(knn.findNearest(test, k=1)[0])
    # timer.stop('Predicted ' + str(res) + ' in')


if __name__ == '__main__':
    pass

timer = Timer().start()
print 'Loading MNIST data set...'
# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
timer.stop('Data set loaded in')

x_train = x_train.reshape(60000, 784)
x_train = (x_train) > 180
x_train = x_train.astype('float32')
y_train = y_train.astype('float32')

timer.start()
print 'Training...'
knn = cv2.ml.KNearest_create()
knn.train(x_train, cv2.ml.ROW_SAMPLE, y_train)
timer.stop('Finished training in')
Пример #48
0
class PluginDebug(Plugin):
    def __init__(self, application):
        Plugin.__init__(self, application)
        self._url = u"http://jenyay.net/Outwiker/DebugPlugin"
        self._watcher = EventsWatcher(self._application)
        self._timer = Timer()

        self.ID_PLUGINSLIST = wx.NewId()
        self.ID_BUTTONSDIALOG = wx.NewId()
        self.ID_START_WATCH_EVENTS = wx.NewId()
        self.ID_STOP_WATCH_EVENTS = wx.NewId()

    def enableFeatures(self):
        config = DebugConfig(self._application.config)

        self._enablePreProcessing = config.enablePreprocessing.value
        self._enablePostProcessing = config.enablePostprocessing.value
        self._enableOnHoverLink = config.enableOnHoverLink.value
        self._enableOnLinkClick = config.enableOnLinkClick.value
        self._enableOnEditorPopup = config.enableOnEditorPopup.value
        self._enableRenderingTimeMeasuring = config.enableRenderingTimeMeasuring.value
        self._enableNewPageDialogTab = config.enableNewPageDialogTab.value
        self._enablePageDialogEvents = config.enablePageDialogEvents.value

        config.enablePreprocessing.value = self._enablePreProcessing
        config.enablePostprocessing.value = self._enablePostProcessing
        config.enableOnHoverLink.value = self._enableOnHoverLink
        config.enableOnLinkClick.value = self._enableOnLinkClick
        config.enableOnEditorPopup.value = self._enableOnEditorPopup
        config.enableRenderingTimeMeasuring.value = self._enableRenderingTimeMeasuring
        config.enableNewPageDialogTab.value = self._enableNewPageDialogTab
        config.enablePageDialogEvents.value = self._enablePageDialogEvents

    def initialize(self):
        self.enableFeatures()

        domain = u"testdebug"
        self.__ID_TREE_POPUP = wx.NewId()
        self.__ID_TRAY_POPUP = wx.NewId()

        langdir = unicode(os.path.join(os.path.dirname(__file__), "locale"),
                          getOS().filesEncoding)
        global _

        try:
            _ = self._init_i18n(domain, langdir)
        except BaseException as e:
            print e

        self.__menuName = _(u"Debug")

        if self._application.mainWindow is not None:
            self.__createMenu()
            self.__createTestAction()

            self._application.onTreePopupMenu += self.__onTreePopupMenu
            self._application.onTrayPopupMenu += self.__onTrayPopupMenu
            self._application.onPostprocessing += self.__onPostProcessing
            self._application.onPreprocessing += self.__onPreProcessing
            self._application.onHoverLink += self.__onHoverLink
            self._application.onLinkClick += self.__onLinkClick
            self._application.onEditorPopupMenu += self.__onEditorPopupMenu
            self._application.onHtmlRenderingBegin += self.__onHtmlRenderingBegin
            self._application.onHtmlRenderingEnd += self.__onHtmlRenderingEnd
            self._application.onWikiParserPrepare += self.__onWikiParserPrepare
            self._application.onPageDialogInit += self.__onPageDialogInit
            self._application.onPageDialogPageTypeChanged += self.__onPageDialogPageTypeChanged
            self._application.onPageDialogPageTitleChanged += self.__onPageDialogPageTitleChanged
            self._application.onPageDialogPageStyleChanged += self.__onPageDialogPageStyleChanged
            self._application.onPageDialogPageIconChanged += self.__onPageDialogPageIconChanged
            self._application.onPageDialogPageTagsChanged += self.__onPageDialogPageTagsChanged

    def destroy(self):
        """
        Уничтожение (выгрузка) плагина. Здесь плагин должен отписаться от всех событий
        """
        mainWindow = self._application.mainWindow
        if mainWindow is not None and mainWindow.PLUGINS_TOOLBAR_STR in mainWindow.toolbars:
            self._application.actionController.removeMenuItem(
                DebugAction.stringId)
            self._application.actionController.removeToolbarButton(
                DebugAction.stringId)
            self._application.actionController.removeAction(
                DebugAction.stringId)

            self._application.mainWindow.Unbind(wx.EVT_MENU,
                                                handler=self.__onPluginsList,
                                                id=self.ID_PLUGINSLIST)

            self._application.mainWindow.Unbind(wx.EVT_MENU,
                                                handler=self.__onButtonsDialog,
                                                id=self.ID_BUTTONSDIALOG)

            self._application.mainWindow.Unbind(
                wx.EVT_MENU,
                handler=self.__onStartWatchEvents,
                id=self.ID_START_WATCH_EVENTS)

            self._application.mainWindow.Unbind(
                wx.EVT_MENU,
                handler=self.__onStopWatchEvents,
                id=self.ID_STOP_WATCH_EVENTS)

            index = self._application.mainWindow.mainMenu.FindMenu(
                self.__menuName)
            assert index != wx.NOT_FOUND

            index = self._application.mainWindow.mainMenu.Remove(index)

            self._application.onTreePopupMenu -= self.__onTreePopupMenu
            self._application.onTrayPopupMenu -= self.__onTrayPopupMenu
            self._application.onPostprocessing -= self.__onPostProcessing
            self._application.onPreprocessing -= self.__onPreProcessing
            self._application.onHoverLink -= self.__onHoverLink
            self._application.onLinkClick -= self.__onLinkClick
            self._application.onEditorPopupMenu -= self.__onEditorPopupMenu
            self._application.onHtmlRenderingBegin -= self.__onHtmlRenderingBegin
            self._application.onHtmlRenderingEnd -= self.__onHtmlRenderingEnd
            self._application.onWikiParserPrepare -= self.__onWikiParserPrepare
            self._application.onPageDialogInit -= self.__onPageDialogInit
            self._application.onPageDialogPageTypeChanged -= self.__onPageDialogPageTypeChanged
            self._application.onPageDialogPageTitleChanged -= self.__onPageDialogPageTitleChanged
            self._application.onPageDialogPageStyleChanged -= self.__onPageDialogPageStyleChanged
            self._application.onPageDialogPageIconChanged -= self.__onPageDialogPageIconChanged
            self._application.onPageDialogPageTagsChanged -= self.__onPageDialogPageTagsChanged

    def __createMenu(self):
        self.menu = wx.Menu(u"")
        self.menu.Append(self.ID_PLUGINSLIST, _(u"Plugins List"))
        self.menu.Append(self.ID_BUTTONSDIALOG, _(u"ButtonsDialog"))
        self.menu.Append(self.ID_START_WATCH_EVENTS, _(u"Start watch events"))
        self.menu.Append(self.ID_STOP_WATCH_EVENTS, _(u"Stop watch events"))

        self._application.mainWindow.mainMenu.Append(self.menu,
                                                     self.__menuName)

        self._application.mainWindow.Bind(wx.EVT_MENU,
                                          self.__onPluginsList,
                                          id=self.ID_PLUGINSLIST)

        self._application.mainWindow.Bind(wx.EVT_MENU,
                                          self.__onButtonsDialog,
                                          id=self.ID_BUTTONSDIALOG)

        self._application.mainWindow.Bind(wx.EVT_MENU,
                                          self.__onStartWatchEvents,
                                          id=self.ID_START_WATCH_EVENTS)

        self._application.mainWindow.Bind(wx.EVT_MENU,
                                          self.__onStopWatchEvents,
                                          id=self.ID_STOP_WATCH_EVENTS)

    def __createTestAction(self):
        mainWindow = self._application.mainWindow

        if mainWindow is not None and mainWindow.PLUGINS_TOOLBAR_STR in mainWindow.toolbars:
            action = DebugAction(self._application)
            hotkey = HotKey("T", ctrl=True, shift=True, alt=True)
            toolbar = mainWindow.toolbars[mainWindow.PLUGINS_TOOLBAR_STR]
            image = self.getImagePath("bug.png")

            controller = self._application.actionController

            controller.register(action, hotkey=hotkey)

            controller.appendMenuCheckItem(DebugAction.stringId, self.menu)
            controller.appendToolbarCheckButton(DebugAction.stringId, toolbar,
                                                image)

    def getImagePath(self, imageName):
        """
        Получить полный путь до картинки
        """
        imagedir = unicode(os.path.join(os.path.dirname(__file__), "images"),
                           getOS().filesEncoding)
        fname = os.path.join(imagedir, imageName)
        return fname

    def __onTreePopupMenu(self, menu, page):
        """
        Событие срабатывает после создания всплывающего меню над деревом заметок
        """
        if page.getTypeString() == "wiki":
            menu.Append(self.__ID_TREE_POPUP, _(u"Message For Wiki Page"))
            menu.Bind(wx.EVT_MENU,
                      lambda event: MessageBox(_("Wiki Message"),
                                               _(u"This is wiki page")),
                      id=self.__ID_TREE_POPUP)

        elif page.getTypeString() == "html":
            menu.Append(self.__ID_TREE_POPUP, _(u"Message For HTML Page"))
            menu.Bind(wx.EVT_MENU,
                      lambda event: MessageBox(_("HTML Message"),
                                               _(u"This is HTML page")),
                      id=self.__ID_TREE_POPUP)

        elif page.getTypeString() == "text":
            menu.Append(self.__ID_TREE_POPUP, _(u"Message For Text Page"))
            menu.Bind(wx.EVT_MENU,
                      lambda event: MessageBox(_("Text Message"),
                                               _(u"This is Text page")),
                      id=self.__ID_TREE_POPUP)

    def __onTrayPopupMenu(self, menu, tray):
        menu.Insert(0, self.__ID_TRAY_POPUP, _(u"Tray Menu From Plugin"))
        menu.Bind(
            wx.EVT_MENU,
            lambda event: MessageBox(_("Tray Icon"), _(u"This is tray icon")),
            id=self.__ID_TRAY_POPUP)

    def __onPostProcessing(self, page, params):
        if self._enablePostProcessing:
            params.result = re.compile(re.escape(u"абырвалг"),
                                       re.I | re.U).sub(
                                           u"Главрыба", params.result)

    def __onPreProcessing(self, page, params):
        if self._enablePreProcessing:
            params.result = "!! Debug!!!\n" + params.result

    def __onButtonsDialog(self, event):
        buttons = [
            _(u"Button 1"),
            _(u"Button 2"),
            _(u"Button 3"),
            _(u"Cancel")
        ]
        with ButtonsDialog(self._application.mainWindow,
                           _(u"Message"),
                           _(u"Caption"),
                           buttons,
                           default=0,
                           cancel=3) as dlg:
            result = dlg.ShowModal()

            if result == wx.ID_CANCEL:
                print u"Cancel"
            else:
                print result

    def __onPluginsList(self, event):
        pluginslist = [
            plugin.name + "\n" for plugin in self._application.plugins
        ]
        MessageBox(u"".join(pluginslist), _(u"Plugins List"))

    def __onStartWatchEvents(self, event):
        self._watcher.startWatch()

    def __onStopWatchEvents(self, event):
        self._watcher.stopWatch()

    def __onHoverLink(self, page, params):
        if not self._enableOnHoverLink:
            return

        if params.link is None:
            return

        if params.link.startswith(u"http"):
            params.text = u"(link) {}".format(params.text)
        elif params.link.startswith(u"tag://"):
            params.text = u"(tag) {}".format(params.link)

    def __onLinkClick(self, page, params):
        if not self._enableOnLinkClick:
            return

        print params.link
        # params["process"] = True

    def __onEditorPopupMenu(self, page, params):
        if self._enableOnEditorPopup:
            params.menu.AppendSeparator()
            params.menu.Append(-1, u'Debug popup menu item')

    def __onHtmlRenderingBegin(self, page, htmlView):
        self._timer.start()

    def __onHtmlRenderingEnd(self, page, htmlView):
        assert page is not None

        if self._enableRenderingTimeMeasuring:
            interval = self._timer.getTimeInterval()
            text = u'Rendering "{page}": {time} sec'.format(page=page.title,
                                                            time=interval)

            logging.info(text)

    def __onWikiParserPrepare(self, parser):
        token = DebugTokenFactory.makeDebugToken(parser)

        parser.listItemsTokens.append(token)
        parser.wikiTokens.append(token)
        parser.linkTokens.append(token)
        parser.headingTokens.append(token)
        parser.textLevelTokens.append(token)

    def __onPageDialogInit(self, page, params):
        if self._enableNewPageDialogTab:
            panel = NewPageDialogPanel(params.dialog.getPanelsParent())
            params.dialog.addPanel(panel, _(u'Debug'))

            controller = DebugPageDialogController(self._application)
            params.dialog.addController(controller)

    def __onPageDialogPageTypeChanged(self, page, params):
        if self._enablePageDialogEvents:
            print u'Selected page type: {}'.format(params.pageType)

    def __onPageDialogPageTitleChanged(self, page, params):
        if self._enablePageDialogEvents:
            print u'New page title: {}'.format(params.pageTitle)

    def __onPageDialogPageStyleChanged(self, page, params):
        if self._enablePageDialogEvents:
            print u'New page style: {}'.format(params.pageStyle)

    def __onPageDialogPageIconChanged(self, page, params):
        if self._enablePageDialogEvents:
            print u'New page icon: {}'.format(params.pageIcon)

    def __onPageDialogPageTagsChanged(self, page, params):
        if self._enablePageDialogEvents:
            print u'New page tags: {}'.format(params.pageTags)

    ###################################################
    # Свойства и методы, которые необходимо определить
    ###################################################

    @property
    def name(self):
        return u"Debug Plugin"

    @property
    def description(self):
        return _(u"""Debug Plugin
                 <a href="http://jenyay.net">http://jenyay.net</a>

                 <a href="/111">Link to page</a>
                 """)

    @property
    def version(self):
        return u"0.5"

    @property
    def url(self):
        return self._url

    @url.setter
    def url(self, value):
        self._url = value
"""perturb_transmon.py - library of transmon perturbative solutions based on Didier...Rigetti (2018)"""

import qutip as qt
import numpy as np
import matplotlib.pyplot as plt
import math
import sys
from timer import Timer
from qtools import pad_ket
from qtools import truncate_ket
import io_tools as io

# # # # # # # # # # # # # # # # # # # #
# Initialization
DEBUG = False
time = Timer()
# # # # # # # # # # # # # # # # # # # #

# # # # # # # # # # # # # # # # # # # #

# GLOBAL PARAMS debug
W0 = 1
WR = 1.2
XI = .1
G = .2
# # # # # # # # # # # # # # # # # # # #


def get_phieff(phiext, ej1, ej2):
    # didier eqn 17
    return np.arctan2(np.sin(phiext), np.cos(phiext) + ej2 / ej1)
Пример #50
0
    if do_print:
        print("Running with {} MPI processes.".format(MPI.COMM_WORLD.Get_size()))

    ################################################## 
    # set up plotting and figure
    try:
        if do_plots:
            pass
    except:
        #print()
        pass


    # Timer for profiling
    timer = Timer()
    timer.start("total")
    timer.start("init")

    timer.do_print = do_print


    # parse command line arguments
    parser = argparse.ArgumentParser(description='Simple PIC-Maxwell simulations')
    parser.add_argument('--conf', dest='conf_filename', default=None,
                       help='Name of the configuration file (default: None)')
    args = parser.parse_args()
    if args.conf_filename == None:
        conf = Configuration('gyration.ini', do_print=do_print) 
    else:
        if do_print:
Пример #51
0
    for i in xrange(1, len(tracks)):
        print "%2.2f" % distance(tracks[i], tracks[i - 1]),
        for criterion in criteria:
            print "\t%2.1f/%2.1f" % criterion(tracks[i], tracks[i - 1]),
        print "\t%2.1f" % ((tracks[i].tempo if hasattr(tracks[i], 'tempo') else tracks[i].bpm) or 0),
        print "\t", tracks[i].title, "by", tracks[i].user['username']

if __name__ == "__main__":
    print "Testing the BRAIN..."
    d = Database()
    o = None
    while not o:
        try:
            o  = client.get('/tracks', order='hotness', limit=200)
            o += client.get('/tracks', order='hotness', limit=200, offset=200)
        except HTTPError as e:
            print "Error from SC. (%s) Trying again..." % e
            pass
    tracks = cull([d.merge(t) for t in o])

    print "Solving TSP on %d tracks..." % len(tracks)

    with Timer() as t:
        tracks = [tracks[i] for i in tsp.solve(tracks, distance, len(tracks) * config.tsp_mult)]
    print "Solved TSP in %2.2fms." % t.ms
    #   TODO:   Use standard deviation to find the limit of deviation
    #           for tempo difference in tracks. I.e.: Any tracks that don't
    #           fit next to their neighbours should be removed, then TSP re-run.

    print_table(tracks)
Пример #52
0
        c = p.find(v)
        if c not in ccs:
            ccs[c] = set()
        ccs[c].add(v)
    return ccs


vs, es = load.load_snap_undirected('data/snap/ca-GrQc.txt')
g = sg.SimpleGraph(vs, es)
n = len(g.vertices)
m = len(g.edges)
print("Loaded graph with %d vertices and %d edges" % (n, m))
print()

print("Computing connected components with naive find-union:")
with Timer(verbose=True):
    ccs = compute_ccs(g, part.NaivePartition)
    print("found %d components" % len(ccs))

print()
print("Computing connected components with efficient find-union:")
with Timer(verbose=True):
    ccs = compute_ccs(g, part.Partition)
    print("found %d components" % len(ccs))

print()
print("Computing connected components with graph traversal:")
with Timer(verbose=True):
    ccs = ccmod.compute_ccs(g)
    print("found %d components" % len(ccs))
Пример #53
0
def plot_genomic_pos(gene,
                     sqlite_path_organism,
                     sqlite_path_reads,
                     exclude=True):
    # Conctructs a computational graph using the exons as nodes (splice graph). Exons are labeled with number ID's
    # exon_positions_with_numbers gets the genomic position of the exon start for each node.
    # get y_values sacks nodes up the y axis depending how populated that locus is with the annotated exons.
    # this ensures no overlapping of nodes
    t = Timer()
    t.start()

    supported_transcripts = filter_unsupported_transcripts(
        gene, sqlite_path_organism, sqlite_path_reads)
    try:
        numbers_position = exon_positions_with_numbers(gene,
                                                       sqlite_path_organism,
                                                       supported_transcripts,
                                                       exclude)
    except ValueError:
        print(
            "There are no transcripts where all exons have supporting reads for this gene."
        )
        print()
        user_input = input("Set exclude to False? (True/False): ")
        if (user_input == "True") or (user_input == "T"):
            exclude = False
            numbers_position = exon_positions_with_numbers(
                gene, sqlite_path_organism, supported_transcripts, False)
        else:
            print()
            print(
                "No fully supported transcripts. No unfiltered plot requested")
            return

    number_x_y = get_y_values(numbers_position)
    node_labels = relabel_nodes_L_R(number_x_y)
    graph = nx.DiGraph()
    for node in number_x_y:
        graph.add_node(node, pos=(number_x_y[node][0], number_x_y[node][1]))

    edge_numbers = get_edges_numbers(gene, sqlite_path_organism,
                                     supported_transcripts, exclude)
    graph.add_edges_from(edge_numbers, color="black")

    handles = []
    exon_dict = assign_exon_numbers(gene, sqlite_path_organism,
                                    supported_transcripts, exclude)
    number_of_exons = len(exon_dict.keys())

    # Nodes are coloured based on the degree to which they were supported by the reads
    scores, junction_pileup = get_scores_for_gene(gene,
                                                  sqlite_path_organism,
                                                  sqlite_path_reads,
                                                  supported_transcripts,
                                                  filter=True)
    for i in range(1, number_of_exons + 1):
        if i not in scores:
            scores[i] = 0
    principal_path = principal_path_in_numbers(gene, sqlite_path_organism,
                                               supported_transcripts, exclude)
    if exclude:
        zero_support = []
        for exon in scores:
            if (scores[exon] == 0) and (exon not in principal_path):
                graph.remove_node(exon)
                zero_support.append(exon)

        for exon in zero_support:
            del scores[exon]

    for i in exon_dict:
        handles.append(
            mpatches.Patch(label=str(i) + " : " + ": " + exon_dict[i]))

    color_lookup = scores
    low, *_, high = sorted(color_lookup.values())
    norm = mpl.colors.Normalize(vmin=low, vmax=high, clip=True)
    mapper = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.Blues)

    pos = nx.get_node_attributes(graph, 'pos')

    # Path of principal isoform as per APPRIS database is coloured red
    principal_edges = []
    edges = graph.edges()

    for i in range(len(principal_path) - 1):
        if principal_path[i] not in list(edges):
            graph.add_node(principal_path[i])
        elif principal_path[i + 1] not in list(edges):
            graph.add_node(principal_path[i + 1])

        principal_edges.append((principal_path[i], principal_path[i + 1]))

    graph.add_edges_from(principal_edges, color="r")
    colors = [graph[u][v]['color'] for u, v in edges]

    edge_labels = get_edges_scores_numbers(gene,
                                           sqlite_path_organism,
                                           supported_transcripts,
                                           junction_pileup,
                                           filter=exclude)
    nx.draw(graph,
            pos,
            edges=edges,
            edge_color=colors,
            node_shape='s',
            nodelist=color_lookup,
            node_size=150,
            node_color=[mapper.to_rgba(i) for i in color_lookup.values()],
            with_labels=False,
            linewidths=1,
            font_size=8)

    ax = plt.gca()  # to get the current axis
    ax.collections[0].set_edgecolor("#000000")

    # nx.draw_networkx_labels(graph, pos, node_labels, font_size=7) # Node labels from L to R
    nx.draw_networkx_labels(graph, pos, scores,
                            font_size=5)  #Node lables as scores per that exon
    nx.draw_networkx_edge_labels(graph,
                                 pos,
                                 edge_labels=edge_labels,
                                 font_color='blue',
                                 font_size=6)
    principal_path_new = [node_labels[i] for i in principal_path]
    principal_text = "Principal Path: ", principal_path_new

    # plt.figtext(0.01, 0.95, principal_text)
    plt.margins(x=0, y=0.5)
    t.stop()
    plt.show()
Пример #54
0
	def display_day(self):
		'''
		Shows the name of the day.
		:return: str
		'''
		self.label['text'] = Timer.name_day(self)
Пример #55
0
def search_frame_for_triangulation_test(f1, f2, img2, img1=None):

    idxs2_out = []
    idxs1_out = []
    lines_out = []
    num_found_matches = 0
    img2_epi = None

    if __debug__:
        timer = Timer()
        timer.start()

    O1w = f1.Ow
    O2w = f2.Ow
    # compute epipoles
    e1, _ = f1.project_point(O2w)  # in first frame
    e2, _ = f2.project_point(O1w)  # in second frame
    #print('e1: ', e1)
    #print('e2: ', e2)

    baseline = np.linalg.norm(O1w - O2w)

    # if the translation is too small we cannot triangulate
    # if False:
    #     if baseline < Parameters.kMinTraslation:  # we assume the Inializer has been used for building the first map
    #         Printer.red("search for triangulation: impossible with almost zero translation!")
    #         return idxs1_out, idxs2_out, num_found_matches, img2_epi # EXIT
    # else:
    medianDepthF2 = f2.compute_points_median_depth()
    ratioBaselineDepth = baseline / medianDepthF2
    if ratioBaselineDepth < Parameters.kMinRatioBaselineDepth:
        Printer.red(
            "search for triangulation: impossible with too low ratioBaselineDepth!"
        )
        return idxs1_out, idxs2_out, num_found_matches, img2_epi  # EXIT

    # compute the fundamental matrix between the two frames by using their estimated poses
    F12, H21 = computeF12(f1, f2)

    idxs1 = []
    for i, p in enumerate(f1.get_points()):
        if p is None:  # we consider just unmatched keypoints
            kp = f1.kpsu[i]
            scale_factor = Frame.feature_manager.scale_factors[f1.octaves[i]]
            # discard points which are too close to the epipole
            if np.linalg.norm(
                    kp -
                    e1) < Parameters.kMinDistanceFromEpipole * scale_factor:
                continue
            idxs1.append(i)
    kpsu1 = f1.kpsu[idxs1]

    if __debug__:
        #print('search_frame_for_triangulation - timer1: ', timer.elapsed())
        timer.start()

    # compute epipolar lines in second image
    lines2 = cv2.computeCorrespondEpilines(kpsu1.reshape(-1, 1, 2), 2, F12)
    lines2 = lines2.reshape(-1, 3)

    xs2_inf = np.dot(
        H21,
        add_ones(kpsu1).T
    ).T  # x2inf = H21 * x1  where x2inf is corresponding point according to infinite homography [Hartley Zisserman pag 339]
    xs2_inf = xs2_inf[:, 0:2] / xs2_inf[:, 2:]
    line_edges = [
        epiline_to_end_points(line, e2, x2_inf, f2.width)
        for line, x2_inf in zip(lines2, xs2_inf)
    ]
    #print("line_edges: ", line_edges)

    if __debug__:
        #print('search_frame_for_triangulation - timer3: ', timer.elapsed())
        assert (len(line_edges) == len(idxs1))
        timer.start()

    len_des2 = len(f2.des)
    flag_match = np.full(len_des2, False, dtype=bool)
    dist_match = np.zeros(len_des2)
    index_match = np.full(len_des2, 0, dtype=int)
    for i, idx in enumerate(
            idxs1
    ):  # N.B.: a point in f1 can be matched to more than one point in f2, we avoid this by caching matches with f2 points
        f2_idx, dist = find_matches_along_line(f2, e2, line_edges[i],
                                               f1.des[idx])
        if f2_idx > -1:
            if not flag_match[f2_idx]:  # new match
                flag_match[f2_idx] = True
                dist_match[f2_idx] = dist
                idxs2_out.append(f2_idx)
                idxs1_out.append(idx)
                index_match[f2_idx] = len(idxs2_out) - 1
                assert (f2.get_point_match(f2_idx) is None)
                assert (f1.get_point_match(idx) is None)
                if __debug__:
                    lines_out.append(line_edges[i])
            else:  # already matched
                if dist < dist_match[
                        f2_idx]:  # update in case of a smaller distance
                    dist_match[f2_idx] = dist
                    index = index_match[f2_idx]
                    idxs1_out[index] = idx
                    if __debug__:
                        lines_out[index] = line_edges[i]

    num_found_matches = len(idxs1_out)
    assert (len(idxs1_out) == len(idxs2_out))

    if __debug__:
        #print("num found matches: ", num_found_matches)
        if True:
            kpsu2 = f2.kpsu[idxs2_out]
            img2_epi = draw_lines(img2.copy(), lines_out, kpsu2)
            #cv2.imshow("epipolar lines",img2_epi)
            #cv2.waitKey(0)

    #if __debug__:
    #print('search_frame_for_triangulation - timer4: ', timer.elapsed())

    return idxs1_out, idxs2_out, num_found_matches, img2_epi
Пример #56
0
# ゲーム中で使う変数の一覧
blocks = []
block_size = {"x": 100, "y": 20}
ball = {"dirx": 15, "diry": -15, "x": 350, "y": 300, "w": 10}
bar = {"x": 10, "w": 100}
is_gameover = False
point = 0

# ウィンドウの作成
win = Tk()
cv = Canvas(win, width=600, height=400)
cv.pack()

# タイマーの用意
timer = Timer()


# ゲームの初期化
def init_game():
    global is_gameover, point
    is_gameover = False

    ball["y"] = 500
    ball["diry"] = -10
    point = 0
    # ブロックを配置する
    for iy in range(0, 5):
        for ix in range(0, 8):
            color = "green"
            if (iy + ix) % 2 == 1: color = "yellow"
Пример #57
0
    # and compare runtimes!
    for stack_size in [1000, 10000, 100000, 1000000]:
        # Uncomment out the stack implementation that we want
        # to time.
        stack = Stack()
        # stack = Stack2()      # eg) implement Stack2 with a linked list

        # Bypass the Stack interface to create a stack of
        # size <stack_size>.  We know this is cheating!
        stack._items = list(range(stack_size))

        # Create a Timer that will report how long it takes
        # to add and remove 1000 times on our stack. What
        # value we add should make no difference to the time
        # required, so we arbitrarily add 1.
        with Timer(f'Stack add/remove [size {stack_size}]'):
            for _ in range(1000):
                stack.add(1)
                stack.remove()

    # mess around example
    # s = Stack()
    # stopped = False
    # while not stopped:
    #     item = input('Enter a string or type \'end\' to exit: ')
    #     s.add(item)
    #     if item == 'end':
    #         stopped = True
    #
    # print("Your string stack contains:")
    # while not s.is_empty():
Пример #58
0
    def Fit(self, dataset):
        """ Calcula la mejor distribución de los puntos del dataset, según los parámetros elegidos."""
        t = Timer()

        wx.CallAfter(self.listener.SetMaxRange, self.NIterations)

        t.AddTime("Start")
        self.dataset = dataset
        self.datasetLen, self.datasetDimension = list(dataset.shape)

        self.population = self._GetInitialPop(
        )  # 1. Generación de población inicial

        t.AddTime("Initial pop")

        self.bestIndividual = None

        for it in range(self.NIterations):
            self.fitness = [i.Fitness() for i in self.population
                            ]  # 2. Calculo de aptitud de la población

            minFit = np.argmax(self.fitness)
            print('DEBUG - Min fit key %d - value: %f' %
                  (minFit, self.fitness[minFit]))

            # if (self.fitness[minFit] <= self.FITNESS_THRESHOLD): # 3. Primera condición de parada
            #     self.bestIndividual = self.population[minFit]
            #     break

            newPop = []  # Construcción de la nueva población

            # 4. Selección de individuos. Elitista + Ruleta

            # Aseguro al mejor miembro de la población
            eliteInd = self._ElitistSelection()
            newPop.append(eliteInd)

            # Selecciona el resto por ruleta

            selectionAmount = int(len(self.population) * self.SELECTION_RATIO)

            print('DEBUG - Selection amount: %s' % selectionAmount)

            selected = self._WheelSelection(selectionAmount -
                                            1)  # Porque ya tengo uno de elite
            newPop.extend(selected)

            # 5. Cruza pares de individuos seleccionados al azar

            crossAmount = int(
                len(self.population) * self.CROSSING_RATIO
            )  # Cantidad de individuos resultados de la cruza

            print('DEBUG - Crossing amount: %s' % crossAmount)

            crossOverflow = crossAmount % 2.0
            crossAmount = int(math.ceil(
                crossAmount /
                2.0))  # Se usa la mitad de pares para generar 2 hijos

            print('DEBUG - Overflow: %s' % crossOverflow)
            print('DEBUG - Cross: %s' % crossAmount)

            toCross = self._GetCrossingPairs(crossAmount)  # Selección de pares

            for pair in toCross:
                child1, child2 = pair[0].CrossWith(pair[1])  # Cruza
                newPop.append(child1)
                newPop.append(child2)

            # 6. Mutación de individuos seleccionados al azar

            mutationAmount = int(len(self.population) * self.MUTATION_RATIO)

            # Si se obtuvo un individuo extra en la cruza resto uno para mutar
            if crossOverflow > 0:
                mutationAmount -= 1

            print('DEBUG - Mutation amount: %s' % mutationAmount)

            mutated = self._GetMutated(mutationAmount)

            newPop.extend(mutated)

            # El método anterior no asegura individuos mutados por lo tanto
            # se completa la población con nuevas cruzas si es necesario
            if (len(newPop) < len(self.population)):
                missingPop = len(self.population) - len(newPop)

                toCross = self._GetCrossingPairs(missingPop)

                for pair in toCross:
                    child1, child2 = pair[0].CrossWith(pair[1])

                    newPop.append(child1)

                    if (len(newPop) == len(self.population)):
                        break

                    newPop.append(child2)

                    if (len(newPop) == len(self.population)):
                        break

            print("New pop lenght: %d" % len(newPop))

            self.population = newPop

            t.AddTime("Iteration %d" % it)

            wx.CallAfter(self.listener.UpdateProgress, it)

        # 7. Ultima condición de parada, fin de las iteraciones
        # Si no encontré una solución antes, uso la mejor despues del proceso
        if self.bestIndividual is None:
            minFit = np.argmax(self.fitness)
            self.bestIndividual = self.population[minFit]

        t.AddTime("End")

        t.PrintTimes()

        print('DEBUG - Fitness: %s' % self.fitness[minFit])
Пример #59
0
class JdSeckill(object):
    def __init__(self):
        self.spider_session = SpiderSession()
        self.spider_session.load_cookies_from_local()

        self.qrlogin = QrLogin(self.spider_session)

        # 初始化信息
        self.sku_id = global_config.getRaw('config', 'sku_id')
        self.seckill_num = 2
        self.seckill_init_info = dict()
        self.seckill_url = dict()
        self.seckill_order_data = dict()
        self.timers = Timer()

        self.session = self.spider_session.get_session()
        self.user_agent = self.spider_session.user_agent
        self.nick_name = None

    def login_by_qrcode(self):
        """
        二维码登陆
        :return:
        """
        if self.qrlogin.is_login:
            logger.info('登录成功')
            return

        self.qrlogin.login_by_qrcode()

        if self.qrlogin.is_login:
            self.nick_name = self.get_username()
            self.spider_session.save_cookies_to_local(self.nick_name)
        else:
            raise SKException("二维码登录失败!")

    def check_login(func):
        """
        用户登陆态校验装饰器。若用户未登陆,则调用扫码登陆
        """
        @functools.wraps(func)
        def new_func(self, *args, **kwargs):
            if not self.qrlogin.is_login:
                logger.info("{0} 需登陆后调用,开始扫码登陆".format(func.__name__))
                self.login_by_qrcode()
            return func(self, *args, **kwargs)
        return new_func

    @check_login
    def reserve(self):
        """
        预约
        """
        self._reserve()

    @check_login
    def seckill(self):
        """
        抢购
        """
        self._seckill()

    @check_login
    def seckill_by_proc_pool(self, work_count=5):
        """
        多进程进行抢购
        work_count:进程数量
        """
        with ProcessPoolExecutor(work_count) as pool:
            for i in range(work_count):
                pool.submit(self.seckill)

    def _reserve(self):
        """
        预约
        """
        while True:
            try:
                self.make_reserve()
                break
            except Exception as e:
                logger.info('预约发生异常!', e)
            wait_some_time()

    def _seckill(self):
        """
        抢购
        """
        while True:
            try:
                self.request_seckill_url()
                while True:
                    self.request_seckill_checkout_page()
                    self.submit_seckill_order()
            except Exception as e:
                logger.info('抢购发生异常,稍后继续执行!', e)
            wait_some_time()

    def make_reserve(self):
        """商品预约"""
        logger.info('商品名称:{}'.format(self.get_sku_title()))
        url = 'https://yushou.jd.com/youshouinfo.action?'
        payload = {
            'callback': 'fetchJSON',
            'sku': self.sku_id,
            '_': str(int(time.time() * 1000)),
        }
        headers = {
            'User-Agent': self.user_agent,
            'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id),
        }
        resp = self.session.get(url=url, params=payload, headers=headers)
        resp_json = parse_json(resp.text)
        reserve_url = resp_json.get('url')
        self.timers.start()
        while True:
            try:
                self.session.get(url='https:' + reserve_url)
                logger.info('预约成功,已获得抢购资格 / 您已成功预约过了,无需重复预约')
                if global_config.getRaw('messenger', 'enable') == 'true':
                    success_message = "预约成功,已获得抢购资格 / 您已成功预约过了,无需重复预约"
                    send_wechat(success_message)
                break
            except Exception as e:
                logger.error('预约失败正在重试...')

    def get_username(self):
        """获取用户信息"""
        url = 'https://passport.jd.com/user/petName/getUserInfoForMiniJd.action'
        payload = {
            'callback': 'jQuery{}'.format(random.randint(1000000, 9999999)),
            '_': str(int(time.time() * 1000)),
        }
        headers = {
            'User-Agent': self.user_agent,
            'Referer': 'https://order.jd.com/center/list.action',
        }

        resp = self.session.get(url=url, params=payload, headers=headers)

        try_count = 5
        while not resp.text.startswith("jQuery"):
            try_count = try_count - 1
            if try_count > 0:
                resp = self.session.get(url=url, params=payload, headers=headers)
            else:
                break
            wait_some_time()
        # 响应中包含了许多用户信息,现在在其中返回昵称
        # jQuery2381773({"imgUrl":"//storage.360buyimg.com/i.imageUpload/xxx.jpg","lastLoginTime":"","nickName":"xxx","plusStatus":"0","realName":"xxx","userLevel":x,"userScoreVO":{"accountScore":xx,"activityScore":xx,"consumptionScore":xxxxx,"default":false,"financeScore":xxx,"pin":"xxx","riskScore":x,"totalScore":xxxxx}})
        return parse_json(resp.text).get('nickName')

    def get_sku_title(self):
        """获取商品名称"""
        url = 'https://item.jd.com/{}.html'.format(global_config.getRaw('config', 'sku_id'))
        resp = self.session.get(url).content
        x_data = etree.HTML(resp)
        sku_title = x_data.xpath('/html/head/title/text()')
        return sku_title[0]

    def get_seckill_url(self):
        """获取商品的抢购链接
        点击"抢购"按钮后,会有两次302跳转,最后到达订单结算页面
        这里返回第一次跳转后的页面url,作为商品的抢购链接
        :return: 商品的抢购链接
        """
        url = 'https://itemko.jd.com/itemShowBtn'
        payload = {
            'callback': 'jQuery{}'.format(random.randint(1000000, 9999999)),
            'skuId': self.sku_id,
            'from': 'pc',
            '_': str(int(time.time() * 1000)),
        }
        headers = {
            'User-Agent': self.user_agent,
            'Host': 'itemko.jd.com',
            'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id),
        }
        while True:
            resp = self.session.get(url=url, headers=headers, params=payload)
            resp_json = parse_json(resp.text)
            if resp_json.get('url'):
                # https://divide.jd.com/user_routing?skuId=8654289&sn=c3f4ececd8461f0e4d7267e96a91e0e0&from=pc
                router_url = 'https:' + resp_json.get('url')
                # https://marathon.jd.com/captcha.html?skuId=8654289&sn=c3f4ececd8461f0e4d7267e96a91e0e0&from=pc
                seckill_url = router_url.replace(
                    'divide', 'marathon').replace(
                    'user_routing', 'captcha.html')
                logger.info("抢购链接获取成功: %s", seckill_url)
                return seckill_url
            else:
                logger.info("抢购链接获取失败,稍后自动重试")
                wait_some_time()

    def request_seckill_url(self):
        """访问商品的抢购链接(用于设置cookie等"""
        logger.info('用户:{}'.format(self.get_username()))
        logger.info('商品名称:{}'.format(self.get_sku_title()))
        self.timers.start()
        self.seckill_url[self.sku_id] = self.get_seckill_url()
        logger.info('访问商品的抢购连接...')
        headers = {
            'User-Agent': self.user_agent,
            'Host': 'marathon.jd.com',
            'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id),
        }
        self.session.get(
            url=self.seckill_url.get(
                self.sku_id),
            headers=headers,
            allow_redirects=False)

    def request_seckill_checkout_page(self):
        """访问抢购订单结算页面"""
        logger.info('访问抢购订单结算页面...')
        url = 'https://marathon.jd.com/seckill/seckill.action'
        payload = {
            'skuId': self.sku_id,
            'num': self.seckill_num,
            'rid': int(time.time())
        }
        headers = {
            'User-Agent': self.user_agent,
            'Host': 'marathon.jd.com',
            'Referer': 'https://item.jd.com/{}.html'.format(self.sku_id),
        }
        self.session.get(url=url, params=payload, headers=headers, allow_redirects=False)

    def _get_seckill_init_info(self):
        """获取秒杀初始化信息(包括:地址,发票,token)
        :return: 初始化信息组成的dict
        """
        logger.info('获取秒杀初始化信息...')
        url = 'https://marathon.jd.com/seckillnew/orderService/pc/init.action'
        data = {
            'sku': self.sku_id,
            'num': self.seckill_num,
            'isModifyAddress': 'false',
        }
        headers = {
            'User-Agent': self.user_agent,
            'Host': 'marathon.jd.com',
        }
        resp = self.session.post(url=url, data=data, headers=headers)

        resp_json = None
        try:
            resp_json = parse_json(resp.text)
        except Exception:
            raise SKException('抢购失败,返回信息:{}'.format(resp.text[0: 128]))

        return resp_json

    def _get_seckill_order_data(self):
        """生成提交抢购订单所需的请求体参数
        :return: 请求体参数组成的dict
        """
        logger.info('生成提交抢购订单所需参数...')
        # 获取用户秒杀初始化信息
        self.seckill_init_info[self.sku_id] = self._get_seckill_init_info()
        init_info = self.seckill_init_info.get(self.sku_id)
        default_address = init_info['addressList'][0]  # 默认地址dict
        invoice_info = init_info.get('invoiceInfo', {})  # 默认发票信息dict, 有可能不返回
        token = init_info['token']
        data = {
            'skuId': self.sku_id,
            'num': self.seckill_num,
            'addressId': default_address['id'],
            'yuShou': 'true',
            'isModifyAddress': 'false',
            'name': default_address['name'],
            'provinceId': default_address['provinceId'],
            'cityId': default_address['cityId'],
            'countyId': default_address['countyId'],
            'townId': default_address['townId'],
            'addressDetail': default_address['addressDetail'],
            'mobile': default_address['mobile'],
            'mobileKey': default_address['mobileKey'],
            'email': default_address.get('email', ''),
            'postCode': '',
            'invoiceTitle': invoice_info.get('invoiceTitle', -1),
            'invoiceCompanyName': '',
            'invoiceContent': invoice_info.get('invoiceContentType', 1),
            'invoiceTaxpayerNO': '',
            'invoiceEmail': '',
            'invoicePhone': invoice_info.get('invoicePhone', ''),
            'invoicePhoneKey': invoice_info.get('invoicePhoneKey', ''),
            'invoice': 'true' if invoice_info else 'false',
            'password': global_config.get('account', 'payment_pwd'),
            'codTimeType': 3,
            'paymentType': 4,
            'areaCode': '',
            'overseas': 0,
            'phone': '',
            'eid': global_config.getRaw('config', 'eid'),
            'fp': global_config.getRaw('config', 'fp'),
            'token': token,
            'pru': ''
        }

        return data

    def submit_seckill_order(self):
        """提交抢购(秒杀)订单
        :return: 抢购结果 True/False
        """
        url = 'https://marathon.jd.com/seckillnew/orderService/pc/submitOrder.action'
        payload = {
            'skuId': self.sku_id,
        }
        try:
            self.seckill_order_data[self.sku_id] = self._get_seckill_order_data()
        except Exception as e:
            logger.info('抢购失败,无法获取生成订单的基本信息,接口返回:【{}】'.format(str(e)))
            return False

        logger.info('提交抢购订单...')
        headers = {
            'User-Agent': self.user_agent,
            'Host': 'marathon.jd.com',
            'Referer': 'https://marathon.jd.com/seckill/seckill.action?skuId={0}&num={1}&rid={2}'.format(
                self.sku_id, self.seckill_num, int(time.time())),
        }
        resp = self.session.post(
            url=url,
            params=payload,
            data=self.seckill_order_data.get(
                self.sku_id),
            headers=headers)
        resp_json = None
        try:
            resp_json = parse_json(resp.text)
        except Exception as e:
            logger.info('抢购失败,返回信息:{}'.format(resp.text[0: 128]))
            return False
        # 返回信息
        # 抢购失败:
        # {'errorMessage': '很遗憾没有抢到,再接再厉哦。', 'orderId': 0, 'resultCode': 60074, 'skuId': 0, 'success': False}
        # {'errorMessage': '抱歉,您提交过快,请稍后再提交订单!', 'orderId': 0, 'resultCode': 60017, 'skuId': 0, 'success': False}
        # {'errorMessage': '系统正在开小差,请重试~~', 'orderId': 0, 'resultCode': 90013, 'skuId': 0, 'success': False}
        # 抢购成功:
        # {"appUrl":"xxxxx","orderId":820227xxxxx,"pcUrl":"xxxxx","resultCode":0,"skuId":0,"success":true,"totalMoney":"xxxxx"}
        if resp_json.get('success'):
            order_id = resp_json.get('orderId')
            total_money = resp_json.get('totalMoney')
            pay_url = 'https:' + resp_json.get('pcUrl')
            logger.info('抢购成功,订单号:{}, 总价:{}, 电脑端付款链接:{}'.format(order_id, total_money, pay_url))
            if global_config.getRaw('messenger', 'enable') == 'true':
                success_message = "抢购成功,订单号:{}, 总价:{}, 电脑端付款链接:{}".format(order_id, total_money, pay_url)
                send_wechat(success_message)
            return True
        else:
            logger.info('抢购失败,返回信息:{}'.format(resp_json))
            if global_config.getRaw('messenger', 'enable') == 'true':
                error_message = '抢购失败,返回信息:{}'.format(resp_json)
                send_wechat(error_message)
            return False
Пример #60
0
	def clock(self):
		'''
		Return clock
		'''
		self.tmp = self.label.after(200, self.clock)
		self.label['text'] = Timer.set_clock(self)