Beispiel #1
0
def timeTrial(n):
    a = stdarray.create1D(n, 0)
    for i in range(n):
        a[i] = stdrandom.uniformInt(-1000000, 1000000)
    watch = Stopwatch()
    count = threesum.countTriples(a)
    return watch.elapsedTime()
Beispiel #2
0
def timeTrial(n):
    a = stdarray.create1D(n, 0)
    for i in range(n):
        a[i] = stdrandom.uniformInt(-1000000, 1000000)
    watch = Stopwatch()
    count = threesum.countTriples(a)
    return watch.elapsedTime()
Beispiel #3
0
    def testDuration(self):
        """Tests that the duration results works as expected"""
        stopwatch = Stopwatch()
        time.sleep(1)
        stopwatch.stop()

        self.assertTrue(stopwatch.duration >= 1)
Beispiel #4
0
    def new(self):
        # start a new game
        self.timer = Stopwatch()
        self.all_sprites = pg.sprite.Group()
        self.platforms = pg.sprite.Group()
        self.enemies = pg.sprite.Group()
        self.player = Player(self)
        self.all_sprites.add(self.player)
        self.last_update = 0
        pg.mixer.music.load(path.join(SOUND, GAME_TRACK))
        pg.mixer.music.play(LOOP)
        pg.mixer.music.set_volume(0.6)
        self.pausedtime = 0

        # Enemies
        for i in range(0):
            m = Enemy(self)
            self.all_sprites.add(m)
            self.enemies.add(m)

        # Platforms
        for plat in PLATFORM_LIST:
            p = Platform(self, *plat)
            self.all_sprites.add(p)
            self.platforms.add(p)

        # Other platforms

        self.run()
class CountingStopwatch2:
    """ This counting stopwatch uses composition instead of 
        inheritance. """
    def __init__(self):
        # Create a stopwatch object to keep the time
        self.watch = Stopwatch()
        # Set number of starts to zero
        self._count = 0

    def start(self):
        # Count this start message unless the watch already is running
        if not self.watch._running:
            self._count += 1
        # Delegate other work to the stopwatch object
        self.watch.start()

    def stop(self):
        # Delegate to stopwatch object
        self.watch.stop()

    def reset(self):
        # Let the stopwatch object reset the time
        watch.reset()
        # Reset the count
        self._count = 0

    def elapsed(self):
        # Delegate to stopwatch object
        return self.watch.elapsed()

    def count(self):
        return self._count
    def test_sanity(self):
        lock1 = threading.RLock()
        lock2 = threading.RLock()
        
        def sleep_and_inc(lock,sleep_time): 
            with synchronize_using(lock):
                time.sleep(sleep_time)
                lock.sync_test_counter = getattr(lock,'sync_test_counter',0) + 1
                
        sleep_time = 0.5
        n = 4
        
        s = Stopwatch()
        lst_threads = []
        for lock in [lock1,lock2]:
            for _ in xrange(n):
                t = threading.Thread(target=sleep_and_inc,args=[lock,sleep_time])
                lst_threads.append(t)
                t.start()

        # wait for all threads, then check results
        for t in lst_threads:
            t.join()
            
        duration = s.duration()
        self.assertEqual(lock1.sync_test_counter,n)
        self.assertEqual(lock2.sync_test_counter,n)
        ideal_time = n*sleep_time
        self.assert_(ideal_time*0.9 < duration < ideal_time*1.1, "duration=%s, ideal=%s" % (duration,ideal_time))
class Game:
    def __init__(self, resources: Resources) -> None:
        self.camera = Vector2d(0, 0)
        self.stopwatch = Stopwatch(resources)

        # Objective 4: Create a Player
        # YOUR CODE HERE...

        # Objective 5: Create a Map
        # YOUR CODE HERE...

    def update(self, controller: Controller) -> None:
        if controller.has_input(Input.RESTART):
            self.stopwatch.reset()

            # Objective 4: Put the player back at the start
            # YOUR CODE HERE...

        # Objective 6: Call the player update method
        # YOUR CODE HERE...

        # Objective 7: Call the move_camera function with a focus on the player position
        # YOUR CODE HERE...

        # Objective 8: Update the stopwatch according to the player tile
        # YOUR CODE HERE...

    def render(self, renderer: Renderer) -> None:
        # Objective 4: Render the player
        # YOUR CODE HERE...

        # Objective 5: Render the tilemap
        # YOUR CODE HERE...

        self.stopwatch.render(renderer)
Beispiel #8
0
def GetDataForCatsFromServer(cat, desc, orgId, orgName, action):
  #action = 'GetData'
  #action = 'GetDataTest'

  reqUrl = base_url + '/api/Search/' + action #GetData

  SearchDataRequest = {
    'ContextTypes': 'Organization',
    'BuiltInCategories': [cat],
    'Version': '2019',
    'OrgId': orgId
  }

  sw = Stopwatch()
  while True:
    verbose = False
    if verbose:
      print("before GetData", SearchDataRequest['BuiltInCategories'], desc, reqUrl )

    r = requests.post( reqUrl, json = SearchDataRequest, headers=headers)
    if r.status_code == 200:
      break

    print("after GetData", r.status_code, orgId, orgName)
    if r.status_code == 401:
      ensureLogin()
    else:
      print(r.text)
      raise  
      break # or even throw?
    sw = Stopwatch() # start new stopwatch.
 
  m = sw.measure(silent=True) 
  return (r,m) 
Beispiel #9
0
class RaisArmTime(Command):

    def __init__(self, robot, raise_speed, stop_time, name=None, timeout=None):
        '''
        Constructor
        '''
        super().__init__(name, timeout)
        self._robot = robot
        self._raise_speed = raise_speed
        self._stop_time = stop_time
        self.requires(robot.arm)
        self._stopwatch = Stopwatch()

    def initialize(self):
        """Called before the Command is run for the first time."""
        self._stopwatch.start()

    def execute(self):
        """Called repeatedly when this Command is scheduled to run"""
        self._robot.arm.move_arm(self._raise_speed)

    def isFinished(self):
        """Returns true when the Command no longer needs to be run"""
        return self._stopwatch.elapsed_time_in_secs() >= self._stop_time

    def end(self):
        """Called once after isFinished returns true"""
        self._robot.arm.move_arm(0)

    def interrupted(self):
        """Called when another command which requires one or more of the same subsystems is scheduled to run"""
        self.end()
    def __init__(self, model, device):

        ie = IECore()
        model_xml = model
        model_bin = os.path.splitext(model_xml)[0] + ".bin"
        net = IENetwork(model=model_xml, weights=model_bin)

        for input_key in net.inputs:
            if len(net.inputs[input_key].layout) == 4:
                self.n, self.c, self.h, self.w = net.inputs[input_key].shape

        assert (len(net.inputs.keys()) == 1 or len(net.inputs.keys())
                == 2), "Sample supports topologies only with 1 or 2 inputs"
        self.out_blob = next(iter(net.outputs))
        self.input_name, input_info_name = "", ""

        for input_key in net.inputs:
            if len(net.inputs[input_key].layout) == 4:
                self.input_name = input_key
                net.inputs[input_key].precision = 'U8'
            elif len(net.inputs[input_key].layout) == 2:
                input_info_name = input_key
                net.inputs[input_key].precision = 'FP32'
                if net.inputs[input_key].shape[1] != 3 and net.inputs[input_key].shape[1] != 6 or \
                        net.inputs[input_key].shape[0] != 1:
                    print(
                        'Invalid input info. Should be 3 or 6 values length.')

        self.data = {}

        if input_info_name != "":
            infos = np.ndarray(shape=(self.n, self.c), dtype=float)
            for i in range(self.n):
                infos[i, 0] = self.h
                infos[i, 1] = self.w
                infos[i, 2] = 1.0
            self.data[input_info_name] = infos

        output_name, output_info = "", net.outputs[next(
            iter(net.outputs.keys()))]
        for output_key in net.outputs:
            if net.layers[output_key].type == "DetectionOutput":
                output_name, output_info = output_key, net.outputs[output_key]

        if output_name == "":
            print("Can't find a DetectionOutput layer in the topology")

        output_dims = output_info.shape
        if len(output_dims) != 4:
            print("Incorrect output dimensions for SSD model")
        max_proposal_count, object_size = output_dims[2], output_dims[3]

        if object_size != 7:
            print("Output item should have 7 as a last dimension")

        output_info.precision = "FP32"

        self.exec_net = ie.load_network(network=net, device_name=device)

        self.watch = Stopwatch()
Beispiel #11
0
    def __init__(self, model):

        # Initialize TRT environment
        self.input_shape = (300, 300)
        trt_logger = trt.Logger(trt.Logger.INFO)
        trt.init_libnvinfer_plugins(trt_logger, '')
        with open(model, 'rb') as f, trt.Runtime(trt_logger) as runtime:
            engine = runtime.deserialize_cuda_engine(f.read())

        self.host_inputs = []
        self.cuda_inputs = []
        self.host_outputs = []
        self.cuda_outputs = []
        self.bindings = []
        self.stream = cuda.Stream()

        for binding in engine:
            size = trt.volume(
                engine.get_binding_shape(binding)) * engine.max_batch_size
            host_mem = cuda.pagelocked_empty(size, np.float32)
            cuda_mem = cuda.mem_alloc(host_mem.nbytes)
            self.bindings.append(int(cuda_mem))
            if engine.binding_is_input(binding):
                self.host_inputs.append(host_mem)
                self.cuda_inputs.append(cuda_mem)
            else:
                self.host_outputs.append(host_mem)
                self.cuda_outputs.append(cuda_mem)
        self.context = engine.create_execution_context()

        self.watch = Stopwatch()
Beispiel #12
0
    def test_n_threads(self):
        sleep_time = 0.1

        class Sleeper(object):
            def __init__(self):
                self._lock = threading.RLock()  # used by @synchronized decorator
                self.i = 0
                self.thread_ids = set()

            @synchronized
            def _critical_section(self):
                self.thread_ids.add(id(threading.currentThread()))
                self.i += 1

            def sleep(self):
                time.sleep(sleep_time)
                self._critical_section()

        n_threads = 5
        n_calls = 20
        ao = AO.AO(Sleeper(), n_threads)
        ao.start()
        self.aos_to_stop.append(ao)

        s = Stopwatch()
        futures = [ao.sleep() for i in xrange(n_calls)]
        for f in futures:
            f.get()
        duration = s.duration()
        expected = sleep_time * n_calls / float(n_threads)
        self.assert_(0.9 * expected < duration < 1.2 * expected, "duration=%s, expected=%s" % (duration, expected))
        self.assertEqual(ao.obj.i, n_calls)
        self.assertEqual(len(ao.obj.thread_ids), n_threads)
        self.failIf(id(threading.currentThread()) in ao.obj.thread_ids)
Beispiel #13
0
	def run(self, img, step=None, debug=False, print_time=False, filename='unknown'):
		self.debug_out_list = []
		self.source = img
		funcs_to_run = self.functions[:step]
		output = self.source
		stopwatch = Stopwatch()
		log_string = '{}\t{: <16}\t{:.04f}s   {:.02f} fps'
		for func in funcs_to_run:
			if debug:
				output, output_debug = func.run(debug, input=output)
				self.debug_out_list.append(output_debug)
			else:
				output = func.run(debug, input=output)
			t = stopwatch.round()
			if print_time:
				fps = 1 / t if t != 0 else 999
				print(log_string.format(filename, str(func), t, fps))
			
		t = stopwatch.total()
		fps = 1 / t if t != 0 else 999
		print(Fore.YELLOW + log_string.format(filename, 'TOTAL', t, fps) + Fore.RESET)
		print() if print_time else None

		if debug:
			return self.debug_out_list[-1]
		else:
			return output
Beispiel #14
0
    def do_GET(self):
        if 0:
          self.send_response(200)
          self.end_headers()
          self.wfile.write(b'fast')
          return

        watch = Stopwatch()
        global ourData 

        try:
          args = self.path.split('?')
          if len(args)<2:
            print("no size arg", args)
            return
          sizearg = int(args[1])

          front = '[%s]\n' % sizearg
        except Exception as e:
          self.send_response(500)
          self.end_headers()
          err_out = str(e).encode()
          self.wfile.write(err_out)
          return

        self.send_response(200)
        self.end_headers()

        self.wfile.write(front.encode())

        #print('len:', len(ourData.slices.get(sizearg,'missing')))
        self.wfile.write( ourData.slices.get(sizearg,'missing') )
        watch.measure()
Beispiel #15
0
    def add_widgets(self):
        # Tabbed view
        self.notebook = ttk.Notebook(self)
        self.notebook.pack(fill=tk.BOTH, expand=1)
        self.notebook.bind("<<NotebookTabChanged>>", self.manage_threads)

        # First Tab: Alarms
        self.alarms = Alarms(self.notebook)
        self.protocol("WM_DELETE_WINDOW", self.on_close)
        self.alarms.pack(fill=tk.BOTH, expand=1)
        self.notebook.add(self.alarms, text="Alarms")

        # Second Tab: Clock (Hopefully will add analog and digital)
        self.clock = Clock(self.notebook)
        self.clock.pack(fill=tk.BOTH, expand=1)
        self.notebook.add(self.clock, text="Clock")

        # Third Tab: Stopwatch
        self.stopwatch = Stopwatch(self.notebook)
        self.stopwatch.pack(fill=tk.BOTH, expand=1)
        self.notebook.add(self.stopwatch, text="Stopwatch")

        # Fourth Tab: Timer
        self.timer = Timer(self.notebook)
        self.timer.pack(fill=tk.BOTH, expand=1)
        self.notebook.add(self.timer, text="Timer")
Beispiel #16
0
 def __init__(self, robot, duration, speed, name=None, timeout=15):
     """Constructor"""
     super().__init__(name, timeout)
     self.robot = robot
     self.requires(robot.drivetrain)
     self._stopwatch = Stopwatch()
     self._duration = duration
     self._speed = speed
Beispiel #17
0
async def help(ctx: commands.Context):
    Console.printc(f"user: {ctx.author} Started help", Fore.LIGHTBLUE_EX)

    sw = Stopwatch()
    await ctx.send(f"Help: ```{tabulate(HELP_LIST, headers=[' ', ' '], stralign='left', tablefmt='plain')}```")

    Console.log("SYS (help)", f"Total time taken: {round(sw.duration * 1000)} ms")
    sw.reset()
Beispiel #18
0
async def version(ctx: commands.Context):
    Console.printc(f"user: {ctx.author} Started version", Fore.LIGHTBLUE_EX)

    sw = Stopwatch()
    await send_msg(ctx, f"```yaml\nVersion: {VERSION}\n```")

    Console.log("SYS (version)", f"Total time taken: {round(sw.duration * 1000)} ms")
    sw.reset()
Beispiel #19
0
    def testDigits(self):
        """Tests that the string contains the correct precision"""
        stopwatch = Stopwatch(4)
        time.sleep(1)
        stopwatch.stop()

        # e.g 5.7282s
        self.assertTrue(len(str(stopwatch)) == 7)
    def time_trial(n):
        a = []
        for i in range(0, n):
            a.append(random.randint(-MAXIMUM_INTEGER, MAXIMUM_INTEGER))

        stopwatch = Stopwatch()
        ThreeSum.count(a)
        return stopwatch.elapsed_time()
Beispiel #21
0
    def __init__(self, resources: Resources) -> None:
        self.camera = Vector2d(0, 0)
        self.stopwatch = Stopwatch(resources)

        # Objective 4: Create a Player
        self.player = Player(resources)

        # Objective 5: Create a Map
        self.map = Map(resources)
 def test_no_sync(self):
     stopwatch = Stopwatch()
     threading.Thread(target=self.s.add,args=[10]).start()
     time.sleep(0.05) # make sure other thread gets head start
     val = self.s.add(5)
     self.assertEqual(val,0)
     
     duration = stopwatch.duration()
     self.assert_(duration < 1.2*self.s.sleep_time, 'calls took too long. duration=%s' % duration)
Beispiel #23
0
 def testStop(self):
     """Tests stopwatch's stopped state"""
     stopwatch = Stopwatch()
     stopwatch.stop()
     now = str(stopwatch)
     time.sleep(0.1)
     after = str(stopwatch)
     # A stopped stopwatch should not move
     self.assertEqual(now, after)
 def test_normal(self):
     stopwatch = Stopwatch()
     threading.Thread(target=self.s.sync_add,args=[10]).start()
     time.sleep(0.05) # make sure other thread gets head start (and the mutex)
     val = self.s.sync_add(5)
     self.assertEqual(val,10)
     
     duration = stopwatch.duration()
     self.assert_(duration > 1.9*self.s.sleep_time, 'calls completed too quickly. duration=%s' % duration)
def timeTrials(f, n, trials):
    total = 0.0
    a = stdarray.create1D(n, 0.0)
    for t in range(trials):
        for i in range(n):
            a[i] = stdrandom.uniformFloat(0.0, 1.0)
        watch = Stopwatch()
        f(a)
        total += watch.elapsedTime()
    return total
Beispiel #26
0
def main():
    killhandler = KillHandler()

    reddit = praw.Reddit(client_id=config.client_id,
                         client_secret=config.client_secret,
                         username=config.username,
                         password=config.password,
                         user_agent=config.user_agent)

    logging.info("Starting checking submissions...")

    stopwatch = Stopwatch()

    while not killhandler.killed:
        try:
            for submission in reddit.subreddit('+'.join(
                    config.subreddits)).stream.submissions(skip_existing=True):
                duration = stopwatch.measure()

                logging.info(f"New submission: {submission}")
                logging.info(f" -- retrieved in {duration:5.2f}s")

                # We don't need to post a sticky on stickied posts
                if submission.stickied:
                    logging.info(f" -- skipping (stickied)")
                    continue

                # Post a comment to let people know where to invest
                bot_reply = submission.reply_wrap(message.invest_place_here)

                # Sticky the comment
                if config.is_moderator:
                    bot_reply.mod.distinguish(how='yes', sticky=True)

                # Measure how long processing took
                duration = stopwatch.measure()
                logging.info(f" -- processed in {duration:5.2f}s")

                if killhandler.killed:
                    logging.info("Termination signal received - exiting")
                    break

        except prawcore.exceptions.OAuthException as e_creds:
            traceback.print_exc()
            logging.error(e_creds)
            logging.critical("Invalid login credentials. Check your .env!")
            logging.critical(
                "Fatal error. Cannot continue or fix the problem. Bailing out..."
            )
            exit()

        except Exception as e:
            logging.error(e)
            traceback.print_exc()
            time.sleep(10)
Beispiel #27
0
    def testStopwatch(self):
        """Tests stopwatch timing"""
        stopwatch = Stopwatch()
        time.sleep(0.1)
        stopwatch.stop()
        m = str(stopwatch)

        # Can't gurantee exact timings as python speed may differ each execution
        # so ensure it is atleast a 100ms
        # also a test for friendly time string
        self.assertTrue(m.startswith("100") and m.endswith("ms"))
Beispiel #28
0
async def constructors_standings(ctx: commands.Context):
    Console.printc(f"user: {ctx.author} Started constructors_standings", Fore.LIGHTBLUE_EX)

    sw = Stopwatch()

    cs = API.Get.constructor_standings()

    Console.log("constructors_standings", cs)
    await send_msg(ctx, f"Constructors Standings:\n```{cs}```")

    Console.log("SYS (constructors_standings)", f"Total time taken: {round(sw.duration * 1000)} ms")
    sw.reset()
Beispiel #29
0
async def calendar(ctx: commands.Context):
    Console.printc(f"user: {ctx.author} Started calendar", Fore.LIGHTBLUE_EX)

    sw = Stopwatch()

    _calendar = API.Get.calendar()

    Console.log("calendar", _calendar)
    await send_msg(ctx, f"Calendar:\n```{_calendar}```")

    Console.log("SYS (calendar)", f"Total time taken: {round(sw.duration * 1000)} ms")
    sw.reset()
Beispiel #30
0
async def driver_standings(ctx: commands.Context):
    Console.printc(f"user: {ctx.author} Started driver_standings", Fore.LIGHTBLUE_EX)

    sw = Stopwatch()

    ds = API.Get.driver_standings()

    Console.log("driver_standings", ds)
    await send_msg(ctx, f"Driver Standings:\n```{ds}```")

    Console.log("SYS (driver_standings)", f"Total time taken: {round(sw.duration * 1000)} ms")
    sw.reset()
Beispiel #31
0
async def last_qualifying_results(ctx: commands.Context):
    Console.printc(f"user: {ctx.author} Started last_qualifying_results", Fore.LIGHTBLUE_EX)

    sw = Stopwatch()

    lqr = API.Get.last_qualifying_results()

    Console.log("last_qualifying_results", lqr[1])
    await send_msg(ctx, f"Last Qualifying Results: {lqr[0]}\n```{lqr[1]}```")

    Console.log("SYS (last_qualifying_results)", f"Total time taken: {round(sw.duration * 1000)} ms")
    sw.reset()
Beispiel #32
0
async def following_week(ctx: commands.Context):
    Console.printc(f"user: {ctx.author} Started following_week", Fore.LIGHTBLUE_EX)

    sw = Stopwatch()

    race_info = f"Following Week:\n```json\n{API.Get.next_week()}```"

    Console.log("following_week", race_info)
    await send_msg(ctx, race_info)

    Console.log("SYS (following_week)", f"Total time taken: {round(sw.duration * 1000)} ms")
    sw.reset()
Beispiel #33
0
async def current(ctx: commands.Context):
    Console.printc(f"user: {ctx.author} Started current", Fore.LIGHTBLUE_EX)

    sw = Stopwatch()

    race_info = f"```json\n{API.Get.current()}```"

    Console.log("current", race_info)
    await send_msg(ctx, race_info)

    Console.log("SYS (current)", f"Total time taken: {round(sw.duration * 1000)} ms")
    sw.reset()
Beispiel #34
0
    def test_timeout(self):
        # preset future - should return within timeout
        f = future.Future.preset(3)
        self.assertEqual(f.get(100),3)

        # unset future - should raise exception
        timeout = 1 # timeout in seconds
        f = future.Future()
        stopwatch = Stopwatch()
        stopwatch.start()
        self.assertRaises(future.FutureTimeoutException,f.get,timeout*1000)
        duration = stopwatch.duration()
        self.assert_(0.9*timeout < duration < 1.3*timeout, 'duration=%s' % duration)  
Beispiel #35
0
def doDB_Work(limit=9999):
  dbServer = r'jg-pc\jg1' 
  dbName = 'Ajour_System_A/S_10aee6e8b7dd4f4a8fd0cbf9cedf91cb'

  theDBCfg = { 'server': dbServer, 'db': dbName, 'user': '******', 'pwd': 'morOg234' }

  with getConn(theDBCfg) as conn:
    csr = conn.cursor()

    sw = Stopwatch()
    a = selectFromDB(csr) 
    sw.measure()
    print(len(a))
Beispiel #36
0
async def uptime(ctx: commands.Context):
    global START_TIME
    Console.printc(f"user: {ctx.author} Started uptime", Fore.LIGHTBLUE_EX)

    sw = Stopwatch()

    timedelta = datetime.now() - START_TIME

    Console.log("uptime", f"Uptime: {timedelta}")
    await send_msg(ctx, f"Uptime: ```json\n{timedelta}```")

    Console.log("SYS (uptime)", f"Total time taken: {round(sw.duration * 1000)} ms")
    sw.reset()
Beispiel #37
0
 async def _ping(self, ctx):
     stopwatch_banco = Stopwatch()
     async with self.bot.db_connection.acquire() as conn:
         await conn.fetch('select version();')
     stopwatch_banco.stop()
     e1 = discord.Embed(
         title=f'Calculando ping {self.bot.emoji("loading")}',
         colour=discord.Colour.random(),
         timestamp=datetime.utcnow())
     e1.set_footer(text=f'{ctx.author}',
                   icon_url=f'{ctx.author.avatar_url}')
     stopwatch_message = Stopwatch()
     mensagem_do_bot = await ctx.reply(embed=e1, mention_author=False)
     stopwatch_message.stop()
     e2 = discord.Embed(
         title=
         f'🏓 Latência da API: {prettify_number(int(self.bot.latency * 1000))}ms!\n'
         f'{self.bot.emoji("database")} Tempo de resposta do banco: {stopwatch_banco}!\n'
         f'📥 Tempo de resposta no discord: {stopwatch_message}!',
         colour=discord.Colour.random(),
         timestamp=datetime.utcnow())
     e2.set_footer(text=f'{ctx.author}',
                   icon_url=f'{ctx.author.avatar_url}')
     await asyncio.sleep(stopwatch_message.duration * 2)
     await mensagem_do_bot.edit(
         embed=e2,
         allowed_mentions=discord.AllowedMentions(replied_user=False))
Beispiel #38
0
def getBCbyVsId(
  vsId = 'B14462',
  releaseId='624d9489-0f8c-48db-99f9-67701a040742'
 ):
  global headers, url
  bcUrl = url + '/api/v1/BuildingComponent/VSID/{vsId}/Release/{releaseId}'.format(vsId=vsId, releaseId=releaseId)
  watch = Stopwatch('req')
  r = requests.get( bcUrl, headers=headers)
  watch.measure()
  logIfBad(r)
  exes = json.loads(r.text)
  print(len(r.text))
  if 0:
    pprint.pprint(exes)
def evaluate(function, eval_func, test_perc=1.0, seed=0, **kwargs):
    masks_path = 'data_test/paintings_gt/masks'
    imgs_path = 'data_test/paintings_gt/imgs'
    random.seed(seed)

    all_imgs = all_files_in(imgs_path)
    all_masks = all_files_in(masks_path)

    dice_vals = []
    tversky_vals = []
    specificity_vals = []
    presicion_vals = []
    recall_vals = []
    iou_vals = []
    filenames = []

    if test_perc == 1.0:
        pairs = list(zip(all_imgs, all_masks))
    else:
        pairs = random.sample(list(zip(all_imgs, all_masks)),
                              int(len(all_imgs) * test_perc))

    watch = Stopwatch()
    for i, (paint_path, mask_path) in enumerate(pairs):
        sys.stdout.write("\033[K")
        filename = os.path.basename(paint_path)
        mask = xml2img(mask_path)
        if mask is None:
            print(f'  [{i + 1}/{len(pairs)}] ERROR "{filename}"', end='\r')
            continue
        paint = cv2.imread(paint_path)
        out = function(paint, **kwargs)
        # out = np.zeros_like(mask) + 255
        dice, tversky, specificity, presicion, recall, iou = eval_func(
            out, mask)
        dice_vals.append(dice)
        tversky_vals.append(tversky)
        specificity_vals.append(specificity)
        presicion_vals.append(presicion)
        recall_vals.append(recall)
        iou_vals.append(iou)
        print(
            f'  [{i + 1}/{len(pairs)}] dice={mean(dice_vals):0.4f} tversky={mean(tversky_vals):0.4f} specificity={mean(specificity_vals):0.4f} presicion={mean(presicion_vals):0.4f} recall={mean(recall_vals):0.4f} iou={mean(iou_vals):0.4f} time={watch.total():.0f}s of "{filename}"',
            end='\r')
    sys.stdout.write("\033[K")
    time = watch.total()
    print(' '.join([f'({i}, {v:0.3f})' for i, v in enumerate(dice_vals, 1)]))
    return dice_vals, filenames, mean(dice_vals), mean(tversky_vals), mean(
        specificity_vals), mean(presicion_vals), mean(recall_vals), mean(
            iou_vals), time
Beispiel #40
0
def compute_fitness(representation, chunk):
    sw = Stopwatch()
    sw.start()
    score = 0
    gene_ct = 0
    covered_pts = set([])
    for color in representation.keys():
        lab_c1 = to_lab_color(color)
        sw2 = Stopwatch()

        sw2.start()
        for allele in representation[color]:
            gene_ct += 1
            pts = allele.allele_pts()
            for pt in pts:
                pt_color = to_lab_color(TARGET_ARRAY[chunk][pt[0], pt[1]])
                dist = color_distance(lab_c1, pt_color)
                # print("pt {} draw {} dist {}".format(color, pt_color, dist))
                score += 50 - dist
                if pt in covered_pts:
                    score -= 1000
                covered_pts.add(pt)
        # print("color {}".format(sw2.reset()))
    # score -= gene_ct ** 2
    score -= (PAPER_WIDTH * PAPER_HEIGHT - len(covered_pts))
    #print("fitness in {}".format(sw.reset()))
    if gene_ct > 0:
        return score
    return -1e128
Beispiel #41
0
async def clear(ctx: commands.Context):
    Console.printc(f"user: {ctx.author} Started clear", Fore.LIGHTBLUE_EX)

    sw = Stopwatch()
    messages = await ctx.message.channel.history().flatten()

    Console.log(f"clear", f"Msg list length {len(messages)}")

    for message in messages:
        time.sleep(0.2)  # To avoid rate limit
        if message.author.bot or message.content[:len(USER_CFG.prefix)] == USER_CFG.prefix:
            await message.delete()

    Console.log("SYS (clear)", f"Total time taken: {round(sw.duration * 1000)} ms")
    sw.reset()
Beispiel #42
0
def getBC_chunk(chunkSet):
  global headers, url
  bcUrl = url + '/api/v1/BuildingComponent/VSIDs/Release/624d9489-0f8c-48db-99f9-67701a040742?' + chunkSet #bcArgs
  print(bcUrl)
  #return
  watch = Stopwatch('req')
  r = requests.post( bcUrl, headers=headers)
  watch.measure()
  logIfBad(r)
  exes = json.loads(r.text)
  print('len:', len(r.text))
  with open( 'BCs.json', "w") as outfile:
    json.dump(exes, outfile, indent=2)
  if 0:
    pprint.pprint(exes)
Beispiel #43
0
def getBCs(
  releaseId='624d9489-0f8c-48db-99f9-67701a040742'
):
  global headers, url
  bcUrl = url + '/api/v1/BuildingComponent/VSIDs/Release/{releaseId}?VSID1=B33321&VSID2=B96932&VSID3=B75326&VSID4=B36547&VSID5=B20553&VSID6=B59061&VSID7=B58491&VSID8=B80296&VSID9=B81223'.format(releaseId=releaseId)
  print(bcUrl)
  watch = Stopwatch('req')
  r = requests.post( bcUrl, headers=headers)
  watch.measure()
  logIfBad(r)
  exes = json.loads(r.text)
  print(len(r.text))
  with open( 'BCs.json', "w") as outfile:
    json.dump(exes, outfile, indent=2)
  if 0:
    pprint.pprint(exes)
Beispiel #44
0
def getBCbyGroup(  # get the BCs within a BC-group.
  groupId = 'B14462',
  releaseId='624d9489-0f8c-48db-99f9-67701a040742'
):
  global headers, url
  bcUrl = url + '/api/v1/BuildingComponent/BuildingComponentGroup/{groupId}/Release/{releaseId}'.format(groupId=groupId, releaseId=releaseId)
  watch = Stopwatch('req')
  r = requests.get( bcUrl, headers=headers)
  watch.measure(show=False)
  logIfBad(r)
  exes = json.loads(r.text)
  if 0:
    print(len(r.text))
  if 0:
    pprint.pprint(exes)
  exes = exes['buildingComponents']
  return exes
Beispiel #45
0
def getPrices():
  global headers, url
  releaseID = '624d9489-0f8c-48db-99f9-67701a040742'
  priceUrl = url + '/api/v1/BuildingComponent/Calculate/Release/%s?' % releaseID
  priceUrl += 'id1=d03b8b89-fb70-47da-9a18-011132b22921&id2=32e920bb-e927-4a10-ad85-14c32bd197ff&id3=3dbf3ce5-f7e5-4745-bf18-1bd766c1b54d'
  priceUrl += '&amount1=10&amount2=10&amount3=10'
  priceUrl += "&yourCalculationId=1246" #{myRandomCalculationNumber}
  print(priceUrl)
  watch = Stopwatch('req')
  r = requests.post( priceUrl, headers=headers)
  watch.measure()
  logIfBad(r)
  prices = json.loads(r.text)
  if 0:
    pprint.pprint(prices)
  with open( 'prices.json', "w") as outfile:
    json.dump(prices, outfile, indent=2)
Beispiel #46
0
def getPrice_chunk(chunkSet, chunkIx):
  global headers, url
  releaseID = '624d9489-0f8c-48db-99f9-67701a040742'
  priceUrl = url + '/api/v1/BuildingComponent/Calculate/Release/%s?' % releaseID
  priceUrl += chunkSet

  print(chunkIx, priceUrl)
  #return
  watch = Stopwatch('req')
  r = requests.post( priceUrl, headers=headers)
  watch.measure()
  logIfBad(r)
  prices = json.loads(r.text)
  if 0:
    pprint.pprint(prices)
  with open( 'prices.json', "w") as outfile:
    json.dump(prices, outfile, indent=2)
Beispiel #47
0
 def init(self):
     self.initStyles()
     self.initMaps()
     Terrain.initImages()
     Terrain.initSounds()
     self.initMenus()
     self.stopwatch = Stopwatch()
     self.initHelp()
     self.mode = "menu"
     self.menu = self.mainMenu
Beispiel #48
0
def GetToken_Password():  # oauth, exchange a password for a token.
  global env, url
  print(env['username'], env['password'])

  tokenReq = {
    'grant_type':    'password',
    'username':      env['username'], #+'2',
    'password':      env['password'],
    'client_id':     env['client_id'],
    'client_secret': env['client_secret'] #+'2'
  }

  token_url = url + '/token'
  print('before', token_url)
  watch = Stopwatch('req')
  r = requests.post(token_url, tokenReq)
  watch.measure()
  logIfBad(r)
  return r
Beispiel #49
0
 def __init__(self, robot, raise_speed, stop_time, name=None, timeout=None):
     '''
     Constructor
     '''
     super().__init__(name, timeout)
     self._robot = robot
     self._raise_speed = raise_speed
     self._stop_time = stop_time
     self.requires(robot.arm)
     self._stopwatch = Stopwatch()
Beispiel #50
0
 def __init__(self, name=None):
     if name is None:
         self._name_argument_string = ""
     else:
         self._name_argument_string = "(%s)" % name
     self._fps_history = collections.deque(maxlen=10)
     self._previous_time = None
     self._previous_calculated_fps_time = None
     self._stopwatch = Stopwatch()
     self._fps = None
Beispiel #51
0
class FpsMeter:
    print_fps = True
    
    def __init__(self, name=None):
        if name is None:
            self._name_argument_string = ""
        else:
            self._name_argument_string = "(%s)" % name
        self._fps_history = collections.deque(maxlen=10)
        self._previous_time = None
        self._previous_calculated_fps_time = None
        self._stopwatch = Stopwatch()
        self._fps = None

    def update(self):
        self._now = self._stopwatch.get_elapsed_time()
        if self._previous_time is None:
            self._stopwatch.start()
        else:
            self._update_fps_history()
            self._update_fps_if_timely()
        self._previous_time = self._now

    def _update_fps_history(self):
        time_increment = self._now - self._previous_time
        fps = 1.0 / time_increment
        self._fps_history.append(fps)

    def _update_fps_if_timely(self):
        if self._previous_calculated_fps_time:
            if (self._stopwatch.get_elapsed_time() - self._previous_calculated_fps_time) > 1.0:
                self._calculate_fps()
        else:
            self._calculate_fps()

    def _calculate_fps(self):
        self._fps = sum(self._fps_history) / len(self._fps_history)
        if self.print_fps:
            print "FPS%s: %.1f" % (self._name_argument_string, self._fps)
        self._previous_calculated_fps_time = self._stopwatch.get_elapsed_time()

    def get_fps(self):
        return self._fps
Beispiel #52
0
 def __init__(self, robot, duration, speed, ramp_threshold, name=None, timeout=None):
     '''
     Constructor
     '''
     super().__init__(name, timeout)
     self.robot = robot;
     self.requires(robot.drivetrain)
     self._stopwatch = Stopwatch()
     self._duration = duration
     self._speed = speed
     self._ramp_threshold = ramp_threshold
 def __init__(self):
     Behavior.__init__(self)
     self._recall_amount = args.recall_amount
     self.memorize = args.memorize
     self.auto_friction = args.auto_friction
     self._auto_switch_enabled = False
     self.input_only = False
     self._input = None
     self._noise_amount = 0
     self.reset_translation()
     self._stopwatch = Stopwatch()
     self._stopwatch.start()
Beispiel #54
0
 def loadLevel(self):
     terrain, self.startpos = self.maps.load(self.level)
     self.terrain = pygame.sprite.Group(*terrain)
     self.ball = Ball(*self.startpos)
     self.score = 0
     self.stopwatch.restart()
     if self.level != "test":
         highscore = self.progress[self.level]["score"]
         bestTime = self.progress[self.level]["time"]
     else:
         highscore, bestTime = None, None
     self.highscoreText = str(highscore) if highscore != None else "---"
     if bestTime != None:
         self.bestTimeText = Stopwatch.secToMin(bestTime)
     else:
         self.bestTimeText = "---"
Beispiel #55
0
    def __init__(self, experiment):
        QtGui.QMainWindow.__init__(self)
        experiment.window = self
        self._experiment = experiment
        self._layout = QtGui.QVBoxLayout()
        self.setLayout(self._layout)
        self._add_parameter_form()
        self._add_map_view()
        self._create_menu()

        self.stopwatch = Stopwatch()
        self._frame_count = 0
        timer = QtCore.QTimer(self)
        timer.setInterval(1000. / FRAME_RATE)
        QtCore.QObject.connect(timer, QtCore.SIGNAL('timeout()'), self._update)
        timer.start()
Beispiel #56
0
class DriveTime(Command):
    '''
    classdocs
    '''
    _stopwatch = None
    _start_time = None
    _duration = None
    _speed = None
    _ramp_threshold = None

    def __init__(self, robot, duration, speed, ramp_threshold, name=None, timeout=None):
        '''
        Constructor
        '''
        super().__init__(name, timeout)
        self.robot = robot;
        self.requires(robot.drivetrain)
        self._stopwatch = Stopwatch()
        self._duration = duration
        self._speed = speed
        self._ramp_threshold = ramp_threshold

    def initialize(self):
        """Called before the Command is run for the first time."""
        # Start stopwatch
        self._stopwatch.start()
        return Command.initialize(self)

    def execute(self):
        """Called repeatedly when this Command is scheduled to run"""
        speed = self._speed
        time_left = self._duration - self._stopwatch.elapsed_time_in_secs()
        if (time_left < self._ramp_threshold):
            speed = speed * time_left / self._ramp_threshold
        self.robot.drivetrain.arcade_drive(speed, 0.0)
        return Command.execute(self)

    def isFinished(self):
        """Returns true when the Command no longer needs to be run"""
        # If elapsed time is more than duration
        return self._stopwatch.elapsed_time_in_secs() >= self._duration

    def end(self):
        """Called once after isFinished returns true"""
        self._stopwatch.stop()
        # Stop driving
        self.robot.drivetrain.arcade_drive(0.0, 0.0)

    def interrupted(self):
        """Called when another command which requires one or more of the same subsystems is scheduled to run"""
        self.end()
 def evaluate(self,times=None):
     results = []
     s = Stopwatch()
     times = times if times != None else self._times
     for i in range(times):
         self._setup()
         s.reset()
         gc.disable()
         s.start()
         self._code()
         gc.enable()
         results.append(s.read())
     self._evaluate_results = [(min(results),sum(results)/times,max(results))] + [results]
     return self._evaluate_results
    def __init__(self, master=None):
        super().__init__(master)

        # Initialize widgets
        self.create_widgets()

        # Create a Stopwatch interpreter
        with open('stopwatch_external.yaml') as f:
            statechart = import_from_yaml(f)

        # Create a stopwatch object and pass it to the interpreter
        self.stopwatch = Stopwatch()
        self.interpreter = Interpreter(statechart, initial_context={'stopwatch': self.stopwatch})
        self.interpreter.time = time.time()

        # Run the interpreter
        self.run()

        # Update the stopwatch every 100ms
        self.after(100, self.update_stopwatch)
Beispiel #59
0
 def initLevelMenu(self):
     top = 60
     left = 130
     entries = []
     actions = []
     for i, level in enumerate(self.maps.levels):
         prevLevel = self.maps.levels[i - 1]
         if i > 0 and self.progress[prevLevel]["score"] == None:
             entries.append("Level %s    Locked" % level)
             actions.append(None)
             continue
         elif self.progress[level]["score"] == None:
             entries.append("Level %s    Unlocked" % level)
         else:
             entries.append("Level %s    Highscore: %d    Best time: %s" %
                 (level, self.progress[level]["score"],
                     Stopwatch.secToMin(self.progress[level]["time"])))
         # Locally scope level
         actions.append(lambda level=level: self.playLevel(level))
     entries += ["Return to main menu", "Clear progress"]
     actions += [self.doMainMenu, self.progress.clear]
     self.levelMenu = Menu(left, top, entries, actions)
Beispiel #60
0
    def __init__(self, args):
        self.args = args
        self.width = args.width
        self.height = args.height
        self.margin = args.margin
        self.show_fps = args.show_fps
        self.gl_display_mode = GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH
        self._fullscreen = False
        self.exiting = False
        self._frames = []
        self.time_increment = 0
        self.stopwatch = Stopwatch()
        self._frame_count = 0
        self._set_camera_position(CAMERA_POSITION)
        self._set_camera_orientation(CAMERA_Y_ORIENTATION, CAMERA_X_ORIENTATION)
        self.fovy = 45
        self.near = 0.1
        self.far = 100.0
        self._text_renderer_class = getattr(text_renderer_module, TEXT_RENDERERS[args.text_renderer])

        if self.show_fps:
            self.fps_history = collections.deque(maxlen=10)
            self.previous_shown_fps_time = None