def __init__(self, tap):
     """
     tap (RingPosition): the starting point where our stretch begins
     """
     self.__in_tap = tap
     self.__buffer = Ring(2**16)
     self.__fading_out = False
예제 #2
0
    def __init__(self):
        """
        The constructor and initiator.
        :return:
        """
        # initial setup
        super(mainWindow, self).__init__()
        self.setupUi(self)

        # create an instance of the table data and give yourself as UI Interface
        self.ame_data = AMEData(self)

        # take care about ring combo
        self.ring_dict = Ring.get_ring_dict()
        keys = list(self.ring_dict.keys())
        keys.sort()
        self.comboBox_ring.addItems(keys)
        self.current_ring_name = ''

        self.comboBox_ring.setCurrentIndex(4)
        self.on_comboBox_ring_changed(4)

        # fill combo box with names
        self.comboBox_name.addItems(self.ame_data.names_list)

        # UI related stuff
        self.setup_table_view()
        self.connect_signals()

        # A particle to begin with
        self.particle = None
        self.comboBox_name.setCurrentIndex(6)
        self.reinit_particle()
예제 #3
0
    def __init__(self, expression):

        FieldItem.__init__(self)

        # Parse Expression if needed
        if type(expression) is str:
            expression = parse(expression)
            debug(2, 'init Figure', expression)

        self.expression = expression.withRoot()

        # History of Expression
        self.history = history.History()

        # Colorspace
        self.detColorSpace()

        # Size of Figure
        self.sizeRing = Ring(
            (0, 0), 1.0)  # Ring for setting size of Figure (used in morphing)
        self.refreshTransform()

        self.groups = []
        self.buildGroups()
        self.buildGeometry()

        self.history.step(self.expression.copy())

        # Eating Act
        self.eating = None
예제 #4
0
    def __init__(self):
        """
        The constructor and initiator.
        :return:
        """
        # initial setup
        super(mainWindow, self).__init__()
        self.setupUi(self)

        # create an instance of the table data and give yourself as UI Interface
        self.ame_data = AMEData(self)

        # take care about ring combo
        self.ring_dict = Ring.get_ring_dict()
        keys = list(self.ring_dict.keys())
        keys.sort()
        self.comboBox_ring.addItems(keys)
        self.current_ring_name = ''

        self.comboBox_ring.setCurrentIndex(4)
        self.on_comboBox_ring_changed(4)

        # fill combo box with names
        self.comboBox_name.addItems(self.ame_data.names_list)

        # UI related stuff
        self.setup_table_view()
        self.connect_signals()

        # A particle to begin with
        self.particle = None
        self.comboBox_name.setCurrentIndex(6)
        self.reinit_particle()
예제 #5
0
    def prepare(self):
        ame_data = AMEData(DummyIFace())

        # create reference particle
        p = Particle(6, 6, ame_data, Ring('ESR', 108.5))
        p.qq = 3
        p.ke_u = 422
        p.path_length_m = 108.5
        p.f_analysis_mhz = 245
        p.i_beam_uA = 1.2
        print('Reference particle:', p)
        print('Isobars:')
        for pp in p.get_isobars():
            print(pp)
        # get some nuclides
        # nuclides = p.get_all_in_all()
        nuclides = p.get_nuclides(57, 59, 81, 83, 2)
        #nuclides = p.get_nuclides(20, 92, 40, 143, 10)
        self.n_rows = int(len(nuclides))

        self.nuclidic_data = np.array([])
        self.nuclidic_labels = []

        for pp in nuclides:
            pp.calculate_revolution_frequency()
            brho = pp.get_magnetic_rigidity()
            values = [pp.revolution_frequency, brho]
            self.n_cols = len(values)

            self.nuclidic_data = np.append(self.nuclidic_data, values)
            self.nuclidic_labels.append(pp.get_short_name())

        # print(self.nuclidic_labels)
        self.nuclidic_data = np.reshape(self.nuclidic_data,
                                        (self.n_rows, self.n_cols))
	def packetizerReset(self):
		"""
		To be called on an error; flush out the packetizer and return it
		to its normal state.
		"""
		self._state = self.FRAME
		self._ring = Ring()
예제 #7
0
 def key_listener(self, event):
     key = repr(event.char) 
     if key == "'q'":
         self.entities.append(Ring("blue", self))
     else:
         for i in self.entities:
             if type(i) is Ring:
                 ring = i
                 print("Ring pos: " , ring.y)
                 msg = self.check_accuracy(ring.y)
예제 #8
0
    def __init__(self):

        # Group Topology
        self.parent = None  # Noke  # not Bubble: for Group.buildGeometry()
        self.childs = []  # Nokes
        self.upper = False  # Upper level - first child

        self.group = None  # Parent Group of Bubble

        # Geometry and Correction
        self.ring = Ring((0, 0), 1)

        # For building Geometry
        self.tight = 0  # Left (Parents) and right (Childs) Tights
        self.corr = 0  # Correction of Radius
        self.angles = {}  # dict {Bubble:angle}

        # Eating
        self.fading = None  # Fading object
예제 #9
0
 def testNecklace(self):
     testMetal: str = "platinum"
     testGem: str = "ruby"
     testSize: int = 8
     ring = Ring(metal=testMetal, gem=testGem, size=testSize)
     self.assertEqual(ring.gem, "ruby")
     self.assertEqual(ring.metal, "platinum")
     ring.gem = "pearl"
     ring.metal = "titanium"
     ring.size = 7
     self.assertEqual(ring.gem, "pearl")
     self.assertEqual(ring.metal, "titanium")
     ring.wear()
     self.assertEqual(ring.polished, False)
     ring.polish()
     self.assertEqual(ring.polished, True)
예제 #10
0
 def testRing(self):
     ring = Ring()
     self.assertEqual(ring.polished, True)
     ring.wear()
     self.assertEqual(ring.polished, False)
     ring.polish()
     self.assertEqual(ring.polished, True)
예제 #11
0
    def start_draft(
        self,
        users: t.Iterable[AbstractUser],
        pool_specification: PoolSpecification,
        infinites: Infinites,
        draft_format: str,
        reverse: bool,
        finished_callback: t.Callable[[Draft], None],
    ) -> t.Tuple[t.Tuple[AbstractUser, Drafter], ...]:

        drafters = tuple(
            (
                user,
                Drafter(
                    user,
                    str(uuid.uuid4()),
                ),
            )
            for user in
            users
        )

        drafters_ring = Ring(
            drafter
            for _, drafter in
            drafters
        )

        def _finished_callback(_draft: Draft):
            self.draft_complete(_draft)
            finished_callback(_draft)

        draft = Draft(
            key = str(uuid.uuid4()),
            drafters = drafters_ring,
            pool_specification = pool_specification,
            infinites = infinites,
            draft_format = draft_format,
            finished_callback = _finished_callback,
            reverse = reverse,
        )

        draft.start()

        with self._lock:
            self._drafts.add(draft)

            for drafter in drafters_ring.all:
                self._drafters[drafter.key] = draft.get_draft_interface(drafter)

        return drafters
예제 #12
0
    def __init__(self, env, inner_circle_len, outer_circle_len):
        # Test circle lengths
        for circle_len in (inner_circle_len, outer_circle_len):
            assert circle_len >= 16, 'Circle lenght has to be at least 16'
            assert circle_len % 4 == 0, 'Circle lenght must be divisible by 4'

        self.env = env

        # Generate circles of Resources
        self.inner_circle = Ring([
            simpy.resources.resource.PriorityResource(env, capacity=1)
            for i in range(inner_circle_len)
        ])
        self.outer_circle = Ring([
            simpy.resources.resource.PriorityResource(env, capacity=1)
            for i in range(outer_circle_len)
        ])

        # Create indices of exit slots (exit pointers)
        self.inner_exits_indices = RoundAbout.Exits(
            *RoundAbout.calculate_exit_indices(inner_circle_len))
        self.outer_exits_indices = RoundAbout.Exits(
            *RoundAbout.calculate_exit_indices(outer_circle_len))
예제 #13
0
def test_tap_activation():
    a = Ring(16)
    t = a.create_tap()
    t.deactivate()
    assert t.name in a.inactive_taps
    assert t.name not in a.active_taps
    a.append(np.arange(15))
    a.append([99])
    t.activate()
    assert t.name in a.active_taps
    assert t.name not in a.inactive_taps
    s = t.get_samples(1)
    assert s[0] == 99
예제 #14
0
    def getBounding(bubbles):
        "Returns Bounding Ring of Bubbles in Group"

        center = Vector2((0, 0))
        ws = 0
        for b in bubbles:
            weight = b.ring.r**2
            center += b.ring.pos * weight
            ws += 1.0 * weight
        center /= ws

        radius = max([ Vector2( center, b.ring.pos ).length() + b.ring.r  \
                        for b in bubbles ])

        return Ring(center, radius)
예제 #15
0
class EggRing(object):
    def __init__(self, x, y, t, sp):
        self.ovoid = Egg(x, y, t, sp)
        self.circle = Ring()
        self.circle.start(x, y - sp / 2)

    def transmit(self):
        self.ovoid.wobble()
        self.ovoid.display()
        self.circle.grow()
        self.circle.display()
        if self.circle.on == False:
            self.circle.on = True
예제 #16
0
class EggRing(object):

    def __init__(self, x, y, t, sp):
        self.ovoid = Egg(x, y, t, sp)
        self.circle = Ring()
        self.circle.start(x, y - sp / 2)

    def transmit(self):
        self.ovoid.wobble()
        self.ovoid.display()
        self.circle.grow()
        self.circle.display()
        if self.circle.on == False:
            self.circle.on = True
예제 #17
0
    def __init__( self ):

        # Group Topology
        self.parent = None     # Noke  # not Bubble: for Group.buildGeometry()
        self.childs = []       # Nokes
        self.upper  = False    # Upper level - first child

        self.group  = None     # Parent Group of Bubble

        # Geometry and Correction
        self.ring   = Ring((0,0),1)
        
        # For building Geometry
        self.tight  = 0         # Left (Parents) and right (Childs) Tights
        self.corr   = 0         # Correction of Radius
        self.angles = {}        # dict {Bubble:angle}

        
        # Eating
        self.fading = None      # Fading object
예제 #18
0
파일: node.py 프로젝트: vamc19/pythonamo
class Node(object):

    def __init__(self, is_leader, leader_hostname, my_hostname, tcp_port=13337, sloppy_Qsize=5, sloppy_R=3, sloppy_W=3):

        self.ongoing_requests = []
        self.is_leader = is_leader
        self.leader_hostname = leader_hostname
        self.hostname = my_hostname
        self.tcp_port = tcp_port
        self.my_address = (self.hostname, self.tcp_port)

        self.membership_ring = Ring(replica_count=sloppy_Qsize - 1)  # Other nodes in the membership
        if self.is_leader:
            self.membership_ring.add_node(leader_hostname)

        # todo: look into this, do we need both?
        self.bootstrapping = True
        self.is_member = False

        # Flag to keep track of a add-node is underway
        self._membership_in_progress = False

        self.sloppy_Qsize = sloppy_Qsize  # total members to replicate on

        # number of peers required for a read or write to succeed.
        self.sloppy_R = sloppy_R
        self.sloppy_W = sloppy_W

        # Book keeping for membership messages
        self._req_responses = defaultdict(set)
        self._sent_req_messages = {}
        self._received_req_messages = {}
        self._req_sender = {}  # Keeps track to sender for add and delete requests
        self.current_view = 0  # increment this on every leader election
        self.membership_request_id = 0  # increment this on every request sent to peers

        # Maintains handoff messages to be sent
        # IP : set(handoff messages)
        self._handoff_messages = defaultdict(set)
        self.handoff_timer = None
        self.create_handoff_timer = lambda: Timer(5, self.try_sending_handoffs)

        self.log_prefix = os.getcwd()
        self.ring_log_file = os.path.join(self.log_prefix, self.hostname + '.ring')
        self.db_path = os.path.join(self.log_prefix, self.hostname + '.db')
        self.handoff_log = os.path.join(self.log_prefix, self.hostname + '.pickle')

        try:
            with open(self.ring_log_file, 'r') as f:
                hosts = f.readlines()
                for h in hosts:
                    self.membership_ring.add_node(h.strip())
            print("Restored membership information from %s" % self.ring_log_file)
        except FileNotFoundError:
            pass

        try:
            with open(self.handoff_log, 'rb') as f:
                self._handoff_messages = pickle.loads(f.read())

            if len(self._handoff_messages) > 0:
                self.handoff_timer = self.create_handoff_timer()
                self.handoff_timer.start()

            print("Restored hand off messages from %s" % self.handoff_log)
        except FileNotFoundError:
            pass

        self.request_timelimit = 2.0
        self.req_message_timers = {}

        self.db = Storage(self.db_path)  # set up sqlite table

        # create tcp socket for communication with peers and clients
        self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_socket.setblocking(False)  # Non-blocking socket
        self.tcp_socket.bind((self.hostname, self.tcp_port))
        self.tcp_socket.listen(10)

        # has hostnames mapped to open sockets
        self.connections = {}
        self.client_list = set()

    def accept_connections(self):
        incoming_connections = {self.tcp_socket}
        print("Accepting connections...")

        while True:
            readable, _, _ = select.select(incoming_connections, [], [], 0)
            for s in readable:
                if s is self.tcp_socket:
                    connection, client_address = s.accept()
                    connection.setblocking(False)

                    incoming_connections.add(connection)
                    self.connections[client_address[0]] = connection

                else:
                    try:
                        header = s.recv(5)
                    except:
                        print("Connection reset.")
                        continue

                    if not header:  # remove for connection pool and close socket
                        incoming_connections.remove(s)
                        # del self.connections[s.getpeername()[0]]
                        s.close()
                    else:
                        message_len = struct.unpack('!i', header[1:5])[0]

                        data = b''
                        while len(data) < message_len:
                            try:
                                data += s.recv(message_len - len(data))
                            except socket.error as err:
                                pass

                        self._process_message(header + data, s.getpeername()[0])  # addr is a tuple of hostname and port

    def _process_message(self, data, sender):
        message_type, data_tuple = messages._unpack_message(data)

        message_type_mapping = {
            b'\x00': self._process_command,
            b'\x01': self._process_req_message,
            b'\x10': self._membership_change_message,
            b'\xff': self._process_ok_message,
            b'\x07': self.perform_operation,
            b'\x08': self.perform_operation,
            b'\x70': self.update_request,
            b'\x80': self.update_request,
            b'\x0B': self.update_request,
            b'\x0A': self.handle_forwarded_req,
            b'\x0C': self.handle_handoff
        }

        message_type_mapping[message_type](data_tuple, sender)
        return

    def _process_command(self, user_input, sendBackTo):
        """Process commands"""

        self.client_list.add(sendBackTo)

        # Maps command to the corresponding function.
        # Command arguments are passed as the first argument to the function.
        command_registry = {  # Possible commands:
            "add-node": self.add_node,  # 1. add node to membership
            "remove-node": self.remove_node,  # 2. remove node from membership
            "put": self.put_data,  # 3. put data
            "get": self.get_data,  # 4. get data
        }

        if not user_input:
            self._send_req_response_to_client(sendBackTo, "User input empty")

        # First word is command. Rest are then arguments.
        command, *data = user_input.split(" ")
        if command not in command_registry:
            self._send_req_response_to_client(sendBackTo, "Invalid command")

        # Call the function associated with the command in command_registry
        return command_registry[command](data, sendBackTo)

    def handle_handoff(self, data, sendBackTo):
        # data should have (message, list of hosts to hand data off to)

        for h in data[1]:
            print("Storing hand off message for %s" % h)
            self._handoff_messages[h].add(data[0])

        # Save handoff messages to disk
        self.sync_handoffs_to_disk()

        # check and start timer
        if not self.handoff_timer:
            self.handoff_timer = self.create_handoff_timer()
            self.handoff_timer.start()

    def try_sending_handoffs(self):
        print("Attempting to send hand off messages...")

        updated_handoff_messages = defaultdict(set)

        for (host, msgs) in self._handoff_messages.items():
            for msg in msgs:
                fail = self.broadcast_message([host], msg)
                if fail:
                    updated_handoff_messages[host].add(msg)

        self._handoff_messages = updated_handoff_messages
        self.sync_handoffs_to_disk()

        if len(self._handoff_messages) > 0:
            print("Undelivered hand offs. Restarting timer")
            self.handoff_timer = self.create_handoff_timer()
            self.handoff_timer.start()
            return

        print("Sent all hand off messages.")
        self.handoff_timer = None

    def sync_handoffs_to_disk(self):
        # Save hand off messages to disk
        with open(self.handoff_log, 'wb') as f:
            f.write(pickle.dumps(self._handoff_messages))

    def add_node(self, data, sender):
        """Add node to membership. data[0] must be the hostname. Initiates 2PC."""

        if not self.is_leader:
            self._send_req_response_to_client(sender, "Error: This is not the leader")
            return

        if not data:
            self._send_req_response_to_client(sender, "Error: hostname required")
            return

        if self._membership_in_progress:
            self._send_req_response_to_client(sender, "Membership operation in progress. Try again")
            return

        if data[0] in self.membership_ring:
            self._send_req_response_to_client(sender, "Already in the membership")
            return

        self._membership_in_progress = True

        print("Starting add-node operation for %s" % data[0])
        new_peer_message = messages.reqMessage(self.current_view, self.membership_request_id, 1, data[0])

        # associate hostname to (view_id, req_id)
        self._sent_req_messages[(self.current_view, self.membership_request_id)] = (data[0], 1)
        self._req_sender[(self.current_view, self.membership_request_id)] = sender

        # broadcast to all but leader.
        nodes_to_broadcast = self.membership_ring.get_all_hosts()
        nodes_to_broadcast.remove(self.hostname)
        nodes_to_broadcast.add(data[0])  # Add new host to broadcast list

        self.broadcast_message(nodes_to_broadcast, new_peer_message)

        t = Timer(self.request_timelimit, self._req_timeout, args=[(self.current_view, self.membership_request_id)])
        self.req_message_timers[(self.current_view, self.membership_request_id)] = t
        t.start()

        self.membership_request_id += 1

    # Send a remove node message to everyone and if you are that node, shutdown
    def remove_node(self, data, sender):
        if not self.is_leader:
            self._send_req_response_to_client(sender, "Error: This is not the leader")
            return

        if not data:
            self._send_req_response_to_client(sender, "Error: hostname required")
            return

        if self._membership_in_progress:
            self._send_req_response_to_client(sender, "Membership operation in progress. Try again")
            return

        if data[0] not in self.membership_ring:
            self._send_req_response_to_client(sender, "Cannot remove. Node not in membership")
            return

        self._membership_in_progress = True
        print("Starting remove-node operation for %s" % data[0])
        new_peer_message = messages.reqMessage(self.current_view, self.membership_request_id, 2, data[0])

        # associate hostname to (view_id, req_id)
        self._sent_req_messages[(self.current_view, self.membership_request_id)] = (data[0], 2)
        self._req_sender[(self.current_view, self.membership_request_id)] = sender

        # broadcast to all but leader.
        nodes_to_broadcast = self.membership_ring.get_all_hosts()
        nodes_to_broadcast.remove(self.hostname)
        nodes_to_broadcast.add(data[0])  # Add new host to broadcast list

        self.broadcast_message(nodes_to_broadcast, new_peer_message)

        t = Timer(self.request_timelimit, self._req_timeout, args=[(self.current_view, self.membership_request_id)])
        self.req_message_timers[(self.current_view, self.membership_request_id)] = t
        t.start()

        self.membership_request_id += 1

        # self.membership_ring.remove_node(data[0])

    def put_data(self, data, sendBackTo):
        if len(data) != 3:
            return "Error: Invalid operands\nInput: (<key>,<prev version>,<value>)"

        data = [data[0], json.loads(data[1]), data[2]]
        key = data[0]
        prev = data[1]
        value = data[2]
        target_node = self.membership_ring.get_node_for_key(data[0])
        if not self.is_leader:
            # forward request to leader for client
            return self._send_data_to_peer(self.leader_hostname, data, sendBackTo)

        else:  # I am the leader
            if target_node == self.hostname:
                # I'm processing a request for a client directly
                self.start_request('put', data, sendBackTo=sendBackTo)
                return

            else:  # I am forwarding a request from the client to the correct node
                return self._send_data_to_peer(target_node, data, sendBackTo)

    def get_data(self, data, sendBackTo):
        """Retrieve V for given K from the database. data[0] must be the key"""
        if not data:
            return "Error: key required"

        target_node = self.membership_ring.get_node_for_key(data[0])
        # if I can do it myself
        if target_node == self.hostname:
            # I am processing a request for a client directly
            self.start_request('get', data[0], sendBackTo=sendBackTo)

        else:  # forward the client request to the peer incharge of req
            self._request_data_from_peer(target_node, data[0], sendBackTo)

    def _process_req_message(self, data, sender):
        # data = (view_id, req_id, operation, address)
        (view_id, req_id, operation, address) = data

        print("Processed request message to add %s" % address)
        # save the message type
        self._received_req_messages[(view_id, req_id)] = (address, operation)
        ok_message = messages.okMessage(view_id, req_id)
        self.connections.get(sender, self._create_socket(sender)).sendall(ok_message)

    def _process_ok_message(self, data, sender):
        self._req_responses[data].add(sender)
        (new_peer_hostname, operation) = self._sent_req_messages[data]
        required_responses = len(self.membership_ring) if operation == 1 else (len(self.membership_ring) - 1)

        # number of replies equal number of *followers* already in the ring, add peer to membership
        if len(self._req_responses[data]) == required_responses:

            # Cancel timer
            t = self.req_message_timers.get(data, None)
            if not t:
                return
            t.cancel()

            # Send newViewMessage
            # self.current_view += 1

            if operation == 1:   # adding new node
                self.membership_ring.add_node(new_peer_hostname)
                hosts_to_send = self.membership_ring.get_all_hosts()
                nodes_to_broadcast = self.membership_ring.get_all_hosts()
            else:
                hosts_to_send = (new_peer_hostname, )
                nodes_to_broadcast = self.membership_ring.get_all_hosts()
                nodes_to_broadcast.remove(new_peer_hostname)
                self.membership_ring.remove_node(new_peer_hostname)

            membership_change_msg = messages.membershipChange(self.current_view, operation, hosts_to_send)

            nodes_to_broadcast.remove(self.hostname)
            self.broadcast_message(nodes_to_broadcast, membership_change_msg)

            print("Successfully %s %s." % ("added" if operation == 1 else "removed", new_peer_hostname))

            client = self._req_sender.get(data, None)
            self._send_req_response_to_client(client, "Successfully %s %s." %
                                              ("added" if operation == 1 else "removed", new_peer_hostname))

            self._membership_in_progress = False  # reset state to accept new connections

    def _membership_change_message(self, data, sender):
        (view_id, operation, peers) = data
        # self.current_view = view_id

        if operation == 1:  # add nodes
            for p in peers:
                if p not in self.membership_ring:
                    self.membership_ring.add_node(p)

        if operation == 2:
            for p in peers:
                if p in self.membership_ring:
                    self.membership_ring.remove_node(p)

        with open(self.ring_log_file, 'w') as f:
            for node in self.membership_ring.get_all_hosts():
                f.write(node + '\n')

        print("Successfully modified membership ring. Total members: %d" % len(self.membership_ring.get_all_hosts()))
        print("Current members: %s" % ", ".join(self.membership_ring.get_all_hosts()))
        print("Keys to manage: ", self.membership_ring.get_key_range(self.hostname))

    def _req_timeout(self, req_id):
        print("Error adding node to network. One or more nodes is offline.")

        # failed_hosts = set(self.membership_ring.get_all_hosts()) - self._req_responses[req_id]
        # failed_hosts.remove()
        sender = self._req_sender.get(req_id, None)
        self._send_req_response_to_client(sender, "Failed to add node to the network")
        self._membership_in_progress = False

    def _send_req_response_to_client(self, client, message):
        msg = messages.responseForForward(message)
        self.broadcast_message([client], msg)

    # request format:
    # object which contains
    # type
    # sendBackTo
    # forwardedTo =None if type is not for_*
    # hash
    # value =None if type is get or forget
    # context =None if type is get or forget
    # responses = { sender:msg, sender2:msg2... }

    # args format is determined by type:
    #   type='get', args='hash'
    #   type='put', args=('hash','value',{context})
    #   type='for_get', args=(target_node,'hash')
    #   type='for_put', args=(target_node, 'hash','value',{context})
    # Type can be 'put', 'get', 'for_put', 'for_get'
    # 'for_*' if for requests that must be handled by a different peer
    # then when the response is returned, complete_request will send the
    # output to the correct client or peer (or stdin)
    def start_request(self, rtype, args, sendBackTo, prev_req=None):
        print("%s request from %s: %s" % (rtype, sendBackTo, args))
        req = Request(rtype, args, sendBackTo, previous_request=prev_req)  # create request obj
        self.ongoing_requests.append(req)  # set as ongoing

        target_node = self.membership_ring.get_node_for_key(req.hash)
        replica_nodes = self.membership_ring.get_replicas_for_key(req.hash)

        T = Timer(self.request_timelimit + (1 if rtype[:3] == 'for' else 0),
                  self.complete_request, args=[req], kwargs={"timer_expired": True}
                  )
        T.start()
        self.req_message_timers[req.time_created] = T

        # Find out if you can respond to this request
        if rtype == 'get':
            # add my information to the request
            result = self.db.getFile(args)
            my_resp = messages.getFileResponse(args, result, req.time_created)
            self.update_request(messages._unpack_message(my_resp)[1], socket.gethostbyname(self.hostname), req)
            # send the getFile message to everyone in the replication range
            msg = messages.getFile(req.hash, req.time_created)
            # this function will need to handle hinted handoff

            print("Sending getFile message to %s" % ", ".join(replica_nodes))
            fails = self.broadcast_message(replica_nodes, msg)
            if fails:
                print("Failed to send get msg to %s" % ', '.join(fails))

        elif rtype == 'put':
            self.db.storeFile(args[0], socket.gethostbyname(self.hostname), args[1], args[2])
            my_resp = messages.storeFileResponse(args[0], args[1], args[2], req.time_created)
            # add my information to the request
            self.update_request(messages._unpack_message(my_resp)[1], socket.gethostbyname(self.hostname), req)
            # send the storeFile message to everyone in the replication range
            msg = messages.storeFile(req.hash, req.value, req.context, req.time_created)
            # this function will need to handle hinted handoff
            print("Sending storeFile message to %s" % ", ".join(replica_nodes))
            fails = self.broadcast_message(replica_nodes, msg)
            if fails:
                print("Failed to send put msg to %s" % ', '.join(fails))

        else:
            msg = messages.forwardedReq(req)
            # forward message to target node
            # self.connections[req.forwardedTo].sendall(msg)
            if self.broadcast_message([req.forwardedTo], msg):
                self.leader_to_coord(req)
            else:
                print("Forwarded Request to %s" % req.forwardedTo)

    def leader_to_coord(self, req):
        print("Leader is assuming role of coordinator")
        replica_nodes = self.membership_ring.get_replicas_for_key(req.hash)
        req.type = req.type[4:]

        if req.type == 'get':
            msg = messages.getFile(req.hash, req.time_created)
        else:
            msg = messages.storeFile(req.hash, req.value, req.context, req.time_created)

        self.broadcast_message(replica_nodes, msg)

    def find_req_for_msg(self, req_ts):
        return list(filter(
            lambda r: r.time_created == req_ts, self.ongoing_requests
        ))

    # after a \x70, \x80 or \x0B is encountered from a peer, this method is called
    def update_request(self, msg, sender, request=None):
        print("Updating Request with message ", msg, " from ", sender)
        if isinstance(msg, tuple):
            if not request:
                request = self.find_req_for_msg(msg[-1])
            min_num_resp = self.sloppy_R if len(msg) == 3 else self.sloppy_W
        else:
            request = self.find_req_for_msg(msg.previous_request.time_created)
            min_num_resp = 1

        if not request:
            print("No request found, ", sender, " might have been too slow")
            return
        elif isinstance(request, list):
            request = request[0]

        request.responses[sender] = msg
        if len(request.responses) >= min_num_resp:
            self.complete_request(request)

    def coalesce_responses(self, request):
        resp_list = list(request.responses.values())
        # check if you got a sufficient number of responses
        if len(resp_list) < self.sloppy_R:
            return None
        results = []
        for resp in resp_list:
            # print(resp)
            results.extend([
                tup for tup in resp[1] if tup not in results
            ])
        return self.db.sortData(results)

    def complete_request(self, request, timer_expired=False):

        failed = False

        if request.type == 'get':
            # if sendbackto is a peer
            if request.sendBackTo not in self.client_list:
                # this is a response to a for_*
                # send the whole request object back to the peer
                msg = messages.responseForForward(request)
            else:
                # compile results from responses and send them to client
                # send message to client
                msg = messages.getResponse(request.hash, (
                    self.coalesce_responses(request) if not failed else "Error"
                ))

        elif request.type == 'put':
            if len(request.responses) >= self.sloppy_W:
                print("Successful put completed for ", request.sendBackTo)

            if request.sendBackTo not in self.client_list:
                # this is a response to a for_*
                # send the whole request object back to the peer
                msg = messages.responseForForward(request)
            else:
                # send success message to client
                # check if you were successful
                msg = messages.putResponse(request.hash, (
                    request.value if len(request.responses) >= self.sloppy_W and not failed else "Error"
                ), request.context)

            # if len(request.responses) >= self.sloppy_W and timer_expired:
            if timer_expired and len(request.responses) < self.sloppy_Qsize:
                target_node = self.membership_ring.get_node_for_key(request.hash)
                replica_nodes = self.membership_ring.get_replicas_for_key(request.hash)

                all_nodes = set([target_node] + replica_nodes)
                missing_reps = set([self.membership_ring.hostname_to_ip[r] for r in all_nodes]) - set(request.responses.keys())

                handoff_store_msg = messages.storeFile(request.hash, request.value, request.context, request.time_created)

                handoff_msg = messages.handoff(
                    handoff_store_msg,
                    missing_reps
                )

                hons = [
                    self.membership_ring.get_handoff_node(r)
                    for r in missing_reps
                ]

                print("Handing off messages for %s to %s" % (", ".join(missing_reps), ", ".join(hons)))
                if self.hostname in hons:
                    self.handle_handoff((handoff_store_msg, missing_reps), self.hostname)
                    hons.remove(self.hostname)
                self.broadcast_message(hons, handoff_msg)

        else:  # request.type == for_*
            # unpack the forwarded request object
            data = list(request.responses.values())

            if not data:
                # del self.req_message_timers[request.time_created]
                # request.time_created=time.time()
                self.leader_to_coord(request)
                T = Timer(self.request_timelimit,
                          self.complete_request, args=[request], kwargs={"timer_expired": True}
                          )
                T.start()
                self.req_message_timers[request.time_created] = T
                return
            else:
                data = data[0]
                # if sendbackto is a peer
                if request.sendBackTo not in self.client_list:
                    # unpickle the returned put request
                    data.previous_request = data.previous_request.previous_request
                    # send the response object you got back to the peer
                    # from request.responses (it is the put or get they need)
                    # if you need to, make req.prev_req = req.prev_req.prev_req
                    # so it looks like you did the request yourself
                    msg = messages.responseForForward(data)
                elif request.type == 'for_put':
                    msg = messages.putResponse(request.hash, (
                        request.value if data and len(data.responses) >= self.sloppy_W and not failed else "Error"
                    ), request.context)
                else:  # for_get
                    msg = messages.getResponse(request.hash, (
                        self.coalesce_responses(data) if not failed else "Error"
                    ))

        # send msg to request.sendBackTo
        # if request.sendBackTo not in self.client_list:
        if not request.responded:
            print("Sending response back to ", request.sendBackTo)
            self.broadcast_message([request.sendBackTo], msg)
            request.responded = True

        if timer_expired:
            # remove request from ongoing list
            self.ongoing_requests = list(filter(
                lambda r: r.time_created != request.time_created, self.ongoing_requests
            ))

    def perform_operation(self, data, sendBackTo):
        if len(data) == 2:  # this is a getFile msg
            print("%s is asking me to get %s" % (sendBackTo, data[0]))
            msg = messages.getFileResponse(data[0], self.db.getFile(data[0]), data[1])
        else:  # this is a storeFile
            print("%s is asking me to store %s" % (sendBackTo, data[0]))
            self.db.storeFile(data[0], sendBackTo, data[1], data[2])
            msg = messages.storeFileResponse(*data)

        self.broadcast_message([sendBackTo], msg)

    def handle_forwarded_req(self, prev_req, sendBackTo):
        target_node = self.membership_ring.get_node_for_key(prev_req.hash)
        print("Handling a forwarded request [ %s, %f ]" % (prev_req.type, prev_req.time_created))

        if time.time() - prev_req.time_created < self.request_timelimit:
            # someone forwarded you a put request
            # if you are the leader, check if you can takecare of it, else,
            # start a new put request with this request as the previous one
            if prev_req.type == 'put' or prev_req.type == 'for_put':
                if self.is_leader:
                    if target_node == self.hostname:
                        args = (prev_req.hash, prev_req.value, prev_req.context)
                        self.start_request('put', args, sendBackTo, prev_req=prev_req)
                    else:
                        args = (target_node, prev_req.hash,
                                prev_req.value, prev_req.context
                                )
                        self.start_request('for_put', args, sendBackTo, prev_req)

                else:  # the leader is forwarding you a put
                    args = (prev_req.hash, prev_req.value, prev_req.context)
                    self.start_request('put', args, sendBackTo, prev_req=prev_req)

            # someone forwarded you a get request, you need to take care of it
            # start new get request with this as the previous one
            else:  # type is get or for_get
                self.start_request('get', prev_req.hash, sendBackTo, prev_req)

    def _send_data_to_peer(self, target_node, data, sendBackTo):
        # create for_put request
        self.start_request('for_put', [target_node] + data, sendBackTo=sendBackTo)

    def _request_data_from_peer(self, target_node, data, sendBackTo):
        self.start_request('for_get', (target_node, data), sendBackTo=sendBackTo)

    def _create_socket(self, hostname):
        """Creates a socket to the host and adds it connections dict. Returns created socket object."""
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setblocking(False)
        s.settimeout(1)  # 10 seconds
        try:
            s.connect((hostname, self.tcp_port))
            self.connections[socket.gethostbyname(hostname)] = s
            return s
        except Exception as e:
            if hostname not in self.client_list:
                print("Error creating connection to %s: %s" % (hostname, e))
            return None

    # this is where we need to handle hinted handoff if a
    # peer is not responsive by asking another peer to hold the
    # message until the correct node recovers
    def broadcast_message(self, nodes, msg):
        fails = []
        for node in nodes:
            c = self.connections.get(node, self._create_socket(node))
            if not c:
                fails.append(node)
                continue
            c.sendall(msg)

        return fails
예제 #19
0
 def __init__(self, ring_name, module_id):
     Ring.__init__(self, ring_name, module_id, StatusMessage)
예제 #20
0
    def test_ring_size(self):
        ring = Ring(1)

        self.assertEqual(str(ring), '1')
예제 #21
0
	def validateRings(self, ringContent):
		
		if self.dbwritten:
			self.webclient.sendMessage(WebSocketMessage.create("local","TTTS_GAME_OVER_MSGS","Rings verification cancelled, results already written to DB"))
			return
		
		ring = json.loads(ringContent)
		
		result = ring['result']
		sha256 = ring['sha256']
		ringsignature = ring['sign']
		
		testsha256 = hashlib.sha256(result).hexdigest()

		if testsha256 != sha256:
			print "ERROR: The hashes %s and %s are not equal"%(testsha256,sha256)
			return;
		
		result = json.loads(result.replace("'", "\"").replace("\n", "$"))
		
		p1 = result['player1']
		p2 = result['player2']
		s1 = result['spectator']
		
		result['player1'][1] = result['player1'][1].replace("$", "\n")
		result['player2'][1] = result['player2'][1].replace("$", "\n")
		result['spectator'][1] = result['spectator'][1].replace("$", "\n")
		
		p1key = RSA.importKey(result['player1'][1])
		p2key = RSA.importKey(result['player2'][1])
		s1key = RSA.importKey(result['spectator'][1])
		
		ringGroupStr = ringsignature.keys()[0]
		
		ringGroup = ringGroupStr.split(":")
		
		if ringGroup[0] == "player1":
			firstkey = p1key;
		elif ringGroup[0] == "player2":
			firstkey = p2key;
		elif ringGroup[0] == "spectator":
			firstkey = s1key
		else:
			print "Signature label unknown: " + ringGroup[1]
		
		if ringGroup[1] == "player1":
			secondkey = p1key;
		elif ringGroup[1] == "player2":
			secondkey = p2key;
		elif ringGroup[1] == "spectator":
			secondkey = s1key
		else:
			print "Signature label unknown: " + ringGroup[1]
			
		testring = Ring([firstkey, secondkey], 2048)
		
		verify = testring.verify(sha256, ringsignature[ringsignature.keys()[0]] )

		if (verify):
			added = False
			for (k, r) in self.validrings:
				if k == ringGroupStr:
					added = True
			
			if not added:
				ring['result'] = result;
				self.validrings.append((ringGroupStr, ring))
		else:
			print "Ring verification failed "
			self.webclient.sendMessage(WebSocketMessage.create("local","TTTS_GAME_OVER_MSGS","Verification of a ring failed"))
		
		verif = str(len(self.validrings)) + " rings verified"
		print verif
		self.webclient.sendMessage(WebSocketMessage.create("local","TTTS_GAME_OVER_MSGS", verif))
		self.storeifthree()
class Packetizer (log.Base):
	"""
	A packetizer that is used to read and write to an underlying
	stream (like a Transport). Should be inherited by such a class.
	The subclass should implement:

		rawWrite(msg) --- write this msg to the stream.
		   Typically handled at the Transport level (2 classes higher)

		packetizeError(e) --- report an error with the stream.
		   Typically handled by the dispatcher (1 class higher).

		dispatch(msg) --- emit a packetized imcoming message.
			Typically handled by the Dispatcher (1 class higher)

	The subclass should call packetizeData(m) whenever it has
	data to stuff in to the packetizer's input path, and call
	send(m) whenever it wants to stuff data into the packetizer's
	output path.
	"""

	#-------------------------------

	# The two states we can be in
	FRAME = 1
	DATA = 2

	# Results of getting
	OK = 0
	WAIT = 1
	ERR = -1

	#-------------------------------

	def __init__ (self, log_obj):
		self._ring = Ring()
		self._state = self.FRAME
		self._next_msg_len = 0
		log.Base.__init__(self, log_obj)

	#-------------------------------

	def send (self, msg):
		b2 = msgpack.packb(msg)
		b1 = msgpack.packb(len(b2))
		self.rawWrite(b1)
		self.rawWrite(b2)

	#-------------------------------

	def __getFrame (self):
		"""
		Internal method: get the frame part of a stream.
		"""

		if len(self._ring) is 0: return self.WAIT
		f0 = self._ring.grab(1)
		if not f0: return self.WAIT

		frame_len = msgpackFrameLen(ord(f0))
		if not frame_len:
			self.packetizeError("Bad frame header received")
			return self.ERR

		# Now we know have many bytes to grab for real.  It's a function 
		# of the first byte of the stream....
		f_full = self._ring.grab(frame_len)
		if not f_full: return self.WAIT

		try:
			r = unpackType(f_full, int)
			# pull the frame out of the input stream...
			self._ring.consume(frame_len)
			self._next_msg_len = r
			self._state = self.DATA
			return self.OK
		except UnpackValueError:
			self.packetizeError("Bad decoding in frame header; unpackb failed")
		except UnpackTypeError as e:
			self.packetizeError("Bad data type in frame header: {0}".format(e))
		return self.ERR

	#-------------------------------

	def __getPayload(self):
		"""
		Internal method: get the msg part of the stream.
		"""
		l = self._next_msg_len
		if l > len(self._ring): return self.WAIT
		buf = self._ring.grab(l)
		if not buf: return self.WAIT

		try:
			msg = unpackType(buf, list)
			self._ring.consume(l)
			self._state = self.FRAME
			self.dispatch(msg)
			return self.OK
		except UnpackValueError:
			self.packetizeError("Bad encoding found in data; len={0}"
				.format(l))
		except UnpackTypeError as e:
			self.packetizeError("In data: {0}".format(e))
		return self.ERR

	#-------------------------------

	def packetizeData(self, msg):
		"""
		To be called wheneve new data arrives on the transport.
		This method will stuff the new data into the bufffer ring
		and then attempt to fetch as many messages as possible
		from the stream, stopping if either there's a wait condition
		or if an error occurred.
		"""
		self._ring.buffer(msg)
		go = self.OK
		while go is self.OK:
			if self._state is self.FRAME:
				go = self.__getFrame()
			else:
				go = self.__getPayload()

	#-------------------------------

	def packetizerReset(self):
		"""
		To be called on an error; flush out the packetizer and return it
		to its normal state.
		"""
		self._state = self.FRAME
		self._ring = Ring()
	def __init__ (self, log_obj):
		self._ring = Ring()
		self._state = self.FRAME
		self._next_msg_len = 0
		log.Base.__init__(self, log_obj)
예제 #24
0
class Bubble:
    @staticmethod
    def getDir(key):  # key is pair of Bubbles
        return Vector2(key[0].ring.pos, key[1].ring.pos).unit()

    @staticmethod
    def getArc(key):  # key is pair of Bubbles
        a, b = key[0].ring, key[1].ring
        return math.asin(1.0 * b.r / (a.r + b.r))

    dirs = None  # Cache
    arcs = None

    def __init__(self):

        # Group Topology
        self.parent = None  # Noke  # not Bubble: for Group.buildGeometry()
        self.childs = []  # Nokes
        self.upper = False  # Upper level - first child

        self.group = None  # Parent Group of Bubble

        # Geometry and Correction
        self.ring = Ring((0, 0), 1)

        # For building Geometry
        self.tight = 0  # Left (Parents) and right (Childs) Tights
        self.corr = 0  # Correction of Radius
        self.angles = {}  # dict {Bubble:angle}

        # Eating
        self.fading = None  # Fading object

    def __repr__(self):
        return 'Bubble: %s' % self.ring

    def neighbor(self, n):
        "Returns previous or next neighbor (or parent if not); n = -1 or 1"
        if self.parent:
            nokes = self.parent().childs + [self.parent]
            bubbles = map(Noke.get, nokes)
            return nokes[bubbles.index(self) + n]

    def neighbors(self):
        "Iterates all neighbor Nokes"
        if self.childs:
            for n in self.childs:
                yield n

        if self.parent:
            yield self.parent
            for n in (-1, 1):
                neighbor = self.neighbor(n)
                if neighbor != self.parent:
                    yield neighbor

    #def strongParents( self ):
    #    "Skips first Parent if Bubble is not on upper level"
    #    return  self.parents[ self.upper^1 :]

    def lightCopy(self):
        "Copies main attributes of Bubble"
        bubble = Bubble()
        bubble.group = self.group
        bubble.ring = self.ring.copy()
        bubble.fading = self.fading
        return bubble

    def markUpperChilds(self, mark):

        self.upper = mark

        if self.childs:
            upper = self.childs[0]
            for c in self.childs:
                c().markUpperChilds(c == upper)

    def detTights(self):
        def arc(noke):
            return Bubble.arcs[(self, noke())]

        if self.parent:
            self.tight += arc(self.neighbor(-1))
            self.tight += arc(self.neighbor(1))
        if self.childs:
            self.tight += arc(self.childs[0])
            self.tight += arc(self.childs[-1])

        if not self.upper:

            a = self.parent()  # Bubbles: Parent
            c = self.neighbor(-1)()  #          Prev Neighbor

            ra = c.ring.r + self.ring.r  # Radiuses
            rb = a.ring.r + c.ring.r
            rc = a.ring.r + self.ring.r
            # Cosines
            ca = 1.0 * (rb**2 + rc**2 - ra**2) / (2 * rb * rc)
            cc = 1.0 * (ra**2 + rb**2 - rc**2) / (2 * ra * rb)

            aa = math.acos(ca)  # Angles
            ac = math.acos(cc)
            ab = math.pi - (aa + ac)

            a.tight += aa  # Increase Tights
            c.tight += ac
            self.tight += ab

            # Save angle aa for detPosition()
            a.angles[self] = aa

    def detCorrections(self):
        "Dets Correction values. Returns False if Correction is not needed."

        if not (self.parent or self.childs):  # Skip single Bubbles
            return False

        minChink = math.pi * 0.2  # ?? maybe to Constants

        # Set tight as chink
        self.tight = math.pi * 2 - self.tight
        self.tight /= 2

        if self.tight < minChink:  # Correction needed

            self.corr += 2
            for n in self.neighbors():
                n(
                ).corr -= 0.2  # ?? Here may be wrong values, and some Figures may be unbuildable

            return True

        return False  # Correction is not needed

    def correct(self):
        "Corrects Radius of Ring."
        if self.corr:
            self.ring.r *= math.exp(self.corr * 0.06)

    def detPosition(self):
        "Dets Position of Bubble. Calculates initial values of Chinks."

        if self.upper:

            if not self.parent:  # Root of Group
                self.ring.pos = Vector2((0, 0))
                return

            else:
                parent = self.parent()  # Parent Bubble

                if not parent.parent:
                    dir = Vector2((1, 0))  # Default direction

                else:
                    parent1 = parent.neighbor(-1)()
                    a = parent.tight + Bubble.arcs[
                        (parent, self)] + Bubble.arcs[(parent,
                                                       parent1)] - math.pi
                    dir = Bubble.dirs[(parent1, parent)]
                    dir = dir.rotate(Vector2(angle=-a))  # Det direction

        else:
            parent = self.parent()
            prev = self.neighbor(-1)()
            a = parent.angles[self]
            dir = Bubble.dirs[(parent, prev)]
            dir = dir.rotate(Vector2(angle=-a))  # Det direction

        Bubble.dirs[(parent, self)] = dir

        self.ring.pos = parent.ring.pos + dir * (parent.ring.r + self.ring.r)

    def transform(self):
        """
        Returns transformation Matrix of Bubble,
        includes transformation Matrix of Group if is.
        """

        # Default transformation is Unit
        # (Variable or Lambda inside another Lambda)
        matrix = TransformMatrix()
        matrix.unit()

        # Group reference may not exist
        # (Variable or Lambda inside fading Let-Bound Variable ??)
        if self.group:
            matrix *= self.group.transformMatrix

        if self.ring:
            matrix *= TransformMatrix(ring=self.ring)

        return matrix
예제 #25
0
    
    def remove_entity(self, key): 
        self.entities.remove(key)
    
root = tk.Tk()

canvas = Canvas(root, width=500, height=500)
canvas.pack()

canvas.create_text(100, 100, anchor=W, font="Purisa",
                text="{}".format("asd"))
        

app = Application(canvas, master=root)

app.add_entity(Ring("#264348", app))

continuing_game = True
while continuing_game:
    root.update_idletasks()
    root.update()    
    time.sleep(1 / 15)
    try:
        app.update()
    except:
        print("Program terminated")
        continuing_game = False
    

    
    
예제 #26
0
 def __init__(self, ring_name, module_id):
     Ring.__init__(self, ring_name, module_id, StatusMessage)
예제 #27
0
파일: note.py 프로젝트: jxxcarlson/sf2sound
 def __init__(self, NOTES, FREQ):
   self.ring = Ring()
   self.setNotes(NOTES)
   self.setAlternateNoteDict()
   self.accents = ['+', '-', ',', '.', '_', '^']
   self.setFrequencyDictionary(self.CFreq_4, FREQ)
예제 #28
0
 def __init__(self, x, y, t, sp):
     self.ovoid = Egg(x, y, t, sp)
     self.circle = Ring()
     self.circle.start(x, y - sp / 2)
예제 #29
0
파일: node.py 프로젝트: vamc19/pythonamo
    def __init__(self, is_leader, leader_hostname, my_hostname, tcp_port=13337, sloppy_Qsize=5, sloppy_R=3, sloppy_W=3):

        self.ongoing_requests = []
        self.is_leader = is_leader
        self.leader_hostname = leader_hostname
        self.hostname = my_hostname
        self.tcp_port = tcp_port
        self.my_address = (self.hostname, self.tcp_port)

        self.membership_ring = Ring(replica_count=sloppy_Qsize - 1)  # Other nodes in the membership
        if self.is_leader:
            self.membership_ring.add_node(leader_hostname)

        # todo: look into this, do we need both?
        self.bootstrapping = True
        self.is_member = False

        # Flag to keep track of a add-node is underway
        self._membership_in_progress = False

        self.sloppy_Qsize = sloppy_Qsize  # total members to replicate on

        # number of peers required for a read or write to succeed.
        self.sloppy_R = sloppy_R
        self.sloppy_W = sloppy_W

        # Book keeping for membership messages
        self._req_responses = defaultdict(set)
        self._sent_req_messages = {}
        self._received_req_messages = {}
        self._req_sender = {}  # Keeps track to sender for add and delete requests
        self.current_view = 0  # increment this on every leader election
        self.membership_request_id = 0  # increment this on every request sent to peers

        # Maintains handoff messages to be sent
        # IP : set(handoff messages)
        self._handoff_messages = defaultdict(set)
        self.handoff_timer = None
        self.create_handoff_timer = lambda: Timer(5, self.try_sending_handoffs)

        self.log_prefix = os.getcwd()
        self.ring_log_file = os.path.join(self.log_prefix, self.hostname + '.ring')
        self.db_path = os.path.join(self.log_prefix, self.hostname + '.db')
        self.handoff_log = os.path.join(self.log_prefix, self.hostname + '.pickle')

        try:
            with open(self.ring_log_file, 'r') as f:
                hosts = f.readlines()
                for h in hosts:
                    self.membership_ring.add_node(h.strip())
            print("Restored membership information from %s" % self.ring_log_file)
        except FileNotFoundError:
            pass

        try:
            with open(self.handoff_log, 'rb') as f:
                self._handoff_messages = pickle.loads(f.read())

            if len(self._handoff_messages) > 0:
                self.handoff_timer = self.create_handoff_timer()
                self.handoff_timer.start()

            print("Restored hand off messages from %s" % self.handoff_log)
        except FileNotFoundError:
            pass

        self.request_timelimit = 2.0
        self.req_message_timers = {}

        self.db = Storage(self.db_path)  # set up sqlite table

        # create tcp socket for communication with peers and clients
        self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_socket.setblocking(False)  # Non-blocking socket
        self.tcp_socket.bind((self.hostname, self.tcp_port))
        self.tcp_socket.listen(10)

        # has hostnames mapped to open sockets
        self.connections = {}
        self.client_list = set()
예제 #30
0
class Bubble:


    @staticmethod
    def getDir( key ):      # key is pair of Bubbles
        return Vector2( key[0].ring.pos, key[1].ring.pos ).unit()
    
    @staticmethod
    def getArc( key ):      # key is pair of Bubbles
        a,b = key[0].ring, key[1].ring
        return math.asin( 1.0 * b.r / (a.r + b.r) )



    dirs = None     # Cache
    arcs = None

    

    def __init__( self ):

        # Group Topology
        self.parent = None     # Noke  # not Bubble: for Group.buildGeometry()
        self.childs = []       # Nokes
        self.upper  = False    # Upper level - first child

        self.group  = None     # Parent Group of Bubble

        # Geometry and Correction
        self.ring   = Ring((0,0),1)
        
        # For building Geometry
        self.tight  = 0         # Left (Parents) and right (Childs) Tights
        self.corr   = 0         # Correction of Radius
        self.angles = {}        # dict {Bubble:angle}

        
        # Eating
        self.fading = None      # Fading object


    def __repr__( self ):
        return 'Bubble: %s' % self.ring


    def neighbor( self, n ):
        "Returns previous or next neighbor (or parent if not); n = -1 or 1"
        if self.parent:
            nokes = self.parent().childs + [self.parent]
            bubbles = map( Noke.get, nokes )
            return nokes[ bubbles.index( self ) + n ]

    def neighbors( self ):
        "Iterates all neighbor Nokes"
        if self.childs:
            for n in self.childs:
                yield n
        
        if self.parent:
            yield self.parent
            for n in (-1,1):
                neighbor = self.neighbor( n )
                if neighbor != self.parent:
                    yield neighbor


    #def strongParents( self ):
    #    "Skips first Parent if Bubble is not on upper level"
    #    return  self.parents[ self.upper^1 :]


    def lightCopy( self ):
        "Copies main attributes of Bubble"
        bubble = Bubble()
        bubble.group  = self.group
        bubble.ring   = self.ring.copy()
        bubble.fading = self.fading
        return bubble
        
    def markUpperChilds( self, mark ):
        
        self.upper = mark
        
        if self.childs:
            upper = self.childs[0]
            for c in self.childs:
                c().markUpperChilds( c == upper )
            

            

    def detTights( self ):
        
        def arc( noke ):
            return Bubble.arcs[ ( self,noke() ) ]

            
        if self.parent:
            self.tight += arc( self.neighbor(-1) )
            self.tight += arc( self.neighbor( 1) )
        if self.childs:
            self.tight += arc( self.childs[ 0] )
            self.tight += arc( self.childs[-1] )
        
        
        if not self.upper:

            a = self.parent()                   # Bubbles: Parent
            c = self.neighbor(-1)()             #          Prev Neighbor

            ra = c.ring.r + self.ring.r         # Radiuses
            rb = a.ring.r + c.ring.r
            rc = a.ring.r + self.ring.r
                                                # Cosines
            ca = 1.0 * ( rb**2 + rc**2 - ra**2 ) / ( 2 * rb * rc )
            cc = 1.0 * ( ra**2 + rb**2 - rc**2 ) / ( 2 * ra * rb )
            
            aa = math.acos( ca )                # Angles
            ac = math.acos( cc )
            ab = math.pi - (aa + ac)
            
            a   .tight += aa                    # Increase Tights
            c   .tight += ac
            self.tight += ab
        
            # Save angle aa for detPosition()
            a.angles[ self ] = aa
            

            
    def detCorrections( self ):
        "Dets Correction values. Returns False if Correction is not needed."

        if not ( self.parent or self.childs ):  # Skip single Bubbles
            return False


        minChink = math.pi * 0.2        # ?? maybe to Constants
        
        # Set tight as chink
        self.tight = math.pi*2 - self.tight
        self.tight /= 2
            

            
        if self.tight < minChink:       # Correction needed
        
            self.corr += 2
            for n in self.neighbors():
                n().corr -= 0.2         # ?? Here may be wrong values, and some Figures may be unbuildable
            
            return True
        
        return False                    # Correction is not needed
            
            
    def correct( self ):
        "Corrects Radius of Ring."
        if self.corr:
            self.ring.r *= math.exp( self.corr * 0.06 )

            
    def detPosition( self ):
        "Dets Position of Bubble. Calculates initial values of Chinks."
        
        if self.upper:
            
            if not self.parent:             # Root of Group
                self.ring.pos = Vector2((0,0))
                return
            
            else:
                parent = self.parent()      # Parent Bubble
                
                if not parent.parent:
                    dir = Vector2((1,0))    # Default direction
                
                else:
                    parent1 = parent.neighbor( -1 )()
                    a = parent.tight + Bubble.arcs[(parent,self)] + Bubble.arcs[(parent,parent1)] - math.pi
                    dir = Bubble.dirs[(parent1,parent)]
                    dir = dir.rotate( Vector2( angle= -a ) )     # Det direction

        else:
            parent = self.parent()
            prev   = self.neighbor(-1)()
            a = parent.angles[ self ]
            dir = Bubble.dirs[(parent,prev)]
            dir = dir.rotate( Vector2( angle= -a ) )             # Det direction

            
        Bubble.dirs[(parent,self)] = dir
        
        self.ring.pos = parent.ring.pos + dir * (parent.ring.r + self.ring.r)
          


    def transform( self ):
        """
        Returns transformation Matrix of Bubble,
        includes transformation Matrix of Group if is.
        """
        
        # Default transformation is Unit 
        # (Variable or Lambda inside another Lambda)
        matrix = TransformMatrix()
        matrix.unit()
        
        # Group reference may not exist 
        # (Variable or Lambda inside fading Let-Bound Variable ??)
        if self.group:
            matrix *= self.group.transformMatrix

        if self.ring:
            matrix *= TransformMatrix( ring= self.ring )

        return  matrix
class Stretcher(object):
    """ Given a tap pointer in a Ring buffer, generate the stretched audio
    """
    def __init__(self, tap):
        """
        tap (RingPosition): the starting point where our stretch begins
        """
        self.__in_tap = tap
        self.__buffer = Ring(2**16)
        self.__fading_out = False

    def step(self, windowsize, *args, **kwargs):
        results = self.stretch(windowsize, *args, **kwargs)

        return results

    def stretch(self, windowsize, stretch_amount=4):
        """
        Run paulstretch once from the current location of the tap point
        """
        sw = get_strech(windowsize)
        audio_in = self.__in_tap.get_samples(sw.size)

        # Magnitude spectrum of windowed samples
        mX = np.abs(fft.rfft(audio_in * sw.window))
        # Randomise the phases for each bin between 0 and 2pi
        pX = np.random.uniform(0, 2 * np.pi, len(mX)) * 1j
        # use e^x to Convert our array of random values from 0 to 2pi to an
        # array of cartesian style real+imag vales distributed around the unit
        # circle. Then multiply with magnitude spectrum to rotate the magnitude
        # spectrum around the circle.
        freq = mX * np.exp(pX)
        # Get the audio samples with randomized phase. When we randomized the
        # phase, we changed the waveform so it no longer starts and ends at
        # zero. We will need to apply another window -- however do not know the
        # size of the next window, so instead of applying the full window to
        # our audio samples, we will close the window from the previous step,
        # and open the window on our current samples.
        audio_phased = fft.irfft(freq)
        # counter the tremelo for both halves of the audio snippet
        audio_phased *= sw.double_hinv_buf
        # Open the window to the newly generated audio sample
        audio_phased *= sw.open_window

        # Next we will do the overlap/add with the tail of our local buffer.
        # First, retrive the the samples, apply the closing window
        previous = self.__buffer.recent(sw.half) * sw.close_window

        # overlap add this the newly generated audio with the closing tail of
        # the previous signal
        audio_phased[:sw.half] += previous
        # replace the tail end of the output buffer with the new signal
        self.__buffer.rewind(sw.half)
        self.__buffer.append(audio_phased)
        # The last <sw.half> samples are not valid (the window has not yet
        # been closed). These will be closed the next time we call step.

        # Advance our input tap
        self.__in_tap.advance(sw.hopsize(stretch_amount))

        # append the audio output to our output buffer
        self.__buffer.append(audio_phased)

        return audio_phased[:sw.half]

    def fade_out(self):
        """Begin fading the stretch with each .step() .step should deactivate
    
        Caution: fade_out is currently implemeted in StretchGroup. See:
        https://github.com/CharlesHolbrow/realtime-fft-experiment/issues/4
        """
        self.__fading_out = True

    def activate(self):
        self.__fading_out = False
        self.tap.activate()

    def deactivate(self):
        self.clear()
        self.tap.deactivate()

    @property
    def fading_out(self):
        return self.__fading_out

    @fading_out.setter
    def fading_out(self, val):
        self.__fading_out = bool(val)

    @property
    def tap(self):
        return self.__in_tap

    def clear(self):
        self.__buffer.raw.fill(0.)
예제 #32
0
파일: campaign.py 프로젝트: eliot2/RGB
def campaign(c, background, stock, store):

    debug(c.DEBUG, "ENTERING: campaign")
    load_song(c, "It's Melting.ogg")

    versionID = stock.getVersion()

    #    pygame.key.set_repeat(0, 0)

    allSprites = pygame.sprite.Group()
    ringSprite = pygame.sprite.GroupSingle()
    circSprites = pygame.sprite.LayeredUpdates()
    buttonSprites = pygame.sprite.Group()  # @UnusedVariable
    starSprites = pygame.sprite.LayeredUpdates()
    caughtSprite = pygame.sprite.GroupSingle()
    dieingSprites = pygame.sprite.GroupSingle()
    scoreSprite = pygame.sprite.GroupSingle()
    pBox = playBox()  # a jukebox for handling music settings.

    ring = Ring(c.CENTER, stock.campaign["Ring"], stock.campaign["Ring Glow"],
                c.FULLSCREEN)
    '''CREATE IMAGES'''
    ring.add(ringSprite, allSprites)
    scoreboard = Scoreboard(c.DISPLAY_W, c.DISPLAY_H)
    scoreboard.add(scoreSprite, allSprites)
    box_img = stock.campaign["RGB Light"]
    background_rect = background.get_rect()
    background_rect.center = c.CENTER
    OGBackground = background.copy()
    '''INSTANTIATING OTHER VARIABLES'''
    rotAngle = 0  # background rotation angle
    waitCounterCirc = 0
    waitCounterStar = 0
    circleWaitStart = 0
    circleWaitMade = 0
    starWaitStart = 0
    starWaitMade = 0
    finishedCircleActions = False
    finishedStarActions = False
    circleAction = '_'
    starAction = '_'
    counter = 0
    starWaiting = False
    circleWaiting = False
    pauseStartTime = None  #datetime variable
    pauseEndTime = None  #datetime variable
    r = 0
    g = 0
    b = 0
    pause_selection = 0
    gamePaused = False
    total_input = 0
    fpsList = []
    toggle_color_r = False
    toggle_color_g = False
    toggle_color_b = False
    display_sprites = True
    controls = c.CONTROL_LIST
    leftHold = False
    rightHold = False
    upHold = False
    downHold = False
    #quitGame = False  # if user returns a True from pause, we quit game, etc.
    startTime = 0
    genList = os.path.join(c.DATA_DIR, 'campaign_commands/genCommands.txt')
    circleList = os.path.join(c.DATA_DIR,
                              'campaign_commands/circleCommands.txt')
    starList = os.path.join(c.DATA_DIR, 'campaign_commands/starCommands.txt')
    genList, circleList, starList = commander(c, genList, circleList,
                                              starList)  # commander takes the
    #                     commands.txt and converts it into a formatted list.
    circleList, starList = iter(circleList), iter(starList)

    # take in the genList parameters now, before the level begins.
    for loop in range(len(genList)):
        setting = genList[loop]
        if setting[0] == 'B':
            # if the command is BPM, set the proper variables.
            pBox.cWait = setting[1]
            pBox.fWait = setting[2]
            pBox.cSpeed = setting[3]
            pBox.fSpeed = setting[4]
        elif setting[0] == 'J':
            __startTime = setting[1]  #different startTime, unused
        # change the general speed for circles/stars
        elif setting[0][0] == 'W':
            if setting[0] == 'WG':
                pBox.cWait = setting[1]
                pBox.fWait = setting[1]
            elif setting[0] == 'WC':
                pBox.cWait = setting[1]
            elif setting[0] == 'WF':
                pBox.fWait = setting[1]
    """BUTTON / SPRITE RENDERING"""
    r_letter = c.FONT_LARGE.render('R', True, c.RED)
    r_letter.scroll(2, 0)
    r_letter_rect = r_letter.get_rect()
    r_letter_rect.center = (c.CENTER_X - 50, (c.CENTER_Y * 2) - 20)
    box_rectR = r_letter_rect

    g_letter = c.FONT_LARGE.render('G', True, c.GREEN)
    g_letter.scroll(1, 0)
    g_letter_rect = g_letter.get_rect()
    g_letter_rect.center = (c.CENTER_X, (c.CENTER_Y * 2) - 20)
    box_rectG = g_letter_rect

    b_letter = c.FONT_LARGE.render('B', True, c.BLUE)
    b_letter.scroll(2, 0)
    b_letter_rect = b_letter.get_rect()
    b_letter_rect.center = (c.CENTER_X + 50, (c.CENTER_Y * 2) - 20)
    box_rectB = b_letter_rect

    debug(c.DEBUG, "Variable and object instantiating successful.")
    showSplashScreen(c, stock)
    songLength = store.music["Spicy Chips"].get_length()
    #pygame.mixer.music.set_endevent(USEREVENT)
    debug(c.DEBUG, "Song loading successful, main game loop about to begin.")
    # --Main Game Loop//--
    playing_campaign = True
    startTime = datetime.datetime.now()
    pygame.mixer.music.play()
    while playing_campaign:
        counter += 1
        waitCounterCirc += 1
        waitCounterStar += 1
        # Paint the background
        c.DISPLAYSURFACE.fill((0, 0, 0))
        #c.DISPLAYSURFACE.blit(background, background_rect)
        #if not c.FULLSCREEN:
        #   if counter%2 == 0:
        #      background, background_rect, rotAngle = \
        #     rotateBackground(c.CENTER, OGBackground, counter, rotAngle)
        """LOGGING output information: FPS, event info, AA, etc."""
        # for every 30 or FPS number of frames, print an average fps.
        fpsList.append(c.FPSCLOCK.get_fps())
        if counter == (c.FPS):
            AverageFPS = mean(fpsList)
            debug(c.DEBUG, ("Average FPS: {0}".format(AverageFPS)))
            debug(c.DEBUG,
                  ("Current Score: {0}".format(scoreboard.scoreString)))
            counter = 0
            pygame.display.set_caption('RGB. FPS: {0}'.format(mean(fpsList)))
            fpsList = []

            #===================================================================
            # this includes other things that i feel like should only be done
            # once a second, to save computation time, such as song ending check
            #===================================================================
            # test real quick to see if the song is over.
            deltaTime = (datetime.datetime.now() - startTime).total_seconds()
            if deltaTime > songLength:
                timeMessage = "SongTime: {0}, GameTIme: {1}".format(
                    songLength, deltaTime)
                debug(c.DEBUG, timeMessage)
                pygame.mixer.music.stop()
                playing_campaign = False
                debug(c.DEBUG, "MUSIC ENDED, CAMPAIGN SESSION OVER")
        """TAKE ACTION COMMAND LIST"""
        # for every new action, if the wait was long enough, perform the action
        if not circleWaiting:
            if not finishedCircleActions:
                try:
                    circleAction = circleList.next()
                except:
                    finishedCircleActions = True
            # if the circleAction is to spawn a circle/star, gotta que it up.
            if circleAction[0] == 'C':
                circleWaiting = True
            # change the general speed for circles/stars
            elif circleAction[0] == 'CS':
                if circleAction[0] == 'CS':
                    pBox.cSpeed = circleAction[1]
            elif circleAction[0][0] == 'W':
                if circleAction[0] == 'W':
                    circleWaitStart = datetime.datetime.now()
                    circleWaiting = True
                    circleWaitMade = datetime.datetime.now(
                    )  # time started waiting
                elif circleAction[0] == 'WC':
                    pBox.cWait = circleAction[1]
            elif circleAction[0] == 'S':
                pygame.mixer.music.stop()
                playing_campaign = False
        if circleWaiting:
            # All main actions have to wait before they can be performed,
            # so once an action is read, waiting becomes True, and we test to
            # see if the time passed is valid for the given wait time.
            if circleAction[0] == 'C':
                if waitCounterCirc >= pBox.cWait:
                    if circleAction[2] == '':
                        # if there is no given speed, then it's the global
                        # speed. . .
                        tempSpeed = pBox.cSpeed
                    else:
                        tempSpeed = circleAction[2]
                    tempColor = circleAction[1]
                    debug(c.DEBUG,
                          ("{0}'s speed: {1}".format(tempColor, tempSpeed)))
                    tempCirc = Circle(stock.campaign['Circle'], c.CENTER,
                                      tempSpeed, tempColor, pBox.layer)
                    tempCirc.add(circSprites, allSprites)
                    circMade = datetime.datetime.now()  #for debugging
                    pBox.layer += 1  #determines which get drawn on top
                    circleWaiting = False
                    waitCounterCirc = 0
            elif circleAction[0] == 'W':
                change = datetime.datetime.now() - circleWaitStart
                # if the action is to JUST wait x amount of time
                if change.total_seconds() >= circleAction[1] / c.FPS:
                    circleWaiting = False
                    totalWaitTime = datetime.datetime.now() - circleWaitMade
                    debug(c.DEBUG,
                          ("Wait Time: ", totalWaitTime.total_seconds()))
                    waitCounterCirc = 0

        if not starWaiting:
            if not finishedStarActions:
                try:
                    starAction = starList.next()
                except:
                    finishedStarActions = True
            if starAction[0] == 'F':
                starWaiting = True
            # change the general speed for circles/stars
            elif starAction[0] == 'FS':
                pBox.fSpeed = starAction[1]
            elif starAction[0][0] == 'W':
                if starAction[0] == 'W':
                    starWaitStart = datetime.datetime.now()
                    starWaiting = True
                    starWaitMade = datetime.datetime.now(
                    )  # for debug purposes
                elif starAction[0] == 'WF':
                    pBox.fWait = starAction[1]
            elif starAction[0] == 'S':
                pygame.mixer.music.stop()
                playing_campaign = False
        if starWaiting:
            if starAction[0] == 'F':
                if waitCounterStar >= pBox.fWait:
                    if starAction[2] == '':
                        tempSpeed = pBox.fSpeed
                    else:
                        tempSpeed = starAction[2]
                    tempAngle = starAction[1]
                    images = (stock.campaign['Star Lit'],
                              stock.campaign['Star Unlit'])
                    tempStar = Star(images, c.CENTER, tempSpeed, tempAngle)
                    tempStar.add(starSprites, allSprites)
                    # no longer waiting, bring on the next starAction!
                    starWaiting = False
                    waitCounterStar = 0
            elif starAction[0] == 'W':
                change = datetime.datetime.now() - starWaitStart
                # if the starAction is to JUST wait x amount of time
                if change.total_seconds() >= starAction[1] / c.FPS:
                    starWaiting = False
                    totalWaitTime = datetime.datetime.now() - starWaitMade
                    debug(c.DEBUG,
                          ("Wait Time: ", totalWaitTime.total_seconds()))
                    waitCounterStar = 0
                    # we must also set the wait for the next starAction to 0,
                    # or else the wait would be Wx + Wcircle/star.
        """EVENT HANDLING INPUT"""
        # grab all the latest input
        latest_events = pygame.event.get()
        for event in latest_events:
            if event.type == QUIT:
                playing_campaign = False
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                if c.DEBUG:
                    # quit game
                    playing_campaign = False
                    pygame.mixer.music.stop()
                else:
                    # have to time how long pause takes, for the wait.
                    pauseStartTime = datetime.datetime.now()
                    pause_selection = pause(c, stock, c.DISPLAYSURFACE)
                    pauseEndTime = datetime.datetime.now()
                    pauseTotalTime = (pauseEndTime - pauseStartTime)
                    starWaitStart += pauseTotalTime
                    circleWaitStart += pauseTotalTime
            # --game-play events//--
            elif event.type == KEYDOWN and event.key == controls[0]:
                r = 255
                toggle_color_r = True
                total_input += 1
                ring.glowColor((r, g, b))
            elif event.type == KEYUP and event.key == controls[0]:
                r = 0
                toggle_color_r = False
                total_input += -1
                ring.glowColor((r, g, b))
            elif event.type == KEYDOWN and event.key == controls[1]:
                g = 255
                toggle_color_g = True
                total_input += 1
                ring.glowColor((r, g, b))
            elif event.type == KEYUP and event.key == controls[1]:
                g = 0
                toggle_color_g = False
                total_input += -1
                ring.glowColor((r, g, b))
            elif event.type == KEYDOWN and event.key == controls[2]:
                b = 255
                toggle_color_b = True
                total_input += 1
                ring.glowColor((r, g, b))
            elif event.type == KEYUP and event.key == controls[2]:
                b = 0
                toggle_color_b = False
                total_input += -1
                ring.glowColor((r, g, b))
            # Ring Spinning
            elif event.type == KEYDOWN and event.key == controls[5]:
                leftHold = True
                if upHold:
                    ring.spin('upleft')
                elif downHold:
                    ring.spin('downleft')
                else:
                    ring.spin('left')
            elif event.type == KEYUP and event.key == controls[5]:
                leftHold = False
            elif event.type == KEYDOWN and event.key == controls[6]:
                rightHold = True
                if upHold:
                    ring.spin('upright')
                elif downHold:
                    ring.spin('downright')
                else:
                    ring.spin('right')
            elif event.type == KEYUP and event.key == controls[6]:
                rightHold = False
            elif event.type == KEYDOWN and event.key == controls[3]:
                upHold = True
                if leftHold:
                    ring.spin('upleft')
                elif rightHold:
                    ring.spin('upright')
                else:
                    ring.spin('up')
            elif event.type == KEYUP and event.key == controls[3]:
                upHold = False
            elif event.type == KEYDOWN and event.key == controls[4]:
                downHold = True
                if leftHold:
                    ring.spin('downleft')
                elif rightHold:
                    ring.spin('downright')
                else:
                    ring.spin('down')
            elif event.type == KEYUP and event.key == controls[4]:
                downHold = False

            #====================================
            # --non-game-play events//--
            #====================================
            # if O is pressed, toggle context display -------TO BE REMOVED SOON
            elif event.type == KEYDOWN and event.key == K_o:
                if display_sprites == True:
                    display_sprites = False
                else:
                    display_sprites = True
            # if P is pressed, pause game.
            elif event.type == KEYUP and event.key == controls[7]:
                gamePaused = True
            """LOGGING of inputs"""
            if event.type == KEYDOWN or event.type == KEYUP:
                debug(c.DEBUG,
                      (pygame.event.event_name(event.type), event.dict))

        if pause_selection == 3:
            pygame.mixer.music.stop()
            playing_campaign = False
            return
        """CATCH CIRCLES MATCHING COLORS"""
        # catch matching circles!!
        for circle in circSprites.sprites():
            if circle.catchable:
                # catchable becomes true when the circle comes in contact
                # with the ring.
                debug(c.DEBUG, (circle.color, (r, g, b)))
                circle.add(caughtSprite)
                circle.remove(circSprites)
                circle.catch()
                totalCircTime = datetime.datetime.now() - circMade
        """REPEATED POINTS HOLDING COLORS CAUGHT"""
        # every .1 seconds should add or remove points based on accuracy
        if not (caughtSprite.sprite is None):
            for circle in caughtSprite.sprites():
                if circle.color == (r, g, b) and not (circle.dieing):
                    debug(c.DEBUG,
                          ("CIRCTIME: ", totalCircTime.total_seconds()))
                    #if the circle is more than 1 color, than we give bonus
                    if circle.color[0] + circle.color[1] + circle.color[
                            2] > 255:
                        scoreboard.addScore(40)
                    else:
                        scoreboard.addScore(20)
                    circle.remove(caughtSprite)
                    circle.add(dieingSprites)
                else:
                    circle.remove(caughtSprite)
                    circle.add(dieingSprites)
                    scoreboard.addScore(-10)

        # a circle begins in circSprites, then hits the ring, gets caught, and
        # goes into "caughtSprite" group. From there, it tries to match with
        # the user's input, then dies and goes into the "dieingCircs" group.
        # the purpose of the last group is just to have it animate the fading
        # or "dieing" sequence before disappearing.
        for circle in dieingSprites.sprites():
            circle.death()
        """DELETE FREE STARS SHOOTING"""
        for star in starSprites.sprites():

            if star.travDist >= (264 - star.speed) and not (star.shooting):
                # this tests the stars' distance, once it's close enough. . .
                if not ((ringSprite.sprite.angle) % 360
                        == (star.angleDeg) % 360):
                    debug(c.DEBUG, "Star Died at:")
                    debug(c.DEBUG, ("Ring Angle: ", ringSprite.sprite.angle))
                    debug(c.DEBUG, ("Star Angle: ", star.angleDeg))
                    star.kill()
                    scoreboard.addScore(-30)
                else:
                    debug(c.DEBUG, "Star Made it at:")
                    debug(c.DEBUG, ("Ring Angle: ", ringSprite.sprite.angle))
                    debug(c.DEBUG, ("Star Angle: ", star.angleDeg))
            if star.shooting:
                #                 debug(c.DEBUG, 'I AM SHOOTING1!')
                # if the star has gone off the screen in the x or y direction
                # kill it and add points!!
                if star.pos[0] > c.DISPLAY_W or star.pos[0] < 0:
                    star.kill()
                    #                     debug(c.DEBUG, 'KILLED A STAR')
                    scoreboard.addScore(50)
                elif star.pos[1] > c.DISPLAY_H or star.pos[1] < 0:
                    star.kill()
                    #                     debug(c.DEBUG, 'KILLED A STAR')
                    scoreboard.addScore(50)


#         debug(c.DEBUG, ('Stars #: {0}'.format(len(starSprites.sprites())))
        """DISPLAY SPRITE TOGGLE"""
        allSprites.update()
        if display_sprites == True:
            dieingSprites.draw(c.DISPLAYSURFACE)
            caughtSprite.draw(c.DISPLAYSURFACE)
            circSprites.draw(c.DISPLAYSURFACE)
            starSprites.draw(c.DISPLAYSURFACE)
            ringSprite.draw(c.DISPLAYSURFACE)
            if toggle_color_r:
                c.DISPLAYSURFACE.blit(r_letter, r_letter_rect)
            if toggle_color_g:
                c.DISPLAYSURFACE.blit(g_letter, g_letter_rect)
            if toggle_color_b:
                c.DISPLAYSURFACE.blit(b_letter, b_letter_rect)
            c.DISPLAYSURFACE.blit(box_img, box_rectR)
            c.DISPLAYSURFACE.blit(box_img, box_rectG)
            c.DISPLAYSURFACE.blit(box_img, box_rectB)
            scoreSprite.draw(c.DISPLAYSURFACE)
            c.DISPLAYSURFACE.blit(versionID, (0, 0))
        """DELAY"""
        c.FPSCLOCK.tick_busy_loop(c.FPS)
        """UPDATE"""
        pygame.display.flip()  # update()

        # have to time how long pause takes, for the wait.
        if gamePaused:
            pauseStartTime = datetime.datetime.now()
            pause_selection = pause(c, stock, pygame.display.get_surface())
            pauseEndTime = datetime.datetime.now()
            pauseTotalTime = (pauseEndTime - pauseStartTime)
            starWaitStart += pauseTotalTime
            circleWaitStart += pauseTotalTime
            gamePaused = False

    return
예제 #33
0
 def __init__(self, ring_name, module_id):
     Ring.__init__(self, ring_name, module_id, Tracebuf2Message)
예제 #34
0
파일: game.py 프로젝트: outshaker/pyCFE
# game object, use ring to keep game running
from card import Deck, Cards
from player import Player
from ring import Ring
from time import sleep

deck = Deck()
disP = Cards()
p1 = Player("A", deck, disP)
p2 = Player("B", deck, disP)
players = Ring([p1, p2])
turn = 0

while True:
    turn = turn + 1
    print("turn#%d " % turn, end='')
    players.now().action()
    players.goNext()
    sleep(1)
예제 #35
0
from kuju import Kuju
from ruut import Ruut
from kolmnurk import Kolmnurk
from ring import Ring

kuju = Kuju()
ruut = Ruut(2)
kolmnurk = Kolmnurk(5, 2)
ring = Ring(5)

print(kuju)
print(ruut)
print(kolmnurk)
print(ring)

print("kuju pindala " + str(kuju.pindala()))
print("ruut pindala " + str(ruut.pindala()))
print("kolmnurga pindala " + str(kolmnurk.pindala()))
print("ringi pindala " + str(ring.pindala()))
예제 #36
0
 def add_ring(self):
     r = Ring(self.size)
     r.position = (self.size.width + self.new_pipe_trigger / 2 +
                   Pipe.blocksize / 2, r.position.y)
     self.add_child(r)
     self.rings.append(r)
예제 #37
0
from ring import Ring

inp = [int(l.strip()) for l in open('input.txt').read()]

inp.extend(range(max(inp) + 1, 10**6 + 1))

r = Ring(inp)
curr = r.find(inp[0])
inp_min = min(inp)

for i in range(10**7):
    tmp = r.remove(curr.nxt.val, 2)

    destination_val = curr.val - 1
    while not r.has(destination_val):
        destination_val -= 1
        if destination_val < inp_min:
            destination_val = r.get_max_val()
            break
    r.insert(destination_val, tmp)
    curr = curr.nxt

one = r.find(1)
print(one.nxt.val * one.nxt.nxt.val)
예제 #38
0
	def gameSummary(self, p1peer, p2peer, s1peer, winner):
		p1key = p1peer[2].publickey if p1peer[2] is not None else self.main.getPublicKey()
		p2key = p2peer[2].publickey if p2peer[2] is not None else self.main.getPublicKey()
		s1key = s1peer[2].publickey if s1peer[2] is not None else self.main.getPublicKey()
		
		scoreJsonHash, scoreJson = self.createScoreFile(p1peer, p2peer, s1peer, winner)
		
		myprivateKey = self.main.rsaKey;

		if p1peer[2] is None:
			#create two ring with both player and sign it and send it to the other two
			ringP1P2 = Ring([p1key, p2key], 2048)
			ringP1S1 = Ring([p1key, s1key], 2048)

			signp1p2 = ringP1P2.sign(scoreJsonHash, myprivateKey);
			signp1s1 = ringP1S1.sign(scoreJsonHash, myprivateKey);

			signs = [{"player1:player2": signp1p2}, {"player1:spectator": signp1s1}]
		
		if p2peer[2] is None:
			ringP1P2 = Ring([p1key, p2key], 2048)
			ringP2S1 = Ring([p2key, s1key], 2048)

			signp1p2 = ringP1P2.sign(scoreJsonHash, myprivateKey);
			signp2s1 = ringP2S1.sign(scoreJsonHash, myprivateKey);

			signs = [{"player1:player2": signp1p2}, {"player2:spectator": signp2s1}]
		
		if s1peer[2] is None:
			ringP1S1 = Ring([p1key, s1key], 2048)
			ringP2S1 = Ring([p2key, s1key], 2048)

			signp1s1 = ringP1S1.sign(scoreJsonHash, myprivateKey);
			signp2s1 = ringP2S1.sign(scoreJsonHash, myprivateKey);

			signs = [{"player1:spectator": signp1s1}, {"player2:spectator": signp2s1}]
	
		self.summary = [{"result": scoreJson,
					"sha256": scoreJsonHash,
					"sign": signs[0]
				},{"result": scoreJson,
					"sha256": scoreJsonHash,
					"sign": signs[1]
				}]
		print ">>>>>>>Summary ready<<<<<<<";
		self.webclient.sendMessage(WebSocketMessage.create
					("local","TTTS_GAME_OVER_MSGS","Game Result Object [" + str(scoreJsonHash) + "] created and signed"))
	
	
		#print "<<Results>>"
		#print summary
		#print
		
		if p1peer[2] is None:
			self.main.sendMulticast("SIGN_RESULT")
			
			signedResults = self.summary
			
			self.main.sendMulticast("RESULT_RING " + json.dumps(signedResults[0]))
			self.main.sendMulticast("RESULT_RING " + json.dumps(signedResults[1]))
예제 #39
0
파일: note.py 프로젝트: jxxcarlson/sf2sound
class Note(object):

  # CONSTANTS
  semitoneFactor = math.exp(math.log(2)/12.0)
  middleCFreq = 261.62556530059868
  CFreq_1 = middleCFreq/2  # 130.81278265029934 Hertz
  CFreq_2 = CFreq_1/2      #  65.40639132514967 Hertz
  CFreq_3 = CFreq_2/2      #  32.70319566257484 Hertz
  CFreq_4 = CFreq_3/2      #  16.351597831287421 Hertz

  alternateNoteDict = { }

  def __init__(self, NOTES, FREQ):
    self.ring = Ring()
    self.setNotes(NOTES)
    self.setAlternateNoteDict()
    self.accents = ['+', '-', ',', '.', '_', '^']
    self.setFrequencyDictionary(self.CFreq_4, FREQ)
     
  def setNotes(self, NOTES):
  # List of note names
    self.notes = NOTES
    self.ring.pushList(self.notes)
  
  # return unique numerical index for each note token
  def index(self, token):
  
    # scale length:
    SL = len(self.notes)
  
    # parse
    root, infix, suffix = trisectToken(token)
    root = self.normalizedNote(root)
    # print "trisection["+token+"]:", root, infix, suffix
   
    # get index of bare note 
    k = self.ring.index(root)
    if k < 0:
      return -1000
   
    # add octave shifts
    if len(infix) > 0:
      octave = int(infix) - 1
    else:
      octave = 0
    octave += count('^', suffix)
    octave -= count('_', suffix)
    k = k + SL*octave
   
    # add semitione shifts
    s = count('+', suffix)
    s -= count('-', suffix)
    k += s
   
    return k
   
  def note(self, j):
  # return normalized note of index j
  # scale length:
    SL = len(self.notes)
    k = j % SL
    octave = j // SL
    if octave == 0:
      return self.notes[k]
    else:
      octave = octave + 1
      return self.notes[k]+`octave`
   
  def isNote(self, token):
    root, suffix = splitToken(token)
    a = alphaPrefix(root)	
    a = self.normalizedNote(a)
    if a in self.notes:
      return True
    else:
      return False
      
  def setAlternateNoteDict(self):
    self.alternateNoteDict = {
     "de":"ti",
     "ra":"di",
     "me":"ri",
     "fe":"mi",
     "se":"fi",
     "le":"si",
     "te":"li"
    } 
    self.alternateNotes = self.alternateNoteDict.keys()
    
  def normalizedNoteData(self, x):
    y = alphaPrefix(x)
    root, suffix = splitToken(x)
    if y in self.alternateNoteDict.keys():
      return self.alternateNoteDict[y]+suffix
    else:
      return y, suffix
    
  def normalizedNote(self, x):
    y = alphaPrefix(x)
    root, suffix = splitToken(x)
    if y in self.alternateNoteDict.keys():
      return self.alternateNoteDict[y]+suffix
    else:
      return y+suffix

  def setFrequencyDictionary(self, baseFrequency, FREQ):
    self.noteFreq = FREQ
    self.noteFreq["x"] = 0.0 # x = 	rest
      

  def freq(self, token, nSemitoneShifts, octaveNumber):
    # Return frequency of note defined by token
    
    # base calculation
    root, suffix = splitToken(token)
    a = alphaPrefix(root)
    a = self.normalizedNote(a)
    f = self.noteFreq[a]
    
    # apply octave number
    for i in range(0, octaveNumber):
      f = 2*f
    
    # apply transpose register
    factor = pow(self.semitoneFactor, nSemitoneShifts);
    # print "factor:", factor
    f = f*factor
    
    # process upward octave shifts 
    n = 0
    np = numPrefix(token[len(a):])
    if len(np) > 0:
      n = int(np[0:1])-1
    else:
      n = 0
    n += count('^', suffix)   
    for i in range(0, n):
      f = 2.0*f 
      
    # process downward octave shifts 
    n = count('_', suffix)
    if n > 0:
      for i in range(0,n):
        f = f/2.0
        
    # process semitone shifts
    n = count('+', suffix) - count('-', suffix)
    if n > 0:
      for i in range(0,n):
        f = f*self.semitoneFactor
    if n < 0:
      for i in range(0,-n):
        f = f/self.semitoneFactor
        
    return f, root, suffix

  # print dictionary
  def printNoteFreq():
    j = 0
    for N in note:
      print j, N, noteFreq[N]
      j = j + 1
예제 #40
0
 def __init__(self, x, y, t, sp):
     self.ovoid = Egg(x, y, t, sp)
     self.circle = Ring()
     self.circle.start(x, y - sp / 2)
예제 #41
0
def creative(c, background):

    debug(c.DEBUG, "ENTERING: creative")
    
    # display the version ID
    font_renderObj = c.FONT_SMALL.render(c.VERSION, False, c.BLACK, c.WHITE)
    versionID_SurfaceObj = font_renderObj
    versionID_RectObj = versionID_SurfaceObj.get_rect()
    versionID_RectObj.topleft = (0, 0)

#    pygame.key.set_repeat(0, 0)

    allSprites = pygame.sprite.Group()
    ringSprite = pygame.sprite.GroupSingle()
    scoreSprite = pygame.sprite.GroupSingle()
    '''CREATE IMAGES'''
    ring = Ring(c, c.CENTER)
    ring.add(ringSprite, allSprites)
    scoreboard = Scoreboard(c.DISPLAY_W, c.DISPLAY_H)
    scoreboard.add(scoreSprite, allSprites)
    box_img, _box_rect = load_image(c, 'letter_box.png')
    background_rect = background.get_rect()
    background_rect.center = c.CENTER
    OGBackground = background.copy()
    logging = False

    '''INSTANTIATING OTHER VARIABLES'''
    dataDir = os.path.join(c.DATA_DIR, 'newCommands.txt')
    frameCount = 0      # tracks the number of frames passed.
    bgRotAngle = 0      # background rotation angle
    logFile = file
    testFrame = 0
    newAction = True
    r = 0
    g = 0
    b = 0
    paused = False
    fpsList = []
    toggle_color_r = False
    toggle_color_g = False
    toggle_color_b = False
    display_sprites = True
    controls = c.CONTROL_LIST
    leftHold = False
    rightHold = False
    upHold = False
    downHold = False
    quitGame = False  # if user returns a True from pause, we quit game, etc.
    firstAction = True

    """BUTTON / SPRITE RENDERING"""
    r_letter = c.FONT_LARGE.render('R', True, c.RED)
    r_letter.scroll(2, 0)
    r_letter_rect = r_letter.get_rect()
    r_letter_rect.center = (c.CENTER_X - 50, (c.CENTER_Y * 2) - 20)
    box_rectR = r_letter_rect

    g_letter = c.FONT_LARGE.render('G', True, c.GREEN)
    g_letter.scroll(1, 0)
    g_letter_rect = g_letter.get_rect()
    g_letter_rect.center = (c.CENTER_X, (c.CENTER_Y * 2) - 20)
    box_rectG = g_letter_rect

    b_letter = c.FONT_LARGE.render('B', True, c.BLUE)
    b_letter.scroll(2, 0)
    b_letter_rect = b_letter.get_rect()
    b_letter_rect.center = (c.CENTER_X + 50, (c.CENTER_Y * 2) - 20)
    box_rectB = b_letter_rect




    # throw down splash screen before beginning
    splashInfo, splashInfo_rect = load_image(c, 'splashInfo.png')
    # adjusting image cuz i can't make images.
    splashInfo_rect.center = (c.CENTER_X - 50, c.CENTER_Y)

    # fade info in and out
    fade = 0
    pgext.color.setAlpha(splashInfo, fade, 1)
    pygame.event.clear()
    # fade in
    inInfoScreen = True
    for fade in range(255):
        c.DISPLAYSURFACE.fill((0, 0, 0))
        c.DISPLAYSURFACE.blit(splashInfo, splashInfo_rect)
        pgext.color.setAlpha(splashInfo, fade, 1)
        c.DISPLAYSURFACE.blit(versionID_SurfaceObj, versionID_RectObj)
        pygame.display.flip()
        if pygame.event.poll().type != NOEVENT:
            inInfoScreen = False
            break
    # if the info is still being read/no button pressed, just wait.
    while inInfoScreen:
        if pygame.event.poll().type != NOEVENT:
            inInfoScreen = False
    fade = 255
    pgext.color.setAlpha(splashInfo, fade, 1)
    load_song(c, "It's Melting.ogg")  # stops other music from playing too
    cmdFile = open(dataDir, 'w')
    cmdFile.write("BPM60 Play:")

    # --Main Game Loop//--
    going = True
    while going:
        

        # Paint the background
        c.DISPLAYSURFACE.fill((0,0,0))
        c.DISPLAYSURFACE.blit(background, background_rect)
        """ROTATION TESTING"""
        # rotate the background, but only 15 times/second, not 30.
        # if the frame rate is 30/sec, then rotate when its an odd frame.
        if frameCount%3 == 0:
            bgRotAngle += .03
            background = pygame.transform.rotozoom(OGBackground, bgRotAngle%360 , 1)
            background_rect = background.get_rect()
            background_rect.center = c.CENTER
        frameCount += 1


        """LOGGING output information: FPS, event info, AA, etc."""
        # for every 30 or FPS number of frames, print an average fps.
        fpsList.append(c.FPSCLOCK.get_fps())
        if testFrame == c.FPS:
            debug(c.DEBUG, ("Average FPS: {0}".format(mean(fpsList))))
            debug(c.DEBUG, ("Current Score: {0}".format(scoreboard.scoreString)))
            testFrame = 0
            pygame.display.set_caption('RGB. FPS: {0}'.format(mean(fpsList)))
            fpsList = []

        """Start the Song!"""
        beginning = True
        if beginning:
            pygame.mixer.music.play()
            beginning = False
            # record the beginning, since no action causes a new time recording
            counter.setTime(1)
        

        """EVENT HANDLING INPUT"""
        # grab all the latest input
        latest_events = pygame.event.get()
        for event in latest_events:
            if (event.type == KEYDOWN or event.type == KEYUP) and \
                (event.key in controls) and firstAction:
                # this is the very first action, and its a correct input,
                # we put a Wait action in, since there was nothing before the 
                # first action to tell us otherwise.
                cmdFile.write(' W%d'%counter.getDelta(True))
                # so we write how long it took to do the action above
                counter.setTime(1)
                # if any button is pressed, a change must be written in. . .
                firstAction = False
            if event.type == QUIT:
                going = False
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                if c.DEBUG:
                    going = False
                else:
                    paused = True
            # --game-play events//--
            elif event.type == KEYDOWN and event.key == controls[0]:
                # default key is R
                r = 255
                toggle_color_r = True
            elif event.type == KEYUP and event.key == controls[0]:
                r = 0
                toggle_color_r = False
            elif event.type == KEYDOWN and event.key == controls[1]:
                # default key is G
                g = 255
                toggle_color_g = True
            elif event.type == KEYUP and event.key == controls[1]:
                g = 0
                toggle_color_g = False
            elif event.type == KEYDOWN and event.key == controls[2]:
                # default key is B
                b = 255
                toggle_color_b = True
            elif event.type == KEYUP and event.key == controls[2]:
                b = 0
                toggle_color_b = False
            # Ring Spinning
            elif event.type == KEYDOWN and event.key == controls[5]:
                leftHold = True
                if upHold:
                    ring.spin('upleft')
                elif downHold:
                    ring.spin('downleft')
                else:
                    ring.spin('left')
            elif event.type == KEYUP and event.key == controls[5]:
                leftHold = False
            elif event.type == KEYDOWN and event.key == controls[6]:
                rightHold = True
                if upHold:
                    ring.spin('upright')
                elif downHold:
                    ring.spin('downright')
                else:
                    ring.spin('right')
            elif event.type == KEYUP and event.key == controls[6]:
                rightHold = False
            elif event.type == KEYDOWN and event.key == controls[3]:
                upHold = True
                if leftHold:
                    ring.spin('upleft')
                elif rightHold:
                    ring.spin('upright')
                else:
                    ring.spin('up')
            elif event.type == KEYUP and event.key == controls[3]:
                upHold = False
            elif event.type == KEYDOWN and event.key == controls[4]:
                downHold = True
                if leftHold:
                    ring.spin('downleft')
                elif rightHold:
                    ring.spin('downright')
                else:
                    ring.spin('down')
            elif event.type == KEYUP and event.key == controls[4]:
                downHold = False

            #====================================
            # --non-game-play events//--
            #====================================
            # if O is pressed, toggle context display -------TO BE REMOVED SOON
            elif event.type == KEYDOWN and event.key == K_o:
                if display_sprites == True:
                    display_sprites = False
                else:
                    display_sprites = True
            # if P is pressed, pause game.
            elif event.type == KEYUP and event.key == controls[7]:
                paused = True

            """LOGGING of inputs"""
            if event.type == KEYDOWN or event.type == KEYUP:
                debug(c.DEBUG, event.dict)

        """DISPLAY SPRITE TOGGLE"""
        allSprites.update()
        if display_sprites == True:
            if toggle_color_r:
                c.DISPLAYSURFACE.blit(r_letter, r_letter_rect)
            if toggle_color_g:
                c.DISPLAYSURFACE.blit(g_letter, g_letter_rect)
            if toggle_color_b:
                c.DISPLAYSURFACE.blit(b_letter, b_letter_rect)
            c.DISPLAYSURFACE.blit(box_img, box_rectR)
            c.DISPLAYSURFACE.blit(box_img, box_rectG)
            c.DISPLAYSURFACE.blit(box_img, box_rectB)
            scoreSprite.draw(c.DISPLAYSURFACE)
            c.DISPLAYSURFACE.blit(versionID_SurfaceObj, versionID_RectObj)

        """DELAY"""
        c.FPSCLOCK.tick_busy_loop(c.FPS)

        """PAUSE UNPAUSE"""
        if paused:
            pygame.mixer.music.pause()
            quitGame = pauseScreen(c)
            if quitGame == 3:
                going = False
            pygame.mixer.music.unpause()
            paused = False

        """UPDATE"""
        pygame.display.flip()  # update()

    try:
        cmdFile.close()
    except Exception:
        debug(c.DEBUG, "File never opened")
    return
예제 #42
0
from neuron import h
from neuron.units import ms, mV
import matplotlib.pyplot as plt
from ring import Ring

ring = Ring()

pc = h.ParallelContext()
pc.set_maxstep(10 * ms)

t = h.Vector().record(h._ref_t)
h.finitialize(-65 * mV)
pc.psolve(100 * ms)

# send all spike time data to node 0
local_data = {cell._gid: list(cell.spike_times) for cell in ring.cells}
all_data = pc.py_alltoall([local_data] + [None] * (pc.nhost() - 1))

if pc.id() == 0:
    # combine the data from the various processes
    data = {}
    for process_data in all_data:
        data.update(process_data)
    # plot it
    plt.figure()
    for i, spike_times in data.items():
        plt.vlines(spike_times, i + 0.5, i + 1.5)
    plt.show()

pc.barrier()
pc.done()