Ejemplo n.º 1
0
 def displayValue_(self, sender):
     if self.viewId != 0 and self.startDate <= self.endDate and self.metrics != '':
         try:
             if int(self.checkBoxSpreadsheetData.state()) == 1:
                 self.viewId, self.metrics, self.dimensions, self.sort, self.filters, self.maxResults \
                 = functions.get_data_from_spreadsheet([self.viewId, self.metrics, self.dimensions, self.sort, \
                 self.filters, self.maxResults], self.serviceSheets, self.spreadsheetIdStack, self.sheetNameStack)
             self.value = ''
             viewIds = self.viewId.split(',')
             for viewId in viewIds:
                 value = functions.get_value(self.serviceAnalytics, viewId, str(self.startDate), str(self.endDate), self.metrics, self.dimensions, self.sort, self.filters, self.maxResults)
                 self.value += functions.str_from_list(value) + '\n'
                 if len(value[0]) == 1:
                     value[0].append('')
                     value[0].reverse()
                 self.values += value
             with open(self.dirpath + 'temp.json', 'w') as f:
                 json.dump(self.temp, f, indent=4)
         except (HttpError) as e:
             self.value = json.loads(e.content.decode('utf-8'))['error']['message']
     else:
         if self.viewId == 0:
             self.value = 'You must enter a view ID'
         elif self.startDate > self.endDate:
             self.value = 'Choose a possible date range'
         else:
             self.value = 'You must enter a metric'
     self.updateDisplay()
def m_plus():
    string = get_value(screen.get())
    try:
        if string[0] == "-":
            string = string[1:]
        else:
            string = "-" + string
    except IndexError:
        pass
    screen_value.set(string)
def point_btn():
    global got_operator, got_point, got_result
    got_result = False
    string = get_value(screen.get())
    if got_point:
        btn_value = '.'
        string = string + btn_value
        got_operator = False
        got_point = False
    screen_value.set(string)
def number_btn(num):
    global got_operator, got_point, got_result
    string = get_value(screen.get())
    if got_result:  # When we calculate result it clear the value and set new input value
        string = num
        got_result = False
    else:
        string = string + num
    screen_value.set(string)
    got_operator = True
def calculate():
    global got_result
    string = get_value(screen.get()).replace(
        '÷', '/')  # Changed the ÷ symbol before devide
    try:
        result = literal_eval(string)
        got_result = True
    except ZeroDivisionError:
        result = string
    except Exception as e:
        print(e)
        result = string
    screen_value.set(result)
Ejemplo n.º 6
0
def solve(endpoints, caches, video_sizes, x):
    num_caches = len(caches)
    itr = 0
    for c in caches:
        print(f"\r{100 * itr / num_caches}%")
        values = [get_value(i, c, endpoints) for i in range(len(video_sizes))]
        __, items = knapsack(x, video_sizes, values)
        c.videos = items
        for e in c.connected_endpoints:
            endpoint = endpoints[e]
            for v in c.videos:
                if v in endpoint.requests:
                    endpoint.requests[v] = 0
        itr += 1
    return caches
def operator_btn(operator):
    global got_operator, got_point, got_result
    got_result = False
    string = get_value(screen.get())
    if got_operator:
        string = string + operator
        got_point = True
        got_operator = False
    else:
        if string == '0' or string == '':
            string = '0'
        else:
            string = string[:-1] + operator
            got_point = True
            got_operator = False
    screen_value.set(string)
def key(event):
    global got_operator, got_point, got_result
    # Get the keypress
    my_input = event.keycode
    string = get_value(screen.get())  # get the existing value of screen
    kp = repr(event.char)
    if my_input == 9:
        # Exit when escape key is pressed
        # root.destroy() # It creates an error
        exit()
    elif my_input == 49:  # Toggle positive and negative
        try:
            if string[0] == "-":  # Value is negative
                string = string[1:]
            else:  # Value is positive
                string = "-" + string
        except IndexError:
            pass  # To do nothing
    elif my_input == 119 or my_input == 22:
        # Delete last later when del key or backspace key is pressed
        new = string[:-1]
        if len(string) == 1 or len(string) == 0:
            string = "0"
            got_operator = False
        else:
            string = new
            if string[-1] in operator_list:  # Multi oprator Bug Was here
                got_operator = False
            else:
                got_operator = True
            if string[-1] in dot_list:
                got_point = False
            else:
                got_point = True

    elif my_input == 36:
        # Calculate the result when enter key is pressed
        try:
            result = literal_eval(string)
            got_result = True
        except ZeroDivisionError:
            result = string
        except Exception as e:
            print(e)
            result = string
        string = str(result)
    if kp[1] in numbers_list:  # Check pressed key is in number list
        num = kp[1]
        got_operator = True
        string = string + num
    elif kp[1] in operator_list:  # Check pressed key is in oprator list
        value_btn = kp[1]
        if got_operator:  # Validation to get oprator
            got_operator = False
            got_point = True
            string = string + value_btn
        else:  # If oprator already typed it replace previous one
            if string == '0' or string == '':
                string = '0'
            else:
                if string[-1] in operator_list and string[-2] in operator_list:
                    string = string[:-3] + string[-1]
                got_point = True
                got_operator = False
    elif kp[1] in dot_list:  # Check pressed key is in oprator list
        if got_point:  # Validation to get number
            num = kp[1]
            got_operator = False
            got_point = False
            string = string + num
    if len(
            string
    ) == 1 and string == "0":  # Whene the value is 0 you can,t input oprator
        got_operator = False
    screen_value.set(string)
    # To handle the bug
    string = get_value(screen.get())
    if string == "":
        screen_value.set("0")
Ejemplo n.º 9
0
    def collection(self, site, indices=None, normalize=True, bbox=0):
        """
        :param indices: vegetation indices to include in the final image. If
            None, no index is calculated
        :type indices: tuple
        :param site: Site geometry
        :type site: ee.Geometry
        :param normalize: Whether to normalize the final score from 0 to 1
            or not
        :type normalize: bool
        :return:
        """
        # Si no se pasa una funcion para aplicar antes de los puntajes, se
        # crea una que devuelva la misma imagen
        if self.fmap is None:
            fmap = lambda x: x
        else:
            fmap = self.fmap

        # colfinal = ee.ImageCollection()
        colfinal = ee.List([])

        # Obtengo la region del site
        try:
            region = site.geometry().bounds().getInfo()['coordinates'][0]
        except AttributeError:
            region = site.getInfo()['coordinates'][0]
        except:
            raise AttributeError

        # lista de nombres de los puntajes para sumarlos al final
        scores = self.score_names
        maxpunt = reduce(lambda i, punt: i + punt.max, self.scores,
                         0) if self.scores else 1

        # Diccionario de cant de imagenes para incluir en las propiedades
        toMetadata = dict()

        if self.verbose: print "scores:", scores

        for colobj in self.collist():

            # Obtengo el ID de la coleccion
            cid = colobj.ID

            # Obtengo el name abreviado para agregar a los metadatos
            short = colobj.short

            # Imagen del col_id de la coleccion
            bid = colobj.bandIDimg

            # diccionario para agregar a los metadatos con la relation entre
            # satelite y col_id
            # prop_codsat = {colobj.ID: colobj.col_id}
            toMetadata["col_id_" + short] = colobj.col_id

            # Collection completa de EE
            c = colobj.colEE

            # Filtro por el site
            if isinstance(site, ee.Feature): site = site.geometry()
            c2 = c.filterBounds(site)

            # Renombra las bandas aca?
            # c2 = c2.map(col.rename())

            if self.verbose: print "\nSatellite:", colobj.ID
            if self.debug:
                print " SIZE AFTER FILTER SITE:", c2.size().getInfo()

            # Filtro por los años
            for anio in self.date_range:
                # Creo un nuevo objeto de coleccion con el id
                col = satcol.Collection.from_id(cid)
                # puntajes = []

                ini = self.season.add_year(anio)[0]
                end = self.season.add_year(anio)[1]

                if self.verbose: print "ini:", ini, ",end:", end

                # Filtro por fecha
                c = c2.filterDate(ini, end)

                if self.debug:
                    n = c.size().getInfo()
                    print "    SIZE AFTER FILTER DATE:", n

                ## FILTROS ESTABAN ACA

                # Si despues de los filters no quedan imgs, saltea..
                size = c.size().getInfo()
                if self.verbose: print "size after filters:", size
                if size == 0: continue  # 1

                # corto la imagen con la region para minimizar los calculos
                if bbox == 0:

                    def cut(img):
                        return img.clip(site)
                else:

                    def cut(img):
                        bounds = site.buffer(bbox)
                        return img.clip(bounds)

                c = c.map(cut)

                # Mascaras
                if self.masks:
                    for m in self.masks:
                        c = c.map(m.map(col=col, year=anio, colEE=c))
                        if self.debug:
                            print " BANDS AFTER THE MASK "+m.nombre, \
                                ee.Image(c.first()).bandNames().getInfo()

                # Transformo los valores enmascarados a cero
                c = c.map(functions.antiMask)

                # Renombra las bandas con los datos de la coleccion
                c = c.map(col.rename(drop=True))

                # Cambio las bandas en comun de las collections
                bandasrel = []

                if self.debug:
                    print " AFTER RENAMING BANDS:", \
                        ee.Image(c.first()).bandNames().getInfo()

                # Escalo a 0-1
                c = c.map(col.do_scale())
                if self.debug:
                    if c.size().getInfo() > 0:
                        print " AFTER SCALING:", \
                            ee.Image(c.first()).bandNames().getInfo()

                # Indices
                if indices:
                    for i in indices:
                        f = col.INDICES[i]
                        c = c.map(f)
                        if self.debug: print c.size().getInfo()

                # Antes de aplicar los puntajes, aplico la funcion que pasa
                # el usuario
                c = c.map(fmap)

                # Puntajes
                if self.scores:
                    for p in self.scores:
                        if self.verbose: print "** " + p.name + " **"
                        # Espero el tiempo seteado en cada puntaje
                        sleep = p.sleep
                        for t in range(sleep):
                            sys.stdout.write(str(t + 1) + ".")
                            time.sleep(1)
                        c = c.map(p.map(col=col, year=anio, colEE=c,
                                        geom=site))

                        # DEBUG
                        if self.debug and n > 0:
                            geom = site if isinstance(site, ee.Geometry)\
                                         else site.geometry()
                            print "value:", functions.get_value(
                                ee.Image(c.first()), geom.centroid())

                # Filtros
                if self.filters:
                    for filtro in self.filters:
                        c = filtro.apply(c, col=col, anio=self.year)

                ## INDICES ESTABA ACA

                ## ESCALAR ESTABA ACA

                # Selecciona solo las bandas que tienen en comun todas las
                # Colecciones

                # METODO ANTERIOR: funcionaba, pero si agregaba una band
                # con fmap, no se seleccionaba
                '''
                def sel(img):
                    puntajes_ = puntajes if self.scores else []
                    indices_ = list(indices) if indices else []
                    relaciones = self.col.bandsrel()
                    return img.select(relaciones+puntajes_+indices_)
                c = c.map(sel)
                '''

                # METODO NUEVO: selecciono las bandas en comun desp de unir
                # todas las collections usando un metodo distinto

                if self.debug:
                    if c.size().getInfo() > 0:
                        print " AFTER SELECTING COMMON BANDS:",\
                            ee.Image(c.first()).bandNames().getInfo()

                # Convierto los valores de las mascaras a 0
                c = c.map(functions.antiMask)

                # Agrego la band de fecha a la imagen
                c = c.map(date.Date.map())

                # Agrego la band col_id de la coleccion
                def addBandID(img):
                    return img.addBands(bid)

                c = c.map(addBandID)

                if self.debug:                    print " AFTER ADDING col_id BAND:", \
         ee.Image(c.first()).bandNames().getInfo()

                # Convierto a lista para agregar a la coleccion anterior
                c_list = c.toList(2500)
                colfinal = colfinal.cat(c_list)

                # Agrego col id y year al diccionario para propiedades
                cant_imgs = "n_imgs_{cid}_{a}".format(cid=short, a=anio)
                toMetadata[cant_imgs] = functions.get_size(c)

        # comprueba que la lista final tenga al menos un elemento
        # s_fin = colfinal.size().getInfo()  # 2
        s_fin = functions.get_size(colfinal)

        # DEBUG
        if self.verbose: print "final collection size:", s_fin

        if s_fin > 0:
            newcol = ee.ImageCollection(colfinal)

            # Selecciono las bandas en comun de todas las imagenes
            newcol = functions.select_match(newcol)

            if self.debug:                print " BEFORE score:", scores, "\n", \
     ee.Image(newcol.first()).bandNames().getInfo()

            # Calcula el puntaje total sumando los puntajes
            ftotal = functions.sumBands("score", scores)
            newcol = newcol.map(ftotal)

            if self.debug:
                print " AFTER score:", \
                    ee.Image(newcol.first()).bandNames().getInfo()

            if normalize:
                newcol = newcol.map(
                    functions.parameterize((0, maxpunt), (0, 1), ("score", )))

            if self.debug:
                print " AFTER parametrize:", \
                    ee.Image(newcol.first()).bandNames().getInfo()

            output = namedtuple("ColBap", ("col", "dictprop"))
            return output(newcol, toMetadata)
        else:
            return None