Exemplo n.º 1
0
def validate_date_birthday(value):
    timetuple = datetime.now().timetuple()[:3]
    if value > date(timetuple[0] - 14, timetuple[1], timetuple[2]):
        raise ValidationError('В соответствии со ст. 188 КЗоТ Украины не допускается использование труда '
                              'лиц не достигших 14 лет')
    elif value < date(timetuple[0] - 100, timetuple[1], timetuple[2]):
        raise ValidationError('Возраст сотрудника должен быть меньше 100 лет')
Exemplo n.º 2
0
def add_request():
    form = RequestForm(request.form)
    form.rq_status.choices = [(Status.id, Status.name)
                              for Status in Status.query.all()]

    if request.method == 'POST':

        start = form.start.data
        finish = form.finish.data
        date_1 = date(start.year, start.month, start.day)
        date_2 = date(finish.year, finish.month, finish.day)

        sum = (date_2 - date_1).days

        req = Request(sum=sum,
                      start_date=start,
                      finish_date=finish,
                      employee=current_user.name,
                      rq_status='Pending')
        db.session.add(req)
        db.session.commit()

        flash('Request created', 'success')
        return redirect(url_for('requests'))

    return render_template('add_request.html', form=form)
Exemplo n.º 3
0
def add_request():
    form = RequestForm(request.form)

    if request.method == 'POST' and form.validate():
        start = form.start.data
        finish = form.finish.data
        date_1 = date(start.year, start.month, start.day)
        date_2 = date(finish.year, finish.month, finish.day)
        number_of_days = (date_2 - date_1).days

        # Create Cursor
        cur = mysql.connection.cursor()

        # Execute
        cur.execute("INSERT INTO requests(start, finish, author) VALUES(%s, %s, %s)",
                    (start, finish, session['username']))

        cur.execute("UPDATE users SET requested_holidays=%s WHERE username=%s",
                    ([number_of_days], [session['username']]))

        # Commit to DB
        mysql.connection.commit()

        # Close connection
        cur.close()

        flash('Request created', 'success')
        return redirect(url_for('add_request'))

    return render_template('add_request.html', form=form)
Exemplo n.º 4
0
def validate_date_birthday(value):
    timetuple = datetime.now().timetuple()[:3]
    if value > date(timetuple[0] - 14, timetuple[1], timetuple[2]):
        raise ValidationError(
            'В соответствии со ст. 188 КЗоТ Украины не допускается использование труда '
            'лиц не достигших 14 лет')
    elif value < date(timetuple[0] - 100, timetuple[1], timetuple[2]):
        raise ValidationError('Возраст сотрудника должен быть меньше 100 лет')
Exemplo n.º 5
0
def make_date():
    '''Generate random date'''
    start = date(2010, 1, 1)
    end = date(2018, 12, 31)

    span = (end - start).days
    ran = randint(0, span)
    ran_date = (start + timedelta(days=ran)).strftime("%m/%d/%Y")
    return ran_date
Exemplo n.º 6
0
def gen_date():
    '''Generate random date'''
    # based on the lowest date in poor_perf
    start = date(2010, 1, 1)
# datetime.date.today()
    end = date(2018, 12, 31)

    span = (end - start).days
    ran = random.randint(0, span)
    ran_date = (start + timedelta(days=ran)).strftime("%m/%d/%Y")
    return ran_date
Exemplo n.º 7
0
    def next_data(self):
        from random import choice
        year = choice(FrankfurtStockPrediction.years)
        month = choice(FrankfurtStockPrediction.months)
        day = choice(FrankfurtStockPrediction.days)
        date_format = '%Y-%m-%d'
        start_date = date(year=year, month=month, day=day)
        end_date = start_date + relativedelta(months=1)
        start_date_str = start_date.strftime(date_format)
        end_date_str = end_date.strftime(date_format)

        ticker_data = []
        for ticker in self.tickers:
            print(f'Getting stock data for {ticker}')
            ticker_data.append(
                self.get_ticker(ticker,
                                start_date=start_date_str,
                                end_date=end_date_str))

        guess_ticker_data = []
        for ticker in self.guess_tickers:
            print(f'Getting stock data for {ticker}')
            guess_ticker_data.append(
                self.get_ticker(ticker,
                                start_date=start_date_str,
                                end_date=end_date_str))

        try:
            tickers = np.vstack(ticker_data)
            guess_tickers = np.vstack(guess_ticker_data)
        except ValueError:
            return self.next_data()

        return tickers, guess_tickers
Exemplo n.º 8
0
def validate_date_naklad(value):
    if value > date.today():
        raise ValidationError(
            'Нельзя указать дату накладной больше сегодняшней')
    elif value < date(1970, 1, 1):
        raise ValidationError(
            'Дата накладной должна быть старше 1 января 1970')
Exemplo n.º 9
0
class SettingsModel(models.Model):
    user_id = models.ForeignKey(DjangoUser,
                                on_delete=models.CASCADE,
                                default='1')
    created_at = models.DateTimeField(default=timezone.now)
    start_date = models.DateField('Startdatum', default=date(2018, 1, 1))
    work_time_mon = models.DecimalField('Arbeitszeit Montag',
                                        max_digits=10,
                                        decimal_places=2,
                                        default=8)
    work_time_tue = models.DecimalField('Arbeitszeit Dienstag',
                                        max_digits=10,
                                        decimal_places=2,
                                        default=8)
    work_time_wed = models.DecimalField('Arbeitszeit Mittwoch',
                                        max_digits=10,
                                        decimal_places=2,
                                        default=8)
    work_time_thu = models.DecimalField('Arbeitszeit Donnerstag',
                                        max_digits=10,
                                        decimal_places=2,
                                        default=8)
    work_time_fri = models.DecimalField('Arbeitszeit Freitag',
                                        max_digits=10,
                                        decimal_places=2,
                                        default=8)
    work_time_sat = models.DecimalField('Arbeitszeit Samstag',
                                        max_digits=10,
                                        decimal_places=2,
                                        default=0)
    work_time_sun = models.DecimalField('Arbeitszeit Sonntag',
                                        max_digits=10,
                                        decimal_places=2,
                                        default=0)
Exemplo n.º 10
0
def get_last_days_of_last_four_months(input_date):
    current_year = input_date.year
    current_month = input_date.month
    first_day = 1

    first_day_of_current_month = date(current_year, current_month, first_day)
    last_day_last_month = edit_date(first_day_of_current_month, cst.DT_MINUS,
                                    1, cst.DT_DAY)

    first_day_last_month = edit_date(first_day_of_current_month, cst.DT_MINUS,
                                     1, cst.DT_MONTH)
    last_day_second_last_month = edit_date(first_day_last_month, cst.DT_MINUS,
                                           1, cst.DT_DAY)

    first_day_second_last_month = edit_date(first_day_of_current_month,
                                            cst.DT_MINUS, 2, cst.DT_MONTH)
    last_day_third_last_month = edit_date(first_day_second_last_month,
                                          cst.DT_MINUS, 1, cst.DT_DAY)

    first_day_third_last_month = edit_date(first_day_of_current_month,
                                           cst.DT_MINUS, 3, cst.DT_MONTH)
    last_day_forth_last_month = edit_date(first_day_third_last_month,
                                          cst.DT_MINUS, 1, cst.DT_DAY)

    return [
        last_day_forth_last_month,
        last_day_third_last_month,
        last_day_second_last_month,
        last_day_last_month,
    ]
Exemplo n.º 11
0
 def _compute_recognition_date(self):
     if self.aquisition_date and self.period:
         if self.period == "years":
             year = self.aquisition_date.strftime("%Y")
             self.first_recognition_date = date(int(year), 12, 31)
         else :
             self.first_recognition_date = self.compute_last_day(self.aquisition_date)
Exemplo n.º 12
0
def handler_date_of_user(user_answer):
    """Проверяет корректность веденных данных пользователем и возвращает словарь из 2 элементов
    date_from - объекта date начало диапазона, date_to объекта date конец диапазона"""
    try:
        date_from, date_to = re.split(r':', user_answer)
        day_date_from, month_date_from = re.split(r'-', date_from)
        day_date_to, month_date_to = re.split(r'-', date_to)
        date_from = date(day=int(day_date_from),
                         month=int(month_date_from),
                         year=2021)
        date_to = date(day=int(day_date_to),
                       month=int(month_date_to),
                       year=2021)
        user_answer = {'date_from': date_from, 'date_to': date_to}
        return user_answer
    except Exception():
        print(f'{user_answer}, дата не соответствует виду dd-mm')
Exemplo n.º 13
0
def findMaxDate():
    myconn=getConnection()
    cur = myconn.cursor()
    sql = "select max(date_practice) from review"
    cur.execute(sql)
    myresult = cur.fetchone()
    if myresult[0] != None:
        return myresult[0]
    else:
        return date(2000,1,1)
Exemplo n.º 14
0
def get_first_friday_of_months(year):
    month_list = []
    for month_ in range(1, 13):
        month_calendar = calendar.monthcalendar(year, month_)
        week1 = month_calendar[0]
        week2 = month_calendar[1]

        if week1[calendar.FRIDAY] != 0:
            week_day_no = date(year=year,
                               month=month_,
                               day=week1[calendar.FRIDAY])
        else:
            week_day_no = date(year=year,
                               month=month_,
                               day=week2[calendar.FRIDAY])

        month_list.append(week_day_no)

    return month_list
Exemplo n.º 15
0
 def set_date(self, month_str=None, day_str=None, year_str=None):
     """ Convert date component strings to date
     :month_str: month string e.g jan, Jan, January
     :day_str: day string 1-31
     :year_str:  year string if < 20 add "2000"
     :returns: date object
     """
     month = self.set_date_month(month_str)
     day = int(day_str)
     year = int(year_str)
     if year <= 20:
         year += 2000
     return date(year=year, month=month, day=day)
Exemplo n.º 16
0
def update():
    if main_list == []:
        print('FIRST ENTER THE DETAILS !')
        main_func()
    '''this function is to update the existing list'''
    inp = input(
        'enter the Id of employee you want to update \n-----------------------------------\n'
    )
    for l in range(0, len(main_list)):
        if inp != main_list[l][0]:
            print('No such employee !')
            main_func()

    for l in range(0, len(main_list)):
        if inp == main_list[l][0]:
            print('ID:', main_list[l][0])
            print('Name:', main_list[l][1])
            print('DoG:', main_list[l][2])
            print('Salary:', main_list[l][3])
            print('--------------------------------')
    dchoose = input('press 0 for update the date else press1')
    '''this input will differentiate the date from other parameters'''
    if dchoose == '0':
        print('Enter date of joining')
        day = int(input('Enter a day'))
        month = int(input('Enter a month'))
        year = int(input('Enter a year'))
        b = date(year, month, day)
        main_list[l][2] = b
        print('Update Done..\n--------------------------------------------')
        print('ID:', main_list[l][0])
        print('Name:', main_list[l][1])
        print('DoG:', main_list[l][2])
        print('Salary:', main_list[l][3])
        print('--------------------------------')
    elif dchoose == '1':
        up = input('enter the parameter to change:')
        for m in range(0, len(main_list)):
            for n in range(0, 4):
                if up == main_list[m][n]:
                    new_value = input('enter new parameter:')
                    main_list[m][n] = new_value
                    print(
                        'Update Done..\n--------------------------------------------'
                    )
                    print('ID:', main_list[m][0])
                    print('Name:', main_list[m][1])
                    print('DoG:', main_list[m][2])
                    print('Salary:', main_list[m][3])
                    print('--------------------------------')
    main_func()
    def read_labels_to_dict(self, label_file_path):
        with open(label_file_path, 'r') as in_fd:
            reader = csv.DictReader(in_fd, delimiter='\t')
            #col_names     = reader.fieldnames
            col_names = [
                'Observation Row', 'Begin Time', 'Location',
                'start_call_24hr_clock', 'is_night'
            ]
            writer = csv.DictWriter(sys.stdout, col_names, delimiter='\t')

            # Col header:
            sys.stdout.write('\t'.join(writer.fieldnames) + '\n')
            row_num = 0
            for row in reader:
                row_num += 1

                begin_time_secs = row['Begin Time (s)']
                # Get location date from nn01_20190320_....txt
                label_loc = row['Begin File'].split('_')[0]
                label_date = row['Begin File'].split('_')[1]

                if DayNightCounter.DATE_PAT.search(label_date) is None:
                    raise ValueError(
                        f"Could not extract date from row {row_num}'s begin-file."
                    )

                # Get a date obj from the date:
                label_date_obj = date(int(label_date[0:4]),
                                      int(label_date[4:6]),
                                      int(label_date[6:8]))

                # Get begin time as seconds since midnight e.g.: 2543.4433
                begin_time_secs = float(row['Begin Time (s)'])
                row['is_night'] = 1 if (begin_time_secs <= DayNightCounter.NIGHT_END_SECS
                                      or begin_time_secs >= DayNightCounter.NIGHT_START_SECS) \
                                    else 0

                start_time_24   = f"{label_date_obj} {math.floor(begin_time_secs / 3600)}:" +\
                                  f"{math.floor((begin_time_secs % 3600) / 60)}:" +\
                                  f"{math.floor((begin_time_secs % 3600) % 60)}"

                #row['start_call_24hr_clock'] = start_time_24
                #row['rounded_time'] = str(round(begin_time_secs / 3600)) + ':00hrs'
                row_extract_values = [
                    row_num, begin_time_secs, label_loc, start_time_24,
                    row['is_night']
                ]
                row_extract = OrderedDict(zip(col_names, row_extract_values))
                writer.writerow(row_extract)
Exemplo n.º 18
0
def send_conflict_notification(request, persons: QuerySet):
    connection = mail.get_connection()

    today = date.today()
    last_year = date(year=today.year - 1, month=12, day=31)

    # Manually open the connection
    connection.open()
    messages = []
    for p in persons:
        if not p.eligibile_onlyOneClub():
            club_memberships: List[
                PersonToClubMembership] = p.get_current_clubmemberships()

            for m in club_memberships:
                club_admins = User.objects.filter(
                    groups__name=f"club_admin_{m.club.name}")

                club_memberships: List[
                    PersonToClubMembership] = p.get_current_clubmemberships()
                templates = (loader.get_template(
                    "mails/nationals_conflict/send_conflict_notification_club_admin.j2"
                ), )
                context = {
                    "person": p,
                    "club_memberships": club_memberships,
                    "affected_club_membership": m,
                    "last_year": last_year,
                    "request": request,
                }

                for admin in club_admins:
                    context["recepient"] = admin
                    msg = mail.EmailMessage(
                        subject=
                        f"Konflikt bei der Vereinsmeldung von {p.firstname} {p.lastname}",
                        body=templates[0].render(context),
                        to=[admin.email],
                        from_email="*****@*****.**",
                        connection=connection,
                    )
                    msg.content_subtype = "html"
                    messages.append(msg)

    # Send the two emails in a single call -
    connection.send_messages(messages)
    # The connection was already open so send_messages() doesn't close it.
    # We need to manually close the connection.
    connection.close()
Exemplo n.º 19
0
def entering_input(count):
    '''this is to enter new employee details'''
    for j in range(0, count):
        a = []
        for i in range(0, 4):

            if i == 0:
                b = input("Enter employee id")
            elif i == 1:
                b = input('Enter employee name')
            elif i == 2:
                print('Enter date of joining')
                day = int(input('Enter a day'))
                month = int(input('Enter a month'))
                year = int(input('Enter a year'))
                b = date(year, month, day)
            elif i == 3:
                b = input('enter the salary/annum(!Digits Only)')
            a.append(b)
        print('the given list is', a)
        main_list.append(a)
        print('----------------------------------------------')
    main_func()
import time
import _datetime
#a=time.ctime()
#print(time.time())
#print(time.ctime(1595290192.9759343))
#print(time.gmtime())
#print(time.asctime())
#print(time.localtime())
#help(time.strftime)
#print(time.strftime("%m/%d/%Y"))
#b="20 August 2020"
#print(time.strptime(b,"%d%B%Y"))
'''print(_datetime.datetime(2020,8,21,12,30,50,757))
print(_datetime.datetime.today())
print(_datetime.datetime.now().month)
print(_datetime.datetime.today().hour)
print(_datetime.datetime.today().year)'''

print(_datetime.date(2019, 7, 5))
print(_datetime.time(12, 3, 23))

c = _datetime.timedelta(days=20, hours=12, minutes=25, seconds=51)
d = _datetime.timedelta(days=30, hours=3, minutes=40, seconds=25)
e = c - d
print(e)
Exemplo n.º 21
0
    def get_all_dates(self, month, year):
        start_date = date(int(year), int(month), 1)
        end_date = date(int(year), int(month) + 1, 1)

        return np.arange(start_date, end_date)
Exemplo n.º 22
0
from _datetime import datetime, date

d1 = input('Введите дату в формате ГГГГ,М,Д :')
d1 = d1.split(',')
d1 = date(int(d1[0]), int(d1[1]), int(d1[2]))
d2 = input('Введите дату в формате ГГГГ,М,Д :')
d2 = d2.split(',')
d2 = date(int(d2[0]), int(d2[1]), int(d2[2]))
q_day = ((d2 - d1).days)
d1w = datetime.weekday(d1)
work_day = []
for i in range(q_day + 1):
    if d1w < 5:
        work_day.append(d1w)
        d1w += 1
    elif d1w > 5:
        d1w = 0
    else:
        d1w += 1

print('Количество рабочих дней ' + str(len(work_day)))
Exemplo n.º 23
0
def validate_date_naklad(value):
    if value > date.today():
        raise ValidationError('Нельзя указать дату накладной больше сегодняшней')
    elif value < date(1970, 1, 1):
        raise ValidationError('Дата накладной должна быть старше 1 января 1970')
Exemplo n.º 24
0
    def action_move_create(self):
        if not self.name:
            raise ValidationError(_("Field name is not defined"))
        if not self.deferred_amount_id:
            raise ValidationError(_("Field Deferred revenue amount is not defined"))
        if not self.expense_account_id:
            raise ValidationError(_("Field Revenue amount is not defined"))
        if not self.journal_id:
            raise ValidationError(_("Field Journal is not defined"))

        depreciation_move_list=[]
        self.env['account.move'].search([('accrual_account_revenue_id', '=',self.id)]).unlink()
        if self.residual_amount > 0:
            price_value = (self.residual_amount)/self.number_recognition
            number = 1
            rec_number = self.number_recognition
            if self.prorata_temporis and self.prorata_date:
                rec_number += 1
                number = 0
                if self.period == "months":
                    last_day = int(self.compute_last_day(self.prorata_date).strftime("%d"))
                    crnt_day= int(self.prorata_date.strftime("%d"))
                    percnt = (crnt_day-1)*100/last_day
                elif self.period == "years":
                    year = int(self.prorata_date.strftime("%Y"))
                    total_days =  int(date(year, 12, 31).strftime("%j"))
                    crnt_day = int(self.prorata_date.strftime("%j"))
                    percnt = (crnt_day)*100/total_days
                    
                last_price = round((price_value*percnt)/100,2)
                first_price = price_value - last_price
                
    #             setting dates for account move ```````````````
            date_list =[]    
            if self.period == "months":
                date_list = [self.compute_last_day(self.first_recognition_date + relativedelta(months=x)) for x in range(rec_number)]
            if self.period == "years":
                date_list = [self.first_recognition_date + relativedelta(years=x) for x in range(rec_number)]
    
            
            cumulative_value = 0.0
            for rec_date in date_list:
                iml = []
                name = self.name or ''
                name = name+"("+str(number)+"/"+str(self.number_recognition)+")"
                calculated_price = price_value
                if number == 0:
                    name = self.name+"(prorata entry)"
                    calculated_price = first_price
                elif number == self.number_recognition and self.prorata_temporis:
                    calculated_price = last_price
                number +=1
                if calculated_price >= 0.005:    
                    cumulative_value += calculated_price
                    iml.append({
                        'type': 'entry',
                        'name': self.name,
                        'price': calculated_price,
                        'account_id': self.deferred_amount_id.id,
                        'date_maturity': rec_date,
                        'amount_currency': False,
                        'debit': calculated_price,
                        'credit':0.0,
                        'currency_id': False,
                        'selfoice_id': self.id
                    })
                    iml.append({
                        'type': 'entry',
                        'name': self.name,
                        'price': calculated_price,
                        'account_id': self.expense_account_id.id,
                        'date_maturity': rec_date,
                        'amount_currency': False,
                        'debit': 0.0,
                        'credit':calculated_price,
                        'currency_id': False,
                        'selfoice_id': self.id
                    })
                    line = [(0, 0, l) for l in iml]
                    acc_move = {
                        'type': 'entry',
                        'ref': name,
                        'date': rec_date,
                        'amount_total' : calculated_price,
                        'asset_depreciated_value': cumulative_value,
                        'asset_remaining_value':self.residual_amount - cumulative_value,
                        'journal_id': self.journal_id.id,
                        'line_ids': line,
                        }
                    depreciation_move_list.append((0, False,acc_move))
            self.depreciation_move_ids = depreciation_move_list
        return True
    
# 
# class AccountMove(models.Model):
#     _inherit = 'account.move'  
#     
#     accrual_account_id = fields.Many2one('accrual.revenue.accounting',"Accrual account")
#     amount_total = fields.Float("Expense")
#     asset_depreciated_value = fields.Float("Cumulative Revenue")
#     asset_remaining_value = fields.Float("Next Period Expense")
#     auto_post = fields.Boolean('Post Automatically')
#     
#     def run_post_account_move(self):
#         for rec in self.search([]):
#             if rec.auto_post:
#                 if rec.date == date.today():
#                     self.action_post()
# 
#     @api.multi
#     def action_post(self):
#         record = super(AccountMove, self).action_post()
# #         print("ssssssssss",self.accrual_account_id.residual_amount)
#         if self.accrual_account_id:
#             residual = self.accrual_account_id.residual_amount - self.amount_total 
#             self.accrual_account_id.write({'residual_amnt_calculate': residual})
#         print("ssssssssss",self.accrual_account_id.residual_amount,residual,self.amount_total)
# #         print("ssssssssss",self.accrual_account_idq)
#         return record
#                 
    
  
  
  
#     value = fields.Integer()
#     value2 = fields.Float(compute="_value_pc", store=True)
#     description = fields.Text()
#
#     @api.depends('value')
#     def _value_pc(self):
#         self.value2 = float(self.value) / 100
 def compute_last_day(self, aquisition_date):
     year = aquisition_date.strftime("%Y")
     month = aquisition_date.strftime("%m")
     day = calendar.monthrange(int(year), int(month))[1]
     last_date = date(int(year), int(month), int(day))
     return last_date
Exemplo n.º 26
0
def loadinfo(folderPath):
    CSXMOVES = load_workbook(folderPath)
    activeSheet = CSXMOVES['CSX MOVES']
    driverSheet = CSXMOVES['Drivers']
    rateSheet = CSXMOVES['Rates']
    colorSheet = CSXMOVES['COLOUR KEY']

    drivers = []
    #RGB 173,216,230
    #     activeColor = RGB("add8e6")

    #     print('aaa')
    #     print(colorSheet.max_row)
    colors = ["", "", "", "", "", ""]
    for xRow in colorSheet.rows:
        for xCell in xRow:
            if xCell.value == "MONDAY":
                colors[0] = xCell.fill
                break
            elif xCell.value == "TUESDAY":
                colors[1] = xCell.fill
                break
            elif xCell.value == "WEDNESDAY":
                colors[2] = xCell.fill
                break
            elif xCell.value == "THURSDAY":
                colors[3] = xCell.fill
                break
            elif xCell.value == "FRIDAY":
                colors[4] = xCell.fill
                break
            elif xCell.value == "SATURDAY":
                colors[5] = xCell.fill
                break

    dayOfTheWeek = [-1]
    startAt = [""]
    top = Tk()
    L1 = Label(
        top,
        text=
        "Please select which driver to start at (optional) \n as well as which day of the week to run on \n "
    )
    L1.config(font=("Courier", 16))
    L1.grid(row=0, column=0, columnspan=6)
    L2 = Label(top, text="Start at driver #:")
    L2.config(font=("Courier", 10))
    L2.grid(row=1, column=0, columnspan=2)
    E1 = Entry(top, bd=5, width=39)
    E1.grid(row=1, column=2, columnspan=2)
    L3 = Label(top, text="OR")
    L3.grid(row=2, column=1, columnspan=2)
    L3.config(font=("Courier", 20))
    top.lift()
    top.attributes('-topmost', True)
    top.after_idle(top.attributes, '-topmost', False)

    def callbackDay(day):
        startAt[0] = E1.get().strip()
        dayOfTheWeek[0] = day
        top.destroy()

    MyButton5 = Button(top, text="MONDAY", command=lambda: callbackDay(0))
    MyButton5.grid(row=4, column=0)
    MyButton5.config(font=("Courier", 16))
    MyButton6 = Button(top, text="TUESDAY", command=lambda: callbackDay(1))
    MyButton6.grid(row=4, column=1)
    MyButton6.config(font=("Courier", 16))
    MyButton7 = Button(top, text="WEDNESDAY", command=lambda: callbackDay(2))
    MyButton7.grid(row=4, column=2)
    MyButton7.config(font=("Courier", 16))
    MyButton8 = Button(top, text="THURSDAY", command=lambda: callbackDay(3))
    MyButton8.grid(row=4, column=3)
    MyButton8.config(font=("Courier", 16))
    MyButton9 = Button(top, text="FRIDAY", command=lambda: callbackDay(4))
    MyButton9.grid(row=4, column=4)
    MyButton9.config(font=("Courier", 16))
    MyButton10 = Button(top, text="SATURDAY", command=lambda: callbackDay(5))
    MyButton10.grid(row=4, column=5)
    MyButton10.config(font=("Courier", 16))

    w = 900  # width for the Tk root
    h = 260  # height for the Tk root

    # get screen width and height
    ws = top.winfo_screenwidth()  # width of the screen
    hs = top.winfo_screenheight()  # height of the screen

    # calculate x and y coordinates for the Tk root window
    x = (ws / 2) - (w / 2)
    y = (hs / 2) - (h / 2)

    # set the dimensions of the screen
    # and where it is placed
    top.geometry('%dx%d+%d+%d' % (w, h, x, y))

    top.mainloop()

    todaysFill = colors[dayOfTheWeek[0]]

    year = folderPath.split("\\")[-2]
    week = folderPath.split("\\")[-1].split(" ")[3]
    pickupDate = date(int(year), 1, 1)

    oneDay = timedelta(1)
    oneWeek = timedelta(7)

    while pickupDate.weekday() != 0:
        pickupDate = pickupDate + oneDay

    pickupDate = pickupDate + (int(week) - 1) * oneWeek

    pickupDate = pickupDate + (dayOfTheWeek[0]) * oneDay

    containerNumberCol = ""
    containerNumber2Col = ""
    parsCol = ""
    pars2Col = ""
    driverCol = ""
    notesCol = ""
    notes2Col = ""

    for cell in next(activeSheet.rows):
        if cell.value == "PB":
            parsCol = cell.col_idx - 1
        elif cell.value == "Container":
            containerNumberCol = cell.col_idx - 1
        elif cell.value == "EX BP":
            notesCol = cell.col_idx - 1
        elif cell.value == "NOTES":
            notes2Col = cell.col_idx - 1
        elif cell.value == "DRIVER":
            driverCol = cell.col_idx - 1
        elif cell.value == "Container IMPORT":
            containerNumber2Col = cell.col_idx - 1
        elif cell.value == "IM BP":
            pars2Col = cell.col_idx - 1

    rates = []

    matchWords = [
        "Owner Operator", "Owner Operator BAREFRAME",
        "Owner Operator 2 containers roundtrip",
        "Owner Operator 3 containers roundtrip",
        "Owner Operator 4 containers roundtrip",
        "Owner Operator  Round trip 5/6 containers", "Company Driver",
        "Company Driver BAREFRAME", "Company Driver Round trip 2 Containers",
        "Company Driver  Round trip 3 Containers",
        "Company Driver  Round trip 4 Containers",
        "Company Driver  Round trip +4 CONTAINERS", "Sunrise Stop-off (x3)"
    ]
    match = 0
    for row in rateSheet:
        for cell in row:
            if str(cell.value) == matchWords[match] or (
                    matchWords[match]
                    == "Company Driver  Round trip 5/6 containers"
                    and str(cell.value)
                    == "Company Driver  Round trip +4 CONTAINERS"):
                rates.append(str(row[cell.col_idx + 1].value))
                match += 1
                break

    print(rates)
    startFound = False
    if startAt[0] != "":
        for row in activeSheet.rows:
            if row[0].fill.fgColor == todaysFill.fgColor:
                print(row[0].row)
                if (not row[driverCol].value == None) and (
                        not row[driverCol].value
                        == "") and row[0].row > 2 and (not startFound) and str(
                            row[driverCol].value) == startAt[0]:
                    startFound = True
                if startFound:
                    if (not row[driverCol].value == None) and (
                            not row[driverCol].value == "") and row[0].row > 2:
                        driver1 = None
                        driver2 = None
                        if not "BAREFRAME" in row[containerNumberCol].value:
                            driver1 = Driver()
                            driver1.driver = str(row[driverCol].value).strip()
                        if not "BAREFRAME" in row[containerNumber2Col].value:
                            driver2 = Driver()
                            driver2.driver = str(row[driverCol].value).strip()

                        numberOfMoves = 0

                        currentRow = row[0].row
                        #             print(currentRow)
                        for i in range(-2, 3):
                            #                 print(i)
                            if not i == 0:
                                #                     print("here")
                                #                     print(str(activeSheet[currentRow+i][driverCol].value))
                                if str(activeSheet[currentRow +
                                                   i][driverCol].value) == str(
                                                       row[driverCol].value):
                                    #                         print(activeSheet[containerNumberCol][currentRow+i].value)
                                    #                         print(activeSheet[containerNumber2Col][currentRow+i].value)
                                    if "BAREFRAME" in str(
                                            activeSheet[currentRow +
                                                        i][containerNumberCol].
                                            value) or "BAREFRAME" in str(
                                                activeSheet[currentRow + i]
                                                [containerNumber2Col].value):
                                        numberOfMoves += 1
            #                             print("+1")
                                    else:
                                        #                             print("+2")
                                        numberOfMoves += 2

                        if numberOfMoves > 0:
                            if "BAREFRAME" in row[
                                    containerNumber2Col].value or "BAREFRAME" in row[
                                        containerNumberCol].value:
                                numberOfMoves += 1
                            else:
                                numberOfMoves += 2

            #             print(numberOfMoves)
                        if numberOfMoves == 6:
                            numberOfMoves = 5

                        if driver1 != None:
                            driver1.PARS = str(row[parsCol].value)

                            if "BAREFRAME" in row[containerNumber2Col].value:
                                driver1.bareframe = True

                            numberOfMoves1 = numberOfMoves
                            numberOfMoves2 = numberOfMoves + 6
                            if driver1.driver[:3] == "801":
                                if numberOfMoves1 == 0 and "BAREFRAME" in row[
                                        containerNumber2Col].value:
                                    numberOfMoves1 += 1
                                driver1.payout = rates[numberOfMoves1]
                            else:
                                if numberOfMoves2 == 6 and "BAREFRAME" in row[
                                        containerNumber2Col].value:
                                    numberOfMoves2 += 1
                                driver1.payout = rates[numberOfMoves2]

                            if len(driver1.driver) < 6:
                                prefix = "801"
                                while len(prefix) + len(driver1.driver) < 6:
                                    prefix += "0"
                                driver1.driver = prefix + driver1.driver

                            driver1.containerNumber = str(
                                row[containerNumberCol].value).strip()
                            if row[notesCol].value == "SUNRISE METALS":
                                driver1.sunrise = True
                            drivers.append(driver1)

                        if driver2 != None:
                            driver2.PARS = str(row[pars2Col].value)

                            if "BAREFRAME" in row[containerNumberCol].value:
                                driver2.bareframe = True

                            numberOfMoves1 = numberOfMoves
                            numberOfMoves2 = numberOfMoves + 6
                            if driver2.driver[:3] == "801":
                                if numberOfMoves1 == 0 and "BAREFRAME" in row[
                                        containerNumberCol].value:
                                    numberOfMoves1 += 1
                                driver2.payout = rates[numberOfMoves1]
                            else:
                                if numberOfMoves2 == 6 and "BAREFRAME" in row[
                                        containerNumberCol].value:
                                    numberOfMoves2 += 1
                                driver2.payout = rates[numberOfMoves2]

                            if len(driver2.driver) < 6:
                                prefix = "801"
                                while len(prefix) + len(driver2.driver) < 6:
                                    prefix += "0"
                                driver2.driver = prefix + driver2.driver

                            driver2.containerNumber = str(
                                row[containerNumber2Col].value).strip()
                            if row[notes2Col].value == "SUNRISE METALS":
                                driver2.sunrise = True
                            drivers.append(driver2)
    else:
        for row in activeSheet.rows:
            if row[0].fill.fgColor == todaysFill.fgColor:
                print(row[0].row)
                if (not row[driverCol].value == None) and (
                        not row[driverCol].value == "") and row[0].row > 2:
                    driver1 = None
                    driver2 = None
                    if not "BAREFRAME" in row[containerNumberCol].value:
                        driver1 = Driver()
                        driver1.driver = str(row[driverCol].value).strip()
                    if not "BAREFRAME" in row[containerNumber2Col].value:
                        driver2 = Driver()
                        driver2.driver = str(row[driverCol].value).strip()

                    numberOfMoves = 0

                    currentRow = row[0].row
                    #             print(currentRow)
                    for i in range(-2, 3):
                        #                 print(i)
                        if not i == 0:
                            #                     print("here")
                            #                     print(str(activeSheet[currentRow+i][driverCol].value))
                            if str(activeSheet[currentRow +
                                               i][driverCol].value) == str(
                                                   row[driverCol].value):
                                #                         print(activeSheet[containerNumberCol][currentRow+i].value)
                                #                         print(activeSheet[containerNumber2Col][currentRow+i].value)
                                if "BAREFRAME" in str(
                                        activeSheet[currentRow +
                                                    i][containerNumberCol].
                                        value) or "BAREFRAME" in str(
                                            activeSheet[currentRow + i]
                                            [containerNumber2Col].value):
                                    numberOfMoves += 1
        #                             print("+1")
                                else:
                                    #                             print("+2")
                                    numberOfMoves += 2

                    if numberOfMoves > 0:
                        if "BAREFRAME" in row[
                                containerNumber2Col].value or "BAREFRAME" in row[
                                    containerNumberCol].value:
                            numberOfMoves += 1
                        else:
                            numberOfMoves += 2

        #             print(numberOfMoves)
                    if numberOfMoves == 6:
                        numberOfMoves = 5

                    if driver1 != None:
                        driver1.PARS = str(row[parsCol].value)

                        if "BAREFRAME" in row[containerNumber2Col].value:
                            driver1.bareframe = True

                        numberOfMoves1 = numberOfMoves
                        numberOfMoves2 = numberOfMoves + 6
                        if driver1.driver[:3] == "801":
                            if numberOfMoves1 == 0 and "BAREFRAME" in row[
                                    containerNumber2Col].value:
                                numberOfMoves1 += 1
                            driver1.payout = rates[numberOfMoves1]
                        else:
                            if numberOfMoves2 == 6 and "BAREFRAME" in row[
                                    containerNumber2Col].value:
                                numberOfMoves2 += 1
                            driver1.payout = rates[numberOfMoves2]

                        if len(driver1.driver) < 6:
                            prefix = "801"
                            while len(prefix) + len(driver1.driver) < 6:
                                prefix += "0"
                            driver1.driver = prefix + driver1.driver

                        driver1.containerNumber = str(
                            row[containerNumberCol].value).strip()
                        if row[notesCol].value == "SUNRISE METALS":
                            driver1.sunrise = True
                        drivers.append(driver1)

                    if driver2 != None:
                        driver2.PARS = str(row[pars2Col].value)

                        if "BAREFRAME" in row[containerNumberCol].value:
                            driver2.bareframe = True

                        numberOfMoves1 = numberOfMoves
                        numberOfMoves2 = numberOfMoves + 6
                        if driver2.driver[:3] == "801":
                            if numberOfMoves1 == 0 and "BAREFRAME" in row[
                                    containerNumberCol].value:
                                numberOfMoves1 += 1
                            driver2.payout = rates[numberOfMoves1]
                        else:
                            if numberOfMoves2 == 6 and "BAREFRAME" in row[
                                    containerNumberCol].value:
                                numberOfMoves2 += 1
#                             print(numberOfMoves2)
#                             print(driver2.containerNumber)
                            driver2.payout = rates[numberOfMoves2]

                        if len(driver2.driver) < 6:
                            prefix = "801"
                            while len(prefix) + len(driver2.driver) < 6:
                                prefix += "0"
                            driver2.driver = prefix + driver2.driver

                        driver2.containerNumber = str(
                            row[containerNumber2Col].value).strip()
                        if row[notes2Col].value == "SUNRISE METALS":
                            driver2.sunrise = True
                        drivers.append(driver2)

    nameDict = {}

    for row in driverSheet:
        if not row[0].value == None:
            nameDict[str(row[0].value)] = str(row[2].value)
#     driverNameSorted = list(nameDict.keys())
#     driverNameSorted.sort()
#     print(driverNameSorted)
    noName = ""
    noNameCount = 1
    noPARS = ""
    noPARSCount = 1
    badDate = ""
    badDateCount = 1
    for driver in drivers:
        if not str(driver.driver)[:3] == "801":
            #                 print(driver.name)
            if not driver.driver in nameDict:
                noNameCount = noNameCount + 1
                if noNameCount % 6 == 0:
                    noName += "\n"
                noName += str(driver.driver) + ", "
        if driver.PARS == None or driver.PARS == "" or len(driver.PARS) < 6:
            noPARS += str(driver.containerNumber) + ", "
            noPARSCount += 1
            if noPARSCount % 4 == 0:
                noPARS += "\n"

        try:
            pickupDate.day
            pickupDate.month
            pickupDate.year
#             driver.pickupDate.day
#             driver.pickupDate.month
#             driver.pickupDate.year
        except:
            badDate += str(driver.containerNumber) + ", "
            badDateCount += 1
            if badDateCount % 4 == 0:
                badDate += "\n"


#         if not driver.pickupDate:

#         if driver.PARS==None or driver.PARS=="":
#             noPARS += str(driver.containerNumber) + ", "
#             noPARSCount+=1
#             if noPARSCount%4==0:
#                 noPARS += "\n"

    if not noName == "":
        top = Tk()
        L1 = Label()
        L1 = Label(
            top,
            text="No driver name for \"" + noName +
            "\". \nPlease fill out the driver columns and start again. \nAlso ensure that the \"Drivers\" tab is filled out"
        )
        L1.config(font=("Courier", 16))
        L1.grid(row=0, column=0)

        def callbackOK():
            sys.exit()
            top.destroy()

        MyButton = Button(top, text="OK", command=callbackOK, width=40)
        MyButton.grid(row=1, column=0)

        w = 750  # width for the Tk root
        h = 300  # height for the Tk root
        ws = top.winfo_screenwidth()  # width of the screen
        hs = top.winfo_screenheight()  # height of the screen
        x = (ws / 2) - (w / 2)
        y = (hs / 2) - (h / 2)
        top.geometry('%dx%d+%d+%d' % (w, h, x, y))

        top.mainloop()

    if not noPARS == "":
        top = Tk()
        L1 = Label()
        L1 = Label(top,
                   text="Invalid PARS for \"" + noPARS +
                   "\". \nPlease fill out the PARS column and start again.")
        L1.config(font=("Courier", 16))
        L1.grid(row=0, column=0)

        def callbackOK():
            sys.exit()
            top.destroy()

        MyButton = Button(top, text="OK", command=callbackOK, width=40)
        MyButton.grid(row=1, column=0)

        w = 700  # width for the Tk root
        h = 300  # height for the Tk root

        ws = top.winfo_screenwidth()  # width of the screen
        hs = top.winfo_screenheight()  # height of the screen
        x = (ws / 2) - (w / 2)
        y = (hs / 2) - (h / 2)
        top.geometry('%dx%d+%d+%d' % (w, h, x, y))
        top.mainloop()

    if not badDate == "":
        top = Tk()
        L1 = Label()
        L1 = Label(
            top,
            text=
            "Invalid date. Make sure the spreadsheet is named\n\"Word Word Week X ...\"\n and is in a folder named the year"
        )
        L1.config(font=("Courier", 16))
        L1.grid(row=0, column=0)

        def callbackOK():
            sys.exit()
            top.destroy()

        MyButton = Button(top, text="OK", command=callbackOK, width=40)
        MyButton.grid(row=1, column=0)

        w = 700  # width for the Tk root
        h = 300  # height for the Tk root

        ws = top.winfo_screenwidth()  # width of the screen
        hs = top.winfo_screenheight()  # height of the screen
        x = (ws / 2) - (w / 2)
        y = (hs / 2) - (h / 2)
        top.geometry('%dx%d+%d+%d' % (w, h, x, y))
        top.mainloop()

    for driver in drivers:
        if not str(driver.driver)[:3] == "801":
            driver.name = nameDict[driver.driver]

    return drivers, pickupDate, rates[-1]
Exemplo n.º 27
0
from _datetime import date
import calendar
testInput = input()
testInput = testInput.split()
day = int(testInput[0])
month = int(testInput[1])
myDate = date(2009, month, day)
print(calendar.day_name[myDate.weekday()])
Exemplo n.º 28
0
    def count_days_mounth(self, month, year):
        start_date = date(int(year), int(month), 1)
        end_date = date(int(year), int(month) + 1, 1)

        return np.busday_count(start_date, end_date)
Exemplo n.º 29
0
        return self._init_assignments


Names = [
    'Mihai', 'Paul', 'Iustin', 'Falviu', 'Sergiu', 'Tudor', 'Marcel', 'Ion',
    'Tudose', 'Nimeni'
]
Groups = [911, 901, 912, 913, 911, 901, 911, 913, 916, 913]

Descriptions = [
    'Game with pirates', 'Calculator with sinus', 'Andorid game', 'Calendar',
    'IOS game', 'Python app', 'Game with barbie', 'IOS plane game',
    'Assignment 06-08', 'Games'
]
Deadlines = [
    date(2019, 12, 1),
    date(2019, 12, 1),
    date(2019, 12, 1),
    date(2019, 12, 1),
    date(2019, 12, 1),
    date(2019, 12, 1),
    date(2019, 12, 1),
    date(2019, 12, 1),
    date(2019, 12, 1),
    date(2019, 12, 1)
]

stud_list = InitializeStudents(Names, Groups)
stud_list.generate()

assignments_list = InitializeAssignments(Descriptions, Deadlines)
    def action_move_create(self):
        if not self.name:
            raise ValidationError(_("Field name is not defined"))
        if not self.deferred_amount_id:
            raise ValidationError(
                _("Field Deferred expense amount is not defined"))
        if not self.expense_account_id:
            raise ValidationError(_("Field Expense amount is not defined"))
        if not self.journal_id:
            raise ValidationError(_("Field Journal is not defined"))

        depreciation_move_list = []
        self.env['account.move'].search([('accrual_account_expense_id', '=',
                                          self.id)]).unlink()
        if self.residual_amount > 0:
            price_value = (self.residual_amount) / self.number_recognition
            number = 1
            rec_number = self.number_recognition
            if self.prorata_temporis and self.prorata_date:
                rec_number += 1
                number = 0
                if self.period == "months":
                    last_day = int(
                        self.compute_last_day(
                            self.prorata_date).strftime("%d"))
                    crnt_day = int(self.prorata_date.strftime("%d"))
                    percnt = (crnt_day - 1) * 100 / last_day
                elif self.period == "years":
                    year = int(self.prorata_date.strftime("%Y"))
                    total_days = int(date(year, 12, 31).strftime("%j"))
                    crnt_day = int(self.prorata_date.strftime("%j"))
                    percnt = (crnt_day) * 100 / total_days

                last_price = round((price_value * percnt) / 100, 2)
                first_price = price_value - last_price

    #             setting dates for account move ```````````````
            date_list = []
            if self.period == "months":
                date_list = [
                    self.compute_last_day(self.first_recognition_date +
                                          relativedelta(months=x))
                    for x in range(rec_number)
                ]
            if self.period == "years":
                date_list = [
                    self.first_recognition_date + relativedelta(years=x)
                    for x in range(rec_number)
                ]

            cumulative_value = 0.0
            for rec_date in date_list:
                iml = []
                name = self.name or ''
                name = name + "(" + str(number) + "/" + str(
                    self.number_recognition) + ")"
                calculated_price = price_value
                if number == 0:
                    name = self.name + "(prorata entry)"
                    calculated_price = first_price
                elif number == self.number_recognition and self.prorata_temporis:
                    calculated_price = last_price
                number += 1
                if calculated_price >= 0.005:
                    cumulative_value += calculated_price
                    iml.append({
                        'type': 'entry',
                        'name': self.name,
                        'price': calculated_price,
                        'account_id': self.deferred_amount_id.id,
                        'date_maturity': rec_date,
                        'amount_currency': False,
                        'debit': calculated_price,
                        'credit': 0.0,
                        'currency_id': False,
                        'selfoice_id': self.id
                    })
                    iml.append({
                        'type': 'entry',
                        'name': self.name,
                        'price': calculated_price,
                        'account_id': self.expense_account_id.id,
                        'date_maturity': rec_date,
                        'amount_currency': False,
                        'debit': 0.0,
                        'credit': calculated_price,
                        'currency_id': False,
                        'selfoice_id': self.id
                    })
                    line = [(0, 0, l) for l in iml]
                    acc_move = {
                        'type': 'entry',
                        'ref': name,
                        'date': rec_date,
                        'amount_total': calculated_price,
                        'asset_depreciated_value': cumulative_value,
                        'asset_remaining_value':
                        self.residual_amount - cumulative_value,
                        'journal_id': self.journal_id.id,
                        'line_ids': line,
                    }
                    depreciation_move_list.append((0, False, acc_move))
            self.depreciation_move_ids = depreciation_move_list
        return True
Exemplo n.º 31
0
def create_assignment(assignment_id, description, deadline):
    deadline = str(deadline)
    deadline = deadline.split('-')
    return Assignment(
        int(assignment_id), description,
        date(int(deadline[0]), int(deadline[1]), int(deadline[2])))
Exemplo n.º 32
0
from _datetime import datetime, date

date1 = input('Ввведите дату начала в формате гггг мм дд:')
date1 = date1.split(' ')
date1 = date(int(date1[0]), int(date1[1]), int(date1[2]))

date2 = input('Ввведите дату окончания в формате гггг мм дд:')
date2 = date2.split(' ')
date2 = date(int(date2[0]), int(date2[1]), int(date2[2]))

difference = ((date2 - date1).days)
weekday = datetime.weekday(date1)
working_day = []
for i in range(difference + 1):
    if weekday < 5:
        working_day.append(weekday)
        weekday += 1
    elif weekday > 5:
        weekday = 0
    else:
        weekday += 1
print('Количесво рабочих денй за период ' + str(len(working_day)))
Exemplo n.º 33
0
import datetime
import threading
import json
import codecs
from bs4 import BeautifulSoup
from yahoo_finance import Share
import urllib
from pip._vendor.distlib.compat import raw_input
from tkinter import Label, Entry, Frame
from tkinter.constants import INSERT
from time import sleep, gmtime
from _datetime import date
import time
print(time.strftime("%H"))
print(time.strftime("%Y"))
print(time.strftime("%m"))
print(time.strftime("%d"))

print(date(int(time.strftime("%Y")), int(time.strftime("%m")), 21).isoweekday())

while(True):
    url="http://mis.twse.com.tw/stock/data/futures_side.txt"   
    FeatureIntTimeResponse = requests.get(url)
    FeatureInfo=json.loads(FeatureIntTimeResponse.text)
    Stage=float(FeatureInfo['msgArray'][0]['h'])-float(FeatureInfo['msgArray'][0]['l'])
    PowerStage = int(float(FeatureInfo['msgArray'][0]['z'])+float(Stage*0.618))
    WeakStage = int(float(FeatureInfo['msgArray'][0]['z'])+float(Stage*0.382))
    print("若關"+WeakStage.__str__())
    print("強關"+PowerStage.__str__())
    print(FeatureInfo['msgArray'][0]['z'])
    sleep(5)