Ejemplo n.º 1
0
def run_worker(do_submit=True, time_limit=None):
	best = float('inf')
	guess = random.getrandbits(RANDOM_BIT_LEN)
	t = time.time()
	i = 0
	while True:
		if gmpy is not None:
			encoded = gmpy.digits(guess, 62).encode('ascii')
			digest = gmpy.mpz(skein.skein1024(encoded).digest()[::-1] + b'\0', 256)
			diff = gmpy.hamdist(digest, TARGET)
		else: # fallback implementation
			encoded = hex(guess)[2:].encode('ascii')
			digest = int(skein.skein1024(encoded).hexdigest(), 16)
			diff = bin(digest ^ TARGET).count('1')
		if diff < best:
			best = diff
			if do_submit:
				submit(guess)
			print('Found new best input with diff [%.3d]: \"%s\"' %
				(diff, guess))
		i += 1
		if time_limit and time.time() - t > time_limit:
			break
		guess += 1
	return i
Ejemplo n.º 2
0
 def states(self):
     """Iterator for the possible states of the SuitcaseLock"""
     for i in range(self.n_values**self.n_vars):
         digits = gmpy.digits(i, self.n_values).zfill(self.n_vars)
         lock = copy.deepcopy(self)
         lock.state = np.asarray(list(map(int, digits)))
         yield lock
Ejemplo n.º 3
0
    def __mul__(self, k):
        """
        point multiplication
        uses Jacobian coordinates internally for speedup
        """
        if state.precompute:
            cost_results.CostSystem.costs["theoretical"]["setup"][
                "accumulated"](EC_Mul=1)
        else:
            cost_results.CostSystem.costs["theoretical"]["online"][
                "accumulated"](EC_Mul=1)

        if self.infinity:
            return ECPoint(0, 0, self.EC, True)
        if k == 1:
            return self
        if k == 2:  # point doubling with affine coordinates
            if self.y == 0:  #then we get the infinity point
                return ECPoint(0, 0, self.EC, True)
            s = gmpy.divm(3 * pow(self.x, 2, self.p) + self.EC.a, 2 * self.y,
                          self.p)
            xn = (pow(s, 2, self.p) - (2 * self.x)) % self.p
            yn = (-self.y + s * (self.x - xn)) % self.p
            return ECPoint(xn, yn, self.EC)
        pc = (0, 0, 1)
        for bit in gmpy.digits(k, 2):
            pc = self._doubleP(pc)
            if bit == "1":
                pc = self._addP(pc)
        x = gmpy.divm(pc[0], pow(pc[2], 2, self.p), self.p)
        y = gmpy.divm(pc[1], pow(pc[2], 3, self.p), self.p)
        return ECPoint(x, y, self.EC)
Ejemplo n.º 4
0
    def set_switch(self,mux,switch_number,state):
        print "Mux Bits :", gmpy.digits(mux,2).zfill(8)
       #need to bit shift that 16 bits to right
        self.data = mux << 16
       #Now just set the singular switch
       #We add it's relevent bit value to the state
       #First check if it's already set
        is_set = (self.switch_state[mux] & (1<<switch_number)) >> switch_number
        if state is False and is_set == 1:
            self.switch_state[mux] = self.switch_state[mux] - (1<<switch_number)
        if state is True and is_set == 0:
            self.switch_state[mux] = self.switch_state[mux] + (1<<switch_number)
        
        print "Switch Bits :", gmpy.digits(self.switch_state[mux],2).zfill(16)

        #And add this to the data
        self.data = self.data + self.switch_state[mux]
        self.send_data(self.data)
Ejemplo n.º 5
0
def ishappy(n, base=10):
    P = {}
    l = digits(n, base)
    #print l
    while True:
        if int(l) == 1:
            return True
        if str(l) in P:
            return False
        P[str(l)] = 1
        l = p(l, base)
Ejemplo n.º 6
0
def Colex2(n,k,pos):
    global B,N
    if k==0:
        print(gmpy.digits(B,2).zfill(N)) 
    else:
        if k<n:
            B &= pos
            Colex2(n-1,k, pos>>1)
        B |= pos
        Colex2(n-1,k-1,pos>>1)
        B &= pos
Ejemplo n.º 7
0
 def _format_gmpy_price(self, x, eurosign=True):
     t = x * gmpy.mpq(100)   # 123.4567 -> 12345.67
     t = int(gmpy.digits(t)) # 12345
     full = t / 100
     part = t % 100
     esign = ''
     if eurosign:
         esign = u' \u20ac'
     if full == 0:
         return u'0,%02d%s' % (part, esign)
     else:
         return u'%d,%02d%s' % (full, part, esign)
Ejemplo n.º 8
0
 def _extract_bits(self, string, no_of_bits):
     """Returns list of first no_of_bits from the given string."""
     word_size = 8  # No of bits in char.
     assert no_of_bits <= word_size * len(string), "Not enough bits"
     res = []
     if no_of_bits == 0:
         return res
     no_of_chars = 1 + no_of_bits / word_size
     for c in string[:no_of_chars]:
         _digits = [int(v) for v in digits(ord(c), 2).zfill(word_size)]
         if len(res) + word_size >= no_of_bits:
             return res + _digits[:no_of_bits - len(res)]
         res += _digits
     return [mpz(b) for b in res]
Ejemplo n.º 9
0
 def _extract_bits(self, string, no_of_bits):
     """Returns list of first no_of_bits from the given string."""
     word_size = 8 # No of bits in char.
     assert no_of_bits <= word_size * len(string), "Not enough bits"
     res = []
     if no_of_bits == 0:
         return res
     no_of_chars = 1 + no_of_bits / word_size
     for c in string[:no_of_chars]:
         _digits = [int(v) for v in digits(ord(c), 2).zfill(word_size)]
         if len(res) + word_size >= no_of_bits:
             return res + _digits[:no_of_bits - len(res)]
         res += _digits
     return [mpz(b) for b in res]
Ejemplo n.º 10
0
    def set_voltage(self,mux,channel,volts):
        self.data = 1 #MSB need to be 1 to work
        self.data = (self.data << 2) + channel
        #Add the mux_pa
        self.data = (self.data << 5) + self.dac_pa[mux]
        #print "Mux Bits :", gmpy.digits(self.data,2).zfill(8)

        bit_value = int(((volts + 5)*(2**14))/10)
        if bit_value < 0 or bit_value > 16383:
            print "DAC Bits out of range:", gmpy.digits(bit_value,2).zfill(16), bit_value

        else:
            self.data = (self.data << 16) + bit_value
            self.send_data(self.data)
Ejemplo n.º 11
0
    def __init__(self, x, radix=2, blocksize=None):
        _x_type = type(x)

        if _x_type in [_gmpy_mpz_type, int, long]:
            self._x = gmpy.digits(x, radix)
        elif _x_type in [FFXInteger]:
            self._x = x._x
        elif _x_type in [str]:
            self._x = x
        elif _x_type in [float, _gmpy_mpf_type]:
            self._x = gmpy.digits(gmpy.mpz(x), radix)
        else:
            raise UnknownTypeException(type(x))

        self._radix = radix
        if blocksize:
            self._blocksize = max(blocksize, len(self._x))
            self._x = '0' * (blocksize - len(self._x)) + self._x
        else:
            self._blocksize = None

        self._as_bytes = None
        self._as_int = None
        self._len = None
Ejemplo n.º 12
0
    def __init__(self, x, radix=2, blocksize=None):
        _x_type = type(x)

        if _x_type in six.integer_types or _x_type in [_gmpy_mpz_type]:
            self._x = gmpy.digits(x, radix)
        elif _x_type in [FFXInteger]:
            self._x = x._x
        elif _x_type in [str]:
            self._x = x
        elif _x_type in [float, _gmpy_mpf_type]:
            self._x = gmpy.digits(gmpy.mpz(x), radix)
        else:
            raise UnknownTypeException(type(x))

        self._radix = radix
        if blocksize:
            self._blocksize = max(blocksize, len(self._x))
            self._x = '0' * (blocksize - len(self._x)) + self._x
        else:
            self._blocksize = None

        self._as_bytes = None
        self._as_int = None
        self._len = None
Ejemplo n.º 13
0
def long_to_bytes(N, blocksize=1):
    """Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes.
    If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes,
    such that the return values length is a multiple of ``blocksize``.
    """

    if type(N) == FFXInteger:
        return N.to_bytes()

    bytestring = gmpy.digits(N, 16)
    bytestring = '0' + bytestring if (len(bytestring) % 2) != 0 else bytestring
    bytestring = binascii.unhexlify(bytestring)

    if blocksize > 0 and (len(bytestring) % blocksize) != 0:
        bytestring = '\x00' * \
            (blocksize - (len(bytestring) % blocksize)) + bytestring

    return bytestring
Ejemplo n.º 14
0
def long_to_bytes(N, blocksize=1):
    """Given an input integer ``N``, ``long_to_bytes`` returns the representation of ``N`` in bytes.
    If ``blocksize`` is greater than ``1`` then the output string will be right justified and then padded with zero-bytes,
    such that the return values length is a multiple of ``blocksize``.
    """

    if type(N) == FFXInteger:
        return N.to_bytes()
    
    bytestring = gmpy.digits(N, 16)
    bytestring = '0' + bytestring if (len(bytestring) % 2) != 0 else bytestring
    bytestring = binascii.unhexlify(bytestring)

    if blocksize>0 and (len(bytestring) % blocksize) != 0:
        bytestring = '\x00' * \
            (blocksize - (len(bytestring) % blocksize)) + bytestring

    return bytestring
Ejemplo n.º 15
0
def run_worker(do_submit=True, time_limit=None):
	best = float('inf')
	guess = random.getrandbits(RANDOM_BIT_LEN)
	t = time.time()
	i = 0
	while True:
		encoded = gmpy.digits(guess, 62).encode('ascii')
		digest = gmpy.mpz(skein.skein1024(encoded).digest()[::-1] + b'\0', 256)
		diff = gmpy.hamdist(digest, TARGET)
		if diff < best:
			best = diff
			if do_submit:
				submit(guess)
			print('Found new best input with diff [%.3d]: \"%s\"' %
				(diff, guess))
		i += 1
		if time_limit and time.time() - t > time_limit:
			break
		guess += 1
	return i
Ejemplo n.º 16
0
ser.parity   = "N"                                        
ser.rtscts   = "off"                                        
ser.xonxoff  = "off"                                       
ser.timeout  = 1     # required so that the reader thread can exit    

try:
	ser.open()
except serial.SerialException, e:
	sys.stderr.write("Could not open serial port %s: %s\n" % (ser.portstr, e))
        sys.exit(1)

lasthexvalue = "00"
lastbutone = "00"
while True:
	data = ser.read(1)
	if data:
		hexvalue = "%02X"%ord(data)
		binvalue = gmpy.digits(ord(data),2).zfill(8) 
		if lasthexvalue == "00" and lastbutone == "78":
			print
			print datetime.datetime.now(),
		#if hexvalue == "39" and lasthexvalue == "00":
		#	print
		#	print datetime.datetime.now(),

		print binvalue,
		lastbutone = lasthexvalue
		lasthexvalue = hexvalue


Ejemplo n.º 17
0
        prime, divisor = is_prime(base)
        if prime:
            return False
        else:
            divisors.append(divisor)
    return divisors

if __name__ == "__main__":
    with open(sys.argv[1], 'r') as f:
        count = int(f.readline())
        cases = [c.strip() for c in f.readlines()]
        for i in range(count):
            print("Case #{}:".format(i+1))
            size, result_count = cases[i].split()
            start = int('1' + '0'*(int(size)-2) + '1', 2)
            stop = int('1'*int(size), 2)
            results = 0
            for i in range(start, stop + 1, 2):
                num = gmpy.digits(i, 2)
                divisors = is_jamcoin(num)
                if not divisors:
                    continue
                print(num, end=' ')
                for d in divisors:
                    print(d, end=' ')
                print()
                results = results + 1
                if results >= int(result_count):
                    exit(0)

Ejemplo n.º 18
0
Archivo: 036.py Proyecto: neilpa/euler
def solve():
    #for n in range(1,1000000):
    #    if pal(str(n)) and pal(digits(n, 2)):
    #        print n

    return sum(n for n in xrange(1,1000000) if pal(str(n)) and pal(digits(n, 2)))
Ejemplo n.º 19
0
def get_policy(mdp, i):
    assert i < n_policies
    pi_string = gmpy.digits(i, mdp.n_actions).zfill(mdp.n_states)
    pi = np.asarray(list(pi_string), dtype=int)
    return pi
Ejemplo n.º 20
0
    [1, 0, 0],
])
mdp1 = MDP([T1, T2], [R, R], gamma=0.9)
v_star, q_star, pi_star = vi(mdp1)
v_star, pi_star

phi = np.array([
    [1, 0],
    [0, 1],
    [0, 1],
])

mdp2 = AbstractMDP(mdp1, phi)
v_phi_star, q_phi_star, pi_phi_star = vi(mdp2)
v_phi_star

# for each ground-state policy
n_policies = mdp1.n_actions**mdp1.n_states
for i in range(n_policies):
    pi_string = gmpy.digits(i, mdp1.n_actions).zfill(mdp1.n_states)
    pi = np.asarray(list(pi_string), dtype=int)

    # compare V^pi vs V_phi^pi
    v_pi = vi(mdp1, pi)[0]
    belief = mdp2.B(pi)
    v_phi_pi = belief @ v_pi
    print(i, pi, v_pi, v_phi_pi)

# (mdp.T[0] * mdp.R[0]).sum(axis=1)
# (mdp.T[1] * mdp.R[1]).sum(axis=1)
Ejemplo n.º 21
0
ser.port = "/dev/ttyS1"
ser.baudrate = "38400"
ser.parity = "N"
ser.rtscts = "off"
ser.xonxoff = "off"
ser.timeout = 1  # required so that the reader thread can exit

try:
    ser.open()
except serial.SerialException, e:
    sys.stderr.write("Could not open serial port %s: %s\n" % (ser.portstr, e))
    sys.exit(1)

lasthexvalue = "00"
lastbutone = "00"
while True:
    data = ser.read(1)
    if data:
        hexvalue = "%02X" % ord(data)
        binvalue = gmpy.digits(ord(data), 2).zfill(8)
        if lasthexvalue == "00" and lastbutone == "78":
            print
            print datetime.datetime.now(),
        #if hexvalue == "39" and lasthexvalue == "00":
        #	print
        #	print datetime.datetime.now(),

        print binvalue,
        lastbutone = lasthexvalue
        lasthexvalue = hexvalue
Ejemplo n.º 22
0
#!/usr/bin/python
from sys import stdin
import gmpy

C = int(stdin.readline())
for c in xrange(1, C + 1):
    sa = stdin.readline().split()
    sa.pop(0)
    a = sorted(gmpy.mpz(x) for x in sa)
    aa = a[1:]
    diffs = [aa[i] - a[i] for i in xrange(len(aa))]
    gcdiff = reduce(gmpy.gcd, diffs, 0)
    more = [(gcdiff - x % gcdiff) % gcdiff for x in a]
    more = (gcdiff - a[0] % gcdiff) % gcdiff
    print 'Case #%d: %s' % (c, gmpy.digits(more))
Ejemplo n.º 23
0
    """
    while n:
        yield n & 1
        n = n >> 1


if __name__ == '__main__':
    try:
        import gmpy
    except ImportError:
        pass
    else:
        ints = range(400)
        for n in ints:
            try:
                assert gmpy.digits(n, 2) == digits(n)
            except AssertionError:
                print 'digits fail %d' % n
                raise
            try:
                assert gmpy.numdigits(n, 2) == numdigits(n)
            except AssertionError:
                print 'numdigits fail %d' % n
                raise
            try:
                assert gmpy.popcount(n) == popcount(n)
            except AssertionError:
                print 'popcount fail %d' % n
                raise
        for n in list(ints):
            for i in ints:
Ejemplo n.º 24
0
class FFXInteger(object):
 def __init__(self, x, radix=2, blocksize=None):        _x_type = type(x)  if _x_type in [_gmpy_mpz_type, int, long]: self._x = gmpy.digits(x, radix) elif _x_type in [FFXInteger]: self._x = x._x elif _x_type in [str]: self._x = x elif _x_type in [float, _gmpy_mpf_type]: self._x = gmpy.digits(gmpy.mpz(x), radix) else: raise UnknownTypeException(type(x))
 self._radix = radix if blocksize: self._blocksize = max(blocksize, len(self._x)) self._x = '0' * (blocksize - len(self._x)) + self._x else: self._blocksize = None
 self._as_bytes = None self._as_int = None self._len = None
 def __add__(self, other):        retval = self.to_int() if type(other) == FFXInteger:            retval += other.to_int() else:            retval += other return retval
 def __sub__(self, other):        retval = self.to_int() if type(other) == FFXInteger:            retval -= other.to_int() else:            retval -= other return retval
 def __mod__(self, other):        retval = self.to_int() if type(other) == FFXInteger:            retval %= other.to_int() else:            retval %= other return retval
 def __eq__(self, other): if type(other) == FFXInteger:            retval = self.to_int() == other.to_int() elif type(other) in [str]:            retval = (self._x == other) elif type(other) in [int]:            retval = (self.to_int() == other) elif type(other) in [type(None)]:            retval = False else: raise UnknownTypeException() return retval
 def __len__(self): if self._len == None: self._len = len(self._x) return self._len
 def __getitem__(self, i): return FFXInteger(self._x[i], self._radix, 1)
 def __getslice__(self, i, j): return FFXInteger(self._x[i:j], self._radix, len(self._x[i:j]))
 def __str__(self): return self._x  def __repr__(self): return self.to_str()
 def to_int(self): if not self._as_int: self._as_int = int(self._x, self._radix) return int(self._x, self._radix)
 def to_bytes(self, blocksize=None): if blocksize is None and self._blocksize is not None:            blocksize = self._radix ** self._blocksize - 1            blocksize = math.log(blocksize, 256)            blocksize = math.ceil(blocksize)            blocksize = int(blocksize) if not self._as_bytes: if blocksize is None:                blocksize = 1 if self.to_int()>0:                    blocksize = math.log(self.to_int(),2)                blocksize /= 8                blocksize = math.ceil(blocksize)                blocksize = int(blocksize) self._as_bytes = long_to_bytes(self.to_int(), blocksize=blocksize) return self._as_bytes
 def to_str(self): return self._x
Ejemplo n.º 25
0
def p(n, base=10):
    #print n,base,type(n)
    #print [x for x in n]
    k = sum([int(x)**2 for x in n])
    #print digits(k,base)
    return digits(k, base)
Ejemplo n.º 26
0
 def get_policy(self, i):
     assert i < self.n_actions**self.n_states
     pi_string = gmpy.digits(i, self.n_actions).zfill(self.n_states)
     pi = np.asarray(list(pi_string), dtype=int)
     return pi
Ejemplo n.º 27
0
# Decimal to binary
def dec2bin(x): return x and (dec2bin(x/2)+str(x%2)) or ''

a = range(256)

for i in xrange(0, 256, 16):
	print ' '.join('%02x' % n for n in a[i:i+16])


import gmpy
int('aaa',36)
13330

for n in xrange(13330,13330+1000):
	print gmpy.digits(n,36),

aaa aab aac aad aae aaf aag aah aai aaj aak aal
aam aan aao aap aaq aar aas aat aau aav aaw aax
aay aaz ab0 ab1 ab2 ab3 ab4 ab5 ab6 ab7 ab8 ab9
aba abb abc abd abe abf abg abh abi abj abk abl
abm abn abo abp abq abr abs abt abu abv abw abx
aby abz ac0 ac1 ac2 ac3 ac4 ac5 ac6 ac7 ac8 ac9

#Python 2.3+
import datetime
d = datetime.date.today()
d.isoformat()
'2007-06-15'

#Python -2.3
Ejemplo n.º 28
0
 def hapval(n, b, path=[]):
     if n in path: return False
     elif n == 1: return True
     else:
         return hapval(sum([int(i)**2 for i in gmpy.digits(n, b)]), b,
                       path + [n])