Esempio n. 1
0
    def checkValidString(self, s: str) -> bool:
        open_parant_count = 0
        star_queue = SimpleQueue()
        for index, c in enumerate(s):
            if c == '*':
                star_queue.put(index)
            elif c == '(':
                open_parant_count += 1
            elif open_parant_count > 0:
                open_parant_count -= 1
            elif not star_queue.empty():
                pos = star_queue.get()
                s = s[:pos] + '(' + s[pos + 1:]
            else:
                return False

        open_parant_count = 0
        star_queue = SimpleQueue()
        for index, c in enumerate(s[::-1]):
            if c == '*':
                star_queue.put(index)
            elif c == ')':
                open_parant_count += 1
            elif open_parant_count > 0:
                open_parant_count -= 1
            elif not star_queue.empty():
                pos = star_queue.get()
                s = s[:pos] + '(' + s[pos + 1:]
            else:
                return False

        return True
Esempio n. 2
0
class MessageBuffer:
    def __init__(self, batch_size):
        self._buffer = SimpleQueue()
        self.set_batch_size(batch_size)

    def put(self, mesg):
        self._buffer.put(mesg)
        return self.batch_size - self._buffer.qsize()

    def get(self):
        if not self._buffer.empty():
            return self._buffer.get()
        return None

    def is_batch_ready(self):
        return self.batch_size <= self._buffer.qsize()

    def empty(self):
        return self._buffer.empty()

    def set_batch_size(self, batch_size):
        if batch_size < 1 or not isinstance(batch_size, (int, float)):
            batch_size = 1
        self.batch_size = int(batch_size)

    def get_batch_size(self):
        return self.batch_size
Esempio n. 3
0
def get_cost(work: SimpleQueue, recipe_book: Dict[str, Recipe],
             extra: Dict[str, int]) -> int:
    ore_used = 0

    while not work.empty():
        to_make: Component = work.get()

        # Ore is infinite, we can just use it
        if to_make.substance == "ORE":
            ore_used += to_make.amount
            continue

        # Use up anything we already have
        usable = min(extra[to_make.substance], to_make.amount)
        to_make.amount -= usable
        extra[to_make.substance] -= usable

        # Dont need to craft it if you dont need it
        if to_make.amount == 0:
            continue

        recipe = recipe_book[to_make.substance]

        scaling_factor = math.ceil(to_make.amount / recipe.result.amount)

        for ingredient in recipe.ingredients:
            work.put(scaling_factor * ingredient)
        leftover = (scaling_factor * recipe.result.amount) - to_make.amount
        extra[to_make.substance] += leftover

    return ore_used
Esempio n. 4
0
    def bfs(self, node_key: int, upside_down: bool):
        """
        gets src and runs bfs algorithm on the graph from src
        if upside down is true that run the bfs on graph transpose
        :param node_key:
        :param upside_down:
        :return:
        """
        # initialize all the tags to -1
        for node in self.my_graph.get_all_v().values():
            if node.get_color != "Red" or node.connected_component is None:  #checks if we are in red mode then only nodes that dont have SCC
                # participants in the bfs
                node.set_tag(-1)
        queue = SimpleQueue()
        src = self.my_graph.get_all_v().get(node_key)
        src.set_tag(0)
        queue.put(src)
        while not queue.empty():
            node_temp = queue.get()
            # graph as is
            if upside_down is False:
                neighbors = self.my_graph.all_out_edges_of_node(node_temp.key)
            # graph transpose
            else:
                neighbors = self.my_graph.all_in_edges_of_node(node_temp.key)
            for key in neighbors:
                node_neighbor = self.my_graph.get_all_v().get(key)

                if node_neighbor.get_tag(
                ) == -1:  # the first time this node is reached
                    node_neighbor.set_tag(0)
                    queue.put(node_neighbor)
def algorithm(start, end, edges, win):
    start.visited = True
    queue = SimpleQueue()
    queue.put(start)

    while not queue.empty():
        node = queue.get()
        if node != end:
            for edge in edges:
                if node == edge[0]:
                    if not edge[1].visited:
                        queue.put(edge[1])
                        edge[1].parent = node
                        edge[1].visited = True
                elif node == edge[1]:
                    if not edge[0].visited:
                        queue.put(edge[0])
                        edge[0].parent = node
                        edge[0].visited = True

            node.make_grey()
        else:
            end.make_grey()
            return True

    return False
Esempio n. 6
0
def run_all(folder, s_target):
    sql_queue = SimpleQueue()
    size = 0
    for filename in glob.iglob(f'{folder}/**/*.sql', recursive=True):
        sql_queue.put(get_sql(filename))
        size += 1
    num_tries = 0
    max_tries = size * 2
    while not sql_queue.empty() and num_tries < max_tries:
        try:
            sql = sql_queue.get()
            s_target.execute(sql)
            s_target.commit()
            num_tries = 0
        except ProgrammingError as e:
            message = str(e.orig).strip()
            if 'relation' in message and 'does not exist' in message:
                s_target.rollback()
                print(f'Object does not exist yet: {message}. Re-queueing...')
                sql_queue.put(sql)
                num_tries += 1
            else:
                raise
    if num_tries >= max_tries:
        print(f'Number of attempts exceeded configured threshold of {max_tries}')
        sys.exit(1)
Esempio n. 7
0
def kahn_topo_sort(grph, nodes, source=None, sink=None):
    result = []
    in_degrees = find_in_degrees(grph, nodes)
    no_inpaths = set([node for node, indg in in_degrees.items() if indg == 0])
    q = SimpleQueue()
    if source is not None:
        # Make sure source is at the start of topo sort
        q.put(source)
        no_inpaths = no_inpaths - set([source])
    for node in no_inpaths:
        q.put(node)
    while not q.empty():
        node = q.get()
        result.append(node)
        for neigh, wt in grph[node]:
            if neigh not in in_degrees:
                continue
            in_degrees[neigh] -= 1
            if in_degrees[neigh] == 0:
                q.put(neigh)
    if sink is not None and result[-1] != sink:
        # if sink is not at the end of topo sort, place it there
        sink_index = result.index(sink)
        result.append(sink)
        result = result[:sink_index] + result[sink_index + 1:]
    return result
Esempio n. 8
0
    def ac3(self, arcs=None):
        """
        Update `self.domains` such that each variable is arc consistent.
        If `arcs` is None, begin with initial list of all arcs in the problem.
        Otherwise, use `arcs` as the initial list of arcs to make consistent.

        Return True if arc consistency is enforced and no domains are empty;
        return False if one or more domains end up empty.
        """
        # Create arcs if None
        if arcs is None:
            arcs = SimpleQueue()
            for x in combinations(self.crossword.variables, 2):
                arcs.put(x)

        while not arcs.empty():
            x, y = arcs.get()
            if self.revise(x, y):
                if not self.domains[x]:
                    return False
                neighbors = self.crossword.neighbors(x)
                neighbors.remove(y)
                for x_neighbor in neighbors:
                    arcs.put((x_neighbor, x))
        return True
def distance(w1: str, w2: str, words: set) -> (int, list):
    d = dict()
    q = SimpleQueue()
    current = ""
    temp = ""

    q.put(w1)
    d[w1] = w1

    if w1 == w2:
        return (0, [w1])

    while q.empty() == False:
        current = q.get()

        for letter in range(len(current)):
            temp = current

            for i in range(97, 123):
                temp = temp[:letter] + chr(i) + temp[letter + 1:]

                if temp in words:
                    if d.get(temp) == None:
                        d[temp] = current

                        if temp == w2:
                            return getPath(w1, w2, d)

                        q.put(temp)

    return ([], -1)
Esempio n. 10
0
def p39(triplet_sum_stop: int) -> int:
    initial_triplet = (3, 4, 5)
    q = SimpleQueue()
    q.put(initial_triplet)

    triplet_sum_counts = [0] * triplet_sum_stop

    while not q.empty():
        triplet = q.get()
        triplet_sum = sum(triplet)
        if triplet_sum < triplet_sum_stop:
            for triplet_sum_multiple in range(triplet_sum, triplet_sum_stop,
                                              triplet_sum):
                triplet_sum_counts[triplet_sum_multiple] += 1
            a, b, c = calculate_next_triplets(triplet)
            q.put(a)
            q.put(b)
            q.put(c)

    largest_triplet_sum = 0
    largest_triplet_sum_count = 0
    for triplet_sum in range(12, triplet_sum_stop):
        triplet_sum_count = triplet_sum_counts[triplet_sum]
        if triplet_sum_count > largest_triplet_sum_count:
            largest_triplet_sum_count = triplet_sum_count
            largest_triplet_sum = triplet_sum

    return largest_triplet_sum
Esempio n. 11
0
    def tree_insert(self, key):
        if self._root == None:
            self._root = BinaryTree.BinaryNode(key)
            return self._root

        q = Queue()
        q.put(self._root)

        while not q.empty():
            cur_node = q.get()

            if cur_node.left == None:
                cur_node.left = BinaryTree.BinaryNode(key, cur_node)
                return cur_node.left
            elif cur_node.right == None:
                cur_node.right = BinaryTree.BinaryNode(key, cur_node)
                return cur_node.right

            if cur_node.left:
                q.put(cur_node.left)

            if cur_node.right:
                q.put(cur_node.right)

        return None
Esempio n. 12
0
def game_player(game_input: OpCodes, opcodes: OpCodes):
    """
    Create the processor to play the game
    """
    input_queue = SimpleQueue()
    output_queue = SimpleQueue()
    processor = Processor(input_queue, output_queue)

    map(input_queue.putm game_input)

    # let the robot run in a separate thread
    thread = threading.Thread(target=processor, args=(opcodes, ), daemon=True)
    thread.start()

    score = 0

    while not output_queue.empty():
        # not sure where the robot will break, so

        x = output_queue.get()
        y = output_queue.get()
        tile_id = output_queue.get()

        if x == -1 and y == 0:
            score = max(tile_id, score)

    return (score, )  # must return a tuple
class RDProxyClientProtocol:
    def __init__(self, server, client_addr):
        self.server = server
        self.client_addr = client_addr
        self.transport = None
        self.q = SimpleQueue()

    def connection_made(self, transport):
        self.transport = transport
        self.dispatch_message()

    def queue_message(self, message):
        self.q.put(message)
        self.dispatch_message()

    def dispatch_message(self):
        if self.transport != None:
            while not self.q.empty():
                item = self.q.get()
                if random.random() >= DROP_RATE:
                    self.transport.sendto(item)

    def datagram_received(self, data, addr):
        if random.random() >= DROP_RATE:
            self.server.transport.sendto(data, self.client_addr)

    def error_received(self, exc):
        print('Error received:', exc)

    def connection_lost(self, exc):
        pass
Esempio n. 14
0
    def __call__(self, problem):
        D = problem.D

        # Draw samples
        X = problem.d.rvs(self.N)
        y = problem.pdf(X)

        root = Container(X, y, mins=[problem.low] * D, maxs=[problem.high] * D)

        # Construct tree
        finished_containers = []
        q = SimpleQueue()
        q.put(root)

        while not q.empty():

            c = q.get()

            if c.N <= self.P:
                finished_containers.append(c)
            else:
                children = self.split(c)
                for child in children:
                    q.put(child)

        # Integrate containers
        contributions = [
            self.integral(cont, problem.pdf) for cont in finished_containers
        ]
        G = np.sum(contributions)

        return G
Esempio n. 15
0
    def list_words_lexicographical(self, n: int) -> Generator[str, None, None]:
        self._deterministic_only()

        if len(self._final_states) == 0:
            return

        queue = SimpleQueue()
        queue.put((self._initial_state, ""))
        if self._initial_state in self._final_states:
            yield ""

        while not (n <= 0 or queue.empty()):
            q1, s = queue.get()
            for (c_index, c) in self._alphabet_iter(with_epsilon=False):
                q2 = sget(self._state_transition_matrix[q1][c_index])

                if q2 in self._stock_states:
                    continue

                new_s = s + c

                if q2 in self._final_states:
                    yield new_s
                    n -= 1

                queue.put((q2, new_s))
Esempio n. 16
0
    def bfs(self, node: List[int]):
        def rotate_wheel(node: List[int], depth: int, pos: int, incre: int):
            assert incre in [1, -1]
            new_node = node.copy()
            new_node[pos] = (node[pos] + incre) % 10

            new_node_str = ''.join(map(str, new_node))
            if new_node_str == self.target:
                self.min_depth = min(self.min_depth, depth + 1)
                self.visited[new_node_str] = None
            elif new_node_str not in self.deadends and \
                 new_node_str not in self.visited:
                q.put([new_node, depth + 1])
                self.visited[new_node_str] = None

        q = SimpleQueue()
        q.put([node, 0])

        while not q.empty():
            node, depth = q.get()

            rotate_wheel(node, depth, 0, 1)
            rotate_wheel(node, depth, 0, -1)
            rotate_wheel(node, depth, 1, 1)
            rotate_wheel(node, depth, 1, -1)
            rotate_wheel(node, depth, 2, 1)
            rotate_wheel(node, depth, 2, -1)
            rotate_wheel(node, depth, 3, 1)
            rotate_wheel(node, depth, 3, -1)

            if self.min_depth == depth + 1: break
Esempio n. 17
0
    def bfs(self, start, target, visited):
        # Create an empty queue.
        q = SimpleQueue()
        # Put the starting userID in a list in our queue.
        q.put([start])
        # While the queue is not empty....
        while not q.empty():
            # Grab the current path.
            path = q.get()
            # Grab the last vertex in the path.
            curr_vertex = path[-1]

            # If current vertex is the target, return the path.
            if curr_vertex == target:
                visited[target] = path
                return

            # Iterate through all neighbors.
            for social_connection in self.friendships[curr_vertex]:
                if social_connection != start and social_connection not in path:
                    # Create new path and add current neighbor.
                    new_path = list(path)
                    new_path.append(social_connection)
                    # Add that new path to the queue.
                    q.put(new_path)
Esempio n. 18
0
    def shortestPath(self, nid1, nid2):
        if nid1 == nid2:
            return [nid1]

        Q = SimpleQueue()
        P = [-1 for _ in range(self.order())]
        visited = [False for _ in range(self.order())]
        Q.put(nid1)
        visited[nid1] = True
        
        while not Q.empty():
            nid = Q.get()
            
            for next_nid in self._nodes[nid].outneighbours:
                if not visited[next_nid]:
                    if next_nid == nid2:
                        path = [next_nid]
                        while nid > -1:
                            path.append(nid)
                            nid = P[nid]
                        return path
                            
                    P[next_nid] = nid
                    Q.put(next_nid)
                    visited[next_nid] = True

        return None
Esempio n. 19
0
def get_details(start_pos, keys, doors, walkable):

    q = SimpleQueue()
    seen = set()
    details = dict()

    q.put({"position": start_pos, "distance": 0, "keys_needed": set()})
    # queue = [{"position": (int, int), "distance": int, "keys_needed": {string}}]

    while not q.empty():
        item = q.get()
        q_pos = item["position"]
        if q_pos in seen:
            continue
        seen.add(q_pos)
        q_distance = item["distance"]
        q_keys = item["keys_needed"]
        if q_pos in keys.keys():
            details[q_pos] = {"distance": q_distance, "keys_needed": q_keys}
        if q_pos in doors.keys():
            q_keys.add(doors[q_pos].lower())
        for n_pos in get_orthogonal_neighbours(q_pos):
            if n_pos in walkable - seen:
                q.put(
                    {"position": n_pos, "distance": q_distance + 1, "keys_needed": q_keys.copy()})

    return details
Esempio n. 20
0
def escape_maze():
    maze = []
    maze.append(['#', '#', 'O', '#', '#', '#', '#'])
    maze.append(['#', ' ', ' ', ' ', '#', ' ', '#'])
    maze.append(['#', ' ', '#', ' ', '#', ' ', '#'])
    maze.append(['#', ' ', '#', ' ', ' ', ' ', '#'])
    maze.append(['#', ' ', '#', '#', '#', ' ', '#'])
    maze.append(['#', ' ', ' ', ' ', '#', ' ', '#'])
    maze.append(['#', '#', '#', '#', '#', 'X', '#'])

    directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]

    visited = [row[:] for row in maze]

    p_end = (6, 5)

    p0 = (0, 2)
    q = SimpleQueue()
    q.put(p0)
    time = 0
    while not q.empty():
        for _ in range(q.qsize()):
            x = q.get()
            visited[x[0]][x[1]] = str(time)
            if x[0] == p_end[0] and x[1] == p_end[1]:
                return visited

            for d in directions:
                p1 = (x[0] + d[0], x[1] + d[1])
                if visited[p1[0]][p1[1]] in ' X':
                    q.put(p1)
        time += 1

    return None
Esempio n. 21
0
    def backward(self, target_node, deriv_pass, ancestors=None):
        """Perform a backward computation to compute the derivatives for all
        parameters that affect the target node

        Parameters
        ----------
        target_node : integer
            The id of the node under consideration

        deriv_pass : np.ndarray (nparams)
            A gradient vector

        Returns
        -------
        derivative : np.ndarray(nparams)
            A vector containing the derivative of all parameters
        """

        if ancestors is None:
            ancestors = nx.ancestors(self.graph, target_node)

        anc_and_target = ancestors.union(set([target_node]))


        # Evaluate the node
        self.graph.nodes[target_node]['pass_down'] = deriv_pass

        # Gradient with respect to beta
        self.graph.nodes[target_node]['derivative'] = \
            np.dot(self.graph.nodes[target_node]['pass_down'],
                   self.graph.nodes[target_node]['pre_grad'])

        queue = SimpleQueue()
        queue.put(target_node)

        for node in ancestors:
            self.graph.nodes[node]['children_left'] = set(
                self.graph.successors(node)).intersection(anc_and_target)
            self.graph.nodes[node]['pass_down'] = 0.0
            self.graph.nodes[node]['derivative'] = 0.0


        while not queue.empty():
            node = queue.get()

            pass_down = self.graph.nodes[node]['pass_down']
            for parent in self.graph.predecessors(node):
                self.graph.nodes[parent]['pass_down'] += \
                    pass_down * self.graph.edges[parent, node]['eval']
                self.graph.edges[parent, node]['derivative'] = \
                    np.dot(pass_down,self.graph.edges[parent, node]['pre_grad'])
                self.graph.nodes[parent]['derivative'] += \
                    np.dot(pass_down * self.graph.edges[parent, node]['eval'],
                           self.graph.nodes[parent]['pre_grad'])

                self.graph.nodes[parent]['children_left'].remove(node)
                if self.graph.nodes[parent]['children_left'] == set():
                    queue.put(parent)

        return self.get_derivative()
Esempio n. 22
0
def run_all(folder, s_target):
    sql_queue = SimpleQueue()
    size = 0
    # Ordered scripts are formatted like {number}-name.sql
    # Scripts without a number prefix will be ran last
    for filename in sorted(glob.iglob(f'{folder}/**/*.sql', recursive=True), key=get_file_order):
        sql_queue.put(get_sql(filename))
        size += 1
    if size == 0:
        return
    num_tries = 0
    max_tries = size * 2
    while not sql_queue.empty() and num_tries < max_tries:
        try:
            sql = sql_queue.get()
            s_target.execute(sql)
            s_target.commit()
            num_tries = 0
        except ProgrammingError as e:
            message = str(e.orig).strip()
            if 'relation' in message and 'does not exist' in message:
                s_target.rollback()
                print(f'Object does not exist yet: {message}. Re-queueing...')
                sql_queue.put(sql)
                num_tries += 1
            else:
                raise
    if num_tries >= max_tries:
        print(
            f'Number of attempts exceeded configured threshold of {max_tries}')
        sys.exit(1)
Esempio n. 23
0
def game_player(opcodes: OpCodes):
    """
    Create the processor to play the game
    """
    painting = defaultdict(lambda: 0)

    input_queue = SimpleQueue()
    output_queue = SimpleQueue()
    processor = Processor(input_queue, output_queue)

    # let the robot run in a separate thread
    thread = threading.Thread(target=processor, name='Game', args=(opcodes, ))
    thread.start()
    thread.join()

    while not output_queue.empty():
        # not sure where the robot will break, so

        x = output_queue.get()
        y = output_queue.get()
        tile_id = output_queue.get()

        painting[(x, y)] = tile_id

    return painting
Esempio n. 24
0
class Bluetooth(Thread):

    Messages = {
        "0,0,0,0,0,0,0,0,0": Action.STOP,
        "1,0,0,0,0,0,0,0,0": Action.FORWARD,
        "2,0,0,0,0,0,0,0,0": Action.BACKWARD,
        "3,0,0,0,0,0,0,0,0": Action.LEFT,
        "4,0,0,0,0,0,0,0,0": Action.RIGHT,
        "0,1,0,0,0,0,0,0,0": Action.LEFT_ALT,
        "0,2,0,0,0,0,0,0,0": Action.RIGHT_ALT,
        "0,0,1,0,0,0,0,0,0": Action.BEEP,
        "0,0,0,1,0,0,0,0,0": Action.SPEED_UP,
        "0,0,0,2,0,0,0,0,0": Action.SPEED_DOWN,
        "0,0,0,0,1,0,0,0,0": Action.SERVO_LEFT,
        "0,0,0,0,2,0,0,0,0": Action.SERVO_RIGHT,
        "0,0,0,0,0,0,1,0,0": Action.LED_OFF,
        "0,0,0,0,0,0,2,0,0": Action.LED_RED,
        "0,0,0,0,0,0,3,0,0": Action.LED_GREEN,
        "0,0,0,0,0,0,4,0,0": Action.LED_BLUE,
        "0,0,0,0,0,0,0,0,1": Action.SERVO_MID,
        "0,0,0,0,0,0,0,1,0": Action.OUTFIRE,
        "0,0,0,0,0,0,8,0,0": Action.LED_OFF
    }

    def __init__(self):
        self.serial = Serial("/dev/ttyAMA0", 9600)
        Thread.__init__(self)
        self.event_queue = SimpleQueue()
        self.daemon = True
        self.start()

    def run(self):
        while True:
            command_string = self._get_command_string()
            action = Bluetooth.Messages[command_string]
            action_key = ActionKey(action)
            self.event_queue.put(action_key)

    def _get_command_string(self):
        #wait for start
        input_str = ""
        while self.serial.read(1).decode() != "$":
            pass
        #wait for end
        while True:
            char = self.serial.read(1).decode()
            if char == "#":
                break
            input_str += char
        return input_str

    def next_action(self):
        action_key = None
        while action_key == None:
            if not self.event_queue.empty():
                next = self.event_queue.get(block=False)
                if not next.is_old():
                    action_key = next
        return action_key.action
Esempio n. 25
0
    def _determinize_without_epsilon_transitions(self) -> StateMachine:
        # implying that no nontrivial (not into itself) epsilon transition exists

        q0 = (self._initial_state, )
        new_states = {q0}
        new_transitions = []

        queue = SimpleQueue()
        queue.put(q0)

        while not queue.empty():
            q1 = queue.get()
            for c_index, c in self._alphabet_iter():
                q2 = set()
                for q1n in q1:
                    q2.update(self._state_transition_matrix[q1n][c_index])
                q2 -= self._stock_states

                if len(q2) == 0:
                    continue

                q2 = tuple(sorted(q2))

                new_transitions.append((q1, c, q2))
                if q2 not in new_states:
                    queue.put(q2)
                    new_states.add(q2)

        new_states = list(new_states)
        state_to_index = dict(zip(new_states, range(len(new_states))))

        # Form result - new state machine

        alphabet = copy.deepcopy(self._alphabet)
        states_count = len(new_states)
        initial_state = new_states.index((self._initial_state, ))
        final_states = {
            i
            for i, q1 in enumerate(new_states)
            if len(set(q1) & self._final_states) != 0
        }
        state_transition = {(state_to_index[q1], c, state_to_index[q2])
                            for (q1, c, q2) in new_transitions}

        states_labels = []
        for q1 in new_states:
            if len(q1) == 1:
                label = self._states_labels[q1[0]]
            else:
                label = "{" + ",".join(self._states_labels[q1n]
                                       for q1n in q1) + "}"
            states_labels.append(label)

        return StateMachine(initial_state,
                            final_states,
                            state_transition,
                            states_labels=states_labels,
                            alphabet=alphabet,
                            states_count=states_count)
Esempio n. 26
0
 def levelOrder(self):
     from queue import SimpleQueue
     FIFOQueue = SimpleQueue()
     FIFOQueue.put(self)
     self.levelOrderEntry(FIFOQueue)
     while not FIFOQueue.empty():
         node = FIFOQueue.get()
         print(str(node.value), ' ')
Esempio n. 27
0
def game_player(scr, *args, opcodes: OpCodes):
    """
    Create the processor to play the game
    """
    painting = defaultdict(lambda: 0)

    input_queue = SimpleQueue()
    output_queue = SimpleQueue()
    processor = Processor(input_queue, output_queue)

    # let the robot run in a separate thread
    thread = threading.Thread(target=processor,
                              name='Game',
                              args=(opcodes, ),
                              daemon=True)
    thread.start()

    curses.curs_set(0)
    scr.nodelay(True)

    scr.border(0)

    max_y = 0
    score = None

    while thread.is_alive():

        ch = scr.getch()
        if ch == ord(','):
            input_queue.put(-1)
        elif ch == ord('.'):
            input_queue.put(1)
        elif ch == ord(' '):
            input_queue.put(0)
        elif ch == ord('q'):
            return 'exit'

        while not output_queue.empty():
            # not sure where the robot will break, so

            x = output_queue.get()
            y = output_queue.get()
            tile_id = output_queue.get()

            if not (x == -1 and y == 0):
                painting[(y + 1, x + 1)] = tile_id
                max_y = max(max_y, y + 1)
            else:
                score = tile_id

        for location, tile_id in painting.items():
            scr.addstr(*location, SYMBOL_MAP[tile_id], curses.A_NORMAL)

        if score is not None:
            scr.addstr(max_y + 4, 1, str(score), curses.A_BOLD)
            scr.clrtoeol()

    return painting
Esempio n. 28
0
def getDoc(docLookupInformation: LookupInformation,
           asyncQueue: queue.SimpleQueue, documents: queue.SimpleQueue):

    intermediateQueue = queue.SimpleQueue()

    isrunning = CancellationToken()
    workers = list()

    executor = ThreadPoolExecutor(max_workers=2)
    future = executor.submit(getDocuments, isrunning, 0, docLookupInformation,
                             asyncQueue, intermediateQueue)
    workers.append(future)

    counts = 0
    while counts < 10 and (runningWorkers(workers) or not asyncQueue.empty()):
        if asyncQueue.empty():
            isrunning.cancel()
        try:
            if not intermediateQueue.empty():
                documents.put(intermediateQueue.get())
                counts = counts + 1
            else:
                time.sleep(1)
        except Queue.Empty:
            pass

    while counts < 10 and not intermediateQueue.empty():
        try:
            if not intermediateQueue.empty():
                doc = intermediateQueue.get()

                documents.put(doc)
                counts = counts + 1
            else:
                time.sleep(1)
        except:
            pass

    isrunning.cancel()

    for worker in workers:
        worker.cancel()

    executor.shutdown()
Esempio n. 29
0
class SimpleQueueStore(Store):
    def __init__(self):
        self._q = SimpleQueue()
        self._len = 0

    def __len__(self):
        return self._len

    def store(self, entity, *args, **kwargs):
        self._q.put(entity)
        self._len += 1

    def pop(self, *args, **kwargs):
        if self._q.empty():
            return None
        return self._q.get()

    def empty(self):
        return self._q.empty()
Esempio n. 30
0
def intcode_helper(code, input_val=None):
    in_msg = SimpleQueue()
    if input_val is not None:
        in_msg.put(input_val)
    out_msg = SimpleQueue()
    intcode(code, in_msg, out_msg)
    output = []
    while not out_msg.empty():
        output.append(out_msg.get())
    return output