コード例 #1
0
ファイル: base.py プロジェクト: openstax/rex-web
    def element_in_viewport(self, target: WebElement):
        """verifies if target element is within viewport."""

        boundry = self.driver.execute_script(BOUNDING_RECTANGLE, target)

        target_left_bound = round_up(boundry.get("left"))
        target_right_bound = round_up(boundry.get("right"))
        target_height = round_up(boundry.get("height"))
        target_top_bound = target.location.get("y")
        target_lower_bound = target_top_bound + target_height

        win_upper_bound = self.driver.execute_script(
            "return window.pageYOffset")
        win_left_bound = self.driver.execute_script(
            "return window.pageXOffset")
        win_width = self.driver.execute_script(
            "return document.documentElement.clientWidth")
        win_height = self.driver.execute_script(
            "return document.documentElement.clientHeight")
        win_right_bound = win_left_bound + win_width
        win_lower_bound = win_upper_bound + win_height

        return all((
            win_left_bound <= target_left_bound,
            win_right_bound >= target_right_bound,
            win_upper_bound <= target_top_bound,
            win_lower_bound >= target_lower_bound,
        ))
コード例 #2
0
ファイル: sequential.py プロジェクト: vdusek/VUT_FIT
def lower_bound_of_rc(adj_mat: list, k: int) -> int:
    """
    Get rc which is the maximum integer assigned by algorithm to some vertex of graph.

    Args:
        adj_mat (list): the adjacency matrix of graph
        k (int): positive integer k

    Raises:
        Exception: when unreachable vertex

    Returns:
        int: lower bound of rc_k(G)
    """
    logger.info(EIGHTY * '-')
    logger.info('Algorithm to Find a Lower Bound of rc')
    logger.info('adj_mat = {}'.format(adj_mat))
    logger.info('k = {}'.format(k))

    # Get number of vertices
    n = len(adj_mat)
    logger.info('n = {}'.format(n))

    # Get distance matrix
    dist_mat = get_dist_mat(adj_mat)
    logger.info('dist_mat = {}'.format(dist_mat))

    # This algorithm cannot work with Graphs with unreachable vertexes
    if INF in (item for lst in dist_mat for item in lst):
        raise Exception("There's unreachable vertex in the Graph")

    # Init rc
    rc = NEG_INF
    logger.info('rc init = {}'.format(rc))

    # Compute rc
    for l in range(n):
        for i in range(n):
            for j in range(n):
                s = dist_mat[l][j] + adj_mat[i][j] + adj_mat[j][i]
                if rc <= s and i not in {l, j} and j != l:
                    rc = s
    logger.info('rc pre = {}'.format(rc))

    # Compute the graph diameter
    diameter = get_diameter(dist_mat)
    logger.info('diameter = {}'.format(diameter))

    # Round rc
    if k == diameter and n % 2 == 0:
        rc = int(round_up((3 * (k + 1) - rc) / 2) * ((n - 2) / 2) + 1)
    else:
        rc = int(round_up((3 * (k + 1) - rc) / 2) * round_down((n - 2) / 2))

    logger.info('rc final = {}'.format(rc))
    return rc
コード例 #3
0
    def lower_volume(self, value):
        current = round_up(self.get_volume() * 100)
        new_volume = current - value
        if new_volume < 0:
            new_volume = 0

        pygame.mixer.music.set_volume(new_volume / 100)
コード例 #4
0
    def increase_volume(self, value):
        current = round_up(self.get_volume() * 100)
        new_volume = current + value
        if new_volume > 100:
            new_volume = 100

        pygame.mixer.music.set_volume(new_volume / 100)
コード例 #5
0
def connect():
    """Funkcja do łączenia się z serwerem otodom i szukania ile jest aktualnie ofert i stron z nimi"""
    session.headers.update({'User-Agent':GET_UA()})
    connect = session.get('https://www.otodom.pl/sprzedaz/mieszkanie/wroclaw/?search%5Bcity_id%5D=39&nrAdsPerPage=72')
    soup = bs(connect.text, 'lxml')
    inide_strong_val = soup.find('div', class_="offers-index pull-left text-nowrap")
    offers_number = int(inide_strong_val.find('strong').text.replace(" ",""))
    page_number = round_up(offers_number/72) 
    return page_number,offers_number
コード例 #6
0
 def flush_buffer_to_queue(multiply_quota: Optional[float] = None):
     while buffer:
         # Requeue the buffered executions, but give them an extra second.
         execution = buffer.pop()
         if multiply_quota is None:
             execution.quota = execution.quota + 1
         else:
             execution.quota = round_up(execution.quota *
                                        multiply_quota)
         heap.push(execution)
コード例 #7
0
def get_caesar_substrings(ciphertext: str, key_length: int) -> list[str]:
    # Step (7)
    ct_length = len(ciphertext)
    caesar_shifts = []
    remainder = ct_length % key_length
    if remainder != 0:
        ciphertext += " " * remainder  # padding for shorter substrings
    number_of_full_substrings = round_up(ct_length / key_length)
    for i in range(key_length):  # for each caesar shift ...
        substring = ""
        for j in range(number_of_full_substrings
                       ):  # ... get the ciphertext for that shift
            letter = ciphertext[j * key_length:j * key_length + key_length][i]
            substring += letter
        caesar_shifts.append(substring)
    return caesar_shifts
コード例 #8
0
ファイル: routes.py プロジェクト: samifriedrich/showquester
def get_venue_events(venue_id):
    """Returns a list of upcoming event objects from Songkick for a given venue."""
    req = f'https://api.songkick.com/api/3.0/venues/{venue_id}/calendar.json?apikey={sk_api_key}'
    response = requests.get(req)
    num_results_per_page = response.json()['resultsPage']['perPage']
    total_num_results = response.json()['resultsPage']['totalEntries']
    if total_num_results > num_results_per_page:
        num_results_pages = round_up(total_num_results / num_results_per_page)
        venue_events = response.json()['resultsPage']['results']['event']
        for page_num in range(2, num_results_pages + 1):
            # get subsequent pages of results
            req = f'https://api.songkick.com/api/3.0/venues/{venue_id}/calendar.json?apikey={sk_api_key}&page={page_num}'
            response = requests.get(req)
            page_events = response.json()['resultsPage']['results']['event']
            venue_events.extend(page_events)
    else:
        venue_events = response.json()['resultsPage']['results']['event']

    return venue_events
コード例 #9
0
from math import ceil as round_up

with open("input.txt", "r") as boarding_pass_list:
    highest_ID = 0
    for boarding_pass in boarding_pass_list:
        row_min = 0
        row_max = 127
        column_min = 0
        column_max = 7

        # Find row
        for split_direction in boarding_pass[0:7]:
            if split_direction == "F":
                row_max = (row_min + row_max) // 2
            else:
                row_min = round_up(((row_min + row_max) / 2))
        row = row_min

        # Find column
        for split_direction in boarding_pass[7:10]:
            if split_direction == "L":
                column_max = (column_min + column_max) // 2
            else:
                column_min = round_up(((column_min + column_max) / 2))
        column = column_min

        # Calculate seat ID and compare to highest found so far
        seat_ID = (8 * row) + column
        if seat_ID > highest_ID:
            highest_ID = seat_ID
コード例 #10
0
ファイル: main.py プロジェクト: justinsloan/DTG
def about():
    tkinter.messagebox.showinfo("About DTG Toy", "Author:    " + __author__ + "\n"
                                + "Copyright: " + __copyright__ + "\n"
                                + "License:   " + __license__ + "\n"
                                + "Version: " + __version__ + "\n"
                                )


def help():
    tkinter.messagebox.showinfo("DTG Toy Help", "For assistance with DTG Toy visit the GitHub page or send an email to " + __email__ + ".")


def shutdown():
    app.destroy()

# create the local time panel
local_diff = datetime.datetime.today() - datetime.datetime.utcnow()
local_offset = round_up(local_diff.seconds / 3600)
if local_offset > 12:
    local_offset = local_offset - 24

# ROUTINE TO DETERMINE THE OFFSET BASED ON local_offset
vprint(local_offset)
local_time_panel = winMain(app, "W %H:%M:%S %m/%d", DTGzones.W)
local_time_panel.pack()

# create the first instance of the time panel
create_time_panel_instance()

app.protocol("WM_DELETE_WINDOW", shutdown)
app.mainloop()
コード例 #11
0
ファイル: loja_tintas.py プロジェクト: wellkamp/listas_python
 def calculo_galoes_tinta(self):
     return round_up(self.calculo_litros_metros() / LITRO_GALAO)
コード例 #12
0
ファイル: loja_tintas.py プロジェクト: wellkamp/listas_python
 def calculo_lata_tinta(self):
     return round_up(self.calculo_litros_metros() / LATA_LITROS)
コード例 #13
0
            def process_queue(max_buffer_size: int):
                # Process queue until empty.
                while heap:
                    execution = heap.pop()
                    lex_file = execution.path
                    quota = execution.quota
                    dest_file = dest_dir / lex_file.with_suffix('.bench').name
                    short_file = dest_file.relative_to(base_dir)
                    # Check if the quota has been exceeded. If it has, remove this execution from the heap, and record
                    # blank values in the output.
                    if max_quota is not None and quota > max_quota:
                        write_out(
                            f"Execution {lex_file.name} exceeds maximum allowable quota. Removing it from the "
                            f"heap and recording -1 values in {res_file}..")
                        row_dict = {
                            FILENAME: short_file,
                            TOKENS: lex_file_lengths[lex_file],
                            QUOTA: quota,
                            TPR: '',
                            CONF: '',
                        }
                        write_res(row_dict)
                        continue
                    timeout = round_up(quota * TIMEOUT_MULTIPLIER)
                    write_out(
                        f"Benchmarking {lex_file.name:{max_filename_length}} -> {parser} -> quota: {quota} -> "
                        f"timeout: {timeout} -> {str(short_file) + '...':{max_short_length}} ",
                        end='')

                    try:
                        result = run([
                            driver, '+time', '-ascii', '-stabilize-gc',
                            '-width', '1000', '-parser', parser, '-input',
                            lex_file, '-quota',
                            str(quota)
                        ],
                                     capture_output=True,
                                     timeout=timeout)
                        if result.returncode == 0:
                            output = result.stdout.decode('utf-8')
                            try:
                                # Move incomplete results back onto the queue, since they may have a chance to complete.
                                tpr, ci = extract_fields_from_output(
                                    output, (TPR, CONF))
                                tpr = parse_time_per_run_in_ns(tpr)
                                # The floating-point math can cause imprecision, so round to compensate.
                                tpr = f'{round(tpr):_.2f}ns'
                                write_dest(dest_file, output)
                                row_dict = {
                                    FILENAME: short_file,
                                    TOKENS: lex_file_lengths[lex_file],
                                    QUOTA: quota,
                                    TPR: tpr,
                                    CONF: ci,
                                }
                                write_res(row_dict)
                                write_out(
                                    f"{GREEN_CHECK} ({TPR}: {tpr} | {CONF}: {ci})"
                                )
                                flush_buffer_to_queue(multiply_quota=1.1)
                            except InsufficientQuota:
                                write_out(WHITE_QUESTION)
                                buffer.push(execution)
                            except Exception as e:
                                write_dest(dest_file, output)
                                write_err(
                                    short_file,
                                    e.args[0] if len(e.args) > 0 else None)
                                write_out(RED_X)
                        else:
                            write_err(short_file, "Non-zero return code.")
                            write_out(RED_X)
                    except TimeoutExpired:
                        write_out(RED_QUESTION)
                        buffer.push(execution)

                    # Test whether we need to empty the buffer and requeue all remaining executions.
                    if buffer and len(buffer) >= max_buffer_size:
                        write_out(
                            f"Buffer filled. Moving remaining executions to next quota..."
                        )
                        # Identify the maximum quota among the incomplete executions in the buffer.
                        min_buffer_quota = float('inf')
                        for execution in buffer:
                            min_buffer_quota = min(min_buffer_quota,
                                                   execution.quota)
                        # Set the new quota.
                        next_quota = min_buffer_quota * quota_factor
                        if heap:
                            min_heap_quota = heap.peek().quota
                        else:
                            min_heap_quota = min_buffer_quota
                        # Migrate all buffered executions to the main queue.
                        while buffer:
                            execution = buffer.pop()
                            heap.push(execution)
                        # Requeue the existing executions in the main queue, changing their quota only if it's less than
                        # or equal to the smallest quota in the heap. This maintains already-adjusted quotas.
                        while heap.peek().quota <= min_heap_quota:
                            execution = heap.pop()
                            if execution.quota <= min_heap_quota:
                                execution.quota = next_quota
                            heap.push(execution)
コード例 #14
0
ファイル: main.py プロジェクト: justinsloan/DTG
        __copyright__ + "\n" + "License:   " + __license__ + "\n" +
        "Version: " + __version__ + "\n")


def help():
    tkinter.messagebox.showinfo(
        "DTG Toy Help",
        "For assistance with DTG Toy visit the GitHub page or send an email to "
        + __email__ + ".")


def shutdown():
    app.destroy()


# create the local time panel
local_diff = datetime.datetime.today() - datetime.datetime.utcnow()
local_offset = round_up(local_diff.seconds / 3600)
if local_offset > 12:
    local_offset = local_offset - 24

# ROUTINE TO DETERMINE THE OFFSET BASED ON local_offset
vprint(local_offset)
local_time_panel = winMain(app, "W %H:%M:%S %m/%d", DTGzones.W)
local_time_panel.pack()

# create the first instance of the time panel
create_time_panel_instance()

app.protocol("WM_DELETE_WINDOW", shutdown)
app.mainloop()