Beispiel #1
0
 def lineReceived(self, line):
     if not line.startswith('$'):
         if self.ignore_invalid_sentence:
             return
         raise InvalidSentence("%r does not begin with $" % (line,))
     # message is everything between $ and *, checksum is xor of all ASCII values of the message
     strmessage, checksum = line[1:].strip().split('*')
     message = strmessage.split(',')
     sentencetype, message = message[0], message[1:]
     dispatch = self.dispatch.get(sentencetype, None)
     if (not dispatch) and (not self.ignore_unknown_sentencetypes):
         raise InvalidSentence("sentencetype %r" % (sentencetype,))
     if not self.ignore_checksum_mismatch:
         checksum, calculated_checksum = int(checksum, 16), reduce(operator.xor, map(ord, strmessage))
         if checksum != calculated_checksum:
             raise InvalidChecksum("Given 0x%02X != 0x%02X" % (checksum, calculated_checksum))
     handler = getattr(self, "handle_%s" % dispatch, None)
     decoder = getattr(self, "decode_%s" % dispatch, None)
     if not (dispatch and handler and decoder):
         # missing dispatch, handler, or decoder
         return
     # return handler(*decoder(*message))
     try:
         decoded = decoder(*message)
     except Exception, e:
         raise InvalidSentence("%r is not a valid %s (%s) sentence" % (line, sentencetype, dispatch))
    def pickServer(self):
        assert self.servers is not None
        assert self.orderedServers is not None

        if not self.servers and not self.orderedServers:
            # no SRV record, fall back..
            return self.domain, self.service

        if not self.servers and self.orderedServers:
            # start new round
            self.servers = self.orderedServers
            self.orderedServers = []

        assert self.servers

        self.servers.sort(self._serverCmp)
        minPriority = self.servers[0][0]

        weightIndex = zip(xrange(len(self.servers)),
                          [x[1] for x in self.servers if x[0] == minPriority])
        weightSum = reduce(lambda x, y: (None, x[1] + y[1]), weightIndex,
                           (None, 0))[1]
        rand = random.randint(0, weightSum)

        for index, weight in weightIndex:
            weightSum -= weight
            if weightSum <= 0:
                chosen = self.servers[index]
                del self.servers[index]
                self.orderedServers.append(chosen)

                p, w, host, port = chosen
                return host, port

        raise RuntimeError, 'Impossible %s pickServer result.' % self.__class__.__name__
Beispiel #3
0
    def pickServer(self):
        assert self.servers is not None
        assert self.orderedServers is not None

        if not self.servers and not self.orderedServers:
            # no SRV record, fall back..
            return self.domain, self.service

        if not self.servers and self.orderedServers:
            # start new round
            self.servers = self.orderedServers
            self.orderedServers = []

        assert self.servers

        self.servers.sort(self._serverCmp)
        minPriority=self.servers[0][0]

        weightIndex = zip(xrange(len(self.servers)), [x[1] for x in self.servers
                                                      if x[0]==minPriority])
        weightSum = reduce(lambda x, y: (None, x[1]+y[1]), weightIndex, (None, 0))[1]
        rand = random.randint(0, weightSum)

        for index, weight in weightIndex:
            weightSum -= weight
            if weightSum <= 0:
                chosen = self.servers[index]
                del self.servers[index]
                self.orderedServers.append(chosen)

                p, w, host, port = chosen
                return host, port

        raise RuntimeError, 'Impossible %s pickServer result.' % self.__class__.__name__
Beispiel #4
0
 def lineReceived(self, line):
     if not line.startswith('$'):
         if self.ignore_invalid_sentence:
             return
         raise InvalidSentence("%r does not begin with $" % (line,))
     # message is everything between $ and *, checksum is xor of all ASCII values of the message
     strmessage, checksum = line[1:].strip().split('*')
     message = strmessage.split(',')
     sentencetype, message = message[0], message[1:]
     dispatch = self.dispatch.get(sentencetype, None)
     if (not dispatch) and (not self.ignore_unknown_sentencetypes):
         raise InvalidSentence("sentencetype %r" % (sentencetype,))
     if not self.ignore_checksum_mismatch:
         checksum, calculated_checksum = int(checksum, 16), reduce(operator.xor, map(ord, strmessage))
         if checksum != calculated_checksum:
             raise InvalidChecksum("Given 0x%02X != 0x%02X" % (checksum, calculated_checksum))
     handler = getattr(self, "handle_%s" % dispatch, None)
     decoder = getattr(self, "decode_%s" % dispatch, None)
     if not (dispatch and handler and decoder):
         # missing dispatch, handler, or decoder
         return
     # return handler(*decoder(*message))
     try:
         decoded = decoder(*message)
     except Exception, e:
         raise InvalidSentence("%r is not a valid %s (%s) sentence" % (line, sentencetype, dispatch))
Beispiel #5
0
    def lineReceived(self, line):
        if not line.startswith('\02'):
            raise InvalidSentence("%r does not begin with \\02" % (line,))

        rfid, checksum = line[1:-2], line[-2:]

        checksum, calculated_checksum = int(checksum, 16), reduce(operator.xor, [int(rfid[x:x+2], 16) for x in range(0,len(rfid), 2)])
        if checksum != calculated_checksum:
            raise InvalidChecksum("Given 0x%02X != 0x%02X" % (checksum, calculated_checksum))

        return self.handle_rfid(rfid)
 def test_zoneTransfer(self):
     """
     Test DNS 'AXFR' queries (Zone transfer)
     """
     default_ttl = soa_record.expire
     results = [copy.copy(r) for r in reduce(operator.add, test_domain_com.records.values())]
     for r in results:
         if r.ttl is None:
             r.ttl = default_ttl
     return self.namesTest(
         self.resolver.lookupZone('test-domain.com').addCallback(lambda r: (r[0][:-1],)),
         results
     )
Beispiel #7
0
 def test_zoneTransfer(self):
     """
     Test DNS 'AXFR' queries (Zone transfer)
     """
     default_ttl = soa_record.expire
     results = [copy.copy(r) for r in reduce(operator.add, test_domain_com.records.values())]
     for r in results:
         if r.ttl is None:
             r.ttl = default_ttl
     return self.namesTest(
         self.resolver.lookupZone('test-domain.com').addCallback(lambda r: (r[0][:-1],)),
         results
     )
Beispiel #8
0
    def jelly_decimal(self, d):
        """
        Jelly a decimal object.

        @param d: a decimal object to serialize.
        @type d: C{decimal.Decimal}

        @return: jelly for the decimal object.
        @rtype: C{list}
        """
        sign, guts, exponent = d.as_tuple()
        value = reduce(lambda left, right: left * 10 + right, guts)
        if sign:
            value = -value
        return ['decimal', value, exponent]
Beispiel #9
0
    def jelly_decimal(self, d):
        """
        Jelly a decimal object.

        @param d: a decimal object to serialize.
        @type d: C{decimal.Decimal}

        @return: jelly for the decimal object.
        @rtype: C{list}
        """
        sign, guts, exponent = d.as_tuple()
        value = reduce(lambda left, right: left * 10 + right, guts)
        if sign:
            value = -value
        return ['decimal', value, exponent]
Beispiel #10
0
def _validateChecksum(sentence):
    """
    Validates the checksum of an NMEA sentence.

    @param sentence: The NMEA sentence to check the checksum of.
    @type sentence: C{str}

    @raise ValueError: If the sentence has an invalid checksum.

    Simply returns on sentences that either don't have a checksum,
    or have a valid checksum.
    """
    if sentence[-3] == '*':  # Sentence has a checksum
        reference, source = int(sentence[-2:], 16), sentence[1:-3]
        computed = reduce(operator.xor, (ord(x) for x in source))
        if computed != reference:
            raise base.InvalidChecksum("%02x != %02x" % (computed, reference))
Beispiel #11
0
def _validateChecksum(sentence):
    """
    Validates the checksum of an NMEA sentence.

    @param sentence: The NMEA sentence to check the checksum of.
    @type sentence: C{bytes}

    @raise ValueError: If the sentence has an invalid checksum.

    Simply returns on sentences that either don't have a checksum,
    or have a valid checksum.
    """
    if sentence[-3:-2] == b'*':  # Sentence has a checksum
        reference, source = int(sentence[-2:], 16), sentence[1:-3]
        computed = reduce(operator.xor, [ord(x) for x in iterbytes(source)])
        if computed != reference:
            raise base.InvalidChecksum("%02x != %02x" % (computed, reference))
Beispiel #12
0
 def test_reduce(self):
     """
     L{reduce} should behave like the builtin reduce.
     """
     self.assertEqual(15, reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]))
     self.assertEqual(16, reduce(lambda x, y: x + y, [1, 2, 3, 4, 5], 1))