def mostLikedVideosCountryTag(catalog, country, tag): ''' funcion que retorna una lista con los videos de un pais pasado por parametro y que contenga el tag deseado por el usuario ''' # Obtenemos la pareja llave valor de la categoria pair = mp.get(catalog['country'], country) if pair is None: newList = 1 else: # Obtenemos la lista con los videos de ese pais countryList = me.getValue(pair) ''' Creamos una lista donde guardaremos los videos que contienen los tags deseados por el usuario ''' finalList = lt.newList('ARRAY_LIST') iterator = ite.newIterator(countryList['videos']) while ite.hasNext(iterator): info = ite.next(iterator) # Buscamos los tags que desea el usuario if tag in info['tags']: # Verificamos que no hayan repeticiones de videos lt.addLast(finalList, info) # Le hacemos un sort a la lista dependiendo de los likes newList = sortVideos(finalList, cmpVideosByLikes) return newList
def add_edges(self): edge_it = al_it.newIterator(self.connections_list) while al_it.hasNext(edge_it): temp = al_it.next(edge_it) new_edge = lt.getElement(temp, 1), lt.getElement(temp, 2) gp.addEdge(self.connections_map, *new_edge, self.haversine(*new_edge))
def ReqCuatro(catalog, tag, country, size): videitos = mp.get(catalog["videos-pais"], country) videillos = me.getValue(videitos)["videos"] elqueitera = it.newIterator(videillos) tagslist = lt.newList(datastructure="ARRAY_LIST") while it.hasNext(elqueitera): fuego = it.next(elqueitera) etiquetas = fuego["tags"].split("|") for j in etiquetas: if tag.lower() in j.lower(): """dictiquetas = mp.newMap() mp.put(dictiquetas, "title",fuego['title']) mp.put(dictiquetas, "channel_title",fuego['channel_title']) mp.put(dictiquetas, "publish_time",fuego['publish_time']) mp.put(dictiquetas, "views",fuego['views']) mp.put(dictiquetas, "likes",fuego['likes']) mp.put(dictiquetas, "dislikes",fuego['dislikes']) mp.put(dictiquetas, "tags",fuego['tags'])""" lt.addLast(tagslist, fuego) if size > lt.size(tagslist): ordenation = 0 else: ordenation = sortVideos(tagslist,size,cmpVideosByLikes) return ordenation
def impresor_de_datos_elefante_de_batalla_psiquico_ancestral(lista): A = it.newIterator(lista) while it.hasNext(A): B = it.next(A) print(B) print( "馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬馃崬" )
def __next__(self): while not aliterator.hasNext(self.category_iter): if not lliterator.hasNext(self.country_iter): raise StopIteration else: self.category_iter = aliterator.newIterator( lliterator.next(self.country_iter)) current = aliterator.next(self.category_iter) return current
def translateCategory(name,catalog): categories = catalog["categories"] iterator = it.newIterator(categories) while it.hasNext(iterator): element = it.next(iterator) if name.lower() in element["name"].lower() : return element["id"] else: pass
def __next__(self): while not aliterator.hasNext(self.category_iter): if not lliterator.hasNext(self.super_iter): raise StopIteration else: country_map = lliterator.next(self.super_iter) category_list = mp.get(country_map, self.category)['value'] self.category_iter = aliterator.newIterator(category_list) current = aliterator.next(self.category_iter) return current
def graph_affected_countries(self, countries): country_it = al_it.newIterator(countries) while al_it.hasNext(country_it): country, dist = al_it.next(country_it) capital = self.data.get_capital_id_safe(country) coords = self.data.point_coords_degrees(capital) folium.Marker(coords, popup="{}: {} kms".format(country, dist)).add_to(self.m) self.m.save('Data/map.html')
def graph_req_2(self, conexion_lp): conexion_it = al_it.newIterator(conexion_lp) while al_it.hasNext(conexion_it): name, vertex, edges = tuple(al_it.next(conexion_it)) coordinates = self.data.point_coords_degrees(vertex) folium.Circle(coordinates, radius=(edges**(0.5) * 9000), popup="{}: {}".format(name, edges), fill_color="#3186cc").add_to(self.m) self.m.save('Data/map.html')
def create_cable_map(self): self.cable_bandwith = mp.newMap(numelements=3268) cable_it = al_it.newIterator(self.connections_list) i = 1 while al_it.hasNext(cable_it): cable = al_it.next(cable_it) self.add_country_cable(cable, i) i += 1 cable_it = ll_it.newIterator(mp.keySet(self.cable_bandwith)) while ll_it.hasNext(cable_it): cable = ll_it.next(cable_it) self.cable_map_to_list(cable)
def Requerimiento_5(hora_min, hora_max, analyzer_context): hora_menor = hora_convertidor_consultas(hora_min) hora_mayor = hora_convertidor_consultas(hora_max) llaves = om.keys(analyzer_context["created_at"], hora_menor, hora_mayor) iterador_2 = llaves["first"] informacion = iterador_2["info"] usuarios_2 = [] tempos = [] while iterador_2["next"] != None: iterador_2 = iterador_2["next"] llave_2 = iterador_2["info"] crimenes2 = me.getValue(om.get(analyzer_context['created_at'], llave_2)) c = it.newIterator(crimenes2) while it.hasNext(c): n = it.next(c) A = m.get(analyzer_context["eventos"], n) B = me.getValue(A) usuarios_2.append(float(B["tempo"])) tempos.append(str(B["track_id"])) géneros = [] for i in usuarios_2: if i >= 60 and i <= 90: géneros.append("Reggae") if i >= 70 and i <= 100: géneros.append("Down-tempo") if i >= 90 and i <= 120: géneros.append("Chill-out") if i >= 85 and i <= 115: géneros.append("Hip-hop") if i >= 120 and i <= 125: géneros.append("Jazz and Funk") if i >= 100 and i <= 130: géneros.append("Pop") if i >= 60 and i <= 80: géneros.append("R&B") if i >= 110 and i <= 140: géneros.append("Rock") if i >= 100 and i <= 160: géneros.append("Metal") h = defaultdict(list) for k, v in zip(géneros, tempos): h[k].append(v) x = { k: v for k, v in sorted( h.items(), key=lambda item: len(item[1]), reverse=True) } longi = [] for i in x: longi.append(len(h[i])) return (x, longi)
def __next__(self): while not aliterator.hasNext(self.category_iter): while not lliterator.hasNext(self.country_iter): if not lliterator.hasNext(self.super_iter): raise StopIteration else: country_list = mp.valueSet(lliterator.next( self.super_iter)) self.country_iter = lliterator.newIterator(country_list) self.category_iter = aliterator.newIterator( lliterator.next(self.country_iter)) current = aliterator.next(self.category_iter) return current
def filterByTag(list, tag): iterator = alit.newIterator(list) filteredList = lt.newList('ARRAY_LIST') while alit.hasNext(iterator): video = alit.next(iterator) cleanTag = video['tags'].replace('"', '').replace('|', '').lower() if tag in cleanTag: lt.addLast(filteredList, video) return filteredList
def obtener_accidentes_en_una_fecha(analyzer, criterioa): criterio = fecha_convertidor_consultas(criterioa) d = lt.newList("ARRAY_LIST") a = om.get(analyzer["index"], criterio) b = me.getValue(a) c = it.newIterator(b) while it.hasNext(c): n = it.next(c) A = m.get(analyzer["accidentes"], n) B = me.getValue(A) lt.addLast(d, B) ins.insertionSort(d, lessfunction) return d
def hasNext(iterator): """ Informa si se puede seguir iterando. Informa si existe un nodo en la siguiente posicion de la lista, a partir de la posicion actual del iterador. Args: iterator: El iterador creado sobre la lista Returns: True si existe un siguiente elemento, False de lo contrario """ if (iterator['type'] == 'ARRAY_ITERATOR'): return ait.hasNext(iterator) else: return lit.hasNext(iterator)
def printReqOne(orderedList, rank): iterator = alit.newIterator(orderedList) counter = 1 print( "trending_date\ttitle\tchannel_title\tpublish_time\tviews\tlikes\tdislikes" ) while alit.hasNext(iterator): element = alit.next(iterator) print("[" + str(counter) + "] " + element['trending_date'] + "\t" + element['title'] + "\t" + element['channel_title'] + "\t" + element['publish_time'] + "\t" + element['views'] + "\t" + str(element['likes']) + "\t" + element['dislikes']) counter += 1
def ReqTres(catalog, name): idee = mp.get(catalog["categories"], name) #print(catalog["categories"]) ideev = me.getValue(idee) valor = mp.get(catalog["videos-cat"],ideev) #print(valor) lista = me.getValue(valor)["videos"] catss = mp.newMap(numelements=500, maptype="CHAINING", loadfactor=4.0) dickss = mp.newMap(numelements=500, maptype="CHAINING", loadfactor=4.0) iterator = it.newIterator(lista) while it.hasNext(iterator): tierra = it.next(iterator) if mp.contains(catss,tierra['title']): #cats[tierra["title"]] += 1 pareja = mp.get(catss,tierra['title']) valor = me.getValue(pareja) + 1 mp.put(catss,tierra["title"],valor) else: mp.put(catss,tierra["title"],1) mp.put(dickss,tierra["title"],tierra) #(a, b) = max((catss[key], key) for key in catss) k = None mx = -1 varx = mp.keySet(catss) itr = varx["first"] if itr == None: return None while itr: element = itr["info"] cnt = mp.get(catss, element) cnts = me.getValue(cnt) if cnts > mx: mx = cnts k = element itr = itr["next"] zzz = mp.get(dickss,k) b = me.getValue(zzz) result = {'title': b["title"], 'channel_title': b['channel_title'], 'category_id': b["category_id"], 'número de días': mx} return result
def req2(catalog,country): #Hecho por Ana Sofia Padilla videos = catalog["ListCompleteVidAll"] dictitles = {} dicsave = {} iterator = it.newIterator(videos) while it.hasNext(iterator): element = it.next(iterator) if element["country"].lower() == country.lower(): if element['title'] in dictitles: dictitles[element["title"]] += 1 else: dictitles[element["title"]] = 1 dicsave[element["title"]] = element (a, b) = max((dictitles[key], key) for key in dictitles) return {'title': b, 'channel_title': dicsave[b]['channel_title'], 'country': country, 'número de días': a}
def analizador_tempos(analyzer_context, tempo_min, tempo_max): tempo = om.keys(analyzer_context["tempo"], tempo_min, tempo_max) iterador_2 = tempo["first"] informacion = iterador_2["info"] usuarios_2 = [] tempos = [] while iterador_2["next"] != None: iterador_2 = iterador_2["next"] llave_2 = iterador_2["info"] crimenes2 = me.getValue(om.get(analyzer_context['tempo'], llave_2)) c = it.newIterator(crimenes2) while it.hasNext(c): n = it.next(c) A = m.get(analyzer_context["eventos"], n) B = me.getValue(A) usuarios_2.append(B["artist_id"]) tempos.append(B["track_id"]) unicos = list(set(usuarios_2)) return (unicos, len(tempos))
def req3(catalog, category): #Hecho por Ernesto José Duartex idd = translateCategory(category,catalog) titles = catalog["ListCompleteVidAll"] cats = {} dick = {} iterator = it.newIterator(titles) while it.hasNext(iterator): element = it.next(iterator) if element["category_id"] == idd: if element['title'] in cats: cats[element["title"]] += 1 else: cats[element["title"]] = 1 dick[element["title"]] = element (a, b) = max((cats[key], key) for key in cats) return {'title': b, 'channel_title': dick[b]['channel_title'], 'category_id': dick[b]["category_id"], 'número de días': a}
def req4(catalog, tag, pais, size): iterator = it.newIterator(catalog["ListCompleteVidAll"]) listags = lt.newList(datastructure="ARRAY_LIST") while it.hasNext(iterator): element = it.next(iterator) tags = element["tags"].split("|") for i in tags: if element["country"].lower() == pais.lower() and tag.lower() in i.lower(): dictags = {'title': element['title'], "channel_title": element['channel_title'], "publish_time": element["publish_time"], 'views': element['views'], "likes": element['likes'], "dislikes": element['dislikes'], "tags": element['tags']} lt.addLast(listags,dictags) if size > lt.size(listags): ordenados = 0 else: ordenados = sortVideos(listags,size,cmpVideosByLikes) return ordenados
def createUniqueCountry(list): idMap = mp.newMap(5500, maptype='CHAINING', loadfactor=4.0) iterator = alit.newIterator(list) while alit.hasNext(iterator): video = alit.next(iterator) newLikes = video['likes'] existingId = mp.get(idMap, video['video_id']) if existingId: keyValueId = mp.get(idMap, video['video_id']) existingVideo = me.getValue(keyValueId) if newLikes > existingVideo['likes']: existingVideo['likes'] = newLikes else: mp.put(idMap, video['video_id'], video) return mp.valueSet(idMap)
def mostTrendingVideoCat(catalog, category): ''' Esta funcion retorna el elemento que estuvo mas dias en trending en una categoria especifica y la cantidad de dias ''' # Tiene un espacio porque los nombres de las categorias se guardaron asi parameter = ' ' + category # Obtenemos la pareja llave valor de la categoria pair = mp.get(catalog['category'], parameter) if pair is None: newlist = 1 days = 0 else: # Sacamos la informacion de la pareja y es la lista con los videos category_list = me.getValue(pair) dictionary = {} iterator = ite.newIterator(category_list['videos']) while ite.hasNext(iterator): info = ite.next(iterator) # Seleccionamos los valores que son utiles para la busqueda newinfo = (info['title'], info['channel_title'], info['category_id']) ''' Iniciamos una lista con 1 que va a ser la primera vez que la info de un video se guardo en el diccionario. Cada vez que se encuentra la misma informacion agrega un 1 a la lista que es valor del diccionario la cantidad de dias que estuvo en trending es en len() de la lista valor ''' llist = [1] if newinfo in dictionary: dictionary[newinfo].append(1) else: dictionary[newinfo] = llist # Sacamos la llave del dicionario cuyo valor es el mayor newlist = max(dictionary, key=dictionary.get) days = dictionary[newlist] return newlist, days
def req1(catalog,name,country,size): videos = catalog["ListCompleteVidAll"] idd = translateCategory(name,catalog) nl = lt.newList(datastructure="ARRAY_LIST") iterator = it.newIterator(videos) while it.hasNext(iterator): element = it.next(iterator) if element["country"].lower() == country.lower() and element["category_id"] == idd: newdict = {"trending_date": element['trending_date'], 'title': element['title'], "channel_title": element['channel_title'], "publish_time": element["publish_time"], 'views': element['views'], "likes": element['likes'], "dislikes": element['dislikes']} lt.addLast(nl,newdict) if lt.size(nl) > 0: ordenados = sortVideos(nl,size,cmpVideosByViews) else: ordenados = "No se han encontrado videos de ese pais con esa categoria" return ordenados
def ReqDos(catalog, country): videitos = mp.get(catalog["videos-pais"], country) #print(mp.valueSet(catalog["videos-pais"])) #print(videitos) videillos = me.getValue(videitos)["videos"] ceteras = mp.newMap(numelements=500, maptype="CHAINING", loadfactor=4.0) dickss = mp.newMap(numelements=500, maptype="CHAINING", loadfactor=4.0) iterator = it.newIterator(videillos) while it.hasNext(iterator): tierra = it.next(iterator) if mp.contains(ceteras,tierra['title']): pareja = mp.get(ceteras,tierra['title']) valor = me.getValue(pareja) + 1 mp.put(ceteras,tierra["title"],valor) else: mp.put(ceteras,tierra["title"],1) mp.put(dickss,tierra["title"],tierra) k = None mx = -1 varx = mp.keySet(ceteras) itr = varx["first"] if itr == None: return None while itr: element = itr["info"] cnt = mp.get(ceteras, element) cnts = me.getValue(cnt) if cnts > mx: mx = cnts k = element itr = itr["next"] zzz = mp.get(dickss,k) b = me.getValue(zzz) result = {'Title': b["title"], 'Channel_title': b['channel_title'], 'Country': country, 'Número de días': mx} return result
def ReqUno(catalog, name, size, country): idee = mp.get(catalog["categories"], name) ideev = me.getValue(idee) valor = mp.get(catalog["videos-cat"],ideev) lista = me.getValue(valor)["videos"] nuevl = lt.newList(datastructure="ARRAY_LIST") iterator = it.newIterator(lista) while it.hasNext(iterator): aire = it.next(iterator) if aire["country"].lower() == country.lower(): newdict = {"trending_date": aire['trending_date'], 'title': aire['title'], "channel_title": aire['channel_title'], "publish_time": aire["publish_time"], 'views': aire['views'], "likes": aire['likes'], "dislikes": aire['dislikes']} lt.addLast(nuevl,newdict) nuevaLista = sortVideos(nuevl, size, cmpVideosByViews) return nuevaLista
def crear_lista_con_criterio(index, accidentes, criterio, fecha1, fecha2, es_fecha): d = {} A = om.values(index, fecha1, fecha2) M = lit.newIterator(A) while lit.hasNext(M): L = lit.next(M) N = it.newIterator(L) while it.hasNext(N): D = it.next(N) R = m.get(accidentes, D) K = me.getValue(R) if es_fecha == True: if fecha_convertidor(K[criterio]) in d: d[fecha_convertidor(K[criterio])] += 1 else: d[fecha_convertidor(K[criterio])] = 1 else: if (K[criterio]) in d: d[(K[criterio])] += 1 else: d[(K[criterio])] = 1 return d
def getVideosCat(catalog, category, country): ''' Esta funcion retorna una lista con todos los videos y su informacion que hay en una categoria y pais pasados por parametro, esta es proporcionada por el usuario ''' # Tiene un espacio porque los nombres de las categorias se guardaron asi parameter = ' ' + category # Obtenemos la pareja llave valor de la categoria pair = mp.get(catalog['category'], parameter) if pair is None: newlist = 1 else: # Sacamos la informacion de la pareja y es la lista con los videos category_list = me.getValue(pair) countryList = lt.newList('ARRAY_LIST') iterator = ite.newIterator(category_list['videos']) while ite.hasNext(iterator): info = ite.next(iterator) if info['country'] == country: lt.addLast(countryList, info) # Organizamos la lista de los videos por la cantidad de likes newlist = sortVideos(countryList, cmpVideosByViews) return newlist
elif int(inputs[0]) == 5: nodos, rama, distancia_rama, distancia_total = controller.req_4(data) print("La red de expansión mínima más grande tiene {} nodos.".format( nodos)) print("La rama más grande de dicha red tiene {} kms y es:".format( distancia_rama)) print(rama) print("La red cubre {} kms.".format(distancia_total)) input("Presione alguna tecla para ver la visualización ") webbrowser.open('file://' + os.path.realpath('Data/map.html')) elif int(inputs[0]) == 6: lp = input("Introduzca el landing point: ") lista_paises = controller.req_5(data, lp) print("Hay {} paises afectados".format(lt.size(lista_paises))) iterador = ll_it.newIterator(lista_paises) while ll_it.hasNext(iterador): tupla = ll_it.next(iterador) print( "{} es afectado. Su landing point más cercano está a {} kms de {}." .format(tupla[0], round(tupla[1], 2), lp)) input("Presione alguna tecla para ver la visualización ") webbrowser.open('file://' + os.path.realpath('Data/map.html')) elif int(inputs[0]) == 7: server = input("Introduzca el país donde se ubica el servidor: ") cable = input("Introduzca el nombre del cable: ") tabla = controller.req_6(data, cable, server) print(tabla[0]) input("Presione alguna tecla para ver la visualización ") webbrowser.open('file://' + os.path.realpath('Data/map.html')) elif int(inputs[0]) == 8: IP1 = input("Introduzca la primera IP: ")
def __next__(self): if al_it.hasNext(self.m_it): return al_it.next(self.m_it) else: raise StopIteration