Esempio n. 1
0
def result():
    text = request.form["gen_text"]
    style = request.form.get('style', 404)
    bias = request.form.get('bias', 1.0)
    print("The text from user is: " + text)
    print("Generating..")
    gen(text, style, bias)
    return """
Esempio n. 2
0
def main(generate, push, clean, image):
    """Set up logging and trigger build."""
    log.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(message)s')
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    log.addHandler(ch)

    if generate:
        gen(log)

    build(image, push, clean)
Esempio n. 3
0
def test():  #Test de gemiddelde snelheid
    pogingen = 1  # Verander deze om de gemiddelde snelheid te berekenen voor een bepaald aantal keer
    keer = 0
    totaal = 0
    maxi = []
    lst = gen()
    while keer != pogingen:
        ans, tijd = algoritme_uitvoering([]) #random.choice(lst)
        maxi.append(tijd)
        keer += 1
        totaal += tijd
        print(keer)
    print('gem',totaal/keer)
    print('max:', max(maxi))



#test()
#lst = gen()
#algoritme_uitvoering([3,2,3,4])




    oplossing = 0

    return oplossing, tijd
Esempio n. 4
0
def main():
    print("\nWelcome to Connor's ASCII sheet music generator!")
    print("------------------------------------------------")
    print("Choose a clef: (1) Treble")
    print("               (2) Bass  ")
    choice = input("> ")
    if (choice == "1"):
        clef = "treble"
        print("You chose: Treble Clef!")
    elif (choice == "2"):
        clef = "bass"
        print("You chose: Bass Clef!")
    master = c.setClef(clef)
    print(master)
    print("Enter a key: (i.e. 'Bb', 'C#', 'A')")
    choice = input("> ")
    key = choice
    master = k.setKey(choice, clef, master)  #sets key, adds key signature
    print(master)
    print("Enter a time signature: (i.e. '4/4', '3/4', '2/4')")
    choice = input("> ")
    time = choice
    master = ts.setTime(choice, master)
    print(master)
    print("Enter the amount of measures you want to generate")
    measures = int(input("> "))
    choice = input("Press ENTER to generate music!")

    master = generate.gen(clef, key, time, master,
                          measures)  # music is generated here

    print(master)  #prints final sheet music
Esempio n. 5
0
    def handle(self):

        # self.request.settimeout(1)

        data_transferred = 0
        print('[%s] 연결됨' % self.client_address[0])
        sock = self.request

        filename = self.request.recv(1024)  # 클라이언트로 부터 파일이름을 전달받음
        filename = filename.decode()
        print(filename)
        # if exists(filename): # 파일이 해당 디렉터리에 존재하면
        #     self.request.send("1010")
        #     return # handle()함수를 빠져 나온다.
        # print(1)
        data = self.request.recv(1024)  # 클라이언트로 부터 이미지를 전달받음
        if not data:
            print('파일[%s]: 서버에 존재하지 않거나 전송중 오류발생' % filename)
            return

        with open(path + '/upload/' + filename, 'wb') as f:
            try:
                while data:
                    f.write(data)
                    data_transferred += len(data)
                    data = sock.recv(1024)

            except Exception as e:
                print(e)
        print('파일[%s] 전송종료. 전송량 [%d]' % (filename, data_transferred))

        gen.gen(filename)  # gen

        print('파일[%s] 전송 시작...' % filename)
        with open(filename, 'rb') as f:
            try:
                data = f.read(1024)  # 파일을 1024바이트 읽음
                while data:  # 파일이 빈 문자열일때까지 반복
                    data_transferred += self.request.send(data)
                    data = f.read(1024)
            except Exception as e:
                print(e)

        print('전송완료[%s], 전송량[%d]' % (filename, data_transferred))
Esempio n. 6
0
File: main.py Progetto: cxcd/CPS803
def gen(input, size=100):
    print("Generated data: ")
    model = util.new_load_model()
    data = np.array(list(input))
    data = torch.from_numpy(data).long()
    index_arr = generate.gen(model, data, size)
    event_arr = dataprocess.indices_to_events(index_arr)
    midi_arr = dataprocess.event_to_midi_array(event_arr)
    util.save_on_gen(input, midi_arr, model_num=None, gen_num=None)
    print(event_arr)
Esempio n. 7
0
def main():
    number_of_points = 100
    random_matrix = generate.gen(2, number_of_points)

    clusters_count = 5

    while clusters_count <= int(number_of_points / 10):
        c = run(random_matrix, clusters_count)
        print_clusters(c)
        plot_2d(c, True)
        clusters_count += 5
def confirm(seed, subreddits = None):
    comment = generate.gen(seed, subreddits)
    print comment
    yn = raw_input("Wanna post this shit? Y/N: ")
    if yn.lower() == "y":
        respond(sys.argv[1], comment)
    else:
        new_seed = raw_input("New seed? (blank=same) ")
        if len(new_seed.split()) == 2:
            confirm(new_seed)
        else:
            confirm(seed)
Esempio n. 9
0
    def result():
        text = request.form["gen_text"]
        style = request.form.get('style', 404)
        bias = request.form.get('bias', 1.0)
        print("The text from user is: " + text)
        print("Generating..")
        gen(text, style, bias)
        print("Genrated and the File is saved")
        email = request.form['email']
        confirm_serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])

        token = confirm_serializer.dumps(email, salt='email-confirmation-salt')
        confirm_url = 'http://localhost:5000/result_page?token=%s' % (token)
        html = render_template('confirmation_result_template.html',
                               confirm_url=confirm_url)
        subject = 'Your Handwriting is Selected for generation'
        send_mail(email, subject, html)
        otp = random.randint(1000, 9000)
        msg = twilioClient.messages.create(body="Your OTP is - " + str(otp),
                                           from_='+12568500359',
                                           to='+917904385351')
        return render_template('otp.html', otp=otp)
Esempio n. 10
0
    def storeLoaded(self, j):
        try:
            loaded = cb.get(self.modname).value
            # replace if element exists
            for l in loaded['cards']:
                if l[0][1] == j[0][1]:
                    loaded['cards'].remove(l)
                    break
            loaded['cards'].append(j)
            cb.upsert(selfmodname, loaded)
        except:
            cb.upsert(selfmodname, {"cards": [j]})

        loaded = cb.get(self.modname).value

        names = []
        for l in loaded['cards']:
            names.append([l[0][1], l[1][1]])

        gen(j);

        return json.dumps(names)
Esempio n. 11
0
def test(eerst):  #Test de gemiddelde snelheid
    pogingen = 1 # Verander deze om de gemiddelde snelheid te berekenen voor een bepaald aantal keer
    keer = 0
    totaal = 0
    maxi = []
    lst = gen()
    while keer != pogingen:
        ans, tijd = heuristiek(eerst,lst) #random.choice(lst)
        maxi.append(tijd)
        keer += 1
        totaal += tijd
    print()
    print('gem:',totaal/keer)
    print('max:', max(maxi))
Esempio n. 12
0
    def replace_rapnouns(self):
        '''
        Get topic words and replace nouns in songs with topics
        '''
        topic_words = gen()
        topic_words.load_topics()
        words = topic_words.topic_words

        mydict = {'NN': words}

        rep = self.c.replace_lyrics(self.artist, mydict)

        for title, sections in self.c.replaced_songs.items():
            for sec_name, lines in sections.items():
                os.system('clear')
                print('\n')
                print("---------------------------%s-%s-%s--------------------------" % (self.artist, title, sec_name))
                print('\n')
                for sec in lines:
                    print('\n'.join([x for x in sec if x != '']))
                _inp = input()
                if _inp == 'q':
                    return
Esempio n. 13
0
        print(combis)
        print(aanroep_best(combis))




def backk(gok, antwoord,tijd):
    back = feedback(gok, antwoord)
    print("{}e feedback:".format(tijd), back, gok)
    return(back)

#kleur([1,2,3,4])



lst = gen()
algoritme(random.choice(lst))




"""oplossing = combi_lijst[0]
    print('Aantal zetten', tijd, '---', 'Antwoord =', combi_lijst[0],'\n')
    return oplossing, tijd"""





def test():  #Test de gemiddelde snelheid
    pogingen = 1  # Verander deze om de gemiddelde snelheid te berekenen voor een bepaald aantal keer
Esempio n. 14
0
# TianTcl - Whisper game - main

import generate, tkinter
from tkinter import messagebox

tkscr = tkinter.Tk()
tkscr.withdraw()

for i in range(5):
    sentence = str(generate.gen())
    print("Your sentence :",sentence)
    messagebox.showinfo("Your sentence",sentence)
Esempio n. 15
0
from . import Assignment_1 as ass
import generate as g

run(g.gen(3, 5), 3)
Esempio n. 16
0
    startingarrgen = input(
        '''\nEnter 1 if you want the program to generate an array of number.\nEnter 2 if you want to import numbers from a text file: '''
    )
listtype = "int"
startarray = []
if startingarrgen == "1":
    n = input("\nHow many integers would you like to generate: ")
    x = input("What is the minimum value of integers: ")
    y = input("What is the maximum value of integers: ")
    while not n.isdigit() or not x.isdigit or not y.isdigit() or int(
            n) < 0 or y < x:
        print("\nInvalid input")
        n = input("\nHow many integers would you like to generate: ")
        x = input("What is the minimum value of integers: ")
        y = input("What is the maximum value of integers: ")
    startarray = gen(int(n), int(x), int(y))
else:
    print(
        "\nYou can import txt or csv files. Please see README for formatting.")
    filename = input("\nEnter the file name please: ")
    while ".txt" not in filename and ".csv" not in filename:
        print("\nInvalid extension.")
        filename = input("\nEnter the file name please: ")
    listtype = input(
        "\nEnter str if the list is of string. Enter int if list is of numbers: "
    )
    while listtype not in ["int", "str"]:
        print("Invalid")
        listtype = input(
            "\nEnter str if the list is of string. Enter int if list is of numbers: "
        )
Esempio n. 17
0
 def generate(self):
     return gen(self.order, self.length, self.seed)
Esempio n. 18
0
board_gen, tiles_left, tiles_right = [], [], []
grid_len = int(input('Grid length? '))


@win.event()
def on_key_press(symbol, modifiers):
    global tiles_left, tiles_right
    if symbol == key._0:
        tiles_left, tiles_right = [], []
    elif symbol == key._1:
        tiles_left = display.draw_tiles(prb, tile_batch, True, True)
    elif symbol == key._2:
        tiles_left = display.draw_tiles(sol, tile_batch, True, False)
    elif symbol == key._3:
        tiles_right = display.draw_tiles(cmp, tile_batch, False, False)


@win.event()
def on_draw():
    win.clear()
    tile_batch.draw()
    grid_batch.draw()


grid = display.draw_grids(grid_len, grid_batch)
[prb, sol] = generate.gen(grid_len)
#prb = [[1,1,1,0,0],[0,1,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
cmp = solve.sol(prb)
pyglet.app.run()
Esempio n. 19
0
#!/usr/bin/python

import time
import poker, poker2, generate

if __name__ == '__main__':

    start = time.time()
    max1 = max(generate.gen(5))
    elapsed = time.time() - start
    print("%.4f" % (elapsed)), max1

    start = time.time()
    max2 = max(generate.gen(5), key=poker.score)
    elapsed = time.time() - start
    print("%.4f" % (elapsed)), max2

    start = time.time()
    max3 = max(generate.gen(5), key=poker2.score2)
    elapsed = time.time() - start
    print("%.4f" % (elapsed)), max3
Esempio n. 20
0
print(dfPosts)

df_maintags.to_csv("Tags.csv")
Tags = pd.read_csv("Tags.csv")
Posts = pd.read_csv("Posts.csv")
df_result = Tags.join(Posts)
df_result = df_result.drop(columns=["Unnamed: 0"])
df_result = df_result.sort_values(by=["posts"])

##########create folder and change directory################
try:
    os.makedirs(tagword)
except:
    print("folder exist")

os.chdir(tagword)
######################################################################

print(df_result)
name = "#" + tagword + ".csv"
df_result.to_csv(name, index=False)

sort(name)
delete_emptycols("sorted.csv")

gen("sorted1.csv")
os.chdir("..")
path = os.path.join(tagword, "hashtags.txt")
tagword = tagword + ".txt"
upload(tagword, path)
Esempio n. 21
0
port = 33890
s.bind(('', port))

s.listen(100)
c = None

generate.setup(5, 'random_half_less10_up5_newline_replaced.txt',
               'kernel5_random_half_less10_up5_newline_replaced_0.pkl')
print('ready')

while True:
    sock, addr = s.accept()
    print('accept')
    seed = sock.recv(1024).decode('utf-8').strip()

    generate.gen(seed)
    if TTS.T2M('./sample/sample.txt'):
        with open('./sample/sample.mp3', 'rb') as f:
            sock.sendall(f.read())

        sock.sendall('---$---'.encode('utf-8'))

        with open('./sample/sample.txt', 'rb') as f:
            sock.sendall(f.read())
    sock.close()

# import socket
#
# s = socket.socket()
# host = 'xxx.xxx.xxx.xxx'
# port = 33890
Esempio n. 22
0
def algoritme(antwoord):
    combi_lijst = gen() #Deze functie staat apart zodat het testen sneller kan gaan (Anders moet gen steeds opnieuw)
    oplossing, tijd =algoritme_uitvoering(antwoord,combi_lijst)
    return oplossing, tijd
Esempio n. 23
0
#!/usr/bin/python

import time
import poker, poker2, generate

if __name__ == '__main__':

	start = time.time()
	max1 = max(generate.gen(5))
	elapsed = time.time() - start
	print ("%.4f" % (elapsed)), max1

	start = time.time()
	max2 = max(generate.gen(5), key=poker.score)
	elapsed = time.time() - start
	print ("%.4f" % (elapsed)), max2

	start = time.time()
	max3 = max(generate.gen(5), key=poker2.score2)
	elapsed = time.time() - start
	print ("%.4f" % (elapsed)), max3

    k=10,
    batch_size=batch_size,
    short=False,
    temperature=args.temperature,
    use_unk=True,
    model=model,
    data=(X_test, Y_test),
    idx2word=idx2word,
    oov0=oov0,
    glove_idx2idx=glove_idx2idx,
    vocab_size=vocab_size,
    nb_unknown_words=nb_unknown_words,
)

# get train and validation generators
r = next(gen(X_train, Y_train, batch_size=batch_size, nb_batches=None, nflips=None, model=None, debug=False, oov0=oov0, glove_idx2idx=glove_idx2idx, vocab_size=vocab_size, nb_unknown_words=nb_unknown_words, idx2word=idx2word))
traingen = gen(X_train, Y_train, batch_size=batch_size, nb_batches=None, nflips=args.nflips, model=model, debug=False, oov0=oov0, glove_idx2idx=glove_idx2idx, vocab_size=vocab_size, nb_unknown_words=nb_unknown_words, idx2word=idx2word)
valgen = gen(X_test, Y_test, batch_size=batch_size, nb_batches=nb_val_samples // batch_size, nflips=None, model=None, debug=False, oov0=oov0, glove_idx2idx=glove_idx2idx, vocab_size=vocab_size, nb_unknown_words=nb_unknown_words, idx2word=idx2word)

# define callbacks for training
callbacks = [TensorBoard(
    log_dir=os.path.join(config.path_logs, str(time.time())),
    histogram_freq=2, write_graph=False, write_images=False)]

# train model and save weights
h = model.fit_generator(
    traingen, samples_per_epoch=nb_train_samples,
    nb_epoch=args.epochs, validation_data=valgen, nb_val_samples=nb_val_samples,
    callbacks=callbacks,
)
model.save_weights(FN1_filename, overwrite=True)
Esempio n. 25
0
from image import get_image
from generate import gen
from encrypt import encrypt_blob
from cloud_deploy import dep
import cv2

# get the secret image and save it
images = get_image()
cv2.imwrite("gallery/c_im.jpg", images[0])

# generate the private and public key
gen()

# loading public key
fd = open("public_key.pem", "rb")
public_key = fd.read()
fd.close()

#loading image
fd = open("gallery/c_im.jpg", "rb")
unencrypted_blob = fd.read()
fd.close()

# encryption
encrypted_blob = encrypt_blob(unencrypted_blob, public_key)

#storing encrypted data
fd = open("gallery/encrypted_img.jpg", "wb")
fd.write(encrypted_blob)
fd.close()