Exemple #1
0
def async_tagger(
) -> Callable[[Path, metadata.MetaData, Callable[[Path], None]], None]:
    sync_queue: queue.SimpleQueue = queue.SimpleQueue()

    threading.Thread(target=_tagger_thread, args=(sync_queue, ),
                     daemon=True).start()

    def tag_file(filename: Path, mdata: metadata.MetaData,
                 post_action: Callable[[Path], None]):
        sync_queue.put((filename, mdata, post_action))

    return tag_file
Exemple #2
0
    def __init__(self, filter_volume, output_pipe, state_callback, prepare,
                 restore):
        self.output_pipe = output_pipe
        self.filter_volume = filter_volume
        self.announce_queue = queue.SimpleQueue()
        self.state_callback = state_callback
        self.prepare = prepare
        self.restore = restore
        self.event = threading.Event()

        self.thread = threading.Thread(target=self.__run)
        self.thread.start()
Exemple #3
0
def produceShardRanges(cancellationtoken : CancellationToken,indexLookupInformation : LookupInformation,output : queue.SimpleQueue, iterator: LookupIterator):
        ranges = queue.SimpleQueue()
        executeIterator(indexLookupInformation,iterator,ranges)
        while not ranges.empty() and not cancellationtoken.cancelled():
            try:
              rng = ranges.get(False)
              output.put(rng,timeout=2)
            except Queue.Empty:
              continue
            except:
              break
        cancellationtoken.cancel()
Exemple #4
0
 def call(self: _MethodClient,
          _rpc_request_proto=None,
          *,
          pw_rpc_timeout_s=UseDefault.VALUE,
          **request_fields) -> StreamingResponses:
     responses: queue.SimpleQueue = queue.SimpleQueue()
     self.invoke(
         self.method.get_request(_rpc_request_proto, request_fields),
         lambda _, response: responses.put(response),
         lambda _, status: responses.put(status),
         lambda rpc, status: responses.put(RpcError(rpc, status)))
     return StreamingResponses(self, responses, pw_rpc_timeout_s)
Exemple #5
0
def main():
    global shutdownRequestFlag

    file = open("input", "r")
    program = [int(x) for x in re.findall(r"-?\d+", file.readline())]
    memory = collections.defaultdict(lambda: 0, enumerate(program))
    file.close()

    NICs = []
    inputQs = []
    outputQs = []
    for address in range(50):
        inputQ = queue.SimpleQueue()
        inputQ.put(tuple([address]))
        inputQs.append(inputQ)
        outputQ = queue.SimpleQueue()
        outputQs.append(outputQ)
        NICs.append(
            threading.Thread(target=intcode,
                             args=[memory.copy(), inputQ, outputQ]))

    for NIC in NICs:
        NIC.start()

    while not shutdownRequestFlag:
        for outputQ in outputQs:
            if not outputQ.empty():
                address = outputQ.get()
                x = outputQ.get()
                y = outputQ.get()

                if address != 255:
                    inputQs[address].put((x, y))
                else:
                    print(y)
                    shutdownRequestFlag = True
                    break

    for NIC in NICs:
        NIC.join()
def bfs_path(graph, min_trap_pos, player_pos):
    player_pos = xy_to_matrix((player_pos))
    if len(min_trap_pos) > 0:
        min_trap_coord = min_trap_pos[0]
        for i in range(1, len(min_trap_pos)):
            coord = min_trap_pos[i]
            if graph[coord[0]][coord[1]] < graph[min_trap_coord[0]][
                    min_trap_coord[1]]:
                min_trap_coord = coord
        q = queue.SimpleQueue()
        q.put((player_pos, graph[player_pos[0]][player_pos[1]]))
        pred = {}
        if min_trap_coord == player_pos:
            return ''
        while not q.empty() and not min_trap_coord in pred:
            node, d = q.get()

            potential_nodes = []  # row, col
            potential_nodes.append((node[0] - 1, node[1]))  # left
            potential_nodes.append((node[0] + 1, node[1]))  # right
            potential_nodes.append((node[0], node[1] - 1))  # up
            potential_nodes.append((node[0], node[1] + 1))  # down

            # add neighbours of current node
            for pot in potential_nodes:
                if pot[0] > 9 or pot[0] < 0 or pot[1] > 11 or pot[
                        1] < 0:  # out of bounds
                    continue
                if graph[pot[0]][pot[1]] == -1 or graph[pot[0]][
                        pot[1]] != d + 1:  # block or not consecutive path
                    continue
                pred[pot] = node
                q.put((pot, d + 1))

        current = min_trap_coord
        pred_node = pred[current]
        while pred_node != player_pos:
            current = pred_node
            pred_node = pred[current]
        print(
            f'Min at: {min_trap_coord} so move from: {pred_node} to {current}')
        if pred_node[0] == current[0]:
            if pred_node[1] > current[1]:
                return 'l'
            else:
                return 'r'
        elif pred_node[0] > current[0]:
            return 'u'
        else:
            return 'd'
    else:
        return random.choice(['', 'u', 'd', 'l', 'r', 'p'])
Exemple #7
0
def form_diffs_for_repo(repo_new, repo_orig):

    # set up logging directory
    if not os.path.exists(repo_new + "_diffs/"):
        os.makedirs(repo_new + "_diffs/")

    log_dir = f"{repo_new}_diffs"

    # make a queue: if a fn is a folder, add all files inside
    # to the file queue; add folder to the folder queue
    folder_queue = queue.SimpleQueue()

    # pull all the folders in both repos and enqueue
    new_folders = glob.glob(repo_new + "/*/")
    print(glob.glob(repo_orig + "/*/"))

    # add folders
    for i in new_folders:
        folder_queue.put(os.path.basename(os.path.dirname(i)))

    # proceed through folders in queue
    while not folder_queue.empty():
        fldr = folder_queue.get()

        print(fldr)
        if not os.path.exists(f"{repo_orig}/{fldr}/"):
            continue

        # find all files in orig/new with this folder name
        new_files = glob.glob(f"{repo_new}/{fldr}/*.*")
        orig_files = glob.glob(f"{repo_orig}/{fldr}/*.*")

        # put in correct relative format
        new_files = set([os.path.basename(i) for i in new_files])
        orig_files = set([os.path.basename(i) for i in orig_files])

        # take ones that are in common, diff them
        files_to_diff = list(new_files.intersection(orig_files))
        if not os.path.exists(f"{log_dir}/{fldr}/"):
            os.makedirs(f"{log_dir}/{fldr}/")
        for f in files_to_diff:
            orig = f"{repo_orig}/{fldr}/{f}"
            new  = f"{repo_new}/{fldr}/{f}"
            output = open(f"{log_dir}/{fldr}/diff_{f[:-2]}.txt", 'w')
            subprocess.call(["diff", orig, new], stdout=output)
            output.close()

        # if folders exist in the current common subfolder, 
        # add them to the list of folders to evaluate
        subfolders_new = glob.glob(f"{repo_new}/{fldr}/*/")
        for i in subfolders_new:
            folder_queue.put(f"{fldr}/{os.path.basename(os.path.dirname(i))}")
    def find_path_from_our_location(self, destination):
        """ Finds path to trap location. """
        if self.location == destination:
            return ''
        q =  queue.SimpleQueue()
        q.put(self.location)
        visited = {}
        visited[self.location] = True
        pred = {}
        reached = False
        while not q.empty() and not reached:
            c_pos = q.get() # current position
            adjacent = self.get_adjacent(c_pos)
            for a_pos in adjacent: # adjacent position
                if a_pos == destination:
                    reached = True
                    pred[a_pos] = c_pos
                    break
                if not self.walkable_node(a_pos) or a_pos in visited or a_pos in self.bombs:
                    continue
                pred[a_pos] = c_pos
                visited[c_pos] = True
                q.put(a_pos)

        if destination not in pred:
            # cannot reach trap from our location
            self.unreachable = True
            print('We cannot reach the destination')  # Consider going for other objectives in that case
            return ''

        # Calculate path
        path = [destination]
        previous = pred[destination]
        while previous != self.location:
            path.append(previous)
            previous = pred[previous]
        path.append(self.location)
        path.reverse()
        # print('Path: ', path)

        # return move
        diff_pos = (path[1][0] - self.location[0], path[1][1] - self.location[1]) 
        if diff_pos[0] == -1:
            return 'u'
        elif diff_pos[0] == 1:
            return 'd'
        elif diff_pos[1] == -1:
            return 'l'
        elif diff_pos[1] == 1:
            return 'r'
        else:
            return random.choice(['u', 'd', 'l', 'r'])
Exemple #9
0
    def evade_bombs(self):  # make sure not in remnant blast here
        q = queue.SimpleQueue()
        q.put((self.location, 0))
        visited = {self.location: True}
        safe = None
        if self.location in self.blast_radius_1tick and self.location not in self.blast_radius_2tick:
            # only looks 1 tile out
            adjacent = self.get_adjacent(self.location)
            for a_pos in adjacent:
                if self.walkable_node(
                        a_pos
                ) and a_pos not in self.bombs and a_pos != self.opponent_location and not a_pos in self.blast_radius_1tick:
                    safe = a_pos
                    break
        elif self.location in self.blast_radius_2tick:
            # looks up to 2 tiles out
            safe = None
            while not q.empty() and safe is None:
                c_pos, d = q.get()  # current position
                if d > 2:  # cannot escape within 2 moves
                    break
                adjacent = self.get_adjacent(c_pos)
                for a_pos in adjacent:  # adjacent position
                    if a_pos in self.bombs or a_pos[0] > 9 or a_pos[0] < 0 or a_pos[1] > 11 or a_pos[1] < 0 \
                        or self.graph[a_pos[0]][a_pos[1]] == -1 or a_pos == self.opponent_location or a_pos in self.blast_radius_1tick:
                        continue
                    if d == 0 and a_pos not in self.blast_radius_1tick and a_pos not in self.blast_radius_2tick and a_pos not in self.remnant_blast:
                        safe = a_pos
                        break
                    if d == 1 and a_pos not in self.blast_radius_2tick:
                        if self.location in self.blast_radius_1tick and c_pos not in self.blast_radius_1tick and c_pos not in self.remnant_blast:
                            safe = c_pos
                            break
                        elif self.location not in self.blast_radius_1tick and self.location not in self.remnant_blast:
                            safe = c_pos
                            break
                    visited[c_pos] = True
                    q.put((a_pos, d + 1))

        # print('Safe pos: ', safe)
        if safe is not None:
            diff_pos = (safe[0] - self.location[0], safe[1] - self.location[1])
            if diff_pos[0] == -1:
                self.action = 'u'
            elif diff_pos[0] == 1:
                self.action = 'd'
            elif diff_pos[1] == -1:
                self.action = 'l'
            elif diff_pos[1] == 1:
                self.action = 'r'
            else:
                self.action = ''
Exemple #10
0
    def __init__(self, cb_profiles=["default"]):
        super().__init__()

        self._leet = None
        self._notification_queue = queue.SimpleQueue()
        self.hostname_list = None
        self.plugin = None
        self.backends = self._load_backends(cb_profiles)

        self._notify_thread = threading.Thread(
            target=self._wait_leet_notification, name="Thr-CLI-Notify")
        self.finished_jobs = []
        self._notified = False
    def __init__(self, reward_offset=100):
        super(ZincCoatingV0, self).__init__()

        self.action_space = spaces.Discrete(len(Actions))
        self.observation_space = spaces.Discrete(
            Constants.ZINC_COATING_DISCRETE_STEPS)

        self.reward_offset = reward_offset
        self.reward_queue = queue.SimpleQueue()
        for i in range(self.reward_offset):
            self.reward_queue.put(0)

        self.plotter = Plotter()
Exemple #12
0
    def __init__(self, index, prefernceString):
        self.index = index
        #makes a preferncelist from a string.

        pl = prefernceString.split(' ')

        prioQueue = queue.SimpleQueue()

        #prioqueue
        for i in range(0, len(pl)):
            prioQueue.put(int(pl[i]))

        self.queue = prioQueue
Exemple #13
0
    def __init__(self, hostname: str, port: int):
        self.hostname = hostname
        self.port = port

        try:
            self.sock = socket.create_connection((self.hostname, self.port),
                                                 2.0)  # 2 second timeout
        except ConnectionError as e:
            e.filename = f"{self.hostname}:{self.port}"
            raise

        # queue of 'dirty' messages to send: "id r,g,b"
        self.message_queue = queue.SimpleQueue()
Exemple #14
0
 def __init__(self, args, actor):
     super(MplayerPollingThread, self).__init__()
     self._actor = actor
     import mplayer
     if args.debug:
         self._player = mplayer.Player()
     else:
         self._player = mplayer.Player(stderr = subprocess.DEVNULL)
         pass
     self._refresh_interval = args.refresh_interval
     self.queue = queue.SimpleQueue()
     self.running = True
     pass
Exemple #15
0
def main():
    file = open("input", "r")
    program = [int(x) for x in re.findall("-?[0-9]+", file.readline())]
    memory = collections.defaultdict(lambda: 0, enumerate(program))
    file.close()

    hull = collections.defaultdict(lambda: 0)

    inputQ = queue.SimpleQueue()
    outputQ = queue.SimpleQueue()
    robot = threading.Thread(target=interpreter,
                             args=[memory.copy(), inputQ, outputQ])

    robot.start()

    position = [0, 0]
    direction = 0

    while robot.is_alive():
        inputQ.put(hull[tuple(position)])
        hull[tuple(position)] = outputQ.get()
        if outputQ.get():
            direction += 1
        else:
            direction -= 1
        direction %= 4

        if direction == 0:
            position[1] -= 1
        elif direction == 1:
            position[0] += 1
        elif direction == 2:
            position[1] += 1
        elif direction == 3:
            position[0] -= 1

    robot.join()

    print(len(hull))
 def get_bfs_graph(self, player_pos):
     bfs_graph = self.graph.copy()
     q = queue.SimpleQueue()
     q.put((player_pos, 0))
     while not q.empty():
         node, d = q.get()
         for neighbour in self.get_adjacent(node):
             if self.walkable_node(neighbour) and bfs_graph[neighbour[0]][neighbour[1]] == 0 and neighbour not in self.bombs:
                 q.put((neighbour, d + 1))
         bfs_graph[node[0]][node[1]] = d
     bfs_graph[player_pos[0]][player_pos[1]] = 0
     # print(bfs_graph)
     return bfs_graph
Exemple #17
0
    def __init__(self, character=characters.Bomber):
        super().__init__(character)

        # this will hold our current position
        self._position = None

        # this will hold the board state
        self._board = None

        # this queue will hold the actions for future turns
        self._actionQueue = queue.SimpleQueue()

        self._planned = False
Exemple #18
0
    def __init__(self, index, prefernceString):
        self.index = index
        #makes a preferncelist from a string.

        pl = prefernceString.split(' ')
        #puts preferenslist
        numberOfPersons = len(pl)
        prioQueue = queue.SimpleQueue()

        for i in range(0, numberOfPersons):
            prioQueue.put(int(pl[i]))

        self.prioQueue = prioQueue
Exemple #19
0
	def __init__(self, i, exp_name, sack, snoop):
		self.routing = routing.Routing(1000, i, exp_name)
		self.addr = self.routing.addr
		self.queues = {}
		self.sack = sack
		self.snoop = snoop
		self.queues[1] = queue.SimpleQueue()
		self.ack_queues = {}
		self.default_rwnd = 50
		self.exp_name = exp_name
		if not os.path.exists(exp_name):
			os.mkdir(exp_name)
		threading.Thread(target = self.listener).start()
 def maxDepth(self, root: TreeNode) -> int:
     if not root:
         return 0
     q = queue.SimpleQueue()
     q.put((1, root))
     res = 1
     while not q.empty():
         res, p = q.get()
         if p.left:
             q.put((res + 1, p.left))
         if p.right:
             q.put((res + 1, p.right))
     return res
Exemple #21
0
    def evade_bombs(self):
        q = queue.SimpleQueue()
        q.put((self.location, 0))
        visited = {self.location: True}

        safe = None
        while not q.empty() and safe is None:
            c_pos, d = q.get()  # current position
            if d > 2:  # cannot escape within 2 moves
                break
            adjacent = self.get_adjacent(c_pos)
            for a_pos in adjacent:  # adjacent position
                if a_pos in self.bombs:
                    continue
                if a_pos[0] > 9 or a_pos[0] < 0 or a_pos[1] > 11 or a_pos[
                        1] < 0:  # out of bounds
                    continue
                if self.graph[a_pos[0]][a_pos[1]] == -1:  # block
                    continue
                if a_pos in visited or a_pos == self.opponent_location:  # already visited
                    continue
                if d == 0 and not a_pos in self.blast_radius_1tick and not a_pos in self.blast_radius_2tick:
                    safe = a_pos
                    break
                if d == 1 and not a_pos in self.blast_radius_2tick:
                    if c_pos not in self.blast_radius_1tick:
                        safe = c_pos
                        break
                visited[c_pos] = True
                q.put((a_pos, d + 1))
        if safe is None:
            return ''

        print(f't1: {self.blast_radius_1tick}')
        print(f't2: {self.blast_radius_2tick}')
        print(f'Going from {self.location} to {safe}')
        diff_pos = (safe[0] - self.location[0], safe[1] - self.location[1])
        if diff_pos[0] == -1:
            print('up')
            return 'u'
        elif diff_pos[0] == 1:
            print('down')
            return 'd'
        elif diff_pos[1] == -1:
            print('left')
            return 'l'
        elif diff_pos[1] == 1:
            print('right')
            return 'r'
        else:
            return ''
Exemple #22
0
 def __init__(self,
              group=None,
              daemon=None,
              autostart=True,
              *args,
              **kwargs):
     super().__init__(target=self.executor,
                      group=group,
                      daemon=daemon,
                      args=args,
                      kwargs=kwargs)
     self.tasks = queue.SimpleQueue()
     if autostart:
         self.start()
Exemple #23
0
    def __init__(self, phy):
        """Sets up data link layer for Root robot. Kicks off some threads
        used to manage the connection, and uses initialize_state() to
        populate some information about the robot into the class.

        Parameters
        ----------
        phy: RootPhy
            Initialized RootPhy object. Used to pick physical layer.
        """

        colorama.init()

        self._phy = phy
        # do some check here to be sure phy is an initialized RootPhy object

        try:
            self._tx_q = queue.SimpleQueue()
        except AttributeError:
            self._tx_q = queue.Queue()
        self._rx_q = self._phy.rx_q

        self.pending_lock = threading.Lock()
        self.pending_resp = []
        """list: List of responses pending from the robot."""

        self.sniff_mode = False
        """bool: If True, shows the raw transactions to and from the robot."""

        self.ignore_crc_errors = False
        """bool: If true, ignores CRC errors in packets from the robot."""

        self.stop_project_flag = threading.Event()
        """Event: signals that Stop Project message was received."""

        self.state = {}
        """dict: Contains local state of robot"""

        self._last_coord = (0 + 0j)
        """complex: Contains last known coordinates of robot."""
        self._last_theta_x10 = 900
        """int: Contains last known heading of robot."""

        self.create_empty_state()

        threading.Thread(target=self._sending_thread).start()
        threading.Thread(target=self._receiving_thread).start()
        threading.Thread(target=self._expiration_thread).start()

        self.initialize_state()
Exemple #24
0
def coop(func, *args, **kwargs):
    """Run the given function in a new thread and make it cooperate with AHK's
    event loop.

    Use :func:`!coop` to execute long-running I/O bound Python processes like
    HTTP servers and stdin readers that are designed to handle
    :exc:`KeyboardInterrupt`::

        import code
        ahkpy.coop(code.interact)

    This call runs the given function in a new thread and waits for the function
    to finish. Returns the function result or raises the exception.

    Whenever :exc:`KeyboardInterrupt` occurs in the main thread, it's propagated
    to the background thread so it could stop.

    Calling :func:`!coop` from a background thread doesn't start a new one.
    Instead, the given function is executed in the current thread.
    """
    if threading.current_thread() is not threading.main_thread():
        # Just execute the function, we are already in another thread.
        return func(*args, **kwargs)

    q = queue.SimpleQueue()
    th = threading.Thread(
        target=_run_coop,
        args=(q, func, args, kwargs),
        daemon=True,
    )
    th.start()
    while True:
        try:
            if not th.is_alive():
                break
            sleep(_poll_interval)
        except KeyboardInterrupt:
            set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
            thread_id = th.ident
            kbd_interrupt = ctypes.py_object(KeyboardInterrupt)
            if th.is_alive():
                set_async_exc(thread_id, kbd_interrupt)

    try:
        val, exc = q.get_nowait()
    except queue.Empty:
        raise RuntimeError("coop thread did not return a value") from None
    if exc is not None:
        raise exc
    return val
Exemple #25
0
def main():
    file = open("input", "r")
    program = [int(x) for x in re.findall(r"-?\d+", file.readline())]
    memory = collections.defaultdict(lambda: 0, enumerate(program))
    file.close()

    inputQ = queue.SimpleQueue()
    outputQ = queue.SimpleQueue()

    jumpProgram = "NOT A T\nNOT B J\nOR T J\nNOT C T\nOR T J\nAND D J\nWALK\n"
    for s in jumpProgram:
        inputQ.put(ord(s))
    print("")

    intcode(memory, inputQ, outputQ)

    output = []
    while outputQ.qsize() > 1:
        charValue = outputQ.get()
        output.append(chr(charValue))

    print("".join(output))
    print(outputQ.get())
Exemple #26
0
    def Demo_Monitor(self, void, context):
        common.authenticate(context, must_be_one_of=(b"PEP3 demonstrator", ))

        q = queue.SimpleQueue()

        with self.messages_lock:
            self.messages_queues.append(q)

        try:
            while True:
                yield q.get()
        finally:
            with self.messages_lock:
                self.messages_queues.remove(q)
Exemple #27
0
 def __init__(
     self,
     parent_stream: typing.IO[str],
     *args: typing.Any,
     **kwargs: typing.Any,
 ) -> None:
     # TODO[mypy issue 4001]: Remove type ignore.
     super().__init__(*args, **kwargs)  # type: ignore[call-arg]
     self._buffered_lines: Queue[str] = Queue()
     self._loop = asyncio.get_event_loop()
     self._parent_stream = parent_stream
     self._request_queue: queue.SimpleQueue[bool] = queue.SimpleQueue()
     self._worker_thread = Thread(target=self._run, daemon=True)
     self._worker_thread.start()
Exemple #28
0
  def execute(self, context):
    self.timer = time.time()
    self.coverage = 0.0
    packer_props = context.scene.UVPackerProps
    packer_props.dbg_msg = ""
    
    if len(bpy.context.selected_objects) == 0:
      return {"FINISHED"}

    options = {
      "PackMode": misc.resolve_engine(packer_props.uvp_engine),
      "Width": packer_props.uvp_width,
      "Height": packer_props.uvp_height,
      "Padding": packer_props.uvp_padding,
      "Rescale": packer_props.uvp_rescale,
      "PreRotate": packer_props.uvp_prerotate,
      "Rotation": int(packer_props.uvp_rotate),
      "FullRotation": packer_props.uvp_fullRotate,
      "Combine": packer_props.uvp_combine,
      "TilesX": packer_props.uvp_tilesX,
      "TilesY": packer_props.uvp_tilesY
    }

    packerDir = os.path.dirname(os.path.realpath(__file__))
    packerExe = packerDir + "\\UV-Packer-Blender.exe"

    try:
      self.process = subprocess.Popen([packerExe], stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=False)
    except:
      msgStr = "UV-Packer executable not found. Please copy UV-Packer-Blender.exe to: " + packerDir
      self.update_status(msgStr, "ERROR")
      return {"FINISHED"}

    wm = context.window_manager
    wm.modal_handler_add(self)

    unique_objects = misc.get_unique_objects(context.selected_objects)
    meshes = misc.get_meshes(unique_objects)

    if packer_props.uvp_create_channel:
      misc.set_map_name(packer_props.uvp_channel_name)
      misc.add_uv_channel_to_objects(unique_objects)

    bpy.ops.object.mode_set(mode = "EDIT")
    self.msg_queue = queue.SimpleQueue()

    self.packer_thread = threading.Thread(target=misc.data_exchange_thread, args=(self.process, options, meshes, self.msg_queue))
    self.packer_thread.daemon = True
    self.packer_thread.start()
    return {"RUNNING_MODAL"}
Exemple #29
0
    def __init__(self, args, stream):
        super().__init__()
        self.output_file = None
        self.queue = queue.SimpleQueue()
        self.num_channels = stream.channels
        self.sample_size = stream.samplesize

        self.encoder = pyflac.StreamEncoder(
            callback=self.encoder_callback,
            sample_rate=int(stream.samplerate),
            compression_level=args.compression_level)

        if args.output_file:
            self.output_file = open(args.output_file, 'wb')
Exemple #30
0
    def __init__(self, speed_normalizer, number_of_sensors,
                 velocity_queue_length, weights):
        self.speed_normalizer = speed_normalizer
        self.number_of_sensors = number_of_sensors
        self.inner_layer_1_nodes = 4
        self.velocity_queue = queue.SimpleQueue()
        self.output_kind = "absolute"
        self.weights = weights
        #self.weights_0           = 2 * (np.random.rand(number_of_sensors + self.inner_layer_1_nodes + 1, self.inner_layer_1_nodes) - 0.5) # initialize weights with random uniform distribution between -1 and 1
        #self.weights_1           = 2 * (np.random.rand(self.inner_layer_1_nodes, 2) - 0.5) # initialize weights with random uniform distribution between -1 and 1

        for i in range(velocity_queue_length):
            self.velocity_queue.put(np.zeros(self.inner_layer_1_nodes))
        pass