def tweetDictionary():

    dictionary = PyDictionary()
    rw = RandomWords()

    word = rw.random_word()
    definitions = dictionary.meaning(word)     # definitions is dictionary of two items (noun,verb)

    # print('\nWord : ',word, '\nDefinitions : ', definitions)
    # F-strings provide a way to embed expressions inside string literals, using a minimal syntax

    now = getDatetime()
    tweet = f'''Word of the Day
    Date: {now.strftime("%y-%m-%d")}
    Word: {word}
    Meaning: {definitions}
    Source: "PyDictionary"
    '''
    size = sys.getsizeof(tweet)
    print('Dictionary tweet size: ', size)

    if size < 362:
        api.update_status(tweet)
        print('Word tweeted successfully')
    else:
        print('error, loading again')
        tweetDictionary()
Exemplo n.º 2
0
def gen(rank):
    # 先确认每个小时的查询数目,里面的数都是随机生成的,没有什么特殊含义
    query_nums = []
    for h in range(0, 6):
        query_nums.append(random.randint(1, 10) * rank) # 0点到6点的比较少
    for h in range(6, 12):
        query_nums.append(random.randint(h * 2, h * 3) * rank) # 6点到12点的逐渐增多
    for h in range(12, 24):
        query_nums.append(random.randint((24 - h) * 2, (24 - h) * 3) * rank) # 12点到24点逐渐减少
    print("每小时访问数"+str(query_nums))
    print("总访问数:"+str(sum(query_nums)))
    rw = RandomWords() # 用于随机生成一个单词
    terminals = ["pc", "android", "iphone"] # 终端,可以分析维度
    zero_ts = time.mktime(time.strptime("2021-01-04 00:00:00", "%Y-%m-%d %H:%M:%S")) # 时间戳的起点
    res = []
    for hour in range(24):
        for cnt in range(0, query_nums[hour]): # 生成每小时的具体访问记录
            user_id = random.randint(50, 100)
            word = rw.random_word()
            terminal = terminals[random.randint(0, 2)]
            ts = str(int(zero_ts) + hour * 3600 + random.randint(0, 3600))
            res.append((str(user_id), word, terminal,ts))
    res.sort(key=lambda x: x[3]) # 按时间戳排序
    # 写入文件
    with open("./user_word.log", mode="w", encoding="utf-8") as f:
        for r in res:
            f.write(",".join(r) + "\n")
Exemplo n.º 3
0
def dbpost():
    # changes these to the master
    try:
        conn = psycopg2.connect(database=os.environ.get('PG_DATABASE'), user=os.environ.get('PG_USER'),
                                host=os.environ.get('MASTER_SERVICE_HOST'), password=os.environ.get('PG_PASSWORD'))
    except:
        print(os.environ.get('MASTER_SERVICE_HOST'))

    # generate a random lat, lon, and place name
    lat = random.uniform(-90, 90)
    lon = random.uniform(-180, 180)
    rw = RandomWords()
    name = rw.random_word() + " " + rw.random_word()

    sql_string = """insert into parkpoints(name, the_geom) values ('""" + name + """', ST_GeomFromText('POINT("""
    sql_string = sql_string + str(lon) + " " + str(lat) + ")', 4326));"

    cur = conn.cursor()
    # I know not this is not good form but I couldn't get it to work with the SRID stuff - probably just being lazy
    cur.execute(sql_string)

    conn.commit()

    # now let's get back our data we just put in
    cur.execute("""select parkid, name, ST_AsText(the_geom) from parkpoints ORDER by parkid DESC LIMIT 10""")

    rows = cur.fetchall()
    result_string = "<h2>Here are your results: </h2>"
    for row in rows:
        result_string += "<h3>" + str(row[0]) + ", " + str(row[1]) + ", " + str(row[2]) + "</h3>"

    cur.close()
    conn.close()
    return result_string
Exemplo n.º 4
0
def dbpost():

    #changes these to the master
    try:
        conn = psycopg2.connect(
            database=os.environ.get('PG_DATABASE'),
            user=os.environ.get('PG_USER'),
            host=os.environ.get('PG_MASTER_RC_SERVICE_HOST'),
            password=os.environ.get('PG_ROOT_PASSWORD'))
    except:
        print(
            os.environ.get('PG_USER') + "  " +
            os.environ.get('PG_SLAVE_RC_SERVICE_HOST'))

    #Need to generate some data - no need for ID
    #NEED a name and a lat and long
    lat = random.uniform(-90, 90)
    lon = random.uniform(-180, 180)
    rw = RandomWords()
    name = rw.random_word() + " " + rw.random_word()

    #here comes the insert srid = 4326
    cur = conn.cursor()
    cur.execute(
        """select parkid, name, ST_AsText(the_geom) from parkpoints limit 10"""
    )

    rows = cur.fetchall()
    result_string = "<h2>Here are your results: </h2>"
    for row in rows:
        result_string += "<h3>" + str(row[0]) + ", " + str(
            row[1]) + ", " + str(row[2]) + "</h3>"

    return result_string
Exemplo n.º 5
0
def generate(request):
    print(request.method)
    print "made it to the route"
    request.session['attempt'] += 1
    rw = RandomWords()
    request.session['random_word'] = word = rw.random_word()
    return redirect('/')
Exemplo n.º 6
0
def setup_nodes(X, Y, holes):
	rw = RandomWords()
	names_count = min(X*Y, 5400)
	node_names = rw.random_words(count=names_count)

	nodes = collections.OrderedDict()
	for y in range(0, Y):
		for x in range(0, X):
			nodes[(x, y)] = Node(x, y, node_names.pop())
			if not len(node_names):
				node_names = rw.random_words(count=names_count)

	to_remove = random.sample(nodes.keys(), holes)
	for trm in to_remove:
		nodes.pop(trm)

	for node in nodes.values():
		node.neighbors = get_neighbors((node.X, node.Y), nodes)

	# Randomly puts flags on a random node. Start in the first 25%
	# and end in the last 25%.
	if len(nodes.keys()) >= 2:
		quarter = int(len(nodes.keys())/4.0 ) or 1
		first_quarter = list(nodes.keys())[:quarter]
		last_quarter = list(nodes.keys())[-quarter:]
		start = random.choice(first_quarter)
		nodes[start].name = "Start"
		end = random.choice(last_quarter)
		nodes[end].name = "End"

	return list(nodes.values())
Exemplo n.º 7
0
def dbpost():

	#changes these to the master
	try:
		conn = psycopg2.connect(database=os.environ.get('PG_DATABASE'), user=os.environ.get('PG_USER'), host=os.environ.get('PG_MASTER_RC_SERVICE_HOST'), password=os.environ.get('PG_ROOT_PASSWORD'))
	except:
		print(os.environ.get('PG_USER')	+ "  " + os.environ.get('PG_SLAVE_RC_SERVICE_HOST'))

	#Need to generate some data - no need for ID
	#NEED a name and a lat and long
	lat = random.uniform(-90,90)
	lon = random.uniform(-180,180)
	rw = RandomWords()
	name = rw.random_word() + " " + rw.random_word()

	#here comes the insert srid = 4326
	cur = conn.cursor()
	cur.execute("""select parkid, name, ST_AsText(the_geom) from parkpoints limit 10""")

	rows = cur.fetchall()
	result_string = "<h2>Here are your results: </h2>"
	for row in rows:
		result_string += "<h3>" + str(row[0]) + ", " + str(row[1]) + ", " + str(row[2]) + "</h3>"

	return  result_string
Exemplo n.º 8
0
def create_task(screen_name, consumer_key, consumer_secret, user_key,
                user_secret):
    ecs = boto3.client('ecs', region_name=conf.get_config('AWS_REGION_NAME'))
    ec2 = boto3.client('ec2', region_name=conf.get_config('AWS_REGION_NAME'))

    try:
        rw = RandomWords()
        word = rw.random_words(count=3)
        password = '******' % (word[0], word[1], word[2])

        tn_logger.debug('Calling run_task')
        task_arn = run_task(ecs, screen_name, consumer_key, consumer_secret,
                            user_key, user_secret, password)
        tn_logger.debug('Done calling run_task')
        task_info = get_task_info(ecs, task_arn)
        ip_address = get_connection_ip(ec2, task_info['instanceId'])
        try_connecting_neo4j(ip_address, task_info['port'])
        tn_logger.info('Created instance for tw:%s at %s:%s' %
                       (screen_name, ip_address, task_info['port']))
    except Exception as e:
        tn_logger.exception(e)
        tn_logger.error('Error creating docker image for: tu:%s' % screen_name)
        print(traceback.format_exc())
        print(e)
        raise e

    response_dict = {
        'url': 'http://%s:%s' % (ip_address, task_info['port']),
        'password': password
    }

    return response_dict
Exemplo n.º 9
0
def generate(request):
    print "You made it to generate!"
    if request.method == "POST":

        try:
            request.session['count'] = request.session['count'] + 1
        except:
            request.session['count'] = 1

        #Even though the image uses a random string of letters/nums
        #I wanted to try and do a length 14 word so I imported
        #the the module RandomWords and used a loop
        #to loop randomly through the dictionary until I found a 14
        #letter word. Not the most efficient in terms of speed
        #by any means, but still a functional product.

        rw = RandomWords()
        word = rw.random_word()

        while len(word) != 14:
          word = rw.random_word()
          print "searching for a word"

        request.session['random_word'] = word

        return redirect('/')

    else:

        return redirect('/')
Exemplo n.º 10
0
def vad():
    if request.method == 'POST':
        global random_words

        f = open('./static/audio/background_noise.wav', 'wb')
        f.write(request.data)
        f.close()

        background_noise = speech_recognition.AudioFile(
            './static/audio/background_noise.wav')
        with background_noise as source:
            speech_recognition.Recognizer().adjust_for_ambient_noise(source, duration=5)

        print("Voice activity detection complete ...")

        random_words = RandomWords().random_words(count=5)
        print(random_words)

        return "  ".join(random_words)

    else:
        background_noise = speech_recognition.AudioFile(
            './static/audio/background_noise.wav')
        with background_noise as source:
            speech_recognition.Recognizer().adjust_for_ambient_noise(source, duration=5)

        print("Voice activity detection complete ...")

        random_words = RandomWords().random_words(count=5)
        print(random_words)

        return "  ".join(random_words)
Exemplo n.º 11
0
 def random_words(self):
     #for url creation
     rw =  RandomWords()
     w1 = rw.random_word()
     w2 = rw.random_word()
     w3 = rw.random_word()
     return w1 + "-" + w2 + "-" + w3
Exemplo n.º 12
0
def rand_words():
    perfect = []
    rw = RandomWords()
    f = input('Enter the first alphabet of word or press enter for all words >'
              ).strip()
    print()
    for n in range(10000):
        score = 0
        if f and f.isascii():
            word = rw.random_word(f).upper()
        else:
            word = rw.random_word().upper()
        for ch in word:
            if ch in alpha_value.keys():
                score += alpha_value[ch]
        if score == 100 and word not in perfect:
            perfect.append(word)
    print('Random words with 100% score value are as listed below:')
    for ch in up_alp:
        subword = []
        for word in perfect:
            if word.startswith(ch):
                subword.append(word)
        if subword:
            print(f'Word starting with "{ch}" are:')
            print(subword)
            print()
    print()
Exemplo n.º 13
0
 def __init__(self):
     self.root = Tk()
     self.root.geometry('300x400')
     self.root.title('Hangman!')
     self.rw = RandomWords()
     self.word = ""
     self.canvas = Canvas(self.root, width=300, height=400, bg='orange')
     self.correct_letters_text = self.canvas.create_text(150,
                                                         250,
                                                         text="_ " *
                                                         len(self.word),
                                                         font='TNR 15 bold')
     self.wrong_letters_text = self.canvas.create_text(75,
                                                       320,
                                                       text="",
                                                       font='TNR 15 bold')
     self.value = True
     self.mouth = None
     self.button = None
     self.entry = None
     self.correct_letters = list()
     self.wrong_letters = list()
     self.status_text = self.canvas.create_text(150, 275, text=' ')
     self.stopwatch_state = True
     self.stopwatch_counter = 0
     self.alphabet = 'abcdefghijklmnopqrstuvwxys'
Exemplo n.º 14
0
def generate_example_fixed_file(outfile,
                                column_names,
                                offsets,
                                include_header,
                                encoding='windows-1252'):
    """Writes an example fixed-width file with random text.

    Args:
        outfile (str): output file name
        column_names (str[]): list of column names
        offsets (int[]): list of widths for each column
        encoding (str): encoding of the output file
        include_header (bool): whether to include the header in the output
            file

    Returns:
        N/A
    """
    log = logging.getLogger(__name__)
    log.info('Writing example fixed-width file following the spec...')

    rw = RandomWords()
    with open(outfile, 'w', encoding=encoding) as out_fh:
        # write header
        if include_header:
            for i, column in enumerate(column_names):
                out_fh.write(pad_fixed_column(column, offsets[i]))
            out_fh.write('\n')
        # write contents
        for i in range(0, EXAMPLE_FIXED_FILE_ROWS):
            for offset in offsets:
                out_fh.write(pad_fixed_column(rw.random_word(), offset))
            out_fh.write('\n')
Exemplo n.º 15
0
    def get_word(self):
        rw = RandomWords()
        word = rw.random_word()
        self.word = word.lower()

        # To show word on terminal for demo purposes only
        print(self.word)
Exemplo n.º 16
0
def goToPhoto():
    driver.implicitly_wait(5)

    photos = []

    elems = driver.find_elements_by_xpath("//a[@href]")
    for elem in elems:
        if (re.search("https://www.instagram.com/p/",
                      elem.get_attribute("href"))):
            photos.append(elem.get_attribute("href"))

    for photo in photos:
        driver.get(photo)
        time.sleep(5)

        if (len(
                driver.find_element_by_tag_name('svg').get_attribute(
                    "aria-label")) == len("J'aime")):
            print("j'aime")
            driver.find_element_by_class_name(
                "_8-yf5 ").click()  #click sur j'aime
        time.sleep(10)

    rw = RandomWords()
    goToTag(rw.random_word())
    goToPhoto()
Exemplo n.º 17
0
def create_task(screen_name, consumer_key, consumer_secret, user_key, user_secret):
    ecs = boto3.client('ecs', region_name=conf.get_config('AWS_REGION_NAME'))
    ec2 = boto3.client('ec2', region_name=conf.get_config('AWS_REGION_NAME'))

    try:
      rw = RandomWords()
      word = rw.random_words(count=3)
      password = '******' % (word[0], word[1], word[2])

      tn_logger.debug('Calling run_task')
      task_arn = run_task(ecs, screen_name, consumer_key, consumer_secret, user_key, user_secret, password)
      tn_logger.debug('Done calling run_task')
      task_info = get_task_info(ecs, task_arn)
      ip_address = get_connection_ip(ec2, task_info['instanceId'])
      try_connecting_neo4j(ip_address, task_info['port'])
      tn_logger.info('Created instance for tw:%s at %s:%s' % (screen_name,ip_address,task_info['port']))
    except Exception as e:
      tn_logger.exception(e)
      tn_logger.error('Error creating docker image for: tu:%s' % screen_name)
      print(traceback.format_exc())
      print(e)
      raise e

    response_dict = { 
      'url': 'http://%s:%s' % (ip_address, task_info['port']),
      'password': password }
 
    return response_dict
def wordgen():
    rw = RandomWords()
    word = str(rw.random_word())
    blank ='_'
    for i in range(0,len(word)):
        blank += '_'
    return word,blank
Exemplo n.º 19
0
 def __init__(self):
     self.data = []
     self.ip_addresses = []
     user_agents = []
     fake = Factory.create('en_AU')
     rw = RandomWords()
     for i in range(randint(1, 15)):
         ip_address = fake.ipv4(network=False)
         self.ip_addresses.append(ip_address)
     for i in range(randint(2, 8)):
         user_agents.append(fake.user_agent())
     # Generate fake query history
     for i in range(randint(1, 500)):
         # Use real Google Trends keywords in 20% of cases
         if randint(1, 100) < 20:
             q = random.choice(google_search_queries)
         else:
             q = ' '.join(rw.random_words(count=randint(1, 4)))
         search_query = {
             # Choose a random IP address
             'ip_address':
             random.choice(self.ip_addresses),
             # Select random date
             'date':
             fake.date_time_between(start_date="-2y",
                                    end_date="now",
                                    tzinfo=None),
             # Generate random keywords
             'search_query':
             q,
             'user_agent':
             random.choice(user_agents),
         }
         self.data.append(search_query)
Exemplo n.º 20
0
def uuid(argc):
    """uuid: Yields a Universal Unique ID (UUID).

    Usage:
        uuid [int | hex | words] [LENGTH]
    """
    
    if not argc.args['LENGTH']:
        length = 4
    else:
        try:
            length = int(argc.args['LENGTH'])
        except ValueError:
            raise ErgonomicaError("[ergo: uuid]: UUID length must be an int.")
            
        
    if argc.args['hex']:
        charset = '0123456789abcdef'
        return "".join([random.choice(charset) for x in range(length)])
    
    elif argc.args['words']:
        rw = RandomWords()
        return " ".join([str(x) for x in rw.random_words(count=length)])

    else:
        charset = "0123456789"
        return "".join([random.choice(charset) for x in range(length)])
Exemplo n.º 21
0
def setup_nodes(X, Y, holes):
    node_positions = []
    for y in range(0, Y):
        for x in range(0, X):
            node_positions.append([x, y])

    # removes 'holes' nodes randomly
    to_remove = random.sample(node_positions, holes)
    for n in to_remove:
        node_positions.remove(n)

    # generate a list of random words to name each node
    rw = RandomWords()
    node_names = rw.random_words(count=len(node_positions))

    nodes = []
    for n in node_positions:
        nodes.append(
            Node(n[0], n[1], neighbors(n, node_positions), node_names.pop()))

    if len(nodes) >= 2:
        quart = int(len(nodes) / 4.0)
        start = random.choice(nodes[:quart])
        start.flag = "start"
        start.name = "name"
        end = random.choice(nodes[-quart:])
        end.flag = "end"
        end.name = "end"
    return nodes
Exemplo n.º 22
0
 def __init__(self, opt, train):
     self.opt = opt
     self.rw = RandomWords()
     self.dictionary = PyDictionary()
     self.prob_repeat_example = 0.25
     self.n_items = int(1 / self.prob_repeat_example)
     self.word_dict()
Exemplo n.º 23
0
def generate_filenames(count=10):
    # this provides filenames to iterate over, replace with e.g. listdir
    rw = RandomWords()
    filenames = []
    for _ in range(count):
        word = ''.join(rw.random_words(count=3))
        filenames.append(word)
    return filenames
Exemplo n.º 24
0
def getQuestion():
    rw = RandomWords()
    ans = rw.random_word()
    hint = dictionary.meaning(ans)
    print(hint)
    print(ans)
    question = reorganize(ans)
    return question, ans, hint
Exemplo n.º 25
0
def getQuestion():
    rw = RandomWords()
    word4game = rw.random_word()
    hint = dictionary.meaning(word4game)
    print(hint)
    print(word4game)
    question, ansLetter = word_to_underscore(word4game)
    return question, ansLetter, hint
Exemplo n.º 26
0
def getRandomSearchWord(listSize):
    global searchQs
    rw = RandomWords()
    word = rw.random_word()
    searchQs=[] # clear existing word list
    for w in range(0,listSize):
        searchQs.append(rw.random_word())
    return searchQs
Exemplo n.º 27
0
def gen_words():
    rw=RandomWords()
    words=[]
    while len(words)<10:
        word=rw.random_word()
        if 3<len(word)<9:
            words.append(word)
    return words
def write_audio(username):
    """
    Obtains audio from the microphone and writes a .wav if the spoken phrase matches the passphrase
    """
    r = sr.Recognizer()
    rw = RandomWords()
    count = random.randint(8, 10)
    words = rw.random_words(count=count)
    while True:
        passed = False
        with sr.Microphone() as source:
            while True:
                r.adjust_for_ambient_noise(source)
                words = rw.random_words(count=count)
                printf("Please read the following words")
                printf(" ".join(words))
                flag = 0
                while flag == 0:
                    audio = r.listen(source, timeout=20)
                    signal = audio.get_wav_data()
                    printf("Processing...")
                    # Mimicking sending it to server. Send audio and bytes of audio
                    signature = verify.sign_wav(signal, username)

                    # Verify the wav
                    verified = verify.verify_wav(signal, username, signature)
                    # if not verified, it will raise an InvalidSignatureError

                    # Is verified, can go on to complete writing the audio to the server
                    try:
                        goog_str = r.recognize_google(audio)
                        goog_str = str(goog_str)
                        flag = flag + 1
                    except:
                        printf("Could not understand audio")
                        printf("Speak again")

                check = check_words(goog_str, words)
                if check:
                    printf("Recognized String")
                    if not os.path.exists("accounts/" + username):
                        os.makedirs("accounts/" + username)
                    path = "C:/Users/Aayush/Desktop/Minor_2/voice" + "/accounts/" + username + "/"
                    i = 0
                    while os.path.isfile(path + str(i) + ".wav"):
                        i += 1
                    filename = path + str(i) + ".wav"
                    print(filename)
                    with open(filename, "wb") as f:
                        f.write(audio.get_wav_data())
                    break
                else:
                    with open('badaudio', "wb") as f:
                        f.write(audio.get_wav_data())
                    printf(" Your words did not match.")
                    continue

        break
Exemplo n.º 29
0
def generate(request):
    if request.method == 'POST':
        rw = RandomWords()
        word = rw.random_word()
        request.session['count'] = request.session['count'] + 1
        request.session['word'] = word
        return redirect('/')
    else:
        return redirect('/')
Exemplo n.º 30
0
 def random_words(self):
     '''
     Generates three random words for meeting id and url creation
     Outputs: meeting id (a string)
     '''
     rw = RandomWords()
     w1 = rw.random_word()
     w2 = rw.random_word()
     w3 = rw.random_word()
     return w1 + "-" + w2 + "-" + w3
Exemplo n.º 31
0
 def get_wordlist(self):
     rw = RandomWords()
     mnemonic_seed = rw.random_words(count=8)
     word_list = {}
     count = 1
     for word in mnemonic_seed:
         word_list[count] = word
         count += 1
     print(word_list)
     return word_list
Exemplo n.º 32
0
 def random_words(self):
     '''
     Generates three random words for meeting id and url creation
     Outputs: meeting id (a string)
     '''
     rw =  RandomWords()
     w1 = rw.random_word()
     w2 = rw.random_word()
     w3 = rw.random_word()
     return w1 + "-" + w2 + "-" + w3
Exemplo n.º 33
0
def index():
    rw = RandomWords()
    print(session['count'])
    session['count'] += 1
    count = 7 - session['count']

    if session['count'] == 1:
        session['guesses'] = []
        session['wordform'] = 'Guess ! \n'
        session['word'] = rw.random_word().upper()
        session['wordlen'] = len(session['word'])
        name = request.form['word']
        session['wordform'] = "Welcome " + name + " ! "
        for i in range(session['wordlen']):
            session['guesses'].append("?")
            session['wordform'] += "_?_"
        return render_template('number2.html',
                               word=session['wordform'],
                               count=count)

    else:
        guess = str(request.form['gue']).upper()
        if len(guess) > 1 or session['word'].find(guess) == -1:

            if session['count'] == 7:
                lost = "YOU LOST ! The Word was "
                lost += session['word']
                return lost
            return render_template('number2.html',
                                   word=session['wordform'],
                                   count=count)

        else:
            indexing = 0
            session['count'] -= 1
            session['wordform'] = ""
            while indexing < session['wordlen']:
                indexing = str(session['word']).find(guess, indexing)
                if indexing == -1:
                    break
                session['guesses'][indexing] = guess
                indexing += 1
            for i in range((session['wordlen'])):
                session['wordform'] += "_ " + str(session['guesses'][i]) + " _"

            if not '?' in session['guesses']:
                text = "YOU WIN !! THE WORD IS "
                for i in range(session['wordlen']):
                    text += session['guesses'][i]
                return text

            return render_template('number2.html',
                                   word=session['wordform'],
                                   count=count)
Exemplo n.º 34
0
    def gen_words(self):
        rw = RandomWords()
        for i in range(50):
            rand_words = rw.random_word()
            while len(rand_words) > 10:
                rand_words = rw.random_word()

            self.falling_words.append(
                Word(rand_words, self.screen, self.game_font, self.white,
                     self.bg_color))
            self.falling_words[i].draw()
Exemplo n.º 35
0
def book_generator():
    chapters_count = input("Enter chapters count: ")
    print("Enter length range (in words)")
    from_num = input("From: ")
    to = input("To: ")

    for i in range(0, chapters_count):
        words_count = random.randint(from_num, to)
        rw = RandomWords()
        words = rw.random_words(count=words_count)
        print(words)
        for word in words:
            yield word
    def _new_game(self, user, game_name):
        # retrieve key from user_name
        user_key = ndb.Key(User, user.user_name)

        # generate game_id
        game_id = Game.allocate_ids(size=1, parent=user_key)[0]

        # create key using generated game_id and user as its ancestor
        game_key = ndb.Key(Game, game_id, parent=user_key)

        # generate random word for this game
        rw = RandomWords()
        word = rw.random_word()

        guessed_chars_of_word = []

        # make this impl more 'pythonic' way
        for c in word:
            guessed_chars_of_word.append('*')

        game = Game(key=game_key,
                    game_id=game_id,
                    game_name=game_name,
                    word=word,
                    guessed_chars_of_word=guessed_chars_of_word)
        # save game
        game.put()

        # score id
        score_id = Score.allocate_ids(size=1, parent=user_key)[0]

        # score key using generated score_id and user as its ancestor
        score_key = ndb.Key(Score, score_id, parent=user_key)

        # score entity for this game
        score = Score(key=score_key,
                      score_id=score_id,
                      game_key=game_key)
        # save score
        score.put()

        # capture game snapshot
        self._capture_game_snapshot(game, '')

        return game
Exemplo n.º 37
0
def generate_songs_file(
        limit, artist_id_limit=1000000, popularity_limit=1000000):
    """
    generates files like
    1|Help|154681|The Beatles|25
    """
    rw = RandomWords()
    rn = RandomNicknames()
    with open(songs_file, 'w+') as f:
        for i in range(limit):
            line = [str(i)]
            # title
            line.append(' '.join(rw.random_words(count=randint(1, 5))))
            line.append(str(int(popularity_limit * betavariate(2, 5))))
            # artist
            line.append(' '.join(rn.random_nicks(count=randint(1, 3))))
            line.append(str(randint(0, artist_id_limit)))
            f.write('|'.join(line) + '\n')
Exemplo n.º 38
0
def generate_post(who, num, flag):
    if(len(num) > 1):
        if(int(num[1]) < 7):
            num = int(num[1])
        else: num = 1
    else: num = 1
    rw = RandomWords()
    if(flag == 0):
        bot.messages.send(peer_id=who, message="Подготавливаю пост, ждите(это может быть быстро, а может долго. Производительность рандомная, также как и генерируемый пост...)", random_id=random.randint(0, 200000))
    """p = requests.get("https://unsplash.it/900/600/?random")"""

    word = rw.random_word()
    url = flickr.get_random_img(word)
    p = requests.get(url)
    out = open("random.jpg", "wb")
    out.write(p.content)
    out.close()

    img = {'photo': ('img.jpg', open(r'random.jpg', 'rb'))}
    # Получаем ссылку для загрузки изображений
    if(flag == 0):
        response = bot.photos.getMessagesUploadServer()
    else: response = bot.photos.getWallUploadServer()
    upload_url = response['upload_url']

    # Загружаем изображение на url
    response = requests.post(upload_url, files=img)
    result=response.json()

    # Сохраняем фото на сервере и получаем id
    photo1=result['photo'] 
    hash1=result['hash'] 
    server1=result['server']
  
    text = requests.get("http://api.forismatic.com/api/1.0/?method=getQuote&key=457653&format=text&lang=ru")
    if(photo1 != '[]'):
        if(flag == 0): 
            response = bot.photos.saveMessagesPhoto(server=server1, photo=photo1,   hash=hash1) 
        else: response = bot.photos.saveWallPhoto(user_id="360474541", server=server1, photo=photo1,   hash=hash1)
        attach="photo"+str(response[0]['owner_id'])+"_"+str(response[0]['id'])+","+get_random_audio(num)
        if(flag == 0):
            bot.messages.send(peer_id=who, random_id=random.randint(0, 200000),message=text.text, attachment=attach)
        else: bot.wall.post(owner_id="360474541", guid=random.randint(0, 200000),message=text.text, attachment=attach)
Exemplo n.º 39
0
    def __init__(self):
        '''the cur and con objects for accsessing the db'''
        global cur,con
        
        self.cur = cur
        self.con = con
        #self.capt_code = capt_code
        self.rw = RandomWords()
        self.pass_enc = self.rw.random_word()

        ses_log('[init]', 'done')
Exemplo n.º 40
0
    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            phone = form.cleaned_data['username']
            # Genarates the random word for the sms code
            random_word = RandomWords()
            sms_code = random_word.random_word()

            # Creates the record with the random 
            # activation word and the phone number
            ActivationSMSCode.objects.create(
                sms_code=sms_code,
                phone=phone,
                sms_code_init_time=datetime.datetime.utcnow().replace(
                    tzinfo=utc)
            )

            try:
                # Sends sms message with the random word
                api.send_sms(
                    body=sms_code,
                    from_phone=settings.PHONE_NUMBER_FROM,
                    to=[phone],
                    flash=True
                )
            except Exception, e:
                messages.add_message(
                    request,
                    messages.ERROR,
                    SEND_MESSAGE_ERROR
                )
                return HttpResponseRedirect(reverse("signup"))

            return HttpResponseRedirect(
                reverse('signup_activation',
                    kwargs={
                        'phone': form.cleaned_data['username']
                    }
                )
            )
Exemplo n.º 41
0
def dbpost():

    # changes these to the master
    try:
        conn = psycopg2.connect(
            database=os.environ.get("PG_DATABASE"),
            user=os.environ.get("PG_USER"),
            host=os.environ.get("PG_MASTER_RC_DC_SERVICE_HOST"),
            password=os.environ.get("PG_ROOT_PASSWORD"),
        )
    except:
        print(os.environ.get("PG_USER") + "  " + os.environ.get("PG_MASTER_RC_DC_SERVICE_HOST"))

        # Need to generate some data - no need for ID
        # NEED a name and a lat and long
    lat = random.uniform(-90, 90)
    lon = random.uniform(-180, 180)
    rw = RandomWords()
    name = rw.random_word() + " " + rw.random_word()

    sql_string = """insert into parkpoints(name, the_geom) values ('""" + name + """', ST_GeomFromText('POINT("""
    sql_string = sql_string + str(lon) + " " + str(lat) + ")', 4326));"

    cur = conn.cursor()
    # I know not this is not good form but I couldn't get it to work with the SRID stuff - probably just being lazy
    cur.execute(sql_string)

    conn.commit()

    # now let's get back our data we just put in
    cur.execute("""select parkid, name, ST_AsText(the_geom) from parkpoints ORDER by parkid DESC LIMIT 10""")

    rows = cur.fetchall()
    result_string = "<h2>Here are your results: </h2>"
    for row in rows:
        result_string += "<h3>" + str(row[0]) + ", " + str(row[1]) + ", " + str(row[2]) + "</h3>"

    cur.close()
    conn.close()
    return result_string
Exemplo n.º 42
0
  def __init__(self, name, equipment, tables, staff, start_time='2019-01-01T00:00:00', day_log = None, food_menu = None, drink_menu = None, verbose=False):
    self.env = simpy.Environment()
    self.setup_constants()
    if food_menu:
      self.food_menu = food_menu
    if drink_menu:
      self.drink_menu = drink_menu
    self.menu = []
    for f in self.food_menu:
      self.menu.append(f)
    for d in self.drink_menu:
      self.menu.append(d)
    self.ledger = Ledger(self.env, self.food_menu,self.drink_menu,verbose=verbose,save_messages=True, rdq = day_log)
    self.env.ledger = self.ledger
    self.env.day = 0 # just a counter for the number of days
    self.name = name
    

    # queue for reporting the days internally or externally (if day_log is an rdq, see flask_app for more details)
    # if day_log:
    #   self.day_log = day_log
    # else:
    #   self.day_log = queue.Queue()

    # sim mechanics note that due to dependencies, the order matters here (e.g. seating needs staff to be setup to calculate table service ratings)
    self.setup_neighborhood()
    self.setup_staffing(staff)
    equipment = self.add_aux_equipment(equipment,tables)
    self.setup_kitchen(equipment)
    self.setup_menu() #notice that here we are refactoring the menu to weed out lesser options in requirements (if we have a brick oven, wood-fired pizza should wait for it)
    self.setup_seating(tables)
    

    # tools
    self.name_generator = RandomWords()
    self.start_time = arrow.get(start_time) # this doesn't really matter unless we start considering seasons etc.
    self.monkey_patch_env()

    # stats
    self.satisfaction_scores = []
    self.restaurant_rating = 1 #score between 0 and 1
    self.checks = []
    self.generated_parties = []
    self.entered_parties = []
    self.seated_parties = []
    self.order_log = []
    self.daily_costs = []
    self.closing_order = 0
    self.env.process(self.simulation_loop())
Exemplo n.º 43
0
class QueryGenerator(object):
    '''
    Query rnadom generator to generate tuples (user_id, query_terms)
    '''
    def __init__(self, user_limit=10000):
        self._user_limit = user_limit
        self._words_generator = RandomWords()

    def __next__(self):
        return self.next()

    def next(self):
        return (randint(0, self._user_limit), ' '.join(
            self._words_generator.random_words(count=randint(1, 5))))

    def __iter__(self):
        return self
Exemplo n.º 44
0
class Command(BaseCommand):
    def __init__(self):
        super(Command, self).__init__()
        self.rw = RandomWords()
        self.li = LoremIpsum()
        self.array_size = 2

    def handle(self, *args, **options):
        tags = []
        for i in xrange(20000):
            name = self.make_name()
            tag, created = Tag.objects.get_or_create(name=name)
            if created:
                tags.append(tag)
        print '{0} tags has been created.'.format(len(tags))

        posts = []
        tags_ids = Tag.objects.all().values_list('id', flat=True)
        if self.array_size < len(tags_ids):
            for i in xrange(100000):
                name = self.make_name()
                rand = random.sample(tags_ids, self.array_size)
                post, created = Post.objects.get_or_create(
                    name=name,
                    defaults={
                        'tags': rand,
                        'description': self.li.get_sentences(5),
                    }
                )
                if created:
                    posts.append(post)
            print '{0} posts has been created.'.format(len(posts))

        else:
            print 'Please generate more tags than {0}.'.format(self.array_size)

    def make_name(self):
        name = self.rw.random_word().capitalize()
        name = '{0}{1}'.format(name, random.randint(1, 10))
        return name
Exemplo n.º 45
0
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 30 12:13:17 2016

@author: SRINIVAS
"""

from nltk.corpus import words
from random_words import RandomWords
rw = RandomWords()
a=0
while a<20:
    
    word = rw.random_word()
    i=list(word)
    i.reverse()
    i=''.join(i)
    if i in words.words():
        print(word)
        a=a+1
Exemplo n.º 46
0
 def __init__(self, *args, **kwargs):
     super(TestBankApi, self).__init__(start_server_func, get_vnc_api_client, *args, **kwargs)
     self.rw = RandomWords()
Exemplo n.º 47
0
class TestBankApi(TestCase):
    def __init__(self, *args, **kwargs):
        super(TestBankApi, self).__init__(start_server_func, get_vnc_api_client, *args, **kwargs)
        self.rw = RandomWords()

    def get_api_server(self):
        return get_api_server()

    def test_domain_crud(self):
        self.useFixture(DomainTestFixtureGen(self._vnc_lib, auto_prop_val=True))

    def test_global_system_config_crud(self):
        self.useFixture(GlobalSystemConfigTestFixtureGen(self._vnc_lib, auto_prop_val=True))

    def test_namespace_crud(self):
        parent_fix = self.useFixture(
            DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
        )
        self.useFixture(NamespaceTestFixtureGen(self._vnc_lib, auto_prop_val=True, parent_fixt=parent_fix))
        self._vnc_lib.namespaces_list()
        objects = self._vnc_lib.namespaces_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.namespaces_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.namespace_read, id="no_op")

    def test_namespace_create_fail(self):
        def _with_fixture():
            parent_fix = None
            parent_fix = self.useFixture(
                DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                NamespaceTestFixtureGen(
                    self._vnc_lib, namespace_name=self.rw.random_word(), auto_prop_val=True, parent_fixt=parent_fix
                )
            )

        flexmock(self.get_api_server()).should_receive("_post_common").replace_with(
            lambda x, y, z: (False, (501, "namespace create Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call("_post_common")
        resource_class = (
            flexmock(NamespaceServerGen)
            .should_receive("http_post_collection")
            .replace_with(lambda x, y, z: (False, (501, "Collection Error")))
        )
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called, 0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_namespace_read_fail(self):
        def _with_fixture():
            parent_fix = self.useFixture(
                DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                NamespaceTestFixtureGen(
                    self._vnc_lib, namespace_name=self.rw.random_word(), auto_prop_val=True, parent_fixt=parent_fix
                )
            )

        flexmock(self.get_api_server()).should_receive("_get_common").replace_with(
            lambda x, y: (False, (501, "account read Error"))
        )
        self.assertRaises(HttpError, _with_fixture)

    def test_access_control_list_crud(self):
        self.useFixture(AccessControlListTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.access_control_lists_list()
        objects = self._vnc_lib.access_control_lists_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.access_control_lists_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.access_control_list_read, id="no_op")

    def test_access_control_list_create_fail(self):
        def _with_fixture():
            parent_fix = None
            self.useFixture(
                AccessControlListTestFixtureGen(
                    self._vnc_lib, access_control_list_name=self.rw.random_word(), auto_prop_val=True
                )
            )

        flexmock(self.get_api_server()).should_receive("_post_common").replace_with(
            lambda x, y, z: (False, (501, "access_control_list create Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call("_post_common")
        resource_class = (
            flexmock(AccessControlListServerGen)
            .should_receive("http_post_collection")
            .replace_with(lambda x, y, z: (False, (501, "Collection Error")))
        )
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called, 0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_access_control_list_read_fail(self):
        def _with_fixture():
            self.useFixture(
                AccessControlListTestFixtureGen(
                    self._vnc_lib, access_control_list_name=self.rw.random_word(), auto_prop_val=True
                )
            )

        flexmock(self.get_api_server()).should_receive("_get_common").replace_with(
            lambda x, y: (False, (501, "account read Error"))
        )
        self.assertRaises(HttpError, _with_fixture)

    def test_account_info_crud(self):
        self.useFixture(AccountInfoTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.account_infos_list()
        objects = self._vnc_lib.account_infos_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.account_infos_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.account_info_read, id="no_op")

    def test_account_info_create_fail(self):
        def _with_fixture():
            parent_fix = None
            self.useFixture(
                AccountInfoTestFixtureGen(self._vnc_lib, account_info_name=self.rw.random_word(), auto_prop_val=True)
            )

        flexmock(self.get_api_server()).should_receive("_post_common").replace_with(
            lambda x, y, z: (False, (501, "account_info create Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call("_post_common")
        resource_class = (
            flexmock(AccountInfoServerGen)
            .should_receive("http_post_collection")
            .replace_with(lambda x, y, z: (False, (501, "Collection Error")))
        )
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called, 0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_account_info_read_fail(self):
        def _with_fixture():
            self.useFixture(
                AccountInfoTestFixtureGen(self._vnc_lib, account_info_name=self.rw.random_word(), auto_prop_val=True)
            )

        flexmock(self.get_api_server()).should_receive("_get_common").replace_with(
            lambda x, y: (False, (501, "account read Error"))
        )
        self.assertRaises(HttpError, _with_fixture)

    def test_phone_crud(self):
        parent_fix = self.useFixture(
            AccountInfoTestFixtureGen(self._vnc_lib, account_info_name=self.rw.random_word(), auto_prop_val=True)
        )
        self.useFixture(PhoneTestFixtureGen(self._vnc_lib, auto_prop_val=True, parent_fixt=parent_fix))
        self._vnc_lib.phones_list()
        objects = self._vnc_lib.phones_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.phones_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.phone_read, id="no_op")

    def test_phone_create_fail(self):
        def _with_fixture():
            parent_fix = None
            parent_fix = self.useFixture(
                AccountInfoTestFixtureGen(self._vnc_lib, account_info_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                PhoneTestFixtureGen(
                    self._vnc_lib, phone_name=self.rw.random_word(), auto_prop_val=True, parent_fixt=parent_fix
                )
            )

        flexmock(self.get_api_server()).should_receive("_post_common").replace_with(
            lambda x, y, z: (False, (501, "phone create Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call("_post_common")
        resource_class = (
            flexmock(PhoneServerGen)
            .should_receive("http_post_collection")
            .replace_with(lambda x, y, z: (False, (501, "Collection Error")))
        )
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called, 0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_phone_read_fail(self):
        def _with_fixture():
            parent_fix = self.useFixture(
                AccountInfoTestFixtureGen(self._vnc_lib, account_info_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                PhoneTestFixtureGen(
                    self._vnc_lib, phone_name=self.rw.random_word(), auto_prop_val=True, parent_fixt=parent_fix
                )
            )

        flexmock(self.get_api_server()).should_receive("_get_common").replace_with(
            lambda x, y: (False, (501, "account read Error"))
        )
        self.assertRaises(HttpError, _with_fixture)

    def test_user_crud(self):
        self.useFixture(UserTestFixtureGen(self._vnc_lib, auto_prop_val=True))
        self._vnc_lib.users_list()
        objects = self._vnc_lib.users_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.users_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.user_read, id="no_op")

    def test_user_create_fail(self):
        def _with_fixture():
            parent_fix = None
            self.useFixture(UserTestFixtureGen(self._vnc_lib, user_name=self.rw.random_word(), auto_prop_val=True))

        flexmock(self.get_api_server()).should_receive("_post_common").replace_with(
            lambda x, y, z: (False, (501, "user create Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call("_post_common")
        resource_class = (
            flexmock(UserServerGen)
            .should_receive("http_post_collection")
            .replace_with(lambda x, y, z: (False, (501, "Collection Error")))
        )
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called, 0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_user_read_fail(self):
        def _with_fixture():
            self.useFixture(UserTestFixtureGen(self._vnc_lib, user_name=self.rw.random_word(), auto_prop_val=True))

        flexmock(self.get_api_server()).should_receive("_get_common").replace_with(
            lambda x, y: (False, (501, "account read Error"))
        )
        self.assertRaises(HttpError, _with_fixture)

    def test_api_access_list_crud(self):
        parent_fix = self.useFixture(
            DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
        )
        self.useFixture(ApiAccessListTestFixtureGen(self._vnc_lib, auto_prop_val=True, parent_fixt=parent_fix))
        self._vnc_lib.api_access_lists_list()
        objects = self._vnc_lib.api_access_lists_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.api_access_lists_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.api_access_list_read, id="no_op")

    def test_api_access_list_create_fail(self):
        def _with_fixture():
            parent_fix = None
            parent_fix = self.useFixture(
                DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                ApiAccessListTestFixtureGen(
                    self._vnc_lib,
                    api_access_list_name=self.rw.random_word(),
                    auto_prop_val=True,
                    parent_fixt=parent_fix,
                )
            )

        flexmock(self.get_api_server()).should_receive("_post_common").replace_with(
            lambda x, y, z: (False, (501, "api_access_list create Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call("_post_common")
        resource_class = (
            flexmock(ApiAccessListServerGen)
            .should_receive("http_post_collection")
            .replace_with(lambda x, y, z: (False, (501, "Collection Error")))
        )
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called, 0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_api_access_list_read_fail(self):
        def _with_fixture():
            parent_fix = self.useFixture(
                DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                ApiAccessListTestFixtureGen(
                    self._vnc_lib,
                    api_access_list_name=self.rw.random_word(),
                    auto_prop_val=True,
                    parent_fixt=parent_fix,
                )
            )

        flexmock(self.get_api_server()).should_receive("_get_common").replace_with(
            lambda x, y: (False, (501, "account read Error"))
        )
        self.assertRaises(HttpError, _with_fixture)

    def test_project_crud(self):
        parent_fix = self.useFixture(
            DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
        )
        self.useFixture(ProjectTestFixtureGen(self._vnc_lib, auto_prop_val=True, parent_fixt=parent_fix))
        self._vnc_lib.projects_list()
        objects = self._vnc_lib.projects_list(detail=True)
        if objects:
            uuids = [obj.uuid for obj in objects]
            self._vnc_lib.projects_list(obj_uuids=uuids)
            self.assertTrue(objects)
        self.assertRaises(NoIdError, self._vnc_lib.project_read, id="no_op")

    def test_project_create_fail(self):
        def _with_fixture():
            parent_fix = None
            parent_fix = self.useFixture(
                DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                ProjectTestFixtureGen(
                    self._vnc_lib, project_name=self.rw.random_word(), auto_prop_val=True, parent_fixt=parent_fix
                )
            )

        flexmock(self.get_api_server()).should_receive("_post_common").replace_with(
            lambda x, y, z: (False, (501, "project create Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
        flexmock(self.get_api_server()).should_call("_post_common")
        resource_class = (
            flexmock(ProjectServerGen)
            .should_receive("http_post_collection")
            .replace_with(lambda x, y, z: (False, (501, "Collection Error")))
        )
        try:
            _with_fixture()
            self.assertEquals(resource_class.times_called, 0)
        except Exception as e:
            self.assertEqual(HttpError, type(e))

    def test_project_read_fail(self):
        def _with_fixture():
            parent_fix = self.useFixture(
                DomainTestFixtureGen(self._vnc_lib, domain_name=self.rw.random_word(), auto_prop_val=True)
            )
            self.useFixture(
                ProjectTestFixtureGen(
                    self._vnc_lib, project_name=self.rw.random_word(), auto_prop_val=True, parent_fixt=parent_fix
                )
            )

        flexmock(self.get_api_server()).should_receive("_get_common").replace_with(
            lambda x, y: (False, (501, "account read Error"))
        )
        self.assertRaises(HttpError, _with_fixture)
Exemplo n.º 48
0
 def random_words(self):
     rw =  RandomWords()
     w1 = rw.random_word()
     w2 = rw.random_word()
     w3 = rw.random_word()
     return w1 + "-" + w2 + "-" + w3
Exemplo n.º 49
0
 def __init__(self):
     super(Command, self).__init__()
     self.rw = RandomWords()
     self.li = LoremIpsum()
     self.array_size = 2
Exemplo n.º 50
0
import os
from random import choice, randint
from random_words import RandomWords

rw = RandomWords()

words = rw.random_words(count=10)

def makefile(name, ext='.txt', size=None):
    fullname = os.path.join('fs', name + ext)
    if not size:
        size = randint(5,10000)
    with open(fullname, 'w') as f:
        f.write('x' * size)

for word in words + ['secrets']:
    makefile(word)

os.makedirs(os.path.join(fs, 'secretsfolder'))
Exemplo n.º 51
0
class Restaurant:
  '''
    equipment is a list of Appliances
    tables is a list of Tables

  '''
  waiting_list_max = 20
  drink_menu = [
    {
      "name": "Beer",
      "price": 6.0,
      "requirements": ["alcohol"],
      "type": "alcohol",
      "cook_time": 2,
      "difficulty": 0,
      "cost": 1.0
    },
    {
      "name": "Vodka",
      "price": 8.0,
      "requirements": ["alcohol"],
      "type": "alcohol",      
      "cook_time": 2,
      "difficulty": 0,
      "cost": 2.5
    }
  ]
  food_menu = [
    {
        "name": "Pizza Slice",
        "price": 2.0,
        "requirements": ["pizza","oven","microwave"],
        "type": "pizza",
        "cook_time": 5, #in minutes
        "difficulty": 0.1,
        "cost": 1.0
    },
    {
        "name": "Personal Pan Pizza",
        "price": 10.0,
        "requirements": ["pizza","oven","microwave"],
        "type": "pizza",
        "difficulty": 0.5,
        "cook_time": 10,
        "cost": 7.0
    },
    {
        "name": "Wood-Fired Pizza",
        "price": 60.0,
        "requirements": ["brick_oven","pizza","oven"],
        "type": "pizza",
        "cook_time":15,
        "difficulty": 0.9,
        "cost": 30
    },
    {
        "name": "Sushi",
        "price": 15.0,
        "requirements": ["sushi"],
        "type": "sushi",
        "cook_time":15,
        "difficulty": 0.9,
        "cost": 8
    }
  ]
  def __init__(self, name, equipment, tables, staff, start_time='2019-01-01T00:00:00', day_log = None, food_menu = None, drink_menu = None, verbose=False):
    self.env = simpy.Environment()
    self.setup_constants()
    if food_menu:
      self.food_menu = food_menu
    if drink_menu:
      self.drink_menu = drink_menu
    self.menu = []
    for f in self.food_menu:
      self.menu.append(f)
    for d in self.drink_menu:
      self.menu.append(d)
    self.ledger = Ledger(self.env, self.food_menu,self.drink_menu,verbose=verbose,save_messages=True, rdq = day_log)
    self.env.ledger = self.ledger
    self.env.day = 0 # just a counter for the number of days
    self.name = name
    

    # queue for reporting the days internally or externally (if day_log is an rdq, see flask_app for more details)
    # if day_log:
    #   self.day_log = day_log
    # else:
    #   self.day_log = queue.Queue()

    # sim mechanics note that due to dependencies, the order matters here (e.g. seating needs staff to be setup to calculate table service ratings)
    self.setup_neighborhood()
    self.setup_staffing(staff)
    equipment = self.add_aux_equipment(equipment,tables)
    self.setup_kitchen(equipment)
    self.setup_menu() #notice that here we are refactoring the menu to weed out lesser options in requirements (if we have a brick oven, wood-fired pizza should wait for it)
    self.setup_seating(tables)
    

    # tools
    self.name_generator = RandomWords()
    self.start_time = arrow.get(start_time) # this doesn't really matter unless we start considering seasons etc.
    self.monkey_patch_env()

    # stats
    self.satisfaction_scores = []
    self.restaurant_rating = 1 #score between 0 and 1
    self.checks = []
    self.generated_parties = []
    self.entered_parties = []
    self.seated_parties = []
    self.order_log = []
    self.daily_costs = []
    self.closing_order = 0
    self.env.process(self.simulation_loop())

  def setup_constants(self):
    self.env.max_budget = 100
    self.env.max_wait_time = 60
    self.env.max_noise_db = 50
    self.env.rent = 200
    self.env.worker_wage = 150
    self.env.sim_loop_delay = 10*60 # in minutes

  def setup_staffing(self,staff):
    self.env.ledger.staff = [Staff(s['x'],s['y']) for s in staff]

  def add_aux_equipment(self,equipment,tables):
    for t in tables:
      if "appliances" in t["attributes"]:
        appliances = t["attributes"]["appliances"]
        for a in appliances:
          a["attributes"]["x"] = t["attributes"]["x"]
          a["attributes"]["y"] = t["attributes"]["y"]
          equipment.append(a)
    return equipment

  def setup_kitchen(self, equipment):
    self.kitchen = simpy.FilterStore(self.env, capacity=len(equipment))
    self.kitchen.items = [Appliance(self.env,e["name"],e["attributes"]) for e in equipment]
    self.food_menu = [m for m in self.food_menu if any(any(req in appliance.capabilities for req in m["requirements"]) for appliance in self.kitchen.items)]
    self.drink_menu = [d for d in self.drink_menu if any(any(req in appliance.capabilities for req in d["requirements"]) for appliance in self.kitchen.items)]
    self.env.ledger.print("Menu: {}".format(self.food_menu))
    self.env.ledger.set_appliances( [a for a in self.kitchen.items] )

  def setup_seating(self, tables):
    self.seating = simpy.FilterStore(self.env, capacity=len(tables))
    self.seating.items = [Table(self.env,t["name"],t["attributes"]) for t in tables]
    self.max_table_size = max([t.seats for t in self.seating.items])
    self.env.ledger.capacity = np.sum([t.seats for t in self.seating.items])
    self.env.ledger.set_tables( [t for t in self.seating.items] )
    for t in self.env.ledger.tables:
      t.start_simulation()
    self.env.ledger.service_rating = np.mean([t.service_rating for t in self.env.ledger.tables])

  def setup_menu(self):
    all_capabilities = []
    for appliance in self.env.ledger.appliances:
      for c in appliance.capabilities:
        all_capabilities.append(c)
    all_capabilities = list(set(all_capabilities))
    for meal in self.food_menu:
      new_reqs = []
      for r in meal["requirements"]:
        new_reqs.append(r)
        if r in all_capabilities:
          meal["requirements"] = new_reqs
          break
    for drink in self.drink_menu:
      new_reqs = []
      for r in drink["requirements"]:
        new_reqs.append(r)
        if r in all_capabilities:
          drink["requirements"] = new_reqs
          break
    for item in self.menu:
      new_reqs = []
      for r in item["requirements"]:
        new_reqs.append(r)
        if r in all_capabilities:
          item["requirements"] = new_reqs
          break
    self.env.ledger.menu = self.menu
    self.env.ledger.food_menu = self.food_menu
    self.env.ledger.drink_menu = self.drink_menu
    #print("\n\nFFFFFFOOOOOODDD",self.food_menu)




  def setup_neighborhood(self):
    self.max_party_size = 10
    self.neighborhood_size = 10000
    self.max_eating_pop = 0.1*self.neighborhood_size
    self.demographics = ["size","affluence","taste","noisiness","leisureliness","patience","noise_tolerance","space_tolerance", "mood","sensitivity", "appetite", "drink_frequency"] #sensitivity has to do with how much you care about service
    self.demographic_means = np.array([0.25,0.3,0.5,0.6,0.6,0.5,0.3,0.5, 0.5, 0.6,0.5, 0.5])
                                        # size aff taste  noi   leis  pat noi_t space_t
    # self.demographic_cov = np.matrix([[ 0.02, 0.00, 0.00, 0.09, 0.02,-0.02, 0.06,-0.02], #size
    #                                   [ 0.00, 0.02, 0.10,-0.02, 0.06,-0.07,-0.07,-0.07], #affluence
    #                                   [ 0.00, 0.10, 0.02,-0.02, 0.07,-0.01,-0.01, 0.0], #taste
    #                                   [ 0.09,-0.02,-0.02, 0.02, 0.01, 0.00, 0.08, 0.03], #noisiness
    #                             self.start_time.replace(seconds=self.env.now)      [ 0.02, 0.06, 0.07, 0.01, 0.02, 0.07,-0.06,-0.06], #leisureliness
    #                             self.start_time.replace(seconds=self.env.now)      [-0.02,-0.07,-0.01, 0.00, 0.07, 0.02, 0.07, 0.06], #patience
    #                             self.start_time.replace(seconds=self.env.now)      [ 0.06,-0.07,-0.01, 0.08,-0.06, 0.07, 0.02, 0.09], #noise tolerance
    #                             self.start_time.replace(seconds=self.env.now)      [-0.02,-0.07, 0.00, 0.03,-0.06, 0.06, 0.09, 0.02] #space toleranceseating.put(self.table)
    #                                  ])  
    self.demographic_cov = np.matrix([[ 0.05,  0.0,   0.0,   0.018, 0.004,-0.004, 0.012,-0.004, 0.00, -0.001, 0.000, 0.000],
                                      [ 0.0,   0.05,  0.03, -0.004, 0.012,-0.014,-0.014,-0.014, 0.00, 0.02, 0.000, 0.000],
                                      [ 0.0,   0.03,  0.05, -0.004, 0.014,-0.002,-0.002, 0.0, 0.00,  0.01, 0.000, 0.000],
                                      [ 0.018,-0.004,-0.004, 0.05,  0.002, 0.0,   0.016, 0.006, 0.00, 0.00, 0.000, 0.01],
                                      [ 0.004, 0.012, 0.014, 0.002, 0.05,  0.014,-0.012,-0.012, 0.00, 0.01, 0.000, 0.000],
                                      [-0.004,-0.014,-0.002, 0.0,   0.014, 0.05,  0.014, 0.012, 0.00, -0.02, 0.000, 0.000],
                                      [ 0.012,-0.014,-0.002, 0.016,-0.012, 0.014, 0.05,  0.018, 0.00, -0.015, 0.000, 0.000],
                                      [-0.004,-0.014, 0.0,   0.006,-0.012, 0.012, 0.018, 0.05, 0.00, -0.010, 0.000, 0.000],
                                      [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.05, -0.01, 0.000, 0.000],
                                      [-0.001, 0.02, 0.01, 0.000, 0.01, -0.02, -0.015, -0.01, -0.01, 0.05, 0.000, 0.000],
                                      [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.05, 0.000],
                                      [0.000, 0.000, 0.000, 0.01, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.05]
                                      ])
    # TODO: write an assertion that this is positive semi-definite

  def current_time(self):
    # let's assume the time step is seconds
    return self.start_time.replace(seconds=self.env.now)
  
  def monkey_patch_env(self):
    self.env.m_start_time = self.start_time
    self.env.m_current_time = self.current_time
    self.env.m_rw = self.rw
  
  def rw(self):
    return self.name_generator.random_word()
  
  def handle_party(self, party):
    if len(self.drink_menu) > 0:
      self.env.process(party.start_ordering_drinks(self.kitchen,self.drink_menu))
    seated = yield self.env.process(party.wait_for_table(self.seating))
    if seated == False:
      check,satisfaction = yield self.env.process(party.leave(self.seating))
    else:
      self.seated_parties.append(party)
      noise_process = self.env.process(party.update_satisfaction(self.env.ledger.tables))  
      # order = Order(self.env,self.rw(),party,party.table)
      # yield self.env.process(order.place_order(self.kitchen,self.food_menu))
      if len(self.food_menu) > 0:
        # if there is a kitchen, then order food
        yield self.env.process(party.place_order(self.kitchen,self.food_menu))
        # self.order_log.append(order)  
        yield self.env.process(party.eat())
      # if there is no kitcehn, but there is a bar, sit for awhile (while ordering drinks)
      # or if there is no anything, just sit here awkwardly for a bit I suppose
      else:
        yield self.env.process(party.chill())
      check,satisfaction = yield self.env.process(party.leave(self.seating))
    self.checks.append(check)
    self.satisfaction_scores.append(satisfaction)
  
  
  def get_customer_rate(self):
    hourly_rates = [
        [0,0,0,0,0,0,0.1,0.2,0.5,0.9,0.7,0.5,1,1,0.6,0.2,0.2,0.6,0.8,0.8,0.7,0.3,0.1,0.1,0], #m
        [0,0,0,0,0,0,0.1,0.2,0.5,0.9,0.7,0.5,1,1,0.6,0.2,0.2,0.6,0.9,0.9,0.8,0.3,0.1,0.1,0], #t
        [0,0,0,0,0,0,0.1,0.2,0.5,0.9,0.7,0.5,1,1,0.6,0.2,0.2,0.6,0.9,0.9,0.8,0.3,0.1,0.1,0], #wseating.put(self.table)
        [0,0,0,0,0,0,0.1,0.2,0.5,0.9,0.7,0.5,1,1,0.6,0.2,0.2,0.6,0.9,0.9,0.8,0.3,0.1,0.1,0], #r
        [0,0,0,0,0,0,0.1,0.2,0.5,1,0.7,0.5,1,1,0.6,0.2,0.2,0.6,1,1,0.8,0.8,0.8,0.1,0], #f
        [0,0,0,0,0,0,0.1,0.2,0.5,1,0.7,0.5,1,1,0.6,0.2,0.2,0.6,1,1,0.8,0.8,0.8,0.1,0], #sa
        [0,0,0,0,0,0,0.1,0.5,0.8,1,1,1,1,1,0.6,0.2,0.2,0.6,0.8,0.8,0.6,0.3,0.1,0.1,0]  #su    
    ]
    cur_time = self.env.m_current_time().timetuple()
    raw_rate = hourly_rates[cur_time.tm_wday][cur_time.tm_hour]
    rate = self.max_eating_pop*raw_rate
    return rate# number of groups /hr
  
  def sample_num_parties(self):
    '''
      Sample the number of parties that are looking to eat in the town at that hour
    '''
    num_parties = np.random.poisson(self.get_customer_rate())
    return num_parties
        
  def generate_parties(self,n=1):
    '''
      Randomly generate a party
    '''
    self.env.ledger.print("Time is: {} from {}".format(self.current_time().format("HH:mm:ss"),self.env.now))
    entered_parties = []
    num_entered = 0
    parties = np.clip(np.random.multivariate_normal(self.demographic_means,self.demographic_cov,n),0.01,1)
    num_generated = len(parties)
    for party in parties:
      self.generated_parties.append(party)
      party_attributes = {k:v for (k,v) in zip(self.demographics,party)}
      party_attributes["size"] = int(np.ceil(party_attributes["size"]*self.max_party_size))
      if(self.decide_entry(party_attributes)):
        num_entered += 1
        p = Party(self.env,self.rw().capitalize(),party_attributes)
        self.env.ledger.parties.append(p)
        entered_parties.append(p)
      else:
        continue
    self.env.ledger.print("Total groups generated: {}, total entered: {}".format(num_generated, num_entered))   
    return entered_parties
  
  def decide_entry(self,party_attributes):
    if(party_attributes["size"] > self.max_table_size):
      return False
    # if the people are unhappy and the restaurant is bad, don't enter
    if party_attributes["mood"] < 1-self.env.ledger.satisfaction:
      if np.random.uniform(0,1) > self.env.ledger.satisfaction/5: #basically if the satisfaction is high, with some small prob they enter anyway 
        return False
    # if the service is bad and the people care about service, don't enter
    if party_attributes["sensitivity"] > self.env.ledger.service_rating:
      if np.random.uniform(0,1) > self.env.ledger.service_rating: #if the service is good, still enter with some probability
        return False
    if party_attributes["affluence"] < 0.3:
      if party_attributes["taste"] > self.env.ledger.yelp_rating:
        return False
    if party_attributes["affluence"] >= 0.3 and party_attributes["affluence"] <= 0.7:
      if party_attributes["taste"] > self.env.ledger.zagat_rating:
        return False
    if party_attributes["affluence"] > 0.7:
      if party_attributes["taste"] > self.env.ledger.michelin_rating:
        return False
    if np.random.uniform(0,1) > 0.05:
      # TODO: replace this with tuning the poisson entry rate
      return False
    else:
       return True
    
  def simulation_loop(self):
    day_of_week = ""
    daily_customers = 0
    party_index = 0
    while True:
      yield self.env.timeout(60*60) #every hour
      today = self.env.m_current_time().format("dddd")
      if today != day_of_week:
        day_of_week = today
        self.env.day += 1
        self.ledger.record_current_day()
        self.calc_stats()
        #costs = self.run_expenses()time_waited = 0
        #self.env.process(self.calc_stats())
        #self.summarize(costs,daily_customers,self.entered_parties[party_index:party_index+daily_customers])
        daily_customers = 0
        party_index += daily_customers
        #self.restaurant_rating = min(0,2)
        #self.restaurant_rating = np.mean(self.satisfaction_scores)
        #day = self.env.m_current_time().format("ddd MMM D")
        #print("Summary for {}: satisfaction: {}".format(day,self.restaurant_rating))
      # generate 0+ parties based on the time of day & popularity of the restaurant
      entering_parties =  self.generate_parties(self.sample_num_parties())
      daily_customers += len(entering_parties) 
      for p in entering_parties:    
        self.env.process(self.handle_party(p))
        
  def simulate(self,seconds=None,days=None):
    if seconds:
      max_seconds = seconds
    elif days:
      max_seconds = days*24*60*60
    else:
      max_seconds = 100
    self.env.run(until=max_seconds)
    
  def run_expenses(self):
    daily_cost = 0
    for a in self.env.ledger.appliances:
      daily_cost += a.daily_upkeep
    for t in self.env.ledger.tables:
      daily_cost += t.daily_upkeep
    for o in self.order_log[self.closing_order:]:
      daily_cost += o.total_cost
      self.closing_order = len(self.order_log)
    self.daily_costs.append(daily_cost)
    return daily_cost
    
  def calc_stats(self):
    if len(self.satisfaction_scores) > 0:
      self.restaurant_rating = np.mean(self.satisfaction_scores)

 
  def summarize(self,costs,volume,parties):
    day = self.env.m_current_time().format("ddd MMM D")
    customers = np.sum([p.size for p in parties])
    if customers > 0:
      noise = np.sum([p.size*p.noisiness for p in parties])/customers
      total_bills = np.sum([p.paid_check for p in parties])
      satisfaction = np.mean([p.satisfaction for p in parties if not np.isnan(p.satisfaction)])
      self.env.ledger.print("Summary for {}: satisfaction: {}".format(day,self.restaurant_rating))
    else:
      noise = 0
      total_bills = 0
      satisfaction = 0
    self.day_log.put({"day": self.env.day,"expenses":costs,"rating":self.restaurant_rating,"num_entered":volume, "noise": noise, "revenue":total_bills, "satisfaction": satisfaction})


  def final_report(self):
    stringbuilder = ""
    stringbuilder += "*"*80+"\n"
    stringbuilder += "Simulation run for {} days.\n".format(self.ledger.num_days)
    stringbuilder += "*"*80+"\n"
    stringbuilder += "Parties entered: {}\nParties seated: {}\nParties paid: {}\n".format(len(self.entered_parties),len(self.seated_parties),len([c for c in self.checks if c > 0]))
    revenue = np.sum(self.checks)
    stringbuilder += "Total Revenue: ${:.2f}\n".format(revenue)
    upfront_costs = np.sum([a.cost for a in self.env.ledger.appliances]) + np.sum([t.cost for t in self.env.ledger.tables])
    stringbuilder += "Total Upfront Costs: ${:.2f}\n".format(upfront_costs)
    costs = np.sum(self.daily_costs)
    stringbuilder += "Total Daily Costs: ${:.2f}\n".format(costs)
    stringbuilder += "Total Profit: ${:.2f}\n".format(revenue-costs-upfront_costs)
    # leftovers = len(self.entered_parties)-len(self.checks) #if we cut off the last day while people were dining
    # if leftovers > 0:
    #   truncated_entered_parties = self.entered_parties[:-leftovers]
    # else:
    #   truncated_entered_parties = self.entered_parties
    num_served = np.sum([p.size for i,p in enumerate(truncated_entered_parties) if p.paid_check>0])
    stringbuilder += "Total individual customers served: {}\nAverage price per entree: ${:.2f}\n".format(num_served,revenue/num_served)
    stringbuilder += "Avg Satisfaction Score: {:.2f}\nStd Satisfaction Score: {:.2f}\n".format(np.mean(self.satisfaction_scores), np.std(self.satisfaction_scores))
    stringbuilder += "Final Restaurant Rating: {:.2f}\n".format(self.restaurant_rating)
    #print(stringbuilder)
    return stringbuilder
def randWord2():
	rw = RandomWords()
	word1 = rw.random_word()
	word2 = rw.random_word()
	word = word1+" "+word2
	return word
def randWord():
	rw = RandomWords()
	word = rw.random_word()
	return word
Exemplo n.º 54
0
import sbpy_utils.core.sets
import sbpy_utils.core.string_manipulation as stringman
from sbpy_utils.core.string_manipulation import concat_string_list,filter_empty_strings
from sbpy_utils.temporal.preprocessing import pad_sequences_tensor,depad_sequences_tensor,split_sequence_tensor,pad_sequence_list
from sbpy_utils.core.key_val import *
from sbpy_utils.core.command_line import my_system
import sbpy_utils.core.my_io
from sbpy_utils.core.chaining import *
from sbpy_utils.image.my_io import imread_safe
from sbpy_utils.core.list_tools import list_split
from random_words import RandomWords


get_copier=lambda tmp:{True:lambda tmp2:copy.deepcopy(tmp2),False:lambda tmp2:tmp2}[tmp]
rw=RandomWords()
get_random_name=lambda:'_'.join([rwstr.title() for rwstr in rw.random_words(count=3)])


class ImgCollection(object):
    def pixels(self):
        return [tmp.pixels() for tmp in self.data]
    
    def print_myname(self,leading_whitespace='',max_depth=10,curr_depth=0):
        print(leading_whitespace+self.myname)
        if(curr_depth<=max_depth):
            for f in self.data:
                f.print_myname(leading_whitespace=leading_whitespace+'  ',
                               max_depth=max_depth,
                               curr_depth=curr_depth+1)
Exemplo n.º 55
0
from __future__ import division
from time import time

s = set()
s.add(1)
s.add(2)
s.add(2)
x = len(s)
print(2 in s)
print(3 in s)

from random_words import RandomWords
rw = RandomWords()
word = rw.random_word()
print(word)

word = rw.random_word('y')
print(word)

words = rw.random_words(count=10)
print(words)

words = rw.random_words(letter='r', count=5)
print(words)

words = rw.random_words(letter=None, count=2)
print(words)

hundreds_of_other_words = []

stopwords_list = ["a", "an", "at"] + hundreds_of_other_words + ["yet", "you"]
Exemplo n.º 56
0
def generate_word():
    # TODO: generate random word
    rw = RandomWords()
    word = rw.random_word()
    return word
Exemplo n.º 57
0
#
#created by flipchan to make it harder for people to 
#perform "timing attacks" where they try to timestamp the data to
#help deanonymize, traffic obfusication and simular systems, originally written
#for the layerprox project but feel free to hack it in anyway you want

import urllib2, httplib
import datetime, time
from random import randint #not great but this is only a beta version, i could mix it with the day gen in otw
from random_words import RandomWords #https://pypi.python.org/pypi/RandomWords/0.1.5
from otw import genday
rw = RandomWords()
#put it in a loop n run with sysd or something simular



def genip():
	f = randint(1,254)
	i = randint(1,254)
	r = randint(1,254)
	s = randint(1,254)
	t = str(f + '.' + i + '.' + r + '.'  + s)
	ip = int(t)
	return ip

while 1:
	host = genip()
	conn = httplib.HTTPConnection(host)
	where = str(rw.random_word() + '.html')#make it look legit with a "random" word
	conn.request("HEAD","/index.html")
	time.sleep(100)# make this a randomly-generated int
Exemplo n.º 58
0
from shell import shell
import uuid
import sys
import webbrowser
from random_words import RandomWords
rw = RandomWords()




route_map = {
    "scaler": "vascodagama-emcworld-scaler",
    "images": "vascodagama-emcworld-prod"
}


domain = "cfapps.io"
base_route = None
base_request = None


if len(sys.argv) < 2:
    print("Not enough arguments - only got {}".format(len(sys.argv)))
    sys.exit(1)

if str(sys.argv[1]).lower() not in route_map.keys():
    print("Failed to specify a known route to modify.  Got '{}', needed: {}".format(sys.argv[1],route_map.keys()))
    sys.exit(1)
else:
    base_route = route_map[str(sys.argv[1]).lower()]
    base_request = str(sys.argv[1]).lower()
Exemplo n.º 59
0
 def __init__(self, user_limit=10000):
     self._user_limit = user_limit
     self._words_generator = RandomWords()
Exemplo n.º 60
0
from random_words import RandomWords
import sys
rw = RandomWords()
entrada = "entradas/"+sys.argv[1]
file = open(entrada, "w")
print "Gerando arquivo ",sys.argv[1]
print "Linhas "+sys.argv[2]
print "Palavras "+sys.argv[3]
for i in range(int(sys.argv[2])):
    words = rw.random_words(letter='r', count=int(sys.argv[3]))

    for i in range(len(words)):
       file.write(words[i],)

    file.write("\n")
file.close()