index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
59,315
MareShae/BattleSnake
refs/heads/main
/NeuralEvolution.py
""" General Information: It starts out with the simple Input & Output Layers. Random mutations occur for the given genome and they are tested with the fitness function. The best out of the mutations get to further develop/mutate their genes and progress. All Neurons can mutate. Given a Neuron & its Links it can: create a new link to another existing neuron modify, i.e increase or decrease, the weights of a link create a new neuron in that link This Version: Combines all hidden layers into one. Total number of hidden neurons is fixed. Simplifies Propagation. Simplifies Crossover. """ from NeuralFunctions import * # NEURAL NETWORK class NeuralNetwork: def __init__(self, genome): self.genome = deepcopy(genome) # Gene will be updated directly self.shape = self.genome['shape'] self.Neuron = self.genome['neuron'] self.Layer = self.genome['layer'] self.input = self.Layer['input'] # ... self.output = self.Layer['output'] # ... self.hidden = self.Layer['hidden'] # Neuron Detail # FEEDING THE NETWORK def ReadOutput(self): return [self.Neuron[Neuron_UID]['activationValue'] for Neuron_UID in self.output] def Propagate(self, Neuron): for endUID in Neuron['synapse']: # Check the status of the Synapse linkWeight = Neuron['synapse'][endUID] # Weight of the StructLink linkOutput = Multiply(linkWeight, Neuron['activationValue']) # Apply Weight UpdateNeuron(self.Neuron[endUID], linkOutput) # Update the Linked Neuron def ForwardPass(self, image: list): for index in range(len(image)): if index >= len(self.input): break Neuron_UID = self.input[index] self.Neuron[Neuron_UID]['neuronValue'] = image[index] # Propagate Input Layers for Neuron_UID in self.input: Neuron = self.Neuron[Neuron_UID] ActivateNeuron(Neuron, ActivationFn=TanH) self.Propagate(self.Neuron[Neuron_UID]) # Propagate Hidden Layers for Neuron_UID in self.hidden: Neuron = self.Neuron[Neuron_UID] ActivateNeuron(Neuron, ActivationFn=TanH) self.Propagate(Neuron) # Propagate Output Layers for Neuron_UID in self.output: Neuron = self.Neuron[Neuron_UID] ActivateNeuron(Neuron) self.Propagate(Neuron) # EVOLVING THE NETWORK def Clone(self): # Create a child network MutateType = [self.LinkMutate, self.DeLinkMutate, self.WeightMutate] if len(self.hidden) < self.shape[2]: MutateType += [self.NeuronMutate] Mutate = Choice(MutateType) return Mutate() def LinkMutate(self): # LINK Mutation: Creating a StructLink between two Neuron childGenome = deepcopy(self.genome) # Copy parent genome childLayer, childNeuron = childGenome['layer'], childGenome['neuron'] Layer1 = childLayer[Choice(['input', 'hidden', 'output'])] Layer2 = childLayer[Choice(['input', 'hidden', 'output'])] if Layer1 and Layer2: NUID1, NUID2 = Choice(Layer1), Choice(Layer2) if NUID2 not in childNeuron[NUID1]['synapse']: StructLink(childGenome, NUID1, NUID2, Random()) # StructLink both Neuron return childGenome def DeLinkMutate(self): # DeLINK Mutation: Modify the StructLink Status childGenome = deepcopy(self.genome) # Copy parent genome childLayer, childNeuron = childGenome['layer'], childGenome['neuron'] Layer = childLayer[Choice(['input', 'hidden', 'output'])] if Layer: NUID = Choice(Layer) Neuron = childNeuron[NUID] # The Neuron synapseUID = list(Neuron['synapse'].keys()) if synapseUID: RemoveLink(childGenome, NUID, Choice(synapseUID)) return childGenome def WeightMutate(self): # WEIGHT Mutation: Modify the weights childGenome = deepcopy(self.genome) # Copy parent genome childLayer, childNeuron = childGenome['layer'], childGenome['neuron'] Layer = childLayer[Choice(['input', 'hidden', 'output'])] if Layer: Neuron = childNeuron[Choice(Layer)] # The Neuron synapseUID = list(Neuron['synapse'].keys()) # The dict keys: UID if synapseUID: endUID = Choice(synapseUID) Neuron['synapse'][endUID] += Multiply(0.01, Random()) # Update the Synapse weight return childGenome def NeuronMutate(self): # NEURON Mutation: Neuron between links childGenome = deepcopy(self.genome) # Copy parent genome childLayer, childNeuron = childGenome['layer'], childGenome['neuron'] Layer = childLayer[Choice(['input', 'hidden', 'output'])] if Layer: NUID1 = Choice(Layer) Neuron = childNeuron[NUID1] # The Neuron synapseUID = list(Neuron['synapse'].keys()) if synapseUID: NUID2 = Choice(synapseUID) NUIDmid = len(childNeuron) + 1 childLayer['hidden'] += [NUIDmid] weight = Neuron['synapse'][NUID2] childNeuron[NUIDmid] = StructNeuron() RemoveLink(childGenome, NUID1, NUID2) StructLink(childGenome, NUID1, NUIDmid, 1) StructLink(childGenome, NUIDmid, NUID2, weight) return childGenome ''' # TESTING THE NETWORK gen = 1 maxGenomes = 200 remnantGenomes = 25 GenomePool = [] GenomePoolScore = [] for _ in range(maxGenomes): GenomePool.append(StructGenome((14, 4, 4))) expected = numpy.array([0.45, 0.29, 0.11, 0.53]) while True: for genome in GenomePool: # Run Net = NeuralNetwork(genome) Net.ForwardPass([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.11, 0.12, 0.13, 0.14]) predicted = numpy.array(Net.ReadOutput()) error = Cost(expected, predicted) GenomePoolScore.append(error) bestScore = min(GenomePoolScore) print('Gen:', gen) print('Min Error:', bestScore) # CHILD Generation: Selection, CrossOver, Mutation gen += 1 # Sort the genes by fitness descending & remove a % for x1 in range(maxGenomes): for x2 in range(maxGenomes): if GenomePoolScore[x1] < GenomePoolScore[x2]: Swap(GenomePool, x1, x2) # Swap genome Swap(GenomePoolScore, x1, x2) # Swap fitness GenomePool = GenomePool[0: remnantGenomes] # Eliminate Genomes if bestScore == 0.0: GenomePoolScore = GenomePoolScore[0: remnantGenomes] # Eliminate Scores print(GenomePool[0]) break # Reproduction between 2 sets of genes crossGenomePool = [] for x in range(len(GenomePool)-1): crossGenomePool.append(CrossOver(GenomePool[x], GenomePool[x+1])) # Modify the Links, Weights or Neurons x = 0 GenomePool = [] GenomePoolScore = [] while len(GenomePool) < maxGenomes: Net = NeuralNetwork(crossGenomePool[x]) childGenome = Net.Clone() if childGenome and childGenome not in GenomePool: GenomePool += [childGenome] x += 1 if x >= len(crossGenomePool): x = 0 # '''
{"/Agent.py": ["/tAssist.py", "/VEnv.py"], "/server.py": ["/tAssist.py", "/VEnv.py", "/Agent.py"], "/VEnv.py": ["/tAssist.py"], "/tAssist.py": ["/NeuralFunctions.py", "/NeuralEvolution.py"], "/NeuralEvolution.py": ["/NeuralFunctions.py"]}
59,316
MareShae/BattleSnake
refs/heads/main
/NeuralFunctions.py
import numpy import random from math import exp from copy import deepcopy # STATIC FUNCTIONS def Round(val): return int(round(val)) def RoundList(image): reImage = [] for val in image: reImage.append(Round(val)) return reImage def Decimal(value, decimalPoints=5): value = format(value, '.' + str(decimalPoints) + 'f') return float(value) # https://stackoverflow.com/questions/17099556/why-do-int-keys-of-a-python-dict-turn-into-strings-when-using-json-dumps def PythonJSONDumps(json_data): correctedDict = {} for key, value in json_data.items(): if isinstance(value, list): value = [PythonJSONDumps(item) if isinstance(item, dict) else item for item in value] elif isinstance(value, dict): value = PythonJSONDumps(value) try: key = int(key) except ValueError: pass correctedDict[key] = value return correctedDict # ARRAY FUNCTIONS def Array(image): # Make sure results are always in FLOAT return numpy.array(image, dtype=float) def Cost(predicted, expected, d_P=5): cost = sum(((expected - predicted) ** 2) / len(predicted)) return Decimal(cost, d_P) def MatMul(weight, image): mul = [] row2 = len(image) row1, col1 = len(weight), len(weight[0]) # R1 must be EQUAL TO C2 if col1 == row2: for r1 in range(row1): rSum = 0 for c1 in range(col1): rSum += weight[r1][c1] * image[c1] mul += [Decimal(rSum)] return mul # ACTIVATION FUNCTIONS def Sigmoid(value, d_P=5): return Decimal(1 / (1 + exp(-value)), d_P) def TanH(value, d_P=5): exponential = exp(2 * value) return Decimal((exponential - 1) / (exponential + 1), d_P) # ARITHMETIC FUNCTIONS def Add(values, d_P=5): return Decimal(sum(values), d_P) def Multiply(*args, d_P=5): multiplied = 1 for value in args: multiplied *= value return Decimal(multiplied, d_P) # RANDOM FUNCTIONS def Choice(sequence): return random.choice(sequence) def Random(start=-1, end=1, d_P=5): return Decimal(random.uniform(start, end), d_P) def RandInt(start, end): if start == end: return start elif start > end: return return random.randint(start, end) def Swap(sequence: list, x1: int, x2: int): temp = sequence[x1] sequence[x1] = sequence[x2] sequence[x2] = temp # CONSTRUCTING A GENOME def RemoveLink(genome: dict, startUID: int, endUID: int): genome['gene'].remove([startUID, endUID]) genome['neuron'][startUID]['synapse'].pop(endUID) def StructLink(genome: dict, startUID: int, endUID: int, weight): genome['gene'].append([startUID, endUID]) genome['neuron'][startUID]['synapse'][endUID] = weight def StructNeuron(): return {'synapse': {}, # Takes the neurons it is linked to 'neuronValue': 0, # Value of the neuron before activation 'activationValue': 0 # Value of the neuron after activation } def StructGenome(shape): # I, O, H Shape Neuron, neuronUID = {}, 1 input_, output_, hidden_ = [], [], [] for _ in range(0, shape[0]): # Input input_.append(neuronUID) Neuron[neuronUID] = StructNeuron() neuronUID += 1 for _ in range(0, shape[1]): # Output output_.append(neuronUID) Neuron[neuronUID] = StructNeuron() neuronUID += 1 return {'gene': [], # Genome Links 'shape': shape, # Input, Output 'neuron': Neuron, # Genome Neuron 'layer': {'input': input_, 'output': output_, 'hidden': hidden_} # Genome Layers } # NEURON def UpdateNeuron(Neuron, value): Neuron['neuronValue'] = Add([value, Neuron['neuronValue']]) def ActivateNeuron(Neuron, ActivationFn=Sigmoid): Neuron['activationValue'] = ActivationFn(Neuron['neuronValue']) Neuron['neuronValue'] = 0 # REPRODUCTION def CrossOver(parent1: dict, parent2: dict): # CROSSOVER: New Gene will be a combination of both parents childGenome = StructGenome(parent1['shape']) childLayer, childNeuron = childGenome['layer'], childGenome['neuron'] hiddenP1, hiddenP2 = parent1['layer']['hidden'], parent2['layer']['hidden'] childHidden = hiddenP1 if len(hiddenP1) >= len(hiddenP2) else hiddenP2 for NUID in childHidden: childLayer['hidden'] += [NUID] childNeuron[NUID] = StructNeuron() geneP1, geneP2 = parent1['gene'], parent2['gene'] neuronP1, neuronP2 = parent1['neuron'], parent2['neuron'] # Align Parent Genes assuming Parent1 has the superior genome inherited = geneP1.copy() # Parent1 + Excess for gene in geneP2: if gene not in geneP1: inherited.append(gene) # Parent2 Excess inherited.sort() for NUID1, NUID2 in inherited: if [NUID1, NUID2] in geneP1 and [NUID1, NUID2] in geneP2: weight = Choice([neuronP1[NUID1]['synapse'][NUID2], neuronP2[NUID1]['synapse'][NUID2]]) elif [NUID1, NUID2] in geneP1: weight = neuronP1[NUID1]['synapse'][NUID2] elif [NUID1, NUID2] in geneP2: weight = neuronP2[NUID1]['synapse'][NUID2] # StructLink both Neurons in Child Gene StructLink(childGenome, NUID1, NUID2, weight) return childGenome
{"/Agent.py": ["/tAssist.py", "/VEnv.py"], "/server.py": ["/tAssist.py", "/VEnv.py", "/Agent.py"], "/VEnv.py": ["/tAssist.py"], "/tAssist.py": ["/NeuralFunctions.py", "/NeuralEvolution.py"], "/NeuralEvolution.py": ["/NeuralFunctions.py"]}
59,317
Baichenjia/DRAW_RNN_ImageGeneration
refs/heads/master
/test.py
import tensorflow as tf tf.enable_eager_execution() import matplotlib.pyplot as plt import numpy as np from DRAW import Draw # 引入模型 model = Draw() cs,_,_,_,_ = model.predict(tf.convert_to_tensor(np.random.random((100, 28*28)).astype(np.float32))) assert cs[0].shape == (100, 28*28) # load_weights print("----------\nload_weights...\n----------") model.load_weights("weights/model_weight.h5") T = 10 # 10个时间步生成 n = 8 # 参数表示产生 n 个图片 cs = model.sample(num=n) # 采样 assert len(cs) == T assert cs[0].shape == (n, 28*28) for t in range(len(cs)): cs[t] = cs[t].reshape((n, 28, 28)) # reshape cs[t] = 1./(1.+np.exp(-(cs[t]))) # sigmoid # 绘图 plt.figure(figsize=(T, n)) for t in range(0, len(cs)): for i in range(0, cs[t].shape[0]): plt.subplot(n, T, i*T+t+1) plt.imshow(cs[t][i], cmap='gray') plt.axis('off') plt.savefig("generated_img/img.jpg")
{"/test.py": ["/DRAW.py"]}
59,318
Baichenjia/DRAW_RNN_ImageGeneration
refs/heads/master
/DRAW.py
# -*- coding: utf-8 -*- import tensorflow as tf tf.enable_eager_execution() import tensorflow.contrib.eager as tfe import numpy as np import os ## MODEL PARAMETERS img_size = 28*28 # the canvas size enc_size = 256 # number of hidden units / output size in LSTM dec_size = 256 read_size = 2*img_size write_size = img_size z_size = 10 # QSampler output size T = 10 # MNIST generation sequence length batch_size = 100 # training minibatch size class Draw(tf.keras.Model): def __init__(self): super(Draw, self).__init__() # rnn self.encoder = tf.nn.rnn_cell.LSTMCell(enc_size) self.decoder = tf.nn.rnn_cell.LSTMCell(dec_size) # dense self.mu_dense = tf.keras.layers.Dense(z_size, activation=None) self.sigma_dense = tf.keras.layers.Dense(z_size, activation=None) self.write_dense = tf.keras.layers.Dense(img_size, activation=None) def predict(self, x): # 初始化 cs = [0]*T # sequence of canvases mus, logsigmas, sigmas = [0]*T,[0]*T,[0]*T # RNN初始化 enc_state = self.encoder.zero_state(batch_size, dtype=tf.float32) dec_state = self.decoder.zero_state(batch_size, dtype=tf.float32) # 输出初始化 h_enc_prev = tf.zeros((batch_size, enc_size)) # encoder输出的结果 h_dec_prev = tf.zeros((batch_size, dec_size)) # decoder输出的结果 # 循环 z_list = [] for t in range(T): c_prev = tf.zeros((batch_size, img_size)) if t==0 else cs[t-1] x_hat = x - tf.sigmoid(c_prev) # error image shape=(batch_size,img_size) r = tf.concat([x,x_hat], 1) h_enc, enc_state = self.encoder(tf.concat([r,h_dec_prev],1), enc_state) # sample e = tf.random_normal((batch_size,z_size), mean=0, stddev=1) mus[t] = self.mu_dense(h_enc) logsigmas[t] = self.sigma_dense(h_enc) sigmas[t] = tf.exp(logsigmas[t]) z = mus[t] + sigmas[t]*e # h_dec, dec_state = self.decoder(z, dec_state) cs[t] = c_prev + self.write_dense(h_dec) h_dec_prev = h_dec z_list.append(z) return cs, mus, logsigmas, sigmas, z_list def loss_fn(self, x): cs, mus, logsigmas, sigmas, z_list = self.predict(x) # cross_entropy cross_ent = tf.nn.sigmoid_cross_entropy_with_logits(logits=cs[-1], labels=x) recons_loss = tf.reduce_mean(tf.reduce_sum(cross_ent, axis=1)) # kl kl_losses = [] for t in range(T): mean, logvar, z = mus[t], 2.*(logsigmas[t]), z_list[t] # method1 logpz = self.log_normal_pdf(z, 0., 0.) logqz_x = self.log_normal_pdf(z, mean, logvar) kl_loss = tf.reduce_mean(logqz_x - logpz) # method2 to compute kl-loss # kl_loss = tf.reduce_mean(0.5*tf.reduce_sum(tf.square(mus[t])+tf.square(sigmas[t])-2.*logsigmas[t]-1., axis=1)) kl_losses.append(kl_loss) klloss = tf.reduce_sum(kl_losses) # 按照时间步加和 loss = recons_loss + klloss return loss, recons_loss, klloss def log_normal_pdf(self, sample, mean, logvar, raxis=1): # 可以验证,是高斯公式 log2pi = tf.log(2. * np.pi) return tf.reduce_sum( -0.5 * ((sample - mean) ** 2. * tf.exp(-logvar) + logvar + log2pi), axis=raxis) def sample(self, num=5): cs = [0]*T mus, logsigmas, sigmas = [0]*T,[0]*T,[0]*T # RNN初始化 dec_state = self.decoder.zero_state(num, dtype=tf.float32) # 循环 for t in range(T): c_prev = tf.zeros((num, img_size)) if t==0 else cs[t-1] z = tf.random_normal((num,z_size), mean=0, stddev=1) h_dec, dec_state = self.decoder(z, dec_state) cs[t] = (c_prev + self.write_dense(h_dec)).numpy() return cs if __name__ == '__main__': # 数据 (train_images, _), (test_images, _) = tf.keras.datasets.mnist.load_data() train_images = train_images.astype(np.float32) / 255. test_images = test_images.astype(np.float32) / 255. train_images = train_images.reshape((train_images.shape[0], np.prod(train_images.shape[1:]))) # (60000,784) test_images = test_images.reshape((test_images.shape[0], np.prod(test_images.shape[1:]))) # (10000,784) assert train_images.shape == (60000, img_size) assert test_images.shape == (10000, img_size) # Binarization train_images[train_images >= .5] = 1. train_images[train_images < .5] = 0. test_images[test_images >= .5] = 1. test_images[test_images < .5] = 0. TRAIN_BUF = 60000 TEST_BUF = 10000 train_dataset = tf.data.Dataset.from_tensor_slices(train_images).shuffle(TRAIN_BUF).batch(batch_size) test_dataset = tf.data.Dataset.from_tensor_slices(test_images).shuffle(TEST_BUF).batch(batch_size) # 训练 optimizer = tf.train.AdamOptimizer(1e-4) model = Draw() cs,_,_,_,_ = model.predict(tf.convert_to_tensor(np.random.random((batch_size, img_size)).astype(np.float32))) assert cs[0].shape == (batch_size, img_size) EPOCHS = 10 for epoch in range(1, EPOCHS + 1): for batch, train_x in enumerate(train_dataset): train_x = tf.convert_to_tensor(train_x) with tfe.GradientTape() as tape: loss, entropyloss, klloss = model.loss_fn(train_x) gradient = tape.gradient(loss, model.trainable_variables) grad, _ = tf.clip_by_global_norm(gradient, 5.) optimizer.apply_gradients(zip(grad, model.trainable_variables)) if batch % 5 == 0: print("Batch=", batch, ",entropy_loss=", entropyloss.numpy(), ",kl_loss=", klloss.numpy(), ",total_loss=", loss.numpy()) if epoch % 1 == 0: eval_loss_list = [] for test_x in test_dataset: eval_loss_list.append(model.loss_fn(train_x)[0].numpy()) eval_loss = np.mean(eval_loss_list) print("Epoch:", epoch, ", Eval_loss:", np.mean(eval_loss_list)) model.save_weights("weights/model_weight_"+str(epoch)+".h5") print("------------------\n\n")
{"/test.py": ["/DRAW.py"]}
59,320
theo-pannethier/Cs_Dev_Space_Invader
refs/heads/master
/principal.py
""" Programme gerant la partie graphique. ToDo: -faire le bouton qui relance la partie ~ -alien special -vie vaisseau -score Theo Pannethier / Jeffrey Simon 17/01/2021 """ import tkinter as tk from random import randint score=10 score= str(score) from tkinter import Tk,Button,Frame,PhotoImage,Canvas,Label import tkinter.font as tkFont class vaisseau(tk.Tk): """classe gerant le vaisseau et sa dynamique""" def __init__(self,pListeAlien): """initialisation de toutes les variables utiles à vaisseau""" self.x = w//2 self.y=550 self.listeAlien=pListeAlien self.vivant=True self.listeIndice = [] self.listeInterdite = [] self.affichage=Label(menu , text='vie : ' + '3' , font=normal ) self.vie=3 self.vaisseaux=canva.create_rectangle(self.x, self.y, self.x+40, self.y+40, fill="red") self.lmissile=[] self.listeIndiceAlien() self.status = True self.dynmissile(self.listeAlien,self.listeIndice,self.listeInterdite) canva.bind_all("<Left>", lambda direction='Left':self.bouger(direction)) canva.bind_all("<Right>", lambda direction='Right':self.bouger(direction)) canva.bind_all("<Key>", self.missiles) self.affichage.pack() def listeIndiceAlien(self): """Programme donnant la liste des indices des aliens""" for i in range ( len(self.listeAlien) ): self.listeIndice.append(i+1) def destructionDuVaisseau(self): """"permet de faire disparaitre la vaisseau en cas defaite""" canva.delete(self.vaisseaux) self.vivant=False return 'perdu' def CoordsX(self): """donne la coordonnée x1 (c'est a dire le x à gauche du vaisseau)""" if canva.coords(self.vaisseaux) : return canva.coords(self.vaisseaux)[0] def CoordsX2(self): """donne la coordonnée x2 (c'est a dire le x à droite du vaisseau)""" if canva.coords(self.vaisseaux) : return canva.coords(self.vaisseaux)[2] def bouger(self, event): """permet d'enregistrer la demande de deplacement du vaisseau Entrée : event car permet de donner la touche appuyée""" x,y=0,0 if event.keysym == 'Left': x=-10 if event.keysym == 'Right': x=10 canva.move(self.vaisseaux,x,y) def missiles(self, event): """permet de cree les missiles du vaisseau Entrée : event car permet de donner la touche appuyée""" if self.vivant and event.keysym == 'space': xmissile=canva.coords(self.vaisseaux)[0]+(canva.coords(self.vaisseaux)[2]- canva.coords(self.vaisseaux)[0])/2 ymissile = canva.coords(self.vaisseaux)[1] self.missile = canva.create_rectangle(xmissile-5, ymissile, xmissile + 5, ymissile - 20, fill="blue") self.lmissile=self.lmissile+[self.missile] def dynmissile(self,liste,listeIndice,listeInterdite): """permet de faire bouger les missile du vaisseau Entrée : -liste : liste des aliens -listeIndice : Liste de la liste des aliens -listeInterdite: Liste des indices des aliens detruits""" annule=False Listecoord=[] for i in range (len(listeIndice)): '''boucle for permettant la recuperation des coordonées de chaque alien''' ListeCoordAlien=[] ListeCoordAlien.append(liste[i].donneCoordsX()) ListeCoordAlien.append(liste[i].donneCoordsX2()) ListeCoordAlien.append(liste[i].donneCoordsY()) ListeCoordAlien.append(liste[i].donneCoordsY2()) Listecoord.append(ListeCoordAlien) w=0 for i in range (0,len(self.lmissile)): objetMissile=self.lmissile[i-w] canva.move(objetMissile,0,-10) if canva.coords(objetMissile)[1] <= 0: canva.delete(objetMissile) self.lmissile.pop(i - w) w = w + 1 if self.lmissile != []: for k in range( len(listeIndice)): objetMissile=self.lmissile[i - w] coordMissile=canva.coords(objetMissile) if coordMissile[0] >= Listecoord[k][0] and ( coordMissile[2] <= Listecoord[k][1] and ( coordMissile[1] >= Listecoord[k][2] and ( coordMissile[1] <= Listecoord[k][3]) or ( coordMissile[3] >= Listecoord[k][2] and ( coordMissile[3] <= Listecoord[k][3])))): val=listeIndice[k] val=listeIndice[k] if val not in listeInterdite: liste[k].destroyAlien() liste.pop(k) listeIndice.remove(val) canva.delete(self.lmissile[i - w]) self.lmissile.pop(i - w) w = w + 1 listeInterdite.append(val) annule = True break if annule == True: break canva.after(50,self.dynmissile,liste,listeIndice,listeInterdite) def getVie(self): """permet de recuperer le nombre de point de vie""" return self.vie def vivre(self): """permet de tuer le vaisseau si self.vie < 1 """ if self.vie <= 1: self.vie =self.vie - 1 self.destructionDuVaisseau() canva.after(100,self.fin) else : self.vie =self.vie - 1 self.affichage.destroy() self.affichage=Label(menu , text='vie : ' + str(self.vie) , font=normal ) self.affichage.pack() def fin(self): canva.destroy() fin = Canvas(Fenetre,height=600 , width=1100) fin.grid(row=0, column=0) gameOver= Label(fin , text='Game Over' , font=normal ) gameOver.pack() class Alien(tk.Tk): """classe permettant la gestion des aliens (chaque alien est independant et representeun appel à Alien)""" def __init__(self,n): """initialisation de la classe alien Entrée: -n : indice de l'alien crée""" self.n = n self.x = 100+self.n*100 self.y = 30 self.dx = 10 self.allee = 0 self.alien = canva.create_rectangle(self.x, self.y, self.x + 20, self.y + 20, fill="white") self.move(self.dx, self.allee) """les methodes suivantes permettent de recuperer les coordonnées de chaque alien à l'exterieur de la classe """ def donneCoordsX(self): return canva.coords(self.alien)[0] def donneCoordsX2(self): return canva.coords(self.alien)[2] def donneCoordsY(self): return canva.coords(self.alien)[1] def donneCoordsY2(self): return canva.coords(self.alien)[3] def destroyAlien(self): """programme qui appelé, permet de supprimer l'alien""" canva.delete(self.alien) return 'gagné' def move (self, dx, allee): """programme gerant le deplacement horizontale et verticale de l'alien Entrée: -dx : permet de donner la vitesse à l'alien, ici soit 10 soit -10 en fonction de la direction de deplacement. -allee : permet de compter le nombre d'aller effectué""" if canva.coords(self.alien) == []: return "gagné" canva.move(self.alien, dx, 0) if canva.coords(self.alien)[2] > 1050: dx=-10 allee=allee+1 if canva.coords(self.alien)[0] < 50: dx=10 allee=allee+1 if allee == 2 : allee = 0 canva.move(self.alien, 0, 30) if canva.coords(self.alien)[1] > 400 : leVaisseau.destructionDuVaisseau() canva.after(100, lambda : self.move(dx, allee) ) class tirer(tk.Tk): """"classe permettant le tire des aliens A l'origine, cette classe etait une methode de alien, mais pour une separation en fichier, sa creation s'imposait""" def __init__(self,pListe,leVaisseau,ilot) : """initialisation de la classe tirer Entrée: -pListe: liste des aliens""" self.ListeAlien=pListe self.listeLaser = [] self.laser() self.leVaisseau=leVaisseau self.ilot=ilot def laser(self): """methode permettant la géneration des lasers """ i=0 while i < len(self.ListeAlien): Alien = self.ListeAlien[i] nbrAlea=randint(0, 100) if nbrAlea > 90 and Alien: xlaser = Alien.donneCoordsX() + (Alien.donneCoordsX2() - Alien.donneCoordsX()) / 2 ylaser = Alien.donneCoordsY() self.rayonLaser = canva.create_rectangle(xlaser, ylaser+20, xlaser + 10, ylaser + 40, fill="green") self.listeLaser = self.listeLaser + [self.rayonLaser] i+=1 canva.after(0, self.tir) canva.after(100, self.laser) def tir(self): """methode permettant le deplacement des missiles des aliens, ainsi que leur gestion dynamique (colision avec le vaisseau,les blocs,sortie du canva)""" x1Vaisseau = self.leVaisseau.CoordsX() x2Vaisseau = self.leVaisseau.CoordsX2() coordIlot=self.ilot.ilotCoord() w = 0 i=0 while i < len(self.listeLaser): laserIndice=self.listeLaser[i - w] coordlaser=canva.coords(laserIndice) canva.move(self.listeLaser[i], 0, 10) if coordlaser[1] >= 600: canva.delete(laserIndice) self.listeLaser.pop(i - w) w = w + 1 if self.listeLaser != []: k=0 while k < len(coordIlot): if coordlaser[0] >= coordIlot[k][1][0] and ( coordlaser[2] <= coordIlot[k][1][2] and ( coordlaser[3] >= coordIlot[k][1][1] )): canva.delete(laserIndice) self.listeLaser.pop(i - w) self.ilot.toucheIlot( coordIlot[k][0]) w = w + 1 coordIlot=self.ilot.ilotCoord() k+=1 if x1Vaisseau and x2Vaisseau: if coordlaser[0] >= x1Vaisseau and ( coordlaser[2] <= x2Vaisseau and ( coordlaser[3] >= 550 )) : canva.delete(laserIndice) self.listeLaser.pop(i - w) w = w + 1 self.leVaisseau.vivre() i+=1 class ilot(tk.Tk): """classe permettant l'apparition de bloc""" def __init__(self): """initialisation de la classe avec notamment la creation visuelle des blocs""" self.x=500 self.y=400 self.vie = [2,2,2] self.carréC = [0,canva.create_rectangle(self.x, self.y, self.x + 20, self.y + 20, fill="brown")] self.carréD = [1,canva.create_rectangle(self.x+20, self.y, self.x + 20+20, self.y + 20, fill="brown")] self.carréG = [2,canva.create_rectangle(self.x -20, self.y, self.x + 20 - 20, self.y + 20, fill="brown")] self.liste=[self.carréC,self.carréD,self.carréG] def toucheIlot(self,pIndice): """permet de reduire la vie d'un ilot si celui-ci est touché Entrée: -pIndice : indice de l'ilot touché""" if self.vie[pIndice] >= 2 : self.vie[pIndice] = self.vie[pIndice] - 1 else: for carre in [self.carréC,self.carréD,self.carréG]: if carre[0] == pIndice : canva.delete(carre[1]) self.liste.remove(carre) def ilotCoord(self): """permet la recuperation à l'exterieur de la classe des coordonnées des ilots encore en vie (present dans self.iste)""" coord=[] for carre in self.liste: coord.append([carre[0],canva.coords(carre[1])]) return coord Fenetre = Tk() Fenetre.geometry('1200x600+75+20') Fond = PhotoImage(file = 'FondJeu.gif') normal = tkFont.Font(family = 'Helvetica',size=12) ptmarq=tkFont.Font(family='Helvetica',size=14, weight='bold') Fenetre.title('Space Invader ' ) canva = Canvas(Fenetre,height=600 , width=1100) item = canva.create_image(0,0,anchor='nw',image = Fond ) canva.grid(row=0, column=0) menu = Frame(Fenetre) menu.grid(row=0, column=1) QuitBouton = Button(menu,text= "Quit", fg = 'red',width=10, command = Fenetre.destroy) NewGameBouton = Button(menu,text= "New game", fg = 'red',width=10) score = Label(menu , text='score : ' + score , font=normal ) NewGameBouton.pack(padx=0,pady=0) QuitBouton.pack(padx=0,pady=100) score.pack() w=1100 height=600 listeAlien = [] nbrAlienLigne = 8 for i in range(nbrAlienLigne): listeAlien.append(Alien(i)) leVaisseau = vaisseau(listeAlien) ilot1=ilot() tire2=tirer(listeAlien,leVaisseau,ilot1) #afficher la fenetre Fenetre.mainloop()
{"/tire.py": ["/vaisseau.py", "/ilot.py"], "/alien.py": ["/vaisseau.py"], "/programeGlobal.py": ["/vaisseau.py", "/ilot.py", "/alien.py", "/tire.py"]}
59,321
theo-pannethier/Cs_Dev_Space_Invader
refs/heads/master
/vaisseau.py
# -*- coding: utf-8 -*- """ Programme contenant la classe vaisseau celle-ci permet le deplacemnt, le tire, et la destruction du vaissseau ToDo: -vie du vaisseau Theo Pannethier / Jeffrey Simon 17/01/2021 """ import tkinter as tk class vaisseau2(tk.Tk): """classe gerant le vaisseau et sa dynamique""" def __init__(self,pListeAlien,canva): """initialisation de toutes les variables utiles à vaisseau""" w=1100 self.canva=canva #self.imageVaisseau = PhotoImage(file = "vaisseau.png") #création image de fond du vaisseau self.x=w//2 self.y=550 self.listeAlien=pListeAlien self.vivant=True self.listeIndice=[] self.listeInterdite=[] self.vaisseaux=self.canva.create_rectangle(self.x, self.y, self.x+40, self.y+40, fill="red") self.lmissile=[] self.listeIndiceAlien() self.dynmissile(self.listeAlien,self.listeIndice,self.listeInterdite) self.canva.bind_all("<Left>", lambda direction='Left':self.bouger(direction)) self.canva.bind_all("<Right>", lambda direction='Right':self.bouger(direction)) self.canva.bind_all("<Key>", self.missiles) def listeIndiceAlien(self): """Programme donnant la liste des indices des aliens""" for i in range ( len(self.listeAlien) ): self.listeIndice.append(i+1) def destructionDuVaisseau(self): """"permet de faire disparaitre la vaisseau en cas defaite""" self.canva.delete(self.vaisseaux) self.vivant=False return 'perdu' def CoordsX(self): """donne la coordonnée x1 (c'est a dire le x à gauche du vaisseau)""" if self.canva.coords(self.vaisseaux) : return self.canva.coords(self.vaisseaux)[0] def CoordsX2(self): """donne la coordonnée x2 (c'est a dire le x à droite du vaisseau)""" if self.canva.coords(self.vaisseaux) : return self.canva.coords(self.vaisseaux)[2] def bouger(self, event): """permet d'enregistrer la demande de deplacement du vaisseau Entrée : event car permet de donner la touche appuyée""" x,y=0,0 if event.keysym == 'Left': x=-10 if event.keysym == 'Right': x=10 self.canva.move(self.vaisseaux,x,y) def missiles(self, event): """permet de cree les missiles du vaisseau Entrée : event car permet de donner la touche appuyée""" if self.vivant and event.keysym == 'space': xmissile=self.canva.coords(self.vaisseaux)[0]+(self.canva.coords(self.vaisseaux)[2]- self.canva.coords(self.vaisseaux)[0])/2 ymissile = self.canva.coords(self.vaisseaux)[1] self.missile = self.canva.create_rectangle(xmissile-5, ymissile, xmissile + 5, ymissile - 20, fill="blue") self.lmissile=self.lmissile+[self.missile] def dynmissile(self,liste,listeIndice,listeInterdite): """permet de faire bouger les missile du vaisseau Entrée : -liste : liste des aliens -listeIndice : Liste de la liste des aliens -listeInterdite: Liste des indices des aliens detruits""" annule=False Listecoord=[] for i in range (len(listeIndice)): '''boucle for permettant la recuperation des coordonées de chaque alien''' ListeCoordAlien=[] ListeCoordAlien.append(liste[i].donneCoordsX()) ListeCoordAlien.append(liste[i].donneCoordsX2()) ListeCoordAlien.append(liste[i].donneCoordsY()) ListeCoordAlien.append(liste[i].donneCoordsY2()) Listecoord.append(ListeCoordAlien) w=0 for i in range (0,len(self.lmissile)): objetMissile=self.lmissile[i-w] self.canva.move(objetMissile,0,-10) if self.canva.coords(objetMissile)[1]<=0: self.canva.delete(objetMissile) self.lmissile.pop(i - w) w = w + 1 if self.lmissile != []: for k in range( len(listeIndice)): objetMissile=self.lmissile[i - w] coordMissile=self.canva.coords(objetMissile) if coordMissile[0] >= Listecoord[k][0] and ( coordMissile[2] <= Listecoord[k][1] and ( coordMissile[1] >= Listecoord[k][2] and ( coordMissile[1] <= Listecoord[k][3]) or ( coordMissile[3] >= Listecoord[k][2] and ( coordMissile[3] <= Listecoord[k][3])))): val=listeIndice[k] if val not in listeInterdite: liste[k].destroyAlien() liste.pop(k) listeIndice.remove(val) self.canva.delete(self.lmissile[i - w]) self.lmissile.pop(i - w) w = w + 1 listeInterdite.append(val) annule = True break if annule == True: break self.canva.after(50,self.dynmissile,liste,listeIndice,listeInterdite)
{"/tire.py": ["/vaisseau.py", "/ilot.py"], "/alien.py": ["/vaisseau.py"], "/programeGlobal.py": ["/vaisseau.py", "/ilot.py", "/alien.py", "/tire.py"]}
59,322
theo-pannethier/Cs_Dev_Space_Invader
refs/heads/master
/tire.py
# -*- coding: utf-8 -*- """ Programme contenant la classe tirer et ainsi permettant le deplacement du missile, ainsi que ses effets sur son environement (destruction des ilots ou du vaisseau et autodestruction en cas de sorti du canva ) ToDo: -regler le probleme du 'kernel died' probablement lié aux performances Theo Pannethier / Jeffrey Simon 17/01/2021 """ import tkinter as tk from random import randint from vaisseau import vaisseau2 from ilot import ilot class tirer(tk.Tk): """"classe permettant le tire des aliens A l'origine, cette classe etait une methode de alien, mais pour une separation en fichier, sa creation s'imposait""" def __init__(self,pListe,canva) : """initialisation de la classe tirer Entrée: -pListe: liste des aliens -canva: canva du jeu""" self.ListeAlien=pListe self.listeLaser = [] self.laser() # self.permissionDeTirer() self.canva=canva self.leVaisseau = vaisseau2(self.ListeAlien,self.canva) self.ilot1=ilot(self.canva) def laser(self): """methode permettant la géneration des lasers """ i=0 while i < len(self.ListeAlien): Alien = self.ListeAlien[i] nbrAlea=randint(0, 100) if nbrAlea > 99 and Alien: xlaser = Alien.donneCoordsX() + (Alien.donneCoordsX2() - Alien.donneCoordsX()) / 2 ylaser = Alien.donneCoordsY() self.rayonLaser = self.canva.create_rectangle(xlaser, ylaser+20, xlaser + 10, ylaser + 40, fill="green") self.listeLaser = self.listeLaser + [self.rayonLaser] i+=1 #self.canva.after(0, self.tir) #self.canva.after(100, self.laser) # def permissionDeTirer(self): # self.canva.after(1000, self.tir) # def tir(self): # """methode permettant le deplacement des missiles des aliens, ainsi que # leur gestion dynamique (colision avec le vaisseau,les blocs,sortie du canva)""" # x1Vaisseau = self.leVaisseau.CoordsX() # x2Vaisseau = self.leVaisseau.CoordsX2() # coordIlot=self.ilot1.ilotCoord() # w = 0 # i=0 # while i < len(self.listeLaser): # laserIndice=self.listeLaser[i - w] # coordlaser=self.canva.coords(laserIndice) # self.canva.move(self.listeLaser[i], 0, 10) # if coordlaser[1] >= 600: # self.canva.delete(laserIndice) # self.listeLaser.pop(i - w) # w = w + 1 # if self.listeLaser != []: # k=0 # while k<len(coordIlot): # if coordlaser[0] >= coordIlot[k][1][0] and ( # coordlaser[2] <= coordIlot[k][1][2] and ( # coordlaser[3] >= coordIlot[k][1][1] )): # self.canva.delete(laserIndice) # self.listeLaser.pop(i - w) # self.ilot1.toucheIlot( coordIlot[k][0]) # w = w + 1 # coordIlot=self.ilot1.ilotCoord() # k+=1 # if x1Vaisseau and x2Vaisseau: # if coordlaser[0] >= x1Vaisseau and ( # coordlaser[2] <= x2Vaisseau and ( # coordlaser[3] >= 550 )) : # self.canva.delete(laserIndice) # self.listeLaser.pop(i - w) # w = w + 1 # self.leVaisseau.destructionDuVaisseau() # i+=1
{"/tire.py": ["/vaisseau.py", "/ilot.py"], "/alien.py": ["/vaisseau.py"], "/programeGlobal.py": ["/vaisseau.py", "/ilot.py", "/alien.py", "/tire.py"]}
59,323
theo-pannethier/Cs_Dev_Space_Invader
refs/heads/master
/ilot.py
# -*- coding: utf-8 -*- """ Programme contenant la classe ilot et ainsi permettant la creationet la gestion de la vie des ilots ToDo: Theo Pannethier / Jeffrey Simon 17/01/2021 """ import tkinter as tk class ilot(tk.Tk): """classe permettant l'apparition de bloc""" def __init__(self,canva): """initialisation de la classe avec notamment la creation visuelle des blocs""" self.canva=canva self.x=500 self.y=400 self.vie = [1,1,1] self.carréC = [0,self.canva.create_rectangle(self.x, self.y, self.x + 20, self.y + 20, fill="brown")] self.carréD = [1,self.canva.create_rectangle(self.x+20, self.y, self.x + 20+20, self.y + 20, fill="brown")] self.carréG = [2,self.canva.create_rectangle(self.x -20, self.y, self.x + 20 - 20, self.y + 20, fill="brown")] self.liste=[self.carréC,self.carréD,self.carréG] def toucheIlot(self,pIndice): """permet de reduire la vie d'un ilot si celui-ci est touché Entrée: -pIndice : indice de l'ilot touché""" if self.vie[pIndice] >= 2 : self.vie[pIndice] = self.vie[pIndice] - 1 else: for carre in [self.carréC,self.carréD,self.carréG]: if carre[0] == pIndice : self.canva.delete(carre[1]) self.liste.remove(carre) def ilotCoord(self): """permet la recuperation à l'exterieur de la classe des coordonnées des ilots encore en vie (present dans self.iste)""" coord=[] for carre in self.liste: coord.append([carre[0],self.canva.coords(carre[1])]) return coord
{"/tire.py": ["/vaisseau.py", "/ilot.py"], "/alien.py": ["/vaisseau.py"], "/programeGlobal.py": ["/vaisseau.py", "/ilot.py", "/alien.py", "/tire.py"]}
59,324
theo-pannethier/Cs_Dev_Space_Invader
refs/heads/master
/alien.py
# -*- coding: utf-8 -*- """ Programme contenant la classe alien et ainsi permettant le tire sans deplacement du missile, le deplacement des aliens, et leur destruction ToDo: Theo Pannethier / Jeffrey Simon 17/01/2021 """ import tkinter as tk from vaisseau import vaisseau2 class Alien(tk.Tk): """classe permettant la gestion des aliens (chaque alien est independant et representeun appel à Alien)""" def __init__(self,n,canva): """initialisation de la classe alien Entrée: -n : indice de l'alien crée""" self.n = n self.canva=canva self.x = 100+self.n*100 self.y = 30 self.dx = 10 self.allee = 0 self.alien = self.canva.create_rectangle(self.x, self.y, self.x + 20, self.y + 20, fill="white") self.move(self.dx, self.allee) # self.listeLaser = [] # self.laser() # self.permissionDeTirer() """les methodes suivantes permettent de recuperer les coordonnées de chaque alien à l'exterieur de la classe """ def donneCoordsX(self): return self.canva.coords(self.alien)[0] def donneCoordsX2(self): return self.canva.coords(self.alien)[2] def donneCoordsY(self): return self.canva.coords(self.alien)[1] def donneCoordsY2(self): return self.canva.coords(self.alien)[3] def destroyAlien(self): """programme qui appelé, permet de supprimer l'alien""" self.canva.delete(self.alien) return 'gagné' def move (self, dx, allee): """programme gerant le deplacement horizontale et verticale de l'alien Entrée: -dx : permet de donner la vitesse à l'alien, ici soit 10 soit -10 en fonction de la direction de deplacement. -allee : permet de compter le nombre d'aller effectué""" if self.canva.coords(self.alien) == []: return "gagné" self.canva.move(self.alien, dx, 0) if self.canva.coords(self.alien)[2] > 1050: dx=-10 allee=allee+1 if self.canva.coords(self.alien)[0] < 50: dx=10 allee=allee+1 if allee == 2 : allee = 0 self.canva.move(self.alien, 0, 30) if self.canva.coords(self.alien)[1] > 400: a = vaisseau2.destructionDuVaisseau() return a self.canva.after(100, lambda : self.move(dx, allee) )
{"/tire.py": ["/vaisseau.py", "/ilot.py"], "/alien.py": ["/vaisseau.py"], "/programeGlobal.py": ["/vaisseau.py", "/ilot.py", "/alien.py", "/tire.py"]}
59,325
theo-pannethier/Cs_Dev_Space_Invader
refs/heads/master
/programeGlobal.py
# -*- coding: utf-8 -*- """ Programme gerant la partie graphique ainsi que le lancement du programme. Ne marche qu'en partie peut etre à cause d'un probleme de preformance. ToDo: -regler le probleme 'kernel died' Theo Pannethier / Jeffrey Simon 17/01/2021 """ filin = open("information.txt", "r") filin from vaisseau import vaisseau2 from ilot import ilot from alien import Alien from tire import tirer score=10 score= str(score) from tkinter import Tk,Button,Frame,PhotoImage,Canvas,Label import tkinter.font as tkFont Fenetre = Tk() Fenetre.geometry('1200x600+75+20') Fond = PhotoImage(file = 'FondJeu.gif') normal = tkFont.Font(family = 'Helvetica',size=12) ptmarq=tkFont.Font(family='Helvetica',size=14, weight='bold') Fenetre.title('Space Invader ' ) canva = Canvas(Fenetre,height=600 , width=1100) item = canva.create_image(0,0,anchor='nw',image = Fond ) canva.grid(row=0, column=0) menu = Frame(Fenetre) menu.grid(row=0, column=1) QuitBouton = Button(menu,text= "Quit", fg = 'red',width=10, command = Fenetre.destroy) NewGameBouton = Button(menu,text= "New game", fg = 'red',width=10) test = Label(menu , text='score : ' + score , font=normal ) test.config() NewGameBouton.pack(padx=0,pady=0) QuitBouton.pack(padx=0,pady=100) test.pack() w=1100 height=600 listeAlien = [] nbrAlienLigne = 8 for i in range(nbrAlienLigne): listeAlien.append(Alien(i,canva)) leVaisseau = vaisseau2(listeAlien,canva) ilot=ilot(canva) tire=tirer(listeAlien,canva) #afficher la fenetre Fenetre.mainloop()
{"/tire.py": ["/vaisseau.py", "/ilot.py"], "/alien.py": ["/vaisseau.py"], "/programeGlobal.py": ["/vaisseau.py", "/ilot.py", "/alien.py", "/tire.py"]}
59,334
AdrianaViabL/PycharmProjectsDjango
refs/heads/main
/vdjango/blog/posts/admin.py
from django.contrib import admin from .models import Post class PostAdmin(admin.ModelAdmin): list_display = ('id', 'titulo_post', 'autor_post', 'data_post', 'categoria_post', 'publicado_post') list_editable = ('publicado_post',) list_display_links = ('id', 'titulo_post',) summernote_fields = ('conteudo_post',) admin.site.register(Post, PostAdmin)
{"/agenda/accounts/views.py": ["/agenda/accounts/models.py"], "/agenda/contatos/views.py": ["/agenda/contatos/models.py"], "/BlogDjango/posts/views.py": ["/BlogDjango/posts/models.py"], "/agenda/contatos/admin.py": ["/agenda/contatos/models.py"], "/vdjango/blog/comentarios/forms.py": ["/vdjango/blog/comentarios/models.py"], "/vdjango/blog/comentarios/admin.py": ["/vdjango/blog/comentarios/models.py"]}
59,335
AdrianaViabL/PycharmProjectsDjango
refs/heads/main
/agenda/accounts/views.py
from django.shortcuts import render, redirect from django.contrib import messages, auth from django.core.validators import validate_email from django.contrib.auth.models import User # para verificar se existe no sistema um usuario ja cadastrado from django.contrib.auth.decorators import login_required from .models import FormContato # puxando o formulario def login(request): if request.method != 'POST': return render(request, 'accounts/login.html') usuario = request.POST.get('usuario') senha = request.POST.get('senha') user = auth.authenticate(request, username=usuario, password=senha) # se incorreto retorna NONE if not user: messages.error(request, 'usuario ou senha invalidos') return render(request, 'accounts/login.html') else: auth.login(request, user) messages.success(request, 'login efetuaco com sucesso') return redirect('dashboard') def logout(request): auth.logout(request) return redirect() def cadastro(request): if request.method != 'POST': return render(request, 'accounts/cadastro.html') # pegando os dados da tela para validação nome = request.POST.get('nome') sobrenome = request.POST.get('sobrenome') email = request.POST.get('email') usuario = request.POST.get('usuario') senha = request.POST.get('senha') Rsenha = request.POST.get('Rsenha') if not nome or not sobrenome or not email or not senha or not Rsenha or not usuario: messages.error(request, 'nenhum campo pode estar vazio.') return render(request, 'accounts/cadastro.html') try: validate_email(email) except: messages.error(request, 'Email invalido') return render(request, 'accounts/cadastro.html') if len(usuario) < 6: messages.error(request, 'usuario deve ter mais de 6 caracteres') return render(request, 'accounts/cadastro.html') if len(senha) < 6: messages.error(request, 'senha deve ter mais de 6 caracteres') return render(request, 'accounts/cadastro.html') if senha != Rsenha: messages.error(request, 'senha nao bate') return render(request, 'accounts/cadastro.html') print(usuario) if User.objects.filter(username=usuario).exists(): messages.error(request, 'usuario ja existe') return render(request, 'accounts/cadastro.html') if User.objects.filter(email=email).exists(): messages.error(request, 'email ja cadastrado') return render(request, 'accounts/cadastro.html') messages.success(request, 'usuario registrado com sucesso') user = User.objects.create_user(username=usuario, email=email, password=senha, first_name=nome, last_name=sobrenome) user.save() return redirect('login') @login_required(redirect_field_name='login') # caso a pessoa nao esteja logada manda para a pagina de login def dashboard(request): if request.method != 'POST': # se nao for enviado POST, recarrega o formulario form = FormContato() return render(request, 'accounts/dashboard.html', {'form': form}) form = FormContato(request.POST, request.FILES) if not form.is_valid(): messages.error(request, 'erro ao enviar o formulário') form = FormContato(request.POST) return render(request, 'accounts/dashboard.html', {'form': form}) descricao = request.POST.get('descricao') if len(descricao) < 5: messages.error(request, 'descrição deve ter mais de 5 caracteres') form = FormContato(request.POST) return render(request, 'accounts/dashboard.html', {'form': form}) form.save() messages.success(request, f'contato {request.POST.get("nome")} salvo com sucesso') return redirect('dashboard')
{"/agenda/accounts/views.py": ["/agenda/accounts/models.py"], "/agenda/contatos/views.py": ["/agenda/contatos/models.py"], "/BlogDjango/posts/views.py": ["/BlogDjango/posts/models.py"], "/agenda/contatos/admin.py": ["/agenda/contatos/models.py"], "/vdjango/blog/comentarios/forms.py": ["/vdjango/blog/comentarios/models.py"], "/vdjango/blog/comentarios/admin.py": ["/vdjango/blog/comentarios/models.py"]}
59,336
AdrianaViabL/PycharmProjectsDjango
refs/heads/main
/agenda/contatos/models.py
from django.db import models from django.utils import timezone # colocar o comando no terminal(dentro do pycharm ou do projeto) # para que as alterações feitas no banco de dados sejam migradas # = python manage.py makemigrations class Categoria(models.Model): nome = models.CharField(max_length=255) def __str__(self): return self.nome # para que o nome da categoria apareça no caminho do admin class Contato(models.Model): nome = models.CharField(max_length=255) # campo do tipo String sobrenome = models.CharField(max_length=255, blank=True) # tornando um campo opcional telefone = models.CharField(max_length=100) email = models.CharField(max_length=255, blank=True) data_criacao = models.DateTimeField(default=timezone.now) descricao = models.TextField(blank=True) categoria = models.ForeignKey(Categoria, on_delete=models.DO_NOTHING) mostrar = models.BooleanField(default=True) fotos = models.ImageField(blank=True, upload_to='fotos/%Y/%m/%d') # para cada imagem em dias diferentes a seu upada uma pasta nova com o dia do upload sera criada def __str__(self): return self.nome
{"/agenda/accounts/views.py": ["/agenda/accounts/models.py"], "/agenda/contatos/views.py": ["/agenda/contatos/models.py"], "/BlogDjango/posts/views.py": ["/BlogDjango/posts/models.py"], "/agenda/contatos/admin.py": ["/agenda/contatos/models.py"], "/vdjango/blog/comentarios/forms.py": ["/vdjango/blog/comentarios/models.py"], "/vdjango/blog/comentarios/admin.py": ["/vdjango/blog/comentarios/models.py"]}
59,337
AdrianaViabL/PycharmProjectsDjango
refs/heads/main
/agenda/accounts/models.py
from django.db import models from contatos.models import Contato from django import forms class FormContato(forms.ModelForm): class Meta: model = Contato # qual modelo esse formulario esta representando exclude = () # se irao ter campos que nao devem aparecer no template renderizado
{"/agenda/accounts/views.py": ["/agenda/accounts/models.py"], "/agenda/contatos/views.py": ["/agenda/contatos/models.py"], "/BlogDjango/posts/views.py": ["/BlogDjango/posts/models.py"], "/agenda/contatos/admin.py": ["/agenda/contatos/models.py"], "/vdjango/blog/comentarios/forms.py": ["/vdjango/blog/comentarios/models.py"], "/vdjango/blog/comentarios/admin.py": ["/vdjango/blog/comentarios/models.py"]}
59,338
AdrianaViabL/PycharmProjectsDjango
refs/heads/main
/agenda/contatos/views.py
from django.shortcuts import render, get_object_or_404, redirect from django.http import Http404 from .models import Contato from django.core.paginator import Paginator from django.db.models import Q, Value from django.db.models.functions import Concat from django.contrib import messages def index(request): contatos = Contato.objects.order_by('-id').filter( mostrar=True ) paginator = Paginator(contatos, 5) page = request.GET.get('p') contatos = paginator.get_page(page) return render(request, 'contatos/index.html', { 'contatos': contatos }) def ver_contato(request, contato_id): # forma 1 de tratar o erro 404 # try: # contato = Contato.objects.get(id=contato_id) # return render(request, 'contatos/ver_contato.html', { # 'contato': contato # }) # except Contato.DoesNotExist as e: # raise Http404() contato = get_object_or_404(Contato, id=contato_id) if not contato.mostrar: raise Http404() return render(request, 'contatos/ver_contato.html', { 'contato': contato }) def busca(request): termo = request.GET.get('termo') # pegando o valor que esta sendo digitado no campo 'termo' if termo is None or not termo: messages.add_message(request, messages.ERROR, 'Campo termo não pode ficar vazio.') return redirect('index') #nome da view que ele vai ser redirecionado campos = Concat('nome', Value(' '), 'sobrenome') # forma de pesquisa usando os campos 'nome' e 'sobrenome' de forma separada # contatos = Contato.objects.order_by('-id').filter( # Q(nome__icontains=termo) | Q(sobrenome__icontains=termo), # mostrar=True # ) contatos = Contato.objects.annotate( nome_completo=campos ).filter( Q(nome_completo__icontains=termo) | Q(telefone__icontains=termo) ) paginator = Paginator(contatos, 5) page = request.GET.get('p') contatos = paginator.get_page(page) return render(request, 'contatos/busca.html', { 'contatos': contatos })
{"/agenda/accounts/views.py": ["/agenda/accounts/models.py"], "/agenda/contatos/views.py": ["/agenda/contatos/models.py"], "/BlogDjango/posts/views.py": ["/BlogDjango/posts/models.py"], "/agenda/contatos/admin.py": ["/agenda/contatos/models.py"], "/vdjango/blog/comentarios/forms.py": ["/vdjango/blog/comentarios/models.py"], "/vdjango/blog/comentarios/admin.py": ["/vdjango/blog/comentarios/models.py"]}
59,339
AdrianaViabL/PycharmProjectsDjango
refs/heads/main
/BlogDjango/posts/views.py
from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic.list import ListView from django.views.generic.edit import UpdateView from .models import Post from django.db.models import Q, Count, Case, When from categoria.models import Categoria from comentarios.forms import FormComentario, Comentario from django.contrib import messages from django.views import View class PostIndex(ListView): model = Post # sobrescrevendo as variaveis vindas do ListView template_name = 'posts/index.html' paginate_by = 3 context_object_name = 'posts' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['categorias'] = Categoria.objects.all() return context def get_queryset(self): qs = super().get_queryset() # chamando o comando responsavel pelo query dos posts e alterando a ordem dos dados qs = qs.select_related('categoria_post') qs = qs.order_by('-id').filter(publicado_post=True) qs = qs.annotate( num_comentarios=Count( Case( When(comentario__publicado_comentario=True, then=1) ) ) ) return qs class PostBusca(PostIndex): template_name = 'posts/post_busca.html' def get_queryset(self): qs = super().get_queryset() termo = self.request.GET.get('termo') if not termo: return qs qs = qs.filter( Q(titulo_post__icontains=termo) | Q(autor_post__first_name__iexact=termo) | # por ser uma foreing key usar iexact Q(conteudo_post__icontains=termo) | # por ser uma foreing key usar iexact Q(excerto_post__icontains=termo) | # por ser uma foreing key usar iexact Q(categoria_post__nome_cat__iexact=termo) # por ser uma foreing key usar iexact ) return qs class PostCategoria(PostIndex): template_name = 'posts/post_categoria.html' def get_queryset(self): qs = super().get_queryset() categoria = self.kwargs.get('categoria', None) if not categoria: return qs qs = qs.filter(categoria_post__nome_cat__iexact=categoria) return qs class PostDetalhes(View): template_name = 'posts/post_detalhes.html' def setup(self, request, *args, **kwargs): super().setup(request, *args, **kwargs) pk = self.kwargs.get('pk') post = get_object_or_404(Post, pk=pk, publicado_post=True) self.contexto = { 'post': post, 'comentarios': Comentario.objects.filter(post_comentario=post, publicado_comentario=True), 'form': FormComentario(request.POST or None), } def get(self, request, *args, **kwargs): return render(request, self.template_name, self.contexto) def post(self, request, *args, **kwargs): form = self.contexto['form'] if not form.is_valid(): return render(request, self.template_name, self.contexto) comentario = form.save(commit=False) if request.user.is_authenticated: comentario.usuario_comentario = request.user comentario.post_comentario = self.contexto['post'] comentario.save() messages.success(request, 'seu comentario foi enviado para revisão') return redirect('post_detalhes', pk=self.kwargs.get('pk')) # primeira forma de criar a classe PostDetalhes, usando a classe UpdateView # class PostDetalhes(UpdateView): # template_name = 'posts/post_detalhes.html' # model = Post # form_class = FormComentario # context_object_name = 'post' # # def get_context_data(self, **kwargs): # contexto = super().get_context_data(**kwargs) # post = self.get_object() #pegando o post onde estamos no momento # comentarios = Comentario.objects.filter( # publicado_comentario=True, # post_comentario=post.id # ) # contexto['comentarios'] = comentarios # return contexto # # def form_valid(self, form): # post = self.get_object() # comentario = Comentario(**form.cleaned_data) # comentario.post_comentario = post # # if self.request.user.is_authenticated: # comentario.usuario_comentario = self.request.user # # comentario.save() # messages.success(self.request, 'Comentario enviado com sucesso!') # return redirect('post_detalhes', pk=post.id)
{"/agenda/accounts/views.py": ["/agenda/accounts/models.py"], "/agenda/contatos/views.py": ["/agenda/contatos/models.py"], "/BlogDjango/posts/views.py": ["/BlogDjango/posts/models.py"], "/agenda/contatos/admin.py": ["/agenda/contatos/models.py"], "/vdjango/blog/comentarios/forms.py": ["/vdjango/blog/comentarios/models.py"], "/vdjango/blog/comentarios/admin.py": ["/vdjango/blog/comentarios/models.py"]}
59,340
AdrianaViabL/PycharmProjectsDjango
refs/heads/main
/vdjango/blog/posts/templatetags/afilters.py
from django import template register = template.Library() @register.filter() def plural_comentarios(num_coment): try: num_coment = int(num_coment) if num_coment == 0: return f'Nenhum comentario' elif num_coment == 1: return f'{num_coment} comentario' else: return f'{num_coment} comentarios' except: return f'{num_coment} comentario(s)'
{"/agenda/accounts/views.py": ["/agenda/accounts/models.py"], "/agenda/contatos/views.py": ["/agenda/contatos/models.py"], "/BlogDjango/posts/views.py": ["/BlogDjango/posts/models.py"], "/agenda/contatos/admin.py": ["/agenda/contatos/models.py"], "/vdjango/blog/comentarios/forms.py": ["/vdjango/blog/comentarios/models.py"], "/vdjango/blog/comentarios/admin.py": ["/vdjango/blog/comentarios/models.py"]}
59,341
AdrianaViabL/PycharmProjectsDjango
refs/heads/main
/agenda/contatos/admin.py
from django.contrib import admin from .models import Categoria, Contato class ContatoAdmin(admin.ModelAdmin): list_display = ('id', 'nome', 'sobrenome', 'telefone', 'email', 'data_criacao', 'categoria', 'mostrar') list_display_links = ('id', 'nome', 'sobrenome') list_per_page = 5 search_fields = ('nome', 'sobrenome') admin.site.register(Categoria) admin.site.register(Contato, ContatoAdmin)
{"/agenda/accounts/views.py": ["/agenda/accounts/models.py"], "/agenda/contatos/views.py": ["/agenda/contatos/models.py"], "/BlogDjango/posts/views.py": ["/BlogDjango/posts/models.py"], "/agenda/contatos/admin.py": ["/agenda/contatos/models.py"], "/vdjango/blog/comentarios/forms.py": ["/vdjango/blog/comentarios/models.py"], "/vdjango/blog/comentarios/admin.py": ["/vdjango/blog/comentarios/models.py"]}
59,342
AdrianaViabL/PycharmProjectsDjango
refs/heads/main
/BlogDjango/posts/urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.PostIndex.as_view(), name='index'), path('categoria/<str:categoria>', views.PostCategoria.as_view(), name='post_categoria'), path('busca/', views.PostBusca.as_view(), name='post_busca'), path('post/<int:pk>', views.PostDetalhes.as_view(), name='post_detalhes'), ]
{"/agenda/accounts/views.py": ["/agenda/accounts/models.py"], "/agenda/contatos/views.py": ["/agenda/contatos/models.py"], "/BlogDjango/posts/views.py": ["/BlogDjango/posts/models.py"], "/agenda/contatos/admin.py": ["/agenda/contatos/models.py"], "/vdjango/blog/comentarios/forms.py": ["/vdjango/blog/comentarios/models.py"], "/vdjango/blog/comentarios/admin.py": ["/vdjango/blog/comentarios/models.py"]}
59,343
AdrianaViabL/PycharmProjectsDjango
refs/heads/main
/vdjango/blog/comentarios/forms.py
from django.forms import ModelForm from .models import Comentario class FormComentario(ModelForm): def clean(self): data = self.cleaned_data nome = data.get('nome_comentario') email = data.get('email_comentario') comentario = data.get('comentario') if len(nome) < 5: self.add_error( 'nome_comentario', 'Nome precisa ter mais de 5 caracteres.' ) if len(comentario) < 10: self.add_error( 'comentario', 'Insira um comentario maior que 10 caracteres' ) class Meta: model = Comentario fields = ('nome_comentario', 'email_comentario', 'comentario')
{"/agenda/accounts/views.py": ["/agenda/accounts/models.py"], "/agenda/contatos/views.py": ["/agenda/contatos/models.py"], "/BlogDjango/posts/views.py": ["/BlogDjango/posts/models.py"], "/agenda/contatos/admin.py": ["/agenda/contatos/models.py"], "/vdjango/blog/comentarios/forms.py": ["/vdjango/blog/comentarios/models.py"], "/vdjango/blog/comentarios/admin.py": ["/vdjango/blog/comentarios/models.py"]}
59,344
AdrianaViabL/PycharmProjectsDjango
refs/heads/main
/vdjango/blog/posts/migrations/0002_auto_20201221_1710.py
# Generated by Django 3.1.4 on 2020-12-21 20:10 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('categoria', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('posts', '0001_initial'), ] operations = [ migrations.AlterField( model_name='post', name='autor_post', field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL, verbose_name='Autor'), ), migrations.AlterField( model_name='post', name='categoria_post', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='categoria.categoria', verbose_name='categoria'), ), migrations.AlterField( model_name='post', name='conteudo_post', field=models.TextField(verbose_name='Conteúdo'), ), migrations.AlterField( model_name='post', name='data_post', field=models.DateTimeField(default=django.utils.timezone.now, verbose_name='data'), ), migrations.AlterField( model_name='post', name='excerto_post', field=models.TextField(verbose_name='excerto'), ), migrations.AlterField( model_name='post', name='imagem_post', field=models.ImageField(blank=True, null=True, upload_to='post_img/%Y/%m', verbose_name='Imagem'), ), migrations.AlterField( model_name='post', name='publicado_post', field=models.BooleanField(default=False, verbose_name='publicado'), ), migrations.AlterField( model_name='post', name='titulo_post', field=models.CharField(max_length=255, verbose_name='Títilo'), ), ]
{"/agenda/accounts/views.py": ["/agenda/accounts/models.py"], "/agenda/contatos/views.py": ["/agenda/contatos/models.py"], "/BlogDjango/posts/views.py": ["/BlogDjango/posts/models.py"], "/agenda/contatos/admin.py": ["/agenda/contatos/models.py"], "/vdjango/blog/comentarios/forms.py": ["/vdjango/blog/comentarios/models.py"], "/vdjango/blog/comentarios/admin.py": ["/vdjango/blog/comentarios/models.py"]}
59,345
AdrianaViabL/PycharmProjectsDjango
refs/heads/main
/vdjango/blog/comentarios/models.py
from django.db import models from posts.models import Post from django.contrib.auth.models import User from django.utils import timezone class Comentario(models.Model): nome_comentario = models.CharField(max_length=155, verbose_name='Nome') email_comentario = models.EmailField(verbose_name='E-mail') comentario = models.TextField() post_comentario = models.ForeignKey(Post, on_delete=models.CASCADE) usuario_comentario = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True, null=True) data_comentario = models.DateTimeField(default=timezone.now) publicado_comentario = models.BooleanField(default=False) def __str__(self): return self.nome_comentario
{"/agenda/accounts/views.py": ["/agenda/accounts/models.py"], "/agenda/contatos/views.py": ["/agenda/contatos/models.py"], "/BlogDjango/posts/views.py": ["/BlogDjango/posts/models.py"], "/agenda/contatos/admin.py": ["/agenda/contatos/models.py"], "/vdjango/blog/comentarios/forms.py": ["/vdjango/blog/comentarios/models.py"], "/vdjango/blog/comentarios/admin.py": ["/vdjango/blog/comentarios/models.py"]}
59,346
AdrianaViabL/PycharmProjectsDjango
refs/heads/main
/vdjango/blog/comentarios/admin.py
from django.contrib import admin from .models import Comentario class ComentariosAdmin(admin.ModelAdmin): list_display = ('id', 'nome_comentario', 'email_comentario', 'post_comentario', 'data_comentario', 'publicado_comentario') list_editable = ('publicado_comentario',) list_display_links = ('id', 'nome_comentario', 'email_comentario',) admin.site.register(Comentario, ComentariosAdmin)
{"/agenda/accounts/views.py": ["/agenda/accounts/models.py"], "/agenda/contatos/views.py": ["/agenda/contatos/models.py"], "/BlogDjango/posts/views.py": ["/BlogDjango/posts/models.py"], "/agenda/contatos/admin.py": ["/agenda/contatos/models.py"], "/vdjango/blog/comentarios/forms.py": ["/vdjango/blog/comentarios/models.py"], "/vdjango/blog/comentarios/admin.py": ["/vdjango/blog/comentarios/models.py"]}
59,347
AdrianaViabL/PycharmProjectsDjango
refs/heads/main
/BlogDjango/posts/models.py
from django.db import models from categoria.models import Categoria from django.contrib.auth.models import User from django.utils import timezone from PIL import Image from django.conf import settings import os class Post(models.Model): titulo_post = models.CharField(max_length=255, verbose_name='Títilo') autor_post = models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name='Autor') data_post = models.DateTimeField(default=timezone.now, verbose_name='data') conteudo_post = models.TextField(verbose_name='Conteúdo') excerto_post = models.TextField(verbose_name='excerto') categoria_post = models.ForeignKey(Categoria, on_delete=models.DO_NOTHING, blank=True, null=True, verbose_name='categoria') imagem_post = models.ImageField(upload_to='post_img/%Y/%m', blank=True, null=True, verbose_name='Imagem') publicado_post = models.BooleanField(default=False, verbose_name='publicado') def __str__(self): return self.titulo_post def save(self, *args, **kwargs): super().save(*args, **kwargs) # repassando e salvando qualquer alteração no template (quando chamado) self.resize_image(self.imagem_post.name, 800) @staticmethod # é estatico pois nao vai alterar nada dentro da classe def resize_image(nome_imagem, nova_largura): img_path = os.path.join(settings.MEDIA_ROOT, nome_imagem) img = Image.open(img_path) width, height = img.size print(width, height, nova_largura) new_height = round((nova_largura * height) / width) if width <= nova_largura: img.close() return nova_img = img.resize((nova_largura, new_height), Image.ANTIALIAS) nova_img.save( img_path, optimize=True, quality=60 ) nova_img.close()
{"/agenda/accounts/views.py": ["/agenda/accounts/models.py"], "/agenda/contatos/views.py": ["/agenda/contatos/models.py"], "/BlogDjango/posts/views.py": ["/BlogDjango/posts/models.py"], "/agenda/contatos/admin.py": ["/agenda/contatos/models.py"], "/vdjango/blog/comentarios/forms.py": ["/vdjango/blog/comentarios/models.py"], "/vdjango/blog/comentarios/admin.py": ["/vdjango/blog/comentarios/models.py"]}
59,352
maakolk/Majo
refs/heads/master
/rotaryEncoderGrayCode/helper/test_slicer.py
from rotaryEncoder.helper.slicer import Slices from unittest import TestCase class TestSlices(TestCase): def test_nextSector(self): sl = Slices(3, 180, 360); hasNext = True results = [] while hasNext: result = (sl.nextInterval()) hasNext = result[2] print(result) results.append(result) self.assertEquals(3, len(results)) self.assertEquals((180,240,True), results[0]) self.assertEquals((240,300,True), results[1]) self.assertEquals((300,360,False), results[2])
{"/rotaryEncoderGrayCode/helper/test_slicer.py": ["/rotaryEncoder/helper/slicer.py"], "/rotaryEncoderGrayCode/RotaryEncoderDiscFactory.py": ["/rotaryEncoder/helper/slicer.py"]}
59,353
maakolk/Majo
refs/heads/master
/Voltmeter/AnalogVoltmeter.py
import math import random import serial # import Serial Library import numpy # Import numpy from drawnow import * from matplotlib.animation import FuncAnimation BAUD = 9600 # 9600 or 500000 # https://stackoverflow.com/questions/5285912/how-can-i-create-a-frontend-for-matplotlib REFRESH_MS = 500 X_LIMIT_MS = 10000 X_TICKS_COUNT = 20 VOLTAGE_SHOW = True Y_LIMIT_VOLT = 5 Y_TICK_COUNTS = 5 # 5 or None for auto scaling Y_CHANNELS = 1024 FREQUENCIES_SHOW = False FREQUENCIES_LOG = False RATE_SHOW = False current_time = lambda: serial.time.time() class ArduinoConnection: SINUS_LENGTH_FRAMES = 650 arduinoConnection = None def __init__(self): self.count = -1 self.arduinoConnection = None def getRealData(self): first = False if (self.arduinoConnection == None): self.arduinoConnection = serial.Serial('com4', BAUD) # Creating our serial object named arduinoData first = True while (self.arduinoConnection.inWaiting() == 0): # Wait here until there is data pass # do nothing if first: for i in range(5): self.arduinoConnection.readline() return float(self.arduinoConnection.readline()) # read the line of text from the serial port def getSimulateData(self): self.count += 1 return ((math.sin(2 * math.pi * self.count / self.SINUS_LENGTH_FRAMES) + 1) + ( random.random() - 0.5) * 0.5 + 0.25) * 1024.0 / 2.5 def getData(self): return self.getRealData() timeValues = [] rateValues = [] connection = ArduinoConnection() end = [] refresh_ms = min(REFRESH_MS, X_LIMIT_MS) xTickNames = numpy.linspace(0, X_LIMIT_MS, X_TICKS_COUNT + 1, endpoint=True) if Y_TICK_COUNTS != None: yTickPositions = numpy.linspace(0, Y_CHANNELS, Y_TICK_COUNTS + 1, endpoint=True) yTickNames = numpy.linspace(0, Y_LIMIT_VOLT, Y_TICK_COUNTS + 1, endpoint=True) def update(frame): if len(timeValues) == 0: for i in range(25): connection.getData() end.append(current_time() + X_LIMIT_MS / 1000) else: skip = int(round(len(timeValues) * refresh_ms / X_LIMIT_MS)) del timeValues[:skip] del rateValues[:skip] current_tim = 0 while current_tim < end[0]: analog = connection.getData() timeValues.append(analog) current_tim = current_time() rateValues.append(current_tim) # print(analog) end[0] += refresh_ms / 1000 if len(timeValues) < 2: raise TimeoutError('No data found') if VOLTAGE_SHOW: makeTimePlot(axt, timeValues) if FREQUENCIES_SHOW: frequencyValues = executeFft() makeFrequencyPlot(axf, frequencyValues, len(timeValues)) if RATE_SHOW: makeDataRatePlot(axr, rateValues) def executeFft(): hann = numpy.hanning(len(timeValues)) frequencyValues = numpy.fft.fft(timeValues * hann) N = int(len(timeValues) / 2 ) frequencyValues = numpy.abs(frequencyValues[:N]) if FREQUENCIES_LOG: frequencyValues = numpy.log(frequencyValues + 0.001) return frequencyValues def makeDataRatePlot(ax, yValues): ax.clear() ax.grid(True) # Turn the grid on setXaxesTimeScaling(ax, yValues) ax.set_ylabel('Time') # Set ylabels ax.plot(yValues, 'b-', label='RATE') ax.legend(loc='upper left') # plot the legend def makeTimePlot(ax, yValues): ax.clear() ax.grid(True) # Turn the grid on setXaxesTimeScaling(ax, yValues) ax.set_ylabel('Voltage in Volt') # Set ylabels if Y_TICK_COUNTS != None: # Set to None for AutoScale ax.set_ylim(0, Y_CHANNELS) ax.set_yticks(yTickPositions) ax.yaxis.set_ticklabels(yTickNames) ax.plot(yValues, 'r-', label='A0') ax.legend(loc='upper left') # plot the legend def setXaxesTimeScaling(ax, yValues): ax.set_xlabel('Time in Milliseconds with ' + str( round(len(yValues) / X_LIMIT_MS * 1000)) + ' Data Samples per Second') # Set ylabels ax.set_xlim(0, len(yValues) - 1) if len(yValues) > 0: # Avoid divisions by zero # xTickPositions = Slices.arrangeSlicesIntegerArray(X_TICKS_COUNT, 0, len(yValues) - 1) xTickPositions = numpy.linspace(0, len(yValues) - 1, X_TICKS_COUNT + 1, endpoint=True) ax.set_xticks(xTickPositions) ax.xaxis.set_ticklabels(xTickNames) def makeFrequencyPlot(ax, yValues, samples): ax.clear() ax.grid(True) # Turn the grid on ax.set_ylabel('Amplitude') # Set ylabels ax.set_xlabel('Frequency in Kiloherz with ' + str(samples) + ' Samples') ax.set_xlim(0, len(yValues) - 1) if len(yValues) > 0: # Avoid divisions by zero # xTickPositions = Slices.arrangeSlicesIntegerArray(X_TICKS_COUNT, 0, len(yValues) - 1) xTickPositions = numpy.linspace(0, len(yValues) - 1, X_TICKS_COUNT + 1, endpoint=True) ax.set_xticks(xTickPositions) fMax = 0.5 * samples / X_LIMIT_MS xTickNamesF = numpy.linspace(0, fMax, X_TICKS_COUNT + 1, endpoint=True) for i in range(0, len(xTickNamesF)): xTickNamesF[i] = round(xTickNamesF[i] * 1000) / 1000 ax.xaxis.set_ticklabels(xTickNamesF) for i in range(0, 2): yValues[i] = 0 ax.plot(yValues, 'g-', label='A0') ax.legend(loc='upper left') # plot the legend fig = plt.figure(figsize=(23, 12), dpi=80) plot = 10 if VOLTAGE_SHOW: plot += 100; if FREQUENCIES_SHOW: plot += 100; if RATE_SHOW: plot += 100; if VOLTAGE_SHOW: plot +=1 axt = fig.add_subplot(plot) if FREQUENCIES_SHOW: plot +=1 axf = fig.add_subplot(plot) if RATE_SHOW: plot +=1 axr = fig.add_subplot(plot) animation = FuncAnimation(fig, update, interval=1, frames=10) plt.show()
{"/rotaryEncoderGrayCode/helper/test_slicer.py": ["/rotaryEncoder/helper/slicer.py"], "/rotaryEncoderGrayCode/RotaryEncoderDiscFactory.py": ["/rotaryEncoder/helper/slicer.py"]}
59,354
maakolk/Majo
refs/heads/master
/polarCoordinates/polarCoordinatesSimulateData.py
import math import random import patch as patch import serial # import Serial Library import numpy # Import numpy import matplotlib.pyplot as plt # import matplotlib library from drawnow import * from matplotlib.animation import FuncAnimation X_LIMIT = 100 class ArduinoConnection: arduinoConnection = None def __init__(self): self.count = -1 self.arduinoConnection = None def getRealData(self): if (self.arduinoConnection == None): self.arduinoConnection = serial.Serial('com6', 9600) # Creating our serial object named arduinoData while (self.arduinoConnection.inWaiting() == 0): # Wait here until there is data pass # do nothing return int(self.arduinoConnection.readline()) # read the line of text from the serial port def getSimulateData(self): self.count += 1 self.count = self.count % 40 print(self.count) return self.count connection = ArduinoConnection() def update(frame): angle = connection.getSimulateData() # < change to: .getRealData() alphaRad = 2 * numpy.pi * angle / 40. r = [0.0001, 1.9] theta = [alphaRad, alphaRad] ax = plt.subplot(111, ) ax.clear() ax.plot(theta, r, color="red") ax.set_rmax(2) ax.set_rticks([]) # less radial ticks ax.set_xticklabels(['E', 'NE', 'N', 'NW', 'W', 'SW', 'S', 'SE']) fig = plt.figure(figsize=(10, 10), dpi=80) ax = fig.add_subplot(111, projection='polar') animation = FuncAnimation(fig, update, interval=500, frames=10) # < change to: interval=1 plt.show()
{"/rotaryEncoderGrayCode/helper/test_slicer.py": ["/rotaryEncoder/helper/slicer.py"], "/rotaryEncoderGrayCode/RotaryEncoderDiscFactory.py": ["/rotaryEncoder/helper/slicer.py"]}
59,355
maakolk/Majo
refs/heads/master
/rotaryEncoder/helper/slicer.py
class Slices: def __init__(self, slicescount, begin, end): self.remainingSlicesCount = slicescount self.begin = begin self.end = begin self.remainder = end - begin def nextInterval(self): self.begin = self.end delta = self.remainder / self.remainingSlicesCount self.remainder -= delta self.end += delta self.remainingSlicesCount -= 1 return self.begin, self.end, self.remainingSlicesCount > 0 @staticmethod def arrangeSlicesIntegerArray(slicesCount, begin, end): slicer = Slices(slicesCount, begin, end) results = [] results.append(begin) hasNext = True while hasNext: begin, end, hasNext = slicer.nextInterval() results.append(end) return results
{"/rotaryEncoderGrayCode/helper/test_slicer.py": ["/rotaryEncoder/helper/slicer.py"], "/rotaryEncoderGrayCode/RotaryEncoderDiscFactory.py": ["/rotaryEncoder/helper/slicer.py"]}
59,356
maakolk/Majo
refs/heads/master
/polarCoordinates/polarCoordinates.py
""" https://matplotlib.org/examples/pylab_examples/polar_demo.html Demo of a line plot on a polar axis. """ import numpy as np import matplotlib.pyplot as plt # r = np.arange(0, 2, 0.01) # theta = 2 * np.pi * r alpha = 30.0 alphaRad = 2 * np.pi * alpha / 360. r = [0.0001, 2.0] theta = [alphaRad, alphaRad] ax = plt.subplot(111, projection='polar') ax.plot(theta, r, color = "red") ax.set_rmax(2) ax.set_rticks([]) # less radial ticks # ax.set_xticks(np.pi/180. * np.linspace(0, 360, 16, endpoint=False)) # ax.set_xticklabels(['E', '', 'N', '', 'W', '', 'S', '']) xT=plt.xticks()[0] xL=['0',r'$\frac{\pi}{4}$',r'$\frac{\pi}{2}$',r'$\frac{3\pi}{4}$',\ r'$\pi$',r'$\frac{5\pi}{4}$',r'$\frac{3\pi}{2}$',r'$\frac{7\pi}{4}$'] plt.xticks(xT, xL) ax.grid(True) plt.show()
{"/rotaryEncoderGrayCode/helper/test_slicer.py": ["/rotaryEncoder/helper/slicer.py"], "/rotaryEncoderGrayCode/RotaryEncoderDiscFactory.py": ["/rotaryEncoder/helper/slicer.py"]}
59,357
maakolk/Majo
refs/heads/master
/rotaryEncoderGrayCode/GrayCode.py
BIN_FORMAT = '05b' for i in range(0, 2 ** 5): j = i ^ (i >> 1) print(i, format(i, BIN_FORMAT), format(j, BIN_FORMAT)) for k in range(0, 5): print((j >> k) & 1) for k in range(4, -1, -1): print(k, '>>>>>>>>>>>>>>>>>>>>>>>>>>') for i in range(0, 2 ** 5): print((((i ^ (i >> 1)) >> k) & 1))
{"/rotaryEncoderGrayCode/helper/test_slicer.py": ["/rotaryEncoder/helper/slicer.py"], "/rotaryEncoderGrayCode/RotaryEncoderDiscFactory.py": ["/rotaryEncoder/helper/slicer.py"]}
59,358
maakolk/Majo
refs/heads/master
/rotaryEncoderGrayCode/RotaryEncoderDiscFactory.py
import matplotlib.pyplot as plt from matplotlib.collections import PatchCollection from matplotlib.patches import Wedge from rotaryEncoder.helper.slicer import Slices SEPARATOR_WIDTH = 0.0001 class RingTraveller: def __init__(self, n, begin, end): self.n = n self.tp = None self.rp = Slices(n, begin, end) self.begin = 0 self.end = 0 self.rpHasNext = False self.ring = n def nextRing(self): if self.tp == None: self.tp = Slices(2 ** self.n, 0, 360) self.begin, self.end, self.rpHasNext = self.rp.nextInterval() self.ring = self.ring - 1 self.segment = -1 theta1, theta2, hasNext = self.tp.nextInterval(); if not hasNext: self.tp = None self.segment = self.segment + 1 return self.begin, self.end, theta1, theta2, self.ring, self.segment, (hasNext | self.rpHasNext); class WedgeProvider: def __init__(self, n, inner, outer): self.count = 0 self.n = n self.rt = RingTraveller(n, inner, outer) def grayCode(self, segment): return segment ^ (segment >> 1) def colour(self, ring, segment): return (self.grayCode(segment) >> ring) & 1 def nextWedge(self, ax): begin, end, theta1, theta2, ring, segment, next = self.rt.nextRing() self.count += 1 colour = self.colour(ring, segment); invertedColour = int(not colour) print(begin, end, theta1, theta2, colour, ring, segment) ax.add_patch(Wedge((0, 0), end, theta1, theta2, width=end - begin, color=str(colour))) if ring > 0 and colour == self.colour(ring - 1, segment): ax.add_patch(Wedge((0, 0), end - SEPARATOR_WIDTH, theta1, theta2, width=SEPARATOR_WIDTH, color=str(invertedColour))) if ring == 0 and not invertedColour: ax.add_patch(Wedge((0, 0), end - SEPARATOR_WIDTH, theta1, theta2, width=SEPARATOR_WIDTH, color=str(invertedColour))) if ring == self.n -1 and not invertedColour: ax.add_patch(Wedge((0, 0), begin, theta1, theta2, width=SEPARATOR_WIDTH, color=str(invertedColour))) return next fig = plt.figure(figsize=(12, 12), dpi=80) ax = fig.add_subplot(111) ax.set_xlim(-1, 1) ax.set_ylim(-1, 1) next = True wp = WedgeProvider(5, 0.2, 1.0) while (next): next = wp.nextWedge(ax) fig.savefig("Rotary.jpg", dpi=500) plt.show() # Documentation # ============= # https://en.wikipedia.org/wiki/Rotary_encoder#Ways_of_encoding_shaft_position # https://de.wikipedia.org/wiki/Gray-Code # https://matplotlib.org/gallery/api/patch_collection.html#sphx-glr-gallery-api-patch-collection-py
{"/rotaryEncoderGrayCode/helper/test_slicer.py": ["/rotaryEncoder/helper/slicer.py"], "/rotaryEncoderGrayCode/RotaryEncoderDiscFactory.py": ["/rotaryEncoder/helper/slicer.py"]}
59,362
Jay54520/data-aggregrate-demo
refs/heads/master
/settings.py
# -*- coding: utf-8 -*- MONGO_URI = 'mongodb://localhost:27017/' PAY_DB = 'pay' TEST_PAY_DB = 'test_pay' ORDER_COLL = 'order' AGGREGATE_COLL = 'aggregate' LOCAL_TZ = 'Asia/Shanghai' DATE_TYPE_MINUTELY = 'minutely' DATE_TYPE_HOURLY = 'hourly' DATE_TYPE_DAILY = 'daily' DATE_TYPE_WEEKLY = 'weekly' DATE_TYPE_MONTHLY = 'monthly' DATE_TYPE_YEARLY = 'yearly' CREATED_TIME = 'created_time' TIME_START = 'time_start' PRICE = 'price' SALES = 'sales' DATE_TYPE = 'date_type'
{"/tests/test_aggregate_data.py": ["/settings.py", "/tasks.py", "/tests/conftest.py"], "/tasks.py": ["/settings.py", "/utils.py"], "/utils.py": ["/settings.py"], "/tests/test_create_order.py": ["/settings.py", "/tasks.py"], "/tests/conftest.py": ["/settings.py"]}
59,363
Jay54520/data-aggregrate-demo
refs/heads/master
/tests/test_aggregate_data.py
# -*- coding: utf-8 -*- import datetime import time import pytz from dateutil.relativedelta import relativedelta import settings from tasks import create_order, aggregate from tests.conftest import order_coll, aggregate_coll class TestAggregateData: def setup_class(self): self.order_coll = next(order_coll()) self.aggregate_coll = next(aggregate_coll()) def _generate_data(self, date_type, end_time=None): end_time = end_time or datetime.datetime.now(pytz.timezone(settings.LOCAL_TZ)) if date_type == settings.DATE_TYPE_MINUTELY: create_order(use_test_db=True, created_time=end_time - datetime.timedelta(minutes=2)) create_order(use_test_db=True, created_time=end_time - datetime.timedelta(minutes=1)) elif date_type == settings.DATE_TYPE_HOURLY: create_order(use_test_db=True, created_time=end_time - datetime.timedelta(minutes=2), date_type=settings.DATE_TYPE_MINUTELY) create_order(use_test_db=True, created_time=end_time - datetime.timedelta(minutes=1), date_type=settings.DATE_TYPE_MINUTELY) elif date_type == settings.DATE_TYPE_DAILY: create_order(use_test_db=True, created_time=end_time - datetime.timedelta(hours=2), date_type=settings.DATE_TYPE_HOURLY) create_order(use_test_db=True, created_time=end_time - datetime.timedelta(hours=1), date_type=settings.DATE_TYPE_HOURLY) elif date_type == settings.DATE_TYPE_WEEKLY: create_order(use_test_db=True, created_time=end_time - datetime.timedelta(days=2), date_type=settings.DATE_TYPE_DAILY) create_order(use_test_db=True, created_time=end_time - datetime.timedelta(days=1), date_type=settings.DATE_TYPE_DAILY) elif date_type == settings.DATE_TYPE_MONTHLY: create_order(use_test_db=True, created_time=end_time - datetime.timedelta(days=2), date_type=settings.DATE_TYPE_DAILY) create_order(use_test_db=True, created_time=end_time - datetime.timedelta(days=1), date_type=settings.DATE_TYPE_DAILY) elif date_type == settings.DATE_TYPE_YEARLY: create_order(use_test_db=True, created_time=end_time - relativedelta(months=2), date_type=settings.DATE_TYPE_MONTHLY) create_order(use_test_db=True, created_time=end_time - relativedelta(months=1), date_type=settings.DATE_TYPE_MONTHLY) else: raise ValueError('日期类型不正确') def teardown_method(self): self.order_coll.database.client.drop_database(settings.TEST_PAY_DB) def test_minutely(self): local_now = datetime.datetime( 2016, 1, 1, tzinfo=pytz.timezone(settings.LOCAL_TZ) ) self._generate_data(settings.DATE_TYPE_MINUTELY, local_now) async_result = aggregate(use_test_db=True, local_now=local_now) self.is_task_success(async_result) docs = list(self.aggregate_coll.find({ settings.DATE_TYPE: settings.DATE_TYPE_MINUTELY })) assert len(docs) == 1 doc = docs[0] assert doc[settings.DATE_TYPE] == settings.DATE_TYPE_MINUTELY assert doc[settings.SALES] == 1 def test_hourly(self): local_now = datetime.datetime( 2016, 1, 1, tzinfo=pytz.timezone(settings.LOCAL_TZ) ) self._generate_data(settings.DATE_TYPE_HOURLY, local_now) async_result = aggregate(use_test_db=True, local_now=local_now) self.is_task_success(async_result) docs = list(self.aggregate_coll.find({ settings.DATE_TYPE: settings.DATE_TYPE_HOURLY })) assert len(docs) == 1 doc = docs[0] assert doc[settings.DATE_TYPE] == settings.DATE_TYPE_HOURLY assert doc[settings.SALES] == 2 def test_daily(self): local_now = datetime.datetime( 2016, 1, 1, tzinfo=pytz.timezone(settings.LOCAL_TZ) ) self._generate_data(settings.DATE_TYPE_DAILY, local_now) async_result = aggregate(use_test_db=True, local_now=local_now) self.is_task_success(async_result) docs = list(self.aggregate_coll.find({ settings.DATE_TYPE: settings.DATE_TYPE_DAILY })) assert len(docs) == 1 doc = docs[0] assert doc[settings.DATE_TYPE] == settings.DATE_TYPE_DAILY assert doc[settings.SALES] == 2 def test_weekly(self): local_now = datetime.datetime( 2016, 1, 4, tzinfo=pytz.timezone(settings.LOCAL_TZ) ) self._generate_data(settings.DATE_TYPE_WEEKLY, local_now) async_result = aggregate(use_test_db=True, local_now=local_now) self.is_task_success(async_result) docs = list(self.aggregate_coll.find({ settings.DATE_TYPE: settings.DATE_TYPE_WEEKLY })) assert len(docs) == 1 doc = docs[0] assert doc[settings.DATE_TYPE] == settings.DATE_TYPE_WEEKLY assert doc[settings.SALES] == 2 def test_monthly(self): local_now = datetime.datetime( 2016, 1, 1, tzinfo=pytz.timezone(settings.LOCAL_TZ) ) self._generate_data(settings.DATE_TYPE_MONTHLY, local_now) async_result = aggregate(use_test_db=True, local_now=local_now) self.is_task_success(async_result) docs = list(self.aggregate_coll.find({ settings.DATE_TYPE: settings.DATE_TYPE_MONTHLY })) assert len(docs) == 1 doc = docs[0] assert doc[settings.DATE_TYPE] == settings.DATE_TYPE_MONTHLY assert doc[settings.SALES] == 2 def test_yearly(self): local_now = datetime.datetime( 2016, 1, 1, tzinfo=pytz.timezone(settings.LOCAL_TZ) ) self._generate_data(settings.DATE_TYPE_YEARLY, local_now) async_result = aggregate(use_test_db=True, local_now=local_now) self.is_task_success(async_result) docs = list(self.aggregate_coll.find({ settings.DATE_TYPE: settings.DATE_TYPE_YEARLY })) assert len(docs) == 1 doc = docs[0] assert doc[settings.DATE_TYPE] == settings.DATE_TYPE_YEARLY assert doc[settings.SALES] == 2 def is_task_success(self, async_result): counter = 0 while not async_result.successful(): if counter > 30: raise Exception('任务超时') time.sleep(0.1) counter += 1 return True
{"/tests/test_aggregate_data.py": ["/settings.py", "/tasks.py", "/tests/conftest.py"], "/tasks.py": ["/settings.py", "/utils.py"], "/utils.py": ["/settings.py"], "/tests/test_create_order.py": ["/settings.py", "/tasks.py"], "/tests/conftest.py": ["/settings.py"]}
59,364
Jay54520/data-aggregrate-demo
refs/heads/master
/tasks.py
# -*- coding: utf-8 -*- import datetime import pytz from celery import Celery from dateutil.relativedelta import relativedelta import settings from utils import get_collections app = Celery( 'tasks', broker="redis://127.0.0.1:6379/1", backend="redis://127.0.0.1:6379/0", ) app.conf.task_serializer = 'pickle' app.conf.result_serializer = 'pickle' app.conf.accept_content = ['pickle'] app.conf.task_routes = { 'tasks._calculate_sales': {'queue': 'aggregate'}, 'tasks.aggregate': {'queue': 'aggregate'}, } @app.task def create_order(use_test_db=False, created_time=None, date_type=None): """生成数据价格为 1 的,创建时间为当前时间的订单""" collections = get_collections(use_test_db) order_coll = collections[settings.ORDER_COLL] aggregate_coll = collections[settings.AGGREGATE_COLL] if date_type: aggregate_coll.insert({ settings.TIME_START: created_time or datetime.datetime.utcnow(), settings.PRICE: 1, settings.DATE_TYPE: date_type }) else: order_coll.insert({ settings.CREATED_TIME: created_time or datetime.datetime.utcnow(), settings.PRICE: 1, }) @app.task def _calculate_sales(match_condition, aggregate_date_type, use_test_db=False): """根据 match_condition,计算出销售额""" collections = get_collections(use_test_db) order_coll = collections[settings.ORDER_COLL] aggregate_coll = collections[settings.AGGREGATE_COLL] if aggregate_date_type == settings.DATE_TYPE_MINUTELY: result = list(order_coll.aggregate([ {'$match': match_condition}, {'$group': {'_id': None, settings.SALES: {'$sum': '${}'.format(settings.PRICE)}}} ])) time_key = settings.CREATED_TIME else: result = list(aggregate_coll.aggregate([ {'$match': match_condition}, {'$group': {'_id': None, settings.SALES: {'$sum': '${}'.format(settings.PRICE)}}} ])) time_key = settings.TIME_START # 如果没有匹配的记录,那么销售额是 0 sales = 0 if not result else result[0][settings.SALES] aggregate_coll.update_one( { settings.DATE_TYPE: aggregate_date_type, time_key: match_condition[time_key]['$gte'], }, {'$set': {settings.SALES: sales}}, upsert=True ) @app.task def aggregate(use_test_db=False, local_now=None): local_now = local_now or datetime.datetime.now(pytz.timezone(settings.LOCAL_TZ)) # 聚合上一分钟数据 current_minute = local_now.replace(microsecond=0) last_minute = current_minute - datetime.timedelta(minutes=1) signature = _calculate_sales.si( match_condition={ settings.CREATED_TIME: {'$gte': last_minute, '$lt': current_minute}, }, aggregate_date_type=settings.DATE_TYPE_MINUTELY, use_test_db=use_test_db ) # 聚合上一小时的数据 if local_now.minute == 0: current_hour = local_now.replace(second=0, microsecond=0) last_hour = current_minute - datetime.timedelta(hours=1) signature |= _calculate_sales.si( match_condition={ settings.TIME_START: {'$gte': last_hour, '$lt': current_hour}, settings.DATE_TYPE: settings.DATE_TYPE_MINUTELY }, aggregate_date_type=settings.DATE_TYPE_HOURLY, use_test_db=use_test_db ) # 聚合昨天的数据 if local_now.hour == 0 and local_now.minute == 0: current_day = local_now.replace(second=0, microsecond=0) last_day = current_minute - datetime.timedelta(days=1) signature |= _calculate_sales.si( match_condition={ settings.TIME_START: {'$gte': last_day, '$lt': current_day}, settings.DATE_TYPE: settings.DATE_TYPE_HOURLY }, aggregate_date_type=settings.DATE_TYPE_DAILY, use_test_db=use_test_db ) # 聚合上一周的数据 if local_now.isoweekday() == 1 and local_now.hour == 0 and local_now.minute == 0: current_monday = local_now.replace(second=0, microsecond=0) last_monday = current_minute - datetime.timedelta(weeks=1) signature |= _calculate_sales.si( match_condition={ settings.TIME_START: {'$gte': last_monday, '$lt': current_monday}, settings.DATE_TYPE: settings.DATE_TYPE_DAILY }, aggregate_date_type=settings.DATE_TYPE_WEEKLY, use_test_db=use_test_db ) # 聚合上一月的数据 if local_now.day == 1 and local_now.hour == 0 and local_now.minute == 0: current_month = local_now.replace(second=0, microsecond=0) last_month = current_month - relativedelta(months=1) signature |= _calculate_sales.si( match_condition={ settings.TIME_START: {'$gte': last_month, '$lt': current_month}, settings.DATE_TYPE: settings.DATE_TYPE_DAILY }, aggregate_date_type=settings.DATE_TYPE_MONTHLY, use_test_db=use_test_db ) # 聚合上一年的数据 if local_now.month == 1 and local_now.day == 1 and local_now.hour == 0 and \ local_now.minute == 0: current_year = local_now.replace(second=0, microsecond=0) last_year = current_year - relativedelta(years=1) signature |= _calculate_sales.si( match_condition={ settings.TIME_START: {'$gte': last_year, '$lt': current_year}, settings.DATE_TYPE: settings.DATE_TYPE_MONTHLY }, aggregate_date_type=settings.DATE_TYPE_YEARLY, use_test_db=use_test_db ) return signature()
{"/tests/test_aggregate_data.py": ["/settings.py", "/tasks.py", "/tests/conftest.py"], "/tasks.py": ["/settings.py", "/utils.py"], "/utils.py": ["/settings.py"], "/tests/test_create_order.py": ["/settings.py", "/tasks.py"], "/tests/conftest.py": ["/settings.py"]}
59,365
Jay54520/data-aggregrate-demo
refs/heads/master
/utils.py
# -*- coding: utf-8 -*- from pymongo import MongoClient import settings def get_collections(use_test_db=False): """ 获取数据表 :param use_test_db: 是否使用测试数据库 :return: {'collection_name': collection} """ if use_test_db: order_coll = MongoClient(settings.MONGO_URI)[settings.TEST_PAY_DB][settings.ORDER_COLL] aggregate_coll = MongoClient(settings.MONGO_URI)[settings.TEST_PAY_DB][settings.AGGREGATE_COLL] else: order_coll = MongoClient(settings.MONGO_URI)[settings.PAY_DB][settings.ORDER_COLL] aggregate_coll = MongoClient(settings.MONGO_URI)[settings.PAY_DB][settings.AGGREGATE_COLL] return { settings.ORDER_COLL: order_coll, settings.AGGREGATE_COLL: aggregate_coll }
{"/tests/test_aggregate_data.py": ["/settings.py", "/tasks.py", "/tests/conftest.py"], "/tasks.py": ["/settings.py", "/utils.py"], "/utils.py": ["/settings.py"], "/tests/test_create_order.py": ["/settings.py", "/tasks.py"], "/tests/conftest.py": ["/settings.py"]}
59,366
Jay54520/data-aggregrate-demo
refs/heads/master
/tests/test_create_order.py
# -*- coding: utf-8 -*- import datetime import settings from tasks import create_order class TestCreateOrder: def test_create_order(cls, order_coll): create_order(order_coll) orders = list(order_coll.find()) assert len(orders) == 1 assert orders[0][settings.PRICE] == 1 def test_create_order_with_time(cls, order_coll): created_time = datetime.datetime(2017, 1, 1) create_order(order_coll, created_time) assert order_coll.find_one()[settings.CREATED_TIME] == created_time
{"/tests/test_aggregate_data.py": ["/settings.py", "/tasks.py", "/tests/conftest.py"], "/tasks.py": ["/settings.py", "/utils.py"], "/utils.py": ["/settings.py"], "/tests/test_create_order.py": ["/settings.py", "/tasks.py"], "/tests/conftest.py": ["/settings.py"]}
59,367
Jay54520/data-aggregrate-demo
refs/heads/master
/tests/conftest.py
# -*- coding: utf-8 -*- import pytest from pymongo import MongoClient import settings @pytest.fixture def order_coll(): yield MongoClient(settings.MONGO_URI)[settings.TEST_PAY_DB][settings.ORDER_COLL] MongoClient(settings.MONGO_URI).drop_database(settings.TEST_PAY_DB) @pytest.fixture def aggregate_coll(): yield MongoClient(settings.MONGO_URI)[settings.TEST_PAY_DB][settings.AGGREGATE_COLL] MongoClient(settings.MONGO_URI).drop_database(settings.TEST_PAY_DB)
{"/tests/test_aggregate_data.py": ["/settings.py", "/tasks.py", "/tests/conftest.py"], "/tasks.py": ["/settings.py", "/utils.py"], "/utils.py": ["/settings.py"], "/tests/test_create_order.py": ["/settings.py", "/tasks.py"], "/tests/conftest.py": ["/settings.py"]}
59,368
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py
# openstack_dashboard.local.dashboards.project_nci.vlconfig.forms # # Copyright (c) 2015, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import datetime import json import logging #import pdb ## DEBUG import re import sys import uuid from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from openstack_dashboard import api from openstack_dashboard.local.nci import crypto as ncicrypto from openstack_dashboard.local.nci.constants import * LOG = logging.getLogger(__name__) SPECIAL_FIELDS_REGEX = r"(repo_key|eyaml)" class VLConfigForm(forms.SelfHandlingForm): puppet_action = forms.ChoiceField( label=_("Default Puppet Action"), required=True, choices=[("auto", _("Automatic"))] + PUPPET_ACTION_CHOICES, help_text=_("Default Puppet command to execute. This value can be overridden in the launch instance dialog.")) puppet_env = forms.RegexField( label=_("Default Puppet Environment"), required=True, regex=REPO_BRANCH_REGEX, help_text=_("Default Puppet configuration environment (or branch name). This value can be overridden in the launch instance dialog.")) repo_path = forms.RegexField( label=_("Puppet Repository Path"), required=True, regex=REPO_PATH_REGEX, help_text=_("Path component of the Puppet configuration repository URL.")) repo_key_public = forms.CharField( widget=forms.Textarea(attrs={"readonly": True}), label=_("Public Deployment Key"), required=False) repo_key_fp = forms.CharField( widget=forms.TextInput(attrs={"readonly": True}), label=_("Deployment Key Fingerprint"), required=False) repo_key_create = forms.BooleanField( label=_("Create New Deployment Key"), required=False, initial=True, help_text=_("Generates a new SSH key for deploying the Puppet configuration repository.")) eyaml_key_fp = forms.CharField( widget=forms.TextInput(attrs={"readonly": True}), label=_("Hiera eyaml Key Fingerprint"), required=False) eyaml_key_upload = forms.FileField( label=_("Import Hiera eyaml Key"), required=False) eyaml_cert_fp = forms.CharField( widget=forms.TextInput(attrs={"readonly": True}), label=_("Hiera eyaml Certificate Fingerprint"), required=False) eyaml_cert_upload = forms.FileField( label=_("Import Hiera eyaml Certificate"), required=False) eyaml_update = forms.ChoiceField( label=_("Modify Hiera eyaml Certificate/Key Pair"), required=False, choices=[ ("", _("No Change")), ("create", _("Create New")), ("import", _("Import")), ], initial="create", help_text=_("Create or import a certificate/key pair for encrypting data in Hiera.")) revision = forms.CharField( widget=forms.HiddenInput(), required=False) def __init__(self, request, *args, **kwargs): super(VLConfigForm, self).__init__(request, *args, **kwargs) self.saved_params = {} self.cfg_timestamp = None self.stash = ncicrypto.CryptoStash(request) obj = None try: LOG.debug("Checking if project configuration exists") container = nci_private_container_name(request) config_obj_name = nci_vl_project_config_name() if api.swift.swift_object_exists(request, container, config_obj_name): LOG.debug("Loading project configuration") obj = api.swift.swift_get_object(request, container, config_obj_name, resp_chunk_size=None) self.cfg_timestamp = obj.timestamp if self.cfg_timestamp is None: # Workaround bug in Ceph which doesn't return the "X-Timestamp" # header. This appears to be fixed in Ceph 0.87.1 (Giant). # http://tracker.ceph.com/issues/8911 # https://github.com/ceph/ceph/commit/8c573c8826096d90dc7dfb9fd0126b9983bc15eb metadata = api.swift.swift_api(request).head_object(container, config_obj_name) try: lastmod = metadata["last-modified"] # https://github.com/ceph/ceph/blob/v0.80.6/src/rgw/rgw_rest.cc#L325 dt = datetime.datetime.strptime(lastmod, "%a, %d %b %Y %H:%M:%S %Z") assert dt.utcoffset() is None self.cfg_timestamp = dt.strftime("%Y-%m-%dT%H:%M:%SZ") except Exception as e: LOG.exception("Error getting project config timestamp: {0}".format(e)) except: exceptions.handle(request) # NB: Can't use "self.api_error()" here since form not yet validated. msg = _("Failed to load configuration data.") self.set_warning(msg) return try: if obj and obj.data: LOG.debug("Parsing project configuration") self.saved_params = json.loads(obj.data) except ValueError as e: LOG.exception("Error parsing project configuration: {0}".format(e)) messages.error(request, str(e)) # NB: Can't use "self.api_error()" here since form not yet validated. msg = _("Configuration data is corrupt and cannot be loaded.") self.set_warning(msg) return if not self.saved_params: if request.method == "GET": msg = _("No existing project configuration found.") self.set_warning(msg) self.fields["puppet_action"].initial = "auto" self.fields["puppet_env"].initial = "production" self.fields["repo_path"].initial = "{0}/puppet.git".format(request.user.project_name) return for k, v in self.saved_params.iteritems(): if (k in self.fields) and not re.match(SPECIAL_FIELDS_REGEX, k): self.fields[k].initial = v partial_load = False if self.saved_params.get("stash"): try: self.stash.init_params(self.saved_params["stash"]) except: exceptions.handle(request) partial_load = True else: if self.saved_params.get("repo_key"): self.fields["repo_key_create"].initial = False if request.method == "GET": try: key = self.stash.load_private_key(self.saved_params["repo_key"]) self.fields["repo_key_public"].initial = key.ssh_publickey() self.fields["repo_key_fp"].initial = key.ssh_fingerprint() except: exceptions.handle(request) partial_load = True if self.saved_params.get("eyaml_key"): self.fields["eyaml_update"].initial = "" if request.method == "GET": try: key = self.stash.load_private_key(self.saved_params["eyaml_key"]) self.fields["eyaml_key_fp"].initial = key.fingerprint() except: exceptions.handle(request) partial_load = True if self.saved_params.get("eyaml_cert"): self.fields["eyaml_update"].initial = "" if request.method == "GET": try: cert = self.stash.load_x509_cert(self.saved_params["eyaml_cert"]) self.fields["eyaml_cert_fp"].initial = cert.fingerprint() except: exceptions.handle(request) partial_load = True if partial_load: # NB: Can't use "self.api_error()" here since form not yet validated. msg = _("The project configuration was only partially loaded.") self.set_warning(msg) def clean(self): data = super(VLConfigForm, self).clean() # Don't allow the form data to be saved if the revision stored in the # form by the GET request doesn't match what we've just loaded while # processing the POST request. if data.get("revision", "") != self.saved_params.get("revision", ""): if self.saved_params.get("revision"): msg = _("Saved configuration has changed since form was loaded.") else: msg = _("Failed to retrieve existing configuration for update.") raise forms.ValidationError(msg) if data.get("puppet_action", "none") != "none": if not (data.get("repo_key_create", False) or self.saved_params.get("repo_key")): msg = _("The selected Puppet action requires a deployment key.") self._errors["puppet_action"] = self.error_class([msg]) elif not (data.get("eyaml_update") or (self.saved_params.get("eyaml_key") and self.saved_params.get("eyaml_cert"))): msg = _("The selected Puppet action requires a Hiera eyaml certificate/key pair.") self._errors["puppet_action"] = self.error_class([msg]) if data.get("eyaml_update", "") == "import": if not data.get("eyaml_key_upload"): msg = _("No private key specified to import.") self._errors["eyaml_key_upload"] = self.error_class([msg]) if not data.get("eyaml_cert_upload"): msg = _("No certificate specified to import.") self._errors["eyaml_cert_upload"] = self.error_class([msg]) return data def handle(self, request, data): new_params = self.saved_params.copy() if "repo_branch" in new_params: del new_params["repo_branch"] new_params.update([(k, v) for k, v in data.iteritems() if not re.match(SPECIAL_FIELDS_REGEX, k)]) try: # Make sure the container exists first. container = nci_private_container_name(request) if not api.swift.swift_container_exists(request, container): api.swift.swift_create_container(request, container) if not api.swift.swift_object_exists(request, container, "README"): msg = "**WARNING** Don't delete, rename or modify this container or any objects herein." api.swift.swift_api(request).put_object(container, "README", msg, content_type="text/plain") # And check that a temporary URL key is defined as we'll need it # when launching new instances. if not ncicrypto.swift_get_temp_url_key(request): LOG.debug("Generating temp URL secret key") ncicrypto.swift_create_temp_url_key(request) messages.success(request, _("Temporary URL key generated successfully.")) except: exceptions.handle(request) msg = _("Failed to save configuration.") self.api_error(msg) return False if not self.stash.initialised: LOG.debug("Configuring crypto stash") try: self.stash.init_params() new_params["stash"] = self.stash.params except: exceptions.handle(request) msg = _("Failed to setup crypto stash.") self.api_error(msg) return False new_repo_key = None new_eyaml_key = None new_eyaml_cert = None try: if data.get("repo_key_create", False): LOG.debug("Generating new deployment key") try: new_repo_key = self.stash.create_private_key() new_params["repo_key"] = new_repo_key.metadata() except: exceptions.handle(request) msg = _("Failed to generate deployment key.") self.api_error(msg) return False eyaml_update = data.get("eyaml_update", "") if eyaml_update: try: if eyaml_update == "create": LOG.debug("Generating new eyaml key") new_eyaml_key = self.stash.create_private_key() elif eyaml_update == "import": LOG.debug("Importing eyaml key") new_eyaml_key = self.stash.import_private_key(data.get("eyaml_key_upload")) assert new_eyaml_key new_params["eyaml_key"] = new_eyaml_key.metadata() except: exceptions.handle(request) msg = _("Failed to update Hiera eyaml key.") self.api_error(msg) return False try: if eyaml_update == "create": LOG.debug("Generating new eyaml certificate") new_eyaml_cert = self.stash.create_x509_cert(new_eyaml_key, "hiera-eyaml-{0}".format(request.user.project_name), 100 * 365) elif eyaml_update == "import": LOG.debug("Importing eyaml certificate") new_eyaml_cert = self.stash.import_x509_cert(data.get("eyaml_cert_upload")) assert new_eyaml_cert new_params["eyaml_cert"] = new_eyaml_cert.metadata() except: exceptions.handle(request) msg = _("Failed to update Hiera eyaml certificate.") self.api_error(msg) return False try: if not new_eyaml_cert.verify_key_pair(new_eyaml_key): msg = _("Hiera eyaml certificate was not signed with the given key.") self.api_error(msg) return False except: exceptions.handle(request) msg = _("Failed to verify Hiera eyaml certificate/key pair.") self.api_error(msg) return False if new_params != self.saved_params: new_params["revision"] = datetime.datetime.utcnow().isoformat() obj_data = json.dumps(new_params) try: config_obj_name = nci_vl_project_config_name() if self.cfg_timestamp: backup_name = "{0}_{1}".format(config_obj_name, self.cfg_timestamp) if not api.swift.swift_object_exists(request, container, backup_name): LOG.debug("Backing up current project configuration") api.swift.swift_copy_object(request, container, config_obj_name, container, backup_name) elif api.swift.swift_object_exists(request, container, config_obj_name): msg = _("Couldn't backup previous configuration. No timestamp available.") messages.warning(request, msg) LOG.debug("Saving project configuration") api.swift.swift_api(request).put_object(container, config_obj_name, obj_data, content_type="application/json") except: exceptions.handle(request) msg = _("Failed to save configuration.") self.api_error(msg) return False new_repo_key = None new_eyaml_key = None new_eyaml_cert = None self.saved_params = new_params messages.success(request, _("Configuration saved.")) finally: try: if new_repo_key: LOG.debug("Rolling back deployment key generation") self.stash.delete(new_repo_key) except Exception as e: LOG.exception("Error deleting orphaned deployment key: {0}".format(e)) try: if new_eyaml_key: LOG.debug("Rolling back eyaml key generation") self.stash.delete(new_eyaml_key) except Exception as e: LOG.exception("Error deleting orphaned eyaml key: {0}".format(e)) try: if new_eyaml_cert: LOG.debug("Rolling back eyaml certificate generation") self.stash.delete(new_eyaml_cert) except Exception as e: LOG.exception("Error deleting orphaned eyaml certificate: {0}".format(e)) return True # vim:ts=4 et sw=4 sts=4:
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,369
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/identity_nci/projects/panel.py
../../../../dashboards/identity/projects/panel.py
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,370
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/enabled/_60_admin_add_hvlist.py
PANEL_DASHBOARD = 'admin' PANEL_GROUP = 'admin' PANEL = 'hvlist' ADD_PANEL = 'openstack_dashboard.local.dashboards.admin_nci.hvlist.panel.Hvlist'
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,371
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/enabled/_59_project_add_panel_vlconfig.py
PANEL_DASHBOARD = 'project' PANEL_GROUP = 'virtlab' PANEL = 'vlconfig' ADD_PANEL = 'openstack_dashboard.local.dashboards.project_nci.vlconfig.panel.VLConfig'
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,372
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/identity_nci/projects/urls.py
# openstack_dashboard.local.dashboards.identity_nci.projects.urls # # Copyright (c) 2015, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from django.conf.urls import patterns from django.conf.urls import url from openstack_dashboard.dashboards.identity.projects.urls import urlpatterns as orig_urlpatterns from . import views VIEW_MOD = "openstack_dashboard.local.dashboards.identity_nci.projects.views" urlpatterns = [] for x in orig_urlpatterns: if getattr(x, "name", "") == "create": x = patterns(VIEW_MOD, url(x.regex.pattern, views.NCICreateProjectView.as_view(), name=x.name))[0] elif getattr(x, "name", "") == "update": x = patterns(VIEW_MOD, url(x.regex.pattern, views.NCIUpdateProjectView.as_view(), name=x.name))[0] urlpatterns.append(x) # vim:ts=4 et sw=4 sts=4:
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,373
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/project_nci/access_and_security/panel.py
../../../../dashboards/project/access_and_security/panel.py
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,374
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/enabled/_61_admin_add_pupha.py
PANEL_DASHBOARD = 'admin' PANEL_GROUP = 'admin' PANEL = 'pupha' ADD_PANEL = 'openstack_dashboard.local.dashboards.admin_nci.pupha.panel.ProjectUsagePerHostAggregate'
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,375
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/enabled/_10_project.py
DASHBOARD = 'project' # Add our modified project dashboard to the "INSTALLED_APPS" path. # Django doco says that the final component of each path has to be unique, # however it doesn't seem to bother Horizon. But just to be on the safe # side we've named the module "project_nci", although the slug will # still be "project". ADD_INSTALLED_APPS = [ 'openstack_dashboard.local.dashboards.project_nci', 'openstack_dashboard.dashboards.project', ] from openstack_dashboard.local.nci.exceptions import CryptoError ADD_EXCEPTIONS = { 'recoverable': (CryptoError,), }
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,376
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/enabled/_20_admin.py
../../enabled/_20_admin.py
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,377
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/project_nci/containers/urls.py
# openstack_dashboard.local.dashboards.project_nci.containers.urls # # Copyright (c) 2014, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from django.conf.urls import patterns from django.conf.urls import url from openstack_dashboard.dashboards.project.containers.urls import urlpatterns as orig_urlpatterns from . import views VIEW_MOD = "openstack_dashboard.local.dashboards.project_nci.containers.views" urlpatterns = [] for x in orig_urlpatterns: if getattr(x, "name", "") == "index": x = patterns(VIEW_MOD, url(x.regex.pattern, views.NCIContainerView.as_view(), name=x.name))[0] urlpatterns.append(x) # vim:ts=4 et sw=4 sts=4:
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,378
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/project_nci/containers/panel.py
../../../../dashboards/project/containers/panel.py
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,379
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/nci/customisation.py
# openstack_dashboard.local.nci.customisation # # Copyright (c) 2015, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # You might assume that it ought to be possible to replace the built-in # panels with customised versions using the "Pluggable Settings" mechanism by # first removing the existing panel and then adding the custom panel class. # Unfortunately this doesn't work in practice due to the limitations # described below. # # In "horizon.Site._process_panel_configuration()", when a panel is removed # it is only removed from the dashboard's class registry. Any corresponding # panel group in the "panels" attribute is *not* updated. In contrast, # when a panel is added then in addition to the registry being updated, # the slug is appended to the corresponding panel group, or else the panel # class is added directly to the "panels" attribute if no group is specified. # This has the following effects: # # (i) Adding the new panel to the same group fails because this results in # duplicate slugs in the group which in turn causes a "KeyError" when # removing classes from a temporary copy of the class registry in # "horizon.Dashboard.get_panel_groups()". # # (ii) Adding the new panel without a group succeeds at first, but later on # an error occurs in "horizon.Dashboard._autodiscover()" when it tries to # wrap the panel class in a panel group but that fails as the constructor # expects an iterable type. # # So to work around this, we are using the older customisation mechanism # instead to programatically replace the panels. This also has an added # benefit of maintaining the relative order of panels in each dashboard. # # Another possible option could be to symlink "dashboard.py" into the # custom directory tree but that would also then require symlinking # every unmodified panel as well since the code always looks for them # relative to that file. # https://github.com/openstack/horizon/blob/stable/kilo/horizon/base.py#L563 # import logging #import pdb ## DEBUG from django.utils.importlib import import_module import horizon LOG = logging.getLogger(__name__) def replace_panels(dash_slug, panels): dash = horizon.get_dashboard(dash_slug) for slug, mod_path in panels: if not dash.unregister(dash.get_panel(slug).__class__): LOG.error("Failed to unregister panel: %s" % slug) else: # When the panel module is imported it registers its panel class # with the dashboard. import_module(mod_path) identity_panels = [ ("projects", "openstack_dashboard.local.dashboards.identity_nci.projects.panel"), ("users", "openstack_dashboard.local.dashboards.identity_nci.users.panel"), ] replace_panels("identity", identity_panels) project_panels = [ ("access_and_security", "openstack_dashboard.local.dashboards.project_nci.access_and_security.panel"), ("containers", "openstack_dashboard.local.dashboards.project_nci.containers.panel"), ("instances", "openstack_dashboard.local.dashboards.project_nci.instances.panel"), ] replace_panels("project", project_panels) # vim:ts=4 et sw=4 sts=4:
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,380
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/project_nci/containers/views.py
# openstack_dashboard.local.dashboards.project_nci.containers.views # # Copyright (c) 2015, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from openstack_dashboard.dashboards.project.containers import views as base_mod from openstack_dashboard.local.nci.constants import NCI_PVT_CONTAINER_PREFIX class NCIContainerView(base_mod.ContainerView): def get_containers_data(self): containers = super(NCIContainerView, self).get_containers_data() if self.request.user.is_superuser: return containers else: # Hide the private NCI configuration container to help prevent # accidental deletion etc. return [x for x in containers if not x.name.startswith(NCI_PVT_CONTAINER_PREFIX)] # vim:ts=4 et sw=4 sts=4:
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,381
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/identity_nci/users/views.py
# openstack_dashboard.local.dashboards.identity_nci.users.views # # Copyright (c) 2015, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from openstack_dashboard.dashboards.identity.users import views as base_mod class NCIIndexView(base_mod.IndexView): def get_data(self): # Keystone users have UUIDs so this effectively filters out # any LDAP users. users = super(NCIIndexView, self).get_data() return [u for u in users if len(u.id) >= 32] # vim:ts=4 et sw=4 sts=4:
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,382
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/project_nci/instances/panel.py
../../../../dashboards/project/instances/panel.py
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,383
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/admin_nci/pupha/tables.py
# openstack_dashboard.local.dashboards.admin_nci.pupha.tables # # Copyright (c) 2016, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from horizon import tables from django.utils.translation import ugettext_lazy as _ from .constants import format_bytes, su, short_name from django.utils.safestring import mark_safe from django.core import urlresolvers class Format(object): """ Helpers for various formatting-related operations. These may be candidates for conversion to Django filter functions, for better separation of logic and rendering code. """ precision = 1 precision_f = '{{:.{}f}}'.format(precision) overcommit = u'\u00d7 {{factor:.{}f}} = {{total}}'.format(precision) @staticmethod def mb(mb, precision=precision): return format_bytes(mb*1024*1024, precision=precision) @staticmethod def gb(gb, precision=precision): return format_bytes(gb*1024*1024*1024, precision=precision) @staticmethod def progress_bar(u, t, label='&nbsp;'): """Return html for progress bar showing u/t (used/total).""" return '<span class="bar"><span class="fill" style="width:{percent}%">{label}</span></span>'.format(used=u, total=t, percent=100*float(u)/t, label=label) @staticmethod def instances_list(instances): """ Return unordered list markup for list of instance names with hyperlinks to instance detail pages. """ return '<ul>'+''.join( '<li><a href="{link}">{name}</a></li>'.format( name=i.name, link=urlresolvers.reverse('horizon:admin:instances:detail', args=(i.id,) ) ) for i in instances)+'</ul>' @staticmethod def hypervisor_color(load): """Return 12-bit hexadecimal color string (e.g. "#d37") for hypervisor with the given load, which is a floating-point value between 0 and 1. This implementation uses linear interpolation in hsv space between green and red. """ from colorsys import hsv_to_rgb hue0, hue1 = 1/3., 0 # green, red hard-coded because that's how i roll hue = hue0 + min(load,1)*(hue1-hue0) # lerp r, g, b = hsv_to_rgb(hue, 0.85, 0.9) r, g, b = ('0123456789abcdef'[int(15*x+0.5)] for x in (r,g,b)) return '#{0}{1}{2}'.format(r, g, b) class SummaryTable(tables.DataTable): name = tables.Column('name') vcpu = tables.Column('vcpus', verbose_name=_('VCPU')) vcpu_o = tables.Column( lambda o: (o.vcpu_o, o.vcpus), verbose_name=_('overcommit'), filters=[lambda (overcommit, vcpus): Format.overcommit.format(factor=overcommit, total=Format.precision_f.format(overcommit*vcpus))] ) vcpu_u = tables.Column('vcpus_used', verbose_name=_('allocated')) vcpu_f = tables.Column( lambda o: (o.vcpu_o, o.vcpus, o.vcpus_used), verbose_name = _('free'), filters = [lambda (overcommit, vcpus, used): Format.precision_f.format(overcommit*vcpus-used)], ) ram = tables.Column( 'memory_mb', verbose_name = _('RAM'), filters = [Format.mb] ) ram_o = tables.Column( lambda o: (o.memory_mb_o, o.memory_mb), verbose_name=_('overcommit'), filters = [ # (these are applied in the order written, with output(n)=input(n+1) lambda (o, m): (o, Format.mb(m)), lambda (o, fm): Format.overcommit.format(factor=o, total=fm), ] ) ram_u = tables.Column( 'memory_mb_used', verbose_name = _('allocated'), filters = [Format.mb] ) ram_f = tables.Column( lambda o: (o.memory_mb_o, o.memory_mb, o.memory_mb_used), verbose_name = _('free'), filters = [ lambda (overcommit, mb, used): overcommit*mb-used, Format.mb, ] ) class Meta(object): name = 'summary' class ProjectUsageTable(tables.DataTable): name = tables.Column(lambda pu: pu.project.name, verbose_name=_('Name')) desc = tables.Column(lambda pu: pu.project.description, verbose_name=_('Description')) vcpu = tables.Column('vcpus', verbose_name=_('VCPU'), summation='sum') ram = tables.Column( 'memory_mb', verbose_name = _('RAM'), filters = [lambda mb: format_bytes(mb*1024*1024)], summation = 'sum') sus = tables.Column( lambda pu: float(su(pu.vcpus, pu.memory_mb)), # without float cast, summation doesn't work (but with float cast, we could potentially lose nice formatting) verbose_name = _('SU'), help_text = u'1 SU \u223c 1 VCPU \u00d7 {} RAM'.format(format_bytes(su.memory_mb*1024*1024)), # \u223c is tilde operator; \u00d7 is times operator summation = 'sum') class Meta(object): hidden_title = False class HypervisorTable(tables.DataTable): status_icon = tables.Column( lambda h: h._meta.usage, verbose_name = '', # no title for this column filters = [ Format.hypervisor_color, lambda col: '<span style="background-color:{}">&nbsp;</span>'.format(col), mark_safe ], classes = ['usage'] ) name = tables.Column( lambda h: short_name(getattr(h, h.NAME_ATTR)) + u'\u21d7', # \u21d7 is very roughly what wikipedia uses to mark external links... verbose_name = _('Name'), # this is the hackiest line of code ever written: link = lambda h: 'https://tenjin-monitor.nci.org.au/ganglia/?p=2&c=tenjin&h='+short_name(getattr(h, h.NAME_ATTR)), ) status = tables.Column('status') state = tables.Column('state') vcpu = tables.Column( lambda h: (h.vcpus, h.vcpus_used, h._meta.overcommit['cpu']), verbose_name = _('VCPU'), filters = [ lambda (t, u, o): Format.progress_bar(u, t*o, '{u} / {t}'.format(u=u, t=t*o)), mark_safe ], ) ram = tables.Column( lambda h: (h.memory_mb, h.memory_mb_used, h._meta.overcommit['ram']), verbose_name = _('RAM'), filters = [ lambda (t, u, o): Format.progress_bar(u, t*o, '{u} / {t}'.format(u=Format.mb(u, precision=0), t=Format.mb(t*o, precision=0))), mark_safe ], ) disk = tables.Column( lambda h: (h.local_gb, h.local_gb_used, h._meta.overcommit['disk']), verbose_name = _('Local storage'), filters = [ lambda (t, u, o): Format.progress_bar(u, t*o, '{u} / {t}'.format(u=Format.gb(u, precision=0), t=Format.gb(t*o, precision=0))), mark_safe ], ) instances = tables.Column( lambda h: h.instances, verbose_name = _('Instances'), filters = [ Format.instances_list, # could try to use django built-in "unordered_list" filter for this mark_safe, ], ) class Meta(object): hidden_title = False
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,384
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py
# openstack_dashboard.local.dashboards.admin_nci.pupha.tabs # # Copyright (c) 2016, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import types import itertools from .constants import TABLES_TEMPLATE_NAME, SUMMARY_TEMPLATE_NAME from . import tables from horizon import tabs from django.utils.translation import ugettext_lazy as _ class DictObject(object): """Would have thought that this would be built-in somehow....""" def __init__(self, *args, **kwargs): self.__dict__.update(kwargs) class ProjectsTab(tabs.TableTab): """ Displays per-project summary of resource usage within each host aggregate. If there is ever a host aggregate with name "context" or "aggregate", this will break. This is because TableTab makes calls to "get_{}_data". """ name = _('Projects') # rendered as text in html slug = 'projects' # url slug and id attribute (=> unique) template_name = TABLES_TEMPLATE_NAME @staticmethod def table_factory(aggregate): class AggregateProjectUsageTable(tables.ProjectUsageTable): class Meta(tables.ProjectUsageTable.Meta): name = verbose_name = aggregate.name return AggregateProjectUsageTable def __init__(self, tab_group, request): try: # make sure host aggregates are exposed self.host_aggregates = tab_group.host_aggregates except AttributeError: # raise the exception with slightly better description raise AttributeError('{} must be part of a tab group that exposes host aggregates'.format(self.__class__.__name__)) # define table_classes, which get used in TableTab.__init__ self.table_classes = [ProjectsTab.table_factory(a.aggregate) for a in self.host_aggregates] # set up get_{{ table_name }}_data methods, which get called by TableTab for ha in self.host_aggregates: # types.MethodType is used to bind the function to this object; # dummy "agg=agg" parameter is used to force capture of agg setattr(self, 'get_{}_data'.format(ha.aggregate.name), types.MethodType(lambda slf, ha=ha: self.get_aggregate_data(ha), self)) # remaining initialisation can proceed now that tables are set up super(ProjectsTab, self).__init__(tab_group, request) def get_aggregate_data(self, host_aggregate): """ Retrieve data for the specified HostAggregate, in a format that can be understood by an object from table_factory. This must be called after (or from within) get_context_data, otherwise the necessary data will not have been loaded. """ # find instances running in this host aggregate instances = list(itertools.chain(*(h.instances for h in host_aggregate.hypervisors))) # find projects with instances running in this host aggregate projects = set([i.project for i in instances]) # sum usage per project, and sort from most vcpus to fewest return sorted([DictObject( id = p.id, project = p, vcpus = sum(i.flavor.vcpus for i in instances if i.project == p), memory_mb = sum(i.flavor.ram for i in instances if i.project == p) ) for p in projects], key=lambda pu:pu.vcpus, reverse=True) def get_context_data(self, request, **kwargs): # parent sets "{{ table_name }}_table" keys corresponding to items in table_classes # (this call causes calls back to get_{}_data for each table in the Tab) context = super(ProjectsTab, self).get_context_data(request, **kwargs) # reorganise that a bit so that the template can iterate dynamically context['tables'] = [context['{}_table'.format(ha.aggregate.name)] for ha in self.host_aggregates] return context class SummaryTab(tabs.TableTab): """ Displays resource usage (physical count, overcommit value, used, remaining) for vcpus and memory for each host aggregate. It's a bit ugly. """ table_classes = (tables.SummaryTable,) name = _('Summary') slug = 'summary' template_name = SUMMARY_TEMPLATE_NAME def __init__(self, tab_group, request): try: self.host_aggregates = tab_group.host_aggregates except AttributeError: raise AttributeError('{} must be part of a tab group that exposes host aggregates'.format(self.__class__.__name__)) super(SummaryTab, self).__init__(tab_group, request) def get_summary_data(self): return [DictObject( id = a.aggregate.id, name = a.aggregate.name, vcpus = sum(h.vcpus for h in a.hypervisors), memory_mb = sum(h.memory_mb for h in a.hypervisors), vcpus_used = sum(h.vcpus_used for h in a.hypervisors), memory_mb_used = sum(h.memory_mb_used for h in a.hypervisors), vcpu_o = a.overcommit['cpu'], # these keys are hard-coded memory_mb_o = a.overcommit['ram'], # to match nova.conf ) for a in self.host_aggregates] class HypervisorsTab(tabs.TableTab): """ Lists hypervisors within each host aggregate, and instances and resource usage on each hypervisor. This shares code with ProjectsTab, so should probably be refactored. If there is ever a hypervisor with name "context" or "aggregate", this will break (see ProjectsTab). """ name = _('Hypervisors') slug = 'hypervisors' template_name = TABLES_TEMPLATE_NAME @staticmethod def table_factory(aggregate): class HypervisorTable(tables.HypervisorTable): class Meta(tables.HypervisorTable.Meta): name = verbose_name = aggregate.name return HypervisorTable def __init__(self, tab_group, request): """ This is copy+paste from ProjectsTab... DRY! """ try: # make sure host aggregates are exposed self.host_aggregates = tab_group.host_aggregates except AttributeError: # raise the exception with slightly better description raise AttributeError('{} must be part of a tab group that exposes host aggregates'.format(self.__class__.__name__)) # define table_classes, which get used in TableTab.__init__ HypervisorsTab.table_classes = [HypervisorsTab.table_factory(a.aggregate) for a in self.host_aggregates] # set up get_{{ table_name }}_data methods, which get called by TableTab for ha in self.host_aggregates: # types.MethodType is used to bind the function to this object; # dummy "agg=agg" parameter is used to force capture of agg setattr(self, 'get_{}_data'.format(ha.aggregate.name), types.MethodType(lambda slf, ha=ha: self.get_aggregate_data(ha), self)) # remaining initialisation can proceed now that tables are set up super(HypervisorsTab, self).__init__(tab_group, request) def get_aggregate_data(self, host_aggregate): """ Retrieve data for the specified HostAggregate, in a format that can be understood by an object from table_factory. This must be called after (or from within) get_context_data, otherwise the necessary data will not have been loaded. """ # decorate hypervisors with some extra information # (need to do this in a context where host_aggregate is defined; # i.e. it cannot be done in the Table code.) for h in host_aggregate.hypervisors: h._meta = DictObject() # calculate resource usage, accounting for overcommit hypervisor_attr = {'cpu':'vcpus', 'ram':'memory_mb', 'disk':'local_gb'} # mapping host_aggregate.overcommit keys => hypervisor object attributes h._meta.usages = {k:float(getattr(h, r+'_used'))/(getattr(h, r)*host_aggregate.overcommit[k]) for (k, r) in hypervisor_attr.items()} h._meta.usage = max(h._meta.usages.values()) h._meta.overcommit = host_aggregate.overcommit return host_aggregate.hypervisors #sorted(xs, key=lambda pu:pu.vcpus, reverse=True) def get_context_data(self, request, **kwargs): # parent sets "{{ table_name }}_table" keys corresponding to items in table_classes # (this call causes calls back to get_{}_data for each table in the Tab) context = super(HypervisorsTab, self).get_context_data(request, **kwargs) # reorganise that a bit so that the template can iterate dynamically context['tables'] = [context['{}_table'.format(ha.aggregate.name)] for ha in self.host_aggregates] return context class TabGroup(tabs.TabGroup): tabs = (SummaryTab, ProjectsTab, HypervisorsTab) slug = "pupha" # this is url slug, used with .. sticky = True # .. this to store tab state across requests def __init__(self, request, **kwargs): if 'host_aggregates' in kwargs: self.host_aggregates = kwargs['host_aggregates'] super(TabGroup, self).__init__(request, **kwargs)
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,385
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py
# openstack_dashboard.local.dashboards.project_nci.instances.workflows.create_instance # # Copyright (c) 2015, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import copy import itertools import json import logging import netaddr import operator import os.path #import pdb ## DEBUG import re import socket import time import types from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.views.decorators.debug import sensitive_variables from django.template.defaultfilters import filesizeformat from horizon import exceptions from horizon import forms from horizon import messages from horizon import workflows from openstack_dashboard import api from openstack_dashboard.dashboards.project.instances.workflows import create_instance as base_mod from openstack_dashboard.local.nci import crypto as ncicrypto from openstack_dashboard.local.nci import utils as nciutils from openstack_dashboard.local.nci.constants import * LOG = logging.getLogger(__name__) class SetInstanceDetailsAction(base_mod.SetInstanceDetailsAction): Meta = nciutils.subclass_meta_type(base_mod.SetInstanceDetailsAction) def populate_image_id_choices(self, request, context): choices = super(SetInstanceDetailsAction, self).populate_image_id_choices(request, context) # Find the latest VL image for each unique series tag and add an # alias item to the top of the images list with a more friendly name # so that the user doesn't have to hunt through the entire list # looking for the correct image to use. self.vl_tags = {} for id, image in choices: if not id: continue parts = image.name.split("-") if parts[0] == "vl": if not image.is_public: LOG.debug("Ignoring non-public VL image: {0}".format(image.name)) continue # VL images have the following name format: # vl-<tag_base>[-<tag_variant>-...]-<timestamp> if len(parts) < 3: LOG.warning("Invalid VL image name format: {0}".format(image.name)) continue tag = "-".join(parts[1:-1]) if re.match(r"2[0-9]{7}", parts[-1]): image._vl_ts = parts[-1] else: LOG.warning("Invalid or missing timestamp in VL image name: {0}".format(image.name)) continue if (tag not in self.vl_tags) or (image._vl_ts > self.vl_tags[tag]._vl_ts): self.vl_tags[tag] = image def clone_image(tag): if "-" in tag: (base, variant) = tag.split("-", 1) else: base = tag variant = "" if base.startswith("centos"): title = "CentOS" base = base[6:] elif base.startswith("ubuntu"): title = "Ubuntu" base = base[6:] else: title = tag base = "" variant = "" if base: title += " " + base if variant: title += " " + variant image = copy.copy(self.vl_tags[tag]) image._real_id = image.id image.id = "vltag:" + tag image.name = title self.vl_tags[tag] = image return image if self.vl_tags: choices.insert(1, ("---all", "----- All Images -----")) for tag in reversed(sorted(self.vl_tags.keys())): image = clone_image(tag) choices.insert(1, (image.id, image)) choices.insert(1, ("---vl", "----- VL Images -----")) return choices def clean_name(self): if hasattr(super(SetInstanceDetailsAction, self), "clean_name"): val = super(SetInstanceDetailsAction, self).clean_name() else: val = self.cleaned_data.get("name") val = val.strip() if val and ("." in val): valid_fqdn = r"^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$" if not re.search(valid_fqdn, val): msg = _("The specified FQDN doesn't satisfy the requirements of a valid DNS hostname.") raise forms.ValidationError(msg) return val def clean_image_id(self): if hasattr(super(SetInstanceDetailsAction, self), "clean_image_id"): val = super(SetInstanceDetailsAction, self).clean_image_id() else: val = self.cleaned_data.get("image_id") if val: if val.startswith("---"): val = "" elif val.startswith("vltag:"): # Convert the VL image tag back into the real image ID. tag = val[6:] if tag not in self.vl_tags: msg = _("Image tag doesn't exist") raise forms.ValidationError(msg) val = self.vl_tags[tag]._real_id return val def get_help_text(self): saved = self._images_cache try: # Add our VL image aliases to the image cache temporarily so # that they are included in the list passed to "initWithImages()" # in "horizon/static/horizon/js/horizon.quota.js" (via the # "_flavors_and_quotas.html" template). The result will be # that any flavours which are too small will be disabled when # a given image alias is selected in the drop down. self._images_cache["public_images"].extend(self.vl_tags.values()) return super(SetInstanceDetailsAction, self).get_help_text() finally: self._images_cache = saved class SetInstanceDetails(base_mod.SetInstanceDetails): action_class = SetInstanceDetailsAction class SetAccessControlsAction(base_mod.SetAccessControlsAction): Meta = nciutils.subclass_meta_type(base_mod.SetAccessControlsAction) def __init__(self, request, context, *args, **kwargs): super(SetAccessControlsAction, self).__init__(request, context, *args, **kwargs) # Remove the security groups field since they aren't functional on # our new cloud. del self.fields["groups"] def populate_groups_choices(self, request, context): return [] class SetAccessControls(base_mod.SetAccessControls): action_class = SetAccessControlsAction class FixedIPMultiWidget(forms.MultiWidget): def __init__(self, choices, attrs=None): sub_widgets = ( forms.Select(choices=choices, attrs=attrs), forms.TextInput(attrs=attrs), ) super(FixedIPMultiWidget, self).__init__(sub_widgets, attrs) def has_choice(self, value): for x in self.widgets[0].choices: if isinstance(x[1], (list, tuple)): for y in x[1]: if y[0] == value: return True elif x[0] == value: return True return False def decompress(self, value): if value is not None: if self.has_choice(value): return [value, None] else: return ["manual", value] else: return [None, None] def value_from_datadict(self, data, files, name): v = super(FixedIPMultiWidget, self).value_from_datadict(data, files, name) if v[0] == "manual": return v[1].strip() else: return v[0] # NB: We aren't subclassing the upstream implementation of this action. class SetNetworkAction(workflows.Action): Meta = nciutils.subclass_meta_type(base_mod.SetNetworkAction) @staticmethod def user_has_ext_net_priv(request): return (request.user.is_superuser or request.user.has_perms([settings.NCI_EXTERNAL_NET_PERM])) def __init__(self, request, context, *args, **kwargs): super(SetNetworkAction, self).__init__(request, context, *args, **kwargs) # If the user has access to the external network then retrieve any # fixed public IP allocations defined for this tenant. all_fixed_pub_ips = netaddr.IPSet() self.fixed_pub_ips_pool = False if self.user_has_ext_net_priv(request): try: if request.user.project_name in settings.NCI_FIXED_PUBLIC_IPS: for cidr in settings.NCI_FIXED_PUBLIC_IPS[request.user.project_name]: if cidr == "pool": self.fixed_pub_ips_pool = True else: all_fixed_pub_ips.add(netaddr.IPNetwork(cidr)) elif request.user.project_name == "admin": self.fixed_pub_ips_pool = True except (netaddr.AddrFormatError, ValueError) as e: LOG.exception("Error parsing fixed public IP list: {0}".format(e)) messages.error(request, str(e)) msg = _("Failed to load fixed public IP configuration.") messages.warning(request, msg) all_fixed_pub_ips = netaddr.IPSet() self.fixed_pub_ips_pool = False self.fixed_pub_ips_enabled = (bool(all_fixed_pub_ips) or self.fixed_pub_ips_pool) # Build the list of network choices. networks_list = self.get_networks(request) self.networks = dict([(x.id, x) for x in networks_list]) network_choices = [(x.id, x.name) for x in sorted(networks_list, key=operator.attrgetter('name'))] network_choices.insert(0, ("", "-- Unassigned --")) # Build the fixed and floating IP choice lists. self.pub_ips = self.get_public_ips(request, all_fixed_pub_ips) fixed_ip_choices = [ ("auto", "Automatic"), ("manual", "Manual"), ] if self.fixed_pub_ips_enabled: ext_fixed_ip_choices = [(str(x), str(x)) for x in self.pub_ips["fixed"]] if self.fixed_pub_ips_pool: ext_fixed_ip_choices.append(["ext_pool", "Global Allocation Pool"]) grp_title = "External" if not ext_fixed_ip_choices: grp_title += " (none available)" fixed_ip_choices.append((grp_title, ext_fixed_ip_choices)) else: ext_fixed_ip_choices = [] floating_ip_choices = [(x.id, x.ip) for x in sorted(self.pub_ips["float"].itervalues(), key=lambda x: netaddr.IPAddress(x.ip))] floating_ip_choices.insert(0, ("", "-- None --")) # Create the form fields for each network interface. self.intf_limit = settings.NCI_VM_NETWORK_INTF_LIMIT if not settings.NCI_DUPLICATE_VM_NETWORK_INTF: self.intf_limit = max(1, min(self.intf_limit, len(networks_list))) for i in range(0, self.intf_limit): self.fields["eth{0:d}_network".format(i)] = forms.ChoiceField( label=_("Network"), required=(i == 0), choices=network_choices, initial="", help_text=_("The network that this interface should be attached to.")) self.fields["eth{0:d}_fixed_ip".format(i)] = forms.CharField( widget=FixedIPMultiWidget(fixed_ip_choices), label=_("Fixed IP"), required=True, initial="auto", help_text=_("The fixed IP address to assign to this interface.")) self.fields["eth{0:d}_floating_ip".format(i)] = forms.ChoiceField( label=_("Floating Public IP"), required=False, choices=floating_ip_choices, initial="", help_text=_("A floating IP address to associate with this interface.")) # Select reasonable defaults if there is an obvious choice. We only # consider external networks as an option if there aren't any floating # IPs available. external_net_ids = set([x for x, y in self.networks.iteritems() if y.get("router:external", False)]) private_net_ids = set(self.networks.keys()) - external_net_ids default_priv_net = None if len(private_net_ids) == 1: default_priv_net = iter(private_net_ids).next() elif private_net_ids: # As a convention, when we setup a new tenant we create a network # with the same name as the tenant. search = [request.user.project_name] if request.user.project_name in ["admin", "z00"]: search.append("internal") matches = [x for x in private_net_ids if self.networks[x].name in search] if len(matches) == 1: default_priv_net = matches[0] if len(floating_ip_choices) > 1: if default_priv_net: self.fields["eth0_network"].initial = default_priv_net self.fields["eth0_floating_ip"].initial = floating_ip_choices[1][0] elif ext_fixed_ip_choices: if len(external_net_ids) == 1: self.fields["eth0_network"].initial = iter(external_net_ids).next() self.fields["eth0_fixed_ip"].initial = ext_fixed_ip_choices[0][0] if default_priv_net: assert self.intf_limit > 1 self.fields["eth1_network"].initial = default_priv_net elif default_priv_net: self.fields["eth0_network"].initial = default_priv_net # A list of external network IDs is needed for the client side code. self.external_nets = ";".join(external_net_ids) def get_networks(self, request): networks = [] try: networks = api.neutron.network_list_for_tenant(request, request.user.project_id) except: exceptions.handle(request) msg = _("Unable to retrieve available networks.") messages.warning(request, msg) if not self.fixed_pub_ips_enabled: LOG.debug("Excluding external networks") networks = filter(lambda x: not x.get("router:external", False), networks) # TODO: Workaround until we can unshare the "internal" network. if request.user.project_name not in ["admin", "z00"]: networks = filter(lambda x: x.get("router:external", False) or not x.shared, networks) any_ext_nets = False for net in networks: # Make sure the "name" attribute is defined. net.set_id_as_name_if_empty() any_ext_nets = any_ext_nets or net.get("router:external", False) if self.fixed_pub_ips_enabled and not any_ext_nets: LOG.debug("No external networks found - disabling fixed public IPs") self.fixed_pub_ips_enabled = False return networks def get_public_ips(self, request, all_fixed_pub_ips): ips = {} try: # Select any unassigned floating IPs. floats = api.network.tenant_floating_ip_list(request) ips["float"] = dict([(x.id, x) for x in floats if not x.port_id]) if self.fixed_pub_ips_enabled and all_fixed_pub_ips: # Take note of all floating IPs (including assigned) since they # can't be used as a fixed IP given that a port already exists. used_ips = [x.ip for x in floats] # Locate any fixed IPs already assigned to an external network # port so that we can exclude them from the list. for net_id, net in self.networks.iteritems(): if not net.get("router:external", False): continue LOG.debug("Getting all ports for network: {0}".format(net_id)) ports = api.neutron.port_list(request, tenant_id=request.user.project_id, network_id=net_id) for port in ports: for fip in port.fixed_ips: if fip.get("ip_address"): used_ips.append(fip["ip_address"]) # Select fixed IPs allocated to the tenant that aren't in use. ips["fixed"] = all_fixed_pub_ips - netaddr.IPSet(used_ips) else: ips["fixed"] = [] except: exceptions.handle(request) msg = _("Failed to determine available public IPs.") messages.warning(request, msg) ips["float"] = {} ips["fixed"] = [] return ips def clean(self): data = super(SetNetworkAction, self).clean() nics = [] used_ips = {"_float_": set()} try: for i in range(0, self.intf_limit): nic = {} field_id = "eth{0:d}_network".format(i) net_id = data.get(field_id) if net_id: used_ips.setdefault(net_id, set()) nic["network_id"] = net_id if i != len(nics): msg = _("Network interfaces must be assigned consecutively.") self._errors[field_id] = self.error_class([msg]) elif (not settings.NCI_DUPLICATE_VM_NETWORK_INTF) and (net_id in [n["network_id"] for n in nics]): msg = _("Network is assigned to another interface.") self._errors[field_id] = self.error_class([msg]) # Field level validation will have already checked that the # network ID exists by virtue of being a valid choice. assert net_id in self.networks external = self.networks[net_id].get("router:external", False) else: external = False fixed_subnet_id = None field_id = "eth{0:d}_fixed_ip".format(i) fixed_ip = data.get(field_id) if not fixed_ip: # Value could only be undefined if field level validation # failed since "required=True" for this field. assert self._errors.get(field_id) elif fixed_ip == "auto": if external: msg = _("Selected option is not valid on this network.") self._errors[field_id] = self.error_class([msg]) elif not net_id: msg = _("No network selected.") self._errors[field_id] = self.error_class([msg]) elif fixed_ip == "ext_pool": if external: # Choice won't be available unless global allocation pool # is enabled. assert self.fixed_pub_ips_pool else: msg = _("Selected option is not available on this network.") self._errors[field_id] = self.error_class([msg]) else: try: fixed_ip = netaddr.IPAddress(fixed_ip) except (netaddr.AddrFormatError, ValueError) as e: msg = _("Not a valid IP address format.") self._errors[field_id] = self.error_class([msg]) else: if external: assert self.fixed_pub_ips_enabled if fixed_ip not in self.pub_ips["fixed"]: msg = _("\"{0}\" is not available on this network.".format(fixed_ip)) self._errors[field_id] = self.error_class([msg]) elif fixed_ip in used_ips[net_id]: msg = _("IP address is assigned to another interface.") self._errors[field_id] = self.error_class([msg]) else: nic["fixed_ip"] = fixed_ip used_ips[net_id].add(fixed_ip) else: # Verify that there is a subnet for the selected network # which contains the fixed IP address. subnet_cidr = None for subnet in self.networks[net_id].subnets: subnet_cidr = netaddr.IPNetwork(subnet.cidr) if fixed_ip in subnet_cidr: break else: subnet_cidr = None if not subnet_cidr: msg = _("IP address must be in a subnet range for the selected network.") self._errors[field_id] = self.error_class([msg]) elif fixed_ip == subnet_cidr.network: msg = _("Network address is reserved.") self._errors[field_id] = self.error_class([msg]) elif fixed_ip == subnet_cidr.broadcast: msg = _("Broadcast address is reserved.") self._errors[field_id] = self.error_class([msg]) elif subnet.get("gateway_ip") and (fixed_ip == netaddr.IPAddress(subnet.gateway_ip)): msg = _("IP address is reserved for the subnet gateway.") self._errors[field_id] = self.error_class([msg]) else: fixed_subnet_id = subnet.id # Is the IP address already assigned to a port on # this network? LOG.debug("Getting all ports for network: {0}".format(net_id)) ports = api.neutron.port_list(self.request, tenant_id=self.request.user.project_id, network_id=net_id) found = False for port in ports: for fip in port.fixed_ips: if fip.get("ip_address") and (fixed_ip == netaddr.IPAddress(fip["ip_address"])): found = True break if found: msg = _("IP address is already in use.") self._errors[field_id] = self.error_class([msg]) elif fixed_ip in used_ips[net_id]: msg = _("IP address is assigned to another interface.") self._errors[field_id] = self.error_class([msg]) else: nic["fixed_ip"] = fixed_ip used_ips[net_id].add(fixed_ip) field_id = "eth{0:d}_floating_ip".format(i) floating_ip = data.get(field_id) if floating_ip: assert floating_ip in self.pub_ips["float"] if not net_id: msg = _("No network selected.") self._errors[field_id] = self.error_class([msg]) elif external: msg = _("Floating IPs cannot be used on an external network.") self._errors[field_id] = self.error_class([msg]) elif floating_ip in used_ips["_float_"]: msg = _("IP address is assigned to another interface.") self._errors[field_id] = self.error_class([msg]) else: float_net_id = self.pub_ips["float"][floating_ip].floating_network_id LOG.debug("Looking for a route between the networks {0} and {1}".format(net_id, float_net_id)) ports = api.neutron.port_list(self.request, network_id=net_id, device_owner="network:router_interface") found = False for port in ports: if fixed_subnet_id and (fixed_subnet_id not in [x.get("subnet_id") for x in port.fixed_ips]): LOG.debug("Ignoring port {0} due to subnet mismatch".format(port.id)) continue router = api.neutron.router_get(self.request, port.device_id) if router.get("external_gateway_info", {}).get("network_id") == float_net_id: LOG.debug("Found path to floating IP network via router: {0}".format(router.id)) found = True break if not found: if self.networks[net_id].shared: # The Neutron API doesn't return interface ports for routers # owned by another tenant, even if that network is shared # with us. So we just have to accept the user's request. LOG.warning("Unable to locate router for floating IP on shared network: {0}".format(net_id)) else: msg = _("No router interface found that connects the selected network with the floating IP.") self._errors[field_id] = self.error_class([msg]) else: nic["floating_ip"] = floating_ip used_ips["_float_"].add(floating_ip) if "network_id" in nic: nics.append(nic) except: exceptions.handle(self.request) msg = _("Validation failed with an unexpected error.") raise forms.ValidationError(msg) if not nics: msg = _("At least one network interface must be assigned.") raise forms.ValidationError(msg) if settings.NCI_DUPLICATE_VM_NETWORK_INTF: # See "server_create_hook_func()" for why this check is made. float_nets = set([n["network_id"] for n in nics if "floating_ip" in n]) for net_id in float_nets: if len(filter(lambda x: x["network_id"] == net_id, nics)) > 1: msg = _("Networks with a floating IP specified can only be assigned to one interface.") raise forms.ValidationError(msg) data["nics"] = nics return data # NB: We aren't subclassing the upstream implementation of this step. class SetNetwork(workflows.Step): action_class = SetNetworkAction contributes = ("nics", "network_id") template_name = "project/instances/../instances_nci/_update_networks.html" def contribute(self, data, context): context = super(SetNetwork, self).contribute(data, context) if context["nics"]: # Emulate the network list set in the upstream implementation. context["network_id"] = [n["network_id"] for n in context["nics"]] return context class BootstrapConfigAction(workflows.Action): puppet_action = forms.ChoiceField( label=_("Puppet Action"), required=True, choices=[x for x in PUPPET_ACTION_CHOICES if x[0] == "none"], initial="none", help_text=_("Puppet command to execute.")) puppet_env = forms.RegexField( label=_("Puppet Environment"), required=False, regex=REPO_BRANCH_REGEX, help_text=_("Puppet configuration environment (or equivalent branch name) to deploy.")) install_updates = forms.ChoiceField( label=_("Install Updates"), required=True, choices=[ ("reboot", _("Yes (reboot if required)")), ("yes", _("Yes (don't reboot)")), ("no", _("No")), ], initial="reboot", help_text=_("Whether to install system updates. (Recommended)")) class Meta(object): name = _("Initial Boot") help_text_template = ("project/instances/../instances_nci/_bootstrap_help.html") def __init__(self, request, context, *args, **kwargs): super(BootstrapConfigAction, self).__init__(request, context, *args, **kwargs) # Check if the project's VL config exists. We only assign a default # Puppet action if it does. This will allow projects not using the # VL environment to still be able to launch VMs without having to # change the Puppet action first. is_vl = False try: container = nci_private_container_name(request) config_obj_name = nci_vl_project_config_name() is_vl = api.swift.swift_object_exists(request, container, config_obj_name) except: exceptions.handle(request) if is_vl: obj = None try: obj = api.swift.swift_get_object(request, container, config_obj_name, resp_chunk_size=None) except: exceptions.handle(request) msg = _("VL project configuration not found.") messages.warning(request, msg) if obj: project_cfg = None try: project_cfg = json.loads(obj.data) except ValueError as e: LOG.exception("Error parsing project configuration: {0}".format(e)) messages.error(request, str(e)) msg = _("VL project configuration is corrupt.") messages.warning(request, msg) if project_cfg: self.fields["puppet_env"].initial = project_cfg.get("puppet_env", "") if project_cfg.get("repo_key") and project_cfg.get("eyaml_key") and project_cfg.get("eyaml_cert"): self.fields["puppet_action"].choices = PUPPET_ACTION_CHOICES self.fields["puppet_action"].initial = "apply" default_action = project_cfg.get("puppet_action", "auto") if default_action != "auto": avail_actions = [x[0] for x in self.fields["puppet_action"].choices] if default_action in avail_actions: self.fields["puppet_action"].initial = default_action def clean(self): data = super(BootstrapConfigAction, self).clean() if (data.get("puppet_action", "none") != "none") and not data.get("puppet_env"): msg = _("An environment name is required for the selected Puppet action.") raise forms.ValidationError(msg) return data class BootstrapConfig(workflows.Step): action_class = BootstrapConfigAction contributes = ("puppet_action", "puppet_env", "install_updates") template_name = "project/instances/../instances_nci/_bootstrap_step.html" def server_create_hook_func(request, context, floats): def _impl(*args, **kwargs): float_nets = {} kwargs["nics"] = [] nics = context["nics"] or [] for n in nics: # https://github.com/openstack/python-novaclient/blob/2.20.0/novaclient/v1_1/servers.py#L528 nic = {"net-id": n["network_id"]} ip = n.get("fixed_ip") if ip: if ip.version == 6: nic["v6-fixed-ip"] = str(ip) else: assert ip.version == 4 nic["v4-fixed-ip"] = str(ip) kwargs["nics"].append(nic) if "floating_ip" in n: assert n["network_id"] not in float_nets float_nets[n["network_id"]] = n["floating_ip"] srv = api.nova.server_create(*args, **kwargs) if float_nets: # Find the ports created for the new instance which we need to # associate each floating IP with. We have to wait until the # ports are created by Neutron. Note that the only unique # information we have to identify which port should be paired # with each floating IP is the network ID. Hence we don't # support more than one interface connected to the same network # when floating IPs are specified. try: max_attempts = 15 attempt = 0 while attempt < max_attempts: attempt += 1 LOG.debug("Fetching network ports for instance: {0}".format(srv.id)) ports = api.neutron.port_list(request, device_id=srv.id) for p in ports: LOG.debug("Found port: id={0}; owner={1}; network={2}".format(*[p.get(x) for x in ["id", "device_owner", "network_id"]])) if p.get("device_owner", "").startswith("compute:") and (p.get("network_id") in float_nets): for t in api.network.floating_ip_target_list_by_instance(request, srv.id): LOG.debug("Got floating IP target: {0}".format(t)) if t.startswith(p.id): float_id = float_nets[p.network_id] api.network.floating_ip_associate(request, float_id, t) del float_nets[p.network_id] msg = _("Floating IP {0} associated with new instance.".format(floats[float_id].ip)) messages.info(request, msg) break if not float_nets: # All floating IPs have now been assigned. srv = api.nova.server_get(request, srv.id) break status = api.nova.server_get(request, srv.id).status.lower() if status == "active": if max_attempts != 2: LOG.debug("VM state has become active") max_attempts = 2 attempt = 0 elif status != "build": LOG.debug("Aborting wait loop due to server status: {0}".format(status)) break LOG.debug("Waiting for network port allocation") time.sleep(2) except: exceptions.handle(request) for f in float_nets.itervalues(): msg = _("Failed to associate floating IP {0} with new instance.".format(floats[f].ip)) messages.warning(request, msg) return srv return _impl def step_generator(): for step in base_mod.LaunchInstance.default_steps: if step == base_mod.SetInstanceDetails: yield SetInstanceDetails elif step == base_mod.SetAccessControls: yield SetAccessControls elif step == base_mod.SetNetwork: yield SetNetwork elif step == base_mod.PostCreationStep: # Replace the "Post-Creation" tab with our bootstrap parameters. yield BootstrapConfig else: yield step class NCILaunchInstance(base_mod.LaunchInstance): default_steps = [x for x in step_generator()] @sensitive_variables("context") def validate(self, context): if context["count"] > 1: keys = set(itertools.chain.from_iterable(context["nics"])) if filter(lambda k: k.endswith("_ip"), keys): msg = _("Multiple instances cannot be launched with the same IP address.") self.add_error_to_step(msg, SetNetworkAction.slug) # Missing from "add_error_to_step()"... self.get_step(SetNetworkAction.slug).has_errors = True return False return True @sensitive_variables("context") def handle(self, request, context): cloud_cfg = {} if context["puppet_action"] != "none": # Load the project's VL configuration. try: obj = api.swift.swift_get_object(request, nci_private_container_name(request), nci_vl_project_config_name(), resp_chunk_size=None) except: exceptions.handle(request) msg = _("VL project configuration not found.") messages.error(request, msg) return False try: project_cfg = json.loads(obj.data) except ValueError as e: LOG.exception("Error parsing project configuration: {0}".format(e)) messages.error(request, str(e)) msg = _("VL project configuration is corrupt.") messages.error(request, msg) return False # Add the cloud-config parameters for the "nci.puppet" module. puppet_cfg = cloud_cfg.setdefault("nci", {}).setdefault("puppet", {}) puppet_cfg["action"] = context["puppet_action"] puppet_cfg["environment"] = context["puppet_env"] repo_cfg = puppet_cfg.setdefault("repo", {}) repo_cfg["path"] = project_cfg.get("repo_path", "") eyaml_cfg = puppet_cfg.setdefault("eyaml", {}) try: msg = _("Failed to initialise crypto stash.") stash = ncicrypto.CryptoStash(request, project_cfg.get("stash") or {}) msg = _("Failed to load deployment key.") key = stash.load_private_key(project_cfg.get("repo_key")) repo_cfg["key"] = key.cloud_config_dict() msg = _("Failed to load eyaml key.") key = stash.load_private_key(project_cfg.get("eyaml_key")) eyaml_cfg["key"] = key.cloud_config_dict() msg = _("Failed to load eyaml certificate.") cert = stash.load_x509_cert(project_cfg.get("eyaml_cert")) eyaml_cfg["cert"] = cert.cloud_config_dict() except: exceptions.handle(request) messages.error(request, msg) return False cloud_cfg["package_upgrade"] = (context["install_updates"] != "no") cloud_cfg["package_reboot_if_required"] = (context["install_updates"] == "reboot") if "." in context["name"]: cloud_cfg["fqdn"] = context["name"] # Construct the "user data" to inject into the VM for "cloud-init". user_data = MIMEMultipart() try: # Note that JSON is also valid YAML: # http://yaml.org/spec/1.2/spec.html#id2759572 part = MIMEText(json.dumps(cloud_cfg), "cloud-config") user_data.attach(part) except (ValueError, TypeError) as e: LOG.exception("Error serialising userdata: {0}".format(e)) messages.error(request, str(e)) msg = _("Failed to construct userdata for VM instance.") messages.error(request, msg) return False context["script_data"] = user_data.as_string() # We could copy the contents of the base class function here and make # the changes that we need. But that would create a maintenance # headache since for each OpenStack update we'd have to check whether # anything in the original implementation changed and replicate it # here. Instead, we'll rebind the "api.nova.server_create()" function # in the namespace of the base class function to call our hook closure # instead. api_proxy = nciutils.AttributeProxy(base_mod.api) api_proxy.nova = nciutils.AttributeProxy(base_mod.api.nova) floats = self.get_step(SetNetworkAction.slug).action.pub_ips["float"] api_proxy.nova.server_create = server_create_hook_func(request, context, floats) # We have to strip off any function decorators, otherwise the rebind # won't be visible inside the function. Whilst this does rely on some # Python internals, the chances of those changing is significantly # lower especially since RedHat doesn't change the Python version # in a major release series. base_func = nciutils.undecorate(super(NCILaunchInstance, self).handle.__func__, "handle") g_dict = base_func.__globals__ g_dict.update({"api": api_proxy}) return types.FunctionType(base_func.__code__, g_dict)(self, request, context) # vim:ts=4 et sw=4 sts=4:
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,386
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/nci/crypto.py
# openstack_dashboard.local.nci.crypto # # Copyright (c) 2015, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import base64 import binascii import datetime import hashlib import hmac import logging import os import os.path import paramiko.rsakey #import pdb ## DEBUG import six import subprocess import time import uuid import urllib import urlparse from StringIO import StringIO try: from cryptography import x509 from cryptography.exceptions import InvalidSignature from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding, rsa from cryptography.hazmat.primitives.serialization import BestAvailableEncryption, Encoding, load_pem_private_key, NoEncryption, PrivateFormat from cryptography.x509.oid import NameOID USE_NEW_CRYPTO_LIB=True except: from OpenSSL import crypto from Crypto.PublicKey import RSA as pycrypto_RSA USE_NEW_CRYPTO_LIB=False from django.conf import settings from openstack_dashboard import api from .constants import * from .exceptions import CryptoError LOG = logging.getLogger(__name__) TEMP_URL_KEY_METADATA_HDR = "X-Account-Meta-Temp-URL-Key" class CryptoStashItem(object): def __init__(self, impl, stash, metadata): self._impl = impl self._stash = stash if metadata is None: # Avoid overwriting an existing object in case we happen to get a # duplicate UUID (should be very rare). Swift API doesn't have an # atomic "create unique" function so there is a race condition here # but risk should be low. container = nci_private_container_name(self._request) ref = "{0}/{1}".format(self._stash._base_ref, uuid.uuid4()) if api.swift.swift_object_exists(self._request, container, ref): ref = "{0}/{1}".format(self._stash._base_ref, uuid.uuid4()) if api.swift.swift_object_exists(self._request, container, ref): raise CryptoError("Unable to generate unique stash item reference") else: ref = metadata.get("ref") if not ref: raise CryptoError("Incomplete metadata for crypto stash item") self._ref = ref @property def _request(self): return self._stash._request @property def ref(self): """Returns the stash reference for this item.""" assert self._ref return self._ref @property def public_ref(self): """Returns the full public URL stash reference for this item.""" endpoint = urlparse.urlsplit(api.base.url_for(self._request, "object-store")) path = "/".join([ endpoint.path, urllib.quote(nci_private_container_name(self._request)), urllib.quote(self.ref), ]) return urlparse.urlunsplit(list(endpoint[:2]) + [path, "", ""]) def metadata(self): """Returns a dictionary of the item's metadata for storage.""" return { "version": 1, "ref": self.ref, } def generate_temp_url(self): """Generates a signed temporary URL for this item.""" secret = swift_get_temp_url_key(self._request) if not secret: raise CryptoError("Temporary URL key not configured in object storage") # The signature needs to include the full path to the object as # requested by the client. public_url = urlparse.urlsplit(self.public_ref) sig_path = public_url.path if sig_path.startswith("/swift/"): # Ceph uses a URI prefix to distinguish between S3 and Swift API # calls so we need to remove this otherwise the calculated # signature will be wrong. # https://github.com/ceph/ceph/blob/v0.80.7/src/rgw/rgw_swift.cc#L578 sig_path = sig_path[6:] expires = int(time.time()) + 3600 data = "\n".join(["GET", str(expires), sig_path]) LOG.debug("Temporary URL data for signature: {0}".format(repr(data))) sig = hmac.new(secret.encode(), data.encode(), hashlib.sha1).hexdigest() params = urllib.urlencode({ "temp_url_sig": sig, "temp_url_expires": expires, }) return urlparse.urlunsplit(list(public_url[:3]) + [params, ""]) def cloud_config_dict(self): """Dictionary for referencing item in user-data for a VM instance.""" return { "url": self.generate_temp_url(), } class CryptoStashItemWithPwd(CryptoStashItem): def __init__(self, impl, stash, metadata): super(CryptoStashItemWithPwd, self).__init__(impl, stash, metadata) @property def password(self): s1key = self._stash._s1key assert len(s1key) >= hashlib.sha256().digest_size # Second stage of HKDF simplified since we only need one round to # reach a key length equal to the digest size. h = hmac.new(s1key, digestmod=hashlib.sha256) h.update(self.ref) h.update(six.int2byte(1)) k = h.digest() return base64.b64encode(k) def cloud_config_dict(self): d = super(CryptoStashItemWithPwd, self).cloud_config_dict() d["pw"] = self.password return d class PrivateKey(CryptoStashItemWithPwd): def __init__(self, impl, stash, metadata): super(PrivateKey, self).__init__(impl, stash, metadata) self._cache = {} def export(self): """Exports the private key in encrypted PEM format.""" pw = self.password try: if USE_NEW_CRYPTO_LIB: return self._impl.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, BestAvailableEncryption(pw)) else: return crypto.dump_privatekey(crypto.FILETYPE_PEM, self._impl, "aes-256-cbc", pw) except Exception as e: LOG.exception("Error exporting private key (ref {0}): {1}".format(self.ref, e)) raise CryptoError("Failed to export private key with ref: {0}".format(self.ref)) def fingerprint(self): """Returns the fingerprint of the PKCS#8 DER key.""" try: if USE_NEW_CRYPTO_LIB: der = self._impl.private_bytes(Encoding.DER, PrivateFormat.PKCS8, NoEncryption()) else: pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, self._impl) # Convert from PEM encoding to PKCS#8 DER. # There isn't a way to do this via the PyOpenSSL API so we # have to use PyCrypto instead. der = pycrypto_RSA.importKey(pem).exportKey('DER', pkcs=8) except Exception as e: LOG.exception("Error generating key fingerprint (ref {0}): {1}".format(self.ref, e)) raise CryptoError("Failed to get fingerprint for key with ref: {0}".format(self.ref)) fp = hashlib.sha1(der).digest() return ":".join([binascii.hexlify(x) for x in fp]) @property def _ssh_key(self): if "ssh_key" not in self._cache: if USE_NEW_CRYPTO_LIB: pem = self._impl.private_bytes(Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption()) else: pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, self._impl) if "BEGIN RSA PRIVATE KEY" not in pem: # Convert from PKCS#8 into "traditional" RSA format. # There isn't a way to do this via the PyOpenSSL API so we # have to use PyCrypto instead. pem = pycrypto_RSA.importKey(pem).exportKey('PEM', pkcs=1) self._cache["ssh_key"] = paramiko.rsakey.RSAKey(file_obj=StringIO(pem)) return self._cache["ssh_key"] def ssh_publickey(self): """Exports the public key component in OpenSSH format.""" try: return "{0} {1} {2}".format( self._ssh_key.get_name(), self._ssh_key.get_base64(), self._request.user.project_name, ) except Exception as e: LOG.exception("Error exporting public SSH key (ref {0}): {1}".format(self.ref, e)) raise CryptoError("Failed to export public SSH key with ref: {0}".format(self.ref)) def ssh_fingerprint(self): """Returns the SSH fingerprint of the key.""" try: fp = self._ssh_key.get_fingerprint() except Exception as e: LOG.exception("Error generating SSH key fingerprint (ref {0}): {1}".format(self.ref, e)) raise CryptoError("Failed to get SSH fingerprint for key with ref: {0}".format(self.ref)) return ":".join([binascii.hexlify(x) for x in fp]) class Certificate(CryptoStashItem): def __init__(self, impl, stash, metadata): super(Certificate, self).__init__(impl, stash, metadata) def export(self): """Exports the certificate in PEM format.""" try: if USE_NEW_CRYPTO_LIB: return self._impl.public_bytes(Encoding.PEM) else: return crypto.dump_certificate(crypto.FILETYPE_PEM, self._impl) except Exception as e: LOG.exception("Error exporting certificate (ref {0}): {1}".format(self.ref, e)) raise CryptoError("Failed to export certificate with ref: {0}".format(self.ref)) def fingerprint(self): """Returns the fingerprint of the certificate.""" try: if USE_NEW_CRYPTO_LIB: fp = self._impl.fingerprint(hashes.SHA1()) return ":".join([binascii.hexlify(x) for x in fp]) else: return self._impl.digest("sha1").lower() except Exception as e: LOG.exception("Error generating certificate fingerprint (ref {0}): {1}".format(self.ref, e)) raise CryptoError("Failed to get fingerprint for certificate with ref: {0}".format(self.ref)) def verify_key_pair(self, key): """Verifies that the certificate is paired with the given private key.""" assert isinstance(key, PrivateKey) test_data = base64.b64decode("Ag5Ns98mgdLxiq3pyuNecMCXGUcYopmPNyc6GsJ6wd0=") try: if USE_NEW_CRYPTO_LIB: pad = padding.PSS(padding.MGF1(hashes.SHA256()), padding.PSS.MAX_LENGTH) signer = key._impl.signer(pad, hashes.SHA256()) signer.update(test_data) sig = signer.finalize() verifier = self._impl.public_key().verifier(sig, pad, hashes.SHA256()) verifier.update(test_data) try: verifier.verify() except InvalidSignature: return False else: sig = crypto.sign(key._impl, test_data, "sha256") try: crypto.verify(self._impl, sig, test_data, "sha256") except: return False except Exception as e: LOG.exception("Error verifying certificate/key pair (cert {0}; key {1}): {2}".format(self.ref, key.ref, e)) raise CryptoError("Failed to verify certificate \"{0}\" and key \"{1}\"".format(self.ref, key.ref)) return True # TODO: Use Barbican for storage instead of Swift. However, the following # blueprint will need to be implemented first so that we can retrieve # items via cloud-init in the VM without needing a full user token. # https://blueprints.launchpad.net/nova/+spec/instance-users class CryptoStash(object): def __init__(self, request, params=None): self._request = request self._base_ref = "stash" self._params = {} self._s1key_cache = None if params is not None: self.init_params(params) @property def _s1key(self): if self._s1key_cache is None: if "salt" not in self.params: raise CryptoError("Crypto stash parameters incomplete") try: salt = base64.b64decode(self.params.get("salt")) if len(salt) < 32: raise ValueError("Salt is too short") except Exception as e: LOG.exception("Error decoding crypto stash salt: {0}".format(e)) raise CryptoError("Crypto stash internal fault") if hasattr(settings, "NCI_CRYPTO_STASH_SECRET_PATH"): path = settings.NCI_CRYPTO_STASH_SECRET_PATH else: path = "/etc/openstack-dashboard" if not os.path.isdir(path): path = settings.LOCAL_PATH path = os.path.join(path, ".crypto_stash") try: with open(path) as fh: master = fh.readline().strip() if not master: raise ValueError("Master secret is empty") master = base64.b64decode(master) if len(master) < 32: raise ValueError("Master secret is too short") except Exception as e: LOG.exception("Error loading crypto stash master secret: {0}".format(e)) raise CryptoError("Crypto stash internal fault") # This is the first stage of HKDF: # https://tools.ietf.org/html/rfc5869 # NB: It's assumed that the master key was generated from a # cryptographically strong random source. h = hmac.new(salt, digestmod=hashlib.sha256) h.update(master) self._s1key_cache = h.digest() return self._s1key_cache def init_params(self, params=None): """Creates new or loads existing stash parameters.""" if params is not None: if not isinstance(params, dict): raise CryptoError("Invalid crypto stash parameters type") elif params.get("version", 0) != 1: raise CryptoError("Unsupported crypto stash format") self._params = params else: self._params = { "version": 1, "salt": base64.b64encode(os.urandom(32)), } self._s1key_cache = None @property def initialised(self): return bool(self._params) @property def params(self): """Returns current stash parameters.""" if not self._params: raise CryptoError("Crypto stash parameters not set") return self._params def _save_to_stash(self, item_cls, key_impl): item = item_cls(key_impl, self, None) container = nci_private_container_name(self._request) api.swift.swift_api(self._request).put_object(container, item.ref, item.export(), content_type="text/plain") return item def create_private_key(self): """Generates a new private key and saves it in the stash.""" try: if USE_NEW_CRYPTO_LIB: key_impl = rsa.generate_private_key(65537, 3072, default_backend()) else: key_impl = crypto.PKey() key_impl.generate_key(crypto.TYPE_RSA, 3072) except Exception as e: LOG.exception("Error generating new RSA key: {0}".format(e)) raise CryptoError("Failed to generate new private key") return self._save_to_stash(PrivateKey, key_impl) def import_private_key(self, upload): """Imports an unencrypted private key into the stash.""" if (upload.size < 0) or (upload.size > 262144): raise CryptoError("Uploaded file too large - expected a private key") try: if USE_NEW_CRYPTO_LIB: key_impl = load_pem_private_key(upload.read(), None, default_backend()) key_size = key_impl.key_size else: key_impl = crypto.load_privatekey(crypto.FILETYPE_PEM, upload.read()) key_size = key_impl.bits() except Exception as e: LOG.exception("Error importing RSA key: {0}".format(e)) raise CryptoError("Import failed - expected a PEM encoded unencrypted private key") if key_size < 3072: raise CryptoError("Import failed - key must be 3072 bits or larger") return self._save_to_stash(PrivateKey, key_impl) def load_private_key(self, metadata): """Loads an existing private key from the stash.""" if not isinstance(metadata, dict): raise CryptoError("Metadata missing or invalid type when loading private key") key = PrivateKey(None, self, metadata) swift_obj = api.swift.swift_get_object(self._request, nci_private_container_name(self._request), key.ref, resp_chunk_size=None) pw = key.password try: if USE_NEW_CRYPTO_LIB: LOG.debug("Using new cryptography library") key._impl = load_pem_private_key(swift_obj.data, pw, default_backend()) else: LOG.debug("Using old cryptography library") key._impl = crypto.load_privatekey(crypto.FILETYPE_PEM, swift_obj.data, pw) except Exception as e: LOG.exception("Error loading RSA key: {0}".format(e)) raise CryptoError("Failed to load private key with ref: {0}".format(key.ref)) return key def create_x509_cert(self, key, subject_cn, valid_days): """Returns a new self-signed X.509 certificate in PEM format.""" assert isinstance(key, PrivateKey) now = datetime.datetime.utcnow() nvb = now + datetime.timedelta(days=-1) nva = now + datetime.timedelta(days=valid_days) try: if USE_NEW_CRYPTO_LIB: builder = x509.CertificateBuilder() builder = builder.serial_number(int(uuid.uuid4())) builder = builder.not_valid_before(nvb) builder = builder.not_valid_after(nva) pub_key_impl = key._impl.public_key() builder = builder.public_key(pub_key_impl) cn = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, subject_cn if isinstance(subject_cn, six.text_type) else six.u(subject_cn)), ]) builder = builder.subject_name(cn) builder = builder.issuer_name(cn) builder = builder.add_extension( x509.BasicConstraints(ca=True, path_length=0), True) builder = builder.add_extension( x509.SubjectKeyIdentifier.from_public_key(pub_key_impl), False) builder = builder.add_extension( x509.AuthorityKeyIdentifier.from_issuer_public_key(pub_key_impl), False) cert_impl = builder.sign(key._impl, hashes.SHA256(), default_backend()) else: cert_impl = crypto.X509() cert_impl.set_version(2) cert_impl.set_serial_number(int(uuid.uuid4())) cert_impl.set_notBefore(nvb.strftime("%Y%m%d%H%M%SZ")) cert_impl.set_notAfter(nva.strftime("%Y%m%d%H%M%SZ")) cert_impl.set_pubkey(key._impl) subject = cert_impl.get_subject() subject.CN = subject_cn cert_impl.set_issuer(subject) cert_impl.add_extensions([ crypto.X509Extension(b"basicConstraints", True, b"CA:TRUE, pathlen:0"), crypto.X509Extension(b"subjectKeyIdentifier", False, b"hash", subject=cert_impl), ]) # This has to be done after the above since it can't extract # the subject key from the certificate until it's assigned. cert_impl.add_extensions([ crypto.X509Extension(b"authorityKeyIdentifier", False, b"keyid:always", issuer=cert_impl), ]) cert_impl.sign(key._impl, "sha256") except Exception as e: LOG.exception("Error creating X.509 certificate: {0}".format(e)) raise CryptoError("Failed to create X.509 certificate") return self._save_to_stash(Certificate, cert_impl) def import_x509_cert(self, upload): """Imports a certificate into the stash.""" if (upload.size < 0) or (upload.size > 262144): raise CryptoError("Uploaded file too large - expected an X.509 certificate") try: if USE_NEW_CRYPTO_LIB: cert_impl = x509.load_pem_x509_certificate(upload.read(), default_backend()) else: cert_impl = crypto.load_certificate(crypto.FILETYPE_PEM, upload.read()) except Exception as e: LOG.exception("Error importing X.509 certificate: {0}".format(e)) raise CryptoError("Import failed - expected a PEM encoded X.509 certificate") return self._save_to_stash(Certificate, cert_impl) def load_x509_cert(self, metadata): """Loads an existing certificate from the stash.""" if not isinstance(metadata, dict): raise CryptoError("Metadata missing or invalid type when loading certificate") cert = Certificate(None, self, metadata) swift_obj = api.swift.swift_get_object(self._request, nci_private_container_name(self._request), cert.ref, resp_chunk_size=None) try: if USE_NEW_CRYPTO_LIB: cert._impl = x509.load_pem_x509_certificate(swift_obj.data, default_backend()) else: cert._impl = crypto.load_certificate(crypto.FILETYPE_PEM, swift_obj.data) except Exception as e: LOG.exception("Error loading X.509 certificate: {0}".format(e)) raise CryptoError("Failed to load X.509 certificate with ref: {0}".format(cert.ref)) return cert def delete(self, obj): """Deletes the given item from the stash.""" assert isinstance(obj, CryptoStashItem) container = nci_private_container_name(self._request) api.swift.swift_delete_object(self._request, container, obj.ref) def swift_create_temp_url_key(request): """Assigns a secret key for generating temporary Swift URLs.""" try: secret = base64.b64encode(os.urandom(32)) except Exception as e: LOG.exception("Error generating temp URL key: {0}".format(e)) raise CryptoError("Failed to generate temporary URL key") headers = { TEMP_URL_KEY_METADATA_HDR: secret } api.swift.swift_api(request).post_account(headers) # Workaround for Ceph bug #10668 which doesn't include the key in the # returned metadata even though a value is assigned. # http://tracker.ceph.com/issues/10668 # https://github.com/ceph/ceph/commit/80570e7b6c000f45d81ac3d05240b1f5c85ce125 metadata = api.swift.swift_api(request).head_account() if TEMP_URL_KEY_METADATA_HDR.lower() not in metadata: container = nci_private_container_name(request) api.swift.swift_api(request).put_object(container, "temp-url-key", secret, content_type="text/plain") def swift_get_temp_url_key(request): """Retrieves the secret key for generating temporary Swift URLs.""" secret = None container = nci_private_container_name(request) metadata = api.swift.swift_api(request).head_account() if TEMP_URL_KEY_METADATA_HDR.lower() in metadata: secret = metadata[TEMP_URL_KEY_METADATA_HDR.lower()] try: if api.swift.swift_object_exists(request, container, "temp-url-key"): api.swift.swift_delete_object(request, container, "temp-url-key") except: pass else: # See above notes on Ceph workaround. if api.swift.swift_object_exists(request, container, "temp-url-key"): swift_obj = api.swift.swift_get_object(request, container, "temp-url-key", resp_chunk_size=None) secret = swift_obj.data return secret # vim:ts=4 et sw=4 sts=4:
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,387
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py
# openstack_dashboard.local.dashboards.project_nci.vlconfig.views # # Copyright (c) 2015, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from horizon import forms from .forms import VLConfigForm VLCONFIG_INDEX_URL = "horizon:project:vlconfig:index" class IndexView(forms.ModalFormView): form_class = VLConfigForm form_id = "project_config_form" modal_header = _("Project Configuration") modal_id = "project_config_modal" page_title = _("Project Configuration") submit_label = _("Save") submit_url = reverse_lazy(VLCONFIG_INDEX_URL) success_url = reverse_lazy(VLCONFIG_INDEX_URL) template_name = "project/vlconfig/index.html" # vim:ts=4 et sw=4 sts=4:
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,388
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/enabled/_40_router.py
../../enabled/_40_router.py
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,389
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py
# openstack_dashboard.local.dashboards.admin_nci.pupha.constants # # Copyright (c) 2016, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import re from openstack_dashboard.openstack.common import log as logging from django.utils.translation import ugettext_lazy as _ from django.conf import settings TEMPLATE_NAME = 'admin/pupha/index.html' TABLES_TEMPLATE_NAME = 'admin/pupha/tables.html' SUMMARY_TEMPLATE_NAME = 'horizon/common/_detail_table.html' TITLE = _('Host Aggregate Details') def binary_prefix_scale(b): """Return (prefix, scale) so that (b) B = (b*scale) (prefix)B. For example, binary_prefix_scale(1536) == ('Ki', 1024**-1).""" binary = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei'] scale = 1 for p in binary: if b < 1024: return (p, scale) scale /= 1024. b /= 1024. return (p, scale) def format_bytes(b, precision=0): p, s = binary_prefix_scale(float(b)) format_str = '{{scaled:.{}f}} {{prefix}}B'.format(max(0, int(precision))) return format_str.format(scaled=b*s, prefix=p) def su(vcpus, memory_mb, precision=1): return ('{:.'+str(max(0, int(precision)))+'f}').format(max(vcpus, memory_mb/su.memory_mb)) def short_name(hostname): """ If the given hostname matches the pattern in NCI_HOSTNAME_PATTERN, return a substring of the hostname (the group from the pattern match). This is useful for two things: - making output more concise, by removal of common substring - data matching, e.g. "tc0123" and "tc0123.ncmgmt" refer to same entity """ m = short_name.p.match(hostname) if m: return m.group('name') return hostname def load_settings(): LOG = logging.getLogger(__name__) def get_setting(setting, default): try: return getattr(settings, setting) except AttributeError: LOG.debug('Missing {} in Django settings.'.format(setting)) return default short_name.p = re.compile(get_setting('NCI_HOSTNAME_PATTERN', r'(?P<name>)')) su.memory_mb = get_setting('NCI_SU_MEMORY_MB', 4096.) load_settings()
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,390
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py
# openstack_dashboard.local.dashboards.admin_nci.pupha.views # # Copyright (c) 2016, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import re from openstack_dashboard import api from openstack_dashboard.openstack.common import log as logging from horizon import tabs from horizon import messages from .tabs import TabGroup, DictObject from . import constants from .constants import short_name # separate import because it feels weird having short_name live in constants, so that may change.. # surely there is a cleaner way to do this...? from novaclient.exceptions import NotFound as NotFoundNova from keystoneclient.openstack.common.apiclient.exceptions import NotFound as NotFoundKeystone from django.conf import settings LOG = logging.getLogger(__name__) def get_overcommit_ratios(): """Return {cpu,ram,disk}_allocation_ratio values from django settings. Return 1.0 for any missing allocation ratios. """ setting = 'NCI_NOVA_COMMIT_RATIOS' resources = ['cpu', 'ram', 'disk'] # hard-coded strings to match names in nova.conf ratios = getattr(settings, setting, {}) for r in resources: if r not in ratios: LOG.debug('Missing {} overcommit ratio in {}; assuming value of 1.'.format(r, setting)) ratios[r] = 1. return ratios class HostAggregate(object): """ Has attributes: aggregate -- object from api.nova.aggregate_details_list overcommit -- dict with keys matching "{}_allocation_ratio" in nova.conf (see comment in get_overcommit_ratios) hypervisors -- list of objects with attributes including instances -- list of objects with attributes including project flavor """ def __init__(self, aggregate, hypervisors=None): self.aggregate = aggregate self.hypervisors = [] if hypervisors == None else hypervisors class IndexView(tabs.TabbedTableView): tab_group_class = TabGroup template_name = constants.TEMPLATE_NAME page_title = constants.TITLE def get_tabs(self, request, **kwargs): """ Pass host aggregate data to the TabGroup on construction, as an attribute "host_aggregates" in kwargs, which is a list of HostAggregate objects. This is useful because it avoids re-fetching the same data for each Tab in the TabGroup (which would take some time -- there's no caching). This is a slightly hacky solution, because if the way that TabView instantiates its TabGroup changes such that it's no longer done in get_tabs, this code will need to be updated accordingly. This seemed like this least hacky way of doing it, though. (TabView.get_tabs performs the initialisation of the TabGroup.) """ aggregates = api.nova.aggregate_details_list(request) hypervisors = api.nova.hypervisor_list(request) instances, _ = api.nova.server_list(request, all_tenants=True) projects, _ = api.keystone.tenant_list(request) flavors = api.nova.flavor_list(request) # define these dicts to make it easier to look up objects flavor_d = {f.id : f for f in flavors} project_d = {p.id : p for p in projects} hypervisor_d = {short_name(getattr(h, h.NAME_ATTR)) : h for h in hypervisors} # (only) this list ends up being shared with the TabGroup host_aggregates = [HostAggregate(aggregate=a) for a in aggregates] # if there are no aggregates, invent a HostAggregate to hold everything # (this is hacky but that's okay because nobody should actually want to # use this panel if running a cloud with no host aggregates.. this code # exists just so the dashboard doesn't break in that odd non-use case.) if not host_aggregates: host_aggregates = [HostAggregate(aggregate=DictObject( id = 0, name = '(none)', hosts = [h.service['host'] for h in hypervisors], metadata = {} ))] # check if any instances are missing necessary data, and if so, skip them hypervisor_instances = {} # otherwise, add them to this (short_name => [instance]) for i in instances: # make sure we can tell which hypervisor is running this instance; if not, ignore it try: host = short_name(i.host_server) if host not in hypervisor_d: messages.error(request, 'Instance {} has unknown host, so was ignored.'.format(i.id)) continue except AttributeError: messages.error(request, 'Instance {} is missing host, so was ignored.'.format(i.id)) continue # api.nova.flavor_list (which wraps novaclient.flavors.list) does not get all flavors, # so if we have a reference to one that hasn't been retrieved, try looking it up specifically # (wrap this rather trivially in a try block to make the error less cryptic) if i.flavor['id'] not in flavor_d: try: LOG.debug('Extra lookup for flavor "{}"'.format(i.flavor['id'])) flavor_d[i.flavor['id']] = api.nova.flavor_get(request, i.flavor['id']) except NotFoundNova: messages.error(request, 'Instance {} has unknown flavor, so was ignored.'.format(i.id)) continue # maybe the same thing could happen for projects (haven't actually experienced this one though) if i.tenant_id not in project_d: try: LOG.debug('Extra lookup for project "{}"'.format(i.tenant_id)) project_d[i.tenant_id] = api.keystone.tenant_get(request, i.tenant_id) except NotFoundKeystone: messages.error(request, 'Instance {} has unknown project, so was ignored.'.format(i.id)) continue # expose related objects, so that no further lookups are required i.flavor = flavor_d[i.flavor['id']] i.project = project_d[i.tenant_id] # all the necessary information is present, so populate the dict if host not in hypervisor_instances: hypervisor_instances[host] = [] hypervisor_instances[host].append(i) # assign hypervisors to host aggregates for h in hypervisors: h.instances = hypervisor_instances.get(short_name(getattr(h, h.NAME_ATTR)), []) for ha in host_aggregates: if h.service['host'] in ha.aggregate.hosts: ha.hypervisors.append(h) # get overcommit values and allocated/available resource counts oc = get_overcommit_ratios() p = re.compile(r'^(?P<resource>cpu|ram|disk)_allocation_ratio$') for h in host_aggregates: h.overcommit = {k:oc[k] for k in oc} # copy default overcommit values for k in h.aggregate.metadata: m = p.match(k) if m: try: h.overcommit[m.group('resource')] = float(h.aggregate.metadata[k]) except ValueError: LOG.debug('Could not parse host aggregate "{key}" metadata value "{value}" as float.'.format(key=k, value=h.aggregate.metadata[k])) continue return super(IndexView, self).get_tabs(request, host_aggregates=host_aggregates, **kwargs)
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,391
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/enabled/_30_settings.py
../../enabled/_30_settings.py
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,392
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/identity_nci/projects/workflows.py
# openstack_dashboard.local.dashboards.identity_nci.projects.workflows # # Copyright (c) 2015, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # #import pdb ## DEBUG from openstack_dashboard.dashboards.identity.projects import workflows as base_mod BASIC_MEMBERSHIP_TEMPLATE = "identity/projects/../projects_nci/_workflow_step_update_members_basic.html" class NCICreateProject(base_mod.CreateProject): def __init__(self, request=None, context_seed=None, entry_point=None, *args, **kwargs): super(NCICreateProject, self).__init__(request=request, context_seed=context_seed, entry_point=entry_point, *args, **kwargs) members_step = self.get_step(base_mod.UpdateProjectMembersAction.slug) members_step.template_name = BASIC_MEMBERSHIP_TEMPLATE groups_step = self.get_step(base_mod.UpdateProjectGroupsAction.slug) if groups_step: groups_step.template_name = BASIC_MEMBERSHIP_TEMPLATE class NCIUpdateProject(base_mod.UpdateProject): def __init__(self, request=None, context_seed=None, entry_point=None, *args, **kwargs): super(NCIUpdateProject, self).__init__(request=request, context_seed=context_seed, entry_point=entry_point, *args, **kwargs) members_step = self.get_step(base_mod.UpdateProjectMembersAction.slug) members_step.template_name = BASIC_MEMBERSHIP_TEMPLATE groups_step = self.get_step(base_mod.UpdateProjectGroupsAction.slug) if groups_step: groups_step.template_name = BASIC_MEMBERSHIP_TEMPLATE # vim:ts=4 et sw=4 sts=4:
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,393
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/identity_nci/users/panel.py
../../../../dashboards/identity/users/panel.py
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,394
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/nci/utils.py
# openstack_dashboard.local.nci.utils # # Copyright (c) 2014, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # def subclass_meta_type(base_class): """Returns a "Meta" type using the given base class. This is required because "horizon.workflows.base.ActionMetaclass" removes "Meta" from the class namespace during initialisation which in turn means that it can't be referenced in a subclass since it no longer exists. Instead, we copy all the attributes from the base class which includes those assigned from the original "Meta" class by "ActionMetaclass". """ return type("Meta", (object,), dict(filter(lambda x: not x[0].startswith("_"), vars(base_class).iteritems()))) def undecorate(func, name): """Returns original undecorated version of a given function.""" if hasattr(func, "__closure__") and func.__closure__: for cell in func.__closure__: if cell.cell_contents is not func: rv = undecorate(cell.cell_contents, name) if rv: return rv if hasattr(func, "__code__") and hasattr(func, "__name__") and (func.__name__ == name): return func else: return None class AttributeProxy(object): """Wraps a Python object allowing local modifications to the attribute namespace.""" def __init__(self, obj): self.__wrapped = obj def __getattr__(self, name): return getattr(self.__wrapped, name) # vim:ts=4 et sw=4 sts=4:
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,395
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/dashboards/admin_nci/hvlist/views.py
# openstack_dashboard.local.dashboards.admin_nci.hvlist.views # # Copyright (c) 2015, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from horizon import views, messages from openstack_dashboard import api from iso8601 import parse_date from colorsys import hsv_to_rgb import re from django.conf import settings from openstack_dashboard.openstack.common import log as logging LOG = logging.getLogger(__name__) def hypervisor_status_symbol(h): return hypervisor_status_symbol.symbols[h.status] if h.status in hypervisor_status_symbol.symbols else '?' hypervisor_status_symbol.symbols = { # see http://docs.openstack.org/developer/nova/v2/2.0_server_concepts.html 'ACTIVE' : '', 'SHUTOFF' : '&darr;', 'ERROR' : '&#x2715;', # this is a big cross X } def short_name(hostname): """If the given hostname matches the pattern specified below, return a substring of the hostname (the group from the pattern match).""" m = short_name.p.match(hostname) if m: return m.group('n') return hostname short_name.p = re.compile(r'^tc(?P<n>\d+)$') def binary_prefix_scale(b): """Return (prefix, scale) so that (b) B = (b*scale) (prefix)B. For example, binary_prefix_scale(1536) == ('Ki', 1024**-1).""" binary = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei'] scale = 1 for p in binary: if b < 1024: return (p, scale) scale /= 1024. b /= 1024. return (p, scale) def usage_string(now, tot): """Return something like "0.5 / 1.0 kB" from now,tot=512,1024.""" prefix, scale = binary_prefix_scale(tot) now *= scale tot *= scale def pretty(n): """Normally it is fine to round display values to nearest int, but for positive values < 1 it is helpful to show that they are nonzero.""" if n >= 1: return '{:.0f}'.format(n) if n > 0: return '{:.1f}'.format(n) return '0' return '{n} / {t} {p}B'.format(n=pretty(now), t=pretty(tot), p=prefix) def hypervisor_color(cpu_utilisation, memory_utilisation, disk_utilisation): """Return 12-bit hexadecimal color string (e.g. "#d37") for hypervisor with the given cpu, memory and disk utilisations. (These are floating-point values between 0 and 1.) This implementation uses linear interpolation in hsv space between green and red, based on the highest of the three resource utilisations. """ load = max(cpu_utilisation, memory_utilisation, disk_utilisation) hue0, hue1 = 1/3., 0 # green, red hard-coded because that's how i roll hue = hue0 + min(load,1)*(hue1-hue0) # lerp r, g, b = hsv_to_rgb(hue, 0.85, 0.9) r, g, b = ('0123456789abcdef'[int(15*x+0.5)] for x in (r,g,b)) return '#{0}{1}{2}'.format(r, g, b) def get_overcommit_ratios(): """Return {cpu,ram,disk}_allocation_ratio values from django settings. Return 1.0 for any missing allocation ratios. """ setting = 'NCI_NOVA_COMMIT_RATIOS' resources = ['cpu', 'ram', 'disk'] # hard-coded strings to match names in nova.conf ratios = getattr(settings, setting, {}) for r in resources: if r not in ratios: LOG.debug('Missing {} overcommit ratio in {}; assuming value of 1.'.format(r, setting)) ratios[r] = 1. return ratios class AggregateHack(object): def __init__(self, hypervisors): self.id = 0 self.name = '(none)' self.hosts = [h.service['host'] for h in hypervisors] self.metadata = {} class IndexView(views.APIView): template_name = 'admin/hvlist/index.html' def get_data(self, request, context, *args, **kwargs): # grab all the data aggregates = api.nova.aggregate_details_list(request) hypervisors = api.nova.hypervisor_list(request) instances, _ = api.nova.server_list(request, all_tenants=True) projects, _ = api.keystone.tenant_list(request) flavs = api.nova.flavor_list(request) # reorganise some if not aggregates: aggregates = [AggregateHack(hypervisors)] host_aggregates = [{'name':a.name, 'hypervisors':[]} for a in aggregates] projects = {p.id : p for p in projects} flavs = {f.id : f for f in flavs} hypervisor_instances = {} # OS-EXT-SRV-ATTR:host : [instance] for i in instances: # make sure we can tell which hypervisor is running this instance; if not, ignore it try: host = getattr(i, 'OS-EXT-SRV-ATTR:host') except AttributeError: messages.error(request, 'could not get OS-EXT-SRV-ATTR:host attribute of instance '+str(i.id)+' ('+str(i.name)+'); it will be ignored') continue # api.nova.flavor_list (which wraps novaclient.flavors.list) does not get all flavors, # so if we have a reference to one that hasn't been retrieved, try looking it up specifically # (wrap this rather trivially in a try block to make the error less cryptic) if i.flavor['id'] not in flavs: try: flavs[i.flavor['id']] = api.nova.flavor_get(request, i.flavor['id']) LOG.debug('Extra lookup for flavor "'+str(i.flavor['id'])+'"') except NotFound as e: messages.error(request, 'Instance '+i.id+' has unknown flavor, so will be ignored.') continue # maybe the same thing could happen for projects (haven't actually experienced this one though) if i.tenant_id not in projects: try: projects[i.tenant_id] = api.keystone.tenant_get(request, i.tenant_id) LOG.debug('Extra lookup for project "'+str(i.tenant_id)+'"') except NotFound as e: messages.error(request, 'Instance '+i.id+' has unknown project, so will be ignored.') continue # extract flavor data flav = flavs[i.flavor['id']] try: ephemeral = getattr(flav, 'OS-FLV-EXT-DATA:ephemeral') except AttributeError: messages.error(request, 'could not get OS-FLV-EXT-DATA:ephemeral attribute of flavor '+str(flav.id)+' ('+str(flav.name)+'); associated instance will be ignored') continue # everything's sane, so set some fields for the template to use def format_bytes(b): # formatter for bytes p, s = binary_prefix_scale(b) return '{scaled:.0f} {prefix}B'.format(scaled=b*s, prefix=p) i.project = projects[i.tenant_id] i.created = parse_date(i.created) i.flavor_name = flav.name i.flavor_vcpus = float(flav.vcpus) i.flavor_memory_bytes = float(flav.ram) * 1024**2 i.flavor_disk_bytes = (float(flav.disk) + float(ephemeral)) * 1024**3 i.flavor_description = '{vcpus} / {memory} / {disk}'.format( vcpus = flav.vcpus, memory = format_bytes(i.flavor_memory_bytes), disk = format_bytes(i.flavor_disk_bytes) ) # maintain lists of which instances belong to which hypervisors if host not in hypervisor_instances: hypervisor_instances[host] = [] hypervisor_instances[host].append(i) # get overcommit values oc = get_overcommit_ratios() p = re.compile(r'^(?P<resource>cpu|ram|disk)_allocation_ratio$') for (a, h) in zip(aggregates, host_aggregates): h['overcommit'] = {k:oc[k] for k in oc} # copy default overcommit values for k in a.metadata: m = p.match(k) if m: try: h['overcommit'][m.group('resource')] = float(a.metadata[k]) except ValueError: LOG.debug('Could not parse host aggregate "{key}" metadata value "{value}" as float.'.format(key=k, value=a.metadata[k])) continue h['pretty_overcommit'] = '{cpu} / {ram} / {disk}'.format(**h['overcommit']) # assign hosts to host aggregates for h in hypervisors: for (ha, agg) in zip(host_aggregates, aggregates): if h.service['host'] in agg.hosts: ha['hypervisors'].append(h) for ha in host_aggregates: for h in ha['hypervisors']: h.host = h.service['host'] h.short_name = short_name(h.host) h.instances = hypervisor_instances[h.host] if h.host in hypervisor_instances else [] # convert number of vcpus used (n)ow, and (t)otal available, to float, for arithmetic later on vcpus_used, total_vcpus = float(h.vcpus_used), float(h.vcpus) * ha['overcommit']['cpu'] memory_bytes_used, total_memory_bytes = float(h.memory_mb_used)*1024**2, float(h.memory_mb)*1024**2 * ha['overcommit']['ram'] disk_bytes_used, total_disk_bytes = float(h.local_gb_used)*1024**3, float(h.local_gb)*1024**3 * ha['overcommit']['disk'] # save these values for scaling visual elements later on... h.max_vcpus = max(vcpus_used, total_vcpus) h.max_memory_bytes = max(memory_bytes_used, total_memory_bytes) h.max_disk_bytes = max(disk_bytes_used, total_disk_bytes) # colour hypervisors that are up h.color = hypervisor_color(vcpus_used/total_vcpus, memory_bytes_used/total_memory_bytes, disk_bytes_used/total_disk_bytes) if h.state == 'up' else '#999' # calculate how much of the hypervisor's resources each instance is using for i in h.instances: i.status_symbol = hypervisor_status_symbol(i) i.cpuu = i.flavor_vcpus i.memu = i.flavor_memory_bytes i.disku = i.flavor_disk_bytes # count resources used by host but not allocated to any instance h.cpuu = (vcpus_used - sum(i.flavor_vcpus for i in h.instances)) h.memu = (memory_bytes_used - sum(i.flavor_memory_bytes for i in h.instances)) h.disku = (disk_bytes_used - sum(i.flavor_disk_bytes for i in h.instances)) # usage strings for cpu/mem/disk h.cpu_usage = '{n:d} / {t:.2g}'.format(n=int(vcpus_used), t=total_vcpus) h.mem_usage = usage_string(memory_bytes_used, total_memory_bytes) h.disk_usage = usage_string(disk_bytes_used, total_disk_bytes) # are resources overcommitted? h.cpu_overcommit = 'overcommitted' if vcpus_used > total_vcpus else '' h.mem_overcommit = 'overcommitted' if memory_bytes_used > total_memory_bytes else '' h.disk_overcommit = 'overcommitted' if disk_bytes_used > total_disk_bytes else '' # sort lists of hypervisors in host aggregates ha['hypervisors'] = sorted(ha['hypervisors'], key=lambda hyp: hyp.short_name) # scale by 100 everything that will be rendered as a percentage... # this would be better in a custom template tag, but here is a link # to the documentation I could find about how to do that in horizon: resbar_width = 100 for h in hypervisors: h.cpuu *= resbar_width / h.max_vcpus h.memu *= resbar_width / h.max_memory_bytes h.disku *= resbar_width / h.max_disk_bytes for i in h.instances: i.cpuu *= resbar_width / h.max_vcpus i.memu *= resbar_width / h.max_memory_bytes i.disku *= resbar_width / h.max_disk_bytes context['total_hypervisors'] = len(hypervisors) context['host_aggregates'] = host_aggregates context['used_count'] = sum(1 for h in hypervisors if h.instances) context['instance_count'] = sum(len(h.instances) for h in hypervisors) return context
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,396
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/enabled/_25_identity.py
DASHBOARD = 'identity' # See also: _10_project.py ADD_INSTALLED_APPS = [ 'openstack_dashboard.local.dashboards.identity_nci', 'openstack_dashboard.dashboards.identity', ]
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,397
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/nci/constants.py
# openstack_dashboard.local.nci.constants # # Copyright (c) 2015, NCI, Australian National University. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import os from django.conf import settings from django.utils.translation import ugettext_lazy as _ __all__ = ( "REPO_PATH_REGEX", "REPO_BRANCH_REGEX", "PUPPET_ACTION_CHOICES", "NCI_PVT_CONTAINER_PREFIX", "nci_private_container_name", "nci_vl_project_config_name", ) REPO_PATH_REGEX = r"^[a-zA-Z][-a-zA-Z0-9_./]*\.git$" REPO_BRANCH_REGEX = r"^[a-zA-Z][-a-zA-Z0-9_./]*$" PUPPET_ACTION_CHOICES = [ ("apply", _("Apply")), ("r10k-deploy", _("R10k Deploy")), ("none", _("None")), ] NCI_PVT_CONTAINER_PREFIX = "nci-private-" def nci_private_container_name(request): return NCI_PVT_CONTAINER_PREFIX + request.user.project_id def nci_vl_project_config_name(): if hasattr(settings, "NCI_VL_PROJECT_CFG_SUFFIX"): suffix = settings.NCI_VL_PROJECT_CFG_SUFFIX else: suffix = os.uname()[1].split(".")[0] assert suffix if suffix: return "project-config-{0}".format(suffix) else: return "project-config" # vim:ts=4 et sw=4 sts=4:
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,398
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/enabled/_50_project_add_panelgrp_vl.py
PANEL_GROUP_DASHBOARD = 'project' PANEL_GROUP = 'virtlab' PANEL_GROUP_NAME = 'Virtual Lab'
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,399
NCI-Cloud/horizon
refs/heads/nci/kilo
/openstack_dashboard/local/nci/settings_defaults.py
# Defaults for the NCI Partner Cloud dashboard. These can be overridden in # the "local_settings.py" file. SESSION_TIMEOUT = 86400 # Protect CSRF/session cookies from cross-site scripting. CSRF_COOKIE_HTTPONLY = True SESSION_COOKIE_HTTPONLY = True # Hook for replacing built-in dashboard panels. HORIZON_CONFIG["customization_module"] = "openstack_dashboard.local.nci.customisation" # Add the "local" directory to the "INSTALLED_APPS" path so that we can # publish static files from there. # NB: This doesn't apply to static files served via Apache. # TODO: Change logo using new theme support instead? # TODO: Investigate "AUTO_DISCOVER_STATIC_FILES" in Liberty or later. ADD_INSTALLED_APPS = [ 'openstack_dashboard.local', ] # Maximum number of vNICs to attach when launching a VM. NCI_VM_NETWORK_INTF_LIMIT = 4 # Whether to permit two or more vNICs to be connected to the same network. # In the Icehouse release, Nova rejects all such requests with a # "NetworkDuplicated" exception. But starting in Juno there is a new # configuration option which can enable it (default is off): # https://github.com/openstack/nova/commit/322cc9336fe6f6fe9b3f0da33c6b26a3e5ea9b0c # And from Liberty onwards, the option will be removed and it will # be enabled by default: # https://github.com/openstack/nova/commit/4306d9190f49e7fadf88669d18effedabc880d3b NCI_DUPLICATE_VM_NETWORK_INTF = False # Role that grants users the ability to attach a VM to the external network. NCI_EXTERNAL_NET_PERM = "openstack.roles.nci_external_net" # Per-tenant fixed public IP address allocations. The default of an empty # dictionary means that all tenants will use the global IP allocation pool. NCI_FIXED_PUBLIC_IPS = {} # How much memory per vcpu in 1 SU (service unit, base unit for billing) NCI_SU_MEMORY_MB = 4096. # Pattern to match hypervisor.hypervisor_hostname (e.g. "tc097.ncmgmt") and # instance.host_server (e.g. "tc097"), with common part as group 'name' NCI_HOSTNAME_PATTERN = r'^(?P<name>tc\d+)(\.ncmgmt)?$'
{"/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/containers/views.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/instances/workflows/create_instance.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/nci/crypto.py": ["/openstack_dashboard/local/nci/constants.py"], "/openstack_dashboard/local/dashboards/project_nci/vlconfig/views.py": ["/openstack_dashboard/local/dashboards/project_nci/vlconfig/forms.py"], "/openstack_dashboard/local/dashboards/admin_nci/pupha/views.py": ["/openstack_dashboard/local/dashboards/admin_nci/pupha/tabs.py", "/openstack_dashboard/local/dashboards/admin_nci/pupha/constants.py"]}
59,402
squirl/squirl
refs/heads/master
/squirl/migrations/0009_auto_20150905_1622.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import squirl.models class Migration(migrations.Migration): dependencies = [ ('squirl', '0008_auto_20150904_2245'), ] operations = [ migrations.RemoveField( model_name='location', name='name', ), migrations.AddField( model_name='location', name='city', field=models.CharField(default=b'Unnamed', max_length=100), ), migrations.AddField( model_name='location', name='state', field=models.ForeignKey(default=squirl.models.DEFAULT_STATE, to='squirl.State'), ), ]
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,403
squirl/squirl
refs/heads/master
/squirl/groupForms.py
from django import forms from django.db import models from .models import Group, Squirl, SubGroupNotification, ParentEventNotice class JoinGroupRequestForm(forms.Form): user = forms.CharField(widget= forms.HiddenInput()) group = forms.CharField(widget =forms.HiddenInput()) FORM_CHOICES=( (0, 'View Later'), (1,'Decline'), (2,'Owner'), (3, 'Member'), (4, 'Editor'), ) role = forms.ChoiceField(choices=FORM_CHOICES, initial = 0) class CreateSubGroupRequestForm(forms.Form): group1 = forms.CharField() FORM_CHOICES=( (0, 'Child'), (1, 'Parent'), ) role = forms.ChoiceField(choices=FORM_CHOICES, initial=0) group2 = forms.ModelChoiceField(queryset=Group.objects.all()) class SubGroupNotificationForm(forms.Form): ## fromGroup = forms.ModelChoiceField(queryset=Group.objects.all(),widget= forms.HiddenInput()) ## toGroup = forms.ModelChoiceField(queryset=Group.objects.all(), widget= forms.HiddenInput()) ## CHOICES=( ## (0, 'Child'), ## (1, 'Parent'), ## (2, 'Both'), ## ) ## role = forms.ChoiceField(choices=CHOICES) subNoticeModel = forms.ModelChoiceField(queryset= SubGroupNotification.objects.all(), widget= forms.HiddenInput()) ACTIONS = ( (0, "View Later"), (1, "Accept"), (2, "Decline"), ) action = forms.ChoiceField(choices=ACTIONS, initial =0) class ParentEventNoticeForm(forms.Form): ACTIONS = ( (0, "View Later"), (1, "Accept"), (2, "Decline"), ) choice = forms.ChoiceField(choices=ACTIONS, initial =0) notice = forms.ModelChoiceField(queryset= ParentEventNotice.objects.all(), widget= forms.HiddenInput())
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,404
squirl/squirl
refs/heads/master
/squirl/forms.py
from django import forms from django.db import models from django.forms import ModelForm from django.contrib.auth.models import User from django.core.validators import RegexValidator from .models import Location, Group, Squirl, Relation, Connection, Interest, Event, Address, State from django.forms import MultiWidget alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.', code = 'invalid_characters') standard_validator = RegexValidator(r'^[0-9a-zA-Z-]*$', 'Only alphanumeric characters and "-" are allowed.', code = 'invalid_characters') class InterestsForm(forms.Form): interest=forms.CharField( max_length=150, required=True, validators=[alphanumeric], ) class CreateEventForm(forms.Form): error_css_class = 'error' required_css_class = 'required' isUserEvent = forms.BooleanField( widget=forms.CheckboxInput(attrs={'onclick': 'javascript:viewGroup()'}), label = 'User Event', required = False, initial = False ) title = forms.CharField( max_length = 150, required = True, validators=[standard_validator] ) startTime = forms.SplitDateTimeField( input_time_formats=['%H:%M'], input_date_formats =['%m/%d/%Y'], label = 'Start Time', widget=forms.SplitDateTimeWidget( date_format='%m/%d/%Y', time_format='%H:%M', ) ) endTime = forms.SplitDateTimeField( input_time_formats=['%H:%M'], input_date_formats =['%m/%d/%Y'], label = 'End Time', widget=forms.SplitDateTimeWidget( date_format='%m/%d/%Y', time_format='%H:%M', ) ) description = forms.CharField( label='Description', max_length=1000, widget=forms.Textarea ) group = forms.ModelChoiceField( queryset = Group.objects.all(), label='Group', required = False, ) friends = forms.ModelMultipleChoiceField(queryset=Squirl.objects.all() , widget=forms.CheckboxSelectMultiple, required=False) def is_valid(self): # run the parent validation first valid = super(CreateEventForm, self).is_valid() # we're done now if not valid if not valid: return valid if self.cleaned_data['startTime'] > self.cleaned_data['endTime'] : self.errors['start_end_time']='The start time cannot be after the end time' return False return True class Media: js=('QED/addEventValidation.js') #cannot have below line in initialization function. #self.fields['friends'].queryset = Squirl.objects.filter(pk__in=set( Connection.objects.filter(relation__user =s_user).values_list('user', flat=True))) class CreateGroupForm(forms.Form): title = forms.CharField( label='Group Name', max_length = 100, required = True, validators=[standard_validator] ) description = forms.CharField( label='Description', max_length=1000, widget=forms.Textarea ) ## interests = forms.ModelMultipleChoiceField( ## label='Interests', ## queryset=Interest.objects.all(), ## widget=forms.CheckboxSelectMultiple, ## required=True ## ) friends = forms.ModelMultipleChoiceField( label='Friends', queryset=Squirl.objects.all(), widget=forms.CheckboxSelectMultiple, required=False ) class CreateUserForm(forms.Form): username = forms.CharField( validators=[standard_validator] ) email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) verify_password = forms.CharField(widget=forms.PasswordInput) class EventNotificationForm(forms.Form): eventName = forms.CharField(max_length=150, widget=forms.HiddenInput()) eventId = forms.CharField(widget=forms.HiddenInput()) FORM_CHOICES=( (0, 'View Later'), (1,'Decline'), (2,'Accept'), (3, 'Commit'), (4, 'Probably'), (5, 'Unlikely') ) response=forms.ChoiceField(choices=FORM_CHOICES, initial = 0) #Actual id for the event notification. noticeId= forms.CharField(widget=forms.HiddenInput()) class SendFriendRequestForm(forms.Form): RELATION=( (0, 'acquaintance'), (1, 'block'), (2, 'friend'), ) relation = forms.ChoiceField(choices=RELATION, initial =0) friend = forms.CharField(widget=forms.HiddenInput()) class FriendNotificationForm(forms.Form): RELATION=( (0, 'acquaintance'), (1, 'block'), (2, 'friend'), ) relation = forms.ChoiceField(choices=RELATION, initial =0) friend = forms.CharField(widget=forms.HiddenInput()) class EventFilterForm(forms.Form): location = forms.ModelChoiceField( label=("Location"), required=False, queryset=Location.objects.all(), ) interest = forms.ModelChoiceField( label=("Interests"), required=False, queryset=Interest.objects.all(), ) class AddressForm(forms.Form): num=forms.IntegerField( min_value=0, ) street=forms.CharField(max_length=100) city=forms.CharField(max_length=100) state=forms.ModelChoiceField( queryset=State.objects.all() ) zipcode=forms.IntegerField( min_value=10000, max_value=99999, widget=forms.NumberInput(), ) ## class Meta: ## model=Address ## fields=['num','street','city','state','zipcode'] class SearchPageForm(forms.Form): interest = forms.CharField(max_length=150, required=False) state = forms.ModelChoiceField( queryset=State.objects.all(), required=False ) city = forms.CharField(max_length= 100, required=False) def is_valid(self): # run the parent validation first valid = super(SearchPageForm, self).is_valid() if not valid: return valid data = self.cleaned_data if (len(data['city']) ==0 or data['state'] is None) and len(data['interest']) == 0: self.errors['loc_or_interest'] = "Need to select state and city and or select just an interest" return False return True
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,405
squirl/squirl
refs/heads/master
/squirl/methods.py
from .models import Group from .models import Event, Notice, Address, Zipcode from .models import UserEventPlan, FriendNotification, Squirl, Interest from datetime import datetime, timedelta from django.forms.formsets import formset_factory from .forms import FriendNotificationForm, InterestsForm from django.utils.html import conditional_escape as esc from .forms import AddressForm import random def get_notice(notice_id): try: return Notice.objects.get(id = notice_id) except Notice.DoesNotExist: return None def create_address_form_from_address(addr): addressForm = AddressForm(initial= {'num': addr.num, 'street': addr.street, 'city': addr.city, 'state' :addr.state, 'zipcode' : int(addr.zipcode.code)}) return addressForm """ Gets a suggested group for the user """ def get_suggested_group(): qs = Group.objects.all() toReturn = list(qs) if(len(toReturn) == 0): return None toReturn = toReturn[random.randint(0, len(toReturn)-1)] if toReturn: return toReturn return None """ Returns the calendar events as html so that it can be displayed for the user. """ def get_calendar_events(squirl, date = datetime.now().date): events = UserEventPlan.objects.filter(squirl_user__squirl_user = squirl).order_by('event__start_time') startdate = get_date_beginning_week(date) body = '<table id ="eventsCalendar">' body+='<tr id="month"><td><p>'+ get_display_month(date) +'</p></td></tr>' body+= '<tr><td class= "dayOfWeek">Sunday</td><td class= "dayOfWeek">Monday</td><td class= "dayOfWeek">Tuesday</td><td class= "dayOfWeek">Wednesday</td><td class= "dayOfWeek">Thursday</td><td class= "dayOfWeek">Friday</td><td class= "dayOfWeek">Saturday</td></tr>' for loopweek in range(0,4): body = body +'<tr>' for loopday in range(0,7): todaysEvents = events.filter(event__start_time__year = startdate.year , event__start_time__month = startdate.month, event__start_time__day = startdate.day) body= body+ '<td class="eventsOnDay"><div class="date">%s</div>' % esc(startdate.day) startdate += timedelta(days=1) if todaysEvents: for event in todaysEvents: body= body +"<div><a onclick='getEvent({0})' >{1}</a></div>".format( event.event.id, esc(event.event.name)) body= body +'</td>' body= body+'</tr>' body+='</table>' return body """ Method obtains month(s) to display """ def get_display_month(date): toreturn = date.strftime('%B') if(date.day >= 15): toreturn +='/' + datetime(date.year, date.month +1, 15).strftime('%B') return toreturn """ Gets the day at the beginning of the week. """ def get_date_beginning_week(date): if(date.weekday() != 6): return date - timedelta(days =date.weekday() + 1) return date """ Returns a formset with all of the user's unviewed friend notifications """ def get_friend_notifications(user): squirl = Squirl.objects.get(squirl_user=user) friend_notifications = FriendNotification.objects.filter(notice__user=squirl, notice__viewed=False) friend_form_set = formset_factory(FriendNotificationForm, extra=0) initial_list=[] for f_notice in friend_notifications: initial_list.append({'friend': f_notice.user.squirl_user.id, 'relation': 0}) formset=friend_form_set(initial=initial_list, prefix = 'friends') return formset def get_squirl(user_id): try: squirl = Squirl.objects.get(squirl_user__id = user_id) return squirl except Squirl.DoesNotExist : return None def get_interests_formset(): formset = formset_factory(InterestsForm, extra=1) return formset(prefix='interests') def get_interest_by_name(name): try: toReturn = Interest.objects.get(name=name) return toReturn except Interest.DoesNotExist: return None """ Validates the address form. """ def validate_address_form(data): valid = len(str(data['num'])) > 0 and len(data['street']) > 0 and len(data['city']) > 0 and len(str(data['zipcode'])) == 5 return valid """Finds a zipcode""" def get_zipcode(code): try: zip = Zipcode.objects.get(code=code) return zip except Zipcode.DoesNotExist: return None """Finds and returns address from form data if it exists. otherwise returns none""" def get_address_from_form(data): zip = get_zipcode(data['zipcode']) if zip is None: return None try: addr = Address.objects.get(num=data['num'], street=data['street'], city=data['city'], state=data['state'], zipcode=zip) return addr except Address.DoesNotExist: return None def create_zipcode(code): zip = Zipcode() zip.code = code zip.save() return zip """Creates an address from form data""" def create_address(data): zip = get_zipcode(data['zipcode']) if zip is None: zip = create_zipcode(data['zipcode']) address = Address() address.num = data['num'] address.street=data['street'] address.city=data['city'] address.state=data['state'] address.zipcode=zip address.save() return address
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,406
squirl/squirl
refs/heads/master
/squirl/utils.py
from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.core.exceptions import FieldError def object_relation_mixin_factory( prefix=None, prefix_verbose=None, add_related_name=False, limit_content_type_choices_to={}, limit_object_choices_to={}, is_required=False, ): """ """ if prefix: p = "%s_" % prefix else: p = "" content_type_field = "%scontent_type" %p object_id_field = "%sobject_id" % p content_object_field = "%scontent_object" % p class AClass(models.Model): class Meta: abstract = True if add_related_name: if not prefix: raise FieldError("if add_related_name is set to True," "a prefix must be given") related_name = prefix else: related_name = None content_type = models.ForeignKey( ContentType, verbose_name = (prefix_verbose and _("%s's type (model)") %\ prefix_verbose or _("Related object's type (model)")), related_name=related_name, blank=not is_required, null=not is_required, help_text=_("Please select the type (model) for the relation," "you want to build."), limit_choices_to=limit_content_type_choices_to, ) object_id = models.CharField( (prefix_verbose or _("Related object")), blank=not is_required, null=False, help_text=_("Please enter the ID of the related object."), max_length=255, default="", ) object_id.limit_choices_to = limit_object_choices_to content_object = generic.GenericForeignKey( ct_field=content_type_field, fk_field=object_id_field, ) AClass.add_to_class(content_type_field, content_type) AClass.add_to_class(object_id_field, object_id) AClass.add_to_class(content_object_field, content_object) return AClass
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,407
squirl/squirl
refs/heads/master
/squirl/admin.py
from django.contrib import admin # Register your models here. from .models import Squirl,Interest,Event, Group, Location, UserEventPlan, UserEvent, Member, Relation, Connection, EventNotification, Notice from .models import FriendNotification, JoinGroupNotification, State, Zipcode, Address,ParentEventNotice, AncestorGroupEvent class SquirlAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['squirlUser']}), ('Interests', {'fields': ['interests']}), ] admin.site.register(Member) admin.site.register(Squirl) admin.site.register(Interest) admin.site.register(Event) admin.site.register(Group) admin.site.register(Location) admin.site.register(UserEventPlan) admin.site.register(UserEvent) admin.site.register(Connection) admin.site.register(Relation) admin.site.register(EventNotification) admin.site.register(Notice) admin.site.register(FriendNotification) admin.site.register(JoinGroupNotification) admin.site.register(State) admin.site.register(Zipcode) admin.site.register(Address) admin.site.register(ParentEventNotice) admin.site.register(AncestorGroupEvent)
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,408
squirl/squirl
refs/heads/master
/squirl/ajax.py
from django.template.loader import render_to_string from dajaxice.decorators import dajaxice_register try: from django.utils import simplejson as json except: import simplejson as json from dajaxice.decorators import dajaxice_register from .views import get_upcomingEventsPaginationPage @dajaxice_register def sayhello(request): return json.dumps({'message':'Hello World'}) @dajaxice_register def upcomingEventsPagination(request, p): user_events = get_upcomingEventsPaginationPage(p) render = render_to_string('QED/upcomingEventsPagination.html') dajax = Dajax() dajax.assign('#upcomingEvents', 'innerHTML', render) return dajax.json()
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,409
squirl/squirl
refs/heads/master
/squirl/views.py
from django.shortcuts import render from django.http import HttpResponse from .models import Event, UserEventPlan, UserEvent, Squirl, GroupEvent, Member, Notice, EventNotification, Connection, Interest, AncestorGroupEvent from .models import Group, Location, Relation, FriendNotification, ParentEventNotice from django.utils.safestring import mark_safe from django.shortcuts import render_to_response from .methods import get_calendar_events, get_suggested_group, get_display_month, get_friend_notifications, get_squirl, get_interests_formset, get_interest_by_name, validate_address_form, get_address_from_form, create_address, create_address_form_from_address from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.contrib.auth.models import User from datetime import datetime from django.shortcuts import redirect from .forms import CreateEventForm, CreateGroupForm, CreateUserForm, EventNotificationForm, EventFilterForm, SendFriendRequestForm, FriendNotificationForm, InterestsForm, AddressForm, SearchPageForm from django.forms.formsets import formset_factory from .import groupMethods as gm from .groupForms import JoinGroupRequestForm, SubGroupNotificationForm, ParentEventNoticeForm from .import friendMethods as fm from .eventMethods import display_event, get_user_event_notifications, validate_event_notifications_formset, create_from_event_notification_formset, get_user_upcoming_events, get_event_notification_by_user_and_event, can_user_edit_event, get_event #Get javascript going from django.utils.dateformat import DateFormat import json from django.core.serializers.json import DjangoJSONEncoder from django import forms #below is just a test import from .models import Location def squirl_logout(request): auth_logout(request) return render(request, "squirl/signOutConfirmation.html") def create_account(request): error=None form = CreateUserForm() if request.method=='POST': form = CreateUserForm(request.POST) if form.is_valid(): data = form.cleaned_data try: check_user = User.objects.get(username=data.get('username')) error = "User with username: " + data.get('username') + " already exists." except User.DoesNotExist: if data.get('password') != data.get('verify_password'): error= "Passwords do not match." else: user = User() user.username=data.get('username') user.set_password(data.get('password')) user.email=data.get('email') user.save() squirl=Squirl() squirl.squirl_user=user squirl.save() auth_user = authenticate(username=data.get('username'), password=data.get('password')) auth_login(request, auth_user) return redirect(index) else: error = "Try Again" return render(request, 'squirl/createAccount.html', {'form': form, 'error': error}) def squirl_login(request): if request.method =='POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: auth_login(request, user) return redirect(index) else: return HttpResponse("Your account is disabled") else: return HttpResponse("Invalid login") else: return render(request, 'squirl/login.html') def index(request): if not request.user.is_authenticated(): return redirect(squirl_login) else: join_group_formset = formset_factory(JoinGroupRequestForm) friend_formset = formset_factory(FriendNotificationForm) squirl = get_squirl(request.user.id) parent_event_notifications_formset = gm.get_parent_event_notification_formset(squirl) if request.method =='POST': parent_event_notices = gm.get_parent_event_notifications(squirl) if parent_event_notices is not None: parent_event_notifications_formset = formset_factory(ParentEventNoticeForm) parent_event_notifications_formset = parent_event_notifications_formset(request.POST, request.FILES, prefix = "parentEventNotices") sub_notif_post_formset = formset_factory(SubGroupNotificationForm) sub_notif_post_formset = sub_notif_post_formset(request.POST, request.FILES, prefix = 'subGroupNotifications') event_notification_formset = formset_factory(EventNotificationForm) event_notification_formset = event_notification_formset(request.POST, request.FILES, prefix= 'event_notices') join_group_formset = join_group_formset(request.POST, request.FILES, prefix='joinGroup') valid = True if join_group_formset.is_valid(): valid = valid and gm.validate_join_group_formset(join_group_formset, squirl) if not valid: print("groups bad") else: return HttpResponse("Form not valid") if event_notification_formset.is_valid(): valid = valid and validate_event_notifications_formset(event_notification_formset, squirl) if not valid: print("events bad") else: return HttpResponse("Form not valid") friend_notifications = friend_formset(request.POST, request.FILES, prefix='friends') if friend_notifications.is_valid(): valid = valid and fm.validate_friend_formset(friend_notifications, squirl) if not valid: print("friends bad") else: return HttpResponse("Form not valid") if sub_notif_post_formset.is_valid(): valid = valid and gm.validate_sub_group_notification_post(sub_notif_post_formset, squirl) else: print ("sub form not valid") valid = False if parent_event_notices is not None: if parent_event_notifications_formset.is_valid(): print("parent event formset") valid = gm.validate_parent_event_formset(parent_event_notifications_formset, squirl) else: print("parent event not valid") valid = False if valid: gm.create_members_join_group_formset(join_group_formset) fm.handle_friend_formset(friend_notifications, squirl) create_from_event_notification_formset(event_notification_formset, squirl) gm.handle_sub_group_notification_post(sub_notif_post_formset, squirl) gm.handle_parent_event_formset(parent_event_notifications_formset) else: print("not valid valid") print("Test before ajax") if request.is_ajax(): print("Ajax") print(request.GET['event']) return HttpResponse(mark_safe(display_event(request.GET['event']))) friend_notifications = get_friend_notifications(request.user) event_notices = get_user_event_notifications(squirl) events = get_user_upcoming_events(squirl) paginator = Paginator(events, 2) page_number = request.GET.get('page') suggested_group = get_suggested_group() date= datetime.today() events_list = UserEventPlan.objects.filter(squirl_user__squirl_user = request.user).order_by('event__start_time') try: page = paginator.page(page_number) except PageNotAnInteger: page = paginator.page(1) except EmptyPage: page = paginator.page(paginator.num_pages) join_group_formset = gm.get_join_group_formset(Squirl.objects.get(squirl_user= request.user)) calendar = get_calendar_events(request.user, date) context = {'formset': event_notices, 'user_event_list': events, 'user_events': page, 'calendar' : mark_safe(calendar), 'suggested_group': suggested_group, 'friend_formset': friend_notifications, 'join_group_formset': join_group_formset, 'sub_group_formset': gm.get_sub_group_notifications_formset(get_squirl(request.user.id)), 'parent_event_formset': parent_event_notifications_formset, } return render(request, 'squirl/index.html', context) def event_page(request, event_id): if not request.user.is_authenticated(): return redirect(squirl_login) else: try : event = Event.objects.get(pk=event_id) if(event.privacy==1): userPlan = None try: userPlan =UserEventPlan.objects.get(squirl_user__squirl_user = request.user.id, event__pk=event_id) except UserEventPlan.DoesNotExist: userPlan=None print ("userplan none") userInvite=None try: userInvite=EventNotification.objects.get(notice__user__squirl_user = request.user.id, event__id =event_id) except EventNotification.DoesNotExist: userInvite=None if(userPlan ==None and userInvite==None): return HttpResponse("You do not have access to EVENT: " + event__pk) else: return HttpResponse("In progress 1") else: squirl = get_squirl(request.user.id) can_edit = can_user_edit_event(squirl, event) attendance=UserEventPlan.objects.filter(event__pk =event_id) return render(request, 'squirl/eventPage.html', {'event':event, 'attendance': attendance, "can_edit" :can_edit}) except Event.DoesNotExist: return HttpResponse("Error! You do not have access to "+ event_id); def group_page(request, group_id): group = None try: group =Group.objects.get(pk =group_id) members = Member.objects.filter(group=group) g_events = GroupEvent.objects.filter(group=group) squirl= get_squirl(request.user.id) form = gm.get_sub_group_request(group, squirl) membership = False if gm.get_member(squirl, group): membership=True if form: form.fields['group1'].widget = forms.HiddenInput() return render(request, 'squirl/groupPage.html', {'group': group, 'members': members, 'groupEvents':g_events, 'subGroupForm': form, 'membership' : membership}) except Group.DoesNotExist: return HttpResponse("Group does not exist") return HttpResponse("in progress") def add_event(request): if not request.user.is_authenticated(): return redirect(squirl_login) else: interests = get_interests_formset() form = CreateEventForm() addressForm = AddressForm() if request.method =='POST': form = CreateEventForm(request.POST) addressForm= AddressForm(request.POST) interests = formset_factory(InterestsForm, extra=0) interests= interests(request.POST, request.FILES, prefix="interests") if form.is_valid() and addressForm.is_valid() and validate_address_form(addressForm.cleaned_data) and interests.is_valid(): valid_interest = False for interform in interests: interform.is_valid() inter = interform.cleaned_data if len(inter['interest']) > 0: valid_interest=True all_interests= [] for interform in interests: interest = get_interest_by_name(inter['interest']) #if the interest does not exist create it. if interest is None: interest = Interest() interest.name = inter['interest'] interest.save() all_interests.append(interest) else: all_interests.append(interest) data = form.cleaned_data event = Event() addr = get_address_from_form(addressForm.cleaned_data) if addr is None: addr=create_address(addressForm.cleaned_data) if form.cleaned_data.get('isUserEvent'): userEvent = UserEvent() userEvent.creator = Squirl.objects.get(squirl_user= request.user) event.main_location = addr event.start_time=data.get('startTime') event.end_time=data.get('endTime') event.name=data.get('title') event.description= data.get('description') event.save() userEvent.event = event userEvent.save() for inter in all_interests: event.interests.add(inter) else: data = form.cleaned_data if data.get('group'): groupEvent = GroupEvent() event.main_location = addr event.start_time=data.get('startTime') event.end_time=data.get('endTime') event.name=data.get('title') event.description=data.get('description') test_group = gm.get_group(data.get('group')) if test_group is None: return HttpResponse("try again") if test_group not in gm.get_groups_user_admin(get_squirl(request.user.id)): return HttpResponse("you do not have access to the group") groupEvent.group=data.get('group') event.save() for inter in all_interests: event.interests.add(inter) groupEvent.event = event #TODO make sure the user was only submitting data that they had access to. groupEvent.save() members = Member.objects.filter(group = groupEvent.group) for member in members: if get_event_notification_by_user_and_event(member.user, event) is None: notice = Notice() notice.user = member.user notice.save() eventNotification = EventNotification() eventNotification.event =event eventNotification.notice= notice eventNotification.save() sub_groups = groupEvent.group.sub_group.all() if sub_groups is not None: #create that ancestor group event and then send out notifications ancestor_event = AncestorGroupEvent() ancestor_event.event = groupEvent ancestor_event.save() for g in sub_groups: notice = ParentEventNotice() notice.group = g notice.parent_group = groupEvent notice.ancestor_event = ancestor_event notice.save() ancestor_event.notified_groups.add(g) ancestor_event.save() else: return HttpResponse("Try again") friends = data.get('friends') for invite in friends: if get_event_notification_by_user_and_event(invite, event) is None: notice = Notice() notice.user=invite notice.save() eventNotification=EventNotification() eventNotification.event =event eventNotification.notice=notice eventNotification.save() if get_event_notification_by_user_and_event(get_squirl(request.user.id), event) is None: notice = Notice() notice.user = get_squirl(request.user.id) notice.save() eventNotification = EventNotification() eventNotification.event = event eventNotification.notice= notice eventNotification.save() return redirect(index) squirl= Squirl.objects.get(squirl_user= request.user) form.fields['friends'].queryset = Squirl.objects.filter(pk__in=set( Connection.objects.filter(relation__user =squirl).values_list('user', flat=True))) #below line can definitely be improved. If I could access the list of objects instead of the queryset I could make it work better. f_groups = gm.get_groups_user_admin(squirl) if f_groups is None: form.fields['group'].queryset = Group.objects.none() else: form.fields['group'].queryset = Group.objects.filter(pk__in=[item.pk for item in f_groups]) return render(request, 'squirl/addEvent.html', {'form': form, 'interests': interests, 'addressForm': addressForm}) def create_group(request): if not request.user.is_authenticated(): return redirect(squirl_login) else: squirl= Squirl.objects.get(squirl_user= request.user) form = CreateGroupForm() interests = get_interests_formset() addressForm = AddressForm() if request.method =='POST': interests = formset_factory(InterestsForm, extra=0) interests= interests(request.POST, request.FILES, prefix="interests") form = CreateGroupForm(request.POST) addressForm = AddressForm(request.POST) if form.is_valid() and interests.is_valid() and addressForm.is_valid() and validate_address_form(addressForm.cleaned_data): data= form.cleaned_data group = Group() group.name = data.get('title') all_interests= [] valid_interest = False for interform in interests: inter = interform.cleaned_data if len(inter['interest']) > 0: valid_interest=True interest = get_interest_by_name(inter['interest']) #if the interest does not exist create it. if interest is None: interest = Interest() interest.name = inter['interest'] interest.save() all_interests.append(interest) else: all_interests.append(interest) if not valid_interest: form.fields['friends'].queryset = Squirl.objects.filter(pk__in=set( Connection.objects.filter(relation__user =squirl).values_list('user', flat=True))) return render(request, 'squirl/createGroup.html', {'form': form, 'interests': interests, 'addressForm':addressForm}) addr= get_address_from_form(addressForm.cleaned_data) if addr is None: #create the address #TODO addr = create_address(addressForm.cleaned_data) group.location=addr group.description=data.get('description') group.save() for inter in all_interests: group.interests.add(inter) owner=Member() owner.user=squirl owner.group=group owner.role=0 owner.save() return redirect(index) else: form.fields['friends'].queryset = Squirl.objects.filter(pk__in=set( Connection.objects.filter(relation__user =squirl).values_list('user', flat=True))) return render(request, 'squirl/createGroup.html', {'form': form, 'interests': interests, 'addressForm':addressForm}) else: groupForm=CreateGroupForm() groupForm.fields['friends'].queryset = Squirl.objects.filter(pk__in=set( Connection.objects.filter(relation__user =squirl).values_list('user', flat=True))) return render(request, 'squirl/createGroup.html', {'form': groupForm, 'interests': interests, 'addressForm':addressForm}) def search_page(request): if not request.user.is_authenticated(): return redirect(squirl_login) else: searchForm = SearchPageForm() qs = Event.objects.order_by('name') group_qs = Group.objects.order_by('name') user_qs = Squirl.objects.order_by('squirl_user__username') eventForm = EventFilterForm(data=request.REQUEST) facets= { 'selected':{}, 'categories':{ 'locations': Location.objects.all(), 'interests': Interest.objects.all(), }, } groupt_facets ={ 'selected':{}, 'categories':{ 'locations': Location.objects.all(), 'interests': Interest.objects.all(), }, } if eventForm.is_valid(): location=eventForm.cleaned_data['location'] if location: facets['selected']['location']= location qs=qs.filter(main_location=location).distinct() group_qs=group_qs.filter(location=location).distinct() user_qs = user_qs.filter(home=location).distinct() interest=eventForm.cleaned_data['interest'] if interest: facets['selected']['interest']=interest qs=qs.filter(interests=interest).distinct() group_qs=group_qs.filter(interests=interest).distinct() user_qs = user_qs.filter(interests=interest).distinct() context={'form': eventForm, 'facets': facets, 'object_list': qs, 'group_list': group_qs, 'user_list': user_qs, 'searchForm': searchForm, } return render(request, 'squirl/searchPage.html', context) def profile_page(request, user_id): if not request.user.is_authenticated(): return redirect(squirl_login) else: if request.method =='POST': #this check is inside here instead of outside because the user might later be able to interact with their profile page for something else. if request.user.id != user_id: form = SendFriendRequestForm(request.POST) if form.is_valid(): squirl = Squirl.objects.get(squirl_user__id = user_id) connection = Connection.objects.filter(user__squirl_user__id =request.user.id, relation__user = squirl) if not connection: relation = Relation() relation.user=squirl relation.relation=form.cleaned_data['relation'] connection = Connection() connection.user = Squirl.objects.get(squirl_user = request.user) relation.save() connection.relation = relation connection.save() print('working') #Check if the otehr person has friended/or worse this person other_connection = Connection.objects.filter(user=squirl, relation__user__squirl_user =request.user) if not other_connection: #search for a friend request friend_notification = FriendNotification.objects.filter(user__squirl_user=request.user, notice__user=squirl) if not friend_notification: notice = Notice() notice.user=squirl notice.save() friend_notification = FriendNotification() friend_notification.user = Squirl.objects.get(squirl_user = request.user) friend_notification.notice = notice friend_notification.save() else: return HttpResponse("Error") form = None if request.user.id != user_id: form = SendFriendRequestForm(initial={'friend' :user_id}) context={ 'form': form } return render(request, 'squirl/profile.html', context) def join_group_request(request, group_id): if not request.user.is_authenticated(): return redirect(squirl_login) else: squirl = Squirl.objects.get(squirl_user=request.user) group = gm.get_group(group_id) if group is not None: if gm.user_has_access_to_group(squirl, group): if gm.get_member(squirl, group) is None: if gm.group_requires_admin_to_add_member(squirl, group): if gm.get_group_notification(squirl, group) is None: if gm.create_group_notification(squirl, group) ==1 : return HttpResponse("Error creating notification") else: print("notificaiton created") else: if gm.add_member_to_group(squirl, group) ==1: return HttpResponse("Error adding user to group") else: return HttpResponse("You do not have access to this group") else: return HttpResponse("The group does not exist") return redirect('/squirl/group/' + group_id) def get_upcomingEventsPaginationPage(page = 1): events = Event.objects.all() paginator = Paginator(events, 2) try: page_number = int(page) except ValueError: pag_number = 1 try: page = paginator.page(page_number) except PageNotAnInteger: page = paginator.page(1) except EmptyPage: page = paginator.page(paginator.num_pages) #TODO have to change the body so it doesn't save a new event and need to populate fields with current values. def edit_event(request, event_id): if not request.user.is_authenticated(): return redirect(squirl_login) event = get_event(event_id) if event is None: return HttpResponse("Event does not exist") squirl = get_squirl(request.user.id) if can_user_edit_event(squirl, event): interests = formset_factory(InterestsForm, extra=len(event.interests.all())) interests = interests(prefix="interests") form = CreateEventForm() addressForm = AddressForm() if request.method =='POST': form = CreateEventForm(request.POST) addressForm= AddressForm(request.POST) interests = formset_factory(InterestsForm, extra=0) interests= interests(request.POST, request.FILES, prefix="interests") if form.is_valid() and addressForm.is_valid() and validate_address_form(addressForm.cleaned_data) and interests.is_valid(): valid_interest = False for interform in interests: interform.is_valid() inter = interform.cleaned_data if len(inter['interest']) > 0: valid_interest=True all_interests= [] for interform in interests: interest = get_interest_by_name(inter['interest']) #if the interest does not exist create it. if interest is None: interest = Interest() interest.name = inter['interest'] interest.save() all_interests.append(interest) else: all_interests.append(interest) data = form.cleaned_data addr = get_address_from_form(addressForm.cleaned_data) if addr is None: addr=create_address(addressForm.cleaned_data) #TODO continue here event = get_event(event_id) event.start_time = data['startTime'] event.end_time = data['endTime'] event.name=data['title'] event.description = data['description'] event.main_location=addr for inter in all_interests: event.interests.add(inter) event.save() return redirect(index) squirl= Squirl.objects.get(squirl_user= request.user) form.fields['friends'].queryset = Squirl.objects.filter(pk__in=set( Connection.objects.filter(relation__user =squirl).values_list('user', flat=True))) #populate form initial from actual event form.fields['title'].initial = event.name form.fields['startTime'].initial = event.start_time form.fields['endTime'].initial = event.end_time form.fields['description'].initial=event.description form.fields['isUserEvent'].widget = forms.HiddenInput() form.fields['group'].widget = forms.HiddenInput() i_interests = [] for inter in event.interests.all(): i_interests.append(inter.name) i =0 for inter in interests: inter.fields['interest'].initial = i_interests[i] i +=1 addressForm = create_address_form_from_address(event.main_location) f_groups = gm.get_groups_user_admin(squirl) if f_groups is None: form.fields['group'].queryset = Group.objects.none() else: form.fields['group'].queryset = Group.objects.filter(pk__in=[item.pk for item in f_groups]) return render(request, 'squirl/editEvent.html', {'form': form, 'interests': interests, 'addressForm': addressForm}) else: return HttpResponse("You do not have permission to edit this event")
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,410
squirl/squirl
refs/heads/master
/squirl/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Address', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('num', models.IntegerField()), ('street', models.CharField(max_length=100)), ('city', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='Connection', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ], ), migrations.CreateModel( name='Event', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('start_time', models.DateTimeField(verbose_name=b'Start time')), ('end_time', models.DateTimeField(verbose_name=b'End time')), ('name', models.CharField(max_length=150)), ('description', models.CharField(max_length=1000)), ('privacy', models.IntegerField(default=0, choices=[(0, b'open'), (1, b'invite only'), (2, b'friends only'), (3, b'acquaintance only')])), ], ), migrations.CreateModel( name='EventNotification', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('event', models.ForeignKey(to='squirl.Event')), ], ), migrations.CreateModel( name='FriendNotification', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ], ), migrations.CreateModel( name='Group', fields=[ ('name', models.CharField(max_length=100, serialize=False, primary_key=True)), ('description', models.CharField(max_length=1000)), ], ), migrations.CreateModel( name='GroupEvent', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('event', models.ForeignKey(to='squirl.Event')), ('group', models.ForeignKey(to='squirl.Group')), ], ), migrations.CreateModel( name='GroupNotice', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('viewed', models.BooleanField(default=0)), ('group', models.ForeignKey(to='squirl.Group')), ], ), migrations.CreateModel( name='Interest', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(default=b'None', max_length=100)), ('description', models.CharField(max_length=300, null=True, blank=True)), ], ), migrations.CreateModel( name='JoinGroupNotification', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('notice', models.ForeignKey(to='squirl.GroupNotice')), ], ), migrations.CreateModel( name='Location', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=200)), ], ), migrations.CreateModel( name='Member', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('role', models.IntegerField(default=1, choices=[(0, b'Owner'), (1, b'Member'), (2, b'Editor')])), ('group', models.ForeignKey(to='squirl.Group')), ], ), migrations.CreateModel( name='Notice', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('viewed', models.BooleanField(default=0)), ], ), migrations.CreateModel( name='Relation', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('relation', models.IntegerField(default=0, choices=[(0, b'acquaintance'), (1, b'block'), (2, b'friend')])), ], ), migrations.CreateModel( name='Squirl', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('home', models.ForeignKey(blank=True, to='squirl.Location', null=True)), ('interests', models.ManyToManyField(to='squirl.Interest', null=True, blank=True)), ('squirl_user', models.OneToOneField(to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='State', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=100)), ('abbr', models.CharField(max_length=2)), ], ), migrations.CreateModel( name='SubGroupNotification', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('viewed', models.BooleanField(default=0)), ('role', models.IntegerField(default=0, choices=[(0, b'Child'), (1, b'Parent'), (2, b'Parent and child')])), ('fromGroup', models.ForeignKey(related_name='fromGroup', blank=True, to='squirl.Group', null=True)), ('toGroup', models.ForeignKey(related_name='toGroup', blank=True, to='squirl.Group', null=True)), ], ), migrations.CreateModel( name='UserEvent', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('creator', models.ForeignKey(blank=True, to='squirl.Squirl', null=True)), ('event', models.ForeignKey(blank=True, to='squirl.Event', null=True)), ], ), migrations.CreateModel( name='UserEventPlan', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('status', models.IntegerField(default=3, choices=[(0, b'Commit'), (1, b'Not Sure'), (2, b'Probably'), (3, b'No'), (4, b'Unlikely')])), ('event', models.ForeignKey(blank=True, to='squirl.Event', null=True)), ('squirl_user', models.ForeignKey(blank=True, to='squirl.Squirl', null=True)), ], ), migrations.CreateModel( name='Zipcode', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('code', models.CharField(max_length=5)), ], ), migrations.AddField( model_name='relation', name='user', field=models.ForeignKey(blank=True, to='squirl.Squirl', null=True), ), migrations.AddField( model_name='notice', name='user', field=models.ForeignKey(to='squirl.Squirl'), ), migrations.AddField( model_name='member', name='user', field=models.ForeignKey(blank=True, to='squirl.Squirl', null=True), ), migrations.AddField( model_name='joingroupnotification', name='user', field=models.ForeignKey(blank=True, to='squirl.Squirl', null=True), ), migrations.AddField( model_name='group', name='interests', field=models.ManyToManyField(to='squirl.Interest'), ), migrations.AddField( model_name='group', name='location', field=models.ForeignKey(blank=True, to='squirl.Address', null=True), ), migrations.AddField( model_name='group', name='sub_group', field=models.ManyToManyField(to='squirl.Group', null=True, blank=True), ), migrations.AddField( model_name='friendnotification', name='notice', field=models.ForeignKey(to='squirl.Notice'), ), migrations.AddField( model_name='friendnotification', name='user', field=models.ForeignKey(to='squirl.Squirl'), ), migrations.AddField( model_name='eventnotification', name='notice', field=models.ForeignKey(to='squirl.Notice'), ), migrations.AddField( model_name='event', name='interests', field=models.ManyToManyField(to='squirl.Interest', null=True, blank=True), ), migrations.AddField( model_name='event', name='main_location', field=models.ForeignKey(to='squirl.Location'), ), migrations.AddField( model_name='connection', name='relation', field=models.ForeignKey(to='squirl.Relation'), ), migrations.AddField( model_name='connection', name='user', field=models.ForeignKey(blank=True, to='squirl.Squirl', null=True), ), migrations.AddField( model_name='address', name='state', field=models.ForeignKey(to='squirl.State'), ), migrations.AddField( model_name='address', name='zipcode', field=models.ForeignKey(to='squirl.Zipcode'), ), ]
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,411
squirl/squirl
refs/heads/master
/squirl/models.py
from django.db import models from django.contrib.auth.models import User from django.contrib.gis.db import models class AncestorGroupEvent(models.Model): notified_groups= models.ManyToManyField('Group') event = models.ForeignKey('GroupEvent') class ParentEventNotice(models.Model): group = models.ForeignKey('Group', related_name= 'notified_group') parent_event = models.ForeignKey('GroupEvent', null=True, blank = True) ancestor_event = models.ForeignKey('AncestorGroupEvent') viewed = models.BooleanField(default=0) class Zipcode(models.Model): code = models.CharField(max_length=5) ## poly = models.PolygonField() ## objects = models.GeoManager() class Address(models.Model): num = models.IntegerField() street = models.CharField(max_length=100) city = models.CharField(max_length=100) state = models.ForeignKey('State') zipcode = models.ForeignKey(Zipcode) def __unicode__(self): return str(self.id) #objects = models.GeoManager() #Might not have to do below lin 05/27/15 #will implement model mixins shortly def DEFAULT_STATE(): return list(State.objects.all()[:1])[0].id ##def SECOND_DEFAULT_USER(): ## user = User.objects.get(username='aklapper') ## return Squirl.objects.get(squirl_user=user).id ##def DEFAULT_USER(): ## user = User.objects.get(username= 'squirladmin') ## return Squirl.objects.get(squirl_user = user).id ##def DEFAULT_EVENT(): ## events = Event.objects.all() ## event = list(events[:1]) ## return event[0].id ##def DEFAULT_GROUP(): ## groups = Group.objects.all() ## group = list(groups[:1]) ## return group[0].pk ##def DEFAULT_LOCATION(): ## locations = Location.objects.all() ## location = list(locations[:1]) ## return location[0].id class Location(models.Model): city = models.CharField(max_length=100, default='Unnamed') state = models.ForeignKey('State', default = DEFAULT_STATE) def __str__(self): return self.name """user that the request is being sent to and whether or not they have taken action yet.""" class Notice(models.Model): user = models.ForeignKey('Squirl') viewed = models.BooleanField(default=0) def __unicode__(self): return str(self.id) """group that request is being sent to and whether or not one of the admins took action""" class GroupNotice(models.Model): group = models.ForeignKey('Group') viewed=models.BooleanField(default=0) """Used for friend notifications""" class FriendNotification(models.Model): notice = models.ForeignKey('Notice') user = models.ForeignKey('Squirl') class EventNotification(models.Model): notice = models.ForeignKey('Notice') event = models.ForeignKey('Event') ancestor_event = models.ForeignKey('AncestorGroupEvent', null=True, blank = True) def __unicode__(self): return self.event.name class JoinGroupNotification(models.Model): notice = models.ForeignKey('GroupNotice') ## user=models.ForeignKey('Squirl', default=DEFAULT_USER) user=models.ForeignKey('Squirl', null = True, blank=True) class Event(models.Model): main_location = models.ForeignKey("Address") start_time = models.DateTimeField('Start time') end_time = models.DateTimeField('End time') name = models.CharField(max_length = 150) description = models.CharField(max_length = 1000) PRIVACY_SETTINGS=( (0,'open'), (1,'invite only'), (2, 'friends only'), (3, 'acquaintance only'), ) privacy=models.IntegerField(choices=PRIVACY_SETTINGS, default = 0) interests = models.ManyToManyField('Interest') def __str__(self): return self.name def __unicode__(self): return self.name class SubGroupNotification(models.Model): ## fromGroup = models.ForeignKey('Group', related_name= "fromGroup", default=DEFAULT_GROUP) ## toGroup = models.ForeignKey('Group', related_name="toGroup", default=DEFAULT_GROUP) fromGroup = models.ForeignKey('Group', related_name= "fromGroup", null = True, blank=True) toGroup = models.ForeignKey('Group', related_name="toGroup", null = True, blank=True) viewed = models.BooleanField(default=0) CHOICES=( (0, 'Child'), (1, 'Parent'), (2, 'Parent and child'), ) role = models.IntegerField(choices=CHOICES, default = 0) class Interest(models.Model): name = models.CharField(max_length = 100, default = 'None') description = models.CharField(max_length = 300, null = True, blank = True) def __str__(self): return self.name class Squirl(models.Model): squirl_user = models.OneToOneField(User) interests = models.ManyToManyField('Interest') ## home = models.ForeignKey('Location', default = DEFAULT_LOCATION) home = models.ForeignKey('Location', null = True, blank = True) def __str__(self): return self.squirl_user.username class Connection(models.Model): ## user = models.ForeignKey('Squirl', default=DEFAULT_USER) user = models.ForeignKey('Squirl', null = True, blank = True) relation = models.ForeignKey('Relation') class Relation(models.Model): ## user = models.ForeignKey('Squirl', default=SECOND_DEFAULT_USER) user = models.ForeignKey('Squirl', null = True, blank = True) RELATION=( (0, 'acquaintance'), (1, 'block'), (2, 'friend'), ) relation = models.IntegerField(choices=RELATION, default=0) def __str__(self): return self.user.squirl_user.username def __unicode__(self): return self.user.squirl_user.username class UserEventPlan(models.Model): USER_STATUS = ( (0, 'Commit'), (1, 'Not Sure'), (2, 'Probably'), (3, 'No'), (4, 'Unlikely'), ) ##Don't think I need the previous event relation field for this status = models.IntegerField(choices=USER_STATUS, default = 3) ## squirl_user = models.ForeignKey('Squirl', default = DEFAULT_USER) ## event = models.ForeignKey('Event', default = DEFAULT_EVENT) squirl_user = models.ForeignKey('Squirl', null = True, blank = True) event = models.ForeignKey('Event', null = True, blank = True) def __str__(self): return self.event.name def __unicode__(self): return self.event.name class Member(models.Model): ## user=models.ForeignKey('Squirl', default =DEFAULT_USER) user=models.ForeignKey('Squirl', null = True, blank = True) group = models.ForeignKey('Group') #decide if we want to have any data about how often they attend meetings GROUP_ROLE_CHOICES = ( (0,'Owner'), (1, 'Member'), (2, 'Editor'), ) role = models.IntegerField(choices=GROUP_ROLE_CHOICES, default = 1) def __str__(self): return self.user.squirl_user.username def __unicode__(self): return self.user.squirl_user.username class UserEvent(models.Model): ## event = models.ForeignKey('Event', default = DEFAULT_EVENT) ## creator = models.ForeignKey('Squirl', default = DEFAULT_USER) event = models.ForeignKey('Event', null = True, blank = True) creator = models.ForeignKey('Squirl', null = True, blank = True) def __str__(self): return self.event.name def __unicode__(self): return self.event.name class GroupEvent(models.Model): group = models.ForeignKey('Group') event = models.ForeignKey('Event') parent = models.ForeignKey('GroupEvent', null=True, blank=True) greatest_ancestor = models.ForeignKey('AncestorGroupEvent', null=True, blank=True) def __unicode__(self): return str(self.id) class Group( models.Model): name = models.CharField(max_length = 100, primary_key = True) interests = models.ManyToManyField(Interest) description = models.CharField(max_length = 1000) sub_group = models.ManyToManyField('Group') ## location = models.ForeignKey('Location', default=DEFAULT_LOCATION) location = models.ForeignKey('Address', null = True, blank = True) def __str__(self): return self.name def __unicode__(self): return self.name class State(models.Model): name = models.CharField(max_length=100) abbr = models.CharField(max_length=2) def __str__(self): return self.name def __unicode__(self): return self.name
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,412
squirl/squirl
refs/heads/master
/squirl/eventMethods.py
from .models import Event, EventNotification, UserEventPlan, Notice, Event, GroupEvent, UserEvent from django.utils.html import conditional_escape as esc from django.forms.formsets import formset_factory from .methods import get_notice from .groupMethods import has_edit_privileges_for_group from .forms import EventNotificationForm import datetime def get_event(event_id): try: return Event.objects.get(id=event_id) except Event.DoesNotExist: return None def get_event_notification_by_notice_event(notice, event): try : return EventNotification.objects.get(notice=notice, event=event) except EventNotification.DoesNotExist: return None def display_event(event_id): event = get_event(event_id) if event is None: return "<p>Event does not exist</p>" else: invites = EventNotification.objects.filter(event =event) responses = UserEventPlan.objects.filter(event=event) toReturn = "" toReturn += "<p> <h4>%s</h4>" % esc(event.name) toReturn +="<a href= '/squirl/event/%s'>Go to event page</a>" %esc(event.id) toReturn +="<div>Location: %s</div>" %esc(event.main_location) toReturn +="<div>Start: %s </div>" %esc(event.start_time) toReturn +="<div>End: %s </div>" %esc(event.end_time) toReturn +="<div>%s users invited</div>" %invites.count() toReturn +="<div>%s are committed</div>" % responses.filter(status=0).count() toReturn +="<div>%s are probably going</div>" % responses.filter(status=2).count() toReturn +="<div>%s are not sure</div>" % responses.filter(status=1).count() toReturn +="<div>%s are unlikely to show up</div>" % responses.filter(status=4).count() toReturn +="<div>%s have declined</div>" % responses.filter(status=3).count() toReturn += "</p>" return toReturn def get_user_event_notifications(squirl): event_formset = formset_factory(EventNotificationForm, extra=0) event_notifications = EventNotification.objects.filter(notice__user = squirl, notice__viewed=0) initial_list = [] for event in event_notifications: initial_list.append({'eventName': event.event.name, 'noticeId': event.notice.id,'response': 0, 'eventId': event.event.id,}) return event_formset(initial=initial_list, prefix = 'event_notices') def validate_event_notifications_formset(formset, squirl): for form in formset: if form.is_valid(): data = form.cleaned_data event = get_event(data['eventId']) print(event.name) if event is None: print("event does not exist") return False notice = get_notice(int(data['noticeId'])) if notice is None: print("notice does not exist") return False if notice.user != squirl: print("wrong user") return False print(notice.id) event_notice = get_event_notification_by_notice_event(notice, event) if event_notice is None: print("event notice does not exist") return False response = int(data['response']) if response > 5 or response <0: print("response not valid") return False else: return False return True def create_from_event_notification_formset(formset, squirl): for form in formset: data = form.cleaned_data response = int(data['response']) if response != 0: notice = get_notice(data['noticeId']) event = get_event(data['eventId']) event_notice = get_event_notification_by_notice_event(notice, event) notice.viewed = True notice.save() if response != 1: userPlan = UserEventPlan() userPlan.squirl_user = squirl userPlan.event = event if response == 2: userPlan.status= 1 if response == 3: userPlan.status=0 if response == 4: userPlan.status=2 if response ==5: userPlan.status =4 userPlan.save() #actually gets user event plans def get_user_upcoming_events(squirl): now = datetime.datetime.now().replace(hour=0,minute=0,second=0) events = UserEventPlan.objects.filter(squirl_user = squirl, event__end_time__gte = now).order_by('event__start_time') ## to_exclude = events.filter(start_time__date__year = now.date.year, start_time__date__month__lt = now.date.month).values('id') ## ## events = events.exclude(id__in=to_exclude) ## ## to_exclude = events.filter(start_time__date__year = now.date.year, start_time__date__month = now.date.month, start_time__date__day__lt = now.date.day).values('id') ## ## events = events.exclude(id__in=to_exclude) #the below line is wrong. #events = events.filter(start_time__year >=now.year, start_time__month >=now.month, start_time__day >= now.day) return events def get_event_notification_by_user_and_event(squirl, event): try: toReturn = EventNotification.objects.get(notice__user = squirl, event= event) return toReturn except EventNotification.DoesNotExist: return None def can_user_edit_event(squirl, event): u_event = None try: u_event = GroupEvent.objects.get(event=event) return has_edit_privileges_for_group(squirl, u_event.group) except GroupEvent.DoesNotExist: u_event = None if u_event is None: try: u_event = UserEvent.objects.get(event=event) if u_event.creator == squirl: return True except UserEvent.objects.DoesNotExist: print("Event is not associated with anyone") return False return false
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,413
squirl/squirl
refs/heads/master
/squirl/friendMethods.py
from .models import FriendNotification, Connection, Relation from .methods import get_squirl def get_friend_notification(to_squirl, from_squirl): try: notice = FriendNotification.objects.get(user =from_squirl, notice__user=to_squirl) return notice except FriendNotification.DoesNotExist: return None def get_friend_connection(owner_squirl, relation_squirl): try: connection = Connection.objects.get(user=owner_squirl, relation__user=relation_squirl) return connection except Connection.DoesNotExist: return None def valid_connection(owner_squirl, relation_squirl): return owner_squirl != relation_squirl def create_connection(owner_squirl, relation_squirl, role): relation = Relation() relation.relation = role relation.user = relation_squirl connection = Connection() connection.user = owner_squirl relation.save() connection.relation = relation connection.save() def update_connection(connection, role): connection.relation.relation = role connection.relation.save() def validate_friend_formset(formset, s_user): for form in formset: data = form.cleaned_data r_friend = get_squirl(data['friend']) if r_friend is None: print("Friend is none") return False if int(data['relation']) < 0 or int(data['relation']) > 2: print("incorrect range") return False if r_friend == s_user: print("friend == request") return False if get_friend_notification(s_user, r_friend) is None: print("notice is None") return False return True """Assumes that all validation was done.""" def handle_friend_formset(formset, s_user): for form in formset: data = form.cleaned_data r_user = get_squirl(data['friend']) connection = get_friend_connection(s_user, r_user) if connection is None: create_connection(s_user, r_user, int(data['relation'])) else: update_connection(connection, int(data['relation'])) notice = get_friend_notification(s_user, r_user) notice.notice.viewed = True notice.notice.save()
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,414
squirl/squirl
refs/heads/master
/squirl/groupMethods.py
from .models import Group, Squirl, Member, JoinGroupNotification, GroupNotice from django.forms.formsets import formset_factory from .groupForms import JoinGroupRequestForm, CreateSubGroupRequestForm, SubGroupNotificationForm, ParentEventNoticeForm from .methods import get_squirl from .models import SubGroupNotification, ParentEventNotice, AncestorGroupEvent, Notice, GroupEvent, Event, EventNotification """ Determines if the user has access to the group """ def user_has_access_to_group(squirl, group): return True """ Returns either the group with the specified primary key or None if it does not exist """ def get_group(group_pk): try: group = Group.objects.get(pk=group_pk) return group except Group.DoesNotExist: return None """ Determines whether or not the group requires an admin to add members. """ def group_requires_admin_to_add_member(squirl, group): return True """ Returns the member that has that squirl and group as properties or returns None if no member can be found """ def get_member(squirl, group): try: member = Member.objects.get(user=squirl, group=group) return member except Member.DoesNotExist: return None """ Gets a notification that has the specified user and group or returns None if it doesn't exist """ def get_group_notification(squirl, group): try: notification = JoinGroupNotification.objects.get(user=squirl, notice__group=group) return notification except JoinGroupNotification.DoesNotExist: return None """ Adds a user as a member of a group """ def add_member_to_group(squirl, group, role=1): try: member = Member() member.role = role member.user = squirl member.group = group member.save() return 0 except: return 1 """ Creates a notification for a user trying to join a gorup """ def create_group_notification(squirl,group): try: notice = GroupNotice() notification = JoinGroupNotification() notice.group = group notice.save() notification.notice = notice notification.user = squirl notification.save() return 0 except: return 1 def has_admin_rights_to_group(squirl, group): try: member = Member.objects.get(user=squirl, group=group,role=0) return True except Member.DoesNotExist: return False def has_edit_privileges_for_group(squirl, group): return has_admin_rights_to_group(squirl, group) def get_groups_user_admin(squirl): memberships = Member.objects.filter(user=squirl, role = 0) if memberships: groups = [] for member in memberships: groups.append(member.group) return groups else: return None def get_join_group_notifications(group): return JoinGroupNotification.objects.filter(notice__group=group, notice__viewed=0) def get_join_group_formset(squirl): groups = get_groups_user_admin(squirl) notifications= [] join_group_formset = formset_factory(JoinGroupRequestForm, extra =0) if groups is not None: for group in groups: temp_notifications = get_join_group_notifications(group) for notice in temp_notifications: notifications.append(notice) initial_list = [] for notice in notifications: initial_list.append({'user': notice.user.squirl_user.id, 'group': notice.notice.group, }) return join_group_formset(initial=initial_list, prefix='joinGroup') return join_group_formset(prefix='joinGroup') def validate_join_group_formset(formset, squirl): valid = True groups = get_groups_user_admin(squirl) for form in formset: group = get_group(form['group'].value) if group is None or group not in groups: valid = False break s_user = get_squirl(form['user'].value) if s_user is None: valid = False break notice = get_group_notification(s_user, group) if notice is None or notice.notice.viewed == 1: valid = False break return valid def create_members_join_group_formset(formset): for form in formset: if form.is_valid(): data = form.cleaned_data s_user = get_squirl(data['user']) group = get_group(data['group']) if get_member(s_user, group) is None: role = int(data['role']) if role != 0: print(role) notice = get_group_notification(s_user, group) notice.notice.viewed = 1 notice.notice.save() if role != 1: member = Member() member.user = s_user member.group=group if role == 2: member.role = 0 elif role ==3: member.role = 1 elif role ==4: member.role = 2 else: member.role=1 member.save() def get_sub_group_request(group, squirl): admin_groups = get_groups_user_admin(squirl) if admin_groups is None: return None if group in admin_groups: admin_groups.remove(group) if len(admin_groups) == 0: return None groups = Group.objects.filter(pk__in=admin_groups) #TODO check if relations exist form = CreateSubGroupRequestForm(initial={'group1': group.pk}) form.fields['group2'].queryset=groups return form def validate_create_subgroup_request_form(data, squirl): group = data['group2'] admin_groups= get_groups_user_admin(squirl) if group not in admin_groups: return False group1 = get_group(data['group1']) if group1 is None: return False return True def create_subgroup_request(data, squirl): group1 = get_group(data['group1']) group2 = get_group(data['group2']) choice = int(data['role']) admin_groups = get_groups_user_admin(squirl) #don't need to create request. Can instead make it happen. if group2 not in admin_groups: return "Error, you need to be an admin of group {0}".format(group2.name) if group1 in admin_groups: groups = group1.sub_group.filter(pk=group2.pk) if choice == 0: print("here") if group2 in groups: print("not here") return "Group {0} is already a subgroup of {1}".format(group2.name, group1.name) else: print("not hhhhre") group1.sub_group.add(group2) group1.save() return "Success the subgroup was added." else: groups = group2.sub_group.filter(pk =group1.pk) if group1 in groups: return "Group %s is already a subgroup of %s" % group1.name, group2.name else: group2.sub_group.add(group1) group2.save() return "Success the subgroup was added." else: subNotice = get_sub_group_notification(group1, group2) #Check if there is already a sub group notification. if subNotice is None: if choice == 0: if group2 in group1.sub_group.all(): return "Group {0} is already a subgroup of {1}".format(group2.name, group1.name) else: print("create notice here") subGroupNotice = SubGroupNotification() subGroupNotice.toGroup=group1 subGroupNotice.fromGroup=group2 subGroupNotice.choice=0 subGroupNotice.save() return ("success, notice sent") else: if group1 in group2.sub_group.all(): return "Group {0} is already a subgroup of {1}".format(group1.name, group2.name) else: print("create notice here") subGroupNotice = SubGroupNotification() subGroupNotice.toGroup=group1 subGroupNotice.fromGroup=group2 subGroupNotice.choice=1 subGroupNotice.save() return ("success, notice sent") #create new notice #If there is check if it is for the correct role. #Check if sub group relation already exists. else: print("turd bucket") if subNotice.role == choice: if subNotice.viewed: if choice == 0 and group2 in group1.sub_group.all(): return "Group {0} is already a subgroup of {1}".format(group2.name, group1.name) elif choice == 1 and group1 in group2.sub_group.all(): return "Group {0} is already a subgroup of {1}".format(group1.name, group2.name) else: subNotice.viewed = False subNotice.save() return "Notification already exists" else: return "Notification already exists." else: otherExists = False if choice == 0: otherExists = group1 in group2.sub_group.all() elif choice ==1: otherExists = group2 in group1.sub_group.all() if otherExists: subNotice.role = choice subNotice.save() else: if subNotice.role == 2: subNotice.role = choice else: subNotice.role = 2 subNotice.viewed = False subNotice.save() return "Notification updated." #alter notification set to not viewed and save. #or create a new notification. return "still need to implement subgroup notifications" def get_sub_group_notification(group1, group2): try: notice = SubGroupNotification.objects.get(toGroup=group1, fromGroup=group2) return notice except SubGroupNotification.DoesNotExist: return None """ Returns the sub group notification if it exists otherwise it returns None. Uses an id to search for the sub_group_notification """ def get_sub_group_notification_by_id(notice_id): try: notice = SubGroupNotification.objects.get(id = notice_id) return notice except SubGroupNotification.DoesNotExist: return None def get_parent_event_notifications(squirl): adminGroups = get_groups_user_admin(squirl) to_return = [] for tGroup in adminGroups: notices = ParentEventNotice.objects.filter(group = tGroup, viewed=False) for tNotice in notices: to_return.append(tNotice) if len(to_return) == 0: return None return to_return def get_parent_event_notification_formset(squirl): adminGroups = get_groups_user_admin(squirl) #create initial formset formset = formset_factory(ParentEventNoticeForm, extra =0) if adminGroups is not None: initial_list =[] for tGroup in adminGroups: notices = ParentEventNotice.objects.filter(group = tGroup, viewed=False) for tNotice in notices: #{'toGroup': tNotice.toGroup, 'fromGroup': tNotice.fromGroup, 'role': tNotice.role, } initial_list.append({'notice': tNotice}) return formset(initial=initial_list, prefix='parentEventNotices') else: return None def validate_parent_event_formset(formset, squirl): valid = True notices = get_parent_event_notifications(squirl) for form in formset: if form.is_valid(): if form.cleaned_data['notice'] not in notices: return False else: return False return valid def handle_parent_event_formset(formset): print("lskdjflksdjf") for form in formset: data = form.cleaned_data action = int(data['choice']) if action != 0: notice = data['notice'] notice.viewed = True notice.save() if action == 1: t_event = notice.ancestor_event.event event = Event() event.main_location= t_event.event.main_location event.start_time = t_event.event.start_time event.end_time = t_event.event.end_time event.name = t_event.event.name event.description = t_event.event.description event.privacy = t_event.event.privacy event.save() for interest in t_event.event.interests.all(): event.interests.add(interest) event.save() groupEvent = GroupEvent() groupEvent.group = notice.group groupEvent.event = event groupEvent.parent = notice.parent_event groupEvent.greatest_ancestor = notice.ancestor_event groupEvent.save() mems = Member.objects.filter(group = groupEvent.group) for m in mems: if not EventNotification.objects.filter(notice__user = m.user, ancestor_event = notice.ancestor_event) and not EventNotification.objects.filter(notice__user = m.user, event = notice.ancestor_event.event.event): #Notify them note = Notice() note.user = m.user note.save() n = EventNotification() n.notice = note n.event = event n.ancestor_event = notice.ancestor_event n.save() sub_groups = notice.group.sub_group.all() for g in sub_groups: if g not in notice.ancestor_event.notified_groups.all(): notice.ancestor_event.notified_groups.add(g) #create new notice pn = ParentEventNotice() pn.group = g pn.parent_group = notice.notice.group pn.ancestor_event = notice.ancestor_event pn.save() notice.ancestor_event.save() return "success" #notify all members that haven't been def get_sub_group_notifications_formset(squirl): adminGroups = get_groups_user_admin(squirl) formset = formset_factory(SubGroupNotificationForm, extra =0) if adminGroups is not None: initial_list =[] for tGroup in adminGroups: notices = SubGroupNotification.objects.filter(toGroup=tGroup, viewed = False) for tNotice in notices: #{'toGroup': tNotice.toGroup, 'fromGroup': tNotice.fromGroup, 'role': tNotice.role, } initial_list.append({'subNoticeModel': tNotice}) return formset(initial=initial_list, prefix='subGroupNotifications') else: return formset(prefix='subGroupNotifications') def validate_sub_group_notification_post(formset, squirl): for form in formset: data = form.cleaned_data # print "Data['subNoticeModel']" + data['subNoticeModel'] notice = get_sub_group_notification_by_id(data['subNoticeModel'].id) if notice is None: return False if not has_admin_rights_to_group(squirl, notice.toGroup): return False return True def handle_sub_group_notification_post(formset, squirl): for form in formset: data = form.cleaned_data notice = get_sub_group_notification_by_id(data['subNoticeModel'].id) action = int(data['action']) if action != 0: if action == 1: #create stuff relation = notice.role if relation == 0 or relation == 2: if not notice.fromGroup in notice.toGroup.sub_group.all(): notice.toGroup.sub_group.add(notice.fromGroup) notice.toGroup.save() if relation ==1 or relation == 2: if not notice.toGroup in notice.fromGroup.sub_group.all(): notice.fromGroup.sub_group.add(notice.toGroup) notice.fromGroup.save() notice.viewed = True notice.save() return "Success"
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,415
squirl/squirl
refs/heads/master
/squirl/migrations/0003_auto_20150904_2015.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('squirl', '0002_auto_20150827_2052'), ] operations = [ migrations.CreateModel( name='AncestorGroupEvent', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ], ), migrations.CreateModel( name='ParentEventNotice', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('ancestor_event', models.ForeignKey(to='squirl.AncestorGroupEvent')), ('group', models.ForeignKey(to='squirl.Group')), ], ), migrations.AddField( model_name='groupevent', name='parent', field=models.ForeignKey(blank=True, to='squirl.GroupEvent', null=True), ), migrations.AddField( model_name='ancestorgroupevent', name='event', field=models.ForeignKey(to='squirl.GroupEvent'), ), migrations.AddField( model_name='ancestorgroupevent', name='notified_groups', field=models.ManyToManyField(to='squirl.Group'), ), migrations.AddField( model_name='groupevent', name='greatest_ancestor', field=models.ForeignKey(blank=True, to='squirl.AncestorGroupEvent', null=True), ), ]
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,416
squirl/squirl
refs/heads/master
/squirl/ajaxViews.py
from django.shortcuts import render from django.http import HttpResponse from .views import squirl_login from .groupForms import CreateSubGroupRequestForm from .methods import get_squirl from .groupMethods import create_subgroup_request, validate_create_subgroup_request_form from .models import SubGroupNotification, Event, Group, Squirl from .forms import SearchPageForm from .methods import get_interest_by_name import datetime import json def handle_sub_group_request(request): if not request.user.is_authenticated(): return redirect(squirl_login) else: if request.method == 'POST': success = True print("post") #handle the post form = CreateSubGroupRequestForm(request.POST) squirl = get_squirl(request.user.id) message = "" if form.is_valid(): print("valid") data = form.cleaned_data success = validate_create_subgroup_request_form(data, squirl) print(success) message = create_subgroup_request(data, squirl) if message == "": message = "no news" else: print("form not valid") print(form) success= False if request.is_ajax(): print("ajax") if message is None: message = "Form was not valid" response_data = {'message': message} print(response_data); return HttpResponse(json.dumps(response_data), content_type="application/json") #this is where we have a something else: return HttpResponse("Error. Can only post to this page.") def search_page(request): if not request.user.is_authenticated(): return redirect(squirl_login) form = SearchPageForm() response_data = {'message': ""} if request.method == 'POST': form = SearchPageForm(request.POST) if form.is_valid(): #get events events = Event.objects.order_by('start_time') #only want current events events = events.filter(end_time__gte = datetime.datetime.now()).distinct() #get groups groups = Group.objects.order_by('name').distinct() #get users users = Squirl.objects.order_by('squirl_user__username').distinct() #filter by interest data = form.cleaned_data if len(data['interest']) != 0: inter = get_interest_by_name(data['interest']) if inter is None: response_data['message'] = "No results." events = events.none() groups = groups.none() users = users.none() else: events = events.filter(interests= inter).distinct() groups = groups.filter(interests = inter).distinct() users = users.filter(interests = inter).distinct() if len(data['city']) != 0 and data['state'] is not None: #filter things by city and state events = events.filter(main_location__city = data['city'], main_location__state = data['state']) groups = groups.filter(location__city = data['city'], location__state = data['state']) users = users.filter(home__city=data['city'], home__state=data['state']) response_data['groups'] = "none" response_data['events'] = "none" response_data['users'] = "none" #package the data and send her off. g_data = [] for g in groups: g_data.append({'groupName': g.name, 'groupPk': g.pk}) response_data['groups'] = g_data e_data = [] for e in events: e_data.append({'eventName': e.name, 'eventId': e.id}) response_data['events'] = e_data u_data = [] for u in users: u_data.append({'userName': u.squirl_user.username, 'userId':u.squirl_user.id}) response_data['users'] = u_data if len(response_data['message']) ==0: response_data['message'] = "Success!" return HttpResponse(json.dumps(response_data), content_type="application/json") response_data['message'] = "Error, only posts allowed" return HttpResponse(json.dumps(response_data), content_type="application/json")
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,417
squirl/squirl
refs/heads/master
/squirl/migrations/0002_auto_20150827_2052.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('squirl', '0001_initial'), ] operations = [ migrations.AlterField( model_name='event', name='main_location', field=models.ForeignKey(to='squirl.Address'), ), ]
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,418
squirl/squirl
refs/heads/master
/squirl/urls.py
from django.conf.urls import url from . import views from . import ajaxViews urlpatterns = [ url(r'^$', views.index, name = 'index'), url(r'^login/$', views.squirl_login, name = 'squirl_login'), url(r'^addEvent/$', views.add_event, name = 'addEvent'), url(r'^signOut/$', views.squirl_logout, name='squirl_logout'), url(r'^createGroup/$', views.create_group, name='createGroup'), url(r'^event/(?P<event_id>[0-9]+)/$',views.event_page, name='event_page'), url(r'^group/(?P<group_id>[-\w ]+)/$',views.group_page, name='group_page'), url(r'^createAccount/$', views.create_account, name='create_account'), url(r'^search/$', views.search_page, name='search_page'), url(r'^profile/(?P<user_id>[0-9]+)/$', views.profile_page, name='profile_page'), url(r'^joinGroup/(?P<group_id>[\w ]+)/$', views.join_group_request, name='join_group_request'), url(r'^subGroupRequest/$', ajaxViews.handle_sub_group_request, name='handle_sub_group_request'), url(r'^editEvent/(?P<event_id>[0-9]+)/$',views.edit_event, name='edit_event'), url(r'^searchSubmit/$', ajaxViews.search_page, name='search_page'), ]
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,419
squirl/squirl
refs/heads/master
/squirl/migrations/0008_auto_20150904_2245.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('squirl', '0007_auto_20150904_2036'), ] operations = [ migrations.RemoveField( model_name='parenteventnotice', name='parent_group', ), migrations.AddField( model_name='parenteventnotice', name='parent_event', field=models.ForeignKey(blank=True, to='squirl.GroupEvent', null=True), ), ]
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,420
squirl/squirl
refs/heads/master
/squirl/migrations/0004_auto_20150904_2016.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('squirl', '0003_auto_20150904_2015'), ] operations = [ migrations.AlterField( model_name='event', name='interests', field=models.ManyToManyField(to='squirl.Interest'), ), migrations.AlterField( model_name='group', name='sub_group', field=models.ManyToManyField(to='squirl.Group'), ), migrations.AlterField( model_name='squirl', name='interests', field=models.ManyToManyField(to='squirl.Interest'), ), ]
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,421
squirl/squirl
refs/heads/master
/utils/templatetags/utility_tags.py
import urllib from django import template from django.utils.encoding import force_str from django.contrib.auth.models import User from squirl.models import SubGroupNotification, Event, GroupEvent, UserEvent register = template.Library() @register.simple_tag(takes_context=True) def append_to_query(context, **kwargs): """Renders a link with modified current query parameters""" query_params = context['request'].GET.copy() for key, value in kwargs.items(): query_params[key] = value query_string= u"" if len(query_params): query_string += u"?%s" % urllib.urlencode([ (key, force_str(value)) for (key, value) in query_params. iteritems() if value ]).replace('&', '&amp;') return query_string @register.simple_tag def get_username_from_userid(user_id): try: return User.objects.get(id=user_id).username except User.DoesNotExist: return 'Unknown' @register.simple_tag def print_sub_group_request_form(form_id): toReturn = "" try: subNotice = SubGroupNotification.objects.get(id=form_id) except SubGroupNotification.DoesNotExist: return None temp = subNotice.role text = "" if temp ==0: text = "child" elif temp == 1: text = "parent" elif temp ==2: text = "both a parent and child" else: text = "BLANK" toReturn+= "{0}".format(subNotice.fromGroup) toReturn += " would like to be a {0}".format(text) toReturn += " of {0}".format(subNotice.toGroup) return toReturn @register.simple_tag def print_address(address): to_print = "" to_print +=str(address.num) + " " + address.street + " " + address.city + "," + address.state.abbr return to_print @register.simple_tag def print_part_of(event): u_event = None try: u_event = GroupEvent.objects.get(event=event) except GroupEvent.DoesNotExist: u_event = None if u_event is None: try: u_event = UserEvent.objects.get(event=event) except UserEvent.DoesNotExist: print("Event is not associated with anyone") return "Error" return "User: {0} is the owner of the event".format(u_event.creator.squirl_user.username) else: return "Part of Group: {0}".format(u_event.group.name) @register.simple_tag def print_event_role(role): role = int(role) options= {0: 'Commit', 1: 'Not Sure', 2: 'Probably', 3: 'No', 4: 'Unlikely' } return options[role] @register.simple_tag def print_membership(membership): roles ={ 0: 'Owner', 1: 'Member', 2: 'Editor', } return roles[membership]
{"/squirl/migrations/0009_auto_20150905_1622.py": ["/squirl/models.py"], "/squirl/groupForms.py": ["/squirl/models.py"], "/squirl/forms.py": ["/squirl/models.py"], "/squirl/methods.py": ["/squirl/models.py", "/squirl/forms.py"], "/squirl/admin.py": ["/squirl/models.py"], "/squirl/ajax.py": ["/squirl/views.py"], "/squirl/eventMethods.py": ["/squirl/models.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/forms.py"], "/squirl/friendMethods.py": ["/squirl/models.py", "/squirl/methods.py"], "/squirl/groupMethods.py": ["/squirl/models.py", "/squirl/groupForms.py", "/squirl/methods.py"], "/squirl/ajaxViews.py": ["/squirl/views.py", "/squirl/groupForms.py", "/squirl/methods.py", "/squirl/groupMethods.py", "/squirl/models.py", "/squirl/forms.py"], "/utils/templatetags/utility_tags.py": ["/squirl/models.py"]}
59,425
Zorking/debug_examples
refs/heads/master
/qwerty/views.py
from django.shortcuts import render from rest_framework import serializers from rest_framework import views # Create your views here. from rest_framework.generics import ListAPIView from rest_framework.response import Response from qwerty.models import Order, Films class Example3Serializer(serializers.Serializer): id = serializers.CharField() class Example3_2Serializer(serializers.Serializer): id = serializers.CharField() name = serializers.CharField() cost = serializers.CharField() class Example3(views.APIView): def post(self, request, *_, **__): serializer = Example3Serializer(data=request.data) serializer.is_valid(raise_exception=True) orders = Order.objects.raw("SELECT id, name, cost FROM qwerty_order WHERE id=" + serializer.validated_data.get("id")) data = [] for order in orders: data.append({"id": order.id, "name": order.name, "cost": order.cost}) return Response(data) class Example4(views.APIView): def post(self, *_, **__): order = Order.objects.last() order.name = "example" order.save() return Response() class Example4_2(views.APIView): def post(self, *_, **__): order = Order.objects.last() order.cost = "example" order.save() return Response() class Example5(views.APIView): def get(self, *_, **__): orders = Order.objects.all() customer_names = [] for order in orders: customer_names.append(order.customer.name) return Response(len(customer_names)) class Example6Serializer(serializers.ModelSerializer): class Meta: model = Films fields = "__all__" # another common mistake class Example6Serializer(serializers.Serializer): field1 = serializers.CharField(default="") field2 = serializers.CharField(default="") field3 = serializers.CharField(default="") field4 = serializers.CharField(default="") field5 = serializers.CharField(default="") class Example6(views.APIView): # FIXED IN NEXT DJANGO VERSION def patch(self, *_, **__): instance = {"field1": "example"} serialized_data = Example6Serializer(data=instance, partial=True) if serialized_data.is_valid(): _declared_fields = serialized_data._declared_fields.keys() _declared_fields = [x for x in _declared_fields] for key in _declared_fields: if key not in serialized_data.validated_data.keys(): serialized_data._declared_fields.pop(key) _ = serialized_data._fields _ = serialized_data._readable_fields del serialized_data._fields del serialized_data._readable_fields return Response(serialized_data.data) def get(self, *args, **kwargs): return Response(Example6Serializer(instance={}).data)
{"/qwerty/views.py": ["/qwerty/models.py"], "/example2_2.py": ["/example2.py"], "/example2.py": ["/example2_2.py"]}
59,426
Zorking/debug_examples
refs/heads/master
/example2_2.py
import example2 x = 1 def g(): print(example2.f())
{"/qwerty/views.py": ["/qwerty/models.py"], "/example2_2.py": ["/example2.py"], "/example2.py": ["/example2_2.py"]}
59,427
Zorking/debug_examples
refs/heads/master
/qwerty/models.py
from django.db import models # Create your models here. class Customer(models.Model): name = models.CharField(max_length=255) class Order(models.Model): name = models.CharField(max_length=255) cost = models.CharField(max_length=255) ... customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class Films(models.Model): nconst = models.CharField(max_length=3000, blank=True, null=True) primaryName = models.CharField(max_length=3000, blank=True, null=True) birthYear = models.CharField(max_length=3000, blank=True, null=True) deathYear = models.CharField(max_length=3000, blank=True, null=True) primaryProfession = models.CharField(max_length=3000, blank=True, null=True) knownForTitles = models.CharField(max_length=3000, blank=True, null=True)
{"/qwerty/views.py": ["/qwerty/models.py"], "/example2_2.py": ["/example2.py"], "/example2.py": ["/example2_2.py"]}
59,428
Zorking/debug_examples
refs/heads/master
/example2.py
import example2_2 def f(): return example2_2.x print(f())
{"/qwerty/views.py": ["/qwerty/models.py"], "/example2_2.py": ["/example2.py"], "/example2.py": ["/example2_2.py"]}
59,429
Zorking/debug_examples
refs/heads/master
/example1.py
def is_odd(x: int) -> bool: return bool(x % 2) numbers = [n for n in range(10)] for i in range(len(numbers)): if is_odd(numbers[i]): del numbers[i] print(numbers)
{"/qwerty/views.py": ["/qwerty/models.py"], "/example2_2.py": ["/example2.py"], "/example2.py": ["/example2_2.py"]}
59,430
Zorking/debug_examples
refs/heads/master
/qwerty/migrations/0002_auto_20200421_2131.py
# Generated by Django 2.2.9 on 2020-04-21 21:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('qwerty', '0001_initial'), ] operations = [ migrations.AlterField( model_name='films', name='birthYear', field=models.CharField(blank=True, max_length=3000, null=True), ), migrations.AlterField( model_name='films', name='deathYear', field=models.CharField(blank=True, max_length=3000, null=True), ), migrations.AlterField( model_name='films', name='knownForTitles', field=models.CharField(blank=True, max_length=3000, null=True), ), migrations.AlterField( model_name='films', name='nconst', field=models.CharField(blank=True, max_length=3000, null=True), ), migrations.AlterField( model_name='films', name='primaryName', field=models.CharField(blank=True, max_length=3000, null=True), ), migrations.AlterField( model_name='films', name='primaryProfession', field=models.CharField(blank=True, max_length=3000, null=True), ), ]
{"/qwerty/views.py": ["/qwerty/models.py"], "/example2_2.py": ["/example2.py"], "/example2.py": ["/example2_2.py"]}
59,431
Zorking/debug_examples
refs/heads/master
/example1_2.py
def is_odd(x: int) -> bool: return bool(x % 2) numbers = [n for n in range(10)] numbers[:] = [n for n in numbers if not is_odd(n)] print(numbers)
{"/qwerty/views.py": ["/qwerty/models.py"], "/example2_2.py": ["/example2.py"], "/example2.py": ["/example2_2.py"]}
59,433
fpwanderley/InfoMe-Backend
refs/heads/master
/infome/admin.py
from django.contrib import admin from infome.models import Call, Tag # Register your models here. class CallAdmin(admin.ModelAdmin): fields = ('description', 'status') list_display = ('description', 'status') class Meta: model = Call class TagAdmin(admin.ModelAdmin): fields = ('description',) list_display = ('description',) class Meta: model = Tag admin.site.register(Call, CallAdmin) admin.site.register(Tag, TagAdmin)
{"/infome/admin.py": ["/infome/models.py"], "/test_db.py": ["/infome/models.py"], "/infome/hand/serializers.py": ["/infome/models.py"], "/infome/call/serializers.py": ["/infome/models.py"], "/infome/call/endpoints.py": ["/infome/models.py", "/infome/call/serializers.py"], "/infome/hand/endpoints.py": ["/infome/models.py", "/infome/hand/serializers.py"], "/infome/call/urls.py": ["/infome/call/endpoints.py"], "/infome/hand/urls.py": ["/infome/hand/endpoints.py"]}
59,434
fpwanderley/InfoMe-Backend
refs/heads/master
/test_db.py
# -*- coding: utf-8 -*- import random from infome.models import * CALL_DESCRIPTIONS = [ u'Preciso de um Eletricista', u'Preciso de um Encanador', u'Preciso de um bolo', u'Preciso de uma dedada', u'Preciso de um Tecnico em Informatica', ] print ('Creating Test DB.') for description in CALL_DESCRIPTIONS: new_location = Location.objects.create(latitude=random.uniform(1,2), longitude=random.uniform(1,2)) Call.objects.create(description=description, location=new_location)
{"/infome/admin.py": ["/infome/models.py"], "/test_db.py": ["/infome/models.py"], "/infome/hand/serializers.py": ["/infome/models.py"], "/infome/call/serializers.py": ["/infome/models.py"], "/infome/call/endpoints.py": ["/infome/models.py", "/infome/call/serializers.py"], "/infome/hand/endpoints.py": ["/infome/models.py", "/infome/hand/serializers.py"], "/infome/call/urls.py": ["/infome/call/endpoints.py"], "/infome/hand/urls.py": ["/infome/hand/endpoints.py"]}
59,435
fpwanderley/InfoMe-Backend
refs/heads/master
/infome/hand/serializers.py
# -*- coding: utf-8 -*- from rest_framework import serializers from infome.models import Hand class HandSerializer(serializers.ModelSerializer): call = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Hand fields = ('id', 'call')
{"/infome/admin.py": ["/infome/models.py"], "/test_db.py": ["/infome/models.py"], "/infome/hand/serializers.py": ["/infome/models.py"], "/infome/call/serializers.py": ["/infome/models.py"], "/infome/call/endpoints.py": ["/infome/models.py", "/infome/call/serializers.py"], "/infome/hand/endpoints.py": ["/infome/models.py", "/infome/hand/serializers.py"], "/infome/call/urls.py": ["/infome/call/endpoints.py"], "/infome/hand/urls.py": ["/infome/hand/endpoints.py"]}
59,436
fpwanderley/InfoMe-Backend
refs/heads/master
/infome/migrations/0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-11-09 00:26 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Call', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('description', models.TextField(default='', max_length=300)), ('status', models.IntegerField(choices=[(1, 'Aberta'), (2, 'Resolvida'), (3, 'Cancelada')], default=1)), ('created', models.DateTimeField(auto_now_add=True)), ], ), migrations.CreateModel( name='Hand', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('call', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='infome.Call')), ], ), migrations.CreateModel( name='Location', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('latitude', models.DecimalField(decimal_places=6, max_digits=9)), ('longitude', models.DecimalField(decimal_places=6, max_digits=9)), ], ), migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('description', models.CharField(max_length=50)), ], ), migrations.AddField( model_name='hand', name='location', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='infome.Location'), ), migrations.AddField( model_name='call', name='location', field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='infome.Location'), ), migrations.AddField( model_name='call', name='tags', field=models.ManyToManyField(to='infome.Tag'), ), ]
{"/infome/admin.py": ["/infome/models.py"], "/test_db.py": ["/infome/models.py"], "/infome/hand/serializers.py": ["/infome/models.py"], "/infome/call/serializers.py": ["/infome/models.py"], "/infome/call/endpoints.py": ["/infome/models.py", "/infome/call/serializers.py"], "/infome/hand/endpoints.py": ["/infome/models.py", "/infome/hand/serializers.py"], "/infome/call/urls.py": ["/infome/call/endpoints.py"], "/infome/hand/urls.py": ["/infome/hand/endpoints.py"]}