def test_with_word_nums(self, make_random_text_mock, make_network_mock): return_value = 'a1', 'a2' make_network_mock.return_value = return_value text_arg = 'text_arg' words_num = 50 markov.markov(text_arg, words_num) make_network_mock.assert_called_once_with(text_arg) args = return_value + (words_num, ) make_random_text_mock.assert_called_once_with(*args)
def load(a_Markov, a_all_words, filename): if a_Markov == None: import cPickle Markov = markov() Markov = cPickle.load(open(".m_" + filename + '.dmp', "rb")) all_words = cPickle.load(open(".w_" + filename + '.dmp', "rb")) else: Markov = a_Markov all_words = a_all_words new_words = [''] print "total:", len(all_words) new_words.append(Markov.predict(' '.join(new_words[-1:]).lower())) j = 0 while j < 500 or (next_word != '.' and next_word != '!' and next_word != '?'): j += 1 next_word = None i = depth while next_word == None and i > 0: next_word = Markov.predict(' '.join(new_words[-i:]).lower()) i -= 1 if next_word == None and new_words[-1:][0] in ['.', '?', '!']: next_word = '\n\n' + Markov.predict('') if next_word == None: next_word = Markov.predict('') new_words.append(next_word) output = ' '.join(new_words) for char in punc: output = output.replace(' ' + char, char) print output
def load( a_Markov, a_all_words, filename ): if a_Markov == None: import cPickle Markov = markov() Markov = cPickle.load( open( ".m_" + filename + '.dmp', "rb" ) ) all_words = cPickle.load( open( ".w_" + filename + '.dmp', "rb" ) ) else: Markov = a_Markov all_words = a_all_words new_words = [ '' ] print "total:", len( all_words ) new_words.append( Markov.predict( ' '.join(new_words[ -1:]).lower() ) ) j = 0 while j < 500 or ( next_word != '.' and next_word != '!' and next_word != '?' ): j += 1 next_word = None i = depth; while next_word == None and i > 0: next_word = Markov.predict( ' '.join(new_words[ -i:]).lower() ) i -= 1 if next_word == None and new_words[-1:][0] in ['.','?','!']: next_word = '\n\n' + Markov.predict( '' ) if next_word == None: next_word = Markov.predict( '' ) new_words.append( next_word ) output = ' '.join(new_words) for char in punc: output = output.replace( ' ' + char, char ) print output
def generate_post(fedi, db, seed_post, reply=False): seed = TakeADump(seed_post.content).data if seed: seed = random.choice(seed).encode("utf-8", errors="replace") else: seed = random.choice(chain_from_none(db)) if reply: mentions = [b"@" + seed_post.account.acct.encode("utf-8")] for i in seed_post.mentions: if i.acct == "Stan": continue mentions.append(b"@" + i.acct.encode("utf-8")) mentions = b" ".join(mentions) + b" " fedi.status_post(mentions + markov(db, seed), in_reply_to_id=seed_post) else: fedi.status_post(markov(db, seed))
def __init__(self, groupName): self.m_groupName = groupName self.refreshGroup() self.refreshBot() self.getAdmins() self.m_thisTwitch = twitch.emotes() self.m_thisAlarm = timer.alarm() self.m_thisMarkov = markov.markov(self.m_thisGroup, self.m_groupName, self.m_thisBot) utils.showOutput('Bot initialized successfully...listening...', verbosity=utils.INFO_LEVEL_Useful)
def run(self, num_traits, pop_size, num_gen, influencer): m = markov(open('static/pitches/pitches_' + influencer + '.txt')) pop = individual.genome(m,num_traits) print 'population is ',pop # crossover p1 = random.choice(pop) p2 = random.choice(pop) child = crossover.mate(p1,p2, num_traits) print 'p1 is ',p1 print 'p2 is ',p2 print 'child is ',child
def handle_command(command, channel): """ Execute a command. Idiot. """ default_response = "Not a valid command." # Find and exec the command response = None if command.startswith(EXAMPLE_COMMAND): response = "AAAAAAAAAAAAAAAAAa" elif command.startswith(SHITPOST_SEND_COMMAND): post_rand_image(SHITPOST_TAG, 'shitpost', channel) response = "beep boop" elif command.startswith(SHITPOST_COUNT_COMMAND): response = "i got %d shitposts" % count_img(SHITPOST_TAG) elif command.startswith(SHITPOST_HELP_COMMAND): response = "upload shitposts to https://volafile.org/r/" + VOLA_ROOM_ID + " and ill dl 'em. " + \ "ill need like a minute or 2 to do that." elif command.startswith(JUKEBOX_ADD_COMMAND): jb_song = command jb_song = jb_song.replace(JUKEBOX_ADD_COMMAND, '', 1) print("jb_song: " + jb_song) response = save_jukebox(jb_song) elif command.startswith(JUKEBOX_DIME_COMMAND): response = dime_jukebox() elif command.startswith(BIRTHDAY_COMMAND): response = "I was born on " + find_birthday() elif command.startswith(MARKOV_COMMAND): # Default response response = 'No can markov' markov_target_user = command markov_target_user = markov_target_user.replace('markov', '') markov_target_user = markov_target_user.replace(' ', '') print('markov_target_user: '******'fail'): response = markov_response elif command.startswith(GREETING_1_COMMAND): time.sleep(RESP_DELAY) response = "hello humans" elif command.startswith(GREETING_2_COMMAND): time.sleep(RESP_DELAY) response = "howdy" elif command.startswith(CHOOSE_COMMAND): time.sleep(RESP_DELAY) response = parse_choice(command) slack_client.api_call("chat.postMessage", channel=channel, text=response or default_response)
def __init__(self, d=None): if d: self.__dict__ = d return self.headline = markov() image_urls = image.get_image_urls(self.headline) self.guid = uuid4().hex self.images = [] for _ in image_urls: img = image(_, self.guid) self.images.append( ('./static/images/{}/{}'.format(self.guid, img.filename), img.caption)) return None
def test_markov(): # fmt: off bits = [ 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0 ] # fmt: on import markov assert_eq( 0.761, markov.markov(bits).min_entropy, tolerance=0.001, )
def init(self, artist): self.markov = markov(open('./static/pitches/pitches_' + artist + '.txt')) tmp_pitch = self.markov_pitch() duration = [ 'whole', 'half', 'quarter', 'eighth', '16th'] indi_id = 0 generation = 0 for i in range(0, model.get_pop_size()): tmp_pitch = self.markov_pitch() dur = random.choice(duration) for j in range(0, model.get_num_traits()): self.create_trait(indi_id, generation, tmp_pitch[j], dur) indi_id += 1 raise web.seeother('/fitness/0')
def modulate(nus, bp=None, bs=1, t0=0, DM=500, mod=None): ''' Modulate over frequencies, here's just an example, using gaussian envelop try to mimick whatever variations/patterns seen in data nu in GHz ''' length = nus.size df = nus[1] - nus[0] if mod is None: p = np.random.random() if p > 0.01: mod = 'markov' else: mod = 'sinc' if mod == 'markov': p1, p2 = FREQ_BAND_TO_INFO[args.band]['markov_t'] #CHANGEBACK tscale = np.random.uniform(p1, p2) mark = markov(length, tscale) #import IPython; IPython.embed() mark = ndimage.filters.gaussian_filter1d(mark, sigma=float(length) / 100) #CHANGEBACK elif mod == 'sinc': scint_scale = np.random.uniform(0.005, 0.03) domain = np.linspace(-20, 20, int( length * 2.2)) * np.abs(nus[-1] - nus[0]) / scint_scale start = np.random.randint(0, int(length * 1.1)) mark = np.sqrt(np.sinc(domain)**2)[start:start + length] return mark else: mark = np.ones_like(nus) fpeak = np.random.uniform(nus[0], nus[-1], size=bs) fwidth = np.random.uniform(length / 30, length / 5, size=bs) * df #CHANGEBACK if bp is None: broad = np.random.random() if broad > 0.5: return np.exp(-0.5 * (nus[np.newaxis, ...] - fpeak[..., np.newaxis])**4 / fwidth**4.) * mark else: return mark[np.newaxis, ...] else: bpmod = np.where(bp > np.mean(bp), 1., bp / np.mean(bp)) return np.exp(-0.5 * (nus - fpeak)**2 / fwidth**2.) * bpmod * mark
def dump( filename ): import cPickle f = open( filename ) Markov = markov() prev_word = [ '' ] line = f.readline() all_words = set() lines = 0 while True: lines += 1 if lines % 10 == 0: sys.stdout.write( '\r%d' % lines ) sys.stdout.flush() for char in punc: line = line.replace( char, ' ' + char ) prev_word = [''] for word in line.split(' '): word = clean(word) if len( word ) == 0: continue all_words.add( word ) for i in range( depth ): if i > len( prev_word ): break; Markov.record( ' '.join(prev_word[-i:]).lower(), word ) prev_word.append( word ) if len( prev_word ) > depth: prev_word.pop(0) line = f.readline() if len( line ) == 0: f.close() break print '' all_words = list( all_words ) cPickle.dump( Markov, open( '.m_' + filename + '.dmp', "wb" ) ) cPickle.dump( all_words, open( '.w_' + filename + '.dmp', "wb" ) ) load( Markov, all_words, None )
def dump(filename): import cPickle f = open(filename) Markov = markov() prev_word = [''] line = f.readline() all_words = set() lines = 0 while True: lines += 1 if lines % 10 == 0: sys.stdout.write('\r%d' % lines) sys.stdout.flush() for char in punc: line = line.replace(char, ' ' + char) prev_word = [''] for word in line.split(' '): word = clean(word) if len(word) == 0: continue all_words.add(word) for i in range(depth): if i > len(prev_word): break Markov.record(' '.join(prev_word[-i:]).lower(), word) prev_word.append(word) if len(prev_word) > depth: prev_word.pop(0) line = f.readline() if len(line) == 0: f.close() break print '' all_words = list(all_words) cPickle.dump(Markov, open('.m_' + filename + '.dmp', "wb")) cPickle.dump(all_words, open('.w_' + filename + '.dmp', "wb")) load(Markov, all_words, None)
def cmd_kriegs(self): return markov.markov("KriegsaffeNo9")
URL = "https://api.twitter.com/1.1/statuses/update.json" message = str(chain) """while len(messagestr) > 280: message = markov.Chain() messagestr = str(message)""" print(message) auth = makeAuth(consumer_key, oauth_token, consumer_secret, token_secret, message, timestamp, nonce, URL) URL = URL + "?include_entities=true" headers = {"Authorization": auth} data = {"status": message} r = requests.post(url=URL, data=data, headers=headers) print(r.request.headers) print(r.text) print(chain.trace()) retval = r.json() log = open("output.log", "a") log.write(retval["created_at"] + " " + nonce + "\n") log.write(chain.trace() + "\n") if __name__ == "__main__": chain = markov.markov() postToTwitter(chain)
def mcInterface(method, uncMean, persistence, varCov, nval, verb = 'DEBUG'): ''' Inputs: 1) method 2) uncMean as column vector 3) persistence as matrix 4) varCov as matrix 5) nval as column vector ''' # Get a logger instance logger = wrapLogger(loggerName = 'mcInterface', streamVerb = verb, logFile = '') # Make sure that input matrices are not arrays to allow for * notation # Also enforce column vectors nVars = len(nval) uncMean = np.mat(uncMean).reshape(len(uncMean), 1) persistence = np.mat(persistence) varCov = np.mat(varCov) nval = np.mat(nval).reshape(len(nval), 1) if nval[0, 0] == 1: ShockMatrix = uncMean.T TransMatrix = 1 return # Map unconditional mean into an intercept of a VAR process I = np.mat(np.eye(len(nval))) intercept = ( I - persistence ) * uncMean # Derivation: varEps # see wave Variance Covariance Vector Operations for rules # Y_t = alpha + theta Y_{t-1} + eps_{t+1} # V(Y_t) = V(theta Y_{t-1} + V(eps_{t+1}) # V(Y) = theta V(Y) theta' + V(eps) # V(eps) = (I-theta I theta') V(Y) varEps = ( I - persistence * I * persistence.T ) * varCov logger.debug('uncMean %s' % uncMean) logger.debug('persistence %s' % persistence) logger.debug('varCov %s' % varCov) if method.lower() == 'Tauchen1987Joh'.lower(): Ns = nval[0, 0] bandwidth = 1 retDict = Tauchen1987Joh(persistence, intercept, varCov, Ns, bandwidth, verb) ShockMatrix = retDict['y'] TransMatrix = retDict['P'] elif method.lower() == 'KnotekTerry'.lower(): ''' needs 3 shock states to match standard deviation and/or persistence. ''' A0 = np.eye(nVars) A1 = intercept A2 = persistence sigma = varEps N = nval random_draws = 10000 method = 1 [P,states,zbar] = fn_var_to_markov(A0,A1,A2,sigma,N,random_draws,method) ShockMatrix = states.T TransMatrix = P elif method.lower() == 'Tauchen1987fortran'.lower(): ''' doesn't match persistence ''' pathToFile = os.path.dirname( __file__ ) if not os.path.isfile(os.path.join(os.getcwd(), 'GHQUAD.DAT')): shutil.copy(os.path.join(pathToFile, 'GHQUAD.DAT'), os.getcwd()) markovInputFile = open('PARMS', 'w') print >> markovInputFile, len(nval) print >> markovInputFile, 1 for ele in nval.flat: print >> markovInputFile, ele for ele in uncMean.flat: print >> markovInputFile, ele for ele in persistence.flat: print >> markovInputFile, ele for ele in varCov.flat: print >> markovInputFile, ele markovInputFile.close() states = nval.prod() vars = len(nval) TransMatrix, ShockMatrix = markov.markov(states, vars) os.remove('GHQUAD.DAT') os.remove('PARMS') os.remove('dog') elif method.lower() == 'momentMatching'.lower(): dims = {} # all variables have the same # of states. dims['states'] = np.prod(nval) dims['vars'] = len(nval) shockTarget = {} shockTarget['E'] = np.ravel(uncMean) shockTarget['Std'] = np.asarray(np.sqrt(np.diag(varCov))) shockTarget['Cor'] = np.asarray([varCov[0, 1] / np.sqrt(varCov[0,0]) * np.sqrt(varCov[1,1])]) S = optShock(dims, shockTarget) # sort S ind = np.lexsort((S.T[1], S.T[0])) ShockMatrix = S[ind].copy() transTarget = {} transTarget['Theta'] = persistence TransMatrix = optTrans(dims, transTarget, S) else: print('method not implemented. exiting... ') os._exit(1) logger.debug('ShockMatrix %s' % ShockMatrix) logger.debug('TransMatrix %s' % TransMatrix) return ShockMatrix, TransMatrix
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import re from markov import markov, generate_text with open('memoirs.json') as infile: memoirs = json.load(infile) memoirs = [re.sub('[",\.!?-]+', '', m).lower() for m in memoirs] chain = None for m in memoirs: chain = markov(m, chain) text = generate_text(chain) while " ".join(text) in memoirs or len(text) != 6: text = generate_text(chain) print " ".join(text).capitalize()
def mcInterface(method, uncMean, persistence, varCov, nval, verb='DEBUG'): ''' Inputs: 1) method 2) uncMean as column vector 3) persistence as matrix 4) varCov as matrix 5) nval as column vector ''' # Get a logger instance logger = wrapLogger(loggerName='mcInterface', streamVerb=verb, logFile='') # Make sure that input matrices are not arrays to allow for * notation # Also enforce column vectors nVars = len(nval) uncMean = np.mat(uncMean).reshape(len(uncMean), 1) persistence = np.mat(persistence) varCov = np.mat(varCov) nval = np.mat(nval).reshape(len(nval), 1) if nval[0, 0] == 1: ShockMatrix = uncMean.T TransMatrix = 1 return # Map unconditional mean into an intercept of a VAR process I = np.mat(np.eye(len(nval))) intercept = (I - persistence) * uncMean # Derivation: varEps # see wave Variance Covariance Vector Operations for rules # Y_t = alpha + theta Y_{t-1} + eps_{t+1} # V(Y_t) = V(theta Y_{t-1} + V(eps_{t+1}) # V(Y) = theta V(Y) theta' + V(eps) # V(eps) = (I-theta I theta') V(Y) varEps = (I - persistence * I * persistence.T) * varCov logger.debug('uncMean %s' % uncMean) logger.debug('persistence %s' % persistence) logger.debug('varCov %s' % varCov) if method.lower() == 'Tauchen1987Joh'.lower(): Ns = nval[0, 0] bandwidth = 1 retDict = Tauchen1987Joh(persistence, intercept, varCov, Ns, bandwidth, verb) ShockMatrix = retDict['y'] TransMatrix = retDict['P'] elif method.lower() == 'KnotekTerry'.lower(): ''' needs 3 shock states to match standard deviation and/or persistence. ''' A0 = np.eye(nVars) A1 = intercept A2 = persistence sigma = varEps N = nval random_draws = 10000 method = 1 [P, states, zbar] = fn_var_to_markov(A0, A1, A2, sigma, N, random_draws, method) ShockMatrix = states.T TransMatrix = P elif method.lower() == 'Tauchen1987fortran'.lower(): ''' doesn't match persistence ''' pathToFile = os.path.dirname(__file__) if not os.path.isfile(os.path.join(os.getcwd(), 'GHQUAD.DAT')): shutil.copy(os.path.join(pathToFile, 'GHQUAD.DAT'), os.getcwd()) markovInputFile = open('PARMS', 'w') print >> markovInputFile, len(nval) print >> markovInputFile, 1 for ele in nval.flat: print >> markovInputFile, ele for ele in uncMean.flat: print >> markovInputFile, ele for ele in persistence.flat: print >> markovInputFile, ele for ele in varCov.flat: print >> markovInputFile, ele markovInputFile.close() states = nval.prod() vars = len(nval) TransMatrix, ShockMatrix = markov.markov(states, vars) os.remove('GHQUAD.DAT') os.remove('PARMS') os.remove('dog') elif method.lower() == 'momentMatching'.lower(): dims = {} # all variables have the same # of states. dims['states'] = np.prod(nval) dims['vars'] = len(nval) shockTarget = {} shockTarget['E'] = np.ravel(uncMean) shockTarget['Std'] = np.asarray(np.sqrt(np.diag(varCov))) shockTarget['Cor'] = np.asarray( [varCov[0, 1] / np.sqrt(varCov[0, 0]) * np.sqrt(varCov[1, 1])]) S = optShock(dims, shockTarget) # sort S ind = np.lexsort((S.T[1], S.T[0])) ShockMatrix = S[ind].copy() transTarget = {} transTarget['Theta'] = persistence TransMatrix = optTrans(dims, transTarget, S) else: print('method not implemented. exiting... ') os._exit(1) logger.debug('ShockMatrix %s' % ShockMatrix) logger.debug('TransMatrix %s' % TransMatrix) return ShockMatrix, TransMatrix
def game(): upoint=0 cpoint=0 REV_CLASS_MAP = { 0: "rock", 1: "paper", 2: "scissors", 3: "none" } print(os.getcwd()) def mapper(val): return REV_CLASS_MAP[val] model = load_model(r"C:\Users\melbi\game-master\gestures\rock-paper-scissors-model.h5") cap = cv2.VideoCapture(0) prev_move = None cap.set(3,1280) cap.set(4,720) while True: ret, frame = cap.read() frame=cv2.flip(frame,1) if not ret: continue # rectangle for user to play cv2.rectangle(frame, (100, 100), (500, 500), (255, 255, 255), 2) # rectangle for computer to play cv2.rectangle(frame, (800, 100), (1200, 500), (255, 255, 255), 2) # extract the region of image within the user rectangle roi = frame[100:500, 100:500] img = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB) img = cv2.resize(img, (227, 227)) # predict the move made pred = model.predict(np.array([img])) move_code = np.argmax(pred[0]) user_move_name = mapper(move_code) # # predict the winner (human vs computer) if prev_move != user_move_name: if user_move_name != "none": #computer_move_name = choice(['rock', 'paper', 'scissors']) winner,computer_code = markov.markov(move_code) computer_move_name=mapper(computer_code) if(winner=="Win"): upoint=upoint+1 elif(winner=="Lose"): cpoint=cpoint+1 else: pass else: computer_move_name = "none" winner = "Waiting..." prev_move = user_move_name # display the information font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(frame, "Your Move: " + user_move_name,(50, 50), font, 1.2, (255, 255, 255), 2, cv2.LINE_AA) cv2.putText(frame, "Your score: " + str(upoint),(50, 600), font, 1.2, (255, 255, 255), 2, cv2.LINE_AA) cv2.putText(frame, "Computer's Move: " + computer_move_name,(750, 50), font, 1.2, (255, 255, 255), 2, cv2.LINE_AA) cv2.putText(frame, "Computer's Score: " + str(cpoint),(750, 600), font, 1.2, (255, 255, 255), 2, cv2.LINE_AA) cv2.putText(frame, "Winner: " + winner,(400, 700), font, 2, (0, 0, 255), 3, cv2.LINE_AA) if computer_move_name != "none": icon = cv2.imread("images/{}.png".format(computer_move_name)) icon = cv2.resize(icon, (400, 400)) frame[100:500, 800:1200] = icon cv2.imshow("Rock Paper Scissors", frame) k = cv2.waitKey(10) if k == ord('q'): break cap.release() cv2.destroyAllWindows()
def load(filename): Markov = markov() Markov = cPickle.load(open(".m_" + filename + '.dmp', "rb")) return Markov
import praw, markov, time done = set() m = markov.markov() r = praw.Reddit('comment getter thing') def add_comments(sub): for i in range(1): cmts = r.get_comments(sub) for comment in cmts: if comment.id not in done: done.add(comment.id) m.addwords(comment.body) time.sleep(30) #print m.gen(30)
def index(): #Testcase output = "<p>" + str(markov.markov()) + "</p>" return output
def postFromWeb(): chain = markov.markov(True) postToTwitter(chain) return chain
def cmd_markov(self, nick): return markov.markov(nick)[:400]
def main(): chain = markov.markov(True) postToTwitter(chain)
from twitter import Twitter, OAuth from secrets import auth from markov import markov, OUTPUT_BLACKLIST api = Twitter(auth=OAuth(*auth)) if __name__ == '__main__': while True: string = markov() if (len(string) < 140 and string not in OUTPUT_BLACKLIST): api.statuses.update(status=string) break
def main(): pygame.init() piano = key.piano() midiList = [] directory = 'Bach' files = Path(directory).glob('*') for file in files: timing = FileOpener.FileOpener(midiList, file) #print(file) finalList = [] for track in midiList: finalList += track print(len(finalList)) print(timing[0], timing[1]) outport = mido.open_output() #m = markov.markov(finalList, 2, 500) newSong = [] looptime = time.time() s = 0 i = 0 delta = 0 piano = key.piano() piano.build(screen) curr_width = screen.get_width() curr_height = screen.get_height() playfont = pygame.font.SysFont('Raleway Bold', int(curr_height / 15)) playButton = clickBox((curr_width / 4, (curr_height * 4) / 6), (100 * (curr_width / 800), 50 * (curr_height / 600)), (211, 211, 211), (128, 128, 128), playfont, "Play", (128, 128, 0)) stopButton = clickBox((curr_width * 3 / 4, (curr_height * 4) / 6), (100 * (curr_width / 800), 50 * (curr_height / 600)), (211, 211, 211), (128, 128, 128), playfont, "Stop", (128, 0, 0)) isRunning = True playSong = False while isRunning: screen.fill((128, 128, 128)) curr_width = screen.get_width() curr_height = screen.get_height() pygame.draw.rect(screen, (0, 0, 0), (0, 0, curr_width, curr_height / 4)) piano.draw(screen) #draw buttons: playButton.moveAndResize( (curr_width / 4, (curr_height * 4) / 6), (100 * (curr_width / 800), 50 * (curr_height / 600))) stopButton.moveAndResize( (curr_width * 3 / 4, (curr_height * 4) / 6), (100 * (curr_width / 800), 50 * (curr_height / 600))) playButton.draw(screen) stopButton.draw(screen) textsurface = playfont.render('Infinite Music Generator', True, (0, 0, 0)) srfRect = textsurface.get_rect(center=(curr_width / 2, curr_height / 2.5)) screen.blit(textsurface, srfRect) for event in pygame.event.get(): if event.type == pygame.QUIT: isRunning = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: isRunning = False if playButton.testClick(event): playSong = True if stopButton.testClick(event): isRunning = False pygame.display.update() if playSong: if i >= len(newSong): #print("song over") for i in range(0, 88): piano.release(i) m = markov.markov(finalList, 3, 100) newSong = TupleToMessage(m) i = 0 s = 0 delta = 0 looptime = time.time() if (time.time() - looptime > 0.001): looptime = time.time() s += 0.001 delta = math.floor(s * (1000000 / (timing[0] / timing[1]))) if delta >= newSong[i].time: #print(newSong[i]) if (newSong[i].type == 'note_on'): piano.press(newSong[i].note - 21) elif (newSong[i].type == 'note_off'): piano.release(newSong[i].note - 21) outport.send(newSong[i]) i += 1 delta = 0 s = 0
def load( filename ): Markov = markov() Markov = cPickle.load( open( ".m_" + filename + '.dmp', "rb" ) ) return Markov
def setUp(self): super(TestMarkov, self).setUp() self.markov_obj = markov.markov(self.bot)