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 #2
0
def test_largescale():
    s = Stopwatch()
    integration_factor = 5
    device_map = device_parser.build_device_map(device_parser.parse_data('test.xml'))
    test_size = 10000
    histogram = OrderedDict()
    
    for i in range(5):
        time = 0.0

        for j in range(5):
            s.start()
            generate_test_input(device_map, test_size, file_name='test_input1.csv')
            s.stop()
            print('Generating test input of size {}: '.format(test_size), s.read())
        
            s.reset()
            s.start()
            analyze_data_nograph('csvs/test_input1.csv', integration_factor, device_map)
            s.stop()
            print('Processing input of size {}:     '.format(test_size), s.read())

            time += s.read()
            s.reset()
            
        print('Average time for input of size {}:  '.format(test_size), time/5)
        histogram[test_size] = time/5
        
        test_size *= 2

    print(histogram)
    
    for i,j in histogram.items():
        print(' size | time ')
        print('{0:5d}|{1:5f}'.format(i,j))
Beispiel #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
0
 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 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
Beispiel #14
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 #15
0
class Solver:
    def __init__(self):
        self.stopwatch = Stopwatch()

    def SolveTime(self):
        return str(self.stopwatch)

    def NotEnoughFilledSquaresToSolve(self, grid: Grid):
        return grid.nrSquaresWithValues() < SCS.MINIMUMFILLEDSQUARES

    def Solve(self, grid: Grid, strategy: SolveStrategy) -> bool:
        if self.NotEnoughFilledSquaresToSolve(grid):
            return False
        self.stopwatch.reset()
        self.stopwatch.start()
        return strategy.Solve(grid)
        self.stopwatch.stop()
Beispiel #16
0
class Game:
    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 update(self, controller: Controller) -> None:
        if controller.has_input(Input.RESTART):
            self.stopwatch.reset()

            # Objective 4: Put the player back at the start

            self.player.restart()
        # Objective 6: Call the player update method
        # YOUR CODE HERE...
        self.player.update(controller, self.map)

        # Objective 7: Call the move_camera function with a focus on the player position
        # YOUR CODE HERE...
        move_camera(self.camera, self.player.pos)

        # Objective 8: Update the stopwatch according to the player tile
        # YOUR CODE HERE...
        value = self.map.get_tile(self.player.pos)
        if value == Tile.START:
            self.stopwatch.start()
        elif value == Tile.FINISH:
            self.stopwatch.stop()
        else:
            self.stopwatch.step()

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

        self.stopwatch.render(renderer)
def test_searches(lst):
    from stopwatch import Stopwatch
    timer = Stopwatch()
    # Find each element using ordered linear search
    timer.start()  # Start the clock
    n = len(lst)
    for i in range(n):
        if ordered_linear_search(lst, i) != i:
            print("error")
    timer.stop()  # Stop the clock
    print("Linear elapsed time", timer.elapsed())
    # Find each element using binary search
    timer.reset()  # Reset the clock
    timer.start()  # Start the clock
    n = len(lst)
    for i in range(n):
        if binary_search(lst, i) != i:
            print("error")
    timer.stop()  # Stop the clock
    print("Binary elapsed time", timer.elapsed())
Beispiel #18
0
def main():
    sw = Stopwatch()
    sw.start()
    try:
        os.makedirs("./tmp", exist_ok=True)
        pops = [Population(i) for i in range(374)]
        print("Gen 0 took {} to init".format(sw.reset()))
        for i in range(100):
            print(pops)

            drawing = svgwrite.Drawing(size=(550, 425),
                                       filename='tmp/gen-{}.svg'.format(i))
            inkscape = Inkscape(drawing)
            layers = {}
            [
                pop.add_best_to_drawing(drawing, inkscape, layers)
                for pop in pops
            ]
            drawing.save(pretty=True, indent=2)

            pops = [pop.next_generation() for pop in pops]
            print("Next gen took {}".format(sw.reset()))
    finally:
        THREAD_POOL.shutdown()
Beispiel #19
0
    def collect(self):
        """Collect taxes"""
        logging.info("Fetching investors...")
        stopwatch = Stopwatch()
        investors = self.sess.query(Investor).\
            filter(Investor.completed > 0).\
            all()
        duration = stopwatch.measure()
        logging.info("Investors : %d", len(investors))
        logging.info(" -- fetched in %ss", duration)

        logging.info("Adjusting investors...")
        stopwatch.reset()
        for investor in investors:
            investor.balance = self.adjust_amount(investor)
        duration = stopwatch.measure()
        logging.info(" -- calculated in %ss", duration)

        logging.info("Committing ...")
        stopwatch.reset()
        self.sess.commit()
        self.sess.close()
        duration = stopwatch.measure()
        logging.info(" -- committed in %ss", duration)
Beispiel #20
0
def CheckTimesForN(n):

    times = []
    arrayDetection = Collision_detection_Array()
    arrayStop = Stopwatch()

    hashDetection = Collision_Detection_Spatial_hashing()
    hashStop = Stopwatch()

    skipDetection = Collision_Detection_SkipList()
    skipStop = Stopwatch()

    quadDetection = Collision_Detection_Quad_Tree()
    quadStop = Stopwatch()

    aabbDetection = Collision_detection_AABB()
    aabbStop = Stopwatch()

    binDetection = Collision_Detection_Binary_Tree()
    binStop = Stopwatch()

    r = GetRandomRects(n)
    arrayStop.start()
    arrayResult = arrayDetection.CheckCollisions(r)
    arrayStop.stop()
    arrayTimeNum = arrayStop.time_elapsed()
    times.append(arrayTimeNum)
    arrayStop.reset()

    hashStop.start()
    hashResult = hashDetection.CheckCollisions(r)
    hashStop.stop()
    hashTimeNum = hashStop.time_elapsed()
    times.append(hashTimeNum)
    hashStop.reset()

    skipStop.start()
    skipResult = skipDetection.CheckCollisions(r)
    skipStop.stop()
    skipTimeNum = skipStop.time_elapsed()
    times.append(skipTimeNum)
    skipStop.reset()

    quadStop.start()
    quadResult = quadDetection.CheckCollisions(r)
    quadStop.stop()
    quadTimeNum = quadStop.time_elapsed()
    times.append(quadTimeNum)
    quadStop.reset()

    binStop.start()
    binResult = binDetection.CheckCollisions(r)
    binStop.stop()
    binTimeNum = binStop.time_elapsed()
    times.append(binTimeNum)
    binStop.reset()

    # aabbStop.start()
    # aabbResult = aabbDetection.CheckCollisions(r)
    # aabbStop.stop()
    # aabbTimeNum = aabbStop.time_elapsed()
    # times.append(aabbTimeNum)
    # aabbStop.reset()

    return times
Beispiel #21
0
def main():
    r = auth()
    s = r.subreddit(config.SUBREDDIT)

    df = pd.DataFrame(columns=attr)
    df_old = pd.DataFrame(columns=attr)
    handler = Handler()
    stopwatch = Stopwatch()

    def kill_check():
        if handler.killed:
            logger.info(
                f"Received kill signal {handler.lastSignal} (code {handler.lastSignum})"
            )
            if not config.DRY_RUN:
                logger.info("Writing dataframe to .CSV")
                try:
                    # df.drop(['pickup_no'], axis=1).to_csv(config.DATAFILE, index=False)
                    df.to_csv(config.DATAFILE, index=False)
                except Exception:
                    logger.warning(get_error())
                    logger.warning("Failed to write to CSV.")
                else:
                    logger.info("Successfully wrote dataframe.")
            logger.info("Exited.")

            return True

        else:
            return False

    retries = 0

    while not handler.killed:
        try:
            if retries:
                logger.info(f"Attempting to retry, attempt {retries}...")

            values = df.sort_values(
                'pickup_no', ascending=False).drop_duplicates(
                    subset=['id']).sort_index().reset_index(drop=True)

            row = dict((a, []) for a in attr)

            # There are better ways of doing this entire block. Also it might be slow
            for post_id in values['id'].values:
                stopwatch.reset()

                match_row = values.loc[values['id'] == post_id]
                iteration = match_row['pickup_no'].iloc[0]
                waited = time.time() - match_row['post_pickup'].iloc[0]

                try:
                    time_wait = config.POST_PICKUPS[iteration]
                    logger.debug(
                        f"{post_id}: {waited} / {time_wait} secs,  {iteration} / {len(config.POST_PICKUPS)}"
                    )

                except IndexError:
                    logger.info(f"Hit final iteration of {post_id} @ {len(df.loc[df['id'] == post_id])}x " \
                                 "(should be 18), dropping")
                    df_old = pd.concat(df_old, df.loc[df['id'] == post_id])
                    df.drop(df.loc[df['id'] == post_id].index, inplace=True)
                    continue

                if waited < time_wait:
                    continue

                logger.debug("Post has passed threshold")

                post = r.submission(post_id)
                for _a in p_attr:
                    row[_a].append(getattr(post, _a))
                for _s in s_attr:
                    row[_s].append(getattr(s, _s))
                row['pickup_no'].append(iteration + 1)
                row['post_pickup'].append(match_row['post_pickup'].iloc[0])
                row['time_now'].append(time.time())

                # MAGIC NUMBER 2.5: don't know just threw it in there
                # it's a good estimate for how long it should take to get a post
                if stopwatch.mark() > 2.5 * len(values.index):
                    logger.warning(
                        f'Warning: Slow iteration, {stopwatch.mark()} secs for {len(values.index)} items'
                    )

            row_new = dict((a, []) for a in attr)

            for post in s.new(limit=config.POST_GET_LIMIT):
                if (post.id in df['id'].values) or (post.id
                                                    in df_old['id'].values):
                    logger.debug(f"{post.id} is a duplicate, continuing")
                    continue

                logger.debug(f"Picked up {post.id}")

                for _a in p_attr:
                    row_new[_a].append(getattr(post, _a))
                for _s in s_attr:
                    row_new[_s].append(getattr(s, _s))
                row_new['pickup_no'].append(0)
                row_new['post_pickup'].append(time.time())
                row_new['time_now'].append(time.time())

            logger.debug(f"Old {len(row['id'])} / new {len(row_new['id'])}")

            df_new = pd.DataFrame(row_new, columns=attr)
            df_update = pd.DataFrame(row, columns=attr)

            modified = False if df.equals(df.append(df_new)) and df.equals(
                df.append(df_update)) else True

            df = pd.concat([df, df_new, df_update], ignore_index=True)
            if not config.DRY_RUN:
                # df.drop(['pickup_no'], axis=1).to_csv(config.DATAFILE, index=False)
                df.to_csv(config.DATAFILE, index=False)

            logger.debug(len(df.index))

            del row, row_new
            del df_new, df_update

        except prawcore.exceptions.RequestException:  # You most likely do not need this
            retries += 1
            if retries < len(config.TIMEOUTS):
                logger.warning(
                    f'Connection lost. Waiting for {config.TIMEOUTS[retries-1]} sec...'
                )
                time.sleep(config.TIMEOUTS[retries - 1])
            else:
                logger.critical('Max retries exceeded. Exiting.')
                break

        except Exception:  # Or this
            logger.error(get_error())
            time.sleep(10)

        else:
            if retries:
                logger.info("Connection reestablished")
                retries = 0

            if modified:
                logger.info(
                    f"{len(df.index)} entries, {len(df.drop_duplicates(subset=['id']).index)} unique"
                )

        finally:
            logger.debug(f'{len(values)} unique values')

            rem = r.auth.limits['remaining']
            res = r.auth.limits['reset_timestamp'] - time.time()
            if rem < 5:
                logger.warning('Out of calls! Waiting...')
                for _ in range(int(res + 1)):
                    time.sleep(1)
                    if kill_check():
                        killed = True
                    else:
                        killed = False

                if (res - config.TIMEOUT_SECS) > 0 and not killed:
                    for _ in range(int(res - config.TIMEOUT_SECS)):
                        time.sleep(1)
                        if kill_check():
                            break
            else:
                if modified:
                    logger.info(
                        f"{rem:.0f} calls remaining, {res:.0f} till next reset"
                    )
                    logger.info(
                        f"-- {time.strftime('%Y-%m-%d %H:%M:%S')} on {sys.platform}, pid {os.getpid()}"
                    )
                    logger.info(
                        f"-- Reading from {config.SUBREDDIT}; for more inforation see config.py.\n"
                    )
                for _ in range(config.TIMEOUT_SECS):
                    time.sleep(1)
                    if kill_check():
                        break
Beispiel #22
0
class Window(QWidget):
    """ The Stopwatch window """
    def __init__(self):
        super().__init__()
        self.stopwatch = Stopwatch()
        self.init_window()
        self.updater = ValueUpdater(self)

    def init_window(self):
        """ Initialize window content """

        # Window properties
        self.setGeometry(50, 50, 300, 200)
        self.setWindowTitle('PythonTimer')

        # Label
        self.timer_label = QLabel(self)
        self.timer_label.setText(self.get_formatted_time())
        self.timer_label.setFont(QFont('SansSerif', 20))

        # Push buttons
        self.start_button = QPushButton('Start / Pause', self)
        self.start_button.clicked.connect(self.start_pressed)
        self.reset_button = QPushButton('Reset', self)
        self.reset_button.clicked.connect(self.reset_pressed)

        # Layout

        label_row = QHBoxLayout()
        label_row.addStretch(1)
        label_row.addWidget(self.timer_label)
        label_row.addStretch(1)

        button_row = QHBoxLayout()
        button_row.addStretch(1)
        button_row.addWidget(self.start_button)
        button_row.addWidget(self.reset_button)
        button_row.addStretch(1)

        vert_layout = QVBoxLayout()
        vert_layout.addStretch(1)
        vert_layout.addLayout(label_row)
        vert_layout.addStretch(1)
        vert_layout.addLayout(button_row)

        self.setLayout(vert_layout)

        self.show()

    def start_pressed(self):
        """ Start button behaviour """

        if self.updater.isRunning():
            self.updater.quit()
        else:
            self.updater.start()
        self.stopwatch.start_or_pause()

    def reset_pressed(self):
        """ Reset button behaviour """
        self.stopwatch.reset()

    def get_formatted_time(self):
        """ Get the stopwatch time and format it """
        sec = self.stopwatch.get_time()
        hour = (int)(sec // 3600)
        sec -= hour * 3600
        mins = (int)(sec // 60)
        sec -= mins * 60
        return "{:02d}:{:02d}:{:04.1f}".format(hour, mins, sec)
Beispiel #23
0
#get the address and name of all countries and the instances in a class
for tag in soup.find_all('option'):
    name = tag.text.strip()
    countries.append(Country(name, tag.get('value')[5:7]))

#delete the first two articles (They are not countries)
countries.pop(0)
countries.pop(0)

#Sequential
stopwatch.start()
getActivities(countries)
stopwatch.stop()
print("Duration:", stopwatch.duration)
saveImage("IndustrialSecuencial.png", "AgriculturaSecuencial.png")
stopwatch.reset()

#First Parallel by Jairo Pacheco
list1 = []
list2 = []

mid = len(countries) >> 1

for i in range(0, mid):
    list1.append(countries[i])

for i in range(mid + 1, len(countries)):
    list2.append(countries[i])

stopwatch.start()
Beispiel #24
0
from testRequest import getTimes, addTime

#initializing the GPIO pin 18 to be an input

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)


url = 'https://jeyvj7tvwe.execute-api.us-east-2.amazonaws.com/beta2'
apikey = 'FVTP4xt1vA5Gb66gkIxn99O8RsfTL8KH9BsSuExG'


#initializing the stopwatch and then resetting since creating a stopwatch instance immediately starts he stopwatch clock

sw = Stopwatch()
sw.reset()


rst = True;
running = True;


# Function: quit()
# Param: *args
# This function closes the tkinter instance
def quit(*args):
    root.destroy()

# Function: show_time()
# This function constantly updates the time and checks both system states to start a stopwatch when the button is pressed
# and display a nice message when the button is not pressed (when the dog is being walked).
Beispiel #25
0
def main():
    logging.info("Starting main")

    if config.post_to_reddit:
        logging.info("Warning: Bot will actually post to Reddit!")

    logging.info("Setting up database")

    killhandler = KillHandler()
    engine = create_engine(config.db, pool_recycle=60)
    sm = scoped_session(sessionmaker(bind=engine))
    worker = CommentWorker(sm)

    while True:
        try:
            Base.metadata.create_all(engine)
            break
        except sqlalchemy.exc.OperationalError:
            logging.info("Database not available yet; retrying in 5s")
            time.sleep(5)

    logging.info("Setting up Reddit connection")

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

    stopwatch = Stopwatch()

    logging.info("Listening for inbox replies...")

    while not killhandler.killed:
        try:
            # Iterate over the latest comment replies in inbox
            reply_function = reddit.inbox.comment_replies

            if (config.maintenance):
                logging.info(
                    "ENTERING MAINTENANCE MODE. NO OPERATIONS WILL BE PROCESSED."
                )
                for comment in praw.models.util.stream_generator(
                        reply_function):
                    logging.info(f"New comment {comment}:")
                    if comment.new:
                        comment.reply_wrap(message.maintenance_org)
                        comment.mark_read()

            for comment in praw.models.util.stream_generator(reply_function):
                # Measure how long since we finished the last loop iteration
                duration = stopwatch.measure()
                logging.info(f"New comment {comment}:")
                logging.info(f" -- retrieved in {duration:5.2f}s")

                if comment.new:
                    # Process the comment
                    worker(comment)

                    # Mark the comment as processed
                    comment.mark_read()
                else:
                    logging.info(" -- skipping (already processed)")

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

                # Report the Reddit API call stats
                rem = int(reddit.auth.limits['remaining'])
                res = int(reddit.auth.limits['reset_timestamp'] - time.time())
                logging.info(
                    f" -- API calls remaining: {rem:3d}, resetting in {res:3d}s"
                )

                # Check for termination requests
                if killhandler.killed:
                    logging.info("Termination signal received - exiting")
                    break

                stopwatch.reset()

        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 #26
0
        # r[1].vx += -1

    for i in r:
        i.Move()

    screen.fill((MyColor.black))

    for i in r:
        pygame.draw.rect(screen, (255, 255, 255), i.GetBounds(), 0)

    arrayStop.start()
    arrayResult = arrayDetection.CheckCollisions(r)
    arrayStop.stop()
    arrayTimeNum = arrayStop.time_elapsed()
    arrayTime = myfont.render(str(arrayTimeNum) + ' ms', False, MyColor.white)
    arrayStop.reset()
    screen.blit(arrayLabel, (MyScreen.width * 1.05, 0))
    screen.blit(arrayTime, (MyScreen.width * 1.05, 30))

    hashStop.start()
    hashResult = hashDetection.CheckCollisions(r)
    hashStop.stop()
    hashTimeNum = hashStop.time_elapsed()
    hashTime = myfont.render(
        str(hashTimeNum) + ' ms  ~' +
        str(math.ceil(arrayTimeNum / max(hashTimeNum, 1))) + " Times Faster",
        False, MyColor.white)
    hashStop.reset()
    screen.blit(hashLabel, (MyScreen.width * 1.05, 60))
    screen.blit(hashTime, (MyScreen.width * 1.05, 90))
Beispiel #27
0
class App():
    def __init__(self, master, text):
        self.master = master
        self.text = text
        self.score = 0
        self.characters_correct = 0
        self.errors = 0

        self.username = ""

        self.characters_correct_var = IntVar()
        self.errors_var = IntVar()
        self.stats_variable = StringVar()

        self.stopwatch = Stopwatch()

        # Set up menus
        self.menubar = Menu(self.master)  # Initiate menu template
        self.optionsmenu = Menu(self.menubar)  # Initiate options menu
        self.helpmenu = Menu(self.menubar, tearoff=0)  # Initiate help menu

        # Master Window Sizes
        self.x = 800
        self.y = 600

        # User Monitor Resolution
        self.monitor_width = self.master.winfo_screenwidth()
        self.monitor_height = self.master.winfo_screenheight()

        # Centering window
        self.window_placement(self.master, self.x, self.y)
        # Naming the window
        self.master.title("Speed Typing Test")

        # No-resizable master window
        self.master.resizable(False, False)

        # Adding Background
        self.master.configure(background='#617D6F')

        # Setting up the default screen and labels
        self.title_label = Label(self.master, text="SPEED TYPING GAME")
        self.title_label.place(width=200,
                               height=35,
                               relx=0.5,
                               rely=0.09,
                               anchor='center')

        self.score_label = Label(self.master,
                                 text="Highest Score: {}".format(self.score))
        self.score_label.place(width=200, height=35, relx=0.03, rely=0.9)

        self.stopwatch_label = Label(self.master, bg="#ffffff", fg="#000000")
        self.stopwatch_label.place(height=35,
                                   width=100,
                                   relx=0.07,
                                   rely=0.04,
                                   anchor='center')

        self.time_label = Label(self.master)
        self.time_label.place(height=35,
                              width=100,
                              relx=0.93,
                              rely=0.04,
                              anchor='center')

        # Creating interaction Boxes

        self.input_box = Entry(self.master, font=('Arial', 12), bg="#F8F8FF")
        self.input_box.place(height=30,
                             width=300,
                             relx=0.5,
                             rely=0.5,
                             anchor='center')

        self.input_box.bind("<FocusIn>", lambda x: self.stopwatch_on_typing())
        self.input_box.bind("<FocusOut>", lambda x: self.stopwatch_stop())
        self.input_box.bind("<BackSpace>", lambda x: self.backspace())

        self.text_box = Text(self.master,
                             font=('Arial', 12),
                             bg="#F8F8FF",
                             wrap=WORD)
        self.text_box.place(height=130,
                            width=300,
                            relx=0.5,
                            rely=0.3,
                            anchor='center')
        self.text_box.insert(1.0, self.text)
        self.text_box.config(state=DISABLED)

        reg = self.master.register(self.correct_callback)
        self.input_box.config(validate="key",
                              validatecommand=(reg, '%P', self.text))

        # Set up buttons
        self.start_button = Button(self.master,
                                   text="Press me to start",
                                   command=self.start_with_button)
        self.start_button.place(height=30,
                                width=100,
                                relx=0.37,
                                rely=0.6,
                                anchor='center')

        self.restart_button = Button(self.master,
                                     text="Restart",
                                     command=self.stopwatch_restart)
        self.restart_button.place(height=30,
                                  width=100,
                                  relx=0.5,
                                  rely=0.6,
                                  anchor='center')

        self.close_button = Button(self.master,
                                   text="Exit",
                                   command=self.master.destroy)
        self.close_button.place(height=30,
                                width=60,
                                relx=0.92,
                                rely=0.92,
                                anchor='center')

        OPTIONS = ["Article", "Paragraph", "Data Entry"]
        self.genre = StringVar(self.master)
        self.genre.set(OPTIONS[0])  # default value

        dropdown = OptionMenu(
            self.master,
            self.genre,
            *OPTIONS,
            command=lambda x: self.genre_chosen(self.genre.get()))
        dropdown.place(height=30,
                       width=100,
                       relx=0.63,
                       rely=0.6,
                       anchor='center')

        self.user_box()
        self.create_menu()
        self.username = self.set_username()
        self.update_clock()
        self.master.mainloop()

    def window_placement(self, window, x, y):
        """ Takes in a window name and sizes and places it in the middle of the screen """
        pos_horizontally = int((self.monitor_width / 2) - (x / 2))
        pos_vertically = int((self.monitor_height / 2) - (y / 2))
        window.geometry("%dx%d+%d+%d" %
                        (x, y, pos_horizontally, pos_vertically))

    def raise_above_all(window):
        window.attributes('-topmost', 1)

    def genre_chosen(self, genre):
        """Call db to choose a random text with the given genre """
        text = database.get_text(genre)
        self.text_box.config(state=NORMAL)
        self.text_box.delete("1.0", END)
        self.text_box.insert(1.0, text)
        self.text_box.config(state=DISABLED)

    def update_clock(self):
        now = datetime.datetime.now()
        self.time_label.configure(text=now.strftime("%H:%M:%S"))
        self.master.after(1000, self.update_clock)

    def stopwatch_start(self):
        self.input_box.delete("0", END)
        self.current_time = datetime.datetime.now().strftime("%H:%M")
        self.stopwatch.start()
        self.stopwatch_update()

    def start_with_button(self):
        # waits 1 second until player puts their cursor in typing field
        self.stopwatch.reset()
        self.input_box.delete("0", END)
        self.current_time = datetime.datetime.now().strftime("%H:%M")
        time.sleep(1)
        self.stopwatch.start()
        self.stopwatch_update()

    def stopwatch_update(self):
        self.stopwatch_label.configure(text=str(self.stopwatch))
        self.master.after(50, self.stopwatch_update)

    def stopwatch_restart(self):
        self.stopwatch.reset()
        self.input_box.delete("0", END)
        self.master.focus_set()

    def stopwatch_stop(self):
        stopped_time = str(self.stopwatch)
        self.stopwatch.stop()
        print(stopped_time)
        return stopped_time

    def stopwatch_on_typing(self):
        self.stopwatch.reset()
        self.current_time = datetime.datetime.now().strftime("%H:%M")
        self.input_box.delete("0", END)
        time.sleep(0.5)
        self.stopwatch.start()
        self.stopwatch_update()

    def correct_callback(self, input, text):
        self.characters_correct = self.characters_correct_var.get()
        self.errors = self.errors_var.get()

        if input == self.text_box.get(1.0, 'end-1c'):
            self.stopped_time = self.stopwatch_stop()
            words = self.input_box.get().split(" ")
            words_len = len(words)
            total_characters = len(text)
            try:
                attempt_time = eval(str(self.stopped_time).replace("s", ""))
            except SyntaxError:
                attempt_time = eval(str(self.stopped_time).replace("m", ""))

            gross_wpm = calc.wpm(words_len, attempt_time)
            net_wpm = calc.net_wpm(gross_wpm, self.errors)
            chpm = calc.chpm(attempt_time, self.characters_correct)
            error_rate = calc.error_rate(self.errors, self.characters_correct,
                                         total_characters)

            user = User(self.username, gross_wpm, net_wpm, chpm, attempt_time,
                        self.current_time, error_rate, self.score)

            self.display_user_stats(attempt_time, self.current_time, gross_wpm,
                                    net_wpm, chpm, error_rate, self.score)
            print("End")

        if re.match(input, self.text):
            self.input_box.config(fg='green')
            self.characters_correct_var.set(self.characters_correct + 1)
            self.score += 10
        else:
            self.score -= 10
            self.errors_var.set(self.errors + 1)
            self.input_box.config(fg='red')
        return True

    def backspace(self):
        self.characters_correct_var.set(self.characters_correct - 1)

    def display_user_stats(self, attempt_time, current_time, gross_wpm,
                           net_wpm, chpm, error_rate, score):
        self.string = "Attempt Time: {}s\nTime of the attempt: {}\nGross words per minute: {}\nNet words per minute: {}\nCharacters per minute: {}\nAccuracy {}%\nScore: {}"

        self.stats_window = Toplevel(self.master)  # create a window on top
        self.stats_window.title("Player Statistics")

        self.stats_variable.set(
            self.string.format(attempt_time, current_time, gross_wpm, net_wpm,
                               chpm, error_rate, score))

        self.window_placement(self.stats_window, 400, 300)

        label = Label(self.stats_window,
                      text="Statistics",
                      font=('Arial', 12, 'bold'))
        label.place(width=100, height=30, relx=0.5, rely=0.2, anchor='center')

        stats_label = Label(self.stats_window,
                            textvariable=self.stats_variable,
                            font=('Arial', 11, 'bold'),
                            justify='left')
        stats_label.place(width=250,
                          height=150,
                          relx=0.5,
                          rely=0.5,
                          anchor='center')
        self.stopwatch_restart()

    def user_box(self):
        self.username_box = Toplevel(self.master)
        self.username_box.title("Player Username")
        self.username_box.configure(background='#8cab9c')
        self.window_placement(self.username_box, 320, 400)
        self.master.lower()

        self.label_text = "Username must be between 3-15 characters \nValid characters: a-z 0-9 _&$£\nPlease enter your username:\n"
        self.label = Label(self.username_box,
                           wraplength=180,
                           justify="center",
                           bg='#617D6F',
                           fg="#ffffff",
                           text=self.label_text)
        self.label.place(height=200,
                         width=190,
                         relx=0.5,
                         rely=0.4,
                         anchor='center')

        self.user_input_box = Entry(
            self.username_box, font=('Arial', 12),
            bg="#F8F8FF")  # box where user enters their username
        self.user_input_box.place(height=25,
                                  width=140,
                                  relx=0.5,
                                  rely=0.5,
                                  anchor='center')

        self.user_exit_button = Button(
            self.username_box, text="Exit",
            command=self.username_box.destroy)  # exits the program
        self.user_exit_button.place(height=30,
                                    width=60,
                                    relx=0.5,
                                    rely=0.7,
                                    anchor='center')

        self.enter_button = Button(self.username_box,
                                   text="Enter",
                                   command=self.username_enter
                                   )  # creating a button to submit username
        self.enter_button.place(height=30,
                                width=80,
                                relx=0.5,
                                rely=0.6,
                                anchor='center')

        reg = self.username_box.register(self.user_validate)
        self.user_input_box.config(validate="key", validatecommand=(reg, '%P'))

    def username_enter(self):
        """ Hey new user! / Welcome back, <username>! Your last attempt was on... """
        self.username = self.user_input_box.get()

        exists = database.is_username(self.username)
        print(exists)

        print(self.username)

        if exists == True:
            self.confirm_box(self.username)  # if exists, then confirm
        else:
            self.new_user_box()  # if it doesn't exist welcome new user

    def new_user_box(self):
        box = Tk()
        box.title("Welcome!")

        self.window_placement(box, 300, 200)

        self.username = self.user_input_box.get()
        database.add_username(self.username)

        message = Label(
            box,
            text=
            "Hey new user, {}! Here you can test your typing speed, just start typing in the box!"
            .format(self.username),
            wraplength=200)

        message.place(width=200,
                      height=150,
                      relx=0.5,
                      rely=0.4,
                      anchor='center')

        ok_button = Button(box, text="OK", command=lambda: self.ok(box))
        ok_button.place(width=100,
                        height=30,
                        relx=0.5,
                        rely=0.7,
                        anchor='center')
        self.username_box.destroy()

    def user_validate(self, inp):
        set_pat = ["$", "£", "_", "%"]

        if len(inp) > 15:
            root.bell()
            return False

        if inp.isalnum():
            return True

        elif any(char in set_pat for char in inp):

            return True

        elif inp == "":
            return True

        else:
            root.bell()
            print(inp)
            return False

    def confirm_box(self, username):
        confirm_dialog = Tk()  # placing the box

        self.username_box.destroy()
        self.window_placement(confirm_dialog, 300, 200)

        confirm_dialog.title("Confirmation")  # titling the box
        message = Label(
            confirm_dialog,
            text="This username is already in use.\nIs this you coming back?")
        message.place(relx=0.5, rely=0.5, anchor='center')

        y_button = Button(
            confirm_dialog,
            text="Yes",
            command=lambda: self.confirm(username, confirm_dialog))
        n_button = Button(confirm_dialog,
                          text="No",
                          command=lambda: self.not_confirm(confirm_dialog))
        y_button.place(width=50,
                       height=30,
                       relx=0.3,
                       rely=0.76,
                       anchor='center')
        n_button.place(width=50,
                       height=30,
                       relx=0.7,
                       rely=0.76,
                       anchor='center')

    def confirm(self, username, dialog):
        dialog.destroy()
        confirm_box = Tk()
        confirm_box.title(username)

        self.window_placement(confirm_box, 300, 200)

        self.highest_score = database.get_highest_score(username)
        self.last_time = database.get_latest_time(username)

        text = "Welcome back, {}! Your last attempt was on {}, and your highest score is: {}"

        message = Label(confirm_box,
                        text=text.format(username, self.last_time,
                                         self.highest_score),
                        wraplength=300)

        message.place(relx=0.5, rely=0.4, anchor='center')

        ok_button = Button(confirm_box,
                           text="OK",
                           command=lambda: self.ok(confirm_box))
        ok_button.place(width=100,
                        height=30,
                        relx=0.5,
                        rely=0.7,
                        anchor='center')

    def not_confirm(self, dialog):
        dialog.destroy()
        self.master.lift()
        self.user_box()

    def ok(self, dialog):
        dialog.destroy()
        self.master.lift()

    def set_username(self):
        username = self.user_input_box.get()
        return username

    def create_menu(self):
        def _optionsmenu_restart():
            """ Restarts the text, attempt time and clears input box and sets index to 0 """
            self.stopwatch_restart()

        def _optionsmenu_changeusername():
            """ Will allow user to switch username to either already existing user or
            a new one """

            self.user_box()

        def _helpmenu_helpindex():
            """ A new window that gives brief description about the program and how to use it"""
            self.helpindex = Toplevel(self.master)
            self.helpindex.title("Help Index")
            self.helpindex.geometry("300x500")

        def _helpmenu_about():
            """ A new window that gives a brief description about the program and its version, author and rights """
            self.helpindex = Toplevel(self.master)
            self.helpindex.title("About")
            self.helpindex.geometry("500x300")
            message = """VERSION 1.0.0\n© 2021 Ioana Koleva.  All rights reserved."""
            label = Label(self.helpindex, text=message, wraplength=300)
            label.place(relx=0.5, rely=0.5, anchor='center')

        self.optionsmenu.add_command(label="Restart",
                                     command=_optionsmenu_restart)
        self.optionsmenu.add_command(label="Change username",
                                     command=_optionsmenu_changeusername)
        self.optionsmenu.add_separator()
        self.optionsmenu.add_command(label="Exit", command=self.master.destroy)
        self.menubar.add_cascade(label="Options", menu=self.optionsmenu)

        self.helpmenu.add_command(label="Help Index",
                                  command=_helpmenu_helpindex)
        self.helpmenu.add_command(label="About...", command=_helpmenu_about)
        self.menubar.add_cascade(label="Help", menu=self.helpmenu)

        self.master.config(menu=self.menubar)
Beispiel #28
0
def tests():
    test_stopwatch: Stopwatch = Stopwatch()

    test_stopwatch = Stopwatch(default_precision=3)

    test_stopwatch.start()

    if not isinstance(test_stopwatch.lap('tests::test1'), float):
        raise TestError('lap() return value is unexpected')

    if not isinstance(test_stopwatch.lap('tests::test2'), float):
        raise TestError('lap() return value is unexpected')

    if not isinstance(test_stopwatch.lap(), float):
        raise TestError('lap() return value is unexpected')

    time.sleep(1)

    total_of_watch: float = test_stopwatch.get_watch()

    if not isinstance(total_of_watch, float):
        raise TestError('get_watch() return value is unexpected')

    if total_of_watch < 0.9 or total_of_watch > 1.5:
        raise TestError('get_watch() return value is error')

    is_has: bool = test_stopwatch.has_lap('tests::test1')

    if not isinstance(is_has, bool):
        raise TestError('has_lap() return value is unexpected')

    if not is_has:
        raise TestError('has_lap() return value is error')

    if test_stopwatch.get_lap_count() != 3:
        raise TestError('get_lap_count() return value is unexpected')

    if test_stopwatch.get_status() != StopwatchStatus.Started:
        raise TestError('get_status() return value is unexpected')

    if not isinstance(test_stopwatch.stop(), float):
        raise TestError('stop() return value is unexpected')

    if not isinstance(
            test_stopwatch.get_lap(lap_name='tests::test1', lap_precision=3),
            float):
        raise TestError('get_lap() return value is unexpected')

    if not isinstance(test_stopwatch.get_lap(lap_name='tests::test2'), float):
        raise TestError('get_lap() return value is unexpected')

    if not isinstance(test_stopwatch.get_lap_by_number(3), float):
        raise TestError('get_lap_by_number() return value is unexpected')

    if not isinstance(test_stopwatch.get_average_of_laps(), float):
        raise TestError('get_average_of_laps() return value is unexpected')

    if not isinstance(test_stopwatch.get_laps(), list):
        raise TestError('get_laps() return value is unexpected')

    test_stopwatch.reset()

    if test_stopwatch.has_lap('tests::test1'):
        raise TestError('reset() error')
Beispiel #29
0
class App:
    apps = []

    def __init__(self, root, **kwargs):
        self.now = time.time()
        self.toggle_btn_color_stopped = 'green'
        self.toggle_btn_color_stopped_text = 'blue'
        self.toggle_btn_color_running = 'red'
        self.toggle_btn_color_running_text = 'white'
        self.stopwatch_digit_size = 22
        self.testColor_ready = 'light-blue'
        self.testColor_running = 'blue'
        self.testColor_paused = 'orange'
        self.testColor_passed = 'green'
        self.testColor_failed = 'red'
        self.testColor = ['lightblue', 'blue', 'orange', 'green', 'red']
        self.root = root
        self.name = 'Stopwatch'
        for key, value in kwargs.items():
            if key == 'name':
                self.name = value
        self.apps.append(self)
        self.stopwatch = Stopwatch(name=self.name)
        self.currentTestTime = self.stopwatch.getCurrentDuration(self.now)
        self.remainingTestTime = self.stopwatch.getRemainingTestTime(self.now)
        self.testStatus = self.stopwatch.getStatusText(
        )  # "0:Ready, "1:Running", "2:Paused", "3:Passed", "4:Failed"
        print(self.testStatus)

        # GUI
        self.name_label = Label(self.root)
        self.clock_frame = Label(self.root)
        self.timeRemaining_label = Label(self.root)
        self.testStatus_label = Label(self.root)
        self.frame = Frame(self.root)

        self.textEntryTgt_D = StringVar()
        self.textEntryTgt_H = StringVar()
        self.textEntryTgt_M = StringVar()
        self.textEntryTgt_S = StringVar()

        self.textEntryTgt_D.set('1')
        self.textEntryTgt_H.set('0')
        self.textEntryTgt_M.set('0')
        self.textEntryTgt_S.set('0')

        self.tgtTimeEntry_D = Entry(self.root,
                                    textvariable=self.textEntryTgt_D)
        self.tgtTimeEntry_H = Entry(self.root,
                                    textvariable=self.textEntryTgt_H)
        self.tgtTimeEntry_M = Entry(self.root,
                                    textvariable=self.textEntryTgt_M)
        self.tgtTimeEntry_S = Entry(self.root,
                                    textvariable=self.textEntryTgt_S)

        self.day_plus_btn = Button(self.root)
        self.day_minus_btn = Button(self.root)
        self.hr_plus_btn = Button(self.root)
        self.hr_minus_btn = Button(self.root)
        self.min_plus_btn = Button(self.root)
        self.min_minus_btn = Button(self.root)
        self.sec_plus_btn = Button(self.root)
        self.sec_minus_btn = Button(self.root)

        self.tgtTimeEntry_D.bind("<Key>", self.callback_updateTgt)
        self.tgtTimeEntry_H.bind('<Key>', self.callback_updateTgt)
        self.tgtTimeEntry_M.bind('<Key>', self.callback_updateTgt)
        self.tgtTimeEntry_S.bind('<Key>', self.callback_updateTgt)

        self.tgtTimeEntry_D.bind("<FocusOut>", self.callback_exit)
        self.tgtTimeEntry_H.bind('<FocusOut>', self.callback_exit)
        self.tgtTimeEntry_M.bind('<FocusOut>', self.callback_exit)
        self.tgtTimeEntry_S.bind('<FocusOut>', self.callback_exit)

        self.toggle_button = Button(self.root)  # start/stop depending on state
        self.lap_button = Button(self.root)  # not currently used
        self.reset_button = Button(self.root)  # reset the timer to zero
        self.quitButton = Button(self.root)  # not currently used

        self.setup(self.stopwatch)
        print("out of setup")

    def dayPlus(self):
        result = False
        val = int(self.textEntryTgt_D.get())
        if val < 9:
            val = val + 1
            result = True
        self.textEntryTgt_D.set(str(val))
        self.update_sw_tgt()
        return result

    def dayMinus(self):
        result = False
        val = int(self.textEntryTgt_D.get())
        if val > 0:
            val = val - 1
            result = True
        self.textEntryTgt_D.set(str(val))
        self.update_sw_tgt()
        return result

    def hrPlus(self):
        result = False
        val = int(self.textEntryTgt_H.get())
        if val < 23:
            val = val + 1
            result = True
        else:
            if self.dayPlus():
                val = 0
                result = True
            else:
                val = 23  # unable to increase day so hr remains unchanged
        self.textEntryTgt_H.set(str(val))
        self.update_sw_tgt()
        return result

    def hrMinus(self):
        result = False
        val = int(self.textEntryTgt_H.get())
        if val > 0:
            val = val - 1
            result = True
        else:
            if self.dayMinus():
                val = 23
                result = True
            else:
                val = 0
        self.textEntryTgt_H.set(str(val))
        self.update_sw_tgt()
        return result

    def minPlus(self):
        result = False
        val = int(self.textEntryTgt_M.get())
        if val < 59:
            val = val + 1
            result = True
        else:
            if self.hrPlus():
                val = 0
                result = True
            else:
                val = 59  # unable to increase day so hr remains unchanged
        self.textEntryTgt_M.set(str(val))
        self.update_sw_tgt()
        return result

    def minMinus(self):
        result = False
        val = int(self.textEntryTgt_M.get())
        if val > 0:
            val = val - 1
            result = True
        else:
            if self.hrMinus():
                val = 59
                result = True
            else:
                val = 0
        self.textEntryTgt_M.set(str(val))
        self.update_sw_tgt()
        return result

    def secPlus(self):
        result = False
        val = int(self.textEntryTgt_S.get())
        if val < 59:
            val = val + 1
            result = True
        else:
            if self.minPlus():
                val = 0
                result = True
            else:
                val = 59  # unable to increase day so hr remains unchanged
        self.textEntryTgt_S.set(str(val))
        self.update_sw_tgt()
        return result

    def secMinus(self):
        result = False
        val = int(self.textEntryTgt_S.get())
        if val > 0:
            val = val - 1
            result = True
        else:
            if self.minMinus():
                val = 59
                result = True
            else:
                val = 0
        self.textEntryTgt_S.set(str(val))
        self.update_sw_tgt()
        return result

    def callback_exit(self, e):
        print("callback_exit")
        self.callback_updateTgt(e)
        self.timeRemaining_label.focus_set()

    def setup(self, sw):
        # Create all of the GUI components and build all the visuals
        print("setup")
        self.name_label.configure(text=sw.name,
                                  font=("default", 15, "bold"),
                                  bg="blue",
                                  fg="white")
        self.clock_frame.configure(text="0:00:00:00",
                                   bg="white",
                                   fg="blue",
                                   font=("default", self.stopwatch_digit_size,
                                         "bold"),
                                   width=500,
                                   height=200)
        self.timeRemaining_label.configure(text="0:00:00:00",
                                           bg="white",
                                           fg="blue",
                                           font=("default",
                                                 self.stopwatch_digit_size,
                                                 "bold"),
                                           width=500,
                                           height=200)
        self.tgtTimeEntry_D.configure(bg="white",
                                      fg="blue",
                                      font=("default",
                                            self.stopwatch_digit_size - 4,
                                            "bold"),
                                      width=40)
        self.day_plus_btn.configure(text="+",
                                    bg=self.toggle_btn_color_stopped,
                                    fg="white",
                                    command=self.dayPlus,
                                    font=("default", 12, "bold"))
        self.day_minus_btn.configure(text="-",
                                     bg=self.toggle_btn_color_stopped,
                                     fg="white",
                                     command=self.dayMinus,
                                     font=("default", 12, "bold"))
        self.tgtTimeEntry_H.configure(bg="white",
                                      fg="blue",
                                      font=("default",
                                            self.stopwatch_digit_size - 4,
                                            "bold"),
                                      width=40)
        self.hr_plus_btn.configure(text="+",
                                   bg=self.toggle_btn_color_stopped,
                                   fg="white",
                                   command=self.hrPlus,
                                   font=("default", 12, "bold"))
        self.hr_minus_btn.configure(text="-",
                                    bg=self.toggle_btn_color_stopped,
                                    fg="white",
                                    command=self.hrMinus,
                                    font=("default", 12, "bold"))
        self.tgtTimeEntry_M.configure(bg="white",
                                      fg="blue",
                                      font=("default",
                                            self.stopwatch_digit_size - 4,
                                            "bold"),
                                      width=40)
        self.min_plus_btn.configure(text="+",
                                    bg=self.toggle_btn_color_stopped,
                                    fg="white",
                                    command=self.minPlus,
                                    font=("default", 12, "bold"))
        self.min_minus_btn.configure(text="-",
                                     bg=self.toggle_btn_color_stopped,
                                     fg="white",
                                     command=self.minMinus,
                                     font=("default", 12, "bold"))
        self.tgtTimeEntry_S.configure(bg="white",
                                      fg="blue",
                                      font=("default",
                                            self.stopwatch_digit_size - 4,
                                            "bold"),
                                      width=40)
        self.sec_plus_btn.configure(text="+",
                                    bg=self.toggle_btn_color_stopped,
                                    fg="white",
                                    command=self.secPlus,
                                    font=("default", 12, "bold"))
        self.sec_minus_btn.configure(text="-",
                                     bg=self.toggle_btn_color_stopped,
                                     fg="white",
                                     command=self.secMinus,
                                     font=("default", 12, "bold"))
        self.toggle_button.configure(text="START",
                                     bg=self.toggle_btn_color_stopped,
                                     fg=self.toggle_btn_color_stopped_text,
                                     command=self.toggle,
                                     font=("default", 12, "bold"))
        self.reset_button.configure(text="RESET",
                                    bg="orange",
                                    fg="black",
                                    command=self.reset,
                                    font=("default", 12, "bold"))
        self.testStatus_label.configure(
            text=self.testStatus,
            bg="yellow",
            fg=self.testColor[self.stopwatch.getStatus_int()],
            font=("default", self.stopwatch_digit_size - 2, "bold"),
            width=980,
            height=180,
            anchor="w")
        # self.quitButton.configure(text="Quit", bg="red", fg="white", command=self.quit, font=("default", 15, "bold"))

        self.name_label.place(x=10, y=10, width=100, height=33)
        self.clock_frame.place(x=120, y=10, width=200, height=33)
        self.tgtTimeEntry_D.place(x=325, y=10, width=27, height=33)
        self.day_plus_btn.place(x=354, y=8, width=15, height=17)
        self.day_minus_btn.place(x=354, y=27, width=15, height=17)
        self.tgtTimeEntry_H.place(x=371, y=10, width=40, height=33)
        self.hr_plus_btn.place(x=411, y=8, width=15, height=17)
        self.hr_minus_btn.place(x=411, y=27, width=15, height=17)
        self.tgtTimeEntry_M.place(x=428, y=10, width=40, height=33)
        self.min_plus_btn.place(x=468, y=8, width=15, height=17)
        self.min_minus_btn.place(x=468, y=27, width=15, height=17)
        self.tgtTimeEntry_S.place(x=484, y=10, width=40, height=33)
        self.sec_plus_btn.place(x=524, y=8, width=15, height=17)
        self.sec_minus_btn.place(x=524, y=27, width=15, height=17)
        self.timeRemaining_label.place(x=535, y=10, width=195, height=33)
        self.toggle_button.place(x=740, y=10, width=100, height=33)
        self.reset_button.place(x=850, y=10, width=100, height=33)
        # self.quitButton.place(x=950, y=10, width=100, height=33)
        self.testStatus_label.place(x=10, y=45, width=1000, height=33)
        print("finished setup, about to run self.updateTimer")
        self.updateTimer()
        print("finished self.updateTimer")

    def callback_updateTgt(self, e):
        try:
            self.tgt_D = int(self.tgtTimeEntry_D.get())
            if self.tgt_D < 0:
                self.tgtTimeEntry_D.insert(2, '0')
        except:
            if not type(self.tgt_D) is int:
                self.tgtTimeEntry_D.insert(2, '0')
        try:
            self.tgt_H = int(self.tgtTimeEntry_H.get())
        except:
            if not type(self.tgt_H) is int:
                self.tgtTimeEntry_H.insert(2, '0')
        try:
            self.tgt_M = int(self.tgtTimeEntry_M.get())
        except:
            if not type(self.tgt_M) is int:
                self.tgtTimeEntry_M.insert(2, '0')
        try:
            self.tgt_S = int(self.tgtTimeEntry_S.get())
        except:
            if not type(self.tgt_S) is int:
                self.tgtTimeEntry_S.insert(2, '0')
        try:
            tgtSeconds = (self.tgt_D * 24 * 60 * 60) + (
                self.tgt_H * 60 * 60) + (self.tgt_M * 60) + self.tgt_S
            print("in callback_updateTgt, tgtSecs: " + str(tgtSeconds))
            self.stopwatch.setTargetTime(tgtSeconds)
        except:
            print('Error Found: ' + str(e))
        self.updateTimer()

    def update_sw_tgt(self):
        # get the current values from the target entry boxes
        tgt_D = int(self.tgtTimeEntry_D.get())
        tgt_H = int(self.tgtTimeEntry_H.get())
        tgt_M = int(self.tgtTimeEntry_M.get())
        tgt_S = int(self.tgtTimeEntry_S.get())
        # calculate the target number of seconds
        tgtSeconds = (tgt_D * 24 * 60 * 60) + (tgt_H * 60 * 60) + (tgt_M *
                                                                   60) + tgt_S
        # set the target time in the related stopwatch and update the timer
        self.stopwatch.setTargetTime(tgtSeconds)
        self.updateTimer()

    def showTimeDigits(self, digit):
        display = str(digit)
        if digit <= 9:
            display = str(0) + display
        return display

    def toggle(self):
        if self.stopwatch.running:
            self.stop()
        else:
            if not self.stopwatch.failed:
                self.start()

    def fail(self):
        print("fail activated")
        self.stopwatch.fail()
        self.updateTimer()

    def start(self):
        self.stopwatch.start()  # let it do the logical work
        # do your GUI updates
        self.toggle_button.configure(text="Stop",
                                     bg=self.toggle_btn_color_running,
                                     fg=self.toggle_btn_color_running_text)
        self.updateTimer()

    def stop(self):
        self.stopwatch.stop()  # Logic and math here
        # Do GUI updates for stop
        self.toggle_button.configure(text="Start",
                                     bg=self.toggle_btn_color_stopped,
                                     fg=self.toggle_btn_color_stopped_text)
        self.updateTimer()

    def reset(self):
        if self.stopwatch.testStatus_int == 4:  # in failed mode so stop
            self.stop()
        now = time.time()
        self.stopwatch.reset()  # Logic handled in the Stopwatch class
        remainingTime = self.stopwatch.display_remainingTime(drt_now=now)
        # Update GUI components
        self.clock_frame.configure(text=self.stopwatch.display_elapsedTime())
        self.timeRemaining_label.configure(text=remainingTime)

    def updateTimer(self):
        now = time.time()
        self.testStatus_label.configure(
            text=self.stopwatch.getStatusText(),
            fg=self.testColor[self.stopwatch.getStatus_int()])
        if self.stopwatch.running:
            self.clock_frame.configure(
                text=self.stopwatch.display_elapsedTime(now))
            self.timeRemaining_label.configure(
                text=self.stopwatch.display_remainingTime(now))
            self.frame.after(1000, self.updateTimer)
        else:
            self.frame.after(1000, self.updateTimer)

    def getRunning(self):
        return self.stopwatch.running

    def quit(self):
        # self.frame.destroy()
        # temp fail button
        print("Quit activated")
        self.fail()
Beispiel #30
0
def main():
    global votes
    global winners

    pygame.init()

    pygame.display.set_caption("Hack + Tell Timer")

    SIZE = SIZE_W, SIZE_H = (min(pygame.display.Info().current_w, 1024),
                             min(pygame.display.Info().current_h, 600))

    screen = pygame.display.set_mode(SIZE)
    matelight_screen = pygame.Surface((40, 16))

    clock = pygame.time.Clock()

    signs_font = pygame.font.Font("OSP-DIN.ttf", 50)
    time_font = pygame.font.Font("OSP-DIN.ttf", 100)
    applause_font = pygame.font.Font("OSP-DIN.ttf", 200)
    status_font = pygame.font.Font("OSP-DIN.ttf", 20)
    matelight_font = pygame.font.Font("unscii-16-full.ttf", 15)

    time_left_header_text = signs_font.render("Time left", True, (0, 255, 0))
    time_current_header_text = signs_font.render("Current local time", True,
                                                 (0, 255, 0))

    try:
        ip_address = get_ip_address(NETWORK_INTERFACE)
    except Exception as e:
        print("Could not determine {} IP address: {}".format(
            NETWORK_INTERFACE, e))
        ip_address = "Unknown IP"
    status_text = status_font.render(ip_address, True, (0, 255, 0))

    timer = Stopwatch()
    timer.reset()

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    votes_event = threading.Event()
    votes_thread = threading.Thread(name='votes',
                                    target=get_votes,
                                    args=(votes_event, ))
    votes_thread.daemon = True
    votes_thread.start()

    winners_event = threading.Event()
    winners_thread = threading.Thread(name='winners',
                                      target=get_winners,
                                      args=(winners_event, ))
    winners_thread.daemon = True
    winners_thread.start()

    pygame.time.set_timer(MATELIGHT_UDP_SEND_EVENT, UDP_RATE_MS)

    show_applause = False
    show_preview = False
    show_votes = False
    show_winners = False

    run = True
    while run:
        if (TIMER_S - timer.duration) > 0:
            time_left_m, time_left_s = divmod(TIMER_S - timer.duration, 60)
        else:
            time_left_m, time_left_s = 0, 0
        time_left = '{0:02.0f}:{1:06.3f}'.format(time_left_m, time_left_s)
        time_left_text = time_font.render(time_left, True, (0, 255, 0))
        time_current_text = time_font.render(
            datetime.now().strftime("%H:%M:%S.%f")[:-3], True, (0, 255, 0))

        if timer.running and timer.duration >= TIMER_S:
            timer.stop()
            show_applause = True

        if show_applause:
            if (round(time.time()) % 2):
                background = (0, 255, 0)
                foreground = (0, 0, 0)
            else:
                background = (0, 0, 0)
                foreground = (0, 255, 0)
            screen.fill(background)
            applause_text = applause_font.render("APPLAUSE", True, foreground)
            screen.blit(
                applause_text,
                applause_text.get_rect(center=(SIZE_W // 2, SIZE_H // 2)))

        else:
            screen.fill((0, 0, 0))

            screen.blit(time_left_header_text,
                        (SIZE_H // 2,
                         SIZE_W // 10 - time_left_header_text.get_height()))
            screen_time_left_rect = screen.blit(time_left_text,
                                                (SIZE_H // 2, SIZE_W // 10))

            screen.blit(time_current_header_text,
                        (SIZE_H // 2,
                         SIZE_W // 3 - time_current_header_text.get_height()))
            screen.blit(time_current_text, (SIZE_H // 2, SIZE_W // 3))

            screen.blit(status_text, (0, SIZE_H - status_text.get_height()))

        if show_winners:
            winners_text = "&".join(winners)
            matelight_text = matelight_font.render(winners_text, True,
                                                   (150, 0, 150))

        elif show_applause:
            if (round(time.time()) % 2):
                matelight_text = matelight_font.render("CLAP", False,
                                                       (150, 0, 150))
            else:
                matelight_text = matelight_font.render("NOW", False,
                                                       (150, 0, 150))

        elif show_votes:
            matelight_text = matelight_font.render(str(votes), True,
                                                   (150, 0, 150))

        else:
            matelight_text = matelight_font.render(time_left[:5], True,
                                                   (150, 0, 150))

        if show_preview:
            screen.blit(matelight_text, (SIZE_W - matelight_text.get_width(),
                                         SIZE_H - matelight_text.get_height()))

        matelight_screen.fill((0, 0, 0))
        matelight_screen.blit(
            matelight_text,
            matelight_text.get_rect(center=(matelight_screen.get_width() // 2,
                                            matelight_screen.get_height() //
                                            2)))

        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.MOUSEBUTTONUP:
                if show_applause:
                    show_applause = False
                else:
                    mouse_pos = pygame.mouse.get_pos()
                    if screen_time_left_rect.collidepoint(mouse_pos):
                        if not timer.running and timer.duration < TIMER_S:
                            timer.start()
                        else:
                            timer.stop()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:
                    show_applause = not show_applause

                elif event.key == pygame.K_p:
                    show_preview = not show_preview

                # TODO change to control-c
                elif event.key == pygame.K_q:
                    run = False

                elif event.key == pygame.K_r:
                    timer.stop()
                    timer.reset()

                elif event.key == pygame.K_v:
                    show_votes = not show_votes
                    if show_votes:
                        votes_event.set()
                    else:
                        votes_event.clear()

                elif event.key == pygame.K_w:
                    show_winners = not show_winners
                    if show_winners:
                        winners_event.set()
                    else:
                        winners_event.clear()

                elif event.key == pygame.K_SPACE:
                    if not timer.running and timer.duration < TIMER_S:
                        timer.start()
                    else:
                        timer.stop()

            if event.type == MATELIGHT_UDP_SEND_EVENT:
                matelight_send(sock, matelight_screen)

        clock.tick(15)

    sock.close()

    pygame.quit()
Beispiel #31
0
class AppThread(QThread):
    """ Qt Application Class & UI Thread

    Updates UI based on state of the system."""
    App = QtWidgets.QApplication([])
    UI = uic.loadUi('app.ui')
    UI.show()

    def __init__(self):
        super(AppThread, self).__init__()

        # UI Action Handler
        self.UI.start_btn.clicked.connect(self.Start_Timer)
        self.UI.stop_btn.clicked.connect(self.Stop_Timer)
        self.UI.pause_btn.clicked.connect(self.Pause_Timer)
        self.UI.resume_btn.clicked.connect(self.Resume_Timer)
        self.UI.stop_btn.clicked.connect(Generate_Report)
        self.UI.save_btn.clicked.connect(self.Hide_Parameters)
        self.UI.parameters_action.triggered.connect(self.Show_Parameters)
        self.UI.import_file_action.triggered.connect(self.Import_File)
        self.UI.restart_action.triggered.connect(self.Restart)
        self.UI.quit_action.triggered.connect(Quit)

        # Initialize Timer
        self.timer = Stopwatch()
        self.timer.reset()

        # Timer Warnings
        self.first_warning = 3.0
        self.second_warning = 4.0
        self.third_warning = 5.0

        # Speech Disfluency Feedback count
        self.SDF = 0

        # Set Initial UI State
        self.UI.stop_btn.hide()
        self.UI.pause_btn.hide()
        self.UI.resume_btn.hide()
        self.UI.first_lbl.hide()
        self.UI.first_warning.hide()
        self.UI.second_lbl.hide()
        self.UI.second_warning.hide()
        self.UI.third_lbl.hide()
        self.UI.third_warning.hide()
        self.UI.save_btn.hide()

        # System State
        self.state = 'Ready'

    def Get_State(self):
        """Get_State -> state (string)"""
        return self.state

    def Get_SDF(self):
        """Get_SDF -> SDF (string)"""
        return self.SDF

    def Add_SDF(self):
        """Adds one SDF"""
        self.SDF += 1

    def Get_Speech_Time(self):
        """Get_Speech_Timer -> timer (Stopwatch)"""
        return self.timer

    def Get_Speech_Notes(self):
        """Get_Speech_Notes -> UI.speech_notes (string)"""
        return self.UI.speech_notes.toPlainText()

    def Update_Image(self, frame):
        """Update webcam feed on UI"""
        height, width, channel = frame.shape
        bytesPerLine = 3 * width
        h = self.UI.webcam_lbl.height()
        w = self.UI.webcam_lbl.width()
        qImg = QtGui.QImage(frame.data, width, height, bytesPerLine,
                            QtGui.QImage.Format_RGB888)
        qImg = qImg.rgbSwapped()
        # Scale image to widget size maintaining aspect ratio
        self.UI.webcam_lbl.setPixmap(
            QtGui.QPixmap(qImg).scaled(w, h, Qt.KeepAspectRatio,
                                       Qt.FastTransformation))

    def Start_Timer(self):
        """Starts speech timer

        Must be in 'Ready' or 'Paused' state."""
        if self.state == 'Ready' or self.state == 'Paused':
            self.UI.parameters_action.setEnabled(False)
            self.UI.import_file_action.setEnabled(False)

            self.UI.start_btn.hide()
            self.UI.pause_btn.show()
            self.UI.stop_btn.show()

            print('Starting Timer...')
            self.timer.start()
            self.state = 'Running'
            print('Currint State: ' + self.state)

    def Stop_Timer(self):
        """Stops speech timer & ends speech
        
        Must be in 'Running' or 'Paused' state."""
        if self.state == 'Running' or self.state == 'Paused':
            self.UI.pause_btn.hide()
            self.UI.resume_btn.hide()
            self.UI.stop_btn.hide()

            print('Stopping Timer...')
            self.timer.stop()
            self.state = 'End'
            print('Currint State: ' + self.state)

    def Pause_Timer(self):
        """Pauses speech timer
        
        Must be in 'Running' state."""
        if self.state == 'Running':
            self.UI.pause_btn.hide()
            self.UI.resume_btn.show()

            print('Pausing Timer...')
            self.timer.stop()
            self.state = 'Paused'
            print('Currint State: ' + self.state)

    def Resume_Timer(self):
        """Resumes speech timer
        
        Must be in 'Paused' state."""
        if self.state == 'Paused':
            self.UI.resume_btn.hide()
            self.UI.pause_btn.show()

            print('Starting Timer...')
            self.timer.start()
            self.state = 'Running'
            print('Currint State: ' + self.state)

    def Restart_Timer(self):
        """Restarts speech timer"""
        if self.state != 'Ready':
            self.UI.start_btn.show()
            self.UI.stop_btn.hide()
            self.UI.pause_btn.hide()
            self.UI.resume_btn.hide()

            print('Restarting Timer...')
            self.timer.reset()
            self.state = 'Ready'
            print('Currint State: ' + self.state)

    def Show_Parameters(self):
        """Shows speech timer parameters"""
        self.UI.parameters_action.setEnabled(False)
        self.UI.start_btn.hide()
        self.UI.timer_lbl.hide()

        print('Showing Parameters...')
        self.UI.first_lbl.show()
        self.UI.first_warning.show()
        self.UI.second_lbl.show()
        self.UI.second_warning.show()
        self.UI.third_lbl.show()
        self.UI.third_warning.show()
        self.UI.save_btn.show()

        self.UI.first_warning.setValue(self.first_warning)
        self.UI.second_warning.setValue(self.second_warning)
        self.UI.third_warning.setValue(self.third_warning)

    def Hide_Parameters(self):
        """Hides & saves speech timer parameters"""
        self.UI.parameters_action.setEnabled(True)
        self.UI.start_btn.show()
        self.UI.timer_lbl.show()

        self.first_warning = self.UI.first_warning.value()
        self.second_warning = self.UI.second_warning.value()
        self.third_warning = self.UI.third_warning.value()

        print('Hiding Parameters...')
        self.UI.first_lbl.hide()
        self.UI.first_warning.hide()
        self.UI.second_lbl.hide()
        self.UI.second_warning.hide()
        self.UI.third_lbl.hide()
        self.UI.third_warning.hide()
        self.UI.save_btn.hide()

    def Import_File(self):
        """Imports .txt file from file browser"""
        filename = QFileDialog.getOpenFileName()
        path = filename[0]
        print(path)

        self.UI.speech_notes.setText('')
        with open(path, 'r') as f:
            for line in f:
                self.UI.speech_notes.append(line)

    def Restart(self):
        """Resets all speech parameters to defaults"""
        self.Restart_Timer()
        FeedThread.Reset_FER()
        self.SDF = 0

        self.UI.parameters_action.setEnabled(True)
        self.UI.import_file_action.setEnabled(True)

    def run(self):
        """Updates UI elements while app is running"""
        while (1):
            # Set SDF Label
            self.UI.sdf_lbl.setText('Filler used ' + str(self.SDF) + ' times')

            # Set Timer Label
            self.UI.timer_lbl.setText(
                '%02d:%02d' %
                (self.timer.duration // 60, self.timer.duration % 60))
            if self.timer.duration >= self.third_warning * 60:
                BG_Color = 'rgb(250,200,200);'
            elif self.timer.duration >= self.second_warning * 60:
                BG_Color = 'rgb(250,250,200);'
            elif self.timer.duration >= self.first_warning * 60:
                BG_Color = 'rgb(200,250,200);'
            else:
                BG_Color = 'rgb(240,240,240);'
            self.UI.timer_lbl.setStyleSheet('QLabel {background-color :' +
                                            BG_Color + 'color : rgb(0,0,0);}')

            self.UI.fer_lbl.setText('You look ' +
                                    FeedThread.Get_Curr_Emotion())

            self.UI.menuFPS.setTitle('FPS: ' + str(FeedThread.Get_FPS()))

            time.sleep(0.1)