예제 #1
0
    def aluguelreserv(nomeCliente=None, cpfCliente=None):
        clientes = shelve.open("clientes.pyc")  #Clientes eh o ARQUIVO

        for c in clientes:
            if clientes[c].nome == nomeCliente:
                if cpfCliente != None and clientes[c].cpf == cpfCliente:
                    c = clientes[c]
                    break
                else:
                    return "Erro! CPF nao especificado ou congruencia entre CPF/Nome nao encontrada.", False

        if c.filmesReservados[nomeFilme]["DataAluguel"] == date.today():
            for nomeFilme in c.filmesReservados:
                dataDevolucao = date.fromordinal(
                    date.toordinal(dataAluguel) + len(c.filmesReservados)
                )  #Data na qual o DVD esta sendo alugado baseado na quantidade de filmes reservados

                if diaDevolucao == 6:
                    dataDevolucao = date.fromordinal(
                        date.toordinal(dataDevolucao) + 1)

                c.filmesAlugados[nomeFilme] = c.filmesReservados[nomeFilme]
                c.filmesAlugados[nomeFilme]["DataDevolucao"] = "%d-%d-%d" % (
                    dataDevolucao.date, dataDevolucao.month,
                    dataDevolucao.year)
            c.filmesReservados = {}
            return "Aluguel efetuado com exito", valor, True
        else:
            return "Filme reservado para o dia: ", c.filmesReservados[
                nomeFilme]["DataAluguel"], False
def animate_multiple(i, ax, db, lines, frame_dates, franchise_text_array):
    n = 0
    cur_animation_day = frame_dates[i]
    max_gross_to_date = -1
    for franchise_data in db:
        to_index = min(franchise_date_pointer_array[n],
                       len(franchise_data.gross_to_date_array) - 1)
        while cur_animation_day > franchise_data.date_array[to_index]:
            franchise_date_pointer_array[
                n] = franchise_date_pointer_array[n] + 1
        x = franchise_data.date_array[0:to_index]
        y = franchise_data.gross_to_date_array[0:to_index]
        max_y = max(y) if to_index > 0 else -1
        if max_y > max_gross_to_date:
            max_gross_to_date = max_y
        lines[n].set_data(x, y)
        if len(y) > 0:
            film_name = textwrap.wrap(
                franchise_data.film_name_array[to_index - 1], 14)
            franchise_text_array[n].set_text("\n".join(film_name))
            franchise_text_array[n].set_position((x[-1], y[-1] * 1.05))
            # adjust_text(franchise_text_array)
        n = n + 1
    x_from = date.toordinal(frame_dates[0]) - 10
    x_to = max(
        date.toordinal(frame_dates[0]) + 100,
        date.toordinal(frame_dates[i]) + 40)
    ax.set_xlim(x_from, x_to)
    ax.set_ylim(0, max(max_gross_to_date * 1.3, 0.7))
    ax = set_x_axis_locator(ax, x_from, x_to)
    ax.figure.canvas.draw()
    return lines
예제 #3
0
    def update_energy(self):
        self.power = self.ac_output_voltage * self.inverter_current  # power = ac output voltage * inverter sell current
        self.last_timestamp = self.current_timestamp
        self.current_timestamp = time.time()
        dt = self.current_timestamp - self.last_timestamp
        #print "{:03.1f}".format(dt)
        #print "sell current: %d" % self.sell_current
        #print "inverter current %d" % self.inverter_current
        #print "charge current %d" % self.charge_current

        self.energy = self.energy + (self.power *
                                     dt) / 3600 / 1000  # energy in kWH
        if self.host is not None:  # if we have a database to post to
            if self.date != date.toordinal(date.today()):
                con = mdb.connect(host=self.host,
                                  db=self.db,
                                  user=self.user,
                                  passwd=self.passwd)
                with con:
                    cur = con.cursor()
                    statement = "INSERT INTO daily(time,energy,sunny) VALUES (%s, %s, %s)"
                    cur.execute(statement,
                                (date.fromordinal(self.date), self.energy))
                    con.commit()
                    cur.close()
                con.close()
                self.date = date.toordinal(date.today())
                self.energy = 0
예제 #4
0
def count(total):
    zero = date(2011, 1, 16)
    then = date(2011, 12, 31)
    a_day = timedelta(1)
    ratio = find_ratio(
        date.toordinal(then) - date.toordinal(zero) + 2, total + 1)
    count = 0
    days = []
    increment = ratio
    for i in range(total + 1):
        days.append(increment)
        increment *= ratio
    intdays = []
    for i in range(total + 1):
        intdays.append(
            int(floor(sum(days[:i + 1]))) - int(floor(sum(days[:i]))))
    sortdays = sorted(intdays)
    sortdays.reverse()
    exercise_reps = {}
    the_day = zero
    interval = sortdays.pop()
    while the_day < then:
        the_day += a_day
        if date.toordinal(the_day) - date.toordinal(zero) >= interval:
            count += 1
            zero = the_day
            interval = sortdays.pop()
        exercise_reps[the_day] = count
    return exercise_reps
예제 #5
0
    def aluguelreserv(nomeCliente = None, cpfCliente = None):
        clientes = shelve.open("clientes.pyc") #Clientes eh o ARQUIVO

        for c in clientes:
            if clientes[c].nome == nomeCliente:
                if cpfCliente != None and clientes[c].cpf == cpfCliente:
                    c = clientes[c]
                    break
                else:
                    return "Erro! CPF nao especificado ou congruencia entre CPF/Nome nao encontrada.", False


        if c.filmesReservados[nomeFilme]["DataAluguel"] == date.today():
            for nomeFilme in c.filmesReservados:
                dataDevolucao = date.fromordinal(date.toordinal(dataAluguel)+len(c.filmesReservados)) #Data na qual o DVD esta sendo alugado baseado na quantidade de filmes reservados
               
                if diaDevolucao == 6:
                    dataDevolucao = date.fromordinal(date.toordinal(dataDevolucao)+1)
                    
                c.filmesAlugados[nomeFilme] = c.filmesReservados[nomeFilme]
                c.filmesAlugados[nomeFilme]["DataDevolucao"] = "%d-%d-%d" %(dataDevolucao.date,dataDevolucao.month,dataDevolucao.year)           
            c.filmesReservados = {}
            return "Aluguel efetuado com exito", valor, True 
        else:
            return "Filme reservado para o dia: ",c.filmesReservados[nomeFilme]["DataAluguel"], False
    def validar_entradas(self, dt_inicio, verbo, quantidade, unidade,
                         dt_limite):
        #VALIDAR SE AS DATAS SAO RAZOAVEIS
        dt_inicio = date.toordinal(dt_inicio)
        dt_limite = date.toordinal(dt_limite)
        if (dt_limite <= dt_inicio):
            return False

        if ((not verbo) or (not unidade) or (quantidade <= 0)):
            return False

        #PEGAR O PERIODO
        periodo = self.combo_periodo.currentText()
        #SE O PERIODO FOR dia, CHECAR SE PELO MENOS UM DIA ESTA ESCOLHIDO
        if ('diaria' in periodo):
            if (not (self.check_segunda.isChecked()
                     or self.check_terca.isChecked()
                     or self.check_quarta.isChecked()
                     or self.check_quinta.isChecked()
                     or self.check_sexta.isChecked()
                     or self.check_sabado.isChecked()
                     or self.check_domingo.isChecked())):
                return False

        return True
예제 #7
0
def datenum(t_vec):

    t_num = []

    for i in range(0, len(t_vec)):

        year = np.int(t_vec[i][0])
        mon = np.int(t_vec[i][1])
        day = np.int(t_vec[i][2])
        hrs = np.int(t_vec[i][3])
        mins = np.int(t_vec[i][4])
        secs = np.int(np.round(np.float(t_vec[i][5])))
        if secs == 60:
            secs = 0
            mins = mins + 1
            datestr = dt.datetime(year, mon, day, hrs, mins, secs)
            frac_datestr = (hrs + (mins + secs / 60) / 60) / 24
            serial_date = date.toordinal(datestr) + 366 + frac_datestr
        else:
            datestr = dt.datetime(year, mon, day, hrs, mins, secs)
            frac_datestr = (hrs + (mins + secs / 60) / 60) / 24
            serial_date = date.toordinal(datestr) + 366 + frac_datestr

        t_num.append(serial_date)
        # Subtract 366 since MATLAB has a preset date of 1-1-0000
        # and PYTHON has a preset date of 1-1-0001
    t_num = np.array(t_num)
    return t_num  #- 366
예제 #8
0
파일: NDBCdata.py 프로젝트: WEC-Sim/WDRT
def getDateNums(dateArr):
    '''datetime objects

    Parameters
    ----------
        dateArr : np.array
            Array of a specific years date vals from NDBC.fetchFromWeb

    Returns
    -------
        dateNum : np.array
            Array of datetime objects.
    '''
    dateNum = []
    for times in dateArr:
        if  times[0] < 1900:
            times[0] = 1900 + times[0]
        if times[0] < 2005:
            dateNum.append(date.toordinal(datetime(times[0], times[1],
                                                   times[2], times[3])))
        else:
            dateNum.append(date.toordinal(datetime(times[0], times[1],
                                                   times[2], times[3],
                                                   times[4])))
    return dateNum
예제 #9
0
def promotion_generation(current_amount, old_amount, category_args=0, menu_item_args=0):
	
	if(category_args==0):
		cursor.execute("SELECT count(id) FROM menu_category")
		category_amount=cursor.fetchone()[0]
	else:
		category_args=category_args.split(',')

	if(menu_item_args==0):	
		cursor.execute("SELECT count(id) FROM menu_item")
		item_amount=cursor.fetchone()[0]
	else:
		menu_item_args=menu_item_args.split(',')

	insert_promo=""
	for i in range(0, int(old_amount)):
		date_from = get_random_date(opening_date, date.today()-timedelta(days=1))
		date_to=get_random_date(opening_date, date.today()-timedelta(days=1))

		while(date.toordinal(date_from)>=date.toordinal(date_to)):
			date_from = get_random_date(opening_date, date.today()-timedelta(days=1))
			date_to=get_random_date(opening_date, date.today()-timedelta(days=1))
		date_to_str= "\'"+str(date_to)+"\'"
		if(category_args==0):
			category_id,menu_item_id = category_or_item(category_amount,item_amount)
		elif menu_item_args==0:
			category_id=int(random.choice(category_args))
			menu_item_id="NULL"
		else:
			category_id= int(random.choice(category_args))
			menu_item_id= int(random.choice(menu_item_args))
		date_to_str= "\'"+str(date_to)+"\'"
		insert_promo=insert_promo + "( "+"\'"+str(date_from)+"\'"+", "+date_to_str+", "+ str(category_id)+", "+str(menu_item_id)+", "+"\'No Terms\'"+", "+str(random.randint(1,50)/100)+"),"

	for i in range(0, int(current_amount)):
		date_from = get_random_date(opening_date, date.today())
		date_to_check=random.randint(0,9)

		if(date_to_check!=0):
			date_to=get_random_date(date.today(), date.today()+timedelta(days=365))
			date_to_str= "\'"+str(date_to)+"\'"
		else:
			date_to="NULL"

		if(category_args==0):
			category_id,menu_item_id = category_or_item(category_amount,item_amount)
		elif menu_item_args==0:
			category_id=int(random.choice(category_args))
			menu_item_id="NULL"
		else:
			category_id= int(random.choice(category_args))
			menu_item_id= int(random.choice(menu_item_args))
		insert_promo=insert_promo + "( "+"\'"+str(date_from)+"\'"+", "+date_to_str+", "+ str(category_id)+", "+str(menu_item_id)+", "+"\'No Terms\'"+", "+str(random.randint(1,50)/100)+"),"

	exec_str='INSERT INTO public.promotion (date_from, date_to, category_id, menu_item_id, terms, discount) VALUES {}'.format(insert_promo)
	cursor.execute(exec_str[:len(exec_str)-1])
예제 #10
0
    def test_load_files(self):
        self.__start_process()

        ps1_mat = scipy.io.loadmat(os.path.join(self._PATCH_1_FOLDER, 'ps1.mat'))
        # These are saved using Matlab 7.3
        ph1 = self.__load_mat73(os.path.join(self._PATCH_1_FOLDER, 'ph1.mat'), 'ph')
        bp1 = self.__load_mat73(os.path.join(self._PATCH_1_FOLDER, 'bp1.mat'), 'bperp_mat')
        da1 = self.__load_mat73(os.path.join(self._PATCH_1_FOLDER, 'da1.mat'), 'D_A')
        la1 = self.__load_mat73(os.path.join(self._PATCH_1_FOLDER, 'la1.mat'), 'la')
        hgt1 = self.__load_mat73(os.path.join(self._PATCH_1_FOLDER, 'hgt1.mat'), 'hgt')

        self.assertEqual(len(self._ps_files.bperp), len(bp1))
        np.testing.assert_allclose(self._ps_files.bperp, bp1)

        self.assertEqual(len(self._ps_files.da), len(da1))
        # Loadmat results are array of arrays
        np.testing.assert_allclose(np.reshape(self._ps_files.da, (len(self._ps_files.da), 1)), da1)

        ps1_mat_bperp = np.reshape(ps1_mat['bperp'], len(ps1_mat['bperp']))
        np.testing.assert_allclose(self._ps_files.bperp_meaned, ps1_mat_bperp)
        np.testing.assert_allclose(self._ps_files.pscands_ij.view(np.ndarray), ps1_mat['ij'])
        # In our process there isn't first column. That's why we take last two
        np.testing.assert_allclose(self._ps_files.xy, ps1_mat['xy'][:, 1:])

        self.assertAlmostEqual(self._ps_files.mean_range, ps1_mat['mean_range'])

        np.testing.assert_allclose(self._ps_files.mean_incidence.view(np.ndarray),
                                   ps1_mat['mean_incidence'])

        np.testing.assert_allclose(self._ps_files.ll, ps1_mat['ll0'])

        np.testing.assert_allclose(self._ps_files.lonlat, ps1_mat['lonlat'])

        # Because those values aren't added to .mat files so we can only check if these are filled
        self.assertNotEqual(self._ps_files.wavelength, 0)
        self.assertIsNotNone(self._ps_files.heading)

        master_date_days = date.toordinal(self._ps_files.master_date) + 366
        self.assertEqual(master_date_days, ps1_mat['master_day'][0])
        self.assertEqual(self._ps_files.master_nr, ps1_mat['master_ix'])

        ifg_date_days = ArrayUtils.to_col_matrix(
            np.array([date.toordinal(x) + 366 for x in self._ps_files.ifg_dates]))
        np.testing.assert_array_equal(ifg_date_days, ps1_mat['day'])

        np.testing.assert_allclose(self._ps_files.sort_ind.view(np.ndarray), la1)

        self.assertEqual(len(self._ps_files.ifgs), ps1_mat['n_ifg'])

        self.assertEqual(len(self._ps_files.pscands_ij), ps1_mat['n_ps'])

        # hgt1 is array of arrays, need to reshape
        np.testing.assert_allclose(self._ps_files.hgt, np.reshape(hgt1, len(hgt1)))

        self.assertEqual(len(self._ps_files.ph), len(ph1))
        self.assert_ph(self._ps_files.ph, ph1)
def tsregplot(series, ax=None, days_forward=10, color='C0'):
    '''
    A fucntion that makes requests to the wikimedia pagecveiws API

    Parameters
    ----------
    series : Pandas datetime index Series
    A pandas Series with datetime index

    ax : matplotlib axes object
    A matplotlib axes obect

    days_forward : int
    An integer indicating how many days to extend the regression line

    color : string
    A matplotlib color string

    Returns
    -------
    ax : matplotlib axes object
    returns a matplotlib axes object with regplot
    '''

    series = series.reset_index()
    series.columns = ['date', 'value']
    if ax == None:
        series['date_ordinal'] = pd.to_datetime(
            series['date']).apply(lambda date: date.toordinal())
        ax = sns.regplot(data=series, x='date_ordinal', y='value', color=color)
        ax.set_xlim(series['date_ordinal'].min() - 2,
                    series['date_ordinal'].max() + days_forward)
        ax.set_ylim(series['value'].min() * 0.9, series['value'].max() * 1.1)
        ax.set_xlabel('date')
        new_labels = [date.fromordinal(int(item)) for item in ax.get_xticks()]
        ax.set_xticklabels(new_labels)
    else:
        series['date_ordinal'] = pd.to_datetime(
            series['date']).apply(lambda date: date.toordinal())
        ax = sns.regplot(data=series,
                         x='date_ordinal',
                         y='value',
                         ax=ax,
                         color=color)

        ax.set_xlim(series['date_ordinal'].min() - 5,
                    series['date_ordinal'].max() + days_forward)
        ax.set_ylim(series['value'].min() * 0.9, series['value'].max() * 1.1)
        ax.set_xlabel('date')
        new_labels = [
            date.fromordinal(int(item)).strftime("%m/%Y")
            for item in ax.get_xticks()
        ]
        ax.set_xticklabels(new_labels)
        return ax
예제 #12
0
    def aluguel(self,
                CarrinhodeCompras=None,
                nomeCliente=None,
                cpfCliente=None):
        if CarrinhodeCompras == None:
            return "Erro! Produtos não especificados", False
        if len(CarrinhodeCompras) == 0:
            wx.MessageBox("Erro! Nenhum produto selecionado")
        #Verifica se o usuario preencheu a forma de pagamento

        filmes = shelve.open("filmes")
        clientes = shelve.open("clientes")  #Clientes eh o ARQUIVO

        if clientes.has_key(nomeCliente.upper()):
            if cpfCliente != None and clientes[c].cpf == cpfCliente:
                c = clientes[c]
            else:
                wx.MessageBox(
                    "Erro! CPF nao especificado ou congruencia entre CPF/Nome nao encontrada."
                )
                return
        valor = self.TotalPagar(CarrinhodeCompras)
        if len(CarrinhodeCompras) > 0:
            dataAluguel = date.today()
            dataDevolucao = date.fromordinal(
                date.toordinal(dataAluguel) +
                len(CarrinhodeCompras))  #Data na qual o DVD esta sendo alugado
            diaDevolucao = dataDevolucao.weekday()

            if diaDevolucao == 6:
                dataDevolucao = date.fromordinal(
                    date.toordinal(dataDevolucao) + 1)

            for prod in CarrinhodeCompras:
                if filmes[prod.titulo].qtd != 0:
                    filmes[prod.titulo].quantidade -= 1
                    filmeAlugar = filmes[prod.titulo]
                    del filmeAlugar.quantidade
                    filmeAlugar.dataAluguel = "%d-%d-%d" % (
                        dataAluguel.day, dataAluguel.month, dataAluguel.year)
                    filmeAlugar.dataDevolucao = "%d-%d-%d" % (
                        dataDevolucao.day, dataDevolucao.month,
                        dataDevolucao.year)
                    c.filmesAlugados[filmeAlugar.titulo] = filmeAlugar
                    c.situacao = "DEBITO"
                    c.debito += valor
            wx.MessageBox(
                "Aluguel efetuado com exito. Valor a ser pago: %.2f" % (valor))

        else:
            wx.MessageBox(
                "Nenhum Filme selecionado esta disponível no estoque!")
예제 #13
0
    def reserva(CarrinhodeCompras=None,
                nomeCliente=None,
                cpfCliente=None,
                diasparaalugar=None):
        if CarrinhodeCompras == None:
            return "Erro! Produtos não especificados", False
        if len(CarrinhodeCompras) == 0:
            return "Erro! Nenhum produto selecionado", False
        if len(CarrinhodeCompras) > 4:
            return "Erro! Só podem ser reservados ate quatro filmes", False
        #Verifica se o usuario preencheu a forma de pagamento
        filmes = shelve.open("filmes")
        clientes = shelve.open("clientes")  #Clientes eh o ARQUIVO

        for c in clientes:
            if clientes[c].nome == nomeCliente:
                if cpfCliente != None and clientes[c].cpf == cpfCliente:
                    c = clientes[c]
                    break
                else:
                    return "Erro! CPF nao especificado ou congruencia entre CPF/Nome nao encontrada.", False

        valor = conta(CarrinhodeCompras=None)
        if len(CarrinhodeCompras) > 0:
            today = date.today()
            dataAluguel = date.fromordinal(
                date.toordinal(today) +
                diasparaalugar)  #Data na qual o DVD esta sendo alugado
            diaAluguel = dataDevolucao.weekday()

            if diaAluguel == 6:
                dataAluguel = date.fromordinal(
                    date.toordinal(dataDevolucao) + 1)

            for nomefilme in CarrinhodeCompras:
                if filmes[nomeFilme].qtd != 0:
                    filmes[nomeFilme].qtd -= 1
                    files[nomeFilme].reservados += 1
                    c.filmesReservados[nomeFilme] = {
                        filmeReservar.titulo:
                        filmeResevar,
                        "DataAluguel":
                        "%d-%d-%d" % (dataAluguel.date, dataAluguel.month,
                                      dataAluguel.year),
                        "Situação":
                        "Pendente, devendo R$%.2f" % (valor)
                    }
                    c.debito += valor
            return "Reserva efetuada com exito. Valor a ser pago: ", valor, True

        else:
            return "Nenhum Filme selecionado esta disponível para reserva!", False
예제 #14
0
    def get_daf_yomi_bavli(self):
        """Return tuple of Mesechta number and Daf of the days Daf Yomi"""
        #The number of daf per masechta. Since the number of blatt in Shekalim changed on the 8th
        # Daf Yomi cycle beginning on June 24, 1975 from 13 to 22, the actual calculation for
        # blattPerMasechta[4] will later be adjusted based on the cycle.
        blatt_per_masechta = [
            64, 157, 105, 121, 22, 88, 56, 40, 35, 31, 32, 29, 27, 122, 112,
            91, 66, 49, 90, 82, 119, 119, 176, 113, 24, 49, 76, 14, 120, 110,
            142, 61, 34, 34, 28, 22, 4, 10, 4, 73
        ]
        date = self.dt
        cycle_num = 0
        daf_num = 0
        if date < DAF_YOMI_START_DATE:
            # TODO: should we return a null or throw an IllegalArgumentException?
            return None
            # raise IllegalArgumentException(date +
            #    " is prior to organized Daf Yomi Bavli cycles that started on "
            #        + DAF_YOMI_START_DATE)
        if date >= SHEKALIM_CHANGE_DATE:
            cycle_num, daf_num = divmod(
                date.toordinal() - datetime(1975, 6, 24).toordinal(), 2711)
            cycle_num += 8
        else:
            cycle_num, daf_num = divmod(
                date.toordinal() - datetime(1923, 9, 11).toordinal(), 2702)
            cycle_num += 1
        total = 0
        masechta = -1
        blatt = 0

        if cycle_num <= 7:  # Fix Shekalim for old cycles.
            blatt_per_masechta[4] = 13
        else:
            blatt_per_masechta[4] = 22
        for j in range(0, len(blatt_per_masechta)):  # Finally find the daf.
            masechta += 1  #why is this necesar - isnt it the same as j
            total = total + blatt_per_masechta[j] - 1
            if daf_num < total:
                blatt = 1 + blatt_per_masechta[j] - (total - daf_num)
                # Fiddle with the weird ones near the end.
                if masechta == 36:
                    blatt += 21
                elif masechta == 37:
                    blatt += 24
                elif masechta == 38:
                    blatt += 33
                return masechta, blatt
예제 #15
0
    def _pkg_upgradable(self, pn, next_ver, maintainer):
        if not maintainer:
            D(" Skipping upgrade of %s: no maintainer" % pn)
            return False

        if "blacklist" in settings:
            for p in settings["blacklist"].split():
                if p == pn:
                    D(" Skipping upgrade of %s: blacklist" % pn)
                    return False

        if "maintainers_whitelist" in settings:
            found = False
            for m in settings["maintainers_whitelist"].split():
                if maintainer.find(m) != -1:
                    found = True
                    break

            if found == False:
                D(" Skipping upgrade of %s: maintainer \"%s\" not in whitelist"
                  % (pn, maintainer))
                return False

        if pn in self.history:
            # did we already try this version?
            if next_ver == self.history[pn][0]:
                retry_delta = \
                    date.toordinal(date.today()) - \
                    date.toordinal(datetime.strptime(self.history[pn][2], '%Y-%m-%d'))
                # retry recipes that had fetch errors or other errors after
                # more than 30 days
                if (self.history[pn][3] == str(FetchError())
                        or self.history[pn][3] == str(
                            Error())) and retry_delta > 30:
                    return True

                D(" Skipping upgrade of %s: is in history and not 30 days passed"
                  % pn)
                return False

        # drop native/cross/cross-canadian recipes. We deal with native
        # when upgrading the main recipe but we keep away of cross* pkgs...
        # for now
        if pn.find("cross") != -1 or pn.find("native") != -1:
            D(" Skipping upgrade of %s: is cross or native" % pn)
            return False

        return True
예제 #16
0
def swe_calc(Y,M,D,H,LAT,LON):
    #Interpolate temp to input
    f_td = interp2d(ln, la, td, kind='cubic')
    TD = f_td(LON, LAT)
    #Interpolate temp to input
    f_ppt = interp2d(ln, la, pptwt, kind='cubic')
    PPTWT = f_ppt(LON, LAT)
    #Determine day of year
    DOY = date.toordinal(date(Y,M,D))-date.toordinal(date(Y,9,30))
    if DOY < 0:
        DOY = DOY+365
    #Apply regression equation 
    a = [0.0533,0.948,0.1701,-0.1314,0.2922] #accumulation phase
    b = [0.0481,1.0395,0.1699,-0.0461,0.1804]; #ablation phase
    SWE = a[0]*H**a[1]*PPTWT**a[2]*TD**a[3]*DOY**a[4]*     (-np.tanh(.01*(DOY-180))+1)/2 + b[0]*H**b[1]*     PPTWT**b[2]*TD**b[3]*DOY**b[4] * (np.tanh(.01*(DOY-180))+1)/2;
    return SWE,DOY
예제 #17
0
	def _calc_historical_200_day_sma(self,symbol):
		retArray = [];
		prArray = [];
		today = date.today()
		enddate = today.strftime("%Y%m%d")
		today_ordinal = date.toordinal(today)
		start_ordinal = today_ordinal - 380;
		startdate = (date.fromordinal(start_ordinal)).strftime("%Y%m%d")
		#print startdate 
		#print enddate 
		retArray.append(symbol)
		prArray.append(symbol)
		xx = yahoostock.get_historical_prices(symbol,startdate,enddate)
		#print xx
		#print xx[1]

		for i in range (1,241):
		    #print "%d" % (i)
		    #print xx[i]
	    	    x2 = xx[i];
	    	    prArray.append(x2[1])
	
		for i in range (1,self.numSma+1):
	    	    sma = 0.0
	    	    for mm in range (i,i+200):
			sma += float(prArray[mm]);
	    	    sma = sma / 200.0
	    	    retArray.append(sma)

		return [retArray, prArray]
예제 #18
0
def date2num(dtime):
    """
    Covert datetime to number
    :type dtime: datetime
    :rtype: int
    """
    return date.toordinal(dtime)
예제 #19
0
    def _calc_historical_200_day_sma(self,symbol):
        retArray = [];
        prArray = [];
        today = date.today()
        enddate = today.strftime("%Y%m%d")
        today_ordinal = date.toordinal(today)
        start_ordinal = today_ordinal - 380;
        startdate = (date.fromordinal(start_ordinal)).strftime("%Y%m%d")
        #print startdate 
        #print enddate 
        retArray.append(symbol)
        prArray.append(symbol)
        xx = yahoostock.get_historical_prices(symbol,startdate,enddate)

        for i in range (1,241):
            x2 = xx[i];
            prArray.append(x2[4])
    
        for i in range (1,self.numSma+1):
            sma = 0.0
            for mm in range (i,i+200):
                sma += float(prArray[mm]);
            sma = sma / 200.0
            retArray.append(sma)

        return [retArray, prArray]
예제 #20
0
파일: test_csv.py 프로젝트: tarakparikh/sma
def open_writer():
    today = date.today()
    today_ordinal = date.toordinal(today)
    fname = "stocks." + "%s" % (today_ordinal) + ".csv"
    print fname
    writer = csv.writer(open(fname, 'wb', buffering=0))
    return writer
예제 #21
0
 def NextRequisitionDay(cls, InputName):
     df_filterByValue = df_extracted[
         df_extracted['StationeryName'].str.match(InputName)]
     df_filterByValue['Cumulative_RQ'] = df_filterByValue[
         'RequisitionQuantity'].cumsum(axis=0)
     df_filterByValue['Dates_ordinal'] = df_filterByValue['Dates'].apply(
         lambda date: date.toordinal())
     latest_requisition_quantity = df_filterByValue.iloc[-1, 8]
     latest_requisition_date = df_filterByValue.iloc[-1, 9]
     estimate_next_requisition = latest_requisition_date
     X = df_filterByValue[['Dates_ordinal']]
     y = df_filterByValue['Cumulative_RQ']
     X_train, X_test, y_train, y_test = train_test_split(X,
                                                         y,
                                                         random_state=0)
     linReg = LinearRegression()
     linReg.fit(X_train, y_train)
     current_requisition_quantity = linReg.predict(
         [[estimate_next_requisition]])
     if (current_requisition_quantity <= latest_requisition_quantity):
         while (current_requisition_quantity <=
                latest_requisition_quantity):
             estimate_next_requisition = estimate_next_requisition + 1
             current_requisition_quantity = linReg.predict(
                 [[estimate_next_requisition]])
         return date.fromordinal(estimate_next_requisition)
     else:
         return 'You should receive requisition by Now!'
예제 #22
0
 def fromdate(cls, date, correlation=None):
     c = cls.correlation if correlation is None else correlation
     d = date.toordinal() + 1721425 - int(c)
     self = cls.fromordinal(d)
     if correlation is not None:
         self.correlation = correlation
     return self
예제 #23
0
def full_id(file_name):
    """
    This function returns a row vector ['EYE_ID' 'ScanPos' 'year' 'month' 'day' ] for an input file

    :param file_name: file name of scan for which ID is wanted
    :return: see description
    :rtype: (1, 5) array
    """

    # Get the all information about the input vol file
    oct_info_id = OCT_read.OctRead(file_name)

    # Get the header of the input vol file
    header_id = oct_info_id.get_oct_hdr()

    # Scan position
    scan_pos = str(header_id['ScanPosition'])
    scan_pos_input = scan_pos[2:4]

    # EYE ID
    eye_id = int(str(header_id['PatientID'])[5:10])

    eye_id_scan_pos = np.vstack((eye_id, scan_pos_input)).T

    # Scan time
    loc_val = header_id['ExamTime'] / (1e7 * 60 * 60 * 24) + date.toordinal(
        date(1601, 1, 1))
    date_exam = datetime.datetime.fromordinal(int(loc_val))
    time_vector = np.array([date_exam.year, date_exam.month,
                            date_exam.day]).reshape(1, -1)

    # creating id vector
    scan_full_id = np.concatenate((eye_id_scan_pos, time_vector), axis=1)

    return scan_full_id
예제 #24
0
    def handle(self, *args, **options):
        _fields_to_update = ["Joomla Paid Count"]
        joomla = JoomlaInterface(settings.JOOMLA_USER, settings.JOOMLA_PASSWORD)
        joomla.authenticate()

        if options['year']:
            year = options['year']
            month = options['month']
            _start_date = date(year, month, 1)
            _end_date = date.fromordinal(date(year, month + 1, 1).toordinal() - 1)
            _schedules = ProgramSchedule.objects.filter(start_date__gte=_start_date,
                                                        end_date__lte=_end_date)
        else:
            reference_date = date.fromordinal(date.toordinal(date.today()) - 50)
            _schedules = ProgramSchedule.objects.filter(start_date__gte=reference_date)


        for each_schedule in _schedules:
            if not each_schedule.online_registration_code:
                continue

            if each_schedule.online_registration_code.startswith("FAILED"):
                continue

            print(each_schedule)

            paid_count = joomla.get_paid_count(each_schedule.online_registration_code)
            print("%d paid for %s" % (paid_count, each_schedule.online_registration_code))

            _create_or_update(_fields_to_update, (paid_count,), each_schedule)
예제 #25
0
def _fetch_historical_200_day_ema(symbol):
	retArray = [];
	retArray.append(symbol)
	today = date.today()
	enddate = today.strftime("%Y%m%d")
	today_ordinal = date.toordinal(today)
	start_ordinal = today_ordinal - 60;
	startdate = (date.fromordinal(start_ordinal)).strftime("%Y%m%d")
	#print startdate 
	#print enddate 
	ema = float(_fetch_200_day_sma(symbol));
	retArray.append(ema)
	xx = yahoostock.get_historical_prices(symbol,startdate,enddate)
	mult = 0.004975
	one_minus_mult = 1 - float(mult);

	for i in range (1,30):
	    x2 = xx[i];
	    price = float (x2[1]);
	    print ema,price,mult,one_minus_mult
	    newema = (ema - price*mult)/one_minus_mult;
	    retArray.append(newema)
	    ema = newema

	return retArray
예제 #26
0
파일: area3.py 프로젝트: 1425/parts
def main():
    p = ArgumentParser()
    p.add_argument('-o', '--out')
    p.add_argument('--input', action='store_true')
    args = p.parse_args()
    if args.out:
        output = open(args.out, 'w')
    else:
        output = sys.stdout

    if args.input:
        f = get_stdin()
        title, xlabel, ylabel, labels, data = parse_din(f)

        #print 'labels:',labels
        #print data
        def get_col(i):
            return map(lambda x: x[i], data)

        x = get_col(0)
        #print 'x:',x
        y = map(get_col, range(1, len(data[0])))
    else:
        # just create some random data
        fnx = lambda: NP.random.randint(3, 10, 10)
        y = NP.row_stack((fnx(), fnx(), fnx()))
        x = map(lambda x: date.toordinal(date(2019, 3, x)), range(2, 12))
        labels = 'abc'
        title = 'Demo title'
        xlabel = 'xlabel'
        ylabel = 'ylabel'
    plot(output, title, xlabel, ylabel, y, x, labels=labels)
예제 #27
0
def _calc_historical_200_day_sma(symbol):
    retArray = []
    priceArray = []
    today = date.today()
    enddate = today.strftime("%Y%m%d")
    today_ordinal = date.toordinal(today)
    start_ordinal = today_ordinal - 350
    startdate = (date.fromordinal(start_ordinal)).strftime("%Y%m%d")
    #print startdate
    #print enddate
    retArray.append(symbol)
    priceArray.append(symbol)
    xx = yahoostock.get_historical_prices(symbol, startdate, enddate)
    for i in range(1, 241):
        x2 = xx[i]
        priceArray.append(x2[1])

    for i in range(1, 30):
        sma = 0.0
        for mm in (i, i + 200):
            sma += float(priceArray[i])
        sma = sma / 200
        retArray.append(sma)

    return [retArray, priceArray]
예제 #28
0
def write_daily_values(dbname, data):
    print "WRITE DAILY CALLED"
    open_writer()
    sqconn = sqlite3.connect("mystk.db")
    today = date.today()
    today_ordinal = date.toordinal(today)
    if (_check_if_today_written(today_ordinal)):
        #
        #  Today is written. Update values
        #
        my_type_arr_2 = tuple(
            [tuple([row[1], today_ordinal, row[0]]) for row in data])
        my_query_str = "UPDATE " + dbname + " SET VAL = ? WHERE DATEVAL=? AND SYMBOL=?"
        sqconn.executemany(my_query_str, my_type_arr_2)
    else:
        #
        # Insert new values
        #
        my_type_arr_2 = tuple(
            [tuple([today_ordinal, row[0], row[1]]) for row in data])
        my_query_str = "INSERT INTO " + dbname + "(DATEVAL,SYMBOL,VAL) VALUES (?, ?, ?)"
        sqconn.executemany(my_query_str, my_type_arr_2)

    sqconn.commit()
    sqconn.close()
예제 #29
0
파일: db_util.py 프로젝트: tarakparikh/sma
def open_writer(dbname):
    today = date.today()
    today_ordinal = date.toordinal(today)
    fname = "db/stocks." + dbname + "." + "%s" % (today_ordinal) + ".csv"
    print fname
    writer = csv.writer(open(fname, 'wb', buffering=0))
    return writer
예제 #30
0
def get_indexes(date=date.today()):
    day = timedelta(days=1)
    date = date - 1*day
    strdate = date.strftime("%d%m%Y")
    params = urllib.urlencode({'saida': 'csv', 'Idioma': 'PT', 'Dt_ref': strdate})
    headers = {
        "Content-type": "application/x-www-form-urlencoded",
        "Accept": "text/plain"
    }
    conn = httplib.HTTPConnection("www.anbima.com.br")
    conn.request("POST", "/ima/IMA-geral-down.asp", params, headers)
    response = conn.getresponse()
    body = response.read()
    conn.close()
    raw_indexes = body.splitlines()
    indexes = {}
    if len(raw_indexes) < 3:
        return indexes
    for idx in raw_indexes[2:]:
        idx_parts = idx.split(';')
        key = " ".join(idx_parts[0:2])
        indexes[key] = {
            "date":  datetime.datetime.fromordinal(date.toordinal()),
            "value": float(idx_parts[3].replace(".", "").replace(",", "."))
        }
    return indexes
예제 #31
0
 def EstimateRequisitionQuantity(cls, InputYear, InputMonth, InputDay,
                                 InputName):
     df_filterByValue = df_extracted[
         df_extracted['StationeryName'].str.match(InputName)]
     df_filterByValue['Cumulative_RQ'] = df_filterByValue[
         'RequisitionQuantity'].cumsum(axis=0)
     df_filterByValue['Dates_ordinal'] = df_filterByValue['Dates'].apply(
         lambda date: date.toordinal())
     input_date = date(InputYear, InputMonth, InputDay)
     input_date_ordinal = input_date.toordinal()
     X = df_filterByValue[['Dates_ordinal']]
     y = df_filterByValue['Cumulative_RQ']
     X_train, X_test, y_train, y_test = train_test_split(X,
                                                         y,
                                                         random_state=0)
     linReg = LinearRegression()
     linReg.fit(X_train, y_train)
     requisition_quantity_prediction = linReg.predict([[input_date_ordinal]
                                                       ])
     quantity_difference = requisition_quantity_prediction - df_filterByValue.iloc[
         -1, 8]
     requisition_msg_1 = 'May not receive ANY requisition by this date!'
     requisition_msg_2 = 'Estimated requisition quantity: '
     if (quantity_difference > 0):
         return requisition_msg_2 + str(int(quantity_difference))
     else:
         return requisition_msg_1
예제 #32
0
파일: test_csv.py 프로젝트: tarakparikh/sma
def open_writer():
    today = date.today()
    today_ordinal = date.toordinal(today)
    fname = "stocks." + "%s" % (today_ordinal) + ".csv"
    print fname
    writer = csv.writer(open(fname, "wb", buffering=0))
    return writer
예제 #33
0
def _fetch_historical_200_day_ema(symbol):
    retArray = []
    retArray.append(symbol)
    today = date.today()
    enddate = today.strftime("%Y%m%d")
    today_ordinal = date.toordinal(today)
    start_ordinal = today_ordinal - 60
    startdate = (date.fromordinal(start_ordinal)).strftime("%Y%m%d")
    #print startdate
    #print enddate
    ema = float(_fetch_200_day_sma(symbol))
    retArray.append(ema)
    xx = yahoostock.get_historical_prices(symbol, startdate, enddate)
    mult = 0.004975
    one_minus_mult = 1 - float(mult)

    for i in range(1, 30):
        x2 = xx[i]
        price = float(x2[1])
        print ema, price, mult, one_minus_mult
        newema = (ema - price * mult) / one_minus_mult
        retArray.append(newema)
        ema = newema

    return retArray
예제 #34
0
    def _pkg_upgradable(self, pn, next_ver, maintainer):
        if not maintainer:
            D(" Skipping upgrade of %s: no maintainer" % pn)
            return False

        if "blacklist" in settings:
            for p in settings["blacklist"].split():
                if p == pn:
                    D(" Skipping upgrade of %s: blacklist" % pn)
                    return False

        if "maintainers_whitelist" in settings:
            found = False
            for m in settings["maintainers_whitelist"].split():
                if maintainer.find(m) != -1:
                    found = True
                    break

            if found == False:
                D(" Skipping upgrade of %s: maintainer \"%s\" not in whitelist" %
                        (pn, maintainer))
                return False

        if pn in self.history:
            # did we already try this version?
            if next_ver == self.history[pn][0]:
                retry_delta = \
                    date.toordinal(date.today()) - \
                    date.toordinal(datetime.strptime(self.history[pn][2], '%Y-%m-%d'))
                # retry recipes that had fetch errors or other errors after
                # more than 30 days
                if (self.history[pn][3] == str(FetchError()) or
                        self.history[pn][3] == str(Error())) and retry_delta > 30:
                    return True

                D(" Skipping upgrade of %s: is in history and not 30 days passed" % pn)
                return False

        # drop native/cross/cross-canadian recipes. We deal with native
        # when upgrading the main recipe but we keep away of cross* pkgs...
        # for now
        if pn.find("cross") != -1 or pn.find("native") != -1:
            D(" Skipping upgrade of %s: is cross or native" % pn)
            return False

        return True
예제 #35
0
def open_writer():
    sqconn = sqlite3.connect("mystk.db");
    today = date.today()
    today_ordinal = date.toordinal(today)
    my_query_str = "UPDATE DATETABLE SET TODAY = %d WHERE ID=1" % today_ordinal;
    sqconn.execute(my_query_str);
    sqconn.commit()
    sqconn.close();
예제 #36
0
def open_writer():
    sqconn = sqlite3.connect("mystk.db")
    today = date.today()
    today_ordinal = date.toordinal(today)
    my_query_str = "UPDATE DATETABLE SET TODAY = %d WHERE ID=1" % today_ordinal
    sqconn.execute(my_query_str)
    sqconn.commit()
    sqconn.close()
예제 #37
0
    def get(self):
        lastDate = date.fromordinal(date.toordinal(date.today()) - 180)

        casos = requests.get(
            f'https://api.covid19api.com/total/country/brazil?from={lastDate}T00:00:00Z&to={date.today()}T00:00:00Z'
        )

        return casos.json()
예제 #38
0
def _fetch_historical_data(symbol,days):
	today = date.today()
	enddate = today.strftime("%Y%m%d")
	today_ordinal = date.toordinal(today)
	start_ordinal = today_ordinal - days;
	startdate = (date.fromordinal(start_ordinal)).strftime("%Y%m%d")
	retArray = yahoostock.get_historical_prices(symbol,startdate,enddate)
	return retArray
예제 #39
0
 def __init__(self, url):
     self.url = url
     self.content = pdc.open_url(url, output_grid=False)
     self.day = int(url.split('/')[-1].split('.')[2].split('-')[0][7:9])
     self.month = int(url.split('/')[-1].split('.')[2].split('-')[0][5:7])
     self.year = int(url.split('/')[-1].split('.')[2].split('-')[0][1:5])
     self.dayOfYear = int(url.split('/')[9])
     self.datenum = date.toordinal(date(self.year, self.month,
                                        self.day)) + 366
예제 #40
0
 def mass_update_ordered_on(self, date, order_product_ids):
     with self.dbquery() as cur:
         sql = """
             UPDATE order_products
             SET ordered_on = ?
             WHERE id IN (%s)
         """ % ",".join("?"*len(order_product_ids))
         cur.execute(sql, (date.toordinal(),) + tuple(order_product_ids))
         return cur.rowcount
예제 #41
0
 def mass_update_ordered_on(self, date, order_product_ids):
     with self.dbquery() as cur:
         sql = """
             UPDATE order_products
             SET ordered_on = ?
             WHERE id IN (%s)
         """ % ",".join("?" * len(order_product_ids))
         cur.execute(sql, (date.toordinal(), ) + tuple(order_product_ids))
         return cur.rowcount
예제 #42
0
파일: db_util.py 프로젝트: tarakparikh/sma
def check_update(dbname):
    today = date.today()
    dbFound = 0
    today_ordinal = date.toordinal(today)
    fname = "db/stocks."  + dbname + "." + "%s" % (today_ordinal) + ".csv"
    if os.path.isfile(fname):
	    dbFound = 1

    return dbFound
예제 #43
0
파일: util.py 프로젝트: junqueira/routing
def dif_date(day, date=None):
    """
    :param day:
    :param date:
    :return: diferents day in date
    """
    if date is None: date = datetime.today().date()
    day = date.toordinal() + day
    return date.fromordinal(day)
예제 #44
0
파일: bootstrap.py 프로젝트: ANB2/FBox
 def __init__(self,date,instruments,interpolation,debug):
     self.inst = instruments
     self.date = date
     self.interpolation = interpolation
     self.debug = debug
     
     self.fixings = array( [date.toordinal()] + [inst.maturity_date.toordinal() for inst in instruments] )
     self.discounts = ones( len(self.fixings) )
     self.df = None
예제 #45
0
def count_days_month(year, month):
    from datetime import date

# mês inicial
    first_date = date(int(year), int(month), 1)
    ord_first_date = date.toordinal(first_date)

# mês seguinte
    if month == '12':
        last_date = date(int(year) + 1, 1, 1)   # Próximo ano, mês 1
    else:
        last_date = date(int(year), int(month) + 1, 1) # Mesmo ano, Próximo mês

    ord_last_date = date.toordinal(last_date)

    days_month = ord_last_date- ord_first_date

    return days_month
예제 #46
0
 def find_all_not_ordered_before(self, date):
     with self.dbquery() as cur:
         sql = """
             SELECT * FROM order_products
             WHERE ordered_on < ? AND
                   isordered = ?
             ORDER BY created_at ASC
         """
         cur.execute(sql, (date.toordinal(), 0))
         return cur.fetchall()
예제 #47
0
def trataData(data, parcela):
    ano = int(data[0:4])
    mes = int(data[5:7])
    dia = int(data[8:10])
    dataInformada = date(ano, mes, dia)
    if (parcela == 1):
        novaData = dataInformada
    else:
        qtdDiasAcrescentados = (parcela - 1) * 30
        novaDataIntermediaria = \
            date.fromordinal(date.toordinal(dataInformada) +
                             qtdDiasAcrescentados)
        if (novaDataIntermediaria.day == 28):
            novaDataIntermediaria = \
                date.fromordinal(date.toordinal(dataInformada) +
                                 qtdDiasAcrescentados + 3)
            novaData = date(novaDataIntermediaria.year,
                            novaDataIntermediaria.month, dia)
        elif (novaDataIntermediaria.day == 29):
            novaDataIntermediaria = \
                date.fromordinal(date.toordinal(dataInformada) +
                                 qtdDiasAcrescentados + 3)
            novaData = date(novaDataIntermediaria.year,
                            novaDataIntermediaria.month, dia)
        elif (novaDataIntermediaria.day == 30):
            novaDataIntermediaria = \
                date.fromordinal(date.toordinal(dataInformada) +
                                 qtdDiasAcrescentados + 2)
            novaData = date(novaDataIntermediaria.year,
                            novaDataIntermediaria.month, dia)
        elif (novaDataIntermediaria.day == 31):
            novaDataIntermediaria = \
                date.fromordinal(date.toordinal(dataInformada) +
                                 qtdDiasAcrescentados + 1)
            novaData = date(novaDataIntermediaria.year,
                            novaDataIntermediaria.month, dia)
        else:
            novaData = date(novaDataIntermediaria.year,
                            novaDataIntermediaria.month, dia)
        qtdDiasAcrescentados = 0
    return novaData
예제 #48
0
파일: test_csv.py 프로젝트: tarakparikh/sma
def open_reader():
    today = date.today()
    notOpen = 1
    today_ordinal = date.toordinal(today)
    while notOpen:
        today_ordinal -= 1
        fname = "stocks." + "%s" % (today_ordinal) + ".csv"
        if os.path.isfile(fname):
            stocks = csv.reader(open(fname, "rb"))
            notOpen = 0

    return stocks
예제 #49
0
파일: db_util.py 프로젝트: tarakparikh/sma
def open_reader(dbname):
    today = date.today()
    notOpen = 1
    today_ordinal = date.toordinal(today)
    while notOpen:
        fname = "db/stocks."  + dbname + "." + "%s" % (today_ordinal) + ".csv"
	if os.path.isfile(fname):
            stocks = csv.reader(open(fname, 'rb'))
	    notOpen = 0
        today_ordinal -= 1

    return stocks
예제 #50
0
    def aluguel(self,CarrinhodeCompras = None, nomeCliente = None, cpfCliente = None):
        if CarrinhodeCompras == None:
            return "Erro! Produtos não especificados",False
        if len(CarrinhodeCompras) == 0:
            wx.MessageBox("Erro! Nenhum produto selecionado")
        #Verifica se o usuario preencheu a forma de pagamento
        
        filmes = shelve.open("filmes")
        clientes = shelve.open("clientes") #Clientes eh o ARQUIVO

        if clientes.has_key(nomeCliente.upper()):
            if cpfCliente != None and clientes[c].cpf == cpfCliente:
                c = clientes[c]
            else:
                wx.MessageBox("Erro! CPF nao especificado ou congruencia entre CPF/Nome nao encontrada.")
                return
        valor = self.TotalPagar(CarrinhodeCompras)
        if len(CarrinhodeCompras)>0:
            dataAluguel = date.today()
            dataDevolucao = date.fromordinal(date.toordinal(dataAluguel)+len(CarrinhodeCompras)) #Data na qual o DVD esta sendo alugado
            diaDevolucao = dataDevolucao.weekday()

            if diaDevolucao == 6:
                dataDevolucao = date.fromordinal(date.toordinal(dataDevolucao)+1)
                
            for prod in CarrinhodeCompras:
                if filmes[prod.titulo].qtd != 0:
                    filmes[prod.titulo].quantidade-=1
                    filmeAlugar = filmes[prod.titulo]
                    del filmeAlugar.quantidade
                    filmeAlugar.dataAluguel="%d-%d-%d" %(dataAluguel.day,dataAluguel.month,dataAluguel.year)
                    filmeAlugar.dataDevolucao="%d-%d-%d" %(dataDevolucao.day,dataDevolucao.month,dataDevolucao.year)
                    c.filmesAlugados[filmeAlugar.titulo] = filmeAlugar
                    c.situacao = "DEBITO"
                    c.debito += valor
            wx.MessageBox("Aluguel efetuado com exito. Valor a ser pago: %.2f" %(valor))         
                
        else:
            wx.MessageBox("Nenhum Filme selecionado esta disponível no estoque!")
예제 #51
0
def check_update():
    today = date.today()
    dbFound = 0
    today_ordinal = date.toordinal(today)
    sqconn = sqlite3.connect("mystk.db");
    cursor = sqconn.execute("SELECT TODAY from DateTable")
    for row in cursor:
        stored_date = row[0];
        if (stored_date == today_ordinal):
            dbFound = 1

    sqconn.close()
    return dbFound
예제 #52
0
    def reserva(CarrinhodeCompras = None, nomeCliente = None, cpfCliente = None, diasparaalugar = None):
        if CarrinhodeCompras == None:
            return "Erro! Produtos não especificados",False
        if len(CarrinhodeCompras) == 0:
            return "Erro! Nenhum produto selecionado",False
        if len(CarrinhodeCompras) > 4:
            return "Erro! Só podem ser reservados ate quatro filmes",False
        #Verifica se o usuario preencheu a forma de pagamento
        filmes = shelve.open("filmes")
        clientes = shelve.open("clientes") #Clientes eh o ARQUIVO

        for c in clientes:
            if clientes[c].nome == nomeCliente:
                if cpfCliente != None and clientes[c].cpf == cpfCliente:
                    c = clientes[c]
                    break
                else:
                    return "Erro! CPF nao especificado ou congruencia entre CPF/Nome nao encontrada.", False

        valor = conta(CarrinhodeCompras = None)
        if len(CarrinhodeCompras)>0:
            today = date.today()
            dataAluguel = date.fromordinal(date.toordinal(today)+diasparaalugar) #Data na qual o DVD esta sendo alugado
            diaAluguel = dataDevolucao.weekday()

            if diaAluguel == 6:
                dataAluguel = date.fromordinal(date.toordinal(dataDevolucao)+1)
                
            for nomefilme in CarrinhodeCompras:
                if filmes[nomeFilme].qtd != 0:
                    filmes[nomeFilme].qtd-=1
                    files[nomeFilme].reservados += 1
                    c.filmesReservados[nomeFilme] = {filmeReservar.titulo:filmeResevar, "DataAluguel": "%d-%d-%d" %(dataAluguel.date,dataAluguel.month,dataAluguel.year), "Situação":"Pendente, devendo R$%.2f" %(valor)}
                    c.debito += valor
            return "Reserva efetuada com exito. Valor a ser pago: ", valor, True         
                
        else:
            return "Nenhum Filme selecionado esta disponível para reserva!", False
예제 #53
0
 def update_energy(self):
     self.power=self.ac_output_voltage*self.inverter_current # power = ac output voltage * inverter sell current
     self.last_timestamp=self.current_timestamp
     self.current_timestamp=time.time()
     dt=self.current_timestamp-self.last_timestamp
     #print "{:03.1f}".format(dt)
     #print "sell current: %d" % self.sell_current
     #print "inverter current %d" % self.inverter_current
     #print "charge current %d" % self.charge_current
     
     self.energy=self.energy+(self.power*dt)/3600/1000 # energy in kWH 
     if self.host is not None: # if we have a database to post to
         if self.date !=date.toordinal(date.today()):
             con=mdb.connect(host=self.host,db=self.db,user=self.user,passwd=self.passwd)
             with con:
                 cur=con.cursor()
                 statement="INSERT INTO daily(time,energy,sunny) VALUES (%s, %s, %s)"    
                 cur.execute(statement,(date.fromordinal(self.date),self.energy))
                 con.commit()
                 cur.close()
             con.close()
             self.date=date.toordinal(date.today())
             self.energy=0
예제 #54
0
def _fmt_date(date):
    def _timedelta_class(delta):
        return _bootstrap_class(delta, timedelta(days=7), timedelta(days=3))

    if not date:
        return format_datatables_data(u'<span class="label">{0}</span>'.format(_("Never")), -1)
    else:
        return format_datatables_data(
            u'<span class="{cls}">{text}</span>'.format(
                cls=_timedelta_class(datetime.utcnow() - date),
                text=_(_naturaltime_with_hover(date)),
            ),
            date.toordinal(),
        )
예제 #55
0
 def __init__(self,system_battery_voltage=None,data_string=None,socket_address=None,host=None,db=None,user=None,passwd=None):
     self.host=host # MySql database info
     self.db=db
     self.user=user
     self.passwd=passwd
     self.ac_input_voltage     
     self.energy=0
     self.q=Queue.Queue()
     self.serial_errorcount=0
     if socket_address is None:
         self.socket=None
     else:        
         self.socket=setup_socket(socket_address,self.q)
         self.socket_address=socket_address
        # read previous data from file
     with open('/temp/inverter_energy','r') as f:
         read_data=f.readline()
         try:
             self.energy=float(read_data)
         except:
             print read_data
         read_data=f.readline()
         f.close()
     if system_battery_voltage is None:
         self.fx_system_battery_voltage=48.0 # default voltage of the battery
     else:
         self.fx_system_battery_voltage=system_battery_voltage # set entered system voltage
     if data_string is None:
         self.address=0 # outback inverter adress
         self.inverter_current=0.0 # current produced by the inverter
         self.charge_current=0.0 # current sent to the charger
         self.buy_current=0.0 # current bought from the grid
         self.ac_input_voltage=0.0 # AC input voltage
         self.ac_output_voltage=0.0 # AC output from the inverter
         self.sell_current=0.0 # AC current sold to the grid
         self.fx_operational_mode=self.fx_modes['00'] # default mode = off
         self.fx_error_mode=0 # default no error
         self.fx_ac_mode=self.fx_ac_modes['00'];
         self.fx_battery_voltage=0.0 # actual voltage
         self.fx_misc_mode=0 # default no misc mode set
         self.fx_warning_mode=0 # default no warning
     else:
         self.parse_data_string(data_string)
     self.power=self.ac_output_voltage*self.sell_current
     self.current_timestamp=time.time()
     self.last_timestamp=time.time()
     self.date=date.toordinal(date.today())
예제 #56
0
 def __init__(self, name, parameters=None, modellToLoad=None, verboseMode=False):
     if name == None:
         self.name = 'AudioSVMon'+str(date.toordinal(date.today()))
     else:
         self.name = name
     self.allFeatures = []
     self.allLabels = []
     
     self.means = []
     self.stds = []
     self.modell = modellToLoad
     if parameters != None:
         self.parameters = svm_parameter(parameters)
     else:
         self.parameters = None
         
     self.verbose = verboseMode
예제 #57
0
def write_history_symbol (dbname, data):
    sqconn = sqlite3.connect("mystk.db");
    symbol = data[0];
    del data[0];
    data.reverse();
    today = date.today()
    today_ordinal = date.toordinal(today)
    datelist = [];
    numRows = len(data);
    today_ordinal -= numRows;
    for i in range(0,numRows):
        today_ordinal += 1;
        datelist.append(today_ordinal);

    my_type_arr_2 = tuple([tuple([datelist[i],symbol,data[i]]) for i in range (0,numRows)]);
    my_query_str = "INSERT INTO " + dbname + "(DATEVAL, SYMBOL,VAL) VALUES (?, ?, ?)"
    sqconn.executemany( my_query_str, my_type_arr_2);
    sqconn.commit()
    sqconn.close();
예제 #58
0
def write_daily_values (dbname, data):
    print "WRITE DAILY CALLED"
    open_writer();
    sqconn = sqlite3.connect("mystk.db");
    today = date.today()
    today_ordinal = date.toordinal(today)
    if (_check_if_today_written(today_ordinal)):
        #
        #  Today is written. Update values
        #
        my_type_arr_2 = tuple([tuple([row[1],today_ordinal,row[0]]) for row in data]);
        my_query_str = "UPDATE " + dbname + " SET VAL = ? WHERE DATEVAL=? AND SYMBOL=?";
        sqconn.executemany( my_query_str, my_type_arr_2);
    else:
        #
        # Insert new values
        #
        my_type_arr_2 = tuple([tuple([today_ordinal,row[0],row[1]]) for row in data]);
        my_query_str = "INSERT INTO " + dbname + "(DATEVAL,SYMBOL,VAL) VALUES (?, ?, ?)"
        sqconn.executemany( my_query_str, my_type_arr_2);

    sqconn.commit()
    sqconn.close();