Ejemplo n.º 1
0
 def mmasgis(self, user):
     self.util = utility(
         [], 0, user, user.getActiveDb())  #non  potra' popolare' le tabelle
     self.selectionList = Lista(user, user.getActiveDb())
     # create and show the dialog
     #####settrace()
     curLayer = self.iface.mapCanvas().currentLayer()
     #elenco tutti gli elementi del layer corrente
     featids = range(curLayer.featureCount())
     #creo la lista della selezioni
     self.makeList()
     self.log("comuni selezionati mmasgis.py 297",
              self.selectionList.getList())
     self.log(
         "lista inviata a testDialog {0} ".format(
             self.selectionList.getList()), "test.py 212")
     self.dlg = testDialog(self.selectionList.getList(), user,
                           user.getActiveDb())
     # show the dialog
     self.dlg.show()
     #app=QtGui.QApplication(["show",""],True)
     #resetto la lista
     self.selectionList.resetList()
     #sys.exit(app.exec_())
     result = 1
     #dlg.traccheggio()
     # See if OK was pressed
     if result == 1:
         # do something useful (delete the line containing pass and
         # substitute with your code
         pass
Ejemplo n.º 2
0
 def test_count_n_elements_list_same_element(self):
     """Count numa lista com o mesmo elemento retorna o tamanho da lista"""
     x = randint(0, maxsize)
     lista = Lista()
     for i in range(0, self.MAX_VALUE):
         lista.prepend(x)
     self.assertEqual(lista.count(x), len(lista))
Ejemplo n.º 3
0
class Main:
    def __init__(self):
        self.__lista = Lista(4)
        self.__executando = True

    def inicia(self):
        while self.__executando:
            #os.system('cls' if os.name == 'nt' else 'clear')
            print("1 - Inserir elemento na frente")
            print("2 - Inserir elemento no final")
            print("3 - Inserir elemento na posição desejada")
            print("4 - Buscar elemento")
            print("5 - Inserir elemento na frente")
            print("6 - Inserir elemento na frente")

            opcao = int(input("Digite uma opção\n"))
            dado = int(input("Digite um valor\n"))

            if opcao == 1:
                self.__lista.inserirNaFrente(dado)
            elif opcao == 2:
                self.__lista.inserirNoFinal(dado)

            elif opcao == 0:
                self.__executando = False

            print(self.__lista.inicio.dado)
            print(self.__lista.fim.dado)
Ejemplo n.º 4
0
 def test_index_brute_force(self):
     """Testa o índice de todos os elementos da lista - a lista não pode ter repetidos"""
     lista = Lista()
     for i in range(0, 100):
         lista.append(i)
     for i in range(0, len(lista)):
         self.assertEqual(i, lista.index(lista[i]))
Ejemplo n.º 5
0
def eliminar_primos(numeros_enteros: Lista):
    i = 0
    while i < len(numeros_enteros):
        if es_primo(numeros_enteros[i]):
            numeros_enteros.suprime(i)
        else:
            i += 1
Ejemplo n.º 6
0
 def test_index_brute_force(self):
     """Testa o índice de todos os elementos da lista - a lista não pode ter repetidos"""
     lista = Lista()
     for i in range(0, 100):
         lista.append(i)
     for i in range(0, len(lista)):
         self.assertEqual(i, lista.index(lista[i]))
Ejemplo n.º 7
0
 def test_count_n_elements_list_same_element(self):
     """Count numa lista com o mesmo elemento retorna o tamanho da lista"""
     x = randint(0, maxsize)
     lista = Lista()
     for i in range(0, self.MAX_VALUE):
         lista.prepend(x)
     self.assertEqual(lista.count(x), len(lista))
Ejemplo n.º 8
0
class Usuario:
    def __init__(self, nombre_usuario):
        self.nombre = nombre_usuario
        self.commits = Lista()
    
    def nuevo_commit(self, timestamp, mensaje, nombre_archivo, agregadas, eliminadas):
        self.commits.append(Commit(timestamp, mensaje, nombre_archivo, agregadas, eliminadas))

    def __repr__(self):
        texto = '-'*80
        texto += '\n\n'
        texto += '{:25.20}'.format(self.nombre)
        texto += '{} commits'.format(len(self.commits))
        texto += '\n'
        texto += '-'*80
        return texto

    def cant_lineas_agregadas(self):
        suma = 0
        for commit in self.commits:
            suma += commit.agregadas
        
        return suma

    
    def cant_lineas_eliminadas(self):
        suma = 0
        for commit in self.commits:
            suma += commit.eliminadas
        
        return suma

    def cant_commits(self):
        return len(self.commits)
Ejemplo n.º 9
0
    def analyze(self, user):
        print "***selezioni su finestra " + str(self.ui_tree.getList())
        self.selectionList = Lista(user, user.getActiveDb())
        self.util = utility(
            [], 0, user, user.getActiveDb())  #non  potra' popolare' le tabelle
        # create and show the dialog
        curLayer = self.iface.mapCanvas().currentLayer()
        #elenco tutti gli elementi del layer corrente
        featids = range(curLayer.featureCount())
        #creo la lista della selezioni

        self.makeList()
        print("SSScomuni selezionati mmasgis.py 430",
              self.selectionList.getList())
        self.dlg = testDialog(self.selectionList.getList(), user,
                              user.getActiveDb())
        NomeDb = user.getActiveDb().getNameDb()
        self.dlg.setWindowTitle("Elenco Anagrafiche " + NomeDb.capitalize())
        # show the dialog
        self.dlg.show()
        #app=QtGui.QApplication(["show",""],True)
        #resetto la lista
        self.selectionList.resetList()
        #sys.exit(app.exec_())
        result = 1
        #dlg.traccheggio()
        # See if OK was pressed
        if result == 1:
            # do something useful (delete the line containing pass and
            # substitute with your code
            pass
Ejemplo n.º 10
0
    def recorrrer(self, nodo, lista=None, ciclo=None):
        if not lista:
            lista = Lista()
        if not ciclo:
            ciclo = Lista()

        aux = None
        for i in range(len(lista)):
            for arco in lista[i]:
                for j in range(i + 1, len(lista)):
                    if arco in lista[j]:
                        if not aux:
                            aux = Lista()
                        aux.append(arco)
        if aux:
            return aux

        if nodo in map(lambda x: x.padre, ciclo):
            for i in range(len(ciclo)):
                if ciclo[i].padre.id == nodo.id:
                    lista.append(ciclo[i:])
            ciclo = Lista()
        for arco in nodo.arcos:
                ciclo.append(arco)
                return self.recorrrer(arco.hijo, lista, ciclo)
        return None
Ejemplo n.º 11
0
def eliminar_vocales_lista(caracteres: Lista):
    VOCALES = 'AEIOUaeiou'
    i = 0
    while i < len(caracteres):
        if caracteres[i] in VOCALES:
            caracteres.suprime(i)
        else:
            i += 1
Ejemplo n.º 12
0
def get_canciones_por_artista(artista, canciones: Lista):
    artista = artista.upper()
    canciones_artista = Lista()

    for cancion in canciones:
        if artista == cancion.artista:
            canciones_artista.insert(cancion)

    return canciones_artista
Ejemplo n.º 13
0
 def test_extend_empty_list(self):
     """Extend numa lista vazia mantém o tamanho igual da segunda lista"""
     lista = Lista()
     self.assertEqual(len(lista), 0)
     lista.extend(Lista())
     self.assertEqual(len(lista), 0)
     size = len(self.lista)
     self.lista_vazia.extend(self.lista)
     self.assertEqual(len(self.lista_vazia), size)
Ejemplo n.º 14
0
 def test_extend_empty_list(self):
     """Extend numa lista vazia mantém o tamanho igual da segunda lista"""
     lista = Lista()
     self.assertEqual(len(lista), 0)
     lista.extend(Lista())
     self.assertEqual(len(lista), 0)
     size = len(self.lista)
     self.lista_vazia.extend(self.lista)
     self.assertEqual(len(self.lista_vazia), size)
Ejemplo n.º 15
0
 def test_remove_rand_position(self):
     """Remover um elemento aleatório dentro dos limites diminui o tamanho em 1"""
     lista = Lista()
     for i in range(0, self.MAX_VALUE):
         lista.prepend(i)
     size = len(lista)
     i = randint(0, size - 1)
     x =  lista[i]
     lista.remove(x)
     self.assertEqual(len(lista), size - 1)
Ejemplo n.º 16
0
def usuarios_commit_cero_lineas(usuarios):
    lista_cero_lineas = Lista()
    for usuario in usuarios:
        for commit in usuario.commits:
            if commit.agregadas == 0:
                if commit.eliminadas == 0:
                    lista_cero_lineas.append(usuario)
                    break
    
    return lista_cero_lineas
Ejemplo n.º 17
0
 def __init__(self, grafo):
     self.id_bummer = puerto_final()
     self.lista = Lista()
     self.recorridos = Lista()
     self.camino = ""
     inicial = grafo.buscar_nodo(0)
     self.cap = inicial.capacidad
     for arco in inicial.arcos:
         self.lista.append(Lista(arco, Lista(arco.padre)))
     self.recorrer()
Ejemplo n.º 18
0
def separar_por_calificacion(productos):
    clasificados = Lista()
    max_calificacion = 5
    for i in range(0, max_calificacion+1):
        clasificados.append(Lista())

    for producto in productos:
        clasificados[producto.calificacion].append(producto)

    return clasificados
Ejemplo n.º 19
0
 def ruta(self, nodo, lista=None):
     if not(lista):
         lista = Lista()
     for arco in nodo.arcos:
         for arco_2 in arco.hijo.arcos:
             if nodo == arco_2.hijo and arco.hijo not in lista:
                 lista.append(nodo)
                 aux = str(arco.hijo.id) + " "
                 return aux + self.ruta(arco.hijo, lista)
     return ""
Ejemplo n.º 20
0
 def test_extend_n_elements_list(self):
     """Extend numa lista com n elementos resulta num tamanho agregado das duas listas"""
     m = randint(200, 400)
     lista = Lista()
     for i in range(0, m):
         lista.append(randint(0, 100))
     size = len(lista)
     size_n = len(self.lista)
     self.assertNotEqual(len(self.lista), size + size_n)
     self.lista.extend(lista)
     self.assertEqual(len(self.lista), size + size_n)
Ejemplo n.º 21
0
 def test_extend_n_elements_list(self):
     """Extend numa lista com n elementos resulta num tamanho agregado das duas listas"""
     m = randint(200, 400)
     lista = Lista()
     for i in range(0, m):
         lista.append(randint(0, 100))
     size = len(lista)
     size_n = len(self.lista)
     self.assertNotEqual(len(self.lista), size + size_n)
     self.lista.extend(lista)
     self.assertEqual(len(self.lista), size + size_n)
Ejemplo n.º 22
0
def cambios_archivo_entre_fechas(archivo, fecha_inicial, fecha_final, usuarios):
    usuarios_cambios = Lista()
    for usuario in usuarios:
        for commit in usuario.commits:
            if commit.nombre_archivo == archivo:
                if  commit.timestamp >= fecha_inicial:
                    if  commit.timestamp <= fecha_final:
                        usuarios_cambios.append(usuario)
                        break

    return usuarios_cambios
Ejemplo n.º 23
0
 def get_new_snake(self):
     n_snake = Lista()
     snk_x = self.sw / 4
     snk_y = self.sh / 2
     n_snake.agregar(Lista(snk_y, snk_x - 2))
     n_snake.agregar(Lista(snk_y, snk_x - 1))
     n_snake.agregar(Lista(snk_y, snk_x))
     return n_snake
Ejemplo n.º 24
0
def usuario_mas_commits(usuarios):
    mayor = usuarios[0]
    for usuario in usuarios:
        if usuario.cant_commits() > mayor.cant_commits():
            mayor = usuario

    lista_mayores = Lista()
    for usuario in usuarios:
        if usuario.cant_commits() == mayor.cant_commits():
            lista_mayores.append(usuario)
        
    return lista_mayores
Ejemplo n.º 25
0
def concatenar_listas(lista1: Lista, lista2: Lista, omitir_repetidos=False):
    if omitir_repetidos:
        i = 0
        lista_aux = Lista()
        while i < len(lista2):
            if lista2[i] not in lista1:
                lista_aux.insert(lista2[i])
        concatenacion = lista1 + lista_aux
    else:
        concatenacion = lista1 + lista2

    return concatenacion
Ejemplo n.º 26
0
 def top1(canciones: Lista):
     """Devolver y eliminar el top1"""
     mas_escuchada = canciones[0]
     posicion = 0
     i = 1
     while i < len(canciones):
         if canciones[i].reproducciones > mas_escuchada.reproducciones:
             mas_escuchada = canciones[i]
             posicion = i
         i += 1
     canciones.suprime(posicion)
     return mas_escuchada
Ejemplo n.º 27
0
 def __init__(self, grafo):
     self.ruta_bummer = ""
     self.id_bummer = puerto_final()
     self.lista = Lista()
     self.recorridos = Lista()
     inicial = grafo.buscar_nodo(0)
     anterior = None
     self.recorridos.append(Lista(inicial, anterior))
     for arco in inicial.arcos:
         self.lista.append(Lista(arco.hijo, inicial))
     while not self.recorrer():
         pass
Ejemplo n.º 28
0
 def __init__(self):
     os.system("cls")
     self.__switcher = {
         1: self.opcion1,
         2: self.opcion2,
         3: self.opcion3,
         4: self.opcion4,
         5: self.opcion5,
         6: self.opcion6,
         7: self.opcion7,
         0: self.salir
     }
     self.__jsonF = ObjectEncoder()
     self.__lista = Lista()
Ejemplo n.º 29
0
def delete_occurences(lista, e):
    #print(lista.prim.e)
    if lista == None:
        lista = Lista()
        return lista
    elif lista.prim == None:
        return lista
    elif lista.prim.e != e:
        keep_element = lista.prim.e
        lista.prim = lista.prim.urm
        return push(delete_occurences(lista, e), keep_element)
    else:
        lista.prim = lista.prim.urm
        return delete_occurences(lista, e)
Ejemplo n.º 30
0
 def make_obstacle(self):
     true_new_obs = None
     while (true_new_obs is None):
         new_obs = Lista()
         o_x = random.randint(1, self.sw - 1)
         o_y = random.randint(1, self.sh - 1)
         new_obs.agregar(Lista(o_y, o_x))
         new_obs.agregar(Lista(o_y, o_x + 1))
         new_obs.agregar(Lista(o_y, o_x + 2))
         true_new_obs = new_obs if self.validate_obs(new_obs) else None
     self.obstacles.agregar(true_new_obs)
Ejemplo n.º 31
0
 def setUp(self):
     """Esse método é invocado antes de cada Teste. Prepara o ambiente"""
     self.MAX_VALUE = 10000
     self.lista_vazia = Lista()
     self.x = randint(0, maxsize)
     self.lista_um = Lista(self.x)
     self.n = randint(100, 500)
     self.lista = Lista(self.x)
     self.python_list = list()
     self.python_list.append(self.x)
     for i in range(0, self.n):
         element = randint(0, self.MAX_VALUE)
         self.python_list.append(element)
         self.lista.append(element)
     self.n += 1 #conta o elemento x
Ejemplo n.º 32
0
	def analyze(self,user):
		print "***selezioni su finestra "+str(self.ui_tree.getList()) 
		self.selectionList=Lista(user,user.getActiveDb())
		self.util=utility([],0,user,user.getActiveDb())#non  potra' popolare' le tabelle
		# create and show the dialog
		curLayer = self.iface.mapCanvas().currentLayer()
		#elenco tutti gli elementi del layer corrente
		featids = range(curLayer.featureCount())
		#creo la lista della selezioni

		self.makeList()
		print("SSScomuni selezionati mmasgis.py 430",self.selectionList.getList())
		self.dlg = testDialog(self.selectionList.getList(),user,user.getActiveDb())
		NomeDb=user.getActiveDb().getNameDb()
		self.dlg.setWindowTitle("Elenco Anagrafiche "+NomeDb.capitalize())
		# show the dialog
		self.dlg.show()
		#app=QtGui.QApplication(["show",""],True)
		#resetto la lista
		self.selectionList.resetList()
		#sys.exit(app.exec_())
		result=1
		#dlg.traccheggio()
		# See if OK was pressed
		if result == 1:
			# do something useful (delete the line containing pass and
			# substitute with your code
			pass
Ejemplo n.º 33
0
	def mmasgis(self,user):
		self.util=utility([],0,user,user.getActiveDb())#non  potra' popolare' le tabelle
		self.selectionList=Lista(user,user.getActiveDb())
		# create and show the dialog
		#####settrace()
		curLayer = self.iface.mapCanvas().currentLayer()
		#elenco tutti gli elementi del layer corrente
		featids = range(curLayer.featureCount())
		#creo la lista della selezioni
		self.makeList()
		self.log("comuni selezionati mmasgis.py 297",self.selectionList.getList())
		self.log("lista inviata a testDialog {0} ".format(self.selectionList.getList()),"test.py 212")
		self.dlg = testDialog(self.selectionList.getList(),user,user.getActiveDb())
		# show the dialog
		self.dlg.show()
		#app=QtGui.QApplication(["show",""],True)
		#resetto la lista
		self.selectionList.resetList()
		#sys.exit(app.exec_())
		result=1
		#dlg.traccheggio()
		# See if OK was pressed
		if result == 1:
			# do something useful (delete the line containing pass and
			# substitute with your code
			pass	
Ejemplo n.º 34
0
 def test_del_item_brute_force(self):
     """Testa del item para lista inteira"""
     for i in range(0, self.n):
         del self.lista[0]
     self.assertEqual(self.lista, Lista())
     with self.assertRaises(KeyError):
         del self.lista[0]
Ejemplo n.º 35
0
 def __init__(self, matricula, modelo, capacidad, cant_primera_clase):
     self.matricula = matricula
     self.modelo = modelo
     self.asientos = Lista()
     self.capacidad = capacidad
     self.capacidad_turista = capacidad - cant_primera_clase
     self.capacidad_primera_clase = cant_primera_clase
Ejemplo n.º 36
0
 def test_extend_one_element_list(self):
     """Extend numa lista com 1 elemento resulta num tamanho agregado das duas listas"""
     lista = Lista(42)
     size_um = len(self.lista_um)
     size = len(lista)
     self.lista_um.extend(lista)
     self.assertEqual(len(self.lista_um), size_um + size)
Ejemplo n.º 37
0
 def test_remove_item_brute_force(self):
     """Testa remove item para lista inteira"""
     for i in range(0, self.n):
         self.lista.remove(self.lista[0])
     self.assertEqual(self.lista, Lista())
     with self.assertRaises(KeyError):
         self.lista.remove(i)
Ejemplo n.º 38
0
 def __init__(self, tamanio=20):
     self.__tamanio_tabla = tamanio
     self.__tamanio_tabla = self.__siguiente_primo(self.__tamanio_tabla)
     self.__tabla = []
     self.__cantidad_items = 0
     for i in range(0, self.__tamanio_tabla): 
         self.__tabla.append(Lista())
Ejemplo n.º 39
0
 def insertar_vertice(self, dato, criterio='info', data=None):
     self.inicio.insertar(
         {
             'info': dato,
             'visitado': False,
             'aristas': Lista(),
             'data': data
         }, criterio)
Ejemplo n.º 40
0
 def __init__(self, id=0):
     self.id = id
     self.capacidad = get_capacidad()
     self.hijo_izquierdo = None
     self.hijo_derecho = None
     Grafo.arbol.agregar_nodo(self)
     Grafo.lista.append(self)
     self.arcos = Lista()
Ejemplo n.º 41
0
    def __init__(self):
        self.lists = {}

        with open("lists.json") as f:
            crude_lists = json.load(f)

        for list in crude_lists:
            self.lists[list["id"]] = Lista(**list)
Ejemplo n.º 42
0
def dividir_pares_impares(numeros_enteros: Lista):
    pares = Lista()
    impares = Lista()

    for numero in numeros_enteros:
        if numero % 2 == 0:
            pares.insert(numero)
        else:
            impares.insert(numero)
    return pares, impares
Ejemplo n.º 43
0
 def recorrer(self):
     aux = max(self.lista, key=lambda x: x[0].hijo.capacidad)
     arc_max, ant = aux[0], aux[1]
     self.eliminar(arc_max)
     if arc_max.hijo.capacidad < self.cap:
         self.cap = arc_max.hijo.capacidad
     for arco in arc_max.hijo.arcos:
         if arco not in self.recorridos:
             if arco.hijo.id == self.id_bummer:
                 ant.append(arco.hijo)
                 self.ruta(ant)
                 return
             self.recorridos.append(arco)
             aux = Lista()
             for i in ant:
                 aux.append(i)
             aux.append(arco.padre)
             self.lista.append(Lista(arco, aux))
     self.recorrer()
Ejemplo n.º 44
0
 def test_two_lists_with_same_elements_are_equals(self):
     """Duas listas distintas com os mesmos elementos são iguais"""
     lista1 = Lista()
     lista2 = Lista()
     self.assertEqual(lista1, lista2)
     for i in range(0, 30):  # operações caras :-) append e __eq__
         x = randint(0, 10000)
         self.assertEqual(lista1, lista2)
         lista1.append(x)
         self.assertNotEqual(lista1, lista2)
         lista2.append(x)
         self.assertEqual(lista1, lista2)
Ejemplo n.º 45
0
class Grafo:
    arbol = ArbolBinario()
    lista = Lista()

    def __init__(self, id=0):
        self.id = id
        self.capacidad = get_capacidad()
        self.hijo_izquierdo = None
        self.hijo_derecho = None
        Grafo.arbol.agregar_nodo(self)
        Grafo.lista.append(self)
        self.arcos = Lista()

    def agregar_arco(self, arco):
        if arco not in self.arcos:
            self.arcos.append(arco)

    def agregar_nodo(self):
        id_arco = randint(0, posibles_conexiones() - 1)
        hacer_conexion(id_arco)
        if preguntar_puerto_actual()[1]:
            return self.buscar_nodo(0)
        id_hijo = preguntar_puerto_actual()[0]
        hijo = self.buscar_nodo(id_hijo)
        if not hijo:
            hijo = Grafo(id_hijo)
        arco = Arco(id_arco, self, hijo)
        self.agregar_arco(arco)
        return hijo

    def buscar_nodo(self, objetivo):
        return Grafo.arbol.buscar(objetivo)

    def __str__(self):
        linea = ""
        for i in range(len(Grafo.lista)):
            nodo = self.buscar_nodo(i)
            linea += "PUERTO {}".format(nodo.id) + "\n"
            for arco in nodo.arcos:
                linea += "CONEXION {} {}".format(nodo.id, arco.hijo.id)
                linea += "\n"
        return linea
Ejemplo n.º 46
0
 def test_prepend_turns_empty_list_into_one_element_list(self):
     """Prepend numa lista vazia transforma numa lista com 1 elemento, com Cabeça"""
     lista_vazia = Lista()
     self.assertFalse(lista_vazia)
     self.assertTrue(lista_vazia.is_empty())
     self.assertEqual(len(lista_vazia), 0)
     self.assertEqual(lista_vazia.head(), None)
     lista_vazia.prepend(self.x)
     self.assertTrue(lista_vazia)
     self.assertFalse(lista_vazia.is_empty())
     self.assertEqual(len(lista_vazia), 1)
     self.assertEqual(lista_vazia.head(), self.x)
Ejemplo n.º 47
0
class Flujo():

    def __init__(self, grafo):
        self.id_bummer = puerto_final()
        self.lista = Lista()
        self.recorridos = Lista()
        self.camino = ""
        inicial = grafo.buscar_nodo(0)
        self.cap = inicial.capacidad
        for arco in inicial.arcos:
            self.lista.append(Lista(arco, Lista(arco.padre)))
        self.recorrer()

    def recorrer(self):
        aux = max(self.lista, key=lambda x: x[0].hijo.capacidad)
        arc_max, ant = aux[0], aux[1]
        self.eliminar(arc_max)
        if arc_max.hijo.capacidad < self.cap:
            self.cap = arc_max.hijo.capacidad
        for arco in arc_max.hijo.arcos:
            if arco not in self.recorridos:
                if arco.hijo.id == self.id_bummer:
                    ant.append(arco.hijo)
                    self.ruta(ant)
                    return
                self.recorridos.append(arco)
                aux = Lista()
                for i in ant:
                    aux.append(i)
                aux.append(arco.padre)
                self.lista.append(Lista(arco, aux))
        self.recorrer()

    def eliminar(self, arco):
        for i in range(len(self.lista)):
            if self.lista[i][0] == arco:
                self.lista.pop(i)
                break

    def ruta(self, ant):
        self.camino += "CAP {}\n".format(self.cap)
        for i in range(len(ant) - 1):
            self.camino += "{} {}\n".format(ant[i].id, ant[i + 1].id)

    def __str__(self):
        return self.camino
Ejemplo n.º 48
0
 def test_two_lists_with_same_elements_are_equals(self):
     """Duas listas distintas com os mesmos elementos são iguais"""
     lista1 = Lista()
     lista2 = Lista()
     self.assertEqual(lista1, lista2)
     for i in range(0, 30): # operações caras :-) append e __eq__
         x = randint(0, 10000)
         self.assertEqual(lista1, lista2)
         lista1.append(x)
         self.assertNotEqual(lista1, lista2)
         lista2.append(x)
         self.assertEqual(lista1, lista2)
Ejemplo n.º 49
0
class BFS:

    def __init__(self, grafo):
        self.ruta_bummer = ""
        self.id_bummer = puerto_final()
        self.lista = Lista()
        self.recorridos = Lista()
        inicial = grafo.buscar_nodo(0)
        anterior = None
        self.recorridos.append(Lista(inicial, anterior))
        for arco in inicial.arcos:
            self.lista.append(Lista(arco.hijo, inicial))
        while not self.recorrer():
            pass

    def recorrer(self):
        lista = self.lista.popleft()
        nodo, padre = lista[0], lista[1]
        if nodo.id == self.id_bummer:
            self.recorridos.append(Lista(nodo, padre))
            self.ruta_bummer = self.ruta(nodo)[1:]
            return True
        if nodo not in self.recorridos[0]:
            self.recorridos.append(Lista(nodo, padre))
            for arco in nodo.arcos:
                self.lista.append(Lista(arco.hijo, nodo))
        return False

    def ruta(self, nodo):
        for otro, padre in self.recorridos:
            if nodo == otro and padre:
                texto = "CONEXION {} {}".format(padre.id, nodo.id)
                return self.ruta(padre) + "\n" + texto
        return ""

    def __str__(self):
        return self.ruta_bummer
Ejemplo n.º 50
0
 def on_btnConfiguracion_clicked(self):
     lista = Lista(self)
     lista.show()
Ejemplo n.º 51
0
class TestLista(unittest.TestCase):

    def setUp(self):
        """Esse método é invocado antes de cada Teste. Prepara o ambiente"""
        self.MAX_VALUE = 10000
        self.lista_vazia = Lista()
        self.x = randint(0, maxsize)
        self.lista_um = Lista(self.x)
        self.n = randint(100, 500)
        self.lista = Lista(self.x)
        self.python_list = list()
        self.python_list.append(self.x)
        for i in range(0, self.n):
            element = randint(0, self.MAX_VALUE)
            self.python_list.append(element)
            self.lista.append(element)
        self.n += 1 #conta o elemento x


    def test_construtor(self):
        """O construtor deve receber um valor ou None"""
        self.assertIs(type(self.lista_um), Lista)
        self.assertIs(type(self.lista_vazia), Lista)


    def test_bool_false(self):
        """Uma Lista Vazia retorna False"""
        self.assertFalse(bool(self.lista_vazia))
        self.assertFalse(self.lista_vazia)
        self.assertFalse(self.lista_vazia.__bool__())

    def test_bool_true(self):
        """Uma Lista Vazia retorna True"""
        self.assertTrue(bool(self.lista_um))
        self.assertTrue(self.lista_um)
        self.assertTrue(self.lista_um.__bool__())


    def test_empty_list(self):
        """Uma Lista Vazia retorna True para is_empty"""
        self.assertTrue(self.lista_vazia.is_empty())

    def test_not_empty_list(self):
        """Uma Lista Não Vazia retorna False para is_empty"""
        self.assertFalse(self.lista_um.is_empty())

    
    def test_len_empty_list(self):
        """Uma Lista Vazia tem tamanho 0"""
        self.assertEqual(len(self.lista_vazia), 0)

    def test_len_one_element_list(self):
        """Uma Lista com 1 elemento tem tamanho 1"""
        self.assertEqual(len(self.lista_um), 1)

    #Este Teste só funciona quando append tiver sido implementado
    def test_len_arbitrary_size_list(self):
        """Uma Lista com n elementos tem tamanho n"""
        #self.assertEqual(len(self.lista), self.n)

    def test_list_head_empty_list(self):
        """Uma Lista vazia tem None na cabeça"""
        self.assertIsNone(self.lista_vazia.head())

    def test_list_head_one_element_list(self):
        """Uma Lista com 1 elemento tem o primeiro elemento na cabeça"""
        self.assertEqual(self.lista_um.head(), self.x)

    def test_list_head_n_elements_list(self):
        """Uma Lista com n elementos tem o primeiro elemento na cabeça"""
        self.assertEqual(self.lista.head(), self.x)

    def test_list_tail_empty_list(self):
        """Uma Lista vazia tem como Cauda uma Lista Vazia, que é False e tem len zero"""
        self.assertFalse(self.lista_vazia.tail())
        self.assertTrue(self.lista_vazia.tail().is_empty())
        self.assertEqual(len(self.lista_vazia.tail()), 0)

    def test_list_tail_one_element_list(self):
        """Uma Lista com 1 elemento tem como Cauda uma Lista Vazia, que é False e tem len 0"""
        self.assertFalse(self.lista_um.tail())
        self.assertTrue(self.lista_um.tail().is_empty())
        self.assertEqual(len(self.lista_um.tail()), 0)

    def test_list_tail_n_elements_list(self):
        """Uma Lista com n elementos tem como Cauda uma Lista com Tamanho n - 1, True e Não Vazia"""
        self.assertTrue(self.lista.tail())
        self.assertFalse(self.lista.tail().is_empty())
        self.assertEqual(len(self.lista.tail()), len(self.lista) - 1)

    def test_append_turns_empty_list_into_one_element_list(self):
        """Append numa lista vazia transforma numa lista com 1 elemento, com Cabeça"""
        lista_vazia = Lista()
        self.assertFalse(lista_vazia)
        self.assertTrue(lista_vazia.is_empty())
        self.assertEqual(len(lista_vazia), 0)
        self.assertEqual(lista_vazia.head(), None)
        lista_vazia.append(self.x)
        self.assertTrue(lista_vazia)
        self.assertFalse(lista_vazia.is_empty())
        self.assertEqual(len(lista_vazia), 1)
        self.assertEqual(lista_vazia.head(), self.x)

    def test_append_n_elements_list_makes_appended_last_element(self):
        """Append numa lista de n elementos torna o elemento inserido o último"""
        appended = randint(0, 10000)
        self.lista.append(appended)
        cauda = self.lista.tail()
        #iterates over list until it has one element
        while cauda:
          anterior = cauda
          cauda = cauda.tail()
        self.assertEqual(anterior.head(), appended)

    def test_append_n_elements_list_increases_length_by_one(self):
        """Append numa lista de n elementos aumenta seu tamanho em 1"""
        appended = randint(0, 10000)
        size = len(self.lista)
        self.lista.append(appended)
        new_size = len(self.lista)
        self.assertEqual(size + 1, new_size)
        self.assertEqual(self.n + 1, new_size)


    def test_prepend_turns_empty_list_into_one_element_list(self):
        """Prepend numa lista vazia transforma numa lista com 1 elemento, com Cabeça"""
        lista_vazia = Lista()
        self.assertFalse(lista_vazia)
        self.assertTrue(lista_vazia.is_empty())
        self.assertEqual(len(lista_vazia), 0)
        self.assertEqual(lista_vazia.head(), None)
        lista_vazia.prepend(self.x)
        self.assertTrue(lista_vazia)
        self.assertFalse(lista_vazia.is_empty())
        self.assertEqual(len(lista_vazia), 1)
        self.assertEqual(lista_vazia.head(), self.x)

    def test_prepend_n_elements_list_makes_prepended_first_element(self):
        """Prepend numa lista de n elementos torna o elemento inserido o primeiro"""
        prepended = randint(0, 10000)
        old_head = self.lista.head()
        self.lista.prepend(prepended)
        self.assertEqual(self.lista.head(), prepended)
        self.assertNotEqual(self.lista.head(), old_head)
        self.assertEqual(self.lista.tail().head(), old_head)

    def test_prepend_n_elements_list_increases_length_by_one(self):
        """Prepend numa lista de n elementos aumenta seu tamanho em 1"""
        prepended = randint(0, 10000)
        size = len(self.lista)
        self.lista.prepend(prepended)
        new_size = len(self.lista)
        self.assertEqual(size + 1, new_size)
        self.assertEqual(self.n + 1, new_size)


    def test_two_empty_lists_are_equals(self):
        """Duas listas vazias são iguais"""
        self.assertEqual(self.lista_vazia, Lista())
        self.assertEqual(Lista(),Lista())

    def test_two_lists_with_same_elements_are_equals(self):
        """Duas listas distintas com os mesmos elementos são iguais"""
        lista1 = Lista()
        lista2 = Lista()
        self.assertEqual(lista1, lista2)
        for i in range(0, 30): # operações caras :-) append e __eq__
            x = randint(0, 10000)
            self.assertEqual(lista1, lista2)
            lista1.append(x)
            self.assertNotEqual(lista1, lista2)
            lista2.append(x)
            self.assertEqual(lista1, lista2)

    def test_empty_list_n_elements_list_not_equals(self):
        """Uma lista vazia não é igual à uma lista com n elementos"""
        self.assertNotEqual(self.lista_vazia, self.lista)
        self.assertFalse(self.lista_vazia == self.lista)
        self.assertFalse(self.lista == self.lista_vazia)

    def test_str_empty_list(self):
        """Uma lista vazia deve ser representada pela string []"""
        self.assertEqual(str(self.lista_vazia), "[]")

    def test_str_one_element_list(self):
        """Uma lista com somente um elemento x deve ser representada por [x]"""
        self.assertEqual(str(self.lista_um), "[" + str(self.x) + "]")

    def test_str_n_elements_list(self):
        """Uma lista com n elementos imprime como uma lista python"""
        self.assertEqual(str(self.lista), str(self.python_list))

    def test_extend_empty_list(self):
        """Extend numa lista vazia mantém o tamanho igual da segunda lista"""
        lista = Lista()
        self.assertEqual(len(lista), 0)
        lista.extend(Lista())
        self.assertEqual(len(lista), 0)
        size = len(self.lista)
        self.lista_vazia.extend(self.lista)
        self.assertEqual(len(self.lista_vazia), size)

    def test_extend_one_element_list(self):
        """Extend numa lista com 1 elemento resulta num tamanho agregado das duas listas"""
        lista = Lista(42)
        size_um = len(self.lista_um)
        size = len(lista)
        self.lista_um.extend(lista)
        self.assertEqual(len(self.lista_um), size_um + size)

    def test_extend_n_elements_list(self):
        """Extend numa lista com n elementos resulta num tamanho agregado das duas listas"""
        m = randint(200, 400)
        lista = Lista()
        for i in range(0, m):
            lista.append(randint(0, 100))
        size = len(lista)
        size_n = len(self.lista)
        self.assertNotEqual(len(self.lista), size + size_n)
        self.lista.extend(lista)
        self.assertEqual(len(self.lista), size + size_n)

    def test_clear_remove_all_elements(self):
        self.assertEqual(len(self.lista_vazia), 0)
        self.assertNotEqual(len(self.lista_um), 0)
        self.assertNotEqual(len(self.lista), 0)

        self.lista_vazia.clear()
        self.lista_um.clear()
        self.lista.clear()

        self.assertEqual(len(self.lista_vazia), 0)
        self.assertEqual(len(self.lista_um), 0)
        self.assertEqual(len(self.lista), 0)
          
        self.assertEqual(self.lista_um.head(), None)
        self.assertEqual(self.lista.head(), None)
        self.assertEqual(self.lista.tail(), Lista())

    
    def test_contains(self):
        """Verifica se um elemento está na lista"""
        for i in self.python_list:
            not_in_list = (i + self.MAX_VALUE) * 2
            self.assertTrue(i in self.lista)
            self.assertTrue(not_in_list not in self.lista)
            self.assertTrue(self.lista.__contains__(i))
            self.assertFalse(self.lista.__contains__(not_in_list))


    def test_get_item_empty_list(self):
        """Qualquer chave numa lista vazia retorna um erro"""
        with self.assertRaises(KeyError):
            self.lista_vazia[0]
        

    def test_get_item_out_of_bounds(self):
        """Qualquer chave fora dos limites retorna um erro"""
        with self.assertRaises(KeyError):
            self.lista_um[1]
        with self.assertRaises(KeyError):
            size = len(self.lista)
            self.lista[size]
        
    def test_get_item_bounds(self):
        """A primeira chave retorna a cabeça, len - 1 retorna a última"""
        self.assertEqual(self.lista_um.head(), self.lista_um[0])
        self.assertEqual(self.lista_um.head(), self.lista_um[len(self.lista_um) - 1])
        self.assertEqual(self.lista.head(), self.lista[0])
        ultimo_lista = self.python_list[-1]
        self.assertEqual(ultimo_lista, self.lista[len(self.lista) - 1])


    def test_get_rand_position(self):
        """Uma chave aleatória dentro dos limites retorna corretamente"""
        i = randint(0, len(self.lista))
        self.assertEqual(self.lista[i], self.python_list[i])

    def test_get_item_brute_force(self):
        """Testa get item para todos os indices"""
        for i in range(0, self.n):
            self.assertEqual(self.lista[i], self.python_list[i])


    def test_del_item_empty_list(self):
        """Qualquer chave deletada numa lista vazia retorna um erro"""
        with self.assertRaises(KeyError):
            del self.lista_vazia[0]
        

    def test_del_item_out_of_bounds(self):
        """Qualquer chave deletada fora dos limites retorna um erro"""
        with self.assertRaises(KeyError):
            del self.lista_um[1]
        with self.assertRaises(KeyError):
            size = len(self.lista)
            del self.lista[size]
        
    def test_del_item_bounds(self):
        """Deletar a primeira chave faz a segunda ser a primeira. A última, a penúltima ser a última"""
        self.assertEqual(self.lista_um.head(), self.lista_um[0])
        del self.lista_um[0]
        self.assertEqual(self.lista_um.head(), None)
        self.assertEqual(self.lista_um, Lista())
        
        del self.lista[0]
        self.assertEqual(self.lista.head(), self.python_list[1])
      
        del self.lista[len(self.lista) - 1]
        ultimo_lista = self.python_list[-2]
        self.assertEqual(ultimo_lista, self.lista[len(self.lista) - 1])


    def test_del_rand_position(self):
        """Deletar uma chave aleatória dentro dos limites retorna corretamente"""
        i = randint(0, len(self.lista) - 1)
        del self.lista[i]
        self.assertEqual(self.lista[i], self.python_list[i + 1])

    def test_del_item_brute_force(self):
        """Testa del item para lista inteira"""
        for i in range(0, self.n):
            del self.lista[0]
        self.assertEqual(self.lista, Lista())
        with self.assertRaises(KeyError):
            del self.lista[0]
 

    def test_insert_empty_list(self):
        """Inserção numa lista vazia gera erro. Só pode ser usado append ou prepend nelas"""
        with self.assertRaises(KeyError):
            self.lista_vazia.insert(0, self.x)

    def test_insert_first_position(self):
        """Inserção funciona na primeira posição, desde que a lista não seja vazia"""
        y = randint(0, self.MAX_VALUE)
        old_head = self.lista_um.head()
        self.lista_um.insert(0, y)
        self.assertEqual(self.lista_um.head(), y)
        self.assertEqual(self.lista_um.tail().head(), old_head)

    def test_insert_random_position(self):
        """Inserção numa posição aleatória entre 1 e len(lista) -1"""
        i = randint(1, len(self.lista) - 1)
        y = randint(0, self.MAX_VALUE)
        self.lista.insert(i, y)
        self.assertEqual(self.lista[i], y)
        self.assertEqual(self.lista[i - 1], self.python_list[i - 1])
        self.assertEqual(self.lista[i + 1], self.python_list[i])


    def test_insert_makes_list(self):
        """Inserção pode ser usada para construir uma lista igual a já existente"""
        lista = Lista(self.python_list[-1])
        for y in reversed(self.python_list[:-1]):
            lista.insert(0, y)
        self.assertEqual(lista, self.lista)

    def test_index_empty_list(self):
        """Index de lista vazia retorna um erro"""
        with self.assertRaises(ValueError):
            self.lista_vazia.index(self.x)

    def test_index_one_element_list_returns_0(self):
        """Index numa lista com um elemento retorna 0"""
        self.assertEqual(self.lista_um.index(self.x), 0)

    def test_index_n_elements_list(self):
        """Index de uma lista com n elementos retorna o índice correto"""
        random_index = randint(0, len(self.lista))
        random_element = self.python_list[random_index]
        self.assertEqual(self.lista.index(random_element), random_index)

    def test_index_brute_force(self):
        """Testa o índice de todos os elementos da lista - a lista não pode ter repetidos"""
        lista = Lista()
        for i in range(0, 100):
            lista.append(i)
        for i in range(0, len(lista)):
            self.assertEqual(i, lista.index(lista[i]))

    def test_count_empty_list(self):
        """Count numa lista vazia sempre retorna zero"""
        x = randint(0, maxsize)
        self.assertEqual(self.lista_vazia.count(x), 0)

    def test_count_one_element_list(self):
        """Count numa lista com 1 elemento pode retornar zero ou 1, depende se existe"""
        head = self.lista_um.head()
        self.assertEqual(self.lista_um.count(head), 1)
        self.assertEqual(self.lista_um.count(head - 1), 0)

    def test_count_n_elements_list_same_element(self):
        """Count numa lista com o mesmo elemento retorna o tamanho da lista"""
        x = randint(0, maxsize)
        lista = Lista()
        for i in range(0, self.MAX_VALUE):
            lista.prepend(x)
        self.assertEqual(lista.count(x), len(lista))

    def test_count_same_behavior_python_count(self):
        """Count retorna o mesmo valor que o count do python"""
        for i in range(0, len(self.lista)):
            self.assertEqual(self.lista.count(self.lista[i]), \
              self.python_list.count(self.python_list[i]))

    def test_remove_item_empty_list(self):
        """Qualquer chave removida numa lista vazia retorna um erro"""
        with self.assertRaises(KeyError):
            x = randint(0, self.MAX_VALUE)
            self.lista_vazia.remove(x)
        

    def test_remove_item_one_element_list(self):
        """Remover a cabeça de uma lista de um elemento a torna numa lista vazia"""
        head = self.lista_um.head()
        self.lista_um.remove(head)
        self.assertEqual(self.lista_um, Lista())      



    def test_remove_rand_position(self):
        """Remover um elemento aleatório dentro dos limites diminui o tamanho em 1"""
        lista = Lista()
        for i in range(0, self.MAX_VALUE):
            lista.prepend(i)
        size = len(lista)
        i = randint(0, size - 1)
        x =  lista[i]
        lista.remove(x)
        self.assertEqual(len(lista), size - 1)

    def test_remove_item_brute_force(self):
        """Testa remove item para lista inteira"""
        for i in range(0, self.n):
            self.lista.remove(self.lista[0])
        self.assertEqual(self.lista, Lista())
        with self.assertRaises(KeyError):
            self.lista.remove(i)

    def test_reversed_empty_list(self):
        """O reverso de uma lista vazia é uma lista vazia"""
        self.assertEqual(reversed(self.lista_vazia), self.lista_vazia)
      
    def test_reversed_one_element_list(self):
        """O reverso de uma lista com 1 elemento é ela mesma"""
        self.assertEqual(reversed(self.lista_um), self.lista_um)

    def test_reversed_n_elements_list(self):
        """O reverso de uma lista com n elementos, o último é o primeiro e vice-versa"""
        self.assertEqual(reversed(self.lista).head(), self.python_list[-1])
        nova_lista = reversed(self.lista)
        ultimo = nova_lista[len(nova_lista) - 1]
        self.assertEqual(ultimo, self.lista.head())


    def test_reversed_str_n_elements_list(self):
        """Testa a impressão de uma lista reversa de n elementos"""
        self.assertEqual(str(reversed(self.lista)), str(list(reversed(self.python_list))))
Ejemplo n.º 52
0
 def test_insert_makes_list(self):
     """Inserção pode ser usada para construir uma lista igual a já existente"""
     lista = Lista(self.python_list[-1])
     for y in reversed(self.python_list[:-1]):
         lista.insert(0, y)
     self.assertEqual(lista, self.lista)
Ejemplo n.º 53
0
class mmasgis:

	def converter(self,attr,key):
		"""
		converte l' attributo ricevuto
		da provincia a sigla se key e' pro
		da regione a lista di provincie se
		key e' regione
		ritorna lo stesso attributo se key=com
		"""
		result=attr
		if self.cons.attributes2convert[key]:
			#e' una provicia==> converto
			result= self.util.translateProvincia(attr)
		if  self.cons.attributes2expand[key]:
			##self.log("expanding {0}".format(attr),"test.py 50")
			print "mmasgis.py 69 regione da esplodere",str(attr)
			result =self.cons.regione[str(attr)]
			#converto le provincie inserite nella loro sigla
			pr=[self.util.translateProvincia(i) for i in result]
			##self.log("province nella regione {0}".format(attr),"test.py 55")
			##self.log("sigle province test.py 55",pr)
			##self.log("{0} espansa".format(attr),"{0} test.py 52".format(result))
		return pr
	
	def getTime(self):
		year=time.localtime()[0]
		month=time.localtime()[1]
		day=time.localtime()[2]
		hour=time.localtime()[3]
		min=time.localtime()[4]
		sec=time.localtime()[5]
		return"{0}:{1}:{2}:{3}/{4}/{5}".format(hour,min,sec,day,month,year)

	def undo(self):
		self.ui.close()
		infoString=" login non effettuato: sarà possibile usare QGIS, ma  MMASGIS 5.0 non sarà fruibile"
		d=QtGui.QMainWindow()
		QtGui.QMessageBox.warning(d,"LOGIN ANNULLATO!", infoString)

	def logged(self,user):
			self.user=user
			self.user.setLogged(True)
			#print "utente loggato in mmasgis.logged",user
			infoString="benvenuto {0} database di lavoro: {1}".format(self.user.getName(),self.user.getActiveDb().getRDBMS())
			print "Logged",infoString
			d=QtGui.QMainWindow()
			QtGui.QMessageBox.information(d,"logged user", infoString)  
			self.ds=self.ui.getDataSource()
			self.ui.close()
			
	def showTree(self):
		self.albero=Albero(self.iface,self.user)
		self.tree=Tree(self.user)
		self.albero.run()
		
	def userManager(self):
		profilo=self.user.getProfile()
		print "profilo",profilo
		####settrace()
		if profilo.isPermitted(4):
			print "funzione ammessa"
			self.gestioneUtenti_ui=MainWindowUserManager(self.user)
			self.gestioneUtenti_ui.show()
		else:
			infoString="non godi dei diritti sufficienti per questa funzione, contatta il tuo amministratore!"
			d=QtGui.QMainWindow()
			QtGui.QMessageBox.warning(d,"NON AUTORIZZATO!!", infoString)
			

	def __init__(self, iface):
		self.dbSwitcher_ui=None
		self.censimentoSelected=False
		self.ui =LoginRefactored(True)
		self.ds=None
		self.gestioneUtenti_ui=None
		self.user=None
		QtCore.QObject.connect(self.ui,QtCore.SIGNAL("undo"),self.undo)
		QtCore.QObject.connect(self.ui,QtCore.SIGNAL("logged"),self.logged)
		self.ui.show()#comincia il login
		# Save reference to the QGIS interface
		#logging.basicConfig(filename='/home/giuseppe/.qgis/log/mmasgis.log',level=logging.DEBUG)
		self.nLayers=0
		self.iface = iface
		self.albero=Albero(iface,None)
		self.tree=Tree(None)
		self.ui_tree=MainWindowAlbero(iface,self.tree)
		self.textArea=None
		self.dlg=None
		self.selectionList=None
		self.cons=cons()
		self.util=None#non  popolera' le tabelle
		self.login=None
		self.cons=cons()
		
	def log(self, title, txt):
		logging.debug(self.getTime()+" "+title+" "+str(txt))
		
	def test(self):
			infoString="Nessuna anagrafica selezionata"
			d=QtGui.QMainWindow()
			QtGui.QMessageBox.information(d,"Attenzione", infoString)	

	def initGui(self):
		#logging.basicConfig(filename='/home/giuseppe/.qgis/log/mmasgis.log',level=logging.DEBUG)
		# Create action that will start plugin configuration
		self.action = QAction(QIcon(":/plugins/mmasgis/icon.png"), \
			"mmasgis", self.iface.mainWindow())
		# connect the action to the run method
		QObject.connect(self.action, SIGNAL("triggered()"), self.run)


		self.actionTree=QAction(QIcon(":/plugins/mmasgis/resources/tree.png"),"albero delle utb",self.iface.mainWindow())
		self.actionTree.setWhatsThis("fornisce una visualizzazione gerarchica delle utb")
		self.actionManager = QAction(QIcon(":/plugins/mmasgis/iconx.png"), "gestione utenti mmasgis", self.iface.mainWindow())
		self.actionManager.setWhatsThis("gestisce gli utenti mmasgis")
		self.iface.registerMainWindowAction(self.actionManager, "F8")   # The function should also be triggered by the F8 key
		self.iface.registerMainWindowAction(self.actionTree, "F7")   # The function should also be triggered by the F7 key
		QObject.connect(self.actionManager, SIGNAL("triggered()"), self.userManager)
		QObject.connect(self.actionTree, SIGNAL("triggered()"), self.showTree)
		
		
		# Add toolbar button and menu item
		self.iface.addToolBarIcon(self.action)
		self.iface.addPluginToMenu("&mmasgis", self.action)
		self.iface.addPluginToMenu("&mmasgis", self.actionManager)
		self.iface.addPluginToMenu("&mmasgis", self.actionTree)
		self.toolBar = self.iface.addToolBar("MMASGIS")
		self.toolBar.addAction(self.actionManager)
		self.toolBar.addAction(self.actionTree)
		
	def printComune(self,feat):
		attr=feat.attributeMap()
		####settrace()
		
		s="comune: {0}, id: {1}, identificativo comune: {3}, cod: {2}".format(attr[3],feat.id(),attr[0].toString(),attr[1].toString())
		return s
		
	def getSelections(self,curLayer,key):
		####settrace()
		
		#recupero gli id degli items selezionati
		featids=curLayer.selectedFeaturesIds()
		###self.log( "chiave in getselections={0}".format(key),"test.py 102")
		  #featids = range(curLayer.featureCount())		 
		fProvider = curLayer.dataProvider()
		feat = QgsFeature()
		allAttrs = fProvider.attributeIndexes()
		fProvider.select(allAttrs)
		
		##self.log("numero campi: {0}".format(fProvider.fieldCount()),"test.py 112")
#		##self.log()
#recupero gli attributi della feature selezionata
		
		attrmap=QgsFeature().attributeMap()
		####settrace()
		####settrace()
		
		c={}
		c['pro']="provincia"
		c['com']='comune'
		c['cap']='cap'
		c['reg']='regione'
		adder={}
		adder['pro']=self.tree.addProvincia
		adder['com']=self.tree.addComune
		adder['cap']=self.tree.addCap
		adder['reg']=self.tree.addRegione
		fields={}
		fields['pro']={'header':lambda x:str(x[2][1]),'father':lambda x:x[0][1].toInt()[0],'Id':lambda x:x[1][1].toInt()[0]}
		fields['com']={'header':lambda x: unicode(x[3][1]),'father':lambda x : x[1][1].toInt()[0],'Id':lambda x: unicode( x[3][1])}# la lambda function per lo id dovrebbe essere x[2][1].toInt()[0] ma il father_id del cap e' il nome del comune, quindi lo header del comune e' pure il suo id
		fields['cap']={'header':lambda x: unicode(x[1][1]),'father':lambda x: unicode(x[6][1]),'Id':lambda x: x[0][1].toInt()[0]}
		fields['reg']={'header':lambda x:str(x[1][1]),'father':lambda x:0,'Id':lambda x:x[0][1].toInt()[0]}
		while fProvider.nextFeature(feat):
			#esploro gli attributi di feat, non sono uguali tra i vari layer
			d=[(key1,feat.attributeMap()[key1].toString()) for key1 in feat.attributeMap().iterkeys()]
			cat=str(feat.typeName())[0:3].lower()
			header=fields[cat]['header'](d)
			father=fields[cat]['father'](d)
			Id=fields[cat]['Id'](d)
			nodo=Nodo(header,Id,c[cat],father,feat.id())#(header,Id,cathegory,father,featureId)
			
			#print "sto aggiungendo ",nodo
			adder[cat](nodo)
			if key=="com":
				pass###self.log("campi del comune: {0}".format(self.printComune(feat)),"mmasgis.py 131")
		myFields = fProvider.fields()
		allFieldsNames= [f.name() for f in myFields.values()]
		myFieldsNames=[]
		for f in myFields.values():
			print 'for', f.name()
			##self.log("myFields.type {0}".format(f.typeName()),"test.py 127")
			if f.typeName() == "Real":
				##self.log("casting real {0}".format(f),"test.py 129")				
				myFieldsNames.append(f.name())
			if f.typeName() == "String":
				##self.log("casting string ok {0}".format(f),"test.py 116")
				myFieldsNames.append(f.name())
		if len(myFieldsNames) == 0:
		  # QMessageBox.information(self.iface.mainWindow(),"Warning","No string field names. Exiting")
		   return
		elif len(myFieldsNames) == 1:
			#se c'e' un solo nome seleziono il primo
			
			rfield = myFieldsNames[0]
		   ##self.log("attrfield test.py 127",attrfield)
		else:
		  attrfield=myFieldsNames[0]

		  attrindex = allFieldsNames.index(attrfield)
		  ##self.log("attrindex test.py 109", attrindex)
		  ##self.log("featids test.py 110",featids)
		  #return attrindex
	   # adumpfile = QFileDialog.getSaveFileName(None, "save file dialog", attrfield +'.txt', "Text (*.txt)")
#		selectionList =[]
		
		for fid in featids:
			features={}
			result={}
			features[fid]=QgsFeature()
		   ###self.log("fid  test.py 119",fid)
		   ###self.log("features[fid] test.py 120",features[fid])
			curLayer.featureAtId(fid,features[fid])
		   ####settrace()
		   #prendo la tabella degli attributi
			attrmap=features[fid].attributeMap()
#		   ##self.log("attrmap test.py 124",attrmap)
		   ##self.log("comune {0}, indice {1}, provincia {2}".format(len(attrmap.values()),attrmap.values(),attrmap.values()),"mmasgis.py 177")

			attr=attrmap.values()[self.cons.attributes[key]]#in ogni layer la colonna degli attributi utile cambia
			attr=attr.toString()
			getId={}
			getId['pro']=lambda x: int(str(x[1].toString()))
			getId['reg']=lambda x: int(str(x[0].toString()))
			getId['com']=lambda x: int(str(x[2].toString()))
			getId['cap']=lambda x: str(x[1].toString())
			Id=getId[key](attrmap)
			#Id=fields[key]['Id'](attrmap)
		   ##self.log("attr inviato a lista={0}".format(attr),"test.py 175")
			self.selectionList.appendItem([key,unicode(attr),Id])
		   
		   ##self.log("selectionLIst test.py 178",self.selectionList.getList())
#		   ##self.log("selectionList test.py 131 ",self.selectionList)
		####settrace()
		print "utb selezionate",self.selectionList.getList()
		#settrace()
		return self.selectionList

	def unload(self):
		# Remove the plugin menu item and icon
		self.iface.removePluginMenu("&mmasgis",self.action)
		self.iface.removeToolBarIcon(self.action)
	def addList(self,a,b):
		pass #return a+b
	def search(self,string,pattern):
		match=re.compile(pattern)
		b=False
		if match.search(string):
			b=True
		return b
	def match(self,string,pattern):
		match=re.compile(pattern)
		b=False
		if match.match(string):
			b=True
		return b
		
	
	def makeList(self):
		layersmap=QgsMapLayerRegistry.instance().mapLayers()
		
		curLayer = self.iface.mapCanvas().currentLayer()
		mc=self.iface.mapCanvas() 
		self.nLayers=mc.layerCount() 
		self
		##self.log("nLayers test.py 194",self.nLayers)
		
		# rimuovo  il layer aggiunto dal plugin openLayers
		#non posso cambiare il dict mentre sono in un ciclo 
		#quindi creo un dict con i soli layers che mi interessano
		dummymap={}
		for key in layersmap.iterkeys():
			if (self.search(str(key),"_g"))or(self.match(str(key),'Cap')):
				dummymap[key]=layersmap[key]
		##self.log("dummymap={0}".format(dummymap),"203 test.py")
		##self.log("layersmap={0}".format(layersmap),"204 test.py")
		##self.log("lunghezza dummy={0}".format(len(dummymap)),"lunghezza original={0}".format(len(layersmap)))
		for key in dummymap.iterkeys():
			##self.log("esamino layers {0}".format(key),"test.py 212")
			##self.log("type(key {0}".format(type(key))," ###")
			curLayer=layersmap[key]
			fProvider = curLayer.dataProvider()
			myFields = fProvider.fields()
			####settrace()
			##self.log("attributi nel layer {0}: {1}".format(curLayer.name(),[f.name() for f in myFields.values()]),"mmasgis.py 245")
			# verificato cicla una volta
			#aggiungo la lista dei campi selezionati  sul layer
			chiave=str(key[0:3])
			##self.log("full key {0}".format(key),"test.py 214")
			##self.log("key  troncata test.py 215",key[0:3])
			##self.log("chiave convertita test.py 216",self.cons.typeItem[chiave.lower()])
			self.ui_tree.addLayer(str(key).lower()[0:3], curLayer)
			self.getSelections(curLayer,chiave.lower())
			####settrace()
			###self.log("nome layer for key={0}  in selectionList test.py 161".format(key),self.selectionListget[0])
			
			
			##self.log("selectionList test.py 248",self.selectionList.getList())
		
		
	def censusSelected(self,db):
		self.dbSwitcher_ui.close()
		db.setUserName("metmi")
		db.setPassword("metmi")
		#e' stato selezionato il censimento ma manca la porta e la famiglia del server che sono presenti nel db attivo passato da loginrefactored
		db.setPort(self.user.getActiveDb().getPort())
		db.setRDBMS(str(self.user.getActiveDb().getRDBMS()))
		self.user.setActiveDb(db)
		print "utente loggato",self.user
		self.analyze(self.user)
		
	# run method that performs all the real work
	def run(self):
		if not self.censimentoSelected:
			self.dbSwitcher_ui=MainWindowDbSwitcher(self.user,self.ds)
			self.dbSwitcher_ui.show()
			QtCore.QObject.connect(self.dbSwitcher_ui,QtCore.SIGNAL("dbSelected"),self.censusSelected)
	

			
		
			screen = QtGui.QDesktopWidget().screenGeometry()
			#size =  self.login.geometry()
			#self.login.move((screen.width()/2)-(size.width()/2),(screen.height()/2)-size.height())
			#self.login.show()
		else:
			self.mmasgis(self.user)
		
	"""
	analizza i layers cercando le selezioni effettuate
	"""
	def analyze(self,user):
		print "***selezioni su finestra "+str(self.ui_tree.getList()) 
		self.selectionList=Lista(user,user.getActiveDb())
		self.util=utility([],0,user,user.getActiveDb())#non  potra' popolare' le tabelle
		# create and show the dialog
		curLayer = self.iface.mapCanvas().currentLayer()
		#elenco tutti gli elementi del layer corrente
		featids = range(curLayer.featureCount())
		#creo la lista della selezioni

		self.makeList()
		print("SSScomuni selezionati mmasgis.py 430",self.selectionList.getList())
		self.dlg = testDialog(self.selectionList.getList(),user,user.getActiveDb())
		NomeDb=user.getActiveDb().getNameDb()
		self.dlg.setWindowTitle("Elenco Anagrafiche "+NomeDb.capitalize())
		# show the dialog
		self.dlg.show()
		#app=QtGui.QApplication(["show",""],True)
		#resetto la lista
		self.selectionList.resetList()
		#sys.exit(app.exec_())
		result=1
		#dlg.traccheggio()
		# See if OK was pressed
		if result == 1:
			# do something useful (delete the line containing pass and
			# substitute with your code
			pass


	def mmasgis(self,user):
		self.util=utility([],0,user,user.getActiveDb())#non  potra' popolare' le tabelle
		self.selectionList=Lista(user,user.getActiveDb())
		# create and show the dialog
		#####settrace()
		curLayer = self.iface.mapCanvas().currentLayer()
		#elenco tutti gli elementi del layer corrente
		featids = range(curLayer.featureCount())
		#creo la lista della selezioni
		self.makeList()
		self.log("comuni selezionati mmasgis.py 297",self.selectionList.getList())
		self.log("lista inviata a testDialog {0} ".format(self.selectionList.getList()),"test.py 212")
		self.dlg = testDialog(self.selectionList.getList(),user,user.getActiveDb())
		# show the dialog
		self.dlg.show()
		#app=QtGui.QApplication(["show",""],True)
		#resetto la lista
		self.selectionList.resetList()
		#sys.exit(app.exec_())
		result=1
		#dlg.traccheggio()
		# See if OK was pressed
		if result == 1:
			# do something useful (delete the line containing pass and
			# substitute with your code
			pass