Ejemplo n.º 1
0
 def get_coordinate_free(self):
     while True:
         x = int(int(quantumrandom.randint(0, self.size)))
         y = int(int(quantumrandom.randint(0, self.size)))
         print("{} - {}; {} - {}".format(x, type(x), y, type(y)))
         if self.get_value((x, y)) == 0:
             return (x, y)
Ejemplo n.º 2
0
def main():
    usage = "Usage: %s [--binary|--hex|--int --min MIN --max MAX]" % \
            sys.argv[0]
    generator = None
    # TODO -- use argparse here
    if '--binary' in sys.argv or '-b' in sys.argv:
        generator = quantumrandom.binary
    if '--hex' in sys.argv or '-h' in sys.argv:
        generator = quantumrandom.hex
    if '--int' in sys.argv or '-i' in sys.argv:
        # Special case.  Just print one.
        try:
            min = int(sys.argv[sys.argv.index('--min') + 1])
            max = int(sys.argv[sys.argv.index('--max') + 1])
        except ValueError:
            print usage
            sys.exit(1)

        print quantumrandom.randint(min=min, max=max)
        sys.exit(0)

    if not generator:
        print usage
        sys.exit(1)
    try:
        while True:
            print generator(),
    except:
        pass
Ejemplo n.º 3
0
 def setdDefault(self):
     self.P1Strat = 0
     self.P2Strat = 0
     self.Min = 0;
     self.Max = 0;
     self.Weight = quantumrandom.randint(0, 6)
     self.Probability = float(quantumrandom.randint(0, 10) / 10)
Ejemplo n.º 4
0
def main():
    usage = "Usage: %s [--binary|--hex|--int --min MIN --max MAX]" % \
            sys.argv[0]
    generator = None
    # TODO -- use argparse here
    if '--binary' in sys.argv or '-b' in sys.argv:
        generator = quantumrandom.binary
    if '--hex' in sys.argv or '-h' in sys.argv:
        generator = quantumrandom.hex
    if '--int' in sys.argv or '-i' in sys.argv:
        # Special case.  Just print one.
        try:
            min = int(sys.argv[sys.argv.index('--min')+1])
            max = int(sys.argv[sys.argv.index('--max')+1])
        except ValueError:
            print usage
            sys.exit(1)

        print quantumrandom.randint(min=min, max=max)
        sys.exit(0)

    if not generator:
        print usage
        sys.exit(1)
    try:
        while True:
            print generator(),
    except:
        pass
Ejemplo n.º 5
0
async def random(ctx, nb1=None, nb2=None):
  if nb1 is None:
    random_number = round(quantumrandom.randint(0, 100))
    await ctx.send("```" + str(random_number) + "```")
  else:
    if nb1.isdecimal() & nb2.isdecimal():
      random_number = round(quantumrandom.randint(int(nb1), int(nb2)))
      await ctx.send("```" + str(random_number) + "```")
    else:
      await ctx.send("```Those are not numbers```")
Ejemplo n.º 6
0
def quantum_d10(number_of_dice: int):
    '''
    Uses quantum number generation to produce a series of truly random numbers between 1-10.
    Based off the quantumrandom module, this is true RNG, not pseudo-RNG.
    '''
    remove_decimal = [x for x in str(quantumrandom.randint()) if x != '.']

    while len(remove_decimal) < number_of_dice:
        for y in range(round(number_of_dice / 10)):
            remove_decimal = remove_decimal + [
                x for x in str(quantumrandom.randint()) if x != '.'
            ]

    list_of_numbers = [int(y) if y != '0' else 10 for y in remove_decimal]
    return [list_of_numbers[y] for y in range(number_of_dice)]
Ejemplo n.º 7
0
def get_sample(dist_type):
    """ 퀀텀 난수를 가지는 2차원 배열을 반환한다 """

    if dist_type == 'poisson' or dist_type == 'expon':
        random_number = np.zeros((const.EXPERIMENTS, const.SAMPLES))
        cached_generator = qt.cached_generator(
        )  # chached_generator를 생성하면 서버 딜레이를 회피할 수 있다
        for i in range(const.EXPERIMENTS):
            for j in range(const.SAMPLES):
                random_number[i][j] = qt.randfloat(
                    0, 1,
                    cached_generator)  # cached_generator로 0에서 1사이의 값을 생성한다

    elif dist_type == 'binomial':
        random_number = np.zeros((const.EXPERIMENTS, const.SAMPLES))
        cached_generator = qt.cached_generator(
        )  # chached_generator를 생성하면 서버 딜레이를 회피할 수 있다

        for i in range(const.EXPERIMENTS):
            for j in range(const.SAMPLES):
                random_number[i][j] = math.floor(
                    qt.randint(0, 10, cached_generator)
                )  # 홀수인 경우는 1, 3, 5, 7, 9, 짝수인 경우는 0, 2, 4, 6, 8이 된다

    else:
        raise Exception(
            "Invalid distribution type. Allowed types are 'poisson', 'expon', 'binomial'."
        )

    return random_number
Ejemplo n.º 8
0
def bok(bot, update):
    gwa = int(quantumrandom.randint(1, 64))
    print('new command from:', update.message.from_user.username)
    # url_prefix = 'http://www.eee-learning.com/eeeApp/'
    # full_url = url_prefix + str(gwa) + '.html'
    # print(full_url)
    gwa_img = 'gwa_img/' + str(gwa) + '.gif'
    gwa_illustrate = 'gwa_illustrate/' + str(gwa) + '.jpg'

    gwa_index = gwa - 1
    gwa_title = all_gwas[gwa_index]['title']
    gwa_digest = all_gwas[gwa_index]['digest']
    gwa_article = all_gwas[gwa_index]['article']
    print(gwa_illustrate)
    print(gwa_img)
    print(gwa_title)
    print(gwa_digest)
    print(gwa_article)
    bot.send_chat_action(chat_id=update.message.chat_id, action='typing')
    update.message.reply_photo(photo=open(gwa_img, 'rb'), caption=gwa_title)
    bot.send_chat_action(chat_id=update.message.chat_id, action='typing')
    update.message.reply_photo(photo=open(gwa_illustrate, 'rb'),
                               caption=gwa_digest)
    bot.send_chat_action(chat_id=update.message.chat_id, action='typing')
    update.message.reply_text(gwa_article)
Ejemplo n.º 9
0
def selection_from_collection(Card_Set, Card_Subset):
    Cardinality = Card_Set
    Cardinality_Subset = Card_Subset
    universe = []
    sample = []
    #dice = 0
    #element = 0
    # New Universe.
    for i in range(1, Cardinality + 1):
        universe.append(i)
    for i in range(1, Cardinality_Subset + 1):
        Cardinality = len(universe)
        print("Universum (Cardinality = ", Cardinality, "):")
        #print(universe)
        #print("Card of Universum = ", Cardinality)
        dice = round(quantumrandom.randint(1, Cardinality))
        element = universe[dice - 1]
        sample.append(element)
        print("====|||| Dice = ", dice, " ||||   Element selected {", element,
              "}")
        #print("Element selected {", element, "}")
        del universe[dice - 1]
        print("Universe after {", element, "} selected:")
        print(universe)
    sample.sort()
    #print("Sample:")
    return sample
Ejemplo n.º 10
0
def loc(c: Client, m: Message):
    m.reply_chat_action('find_location')
    user = m.from_user
    u = get_user(user)

    loc: Location = m.location
    p = Point(loc.latitude, loc.longitude)
    try:
        d = qr.randint(500, u.distance) / 1000
        angle = qr.randint(0, 360)
        np = distance.distance(d).destination(p, angle)
        m.reply_location(np.latitude, np.longitude)
        c.send_message(m.from_user.id, 'В добрый путь!')
        update_points_count(user)
    except Exception as e:
        m.reply('Error =(\n%s' % e)
Ejemplo n.º 11
0
 async def gostosa(self, ctx):
     role = discord.utils.get(ctx.guild.roles, name="webnamorada")
     gostosas = list()
     for m in role.members:
         if m.id != 552595247809429546 and m.id != 525447699579797505 and m.id != 238803776507478017 and m.id != 523626016145539073 and m.id != 304873309164535808 and m.id != 323236550555074562 and m.id != 361181769380397058:
             gostosas.append(m)
     random.shuffle(gostosas)
     gostosa = gostosas[self.random]
     membro = busca_gostosa(gostosa.id)
     if (membro):
         update_gostosa(gostosa.id, membro[1] + 1)
     else:
         insert_gostosa(gostosa.id)
     role_burro = discord.utils.get(ctx.guild.roles, name="Burro")
     if (role_burro in gostosa.roles):
         response = requests.get(
             'https://media.discordapp.net/attachments/223594824681521152/707385777037901944/EQH1UEyWoAEW1jn.png'
         )
         img = BytesIO(response.content)
         file = discord.File(img, filename='burra_e_gostosa.png')
         await ctx.send(content='<@{}> gostosa'.format(gostosa.id),
                        file=file)
         self.random = int(quantumrandom.randint(0, len(gostosas) - 1))
     else:
         await ctx.send('<@{}> gostosa'.format(gostosa.id))
Ejemplo n.º 12
0
def true_random_roll(num_dice: int, num_sides=10):
    '''Uses quantum number generation to produce a series of truly random numbers, not pseudo-RNG. \n\nBe warned: this function is EXTREMELY slow.'''
    num_dice = int(num_dice)
    num_sides = int(num_sides)
    return [
        int(quantumrandom.randint(1, num_sides + 1)) for r in range(num_dice)
    ]
Ejemplo n.º 13
0
 async def get_random(self):
     guild = self.bot.get_guild(223594824681521152)
     role = discord.utils.get(guild.roles, name="webnamorada")
     gostosas = list()
     for m in role.members:
         if m.id != 552595247809429546 and m.id != 525447699579797505 and m.id != 238803776507478017 and m.id != 523626016145539073 and m.id != 304873309164535808 and m.id != 323236550555074562 and m.id != 361181769380397058:
             gostosas.append(m)
     self.random = int(quantumrandom.randint(0, len(gostosas)))
def setIterationNumber():
    text = pmt.getMaxGamesText()
    for x in text:
        print(x)

    n_max = validateInput()
    n = int(quantumrandom.randint(1, n_max))
    print("\nLooks like you're playing " + str(n) + " games.\n")
    return n
Ejemplo n.º 15
0
def go(ev=None):
    #		time.sleep(20)
    #	try:
    global status
    status = not status

    file = open("numbers.txt", "r")
    #print(file.read())
    num = int(float(file.read()))
    file.close()
    #		print(num)
    num = num * 2
    file = open("numbers.txt", "w")
    file.write('%d' % num)
    file.close()

    x = int(quantumrandom.randint(0, 2))
    #		print(x)
    if (x == 0):

        print('Red ')
        #Turn on LED
        GPIO.output(LedPin, GPIO.LOW)
        time.sleep(2)
        GPIO.output(LedPin, GPIO.HIGH)
    else:
        GPIO.output(LedPinGreen, GPIO.LOW)
        print('Green')
        time.sleep(2)
        GPIO.output(LedPinGreen, GPIO.HIGH)

    #lighting up counter
    timeout = time.time() + 15
    while (True):
        clearDisplay()
        pickDigit(0)
        hc595_shift(number[num % 10])

        clearDisplay()
        pickDigit(1)
        hc595_shift(number[num % 100 // 10])

        clearDisplay()
        pickDigit(2)
        hc595_shift(number[num % 1000 // 100])

        clearDisplay()
        pickDigit(3)
        hc595_shift(number[num % 10000 // 1000])

        if time.time() > timeout:
            break

    print('LED OFF....')
    time.sleep(0.5)
Ejemplo n.º 16
0
def main():
    usage = ("Usage: %s [--binary|--hex|--int --min MIN --max MAX]" + \
             " [--count BLOCKS]") % sys.argv[0]
    generator = None
    # TODO -- use argparse here
    if '--binary' in sys.argv or '-b' in sys.argv:
        generator = quantumrandom.binary
    if '--hex' in sys.argv or '-h' in sys.argv:
        generator = quantumrandom.hex
    if '--int' in sys.argv or '-i' in sys.argv:
        # Special case.  Just print one.
        try:
            min = int(sys.argv[sys.argv.index('--min')+1])
            max = int(sys.argv[sys.argv.index('--max')+1])
        except ValueError:
            print usage
            sys.exit(1)

        print quantumrandom.randint(min=min, max=max)
        sys.exit(0)

    if not generator:
        print usage
        sys.exit(1)
    try:
        #Decided not use argpase to maintain 2.6 compatibility
        maxblocks = 0
        blocks = -1
        if '--count' in sys.argv:
            maxblocks = int(sys.argv[sys.argv.index('--count')+1])  
            blocks = 0
        while True:
            if maxblocks and blocks >= maxblocks:
              break
            print generator(),
            blocks+=1

    except:
        pass
Ejemplo n.º 17
0
def calculatePi(pValue):
    for k in range(pValue):
        j = 0
        count = 0
        while (j < circlePoints):
            x = (quantumrandom.randint(0, 10) * (0.05)) + (
                0.5
            )  # taking a random point in the upper right quadrant of circle
            circleEq = (0.5) + math.sqrt(
                0.25 - ((x - (0.5))**2)
            )  # the circle equation for a circle of center (0.5, 0.5) and radius 1
            y = (quantumrandom.randint(0, 10) * (0.05)) + (0.5)

            if (y <= circleEq):
                count += 1
            j += 1

        frac = (count) / float(circlePoints)
        pi = frac * 4
        datac.append(pi)

    return datac
Ejemplo n.º 18
0
def shuffle_gen():
    for q, r in enumerate(shuffled_deck):
        try:
            if shuffled_deck[q] == shuffled_deck[
                    q + 1] and quantumrandom.randint() <= 0.701:
                tmpnum = random.randrange(0, 52)
                index = tmpnum if tmpnum != q else random.randrange(0, q)
                shuffled_deck.insert(index, shuffled_deck[q])
                del shuffled_deck[q]
            else:
                pass
        except Exception:
            pass
    return shuffled_deck
Ejemplo n.º 19
0
    def form_valid(self, form):
        decohered = form.data['state1']

        if randint(0, 2) > 0:
            decohered = form.data['state2']

        decoherence = Decoherence(
            state1=form.data['state1'],
            state2=form.data['state2'],
            decohered=decohered,
        )

        decoherence.save()

        return render_to_response(
            'decoherence.html',
            {'decohered': decohered}
        )
Ejemplo n.º 20
0
def merge_datasets(pickle_files, train_size, valid_size=0):
  num_classes = len(pickle_files)
  valid_dataset, valid_labels = make_arrays(valid_size, image_size)
  train_dataset, train_labels = make_arrays(train_size, image_size)
  vsize_per_class = valid_size // num_classes
  tsize_per_class = train_size // num_classes
    
  start_v, start_t = 0, 0
  end_v, end_t = vsize_per_class, tsize_per_class
  end_l = vsize_per_class+tsize_per_class
  pbar = tqdm(total = len(pickle_files))
  for label, pickle_file in enumerate(pickle_files):  
    try:
      with open(pickle_file, 'rb') as f:
        letter_set = pickle.load(f)
        # let's shuffle the letters to have random validation and training set
        Nshuf = quantumrandom.randint(0,10)
        for i in range(0,Nshuf):
          np.random.shuffle(letter_set)

        if valid_dataset is not None:
          valid_letter = letter_set[:vsize_per_class, :, :]
          valid_dataset[start_v:end_v, :, :] = valid_letter
          valid_labels[start_v:end_v] = label
          start_v += vsize_per_class
          end_v += vsize_per_class
     
        train_letter = letter_set[vsize_per_class:end_l, :, :]
        train_dataset[start_t:end_t, :, :] = train_letter
        train_labels[start_t:end_t] = label
        start_t += tsize_per_class
        end_t += tsize_per_class
    except Exception as e:
      print('Unable to process data from', pickle_file, ':', e)
      raise
    pbar.update(1)
  return valid_dataset, valid_labels, train_dataset, train_labels
Ejemplo n.º 21
0
    def on_data(self, data):
        print('Incoming: {0}'.format(data))
        tweet = json.loads(data)
        screen_name = tweet['user']['screen_name']
        me = screen_name == bot.SCREEN_NAME
        retweet = 'retweeted_status' in tweet

        if not me and not retweet:
            #declare TRNG lines 42-47
            flip = int(quantumrandom.randint(0, 100))
            if flip >= 50:
                flip = 1
            else:
                flip = 0
            side = bot.SIDES[flip]
            hashtag = random.choice(bot.HASHTAGS)
            e = random.choice(emoji.EMOJI.values())

            # I swear that the next line of code isn't Ruby.
            reply = u'@{0} {1}. #{2} {3}'.format(screen_name, side, hashtag, e)
            try:
                log = u'Outgoing: {0}'.format(reply)
                print(log)
            except UnicodeEncodeError:
                log = bot.unicode_to_ascii(reply)
                log = u'Outgoing: {0}'.format(log)
                print(log)

            if bot.ENV == 'production':
                try:
                    bot.api.update_status(reply, tweet['id'])
                except tweepy.TweepError:
                    pass

        # Return True to keep the stream listener listening.
        return True
Ejemplo n.º 22
0
 def secure_key(self,length):
     self.check_modules()
     keygen = lambda y:''.join([self.characters[int(Random.randint(0,len(self.characters)))] for i in range(0,int(y))])
     return keygen(length)
Ejemplo n.º 23
0
def randint(min, max):
    if trulyRandom:
        return int(quantumrandom.randint(min, max))
    else:
        return int(random.randint(min, max))
Ejemplo n.º 24
0
import math
import numpy as np
import matplotlib.pyplot as plt

datax = []
datay = []

count = 0  # this will keep track of the number of points found in that quarter circle
datac = []  # this will hold the number of calculated Pi values
piValues = 500  # how many pi values we will calculate
totalPoints = 1000  # how many points we set to be found in that quarter of the square
dataPi = []

# this simulates points for square (x,y) between 0 and 1
for i in range(1000):
    datax.append(quantumrandom.randint(0, 10) / 10)
    datay.append(quantumrandom.randint(0, 10) / 10)

# circle function


# This function finds if point is in circle by using a quarter of a circle (upper right quadrant) and takes in a
def calculatePi(pValue):
    for k in range(pValue):
        j = 0
        count = 0
        while (j < circlePoints):
            x = (quantumrandom.randint(0, 10) * (0.05)) + (
                0.5
            )  # taking a random point in the upper right quadrant of circle
            circleEq = (0.5) + math.sqrt(
def all(args):
    """
    run all sequence modification changes
    """


    import random as rand
    import quantumrandom as qrand
    import platform

    if (args.seed):
        RANDOM_SEED=args.seed
        logging.info("User supplied random seed")
    else:
        RANDOM_SEED= int(qrand.randint(0, 20000000000000))

    logging.info("Random seed is: %s",RANDOM_SEED)
    rand.seed(RANDOM_SEED)


    logging.info("==Python Details==")
    logging.info("Version: %s",platform.python_version())
    logging.info("Implementation: %s",platform.python_implementation())
    logging.info("Platform: %s",platform.platform())



    import os
    morph_dir=args.output+"/morph"

    if not os.path.exists(morph_dir):
        os.makedirs(morph_dir)
    import skbio

    bootstrap = args.bootstraps

    for f in args.files:
        
        exp_sequences = []
        # since SecretomeP will remove duplciates in input, implement a ful maping from original header to an incrementing ID
        morph_id=1
        logging.info("Morph_ID initialised at: %d", morph_id)

        sk_seqs = skbio.io.read(f, format='fasta')

        for s in sk_seqs:
            print(s.metadata)
            exp_sequences.append(MorphedSequence(s.metadata['id'],s.metadata['description'],str(s),bootstrap,call_signalP))




        output_stub = morph_dir + "/" + os.path.basename(f.name)
        exclude_less_than=41
        with open(output_stub+"_original.fasta", 'w') as original, open(output_stub+"_rev.fasta", 'w') as reverse,open(output_stub+"_spremove.fasta", 'w') as sp_remove,open(output_stub+"_spcterm.fasta", 'w') as sp_cterm,open(output_stub+"_sprandom.fasta", 'w') as sp_random,open(output_stub+"_random.fasta", 'w') as random:
         for m in exp_sequences:
          if (len(m.seq) < exclude_less_than):
            continue
          # use annotations for headers
          # O)riginal with description intact
          # R)everse
          # r(A)ndom with iteration
          # S)p_remove
          # sp_ra(N)dom with iteration
          # sp_(C)term
          # i.e O1, R2,  A3 
          #
          skbio.sequence.Protein(sequence = m.seq , metadata= {'id': "O"+str(morph_id), 'description': m.header +":"+m.description } ).write(original)
          morph_id = morph_id+1 

          skbio.sequence.Protein(sequence = m.rev , metadata= {'id': "R"+str(morph_id), 'description':m.header +":" + 'sequence reversed'} ).write(reverse)
          morph_id = morph_id+1 

          if (m.positive_data):
             skbio.sequence.Protein(sequence = m.sp_remove , metadata= {'id': "S"+str(morph_id), 
                                                                       'description': m.header+": "+'SP at positions' + m.drange + ' removed using '+str(m.signal_function.__name__)} ).write(sp_remove)
             morph_id = morph_id+1 
             skbio.sequence.Protein(sequence = m.sp_cterm , metadata= {'id': "C"+str(morph_id), 
                                                                      'description': m.header +": "+'SP at positions' + m.drange + ' placed at  C-terminus using '+ str(m.signal_function.__name__)} ).write(sp_cterm)
             morph_id = morph_id+1 
          else:
             skbio.sequence.Protein(sequence = m.sp_remove , metadata= {'id': "S"+str(morph_id),
                                                                       'description': m.header+": "+ 'False SP at positions' + m.drange + ' removed (negative data)'} ).write(sp_remove)
             morph_id = morph_id+1 
             skbio.sequence.Protein(sequence = m.sp_cterm , metadata= {'id': "C"+str(morph_id),
                                                                      'description': m.header +": "+'False SP at positions' + m.drange + ' placed at  C-terminus (negativa data)'} ).write(sp_cterm)
             morph_id = morph_id+1 


          randoms = m.random
          iteration=1
          for r in randoms:
            skbio.sequence.Protein(sequence = r , metadata= {'id': "A"+str(morph_id), 'description':  m.header+":"+  ' randomised iteration '+str(iteration)} ).write(random)
            iteration = iteration +1
            morph_id = morph_id+1 

          sp_randoms = m.sp_random
          iteration=1
          for spr in sp_randoms:
                skbio.sequence.Protein(sequence = spr , metadata= {'id': "N"+str(morph_id), 'description': m.header+": "+' SP randomised' +' using '+ str(m.signal_function.__name__) + 'iteration '+str(iteration)} ).write(sp_random)
                iteration = iteration +1
                morph_id = morph_id+1 


          logging.info("Morph_ID finished at: %d", morph_id)
Ejemplo n.º 26
0
import re

try:
    import quantumrandom
    generator = quantumrandom.cached_generator()
    get_int = lambda n: quantumrandom.randint(1, n, generator)
except ImportError:
    import random
    get_int = lambda n: random.randint(1, n)


def roll(n, sides, bonus=0):
    return sum([get_int(sides) for i in xrange(n)], bonus)


pattern = re.compile(r'^([0-9]*)d([0-9]+)(?:\+([0-9]+))?')


def rollstr(s):
    match = pattern.match(s)
    if not match:
        raise ValueError("Badly formatted roll string: %s" % s)
    n, sides, bonus = match.groups
    if not n: n = 0
    if not bonus: bonus = 0
    return roll(int(n), int(sides), int(bonus))


def check(dc, bonus=0, tie_win=False, extremes=True):
    raw_result = roll(1, 20, 0)
    if extremes and raw_result in (1, 20): return raw_result == 20
Ejemplo n.º 27
0
import quantumrandom


def few_numbers():
    return quantumrandom.get_data(data_type='uint16', array_length=5)


print('число от 0 до 9          = ', quantumrandom.randint(0, 9))
print('целое число от 0 до 9    = ', int(quantumrandom.randint(0, 9)))
random_list = few_numbers()
print(
    'лист из нескольких чисел = ',
    random_list,
)
Ejemplo n.º 28
0
async def quantumroll(client, message):
    i = math.floor(quantumrandom.randint(1, 7))
    response = "You rolled a " + str(i) + " {0.author.mention}."
    await message.channel.send(response.format(message))
    return
Ejemplo n.º 29
0
def MakeAndSendMemeMail():
    import quantumrandom as Qran  #quantumrandom is like random, but it uses a newer method to get better random
    import smtplib  #number. It's called quantumrandom because it uses newer quantum computer
    from email.mime.text import MIMEText  #technology.
    from email.mime.multipart import MIMEMultipart
    from email.mime.base import MIMEBase
    from email import encoders
    import os.path
    import time as T
    from NamesAndImagesLists import image_list
    from NamesAndImagesLists import email_list

    start_time = T.time()  #The timer starts here

    #the program picks the meme with this
    ran_meme = round(Qran.randint(1, 9))
    meme = image_list[ran_meme]
    print(meme, '\n')

    #this program picks the email to send to
    ran_email = round(Qran.randint(1, 6))
    email = email_list[ran_email]

    #for the two parts that randomly get the meme and email, be sure to set the number after Qran.randint. The second number
    #should be the amount you have. I.e., if I have 3 memes and 2 emails it should look like this:
    #    ran_meme = round(Qran.randint(1,3))
    #    ran_email = round(Qran.randint(1, 2))

    print('Starting\n')

    #This is for setting up the email in the code. Look at the readme for the guide on what settings you have to change
    #in the email
    sender = '*****@*****.**'
    password = '******'
    send_to_email = email

    #This is where you set the subject and text of the email
    subject = "You've got MemeMail"
    message = ""

    #This is the program taking the parameters we've set previously in the script and formatting them to be an email
    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = send_to_email
    msg['Subject'] = subject

    #This is converting the image into something that can be sent via email
    msg.attach(MIMEText(message, 'plain'))
    attachment = open(meme, "rb")
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % meme)
    msg.attach(part)

    print('Email Fully Built\n')
    print('Email is being sent to ', send_to_email, ' ')

    try:
        server = smtplib.SMTP(
            'smtp.gmail.com',
            587)  #This part is the program connecting to the server and
        server.starttls()  #attempting to send the email
        server.login(sender, password)
        text = msg.as_string()
        server.sendmail(sender, send_to_email, text)
        server.quit()
        print('Success...?')
    except:
        print('Failed to either connect to server or to send the email')

    end_time = T.time()  #The end of the timer

    print("Ending Program\n", "Finished in", end_time - start_time,
          "seconds.\n")  #Final message stating completion
Ejemplo n.º 30
0
 def __init__(self, e, n):
     self.gameLength = int(quantumrandom.randint(1, n))
     self.currentGame = 0
     self.p1_moves = []
     self.p2_moves = []
     self.entropy = e
Ejemplo n.º 31
0
import re

try:
	import quantumrandom
	generator = quantumrandom.cached_generator()
	get_int = lambda n: quantumrandom.randint(1, n, generator)
except ImportError:
	import random
	get_int = lambda n: random.randint(1, n)


def roll(n, sides, bonus=0):
	return sum([get_int(sides) for i in xrange(n)], bonus)


pattern = re.compile(r'^([0-9]*)d([0-9]+)(?:\+([0-9]+))?')
def rollstr(s):
	match = pattern.match(s)
	if not match:
		raise ValueError("Badly formatted roll string: %s" % s)
	n, sides, bonus = match.groups
	if not n: n = 0
	if not bonus: bonus = 0	
	return roll(int(n), int(sides), int(bonus))


def check(dc, bonus=0, tie_win=False, extremes=True):
	raw_result = roll(1, 20, 0)
	if extremes and raw_result in (1, 20): return raw_result == 20
	result += bonus
	return result > dc or (tie_win and result == dc)
Ejemplo n.º 32
0
        "Ok {}! What is the smartest insect?".format(student),
        "Alright {}! What did the spider make online?".format(student),
        "R U ready {}? Why do magicians always do so well at school?".format(
            student),
        "Your turn {}! Which side of the turkey has the most feathers? left side? Right side?"
        .format(student)
    ]

    as_joke = [
        "Your computer has a byte ^O^", "Bison..... Get it?",
        "They are full of problem T-T",
        "Because the kid wanted to go to HIGH school >O<", "Spelling Bee",
        "A Website! hehe", "They can handle trick question!",
        "is the OUTSIDE! hahahaha"
    ]
    rand = quantumrandom.randint(0, 7)
    print("\n")

    for char in qs_joke[int(rand)]:
        print(char, end='')
        sys.stdout.flush()
        time.sleep(0.15)

    time.sleep(5)
    print("\n")

    for char in as_joke[int(rand)]:
        print(char, end='')
        sys.stdout.flush()
        time.sleep(0.1)
Ejemplo n.º 33
0
def die(sides): return quantumrandom.randint(1, sides, generator)


class Room(object):
Ejemplo n.º 34
0
from lxml import html
import random
import re

#Get string from user

question = input('Question: ')
lucky_number = sum([x for x in map(ord, question)])

#print('Lucky number:', lucky_number) #DEBUG

#Get a random interger

try:
    print('Connecting to quantum random number generator...')
    ran = int(quantumrandom.randint(0, 78))
except:
    print('Failed, falling back to pseudo-random number generator...')
    ran = int(random.randint(0, 77))

#print('Random integer:', ran) #DEBUG

#Combine two numners to get card index

i = (ran + lucky_number) % 78

#print('Card index:', i) #DEBUG

## Major Arcana

if i < 22:
Ejemplo n.º 35
0
def main():
    end = False

    while (end == False):

        print("1: generate a new master password")
        print("2: login")
        print("3: quit")

        mainMenu = input("enter prefered number to proceed.")
        if mainMenu == str(2):
            passDetails = {}
            options = ["site", "login", "rules", "exclude", "length"]

            index = 0

            while index <= 4:
                details = input(f"Enter {options[index]} details")
                if index == 3 and details == "none":
                    passDetails[options[index]] = ""
                    index += 1
                    continue
                if details == 'quit':
                    break

                passDetails[options[index]] = details
                index += 1

            print(passDetails)
            masterPassword = input("enter master password")

            print(makePassword(masterPassword, passDetails))
        elif mainMenu == str(3):
            print("exiting....")
            break
        elif mainMenu == str(1):
            print("PASSWORD")
            len = input("specify length of password")
            #length of string is 94 characters long
            SYMBOLS = CHARACTER_SUBSETS["lowercase"] + CHARACTER_SUBSETS[
                "uppercase"] + CHARACTER_SUBSETS["digits"] + CHARACTER_SUBSETS[
                    "symbols"]
            masterPassword = ""
            for character in range(int(len)):
                num = int(quantumrandom.randint(0, 94))
                masterPassword += SYMBOLS[num]

            passDetails = {
                "site": "37L>,5k*R?y`unyS",
                "login": "******",
                #lowercase, uppercase, digits, symbols
                "rules": ["lowercase", "uppercase", "digits", "symbols"],
                "exclude": "",
                "length": len
            }
            print(
                "write this password down somewhere safe and cozy, we do not reccoment you storing this anywhere but in real life!"
            )
            print(makePassword(masterPassword, passDetails))

    print("generated password", " ",
          makePassword("j^%pC*3UKDgzBr%lXMHqC", passDetails))
Ejemplo n.º 36
0
import quantumrandom
import ssl

ssl._create_default_https_context = ssl._create_unverified_context
Cardinality = 4
Cardinality_Subset = 2
universe = []
sample = []
dice = 0
element = 0
# New Universe.
for i in range(1,Cardinality+1):
    universe.append(i)

for i in range(1,Cardinality_Subset + 1):
    print("Universum:")
    print(universe)
    Cardinality = len(universe)
    print("Card of Universum = ", Cardinality)
    dice = round(quantumrandom.randint(1, Cardinality))
    print("====|||| Dice = ", dice)
    element = universe[dice - 1]
    sample.append(element)
    print("Element selected {", element, "}")
    del universe[dice - 1]
    print("Universe after {", element, "} selected.")
    print(universe)

sample.sort()
print("Sample:")
print(sample)
Ejemplo n.º 37
0
 def test_randint(self):
     for i in range(5):
         for j in range(i + 1, 5):
             for k in range(3):
                 val = quantumrandom.randint(i, j)
                 assert(val >= i and val < j)