def main(argv): ini = "A-large.in" out = "A-large.txt" start = ti() sheep(ini, out) end = ti() print(end - start)
def main(argv): ini = "D-small-attempt0.in" out = "D-small-attempt0.txt" start = ti() fractile(ini, out) end = ti() print(end - start)
def main(argv): ini = "B-large.in" out = "B-large.txt" start = ti() pancake(ini, out) end = ti() print(end - start)
def main(argv): ini = "C-large.in" out = "C-large.txt" start = ti() coin(ini,out) end = ti() print("Time(sec): "+str(end-start))
def main(argv): ini = "A-small-attempt0.in" out = "A-small-attempt0.txt" start = ti() A(ini, out) end = ti() print(end - start)
def __init__(self, c, addr): self.comsock = c self.addr = addr self.backlog = "" self.messages = [] self.lastResponse = ti() self.linkedID = 0 self.lastgamecreation = ti() - CREATIONCOOLDOWN
def test_function(model, train_x, train_y, train_len, test_output=False, test_nan=False, prev_t=None): if test_nan: timei = ti() if prev_t and np.isnan(prev_t[0]): np.set_printoptions(threshold=np.nan) print( model.sess.run([ model.loss, model.log_p, model.logp_nan, model.ls, model.ls_ze, model.covs_inv_nan ], feed_dict={ model.xs: train_x, model.ys: train_y, model.seq_len: train_len })) quit() else: prev_t = model.sess.run([ model.loss, model.log_p, model.logp_nan, model.ls, model.ls_ze, model.covs_inv_nan ], feed_dict={ model.xs: train_x, model.ys: train_y, model.seq_len: train_len }) print(prev_t) print("Test takes time {}".format(ti() - timei)) return prev_t if test_output: last = None try: tes = model.sess.run(model.rnn_out, feed_dict={ model.xs: train_x, model.ys: train_y, model.seq_len: train_len }) print(tes.shape) last = train_x except: print(train_x.shape, train_y.shape, train_len.shape) tes = model.sess.run(model.rnn_out_all, feed_dict={ model.xs: last, model.ys: train_y, model.seq_len: train_len }) print(tes.shape) quit()
def rcv(): c = ncs[-1] while True: try: mail, fromaddr = c.comsock.recvfrom(1024) except ConnectionResetError: print("Client", c.addr, "disconnected!") dcFromGame(c) ncs.remove(c) return except ConnectionAbortedError: print("Client", c.addr, "disconnected!") dcFromGame(c) ncs.remove(c) return except OSError: print("[SYSTEM] OS ERROR") try: dcFromGame(c) ncs.remove(c) except: print("Already done.") if mail == b'': print("Client", c.addr, "disconnected! (Oh no...)") dcFromGame(c) c.comsock.close() ncs.remove(c) return else: c.backlog += str(mail)[2:-1] c.lastResponse = ti() parse_messages(c)
def do_pack(): """Fabric script to compress files in web_static""" local("mkdir -p versions") ver = ti("%Y%m%d%H%M%S") arc = local("tar -cvzf versions/web_static_{}.tgz web_static".format(ver)) if arc.failed: return False else: return ("versions/web_static_{}.tgz".format(ver))
def n_queens(board_size, hint=False): #Main function argument =size of the board st = ti() #Occupied Diagonals and Columns diagonal1 = {} diagonal2 = {} #For right and left Diagonal respectively Col = {} #For Column which are already alloted to some queen ans = place_queen(0, [], board_size, diagonal1, diagonal2, Col) print("Time Taken := ", ti() - st) if hint: n_queens_hint() if not ans: return -1 return ans
def answer(user, num): form = AnswerForm() if form.validate_on_submit(): time = int(ti()) - session["starttime"] counter = 0 for index, entry in enumerate(form.answer.entries): a = "answer_" + str(index + 1) if session[a] == entry.data: counter += 1 #整理数据库 #如果存在记录 if models.User.query.filter_by(nickname=user).all(): old_db = models.User.query.filter_by(nickname=user).first() old_db.numberOfQuestions = int(num) + old_db.numberOfQuestions old_db.correct = counter + old_db.correct old_db.time = time + old_db.time db.session.add(old_db) else: u = models.User(nickname=user, numberOfQuestions=num, correct=counter, time=time) db.session.add(u) db.session.commit() return redirect( url_for('finish', correct=counter, user=user, num=num, time=time)) posts = [] for i in range(1, 1 + int(num)): ansstring = "answer_" + str(i) equclass = homework2.Equation() equclass.start() _Dict = {'num': i, 'equ': equclass.equ, 'ans': equclass.answer} posts.append(_Dict) session[ansstring] = str(equclass.answer) session["starttime"] = int(ti()) return render_template("answer.html", title='Answer', form=form, posts=posts)
def do_pack(): '''Fabric script to compress files in web_static''' local("mkdir -p versions") ver = ti("%Y%m%d%H%M%S") arc = local("tar -cvzf versions/web_static_{}.tgz web_static".format(ver)) if arc is None: return None else: return ("versions/web_static_{}".format(ver))
def time(): return ti()
from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, roc_auc_score, average_precision_score from sklearn.neural_network import MLPClassifier import joblib import collections import math import sys import time import pickle import os from warnings import simplefilter simplefilter(action='ignore', category=FutureWarning) from time import time as ti t1 = ti() ex_name = '10_1_mlp_3.txt' folder_name = 'ml_threads/' folder_name_y = 'ml_y_pred/' f_name = folder_name + ex_name f_y_pred = folder_name_y + 'y{}_' + ex_name n_cors = 4 Y_step = 729000 #0 Y_step = 7290000 X = joblib.load('border_vars/X.j') print('X') Y = joblib.load('border_vars/Y.j') print('Y')
while True: for bus, _ in buses: if time % bus == 0: canary = True print("Earliest time to depart ", time) print("Final output ", (time - target_time) * bus) break if canary: break time += 1 # part 2 canary = False from time import time as ti t1 = ti() time = 1 times = [] def product(xs): product = 1 for x in xs: product *= x return product for i, bus in enumerate(buses): while (time + product([bus[1] for bus in buses[:i + 1]])) % bus[0] != 0: time += 1 times.append(time)
def extract_traj(device_id): global cam_index, t0 cam_index += 1 save_idx = 0 cut_time = '16' date_list = ['2019-11-03'] src_path = '/home/guanyonglai/data21/Reid/cxyt-2019-11-03' save_path = '/home/guanyonglai/data21/Reid/pedestrain_20191103/trajectory' t1 = ti() for date in date_list: json_files = glob.glob( os.path.join(src_path, device_id, date, cut_time, '*.json')) for idx, json_file in enumerate(json_files): if cut_time != json_file.split('/')[-1].split('_')[1].split( '-')[0]: continue try: # time = os.path.splitext(os.path.basename(json_file))[0] if idx % 500 == 0: print('processing :***{} {} {} {}/{} cut_time:{}'.format( cam_index, device_id, date, idx, len(json_files), cut_time)) info = json.load(open(json_file)) img = cv2.imread(os.path.splitext(json_file)[0] + '.jpeg') for person in info['realTimeInfo']: if person['body']['flag'] == 0: continue height = person['imgSize'][0] width = person['imgSize'][1] xmin = int(person['body']['box'][0]) ymin = int(person['body']['box'][1]) xmax = int(person['body']['box'][2]) ymax = int(person['body']['box'][3]) w = xmax - xmin h = ymax - ymin xmin = xmin - int(w / 2.4) # 3.5 h w rate: h/w=2.16 ymin = ymin - int(h / 30) # 2019-8-1 17:01:23 xmax = xmax + int(w / 2.4) # 2.8 h w rate: h/w=1.99 ymax = ymax + int(h / 25) if xmin < 0: xmin = 0 if ymin < 0: ymin = 0 if xmax > width: xmax = width if ymax > height: ymax = height person_id = person['personId'] person_path = os.path.join(save_path, date, device_id, str(person_id)) if not os.path.exists(person_path): os.makedirs(person_path) file_name = os.path.join( person_path, device_id + '_' + json_file.split('/')[-1].replace('.json', '_') + str(person_id) + '.jpg') if cv2.imwrite(file_name, img[ymin:ymax, xmin:xmax, :]): # print(file_name) save_idx += 1 except KeyboardInterrupt as e: print(e) return except BaseException as e: print(type(e), e) print('save img error : ', json_file) now = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S') print('thread finish : {} all use time : {} now : {}'.format( device_id, round(ti() - t0, 2), now))
import os import sys import json import glob import cv2 import threading import argparse from time import time as ti import threadpool import datetime t0 = ti() cam_index = 0 def extract_traj(device_id): global cam_index, t0 cam_index += 1 save_idx = 0 cut_time = '16' date_list = ['2019-11-03'] src_path = '/home/guanyonglai/data21/Reid/cxyt-2019-11-03' save_path = '/home/guanyonglai/data21/Reid/pedestrain_20191103/trajectory' t1 = ti() for date in date_list: json_files = glob.glob( os.path.join(src_path, device_id, date, cut_time, '*.json')) for idx, json_file in enumerate(json_files): if cut_time != json_file.split('/')[-1].split('_')[1].split( '-')[0]:
print pop.get_trait_additive() # Test population initialization pop.track_locus_genealogy([3,6]) pop.set_wildtype(N) #pop.set_allele_frequencies([0.3] * L, N) pop.mutation_rate = 1e-5 pop.outcrossing_rate = 1e-2 pop.crossover_rate = 1e-3 # Test allele frequency readout print np.max(pop.get_allele_frequency(4)) # Test evolution from time import time as ti t0 = ti() pop.evolve(30) t1 = ti() print 'Time for evolving population for 30 generations: {:1.1f} s'.format(t1-t0) ## Write genotypes #pop.write_genotypes('test.txt', 100) #pop.write_genotypes_compressed('test.npz', 100) ## Plot histograms #plt.ion() #pop.plot_fitness_histogram() #pop.plot_divergence_histogram(color='r') #pop.plot_diversity_histogram(color='g') # Look at the genealogy
jeux[1].append( jeux[0][0]) # le gagnant récupère la carte du perdant del jeux[0][0] # puis on supprime la carte du perdant del jeux[1][0] # puis on supprime la carte du gagnant else: jeux = escarmouche(jeux) if jeux != 0 and len(jeux[0]) > len(jeux[1]): # 0 gagne la bataille return 1, nombre_plis, jeu_base # on renvoie 1 elif jeux != 0 and len(jeux[0]) < len(jeux[1]): # 1 gagne la bataille return 2, nombre_plis, jeu_base # on renvoie 2 else: # égalité return 3, nombre_plis, jeu_base # on renvoie 3 result_full = [[0, 0, 0], [], []] """"[victoire 1, victoire 2, égalité], [nombre de plis de chaque parties], [jeux de base]""" nombre_bataille = int(input("Nombre de bataille à simuler: ")) t1 = ti() for i in range(0, nombre_bataille): result_one = bataille() result_full[1].append( result_one[1]) # on récupère le nombre de pli de la bataille simulée result_full[2].append( result_one[2]) # on récupère les jeux de départ de la bataille simulée result_full[0][result_one[0] - 1] += 1 # on récupère lerésultat de la bataille simulée t = ti() - t1 affichage(result_full, nombre_bataille, t)
def extract_match_features(leagues=Leagues, MEANED=False, dyn_length=20, Book=True): for league in leagues: dfl = dfleague.get_group(league) dfl.sort_values(by='date', inplace=True) dfl.reset_index(inplace=True) Score[str( league)] = dfl.loc[:, 'home_team_goal':'away_team_goal'].as_matrix() if Book: BM = dfl.loc[:, 'B365H':'BSA'].as_matrix() BM = BM.reshape(-1, 10, 3) teams = np.unique(dfl.home_team_api_id).tolist() dates = np.unique(dfl.date).tolist() seasons = np.unique(dfl.season) Team_ft = np.zeros((len(dates), len(teams), n_ft)) Match_ft = np.zeros( (len(dfl), 2 * (n_ft + 5 + 28 * (10 - 9 * MEANED)) + 30)) prev_seas = dfl.season[0] k = 0 for i in range(len(dfl)): date = dates.index(dfl.date[i]) if date == 0: continue # Add Bookmaker features bm = BM[i, ...] bm[np.any(np.isnan(bm), 1), :] = 1 / np.array( [0.4587, 0.2539, 0.2874]) Match_ft[i, -30:] = bm.reshape(1, -1) print("features for day ", dfl.date[i], ", league:", league) a = ti() home_team = teams.index(dfl.home_team_api_id[i]) away_team = teams.index(dfl.away_team_api_id[i]) cur_seas = dfl.season[i] if cur_seas != prev_seas: k = 0 if k < len( np.unique(dfl.loc[dfl.season == dfl.season[0], 'home_team_api_id'])) / 2: erase = True k = k + 1 prev_seas = cur_seas # Team Features update htg = dfl.home_team_goal[i] atg = dfl.away_team_goal[i] dtg = htg - atg pts = diff_to_pt(dtg) Team_ft = team_features_update(Team_ft, date, home_team, [htg, atg, pts], erase, True) Team_ft = team_features_update(Team_ft, date, away_team, [htg, atg, pts], erase, False) # TODO FEATURES DYNAMIQUE TODO # Home_story = dfl.loc[((dfl.home_team_api_id == home_team) | # (dfl.away_team_api_id == home_team)) & (dfl.date < dfl.date[i])] # gfh_story # là il faut metre à part les matchs où l'équipe était à domicile # Away_story = dfl.loc[((dfl.home_team_api_id == away_team) | # (dfl.away_team_api_id == away_team)) & (dfl.date < dfl.date[i])] # Match ft. filling Match_ft[i, :n_ft] = Team_ft[date - 1, home_team, :] Match_ft[i, n_ft:2 * n_ft] = Team_ft[date - 1, away_team, :] # Add players features (33 per player: 5GK + 28 field) to the list player_list_id = dfl.loc[ i, 'home_player_1':'away_player_11'].as_matrix() ht_feat = get_team_feat(player_list_id[:11], pd.Series(dfl.date[i]), corresp, MEANED) at_feat = get_team_feat(player_list_id[11:], pd.Series(dfl.date[i]), corresp, MEANED) Match_ft[i, 2 * n_ft:2 * n_ft + 5 + 28 * (10 - 9 * MEANED)] = ht_feat Match_ft[i, 2 * n_ft + 5 + 28 * (10 - 9 * MEANED):2 * (n_ft + 5 + 28 * (10 - 9 * MEANED))] = at_feat M_ft[str(league)] = Match_ft return M_ft, Score
print pop.get_trait_additive() # Test population initialization pop.track_locus_genealogy([3, 6]) pop.set_wildtype(N) #pop.set_allele_frequencies([0.3] * L, N) pop.mutation_rate = 1e-5 pop.outcrossing_rate = 1e-2 pop.crossover_rate = 1e-3 # Test allele frequency readout print np.max(pop.get_allele_frequency(4)) # Test evolution from time import time as ti t0 = ti() pop.evolve(30) t1 = ti() print 'Time for evolving population for 30 generations: {:1.1f} s'.format(t1 - t0) ## Write genotypes #pop.write_genotypes('test.txt', 100) #pop.write_genotypes_compressed('test.npz', 100) ## Plot histograms #plt.ion() #pop.plot_fitness_histogram() #pop.plot_divergence_histogram(color='r') #pop.plot_diversity_histogram(color='g')
from time import time as ti start = ti() from numpy import matrix A = matrix([[1, -2, 2], [2, -1, 2], [2, -2, 3]]) B = matrix([[1, 2, 2], [2, 1, 2], [2, 2, 3]]) C = matrix([[-1, 2, 2], [-2, 1, 2], [-2, 2, 3]]) INIT = matrix([[3], [4], [5]]) FULL = [INIT] F = [] for n in FULL: AA = A * n BB = B * n CC = C * n if sum(AA) < 1001: FULL.append(AA) if sum(BB) < 1001: FULL.append(BB) if sum(CC) < 1001: FULL.append(CC) for i in range(len(FULL)): g = FULL[i] g.transpose() g = g.flatten().tolist()[0] F.append(g) for f in F: for z in range(1, 83): def mult(lis): return [z * f[0], z * f[1], z * f[2]]
get_fractions=False) enc.w2v_embedding_cluster_encode(data_seq, save_model=True, model_name=Model_name + "_WE", get_fractions=False) enc.fastdna_encode(in_df=data_seq, in_data=data, model_name=Model_name, use_premade=False, just_train_model=True) encoded_xs = enc.get_all_enc(model_name=Model_name, in_x=X, max_len=Max_length, dropfastdna=True) # Define grid of parameters param_grid = [{'alpha': (1.0000000000000001e-05, 9.9999999999999995e-07)}] # %% Run CV random_state = 43 start_time = ti() grids = {} for encoding_type, x_encoded in encoded_xs.items(): grid = GridSearchCV(SGDClassifier(tol=1e-3, random_state=random_state, penalty='l2', n_jobs=4), param_grid=param_grid, cv=10, verbose=1, return_train_score=True) grid.verbose = (3 if encoding_type in ['w2v_embedding', 'atchley', 'fastdna', 'elmo_embedding'] else grid.verbose) print(f"Fitting {encoding_type}..") grid.fit(x_encoded, y) grids[encoding_type] = grid print(f"done, score={grid.best_score_}")